Skip to content

API reference

Every public function and class of loadcast, documented from its docstrings. Everything listed here is importable from the package itself (import loadcast) unless its module says otherwise.

What to generate

What to generate: one site's carriers, proportions, rhythm and timing.

The parameterisation is deliberately the one an engineer can answer from a site visit or an energy bill, rather than the one the mathematics wants:

annual_mwh      how much energy the site uses in a year
heat_to_cold    how much more heat than cold it wants
elec_share      what fraction of the total is electricity
process_class   how the process runs: continuously, in shifts, in batches
carrier_lag_h   how far the carriers are offset from one another
carrier_correlation   how tightly they move together when not offset
rated_kw        the most each carrier can draw, if known
load_factor     or each carrier's mean over peak demand instead
calendars       a calendar of its own for a carrier that keeps other hours

The three shares are not independent -- they are a composition summing to one -- so asking for two numbers and deriving the third is both easier to answer and impossible to make inconsistent.

Why a ratio and a share rather than three shares

Given the heat:cold ratio k and the electricity share s_e, the composition follows from s_h + s_c + s_e = 1 and s_h = k * s_c:

s_c = (1 - s_e) / (1 + k)
s_h = k * s_c

so the shares are exact by construction and can never fail to sum to one. A composition that silently renormalises somewhere in the middle is the easiest way to get a study wrong, because the point you solved is then not the point you plotted.

DemandSpec dataclass

DemandSpec(annual_mwh: float = 10000.0, heat_to_cold: float | None = None, elec_share: float = 0.2, process_class: str | ProcessClass = 'semi_continuous', carrier_correlation: float | None = None, carrier_lag_h: dict[str, int] = dict(), waste_to_heat: float | None = None, seed: int = 42, label: str = '', rated_kw: dict[str, float] = dict(), calendars: dict[str, Calendar] = dict(), load_factor: dict[str, float] = dict())

One site to generate.

Parameters:

Name Type Description Default
annual_mwh float

Total annual energy across all three carriers, MWh, as delivered: the heat and cold the process receives and the electricity it uses for everything else, not the fuel and electricity bought. The generated profiles reproduce this exactly.

10000.0
heat_to_cold float | None

Ratio of annual heat demand to annual cold demand, both delivered. Use None (the default) for a site with no cooling demand, or 0 for one with no heat demand. A ratio published in final energy, such as loadcast.reference.heat_to_cold_range, must be converted first.

None
elec_share float

Electricity as a fraction of the annual total.

0.2
process_class str | ProcessClass

The rhythm: the name of a shipped class (see loadcast.available_classes()), or a ProcessClass object, such as one built with loadcast.custom_class, which needs no registering.

'semi_continuous'
carrier_correlation float | None

Correlation wanted between the finished heat and cold profiles, at the offset where they match best. It is what you observe in the output; the generator solves for the internal correlation that delivers it (see loadcast.solve_correlation_knob). It cannot go below the floor the calendars set, loadcast.correlation_floor. None (the default) asks for 0.47, raised to the floor without a warning where the floor is higher; a value you set and the generator cannot deliver draws a TargetMissedWarning.

None
carrier_lag_h dict[str, int]

Hours by which each carrier's process fluctuation trails the others, as {"cold": 6} for cold demand following heat by six hours. Carriers not named have zero lag. The shared calendar is not shifted: a factory's opening hours are common to all its carriers, so only the process fluctuation is offset.

It is an input to choose, not a fitted value. No public archive meters heat and refrigeration at one industrial site, so no heat-to-cold lag can be estimated from data: sweep it.

dict()
waste_to_heat float | None

Waste heat the site rejects, per unit of heat it consumes. None (the default) for no waste heat. Waste heat takes no share of annual_mwh, because the site does not buy it; see waste_mwh.

None
rated_kw dict[str, float]

The most each carrier can draw, kW, as {"heat": 2000, "cold": 400}: the cap on its profile. A rated carrier's load factor is its mean demand over its rating, in place of the process class's. Give the peak the carrier actually reaches -- the measured peak demand, or the rating of equipment that runs flat out at peak. An oversized nameplate leaves the cap unused, and the generator warns. Carriers not named keep the class's load factor.

dict()
load_factor dict[str, float]

Each carrier's load factor, mean demand over peak, as {"heat": 0.5}: the other way to set its cap. Carriers not named keep the class's. A carrier takes a rating or a load factor, not both: with its annual energy fixed, its mean demand is fixed, so a rating already is a load factor.

dict()
calendars dict[str, Calendar]

A calendar of its own for some carriers, as {"cold": Calendar.from_schedule([("daily", 0, 24)])} for cold rooms that run through the weekend. Carriers not named follow the process class's calendar. The carrier keeps the class's fluctuation within its running hours, and takes a load factor that suits its calendar (see loadcast.carrier_load_factors).

dict()
seed int

Random seed. The same seed and spec always give the same profiles.

42
label str

Optional name carried through for plotting and bookkeeping.

''
Notes

At zero offset, a lag and a weak correlation look the same: as the lag grows, the correlation measured at zero offset falls towards the floor the shared calendar imposes, exactly where a small carrier_correlation would also put it. When sweeping the lag, hold carrier_correlation fixed -- it is defined at the offset of best match, so the sweep then changes timing only and not how tightly the carriers move together.

correlation_target property

correlation_target: float

The heat-cold correlation asked for: carrier_correlation, or 0.47.

composition property

composition: tuple[float, float, float]

Annual shares (heat, cold, electricity), summing to one exactly.

lags property

lags: tuple[int, ...]

