Project: Calibration Pipeline

Model Comparison, Multi-Dataset Fitting, and Hybrid Optimization

NISP dispersion calibration — autonomous work

Project Roadmap

#PhaseGoal
1ML model comparison (single dataset)Find the best ML residual corrector using MLflow
2Per-dataset fittingApply full pipeline to all 6 datasets
3Multi-dataset fittingConstrain shared vs specific parameters jointly
4Joint refinementSimultaneous physics + ML optimization
5Comparison with literatureEvaluate against published results (arXiv 2506.08378)
6Scientific reportDocument methods, results, and conclusions
From this point, the implementation is entirely yours. This document provides the goals, the strategy, and the relevant documentation links. No code is provided.

1. ML Model Comparison on a Single Dataset

Starting from the optimized physical model of section 3, you will now systematically compare several ML models for residual correction, and track all experiments with MLflow.
  • Dataset: rgs000_0.csv
  • Input: (y_nisp, z_nisp, wavelength)
  • Target: residuals r_y, r_z from your fitted physical model
  • Metric: RMSE on the test set (80/20 split)
Every model + hyperparameter combination must be logged as a separate MLflow run.

MLflow: Experiment Tracking

MLflow records parameters, metrics, and artifacts for each run, enabling reproducible comparison.

Key concepts
Experiment: a named group of runs
Run: one training trial (model + hyperparams)
Parameters: logged with mlflow.log_param
Metrics: logged with mlflow.log_metric
Minimal usage pattern
  1. Create or set an experiment
  2. Start a run with mlflow.start_run()
  3. Log params and metrics inside the run
  4. End the run
  5. Compare runs in the UI: mlflow ui
Docs: https://mlflow.org/docs/latest/tracking.html

Models to Compare

ModelKey hyperparameters to varysklearn class
Linear RegressionNone (baseline)LinearRegression
Random Forestn_estimators, max_depthRandomForestRegressor
Gradient Boostingmax_iter, max_depth, learning_rateHistGradientBoostingRegressor
SVMC, kernel, epsilonSVR
MLP (neural net)hidden_layer_sizes, activation, alphaMLPRegressor
For each model, test at least 3 hyperparameter configurations. Log each as a separate MLflow run.
Docs: https://scikit-learn.org/stable/supervised_learning.html

Systematic Hyperparameter Search

Instead of trying hyperparameters manually, use GridSearchCV or RandomizedSearchCV to automate the search.
1. Define a parameter grid (dict of lists)
2. Pass it to GridSearchCV(estimator, param_grid, cv=5, scoring="neg_root_mean_squared_error")
3. Fit on the training set
4. Read .best_params_ and .best_score_
5. Log the best result to MLflow
Use RandomizedSearchCV for large grids (MLP, SVM). It samples randomly instead of exhaustively.
Docs: https://scikit-learn.org/stable/modules/grid_search.html

Task 1 — Systematic ML Comparison

  1. Install and import MLflow. Create an experiment named "residual_correction".
  2. For each model: run a hyperparameter search. Log best params, train RMSE, test RMSE, and train/test ratio per run.
  3. Run mlflow ui and compare all runs. Identify the best model for r_y and for r_z.
  4. Plot: predicted vs actual residuals, and histogram of residuals before/after ML correction.
Expected output: one MLflow experiment with 15–30 runs, a results table, and the best model saved to disk.
MLflow sklearn: https://mlflow.org/docs/latest/python_api/mlflow.sklearn.html

Analyzing the Results

After the comparison, answer the following questions in your report:

  1. Which model achieves the lowest test RMSE? By how much does it improve over the physical model alone?
  2. Is the improvement in r_y and r_z symmetric? Why or why not?
  3. Which model overfits the most (largest train/test RMSE ratio)? Is this expected?
  4. Does the best model generalize? Test it on a different dataset without retraining.
  5. Are the residuals after ML correction approximately random, or is there remaining structure?

2. Applying the Pipeline to All Datasets

