nirs4all.controllers.models.stacking package
Submodules
- nirs4all.controllers.models.stacking.branch_validator module
- nirs4all.controllers.models.stacking.classification module
ClassificationFeatureExtractorClassificationInfoClassificationInfo.task_typeClassificationInfo.n_classesClassificationInfo.class_labelsClassificationInfo.has_probabilitiesClassificationInfo.proba_shapeClassificationInfo.class_labelsClassificationInfo.get_n_features_per_model()ClassificationInfo.has_probabilitiesClassificationInfo.is_binaryClassificationInfo.is_classificationClassificationInfo.is_multiclassClassificationInfo.n_classesClassificationInfo.proba_shapeClassificationInfo.task_type
FeatureNameGeneratorMetaFeatureInfoMetaFeatureInfo.feature_namesMetaFeatureInfo.source_modelsMetaFeatureInfo.feature_to_modelMetaFeatureInfo.classification_infoMetaFeatureInfo.n_features_per_modelMetaFeatureInfo.aggregate_importance_by_model()MetaFeatureInfo.classification_infoMetaFeatureInfo.feature_namesMetaFeatureInfo.feature_to_modelMetaFeatureInfo.get_model_for_feature()MetaFeatureInfo.n_features_per_modelMetaFeatureInfo.source_models
StackingTaskTypeStackingTaskType.REGRESSIONStackingTaskType.BINARY_CLASSIFICATIONStackingTaskType.MULTICLASS_CLASSIFICATIONStackingTaskType.UNKNOWNStackingTaskType.BINARY_CLASSIFICATIONStackingTaskType.MULTICLASS_CLASSIFICATIONStackingTaskType.REGRESSIONStackingTaskType.UNKNOWNStackingTaskType.is_classificationStackingTaskType.n_classes
TaskTypeDetectorbuild_meta_feature_info()
- nirs4all.controllers.models.stacking.config module
ReconstructorConfigReconstructorConfig.validate_fold_alignmentReconstructorConfig.validate_sample_coverageReconstructorConfig.log_warningsReconstructorConfig.max_missing_fold_ratioReconstructorConfig.allow_partial_sourcesReconstructorConfig.feature_name_patternReconstructorConfig.excluded_fold_idsReconstructorConfig.__post_init__()ReconstructorConfig.allow_partial_sourcesReconstructorConfig.excluded_fold_idsReconstructorConfig.feature_name_patternReconstructorConfig.log_warningsReconstructorConfig.max_missing_fold_ratioReconstructorConfig.validate_fold_alignmentReconstructorConfig.validate_sample_coverage
- nirs4all.controllers.models.stacking.crossbranch module
BranchPredictionInfoBranchPredictionInfo.branch_idBranchPredictionInfo.branch_nameBranchPredictionInfo.model_namesBranchPredictionInfo.sample_indicesBranchPredictionInfo.n_samplesBranchPredictionInfo.n_foldsBranchPredictionInfo.branch_typeBranchPredictionInfo.branch_idBranchPredictionInfo.branch_nameBranchPredictionInfo.branch_typeBranchPredictionInfo.model_namesBranchPredictionInfo.n_foldsBranchPredictionInfo.n_samplesBranchPredictionInfo.sample_indices
CrossBranchCompatibilityCrossBranchValidationResultCrossBranchValidationResult.is_compatibleCrossBranchValidationResult.compatibilityCrossBranchValidationResult.branchesCrossBranchValidationResult.common_samplesCrossBranchValidationResult.alignment_issuesCrossBranchValidationResult.warningsCrossBranchValidationResult.errorsCrossBranchValidationResult.add_error()CrossBranchValidationResult.add_warning()CrossBranchValidationResult.alignment_issuesCrossBranchValidationResult.branchesCrossBranchValidationResult.common_samplesCrossBranchValidationResult.compatibilityCrossBranchValidationResult.errorsCrossBranchValidationResult.is_compatibleCrossBranchValidationResult.total_modelsCrossBranchValidationResult.warnings
CrossBranchValidatorvalidate_all_branches_scope()
- nirs4all.controllers.models.stacking.exceptions module
BranchFeatureAlignmentErrorBranchMismatchErrorBranchingErrorCircularDependencyErrorCrossBranchStackingErrorCrossPartitionStackingErrorDisjointSampleSetsErrorFeatureOrderMismatchErrorFoldMismatchAcrossBranchesErrorGeneratorSyntaxStackingWarningIncompatibleBranchSamplesErrorIncompatibleBranchTypeErrorInconsistentLevelErrorInvalidMetaModelArtifactErrorMaxStackingLevelExceededErrorMetaModelErrorMetaModelPredictionErrorMetaModelSerializationErrorMissingDependencyErrorMissingSourceModelErrorMultiLevelStackingErrorNestedBranchStackingErrorNoSourcePredictionsErrorSourcePredictionError
- nirs4all.controllers.models.stacking.multilevel module
LevelValidationResultLevelValidationResult.is_validLevelValidationResult.detected_levelLevelValidationResult.source_levelsLevelValidationResult.circular_dependenciesLevelValidationResult.warningsLevelValidationResult.errorsLevelValidationResult.add_error()LevelValidationResult.add_warning()LevelValidationResult.circular_dependenciesLevelValidationResult.detected_levelLevelValidationResult.errorsLevelValidationResult.is_validLevelValidationResult.source_levelsLevelValidationResult.warnings
ModelLevelInfoMultiLevelValidatorMultiLevelValidator.prediction_storeMultiLevelValidator.max_levelMultiLevelValidator.log_warningsMultiLevelValidator.META_MODEL_PATTERNSMultiLevelValidator.clear_cache()MultiLevelValidator.detect_level()MultiLevelValidator.filter_by_level()MultiLevelValidator.get_all_levels()MultiLevelValidator.validate_sources()
detect_stacking_level()validate_multi_level_stacking()
- nirs4all.controllers.models.stacking.reconstructor module
FoldAlignmentValidatorReconstructionResultReconstructionResult.X_train_metaReconstructionResult.X_test_metaReconstructionResult.y_trainReconstructionResult.y_testReconstructionResult.feature_namesReconstructionResult.source_modelsReconstructionResult.valid_train_maskReconstructionResult.valid_test_maskReconstructionResult.validation_resultReconstructionResult.n_foldsReconstructionResult.coverage_ratioReconstructionResult.meta_feature_infoReconstructionResult.classification_infoReconstructionResult.X_test_metaReconstructionResult.X_train_metaReconstructionResult.classification_infoReconstructionResult.coverage_ratioReconstructionResult.feature_namesReconstructionResult.meta_feature_infoReconstructionResult.n_foldsReconstructionResult.source_modelsReconstructionResult.valid_test_maskReconstructionResult.valid_train_maskReconstructionResult.validation_resultReconstructionResult.y_testReconstructionResult.y_train
TrainingSetReconstructorTrainingSetReconstructor.prediction_storeTrainingSetReconstructor.source_model_namesTrainingSetReconstructor.stacking_configTrainingSetReconstructor.reconstructor_configTrainingSetReconstructor.fold_validatorTrainingSetReconstructor.reconstruct()TrainingSetReconstructor.validate_branch_compatibility()
ValidationErrorValidationResultValidationResult.errorsValidationResult.warningsValidationResult.is_validValidationResult.add_error()ValidationResult.add_warning()ValidationResult.errorsValidationResult.format_errors()ValidationResult.format_warnings()ValidationResult.is_validValidationResult.merge()ValidationResult.warnings
ValidationWarning
- nirs4all.controllers.models.stacking.serialization module
MetaModelArtifactMetaModelArtifact.meta_model_typeMetaModelArtifact.meta_model_nameMetaModelArtifact.meta_learner_classMetaModelArtifact.source_modelsMetaModelArtifact.feature_columnsMetaModelArtifact.stacking_configMetaModelArtifact.selector_configMetaModelArtifact.branch_contextMetaModelArtifact.use_probaMetaModelArtifact.n_foldsMetaModelArtifact.coverage_ratioMetaModelArtifact.artifact_idMetaModelArtifact.training_timestampMetaModelArtifact.artifact_idMetaModelArtifact.branch_contextMetaModelArtifact.coverage_ratioMetaModelArtifact.feature_columnsMetaModelArtifact.feature_to_model_mappingMetaModelArtifact.from_dict()MetaModelArtifact.from_json()MetaModelArtifact.get_source_artifact_ids()MetaModelArtifact.get_source_by_index()MetaModelArtifact.meta_learner_classMetaModelArtifact.meta_model_nameMetaModelArtifact.meta_model_typeMetaModelArtifact.n_classesMetaModelArtifact.n_foldsMetaModelArtifact.selector_configMetaModelArtifact.source_modelsMetaModelArtifact.stacking_configMetaModelArtifact.task_typeMetaModelArtifact.to_dict()MetaModelArtifact.to_json()MetaModelArtifact.training_timestampMetaModelArtifact.use_probaMetaModelArtifact.validate_feature_alignment()
MetaModelSerializerSourceModelReferenceSourceModelReference.model_nameSourceModelReference.model_classnameSourceModelReference.step_idxSourceModelReference.artifact_idSourceModelReference.feature_indexSourceModelReference.fold_idSourceModelReference.branch_idSourceModelReference.branch_nameSourceModelReference.branch_pathSourceModelReference.val_scoreSourceModelReference.metricSourceModelReference.artifact_idSourceModelReference.branch_idSourceModelReference.branch_nameSourceModelReference.branch_pathSourceModelReference.feature_indexSourceModelReference.fold_idSourceModelReference.from_dict()SourceModelReference.metricSourceModelReference.model_classnameSourceModelReference.model_nameSourceModelReference.step_idxSourceModelReference.to_dict()SourceModelReference.val_score
stacking_config_from_dict()stacking_config_to_dict()
Module contents
Stacking subpackage for meta-model training set reconstruction.
This module provides the TrainingSetReconstructor class and supporting utilities for building meta-model training features from out-of-fold predictions.
- Phase 2 Classes:
TrainingSetReconstructor: Main class for OOF prediction collection and reconstruction. FoldAlignmentValidator: Validates fold structure consistency across source models. ValidationResult: Container for validation errors and warnings. ReconstructionResult: Container for reconstructed training set data.
- Phase 3 Classes (Serialization & Prediction Mode):
SourceModelReference: Reference to a source model with feature mapping. MetaModelArtifact: Complete artifact for meta-model persistence. MetaModelSerializer: Handles serialization/deserialization of meta-model artifacts.
- Phase 4 Classes (Branching Integration):
BranchValidator: Validates branch contexts for stacking compatibility. BranchType: Enum for branch type detection. BranchInfo: Information about branch context. BranchValidationResult: Result of branch validation.
- Phase 5 Classes (Classification Support):
StackingTaskType: Enum for task types (regression, binary, multiclass). ClassificationInfo: Information about classification task detected from predictions. TaskTypeDetector: Detects task type from prediction metadata. ClassificationFeatureExtractor: Extracts probability features for classification. FeatureNameGenerator: Creates descriptive feature names for meta-features. MetaFeatureInfo: Information about generated meta-features for importance tracking.
- Phase 7 Classes (Advanced Features):
MultiLevelValidator: Validates multi-level stacking hierarchies. ModelLevelInfo: Information about a model’s stacking level. LevelValidationResult: Result of multi-level validation. CrossBranchValidator: Validates cross-branch stacking compatibility. CrossBranchValidationResult: Result of cross-branch validation. BranchPredictionInfo: Information about predictions from a branch.
- Exception Classes:
MetaModelError: Base exception for meta-model errors. MetaModelPredictionError: Base exception for prediction errors. MissingSourceModelError: Source model binary not found. SourcePredictionError: Source model prediction failed. FeatureOrderMismatchError: Feature columns don’t match expected order. BranchMismatchError: Branch context incompatible. MetaModelSerializationError: Base exception for serialization errors. MissingDependencyError: Dependency not serialized. BranchingError: Base exception for branching errors. IncompatibleBranchTypeError: Branch type not compatible with stacking. CrossPartitionStackingError: Cross-partition stacking attempted. NestedBranchStackingError: Nested branching too deep. FoldMismatchAcrossBranchesError: Folds don’t align across branches. DisjointSampleSetsError: Sample sets don’t overlap. MultiLevelStackingError: Base exception for multi-level stacking errors. CircularDependencyError: Circular dependencies detected in stacking. MaxStackingLevelExceededError: Maximum stacking level exceeded. CrossBranchStackingError: Base exception for cross-branch stacking errors. IncompatibleBranchSamplesError: Branches have incompatible samples. BranchFeatureAlignmentError: Feature alignment failed across branches.
Example
>>> from nirs4all.controllers.models.stacking import TrainingSetReconstructor
>>> from nirs4all.operators.models.meta import StackingConfig
>>>
>>> reconstructor = TrainingSetReconstructor(
... prediction_store=predictions,
... source_models=["PLS", "RF"],
... stacking_config=StackingConfig()
... )
>>> result = reconstructor.reconstruct(dataset, context)
- exception nirs4all.controllers.models.stacking.BranchFeatureAlignmentError(expected_features: int, branch_features: Dict[int, int], alignment_issues: List[str] | None = None)[source]
Bases:
CrossBranchStackingErrorRaised when cross-branch features cannot be aligned.
This occurs when attempting to combine predictions from multiple branches but the feature matrices cannot be properly aligned due to different preprocessing or ordering.
- expected_features
Expected number of features.
- branch_features
Dict mapping branch_id to feature count.
- alignment_issues
List of specific alignment problems.
- class nirs4all.controllers.models.stacking.BranchInfo(branch_type: ~nirs4all.controllers.models.stacking.branch_validator.BranchType, branch_id: int | None = None, branch_name: str | None = None, branch_path: ~typing.List[int] = <factory>, partition_info: ~typing.Dict[str, ~typing.Any] | None = None, exclusion_info: ~typing.Dict[str, ~typing.Any] | None = None, sample_indices: ~typing.List[int] | None = None, n_samples: int | None = None, is_nested: bool = False, nesting_depth: int = 0)[source]
Bases:
objectInformation about branch context for stacking validation.
- branch_type: BranchType
- exception nirs4all.controllers.models.stacking.BranchMismatchError(training_branch: Dict[str, Any], prediction_branch: Dict[str, Any], meta_model_id: str)[source]
Bases:
MetaModelPredictionErrorRaised when prediction branch doesn’t match training branch.
This occurs when attempting to use a meta-model trained in one branch for prediction in a different, incompatible branch context.
- training_branch
Branch context during training.
- prediction_branch
Branch context during prediction.
- meta_model_id
The artifact ID of the meta-model.
- class nirs4all.controllers.models.stacking.BranchPredictionInfo(branch_id: int, branch_name: str | None, model_names: List[str], sample_indices: Set[int], n_samples: int, n_folds: int, branch_type: BranchType = BranchType.UNKNOWN)[source]
Bases:
objectInformation about predictions from a specific branch.
- branch_type
Type of branching.
- branch_type: BranchType = 'unknown'
- class nirs4all.controllers.models.stacking.BranchType(value)[source]
Bases:
EnumTypes of branching in nirs4all pipelines.
- GENERATOR = 'generator'
- METADATA_PARTITIONER = 'metadata_partitioner'
- NESTED = 'nested'
- NONE = 'none'
- OUTLIER_EXCLUDER = 'outlier_excluder'
- PREPROCESSING = 'preprocessing'
- SAMPLE_PARTITIONER = 'sample_partitioner'
- UNKNOWN = 'unknown'
- class nirs4all.controllers.models.stacking.BranchValidationResult(is_valid: bool, compatibility: ~nirs4all.controllers.models.stacking.branch_validator.StackingCompatibility, branch_info: ~nirs4all.controllers.models.stacking.branch_validator.BranchInfo, errors: ~typing.List[str] = <factory>, warnings: ~typing.List[str] = <factory>, source_filter_hint: ~typing.Dict[str, ~typing.Any] | None = None)[source]
Bases:
objectResult of branch validation for stacking.
- branch_info: BranchInfo
- compatibility: StackingCompatibility
- class nirs4all.controllers.models.stacking.BranchValidator(prediction_store: Predictions, log_warnings: bool = True)[source]
Bases:
objectValidates branch contexts for meta-model stacking.
This validator checks that the current branch context is compatible with stacking and provides clear error messages for unsupported cases.
Supported scenarios: - No branching: Fully compatible - Preprocessing branches: Stack within branch - Outlier excluder branches: Stack within branch (all samples have predictions) - Sample partitioner branches: Stack within partition only
Unsupported or limited scenarios: - Cross-partition stacking with sample_partitioner - Deeply nested branching (depth > 2) - Generator syntax with large variant counts
Example
>>> validator = BranchValidator(prediction_store) >>> result = validator.validate(context, source_model_names) >>> if not result.is_valid: ... raise ValueError(result.errors[0])
- MAX_GENERATOR_VARIANTS_WARNING = 10
- MAX_NESTING_DEPTH = 2
- validate(context: ExecutionContext, source_model_names: List[str], dataset: SpectroDataset | None = None) BranchValidationResult[source]
Validate branch context for stacking compatibility.
- Parameters:
context – Current execution context with branch info.
source_model_names – List of source model names to validate.
dataset – Optional dataset for sample index validation.
- Returns:
BranchValidationResult with validation status and any errors.
- validate_sample_alignment(source_model_names: List[str], expected_sample_indices: List[int], context: ExecutionContext) BranchValidationResult[source]
Validate that source models have predictions for expected samples.
This is particularly important for sample_partitioner branches where different partitions have different samples.
- Parameters:
source_model_names – List of source model names.
expected_sample_indices – Expected sample indices (from current partition).
context – Execution context.
- Returns:
Validation result with any sample alignment issues.
- exception nirs4all.controllers.models.stacking.BranchingError(message: str, details: Dict[str, Any] | None = None)[source]
Bases:
MetaModelErrorBase exception for branching-related errors in meta-model stacking.
- exception nirs4all.controllers.models.stacking.CircularDependencyError(source_model: str, meta_model: str, dependency_chain: List[str])[source]
Bases:
MultiLevelStackingErrorRaised when circular dependencies are detected in multi-level stacking.
This occurs when a meta-model attempts to use itself or a model that depends on it as a source, creating a circular dependency.
- source_model
Name of the source model causing the cycle.
- meta_model
Name of the current meta-model.
- dependency_chain
List of model names forming the cycle.
- class nirs4all.controllers.models.stacking.ClassificationFeatureExtractor(classification_info: ClassificationInfo, use_proba: bool = False)[source]
Bases:
objectExtracts classification features from predictions.
Handles extraction of probability features for binary and multiclass classification, with proper handling of different array shapes.
- extract_features(pred: Dict[str, Any], n_samples: int) ndarray[source]
Extract features from a single prediction entry.
- Parameters:
pred – Prediction dictionary with y_pred and optionally y_proba.
n_samples – Expected number of samples.
- Returns:
Feature array of shape (n_samples,) or (n_samples, n_features).
- class nirs4all.controllers.models.stacking.ClassificationInfo(task_type: StackingTaskType, n_classes: int | None = None, class_labels: List[Any] | None = None, has_probabilities: bool = False, proba_shape: Tuple[int, ...] | None = None)[source]
Bases:
objectInformation about classification task detected from predictions.
- task_type
Detected task type (regression/binary/multiclass).
- class_labels
Optional class labels if available.
- Type:
List[Any] | None
- get_n_features_per_model(use_proba: bool = False) int[source]
Get number of features per source model.
- Parameters:
use_proba – Whether probability features are requested.
- Returns:
Number of feature columns per source model. - Regression: 1 (y_pred) - Binary + use_proba: 1 (positive class probability) - Multiclass + use_proba: n_classes (all class probabilities) - Classification without use_proba: 1 (y_pred)
- task_type: StackingTaskType
- class nirs4all.controllers.models.stacking.CrossBranchCompatibility(value)[source]
Bases:
EnumCompatibility level for cross-branch stacking.
- COMPATIBLE = 'compatible'
- COMPATIBLE_WITH_ALIGNMENT = 'compatible_with_alignment'
- INCOMPATIBLE_PARTITIONS = 'incompatible_partitions'
- INCOMPATIBLE_SAMPLES = 'incompatible_samples'
- NOT_APPLICABLE = 'not_applicable'
- exception nirs4all.controllers.models.stacking.CrossBranchStackingError(message: str, details: Dict[str, Any] | None = None)[source]
Bases:
BranchingErrorBase exception for cross-branch stacking errors.
- class nirs4all.controllers.models.stacking.CrossBranchValidationResult(is_compatible: bool = True, compatibility: ~nirs4all.controllers.models.stacking.crossbranch.CrossBranchCompatibility = CrossBranchCompatibility.NOT_APPLICABLE, branches: ~typing.Dict[int, ~nirs4all.controllers.models.stacking.crossbranch.BranchPredictionInfo] = <factory>, common_samples: ~typing.Set[int] = <factory>, alignment_issues: ~typing.List[str] = <factory>, warnings: ~typing.List[str] = <factory>, errors: ~typing.List[str] = <factory>)[source]
Bases:
objectResult of cross-branch stacking validation.
- compatibility
Detailed compatibility level.
- branches
Dict of BranchPredictionInfo by branch_id.
- branches: Dict[int, BranchPredictionInfo]
- compatibility: CrossBranchCompatibility = 'not_applicable'
- class nirs4all.controllers.models.stacking.CrossBranchValidator(prediction_store: Predictions, log_warnings: bool = True)[source]
Bases:
objectValidates and supports cross-branch stacking.
This validator checks that stacking across multiple branches is feasible and provides utilities for aligning predictions from different branches.
- prediction_store
Predictions storage.
- log_warnings
Whether to emit Python warnings.
- align_branch_features(branch_features: Dict[int, ndarray], branch_sample_indices: Dict[int, List[int]], target_sample_indices: List[int]) Tuple[ndarray, ndarray][source]
Align features from multiple branches to common sample order.
Combines features from different branches into a single feature matrix, aligning samples to a common order.
- Parameters:
branch_features – Dict mapping branch_id to feature matrix.
branch_sample_indices – Dict mapping branch_id to sample indices.
target_sample_indices – Target sample order for output.
- Returns:
Tuple of (aligned_features, valid_mask).
- Raises:
BranchFeatureAlignmentError – If alignment fails.
- get_cross_branch_sources(source_candidates: List[ModelCandidate], context: ExecutionContext) List[ModelCandidate][source]
Get source models from all branches for cross-branch stacking.
Filters and orders candidates for cross-branch stacking, ensuring proper handling of branch-specific models.
- Parameters:
source_candidates – All candidate source models.
context – Execution context.
- Returns:
Filtered and ordered list of candidates for cross-branch stacking.
- validate_cross_branch_stacking(source_candidates: List[ModelCandidate], context: ExecutionContext, dataset: SpectroDataset | None = None) CrossBranchValidationResult[source]
Validate cross-branch stacking feasibility.
Checks that all branches have compatible samples and predictions can be properly aligned for stacking.
- Parameters:
source_candidates – List of candidate source models.
context – Execution context.
dataset – Optional dataset for sample validation.
- Returns:
CrossBranchValidationResult with compatibility info.
- exception nirs4all.controllers.models.stacking.CrossPartitionStackingError(partition_a: str, partition_b: str, n_samples_a: int, n_samples_b: int)[source]
Bases:
BranchingErrorRaised when attempting cross-partition stacking with sample_partitioner.
Sample partitioner creates disjoint sample sets, making cross-partition stacking impossible without data leakage or sample misalignment.
- partition_a
Name of first partition.
- partition_b
Name of second partition.
- n_samples_a
Number of samples in partition A.
- n_samples_b
Number of samples in partition B.
- exception nirs4all.controllers.models.stacking.DisjointSampleSetsError(source_model: str, expected_samples: int, found_samples: int, overlap_ratio: float)[source]
Bases:
BranchingErrorRaised when source models have disjoint sample sets.
This typically occurs with sample_partitioner where different branches have different samples, making OOF reconstruction impossible.
- source_model
Name of the source model with disjoint samples.
- expected_samples
Number of expected samples.
- found_samples
Number of samples found in predictions.
- overlap_ratio
Ratio of overlapping samples.
- class nirs4all.controllers.models.stacking.FeatureNameGenerator(classification_info: ClassificationInfo, use_proba: bool = False, pattern: str = '{model_name}_pred')[source]
Bases:
objectGenerates meaningful feature names for meta-model.
Creates descriptive feature names that include model name and, for classification with probabilities, class information.
- generate_names(source_model_names: List[str]) List[str][source]
Generate feature names for all source models.
- Parameters:
source_model_names – List of source model names.
- Returns:
List of feature column names.
- get_feature_importance_mapping(source_model_names: List[str]) Dict[str, List[str]][source]
Get mapping from source models to their feature names.
Useful for feature importance analysis.
- Parameters:
source_model_names – List of source model names.
- Returns:
Dictionary mapping model name to list of feature names.
- exception nirs4all.controllers.models.stacking.FeatureOrderMismatchError(expected_columns: List[str], actual_columns: List[str], meta_model_id: str)[source]
Bases:
MetaModelPredictionErrorRaised when feature columns don’t match expected order.
This occurs when the predictions from source models don’t align with the feature column order that was used during meta-model training.
- expected_columns
Expected feature column names in order.
- actual_columns
Actual feature column names found.
- meta_model_id
The artifact ID of the meta-model.
- class nirs4all.controllers.models.stacking.FoldAlignmentValidator(prediction_store: Predictions, config: ReconstructorConfig | None = None)[source]
Bases:
objectValidates fold structure consistency across source models.
Ensures that all source models have compatible fold structures for proper out-of-fold reconstruction.
Checks performed: 1. All models have the same number of folds. 2. Fold indices are sequential (0, 1, 2, …, K-1). 3. No sample appears in multiple validation sets within a model. 4. Sample indices are consistent across folds.
- prediction_store
Predictions storage for accessing fold data.
- config
Reconstructor configuration.
- validate(source_model_names: List[str], context: ExecutionContext, branch_id_override: int | None = -1) ValidationResult[source]
Validate fold alignment across source models.
- Parameters:
source_model_names – List of source model names to validate.
context – Execution context with branch info.
branch_id_override – Optional branch_id override. If -1 (default), use context’s branch_id. If None, don’t filter by branch (for ALL_BRANCHES scope).
- Returns:
ValidationResult with any errors or warnings.
- exception nirs4all.controllers.models.stacking.FoldMismatchAcrossBranchesError(fold_structures: Dict[int, int], affected_models: List[str])[source]
Bases:
BranchingErrorRaised when source models from different branches have mismatched folds.
For stacking to work correctly, all source models must have compatible fold structures (same number of folds, same sample assignments per fold).
- fold_structures
Dict mapping branch_id to fold count.
- affected_models
List of affected model names.
- exception nirs4all.controllers.models.stacking.GeneratorSyntaxStackingWarning(generator_type: str, n_variants: int)[source]
Bases:
BranchingErrorRaised as warning for generator syntax with stacking.
Generator syntax creates multiple model variants which may complicate stacking behavior. This is a warning, not a hard error.
- generator_type
Type of generator used.
- n_variants
Number of variants generated.
- exception nirs4all.controllers.models.stacking.IncompatibleBranchSamplesError(branches: Dict[int, int], overlap_matrix: Dict[tuple, float] | None = None)[source]
Bases:
CrossBranchStackingErrorRaised when branches have incompatible sample sets for cross-branch stacking.
This occurs when attempting ALL_BRANCHES stacking with branches that have different sample indices (e.g., sample_partitioner branches).
- branches
Dict mapping branch_id to sample counts.
- overlap_matrix
Optional matrix showing sample overlap between branches.
- exception nirs4all.controllers.models.stacking.IncompatibleBranchTypeError(branch_type: str, reason: str, suggestions: List[str] | None = None)[source]
Bases:
BranchingErrorRaised when stacking is attempted with incompatible branch type.
This occurs when the branch context is not suitable for stacking, such as attempting cross-partition stacking with sample_partitioner.
- branch_type
Type of branching detected.
- reason
Explanation of why stacking is incompatible.
- suggestions
List of possible solutions.
- exception nirs4all.controllers.models.stacking.InconsistentLevelError(expected_levels: List[int], found_levels: Dict[str, int], problematic_models: List[str])[source]
Bases:
MultiLevelStackingErrorRaised when source models have inconsistent stacking levels.
This occurs when a meta-model tries to use source models from incompatible levels, which could indicate a pipeline configuration issue.
- expected_levels
Expected level(s) for source models.
- found_levels
Actual levels found in source models.
- problematic_models
Models with unexpected levels.
- exception nirs4all.controllers.models.stacking.InvalidMetaModelArtifactError(artifact_id: str, validation_errors: List[str])[source]
Bases:
MetaModelSerializationErrorRaised when a meta-model artifact is invalid or corrupted.
This occurs when loading a meta-model artifact that doesn’t contain the required fields or has inconsistent data.
- artifact_id
The artifact ID being loaded.
- validation_errors
List of validation errors found.
- class nirs4all.controllers.models.stacking.LevelValidationResult(is_valid: bool = True, detected_level: int = 1, source_levels: ~typing.Dict[str, int] = <factory>, circular_dependencies: ~typing.List[~typing.List[str]] = <factory>, warnings: ~typing.List[str] = <factory>, errors: ~typing.List[str] = <factory>)[source]
Bases:
objectResult of multi-level stacking validation.
- exception nirs4all.controllers.models.stacking.MaxStackingLevelExceededError(current_level: int, max_level: int, source_models: List[str] | None = None)[source]
Bases:
MultiLevelStackingErrorRaised when the maximum stacking level is exceeded.
This occurs when attempting to create more stacking levels than allowed, which could lead to overfitting or excessive computational cost.
- current_level
The level that was attempted.
- max_level
The maximum allowed level.
- source_models
Source models that caused the level increase.
- class nirs4all.controllers.models.stacking.MetaFeatureInfo(feature_names: ~typing.List[str], source_models: ~typing.List[str], feature_to_model: ~typing.Dict[str, str], classification_info: ~nirs4all.controllers.models.stacking.classification.ClassificationInfo, n_features_per_model: ~typing.Dict[str, int] = <factory>)[source]
Bases:
objectInformation about generated meta-features.
Used for tracking feature importance and providing interpretable results.
- classification_info
Classification metadata.
- aggregate_importance_by_model(feature_importances: Dict[str, float]) Dict[str, float][source]
Aggregate feature importances by source model.
Sums importance scores for all features from the same source model.
- Parameters:
feature_importances – Mapping from feature name to importance score.
- Returns:
Mapping from model name to aggregated importance.
- classification_info: ClassificationInfo
- class nirs4all.controllers.models.stacking.MetaModelArtifact(meta_model_type: str, meta_model_name: str, meta_learner_class: str, source_models: ~typing.List[~nirs4all.controllers.models.stacking.serialization.SourceModelReference], feature_columns: ~typing.List[str], stacking_config: ~typing.Dict[str, ~typing.Any], selector_config: ~typing.Dict[str, ~typing.Any] | None = None, branch_context: ~typing.Dict[str, ~typing.Any] | None = None, use_proba: bool = False, n_folds: int = 0, coverage_ratio: float = 1.0, artifact_id: str = '', training_timestamp: str = <factory>, task_type: str = 'regression', n_classes: int | None = None, feature_to_model_mapping: ~typing.Dict[str, str] | None = None)[source]
Bases:
objectComplete artifact for meta-model persistence.
Contains all information needed to: - Reload the meta-model and its dependencies - Reconstruct feature columns in the correct order - Validate branch context during prediction - Apply the same stacking configuration
- source_models
Ordered list of source model references.
Example
>>> artifact = MetaModelArtifact( ... meta_model_type="MetaModel", ... meta_model_name="MetaModel_Ridge", ... meta_learner_class="Ridge", ... source_models=[ref1, ref2], ... feature_columns=["PLS_pred", "RF_pred"], ... stacking_config=stacking_config_dict, ... branch_context={"branch_id": None}, ... use_proba=False, ... n_folds=5, ... coverage_ratio=1.0, ... artifact_id="0001:5:all", ... training_timestamp="2024-12-12T14:30:22Z" ... )
- classmethod from_json(json_str: str) MetaModelArtifact[source]
Deserialize from JSON string.
- get_source_artifact_ids() List[str][source]
Get ordered list of source model artifact IDs.
- Returns:
List of artifact IDs in feature column order.
- get_source_by_index(index: int) SourceModelReference | None[source]
Get source model reference by feature index.
- Parameters:
index – Feature column index.
- Returns:
SourceModelReference or None if index out of range.
- source_models: List[SourceModelReference]
- exception nirs4all.controllers.models.stacking.MetaModelError(message: str, details: Dict[str, Any] | None = None)[source]
Bases:
ExceptionBase exception for meta-model errors.
All meta-model specific exceptions inherit from this class, allowing catch-all handling of meta-model issues.
- message
Human-readable error description.
- details
Optional dictionary with additional context.
- exception nirs4all.controllers.models.stacking.MetaModelPredictionError(message: str, details: Dict[str, Any] | None = None)[source]
Bases:
MetaModelErrorBase exception for meta-model prediction errors.
Raised when prediction mode fails for a meta-model.
- exception nirs4all.controllers.models.stacking.MetaModelSerializationError(message: str, details: Dict[str, Any] | None = None)[source]
Bases:
MetaModelErrorBase exception for meta-model serialization errors.
Raised when persistence or loading of meta-model artifacts fails.
- class nirs4all.controllers.models.stacking.MetaModelSerializer[source]
Bases:
objectHandles serialization and deserialization of meta-model artifacts.
Provides methods to: - Build MetaModelArtifact from training context - Convert to/from MetaModelConfig for artifact registry - Validate artifact completeness
Example
>>> serializer = MetaModelSerializer() >>> artifact = serializer.build_artifact( ... meta_operator=meta_model_op, ... source_models=selected_sources, ... reconstruction_result=result, ... context=execution_context ... ) >>> config = serializer.to_meta_model_config(artifact)
- build_artifact(meta_operator: MetaModel, source_models: List[ModelCandidate], reconstruction_result: ReconstructionResult | None = None, context: ExecutionContext | None = None, artifact_id: str = '') MetaModelArtifact[source]
Build MetaModelArtifact from training context.
- Parameters:
meta_operator – The MetaModel operator being trained.
source_models – List of selected source model candidates.
reconstruction_result – Optional result from TrainingSetReconstructor.
context – Optional execution context for branch info.
artifact_id – The artifact ID for this meta-model.
- Returns:
MetaModelArtifact ready for persistence.
- to_meta_model_config(artifact: MetaModelArtifact) MetaModelConfig[source]
Convert MetaModelArtifact to MetaModelConfig for registry.
The ArtifactRegistry uses MetaModelConfig to track source model dependencies. This method creates the appropriate config.
- Parameters:
artifact – MetaModelArtifact to convert.
- Returns:
MetaModelConfig for artifact registry.
- validate_artifact(artifact: MetaModelArtifact) List[str][source]
Validate artifact completeness and consistency.
- Parameters:
artifact – MetaModelArtifact to validate.
- Returns:
List of validation error messages (empty if valid).
- exception nirs4all.controllers.models.stacking.MissingDependencyError(dependency_id: str, meta_model_id: str, dependency_name: str | None = None)[source]
Bases:
MetaModelSerializationErrorRaised when a dependency is not serialized.
This occurs when attempting to serialize a meta-model but one of its source model dependencies hasn’t been persisted yet.
- dependency_id
The artifact ID of the missing dependency.
- meta_model_id
The artifact ID of the meta-model.
- dependency_name
Optional name of the missing dependency.
- exception nirs4all.controllers.models.stacking.MissingSourceModelError(source_model_id: str, meta_model_id: str, all_missing: List[str] | None = None)[source]
Bases:
MetaModelPredictionErrorRaised when a source model binary is not found.
This occurs when trying to load a meta-model for prediction but one or more of its source model dependencies cannot be found in the artifact store.
- source_model_id
The artifact ID of the missing source model.
- meta_model_id
The artifact ID of the meta-model.
- all_missing
List of all missing source model IDs (if multiple).
- class nirs4all.controllers.models.stacking.ModelLevelInfo(model_name: str, level: int, is_meta_model: bool, source_models: ~typing.List[str] = <factory>, step_idx: int = 0)[source]
Bases:
objectInformation about a model’s stacking level.
- exception nirs4all.controllers.models.stacking.MultiLevelStackingError(message: str, details: Dict[str, Any] | None = None)[source]
Bases:
MetaModelErrorBase exception for multi-level stacking errors.
- class nirs4all.controllers.models.stacking.MultiLevelValidator(prediction_store: Predictions, max_level: int = 3, log_warnings: bool = True)[source]
Bases:
objectValidates multi-level stacking configurations.
Ensures that stacking hierarchies are valid, detects circular dependencies, and computes appropriate stacking levels for meta-models.
- prediction_store
Predictions storage for analyzing model metadata.
- max_level
Maximum allowed stacking level.
- log_warnings
Whether to emit Python warnings.
- META_MODEL_PATTERNS = {'MetaModel', 'StackingClassifier', 'StackingRegressor'}
- detect_level(source_candidates: List[ModelCandidate], context: ExecutionContext) int[source]
Detect the appropriate stacking level based on source models.
- Parameters:
source_candidates – List of candidate source models.
context – Execution context.
- Returns:
Detected stacking level (1 if no meta-model sources, 2+ otherwise).
- filter_by_level(candidates: List[ModelCandidate], context: ExecutionContext, max_source_level: int | None = None, exclude_meta_models: bool = False) List[ModelCandidate][source]
Filter source candidates by stacking level.
- Parameters:
candidates – List of candidate source models.
context – Execution context.
max_source_level – Maximum allowed source level (None = no limit).
exclude_meta_models – If True, exclude all meta-models from sources.
- Returns:
Filtered list of candidates.
- get_all_levels(context: ExecutionContext) Dict[str, int][source]
Get levels for all models in the prediction store.
- Parameters:
context – Execution context.
- Returns:
Dict mapping model names to their stacking levels.
- validate_sources(meta_model_name: str, source_candidates: List[ModelCandidate], context: ExecutionContext, allow_meta_sources: bool = True) LevelValidationResult[source]
Validate source models for a meta-model.
Checks for circular dependencies and computes the appropriate stacking level based on source model levels.
- Parameters:
meta_model_name – Name of the meta-model being validated.
source_candidates – List of candidate source models.
context – Execution context.
allow_meta_sources – Whether to allow other meta-models as sources.
- Returns:
LevelValidationResult with validation status and detected level.
- exception nirs4all.controllers.models.stacking.NestedBranchStackingError(branch_depth: int, branch_path: List[int], reason: str)[source]
Bases:
BranchingErrorRaised when stacking is attempted with complex nested branching.
Complex nested branching scenarios may not be fully supported in meta-model stacking due to sample alignment challenges.
- branch_depth
Depth of nesting.
- branch_path
Full path of branch IDs.
- reason
Explanation of the issue.
- exception nirs4all.controllers.models.stacking.NoSourcePredictionsError(expected_sources: List[str], meta_model_id: str)[source]
Bases:
MetaModelPredictionErrorRaised when no source model predictions are available.
This occurs when the prediction store doesn’t contain any predictions from source models, making it impossible to construct meta-features.
- expected_sources
List of expected source model names.
- meta_model_id
The artifact ID of the meta-model.
- class nirs4all.controllers.models.stacking.ReconstructionResult(X_train_meta: ndarray, X_test_meta: ndarray, y_train: ndarray, y_test: ndarray, feature_names: List[str], source_models: List[str], valid_train_mask: ndarray, valid_test_mask: ndarray, validation_result: ValidationResult, n_folds: int, coverage_ratio: float, meta_feature_info: Any | None = None, classification_info: Any | None = None)[source]
Bases:
objectContainer for reconstructed training set data.
Holds the meta-feature matrices for training and test sets, along with metadata about the reconstruction process.
- X_train_meta
Training meta-features (n_train_samples, n_features).
- Type:
- X_test_meta
Test meta-features (n_test_samples, n_features).
- Type:
- y_train
Training targets (n_train_samples,).
- Type:
- y_test
Test targets (n_test_samples,).
- Type:
- valid_train_mask
Boolean mask of valid training samples (after coverage handling).
- Type:
- valid_test_mask
Boolean mask of valid test samples.
- Type:
- validation_result
Validation result from fold alignment.
- meta_feature_info
Optional MetaFeatureInfo for feature importance tracking.
- Type:
Any | None
- classification_info
Optional ClassificationInfo for task type metadata.
- Type:
Any | None
Example
>>> result = reconstructor.reconstruct(dataset, context) >>> X_train = result.X_train_meta[result.valid_train_mask] >>> y_train = result.y_train[result.valid_train_mask] >>> # For feature importance tracking >>> if result.meta_feature_info: ... model_importance = result.meta_feature_info.aggregate_importance_by_model( ... feature_importances ... )
- validation_result: ValidationResult
- class nirs4all.controllers.models.stacking.ReconstructorConfig(validate_fold_alignment: bool = True, validate_sample_coverage: bool = True, log_warnings: bool = True, max_missing_fold_ratio: float = 0.0, allow_partial_sources: bool = False, feature_name_pattern: str = '{model_name}_pred', excluded_fold_ids: ~typing.Set[str] = <factory>)[source]
Bases:
objectConfiguration for TrainingSetReconstructor.
Controls internal behavior of the reconstruction process, separate from the user-facing StackingConfig.
- feature_name_pattern
Pattern for generating feature column names. Supports: {model_name}, {fold_id}, {classname}, {step_idx}
- Type:
Example
>>> config = ReconstructorConfig( ... validate_fold_alignment=True, ... log_warnings=True, ... feature_name_pattern="{model_name}_pred" ... )
- class nirs4all.controllers.models.stacking.SourceModelReference(model_name: str, model_classname: str, step_idx: int, artifact_id: str, feature_index: int, fold_id: str | None = None, branch_id: int | None = None, branch_name: str | None = None, branch_path: List[int] | None = None, val_score: float | None = None, metric: str | None = None)[source]
Bases:
objectReference to a source model used in stacking.
Stores all information needed to locate and validate a source model during prediction mode.
Example
>>> ref = SourceModelReference( ... model_name="PLSRegression", ... model_classname="sklearn.cross_decomposition.PLSRegression", ... step_idx=3, ... artifact_id="0001:3:all", ... feature_index=0, ... branch_id=None, ... val_score=0.92, ... metric="r2" ... )
- exception nirs4all.controllers.models.stacking.SourcePredictionError(source_model_id: str, source_model_name: str, original_error: Exception | None = None)[source]
Bases:
MetaModelPredictionErrorRaised when a source model fails to produce predictions.
This occurs when a source model is loaded successfully but fails during prediction, preventing the meta-model from constructing its input features.
- source_model_id
The artifact ID of the failing source model.
- source_model_name
The name of the failing source model.
- original_error
The underlying exception that caused the failure.
- class nirs4all.controllers.models.stacking.StackingCompatibility(value)[source]
Bases:
EnumCompatibility level for stacking with a branch type.
- COMPATIBLE = 'compatible'
- COMPATIBLE_WITH_WARNINGS = 'compatible_with_warnings'
- NOT_SUPPORTED = 'not_supported'
- WITHIN_PARTITION_ONLY = 'within_partition_only'
- class nirs4all.controllers.models.stacking.StackingTaskType(value)[source]
Bases:
EnumTask type for stacking.
- REGRESSION
Regression task using y_pred as features.
- BINARY_CLASSIFICATION
Binary classification (2 classes).
- MULTICLASS_CLASSIFICATION
Multi-class classification (>2 classes).
- UNKNOWN
Could not determine task type.
- BINARY_CLASSIFICATION = 'binary_classification'
- MULTICLASS_CLASSIFICATION = 'multiclass_classification'
- REGRESSION = 'regression'
- UNKNOWN = 'unknown'
- class nirs4all.controllers.models.stacking.TaskTypeDetector(prediction_store: Predictions)[source]
Bases:
objectDetects task type from prediction metadata.
Uses prediction store metadata and y_proba presence to determine whether the stacking involves regression or classification.
- detect(source_model_names: List[str], context: ExecutionContext) ClassificationInfo[source]
Detect task type from source model predictions.
Examines predictions from source models to determine task type and gather classification metadata.
- Parameters:
source_model_names – List of source model names to examine.
context – Execution context with branch info.
- Returns:
ClassificationInfo with detected task type and metadata.
- class nirs4all.controllers.models.stacking.TrainingSetReconstructor(prediction_store: Predictions, source_model_names: List[str], stacking_config: StackingConfig | None = None, reconstructor_config: ReconstructorConfig | None = None, source_model_branch_map: Dict[str, int | None] | None = None)[source]
Bases:
objectReconstructs meta-model training set from out-of-fold predictions.
This is the core class for Phase 2 of the meta-model stacking implementation. It handles the critical task of collecting OOF predictions from source models and constructing feature matrices for the meta-learner.
The fundamental invariant is: No sample sees predictions from a model trained on that sample. This prevents data leakage.
- prediction_store
Predictions storage for accessing source predictions.
- source_model_names
List of source model names to use.
- stacking_config
Configuration for coverage and aggregation strategies.
- reconstructor_config
Internal configuration for reconstruction.
- fold_validator
Validator for fold alignment.
Example
>>> reconstructor = TrainingSetReconstructor( ... prediction_store=predictions, ... source_model_names=["PLS", "RF", "XGB"], ... stacking_config=StackingConfig( ... coverage_strategy=CoverageStrategy.DROP_INCOMPLETE, ... test_aggregation=TestAggregation.MEAN ... ) ... ) >>> result = reconstructor.reconstruct(dataset, context) >>> print(f"Coverage: {result.coverage_ratio:.1%}") >>> print(f"Features: {result.feature_names}")
- reconstruct(dataset: SpectroDataset, context: ExecutionContext, y_train: ndarray | None = None, y_test: ndarray | None = None, use_proba: bool = False) ReconstructionResult[source]
Reconstruct meta-model training and test sets from predictions.
Collects out-of-fold predictions for training samples and aggregated predictions for test samples.
Phase 5 Enhancement: Supports classification tasks with probability features for binary and multiclass classification.
- Parameters:
dataset – SpectroDataset for sample indices.
context – Execution context with partition and branch info.
y_train – Optional pre-computed training targets.
y_test – Optional pre-computed test targets.
use_proba – If True, use probability predictions for classification.
- Returns:
ReconstructionResult containing meta-feature matrices and metadata.
- Raises:
ValueError – If no source models found or critical validation fails.
- validate_branch_compatibility(context: ExecutionContext) ValidationResult[source]
Validate branch compatibility for stacking.
Checks that the current branch context is compatible with stacking based on the configured BranchScope.
- Parameters:
context – Execution context with branch info.
- Returns:
ValidationResult with any errors or warnings.
- class nirs4all.controllers.models.stacking.ValidationResult(errors: ~typing.List[~nirs4all.controllers.models.stacking.reconstructor.ValidationError] = <factory>, warnings: ~typing.List[~nirs4all.controllers.models.stacking.reconstructor.ValidationWarning] = <factory>)[source]
Bases:
objectContainer for validation errors and warnings.
Accumulates validation issues during fold alignment and coverage checks.
- errors
List of validation errors (critical issues).
- warnings
List of validation warnings (non-critical issues).
- is_valid
True if no errors (warnings are allowed).
Example
>>> result = ValidationResult() >>> result.add_error("FOLD_MISMATCH", "Folds don't align") >>> result.add_warning("PARTIAL_COVERAGE", "80% coverage") >>> if not result.is_valid: ... raise ValueError(result.format_errors())
- add_error(code: str, message: str, details: Dict[str, Any] | None = None) None[source]
Add a validation error.
- add_warning(code: str, message: str, details: Dict[str, Any] | None = None) None[source]
Add a validation warning.
- errors: List[ValidationError]
- merge(other: ValidationResult) None[source]
Merge another validation result into this one.
- warnings: List[ValidationWarning]
- nirs4all.controllers.models.stacking.build_meta_feature_info(source_model_names: List[str], classification_info: ClassificationInfo, use_proba: bool = False, name_pattern: str = '{model_name}_pred') MetaFeatureInfo[source]
Build MetaFeatureInfo from source models and classification info.
- Parameters:
source_model_names – List of source model names.
classification_info – Classification metadata.
use_proba – Whether probability features are used.
name_pattern – Pattern for feature names.
- Returns:
MetaFeatureInfo with all mappings populated.
- nirs4all.controllers.models.stacking.detect_branch_type(context: ExecutionContext) BranchType[source]
Detect the type of branching from execution context.
Convenience function for quick branch type detection.
- Parameters:
context – Execution context with branch info.
- Returns:
Detected BranchType enum value.
- nirs4all.controllers.models.stacking.detect_stacking_level(prediction_store: Predictions, source_candidates: List[ModelCandidate], context: ExecutionContext) int[source]
Convenience function for detecting stacking level.
- Parameters:
prediction_store – Predictions storage.
source_candidates – List of candidate source models.
context – Execution context.
- Returns:
Detected stacking level.
- nirs4all.controllers.models.stacking.get_disjoint_branch_info(context: ExecutionContext) Dict[str, Any] | None[source]
Get information about the disjoint branch if applicable.
- Parameters:
context – Execution context with branch info.
- Returns:
Dict with partition info, or None if not a disjoint branch. Keys may include:
partition_type: “metadata” or “sample”
column: Metadata column name (for metadata partitioner)
partition_value: Value(s) for this partition
sample_indices: List of sample indices in this partition
n_samples: Number of samples in this partition
- nirs4all.controllers.models.stacking.is_disjoint_branch(context: ExecutionContext) bool[source]
Check if the current branch context represents disjoint sample branching.
Disjoint branches partition samples into non-overlapping sets, where each sample exists in exactly ONE branch. This is in contrast to copy branches where all branches see all samples.
- Disjoint branch types:
METADATA_PARTITIONER: Branches by metadata column value
SAMPLE_PARTITIONER: Branches by outlier status
- Copy branch types:
PREPROCESSING: All branches see all samples
GENERATOR: All branches see all samples (model variants)
- Parameters:
context – Execution context with branch info.
- Returns:
True if current context represents a disjoint sample branch.
- nirs4all.controllers.models.stacking.is_stacking_compatible(context: ExecutionContext) bool[source]
Quick check if stacking is compatible with current context.
- Parameters:
context – Execution context.
- Returns:
True if stacking is likely compatible.
- nirs4all.controllers.models.stacking.stacking_config_from_dict(data: Dict[str, Any]) StackingConfig[source]
Create StackingConfig from dictionary.
- Parameters:
data – Dictionary with config values.
- Returns:
StackingConfig instance.
- nirs4all.controllers.models.stacking.stacking_config_to_dict(config: StackingConfig) Dict[str, Any][source]
Convert StackingConfig to serializable dictionary.
- Parameters:
config – StackingConfig instance.
- Returns:
Dictionary with string enum values.
- nirs4all.controllers.models.stacking.validate_all_branches_scope(prediction_store: Predictions, source_candidates: List[ModelCandidate], context: ExecutionContext) CrossBranchValidationResult[source]
Convenience function for validating BranchScope.ALL_BRANCHES.
- Parameters:
prediction_store – Predictions storage.
source_candidates – List of candidate source models.
context – Execution context.
- Returns:
CrossBranchValidationResult with compatibility info.
- nirs4all.controllers.models.stacking.validate_multi_level_stacking(prediction_store: Predictions, meta_model_name: str, source_candidates: List[ModelCandidate], context: ExecutionContext, max_level: int = 3, allow_meta_sources: bool = True) LevelValidationResult[source]
Convenience function for validating multi-level stacking.
- Parameters:
prediction_store – Predictions storage.
meta_model_name – Name of the meta-model.
source_candidates – List of candidate source models.
context – Execution context.
max_level – Maximum allowed stacking level.
allow_meta_sources – Whether to allow meta-model sources.
- Returns:
LevelValidationResult with validation status.