API Reference¶
Everything below is importable from the top-level meteosynth package.
Daily Series Generators¶
The entry point for ordinary use: DayWindowGenerator
for a day, a month or a year on the rolling-window base, and
EnvSeriesGenerator for a single date-blind training
subset.
Daily synthetic-series generators built on top of the Markov-chain simulators.
The main entry point is EnvSeriesGenerator, which manages an initial
distribution plus 23 hourly
MarkovChainSimulator2dKDE
transition models, and stitches them together into a
complete 24-hour profile of a meteorological attribute (e.g. plane-of-array
direct irradiance poa_direct, air temperature, wind speed).
This is the piece intended for Monte-Carlo studies of energy-project output and
requirements: loop EnvSeriesGenerator.gen_day() for independent synthetic days,
or call DayWindowGenerator.generate_series() for a continuous chained series.
Training data can be sliced two ways, and both are supported:
by calendar month, via
get_month_subset();by a rolling window of +/- n days centred on a target day, via
get_day_window_subset()– wrapped ergonomically byDayWindowGenerator, which builds each day’s generator lazily rather than holding all 366 in memory at once.
- class meteosynth.generators.DayWindowGenerator(dataset: MetDataset, attr_str: str, n_days: int = 15, bandwidth: float | None = 0.1, cache_size: int = 8, sampling: str = 'auto')[source]¶
Bases:
objectSeasonal generator built on rolling day windows, fitted lazily per target day.
Wraps a
MetDatasetand hands out anEnvSeriesGeneratorfor any calendar day, trained on the +/-n_dayswindow centred on that day. Unlike a month-based split, the training data is centred on the target and varies smoothly from day to day.Generators are built on demand and held in a small LRU cache rather than precomputed. Holding all 366 days costs ~126 MB for one attribute (~880 MB across all seven), while fitting one costs ~58 ms on a two-year record – a
gaussian_kde“fit” just stores its points and a 2x2 covariance – rising to ~180 ms on eleven years, where there are more pairs to hold.The cache is for repeated requests for the same day, which is the ensemble-of-days use case (
gen_day()in a loop). It does nothing for a calendar walk: an ordered walk visits each slot exactly once and never returns to it, so the hit rate is zero regardless ofcache_size. Measured: a 30-day walk repeated 5 times at the default size performed 150 fits for 30 distinct days. That is the costgenerate_ensemble()exists to remove – it walks the calendar once and lets every realisation share each day’s fit, rather than relying on a cache to notice the repeat.Persisting fitted generators to disk is deliberately not offered: it would write numbers already present in the source data, ~31x duplicated across overlapping windows, to save 58 ms – and it does not work at the default
bandwidth=0.1anyway, sincescipy’sgaussian_kdestores an unpicklable local lambda incovariance_factor. Seedocs/design/completed/rolling-day-window.md.- Parameters:
dataset (MetDataset) – Processor holding the source meteorological data.
attr_str (str) – Attribute to model. Must have a registered
VariableSpec.n_days (int, optional) – Half-width of the training window in days. Defaults to 15 (a 31-day window).
bandwidth (float, optional) – KDE bandwidth forwarded to every hourly simulator.
cache_size (int, optional) – Number of fitted generators to keep in memory. Defaults to 8 (~2.8 MB).
Examples
>>> dwg = DayWindowGenerator(dataset, attr_str='poa_direct') >>> profile = dwg.gen_day(2, 29) >>> year = dwg.generate_series(start=(1, 1), n_days=365)
- for_day(month: int, day: int, sampling: str | None = None) EnvSeriesGenerator[source]¶
Get the generator trained on the window centred on
(month, day).Feb 29 is an ordinary target and needs no special handling.
- Parameters:
month (int) – Month of the target day (1-12).
day (int) – Day of the target month.
- Returns:
Fitted generator, built on first request and cached thereafter.
- Return type:
- for_slot(slot: int, sampling: str | None = None) EnvSeriesGenerator[source]¶
Get the generator for an
all_leapcalendar slot (1-366).- Parameters:
slot (int) – Calendar slot, as produced by
day_slot().- Returns:
Fitted generator, built on first request and cached thereafter.
- Return type:
- gen_day(month: int, day: int, rng=None, seed: int | None = None) ndarray[source]¶
Generate a single synthetic 24-hour profile for a calendar day.
Hour 0 is drawn from that day’s pi(x0). For a chained series across many days, use
generate_series()instead.- Parameters:
month (int) – Month of the target day (1-12).
day (int) – Day of the target month.
rng (None, int or np.random.Generator, optional) – Source of randomness.
seed (int, optional) – Convenience alias for
rng.
- Returns:
Array of shape
(24,)with one value per hour.- Return type:
np.ndarray
- generate_ensemble(start: tuple, n_days: int, n_realisations: int, seed: int | None = None, include_feb29: bool = False, progress: bool = False, sampling: str = 'auto') ndarray[source]¶
Generate many independent synthetic series in one calendar walk.
Statistically this is
generate_series()calledn_realisationstimes: each realisation is its own chain through the same per-day models, and realisation i’s hour 0 on day d is conditioned on realisation i’s own 23:00 of day d-1. What changes is the order of evaluation – the calendar is walked once on the outside, so each day’s models are fitted once and reused by every realisation instead of being refitted per realisation.Measured on Heraklion 2010-2020,
poa_global, +/-7-day window, a 365-day year: 1000 realisations drop from ~26.9 h to ~20.9 min (77x), 100 from ~2.7 h to ~17.5 min. Seedocs/design/FEAT-15-ensemble-generation.md.- starttuple of (int, int)
(month, day)of the first day, as forgenerate_series().- n_daysint
Number of consecutive days per realisation.
- n_realisationsint
How many independent series to generate.
- seedint, optional
Root entropy. Realisation i of this attribute draws from a stream keyed on
(seed, i, attr_str)and nothing else – seerealisation_stream()– so it does not depend on how many realisations were requested, nor on which other attributes were. Subject tosampling; see the note below.- include_feb29bool, optional
Whether the walk visits Feb 29. Defaults to
False, giving a 365-day year.- progressbool, optional
Show a
tqdmbar over the day walk. Unlikegenerate_series()’s, this one persists: an ensemble is a single walk rather than one of hundreds.- sampling{“auto”, “exact”, “grid”}, optional
Which path answers each draw.
"auto"(default) decides fromn_realisationsbefore drawing starts: above 64 it uses the cached grid, at or below it evaluates the density live."exact"never builds a grid;"grid"always does. Naming one of the two explicitly is what makes ensembles of different sizes bit-comparable – see the note below.
- np.ndarray
Array of shape
(n_realisations, n_days, 24).
Which sampler a draw comes from is part of its identity, so it is worth knowing exactly when it changes.
PERF-1gives every simulator two paths: a direct KDE evaluation, and a cached quantile grid built once the simulator turns out to be hot. The two agree distributionally – two-sample KS p = 1.0 – but not to the last digit, differing by ~0.02 % on a daily total.- With
sampling="auto"the choice is made **once, fromn_realisations, before any drawing** – above 64 the grid, at or below it the live density – so every member of one ensemble comes from one sampler and the members stay exchangeable. The consequence: realisation 0 of a 50-realisation ensemble is not bit-identical to realisation 0 of a 500-realisation one, because the two straddle that crossover. Within a regime it is exactly identical.
To compare across the crossover, name the path –
sampling="grid"orsampling="exact"for both runs – and realisation i is then bit-identical at any two sizes.A chained
generate_series()is then_realisations=1case, which resolves to"exact", so it remains bit-for-bit what it always was.>>> ens = dwg.generate_ensemble((1, 1), 365, 1000, seed=1) >>> ens.shape (1000, 365, 24)
- generate_series(start: tuple, n_days: int, rng=None, seed: int | None = None, include_feb29: bool = False, progress: bool = False) ndarray[source]¶
Generate a continuous synthetic series, chained across midnight.
Day 1 starts from its own pi(x0). Every later day’s hour 0 is drawn from that day’s cross-midnight model, conditioned on the previous day’s 23:00 value, and its hours 1-23 from that day’s within-day transitions. The chain is therefore time-inhomogeneous at daily resolution: each calendar day uses models fitted to its own +/-
n_dayswindow, so the models drift smoothly through the season.An ensemble of independent days is
n_days=1called repeatedly: pi(x0) is redrawn at the start of every call, and the cross-midnight model is used only within a call. The boundary of the call is the reset.- Parameters:
start (tuple of (int, int)) –
(month, day)of the first day. Required: pi(x0) is a dated object – midnight temperature in January and in July are different distributions, so a series with no start date has no well-defined initial distribution.n_days (int) – Number of consecutive days to generate.
rng (None, int or np.random.Generator, optional) – Source of randomness, resolved once for the whole series.
seed (int, optional) – Convenience alias for
rng.include_feb29 (bool, optional) – Whether the walk visits Feb 29. Defaults to
False, giving a 365-day year: the series then steps 28 Feb 23:00 -> 1 Mar 00:00 using 1 March’s cross-midnight model, which is fitted from real 1 March dates whose actual predecessor was 29 Feb in leap years and 28 Feb otherwise.progress (bool, optional) –
Show a
tqdmprogress bar over the day walk. Defaults toFalse.Worth it for a year (~4 minutes, since each new calendar day has to fit its own generators) and pointless for a single day. The bar does not persist once the walk finishes: an ensemble is this method called hundreds of times, and hundreds of leftover bars would be worse than none.
- Returns:
Array of shape
(n_days, 24); rowiis thei-th calendar day.- Return type:
np.ndarray
Examples
>>> year = dwg.generate_series(start=(1, 1), n_days=365, seed=1) >>> ens = np.vstack([dwg.generate_series((3, 14), 1, rng=rng) ... for _ in range(500)])
- sampling¶
Default sampling path for every generator handed out. Overridable per call on
for_day()/for_slot().
- class meteosynth.generators.EnsembleDay(day_index: int, slot: int, month: int, day: int, values: dict[str, ndarray])[source]¶
Bases:
objectOne calendar day of an ensemble walk, across every attribute.
- Parameters:
day_index (int) – 1-based position in the walk. Not derivable from
month/day: the walk is circular, so a series starting on 30 December wraps past New Year and the calendar alone does not order it.slot (int) –
all_leapcalendar slot (1-366).month (int) – Calendar position of this day.
day (int) – Calendar position of this day.
values (dict of str to np.ndarray) – Per attribute, an array of shape
(n_realisations, 24).
- day: int¶
- day_index: int¶
- month: int¶
- slot: int¶
- values: dict[str, ndarray]¶
- class meteosynth.generators.EnvSeriesGenerator(met_data: DataFrame, attr_str: str, bandwidth: float | None = 0.1, wide_full: DataFrame | None = None, sampling: str = 'auto')[source]¶
Bases:
objectOne day’s worth of model for a meteorological attribute. Date-blind.
Holds the 25 models that describe a single day:
pi(x0) – the initial distribution, fitted to observed 00:00 values. Used when the day starts a chain.
23 within-day transitions
h-1 -> hfor h = 1..23.one cross-midnight transition
23:00(d-1) -> 00:00(d), used when the day continues a chain. Only built whenwide_fullis supplied, since it needs the full record rather than the training subset.
This class deliberately knows nothing about which day it models: the caller chose the season by choosing the subset. Trajectories therefore live on
DayWindowGenerator, which does know the calendar. Seedocs/design/variable-specs-and-initialisation.md.- Parameters:
met_data (pd.DataFrame) – Processed meteorological data with
hourandattr_strcolumns. Typically a month subset (get_month_subset()) or a rolling day window (get_day_window_subset()); both are accepted unchanged.attr_str (str) – Attribute to model. Must have a registered
VariableSpec.bandwidth (float, optional) – KDE bandwidth forwarded to every simulator.
wide_full (pd.DataFrame, optional) – The full record pivoted to days-by-hours, used to build the cross-midnight model. Without it
gen_day_from()is unavailable.DayWindowGeneratorpivots this once and shares it across all 366 days.
- property cross_midnight: MarkovChainSimulator2dKDE | None¶
00(d) model, or None if not built.
- Type:
The fitted 23
- Type:
00(d-1) -> 00
- gen_day(rng=None, seed: int | None = None) ndarray[source]¶
Generate one synthetic day, starting the chain from pi(x0).
- Parameters:
rng (None, int or np.random.Generator, optional) – Source of randomness. Pass a
Generatorto draw many days from one stream; pass an int for a self-contained reproducible day.seed (int, optional) – Convenience alias for
rng, whenrngis not given.
- Returns:
Array of shape
(24,)with one value per hour.- Return type:
np.ndarray
- gen_day_from(previous_2300: float, rng=None) ndarray[source]¶
Generate one synthetic day continuing from the previous day’s 23:00 value.
Hour 0 is drawn from this day’s cross-midnight model conditioned on
previous_2300; hours 1-23 then follow the ordinary within-day transitions.- Parameters:
previous_2300 (float) – The 23:00 value of the preceding day.
rng (None, int or np.random.Generator, optional) – Source of randomness.
- Returns:
Array of shape
(24,).- Return type:
np.ndarray
- Raises:
ValueError – If no cross-midnight model was built (no
wide_fullat construction, or no target day in the window had a predecessor in the record).
- property initial: MarkovChainSimulator2dKDE¶
The fitted initial distribution pi(x0).
- precompute_grids() None[source]¶
Build every simulator’s cached quantile grid now, rather than on demand.
Worth calling when this day’s models are about to be sampled many times – an ensemble of realisations – and pointless otherwise. Two reasons to do it up front rather than let
PERF-1’s threshold trip part-way through:Every realisation is then drawn from the same sampler. Left to the threshold, realisation 0 would take the direct path and realisation 500 the cached one, so ensemble members would not be quite exchangeable.
It removes the crossover from any timing measurement.
A no-op for the degenerate transitions, which are already a single interpolation or a lookup, and for the initial distribution, whose
previousis constant by construction. In practice it builds a grid for the non-degenerate within-day hours plus the cross-midnight model – 11 of 23 hours on a March day at Heraklion, 8 in December, and all 23 for temperature and wind, which never degenerate.
- sampling¶
Which path every simulator here answers a draw from. See
SAMPLING_PATHS.
- property simulators: dict[int, MarkovChainSimulator2dKDE]¶
The within-day hourly simulators, keyed by hour of day (1-23).
- meteosynth.generators.FEB29_SLOT = 60¶
Slot of Feb 29 on the
all_leapcalendar. A synthetic non-leap year skips it.
- meteosynth.generators.build_cross_midnight_pairs(wide_full: DataFrame, target_index: Index) DataFrame[source]¶
Build 23:00(d-1) -> 00:00(d) pairs from actual consecutive dates.
This is the model that carries a series across midnight, and the one place where the climatological window and the calendar must not be confused.
- Parameters:
wide_full (pd.DataFrame) – Days-by-hours frame over the full record, indexed by
YYYYMMDDstrings. Must be the whole record, not the window: the previous day of a target day may legitimately fall outside the window.target_index (pd.Index) – The
YYYYMMDDindex of the target days – typically a window subset’s days.
- Returns:
previous(23:00 of the preceding calendar day) andcurrent(00:00 of the target day), one row per target day that has a real predecessor in the record.- Return type:
pd.DataFrame
Notes
Target days whose predecessor is absent drop out – the first day of the record always does, since its predecessor precedes the record.
The trap this avoids: the training window wraps climatologically, so a Jan 2 window contains late-December days. Pairing on the calendar slot rather than the actual date would then pair Dec 31 2012 with Jan 1 2012 – a 364-day backwards jump presented as a one-hour step. Looking the predecessor up by real date makes that impossible.
- meteosynth.generators.build_initial_values(wide: DataFrame) DataFrame[source]¶
Build the sample that the initial distribution pi(x0) is fitted to.
pi(x0) is the distribution of the first value of the chain. Unlike a transition it is unconditional – hour 0 has no previous hour, so there is nothing to condition on. It is simply the observed 00:00 value of every training day.
The frame is returned in
previous/currentform, with a constantprevious, so it can be fitted by the ordinaryMarkovChainSimulator2dKDE. That is not a trick: a constantpreviousis exactly theKind.KDE_1Dcase, which already means “there is no information in the previous value, sample the marginal”. When the 00:00 values are themselves constant – as they are for irradiance, which is zero every midnight – it degenerates one step further toKind.CONSTANTand returns that constant. “Irradiance starts at zero” therefore falls out of the data rather than being hard-coded.- Parameters:
wide (pd.DataFrame) – Days-by-hours frame, as produced by
convert_to_daily_wide().- Returns:
Frame with constant
previousand the observed 00:00 values ascurrent.- Return type:
pd.DataFrame
- meteosynth.generators.build_transition_pairs(wide: DataFrame, hour: int) DataFrame[source]¶
Build
previous/currenttransition pairs for one hour from a wide frame.wideis a days-by-hours frame as produced byconvert_to_daily_wide(): one row per day, one column per hour. Both values of a pair are therefore read from the same row, which is what guarantees they come from the same day.That guarantee is the whole point of taking the wide frame rather than two hour-filtered slices of the long frame. Slicing and zipping by position is only correct while both slices happen to share a day ordering; it fails silently – same lengths, no exception, ~27k mispaired rows – as soon as anything re-sorts the input. Here, alignment is keyed on the date index, so it holds under any ordering. See
docs/design/completed/transition-pair-alignment.md.Days with a missing value at either hour are dropped, and only those days.
- Parameters:
wide (pd.DataFrame) – Days-by-hours frame, indexed by date, with integer hour columns.
hour (int) – Target hour of the day (1-23). Hour 0 is not a valid target – see Notes.
- Returns:
Frame with
previousandcurrentfloat columns, one row per day.- Return type:
pd.DataFrame
- Raises:
ValueError – If
houris outside 1-23.
Notes
Valid for hours 1-23 only. Hour 0 has no previous hour within the same day, and the chain no longer fakes one: it is started from an initial distribution (
build_initial_values()) or continued from the previous calendar day (build_cross_midnight_pairs()). The old behaviour usedhour_prev = (hour - 1) % 24, making hour 0’s “previous” hour 23 of the same day – a 23-hour backwards jump rather than a 1-hour step. Measured on the shipped 2011-2012 record, those same-day pairs correlate at 0.360 forwind_speedand 0.890 fortemp_air, against 0.981 and 0.998 for the real cross-midnight step.On data with no missing values – which is what PVGIS supplies – this returns pairs bit-for-bit identical to the positional construction it replaced. It deviates in one respect, deliberately: where the source has a NaN, the positional version emitted a pair containing it (poisoning the KDE), whereas this drops that day.
- meteosynth.generators.generate_hr_simulator(met_data: DataFrame, hour: int, attr_str: str, bandwidth: float | None = 0.1) MarkovChainSimulator2dKDE[source]¶
Build a Markov-chain simulator for the transition into a specific hour.
The current hour’s values (
current) are conditioned on the previous hour’s values (previous), so the resulting simulator models the hour-to-hour transitionhour-1 -> hour.- Parameters:
met_data (pd.DataFrame) – Processed meteorological data containing at least an
hourcolumn and the requestedattr_strcolumn.hour (int) – Target hour of the day (0-23) for which to build the transition model.
attr_str (str) – Attribute to model. Must have a registered
VariableSpec.bandwidth (float, optional) – KDE bandwidth passed to the simulator. Defaults to
0.1for smooth transitions; useNonefor Scott’s rule.
- Returns:
A fitted simulator for the
hour-1 -> hourtransition.- Return type:
Notes
This pivots
met_dataon every call. Building all 24 hourly simulators this way costs ~12x more in pivoting than in KDE fitting, soEnvSeriesGeneratorpivots once and shares the result instead. This function remains as the convenient single-hour entry point.
- meteosynth.generators.realisation_stream(seed: int | None, realisation: int, attr_str: str) Generator[source]¶
The random stream belonging to one
(realisation, attribute)pair.Keyed so that a realisation depends on its own index and its own attribute, and on nothing else. Both halves of that matter, and both were got wrong by the obvious implementations:
Keyed on the realisation index, not drawn from one shared stream. A shared stream makes realisation 0 depend on how many realisations were requested – same seed, different
n_realisations, different series.Keyed on a stable hash of the attribute name, not on its position in the requested list. Positional keying makes
temp_airdepend on whetherpoa_globalwas requested alongside it, which is the trapexamples/use_cases/year/synthetic_year.pyused to carry.
So an ensemble can be extended from 100 to 200 realisations without invalidating the first 100; realisation 743 can be reproduced without generating the other 999; and one attribute can be regenerated alone and still match its column in a multi-attribute run.
zlib.crc32rather than the built-inhash, which is salted per process and would make a run irreproducible between invocations rather than merely between attribute lists.Distinct streams per attribute are required rather than merely tidy: attributes are modelled independently, so feeding them one stream would push the same uniform draws through every attribute’s inverse CDF and lock them together in quantile space – a spurious correlation that looks like physics.
- Parameters:
seed (int or None) – Root entropy.
Nonedraws from the OS, so the run is not reproducible.realisation (int) – Index of the realisation within the ensemble.
attr_str (str) – Attribute name, used as itself rather than as a position.
- Return type:
np.random.Generator
Ensembles¶
Many realisations in one calendar walk, and their on-disk form. Fitting each day’s
models once and sharing them across every realisation is what makes an ensemble of hundreds
affordable; write_ensemble() streams the result to a single
long-format parquet file, one row group per calendar day.
Writing, reading and exporting ensembles of synthetic years.
An ensemble is N independent synthetic realisations of the same calendar span, for one
or more attributes. write_ensemble() produces one long-format parquet file, streamed
one calendar day at a time, so peak memory never holds the whole ensemble; and
read_ensemble() reads it back with its provenance intact.
Long format and one file, deliberately:
One file is easier to move, compress and archive than a folder of N, and a folder can always be produced from it. The reverse costs a re-read of N files.
Long format is what streams – day d contributes its rows and is then done with – and it needs no column-naming scheme. It also matches
MetDataset’s own layout, so the same tools read observed and synthetic data.
The wide layout is not absent, it is derived: Ensemble.to_wide() pivots one attribute
to hours-by-realisations, which is what ensemble_to_xlsx() writes. That asymmetry is
forced rather than chosen – see ensemble_to_xlsx().
See docs/design/FEAT-15-ensemble-generation.md.
- meteosynth.ensemble.ENSEMBLE_SCHEMA_VERSION = 1¶
Version of the on-disk ensemble schema. Bumped when the data contract changes – columns, dtypes, row identity – never for a new metadata field, which readers tolerate.
- class meteosynth.ensemble.Ensemble(frame: DataFrame, meta: dict = <factory>)[source]¶
Bases:
objectAn ensemble read back from disk: the rows, plus what the file says about itself.
- Parameters:
frame (pd.DataFrame) – Long format – one row per
(realisation, day_index, hour), one column per attribute. Row order is as written:(day_index, realisation, hour).meta (dict) – The file’s own record of how it was generated – seed, realisation count, calendar span, window half-width, bandwidth, and the provenance of the dataset it was trained on. Enough to regenerate it.
- property attrs: tuple[str, ...]¶
The generated attribute columns, in file order.
- frame: DataFrame¶
- meta: dict¶
- property n_realisations: int¶
How many realisations the file holds.
- realisation(index: int) DataFrame[source]¶
One realisation as its own frame, in calendar order.
The whole point of
realisation_stream()’s keying is that this is a well-defined object: realisationindexis the same series whether the file holds 10 of them or 10 000.
- to_wide(attr: str) DataFrame[source]¶
Pivot one attribute to hours-by-realisations.
Rows are the calendar span in order (
n_days x 24of them), columns are realisations. This is the layout most external tools want a time series in, and the oneensemble_to_xlsx()writes.- Raises:
KeyError – If
attris not one of this ensemble’s attributes.
- meteosynth.ensemble.ensemble_to_xlsx(ensemble: Ensemble | str | PathLike, path: str | PathLike, attrs: Sequence[str] | None = None) None[source]¶
Export an ensemble to
.xlsx, pivoted to wide, one sheet per attribute.Lossy and one-way, in the same sense as
to_csv(): the metadata does not survive, so this is an export for other software to read rather than a counterpart towrite_ensemble().The pivot is forced, not a preference. A worksheet holds 1 048 576 rows; a long-format ensemble of 1000 realisations x 8760 hours is 8.76 million, so long format caps out at about 119 realisations. Wide –
n_days x 24rows byn_realisationscolumns – fits to N ~ 16 000 instead, which covers the range this package is for.- Parameters:
ensemble (Ensemble or path-like) – An in-memory ensemble, or the path to one written by
write_ensemble().path (str or path-like) – Destination
.xlsx.attrs (sequence of str, optional) – Which attributes to export. Defaults to all of them, one sheet each.
- Raises:
ImportError – If no
.xlsxwriter is installed. This is the one path in the package that needs a dependency the core does not.ValueError – If the export would exceed a worksheet’s limits. It refuses rather than truncating: silently dropping realisations from an ensemble is exactly the kind of quiet wrong answer that is impossible to notice downstream.
- meteosynth.ensemble.read_ensemble(path: str | PathLike) Ensemble[source]¶
Read a file written by
write_ensemble().- Parameters:
path (str or path-like) – The
.parquetfile.- Return type:
- Raises:
ValueError – If the file was written by a newer schema version. Today’s code cannot know whether that version changed the columns or the row identity, and guessing yields a plausible-looking wrong answer – the same rule
load()applies.
- meteosynth.ensemble.write_ensemble(dataset: MetDataset, attrs: Sequence[str], path: str | PathLike, start: tuple, n_days: int, n_realisations: int, seed: int | None = None, n_days_window: int = 15, bandwidth: float | None = 0.1, include_feb29: bool = False, progress: bool = False, sampling: str = 'auto', compression: str = 'snappy') dict[source]¶
Generate an ensemble and stream it to one long-format parquet file.
Walks the calendar once, fitting each day’s models once per attribute and letting every realisation use them, then flushes that day’s rows as a parquet row group before moving on. Peak memory therefore holds one day’s generators plus one day’s values, not the whole ensemble – and not the 366 fitted generators that amortising the fit any other way would require.
Measured on Heraklion 2010-2020,
poa_global, a 365-day year: 1000 realisations drop from ~26.9 h to ~20.9 min (77x) against callinggenerate_series()1000 times. Multiply by the number of attributes – each is fitted and drawn separately.- Parameters:
dataset (MetDataset) – The training data. One
DayWindowGeneratoris built per attribute – fitting stays strictly per-attribute.attrs (sequence of str) – Attributes to generate. Each must have a registered
VariableSpec.path (str or path-like) – Destination
.parquetfile. Parent directories are created.start (tuple of (int, int)) –
(month, day)of the first day.n_days (int) – Number of consecutive days per realisation.
n_realisations (int) – How many independent series to generate.
seed (int, optional) – Root entropy. Realisation i of attribute a is a fixed function of
(seed, i, a)– seerealisation_stream()– so realisation 0 does not change when you ask for more realisations, andtemp_airdoes not change when you addwind_speedalongside it.n_days_window (int, optional) – Half-width of each day’s training window. Defaults to 15.
bandwidth (float, optional) – KDE bandwidth. Defaults to
0.1.include_feb29 (bool, optional) – Whether the walk visits Feb 29. Defaults to
False, giving a 365-day year.progress (bool, optional) – Show a
tqdmbar over the day walk.sampling ({"auto", "exact", "grid"}, optional) – Which path answers each draw.
"auto"(default) decides fromn_realisationsbefore drawing starts. The resolved value – never"auto"– is recorded in the file’s metadata, since it is part of what would be needed to regenerate the ensemble bit-for-bit. SeeSAMPLING_PATHS.compression (str, optional) – Parquet codec. Defaults to
"snappy"for the widest reader compatibility, since these files are written to be read by other software.
- Returns:
The metadata embedded in the file, so a caller can log or assert on it without re-reading.
- Return type:
dict
- Raises:
ValueError – If
attrsis empty or contains duplicates, or the walk request is malformed.
Notes
Row order is
(day_index, realisation, hour), because that is the order a streamed walk produces. A reader wanting one realisation therefore touches every row group; parquet’s column statistics make that cheap rather than free. Sort after reading if the access pattern warrants it –Ensemble.realisation()does.Attributes are generated independently; the file records that in its metadata
notes. SeeFEAT-2.
The Training Dataset¶
MetDataset is the package’s core noun: a validated,
source-agnostic training record that round-trips to disk without loss. Everything
downstream reads one, and nothing downstream cares how it was built.
The training dataset: a strict, source-agnostic, round-trippable record.
This package’s core business is generating synthetic series from a training record.
Getting that record is auxiliary – fetch it, read it from a file, or build the frame by
hand – and nothing downstream should care which. MetDataset is that record: it
owns the schema, validates on construction, carries its own
Provenance, and round-trips to disk without loss:
ds = MetDataset(my_frame) # from anything
ds.save("heraklion.parquet")
MetDataset.load("heraklion.parquet") == ds # True, by construction
Why a format at all¶
A file is optional here – it always was. But “optional to use” does not imply “not worth specifying”, and the package previously drew that inference: with no schema to version, provenance had nowhere to live except a fetcher’s cache, and validation had nowhere to live except a fetcher’s boundary check. So a hand-built frame was never support-validated at all, and a duplicated calendar row surfaced as a pandas reshape error deep inside the generator.
Strictness belongs to the format, so it applies however the data arrived.
What is rejected, and what is repaired¶
condition |
behaviour |
|---|---|
missing index columns / no variable |
raise |
duplicate |
raise |
invalid calendar ( |
raise |
value outside a spec’s physical support |
clip to the bound, warn, count it |
unregistered columns |
drop |
date with fewer than 24 hours |
keep, and report in |
The two structural rejections were already fatal before this class existed – they
just failed later and less legibly, inside pivot and inside day_slot. Moving them
to construction changes the error message, not the set of accepted inputs.
Out-of-support values are clipped rather than rejected because real station records
routinely carry small negative irradiance at night from sensor noise, and refusing a
19-year record over four -2 W/m2 readings would block real work. The check is also
narrower than it looks: it cannot catch the unit errors it was written for – 280 K and
20 degF both sit inside support, as the test suite asserts – so its reach is limited to
violations that happen to cross a bound. Clipping also matches what the model already
does, since sampling is truncated to support by
clamp_domain().
- class meteosynth.dataset.MetDataset(met_data: DataFrame, provenance: Provenance | None = None)[source]¶
Bases:
objectA validated, source-agnostic training record.
Accepts any frame carrying
INDEX_COLSplus at least one column with a registeredVariableSpec. The frame may come frommeteosynth.adaptersor straight from the caller – adapters are an optional collection helper, not a required layer.- Parameters:
met_data (pd.DataFrame) – The record. Never mutated; a canonicalised copy is taken.
provenance (Provenance, optional) – Where it came from. Defaults to
Provenance(source="user"), which invents nothing – it records that nobody claimed a source.
- met_data¶
The canonical frame: trimmed to registered columns, canonical dtypes, sorted by calendar, unique on
(year, month, day, hour), inside physical support.- Type:
pd.DataFrame
- provenance¶
Always present, never
None.- Type:
- clipped¶
How many values each column had clipped into support at construction. A report about this build, not a property of the data – reconstructing from the already-clipped frame yields an empty dict, which is why it takes no part in
__eq__().- Type:
dict of str to int
Examples
>>> ds = MetDataset(frame) >>> ds.irradiance_column 'poa_global' >>> dwg = DayWindowGenerator(ds, ds.irradiance_column)
- describe() Dict[str, Any][source]¶
What this dataset can say about itself.
Note
rowsis the size of the whole record. The size of the set a generator actually trains on is a different number, per calendar day, and lives onDayWindowGenerator– e.g. 341 pooled days for a +/-15-day window on an 11-year record, against 96 432 rows here. Reporting both, each where it is true, beats one number that has to be qualified.
- get_day_window_subset(month: int, day: int, n_days: int = 15) DataFrame[source]¶
Get a rolling window of the meteorological data centred on a calendar day.
Selects every record lying within
n_daysof(month, day)on theall_leapcalendar, pooled across all years in the dataset. This is the seasonal counterpart toget_month_subset(): where a month subset is centred on the middle of the month (so a May 1 model trains on data centred on May 16) and jumps discontinuously at month boundaries, a window is centred on the target day and slides smoothly from one day to the next.The window wraps across New Year, so a Jan 2 target reaches back into December and a Dec 30 target reaches forward into January. Feb 29 needs no special handling: it is an ordinary slot, so it is pooled into any nearby window and can also be requested as the target.
Note this is a climatological window, not a chronological one – a Jan 2 2011 target pools December 2011 as a proxy for “late-December climate”.
- Parameters:
month (int) – Month of the target day (1-12).
day (int) – Day of the target month.
n_days (int, optional) – Half-width of the window in days. Defaults to 15, giving a 31-day window.
n_days=0selects the target day alone; anyn_days >= 183selects the whole year.
- Returns:
Subset of the meteorological data for the window, with the same
date_idcolumn thatget_month_subset()adds, plus theday_slotof each record.- Return type:
pd.DataFrame
- Raises:
ValueError – If
(month, day)is not a valid date, orn_daysis negative.
- get_month_subset(month_ind: int) DataFrame[source]¶
Every record in a calendar month, pooled across years.
- Parameters:
month_ind (int) – Month index (1-12).
- Returns:
The subset, with a
date_idcolumn identifying each unique date.- Return type:
pd.DataFrame
- get_monthly_attribute_wide_format(value_col: str, month_id: int | None = None) DataFrame[source]¶
Pivot one attribute to days-by-hours, optionally for a single month.
- get_period_subset(start: int, end: int, origin: str | None = None) MetDataset[source]¶
The years
start-endinclusive, as a dataset in their own right.This is what makes one download per site enough: a record covering 2005-2023 answers a request for 2010-2020 by narrowing, so a training period does not have to be decided before the data is collected.
- Parameters:
start (int) – Inclusive year range. Must be fully contained in what this dataset holds.
end (int) – Inclusive year range. Must be fully contained in what this dataset holds.
origin (str, optional) – Where the wider record came from – a filename, usually. Recorded in the result’s provenance notes, so a narrowed dataset still says what it was narrowed from.
- Returns:
Carrying provenance for the period it now holds, not the one it was cut from, plus a note naming the origin.
- Return type:
- Raises:
ValueError – If the requested period is not fully contained. Returning the overlap would answer a different question than the one asked – silently, and with a plausible-looking result – which is the failure this format exists to prevent. Whether a cache is wide enough is
meteosynth.store.resolve()’s job, and it applies the same rule.
Notes
Unlike
get_month_subset()andget_day_window_subset(), which return bare frames because they are training slices consumed immediately by a generator, this returns a fullMetDataset. The difference is that the result is still a record of a site over a period – it can be saved, re-sliced, and asked where it came from – so dropping its provenance would lose exactly what the format exists to carry.The narrowing is exact. Measured on a real 19-year PVGIS record narrowed to its middle 11 years against the same 11 years fetched separately: identical row count, index columns aligned exactly,
temp_airandwind_speedbit-identical, andpoa_globalwithin 0.01 W/m2 – PVGIS’s own two-decimal rounding.Examples
>>> ds.describe_time_range() 'Data ranges from 2005 to 2023' >>> ds.get_period_subset(2010, 2020).describe_time_range() 'Data ranges from 2010 to 2020'
- property irradiance_column: str¶
The one irradiance column to model, chosen by availability.
Lets a caller stop caring whether the record came from PVGIS hourly (
poa_global) or a TMY (ghi). Raises when only components of a total are present – seeresolve_irradiance().
- classmethod load(path: str | PathLike) MetDataset[source]¶
Read a dataset written by
save().- Raises:
ValueError – If the file was written by a newer schema version. Today’s code cannot know whether that version changed the column rules, the dtypes or the row identity contract, and guessing yields a plausible-looking wrong dataset – the failure this format exists to prevent. Provenance fields are treated the opposite way: unknown ones are descriptive, so they are ignored with a warning rather than refused.
- classmethod read_csv(path: str | PathLike, provenance: Provenance | None = None, **kwargs) MetDataset[source]¶
Import from CSV – an interchange format, not a counterpart to
load().A CSV carries no provenance and no dtypes, so both are supplied here: dtypes by the schema’s canonicalisation, provenance by the caller if they know it.
- save(path: str | PathLike) None[source]¶
Write to parquet, losslessly, with provenance embedded.
Parquet is the canonical format because it is the only one of the three the package used to write that satisfies round-trip identity: one file, exact dtypes, and metadata carried inside it. CSV widens
int8toint64and drops metadata entirely, which is whyto_csv()is named as an export rather than a counterpart to this.Provenance travels as explicit parquet key-value metadata rather than through
DataFrame.attrs. Both were measured to round-trip, but key-value metadata is a documented feature of the format while attrs-in-parquet is pandas-internal behaviour – and going throughpyarrowon both sides keeps serialisation independent of how a given pandas/pyarrow pair negotiatesattrs.The result stays readable by anything that speaks parquet: a plain
pd.read_parquetreturns the columns and ignores the metadata.
- to_csv(path: str | PathLike, **kwargs) None[source]¶
Export to CSV for something else to read. Lossy, and says so.
The asymmetry with
save()is the point:save/loadare a pair that round-trips,read_csv/to_csvare two independent conveniences.
- property variables: Tuple[str, ...]¶
Every registered column the dataset holds, sorted.
- meteosynth.dataset.SCHEMA_VERSION = 1¶
Version of the on-disk schema. Bumped when the data contract changes – column rules, dtypes, row identity – never for a new provenance field, which readers tolerate.
- meteosynth.dataset.convert_to_daily_wide(met_data: DataFrame, value_col: str) DataFrame[source]¶
Reshape one attribute to one row per day and one column per hour.
- Parameters:
met_data (pd.DataFrame) – A long frame carrying the calendar index columns and
value_col.value_col (str) – The column to spread across hours.
- Returns:
Days-by-hours. Both values of a transition pair are read from the same row, which is what guarantees they come from the same day.
- Return type:
pd.DataFrame
- meteosynth.dataset.trim_columns(met_data: DataFrame) DataFrame[source]¶
Return a copy holding only the index columns and registered variables.
Unregistered columns are dropped rather than carried through, so nothing downstream can come to depend on a provider-specific column – which is exactly how a PVGIS quality flag ended up being treated as a meteorological quantity.
solar_elevationandIntfall out by this rule, not by a hardcoded list: neither is a stochastic environmental quantity, so neither has a spec. A user who genuinely wants to model solar elevation registers a spec for it and it survives. Declaring it is the deliberate act.Note the caller’s original frame is never mutated – only this processed copy is trimmed – so a dropped column remains available to the caller.
- meteosynth.dataset.validate_columns(met_data: DataFrame) None[source]¶
Check a frame carries the calendar index and at least one modellable column.
The rule is conditional – all of
INDEX_COLS, and any registered column – which is why it is a function rather than a flatREQUIRED_COLStuple: a tuple of things that must all be present cannot express “all of these and any of those”.Requiring only one registered column means a temperature-only source with no irradiance at all ingests cleanly. “Is this dataset usable for what you asked?” is a different question, answered later by the generator’s
attr_strvalidation, which can name the specific column that is missing.- Raises:
ValueError – If an index column is missing, or no registered column is present.
Where a training record came from – source, site, period.
A column name says which quantity it holds: poa_global is not poa_direct, and
ghi is not poa_global. That is deliberate and load-bearing. What it cannot say is
which site, which years, and which of a provider’s mutually exclusive fetch modes
produced it, which is what this record adds.
Note the record deliberately carries no irradiance_form field. The column list of
the dataset answers that, because the column name is the quantity – one less field able
to contradict the data it describes.
Pure data, no pandas – mirrors the free-function style of meteosynth.variables.
- class meteosynth.provenance.Provenance(source: str = 'user', site: str | None = None, latitude: float | None = None, longitude: float | None = None, start_year: int | None = None, end_year: int | None = None, fetched: str | None = None, meteosynth_version: str | None = None, notes: str | None = None)[source]¶
Bases:
objectWhat is known about where a dataset came from.
- Parameters:
source (str) – Who supplied it:
"pvgis_hourly","pvgis_tmy","open_meteo", or"user"for a frame the caller built or read themselves.site (str, optional) – Free label, e.g.
"heraklion". Never inferred from coordinates.latitude (float, optional) – Site coordinates as requested, not as the provider snapped them.
longitude (float, optional) – Site coordinates as requested, not as the provider snapped them.
start_year (int, optional) – Inclusive year range. Both
Nonefor a TMY, which genuinely has no single year – seemeteosynth.adapters.fetch_pvgis_tmy(), whose twelve months came from nine distinct years at Heraklion. Writing a range there would be fabrication.end_year (int, optional) – Inclusive year range. Both
Nonefor a TMY, which genuinely has no single year – seemeteosynth.adapters.fetch_pvgis_tmy(), whose twelve months came from nine distinct years at Heraklion. Writing a range there would be fabrication.fetched (str, optional) – ISO-8601 date, set when a network fetch produced the data.
meteosynth_version (str, optional) – The version that wrote it.
notes (str, optional) – Anything a caller wants to carry along.
Notes
Always present, never ``None``. A hand-built frame gets
source="user"with everything else absent. That invents nothing – it records that nobody claimed a source – while sparing every downstream caller anOptionalbranch.- end_year: int | None = None¶
- fetched: str | None = None¶
- classmethod from_dict(data: Dict[str, Any]) Provenance[source]¶
Build from a dict, tolerating keys this version does not know.
This is not sugar:
Provenance(**data)on a frozen dataclass raisesTypeErroron the first unrecognised key, which would make every provenance field ever added a breaking change for readers. A futureelevationortimezonemust not render a dataset unreadable, because nothing in the modelling path depends on it.Unknown keys are dropped after a single warning; missing keys take their defaults.
Note the asymmetry with the dataset’s
schema_version, which is checked strictly and raises on a future file. The schema governs the data, so a reader that cannot understand it must refuse rather than guess; provenance is descriptive, so a reader that cannot understand part of it can still work.
- latitude: float | None = None¶
- longitude: float | None = None¶
- meteosynth_version: str | None = None¶
- notes: str | None = None¶
- site: str | None = None¶
- source: str = 'user'¶
- start_year: int | None = None¶
Source Adapters¶
Optional collection helpers. They construct a
MetDataset with its provenance filled in – they are not a
layer the data has to pass through.
Optional helpers for collecting data from providers.
Adapters are an auxiliary tool for getting data in easily, not a required layer. The
contract between them and the rest of the package is a
MetDataset, which serves both use cases without forcing
either through the other’s path:
# A -- no data for the site; fetch it.
ds = fetch_pvgis(48.86, 2.35, 2011, 2012, cache="data/paris.parquet")
# B -- the user already has data. No adapter involved at all.
register("rel_humidity", VariableSpec((0.0, 100.0), "%"))
ds = MetDataset(my_df)
Both routes produce the same object, validated the same way. That is the point: a fetched record is no more trustworthy than a hand-built one, so the schema checks live in the dataset rather than here, and apply however the data arrived.
What a column name says, and what it cannot¶
poa_global and poa_direct are different columns, and a frame always says which one
it holds: the column name is the quantity, which is why nothing here records an
“irradiance form”. What a name cannot say is which site, which years, and which of a
provider’s mutually exclusive fetch modes produced the record – so each fetch stamps a
Provenance onto the dataset it returns, and
save() carries it into the file.
That is what lets a warm cache answer “are you the answer to what I am asking?” instead of being trusted on the strength of its path alone.
Two PVGIS entry points¶
fetch_pvgis() collects a real multi-year hourly record on the plane of array;
fetch_pvgis_tmy() collects a Typical Meteorological Year on the horizontal.
They are not interchangeable, and again the column names say so – poa_global from
one, ghi / dni / dhi from the other.
Note that a TMY is what this package is an alternative to: it is built to be typical, so it has no bad years in it and offers one profile and one answer. It is here as a baseline to generate against, not as an input the generator is meant to be trained on.
Provider naming¶
SOURCE_RENAMES maps a provider’s column names onto canonical ones. It is keyed
per source rather than being one flat alias map, because two providers can use the
same label for different quantities and a flat map would resolve that silently.
Note it is nearly empty for PVGIS: pvlib.iotools.get_pvgis_hourly already renames
the raw API’s T2m / WS10m / G(i) into temp_air / wind_speed /
poa_global before this package sees anything. The mapping earns its keep for
providers pvlib does not cover.
- exception meteosynth.adapters.CacheMismatchError[source]¶
Bases:
ExceptionA cached dataset does not answer the request that was made of it.
Raised rather than silently refetching, because the caller chose the path: a mismatch means a Paris request was pointed at a Heraklion file, which is a mistake to surface, not a stale entry to evict. Overwriting would destroy a record that may have taken a long download to produce – so repurposing a path is spelled
force_refetch=True.
- meteosynth.adapters.SOURCE_RENAMES: dict[str, dict[str, str]] = {'open_meteo': {'shortwave_radiation': 'poa_global', 'temperature_2m': 'temp_air', 'wind_speed_10m': 'wind_speed', 'windspeed_10m': 'wind_speed'}, 'pvgis': {}}¶
Provider column name -> canonical name, keyed by source.
PVGIS is empty because
pvlibhas already done the renaming; it is present so the source is a known one rather than an error, and as the place a raw-CSV mapping would go if this package ever ingested one.
- meteosynth.adapters.fetch_pvgis(latitude: float | None = None, longitude: float | None = None, start: int | None = None, end: int | None = None, irradiance: str = 'global', cache: None | bool | str | Path = None, data_dir: str | Path | None = None, force_refetch: bool = False, site: str | None = None, full_range: bool = True, components: bool = True, **kwargs) MetDataset[source]¶
Fetch hourly PVGIS data as a
MetDataset.Collect once per site, then work locally. By default this downloads the widest range PVGIS serves, keeps every column it returns, and caches the result – so a later request for any narrower period or any irradiance component is answered from disk.
start/endselect a view of that record, not the size of the download.- Parameters:
latitude (float, optional) – Site coordinates. Optional only when
sitenames a record already cached, from which they are recovered.longitude (float, optional) – Site coordinates. Optional only when
sitenames a record already cached, from which they are recovered.start (int, optional) – Inclusive years to return. Omit for everything the record holds. The download is governed by
full_range, not by these.end (int, optional) – Inclusive years to return. Omit for everything the record holds. The download is governed by
full_range, not by these.irradiance (str, optional) – Which irradiance quantity must be present:
"global"(default),"direct","sky_diffuse"or"ground_diffuse". Each keeps its specific column name, so the name records the quantity.cache (path,
NoneorFalse, optional) –None(default) stores underdata_dirand finds an existing record there by provenance. A path names one file explicitly, which is then required to answer the request or raise.Falsedisables the store in both directions – nothing is read, nothing is written.data_dir (str or Path, optional) –
The project’s data store. Defaults to
meteosynth.store.default_data_dir()–./dataunder the working directory. A relative path here is read from the working directory, not from the calling script’s folder, because a path you typed should mean what your shell would make of it. A script that wants its own folder says so withmeteosynth.paths.workspace():fetch_pvgis(..., data_dir=workspace(__file__).data_dir)
Ignored when
cachenames a file or isFalse.force_refetch (bool, optional) – Ignore any cache, fetch, and overwrite. The explicit way to repurpose a path.
site (str, optional) – Free label recorded in provenance, e.g.
"heraklion". Never inferred from the coordinates – but once bound, it resolves them.full_range (bool, optional) – Download everything PVGIS serves (default), discovered by
probe_year_range().Falsedownloads onlystart-end, which then become required.components (bool, optional) – Ask PVGIS for the three plane-of-array components (default) rather than its own global total. See the note below – this is what makes one file per site enough.
**kwargs – Forwarded to
pvlib.iotools.get_pvgis_hourly().
- Returns:
INDEX_COLS, every irradiance column the provider supplied,temp_airandwind_speed, with provenance filled in.- Return type:
- Raises:
ValueError – For an unknown
irradiance, a non-parquetcachepath, a request the provider cannot satisfy, or missing coordinates that no cached label supplies.CacheMismatchError – If a named cache file holds a different site, period or source.
AmbiguousRecordError – If several records in the default cache answer the request. Name one.
Notes
Why components rather than the provider’s own total. PVGIS returns either
poa_globalor the three components, never both, so a per-component choice at fetch time means a separate download and a separate file for each. Collecting the components instead serves every choice from one record, because the total is recoverable by summation – measured on Heraklion 2010 against a fetchedpoa_global, the maximum difference over 8760 hours is 0.01 W/m2, which is PVGIS’s own two-decimal rounding.A summed total is therefore derived, and says so in
notes. Passcomponents=Falsefor the provider’s ownpoa_globaland nothing else.Requires
pvlib, imported lazily so that the rest of the package does not depend on it.Examples
>>> fetch_pvgis(35.3387, 25.1442, site="heraklion") >>> fetch_pvgis(site="heraklion", start=2010, end=2020)
- meteosynth.adapters.fetch_pvgis_tmy(latitude: float, longitude: float, coerce_year: int | None = None, cache: None | bool | str | Path = None, force_refetch: bool = False, site: str | None = None, **kwargs) MetDataset[source]¶
Fetch a PVGIS Typical Meteorological Year as a
MetDataset.- Parameters:
latitude (float) – Site coordinates.
longitude (float) – Site coordinates.
coerce_year (int, optional) – Force every timestamp into this year. Defaults to
None, matchingpvlib– see the note below on what that means for theyearcolumn.cache (str or Path, optional) – A
.parquetpath, matched against this request exactly as infetch_pvgis(). Caching is opt-in here, unlikefetch_pvgis()– see the note below.force_refetch (bool, optional) – Ignore any existing cache, fetch, and overwrite it.
site (str, optional) – Free label recorded in provenance.
**kwargs – Forwarded to
pvlib.iotools.get_pvgis_tmy().
- Returns:
Carrying
INDEX_COLSand every registered column PVGIS supplied – ordinarilyghi,dni,dhi,temp_airandwind_speed.- Return type:
- Raises:
ValueError – If the provider returns no registered column, or
cacheis not a.parquetpath.CacheMismatchError – If a cache exists at
cachebut holds a different site or source.
Notes
The irradiance is horizontal, not plane-of-array. TMY supplies
ghi/dni/dhi, which is a different quantity from thepoa_*columnsfetch_pvgis()returns – they differ by however much the array is tilted. Transposing onto a plane is the caller’s job; this function does not do it, and the column names are what keep the two from being confused.A TMY has no single year, so its provenance records no period at all rather than a fabricated one. Each month is taken from a different real year, so with the default
coerce_year=Nonetheyearcolumn jumps between months. Measured on Heraklion (35.34, 25.14), the twelve months came from nine distinct years:month 1 2 3 4 5 6 7 8 9 10 11 12 year 2019 2015 2017 2008 2014 2020 2010 2006 2020 2017 2014 2009
That is harmless for the rolling-window training this package does – it pools by month and day, never by year – but it makes
describe_time_range()report a span that looks wrong. Pass a year for a clean single-year calendar.Rewriting the year silently was considered and rejected: it would destroy the record of which real year each month came from, and this package declares rather than infers.
Unlike
fetch_pvgis()there is no component flag to choose – TMY returns all three irradiance columns at once, so every registered column is kept and PVGIS’s unregistered extras (pressure,wind_direction,IR(h), …) fall out by rule.Caching stays opt-in here, and that asymmetry is deliberate.
fetch_pvgis()can cache by default because a record’s identity – site, period, columns – is fully written into itsProvenance, so a file found by searching can be checked against the request. A TMY’s identity is not:coerce_yearandroll_utc_offsetchange what comes back (pvlib’s_coerce_and_roll_tmyrewrites the year and can roll the series), and neither is a provenance field. A discovered TMY could therefore answer a different question than the one asked, silently – which is the failure this whole format exists to prevent. So a TMY is cached only where the caller names a file, and that file’s own contents are what say which encoding it holds.Requires
pvlib, imported lazily so the rest of the package does not depend on it.
- meteosynth.adapters.normalise(met_data: DataFrame, source: str) DataFrame[source]¶
Rename a provider’s columns to canonical names.
- Parameters:
met_data (pd.DataFrame) – Raw frame as the provider supplied it.
source (str) – Key into
SOURCE_RENAMES.
- Returns:
A renamed copy. Column selection and schema validation are left to
MetDataset, which trims to the registered set and enforces the schema on construction – for every route in, not only this one.- Return type:
pd.DataFrame
- Raises:
KeyError – If
sourceis unknown. An unknown source is an error rather than a silent no-op, since passing data through unrenamed would look like it worked.
- meteosynth.adapters.probe_year_range(latitude: float, longitude: float, **kwargs) tuple[source]¶
Ask PVGIS what year range it serves for a site.
Deliberately makes a request that should fail – year 1900 – because the error message names both bounds. One round trip, no bisection, and it cannot go stale the way a hard-coded range does when the provider extends its coverage.
- Parameters:
latitude (float) – Site coordinates.
longitude (float) – Site coordinates.
- Returns:
First and last year available.
- Return type:
tuple of (int, int)
- Raises:
RuntimeError – If PVGIS answers with something this cannot parse. Guessing a range here would silently truncate a record, so it refuses instead.
- meteosynth.adapters.validate_support(met_data: DataFrame) None[source]¶
Check every registered column lies inside its spec’s physical support.
- Parameters:
met_data (pd.DataFrame) – A canonical frame.
- Raises:
ValueError – Naming the column, the offending extreme, and the bound it violates.
Notes
This is an opt-in hard check, not the ingestion rule.
MetDatasetclips out-of-support values and reports the count instead, because real station records routinely carry small negative irradiance at night from sensor noise, and refusing a 19-year record over four of them blocks real work. Call this when you would rather be stopped than repaired.Validation is one-sided by nature either way: support is a necessary condition, not a sufficient one. 20 degC mislabelled from 20 degF is 20 either way and passes cleanly. This catches gross errors that happen to cross a bound; it is not a unit check, and unit conversion is deliberately not attempted here.
Where a Run Reads and Writes¶
The workspace: data/ for what was collected and output/ for what was generated,
under a root chosen by how the code was entered – the script’s own folder for a script,
the working directory for a command.
Which folder is the root of this run: the one question, answered once.
Every entry point that writes something has to answer it – a script fetching a training record, a subcommand writing an ensemble – and there are exactly two right answers, depending on how the code was entered:
A script’s files belong beside the script.
uv run python examples/use_cases/year-leros/leros_year_ensemble.pyshould put its data inexamples/use_cases/year-leros/, whichever folder the terminal happened to be in.A command’s files belong where the command was run.
meteosynth generatein~/my-studyshould put them in~/my-study, because that is the only place a command can mean.
Both give the same layout – data/ for what was collected, output/ for what was
generated – so learning one is learning the other:
<root>/
data/ collected records
output/ generated series, figures, tables
Why a module rather than a line in each script¶
The rule above is four lines of code. Writing those four lines into every script is the
obvious alternative, and it is how this repository arrived at three conventions that
disagree: the working directory in one folder, a hard-coded examples/data in four
more, an explicitly named file in a sixth. Nothing failed; the copies simply stopped
agreeing, and nothing anywhere said so.
So the rule lives here, and everything asks. That is the whole of this module’s job.
An explicit path is read from the working directory¶
The root above applies only when the caller says nothing. A path someone typed is read the way their shell would read it:
fetch_pvgis(..., data_dir="inputs") # <working directory>/inputs, never <root>/inputs
This is deliberate and it is the one place the two ideas meet. Anchoring a typed relative
path to the script would mean --data-dir inputs pointing somewhere the user cannot see
from their prompt, which is exactly the surprise this module exists to remove.
No ambient configuration¶
There is no environment variable and no global setting, for the reason
meteosynth.store.default_data_dir() gives at length: ambient configuration would let
the same script read a different store depending on which shell launched it.
workspace() reads its argument and the working directory, and nothing else.
It also does not go looking for its caller. A library cannot reliably find the file that called it – walking the call stack breaks in a REPL, in a notebook and in anything frozen – so the anchor is passed in, never discovered.
A note on the name¶
The module is paths and the function is workspace(), deliberately not both
workspace. A workspace.py holding a workspace() that the package re-exports
would leave meteosynth.workspace bound to the function, making the module
unreachable by import meteosynth.workspace – import a.b as m binds
getattr(a, "b") when that attribute exists, so it would silently hand back the
callable. Two names, no shadow: meteosynth.paths is the module,
meteosynth.workspace is the function, meteosynth.Workspace the class.
- meteosynth.paths.DATA_DIR_NAME = 'data'¶
Folder collected records go in, under the workspace root.
- meteosynth.paths.OUTPUT_DIR_NAME = 'output'¶
Folder generated files go in, under the workspace root. A sibling of the data folder rather than a child, because the two have opposite lifetimes: a record is collected once and re-read, an output is rewritten every run.
- class meteosynth.paths.Workspace(root: Path)[source]¶
Bases:
objectOne folder a run treats as “here”, and the two folders hanging off it.
- Parameters:
root (pathlib.Path) – The workspace root. Always absolute –
workspace()resolves it, so nothing downstream has to care what the working directory was at the time.
Notes
Construct via
workspace()rather than directly; that is where the rule for choosing a root lives.Nothing here creates a folder until something is written. The properties are plain paths, so importing this module and holding a
Workspaceleaves the disk untouched;data()andoutput()create on demand, because by then a caller has committed to writing.Examples
>>> ws = workspace("/tmp/study") >>> ws.data_dir PosixPath('/tmp/study/data') >>> ws.output("year_2023.csv") PosixPath('/tmp/study/output/year_2023.csv')
- data(name: str) Path[source]¶
Path to
nameinside the data folder, creating the folder.- Parameters:
name (str) – A filename, not a path. Nested names work but say nothing the store can read:
meteosynth.store.scan()looks one level deep, because provenance inside a record is what organises it, not where it sits.
- property data_dir: Path¶
<root>/data– the project’s store of collected records.
- describe() str[source]¶
One line naming where this run reads and writes, for a script to print.
Scripts announce their workspace before doing anything slow, so a wrong folder is caught in the first second rather than after a download. Having the sentence here keeps them all saying it the same way.
- property output_dir: Path¶
<root>/output– everything generated, and nothing collected.
- root: Path¶
- meteosynth.paths.workspace(anchor: None | str | PathLike = None) Workspace[source]¶
The workspace root for this run.
- Parameters:
anchor (str, os.PathLike or None, optional) –
What to anchor to:
None– the working directory. This is the command case, and the fallback in a notebook or REPL where there is no script file.__file__– a file, so the root is the folder containing it. This is the script case: it does not move when the script is launched from elsewhere.a directory – used as the root itself. A relative one is read from the working directory, like any path a user types.
A path that does not exist is treated as a directory, since the folder a run is about to create is a legitimate root.
- Returns:
With an absolute
root.- Return type:
Notes
The file-or-directory test is what makes ``__file__`` work without a second function.
workspace(__file__)andworkspace(some_dir)both mean “root here”, and a script should not have to say which kind of thing it is holding.A script written as
#%%cells runs both as a file and inside an editor’s interactive window, where__file__is undefined. The idiom that covers both:WS = workspace(globals().get("__file__"))
In the editor that yields
Noneand the root falls back to the working directory – the same answer the CLI gets, which is the honest one when there is no script to be beside.Examples
>>> workspace().root == pathlib.Path.cwd() True >>> workspace(__file__).root.name 'meteosynth'
The Download Cache¶
Finding a collected record without opening it. Where the adapters’ cache lives, what a cached file is called, and which one answers a given request – read from parquet footers, so a folder is discoverable without loading any data.
The project’s data store: collected records, kept beside the work that uses them.
A project folder accumulates source records – two sites, three year ranges, a TMY – and this module answers “which of these is the one I asked for?” without opening any of them. It is what lets an analysis be re-run without re-downloading, and what lets a script say “train on Heraklion” rather than naming a file.
Why “store” and not “cache”¶
A cache is expendable, transparent and usually shared: delete it and you lose only time. This is none of those things.
It is not expendable. Delete a record and you lose the exact input a result was built on. Providers revise their archives, so a refetch may not return the same numbers – the file is part of the analysis, not an accelerator for it.
It is not transparent. You name sites, list what you hold, and get an error rather than a silent choice when two records could answer the same question.
It is not shared. The store is
data/under a workspace root – the folder a script lives in, or the folder a command was run from, chosen bymeteosynth.paths.workspace()and by nothing else. Two projects side by side keep two independent stores; there is no user-level location, and no environment variable or global setting by which one could reach into the other.default_data_dir()is the working-directory case of that rule.
Discovery, as distinct from validation¶
MetDataset already answers “are you the answer to what I am
asking?” – a saved dataset carries its Provenance
inside the file, and meteosynth.adapters.fetch_pvgis() checks it before trusting a
record it was handed. That is validation: you name a file, and it either answers your
question or raises.
This module is the other half: discovery. Given a folder and a question, which file answers it?
Why a scan rather than an index¶
The obvious implementation is a manifest listing what the folder holds. It is also the
wrong one: a manifest is a second source of truth that drifts from the files it
describes, and the whole point of FEAT-13 was to put provenance inside the record
so it cannot be separated from it.
A scan is honest instead, and it is affordable because parquet stores its metadata in a footer. Reading provenance costs one seek; reading the data costs megabytes. Measured over three real cached records:
operation |
cost |
|---|---|
provenance via |
1.3 ms/file |
full |
113 ms/file |
So a folder of a hundred datasets is discoverable in ~130 ms, and nothing has to be maintained alongside the files.
Containment, not equality¶
A record covering 2005-2023 does answer a request for 2010-2020 – subsetting it is
exact, and it is what lets one download per site serve every training period. So the
period rule here is containment, and get_period_subset()
does the narrowing.
The same reasoning does not extend to picking between candidates. When two records both contain a request, this module refuses and lists them rather than choosing: which file a result was trained on is part of the result, and a rule like “the widest wins” makes that depend on what else happens to be in the folder. Ambiguity is rare by construction – one file per site – and when it happens it is worth a sentence from the user.
- exception meteosynth.store.AmbiguousRecordError[source]¶
Bases:
ExceptionSeveral cached records answer the same request.
Distinct from
CacheMismatchError, which means “the file you named is the wrong file”. This one means “you did not name a file, and more than one would do” – so the fix is to say which, not to overwrite anything.
- meteosynth.store.COORD_DP = 4¶
finer than any provider’s grid, coarser than float noise, so 35.3387 and 35.33870000001 are the same site. A false miss is not a correctness bug, but it does cost a silent re-download.
- Type:
Decimal places coordinates are compared to. ~11 m
- meteosynth.store.DATA_DIR_NAME = 'data'¶
Folder the store lives in, relative to the workspace root. A plain constant, not a setting: where a project’s data sits is a property of the project, so it is chosen by where you run rather than by anything ambient. Re-exported from
meteosynth.workspace, which owns the layout, so the name has one definition.
- class meteosynth.store.StoredRecord(path: Path, provenance: Provenance, columns: tuple)[source]¶
Bases:
objectOne stored record, identified without being read.
- Parameters:
path (pathlib.Path) – Where it is.
provenance (Provenance) – What it says about itself, read from the parquet footer.
columns (tuple of str) – Column names, also from the footer. Enough to answer “does this record hold the quantity I want to model?” without loading a single row.
- columns: tuple¶
- covers(start: int | None, end: int | None) bool[source]¶
Whether this record’s period contains
start-endinclusive.
- holds(column: str | None) bool[source]¶
Whether the requested column is present, or derivable from what is.
- path: Path¶
- provenance: Provenance¶
- meteosynth.store.default_data_dir() Path[source]¶
Where collected records go when the caller does not say:
./data.- Returns:
DATA_DIR_NAMEunder the current working directory.- Return type:
pathlib.Path
See also
meteosynth.paths.workspacechooses a root; this is its
data_dirfor the no-anchor case.
Notes
There is deliberately no environment variable and no global setting. Where a project’s data sits is a property of that project, so it is decided by the folder you work in and by nothing else. Ambient configuration would mean a script could read a different store depending on which shell launched it, which is precisely the class of surprise a provenance-checked format exists to remove. To use another folder, say so at the call:
fetch_pvgis(..., data_dir="inputs").The working directory rather than the calling script’s folder, because a library cannot reliably find its caller’s file – it would have to walk the call stack, which breaks in a REPL, in a notebook and in anything frozen. A script that wants its own folder regardless of where it is run from passes its anchor in:
from meteosynth import workspace WS = workspace(__file__) fetch_pvgis(..., data_dir=WS.data_dir)
which is this function’s rule with the root chosen explicitly rather than taken from the terminal. This function is defined as
workspace().data_dirso the two cannot drift apart.
- meteosynth.store.read_provenance(path: str | PathLike) StoredRecord | None[source]¶
Read one record’s provenance and column names, without reading its data.
- Parameters:
path (str or Path) – A
.parquetfile.- Returns:
Nonewhen the file carries no meteosynth metadata – an ordinary parquet file someone else wrote. That is not an error here: this function’s job is to report what a folder holds, and a folder is allowed to hold other things.- Return type:
StoredRecord or None
Notes
Deliberately does not check
schema_version. A future-versioned file cannot be loaded by this package –load()refuses it – but it can still be listed, and hiding it would make a folder’s contents depend on which version was doing the looking.
- meteosynth.store.record_filename(provenance: Provenance) str[source]¶
The conventional filename for a record, from what it says about itself.
<source>_<site>_<start>_<end>.parquet, with coordinates standing in for a missing site label and the period omitted when there is none (a TMY).Notes
The name is a convenience, not an identity. Provenance inside the file is what identifies it and what
resolve()matches on, so a renamed file still answers honestly and a mistyped one still fails honestly. The name exists so that a human listing the folder can see what they have.Examples
>>> record_filename(Provenance(source="pvgis_hourly", site="heraklion", ... start_year=2005, end_year=2023)) 'pvgis_hourly_heraklion_2005_2023.parquet'
- meteosynth.store.resolve(directory: str | PathLike, *, source: str, site: str | None = None, latitude: float | None = None, longitude: float | None = None, start: int | None = None, end: int | None = None, column: str | None = None) Path | None[source]¶
The one cached record that answers this request.
- Parameters:
directory (str or Path) – Folder to search, non-recursively.
source (str) – Must match exactly:
"pvgis_hourly","pvgis_tmy", …site (str, optional) – Site label, compared case-insensitively against
site. When given, coordinates are not consulted – a name the user chose is a stronger statement of intent than a pair of floats.latitude (float, optional) – Used when
siteis not given, compared atCOORD_DPdecimal places.longitude (float, optional) – Used when
siteis not given, compared atCOORD_DPdecimal places.start (int, optional) – Inclusive period. A record matches if its own period contains this one.
end (int, optional) – Inclusive period. A record matches if its own period contains this one.
column (str, optional) – A quantity the record must hold, or be able to produce – all three POA components answer a
poa_globalrequest.
- Returns:
Nonewhen nothing matches, which tells the caller to fetch.- Return type:
pathlib.Path or None
- Raises:
AmbiguousRecordError – When more than one record answers, listing every candidate. Choosing for the caller would make a result depend on what else is in the folder.
Examples
>>> resolve("data", source="pvgis_hourly", site="heraklion", ... start=2011, end=2012) PosixPath('data/pvgis_hourly_heraklion_2005_2023.parquet')
- meteosynth.store.scan(directory: str | PathLike) List[StoredRecord][source]¶
Every meteosynth record in a folder, identified from its footer.
- Parameters:
directory (str or Path) – Searched non-recursively. A missing folder is an empty result, not an error – “nothing is cached yet” is the normal first-run state.
- Returns:
Sorted by path, so output is stable across filesystems.
- Return type:
list of StoredRecord
Variables and the Spec Registry¶
What each column physically is. A column is modellable if and only if it has a
registered VariableSpec.
What each quantity physically is – support, units, a human-readable name.
A VariableSpec carries constraints, not an identity. It has no name
field: several column names may legitimately share one spec, and a spec that owned a
name could not honestly serve four columns at once. The name lives on the registry key
instead.
All plane-of-array irradiance components share IRRADIANCE – same support, same
units, same night-time degeneracy. They differ in which part of the incoming radiation
they count, which is a fact about the data rather than about the constraints.
The names stay distinct even though the spec is shared, because
poa_global is roughly poa_direct + poa_sky_diffuse + poa_ground_diffuse.
Collapsing them into one generic irradiance column would let a global series train
under a name meaning direct: same units, same support, passing every validation, and
wrong by roughly a factor of two. Keeping the names distinct makes the column name the
provenance, which is why nothing in this package needs a metadata sidecar.
The same argument runs across planes, which is why IRRADIANCE_HORIZONTAL is a
separate object despite carrying identical constraints. ghi and poa_global are
the same physical quantity measured on different surfaces, and they differ by however
much the array is tilted – so a horizontal series trained under a plane-of-array name is
the factor-of-two error again, in a second dimension. The constraints coincide; the
long_name does not, and that string is what
meteosynth.adapters.validate_support() quotes back to a user who is, by
construction, in the middle of debugging where their numbers came from.
The registry is what makes the package variable-agnostic: a column is modellable if and only if it has a spec. Register one and it works, with no change to the package:
>>> register("rel_humidity", VariableSpec((0.0, 100.0), "%", "Relative humidity"))
>>> get_spec("rel_humidity").support
(0.0, 100.0)
Pure data, no pandas – mirrors the free-function style of meteosynth.day_window.
- meteosynth.variables.IRRADIANCE = VariableSpec(support=(0.0, None), units='W/m2', long_name='Plane-of-array irradiance')¶
Plane-of-array irradiance. Shared by every component – see the module docstring for why the component names stay distinct despite sharing one spec.
- meteosynth.variables.IRRADIANCE_COLUMNS: Tuple[str, ...] = ('poa_global', 'ghi')¶
Irradiance totals, most preferred first – the answer to “which column here is the irradiance?” when a caller has not named one.
Only totals appear. A component is a part of a total, never “the irradiance”:
poa_directis roughly 70 % ofpoa_global, so returning it for a caller who asked for the irradiance would be the factor-of-two error the naming scheme exists to prevent, arrived at from a new direction.resolve_irradiance()therefore raises rather than guessing when only components are present.poa_globaloutranksghibecause plane-of-array is what this package models – but a record holding onlyghiresolves toghirather than erroring, and the returned name is what every caller then uses, so the plane is never silently lost.
- meteosynth.variables.IRRADIANCE_HORIZONTAL = VariableSpec(support=(0.0, None), units='W/m2', long_name='Horizontal-plane irradiance')¶
Horizontal-plane irradiance –
ghi,dni,dhi, as PVGIS TMY and most reanalysis products supply it. Physically identical constraints toIRRADIANCE, deliberately a distinct object: thelong_namereaches the user inmeteosynth.adapters.validate_support()’s error text, and naming a horizontal quantity “plane-of-array” would misinform at precisely the wrong moment.
- meteosynth.variables.TEMP_AIR = VariableSpec(support=(-273.15, None), units='degC', long_name='Air temperature')¶
Air temperature. Bounded below by absolute zero; unbounded in practice.
- class meteosynth.variables.VariableSpec(support: Tuple[float | None, float | None] = (None, None), units: str = '', long_name: str = '')[source]¶
Bases:
objectThe physical constraints of a quantity, independent of what a column calls it.
- Parameters:
support (tuple of (float or None, float or None)) –
(lower, upper)physical bounds.Nonemeans unbounded on that side. Sampling is truncated to this range, so an out-of-support value becomes unsamplable by construction rather than merely unlikely.units (str) – The units the data is expected to already be in. Declarative for now: ingestion validates against
support, it does not convert.long_name (str) – Human-readable description, for plots and error messages.
Notes
Specs are declared, not inferred. Inference reads the sample rather than the physics and gets both hard cases wrong:
wind_speed’s observed minimum is 0.07 in the shipped record, so inference would call it unbounded below; a July-onlytemp_airsubset is entirely positive, so inference would call it non-negative. Both wrong, and silently so.- clamp_domain(data_min: float, data_max: float) Tuple[float, float][source]¶
Intersect an observed data range with this spec’s physical support.
This is the whole of support enforcement: restrict the evaluation domain before building a CDF, and
np.interpcannot then return a value outside it. Truncation is applied to the observed range rather than replacing it – the data still governs where the mass is, the support only says where it may not go.- Parameters:
data_min (float) – The observed range of the values being fitted.
data_max (float) – The observed range of the values being fitted.
- Returns:
The clamped
(min, max)domain.- Return type:
tuple of (float, float)
Examples
>>> IRRADIANCE.clamp_domain(-8.1, 81.0) # negative tail cut at the bound (0.0, 81.0) >>> TEMP_AIR.clamp_domain(5.9, 20.1) # nothing to clamp (5.9, 20.1)
- long_name: str = ''¶
- support: Tuple[float | None, float | None] = (None, None)¶
- units: str = ''¶
- meteosynth.variables.WIND_SPEED = VariableSpec(support=(0.0, None), units='m/s', long_name='Wind speed')¶
Wind speed. Non-negative, but unlike irradiance it never touches the bound.
- meteosynth.variables.get_spec(name: str) VariableSpec[source]¶
Look up the spec registered for a column name.
- Parameters:
name (str) – Column name, e.g.
"poa_direct".- Return type:
- Raises:
KeyError – If nothing is registered under
name, with the registered set and a pointer toregister()in the message – an unregistered column is a normal thing for a user to hit, so the error has to say what to do about it.
- meteosynth.variables.irradiance_columns() Tuple[str, ...][source]¶
Every registered column name whose spec is an irradiance spec, sorted.
Derived from the registry rather than hand-listed, so a user who registers
poa_reflectedagainstIRRADIANCE– the sharing thatregister()already documents as intended – becomes resolvable with no change here.
- meteosynth.variables.register(name: str, spec: VariableSpec, overwrite: bool = False) None[source]¶
Register a spec under a column name, making that column modellable.
- Parameters:
name (str) – Column name to register.
spec (VariableSpec) – Its physical constraints. May be an object already registered under another name – sharing is the intended usage for related quantities.
overwrite (bool, optional) – Permit replacing an existing registration. Defaults to
Falseso that a typo’d re-registration is an error rather than a silent redefinition of what a column physically is.
- Raises:
ValueError – If
nameis already registered andoverwriteis False.
- meteosynth.variables.registered() tuple[str, ...][source]¶
Every registered column name, sorted.
This is the authoritative answer to “what can be modelled?” – generators validate
attr_stragainst it, and ingestion keeps exactly these columns.
- meteosynth.variables.resolve_irradiance(columns: Iterable[str], prefer: Sequence[str] = ('poa_global', 'ghi')) str[source]¶
Pick the one irradiance column to model, by what is available.
This is what lets a caller stop caring whether their record came from PVGIS hourly (
poa_global) or a TMY (ghi). It never renames or converts anything: it returns a name that the caller then uses everywhere –attr_str, plot labels, saved output – so the quantity and its plane travel with the result.- Parameters:
columns (iterable of str) – Column names to choose from, e.g.
dataset.frame.columns.prefer (sequence of str, optional) – Preference order over totals. Defaults to
IRRADIANCE_COLUMNS.
- Returns:
The chosen column name.
- Return type:
str
- Raises:
LookupError – If no irradiance column is present, or if the only ones present are components of a total that is itself absent. Both messages name what was found and what was looked for, because a user hitting this is by construction trying to work out what their data holds.
Examples
>>> resolve_irradiance(["poa_global", "temp_air", "wind_speed"]) 'poa_global' >>> resolve_irradiance(["ghi", "dni", "dhi"]) 'ghi' >>> resolve_irradiance(["poa_direct", "temp_air"]) # sole candidate, no ambiguity 'poa_direct'
- meteosynth.variables.unregister(name: str) None[source]¶
Remove a registration.
Mainly for tests, which must be able to restore the registry to its shipped state; a leaked registration would otherwise make one test’s columns modellable in another.
- Raises:
KeyError – If
nameis not registered.
The canonical calendar schema, and what ships pre-registered.
“Which columns matter” is no longer a fixed list. A column is modellable if and only
if it has a registered VariableSpec, so
meteosynth.variables is the authority and this module holds only the calendar
index plus a documentation-grade note of what ships registered out of the box.
That inversion is deliberate. MODELLED_ATTRS used to be a whitelist that also
doubled as the ingestion requirement, which is how Int – a PVGIS quality flag –
became a modellable “meteorological attribute”. Making the registry authoritative means
a user can model rel_humidity or snow_depth by declaring what it physically is,
with no change to this package, and means provider quirk columns fall out by rule rather
than by a hand-maintained exclusion list.
Pure data, no pandas – mirrors the free-function style of
meteosynth.day_window.
- meteosynth.constants.DEGENERACY_RTOL: float = 1e-09¶
Relative tolerance for calling a slice constant – used by the simulator’s
Kindclassification and by the fidelity metrics’ degenerate-cell mask, so both agree on what a constant (e.g. night-time irradiance) hour is.Degeneracy used to be an exact
np.std(...) == 0test, which worked only because PVGIS happens to store literal zeros at night. Any source that stores a physically-zero night as1e-16– interpolation, resampling, unit conversion, or a provider that keeps near-zero noise – fell through to the 2D branch instead, and a 2D KDE was then fitted across apreviousspanning ~50 and acurrentspanning ~1e-14. That covariance is catastrophically ill-conditioned, which is the failure this tolerance exists to prevent.The comparison is against the scale of this simulator’s own data, not against the slice being tested. A night slice’s spread is large relative to itself – values of ~1e-14 vary by ~1e-14 – so a purely relative test would still call it varying. What makes it degenerate is that it is negligible next to the other axis, and that disparity is precisely what conditions the covariance badly.
1e-9 sits far below any real meteorological signal (irradiance resolved to 1e-6 W/m2 against a 800 W/m2 day) and far above float64 residue from a trigonometric identity.
- meteosynth.constants.INDEX_COLS: tuple[str, ...] = ('year', 'month', 'day', 'hour')¶
Chronological index columns every record must carry.
- meteosynth.constants.SHIPPED_ATTRS: tuple[str, ...] = ('poa_global', 'poa_direct', 'poa_sky_diffuse', 'poa_ground_diffuse', 'ghi', 'dni', 'dhi', 'temp_air', 'wind_speed')¶
What ships pre-registered, for documentation and error messages. This gates nothing:
meteosynth.variables.registered()is what generators validate against, and it grows when a user callsmeteosynth.variables.register().
- meteosynth.constants.modelled_attrs() tuple[str, ...][source]¶
Every currently registered column name.
Thin pass-through to
meteosynth.variables.registered(), kept so callers with a “what can I model?” question have an obvious place to ask it. It is a function rather than a constant because the registry is extensible at runtime – a module level tuple would be a stale snapshot taken at import time.
Seasonal Day Windows¶
The circular all_leap calendar the rolling windows are indexed on.
Canonical calendar helpers for rolling day-of-year windows.
Transition models can be trained either on a calendar-month subset
(get_month_subset()) or on a
rolling window of +/- n days centred on a target day
(get_day_window_subset()). This
module provides the calendar arithmetic the latter needs, as pure functions over
(month, day) pairs with no pandas dependency.
Days are indexed by a slot on the all_leap calendar (CF-conventions all_leap
/ 366_day): every year is treated as if it had 366 days, so Feb 29 owns slot 60
and Mar 1 is always slot 61 regardless of the year:
Jan 1 -> 1 ... Feb 28 -> 59, Feb 29 -> 60, Mar 1 -> 61 ... Dec 31 -> 366
Non-leap years simply never emit slot 60. This keeps the mapping leap-independent, so
records pooled from leap and non-leap years line up. Note that pandas’
.dt.dayofyear does not have this property: it shifts by one after February in leap
years, which would misalign the whole March-December calendar when pooling years.
See docs/design/completed/rolling-day-window.md for the full rationale.
- meteosynth.day_window.DAYS_IN_YEAR = 366¶
Number of slots in the canonical
all_leapyear.
- meteosynth.day_window.MAX_HALF_WIDTH = 183¶
Maximum possible circular distance between two slots.
- meteosynth.day_window.circular_delta(slots: int | ndarray, center: int, period: int = 366) ndarray[source]¶
Circular distance in days between
slotsandcenter.The calendar wraps, so the distance from Dec 31 (366) to Jan 1 (1) is 1, not 365.
- Parameters:
slots (int or np.ndarray) – Slot(s) to measure.
center (int) – Slot at the centre of the window.
period (int, optional) – Length of the calendar. This is not a free parameter – it is fixed by the slot index and defaults to
DAYS_IN_YEAR. The slot axis has unit spacing over1..366, so onlyperiod=366makes the Dec 31 -> Jan 1 wrap cost exactly 1 day. Passing 365 collapses Dec 31 onto Jan 1; passing 365.25 or 366.25 opens a phantom gap at the wrap. It is exposed only so that the invariant can be tested explicitly.
- Returns:
Distance(s) in days, in
0..period // 2.- Return type:
np.ndarray
Examples
>>> int(circular_delta(day_slot(1, 1), day_slot(12, 31))) 1
- meteosynth.day_window.day_slot(month: int, day: int) int[source]¶
Map a calendar
(month, day)to its slot on theall_leapcalendar.The mapping is leap-independent:
Feb 29is an ordinary slot (60), and every date after February keeps the same slot in leap and non-leap years alike.- Parameters:
month (int) – Month of the year (1-12).
day (int) – Day of the month (1-31), validated against the
all_leapmonth length, so(2, 29)is accepted but(2, 30)and(4, 31)are not.
- Returns:
Slot in
1..366.- Return type:
int
- Raises:
ValueError – If
monthis outside 1-12, ordayis not a valid day of that month.
Examples
>>> day_slot(1, 1) 1 >>> day_slot(2, 29) 60 >>> day_slot(12, 31) 366
- meteosynth.day_window.day_slots(months, days) ndarray[source]¶
Vectorised
day_slot()for array-likes of months and days.- Parameters:
months (array-like of int) – Broadcastable arrays of months (1-12) and days of the month.
days (array-like of int) – Broadcastable arrays of months (1-12) and days of the month.
- Returns:
Integer array of slots in
1..366, with the broadcast shape.- Return type:
np.ndarray
- Raises:
ValueError – If any
(month, day)pair is not a validall_leapdate.
- meteosynth.day_window.slot_to_month_day(slot: int) Tuple[int, int][source]¶
Invert
day_slot().- Parameters:
slot (int) – Slot in
1..366.- Returns:
The
(month, day)owning that slot.- Return type:
tuple of (int, int)
- Raises:
ValueError – If
slotis outside1..366.
Examples
>>> slot_to_month_day(60) (2, 29)
- meteosynth.day_window.window_slots(month: int, day: int, n_days: int = 15) ndarray[source]¶
The slots lying within
n_daysof(month, day), wrapping across New Year.- Parameters:
month (int) – Month of the target day (1-12).
day (int) – Day of the target month.
n_days (int, optional) – Half-width of the window in days. Defaults to 15, giving a 31-slot window.
n_days=0selects the target day alone; anyn_days >= 183selects the whole year.
- Returns:
Sorted array of slots, of length
min(2 * n_days + 1, 366).- Return type:
np.ndarray
- Raises:
ValueError – If
n_daysis negative, or(month, day)is not a valid date.
Examples
Feb 29 is an ordinary target – no special-casing needed:
>>> len(window_slots(2, 29, n_days=15)) 31
The window wraps across the year boundary:
>>> [slot_to_month_day(s) for s in window_slots(1, 2, n_days=4)] [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (12, 29), (12, 30), (12, 31)]
Simulators¶
The transition models underneath the generators. All three share a
get_next_state / generate_sequence interface.
Markov chain simulator using 2D kernel density estimation (KDE).
Simulates a continuous Markov-chain process by fitting a 2D KDE to the joint
probability distribution of (previous, current) value pairs and sampling
from the resulting conditional distribution p(current | previous).
Sampling is confined to the physical support declared by a
VariableSpec, so out-of-support values are unsamplable
by construction rather than merely unlikely. See
docs/design/variable-specs-and-initialisation.md section 3.
- class meteosynth.markov_chain_simulator_kde2d.Kind(value)[source]¶
Bases:
EnumWhat kind of transition the data supports – not what kind of variable it is.
Degeneracy is empirical: which hours are constant depends on latitude and season, so it is detected from the data and cannot be declared in a spec. Irradiance is identically zero at night and so degenerates there; wind and temperature never do.
Replaces the old two-letter
singularity_typecodes:Kindmeaning
was
KDE_2Dprevious and current both vary
NNKDE_1Dprevious constant, current varies
CNCONSTANTcurrent constant
NC,CCNCandCCcollapse into one: both already dispatched to the same routine (return the constant), and the distinction never affected behaviour.“Constant” means constant to within tolerance – see
_DEGENERACY_RTOL. A physically-zero night stored as1e-16is constant, whatever an exact comparison against zero would say.- CONSTANT = 3¶
- KDE_1D = 2¶
- KDE_2D = 1¶
- class meteosynth.markov_chain_simulator_kde2d.MarkovChainSimulator2dKDE(data: DataFrame, bandwidth: float | None = None, spec: VariableSpec | None = None, sampling: str = 'auto')[source]¶
Bases:
objectA class to simulate continuous Markov chain processes using a 2D KDE for joint probability distribution between previous and current values.
- Parameters:
data (pd.DataFrame) – DataFrame containing
previousandcurrentcolumns of floats.bandwidth (float, optional) – Bandwidth for the KDE.
Noneuses Scott’s rule.spec (VariableSpec, optional) – Physical constraints of the quantity. When given, the evaluation domain is clamped to
spec.supportin both sampling paths, making out-of-support samples impossible. WhenNonethe domain is the observed range alone, which is the old (unconstrained) behaviour.
- calculate_next_state_cdf(bandwidth: float = None, update_bandwidth: bool = True) DataFrame[source]¶
_summary_
- Parameters:
bandwidth (float, optional) – _description_. Defaults to None.
- Returns:
_description_
- Return type:
pd.DataFrame
- current_values: array¶
- generate_sequence(start_state: float, length: int, rng: None | int | Generator = None) List[float][source]¶
Generate a Markov sequence of states starting from
start_state.- Parameters:
start_state (float) – The initial state of the sequence.
length (int) – Number of transitions to simulate. The returned list has
length + 1elements (the start state plus each transition).rng (None, int or np.random.Generator, optional) – Source of randomness, resolved once so the whole trajectory is reproducible while remaining stochastic from step to step.
- Returns:
The generated sequence, including
start_stateas the first item.- Return type:
List[float]
- get_conditional_density(prev_value: float, resolution: int = 1000) Tuple[ndarray, ndarray][source]¶
Get the conditional probability density function for a given previous value.
Parameters:¶
- x_valuesnp.ndarray
Array of the x domain values to evaluate the conditional density
- prev_valuefloat
The previous value to condition on
- resolutionint
Number of points to evaluate the conditional density
Returns:¶
- Tuple containing:
points: Array of current values
density: Conditional probability density at each point
- get_conditional_density_gen(prev_value: float, x_values: array = None) Tuple[ndarray, ndarray][source]¶
Generate the conditional probability density function given a previous value.
This method creates a conditional probability density function
p(current|previous)by evaluating the joint density of the previous and current values, then normalizing.- Parameters:
prev_value (float) – The previous value to condition on.
x_values (np.array, optional) – Array of x values at which to evaluate the conditional density. If None, a default grid will be created based on the domain.
- Returns:
A tuple containing:
Array of x values
Corresponding conditional density values
- Return type:
Tuple[np.ndarray, np.ndarray]
Notes
The conditional density is calculated as
p(current|previous) = p(previous, current) / p(previous). If the joint KDE is not available (typically when there is no variation in the data), a fallback singularity joint density will be used.
- get_next_state(current_state: float, rng: None | int | Generator = None) float[source]¶
Sample the next state, dispatching on
kind.- Parameters:
current_state (float) – The current state from which to transition. Ignored when
kindis notKind.KDE_2D– a 1D or constant model has nothing to condition on.rng (None, int or np.random.Generator, optional) – Source of randomness. An int is treated as a seed for a fresh generator;
Nonedraws from a fresh unseeded one. Pass aGeneratorto draw successive values from one stream, which is what the chain walkers do.
- Returns:
The next state, guaranteed inside
self.spec.supportwhen a spec is set.- Return type:
float
- property has_quantile_grid: bool¶
True once this simulator has cached its conditional quantile grid.
- property is_degenerate: bool¶
True when the data does not support a full 2D conditional model.
- plot_conditional_densities(prev_values: List[float], resolution: int = 1000) Tuple[Figure, Axes][source]¶
Plot conditional probability densities for multiple previous values.
Parameters:¶
- prev_valuesList[float]
List of previous values to show conditional distributions for
- resolutionint
Number of points to evaluate each conditional density
Returns:¶
fig, ax: Figure and Axes objects
- plot_joint_distribution(resolution: int = 100) Tuple[Figure, Axes][source]¶
Plot the joint distribution of previous and current values.
Parameters:¶
- resolutionint
Grid resolution for plotting
Returns:¶
fig, ax: Figure and Axes objects
- plot_transition_slice(prev_value: float, resolution: int = 100) Tuple[Figure, Axes][source]¶
Visualize a slice through the joint distribution at a specific previous value.
Parameters:¶
- prev_valuefloat
The previous value to slice at
- resolutionint
Grid resolution for plotting
Returns:¶
fig, ax: Figure and Axes objects
- precompute_grid() None[source]¶
Build the conditional quantile grid now, rather than waiting for it to pay off.
Sampling normally uses the direct path until a simulator has been asked for
_GRID_ACTIVATION_CALLSsamples, because building the grid costs about as much as that many direct calls. Call this when the ensemble size is known in advance and is large – it removes the threshold’s crossover from the timing, and makes every draw come from the same sampler.A no-op unless
kindisKind.KDE_2D: the 1D and constant paths are already a single interpolation and a lookup.
- previous_values: array¶
- sampling¶
Which path answers a draw. See
SAMPLING_PATHS. Validated here so a typo fails at construction rather than silently sampling from something else.
- meteosynth.markov_chain_simulator_kde2d.SAMPLING_PATHS = ('auto', 'exact', 'grid')¶
The three ways a draw can be answered, named so a caller can say which rather than discover it from call history (
FEAT-17)."exact"Evaluate the conditional density live, every time. No grid is ever built – not lazily, not eagerly. Deterministic and auditable: a number came from the density and will again next run. ~13x slower than
"grid"for a large ensemble."grid"Build the cached quantile grid up front and draw from it throughout. Right when many draws are coming; a pessimisation when few are (a chained year takes one draw per simulator, so building grids would cost ~9x more than it saves).
"auto"Decide from whatever is known, once, before any drawing starts. Callers that know their draw count – an ensemble knows
n_realisations– resolve to"exact"or"grid"up front and never switch. Only a caller that knows nothing, such as a baregen_dayloop, falls back to_GRID_ACTIVATION_CALLSand switches part-way, which is then a stated choice rather than a hidden one.
“Exact” means no grid, not no approximation. The live path still discretises the value axis and integrates by cumulative sum; the grid adds interpolation across
_CDF_GRID_NODESnodes and a quantile axis of_GRID_QUANTILE_LEVELSon top of that. Measured, the grid’s extra error is 0.03 % on the mean and 0.04-0.31 % on the standard deviation – ~100x below what this repo can resolve. The choice is about determinism, not accuracy.
- meteosynth.markov_chain_simulator_kde2d.resolve_sampling(sampling: str, n_expected_draws: int | None = None) str[source]¶
Turn a requested path and a known draw count into the path that will actually run.
- Parameters:
sampling ({"auto", "exact", "grid"}) – What the caller asked for.
n_expected_draws (int, optional) – How many draws each simulator will see, when the caller knows.
Nonemeans genuinely unknown – not zero.
- Returns:
"auto","exact"or"grid"."auto"is returned only when the count is unknown, and means “let the counter advise”.- Return type:
str
- Raises:
ValueError – For an unknown path. Failing here rather than silently defaulting is the point: a typo in a sampling mode must not quietly change what a result was drawn from.
Examples
>>> resolve_sampling("auto", n_expected_draws=1000) 'grid' >>> resolve_sampling("auto", n_expected_draws=1) 'exact' >>> resolve_sampling("auto") 'auto' >>> resolve_sampling("exact", n_expected_draws=1000) 'exact'
- class meteosynth.markov_implementations.markov_chain_simulator_continuous.ContinuousMarkovChainSimulator(data: DataFrame, bandwidth: float | None = None)[source]¶
Bases:
objectA class to simulate Markov chain processes with continuous (float) state values using kernel density estimation for transition modeling.
- generate_sequence(start_state: float, length: int, seed: int | None = None) List[float][source]¶
Generate a sequence of states starting from the given state.
Parameters:¶
- start_statefloat
The starting state for the sequence
- lengthint
The number of transitions to simulate (resulting sequence will be length+1)
- seedint, optional
Random seed for reproducibility
Returns:¶
List of states including the start state and subsequent transitions
- get_next_state(current_state: float, seed: int | None = None) float[source]¶
Generate the next state based on the current state using conditional density.
Parameters:¶
- current_statefloat
The current state from which to transition
- seedint, optional
Random seed for reproducibility
Returns:¶
float: The next state sampled from the conditional distribution
- plot_sample_transitions(from_values: List[float], n_samples: int = 1000) Tuple[Figure, Axes][source]¶
Plot sample transitions from multiple starting states.
Parameters:¶
- from_valuesList[float]
List of starting states
- n_samplesint
Number of samples to draw for each starting state
Returns:¶
fig, ax: Figure and Axes objects
- plot_transition_density(from_value: float, points: int = 1000, range_padding: float = 1.0) Tuple[Figure, Axes][source]¶
Plot the transition probability density function for a given state.
Parameters:¶
- from_valuefloat
The starting state
- pointsint
Number of points to evaluate the density function
- range_paddingfloat
Factor to extend the range of the plot beyond observed data
Returns:¶
fig, ax: Figure and Axes objects
- class meteosynth.markov_implementations.markov_chain_simulator_discrete.MarkovChainSimulatorDiscrete(data: DataFrame)[source]¶
Bases:
objectA class to simulate Markov chain processes based on transition probabilities derived from historical data.
- generate_sequence(start_state: int | float | str, length: int, seed: int | None = None) List[int | float | str][source]¶
Generate a sequence of states starting from the given state.
Parameters:¶
- start_stateint, float, or str
The starting state for the sequence
- lengthint
The number of transitions to simulate (resulting sequence will be length+1)
- seedint, optional
Random seed for reproducibility
Returns:¶
List of states including the start state and subsequent transitions
- get_next_state(current_state: int | float | str, seed: int | None = None) int | float | str[source]¶
Generate the next state based on the current state.
Parameters:¶
- current_stateint, float, or str
The current state from which to transition
- seedint, optional
Random seed for reproducibility
Returns:¶
The next state according to transition probabilities
- get_transition_probabilities(state: int | float | str) Series[source]¶
Get transition probabilities from a specific state to all other states.
Parameters:¶
- stateint, float, or str
The state for which to get transition probabilities
Returns:¶
pd.Series containing transition probabilities to all possible states
Fidelity Metrics¶
How closely an ensemble reproduces the reference record. Imported as a namespace,
from meteosynth import metrics, rather than flattened into the top level.
Computation only: both sides arrive as a SeriesSet
– one (members, hours) array plus its calendar – and every test returns tables and
arrays. Reading files and plotting stay with the caller.
The one data object every fidelity metric takes: a set of equal-length series on a shared calendar.
Both sides of a comparison arrive in the same form – the reference years (one member per observed year) and the synthetic realisations (one member per realisation) – so every metric is written once, for one shape, and never opens a file or reads metadata.
The helpers here convert the two tables the package already produces into that form. They take in-memory frames, never paths: reading is the caller’s job.
- class meteosynth.metrics.series.SeriesSet(values: ndarray, month: ndarray, day: ndarray, hour: ndarray, members: ndarray | None = None, attr: str = '', dropped: tuple = ())[source]¶
Bases:
objectEqual-length hourly series of one attribute, sharing one calendar.
- Parameters:
values (np.ndarray) –
(n_members, n_hours). A member is one observed year or one realisation.month (np.ndarray) –
(n_hours,)each – the calendar every member is on. Whole days only, hours0..23in order within each day.day (np.ndarray) –
(n_hours,)each – the calendar every member is on. Whole days only, hours0..23in order within each day.hour (np.ndarray) –
(n_hours,)each – the calendar every member is on. Whole days only, hours0..23in order within each day.members (np.ndarray, optional) –
(n_members,)labels: the years, or the realisation indices. Defaults to0..n_members-1.attr (str, optional) – The attribute’s column name. Used in messages and summaries only.
dropped (tuple, optional) – Members a helper removed before construction (e.g. incomplete years), so the caller can report them. Informational; nothing reads it.
- Raises:
ValueError – If shapes disagree, the hours are not whole days in order, a
(month, day)is not a calendar date, orvaluesholds NaN.
Notes
The calendar is shared, not per member. That is what makes the object a plain rectangle: every metric can slice members, hours and
(month, hour)cells with array indexing, and nothing has to re-check alignment. It is also why Feb 29 is absent from the reference side – the ensembles are generated without it, and keeping it would make leap years one day longer than every other member.Arrays are held as given, not copied, so a 70 MB ensemble is not duplicated. Do not modify them after construction.
- cell(month: int, hour: int) ndarray[source]¶
Every value at one hour of one month.
- Returns:
(n_members, n_days_in_month); zero columns if the month is not covered.- Return type:
np.ndarray
- cell_mask(month: int, hour: int) ndarray[source]¶
Boolean
(n_hours,)mask of the columns in one(month, hour)cell.
- classmethod from_ensemble(ensemble: Ensemble, attr: str) SeriesSet[source]¶
One member per realisation, from an in-memory
Ensemble.Built on
Ensemble.to_wide(), so the pivot exists in one place. For a large ensemble on disk, reading one attribute day by day into an(N, n_hours)array and calling the constructor directly is far lighter than loading the whole file.
- classmethod from_ensemble_frame(frame: DataFrame, attr: str) SeriesSet[source]¶
One member per realisation, from the ensemble’s long frame.
Expects
realisation, day_index, month, day, hour, <attr>– the layoutpd.read_parquetreturns for a file written bywrite_ensemble().
- classmethod from_reference_frame(frame: DataFrame, attr: str) SeriesSet[source]¶
One member per observed year, from a long
year, month, day, hour, <attr>frame.Feb 29 is dropped, so every year sits on
no_leap_calendar(). Years that do not cover all 8 760 hours of it (a partial first or last year, gaps, NaN) are left out and listed indropped.- Parameters:
frame (pd.DataFrame) – E.g.
MetDataset.met_dataorpd.read_parquet(path, columns=[...]).attr (str) – The column to take.
- Raises:
KeyError – If a required column is missing.
ValueError – If a
(year, month, day, hour)appears twice, or no year is complete.
- property hours_per_member: int¶
the length of every member’s series.
- Type:
Columns
- property n_members: int¶
observed years, or realisations.
- Type:
Rows
- property slots: ndarray¶
Day-of-year slot (1..366,
all_leap) of every column.
- meteosynth.metrics.series.no_leap_calendar() tuple[ndarray, ndarray, ndarray][source]¶
The
(month, day, hour)columns of one 365-day year, Feb 29 absent.The calendar every ensemble generated with
include_feb29=Falseis on, and the oneSeriesSet.from_reference_frame()reshapes each observed year onto. Useful when building aSeriesSetfrom arrays directly.- Returns:
month, day, hour – Each of length 8 760, in calendar order.
- Return type:
np.ndarray
Marginal fidelity: does the synthetic ensemble reproduce the reference distribution, hour by hour, month by month?
One distance per (month, hour) cell, judged against a year-split control band under a
pre-registered pass rule. Paper Test 3; the scalar summary behind the quantile traces.
- class meteosynth.metrics.marginal.MarginalFidelity(distance: SampleDistance = <factory>, control: YearSplitBand = <factory>, pass_share: float = 0.9, extra_distances: tuple[~meteosynth.metrics.distances.SampleDistance, ...]=(KolmogorovSmirnovStatistic(), ))[source]¶
Bases:
objectDistance per
(month, hour)cell, against a year-split control band.- Parameters:
distance (SampleDistance) – The judged metric. Default
Wasserstein1.control (YearSplitBand) – How the control band is built, and the seed.
pass_share (float) – Pre-registered: the reference passes overall when at least this share of its non-degenerate cells pass. Fix it before looking at any number.
extra_distances (tuple of SampleDistance) – Reported as additional full-power columns, never judged. Default: the KS statistic.
Notes
Per cell, three numbers answer three different questions:
full-power
<name>: all reference values against all synthetic values. The best estimate of the true distance – the number to quote.control band: for each split, the distance between reference half A and half B – how far apart two real samples are.
size-matched
<name>_matched: for the same splits, half A against a synthetic subsample the size of half B, so it sits on the control band’s footing. The median of these is the number to judge: a cell passes when it is at or below the band’s upper edge.
Quoting the full-power number against the size-matched threshold would compare two different measurements.
- evaluate(reference: SeriesSet, synthetic: SeriesSet) MarginalResult[source]¶
Score every
(month, hour)cell both sides cover.Deterministic for a given
control.seed: the splits are drawn first, then one synthetic subsample per cell and split, cells in(month, hour)order.
- class meteosynth.metrics.marginal.MarginalResult(table: DataFrame, attr: str, distance_name: str, n_reference: int, n_synthetic: int, pass_share: float, pass_threshold: float, passed: bool)[source]¶
Bases:
objectThe outcome of
MarginalFidelity.evaluate().- table¶
One row per scored
(month, hour)cell.<name>full-power distance,<name>_normthe same over the reference sd (physical-unit distances only),bias_normandsd_ratio(a level shift and a spread change are different defects, and the distance alone conflates them),<name>_matchedthe judged size-matched median,control_lo/hi/median,degenerate,passes, and one column per extra distance. Normalised columns are NaN where the reference sd is 0.- Type:
pd.DataFrame
Share of non-degenerate cells that pass.
- Type:
float
- passed¶
pass_share >= pass_threshold.- Type:
bool
- grid(column: str) ndarray[source]¶
One column as a
(12, 24)month-by-hour array, NaN where a cell was not scored.Row
month - 1, columnhour– ready for a heatmap.
- property scored: DataFrame¶
non-degenerate cells.
- Type:
The rows that count towards
pass_share
Temporal fidelity: does multi-day persistence emerge correctly?
The generator is first order in the hour index; nothing in it fits memory beyond one hour. Lag 1 is preserved by construction, so the diagnostic range is the lags after it. Paper Test 2, autocorrelation part.
- class meteosynth.metrics.temporal.TemporalFidelity(max_lag: int = 240, control: MemberSpreadBand = <factory>, batch: int = 100)[source]¶
Bases:
objectRaw and anomaly autocorrelation to
max_lag, against the reference members’ spread.- Parameters:
max_lag (int) – Longest lag, in hours. 240 h = 10 days spans the synoptic band.
control (MemberSpreadBand) – Percentiles of the per-member band. A synthetic curve inside it is indistinguishable from a real year.
batch (int) – Realisations per FFT batch; caps working memory.
Notes
Raw and anomaly answer different questions. The raw ACF of an hourly series is dominated by its daily and yearly cycles, so it mostly tests whether their shape is reproduced. The anomaly ACF, with the climatology removed, is what tests the Markov assumption.
- evaluate(reference: SeriesSet, synthetic: SeriesSet, climatology: Climatology) TemporalResult[source]¶
ACFs of every member of both sides, and the per-lag comparison.
- Parameters:
climatology (Climatology) – Subtracted from both sides. Build it from the reference with
Climatology.from_series(), and pass the same one when comparing ensembles.
- class meteosynth.metrics.temporal.TemporalResult(table: DataFrame, attr: str, acf_reference_raw: ndarray, acf_reference_anomaly: ndarray, acf_synthetic_raw: ndarray, acf_synthetic_anomaly: ndarray, tau_reference: ndarray, tau_synthetic: ndarray)[source]¶
Bases:
objectThe outcome of
TemporalFidelity.evaluate().- table¶
Per lag, for
rawandanomaly: reference mean and band edges (ref_<kind>_p5/_p95at the default percentiles), synthetic mean and its standard error, and whether the synthetic mean is inside the band.- Type:
pd.DataFrame
- acf_reference_raw, acf_reference_anomaly
(n_reference, max_lag + 1)– one curve per reference member.- Type:
np.ndarray
- acf_synthetic_raw, acf_synthetic_anomaly
(n_synthetic, max_lag + 1).- Type:
np.ndarray
- tau_reference, tau_synthetic
Anomaly decorrelation time per member, hours.
- Type:
np.ndarray
The typical value of an attribute at each hour of each day of the year.
Subtracting it leaves the weather: an anomaly autocorrelation measures memory, where a raw one mostly measures whether the average day and the average year have the right shape.
- class meteosynth.metrics.climatology.Climatology(means: ndarray, half_width: int)[source]¶
Bases:
objectMean per
(day-of-year slot, hour), smoothed over a circular calendar window.- Parameters:
means (np.ndarray) –
(366, 24); rowslot - 1holds the 24 hourly means of thatall_leapslot.half_width (int) – The
+/-days each slot was pooled over.
Notes
Build it from the reference only, and subtract the same object from both sides, so each is measured against one baseline. Comparing two ensembles (e.g. generated with
+/-7and+/-15day windows) is only fair against one shared climatology, which is why it is an argument toevaluate()rather than computed inside it.- anomalies(series: SeriesSet) ndarray[source]¶
series.valuesminus the climatology:(n_members, n_hours), a new array.
- baseline(series: SeriesSet) ndarray[source]¶
The climatological value at every column of
series:(n_hours,).
- classmethod from_series(reference: SeriesSet, half_width: int = 15) Climatology[source]¶
Estimate from the reference members.
A raw
(slot, hour)mean has one value per member – 19 for a 19-year record – which is too noisy to subtract, so each slot pools the+/-half_widthslots around it, wrapping across New Year. Slots with no data (Feb 29, absent from aSeriesSet) are filled by that pooling. The default of 15 days matches the generator’s own default training window.The slots beside that gap (Feb 28, Mar 1) pool one slot fewer on one side, so on a steep seasonal slope they sit very slightly off it – 1 slot of 31 at the default.
- Raises:
ValueError – If
half_widthis outside0..183, or a slot is still empty after pooling.
Autocorrelation of many series at once, and the decorrelation time read off it.
- meteosynth.metrics.autocorrelation.autocorrelation(matrix: ndarray, max_lag: int, batch: int = 100) ndarray[source]¶
Autocorrelation of each row, lags
0..max_lag, by FFT.- Parameters:
matrix (np.ndarray) –
(n_rows, T)– one series per row, e.g.SeriesSet.valuesor its anomalies. A 1-D series is treated as one row.max_lag (int) – Longest lag, in samples. Must be below
T.batch (int) – Rows transformed at once. Caps the working memory independently of
n_rows.
- Returns:
(n_rows, max_lag + 1); column 0 is 1. A constant row has no defined autocorrelation and comes back as NaN.- Return type:
np.ndarray
Notes
Computed within each row, never across rows. Concatenating independent realisations would put a discontinuity at every join and manufacture a decay that is an artefact of the layout.
The biased estimator (dividing by
Tat every lag) is used deliberately: it gives a smoothly decaying, positive-definite curve, where the unbiased one inflates the long lags exactly where the sample is thinnest.
- meteosynth.metrics.autocorrelation.decorrelation_time(acf: ndarray) float | ndarray[source]¶
Integral decorrelation time, in the ACF’s lag units:
1 + 2 * sum(rho).The sum runs up to the first lag at or below zero. Past that crossing the terms are noise around zero, and summing them adds variance without adding signal.
- Parameters:
acf (np.ndarray) – One ACF (1-D, lag 0 first) or one per row (2-D).
- Returns:
A float for a 1-D input, one value per row for a 2-D input.
- Return type:
float or np.ndarray
Descriptive distribution curves: the empirical CDF and hourly quantile traces.
Instruments, not tests – they describe one side and leave the judging to the fidelity tests. Both return plain arrays or frames, ready to plot.
- meteosynth.metrics.distribution.DEFAULT_QUANTILES = (0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99)¶
The percentile traces the paper’s Figure 1 plots (paper Test 3).
- meteosynth.metrics.distribution.empirical_cdf(values, n_points: int | None = 1001) tuple[ndarray, ndarray][source]¶
The empirical cumulative distribution function of a sample.
- Parameters:
values (array-like) – Any shape; flattened. NaN is dropped.
n_points (int or None) – When the sample is larger than this, return the curve at
n_pointsevenly spaced probabilities instead of at every value. 8.76 M synthetic values plot no better than 1 001 points and take far longer.Nonekeeps every value.
- Returns:
x, p – Values and their cumulative probabilities,
xascending.- Return type:
np.ndarray
- meteosynth.metrics.distribution.quantile_traces(series: SeriesSet, month: int, quantiles=(0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99)) DataFrame[source]¶
Per hour of day, the given quantiles of every value in one month.
- Parameters:
series (SeriesSet) – Either side; all members are pooled.
month (int) – 1..12.
quantiles (sequence of float) – Probabilities in
[0, 1].
- Returns:
Index
hour(0..23), one column per quantile. Plot reference and synthetic on the same axes to see level, spread, skew and boundary behaviour together.- Return type:
pd.DataFrame
- Raises:
ValueError – If
seriesdoes not covermonth.
Distances between two samples of one quantity – the pluggable part of the marginal test.
A distance is any callable taking two 1-D samples and returning a float, with a name
(its column in result tables) and a flag saying whether the number is in the data’s own
units. MarginalFidelity uses one as its judged metric and any
number more as extra columns, so adding a criterion means adding a class here, nothing else.
- class meteosynth.metrics.distances.KolmogorovSmirnovStatistic[source]¶
Bases:
objectThe two-sample Kolmogorov-Smirnov statistic D: the largest gap between the two ECDFs.
The statistic only, never its p-value. With tens of thousands of synthetic values against a few hundred observed, the p-value measures the sample size, not fidelity. D is still a useful unitless effect size.
- class meteosynth.metrics.distances.SampleDistance(*args, **kwargs)[source]¶
Bases:
ProtocolWhat a distance must provide to be used by the fidelity tests.
- in_physical_units: bool¶
True when the value is in the data’s units (so dividing by an sd makes it unitless).
- name: str¶
Column name in result tables, e.g.
"w1".
- class meteosynth.metrics.distances.Wasserstein1[source]¶
Bases:
objectWasserstein-1 (earth mover’s) distance between two 1-D samples.
In the data’s own units – 0.4 m/s can be read without a table – more sensitive in the tails than KS, and comparatively stable against sample size.
Control bands: how far apart two samples of the real climate are.
A distance of 0.4 m/s is neither good nor bad until it is set against the distance between two real samples of the same site and variable. A control band is that scale; a synthetic result inside it is indistinguishable from real data. Different tests build it differently, so each strategy is its own small class.
- class meteosynth.metrics.control.ControlBand(*args, **kwargs)[source]¶
Bases:
ProtocolWhat every control band exposes: the percentiles that bound it.
- class meteosynth.metrics.control.MemberSpreadBand(percentiles: tuple[float, float] = (5.0, 95.0))[source]¶
Bases:
objectThe spread of a per-member curve across the reference members.
Used by
TemporalFidelity: each observed year gives its own autocorrelation curve, so the spread of those curves is the natural scale – no splitting needed.
- class meteosynth.metrics.control.YearSplitBand(n_splits: int = 100, percentiles: tuple[float, float] = (5.0, 95.0), seed: int = 11)[source]¶
Bases:
objectSplit the reference members into two halves at random, many times.
Used by
MarginalFidelity: for every split, the distance between half A and half B is one draw of “two real samples”. The halves are whole members (whole years), because days inside one year are not independent of each other.- Parameters:
n_splits (int) – Random half-splits. The band settles well before 100; more only smooths its edges.
percentiles (tuple of float) – The band’s lower and upper edge. The upper one is the pass threshold.
seed (int) – Root entropy for the splits and for any subsampling done alongside them. Fixed per test, so every variable and every ensemble is judged on identical splits.
Degenerate cells: where reference and synthetic are the same constant.
Night-time irradiance is 0 on both sides. Any distance there is 0, so the cell “passes” automatically – and roughly half of irradiance’s cells are like that. Left in a pooled pass share they inflate it, so they are flagged and excluded.
“Constant” uses DEGENERACY_RTOL, the tolerance behind the
simulator’s Kind.CONSTANT: a night hour here is one where the model is degenerate,
not one where the sun is nominally below the horizon.
- meteosynth.metrics.degeneracy.constant_cells(reference: SeriesSet, synthetic: SeriesSet) ndarray[source]¶
(12, 24)boolean grid: which(month, hour)cells are degenerate.Row
month - 1, columnhour. A cell either side does not cover isFalse.
- meteosynth.metrics.degeneracy.degeneracy_tolerance(reference: SeriesSet, synthetic: SeriesSet) float[source]¶
The spread below which a cell counts as constant, in the data’s units.
Scaled by the largest magnitude on either side, so the test asks “is this negligible next to the rest of the data?” rather than “is this exactly zero?” – the same question the simulator asks.
- meteosynth.metrics.degeneracy.is_degenerate(reference_values: ndarray, synthetic_values: ndarray, tolerance: float) bool[source]¶
True when both samples are constant and equal, to within
tolerance.Two different constants (reference 0, synthetic 5) are not degenerate: that is a real failure and must be scored.
Plotting Utilities¶
- meteosynth.sup_plot_lib.plot_2d_kde_sns(month_data, value_str: str = 'poa_direct', ylabel='Plane of Array Direct Irradiance (W/m^2)', figsize=(10, 6), contour_levels=5)[source]¶
Create a 2D KDE plot with filled contours and contour lines using seaborn.
Parameters: - month_data: DataFrame containing the data to plot. - figsize: Tuple specifying the figure size. - contour_levels: Number of contour levels to display.
- meteosynth.sup_plot_lib.plot_hourly_mean_with_error_bars_plt(met_data, value_str: str = 'poa_direct', k=1.0, show_points: bool = True)[source]¶
Create a plot of the hourly mean and standard error for ‘poa_direct’ with error bars.
- meteosynth.sup_plot_lib.plot_month_by_year_sns(dataset: MetDataset, month_ind: int = 5, value_col: str = 'poa_direct')[source]¶
Create a faceted plot of the monthly data for each year using Seaborn.
Parameters: - dataset: MetDataset instance. - month_ind: Month index (1-12) to filter the data. - value_col: Column name for the value to plot.
Returns: - FacetGrid object.