Sources and adapters¶
sequential_analysis.sources
¶
Sources and adapters: everything that produces Observations.
A live instrument, a file of historical data, a replay log and a simulator
all look the same from the run's side. A real adapter (DICOM, OPC UA,
MQTT, a database cursor) is a function or generator that yields
Observation values bound to a logical input.
ObservationLog
¶
The delivered history of a run: every observation delivery passed on, in order.
Replaying the log through the same delivery policy and topology
reproduces the run. The log holds what was delivered, not every
arrival: duplicates that delivery dropped and observations it still
holds back (the sequence policy) are not in it, so that the log
position and the source positions in a checkpoint describe the same
cut. Invalid values are logged as they were, and a replay skips them
as the run did; an observation delivery cannot handle at all (see
sequential_analysis.core.envelope_problem) is never delivered, so never logged.
With a path, lines are appended as JSON; without one, the log lives in
memory.
The log has a position -- number of records, byte offset and a hash chain over the records -- that a run stores in its checkpoint. Restoring the checkpoint restores the log to that position: the prefix is verified against the hash chain, and records written after the checkpoint are deleted. Only their number is kept, in the provenance. Relative paths are resolved when the log is created.
The file stays open between records; sync chooses between "flush"
(survives a crash of the process) and "fsync" (survives a power
failure), see sequential_analysis.files. Whatever the mode, the log is forced
to the disk whenever a checkpoint records its position. Close the
log, or use it as a context manager, when the run is over.
sequential_analysis does not keep observations beyond the last checkpoint. After a
restore, the run receives them again from its sources (see skip_to).
A source that cannot deliver past observations again -- a live
instrument without a buffer, a stream without retention -- has to be
buffered by the application, between the source and the run.
state()
¶
Durable position of the log, stored in the run checkpoint.
verify(state)
¶
Check that the log starts with the checkpointed records; return how many follow them.
Raises IncompatibleCheckpoint otherwise. Changes nothing.
restore(state)
¶
Return the log to a checkpointed position.
Raises IncompatibleCheckpoint, and changes nothing, if the log does not start with the checkpointed records. Otherwise deletes the records written after the checkpoint and returns how many there were.
from_values(input, values, *, source='', start=0, times=None, keys=None)
¶
Bind a sequence of values to a logical input, numbering them from start.
from_csv(path, input, value, *, convert=float, source='', seq=None, time=None, key=None, start=0)
¶
Read observations of one logical input from a CSV file with a header row.
value names the column that holds the observation. CSV holds text,
so every value is converted explicitly with convert (float by
default; int for counts); a value that does not convert raises
ValueError naming the line, instead of reaching the procedure as a
string. seq, time and key name optional columns; without seq
rows are numbered from start in file order.
gaussian(input, mean, sd, *, seed, n=None, source='')
¶
A simulator. Uses simulation randomness, a stream separate from any procedure's R_t.
interleave(*sources)
¶
Round-robin over pull sources until all are exhausted.
merge_ordered(*sources)
¶
Deterministic total order over time-ordered sources: (time, source, seq).
skip_to(source, positions)
¶
Seek: drop what a restored run has already consumed, according to its source checkpoint.
Pass the run's Delivery (run.delivery): it also knows the sources it
has not seen yet (they start at its start number) and, under the
arrival policy, the observations delivered ahead of a gap. A bare
mapping of positions only knows the next sequence number per source.
Observations without a sequence number cannot be recognised and are always passed on. Under the arrival policy without deduplication, a sequence number delivered before the checkpoint and sent again after it is taken for the replayed original and skipped.
as_async(source, delay=0.0)
async
¶
Turn a pull source into a push producer, optionally with (random) delays.
replay(log)
¶
Replay a recorded delivered history (an ObservationLog or a path to one).
sequential_analysis.adapters
¶
Adapters to data frames, SQL databases and Kafka.
Each adapter turns rows or messages into Observations; none imports the library it talks to, so pandas, polars, a database driver or a Kafka client are needed only by the caller who has them.
A row may carry several logical inputs (an A/B log: arm, outcome,
covariate). inputs maps column (or field) names to input names; each
row yields one Observation per mapped column, all with the row's sequence
number, key and time, so KeyJoin or PositionalPair puts them back
together. Missing values (None, NaN) are not emitted unless
missing="keep"; pass the run's Delivery as delivery and the sequence
number of a skipped value is declared absent (Delivery.skip_range), so
that the arrival policy does not wait for it.
Resuming after a checkpoint: a restored run knows, per source, the next
sequence number it expects (run.delivery.positions()). With
seq naming an increasing column, ask the database for the rows from
there on (see next_position) -- nothing is read twice; reading too
much is harmless, as the delivery drops what it has already seen. For
Kafka, kafka_offsets gives the offset to seek each partition to.
Cost (measured as in PERFORMANCE.md): one Observation per mapped column and row, 1.4 µs per value from pandas, 1.9 µs from sqlite3, 2.3 µs from Kafka messages including JSON decoding -- comparable to the cheapest procedures' step, small next to the others.
from_dataframe(frame, inputs, *, seq=None, key=None, time=None, source='', start=0, missing='skip', delivery=None)
¶
Observations from a pandas or polars DataFrame, row by row.
inputs maps column names to input names (a list or a single name maps
a column to the input of the same name). Without seq rows are
numbered from start in frame order. Timestamps become seconds since
the epoch; numpy scalars become Python numbers.
from_sql(connection, query, parameters=(), *, inputs, seq=None, key=None, time=None, source='', start=0, missing='skip', batch=1000, delivery=None)
¶
Observations from a query on a DB-API 2.0 connection (sqlite3, psycopg, mysqlclient, ...).
The query is the caller's, with the driver's own placeholders for
parameters; columns are matched by the names in the result. Rows are
fetched batch at a time. Order the query by seq when it is given.
next_position(delivery, source)
¶
The first sequence number of source a restored run still needs (its delivery's start if unseen).
from_kafka(messages, inputs, *, decode=json.loads, key=None, time=None, delivery=None, missing='skip')
¶
Observations from Kafka messages (a kafka-python or confluent-kafka consumer, or any iterable of messages).
Each message value is decoded (JSON by default) to a record whose
fields inputs maps to input names. The source of an Observation is
"topic/partition/input" and its sequence number the message offset, so
the delivery deduplicates redelivered messages and a checkpoint records
the offset reached in every partition. key names a record field to
join on (by default the message key, decoded as UTF-8); time a record
field, by default the message timestamp in seconds.
Offsets may have gaps (compacted or transactional topics). Pass the
run's Delivery (arrival policy) as delivery, and the adapter declares
each gap it crosses (Delivery.skip_range), so the checkpoint does not
grow with the gaps; a skipped missing value is declared the same way.
The offsets below the first message read from a partition are declared
absent too: start the consumer at the beginning of the topic, or, for a
restored run, at kafka_offsets (or earlier).
kafka_offsets(delivery, topic)
¶
Per partition of topic, the offset to seek a consumer to when resuming a restored run.
The smallest next position over the inputs read from that partition: nothing still needed is skipped, and what is read twice is dropped by the delivery.