harbor run -t openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0191harbor download openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0191Harder version: Robust parameter and prior utilities with edge-case and efficiency considerations
Goal
- Implement a Python package at /app/py21cmmc featuring advanced parameter handling and priors, designed to pass a stricter and broader set of tests.
- Expose:
- py21cmmc.cosmoHammer
- py21cmmc.prior
- Optional: py21cmmc/__init__.py for a clean public API.
- Implement the following modules and classes with the specified behavior and stricter guarantees, including robust error handling, edge-case coverage, and attention to performance for larger inputs.
What to build and where
- Create a Python package at /app/py21cmmc/ (not a single file). It must expose:
- py21cmmc.cosmoHammer
- py21cmmc.prior
- Implement the following modules and classes with the specified behavior and enhanced requirements:
- py21cmmc/cosmoHammer.py
- py21cmmc/prior.py
- Optional: py21cmmc/__init__.py to expose the package API cleanly
Key expected interfaces and behaviors
1) Params class (py21cmmc.cosmoHammer)
- Purpose: hold parameter definitions and allow convenient iteration over parameter values while exposing the corresponding names, with robust behavior for edge cases and larger scales.
- Constructor signature:
- Params(*args)
- Each arg is a tuple (name, values) where:
- name is a string (e.g., "L_X")
- values is a list-like sequence of numbers, e.g., [40.0, 38.0, 42.0, 0.05]
- Features and compatibility:
- Iteration:
- Implement __iter__ to yield the inner numeric sequences (the "rows"), in the order provided.
- Structure and metadata:
- Implement a keys attribute/property that returns the list of parameter names in the same order as provided.
- Implement __len__ to return the number of parameters.
- Optional: __getitem__ to access a parameter’s values by index or by name (support both integer index and name-based lookup for convenience; tests will use iteration but this aids robustness).
- Validation and robustness:
- Validate that each arg is a 2-tuple (name, values) with a string name and a non-empty, finite-numeric sequence for values (reject non-numeric/NaN-Inf gracefully with a clear ValueError).
- Ensure that iteration yields the numeric rows; ap[0] is the first element of the row and ap[-1] is the last, enabling tests like mean = np.array([ap[0] for ap in astro_params]).reshape(1, -1).
- Performance considerations:
- Iteration and property access should be O(number_of_parameters) with minimal overhead; avoid unnecessary copies.
- Compatibility with tests:
- For astro_params used in tests:
- mean = np.array([ap[0] for ap in astro_params]).reshape(1, -1) should yield [40.0, 500.0].
- std = np.array([ap[-1] for ap in astro_params]).reshape(1, -1) should yield [0.05, 20.0].
- This requires that iterating astro_params yields per-parameter numeric rows in the declared order.
2) PriorBase (py21cmmc.prior)
- Purpose: abstract base for priors.
- Behavior:
- computePrior(theta) must raise NotImplementedError by default (tests explicitly expect this for the base class).
- computeLikelihood(theta) should be provided as an alias to computePrior(theta) in the base class (or as a simple wrapper that can be overridden by subclasses).
3) PriorFunction (py21cmmc.prior)
- Purpose: a prior defined by an external function f over parameter values.
- Constructor signature:
- PriorFunction(arg_names=None, f=None)
- arg_names can be a list of parameter names, or any object that yields the parameter names when turned into a list. The tests pass astro_params.keys (which should provide the ordered parameter names) but your implementation must be robust to any iterable or callable producing a name sequence.
- f is an optional callable; if provided, it should accept a 1D vector theta of length equal to the number of parameters and return a scalar (the log-prior or log-likelihood value for comparison in tests).
- Internal state:
- self.arg_names: a list of parameter names in order
- self.f: the provided function (or None)
- Methods:
- computePrior(theta):
- Validate input length equals len(self.arg_names). If not, raise ValueError with a clear message.
- If self.f is None: raise ValueError (as tests expect for the missing f case).
- Otherwise return the scalar value produced by self.f(theta) (cast to Python float if needed).
- computeLikelihood(theta): alias to computePrior(theta)
- Error handling:
- If arg_names yields an unusual length or contains duplicates, raise a ValueError with a descriptive message.
- Tests expectation:
- When f is provided, computePrior([0.0, 0.0]) must produce the same value as computeLikelihood([0.0, 0.0]).
- When f is not provided, computePrior([0.0, 0.0]) must raise ValueError.
4) PriorGaussianKDE (py21cmmc.prior)
- Purpose: a prior represented by a Gaussian Kernel Density Estimate (KDE) built from a chain of samples, with optional whitening for numerical stability and performance on large datasets.
- Constructor signature:
- PriorGaussianKDE(chain, arg_names=None, bandwidth=None, whiten=True)
- chain: a 2D numpy array of shape (N, D) representing N samples of D parameters (as in tests, N=100, D=2)
- arg_names: list of parameter names (same as for PriorFunction; tests pass astro_params.keys)
- bandwidth: optional smoothing parameter passed through to gaussian_kde as bw_method
- whiten: boolean flag; if True, apply a deterministic whitening transform to the chain before KDE to improve conditioning and performance on larger datasets; if False, skip whitening. This flag must be honored consistently when computing the logpdf for arbitrary theta.
- Internal behavior:
- Build a Gaussian KDE from the provided chain using scipy.stats.gaussian_kde:
- kde = gaussian_kde(chain_whitened.T, bw_method=bandwidth) if whitening is applied, else gaussian_kde(chain.T, bw_method=bandwidth)
- Whitening implementation (when whiten is True):
- Compute a stable whitening transform from the chain:
- Compute mean vector mu (shape D)
- Center data: Xc = chain - mu
- Compute covariance matrix Cov = Xc.T @ Xc / max(N-1, 1)
- Eigen-decompose Cov: w, V = np.linalg.eigh(Cov)
- Sort eigenvalues in descending order and form W = V @ diag(1 / sqrt(w + eps))
- Store mu and W for transforming new theta
- Transform data: chain_whitened = Xc @ W
- Use chain_whitened for KDE fitting
- Robustness and edge cases:
- Handle small N, large D, degenerate covariance (add a small epsilon to eigenvalues)
- Validate shapes; if arg_names is provided, ensure its length matches D
- Methods:
- computePrior(theta):
- Validate input length equals len(self.arg_names). If not, raise ValueError.
- If whitening was applied, transform theta as:
- theta_centered = theta - self.mu
- theta_whitened = theta_centered @ self.W
- return float(self.kde.logpdf(theta_whitened))
- If not whitened: return float(self.kde.logpdf(theta))
- computeLikelihood(theta): alias to computePrior(theta)
- Tests expectation:
- When chain is the full dataset and with default whitening, computePrior/computeLikelihood should return consistent logpdf values.
- When chain is replaced with mean-based data and bandwidth adjusted, computing PriorGaussianKDE(chain=mean, arg_names=..., bandwidth=1.0, whiten=False) and computing its computePrior([0.0, 0.0]) should be numerically consistent with an equivalent PriorFunction defined by an f that encodes the same Gaussian logpdf (or test-provided equivalent). The implementation should be stable for this scenario.
5) DataWhitener (py21cmmc.prior)
- Purpose: a simple data whitening/unwhitening utility with multiple algorithms. Enhanced to be robust to edge-cases and large inputs.
- Constructor signature:
- DataWhitener(algo=None)
- algo can be one of: None, "rescale", "PCA", "ZCA"
- Behavior:
- fit(X): fit internal parameters for the chosen algorithm from data X
- If algo not in {None, "rescale", "PCA", "ZCA"}: raise ValueError with a descriptive message.
- whiten(X): apply the whitening transform to X
- X can be 1D (length D) or 2D (N, D). In both cases, return the transformed array with the same trailing dimension D.
- None: return X unchanged
- "rescale": center by mean and scale by standard deviation per feature (robust to NaNs by erroring out if NaNs present; prefer to raise to avoid silent propagation)
- "PCA": perform PCA-based whitening with invertible transform:
- Store mean, eigenvalues, and eigenvectors from X during fit
- whitened = (X - mean) @ (eigenvectors @ diag(1/√eigenvalues))
- "ZCA": perform ZCA whitening:
- whitened = (X - mean) @ (eigenvectors @ diag(1/√eigenvalues) @ eigenvectors.T)
- Inverse transformation:
- unwhiten(Xw): invert the whitening transform back to the original space
- None: return X unchanged
- "rescale": Xw * scale + mean
- "PCA": unwhitened = Xw @ diag(√eigenvalues) @ eigenvectors.T + mean
- "ZCA": unwhitened = Xw @ (eigenvectors @ diag(√eigenvalues) @ eigenvectors.T) + mean
- Tests expectation:
- For each algo in [None, "rescale", "PCA", "ZCA"]:
- dw[algo].fit(chain) should succeed
- dw[algo].unwhiten(dw[algo].whiten(sample)) should have the same shape as sample
- The recovered values should be consistent across the four algorithms (i.e., unwhiten(whiten(x)) approximately equals x for all algorithms)
- dw["bla"] or DataWhitener("bla") must raise ValueError on fit(chain)
- Edge cases and robustness:
- Empty input handling: both whiten and unwhiten must gracefully handle X with shape (0, D) or (N, 0) where appropriate, returning arrays with matching shapes
- Large inputs: ensure operations are vectorized and avoid Python loops; avoid excessive memory copies
- NaN/Inf handling: raise ValueError or propagate as appropriate; do not silently mask NaNs
- 1D input handling: ensure 1D inputs are treated as a single sample with D features
6) Compatibility and packaging requirements
- Use numpy for numerical operations and scipy for KDE and linear algebra when needed.
- The package must be importable as:
- from py21cmmc.cosmoHammer import Params
- from py21cmmc.prior import DataWhitener, PriorBase, PriorFunction, PriorGaussianKDE
- Optional: __init__.py (py21cmmc/__init__.py) can re-export the public API to make imports convenient.
- Tests rely on the behavior described above and on consistent, well-documented error messages for invalid inputs.
Implementation notes and guidance
- Focus on correctness, numerical stability, and clear error messages.
- Prefer explicit input validation and descriptive exceptions over silent failures.
- Strive for efficient, vectorized implementations to handle larger datasets efficiently.
- Maintain compatibility with the existing test expectations while broadening functionality to cover edge cases.
Deliverables
- A working Python package at /app/py21cmmc implementing:
- py21cmmc.cosmoHammer (Params)
- py21cmmc.prior (PriorBase, PriorFunction, PriorGaussianKDE, DataWhitener)
- Optional: py21cmmc/__init__.py exposing a clean public API
- All tests should pass when running pytest in the project environment.
Notes
- If you choose to implement a single module instead of a package, tests will fail because they rely on py21cmmc.cosmoHammer and py21cmmc.prior submodules. The actionable path is to implement a robust package at /app/.