landlab.data_record.data_record

class DataRecord[source]

Bases: object

Data structure to store variables in time and/or space dimensions.

This class uses a xarray Dataset to store variables. This datastructure is located at the property dataset. The DataRecord expands xarray Dataset with additional attributes and functions, including the ability to aggregate values on Landlab grid elements.

DataRecord uses the concept of an “item”, a physical thing that is located on the grid and has some properties, stored as variables. DataRecord tracks variables through time, variables associated with a Landlab grid across items, or both.

Thus data variables can vary along one or both of the following dimensions:

  • time (model time)

  • item_id: variables can characterize a set of items (each identified by an individual id) that reside on the grid.

If an item or set of items is defined, each item must be defined by the grid element and the element id at which it resides, e.g.:

grid_element = ‘node’ element_id = 9.

When items are defined, each item is given a unique id and the underlying Dataset uses a dimension “item_id”. Items are assigned ids beginning with 0 followed by consecutively increasing integers.

Examples:

  • the variable ‘mean_elevation’ characterizes the grid and varies with time,

  • the variable ‘clast__rock_type’ characterizes a set of items (clasts) and varies with item_id,

  • the variable ‘clast__size’ can vary with both time and item_id

In the above case, grid_element and element_id are default data variables (in addition to any user-specified variables).

For each item, element_id must be less than the number of this item’s grid_element that exist on the grid or be one of the dummy element values. For example, if the grid has 100 links, and no dummy link values are indicated, then, no item can live at link 100 or link -3 because only links 0 to 99 exist in this example.

Anything that the DataRecord keeps track of is considered a “record”, whether it uses one or both of the two standard dimensions (time and item_id).

DataRecord provides two method to assist with adding new records. The method add_item should be used when no new variables are being added. The method add_record should be used when new variables are being added or when a variable is only tracked over the time dimension.

Parameters:
  • grid (ModelGrid)

  • dummy_elements (dict) – Dictionary indicating valid values for dummy grid elements. For example, if you need an “exit” off of a grid with 100 links, you could indicate dummy_elements = {“link”: [9999]} to set a link id of 9999 as a dummy link. Multiple dummy elements are possible and we recommend using values larger than the number of grid elements for the dummy values.

  • time (list or 1-D array of float or int (optional)) – The initial time(s) to add to the record. A time dimension is not created if the value is ‘None’ (default).

  • items (dict (optional)) –

    Generic items that live on grid elements. No item is created if the value is ‘None’ (default). Otherwise, dictionary describes the position of generic items on the grid. The structure is:

    {"grid_element": [grid_element], "element_id": [element_id]}
    

    where:

    • [grid_element] is a str or number-of-items-long array containing strings of the grid element(s) on which the items live. Valid locations depend on the grid type. If provided as a string it is assumed that all items live on the same type of grid element.

    • [element_id] is an array of integers identifying the grid element ID on which each item resides.

    An example argument would be:

    {
        "grid_element": numpy.array(["node"], ["node"], ["link"]),
        "element_id": numpy.array([1], [5], [1]),
    }
    

  • data_vars (dict (optional)) –

    Dictionary of the data variables to be recorded. The structure is:

    {
        "variable_name_1": (["dimensions"], variable_data_1),
        "variable_name_2": (["dimensions"], variable_data_2),
    }
    

    where:

    • ’variable_name…’ is a string of the variable name (label)

    • [‘dimensions’] is the dimension(s) over which the variable exists: can be [‘time’], [‘item_id’] or [‘item_id’, ‘time’].

    • variable_data is an array containing the data, its size must match that of the variable dimension(s).

  • attrs (dict (optional)) – Dictionary of global attributes on the DataRecord (metadata). Example: {‘time_units’ : ‘y’}

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> from landlab.data_record import DataRecord
>>> grid = RasterModelGrid((3, 3))

Example of a DataRecord with time as the only dimension:

