firecrown.app.analysis ====================== .. py:module:: firecrown.app.analysis .. autoapi-nested-parse:: Analysis building infrastructure for Firecrown. Provides base classes and utilities for building complete analysis setups with data files, factory files, and framework-specific configurations. Public API (backward compatibility guaranteed): - AnalysisBuilder: Base class for building analyses - Frameworks: Enum of supported frameworks - Model: Model parameter definition - Parameter: Individual parameter definition Internal modules (prefixed with _) are implementation details and may change without notice. Only use the public API exported in __all__. Attributes ---------- .. autoapisummary:: firecrown.app.analysis.Prior firecrown.app.analysis.COSMO_DESC firecrown.app.analysis.CCL_COSMOLOGY_MINIMAL_SET Classes ------- .. autoapisummary:: firecrown.app.analysis.AnalysisBuilder firecrown.app.analysis.Frameworks firecrown.app.analysis.Model firecrown.app.analysis.Parameter firecrown.app.analysis.ConfigGenerator firecrown.app.analysis.FrameworkCosmology firecrown.app.analysis.PriorUniform firecrown.app.analysis.PriorGaussian firecrown.app.analysis.CCLCosmologySpec firecrown.app.analysis.CosmosisConfigGenerator firecrown.app.analysis.NumCosmoConfigGenerator firecrown.app.analysis.CobayaConfigGenerator Functions --------- .. autoapisummary:: firecrown.app.analysis.get_generator firecrown.app.analysis.download_from_url firecrown.app.analysis.copy_template Package Contents ---------------- .. py:class:: AnalysisBuilder Bases: :py:obj:`firecrown.app.logging.Logging` .. autoapi-inheritance-diagram:: firecrown.app.analysis.AnalysisBuilder :parts: 1 Base class for Firecrown analysis builders. Orchestrates the generation of complete analysis examples through a phased workflow: 1. Generate/download SACC data file 2. Generate likelihood factory file 3. Generate build parameters 4. Generate model parameters 5. Generate framework-specific configuration files Subclasses implement data-specific methods while the base class handles workflow orchestration and framework configuration delegation. .. py:attribute:: description :type: ClassVar[str] Human-readable description of what this analysis demonstrates. .. py:attribute:: output_path :type: Annotated[pathlib.Path, typer.Argument(help='Directory where example files will be generated', show_default=True)] .. py:attribute:: prefix :type: Annotated[str, typer.Option(help="Prefix for generated filenames (e.g., 'analysis1' creates 'analysis1.sacc')", show_default=True)] .. py:attribute:: target_framework :type: Annotated[firecrown.app.analysis._types.Frameworks, typer.Option(help='Framework to generate example for', show_default=True, case_sensitive=False)] .. py:attribute:: sacc_format :type: Annotated[firecrown.app.sacc.SaccFormat, typer.Option(help='SACC file format.', show_default=True)] .. py:attribute:: use_absolute_path :type: Annotated[bool, typer.Option(help='Use absolute file paths in configuration files', show_default=True)] :value: True .. py:attribute:: cosmology_spec :type: Annotated[pathlib.Path | None, typer.Option(help='Path to cosmology specification file', show_default=True)] :value: None .. py:method:: __post_init__() Initialize and execute the complete analysis generation workflow. .. py:method:: generate_sacc(output_path) :abstractmethod: Generate or download the SACC data file. :param output_path: Directory where files should be created :return: Path to the generated SACC file .. py:method:: generate_factory(output_path, sacc) :abstractmethod: Generate the likelihood factory Python file. :param output_path: Directory where files should be created :param sacc: Path to the SACC data file :return: Path to the generated factory file .. py:method:: get_build_parameters(sacc_path) :abstractmethod: Create build parameters for likelihood initialization. :param sacc_path: Path to the SACC data file :return: Build parameters (typically includes sacc_file path) .. py:method:: get_models() :abstractmethod: Define model parameters for sampling. :return: List of models with their parameters (priors, bounds, etc.) .. py:method:: required_cosmology() :abstractmethod: Return whether the analysis requires a cosmology. :return: True if the analysis requires a cosmology, False otherwise .. py:method:: cosmology_analysis_spec() Return the cosmology analysis specification. :return: The cosmology analysis specification .. py:method:: get_sacc_file(sacc_path) Return the path to the SACC data file. Returns either an absolute or relative path based on the use_absolute_path setting. When use_absolute_path is True, returns the full absolute path. Otherwise returns just the filename. :param sacc_path: Path to the SACC data file :return: Path to the SACC file as a string, either absolute or relative .. py:method:: get_options_desc() Return a description of the analysis options. Subclasses can override this method to provide additional information about the options used in the analysis. :return: Description of analysis options .. py:class:: Frameworks Bases: :py:obj:`enum.StrEnum` .. autoapi-inheritance-diagram:: firecrown.app.analysis.Frameworks :parts: 1 Statistical analysis frameworks supported by Firecrown. Each framework has its own configuration generator that produces framework-specific files for cosmological parameter estimation. .. py:attribute:: COBAYA :value: 'cobaya' .. py:attribute:: COSMOSIS :value: 'cosmosis' .. py:attribute:: NUMCOSMO :value: 'numcosmo' .. py:class:: Model(/, **data) Bases: :py:obj:`pydantic.BaseModel` .. autoapi-inheritance-diagram:: firecrown.app.analysis.Model :parts: 1 Model definition with multiple parameters. Groups related parameters (e.g., all photo-z shifts, all galaxy biases) into a named model for organization in configuration files. .. py:attribute:: model_config Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict]. .. py:attribute:: name :type: str .. py:attribute:: description :type: str .. py:attribute:: parameters :type: list[Parameter] .. py:method:: model_post_init(context, /) Validate that parameter names are unique. Creates a dictionary of parameters by name. .. py:method:: has_priors() Check if any parameters have priors defined. :return: True if at least one parameter has a prior; False otherwise .. py:method:: __getitem__(key) Return the value for the given key. If the key has not been used, add it to the set of used keys. :param key: key :return: value .. py:method:: __contains__(key) Return True if the key is in the map, False otherwise. :param key: key :return: True if the key is in the map, False otherwise .. py:class:: Parameter(/, **data) Bases: :py:obj:`pydantic.BaseModel` .. autoapi-inheritance-diagram:: firecrown.app.analysis.Parameter :parts: 1 Model parameter with sampling metadata. Defines a single parameter for cosmological or systematic modeling, including its prior bounds, default value, and whether it's free or fixed. .. py:attribute:: model_config Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict]. .. py:attribute:: name :type: str .. py:attribute:: symbol :type: str .. py:attribute:: lower_bound :type: float .. py:attribute:: upper_bound :type: float .. py:attribute:: scale :type: float :value: 0.0 .. py:attribute:: abstol :type: float :value: 0.0 .. py:attribute:: default_value :type: float .. py:attribute:: free :type: bool .. py:attribute:: prior :type: Prior | None :value: None .. py:method:: fill_defaults(data) :classmethod: Validate that scale is positive if provided. .. py:method:: validate_bounds() Validate that lower_bound < upper_bound. .. py:method:: from_tuple(name, symbol, lower_bound, upper_bound, default_value, free, prior = None) :classmethod: Create Parameter from tuple of values. .. py:class:: ConfigGenerator Bases: :py:obj:`abc.ABC` .. autoapi-inheritance-diagram:: firecrown.app.analysis.ConfigGenerator :parts: 1 Abstract base for framework-specific configuration generators. Uses a builder pattern with phased state management: 1. Create generator with output settings 2. Add components: add_sacc(), add_factory(), add_build_parameters(), add_models() 3. Write configuration: write_config() Subclasses implement write_config() to generate framework-specific files. .. py:attribute:: framework :type: ClassVar[Frameworks] .. py:attribute:: output_path :type: pathlib.Path .. py:attribute:: prefix :type: str .. py:attribute:: use_absolute_path :type: bool .. py:attribute:: cosmo_spec :type: CCLCosmologySpec .. py:attribute:: required_cosmology :type: FrameworkCosmology .. py:attribute:: sacc_path :type: pathlib.Path | None :value: None .. py:attribute:: factory_source :type: str | pathlib.Path | None :value: None .. py:attribute:: build_parameters :type: firecrown.likelihood.NamedParameters | None :value: None .. py:attribute:: models :type: list[Model] :value: [] .. py:method:: add_sacc(sacc_path) Add SACC data file path to generator state. :param sacc_path: Path to SACC data file .. py:method:: add_factory(factory_source) Add likelihood factory source to generator state. :param factory_source: Path to factory Python file or YAML module string .. py:method:: add_build_parameters(build_parameters) Add build parameters to generator state. :param build_parameters: Parameters for likelihood initialization .. py:method:: add_models(models) Add model parameters to generator state. :param models: List of models with sampling parameters .. py:method:: write_config() :abstractmethod: Write framework-specific configuration files using accumulated state. .. py:class:: FrameworkCosmology Bases: :py:obj:`enum.StrEnum` .. autoapi-inheritance-diagram:: firecrown.app.analysis.FrameworkCosmology :parts: 1 Level of cosmology computation required by the framework. Controls whether frameworks include Boltzmann solvers (CAMB/CLASS) and what level of computation they perform. .. py:attribute:: NONE :value: 'none' .. py:attribute:: BACKGROUND :value: 'background' .. py:attribute:: LINEAR :value: 'linear' .. py:attribute:: NONLINEAR :value: 'nonlinear' .. py:data:: Prior .. py:class:: PriorUniform(/, **data) Bases: :py:obj:`pydantic.BaseModel` .. autoapi-inheritance-diagram:: firecrown.app.analysis.PriorUniform :parts: 1 Uniform (flat) prior over a bounded interval [lower, upper]. .. py:attribute:: model_config Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict]. .. py:attribute:: lower :type: float .. py:attribute:: upper :type: float .. py:method:: model_post_init(_, /) Validate that lower < upper. .. py:class:: PriorGaussian(/, **data) Bases: :py:obj:`pydantic.BaseModel` .. autoapi-inheritance-diagram:: firecrown.app.analysis.PriorGaussian :parts: 1 Gaussian (normal) prior with specified mean and standard deviation. .. py:attribute:: model_config Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict]. .. py:attribute:: mean :type: float .. py:attribute:: sigma :type: float .. py:method:: model_post_init(_, /) Validate that sigma > 0. .. py:class:: CCLCosmologySpec(/, **data) Bases: :py:obj:`Model` .. autoapi-inheritance-diagram:: firecrown.app.analysis.CCLCosmologySpec :parts: 1 CCL cosmology specification model. A specialized Model that represents the cosmological parameters used in CCL-based analyses. .. py:attribute:: name :type: str :value: 'ccl_cosmology' .. py:attribute:: description :type: str :value: 'CCL cosmology specification' .. py:attribute:: mass_split :type: str :value: 'normal' .. py:attribute:: transfer_function :type: str | Any :value: 'boltzmann_camb' .. py:attribute:: matter_power_spectrum :type: str | Any :value: 'halofit' .. py:attribute:: extra_parameters :type: firecrown.modeling_tools.CAMBExtraParams | None :value: None .. py:method:: model_post_init(context, /) Validate that all parameters are cosmological. .. py:method:: to_ccl_cosmology() Convert to CCL cosmology dictionary. :return: Dictionary of cosmological parameters for CCL .. py:method:: vanilla_lcdm() :classmethod: Create a vanilla LCDM cosmology analysis spec with standard parameters. .. py:method:: vanilla_lcdm_with_neutrinos() :classmethod: Create a vanilla LCDM cosmology analysis spec with standard parameters. .. py:method:: get_num_massive_neutrinos() Get the number of massive neutrinos defined in the cosmology. .. py:method:: get_amplitude_parameter() Get the amplitude parameter for the power spectrum. .. py:data:: COSMO_DESC .. py:data:: CCL_COSMOLOGY_MINIMAL_SET :value: ['Omega_c', 'Omega_b', 'Omega_k', 'h', 'n_s', 'Neff', 'm_nu', 'w0', 'wa'] .. py:function:: get_generator(framework, output_path, prefix, use_absolute_path, cosmo_spec, required_cosmology = FrameworkCosmology.NONLINEAR) Factory function to create framework-specific configuration generator. :param framework: Target framework (cosmosis, cobaya, numcosmo) :param output_path: Directory where configuration files will be written :param prefix: Prefix for generated filenames (e.g., 'des_y1' → 'cosmosis_des_y1.ini') :param use_absolute_path: Use absolute paths in configs (True) or relative paths (False) :param cosmo_spec: Cosmology specification with parameters and priors :param required_cosmology: Level of cosmology computation (none/background/linear/nonlinear) :return: Initialized configuration generator ready for component addition :raises ValueError: If framework is not supported .. py:function:: download_from_url(url, output_file, console, description = 'Downloading...') Download file from URL with caching and progress indicator. This function implements a caching mechanism to avoid redundant downloads: 1. Checks if the file exists in $HOME/.firecrown/sacc_files cache 2. If cached, copies from cache to output location 3. If not cached, attempts to download from URL 4. On successful download, saves to both cache and output location 5. If download fails, provides helpful instructions for manual placement This significantly improves performance in testing scenarios and handles offline usage gracefully. :param url: URL to download from :param output_file: Path where file will be saved :param console: Rich console for output :param description: Progress description text :raises SystemExit: If download fails and file is not in cache .. py:function:: copy_template(template_module, output_file) Copy template module file to output location. :param template_module: Python module to copy :param output_file: Destination path .. py:class:: CosmosisConfigGenerator Bases: :py:obj:`firecrown.app.analysis._types.ConfigGenerator` .. autoapi-inheritance-diagram:: firecrown.app.analysis.CosmosisConfigGenerator :parts: 1 CosmoSIS configuration generator. Generates CosmoSIS INI files for parameter estimation: - cosmosis_{prefix}.ini: Pipeline configuration with modules and settings - cosmosis_{prefix}_values.ini: Parameter values and sampling bounds - cosmosis_{prefix}_priors.ini: Prior specifications (if priors defined) .. py:attribute:: framework .. py:method:: write_config() Write CosmoSIS configuration. .. py:class:: NumCosmoConfigGenerator Bases: :py:obj:`firecrown.app.analysis._types.ConfigGenerator` .. autoapi-inheritance-diagram:: firecrown.app.analysis.NumCosmoConfigGenerator :parts: 1 NumCosmo configuration generator. Generates NumCosmo YAML files for parameter estimation: - numcosmo_{prefix}.yaml: Experiment configuration with cosmology, dataset, likelihood, and priors - numcosmo_{prefix}.builders.yaml: Model builder definitions for systematic/nuisance parameters Configuration is written in a fresh subprocess to avoid GType conflicts. .. py:attribute:: framework .. py:method:: write_config() Write NumCosmo configuration in a fresh subprocess (safe for GType). .. py:class:: CobayaConfigGenerator Bases: :py:obj:`firecrown.app.analysis._types.ConfigGenerator` .. autoapi-inheritance-diagram:: firecrown.app.analysis.CobayaConfigGenerator :parts: 1 Cobaya configuration generator. Generates a single YAML file for Cobaya parameter estimation: - cobaya_{prefix}.yaml: Complete configuration with theory (CAMB), likelihood (Firecrown), parameters, and sampler settings .. py:attribute:: framework .. py:method:: write_config() Write Cobaya configuration.