psana.smalldata¶
SmallData is the object returned by ds.smalldata(filename=..., batch_size=..., callbacks=[...]).
On big-data ranks it collects per-event values (event()) and summary data
(save_summary(), reductions such as sum()), and sends them in batches to
Server objects on the PS_SRV_NODES server ranks, which write HDF5 files
with h5py. In parallel mode each server writes <base>_part<N>.h5 and
done() joins them into one file with HDF5 virtual datasets; in serial mode
the file is written directly.
psana.smalldata ¶
Smalldata (v2)
Parallel data analysis with MPI send/recv
Analysis consists of two different process types:
1. clients
> these perform per-event analysis
> are associted with one specific server
> after processing `batch_size` events, send a
dict of data over to their server
2. servers (srv)
> recv a batch of events from one of many clients
> add these batches to a `cache`
> when the cache is full, write to disk
> each server produces its OWN hdf5 file
>> at the end of execution, rank 0 "joins" all the
individual hdf5 files together using HDF virtual
datasets -- this provides a "virtual", unified
view of all processed data
CLIENT SRV
[ --------- ] | [ --------- ]
[ -{event}- ] send | [ --------- ]
batch [ --------- ] ~~~> | [ --------- ]
[ --------- ] | [ --------- ]
[ --------- ] | [ --------- ]
|
| [ --------- ]
| [ --------- ]
| [ --------- ]
| [ --------- ]
| [ --------- ]
| -- cache
(I apologize for indulging in some ASCII art)
Some Notes:
* number of servers to use is set by PS_SRV_NODES
environment variable
* if running in psana parallel mode, clients ARE
BD nodes (they are the same processes)
* eventual time-stamp sorting would be doable with
code conceptually similar to this (but would need
to be optimized for performance):
import numpy as np
import h5py
f = h5py.File('smalldata_test.h5')
ts = f['timestamp'][:]
tsneg = f['tsneg']
for i in np.argsort(ts):
print(tsneg[i])
CacheArray ¶
CacheArray(singleton_shape, dtype, cache_size, is_var)
The CacheArray class provides for a data cache in the server's memory.
append ¶
append(data)
Add one event's data to the cache.
For a fixed-shape cache, data is written into the next row of the preallocated array and size grows by 1. For a variable-length cache, the entries of data are appended along axis 0 and size grows by len(data); None or empty data adds nothing.
Notes
n_events is incremented in every case.
reset ¶
reset()
Mark the cache as empty.
Sets size and n_events to 0 and, for a variable-length cache, sets data to None. A
fixed-shape cache keeps its buffer; old rows are overwritten later.
Server ¶
Server(filename=None, smdcomm=None, cache_size=10000, callbacks=[], swmr_mode=False)
Receive per-event data from smalldata clients and write it to one HDF5 file.
For each alignment group it records the dtype and shape of every dataset and keeps a
CacheArray per dataset, which is flushed to the file when it holds cache_size entries;
datasets missing from an event are backfilled. If filename is None nothing is written, but
the callbacks are still called for every event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
HDF5 file to create (opened with mode "w" and |
None
|
smdcomm
|
MPI communicator
|
Communicator used by |
None
|
cache_size
|
int
|
Number of entries cached per dataset before writing. |
10000
|
callbacks
|
list of callable
|
Each is called with one flattened dict per event in |
[]
|
swmr_mode
|
bool
|
If True, turn on HDF5 SWMR mode after the first dataset is created and flush the file after every batch. |
False
|
recv_loop ¶
recv_loop()
Receive batches from clients on smdcomm until every client has sent "done".
The number of clients is smdcomm.Get_size() - 1. A received list is passed to handle; the string "done" counts one finished client.
Notes
The receive wait time and number of events / processing seconds * 1e-3 are set on the "psana_srv_wait" and "psana_srv_rate" Prometheus gauges.
handle ¶
handle(batch)
Process a batch of events: store their datasets and call the callbacks.
When a file is open, new datasets are created with new_dset, values go through
append_to_cache, datasets seen before but absent from this event are backfilled, and the length of "var_"
data is appended to the shared "_len" dataset (once per event when the keys sharing it have
equal lengths). Each callback gets one flat dict
per event whose keys are "
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
list of dict
|
One dict per event, mapping alignment group name to that event's {dataset name: value} dict, which must contain "timestamp" when a file is written. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If an event key is itself a "var_..._len" length key. |
new_dset ¶
new_dset(dataset_name, data, datagroup)
Create an empty, resizable HDF5 dataset for dataset_name in datagroup.
The per-event shape and dtype come from data (from its first element for a "var_" key) and
are recorded in _dsets; the dataset is created at the file root for the default group and in
the group datagroup otherwise, chunked by cache_size. Then, except for non-length "var_"
keys, num_events_seen[datagroup] zero entries are backfilled.
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the per-event shape is (0,). |
append_to_cache ¶
append_to_cache(dataset_name, data, datagroup)
Append data to the cache of dataset_name in datagroup.
Creates a CacheArray from the recorded dtype and shape on first use. When the cache holds
cache_size or more entries, it is written out with write_to_file.
write_to_file ¶
write_to_file(dataset_name, datagroup, cache)
Write the entries held in cache to the end of the HDF5 dataset and reset the cache.
The dataset (dataset_name at the root for the default group, else
datagroup/dataset_name) is resized by cache.size and the first cache.size cached rows are
written into the new space. If the cache has no data, a warning is printed, the cache is reset
and nothing is written.
backfill ¶
backfill(dataset_name, num_to_backfill, datagroup, missing_value=None)
Append num_to_backfill fill entries to the cache of dataset_name.
The fill entry has the dataset's recorded shape and dtype and is filled with missing_value,
or, when that is None, with -99999 for integer dtypes and NaN for float dtypes.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
done ¶
done()
Flush all non-empty caches, close the HDF5 file and fsync it.
Does nothing if filename is None. Errors from the final HDF5 flush and from the fsync are
ignored.
SmallData ¶
SmallData(server_group=None, client_group=None)
Client-side object for saving per-event and summary data to HDF5 with smalldata.
In parallel mode (more than one MPI rank) the constructor builds communicators from
server_group and client_group and gives this rank the role "server", "client" or "other";
in serial mode the constructor does nothing. Clients collect events in batches and send them to
their server, servers write part files, and done joins the part files into one file with HDF5
virtual datasets (on client rank 0).
Raises:
| Type | Description |
|---|---|
Exception
|
In parallel mode, if |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_group
|
Group
|
The MPI group to allocate to server processes |
None
|
client_group
|
Group
|
The MPI group to allocate to client processes |
None
|
summary
property
¶
summary
This "flag" is required when you save summary data OR do a "reduction" operation (e.g. sum) across MPI procs
if SmallData.summary: whole = SmallData.sum(part) SmallData.save_summary(mysum=whole)
setup_parms ¶
setup_parms(filename=None, batch_size=1000, cache_size=None, callbacks=[], swmr_mode=False)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
The file path of the (new) HDF5 file to write data to, will be overwritten if it exits -- if "None", data will not be written to disk. |
None
|
batch_size
|
int
|
Number of events before send/recv |
1000
|
cache_size
|
int
|
Number of events before write |
None
|
callbacks
|
list of functions
|
Functions that get called on each server's data before being written to disk. The functions should take as arguments a dictionary, where the keys are the data field names and the values are the data themselves. Each event processed will have it's own dictionary of this form containing the data saved for that event. |
[]
|
swmr_mode
|
bool
|
Enable SWMR (Single Writer Multiple Reader) mode for HDF5 files. Allows concurrent read access while writing. |
False
|
get_rank ¶
get_rank()
Return this rank's number in the smalldata communicator (servers plus clients).
The communicator is created by the constructor only in parallel mode; in serial mode the attribute does not exist and AttributeError is raised.
sum ¶
sum(value, inplace=False)
Sum value element-wise across client ranks (MPI.SUM) onto client rank 0.
In serial mode value is returned unchanged. In parallel mode ints and floats become
one-element arrays, client ranks with no array contribute zeros, and the result is returned on
client rank 0; other client ranks get None (or their own value if inplace), and non-client
ranks get None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
(int, float or ndarray)
|
Local value. |
required |
inplace
|
bool
|
If True, reduce into |
False
|
Raises:
| Type | Description |
|---|---|
Exception
|
If no client rank has an array, or the arrays differ in shape or dtype. |
max ¶
max(value, inplace=False)
Take the element-wise maximum of value across client ranks (MPI.MAX) onto client rank 0.
In serial mode value is returned unchanged. In parallel mode ints and floats become
one-element arrays, client ranks with no array contribute an array filled with the global
minimum, and the result is returned on client rank 0; other client ranks get None (or their
own value if inplace), and non-client ranks get None.
min ¶
min(value, inplace=False)
Take the element-wise minimum of value across client ranks (MPI.MIN) onto client rank 0.
In serial mode value is returned unchanged. In parallel mode ints and floats become
one-element arrays, client ranks with no array contribute an array filled with the global
maximum, and the result is returned on client rank 0; other client ranks get None (or their
own value if inplace), and non-client ranks get None.
prod ¶
prod(value, inplace=False)
Multiply value element-wise across client ranks (MPI.PROD) onto client rank 0.
In serial mode value is returned unchanged. In parallel mode the result is returned on client rank 0, other client ranks get None (or their own value if inplace), and non-client ranks get None.
Notes
No stand-in array is made for a client rank without data, so every client rank must pass an array or number.
land ¶
land(value, inplace=False)
Combine value across client ranks with logical AND (MPI.LAND) onto client rank 0.
In serial mode value is returned unchanged. In parallel mode the result is returned on client rank 0, other client ranks get None (or their own value if inplace), and non-client ranks get None.
Notes
No stand-in array is made for a client rank without data.
band ¶
band(value, inplace=False)
Combine value across client ranks with bitwise AND (MPI.BAND) onto client rank 0.
In serial mode value is returned unchanged. In parallel mode the result is returned on client rank 0, other client ranks get None (or their own value if inplace), and non-client ranks get None.
Notes
No stand-in array is made for a client rank without data.
lor ¶
lor(value, inplace=False)
Combine value across client ranks with logical OR (MPI.LOR) onto client rank 0.
In serial mode value is returned unchanged. In parallel mode the result is returned on client rank 0, other client ranks get None (or their own value if inplace), and non-client ranks get None.
Notes
No stand-in array is made for a client rank without data.
bor ¶
bor(value, inplace=False)
Combine value across client ranks with bitwise OR (MPI.BOR) onto client rank 0.
In serial mode value is returned unchanged. In parallel mode the result is returned on client rank 0, other client ranks get None (or their own value if inplace), and non-client ranks get None.
Notes
No stand-in array is made for a client rank without data.
lxor ¶
lxor(value, inplace=False)
Combine value across client ranks with logical XOR (MPI.LXOR) onto client rank 0.
In serial mode value is returned unchanged. In parallel mode the result is returned on client rank 0, other client ranks get None (or their own value if inplace), and non-client ranks get None.
Notes
No stand-in array is made for a client rank without data.
bxor ¶
bxor(value, inplace=False)
Combine value across client ranks with bitwise XOR (MPI.BXOR) onto client rank 0.
In serial mode value is returned unchanged. In parallel mode the result is returned on client rank 0, other client ranks get None (or their own value if inplace), and non-client ranks get None.
Notes
No stand-in array is made for a client rank without data.
save_summary ¶
save_summary(*args, **kwargs)
Save 'summary data', ie any data that is not per-event (typically slower, e.g. at the end of the job).
Interface is identical to SmallData.event()
Note: this function should be called in a SmallData.summary: block
join_files ¶
join_files()
Join the per-server part files into the main HDF5 file with virtual datasets.
Looks for <basename>_part<i>.h5 for every server rank i, printing a warning for each one that is missing. For every dataset found in any part file, it creates a virtual dataset whose rows are the part files' rows in server order; a part file without that dataset leaves a gap as long as its "/timestamp" dataset, filled with -99999 (integers) or NaN (floats).
Notes
The main file is opened with _get_full_file_handle and closed at the end.
set_keytypes ¶
set_keytypes(k)
Classify dataset key k and record the result in the module dicts.
A key is variable-length (var_dict[k] = True) if any "/"-separated part starts with "var_". If that part is the last one and ends with "_len", the key is itself a length key; otherwise the name of its length key (the path up to and including that part, plus "_len") is stored in len_map[k], marked as a length key in len_dict and given an empty entry in len_evt.
Notes
Keys with no "var_" part are marked as neither variable nor length keys.
get_len_map ¶
get_len_map(k)
Return the name of the length key for variable key k.
Looks k up in len_map, calling set_keytypes(k) first if it is not there yet.
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
is_len_key ¶
is_len_key(k)
Return True if k is a length key, as classified by set_keytypes.
The classification is computed on first lookup and cached in len_dict.
is_var_key ¶
is_var_key(k)
Return True if any "/"-separated part of k starts with "var_".
The classification is computed by set_keytypes on first lookup and cached in var_dict.
is_group ¶
is_group(event_data_dict)
Return True if event_data_dict contains the reserved key "align_group".
get_group_name ¶
get_group_name(event_data_dict)
Return the value of the "align_group" key of event_data_dict, or "default" if it is absent.