>>> dr1 = DataRecord(
...     grid,
...     time=[0.0],
...     data_vars={"mean_elevation": (["time"], np.array([100]))},
...     attrs={"time_units": "y"},
... )

DataRecord builds off of xarray Dataset, a multi-dimensional, in memory, array database. Dataset implements the mapping interface with keys given by variable names and values given by DataArray objects for each variable name.

A DataRecord can have dimensions ‘time’ and/or ‘item_id’.

The xarray Dataset is stored in the public attribute dataset.

Coordinates are one dimensional arrays used for label-based indexing. DataRecord inherits all the methods and attributes from xarray.Dataset.

>>> dr1.dataset.to_dataframe()
      mean_elevation
time
0.0              100
>>> dr1.dataset.time.values
array([0.])
>>> dr1.variable_names
['mean_elevation']
>>> dr1.dataset["mean_elevation"].values
array([100])
>>> list(dr1.dataset.attrs.items())
[('time_units', 'y')]
>>> list(dr1.dataset.attrs.items())
[('time_units', 'y')]

Example of a DataRecord with item_id as the only dimension:

>>> my_items2 = {
...     "grid_element": np.array(("node", "link"), dtype=str),
...     "element_id": np.array([1, 3]),
... }
>>> dr2 = DataRecord(grid, items=my_items2)

Note that both arrays (grid_element and element_id) have 1 dimension as they only vary along the dimension ‘item_id’.

>>> dr2.dataset.to_dataframe()[["grid_element", "element_id"]]
        grid_element  element_id
item_id
0               node           1
1               link           3

Example of a DataRecord with dimensions time and item_id:

>>> my_items3 = {
...     "grid_element": np.array([["node"], ["link"]]),
...     "element_id": np.array([[1], [3]]),
... }
>>> dr3 = DataRecord(grid, time=[0.0], items=my_items3)

Note that both arrays have 2 dimensions as they vary along dimensions ‘time’ and ‘item_id’.

>>> dr3.dataset.to_dataframe()[["grid_element", "element_id"]]
             grid_element  element_id
item_id time
0       0.0          node           1
1       0.0          link           3
__init__(grid, dummy_elements=None, time=None, items=None, data_vars=None, attrs=None)[source]
Parameters:
  • grid (ModelGrid)

  • dummy_elements (dict) – Dictionary indicating valid values for dummy grid elements. For example, if you need an “exit” off of a grid with 100 links, you could indicate dummy_elements = {“link”: [9999]} to set a link id of 9999 as a dummy link. Multiple dummy elements are possible and we recommend using values larger than the number of grid elements for the dummy values.

  • time (list or 1-D array of float or int (optional)) – The initial time(s) to add to the record. A time dimension is not created if the value is ‘None’ (default).

  • items (dict (optional)) –

    Generic items that live on grid elements. No item is created if the value is ‘None’ (default). Otherwise, dictionary describes the position of generic items on the grid. The structure is:

    {"grid_element": [grid_element], "element_id": [element_id]}
    

    where:

    • [grid_element] is a str or number-of-items-long array containing strings of the grid element(s) on which the items live. Valid locations depend on the grid type. If provided as a string it is assumed that all items live on the same type of grid element.

    • [element_id] is an array of integers identifying the grid element ID on which each item resides.

    An example argument would be:

    {
        "grid_element": numpy.array(["node"], ["node"], ["link"]),
        "element_id": numpy.array([1], [5], [1]),
    }
    

  • data_vars (dict (optional)) –

    Dictionary of the data variables to be recorded. The structure is:

    {
        "variable_name_1": (["dimensions"], variable_data_1),
        "variable_name_2": (["dimensions"], variable_data_2),
    }
    

    where:

    • ’variable_name…’ is a string of the variable name (label)

    • [‘dimensions’] is the dimension(s) over which the variable exists: can be [‘time’], [‘item_id’] or [‘item_id’, ‘time’].

    • variable_data is an array containing the data, its size must match that of the variable dimension(s).

  • attrs (dict (optional)) – Dictionary of global attributes on the DataRecord (metadata). Example: {‘time_units’ : ‘y’}

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> from landlab.data_record import DataRecord
>>> grid = RasterModelGrid((3, 3))