Lag in hours for each carrier, in ALL_CARRIERS order.

waste_mwh property

waste_mwh: float

Annual waste heat rejected, MWh.

Sized off the heat demand rather than given a share of the annual total, because waste heat is not bought. A site consuming 10 GWh of process heat and rejecting 8 GWh of it has waste_to_heat = 0.8 and still an annual_mwh of 10 000 for what it consumes.

active_carriers property

active_carriers: tuple[str, ...]

Carriers with a non-zero share.

A site that buys only electricity, or only heat and electricity, is a perfectly ordinary site. The generated frame always has all three columns so the schema is stable, but the ones not asked for are zero and the coincidence knobs do not apply to them.

annual_mwh_by_carrier

annual_mwh_by_carrier() -> dict[str, float]

Annual energy per carrier, MWh.

from_composition classmethod

from_composition(composition, **kwargs) -> 'DemandSpec'

Build a spec from explicit shares (heat, cold, electricity).

For callers who already work in composition space, such as a simplex design over the three carriers. The shares must sum to one; they are not renormalised, because silently moving the point is worse than failing.

from_shares classmethod

from_shares(shares: dict[str, float], **kwargs) -> 'DemandSpec'

Build a spec from whichever carriers a site actually has.

DemandSpec.from_shares({"heat": 1.0})                  # heat only
DemandSpec.from_shares({"cold": 0.7, "elec": 0.3})     # no heat
DemandSpec.from_shares({"heat": 0.5, "cold": 0.25, "elec": 0.25})

Carriers left out are zero. The shares given must sum to one -- a single carrier is written as {"heat": 1.0} rather than {"heat": 1} meaning "all of it", so that a typo cannot silently rescale the site.

Generating

The generator.

Every profile is a product of four factors, then capped and rescaled:

P_m(t) = L_m * S(t) * M_m(t - tau_m) * R_m(t - tau_m)

where

P_m(t)   demand for carrier m at hour t, kW
L_m      level, set so the annual energy matches the spec exactly
S(t)     calendar factor: month x hour of the week, mean one
M_m(t)   on/off state, 1 when running and `off_level` when idle
R_m(t)   residual fluctuation, lognormal AR(1) with mean one
tau_m    carrier m's lag in hours
Why a product rather than a sum

A multiplicative factor is dimensionless, so the same rhythm transfers between a 200 kW site and a 20 MW one without retuning. Additive noise does not: "plus or minus 50 kW" means something different at each scale, and it can drive the load negative. Every factor here is positive and has mean one, so the level L_m alone sets the energy and nothing downstream can drift it.

The calendar is never shifted, and shared unless the spec gives a carrier one of its own. A factory's opening hours are common to its carriers -- heat and production refrigeration do not take the weekend off at different times -- so only the process fluctuation carries a lag. Cold rooms that run through the weekend are the exception a carrier's own calendar is for. The shift wraps around the end of the year, so it only reorders the hours: lagging a carrier leaves every one of its own statistics (load factor, spread, persistence, annual energy) exactly unchanged. The lag therefore changes only how the carriers relate to one another.

correlated_ar1

correlated_ar1(n: int, n_series: int, phi: float, sigma: float, correlation: float, rng: Generator) -> np.ndarray

n_series Gaussian AR(1) paths sharing a cross-series correlation.

Each path follows z(t) = phi*z(t-1) + eps(t) with the innovations correlated across paths through a Cholesky factor. The innovation standard deviation carries a factor sqrt(1 - phi^2): an AR(1) driven by innovations of variance s^2 settles at stationary variance s^2/(1 - phi^2), so this choice makes the stationary variance exactly sigma^2. Starting the path from a draw of that stationary distribution then removes the burn-in entirely, which matters because at phi = 0.97 the burn-in would be several hundred hours of a year.

lognormal_from_latent

lognormal_from_latent(z: ndarray, sigma: float) -> np.ndarray

Latent to a positive multiplicative factor of mean one.

For z ~ N(0, sigma^2) the expectation of exp(z) is exp(sigma^2/2), which is above one and grows with the spread. Taking it out keeps E[R] = 1 exactly, so widening the noise cannot inflate the annual energy.

onoff_from_latent

onoff_from_latent(latent: ndarray, off_fraction: float, off_level: float) -> np.ndarray

Persistent, cross-correlated on/off masks from Gaussian latent series.

Cutting a correlated Gaussian series at a threshold to make a binary one is called a Gaussian copula. The binary state inherits both the persistence of the latent series and its correlation with the other carriers, with no table of switching probabilities to fit. Cutting at the quantile measured on the series itself makes the off fraction exactly off_fraction.

Giving every carrier the same mask would force their correlation to one, which is the artefact this package exists to avoid.

cap_to_rated_capacity

cap_to_rated_capacity(profile: ndarray, target_load_factor: float, max_iterations: int = 2000, tolerance: float = 1e-12) -> np.ndarray

Impose a rated capacity while preserving annual energy.

A plant cannot draw more than it has installed, so its load duration curve has a hard ceiling; a lognormal tail has none. Capping lowers the mean, which lowers the cap, so cap and rescale are alternated:

P~ = min(P, mean(P)/eta);   P <- P~ * E / sum(P~)

The map is a contraction: each pass shrinks the excess over the cap by about the share of steps held at the cap. A shipped class holds 1-2 % of its hours there and converges in a few passes; a tight rating can hold a third of them, and needs a few dozen. It runs until the peak is within tolerance of the cap. At the fixed point the load factor is eta and the energy is E, both exactly. This is what makes the extreme quantiles right: the coefficient of variation can be correct while the top of the load duration curve is badly wrong.