You have a working pipeline: physical model optimization + ML residual correction. Apply it to each of the 6 calibration configurations.
DatasetGWA angleTilt
rgs000_0
rgs000_m4−4°
rgs000_p4+4°
rgs180_0180°
rgs180_m4180°−4°
rgs180_p4180°+4°
For each dataset: (1) optimize physical parameters, (2) apply best ML correction from task 1, (3) log results to a new MLflow experiment "per_dataset".

Task 2 — Per-Dataset Results

Steps to follow:
  1. Wrap your pipeline into a single reusable function that takes a dataset path and returns optimal parameters + RMSE.
  2. Run it on all 6 datasets. Log physical RMSE and hybrid RMSE per dataset.
  3. Collect the fitted physical parameters in a table (one row per dataset).
  4. Identify which parameters are consistent across datasets (candidates for global fitting in step 3).
  5. Compare RMSE across datasets: which configuration is hardest to fit? Propose a physical explanation.
Key question: are the collimator parameters consistent across all 6 datasets? If yes, they can be treated as global parameters in step 3.

Parameter Consistency Analysis

After fitting each dataset independently, compare the optimal parameters.

Physically shared
These describe the hardware — constant across all configurations:
  • Collimator focal length
  • Camera focal length
  • Prism refractive index
  • Grating period
Configuration-specific
These change per dataset:
  • GWA rotation angle
  • Detector tilt angle
  • Alignment offsets
If a nominally shared parameter converges to very different values across datasets, this signals a model deficiency or a wrong assumption about which parameters are truly global.

3. Multi-Dataset Fitting

The 6 calibration datasets share the same physical instrument.
Some parameters are shared, others are dataset-specific.

Shared parameters
— Collimator focal length
— Camera focal length
— Prism angles / index
— Grating period
Dataset-specific
— GWA angle (per configuration)
— Detector alignment offsets
— Grism rotation
Strategy: build a combined cost function that sums the RMSE across all datasets, with shared parameters appearing in every term.
# Schematic only
def cost_combined(theta):
    shared, specific = unpack(theta)
    total = 0
    for dataset, params in zip(datasets, specific):
        pred = model.forward(dataset.inputs, shared, params)
        total += mse(pred, dataset.targets)
    return total

3. Multi-Dataset Optimization Strategy

Fitting each dataset independently does not enforce consistency of shared parameters. A structured alternating strategy does.
Stage 1. Fit physical model independently on each dataset (no ML correction)
Stage 2. Fix dataset-specific parameters; optimize shared parameters jointly on all 6 datasets
Stage 3. Fix shared parameters; re-optimize specific parameters on each dataset
Stage 4. Fix all physical parameters; add ML residual correction per dataset
This is an alternating optimization strategy. Stages 2 and 3 can be iterated until convergence before applying stage 4.

Stage 2: Joint Optimization of Shared Parameters

The combined cost sums over all datasets, with shared parameters:

\[\mathcal{L}_\text{joint}(\theta_\text{shared}) = \sum_{d=1}^{6} \mathcal{L}_d(\theta_\text{shared},\, \theta_d^*)\]

where θ_d* are the dataset-specific parameters fixed from stage 1.

Steps:
  1. Load all 6 datasets and their stage-1 specific parameters.
  2. Build a combined cost function over all datasets.
  3. Optimize only the shared parameters.
  4. Compare resulting shared parameters to per-dataset stage-1 values.

Stages 3 and 4

Stage 3 — Re-optimize specific parameters
Fix the shared parameters from stage 2. Re-fit dataset-specific parameters independently on each dataset. This is a refinement step — RMSE should improve slightly.
Stage 4 — ML correction
With all physical parameters fixed, compute residuals on each dataset. Train the best ML model (from task 1) per dataset to correct them.
After all 4 stages, compare the final RMSE per dataset against the independent results from task 2.
Expected: the joint strategy produces more consistent and slightly lower RMSE.

Task 3 — Implement the Multi-Dataset Strategy

Steps to follow:
  1. Stage 1: use results from task 2 (already done).
  2. Stage 2: build a combined cost function. Optimize shared parameters. Log to MLflow experiment "stage2".
  3. Stage 3: re-fit specific parameters with shared ones fixed. Log to "stage3".
  4. Stage 4: add ML correction per dataset. Log hybrid RMSE to "stage4".
  5. Build a comparison table: RMSE per dataset × strategy (independent / joint / joint+ML).
  6. Which datasets benefit most from joint fitting? Which parameters changed most between stages?