Example of a DataRecord with time as the only dimension:

>>> dr1 = DataRecord(
...     grid,
...     time=[0.0],
...     data_vars={"mean_elevation": (["time"], np.array([100]))},
...     attrs={"time_units": "y"},
... )

DataRecord builds off of xarray Dataset, a multi-dimensional, in memory, array database. Dataset implements the mapping interface with keys given by variable names and values given by DataArray objects for each variable name.

A DataRecord can have dimensions ‘time’ and/or ‘item_id’.

The xarray Dataset is stored in the public attribute dataset.

Coordinates are one dimensional arrays used for label-based indexing. DataRecord inherits all the methods and attributes from xarray.Dataset.

>>> dr1.dataset.to_dataframe()
      mean_elevation
time
0.0              100
>>> dr1.dataset.time.values
array([0.])
>>> dr1.variable_names
['mean_elevation']
>>> dr1.dataset["mean_elevation"].values
array([100])
>>> list(dr1.dataset.attrs.items())
[('time_units', 'y')]
>>> list(dr1.dataset.attrs.items())
[('time_units', 'y')]

Example of a DataRecord with item_id as the only dimension:

>>> my_items2 = {
...     "grid_element": np.array(("node", "link"), dtype=str),
...     "element_id": np.array([1, 3]),
... }
>>> dr2 = DataRecord(grid, items=my_items2)

Note that both arrays (grid_element and element_id) have 1 dimension as they only vary along the dimension ‘item_id’.

>>> dr2.dataset.to_dataframe()[["grid_element", "element_id"]]
        grid_element  element_id
item_id
0               node           1
1               link           3

Example of a DataRecord with dimensions time and item_id:

>>> my_items3 = {
...     "grid_element": np.array([["node"], ["link"]]),
...     "element_id": np.array([[1], [3]]),
... }
>>> dr3 = DataRecord(grid, time=[0.0], items=my_items3)

Note that both arrays have 2 dimensions as they vary along dimensions ‘time’ and ‘item_id’.

>>> dr3.dataset.to_dataframe()[["grid_element", "element_id"]]
             grid_element  element_id
item_id time
0       0.0          node           1
1       0.0          link           3
classmethod __new__(*args, **kwargs)
add_item(time=None, new_item=None, new_item_spec=None)[source]

Add new items to a DataRecord.

Parameters:
  • time (array_like of number, optional) – Time coordinate(s) for the new items. Required if this DataRecord has a time dimension and must be None otherwise.

  • new_item (mapping) – Mapping that defines the new items. Must contain the keys "grid_element" and "element_id".

  • new_item_spec (mapping, optional) – Additional variables to add for the new items, in xarray-style {name: (dims, values)} form.

Return type:

None

Notes

New items are assigned consecutive item_id values. For time-dependent records, grid_element and element_id are broadcast over the new item_id and time coordinates as needed before merging into the underlying dataset.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> from landlab.data_record import DataRecord

Create a time-independent DataRecord with two items:

>>> grid = RasterModelGrid((3, 3))
>>> items = {
...     "grid_element": ["node", "node"],
...     "element_id": [1, 3],
... }
>>> dr = DataRecord(grid, items=items)

Add two new items:

>>> dr.add_item(
...     new_item={
...         "grid_element": ["node", "node"],
...         "element_id": [4, 5],
...     }
... )
>>> dr.number_of_items
4

Create a time-dependent DataRecord with one time coordinate:

>>> items = {
...     "grid_element": np.array([["node"], ["link"]]),
...     "element_id": np.array([[1], [3]]),
... }
>>> dr = DataRecord(grid, time=[0.0], items=items)

