atomscale.streaming#
High-performance streaming for RHEED and instrument data.
- class atomscale.streaming.RHEEDStreamer(api_key: str, endpoint: str | None = None)
Bases:
objectA thin, high-performance Python interface (via PyO3) for real-time RHEED frame streaming into the Atomscale platform. This class takes chunks of 8-bit frames (NumPy arrays) and uploads them for analysis while they are being captured from a camera programmatically.
Typical usage:
Instantiate the streamer
2) initialize(…) to create the remote data item and receive data_id 3a) run(data_id, frames_iter) to stream by yielding frame chunks from a generator/iterator, or 3b) push(data_id, chunk_idx, frames) repeatedly to send chunks from your own loop 4) finalize(data_id) to mark the stream complete on the server
Notes
Frame dtype is coerced to uint8. Shapes (H, W) or (N, H, W) are accepted; (N,H,W) is preferred for chunks.
push(…) and run(…) write each chunk’s encoded shard to a disk spool and return; upload workers send the spool oldest first in the background, so a slow or failing network never stalls (and so never delays the timestamps of) your acquisition loop. See spool_status().
This class is safe to call from Python; heavy work is offloaded to multithreaded async workers.
See also: finalize(…).
- Parameters:
api_key (str) – Your Atomscale API key.
endpoint (Optional[str]) – Base API URL. Defaults to “https://api.atomscale.ai”.
spool_dir (Optional[str]) – Where chunks wait to upload, one subfolder per stream. Defaults to $ATOMSCALE_SPOOL_DIR, else <user cache dir>/atomscale/rheed-spool.
spool_max_bytes (Optional[int]) – Cap on spooled data; past it, new chunks are dropped (and counted) instead of blocking. Defaults to min(20 GB, 10% of the disk’s free space).
spool_min_free_bytes (Optional[int]) – Free disk space the spool always leaves. Default 1 GB.
spool_retention_s (Optional[float]) – Age past which a chunk that still has not uploaded is discarded. Default 24 h.
- Raises:
RuntimeError – If the HTTP client or async runtime cannot be constructed.
- clock_status(self) dict | None
This computer’s clock measured against AtomCloud’s reference clock, or None when correction is off (ATOMSCALE_SKIP_CLOCK_SYNC) or no measurement has succeeded yet. Every chunk is stamped in reference UTC, so offset_ms (reference minus host) is the correction in effect, uncertainty_ms bounds its error (half the best round trip) and measured_at_unix_ms is the reference time of the sample it came from.
- finalize(self, data_id: str) None
Explicitly closes the remote stream for the given data_id. This signals to the server that no further chunks will be uploaded and allows any downstream jobs (e.g., indexing, aggregation, or post-processing) to begin.
Call it after your last push(…), or after run(…) returns.
Notes
First waits, up to drain_timeout_s, for this stream’s spooled chunks to upload, so a shard still waiting is not cut off. Then it discards whatever is left and closes the stream. If any chunk was never uploaded (dropped, refused, or still spooled at the timeout), it emits one RuntimeWarning with the count; the stream is still closed.
Also accepts a stream an earlier run left in the spool (after a crash), to close it.
The server answers 503 while the stream’s first analysis is still running; the POST to the …/end endpoint is retried with backoff for about three minutes before it fails.
It is safe to call more than once; the server may treat it as idempotent, but repeated calls are unnecessary.
- Parameters:
data_id (str) – The stream identifier returned by initialize(…).
drain_timeout_s (Optional[float]) – How long to wait for spooled chunks to upload. Default 600 (10 minutes).
- Returns:
What became of the stream’s chunks: chunks_spooled, chunks_uploaded, chunks_dropped, chunks_failed, chunks_purged, chunks_not_uploaded (the last three plus dropped), drained (whether the wait finished in time) and lost, a list of (chunk_idx, reason) for chunks not uploaded.
- Return type:
dict
- Raises:
RuntimeError – If the finalization POST fails.
See also
run(data_id, frames_iter), push(data_id, chunk_idx, frames)
- initialize(self, fps: float, rotations_per_min: float, chunk_size: int, stream_name: str | None = None, physical_sample: str | None = None, project_id: str | None = None, tags: List[str] | None = None, azimuth: str | None = None, seed_frame_count: int | None = None) str
Creates a new remote data item for this stream and returns its data_id. Also captures runtime configuration used for subsequent chunk uploads.
The rotational period (frames per rotation) is computed as: fpr = (fps * 60.0) / rotations_per_min. If rotations_per_min <= 0.0, the stream is treated as stationary (no rotation).
After streaming via run(…) or push(…), call finalize(data_id) to mark the stream as complete.
- Parameters:
fps (float) – Capture rate in frames per second.
rotations_per_min (float) – Wafer/crystal rotations per minute; use 0.0 for stationary operation.
chunk_size (int) – The intended number of frames per chunk you will send with run(…) or push(…).
stream_name (Optional[str]) – Human-readable name shown in the platform. If None or an empty string, a default like “RHEED Stream @ 1:23PM” is used.
physical_sample (Optional[str]) – Name or UUID of a physical sample to associate with the data item. If a UUID is provided, it must match an existing sample. If a name is provided, it is matched case-insensitively against existing samples, or a new sample is created if no match is found.
project_id (Optional[str]) – UUID of a project to associate with the stream. When provided along with physical_sample, the project’s tracking_physical_sample_id configuration is automatically updated to link the physical sample to the project for growth monitoring.
tags (Optional[List[str]]) – List of tag names or UUIDs to attach to the data item. Names are matched case-insensitively against existing org tags; unknown names are created. UUIDs must reference existing tags. Tags do not set the stream’s azimuth; use azimuth.
azimuth (Optional[str]) – The azimuth a parked stream is recorded at, e.g. “100”. Its views are labelled with it in place of the automatic azimuth classifier until a user edits the view. Only valid with rotations_per_min == 0; a rotating stream carries several azimuths.
seed_frame_count (Optional[int]) – Number of seed views to select. If omitted or None, defaults to 1 when rotations_per_min == 0, otherwise 3. Must be an integer from 1 through 8; only 1 is allowed when rotations_per_min == 0.
- Returns:
The created data_id for this stream.
- Return type:
str
- Raises:
ValueError – If azimuth is given for a rotating stream, seed_frame_count is outside 1 through 8, or seed_frame_count is not 1 when rotations_per_min == 0.
RuntimeError – If the stream cannot be created or linked. The physical sample and tags are resolved before the stream is created, so a bad one creates nothing. If linking fails after creation, the stream is ended and the error names its data_id.
- push(self, data_id: str, chunk_idx: int, frames: numpy.ndarray, capture_start_ms_utc: int | None = None) None
Callback mode. Push a single chunk of frames that you produced externally (e.g., from a camera callback). Call repeatedly for subsequent chunks.
The chunk is stamped, encoded and written to the disk spool before this returns; it never waits on uploads. If the spool is at its byte cap or the disk at its free-space floor, the chunk is dropped instead (logged, and counted in spool_status() and finalize()), so the backend sees a missing shard rather than your loop stalling.
The frames argument may be (N,H,W) or (H,W); dtype is coerced to uint8.
After your last push(…), call `finalize(data_id)` to mark the stream as complete on the server.
Timestamps#
Every chunk is stamped with when its first frame was captured, so the stream aligns with other lab wall-clock data. The chunk’s end_unix_ms_utc is start + (n / fps) * 1000. Pass capture_start_ms_utc whenever you have a real capture clock (camera trigger, OS monotonic-to-utc conversion). When you do not, the chunk is taken to have just finished being captured: push() samples Utc::now() on entry, before any GIL-held packaging work, and the start is that minus the chunk’s span (n / fps). That estimate is only as good as how promptly you push; a chunk pushed late is stamped late.
- type data_id:
str
- param data_id:
The remote data identifier returned by initialize(…).
- type data_id:
str
- type chunk_idx:
int
- param chunk_idx:
Zero-based index of this chunk (used in Zarr shard path).
- type chunk_idx:
int
- type frames:
numpy.ndarray
- param frames:
(N,H,W) or (H,W) grayscale frames as uint8.
- type frames:
numpy.ndarray
- type capture_start_ms_utc:
Optional[int]
- param capture_start_ms_utc:
Capture-start timestamp in milliseconds since UNIX epoch (UTC). Pass when you have a real capture-time clock (camera trigger, OS monotonic-to-utc conversion). When None, the chunk is taken to have just finished capturing: Utc::now() on entry minus n / fps.
- type capture_start_ms_utc:
Optional[int]
- returns:
None
- raises RuntimeError:
If the chunk cannot be packaged.
See also
finalize(data_id)
- run(self, data_id: str, frames_iter: Iterable) None
Generator/iterator mode. Iterates frames_iter, where each yielded item is one of:
(N, H, W) numpy.ndarray[uint8]: a chunk of N grayscale frames
(H, W) numpy.ndarray[uint8]: a single frame (treated as N = 1)
(frames, capture_start_ms_utc) 2-tuple: frames as above + an explicit capture-start timestamp (int milliseconds since UNIX epoch, UTC). Use this when you have hardware/OS-level timestamps for each chunk (camera trigger time, OS monotonic-to-utc conversion, etc.).
For each yielded item, the method stamps it, encodes its shard and writes it to the disk spool, then asks the iterator for the next one. It never waits on uploads, which run in the background, oldest first. Once the iterator is exhausted, it waits for this stream’s spool to drain (up to 10 minutes). After run(…) returns, call finalize(data_id) to mark the stream complete on the server.
Timestamps#
Every chunk is stamped with when its first frame was captured, so the stream aligns with other lab wall-clock data. The chunk’s end_unix_ms_utc is start + (n / fps) * 1000. Yield (frames, capture_start_ms_utc) whenever you have a real capture clock (camera trigger, OS monotonic-to-utc conversion). When you yield bare frames, each chunk is taken to have just finished capturing: Utc::now() is sampled the moment the iterator yields, before any GIL-held packaging work, and the start is that minus the chunk’s span (n / fps).
- type data_id:
str
- param data_id:
The stream data ID returned by initialize(…).
- type data_id:
str
- type frames_iter:
Iterable
- param frames_iter:
Python iterable/generator of (N,H,W) / (H,W) uint8 arrays, or (frames, capture_start_ms_utc) tuples.
- type frames_iter:
Iterable
- returns:
None
- raises RuntimeError:
If a chunk cannot be packaged, or if any chunk of this run was lost (dropped because the spool was full or the disk low, or refused by the backend). Chunks still uploading when the drain wait ends only warn; finalize keeps draining them.
- raises ValueError:
If a yielded tuple’s second element is not an int.
See also
finalize(data_id)
- spool_status(self) dict
The disk spool chunks wait in before uploading. Keys: dir, bytes (spooled now), max_bytes, min_free_bytes, free_bytes (on its disk; None if unknown), chunks_pending, the cumulative chunks_spooled, chunks_uploaded, chunks_dropped (spool full, disk low or write failed), chunks_failed (refused by the backend) and chunks_purged (discarded unsent: stream finalized or abandoned, or past retention), and streams, the same counts per data_id with closed.
- class atomscale.streaming.TimeseriesStreamer(api_key: str, endpoint: str | None = None, points_per_chunk: int = 100)
Bases:
objectA high-performance Python interface (via PyO3) for real-time instrument time series streaming into the Atomscale platform. This class takes chunks of scalar time series data and uploads them asynchronously for storage and analysis.
Typical usage:
Instantiate the streamer with API key and optional endpoint
initialize(…) to create the remote data item and get data_id
push(…) repeatedly to send data chunks (fire-and-forget, non-blocking)
Notes
Each push() spawns an async upload task and returns immediately; flush() waits for them.
Chunks are ordered server-side by chunk_index, so out-of-order arrival is handled.
Multiple channels can be streamed for the same data_id.
- Parameters:
api_key (str) – Your Atomscale API key.
endpoint (Optional[str]) – Base API URL. Defaults to “https://api.atomscale.ai”.
points_per_chunk (int) – Expected number of points per chunk. Defaults to 100.
- Raises:
RuntimeError – If the HTTP client or async runtime cannot be constructed.
- clock_status(self) dict | None
This computer’s clock measured against AtomCloud’s reference clock, or None when correction is off (ATOMSCALE_SKIP_CLOCK_SYNC) or no measurement has succeeded yet. Pushed timestamps are read as this computer’s clock and sent as reference UTC: offset_ms (reference minus host) is the correction in effect.
- finalize(self, data_id: str, drain_timeout_s: float | None = None) dict
Finalize the stream, marking it as complete on the server.
Call this after all data has been pushed to signal that the stream is finished. It first waits for the stream’s uploads still in flight (as flush() does): the server refuses a chunk that arrives after its stream is finalized. If any chunk was not uploaded, one RuntimeWarning says how many, once the stream is finalized.
- Parameters:
data_id (str) – The stream identifier returned by initialize().
drain_timeout_s (Optional[float]) – How long to wait for uploads in flight, in seconds. Defaults to 120.
- Returns:
The same report as flush().
- Return type:
dict
- Raises:
ValueError – If drain_timeout_s is negative.
RuntimeError – If the request fails. The report is kept for the next flush() or finalize().
- flush(self, data_id: str, timeout_s: float | None = None) dict
Wait until every chunk pushed so far for data_id has finished uploading: landed, or failed after its retries. push() and push_multi() return before their upload is done; call this to know the data arrived.
- Parameters:
data_id (str) – The stream identifier returned by initialize().
timeout_s (Optional[float]) – How long to wait, in seconds. Defaults to 120, longer than one upload’s full retry budget.
- Returns:
What became of the chunks pushed since the last flush() or finalize(): chunks_uploaded, chunks_failed, chunks_pending (still uploading when the wait ended; they are reported by the next flush), drained (whether the wait finished in time) and lost, a list of (chunk_index, reason) for the chunks that failed.
- Return type:
dict
- Raises:
ValueError – If timeout_s is negative.
- initialize(self, stream_name: str | None = None, synth_source_id: str | None = None, ...) str
Initialize a new time series stream on the server.
Creates data_catalogue and processed_tool_state_catalogue entries. Returns data_id to use for subsequent push() calls.
- Parameters:
stream_name (Optional[str]) – Human-readable name for the stream.
synth_source_id (Optional[str]) – Growth instrument ID (a UUID) to link. Must belong to your organization. Use list_growth_instruments() to see available instruments. The integer id an instrument had before instruments took UUIDs is still accepted.
physical_sample (Optional[str]) – Name or UUID of a physical sample to associate with the data item. If a UUID is provided, it must match an existing sample. If a name is provided, it is matched case-insensitively against existing samples, or a new sample is created if no match is found.
project_id (Optional[str]) – UUID of a project to associate with the stream. When provided along with physical_sample, the project’s tracking_physical_sample_id configuration is automatically updated to link the physical sample to the project for growth monitoring.
tags (Optional[List[str]]) – List of tag names or UUIDs to attach to the data item. Names are matched case-insensitively against existing org tags; unknown names are created. UUIDs must reference existing tags.
- Returns:
The data_id for this stream.
- Return type:
str
- Raises:
RuntimeError – If the stream cannot be created or linked, or the instrument is not found. The physical sample and tags are resolved before the stream is created, so a bad one creates nothing. If linking fails after creation, the stream is finalized and the error names its data_id.
- push(self, data_id: str, chunk_index: int, channel_name: str, timestamps: list[float], values: list[float], ...) None
Push a single chunk of time series data for a channel. This method is fire-and-forget: it spawns an async upload task and returns immediately.
- Parameters:
data_id (str) – The stream identifier returned by initialize().
chunk_index (int) – Zero-based index of this chunk for ordering.
channel_name (str) – Name of the data channel (e.g., “temperature”, “pressure”).
timestamps (list[float]) – Unix epoch timestamps in seconds.
values (list[float]) – Measured values corresponding to timestamps.
units (Optional[str]) – Units for the values.
- Returns:
None
- Raises:
RuntimeError – If timestamps/values have different lengths.
- push_multi(self, data_id: str, chunk_index: int, channels: dict[str, dict]) None
Push data for multiple channels at once. All channels of the chunk are uploaded together in one async request, so the server writes the shared time axis once per chunk.
- Parameters:
data_id (str) – The stream identifier returned by initialize().
chunk_index (int) – Zero-based index of this chunk.
channels (dict[str, dict]) – Mapping of channel_name to channel data dict. Each channel dict should have: - “timestamps” (list[float]): Unix epoch timestamps in seconds - “values” (list[float]): Measured values - “units” (str, optional): Units for the values
Example
- streamer.push_multi(data_id, 0, {
“temperature”: {“timestamps”: [0.0, 0.1], “values”: [25.0, 25.1], “units”: “C”}, “pressure”: {“timestamps”: [0.0, 0.1], “values”: [1.0, 1.1]},
})
- Returns:
None
- Raises:
RuntimeError – If any channel has mismatched lengths.
- run(self, data_id: str, channel_name: str, data_iter: Iterable[tuple[list[float], list[float]]], units: str | None = None) None
Iterator mode. Stream time series data by iterating over chunks. The chunk_index is automatically assigned based on iteration order.
Each yielded item should be a tuple of (timestamps, values) where both are lists of floats.
This method blocks until all upload tasks complete.
- Parameters:
data_id (str) – The stream identifier returned by initialize().
channel_name (str) – Name of the data channel (e.g., “temperature”, “pressure”).
data_iter (Iterable[tuple[list[float], list[float]]]) – Iterator yielding (timestamps, values) tuples.
units (Optional[str]) – Units for the values.
- Returns:
None
- Raises:
RuntimeError – If any chunk has mismatched lengths.