residual_cv_for

residual_cv_for(target_cv: float, shape: ndarray) -> float

Residual spread that lands the finished profile on target_cv.

Shape and residual are independent with the residual at mean one, so

1 + CV_total^2 = (1 + CV_shape^2) * (1 + CV_residual^2)

Variances do not add here -- one plus the squared coefficient of variation multiplies. Fitting the residual directly on a measured series and then multiplying the calendar back in double-counts the calendar's own spread.

step_hours

step_hours(index: DatetimeIndex) -> float

Length of one step, in hours, inferred from the index.

Everything resolution-dependent is derived from this rather than assumed, so the same spec can be rendered hourly or quarter-hourly.

rescale_persistence

rescale_persistence(phi_hourly: float, hours_per_step: float) -> float

Convert an hourly AR(1) coefficient to one for a step of another length.

Persistence is a property of time, not of the sampling grid. An AR(1) autocorrelation decays as phi^k over k steps, so a series sampled every h hours must use

phi_step = phi_hourly ** h

to keep the same correlation at the same wall-clock separation. Without this a quarter-hourly profile would carry four times the memory in real time, and its excursions would last four times as long as the site it was calibrated on.

matched_load_factor

matched_load_factor(base: ProcessClass, new: ProcessClass, calendar=None) -> float

The load factor whose cap clips as many hours on new as on base.

A shipped class's cap holds 1-2 % of its hours at the peak. Changing the calendar or the on/off state changes the uncapped profile, and so the cap that clips that same share: on one uncapped reference year of each, with p the share the base's cap holds,

c   = the (1 - p) quantile of the new uncapped profile P
eta = mean(min(P, c)) / c

which is a fixed point of the cap iteration. calendar puts the new class on another calendar, as a carrier given its own.

A base with no fluctuation beyond its calendar and on/off state gives a step function, which no cap can clip by a small share, and whose own load factor (mean over peak) moves by a few per cent with where the stops fall. The new class then takes 1 % above the highest such load factor over eight reference years and four carriers: the cap trims the highest step slightly, and is reached in practice whatever the seed.

carrier_load_factors

carrier_load_factors(spec: DemandSpec, total_hours: float = 8760.0) -> dict[str, float]

The load factor each carrier's cap holds.

A rated carrier's load factor is its mean demand over its rating,

eta_m = E_m * 1000 / (T * P_m)

with E_m its annual energy (MWh), T the hours in the year and P_m its rating (kW). A rating at or below the mean demand cannot deliver the annual energy, and raises.

In order, a carrier takes: its rating, if it has one; else the load factor the spec gives it; else, on a calendar of its own, the load factor whose cap clips as many hours on that calendar as the class's cap does on the class's (matched_load_factor); else the class's load factor.

build_profiles

build_profiles(spec: DemandSpec, index: DatetimeIndex, knob: float | None = None, check: bool = True, load_factors: dict[str, float] | None = None) -> pd.DataFrame

Hourly demand in kW for one site, one column per carrier.

Parameters:

Name Type Description Default
spec DemandSpec

What to generate.

required
index DatetimeIndex

Hourly timestamps. A full year is usual but any length works.

required
knob float | None

Correlation between the carriers' latent series, which the generator sets internally. Leave as None to solve for the value that delivers spec.carrier_correlation in the finished profiles; pass a number to use it directly, which is what the solver itself does.

None
check bool

Compare what was delivered with what was asked, and issue a TargetMissedWarning for each miss, with its cause. See loadcast.delivery_report.

True
load_factors dict[str, float] | None

Load factor of each carrier's cap, in place of the ones the spec implies. The correlation solver uses it; leave it as None.

None

generate

generate(spec: DemandSpec | None = None, year: int = 2025, freq: str = 'h', **kwargs) -> pd.DataFrame

Generate one year of demand at the requested resolution.

The convenience entry point. Either pass a DemandSpec, or pass its fields directly as keyword arguments:

generate(annual_mwh=10_000, heat_to_cold=7.4, elec_share=0.2)
generate(annual_mwh=10_000, freq="15min")     # quarter-hourly

freq is any pandas offset alias -- "h", "30min", "15min". The persistence is rescaled so an excursion lasts the same number of hours at any resolution, and the energy is divided by elapsed hours rather than by step count, so the mean power is unchanged.

Whatever it cannot deliver as asked -- a load factor the cap cannot hold, a spread the calendar leaves no room for, a correlation below the floor -- it reports in a TargetMissedWarning that says why. delivery_report gives the full comparison as a table.

Two caveats apply to sub-hourly output. The process classes were calibrated on hourly meters, so their spread and persistence describe hourly behaviour; asking for 15-minute steps draws those hourly statistics on a finer grid rather than adding measured sub-hourly structure. And the calendar resolves to the hour of day, so every step within an hour carries the same calendar factor: all sub-hourly variation comes from the residual.

solve_correlation_knob

solve_correlation_knob(spec: DemandSpec, tolerance: float = 0.005, max_iterations: int = 20, hours_per_step: float = 1.0) -> float

Internal correlation that delivers the requested finished correlation.

The correlation the generator sets, between the carriers' latent series, and the correlation you observe in the finished profiles are different numbers. Carriers share a calendar, so the finished profiles are correlated even when their residuals are independent -- every carrier dips on a Sunday and in July. The floor this imposes is

g(0) = CV_calendar^2 / CV_total^2