Add two new items at a new time:

>>> dr.add_item(
...     time=[1.0],
...     new_item={
...         "grid_element": [["node"], ["node"]],
...         "element_id": [[4], [5]],
...     },
...     new_item_spec={
...         "size": (["item_id", "time"], [[10], [5]]),
...     },
... )
>>> dr.number_of_items
4

The time coordinate is extended:

>>> dr.time_coordinates
[0.0, 1.0]

Values for a new variable are defined only for the new items at the new time:

>>> dr.dataset["size"][:, 1].values
array([nan, nan, 10.,  5.])
add_record(time=None, item_id=None, new_item_loc=None, new_record=None)[source]

Add data to the DataRecord.

Append new values to existing variables in the DataRecord, optionally at specified time and/or item_id coordinates. It can also update the location of existing items.

Parameters:
  • time (array_like of float or int, optional) – Time(s) at which to add data. Must be one-dimensional and strictly increasing. Required if the DataRecord has a time dimension and new_item_loc is provided. Must be None for time-independent DataRecords.

  • item_id (array_like of int, optional) – IDs of existing items to update. Must be one-dimensional. All values must already exist in the DataRecord. Use add_item to create new items.

  • new_item_loc (dict, optional) – Mapping with keys "grid_element" and "element_id" specifying updated locations for items. Both time and item_id must be provided when using this argument.

  • new_record (dict, optional) – Mapping of variable names to values to add. Values should be compatible with the dimensions implied by time and/or item_id.

Return type:

None

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> from landlab.data_record import DataRecord
>>> grid = RasterModelGrid((3, 3))

Example of a DataRecord with dimensions time and item_id:

>>> items = {
...     "grid_element": [["node"], ["link"]],
...     "element_id": [[1], [3]],
... }

Note that both arrays have 2 dimensions as they vary along dimensions ‘time’ and ‘item_id’.

>>> dr = DataRecord(grid, time=0.0, items=items)

Records relating to pre-existing items can be added to the DataRecord using the method ‘add_record’:

>>> dr.add_record(
...     time=2.0,
...     item_id=0,
...     new_item_loc={
...         "grid_element": [["node"]],
...         "element_id": [[6]],
...     },
...     new_record={"item_size": (["item_id", "time"], [[0.2]])},
... )
>>> dr.dataset["element_id"].values
array([[ 1.,  6.],
       [ 3., nan]])
>>> dr.get_data([2.0], [0], "item_size")
array([0.2])

The ‘add_record’ method can also be used to add a non item-related record:

>>> dr.add_record(time=50.0, new_record={"mean_elev": (("time",), [110])})
>>> dr.dataset["mean_elev"].to_dataframe()
      mean_elev
time
0.0         NaN
2.0         NaN
50.0      110.0
calc_aggregate_value(func, data_variable, at='node', filter_array=None, fill_value=nan, args=(), **kwargs)[source]

Apply a function to a variable aggregated at grid elements.

Parameters:
  • func (function) – Function to apply to be aggregated.

  • data_variable (str) – Name of variable on which to apply the function.

  • at (str, optional) – Name of grid element at which to apply the function. Default is “node”.

  • filter_array (boolean array with dimensions matching that of the) – DataRecord (optional) Array to filter the DataRecord before aggregation.

  • fill_value (float) – Fill value for array. Default is np.nan.

  • args (tuple (optional)) – Additional positional arguments to pass to the function.

  • **kwargs (key value pairs (optional)) – Additional keyword arguments to pass to func.

Returns:

out – Array of size number-of-grid_elements (grid_elements is the group passed as ‘at’ argument).

Return type:

ndarray

Examples

