Slicing

Objects in scipp can be sliced in two ways. The general way to do this is by positional indexing using indices as in numpy. A second approach is to use label-based indexing which is uses actual coordinate values for selection.

Positional indexing

Overview

Data in a variable, data array, or dataset can be indexed in a similar manner to NumPy and xarray. The dimension to be sliced is specified using a dimension label and, in contrast to NumPy, positional dimension lookup is not available. Positional indexing with an integer or an integer range is made via __getitem__ and __setitem__ with a dimension label as first argument. This is available for variables, data arrays, and datasets. In all cases a view is returned, i.e., just like when slicing a numpy.ndarray no copy is performed.

Variables

Consider the following variable:

[1]:
import numpy as np
import scipp as sc

var = sc.array(
    dims=['z', 'y', 'x'],
    values=np.random.rand(2, 3, 4),
    variances=np.random.rand(2, 3, 4))
sc.show(var)
dims=['z', 'y', 'x'], shape=[2, 3, 4], unit=dimensionless, variances=Truevariances z yxvalues z yx

As when slicing a numpy.ndarray, the dimension 'x' is removed since no range is specified:

[2]:
s = var['x', 1]
sc.show(s)
print(s.dims, s.shape)
dims=['z', 'y'], shape=[2, 3], unit=dimensionless, variances=Truevariances zyvalues zy
['z', 'y'] [2, 3]

When a range is specified, the dimension is kept, even if it has extent 1:

[3]:
s = var['x', 1:3]
sc.show(s)
print(s.dims, s.shape)

s = var['x', 1:2]
sc.show(s)
print(s.dims, s.shape)
dims=['z', 'y', 'x'], shape=[2, 3, 2], unit=dimensionless, variances=Truevariances z yxvalues z yx
['z', 'y', 'x'] [2, 3, 2]
dims=['z', 'y', 'x'], shape=[2, 3, 1], unit=dimensionless, variances=Truevariances z yxvalues z yx
['z', 'y', 'x'] [2, 3, 1]

Slicing can be chained arbitrarily:

[4]:
s = var['x', 1:4]['y', 2]['x', 1]
sc.show(s)
print(s.dims, s.shape)
dims=['z'], shape=[2], unit=dimensionless, variances=Truevariances zvalues z
['z'] [2]