which for the shipped process classes runs from 0.08 to 0.64. A carrier given a calendar of its own shares less with the others, and lowers it. No non-negative internal correlation delivers less than the floor; asked for less, the solver returns the value that comes closest, and the generator warns.

Solved by bisection, generating a year at each trial value, and cached. It is solved at zero lag, so carrier_correlation is the peak of the cross-correlogram. A lag sweep then changes timing without also changing how tightly the carriers move together.

Fitting to a measured site

Turning what you can observe into what the generator needs.

This is what separates a demand generator from a random signal generator. A signal generator asks for sigma and phi. Here you supply what a meter, a bill or a datasheet actually tells you --

load factor    mean demand over peak demand
spread         coefficient of variation of the hourly series
persistence    lag-1 autocorrelation, how long an excursion lasts
idle fraction  share of hours the process is effectively off

-- and the generator parameters follow in closed form, with no optimiser and no convergence criterion.

The inversions

For a residual R = exp(z) with z a stationary Gaussian AR(1) of variance sigma^2 and lag-1 coefficient phi:

CV[R]      = sqrt(exp(sigma^2) - 1)
rho_R(1)   = (exp(phi*sigma^2) - 1) / (exp(sigma^2) - 1)

Both invert exactly:

sigma^2 = ln(1 + CV^2)
phi     = ln(1 + rho_R(1)*(exp(sigma^2) - 1)) / sigma^2

More generally a latent correlation rho_z becomes a residual correlation

rho_R = (exp(rho_z * sigma^2) - 1) / (exp(sigma^2) - 1)

of which the lag-1 case above is simply rho_z = phi. The same expression gives the whole cross-correlogram once a lag is in play.

sigma_from_cv

sigma_from_cv(cv: float) -> float

Log-space spread of a lognormal with coefficient of variation cv.

cv_from_sigma

cv_from_sigma(sigma: float) -> float

Coefficient of variation of exp(z) for z ~ N(0, sigma^2).

phi_from_lag1

phi_from_lag1(lag1: float, sigma: float) -> float

Latent AR(1) coefficient giving an observed lag-1 autocorrelation.

The exponential transform compresses correlations, so the latent needs a higher coefficient than the one you measure on the series itself.

lag1_from_phi

lag1_from_phi(phi: float, sigma: float) -> float

Observed lag-1 autocorrelation of a lognormal AR(1).

residual_correlation

residual_correlation(latent_corr: float, sigma: float) -> float

Correlation of two lognormals from the correlation of their latents.

latent_correlation

latent_correlation(residual_corr: float, sigma: float) -> float

Inverse of residual_correlation.

combine_cv

combine_cv(calendar_cv: float, residual_cv: float) -> float

Total spread from calendar and residual spreads.

1 + CV_total^2 = (1 + CV_calendar^2)(1 + CV_residual^2)

split_cv

split_cv(total_cv: float, calendar_cv: float) -> float

Residual spread needed to reach total_cv given the calendar's own.

correlation_transfer

correlation_transfer(latent_corr: float, calendar_cv: float, residual_cv: float, sigma: float | None = None) -> float

Correlation of the finished profiles, from the internal correlation.

latent_corr is the correlation between the carriers' latent series, which the generator sets.

With P_m = L_m * S * R_m sharing one calendar S, writing q = rho_R * CV_R^2:

               CV_S^2 + q + CV_S^2 * q
corr(P_h, P_c) = -----------------------
                        CV_total^2

It matches simulation to three decimals across the range of latent_corr. It is exact without the on/off state and the capacity cap; both shift it, so the generator solves for the internal correlation numerically and uses this formula to explain and diagnose.

correlation_floor

correlation_floor(process_class: str | ProcessClass | DemandSpec, index=None) -> float

Lowest cross-carrier correlation reachable with independent residuals.

g(0) = CV_calendar^2 / CV_total^2

The floor is the share of a profile's total variance that the shared calendar contributes. It is a statement about industry: a high floor means the carriers move together mainly because the factory is open or shut, not because the processes are linked.

No non-negative internal correlation delivers a correlation below this floor. Pass a class (or its name) for the formula above, which assumes every carrier follows the class's calendar. Pass a DemandSpec for the floor of that site, measured on a generated year: a carrier with a calendar of its own, or a cap of its own, shifts it.

bias_report

bias_report(process_class: str | None = None, seeds: int = 4) -> 'pd.DataFrame'

Target statistics against what the generator actually delivers.

Load factor and annual energy are imposed and come out exact. Spread and persistence are not imposed -- they follow from parameters chosen to produce them -- so they land near their targets rather than on them, and this reports how near, averaged over seeds draws. The offset is systematic rather than random, and its sign depends on the class. Without an on/off state, persistence comes out above target, because the capacity cap trims the peaks that would otherwise break up a run; with one, it comes out below, because the on/off state chops runs into pieces.

The gap is reported rather than tuned away: a further parameter fitted to close it would be over-fitting, not calibration.

class_from_observations

class_from_observations(name: str, load_factor: float, cv: float, lag1: float, calendar_from: str = 'continuous', off_fraction: float = 0.0, off_level: float = 0.02, description: str = '', calendar: Calendar | None = None) -> ProcessClass

A process class fitted to statistics you measured yourself.

Supply the numbers a meter gives you and get a class the generator can use. The calendar is your own if you pass one -- from your schedule, your meter or your monthly bills, see loadcast.Calendar -- and is otherwise borrowed from the shipped class named by calendar_from. To change only some of a shipped class's numbers, use custom_class instead.

.. warning::