>>> import numpy as np
>>> from landlab.data_record import DataRecord
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 3))
>>> element_id = [0, 0, 0, 0, 1, 2, 3, 4, 5, 9999]
>>> volumes = [4, 5, 1, 2, 3, 4, 5, 6, 7, 1234]
>>> ages = [10, 11, 12, 13, 14, 15, 16, 8, 10, 3456]
>>> grid_element = "node"
>>> data = {"ages": ages, "volumes": volumes}
>>> dr = DataRecord(
...     grid,
...     dummy_elements={"node": [9999]},
...     items={"grid_element": "node", "element_id": np.array(element_id)},
...     data_vars={
...         "ages": (["item_id"], np.array(ages)),
...         "volumes": (["item_id"], np.array(volumes)),
...     },
... )
>>> s = dr.calc_aggregate_value(func=xr.Dataset.sum, data_variable="ages")
>>> s
array([46., 14., 15., 16.,  8., 10., nan, nan, nan])
>>> len(s) == grid.number_of_nodes
True

If you want to first filter the DataRecord and then aggregate, first create a filter array with dimensions matching that of the DataRecord and has True for entries that should be retained and False for entries that should be ignored.

For example, if we wanted to aggregate volume for items with an age greater than 10 we would to the following:

>>> f = dr.dataset["ages"] > 10.0
>>> v_f = dr.calc_aggregate_value(
...     func=xr.Dataset.sum, data_variable="volumes", filter_array=f
... )
>>> v_f
array([ 8.,  3.,  4.,  5., nan, nan, nan, nan, nan])

If we wanted the value for elements with no volume to be zero instead of np.nan we could use the keyword argument fill_value.

>>> f = dr.dataset["ages"] > 10.0
>>> v_f = dr.calc_aggregate_value(
...     func=xr.Dataset.sum,
...     data_variable="volumes",
...     filter_array=f,
...     fill_value=0.0,
... )
>>> v_f
array([8., 3., 4., 5., 0., 0., 0., 0., 0.])

An array of fill_value is returned when filter_array is all False (np.nan is the default value).

>>> f = dr.dataset["ages"] > 4000.0
>>> v_f = dr.calc_aggregate_value(
...     func=xr.Dataset.sum, data_variable="volumes", filter_array=f
... )
>>> v_f
array([nan, nan, nan, nan, nan, nan, nan, nan, nan])

Other values can be specified for fill_value.

>>> f = dr.dataset["ages"] > 4000.0
>>> v_f = dr.calc_aggregate_value(
...     func=xr.Dataset.sum,
...     data_variable="volumes",
...     filter_array=f,
...     fill_value=0.0,
... )
>>> v_f
array([0., 0., 0., 0., 0., 0., 0., 0., 0.])
property dataset

The xarray Dataset that serves as the core datastructure.

property earliest_time

Return the earliest time coordinate in the DataRecord.

ffill_grid_element_and_id()[source]

Fill NaN values of the fields ‘grid_element’ and ‘element_id’.

Fields are filled by propagating values forward in time.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> from landlab.data_record import DataRecord
>>> grid = RasterModelGrid((3, 3))

Example of a DataRecord with dimensions time and item_id:

>>> my_items3 = {
...     "grid_element": np.array([["node"], ["link"]]),
...     "element_id": np.array([[1], [3]]),
... }

Note that both arrays have 2 dimensions as they vary along dimensions ‘time’ and ‘item_id’.

>>> dr3 = DataRecord(grid, time=[0.0], items=my_items3)

Records relating to pre-existing items can be added to the DataRecord using the method ‘add_record’:

>>> dr3.add_record(
...     time=[2.0, 3.0],
...     new_record={"mean_elevation": (["time"], np.array([200.0, 250.0]))},
... )

Adding this data record created two new time coordinates. The grid_element and element_id of the items has been filled with ‘nan’ for these time coordinates.

>>> dr3.dataset["grid_element"].values
array([['node', nan, nan],
       ['link', nan, nan]], dtype=object)
>>> dr3.dataset["element_id"].values
array([[ 1., nan, nan],
       [ 3., nan, nan]])

