Skip to main content
Version: Next

ts_shape.datasets

Synthetic timeseries generators for trying out ts-shape.

These helpers produce DataFrames in the standard ts-shape schema (systime, uuid, value_*, is_delta) so any detector, transform, or statistic can be exercised without real data or loaders::

import ts_shape
df = ts_shape.make_timeseries(["sensor:temp"], n_outliers=4)
ts_shape.OutlierDetectionEvents(df, value_column="value_double") \
.detect_outliers_zscore()
Functions
NameDescription
make_timeseriesGenerate a standard-schema synthetic timeseries DataFrame.
make_id_signalGenerate a categorical identifier signal in the standard schema.
make_object_signalsGenerate a labelled benchmark of object-identifier signals.
make_plc_cyclesSimulate the raw signals of one cyclic machine PLC, with ground truth.
make_line_stopsSimulate a continuous line (no machine cycle) that stops now and then.
make_control_loopsSimulate PI control loops with setpoint steps, and look-alike signals.

make_timeseries​

functionsource
make_timeseries(
uuids: str | Sequence[str] = ("sensor:signal",),
*,
n_points: int = 1000,
freq: str = "30s",
start: str = "2025-01-01 00:00:00",
baseline: float = 100.0,
noise: float = 1.0,
drift: float = 0.0,
n_outliers: int = 0,
value_column: str = "value_double",
seed: int | None = 42
) -> pd.DataFrame

Generate a standard-schema synthetic timeseries DataFrame.

Parameters
NameTypeDescriptionDefault
uuidsstr | Sequence[str]Signal identifiers (or a single one as a string); one block of n_points rows per uuid. An empty list gives an empty frame with the standard columns.('sensor:signal',)
n_pointsintNumber of samples generated per uuid.1000
freqstrPandas offset alias for the sampling interval (e.g. "30s").'30s'
startstrTimestamp of the first sample.'2025-01-01 00:00:00'
baselinefloatMean level of the generated signal.100.0
noisefloatStandard deviation of the Gaussian noise added to the signal.1.0
driftfloatTotal linear drift applied across the series (tool-wear style).0.0
n_outliersintNumber of large spike outliers injected per uuid. Spikes are 12 * noise high, so with noise=0 none are visible (a :class:~ts_shape.errors.DataQualityWarning says so).0
value_columnstrWhich value column to populate -- one of value_double, value_integer or value_bool.'value_double'
seedint | NoneSeed for reproducibility; pass None for fresh randomness.42
Returns
TypeDescription
DataFrameDataFrame with columns systime, uuid, value_bool,
DataFramevalue_integer, value_double, value_string and is_delta.
DataFrameThe populated column is float64 / int64 / bool; the unused
DataFrameones are missing, as boolean, Int64, float64 and
DataFrameobject.
Raises
TypeDescription
ValueErrorIf value_column is not a supported value column, or n_points is not positive.

make_id_signal​

functionsource
make_id_signal(
uuid: str = "object:id",
values: Sequence[str] = ("A", "B", "C"),
*,
hold: int = 10,
freq: str = "30s",
start: str = "2025-01-01 00:00:00",
value_column: str = "value_string",
source_uuid: str | None = None
) -> pd.DataFrame

Generate a categorical identifier signal in the standard schema.

Each value in values is held for hold consecutive samples, so the signal looks like a real batch / serial / coil / recipe id stream that changes over time. Feed it to :mod:ts_shape.eventlog.objects to extract object instances.

Parameters
NameTypeDescriptionDefault
uuidstrSignal identifier.'object:id'
valuesSequence[str]Ordered id values; each held for hold samples.('A', 'B', 'C')
holdintSamples each value persists before the next one starts.10
freqstrPandas offset alias for the sampling interval.'30s'
startstrTimestamp of the first sample.'2025-01-01 00:00:00'
value_columnstrWhich column carries the id (value_string or value_integer).'value_string'
source_uuidstr | NoneOptional source_uuid to stamp on every row.None
Returns
TypeDescription
DataFrameDataFrame with the standard ts-shape columns, value_column filled.
Raises
TypeDescription
ValueErrorFor an unsupported value_column, hold <= 0, or value_column="value_integer" with ids that are not whole numbers.

make_object_signals​

functionsource
make_object_signals(
*,
seed: int = 0,
days: float = 3,
include: Iterable[str] | None = None,
noise: bool = True
) -> tuple[pd.DataFrame, pd.DataFrame]