The copy() method turns a view obtained from a slice into an independent object:`

[5]:
s = var['x', 1:2].copy()
s += 1000
var
[5]:
Show/Hide data repr Show/Hide attributes
scipp.Variable (384 Bytes)
    • (z: 2, y: 3, x: 4)
      float64
      0.64, 0.03, ..., 0.77, 0.82
      σ = 0.87, 0.21, ..., 0.74, 0.46
      Values:
      array([[[0.63948821, 0.03011472, 0.88713544, 0.37193582], [0.26863327, 0.98277467, 0.35434391, 0.76449566], [0.03615586, 0.76663774, 0.24276739, 0.19384297]], [[0.01005317, 0.38353297, 0.20163522, 0.37767172], [0.27202752, 0.70531149, 0.72985613, 0.38601022], [0.8098249 , 0.80012802, 0.76912284, 0.82170242]]])

      Variances (σ²):
      array([[[0.75148356, 0.04230335, 0.14962838, 0.75480981], [0.51506962, 0.28043353, 0.5412437 , 0.03925559], [0.56732836, 0.20224279, 0.37117503, 0.62630786]], [[0.28089276, 0.80068855, 0.61422433, 0.46709733], [0.03774234, 0.774675 , 0.35697738, 0.69073051], [0.13241331, 0.46727899, 0.54201423, 0.21029939]]])

Data arrays

Slicing for data arrays works in the same way, but some additional rules apply. Consider:

[6]:
a = sc.DataArray(
    data=sc.array(dims=['y', 'x'], values=np.random.rand(2, 3)),
    coords={
        'x': sc.array(dims=['x'], values=np.arange(3.0), unit=sc.units.m),
        'y': sc.array(dims=['y'], values=np.arange(2.0), unit=sc.units.m)},
    masks={
        'mask': sc.array(dims=['x'], values=[True, False, False])},
    attrs={
        'aux_x': sc.array(dims=['x'], values=np.arange(3.0), unit=sc.units.m),
        'aux_y': sc.array(dims=['y'], values=np.arange(2.0), unit=sc.units.m)})
sc.show(a)
a
(dims=['y', 'x'], shape=[2, 3], unit=dimensionless, variances=False)values yx aux_yaux_y(dims=['y'], shape=[2], unit=m, variances=False)values y yy(dims=['y'], shape=[2], unit=m, variances=False)values y xx(dims=['x'], shape=[3], unit=m, variances=False)values x maskmask(dims=['x'], shape=[3], unit=dimensionless, variances=False)values x aux_xaux_x(dims=['x'], shape=[3], unit=m, variances=False)values x
[6]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (131 Bytes)
    • y: 2
    • x: 3
    • x
      (x)
      float64
      m
      0.0, 1.0, 2.0
      Values:
      array([0., 1., 2.])
    • y
      (y)
      float64
      m
      0.0, 1.0
      Values:
      array([0., 1.])
    • (y, x)
      float64
      0.77, 0.95, ..., 0.44, 0.92
      Values:
      array([[0.77447384, 0.94827388, 0.25539558], [0.84912604, 0.4379244 , 0.91732387]])
    • mask
      (x)
      bool
      True, False, False
      Values:
      array([ True, False, False])
    • aux_x
      (x)
      float64
      m
      0.0, 1.0, 2.0
      Values:
      array([0., 1., 2.])
    • aux_y
      (y)
      float64
      m
      0.0, 1.0
      Values:
      array([0., 1.])

As when slicing a variable, the sliced dimension is removed when slicing without range, and kept when slicing with range.

When slicing a data array the following additional rule applies:

  • Meta data (coords, masks, attrs) that do not depend on the slice dimension are marked as readonly

  • Slicing without range:

    • The coordinates for the sliced dimension are removed and inserted as attributes instead.

  • Slicing with a range:

    • The coordinates for the sliced dimension are kept.

The rationale behind this mechanism is as follows. Meta data is often of a lower dimensionality than data, such as in this example where coords, masks, and attrs are 1-D whereas data is 2-D. Elements of meta data entries are thus shared by many data elements, and we must be careful to not apply operations to subsets of data while unintentionally modifying meta data for other unrelated data elements:

[7]:
a['x', 0:1].coords['x'] *= 2  # ok, modifies only coord value "private" to this x-slice
try:
    a['x', 0:1].coords['y'] *= 2  # not ok, would modify coord value "shared" by all x-slices
except sc.VariableError as e:
    print(f'\'y\' is shared with other \'x\'-slices and should not be modified by the slice, so we get an error:\n{e}')
'y' is shared with other 'x'-slices and should not be modified by the slice, so we get an error:
Read-only flag is set, cannot mutate data.

In practice, a much more dangerous issue this mechanism protects from is unintentional changes to masks. Consider

[8]:
val = a['x', 1]['y', 1].copy()
val
[8]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (41 Bytes)
    • ()
      float64
      0.4379244031421974
      Values:
      array(0.4379244)
    • mask
      ()
      bool
      False
      Values:
      array(False)
    • aux_x
      ()
      float64
      m
      1.0
      Values:
      array(1.)
    • aux_y
      ()
      float64
      m
      1.0
      Values:
      array(1.)
    • x
      ()
      float64
      m
      1.0
      Values:
      array(1.)
    • y
      ()
      float64
      m
      1.0
      Values:
      array(1.)

If we now assign this scalar val to a slice at y=0, using = we need to update the mask. However, the mask in this example depends only on x so it also applies to the slices y=1. If we would allow updating the mask, the following would unmask data for all y:

[9]:
try:
    a['y', 0] = val
except sc.DimensionError as e:
    print(e)
Cannot update meta data 'mask' via slice since it is implicitly broadcast along the slice dimension 'y'.

Since we cannot update the mask in a consistent manner the entire operation fails. Data is not modified. The same mechanism is applied for binary arithmetic operations such as += where the masks would be updated using a logical OR operation.

The purpose for turning coords into attrs when slicing without a range is to support useful operations such as:

[10]:
a - a['x', 1]  # compute difference compared to data at x=1
[10]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (107 Bytes)
    • y: 2
    • x: 3
    • x
      (x)
      float64
      m
      0.0, 1.0, 2.0
      Values:
      array([0., 1., 2.])
    • y
      (y)
      float64
      m
      0.0, 1.0
      Values:
      array([0., 1.])
    • (y, x)
      float64
      -0.17, 0.0, ..., 0.0, 0.48
      Values:
      array([[-0.17380004, 0. , -0.6928783 ], [ 0.41120163, 0. , 0.47939947]])
    • mask
      (x)
      bool
      True, False, False
      Values:
      array([ True, False, False])
    • aux_y
      (y)
      float64
      m
      0.0, 1.0
      Values:
      array([0., 1.])

If a['x', 0] had an x coordinate this would fail due to a coord mismatch. If coord checking is required, use a range-slice such as a['x', 1:2]. Compare the two cases shown in the following and make sure to inspect the dims and shape of all variables (data and coordinates) of the resulting slice views (note the tooltip shown when moving the mouse over the name also contains this information):

[11]:
sc.show(a['y', 1:2])  # Range of length 1
a['y', 1:2]
(dims=['y', 'x'], shape=[1, 3], unit=dimensionless, variances=False)values yx aux_yaux_y(dims=['y'], shape=[1], unit=m, variances=False)values y yy(dims=['y'], shape=[1], unit=m, variances=False)values y xx(dims=['x'], shape=[3], unit=m, variances=False)values x maskmask(dims=['x'], shape=[3], unit=dimensionless, variances=False)values x aux_xaux_x(dims=['x'], shape=[3], unit=m, variances=False)values x
[11]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (91 Bytes out of 131 Bytes)
    • y: 1
    • x: 3
    • x
      (x)
      float64
      m
      0.0, 1.0, 2.0
      Values:
      array([0., 1., 2.])
    • y
      (y)
      float64
      m
      1.0
      Values:
      array([1.])
    • (y, x)
      float64
      0.85, 0.44, 0.92
      Values:
      array([[0.84912604, 0.4379244 , 0.91732387]])
    • mask
      (x)
      bool
      True, False, False
      Values:
      array([ True, False, False])
    • aux_x
      (x)
      float64
      m
      0.0, 1.0, 2.0
      Values:
      array([0., 1., 2.])
    • aux_y
      (y)
      float64
      m
      1.0
      Values:
      array([1.])
[12]:
sc.show(a['y', 1])  # No range
a['y', 1]
(dims=['x'], shape=[3], unit=dimensionless, variances=False)values x yy(dims=[], shape=[], unit=m, variances=False)values aux_yaux_y(dims=[], shape=[], unit=m, variances=False)values xx(dims=['x'], shape=[3], unit=m, variances=False)values x maskmask(dims=['x'], shape=[3], unit=dimensionless, variances=False)values x aux_xaux_x(dims=['x'], shape=[3], unit=m, variances=False)values x
[12]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (91 Bytes out of 131 Bytes)
    • x: 3
    • x
      (x)
      float64
      m
      0.0, 1.0, 2.0
      Values:
      array([0., 1., 2.])
    • (x)
      float64
      0.85, 0.44, 0.92
      Values:
      array([0.84912604, 0.4379244 , 0.91732387])
    • mask
      (x)
      bool
      True, False, False
      Values:
      array([ True, False, False])
    • aux_x
      (x)
      float64
      m
      0.0, 1.0, 2.0
      Values:
      array([0., 1., 2.])
    • aux_y
      ()
      float64
      m
      1.0
      Values:
      array(1.)
    • y
      ()
      float64
      m
      1.0
      Values:
      array(1.)

Datasets

Slicing for datasets works just like for data arrays. In addition to changing certain coords into attrs and marking certain meta data entries as read-only, slicing a dataset also marks lower-dimensional data entries readonly. Consider a dataset d:

[13]:
d = sc.Dataset(
    data={
        'a': sc.array(dims=['y', 'x'], values=np.random.rand(2, 3)),
        'b': sc.array(dims=['x', 'y'], values=np.random.rand(3, 2)),
        'c': sc.array(dims=['y'], values=np.random.rand(2)),
        '0d-data': sc.scalar(1.0)},
    coords={
        'x': sc.array(dims=['x'], values=np.arange(3.0), unit=sc.units.m),
        'y': sc.array(dims=['y'], values=np.arange(2.0), unit=sc.units.m)})
sc.show(d)
bb(dims=['x', 'y'], shape=[3, 2], unit=dimensionless, variances=False)values x y aa(dims=['y', 'x'], shape=[2, 3], unit=dimensionless, variances=False)values yx yy(dims=['y'], shape=[2], unit=m, variances=False)values y cc(dims=['y'], shape=[2], unit=dimensionless, variances=False)values y 0d-da..0d-data(dims=[], shape=[], unit=dimensionless, variances=False)values xx(dims=['x'], shape=[3], unit=m, variances=False)values x

and a slice of d:

[14]:
sc.show(d['y', 0])
cc(dims=[], shape=[], unit=dimensionless, variances=False)values 0d-da..0d-data(dims=[], shape=[], unit=dimensionless, variances=False)values bb(dims=['x'], shape=[3], unit=dimensionless, variances=False)values x aa(dims=['x'], shape=[3], unit=dimensionless, variances=False)values x xx(dims=['x'], shape=[3], unit=m, variances=False)values x

By marking lower-dimensional entries in the slice as read-only we prevent unintentional multiple modifications of the same scalar:

[15]:
try:
    d['y', 0] += 1  # would add 1 to `0d-data`
    d['y', 1] += 2  # would add 2 to `0d-data`
except sc.VariableError as e:
    print(e)
Read-only flag is set, cannot mutate data.

This is an important aspect and it is worthwhile to take some time and think through the mechanism.

Slicing a data item of a dataset should not bring any surprises. Essentially this behaves like slicing a data array:

[16]:
sc.show(d['a']['x', 1:2])
(dims=['y', 'x'], shape=[2, 1], unit=dimensionless, variances=False)values yx yy(dims=['y'], shape=[2], unit=m, variances=False)values y xx(dims=['x'], shape=[1], unit=m, variances=False)values x

Slicing and item access can be done in arbitrary order with identical results:

[17]:
d['x', 1:2]['a'] == d['a']['x', 1:2]
d['x', 1:2]['a'].coords['x'] == d.coords['x']['x', 1:2]
[17]:
Show/Hide data repr Show/Hide attributes
scipp.Variable (1 Bytes)
    • (x: 1)
      bool
      True
      Values:
      array([ True])

Label-based indexing

Overview

Data in a dataset or data array can be selected by the coordinate value. This is similar to pandas pandas.DataFrame.loc. Scipp leverages its ubiquitous support for physical units to provide label-based indexing in an intuitive manner, using the same syntax as positional indexing. For example:

  • array['x', 0:3] selects positionally, i.e., returns the first three element along 'x'.

  • array['x', 1.2*sc.units.m:1.3*sc.units.m] selects by label, i.e., returns the elements along 'x' falling between 1.2 m and 1.3 m.

That is, label-based indexing is made via __getitem__ and __setitem__ with a dimension label as first argument and a scalar variable or a Python slice() as created by the colon operator : from two scalar variables. In all cases a view is returned, i.e., just like when slicing a numpy.ndarray no copy is performed.

Consider:

[18]:
da = sc.DataArray(
    data=sc.array(dims=['year','x'], values=np.random.random((3, 7))),
    coords={
        'x': sc.array(dims=['x'], values=np.linspace(0.1, 0.9, num=7), unit=sc.units.m),
        'year': sc.array(dims=['year'], values=[2020,2023,2027])})
sc.show(da)
da
(dims=['year', 'x'], shape=[3, 7], unit=dimensionless, variances=False)values yearx yearyear(dims=['year'], shape=[3], unit=dimensionless, variances=False)values year xx(dims=['x'], shape=[7], unit=m, variances=False)values x
[18]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (248 Bytes)
    • year: 3
    • x: 7
    • x
      (x)
      float64
      m
      0.1, 0.23, ..., 0.77, 0.9
      Values:
      array([0.1 , 0.23333333, 0.36666667, 0.5 , 0.63333333, 0.76666667, 0.9 ])
    • year
      (year)
      int64
      2020, 2023, 2027
      Values:
      array([2020, 2023, 2027])
    • (year, x)
      float64
      0.85, 0.31, ..., 0.18, 0.53
      Values:
      array([[0.84689395, 0.30667282, 0.43493801, 0.02098768, 0.02290353, 0.12808188, 0.69186711], [0.16917547, 0.61556466, 0.64222512, 0.62085289, 0.78313618, 0.55185593, 0.19686669], [0.55935068, 0.40418018, 0.79986936, 0.49671036, 0.74876654, 0.18000935, 0.52911272]])

We can select a slice of da based on the 'year' labels:

[19]:
year = sc.scalar(2023)
da['year', year]
[19]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (120 Bytes out of 248 Bytes)
    • x: 7
    • x
      (x)
      float64
      m
      0.1, 0.23, ..., 0.77, 0.9
      Values:
      array([0.1 , 0.23333333, 0.36666667, 0.5 , 0.63333333, 0.76666667, 0.9 ])
    • (x)
      float64
      0.17, 0.62, ..., 0.55, 0.2
      Values:
      array([0.16917547, 0.61556466, 0.64222512, 0.62085289, 0.78313618, 0.55185593, 0.19686669])
    • year
      ()
      int64
      2023
      Values:
      array(2023)

In this case 2023 is the second element of the coordinate so this is equivalent to positionally slicing data['year', 1] and the usual rules regarding dropping dimensions and converting dimension coordinates to attributes apply:

[20]:
assert sc.identical(da['year', year], da['year', 1])

Warning

It is essential to not mix up integers and scalar scipp variables containing an integer. As in above example, positional indexing yields different slices than label-based indexing.

Note

Here, we created year using sc.scalar. Alternatively, we could use year = 2023 * sc.units.dimensionless which is useful for dimensionful coordinates like 'x' in this case, see below.

For floating-point-valued coordinates selecting a single point would require an exact match, which is typically not feasible in practice. Scipp does not do fuzzy matching in this case, instead an IndexError is raised:

[21]:
x = 0.23 * sc.units.m # No x coordinate value at this point. Equivalent of sc.scalar(0.23, unit=sc.units.m)
try:
    da['x', x]
except IndexError as e:
    print(str(e))
Coord x does not contain unique point with value <scipp.Variable> ()    float64              [m]  [0.230000]

For such coordinates we may thus use an interval to select a range of values using the : operator:

[22]:
x_left = 0.1 * sc.units.m
x_right = 0.4 * sc.units.m
da['x', x_left:x_right]
[22]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (120 Bytes out of 248 Bytes)
    • year: 3
    • x: 3
    • x
      (x)
      float64
      m
      0.1, 0.23, 0.37
      Values:
      array([0.1 , 0.23333333, 0.36666667])
    • year
      (year)
      int64
      2020, 2023, 2027
      Values:
      array([2020, 2023, 2027])
    • (year, x)
      float64
      0.85, 0.31, ..., 0.4, 0.8
      Values:
      array([[0.84689395, 0.30667282, 0.43493801], [0.16917547, 0.61556466, 0.64222512], [0.55935068, 0.40418018, 0.79986936]])

The selection includes the bounds on the “left” but excludes the bounds on the “right”, i.e., we select the half-open interval \(x \in [x_{\text{left}},x_{\text{right}})\), closed on the left and open on the right.

The half-open interval implies that we can select consecutive intervals without including any data point in both intervals:

[23]:
x_mid = 0.2 * sc.units.m
sc.to_html(da['x', x_left:x_mid])
sc.to_html(da['x', x_mid:x_right])
Show/Hide data repr Show/Hide attributes
scipp.DataArray (56 Bytes out of 248 Bytes)
    • year: 3
    • x: 1
    • x
      (x)
      float64
      m
      0.1
      Values:
      array([0.1])
    • year
      (year)
      int64
      2020, 2023, 2027
      Values:
      array([2020, 2023, 2027])
    • (year, x)
      float64
      0.85, 0.17, 0.56
      Values:
      array([[0.84689395], [0.16917547], [0.55935068]])
Show/Hide data repr Show/Hide attributes
scipp.DataArray (88 Bytes out of 248 Bytes)
    • year: 3
    • x: 2
    • x
      (x)
      float64
      m
      0.23, 0.37
      Values:
      array([0.23333333, 0.36666667])
    • year
      (year)
      int64
      2020, 2023, 2027
      Values:
      array([2020, 2023, 2027])
    • (year, x)
      float64
      0.31, 0.43, ..., 0.4, 0.8
      Values:
      array([[0.30667282, 0.43493801], [0.61556466, 0.64222512], [0.40418018, 0.79986936]])

Just like when slicing positionally one of the bounds can be omitted, to include either everything from the start, or everything until the end:

[24]:
da['x', :x_right]
[24]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (120 Bytes out of 248 Bytes)
    • year: 3
    • x: 3
    • x
      (x)
      float64
      m
      0.1, 0.23, 0.37
      Values:
      array([0.1 , 0.23333333, 0.36666667])
    • year
      (year)
      int64
      2020, 2023, 2027
      Values:
      array([2020, 2023, 2027])
    • (year, x)
      float64
      0.85, 0.31, ..., 0.4, 0.8
      Values:
      array([[0.84689395, 0.30667282, 0.43493801], [0.16917547, 0.61556466, 0.64222512], [0.55935068, 0.40418018, 0.79986936]])

Coordinates used for label-based indexing must be monotonically ordered. While it is natural to think of slicing in terms of ascending coordinates, the slicing mechanism also works for descending coordinates.

Bin-edge coordinates

Bin-edge coordinates are handled slightly differently from standard coordinates in label-based indexing. Consider:

[25]:
da = sc.DataArray(
    data = sc.array(dims=['x'], values=np.random.random(7)),
    coords={
        'x': sc.array(dims=['x'], values=np.linspace(1.0, 2.0, num=8), unit=sc.units.m)})
da
[25]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (120 Bytes)
    • x: 7
    • x
      (x [bin-edge])
      float64
      m
      1.0, 1.14, ..., 1.86, 2.0
      Values:
      array([1. , 1.14285714, 1.28571429, 1.42857143, 1.57142857, 1.71428571, 1.85714286, 2. ])
    • (x)
      float64
      0.78, 0.65, ..., 0.56, 0.43
      Values:
      array([0.77697681, 0.64771465, 0.05770556, 0.59625379, 0.63389497, 0.55528656, 0.42803093])

Here 'x' is a bin-edge coordinate, i.e., its length exceeds the array dimensions by one. Label-based slicing with a single coord value finds and returns the bin that contains the given coord value:

[26]:
x = 1.5 * sc.units.m
da['x', x]
[26]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (24 Bytes out of 120 Bytes)
    • ()
      float64
      0.596253788079361
      Values:
      array(0.59625379)
    • x
      (x [bin-edge])
      float64
      m
      1.43, 1.57
      Values:
      array([1.42857143, 1.57142857])

If an interval is provided when slicing with a bin-edge coordinate, the range of bins containing the values falling into the right-open interval bounds is selected:

[27]:
x_left = 1.3 * sc.units.m
x_right = 1.7 * sc.units.m
da['x', x_left:x_right]
[27]:
Show/Hide data repr Show/Hide attributes
scipp.DataArray (56 Bytes out of 120 Bytes)
    • x: 3
    • x
      (x [bin-edge])
      float64
      m
      1.29, 1.43, 1.57, 1.71
      Values:
      array([1.28571429, 1.42857143, 1.57142857, 1.71428571])
    • (x)
      float64
      0.06, 0.6, 0.63
      Values:
      array([0.05770556, 0.59625379, 0.63389497])

Limitations

Label-based indexing not supported for:

  • Multi-dimensional coordinates.

  • Non-monotonic coordinates.

The first is a fundamental limitation since a slice cannot be defined in such as case. The latter two will likely be supported in the future to some extent.