Feed it measurements, never generated output. The generator misses its persistence target by a systematic amount (see bias_report). That offset does no harm once, but it compounds if you measure a generated profile and feed the result back in. Doing so repeatedly from semi_continuous drives the lag-1 autocorrelation 0.79 -> 0.86 -> 0.91 -> 0.94 -> ... up to a fixed point near 0.97, while the spread bleeds down from 0.48 to 0.42: the profile grows smoother and stickier each round until it has lost the high-frequency variability it was supposed to have.

This is the classic degeneration of any model retrained on its own output, and the package never does it -- the shipped classes hold constants measured once, and no code path writes generated statistics back into a class. It is only reachable if a caller builds that loop deliberately.

Parameters:

Name Type Description Default
name str

Name to register the class under, and to pass as process_class.

required
load_factor float

Mean demand over peak demand, in (0, 1).

required
cv float

Coefficient of variation of the hourly series: standard deviation over mean.

required
lag1 float

Lag-1 autocorrelation of the hourly series: its correlation with itself one hour later.

required
calendar_from str

Shipped class whose calendar (month, weekday and hour factors) to borrow when calendar is not given.

'continuous'
off_fraction float

Share of hours the process is off. Leave at zero unless the process runs or stops: spread alone cannot make a profile off rather than merely low, and an on/off state fitted to a process that does not stop overstates its idle time.

0.0
off_level float

Load while off, as a fraction of the running level.

0.02
description str

Free text kept with the class.

''
calendar Calendar | None

Your own loadcast.Calendar. Measured statistics and a calendar must come from the same site: the spread includes the calendar's, and must be larger than it.

None

custom_class

custom_class(base: str | ProcessClass = 'semi_continuous', *, name: str | None = None, calendar: Calendar | None = None, load_factor: float | None = None, cv: float | None = None, lag1: float | None = None, off_fraction: float | None = None, off_level: float | None = None, description: str | None = None) -> ProcessClass

A shipped class with any of its numbers changed.

Start from the class closest to your site, which is calibrated on a metered plant, and change what you know to be different. Everything you leave out is carried over so that the plant behaves as the base class does while it runs:

spread The base's fluctuation within its running hours is kept, and the new calendar's and on/off state's spread added to it, since one plus the squared spread multiplies across independent factors: 1 + cv^2 = (1 + cv_calendar^2)(1 + cv_onoff^2)(1 + cv_fluctuation^2). load factor The cap clips as many hours as the base's does: a shipped class holds 1-2 % of its hours at the peak, and the new class holds the same share on its own calendar and on/off state (see loadcast.generator.matched_load_factor). persistence Unchanged.

So custom_class("semi_continuous", off_fraction=0.3) is the same plant stopping 30 % of the time, and custom_class("semi_continuous", calendar=two_shifts) the same plant on your shifts. Give a number explicitly to override what is derived.

The result needs no registering: pass it as process_class. Register it with register_class only to call it by name.

Parameters:

Name Type Description Default
base str | ProcessClass

Name of a shipped class, or a ProcessClass.

'semi_continuous'
name str | None

Name for the new class; by default the base's with "+custom".

None
calendar Calendar | None

A loadcast.Calendar: from a schedule, a meter or monthly bills.

None
load_factor float | None

Load factor, spread (coefficient of variation, calendar included) and hourly lag-1 autocorrelation of the finished profile.

None
cv float | None

Load factor, spread (coefficient of variation, calendar included) and hourly lag-1 autocorrelation of the finished profile.

None
lag1 float | None

Load factor, spread (coefficient of variation, calendar included) and hourly lag-1 autocorrelation of the finished profile.

None
off_fraction float | None

Share of hours the process is stopped, and its load while stopped relative to running. A base that never stops gets an idle level of 0.02 unless you give one.

None
off_level float | None

Share of hours the process is stopped, and its load while stopped relative to running. A base that never stops gets an idle level of 0.02 unless you give one.

None
description str | None

Free text kept with the class.

None

Process classes

Process classes: how peaky an industrial process is, and on what rhythm.

A process class bundles everything the generator needs that is not specific to one site: the calendar rhythm (month, day-of-week, hour-of-day factors) and the three statistics that describe how the load fluctuates around it (load factor, coefficient of variation, lag-1 autocorrelation), plus an on/off description for processes that stop rather than merely vary.

Each class is calibrated on one metered industrial site. The sites themselves are not distributed -- what ships is the derived statistics and the calendar factors, which are group means and carry no identifying information.

The four classes span the range the archive covers:

continuous       runs around the clock, small excursions
semi_continuous  weekday shift pattern with a weekend trough
campaign         long runs separated by genuine shutdowns
batch            strongly bimodal, most hours near zero

Choose one from the process description of the site you are modelling, not by fitting to an answer you already have. If none fits, loadcast.fitting builds a class from your own observed statistics.

ProcessClass dataclass

ProcessClass(name: str, month: tuple[float, ...], dayofweek: tuple[float, ...], hour: tuple[float, ...], target_load_factor: float, target_cv: float, target_lag1: float, mode: str, off_fraction: float, off_level: float, description: str, anchor_site: str, n_hours: int, week: tuple[float, ...] | None = None)

One calibrated process rhythm.

Attributes:

Name Type Description
name str

Identifier used in DemandSpec.process_class.

month, dayofweek, hour

Calendar factors, each normalised to mean one over a balanced calendar. month is indexed January..December, dayofweek Monday..Sunday, hour 00..23. They carry shape only: the level comes from the spec.

target_load_factor float

Mean over peak of the finished profile. Imposed exactly by the capacity cap, not fitted.

target_cv float

