Data Formats
In-memory Data
Basic Concepts
The main format we're using within plottr is the DataDict
. While most of the actual numeric data will typically live in numpy arrays (or lists, or similar), they don't typically capture easily arbitrary metadata and relationships between arrays. Say, for example, we have some data z
that depends on two other variables, x
and y
. This information has be stored somewhere, and numpy doesn't offer readily a solution here. There are various extensions, for example xarray or the MetaArray class. Those however typically have a grid format in mind, which we do not want to impose. Instead, we use a wrapper around the python dictionary that contains all the required meta information to infer the relevant relationships, and that uses numpy arrays internally to store the numeric data. Additionally we can store any other arbitrary meta data.
A DataDict container (a dataset
) can contain multiple data fields
(or variables), that have values and can contain their own meta information. Importantly, we distinct between independent fields (the axes
) and dependent fields (the data
).
Despite the naming, axes
is not meant to imply that the data
have to have a certain shape (but the degree to which this is true depends on the class used). A list of classes for different shapes of data can be found below.
The basic structure of data conceptually looks like this (we inherit from dict
):
{
'data_1' : {
'axes' : ['ax1', 'ax2'],
'unit' : 'some unit',
'values' : [ ... ],
'__meta__' : 'This is very important data',
...
},
'ax1' : {
'axes' : [],
'unit' : 'some other unit',
'values' : [ ... ],
...,
},
'ax2' : {
'axes' : [],
'unit' : 'a third unit',
'values' : [ ... ],
...,
},
'__globalmeta__' : 'some information about this data set',
'__moremeta__' : 1234,
...
}
In this case we have one dependent variable, data_1
, that depends on two axes, ax1
and ax2
. This concept is restricted only in the following way:
- A dependent can depend on any number of independents.
- An independent cannot depend on other fields itself.
- Any field that does not depend on another, is treated as an axis.
Note that meta information is contained in entries whose keys start and end with double underscores. Both the DataDict itself, as well as each field can contain meta information.
In the most basic implementation, the only restriction on the data values is that they need to be contained in a sequence (typically as list, or numpy array), and that the length of all values in the data set (the number of records
) must be equal. Note that this does not preclude nested sequences!
Relevant Data Classes
DataDictBase: The main base class. Only checks for correct dependencies. Any requirements on data structure is left to the inheriting classes. The class contains methods for easy access to data and metadata.
DataDict: The only requirement for valid data is that the number of records is the same for all data fields. Contains some tools for expansion of data.
MeshgridDataDict: For data that lives on a grid (not necessarily regular).
Datadict
Note
Because DataDicts are python dictionaries , we highly recommend becoming familiar with them before utilizing DataDicts.
Basic Use
We can start by creating an empty DataDict like any other python object:
We can create the structure of the data_dict by creating dictionary items and populating them like a normal python dictionary:
We can also start by creating a DataDict that has the structure of the data we are going to record:
>>> data_dict = DataDict(x=dict(unit='m'), y = dict(unit='m'), z = dict(axes=['x', 'y']))
>>> data_dict
{'x': {'unit': 'm'}, 'y': {'unit': 'm'}, 'z': {'axes': ['x', 'y']}}
The DataDict that we just created contains no data yet, only the structure and relationship of the data fields. We have also specified the unit of x
and y
and which variables are independent variables (x
, y
), or how we will call them from now on, axes
and dependent variables (z
), or, dependents
.
Structure
From the basic and empty DataDict we can already start to inspect its structure. To see the entire structure of a DataDict we can use the structure()
method:
>>> data_dict = DataDict(x=dict(unit='m'), y = dict(unit='m'), z = dict(axes=['x', 'y']))
>>> data_dict.structure()
{'x': {'unit': 'm', 'axes': [], 'label': ''},
'y': {'unit': 'm', 'axes': [], 'label': ''},
'z': {'axes': ['x', 'y'], 'unit': '', 'label': ''}}
We can check for specific things inside the DataDict. We can look at the axes:
We can look at all the dependents:
We can also see the shape of a DataDict by using the shapes()
method:
Populating the DataDict
One of the only "restrictions" that DataDict implements is that every data field must have the same number of records (items). However, restrictions is in quotes because there is nothing that is stopping you from having different data fields have different number of records, this will only make the DataDict invalid. We will explore what his means later.
There are 2 different ways of safely populating a DataDict, adding data to it or appending 2 different DataDict to each other.
Note
You can always manually update the item values
any data field like any other item of a python dictionary, however, populating the DataDict this way can result in an invalid DataDict if you are not being careful. Both population methods presented below contains checks to make sure that the new data being added will not create an invalid DataDict.
We can add data to an existing DataDict with the [add_data()
(#labcore.data.datadict.DataDict.add_data) method:
>>> data_dict = DataDict(x=dict(unit='m'), y = dict(unit='m'), z = dict(axes=['x', 'y']))
>>> data_dict.add_data(x=[0,1,2], y=[0,1,2], z=[0,1,4])
>>> data_dict
{'x': {'unit': 'm', 'axes': [], 'label': '', 'values': array([0, 1, 2])},
'y': {'unit': 'm', 'axes': [], 'label': '', 'values': array([0, 1, 2])},
'z': {'axes': ['x', 'y'], 'unit': '', 'label': '', 'values': array([0, 1, 4])}}
We now have a populated DataDict. It is important to notice that this method will also add any of the missing special keys that a data field doesn't have (values
, axes
, unit
, and label
). Populating the DataDict with this method will also ensure that every item has the same number of records and the correct shape, either by adding nan
to the other data fields or by nesting the data arrays so that the outer most dimension of every data field has the same number of records.
We can see this in action if we add a single record to a data field with items but no the rest:
>>> data_dict.add_data(x=[9])
>>> data_dict
{'x': {'unit': 'm', 'axes': [], 'label': '', 'values': array([0, 1, 2, 9])},
'y': {'unit': 'm', 'axes': [], 'label': '', 'values': array([ 0., 1., 2., nan])},
'z': {'axes': ['x', 'y'], 'unit': '', 'label': '', 'values': array([ 0., 1., 4., nan])}}
As we can see, both y
and z
have an extra nan
record in them. We can observe the change of dimension if we do not add the same number of records to all data fields:
>>> data_dict = DataDict(x=dict(unit='m'), y = dict(unit='m'), z = dict(axes=['x', 'y']))
>>> data_dict.add_data(x=[0,1,2], y=[0,1,2],z=[0])
>>> data_dict
{'x': {'unit': 'm', 'axes': [], 'label': '', 'values': array([[0, 1, 2]])},
'y': {'unit': 'm', 'axes': [], 'label': '', 'values': array([[0, 1, 2]])},
'z': {'axes': ['x', 'y'], 'unit': '', 'label': '', 'values': array([0])}}
If we want to expand our DataDict by appending another one, we need to make sure that both of our DataDicts have the same inner structure. We can check that by utilizing the static method same_structure()
:
>>> data_dict_1 = DataDict(x=dict(unit='m'), y=dict(unit='m'), z=dict(axes=['x','y']))
>>> data_dict_2 = DataDict(x=dict(unit='m'), y=dict(unit='m'), z=dict(axes=['x','y']))
>>> data_dict_1.add_data(x=[0,1,2], y=[0,1,2], z=[0,1,4])
>>> data_dict_2.add_data(x=[3,4], y=[3,4], z=[9,16])
>>> DataDict.same_structure(data_dict_1, data_dict_2)
True
Note
Make sure that both DataDicts have the exact same structure. This means that every item of every data field that appears when using the method same_structure()
(unit
, axes
, and label
) are identical to one another, except for values
. Any slight difference will make this method fail due to conflicting structures.
The append()
method will do this check before appending the 2 DataDict, and will only append them if the check returns True
. Once we know that the structure is the same we can append them:
>>> data_dict_1.append(data_dict_2)
>>> data_dict_1
{'x': {'unit': 'm', 'axes': [], 'label': '', 'values': array([0, 1, 2, 3, 4])},
'y': {'unit': 'm', 'axes': [], 'label': '', 'values': array([0, 1, 2, 3, 4])},
'z': {'axes': ['x', 'y'], 'unit': '', 'label': '', 'values': array([ 0, 1, 4, 9, 16])}}
Meta Data
One of the advantages DataDicts have over regular python dictionaries is their ability to contain meta data. Meta data can be added to the entire DataDict or to individual data fields. Any object inside a DataDict
whose key starts and ends with two underscores is considered meta data.
We can simply add meta data manually by adding an item with the proper notation:
Or we can use the add_meta()
method:
>>> data_dict.add_meta('sample_temperature', '10mK')
>>> data_dict
{'x': {'unit': 'm', 'axes': [], 'label': '', 'values': array([0, 1, 2])},
'y': {'unit': 'm', 'axes': [], 'label': '', 'values': array([0, 1, 2])},
'z': {'axes': ['x', 'y'], 'unit': '', 'label': '', 'values': array([0, 1, 4])},
'__metadata__': 'important meta data',
'__sample_temperature__': '10mK'}
We can also add meta data to a specific data field by passing its name as the last argument:
We can retrieve the meta data with the meta_val()
method:
We can also ask for a meta value from a specific data field by passing the data field as the second argument:
We can delete a specific meta field by using the delete_meta()
method:
This also work for meta data in data fields by passing the data field as the last argument:
>>> data_dict.delete_meta('extra_metadata', 'x')
>>> data_dict['x']
{'unit': 'm', 'axes': [], 'label': '', 'values': array([0, 1, 2])}
We can delete all the meta data present in the DataDict with the clear_meta()
method:
>>> data_dict.add_meta('metadata', 'important meta data')
>>> data_dict.add_meta('extra_metadata', 'important meta data', 'x')
>>> data_dict.clear_meta()
>>> data_dict
{'x': {'unit': 'm', 'axes': [], 'label': '', 'values': array([0, 1, 2])},
'y': {'unit': 'm', 'axes': [], 'label': '', 'values': array([0, 1, 2])},
'z': {'axes': ['x', 'y'], 'unit': '', 'label': '', 'values': array([0, 1, 4])}}
Note
There are 3 helper functions in the datadict module that help converting from meta data name to key. These are:
Meshgrid DataDict
A dataset where the axes form a grid on which the dependent values reside.
This is a more special case than DataDict, but a very common scenario. To support flexible grids, this class requires that all axes specify values for each datapoint, rather than a single row/column/dimension.
For example, if we want to specify a 3-dimensional grid with axes x
, y
, z
, the values of x
, y
, z
all need to be 3-dimensional arrays; the same goes for all dependents that live on that grid. Then, say, x[i,j,k]
is the x-coordinate of point i
,j
,k
of the grid.
This implies that a MeshgridDataDict can only have a single shape, i.e., all data values share the exact same nesting structure.
For grids where the axes do not depend on each other, the correct values for the axes can be obtained from np.meshgrid (hence the name of the class).
Example: a simple uniform 3x2 grid might look like this; x and y are the coordinates of the grid, and z is a function of the two:
Note
Internally we will typically assume that the nested axes are ordered from slow to fast, i.e., dimension 1 is the most outer axis, and dimension N of an N-dimensional array the most inner (i.e., the fastest changing one). This guarantees, for example, that the default implementation of np.reshape
has the expected outcome. If, for some reason, the specified axes are not in that order (e.g., we might have z
with axes = ['x', 'y']
, but x
is the fast axis in the data). In such a case, the guideline is that at creation of the meshgrid, the data should be transposed such that it conforms correctly to the order as given in the axis = [...]
specification of the data. The function datadict_to_meshgrid()
provides options for that.
This implementation of DataDictBase
consists only of three extra methods:
So the only way of populating it is by manually modifying the values
object of each data field since the tools for populating the DataDict are specific to the DataDict
implementation.
DataDict Storage
The datadict_storage.py module offers tools to help with saving DataDicts into disk by storing them in DDH5 files (HDF5 files that contains DataDicts inside).
Description of the HDF5 Storage Format
We use a simple mapping from DataDict to the HDF5 file. Within the file, a single DataDict is stored in a (top-level) group of the file. The data fields are datasets within that group.
Global meta data of the DataDict are attributes of the group; field meta data are attributes of the dataset (incl., the unit
and axes
values). The meta data keys are given exactly like in the DataDict, i.e., includes the double underscore pre- and suffix.
For more specific information on how HDF5 works please read the following documentation
Working With DDH5 Files
When we are working with data, the first thing we usually want to do is to save it in disk. We can directly save an already existing DataDict into disk by calling the function datadict_to_hdf5()
.
>>> data_dict = DataDict(x=dict(values=np.array([0,1,2]), axes=[], __unit__='cm'), y=dict(values=np.array([3,4,5]), axes=['x']))
>>> data_dict
{'x': {'values': array([0, 1, 2]), 'axes': [], '__unit__': 'cm'},
'y': {'values': array([3, 4, 5]), 'axes': ['x']}}
>>> datadict_to_hdf5(data_dict, 'folder\data.ddh5')
datadict_to_hdf5()
will save data_dict in a file named 'data.ddh5' in whatever directory is passed to it, creating new folders if they don't already exists. The file will contain all of the data fields as well as all the metadata,
with some more metadata generated to specify when the DataDict was created.
Note
Meta data is only written during initial writing of the dataset. If we're appending to existing datasets, we're not setting meta data anymore.
Warning
For this method to properly work the objects that are being saved in the values
key of a data field must by a numpy array, or numpy array like.
Data saved on disk is useless however if we do not have a way of accessing it. To do this we use the datadict_from_hdf5()
:
>>> loaded_data_dict = datadict_from_hdf5('folder\data.ddh5')
>>> loaded_data_dict
{'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'x': {'values': array([0, 1, 2]),
'axes': [],
'__shape__': (3,),
'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'__unit__': 'cm',
'unit': '',
'label': ''},
'y': {'values': array([3, 4, 5]),
'axes': ['x'],
'__shape__': (3,),
'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'unit': '',
'label': ''}}
We can see that the DataDict is the same one we saved earlier with the added metadata that indicates the time it was created.
By default both datadict_to_hdf5()
and datadict_from_hdf5()
save and load the datadict in the 'data' group of the DDH5. Both of these can by changed by passing another group to the argument 'groupname'. We can see this if we manually create a second group and save a new DataDict there:
>>> data_dict2 = DataDict(a=dict(values=np.array([0,1,2]), axes=[], __unit__='cm'), b=dict(values=np.array([3,4,5]), axes=['a']))
>>> with h5py.File('folder\data.ddh5', 'a') as file:
>>> file.create_group('other_data')
>>> datadict_to_hdf5(data_dict2, 'folder\data.ddh5', groupname='other_data')
If we then load the DDH5 file like before we only see the first DataDict:
>>> loaded_data_dict = datadict_from_hdf5('folder\data.ddh5', 'data')
>>> loaded_data_dict
{'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'x': {'values': array([0, 1, 2]),
'axes': [],
'__shape__': (3,),
'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'__unit__': 'cm',
'unit': '',
'label': ''},
'y': {'values': array([3, 4, 5]),
'axes': ['x'],
'__shape__': (3,),
'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'unit': '',
'label': ''}}
To see the other DataDict we can specify the group in the argument 'groupname':
>>> loaded_data_dict = datadict_from_hdf5('folder\data.ddh5', 'other_data')
>>> loaded_data_dict
{'a': {'values': array([0, 1, 2]),
'axes': [],
'__shape__': (3,),
'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'__unit__': 'cm',
'unit': '',
'label': ''},
'b': {'values': array([3, 4, 5]),
'axes': ['a'],
'__shape__': (3,),
'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'unit': '',
'label': ''}}
We can also use all_datadicts_from_hdf5()
to get a dictionary with all DataDicts in every group inside:
>>> all_datadicts = all_datadicts_from_hdf5('folder\data.ddh5')
>>> all_datadicts
{'data': {'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'x': {'values': array([0, 1, 2]),
'axes': [],
'__shape__': (3,),
'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'__unit__': 'cm',
'unit': '',
'label': ''},
'y': {'values': array([3, 4, 5]),
'axes': ['x'],
'__shape__': (3,),
'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'unit': '',
'label': ''}},
'other_data': {'a': {'values': array([0, 1, 2]),
'axes': [],
'__shape__': (3,),
'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'__unit__': 'cm',
'unit': '',
'label': ''},
'b': {'values': array([3, 4, 5]),
'axes': ['a'],
'__shape__': (3,),
'__creation_time_sec__': 1651159636.0,
'__creation_time_str__': '2022-04-28 10:27:16',
'unit': '',
'label': ''}}}
DDH5 Writer
Most times we want to be saving data to disk as soon as it is generated by an experiment (or iteration), instead of waiting to have a complete DataDict. To do this, Datadict_storage also offers a context manager with which we can safely save our incoming data.
To use it we first need to create an empty DataDict that contains the structure of how the data is going to look like:
With our created DataDict, we can start the DDH5Writer
context manager and add data to our DataDict utilizing the add_data()
>>> with DDH5Writer(datadict=data_dict, basedir='./data/', name='Test') as writer:
>>> for x in range(10):
>>> writer.add_data(x=x, y=x**2)
Data location: data\2022-04-27\2022-04-27T145308_a986867c-Test\data.ddh5
The writer created the folder 'data' (because it did not exist before) and inside that folder,
created another new folder for the current day and another new folder inside of it day folder for the the DataDict that we saved with the naming structure of YYYY-mm-dd_THHMMSS_<ID>-<name>/<filename>.ddh5
,
where name is the name parameter passed to the writer.
The writer creates this structure such that when we run the writer again with new data, it will create another folder following the naming structure inside the current date folder.
This way each new DataDict will be saved in the date it was generated with a time stamp in the name of the folder containing it.
Change File Extension and Time Format
Finally, datadict_storage contains 2 module variables, 'DATAFILEXT' and 'TIMESTRFORMAT'.
'DATAFILEXT' by default is 'ddh5', and it is used to specify the extension file of all of the module saving functions. Change this variable if you want your HDF5 to have a different extension by default, instead of passing it everytime.
'TIMESTRFORMAT' specifies how the time is formated in the new metadata created when saving a DataDict. The default is: "%Y-%m-%d %H:%M:%S"
, and it follows the structure of strftime.
Reference
Datadict
datadict.py :
Data classes we use throughout the plottr package, and tools to work on them.
DataDict
Bases: DataDictBase
The most basic implementation of the DataDict class.
It only enforces that the number of records
per data field must be
equal for all fields. This refers to the most outer dimension in case
of nested arrays.
The class further implements simple appending of datadicts through the
DataDict.append
method, as well as allowing addition of DataDict
instances.
Source code in labcore/data/datadict.py
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 |
|
__add__(newdata)
Adding two datadicts by appending each data array.
Requires that the datadicts have the same structure. Retains the meta information of the first array.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
newdata
|
DataDict
|
DataDict to be added. |
required |
Returns:
Type | Description |
---|---|
DataDict
|
combined DataDict. |
Source code in labcore/data/datadict.py
add_data(**kw)
Add data to all values. new data must be valid in itself.
This method is useful to easily add data without needing to specify meta data or dependencies, etc.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kw
|
Any
|
one array per data field (none can be omitted). |
{}
|
Source code in labcore/data/datadict.py
append(newdata)
Append a datadict to this one by appending data values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
newdata
|
DataDict
|
DataDict to append. |
required |
Source code in labcore/data/datadict.py
expand()
Expand nested values in the data fields.
Flattens all value arrays. If nested dimensions are present, all data with non-nested dims will be repeated accordingly -- each record is repeated to match the size of the nested dims.
Returns:
Type | Description |
---|---|
DataDict
|
The flattened dataset. |
Source code in labcore/data/datadict.py
is_expandable()
Determine if the DataDict can be expanded.
Expansion flattens all nested data values to a 1D array. For doing so,
we require that all data fields that have nested/inner dimensions (i.e,
inside the records
level) shape the inner shape.
In other words, all data fields must be of shape (N,) or (N, (shape)),
where shape is common to all that have a shape not equal to (N,).
Returns:
Type | Description |
---|---|
bool
|
|
Source code in labcore/data/datadict.py
is_expanded()
Determine if the DataDict is expanded.
Returns:
Type | Description |
---|---|
bool
|
|
Source code in labcore/data/datadict.py
nrecords()
Gets the number of records in the dataset.
Returns:
Type | Description |
---|---|
Optional[int]
|
The number of records in the dataset. |
remove_invalid_entries()
Remove all rows that are None
or np.nan
in all dependents.
Returns:
Type | Description |
---|---|
DataDict
|
The cleaned DataDict. |
Source code in labcore/data/datadict.py
sanitize()
Clean-up.
Beyond the tasks of the base class DataDictBase
:
* remove invalid entries as far as reasonable.
Returns:
Type | Description |
---|---|
DataDict
|
sanitized DataDict. |
Source code in labcore/data/datadict.py
validate()
Check dataset validity.
Beyond the checks performed in the base class DataDictBase
,
check whether the number of records is the same for all data fields.
Returns:
Type | Description |
---|---|
bool
|
|
Source code in labcore/data/datadict.py
DataDictBase
Bases: dict
Simple data storage class that is based on a regular dictionary.
This base class does not make assumptions about the structure of the values. This is implemented in inheriting classes.
Source code in labcore/data/datadict.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 |
|
__eq__(other)
add_meta(key, value, data=None)
Add meta info to the dataset.
If the key already exists, meta info will be overwritten.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
Name of the meta field (without underscores). |
required |
value
|
Any
|
Value of the meta information. |
required |
data
|
Union[str, None]
|
If |
None
|
Source code in labcore/data/datadict.py
astype(dtype)
Convert all data values to given dtype.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dtype
|
dtype
|
np dtype. |
required |
Returns:
Type | Description |
---|---|
T
|
Dataset, with values as given type (not a copy) |
Source code in labcore/data/datadict.py
axes(data=None)
Return a list of axes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Union[Sequence[str], str, None]
|
if |
None
|
Returns:
Type | Description |
---|---|
List[str]
|
The list of axes. |
Source code in labcore/data/datadict.py
axes_are_compatible()
Check if all dependent data fields have the same axes.
This includes axes order.
Returns:
Type | Description |
---|---|
bool
|
|
Source code in labcore/data/datadict.py
clear_meta(data=None)
Deletes all meta data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Union[str, None]
|
If not |
None
|
Source code in labcore/data/datadict.py
copy()
Make a copy of the dataset.
Returns:
Type | Description |
---|---|
T
|
A copy of the dataset. |
Source code in labcore/data/datadict.py
data_items()
Generator for data field items.
Like dict.items(), but ignores meta data.
Returns:
Type | Description |
---|---|
Iterator[Tuple[str, Dict[str, Any]]]
|
Generator yielding first the key of the data field and second its value. |
Source code in labcore/data/datadict.py
data_vals(key)
Return the data values of field key
.
Equivalent to DataDict['key'].values
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
Name of the data field. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
Values of the data field. |
Source code in labcore/data/datadict.py
delete_meta(key, data=None)
Deletes specific meta data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
Name of the meta field to remove. |
required |
data
|
Union[str, None]
|
If |
None
|
Source code in labcore/data/datadict.py
dependents()
Get all dependents in the dataset.
Returns:
Type | Description |
---|---|
List[str]
|
A list of the names of dependents. |
Source code in labcore/data/datadict.py
extract(data, include_meta=True, copy=True, sanitize=True)
Extract data from a dataset.
Return a new datadict with all fields specified in data
included.
Will also take any axes fields along that have not been explicitly
specified. Will return empty if data
consists of only axes fields.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
List[str]
|
Data field or list of data fields to be extracted. |
required |
include_meta
|
bool
|
If |
True
|
copy
|
bool
|
If |
True
|
sanitize
|
bool
|
If |
True
|
Returns:
Type | Description |
---|---|
T
|
New DataDictBase containing only requested fields. |
Source code in labcore/data/datadict.py
has_meta(key)
Check whether meta field exists in the dataset.
Returns:
Type | Description |
---|---|
bool
|
|
Source code in labcore/data/datadict.py
label(name)
Get the label for a data field. If no label is present returns the name of the data field as the label. If a unit is present, it will be appended at the end in brackets: "label (unit)".
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Name of the data field. |
required |
Returns:
Type | Description |
---|---|
Optional[str]
|
Labelled name. |
Source code in labcore/data/datadict.py
mask_invalid()
Mask all invalid data in all values.
Returns:
Type | Description |
---|---|
T
|
Copy of the dataset with invalid entries (nan/None) masked. |
Source code in labcore/data/datadict.py
meta_items(data=None, clean_keys=True)
Generator for meta items.
Like dict.items(), but yields only
meta entries.
The keys returned do not contain the underscores used internally.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Union[str, None]
|
If |
None
|
clean_keys
|
bool
|
If |
True
|
Returns:
Type | Description |
---|---|
Iterator[Tuple[str, Dict[str, Any]]]
|
Generator yielding first the key of the data field and second its value. |
Source code in labcore/data/datadict.py
meta_val(key, data=None)
Return the value of meta field key
(given without underscore).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
Name of the meta field. |
required |
data
|
Union[str, None]
|
|
None
|
Returns:
Type | Description |
---|---|
Any
|
The value of the meta information. |
Source code in labcore/data/datadict.py
nbytes(name=None)
Get the size of data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
Optional[str]
|
Name of the data field. if none, return size of entire datadict. |
None
|
Returns:
Type | Description |
---|---|
Optional[int]
|
size in bytes. |
Source code in labcore/data/datadict.py
remove_unused_axes()
Removes axes not associated with dependents.
Returns:
Type | Description |
---|---|
T
|
Cleaned dataset. |
Source code in labcore/data/datadict.py
reorder_axes(data_names=None, **pos)
Reorder data axes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_names
|
Union[str, Sequence[str], None]
|
Data name(s) for which to reorder the axes. If None, apply to all dependents. |
None
|
pos
|
int
|
New axes position in the form |
{}
|
Returns:
Type | Description |
---|---|
T
|
Dataset with re-ordered axes (not a copy) |
Source code in labcore/data/datadict.py
reorder_axes_indices(name, **pos)
Get the indices that can reorder axes in a given way.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Name of the data field of which we want to reorder axes. |
required |
pos
|
int
|
New axes position in the form |
{}
|
Returns:
Type | Description |
---|---|
Tuple[Tuple[int, ...], List[str]]
|
The tuple of new indices, and the list of axes names in the new order. |
Source code in labcore/data/datadict.py
same_structure(*data, check_shape=False)
staticmethod
Check if all supplied DataDicts share the same data structure (i.e., dependents and axes).
Ignores meta data and values. Checks also for matching shapes if
check_shape
is True
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
T
|
The data sets to compare. |
()
|
check_shape
|
bool
|
Whether to include shape check in the comparison. |
False
|
Returns:
Type | Description |
---|---|
bool
|
|
Source code in labcore/data/datadict.py
sanitize()
shapes()
Get the shapes of all data fields.
Returns:
Type | Description |
---|---|
Dict[str, Tuple[int, ...]]
|
A dictionary of the form |
Source code in labcore/data/datadict.py
structure(add_shape=False, include_meta=True, same_type=False, remove_data=None)
Get the structure of the DataDict.
Return the datadict without values (value
omitted in the dict).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
add_shape
|
bool
|
Deprecated -- ignored. |
False
|
include_meta
|
bool
|
If |
True
|
same_type
|
bool
|
If |
False
|
remove_data
|
Optional[List[str]]
|
any data fields listed will be removed from the result, also when listed in any axes. |
None
|
Returns:
Type | Description |
---|---|
Optional[T]
|
The DataDict containing the structure only. The exact type is the same as the type of |
Source code in labcore/data/datadict.py
to_records(**data)
staticmethod
Convert data to records that can be added to the DataDict
.
All data is converted to np.array, and reshaped such that the first dimension of all resulting
arrays have the same length (chosen to be the smallest possible number
that does not alter any shapes beyond adding a length-1 dimension as
first dimension, if necessary).
If a data field is given as None
, it will be converted to numpy.array([numpy.nan])
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Any
|
keyword arguments for each data field followed by data. |
{}
|
Returns:
Type | Description |
---|---|
Dict[str, ndarray]
|
Dictionary with properly shaped data. |
Source code in labcore/data/datadict.py
validate()
Check the validity of the dataset.
Checks performed: * All axes specified with dependents must exist as data fields.
Other tasks performed:
* unit
keys are created if omitted.
* label
keys are created if omitted.
* shape
meta information is updated with the correct values
(only if present already).
Returns:
Type | Description |
---|---|
bool
|
|
Source code in labcore/data/datadict.py
MeshgridDataDict
Bases: DataDictBase
Implementation of DataDictBase meant to be used for when the axes form a grid on which the dependent values reside.
It enforces that all dependents have the same axes and all shapes need to be identical.
Source code in labcore/data/datadict.py
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 |
|
mean(axis)
Take the mean over the given axis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
axis
|
str
|
which axis to take the average over. |
required |
Returns:
Type | Description |
---|---|
MeshgridDataDict
|
data, averaged over |
reorder_axes(data_names=None, **pos)
Reorder the axes for all data.
This includes transposing the data, since we're on a grid.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_names
|
Union[str, Sequence[str], None]
|
Which dependents to include. if None are given, all dependents are included. |
None
|
pos
|
int
|
New axes position in the form |
{}
|
Returns:
Type | Description |
---|---|
MeshgridDataDict
|
Dataset with re-ordered axes. |
Source code in labcore/data/datadict.py
shape()
Return the shape of the meshgrid.
Returns:
Type | Description |
---|---|
Union[None, Tuple[int, ...]]
|
The shape as tuple. |
Source code in labcore/data/datadict.py
slice(**kwargs)
Return a N-d slice of the data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kwargs
|
Dict[str, Union[slice, int]]
|
slicing information in the format |
{}
|
Returns:
Type | Description |
---|---|
MeshgridDataDict
|
sliced data (as a copy) |
Source code in labcore/data/datadict.py
squeeze()
validate()
Validation of the dataset.
Performs the following checks: * All dependents must have the same axes. * All shapes need to be identical.
Returns:
Type | Description |
---|---|
bool
|
|
Source code in labcore/data/datadict.py
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 |
|
combine_datadicts(*dicts)
Try to make one datadict out of multiple.
Basic rules:
- We try to maintain the input type.
- Return type is 'downgraded' to DataDictBase if the contents are not compatible (i.e., different numbers of records in the inputs).
Returns:
Type | Description |
---|---|
Union[DataDictBase, DataDict]
|
Combined data. |
Source code in labcore/data/datadict.py
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 |
|
datadict_to_meshgrid(data, target_shape=None, inner_axis_order=None, use_existing_shape=False, copy=True)
Try to make a meshgrid from a dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
DataDict
|
Input DataDict. |
required |
target_shape
|
Union[Tuple[int, ...], None]
|
Target shape. If |
None
|
inner_axis_order
|
Union[None, Sequence[str]]
|
If axes of the datadict are not specified in the 'C' order (1st the slowest, last the fastest axis) then the 'true' inner order can be specified as a list of axes names, which has to match the specified axes in all but order. The data is then transposed to conform to the specified order. .. note:: If this is given, then |
None
|
use_existing_shape
|
bool
|
if |
False
|
copy
|
bool
|
if |
True
|
Returns:
Type | Description |
---|---|
MeshgridDataDict
|
The generated |
Source code in labcore/data/datadict.py
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 |
|
datasets_are_equal(a, b, ignore_meta=False)
Check whether two datasets are equal.
Compares type, structure, and content of all fields.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
a
|
DataDictBase
|
First dataset. |
required |
b
|
DataDictBase
|
Second dataset. |
required |
ignore_meta
|
bool
|
If |
False
|
Returns:
Type | Description |
---|---|
bool
|
|
Source code in labcore/data/datadict.py
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 |
|
datastructure_from_string(description)
Construct a DataDict from a string description.
Examples:
* "data[mV](x, y)"
results in a datadict with one dependent data
with unit mV
and
two independents, x
and y
, that do not have units.
* ``"data_1[mV](x, y); data_2[mA](x); x[mV]; y[nT]"`` results in two dependents,
one of them depening on ``x`` and ``y``, the other only on ``x``.
Note that ``x`` and ``y`` have units. We can (but do not have to) omit them when specifying
the dependencies.
* ``"data_1[mV](x[mV], y[nT]); data_2[mA](x[mV])"``. Same result as the previous example.
Rules:
We recognize descriptions of the form field1[unit1](ax1, ax2, ...); field1[unit2](...); ...
.
* Field names (like ``field1`` and ``field2`` above) have to start with a letter, and may contain
word characters.
* Field descriptors consist of the name, optional unit (presence signified by square brackets),
and optional dependencies (presence signified by round brackets).
* Dependencies (axes) are implicitly recognized as fields (and thus have the same naming restrictions as field
names).
* Axes are separated by commas.
* Axes may have a unit when specified as dependency, but besides the name, square brackets, and commas no other
characters are recognized within the round brackets that specify the dependency.
* In addition to being specified as dependency for a field,
axes may be specified also as additional field without dependency,
for instance to specify the unit (may simplify the string). For example,
``z1[x, y]; z2[x, y]; x[V]; y[V]``.
* Units may only consist of word characters.
* Use of unexpected characters will result in the ignoring the part that contains the symbol.
* The regular expression used to find field descriptors is:
``((?<=\A)|(?<=\;))[a-zA-Z]+\w*(\[\w*\])?(\(([a-zA-Z]+\w*(\[\w*\])?\,?)*\))?``
Source code in labcore/data/datadict.py
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 |
|
dd2df(dd)
make a pandas Dataframe from a datadict. Uses MultiIndex, and assumes that all data fields are compatible.
Parameters
dd : DataDict source data
Returns
DataFrame pandas DataFrame
Source code in labcore/data/datadict.py
dd2xr(dd)
makes an xarray Dataset from a MeshgridDataDict.
TODO: currently only supports 'regular' grides, i.e., all axes are independet of each other, and can be represented by 1d arrays. For each axis, the first slice is used as coordinate values.
Parameters
dd : MeshgridDataDict input data
Returns
xr.Dataset xarray Dataset
Source code in labcore/data/datadict.py
guess_shape_from_datadict(data)
Try to guess the shape of the datadict dependents from the axes values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
DataDict
|
Dataset to examine. |
required |
Returns:
Type | Description |
---|---|
Dict[str, Union[None, Tuple[List[str], Tuple[int, ...]]]]
|
A dictionary with the dependents as keys, and inferred shapes as values. Value is |
Source code in labcore/data/datadict.py
is_meta_key(key)
Checks if key
is meta information.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The |
required |
Returns:
Type | Description |
---|---|
bool
|
|
Source code in labcore/data/datadict.py
meshgrid_to_datadict(data)
Make a DataDict from a MeshgridDataDict by reshaping the data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
MeshgridDataDict
|
Input |
required |
Returns:
Type | Description |
---|---|
DataDict
|
Flattened |
Source code in labcore/data/datadict.py
meta_key_to_name(key)
Converts a meta data key to just the name.
E.g: for key
: "meta" returns "meta"
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key that is being converted |
required |
Returns:
Type | Description |
---|---|
str
|
The name of the key. |
Source code in labcore/data/datadict.py
meta_name_to_key(name)
Converts name
into a meta data key. E.g: "meta" gets converted to "meta"
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The name that is being converted. |
required |
Returns:
Type | Description |
---|---|
str
|
The meta data key based on |
Source code in labcore/data/datadict.py
Datadict Storage
plottr.data.datadict_storage
Provides file-storage tools for the DataDict class.
.. note::
Any function in this module that interacts with a ddh5 file, will create a lock file while it is using the file.
The lock file has the following format: ~
AppendMode
Bases: Enum
How/Whether to append data to existing data.
Source code in labcore/data/datadict_storage.py
DDH5Writer
Bases: object
Context manager for writing data to DDH5. Based on typical needs in taking data in an experimental physics lab.
Creates lock file when writing data.
Can be used in safe_write_mode to make sure the experiment and data will be saved even if the ddh5 is being used by other programs. In this mode, the data is individually saved in files in a .tmp folder. When the experiment is finished, the data is unified and saved in the original file. If the data is correctly reconstructed, the .tmp folder is deleted. If not you can use the function unify_safe_write_data to reconstruct the data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
basedir
|
Union[str, Path]
|
The root directory in which data is stored. :meth: |
'.'
|
datadict
|
DataDict
|
Initial data object. Must contain at least the structure of the data to be able to use :meth: |
required |
groupname
|
str
|
Name of the top-level group in the file container. An existing group of that name will be deleted. |
'data'
|
name
|
Optional[str]
|
Name of this dataset. Used in path/file creation and added as meta data. |
None
|
filename
|
str
|
Filename to use. Defaults to 'data.ddh5'. |
'data'
|
file_timeout
|
Optional[float]
|
How long the function will wait for the ddh5 file to unlock. If none uses the default value from the :class: |
None
|
safe_write_mode
|
Optional[bool]
|
If True, will save the data in the safe writing mode. Defaults to False. |
False
|
Source code in labcore/data/datadict_storage.py
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 |
|
__init__(datadict, basedir='.', groupname='data', name=None, filename='data', filepath=None, file_timeout=None, safe_write_mode=False)
Constructor for :class:.DDH5Writer
Source code in labcore/data/datadict_storage.py
add_data(**kwargs)
Add data to the file (and the internal DataDict
).
Requires one keyword argument per data field in the DataDict
, with
the key being the name, and value the data to add. It is required that
all added data has the same number of 'rows', i.e., the most outer dimension
has to match for data to be inserted faithfully.
If some data is scalar and others are not, then the data should be reshaped
to (1, ) for the scalar data, and (1, ...) for the others; in other words,
an outer dimension with length 1 is added for all.
Source code in labcore/data/datadict_storage.py
data_file_path()
Determine the filepath of the data file.
Returns:
Type | Description |
---|---|
Path
|
The filepath of the data file. |
Source code in labcore/data/datadict_storage.py
data_folder()
Return the folder, relative to the data root path, in which data will be saved.
Default format:
<basedir>/YYYY-MM-DD/YYYY-mm-ddTHHMMSS_<ID>-<name>
.
In this implementation we use the first 8 characters of a UUID as ID.
Returns:
Type | Description |
---|---|
Path
|
The folder path. |
Source code in labcore/data/datadict_storage.py
FileOpener
Context manager for opening files, creates its own file lock to indicate other programs that the file is being
used. The lock file follows the following structure: "~
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
Union[Path, str]
|
The file path. |
required |
mode
|
str
|
The opening file mode. Only the following modes are supported: 'r', 'w', 'w-', 'a'. Defaults to 'r'. |
'r'
|
timeout
|
Optional[float]
|
Time, in seconds, the context manager waits for the file to unlock. Defaults to 30. |
None
|
test_delay
|
float
|
Length of time in between checks. I.e. how long the FileOpener waits to see if a file got unlocked again |
0.1
|
Source code in labcore/data/datadict_storage.py
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 |
|
add_cur_time_attr(h5obj, name='creation', prefix='__', suffix='__')
Add current time information to the given HDF5 object, following the format of:
<prefix><name>_time_sec<suffix>
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
h5obj
|
Any
|
The HDF5 object. |
required |
name
|
str
|
The name of the attribute. |
'creation'
|
prefix
|
str
|
Prefix of the attribute. |
'__'
|
suffix
|
str
|
Suffix of the attribute. |
'__'
|
Source code in labcore/data/datadict_storage.py
all_datadicts_from_hdf5(path, file_timeout=None, **kwargs)
Loads all the DataDicts contained on a single HDF5 file. Returns a dictionary with the group names as keys and the DataDicts as the values of that key.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
Union[str, Path]
|
The path of the HDF5 file. |
required |
file_timeout
|
Optional[float]
|
How long the function will wait for the ddh5 file to unlock. If none uses the default value from the :class: |
None
|
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dictionary with group names as key, and the DataDicts inside them as values. |
Source code in labcore/data/datadict_storage.py
datadict_from_hdf5(path, groupname='data', startidx=None, stopidx=None, structure_only=False, ignore_unequal_lengths=True, file_timeout=None)
Load a DataDict from file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
Union[str, Path]
|
Full filepath without the file extension. |
required |
groupname
|
str
|
Name of hdf5 group. |
'data'
|
startidx
|
Union[int, None]
|
Start row. |
None
|
stopidx
|
Union[int, None]
|
End row + 1. |
None
|
structure_only
|
bool
|
If |
False
|
ignore_unequal_lengths
|
bool
|
If |
True
|
file_timeout
|
Optional[float]
|
How long the function will wait for the ddh5 file to unlock. If none uses the default value from the :class: |
None
|
Returns:
Type | Description |
---|---|
DataDict
|
Validated DataDict. |
Source code in labcore/data/datadict_storage.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 |
|
datadict_to_hdf5(datadict, path, groupname='data', append_mode=AppendMode.new, file_timeout=None)
Write a DataDict to DDH5
Note: Meta data is only written during initial writing of the dataset. If we're appending to existing datasets, we're not setting meta data anymore.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
datadict
|
DataDict
|
Datadict to write to disk. |
required |
path
|
Union[str, Path]
|
Path of the file (extension may be omitted). |
required |
groupname
|
str
|
Name of the top level group to store the data in. |
'data'
|
append_mode
|
AppendMode
|
|
new
|
file_timeout
|
Optional[float]
|
How long the function will wait for the ddh5 file to unlock. Only relevant if you are writing to a file that already exists and some other program is trying to read it at the same time. If none uses the default value from the :class: |
None
|
Source code in labcore/data/datadict_storage.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
|
deh5ify(obj)
Convert slightly mangled types back to more handy ones.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
Input object. |
required |
Returns:
Type | Description |
---|---|
Any
|
Object |
Source code in labcore/data/datadict_storage.py
h5ify(obj)
Convert an object into something that we can assign to an HDF5 attribute.
Performs the following conversions: - list/array of strings -> numpy chararray of unicode type
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
Input object. |
required |
Returns:
Type | Description |
---|---|
Any
|
Object, converted if necessary. |
Source code in labcore/data/datadict_storage.py
load_as_xr(folder, fn='data.ddh5', fields=None)
Load ddh5 data as xarray (only for gridable data).
Parameters
folder : data folder fn : str, optional filename, by default 'data.ddh5'
Returns
type description
Source code in labcore/data/datadict_storage.py
reconstruct_safe_write_data(path, unification_from_scratch=True, file_timeout=None)
Creates a new DataDict from the data saved in the .tmp folder. This is used when the data is saved in the safe writing mode. The data is saved in individual files in the .tmp folder. This function reconstructs the data from these files and returns a DataDict with the data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
Union[str, Path]
|
The path to the folder containing the .tmp path |
required |
unification_from_scratch
|
bool
|
If True, will reconstruct the data from scratch. If False, will try to load the data from the last reconstructed file. |
True
|
file_timeout
|
Optional[float]
|
How long the function will wait for the ddh5 file to unlock. If none uses the default value |
None
|
Source code in labcore/data/datadict_storage.py
set_attr(h5obj, name, val)
Set attribute name
of object h5obj
to val
Use :func:h5ify
to convert the object, then try to set the attribute
to the returned value. If that does not succeed due to a HDF5 typing
restriction, set the attribute to the string representation of the value.
Source code in labcore/data/datadict_storage.py
timestamp_from_path(p)
Return a datetime
timestamp from a standard-formatted path.
Assumes that the path stem has a timestamp that begins in ISO-like format
YYYY-mm-ddTHHMMSS
.
Source code in labcore/data/datadict_storage.py
Extra Tools
Data = Union[xr.Dataset, pd.DataFrame]
module-attribute
Type alias for valid data. Can be either a pandas DataFrame or an xarray Dataset.
split_complex(data)
Split complex dependents into real and imaginary parts.
TODO: should update units as well
Parameters
data input data.
Returns
data with complex dependents split into real and imaginary parts.
Raises
NotImplementedError if data is not a pandas DataFrame or an xarray Dataset.