To fill these values with the last valid value, use the method ffill_grid_element_and_id:

>>> dr3.ffill_grid_element_and_id()
>>> dr3.dataset["grid_element"].values
array([['node', 'node', 'node'],
       ['link', 'link', 'link']], dtype=object)
>>> dr3.dataset["element_id"].values
array([[1., 1., 1.],
       [3., 3., 3.]])

In some applications, there may be no prior valid value. Under these circumstances, those values will stay as NaN. That is, this only forward fills, and does not backfill.

>>> my_items3 = {
...     "grid_element": np.array([["node"], ["link"]]),
...     "element_id": np.array([[1], [3]]),
... }
>>> dr3 = DataRecord(grid, time=[0.0], items=my_items3)
>>> dr3.dataset["element_id"].values
array([[1], [3]])
>>> dr3.dataset["grid_element"].values
array([['node'], ['link']], dtype='<U6')

Next add some new items at a new time.

>>> dr3.add_item(
...     time=[1.0],
...     new_item={
...         "grid_element": np.array([["node"], ["node"]]),
...         "element_id": np.array([[4], [4]]),
...     },
...     new_item_spec={"size": (["item_id", "time"], [[10], [5]])},
... )

Two items have been added at a new timestep 1.0:

>>> dr3.number_of_items
4
>>> dr3.time_coordinates
[0.0, 1.0]
>>> dr3.dataset["element_id"].values
array([[ 1., nan],
       [ 3., nan],
       [nan,  4.],
       [nan,  4.]])
>>> dr3.dataset["grid_element"].values
array([['node', nan],
       ['link', nan],
       [nan, 'node'],
       [nan, 'node']], dtype=object)

We expect that the NaN’s to the left of the 4.s will stay NaN. And they do.

>>> dr3.ffill_grid_element_and_id()
>>> dr3.dataset["element_id"].values
array([[ 1.,  1.],
       [ 3.,  3.],
       [nan,  4.],
       [nan,  4.]])
>>> dr3.dataset["grid_element"].values
array([['node', 'node'],
       ['link', 'link'],
       [nan, 'node'],
       [nan, 'node']], dtype=object)

Finally, if we add a new time, we see that we need to fill in the full time column.

>>> dr3.add_record(time=[2])
>>> dr3.dataset["element_id"].values
array([[ 1.,  1., nan],
       [ 3.,  3., nan],
       [nan,  4., nan],
       [nan,  4., nan]])
>>> dr3.dataset["grid_element"].values
array([['node', 'node', nan],
       ['link', 'link', nan],
       [nan, 'node', nan],
       [nan, 'node', nan]], dtype=object)

And that forward filling fills everything as expected.

>>> dr3.ffill_grid_element_and_id()
>>> dr3.dataset["element_id"].values
array([[ 1.,  1.,  1.],
       [ 3.,  3.,  3.],
       [nan,  4.,  4.],
       [nan,  4.,  4.]])
>>> dr3.dataset["grid_element"].values
array([['node', 'node', 'node'],
       ['link', 'link', 'link'],
       [nan, 'node', 'node'],
       [nan, 'node', 'node']], dtype=object)
get_data(time=None, item_id=None, data_variable=None)[source]

Return values of a variable at a given time and/or for selected items.

Parameters:
  • time (array_like of float or int, optional) – Time coordinate to select. Must be length 1 if provided.

  • item_id (array_like of int, optional) – Indices of items to select.

  • data_variable (str) – Name of the variable to retrieve.

Returns:

Values of data_variable after applying any provided selections. The shape depends on the dimensions of the variable and the selections applied.

Return type:

ndarray

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> from landlab.data_record import DataRecord
>>> grid = RasterModelGrid((3, 3))
>>> items = {
...     "grid_element": "node",
...     "element_id": np.array([[1], [3], [3], [7]]),
... }
>>> data = {
...     "item_size": (
...         ["item_id", "time"],
...         np.array([[0.3], [0.4], [0.8], [0.4]]),
...     )
... }
>>> dr = DataRecord(grid, time=[50.0], items=items, data_vars=data)