Coefficient of variation of the finished profile, calendar included.

target_lag1 float

Lag-1 autocorrelation of the finished profile.

mode str

"lognormal" for a process that varies continuously, "onoff" for one that stops. The choice is forced by the data: a lognormal with the right spread still puts a batch process's load factor at 0.02 against 0.22 measured, because a lognormal tail is far longer than an on/off process at equal spread.

off_fraction float

Share of hours in the off state. Zero for "lognormal" classes.

off_level float

Load in the off state, as a fraction of the running level. Non-zero because real plants idle rather than stop.

description str

The kind of process this rhythm was measured on.

anchor_site str

Anonymised label of the metered site it was calibrated against.

n_hours int

Length of the series it was calibrated on.

week tuple[float, ...] | None

Optional 168 hour-of-week factors, Monday 00:00 to Sunday 23:00. When given they replace dayofweek times hour, so each day can keep its own hours. Build one with loadcast.Calendar and pass it to loadcast.custom_class.

calendar

calendar(index) -> np.ndarray

Calendar factor S(t) for every timestamp in index.

The three periodic factors multiply. Each has mean one over a balanced calendar, so their product carries shape and no level -- which is what lets the same rhythm be reused at any plant size.

load_classes cached

load_classes() -> dict[str, ProcessClass]

Every calibrated process class shipped with the package.

register_class

register_class(process_class: ProcessClass, overwrite: bool = False) -> None

Make a process class usable by name in a DemandSpec.

Pair this with loadcast.fitting.class_from_observations to generate from statistics you measured yourself:

own = class_from_observations("my_plant", 0.45, 0.6, 0.9)
register_class(own)
generate(process_class="my_plant", annual_mwh=5_000)

available_classes

available_classes(include_registered: bool = True) -> list[str]

Names of the process classes that can be generated from.

get_class

get_class(name: str | ProcessClass) -> ProcessClass

One process class by name, with a helpful error if it does not exist.

A ProcessClass passed in is returned as it is, so a class built with loadcast.custom_class can be used without registering it.

Calendars

The calendar: when a site runs, as factors of mean one.

A calendar is the deterministic part of a profile: the factor S(t) that every hour of demand is multiplied by, before the fluctuation. It holds

month   12 factors, January to December
week    168 factors, Monday 00:00 to Sunday 23:00

and S(t) is the month factor times the hour-of-week factor. Both sets are normalised to mean one, so a calendar carries shape and no level: the level comes from the annual energy.

A full week of 168 factors, rather than a weekday factor times an hour factor, lets each day keep its own hours: a Saturday morning shift, or a night shift on weekdays only. The shipped classes were calibrated as weekday times hour, and Calendar.of writes them out as a week.

Four ways to build one, from what a user is likely to have:

Calendar.of("semi_continuous")          a shipped class's calendar
Calendar.from_schedule([...])           the shifts the site runs
Calendar.from_series(meter)             a metered series, a week or longer
calendar.with_monthly_energy([...])     twelve monthly bills

What a calendar cannot do: the month scales the whole week, so the daily pattern cannot change with the season.

Calendar dataclass

Calendar(month: tuple[float, ...], week: tuple[float, ...])

Month and hour-of-week factors, each normalised to mean one.

Both sets are rescaled to mean one on construction, so any positive numbers in the right proportions will do.

Parameters:

Name Type Description Default
month tuple[float, ...]

Twelve factors, January to December.

required
week tuple[float, ...]

168 factors, Monday 00:00 to Sunday 23:00.

required

factors

factors(index: DatetimeIndex) -> np.ndarray

The calendar factor S(t) for every timestamp of index.

spread

spread(year: int = 2025) -> float

Coefficient of variation of S(t) over an hourly year.

The part of a profile's spread the calendar alone accounts for.

flat classmethod

flat() -> 'Calendar'

The same factor at every hour of the year: a site that never varies.

of classmethod

of(process_class) -> 'Calendar'

The calendar of a process class, shipped or your own.

Takes a class name or a ProcessClass.

from_schedule classmethod

from_schedule(shifts, base_load: float = 0.0, monthly_energy=None, months=None, year: int = 2025) -> 'Calendar'

A calendar from the hours a site runs.

Parameters:

Name Type Description Default
shifts

One entry per block of running hours, as (days, start_h, end_h) or (days, start_h, end_h, level). days is a string such as "Mon-Fri", "Sat", "Mon,Wed" or "daily"; hours run from start_h up to end_h, and a block that ends before it starts runs past midnight into the next day. level is the demand in that block relative to a full shift, 1 by default.

required
base_load float

Demand outside every block, relative to a full shift: what the site draws when it is not producing (space heating, standby, cold rooms kept cold). Read it off a meter at night or at the weekend.

0.0
monthly_energy

Optional twelve monthly energies, as on the bills, to set the month factors; see with_monthly_energy.

None
months

Optional twelve month factors given directly, such as a shipped class's: Calendar.of("semi_continuous").month. A schedule says nothing about seasons, so without either the months are flat.

None
year int

Year whose weekdays the monthly energies are counted on.

2025

Examples:

Two shifts on weekdays, a morning shift on Saturday, a quarter of the load the rest of the time, and the seasons of the shipped semi-continuous class::

Calendar.from_schedule([("Mon-Fri", 6, 22), ("Sat", 6, 14)],
                       base_load=0.25,
                       months=Calendar.of("semi_continuous").month)

from_series classmethod

from_series(series: Series) -> 'Calendar'

The calendar of a metered series.

