Analyse#
The ModelScenario class allows users to collate related data sources and calculate modelled output based on this data. The types of data currently included are: - Timeseries observation data (ObsData) - Fixed domain sensitivity maps known as footprints (FootprintData) - Fixed domain flux maps (FluxData) - multiple maps can be included and referenced by source name - Fixed domain vertical curtains at the boundaries referred to as boundary conditions (BoundaryConditionsData)
- class openghg.analyse.ModelScenario(site=None, satellite=None, species=None, inlet=None, height=None, network=None, domain=None, platform=None, max_level=None, obs_region=None, selection=None, model=None, met_model=None, fp_inlet=None, source=None, sources=None, bc_input=None, start_date=None, end_date=None, obs=None, obs_column=None, footprint=None, flux=None, bc=None, store=None, time_resolved=None)[source]#
This class stores together observation data with ancillary data and allows operations to be performed combining these inputs.
- __init__(site=None, satellite=None, species=None, inlet=None, height=None, network=None, domain=None, platform=None, max_level=None, obs_region=None, selection=None, model=None, met_model=None, fp_inlet=None, source=None, sources=None, bc_input=None, start_date=None, end_date=None, obs=None, obs_column=None, footprint=None, flux=None, bc=None, store=None, time_resolved=None)[source]#
Create a ModelScenario instance based on a set of keywords to be or directly supplied objects. This can be created as an empty class to be populated.
The keywords are related to observation, footprint and flux data which may be available within the object store. The combination of these supplied will be used to extract the relevant data. Related keywords are as follows:
Observation data: site, species, inlet, network, start_date, end_data
Footprint data: site, inlet, domain, model, met_model, species, start_date, end_date
Flux data: species, sources, domain, start_date, end_date
Args: site: Site code e.g. “TAC”. satellite: Satellite name e.g “GOSAT”. species: Species code e.g. “ch4”. inlet: Inlet value e.g. “10m”. height: Alias for inlet. network: Network name e.g. “AGAGE”. domain: Domain name e.g. “EUROPE”. platform: Platform name e.g “satellite”, “column-insitu”. max_level: Maximum level for processing column observations. This is required when
retrieving column observations. If comparing modelled observations using a footprint, it must match the footprint’s
max_levelattribute. When supplying anObsColumnDataobject directly, its storedmax_levelis used instead.obs_region: The geographic region covered by the data (“BRAZIL”, “INDIA”, “UK”). selection: For satellite only, identifier for any data selection which has been
performed on satellite data. This can be based on any form of filtering, binning etc. but should be unique compared to other selections made e.g. “land”, “glint”, “upperlimit”. If not specified, domain will be used.
model: Model name used in creation of footprint e.g. “NAME”. met_model: Name of met model used in creation of footprint e.g. “UKV”. fp_inlet: Specify footprint release height options if this doesn’t match the site value. source: “anthro” (for “TOTAL”), source name from file otherwise. sources: Emissions sources. bc_input: Input keyword for boundary conditions e.g. “mozart” or “cams”. start_date: Start of date range to use. Note for flux this may not be applied. end_date: End of date range to use. Note for flux this may not be applied. obs: Supply ObsData object directly (e.g. from get_obs…() functions). obs_column: Supply ObsColumnData object directly. footprint: Supply FootprintData object directly (e.g. from get_footprint() function). flux: Supply FluxData object directly (e.g. from get_flux() function). bc: Supply BoundaryConditionsData object directly. store: Name of object store to retrieve data from. time_resolved: Whether to filter retrieved footprints by time resolution.
Trueselects time-resolved footprints,Falseselects integrated footprints, andNonedoes not filter on footprint resolution.- Returns:
None
Sets up instance of class with associated values.
TODO: For obs, footprint, flux should we also allow Dataset input and turn these into the appropriate class?
- add_bc(species=None, bc_input=None, domain=None, start_date=None, end_date=None, bc=None, store=None)[source]#
Add boundary conditions data based on keywords or direct BoundaryConditionsData object.
- Return type:
None
- add_flux(species=None, domain=None, source=None, sources=None, start_date=None, end_date=None, flux=None, store=None)[source]#
Add flux data based on keywords or direct FluxData object. Can add flux datasets for multiple sources.
- Return type:
None
- add_footprint(site=None, inlet=None, height=None, domain=None, model=None, satellite=None, obs_region=None, met_model=None, start_date=None, end_date=None, species=None, fp_inlet=None, network=None, footprint=None, store=None, time_resolved=None)[source]#
Add footprint data based on keywords or a supplied data object.
- Parameters:
site (
str|None) – Site code, such as"TAC".inlet (
str|None) – Observation inlet value, such as"100m".height (
str|None) – Alias forinlet.domain (
str|None) – Domain name for the footprints.model (
str|None) – Model used to create the footprints, such as"NAME".satellite (
str|None) – Satellite name for satellite footprints.obs_region (
str|None) – Geographic region covered by satellite footprints.met_model (
str|None) – Meteorological model used to create the footprints.start_date (
str|Timestamp|None) – Start of the date range to retrieve.end_date (
str|Timestamp|None) – End of the date range to retrieve.species (
str|None) – Species code. This is required for species-specific footprints, including CO2.fp_inlet (
str|list|None) – Footprint release-height option when it differs from the observation inlet.network (
str|None) – Observation network used when inferring the release height.footprint (
FootprintData|None) – Footprint data to attach directly instead of retrieving it.store (
str|None) – Name of the object store from which to retrieve data.time_resolved (
bool|None) – Whether to filter retrieved footprints by time resolution.Trueselects time-resolved footprints,Falseselects integrated footprints, andNonedoes not filter on footprint resolution.
- Return type:
None- Returns:
None. The selected footprint is stored on this scenario.
- add_obs(site=None, species=None, inlet=None, height=None, network=None, start_date=None, end_date=None, obs=None, store=None)[source]#
Add observation data based on keywords or direct ObsData object.
- Return type:
None
- add_obs_column(site=None, satellite=None, max_level=None, species=None, platform=None, obs_region=None, domain=None, selection=None, network=None, obs_column=None, store=None)[source]#
Add column data based on keywords or direct ObsColumnData object.
- Return type:
None
- calc_modelled_baseline(resample_to='coarsest', platform=None, cache=True, recalculate=False, output_sensitivity=False, output_units=None, allow_climatology=True)[source]#
Calculate the modelled baseline points based on site footprint and boundary conditions. Boundary conditions are multipled by any loss (exp(-t/lifetime)) for the species.
The time points returned are dependent on the resample_to option chosen. If obs data is also linked to the ModelScenario instance, this will be used to derive the time points where appropriate.
- Parameters:
resample_to (
str|None) –- Resample option to use for averaging:
either one of [“coarsest”, “obs”, “footprint”] to match to the datasets
or using a valid pandas resample period e.g. “2H”.
None to not resample and to just “ffill” footprint to obs
Default = “coarsest”.
platform (
str|None) – Observation platform used to decide whether to resample e.g. “satellite”, “insitu”, “flask”cache (
bool) – Cache this data after calculation. Default = True.recalculate (
bool) – Make sure to recalculate this data rather than return from cache. Default = False.output_units (
float|str|None) – target units; if None, then obs. units will be used, or “mol/mol” if these are not present.allow_climatology (
bool) – When aligning datasets, allow any datasets which represent a year of data to be treated as a climatology and reindexed accordingly.
- Return type:
Dataset- Returns:
- xarray.Dataset containing modelled baseline values along the time axis and baseline sensitivities
for the NESW boundary regions.
- If cache is True:
This data will also be cached as the ModelScenario.modelled_baseline attribute. The associated scenario data will be cached as the ModelScenario.scenario attribute.
- calc_modelled_obs(sources=None, resample_to='coarsest', platform=None, cache=True, recalculate=False, output_fp_x_flux=False, split_by_sectors=False, output_units=None, use_low_freq_flux=None, allow_climatology=True, *, time_resolved_by_sector=None)[source]#
Calculate the modelled observation points based on site footprint and fluxes.
The time points returned are dependent on the resample_to option chosen. If obs data is also linked to the ModelScenario instance, this will be used to derive the time points where appropriate.
- Parameters:
sources (
str|list|None) – Sources to use for flux. All will be used and stacked if not specified.resample_to (
str|None) –- Resample option to use for averaging:
either one of [“coarsest”, “obs”, “footprint”] to match to the datasets
or using a valid pandas resample period e.g. “2H”.
None to not resample and to just “ffill” footprint to obs
Default = “coarsest”.
platform (
str|None) – Observation platform used to decide whether to resample e.g. “satellite”, “insitu”, “flask”cache (
bool) – Cache this data after calculation. Default = True.recalculate (
bool) – Make sure to recalculate this data rather than return from cache. Default = False.output_fp_x_flux (
bool) – If true, include “fp x flux” data variable in output.split_by_sectors (
bool) – If true, compute separate timeseries (and fp_x_flux) for each flux sector; these are stored under the mf_mod_sectoral and fp_x_flux_sectoral data variables, and have a source dimension for the different flux sources. The total mf_mod and fp_x_flux are available under their usual names.output_units (
float|str|None) – target units; if None, then obs. units will be used, or “mol/mol” if these are not present.use_low_freq_flux (
bool|None) – For integrated footprints, use monthly-mean fluxes instead of the flux at the release time. Defaults to True for an integrated CO2 footprint and False otherwise.allow_climatology (
bool) – Allow a single year of flux data to be reindexed as a climatology for integrated calculations.time_resolved_by_sector (
Mapping[str,bool] |None) – Optional flux-source name to boolean mapping. True uses time-resolved sensitivities and False uses integratedfpfrom the single attached footprint dataset. Unspecified sources retain the existing footprint-based default. None or an empty mapping retains the existing calculation path. Configured calculations returnmf_modand, when requested,mf_mod_sectoralandfp_x_flux_sectoral.
- Returns:
Modelled observation values along the time axis, optionally with “fp x flux”.
- If cache is True:
This data will also be cached as the ModelScenario.modelled_obs attribute. The associated scenario data will be cached as the ModelScenario.scenario attribute.
- Return type:
xarray.Dataset
- combine_flux_sources(sources=None, cache=True, recalculate=False)[source]#
Combine together flux sources on the time dimension. This will align to the time of the highest frequency flux source both for time range and frequency.
- Parameters:
sources (
str|list|None) – Names of sources to combine. Should already be attached to ModelScenario.cache (
bool) – Cache this data after calculation. Default = True
- Returns:
All flux sources stacked on the time dimension.
- Return type:
Dataset
- combine_obs_footprint(resample_to='coarsest', platform=None, cache=True, recalculate=False)[source]#
Combine observation and footprint data so these are on the same time axis. This will both slice and resample the data to align this axis.
Data is slices to smallest timeframe spanned by both footprint and obs
Data is resampled according to resample_to input and using the mean
Data is combined into one dataset
- Parameters:
resample_to (
str|None) –- Resample option to use for averaging:
either one of [“coarsest”, “obs”, “footprint”] to match to the datasets
or using a valid pandas resample period e.g. “2H”.
None to not resample and to just “ffill” footprint to obs
Default = “coarsest”.
platform (
str|None) – Observation platform used to decide on resample and alignment steps. If this is not supplied, function will attempt to extract this value from from the metadata, then the openghg_defs site_info.json details for the site.cache (
bool) – Cache this data after calculation. Default = True.
- Returns:
Combined dataset aligned along the time dimension
- If cache is True:
This data will be also be cached as the ModelScenario.scenario attribute.
- Return type:
xarray.Dataset
- convert_units(ds, output_units=None, data_vars=None)[source]#
Align units in dataset with obs units.
Units will only be updated for data variables that: 1) have units and 2) have a
"time"dimension. Variables whose names end with"_number_of_observations"are never converted, including when explicitly listed indata_vars. The input dataset is not modified.- Parameters:
ds (
Dataset) – dataset to align units onoutput_units (
float|str|None) – target units; if None, then obs. units will be used, or “mol/mol” if these are not present.data_vars (
Iterable[Hashable] |None) – data variables to convert; if None, all data variables satisfying the conditions above will be converted.
- Return type:
Dataset- Returns:
A dataset with aligned units.
- footprints_data_merge(resample_to='coarsest', platform=None, calc_timeseries=True, calc_fp_x_flux=False, sources=None, split_by_sectors=False, calc_bc=True, calc_bc_sensitivity=False, cache=True, recalculate=False, output_units=None, use_low_freq_flux=None, allow_climatology=True, *, time_resolved_by_sector=None)[source]#
Produce combined object containing aligned footprint and observation data. Can also include modelled timeseries data derived from flux.
- Parameters:
resample_to (
str|None) –- Resample option to use for averaging:
either one of [“coarsest”, “obs”, “footprint”] to match to the datasets
or using a valid pandas resample period e.g. “2H”.
None to not resample and to just “ffill” footprint to obs
Default = “coarsest”.
platform (
str|None) – Observation platform used to decide whether to resample.calc_timeseries (
bool) – Calculate modelled timeseries based on flux sources.calc_fp_x_flux (
bool) – Calculate “fp x flux” matrixsources (
str|list|None) – Sources to use for flux if calc_timseries is True. All will be used and stacked if not specified.split_by_sectors (
bool) – if True, separate modelled obs (and footprint x flux) will be calculated for each flux source (“sector”).calc_baseline – Calculate modelled baseline.
cache (
bool) – Cache this data after calculation. Default = True.recalculate (
bool) – Make sure to recalculate this data rather than return from cache. Default = False.output_units (
str|float|None) – units to use for obs, or any data that should have the same units as obs (e.g. mf_mod).use_low_freq_flux (
bool|None) – For integrated footprints, use monthly-mean fluxes instead of the flux at release time.Noneenables this for CO2 only.allow_climatology (
bool) – When aligning datasets, allow any datasets which represent a year of data to be treated as a climatology and reindexed accordingly.time_resolved_by_sector (
Mapping[str,bool] |None) – Flux-source name to True (time-resolved) or False (integrated) mapping, forwarded tocalc_modelled_obs. All sources share the attached footprint dataset.
- Returns:
Combined dataset containing footprint and observation data
- Return type:
xarray.Dataset
- plot_comparison(baseline='boundary_conditions', sources=None, resample_to='coarsest', platform=None, allow_climatology=True, cache=True, recalculate=False, save_path=None, **save_kwargs)[source]#
Plot comparison between observation and modelled timeseries data.
- Parameters:
baseline (
str|None) – Add baseline to data. One of: - “boundary_conditions” - Uses added boundary conditions to calculate modelled baseline - “percentile” - Calculates the 1% value across the whole time period - None - don’t add a baseline and only plot the modelled observationssources (
str|list|None) – Sources to use for flux. All will be used and stacked if not specified.resample_to (
str|None) –- Resample option to use for averaging:
either one of [“coarsest”, “obs”, “footprint”] to match to the datasets
or using a valid pandas resample period e.g. “2H”.
None to not resample and to just “ffill” footprint to obs
Default = “coarsest”.
platform (
str|None) – Observation platform used to decide whether to resample e.g. “satellite”, “insitu”, “flask”allow_climatology (
bool) – When aligning datasets, allow any datasets which represent a year of data to be treated as a climatology and reindexed accordingly.cache (
bool) – Cache this data after calculation. Default = True.recalculate (
bool) – Make sure to recalculate this data rather than return from cache. Default = False.save_path (
str|None) – Path to save the figure. If None, the figure will not be saved.save_kwargs (
Any) – Additional keyword arguments to pass to the save function. These will be passed to the plotly write_html or write_image functions depending on the file extension of save_path.example – width=1000, height=600, scale=2,
- Return type:
Any- Returns:
Plotly Figure
Interactive plotly graph created with observation and modelled observation data.
- plot_timeseries()[source]#
Plot the observation timeseries data.
- Return type:
Any- Returns:
Plotly Figure
Interactive plotly graph created with observations
- property units: str | None#
Units used by this scenario’s obs. data.
Footprint times flux#
fp_x_flux_time_resolved_numba computes source-resolved model sensitivity without
summing the spatial grid. It returns a lazy (source, lat, lon, time) array,
so basis functions can be applied later. When observation times are supplied,
selection happens after the full lagged calculation is constructed. Install
the optional kernel dependency with pip install 'openghg[fp-x-flux]'.
Single-source flux, regularly spaced coarse flux, and irregular footprint
release times are supported.
Flux timestamps are interpreted as the starts of regular averaging intervals.
For a release time and H_back lag, the target belongs to the half-open
interval [flux_time, flux_time + cadence). Values are not interpolated,
matched to the nearest timestamp, or extrapolated across missing intervals.
Use align_flux_to_time_targets when the same explicit alignment is needed
outside the full operator. Non-monotonic release times are sorted internally
for efficient block reads and restored to their exact original positional
order in the result.
The indexed kernel defaults to 32 releases per compute chunk when
time_chunk is omitted; tune this value for the available worker memory and
spatial grid size.
- openghg.analyse.align_flux_to_time_targets(flux, target_times)[source]#
Align flux to target times using interval-start membership.
Flux timestamps are interpreted as the starts of regular, half-open averaging intervals. A target at
treceives the flux whose interval is[flux_time, flux_time + cadence)and containst. Targets outside the represented intervals raiseValueError; values are never matched by nearest-neighbour or extrapolated across a missing interval.- Parameters:
flux (
DataArray|Dataset) – Flux DataArray, or a Dataset containingflux.target_times (
DataArray|Sequence[Any]) – One-dimensional timestamps to align to.
- Return type:
DataArray- Returns:
Flux values with their time dimension replaced by the exact target timestamps, preserving target order and duplicates.
- Raises:
ValueError – If flux lacks time, target timestamps are not one-dimensional, flux timestamps do not describe regular interval starts, or a target lies outside the represented intervals.
- openghg.analyse.fp_x_flux_time_resolved_numba(footprint, flux, *, sources=None, source_labels=None, time_selector=None, time_chunk=None, lat_chunk=None, lon_chunk=None, source_chunk=None, cast_float32=True, fillna_zero=True)[source]#
Multiply time-resolved footprints by source-resolved flux, retaining space.
The lazy result contains
(source, lat, lon, time)and is suitable for later basis-function projection. The resolved term uses the flux interval containing each footprint release time minusH_back; flux timestamps are interpreted as interval starts. The residual term uses monthly mean flux. Regular coarse flux is forward-filled to an hourly grid; flux coarser than the fullH_backwindow uses its monthly mean for the resolved and residual terms. Inputs must include the full lag halo before the first footprint time. Irregular release times retain their exact order and values and use a chunk-indexed Numba kernel.If
time_selectoris supplied, it is applied only after the full lazy operator graph has been constructed. This preserves the lag calculation while allowing callers to retain only actual observation timestamps.- Parameters:
footprint (
DataArray|Dataset) – Dataset containingfp_time_resolvedandfp_residual, or a legacyH_backDataArray whose final lag is the residual.flux (
DataArray|Dataset) – Flux DataArray, or Dataset containingflux. A missingsourcedimension is treated as a single source.sources (
Sequence[Any] |None) – Optional source-coordinate values to select.source_labels (
Sequence[str] |None) – Optional replacement labels for the selected sources.time_selector (
DataArray|Sequence[Any] |None) – Observation timestamps to retain after calculation.time_chunk (
int|None) – Requested compute and output time chunk size. Irregular release times default to compute chunks of 32 observations; the regular kernel retains its existing full-time default.lat_chunk (
int|None) – Requested latitude chunk size; defaults to the full grid.lon_chunk (
int|None) – Requested longitude chunk size; defaults to the full grid.source_chunk (
int|None) – Requested source chunk size; defaults to all sources.cast_float32 (
bool) – Cast inputs and output to float32.fillna_zero (
bool) – Replace missing footprint and flux values with zero.
- Return type:
DataArray- Returns:
A lazy, dimensionless DataArray ordered as
source, lat, lon, time.- Raises:
ImportError – If OpenGHG was installed without the
fp-x-fluxextra.ValueError – If inputs, source labels, interval timestamps, lag values, flux coverage, chunks, or the optional time selector are invalid.
For data pipelines that already guarantee monotonic release time, spatial alignment, float/NaN policy, source selection, and compatible Dask chunks, the computation-only entry point avoids the wrapper’s sorting and rechunking.
- openghg.analyse.fp_x_flux_time_resolved_numba_core(footprint, flux, *, time_selector=None)[source]#
Run the operator on monotonic, aligned, pre-chunked spatial inputs.
This is the computation-only entry point for prepared on-disk data. It does not sort, spatially align, cast, fill missing values, select sources, or rechunk. Footprint time must be monotonic non-decreasing; footprint and flux spatial coordinates and chunks must match;
H_backmust be one chunk; and flux must already contain asourcedimension.Use
fp_x_flux_time_resolved_numba()for arbitrary user inputs. That wrapper establishes this contract, restores non-monotonic input order, and applies requested output chunks.- Parameters:
footprint (
Dataset) – Dataset containing pre-chunkedfp_time_resolvedandfp_residualvariables.flux (
DataArray) – Pre-aligned, pre-chunked, source-resolved flux.time_selector (
DataArray|Sequence[Any] |None) – Optional timestamps retained after the full operator is constructed.
- Return type:
DataArray- Returns:
A lazy, dimensionless DataArray ordered as
source, lat, lon, time.- Raises:
ImportError – If OpenGHG was installed without the
fp-x-fluxextra.ValueError – If prepared dimensions, coordinates, chunks, time labels, lag values, or flux coverage violate the core contract.
- openghg.analyse.write_fp_x_flux_zarr(result, output_path, *, output_chunks=None, provenance, overwrite=False)[source]#
Atomically persist an fp-times-flux result as consolidated float32 ppm Zarr.
A JSON manifest is written beside the store.
provenanceis supplied by the caller because OpenGHG cannot infer record versions, checksums, or an observation-selector identity from arbitrary xarray inputs.- Parameters:
result (
DataArray) – Dimensionless spatially resolved result to persist.output_path (
str|Path) – Destination Zarr store.output_chunks (
Mapping[str,int] |None) – Optional output chunk lengths by dimension.provenance (
Mapping[str,Any]) – Caller-supplied footprint, flux, and observation-selector provenance for the sidecar manifest.overwrite (
bool) – Whether to atomically replace an existing store.
- Return type:
Path- Returns:
Path to the completed consolidated Zarr store.
- Raises:
ValueError – If result dimensions or units are invalid, or required provenance entries are missing.
FileExistsError – If the destination exists and
overwriteis false.
Numba compiles the kernel on first use in each process. For benchmarks or a
distributed cluster, the optional warm-up can be run on every worker with
client.run(warm_numba_fp_x_flux). It is not required for correctness.
- openghg.analyse.warm_numba_fp_x_flux()[source]#
Compile the regular and indexed Numba kernels in the current process.
This is optional. It is mainly useful with
distributed.Client.runto remove first-call compilation cost from every Dask worker.- Return type:
str- Returns:
A readiness message suitable for collecting from distributed workers.
- Raises:
ImportError – If OpenGHG was installed without the
fp-x-fluxextra.