4. Joint Refinement of Physics and ML

This section is more advanced. Attempt it only after completing tasks 1–3.
In the sequential approach, the physical model and the ML corrector are trained one after the other. In joint refinement, both are optimized together, with a penalty to prevent the ML from dominating.
\[\mathcal{L}_\text{total}(\theta, \phi) = \underbrace{\mathcal{L}_\text{data}(\theta, \phi)}_{\text{prediction error}} + \lambda \underbrace{\Omega(\phi)}_{\text{ML complexity penalty}}\]

θ = physical parameters, φ = ML model, λ = regularization weight

The Regularization Penalty

Without a penalty, the optimizer may delegate all prediction error to the ML component, making the physical parameters meaningless.

Possible penalty choices for Ω(φ):

PenaltyEffect
\(\|\delta y_\text{ML}\|^2\)Forces ML correction to be small overall
\(\text{Var}(\delta y_\text{ML})\)Forces correction to be spatially uniform
Fraction of variance explained by MLDirectly caps ML contribution
Start with the L2 norm penalty. Tune λ by monitoring the ratio of ML-explained variance to total variance.

Task 4 — Joint Refinement

Steps to follow:
  1. Define a combined loss: prediction MSE + λ × L2 norm of ML corrections.
  2. Implement an alternating optimization loop: (a) optimize θ with φ fixed; (b) retrain φ with the penalized objective; repeat.
  3. Run for several values of λ (e.g. 0, 0.01, 0.1, 1.0). Log each to MLflow.
  4. For each λ: report physical RMSE, ML correction RMS magnitude, and hybrid RMSE.
  5. Plot ML correction magnitude vs λ. It should decrease monotonically.
  6. Identify the λ that gives the best trade-off between accuracy and physical interpretability.
If λ = 0 gives no improvement over the sequential approach, the joint refinement does not add value. That is also a valid scientific result.

5. Comparison with Published Results

The reference paper (arXiv 2506.08378) reports calibration accuracy for NISP dispersion. Compare your results against theirs.

Before comparing, verify that you are using the same:

  • Definition of the residual (predicted − observed, or opposite?)
  • Metric (RMSE, MAE, or other?)
  • Unit (mm, pixels, arcsec?)
  • Dataset (same configurations? same wavelength range?)
If your model differs from the reference (fewer parameters, different optics), the comparison is approximate. State this explicitly in your report.

Reference: https://arxiv.org/abs/2506.08378

Task 5 — Read and Compare

Steps to follow:
  1. Read the results section of arXiv 2506.08378. Note all reported RMSE values and their units.
  2. Identify which calibration configurations and wavelength ranges they use.
  3. Convert your RMSE to the same unit if necessary (1 NISP pixel ≈ 0.3 mm).
  4. Fill the comparison table on the next slide.
  5. Identify the main sources of discrepancy between your approach and the reference.
  6. Propose at least one concrete improvement that could close the gap.

Comparison Table

Fill this table. Use test-set RMSE only. Units: mm.

ModelRMSE y (mm)RMSE z (mm)Source
Physical model (after fit)Task 2
Hybrid (best ML, single dataset)Task 1
Hybrid (joint fitting)Task 3
Hybrid (joint refinement)Task 4
Reference (arXiv 2506.08378)Paper
If your result is significantly worse than the reference: identify which model component is likely responsible and propose an improvement.

Project Summary

TaskDeliverableKey tool
1. ML comparisonMLflow experiment, best model savedsklearn + MLflow
2. Per-dataset fitting6 RMSE values, parameter tablescipy.optimize
3. Joint fittingShared parameters, RMSE per stageCombined cost function
4. Joint refinementλ sweep, ML magnitude plotCustom penalized loss
5. LiteratureComparison tablearXiv 2506.08378
This project is evaluated on the quality of analysis, not only on achieving a low RMSE.
Justify every methodological choice.