"""Main classes to define High-level Analysis Config and the Analysis Steps."""fromenumimportEnumfromastropyimportunitsasufromgammapy.datasetsimportDatasets,FluxPointsDatasetfromgammapy.estimatorsimportFluxPointsEstimatorfromgammapy.modelingimportFitfromgammapy.utils.metadataimportCreatorMetaDatafromasgardpy.analysis.step_baseimportAnalysisStepBasefromasgardpy.baseimportBaseConfig,EnergyRangeConfigfromasgardpy.versionimport__public_version____all__=["FitAnalysisStep","FitConfig","FluxPointsAnalysisStep","FluxPointsConfig",]# Defining various components of High-level Analysis ConfigclassBackendEnum(str,Enum):"""Config section for a list Fitting backend methods."""minuit="minuit"scipy="scipy"
[docs]classFitConfig(BaseConfig):"""Config section for parameters to use for Fit function."""fit_range:EnergyRangeConfig=EnergyRangeConfig()backend:BackendEnum=BackendEnum.minuitoptimize_opts:dict={}covariance_opts:dict={}confidence_opts:dict={}store_trace:bool=True
[docs]classFluxPointsConfig(BaseConfig):"""Config section for parameters to use for FluxPointsEstimator function."""parameters:dict={"selection_optional":"all"}reoptimize:bool=False
# The main Analysis Steps
[docs]classFitAnalysisStep(AnalysisStepBase):""" Using the Fitting parameters as defined in the Config, with the given datasets perform the fit of the models to the updated list of datasets. """tag="fit"def_run(self):self.fit_params=self.config.fit_paramsself._setup_fit()final_dataset=self._set_datasets()self.fit_result=self.fit.run(datasets=final_dataset)self.log.info(self.fit_result)def_setup_fit(self):""" Setup the Gammapy Fit function with all the provided parameters from the config. """self.fit=Fit(backend=self.fit_params.backend,optimize_opts=self.fit_params.optimize_opts,covariance_opts=self.fit_params.covariance_opts,confidence_opts=self.fit_params.confidence_opts,store_trace=self.fit_params.store_trace,)def_set_datasets(self):""" Prepare each dataset for running the Fit function, by setting the energy range. """en_min=u.Quantity(self.fit_params.fit_range.min)en_max=u.Quantity(self.fit_params.fit_range.max)final_dataset=Datasets()fordatainself.datasets:ifnotisinstance(data,FluxPointsDataset):geom=data.counts.geomdata.mask_fit=geom.energy_mask(en_min,en_max)final_dataset.append(data)returnfinal_dataset
[docs]classFluxPointsAnalysisStep(AnalysisStepBase):""" Using the Flux Points Estimator parameters in the config, and the given datasets and instrument_spectral_info perform the Flux Points Estimation and store the result in a list of flux points for each dataset. """tag="flux-points"def_run(self):self.flux_points=[]datasets,energy_edges=self._sort_datasets_info()fordataset,energy_edgeinzip(datasets,energy_edges,strict=True):self._set_fpe(energy_edge)flux_points=self.fpe.run(datasets=dataset)flux_points.name=dataset.namesflux_points.meta["creation"]=CreatorMetaData()flux_points.meta["creation"].creator+=f", Asgardpy {__public_version__}"flux_points.meta["optional"]={"instrument":flux_points.name,}self.flux_points.append(flux_points)def_set_fpe(self,energy_bin_edges):""" Setup the Gammapy FluxPointsEstimator function with all the provided parameters. """fpe_settings=self.config.flux_points_params.parametersself.fpe=FluxPointsEstimator(energy_edges=energy_bin_edges,source=self.config.target.source_name,n_jobs=self.config.general.n_jobs,parallel_backend=self.config.general.parallel_backend,reoptimize=self.config.flux_points_params.reoptimize,**fpe_settings,)def_sort_datasets_info(self):""" The given list of datasets may contain sub-instrument level datasets. With the help of the dict information for instrument specific name and spectral energy edges, this function, sorts the datasets and returns them to be passed to the Flux Points Estimator function. Returns ------- sorted_datasets: List of Datasets object. sorted_energy_edges: List of energy edges for flux points estimation for respective instruments' datasets """dataset_name_list=self.datasets.namessorted_datasets=[]sorted_energy_edges=[]fori,nameinenumerate(self.instrument_spectral_info["name"]):dataset_list=[]forj,dataset_namesinenumerate(dataset_name_list):ifnameindataset_names:dataset_list.append(self.datasets[j])iflen(dataset_list)!=0:sorted_energy_edges.append(self.instrument_spectral_info["spectral_energy_ranges"][i])dataset_list=Datasets(dataset_list)sorted_datasets.append(dataset_list)returnsorted_datasets,sorted_energy_edges