Select by time and item_id: >>> dr.get_data(time=[50.0], item_id=[2], data_variable=”element_id”) array([3])

Select all items at a time: >>> dr.get_data(time=[50.0], data_variable=”item_size”) array([0.3, 0.4, 0.8, 0.4])

Select items without time: >>> dr.get_data(item_id=[1, 2], data_variable=”grid_element”) array([[‘node’], [‘node’]], dtype=’<U6’)

property item_coordinates

Return a list of the item_id coordinates in the DataRecord.

property latest_time

Return the latest time coordinate in the DataRecord.

property number_of_items

Return the number of items in the DataRecord.

property number_of_timesteps

Return the number of time steps in the DataRecord.

property prior_time

Return the penultimate time coordinate in the DataRecord.

set_data(time=None, item_id=None, data_variable=None, new_value=nan)[source]

Set a variable value at a model time and/or an item to a new value.

The value of only one variable can be changed at a time using this method.

Parameters:
  • time (list or 1-D array of float or int) – The time coordinate of the record to set.

  • item_id (list or 1-D array of int) – The item id of the record to set.

  • data_variable (string) – The label of the variable to set.

  • new_value (list or 1-D array) – The new value to give to the variable data.

Return type:

DataRecord with updated data.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> from landlab.data_record import DataRecord
>>> grid = RasterModelGrid((3, 3))

Example of a DataRecord with dimensions time and item_id:

>>> my_items4 = {
...     "grid_element": "node",
...     "element_id": np.array([[1], [3], [3], [7]]),
... }

Note that both arrays have 2 dimensions as they vary along dimensions ‘time’ and ‘item_id’.

>>> my_data4 = {
...     "item_size": (
...         ["item_id", "time"],
...         np.array([[0.3], [0.4], [0.8], [0.4]]),
...     )
... }
>>> dr4 = DataRecord(grid, time=[50.0], items=my_items4, data_vars=my_data4)
>>> dr4.dataset["item_size"].values
array([[0.3],
       [0.4],
       [0.8],
       [0.4]])
>>> dr4.set_data([50.0], [2], "item_size", [0.5])
>>> dr4.dataset["item_size"].values
array([[0.3],
       [0.4],
       [0.5],
       [0.4]])
property time_coordinates

Return a list of the time coordinates in the DataRecord.

property variable_names

Return the name(s) of the data variable(s) in the record as a list.

norm_element_id(ids)[source]

Normalize element IDs to a 1-D array of np.intp.

Parameters:

ids (array_like) – Element IDs.

Returns:

Normalized element IDs with dtype np.intp.

Return type:

ndarray of intp, shape (n_ids,)

Raises:

ValueError – If ids cannot be safely interpreted as integers.

Examples

>>> norm_element_id([0, 1, 2])
array([0, 1, 2])
>>> norm_element_id(5)
array([5])
>>> ids = norm_element_id(np.array([1, 2], dtype=np.int32))
>>> ids.dtype == np.intp
True
norm_grid_element(elements, *, allowed=())[source]

Normalize grid element names to a NumPy string array.

Parameters:
  • elements (array_like of str or str) – Grid element name(s). A scalar string is treated as a single-element array.

  • allowed (iterable of str, optional) – Valid grid element names. If provided, all values in elements must be contained in allowed.

Returns:

Normalized grid element names.

Return type:

ndarray of str, shape (n_elements,)

Raises:

ValueError – If any value in elements is not in allowed.

Examples

>>> norm_grid_element("node")
array(['node'], dtype='<U4')
>>> norm_grid_element(["node", "link"])
array(['node', 'link'], dtype='<U4')
>>> norm_grid_element(["node", "link"], allowed=["node", "link", "patch"])
array(['node', 'link'], dtype='<U5')