Month and hour-of-week factors are estimated together, in turn: each month's factor is its energy over the energy its hours would hold at the current week factors, and each of the 168 week factors is the mean of the series at that hour, divided by its month's factor. A few rounds converge, and a season does not leak into the week, nor a month's count of working days into its factor. The month factors need all twelve months, and are left flat when the series is shorter; add them from monthly bills with with_monthly_energy.

Sub-hourly series are averaged to hours first. It needs at least one full week.

with_monthly_energy

with_monthly_energy(energies, year: int = 2025) -> 'Calendar'

Set the month factors from twelve monthly energies, such as bills.

A month's energy depends on its activity and on how many running hours it holds: a month with five Mondays holds more. Each month factor is therefore its energy divided by the sum of the week factors over that month's hours, counted on year. A month the site was shut has an energy near zero, and gets a factor near zero.

with_months

with_months(factors) -> 'Calendar'

The same week, with twelve month factors given directly.

describe

describe() -> pd.DataFrame

The week as a 7 x 24 table, days down and hours across.

What was delivered against what was asked

What was asked, what was delivered, and why the two differ.

Some statistics are imposed and come out exact: the annual energy, the composition and, while the cap is reached, the load factor. Others are aimed at: the spread and the persistence follow from parameters chosen to produce them, and the cap and the on/off state act afterwards, so they land near their targets. A miss is reported when an exact statistic is not met, or when an aimed one lands further off than the generator's usual error:

spread (cv)     more than 25 % from its aim
persistence     more than 0.2 from its aim, in hourly terms
correlation     more than 0.03 from the request

The shipped classes, at their defaults, stay within these bands; their usual gaps are listed by loadcast.bias_report.

Every miss names its cause. generate issues a TargetMissedWarning for each; in a sweep, silence them and read delivery_report instead:

import warnings
warnings.simplefilter("ignore", loadcast.TargetMissedWarning)

TargetMissedWarning

Bases: UserWarning

A statistic came out other than asked. The message says why.

delivery_report

delivery_report(spec: DemandSpec, profiles: DataFrame) -> pd.DataFrame

Each requested statistic against what the profiles deliver, and why.

One row per carrier and statistic, with the columns

kind        exact, ceiling, aimed at, or default
requested   what the spec and its class ask for
delivered   what the profiles have
status      ok, missed, or not checked
why         the cause of a miss, and what to change

The spread and persistence asked of a carrier are the class's, or, for a carrier with a calendar of its own, the class's fluctuation on that calendar.

warn_misses

warn_misses(spec: DemandSpec, profiles: DataFrame) -> pd.DataFrame

Issue a TargetMissedWarning for each miss in delivery_report.

Reference data

Indicative starting values, from peer-reviewed sources, with their caveats.

Nothing here predicts your site. These are published aggregates, reported with what is wrong with them so that they do not become assumptions unnoticed. The documentation's page "Choosing inputs" shows how to use them.

Four sources, each used only for what it resolves:

============ ========================================== ==================== source used for lacks ============ ========================================== ==================== JERICHO the only three-carrier split that exists sector detail Rehfeldt heating and cooling by temperature band, electricity 7 UK subsectors, two datasets Naegler heat by temperature level, 13 branches cooling, electricity TNO / Marina process and waste heat temperatures electricity, cooling ============ ========================================== ====================

Energy basis

generate takes delivered energy: the heat and cold the process receives, and the electricity it uses for everything else. JERICHO reports useful energy, which is that basis. Rehfeldt reports final energy: the fuel burnt for heat and the electricity that drives the chillers. Its heat:cold is therefore not the ratio generate takes; convert it first,

delivered heat:cold = final heat:cold * boiler efficiency / chiller COP

which at an efficiency of 0.9 and a COP of 3 divides it by about 3.3.

Why JERICHO is used here and nowhere near a time series

JERICHO is the one peer-reviewed source giving heat, cooling and electricity as useful energy, which is exactly what a three-carrier composition needs. Its annual totals are what it was built to produce and are used for that alone.

Its hourly series must not be used, and neither must any spatial variation in it. Both carry the same artefact: every carrier is a fixed scalar times one shared profile. In time that makes the correlation between any two carriers 1.000000 to six decimals. In space it makes the composition identical across all 38 NUTS2 regions to four parts in 100 million -- while the regions' scale varies by a factor of 17.9. So the dataset contains exactly one composition, repeated, and reporting it as 38 regional observations would be reporting one number 38 times.

Why the subsector ranges are wide

Rehfeldt reports two datasets for the same subsectors, and they disagree by more than some subsectors differ from one another: for chemicals, heat:cold is 6.6 in one and 17.9 in the other, a range that overlaps food's (4.6 to 7.5). That spread is reported rather than averaged away, because a point estimate here would be false precision.

And a warning that matters more than the numbers: branch aggregates cannot place a site. Of three metered food plants, none falls inside the published range for its own branch. On a delivered basis (efficiency 0.9, COP 3) the branch spans 1.4 to 2.2, while the plants sit at 0.33, 7.4 and 44 -- a spread of a factor of 135 within the branch, against 1.6 for the branch range. Use these to start a sweep, never to finish one.

sources

sources() -> 'pd.DataFrame'

Every source behind this module, with scope and what is wrong with it.

citation

citation(source: str) -> str

Full citation for one source.

industry_composition

industry_composition() -> dict[str, float]

Industry-wide useful-energy split, from JERICHO.

German industry, 2019. One composition for all of industry -- the dataset resolves no sector or regional variation, so this is a single anchor point and not a distribution. Useful energy is the delivered basis generate takes, so these shares can be passed to it as they are.