Generate a labelled benchmark of object-identifier signals.

Simulates one or two production lines and the plant around them (work orders with setups, stops and cycles; batches inside the material; one serial per cycle with a companion part counter; carriers circulating in a loop; operators logging in at the 06:00 / 14:00 / 22:00 shift changes; orders, customers and suppliers stamped at shipping and goods receipt; SSCC-labelled boxes put away into storage bins) and samples every signal the way a historian stores it: on change, with keep-alive re-sends, or periodically, with gaps. Identifiers use real formats (SAP numbers, GTIN-13/14 and SSCC with check digits, GS1 application identifiers, EPC GRAI-96 hex, UUIDs, date-coded batches); several formats per object type are drawn per seed. Negative controls (states, alarm texts, measurements, counters, timestamps, constants, plus hard cases such as a 1/2/3 mode code) are mixed in.

The uuids are opaque ("sig:0007") and shuffled, so only the values and their behaviour over time tell what a signal carries.

Seeds 0-4 are the dev split; seeds 100-119 the held-out split (ts_shape._object_signals.DEV_SEEDS / HELDOUT_SEEDS). Seeds from 100 on also draw formats that dev seeds never use, plus wider and differently shaped hold-time distributions; the variant label names the format.

Parameters
NameTypeDescriptionDefault
seedintSeed of the whole simulation; the output is deterministic per seed.0
daysfloatLength of the recording in days.3
includeIterable[str] | NoneObject types ("batch"), roles ("state") or negative kinds ("alarm_text") to keep; None keeps every signal.None
noiseboolAdd realistic read noise: missing readings, empty strings, garbage reads ("NOREAD", truncated ids, 65535), lower-case and stripped leading zeros, and extra per-signal gaps.True
Returns
NameTypeDescription
DataFrame(frame, labels). frame is the long-format frame with the
DataFramestandard columns. labels has one row per uuid with uuid,
tuple[DataFrame, DataFrame]role (identifier, state, free_text, measurement, counter,
tuple[DataFrame, DataFrame]timestamp or constant), object_type (None unless an
tuple[DataFrame, DataFrame]identifier), value_column, parent_uuid (the signal it nests
intuple[DataFrame, DataFrame]batch in material, serial in batch; else None) and
tuple[DataFrame, DataFrame]variant (the format or negative kind).
Raises
TypeDescription
ValueErrorIf days is not positive or include names an unknown object type or role.
Example
>>> import ts_shape
>>> frame, labels = ts_shape.make_object_signals(seed=0, days=1)
>>> sorted(labels["role"].unique())
['constant', 'counter', 'free_text', 'identifier', 'measurement',
'state', 'timestamp']
>>> batch = labels.loc[labels["object_type"] == "batch"].iloc[0]
>>> labels.set_index("uuid").loc[batch["parent_uuid"], "object_type"]
'material'

make_plc_cycles​

functionsource
make_plc_cycles(
*,
n_cycles: int = 300,
seed: int = 0,
start: str | pd.Timestamp = "2026-01-05 06:00:00",
articles: Sequence[str] = ("A", "B"),
article_block: int = 60,
retry_probability: float = 0.06,
abort_probability: float = 0.02,
pause_every: int = 100,
pause_minutes: float = 15.0,
sample_period: str = "1s",
heartbeat: bool = True,
prefix: str = "plc",
parts_per_cycle: int = 1,
reported_cycle_time: bool = False,
alt_sequence_probability: float = 0.0,
shape_fault_probability: float = 0.0,
parallel_lane: bool = False,
poll_period: str | None = None,
stop_causes: int = 0,
stop_probability: float = 0.0,
changeover_steps: bool = False,
rampup_cycles: int = 0,
handshake_partner: bool = False,
order_size: int = 0,
scrap_probability: float = 0.0,
setting_changes: Sequence[tuple[int, float]] = (),
energy: bool = False,
curve_faults: dict[str, float] | None = None
) -> tuple[pd.DataFrame, pd.DataFrame]

Simulate the raw signals of one cyclic machine PLC, with ground truth.

A step chain 10 .. 80 (about 45 s per cycle) drives the signals a historian records for such a machine, with no mapping or naming convention a profiler could rely on:

====================== ===================================================== <prefix>:step step chain (value_integer, one row per change) <prefix>:clamp_closed handshake, True from step 20 to step 70 <prefix>:robot_ready handshake, True in step 30 <prefix>:camera_done pulse at the end of each camera inspection <prefix>:camera_nok pulse when the camera rejects (then re-inspects) <prefix>:part_counter part counter, +1 in step 80 (the cycle boundary) <prefix>:article article (value_string), changes in blocks <prefix>:pressure analog clamp pressure, sampled every sample_period <prefix>:heartbeat alive bit toggling every sample_period ====================== =====================================================

Injected disturbances (the ground truth a cycle profiler should find): camera NOK with one or two re-inspections (+12 s each: long cycles), aborted cycles that skip steps 40-70 (short cycles), breaks of about pause_minutes waiting in step 10 (pauses), every second article 6 s slower in step 40 (a variant) and a conveyor wait of 2.5 s in 40 % of the cycles in step 60 (a bimodal segment).

Parameters
NameTypeDescriptionDefault
n_cyclesintNumber of complete cycles (counter increment to increment).300
seedintRandom seed; the output is deterministic per seed.0
startstr | TimestampTimestamp of the first row.'2026-01-05 06:00:00'
articlesSequence[str]Article names, produced in blocks of article_block.('A', 'B')
article_blockintCycles per article block.60
retry_probabilityfloatShare of cycles with a camera NOK.0.06
abort_probabilityfloatShare of the other cycles that are aborted.0.02
pause_everyintA break every this many cycles (0: none).100
pause_minutesfloatTypical length of a break.15.0
sample_periodstrSample period of the pressure and the heartbeat.'1s'
heartbeatboolWhether to add the heartbeat signal.True
prefixstrPrefix of the signal uuids.'plc'
parts_per_cycleintParts counted per cycle (the counter's step).1
reported_cycle_timeboolAdd <prefix>:last_cycle_time, the duration of the cycle just ended, published 1 s after the cycle boundary (as many controllers do).False
alt_sequence_probabilityfloatShare of cycles that run step 60 before the camera step 50 (an alternative route).0.0
shape_fault_probabilityfloatShare of cycles whose clamp pressure only reaches 130 instead of 180 bar (a curve-shape fault).0.0
parallel_laneboolAdd a second, independent machine on the same controller (<prefix>:lane2_counter, <prefix>:lane2_clamp) at 1/1.13 of the cycle rate, so its phase drifts.False
poll_periodstr | NoneRead every signal at this fixed poll ("13s"), as a polling OPC UA client does; None (default) keeps the change-encoded rows.None
stop_causesintNumber of stop causes (0-4) injected at the start of a cycle with stop_probability: a jam (alarm_1 rises just before, about 2 min), material low (alarm_2, about 5 min), a manual fix (mode 2 and door_open held, about 3 min) and an unknown cause that leaves no trace (about 1.5 min).0
stop_probabilityfloatShare of cycles that start with a stop.0.0
changeover_stepsboolAt an article change, run a changeover in step 10 of the first new cycle: setup_mode held, unlock_tool and lock_tool pulses and a new fixture_id; in about 30 % of the changeovers the fixture is prepared while the old article still runs (an external step).False
rampup_cyclesintAfter a pause, stop or changeover, this many cycles run step 40 slower (up to +60 %), and mold_temp (sampled) cools during the stop and heats up again.0
handshake_partnerboolRun a four-phase handshake with the conveyor in step 60 (req_conveyor / ack_conveyor); the acknowledge delay includes the conveyor wait.False
order_sizeintCycles per production order (order_no, text; 0: no order signal).0
scrap_probabilityfloatShare of bad parts: good_counter and bad_counter add up to the part counter; the rate is 5x in a ramp-up, 10x on a curve fault and 3x after an alarm stop.0.0
setting_changesSequence[tuple[int, float]](cycle, percent) changes of a held speed_override (100 at the start); step 40 runs at 100/percent of its duration.()
energyboolAdd energy_kwh, a cumulative meter (30 kW while producing, 4 kW in stops).False
curve_faultsdict[str, float] | None{fault: probability} pressure-curve faults: low_plateau (130 instead of 180 bar), late_rise (+2 s), spike_in_hold (260 bar for 1 s).None

The optional disturbances draw random numbers only when enabled, so the default data do not change.

Returns
TypeDescription
DataFrame(frame, truth). frame is the long-format frame with the
DataFramestandard columns. truth has one row per cycle: start,
tuple[DataFrame, DataFrame]end, duration_seconds, kind (normal, long,
tuple[DataFrame, DataFrame]short or pause), article, retry_count,
tuple[DataFrame, DataFrame]pause_seconds, parts, sequence (standard /
tuple[DataFrame, DataFrame]swapped) and shape_fault; with the options above also
tuple[DataFrame, DataFrame]stop_cause, stop_seconds, changeover_seconds, startup,
tuple[DataFrame, DataFrame]nok, order_id, setting_value, curve_fault and
tuple[DataFrame, DataFrame]handshake_wait_seconds.
Raises
TypeDescription
ValueErrorIf n_cycles is below 1, articles is empty or sample_period is not positive.
Example
>>> import ts_shape
>>> frame, truth = ts_shape.make_plc_cycles(n_cycles=120, seed=1)
>>> frame["uuid"].nunique(), "plc:part_counter" in set(frame["uuid"])
(9, True)
>>> truth["kind"].value_counts().sort_index().to_dict()
{'long': 2, 'normal': 113, 'pause': 1, 'short': 4}

make_line_stops​

functionsource
make_line_stops(
*,
duration: str = "48h",
seed: int = 0,
start: str | pd.Timestamp = "2026-01-05 06:00:00",
mean_run_minutes: float = 90.0,
count_period: str = "10s",
prefix: str = "line"
) -> tuple[pd.DataFrame, pd.DataFrame]

Simulate a continuous line (no machine cycle) that stops now and then.

The line counts produced units every count_period while it runs (<prefix>:produced_count) and holds <prefix>:running. It stops after an exponential run time for one of three causes: a web break (<prefix>:alarm_break rises just before, about 12 min), die pressure (<prefix>:alarm_pressure, about 25 min) or an unknown cause without a trace (about 6 min). All signals are logged on change.

Parameters
NameTypeDescriptionDefault
durationstrLength of the recording.'48h'
seedintRandom seed; the output is deterministic per seed.0
startstr | TimestampTimestamp of the first row.'2026-01-05 06:00:00'
mean_run_minutesfloatMean run time between two stops.90.0
count_periodstrThe counter counts one unit per this period.'10s'
prefixstrPrefix of the signal uuids.'line'
Returns
TypeDescription
DataFrame(frame, truth): the long-format frame, and one row per stop with
DataFramestart, end, cause and duration_seconds.
Example
>>> import ts_shape
>>> frame, truth = ts_shape.make_line_stops(duration="24h", seed=1)
>>> sorted(truth["cause"].unique())
['die_pressure', 'unknown', 'web_break']

make_control_loops​

functionsource
make_control_loops(
*,
loops: Sequence[str] = ("good", "oscillating", "sluggish"),
duration: str = "8h",
seed: int = 0,
start: str | pd.Timestamp = "2026-01-05 06:00:00",
sample_period: str = "2s",
mean_step_minutes: float = 20.0,
distractors: bool = True
) -> tuple[pd.DataFrame, pd.DataFrame]

Simulate PI control loops with setpoint steps, and look-alike signals.

Each loop is a first-order plant with dead time under a PI controller tuned good (lambda tuning), oscillating (gain far too high) or sluggish (gain far too low). Loop i writes plc:tic10<i>_sp, _pv and _op (output in %, 0..100). The setpoint steps by 5..20 units after an exponential hold (at least 5 min). With distractors, a held setting nobody follows (plc:line_speed_set), a drifting plc:ambient_temp and a randomly moving plc:bypass_valve are added. All signals are sampled every sample_period.

Parameters
NameTypeDescriptionDefault
loopsSequence[str]Tuning quality of each loop: good, oscillating or sluggish.('good', 'oscillating', 'sluggish')
durationstrLength of the recording.'8h'
seedintRandom seed; the output is deterministic per seed.0
startstr | TimestampTimestamp of the first row.'2026-01-05 06:00:00'
sample_periodstrSampling period of every signal.'2s'
mean_step_minutesfloatMean hold of a setpoint (plus 5 min).20.0
distractorsboolAdd the look-alike signals.True
Returns
TypeDescription
DataFrame(frame, truth): the long-format frame, and one row per loop
DataFramewith loop, quality, setpoint_uuid, actual_uuid,
tuple[DataFrame, DataFrame]output_uuid, kp, ti_seconds, plant_gain,
tuple[DataFrame, DataFrame]plant_tau_seconds, dead_time_seconds and step_count.
Example
>>> import ts_shape
>>> frame, truth = ts_shape.make_control_loops(duration="1h", seed=1)
>>> list(truth["quality"])
['good', 'oscillating', 'sluggish']