subsectors

subsectors() -> list[str]

Subsectors with Rehfeldt's heating and cooling shares.

heat_to_cold_range

heat_to_cold_range(subsector: str) -> tuple[float | None, float | None]

Low and high heat:cold for a subsector, across Rehfeldt's two datasets.

Final energy, not the delivered ratio generate takes. The heat is the fuel burnt for it and the cold the electricity that drives the chillers. Convert before generating::

delivered = final * boiler_efficiency / chiller_cop

The ratio counts space heating as heat, as Rehfeldt does.

None as the high value means at least one dataset reports no cooling for the subsector, so the ratio is unbounded above; (None, None) means neither does -- a site with no cooling demand, for which heat_to_cold=None is the right spec.

temperature_bands

temperature_bands(source: str = 'naegler') -> 'pd.DataFrame'

Shares of heat (and, for Rehfeldt, cooling) by temperature band, in %.

"naegler": heat in German industry, 2006, by branch -- space heat and hot water, then process heat below 100, 100-500, 500-1000 and above 1000 C. The finer bands, with no cooling.

"rehfeldt": heating and cooling in UK industry, by subsector, in two datasets (ECUK and FORECAST) kept apart -- cooling, space heating, then heat below 200, 200-500 and above 500 C. Final energy. ECUK's bands are end-use categories (low temperature, drying and separation, high temperature) that Rehfeldt maps onto these temperatures.

Both are digitised from stacked-bar figures, to about +-1 percentage point. Each row sums to 100. Like sector_temperatures, these inform a choice the generator does not make: which temperature a machine must reach to serve a given share of a branch's heat.

sector_temperatures

sector_temperatures(sector: str | None = None)

Process and waste heat temperatures per sector, from the TNO dataset.

Indicative, and energy-weighted: the median is the temperature that splits a sector's heat in half by energy, not by stream count.

These inform a choice the generator does not make. loadcast carries energy by carrier and no temperature at all -- whether a machine can reach a process, or usefully lift a waste stream, is answered from the machine's own limits against numbers like these.

waste_to_heat

waste_to_heat(sector: str) -> float

Indicative waste heat rejected per unit of process heat, 15-200 C.

Feeds DemandSpec.waste_to_heat. From the TNO dataset's own sector totals, so it counts only streams inside 15-200 C -- the range that dataset was built to cover.

reference_table

reference_table() -> 'pd.DataFrame'

Everything indicative, in one table, labelled by provenance.

Read the heat_to_cold_low/high columns as the width of published disagreement, not as an uncertainty band around a true value -- and as final energy, to be converted before it is passed to generate.

Statistics

Diagnostics: what a generated profile actually turned out to be.

Four views, which between them cover what sizing equipment needs:

profile_statistics   the four statistics the generator was asked for
duration_curve       the load duration curve, sorted from the highest hour
cross_correlogram    how the carriers line up, offset by offset
integrated_drift     how far apart they drift over a storage window

The last two describe how the carriers relate, which the generator lets you set.

Offsets, windows and energies are in hours at any step length. Each function reads the length of a step from the series' DatetimeIndex, as the generator writes it; for a bare array, pass hours_per_step (one hour if omitted).

profile_statistics

profile_statistics(series: Series | ndarray, hours_per_step: float | None = None) -> dict[str, float]

Load factor, spread, persistence and idle fraction of one profile.

lag1 is the correlation of the series with itself one step later, as the generator's persistence is defined per step; on a series of 15-minute steps, raise it to the power 4 for the value one hour later. annual_mwh is power times elapsed hours, so it is right at any step length.

duration_curve

duration_curve(series: Series | ndarray, normalise: bool = True) -> np.ndarray

Load duration curve: demand sorted from the highest hour to the lowest.

It is often the only thing an industrial site can supply about itself, and it shows the load factor, the peak and the idle fraction at once, which makes it the right thing to compare against.

cross_correlogram

cross_correlogram(first: Series | ndarray, second: Series | ndarray, max_lag: float = 48, hours_per_step: float | None = None) -> pd.DataFrame

Correlation between two carriers at each offset, in hours.

corr(first(t), second(t + lag)) for every whole step from -max_lag to max_lag hours, so a peak at a positive lag means second trails first. The lag_h column is in hours at any step length: a 15-minute series gives a row every 0.25 h.

Read the position of the peak, not only its height. At zero offset, a lag and a weak coupling look the same: as carriers are offset, their correlation at zero offset falls towards the floor the shared calendar imposes, which is exactly where a small correlation would also put it. Only the correlogram separates the two.

integrated_drift

integrated_drift(first: Series | ndarray, second: Series | ndarray, window_h: float = 24, hours_per_step: float | None = None) -> float

Mean absolute drift between two carriers over a storage window.

Each carrier is divided by its own mean, so this measures a mismatch in timing, not in size:

D(t) = sum over the window of [ a(s)/mean(a) - b(s)/mean(b) ] * h

where h is the length of a step in hours, and the result is the mean of |D(t)|, in hours of mean demand. A store does not see a mismatch hour by hour, it accumulates it, so what sizes a store is the mismatch summed over its window rather than the gap in one hour. The correlation is a single point of that picture, the value at zero offset, and is blind to how long an excursion lasts. Two carrier pairs with the same correlation can differ severalfold here.

window_h is in hours at any step length; it is rounded to whole steps.

summary_table

summary_table(frame: DataFrame) -> pd.DataFrame

profile_statistics for every carrier in a generated frame.

The step length is read from the frame's index, so annual_mwh is right at any resolution.