Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sliceable MetaData Class #455

Open
wants to merge 90 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
90 commits
Select commit Hold shift + click to select a range
ff9b13e
First draft of a sliceable meta obect.
DanRyanIrish Aug 13, 2021
6d0d254
Refactor Meta. Tests now passing.
DanRyanIrish Aug 14, 2021
9166378
Add overwrite option to Meta.add.
DanRyanIrish Aug 14, 2021
a2248c7
Fixes codestyle.
DanRyanIrish Aug 14, 2021
02cdcbb
Adds #455 changelog.
DanRyanIrish Aug 14, 2021
eb57c05
Codestyle fixes.
DanRyanIrish Aug 14, 2021
96b8ab9
Slice meta if possible when slicing NDCube.
DanRyanIrish Aug 14, 2021
303320a
Add docstrings to Meta object.
DanRyanIrish Aug 14, 2021
3cc208d
Create remove method for Meta.
DanRyanIrish Aug 16, 2021
2b5d507
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Aug 21, 2021
041cd1b
Make Meta more memory efficient.
DanRyanIrish Aug 23, 2021
3bdf4a6
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Aug 25, 2021
cd13518
Add Meta to top-level init imports.
DanRyanIrish Aug 25, 2021
ad88f5f
Enable Meta object's shape to be set without axes being set.
DanRyanIrish Aug 25, 2021
873d5b7
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Oct 15, 2021
1d54ba3
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Nov 3, 2021
f8c59ed
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Nov 4, 2021
4611e1e
Avoid possible indexing error when dropping axes during slicing of Me…
DanRyanIrish Nov 4, 2021
048e0ed
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Nov 10, 2021
aa817fd
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Nov 18, 2021
cf923f9
Make NDCube slice meta if it has a magic attribute.
DanRyanIrish Nov 18, 2021
b0e21be
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Aug 26, 2022
7df22e7
Merge branch 'main' into meta
DanRyanIrish May 7, 2024
bbe6c12
Fixes codestyle.
DanRyanIrish May 7, 2024
86dc366
Reverting unintented changes to __init__.py
DanRyanIrish May 7, 2024
7160dc3
Apply suggestions from code review
DanRyanIrish May 8, 2024
b3d439c
Adds nitpicky exceptions for Meta docstring.
DanRyanIrish May 8, 2024
1f04d62
Try fixing hyperlink to "iterable"
DanRyanIrish May 8, 2024
c27d904
Apply suggestions from code review
nabobalis May 8, 2024
8291189
Apply suggestions from code review
nabobalis May 8, 2024
5604de0
Apply suggestions from code review
nabobalis May 8, 2024
cdece82
Apply suggestions from code review
nabobalis May 8, 2024
51617e6
Update ndcube/tests/test_meta.py
nabobalis May 8, 2024
72bccb0
Change denotation of metadata not associated with axes in Meta class …
DanRyanIrish May 9, 2024
120596d
Make NDCube.rebin remove axis-awareness from metadata associated with…
DanRyanIrish May 9, 2024
f3fc5a2
Merge branch 'meta' of https://github.com/DanRyanIrish/ndcube into meta
DanRyanIrish May 9, 2024
ad39c81
Fix codestyle
DanRyanIrish May 9, 2024
ad0e532
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish May 9, 2024
d01f6f6
Add test of meta handling by NDCube.rebin.
DanRyanIrish May 10, 2024
d5ae2ef
Add rebin capability to Meta.
DanRyanIrish May 13, 2024
181d86d
Fix codestyle.
DanRyanIrish May 13, 2024
f17ba0b
Adds tests for Meta.rebin.
DanRyanIrish May 13, 2024
da8df25
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish May 19, 2024
fb45151
Support scalar axis-aware metadata.
DanRyanIrish May 19, 2024
9726b65
Add support for axis-aware metadata that give a scalar per axis.
DanRyanIrish May 19, 2024
a626602
Clarify behavior of axis-aligned and grid-aligned metadata and fix co…
DanRyanIrish May 20, 2024
e848e9f
Make API of Meta.rebin more flexible.
DanRyanIrish May 20, 2024
500843f
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Jul 2, 2024
754385e
change name for metadata used by Meta class from header to meta
DanRyanIrish Jul 2, 2024
e8f9535
Update ndcube/meta.py
DanRyanIrish Jul 2, 2024
fef0de6
Rename Meta to NDMeta.
DanRyanIrish Jul 2, 2024
28eafbb
Move ndcube_can_slice and ndcube_can_rebin to class attributes of NDM…
DanRyanIrish Jul 2, 2024
40b8b26
Create NDMetaABC.
DanRyanIrish Jul 2, 2024
3ba2d9c
Move slicing by data item in NDMeta to new slice method.
DanRyanIrish Jul 2, 2024
f723445
Change NDMeta.shape to data_shape.
DanRyanIrish Jul 2, 2024
6d84e56
Make NDMeta infer data_shape if not provided.
DanRyanIrish Jul 2, 2024
bf078bd
Refactor NDMeta.rebin to take bin_shape as input.
DanRyanIrish Jul 2, 2024
81b84e5
Remove data_shape kwarg from NDMeta init.
DanRyanIrish Jul 2, 2024
b526e3e
Fix codestyle.
DanRyanIrish Jul 2, 2024
cdc3f8f
Add setter for NDMeta.data_shape.
DanRyanIrish Jul 2, 2024
2373209
Replace NDMeta.remove with __delitem__.
DanRyanIrish Jul 2, 2024
6d38c67
Make NDCube.meta have same shape as NDCube if meta is axis-aware.
DanRyanIrish Jul 2, 2024
fb788f7
Fix codestyle.
DanRyanIrish Jul 3, 2024
f315ca6
Apply suggestions from code review
DanRyanIrish Jul 4, 2024
d81db9e
Change NDMeta.comments to key_comments.
DanRyanIrish Jul 4, 2024
b59cbff
Merge branch 'meta' of https://github.com/DanRyanIrish/ndcube into meta
DanRyanIrish Jul 4, 2024
5776dca
Make NDMeta.original_header read-only.
DanRyanIrish Jul 4, 2024
5076384
First incomplete version of docs on NDMeta.
DanRyanIrish Jul 8, 2024
bebcf1f
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Jul 13, 2024
8127514
First complete draft of metadata narrative docs.
DanRyanIrish Jul 14, 2024
c4a83aa
Enable NDMeta to accept data shape on instantiation.
DanRyanIrish Jul 14, 2024
d79a5e6
Enable NDCubeSequence and NDCollection to support sliceable metadata.
DanRyanIrish Jul 14, 2024
7f9f042
Add tests for meta slicing via NDCubeSequence and NDCollection.
DanRyanIrish Jul 16, 2024
e35c34c
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Jul 20, 2024
a58c705
Fixes to make NDMeta slicing work, especially as part of an NDCollect…
DanRyanIrish Jul 20, 2024
944b0df
Some docs bugfixes relating to NDMeta.
DanRyanIrish Jul 21, 2024
8f9816a
Some old changes that werent committed.
DanRyanIrish Nov 6, 2024
e0b9dbe
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Nov 6, 2024
e4bdf03
Fixes codestyle.
DanRyanIrish Nov 6, 2024
ccf35dc
Fix bug when adding axis-aligned metadata.
DanRyanIrish Nov 6, 2024
143afa1
Fix bug in handling slicing meta through NDCube slicing.
DanRyanIrish Nov 6, 2024
aab969b
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Nov 6, 2024
d1b4b47
Some doc build fixes.
DanRyanIrish Nov 6, 2024
1575a22
More doc fixes.
DanRyanIrish Nov 6, 2024
1845572
More doc fixes.
DanRyanIrish Nov 6, 2024
195fe19
More doc fixes.
DanRyanIrish Nov 6, 2024
672007e
Fix 455 changelog entry.
DanRyanIrish Nov 6, 2024
baab449
Replace bare exception with except Exception.
DanRyanIrish Nov 6, 2024
39d675d
Merge branch 'main' of https://github.com/sunpy/ndcube into meta
DanRyanIrish Nov 6, 2024
5c0e2cb
Merge branch 'main' of github.com:sunpy/ndcube into meta
Cadair Nov 13, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/455.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add Sliceable `~ndcube.meta.Meta` class for axis-associated metadata.
3 changes: 2 additions & 1 deletion ndcube/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@ class UnsupportedPythonError(Exception):

from .extra_coords import ExtraCoords
from .global_coords import GlobalCoords
from .meta import Meta
from .ndcollection import NDCollection
from .ndcube import NDCube
from .ndcube_sequence import NDCubeSequence
from .version import version as __version__

__all__ = ['NDCube', 'NDCubeSequence', "NDCollection", "ExtraCoords", "GlobalCoords"]
__all__ = ["ExtraCoords", "GlobalCoords", "Meta", "NDCollection", "NDCube", "NDCubeSequence"]
248 changes: 248 additions & 0 deletions ndcube/meta.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
import copy
import numbers
import collections.abc

import numpy as np

__all__ = ["Meta"]


class Meta(dict):
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
"""
A sliceable object for storing metadata.

Metdata can be linked to a data axis which causes it to be sliced when the
standard Python numeric slicing API is applied to the object.
Specific pieces of metadata can be obtain using the dict-like str slicing API.
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
Metadata associated with an axis/axes must have the same length/shape as those axes.

Parameters
----------
header: dict-like
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
The names and values of metadata.

nabobalis marked this conversation as resolved.
Show resolved Hide resolved
comments: dict-like (optional)
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
Comments associated with any of the above pieces of metadata.

axes: dict-like (optional)
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
The axis/axes associated with the above metadata values.
Each axis value must be None (for no axis association), and `int`
or an iterable of `int` if the metadata is associated with multiple axes.
Metadata in header without a corresponding entry here are assumed to not
be associated with an axis.

data_shape: iterable of `int` (optional)
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
The shape of the data with which this metadata is associated.
Must be set if axes input is set.
"""
def __init__(self, header=None, comments=None, axes=None, data_shape=None):
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
self.original_header = header
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used header as the nomenclature with sunpy.map.Map in mind. But this tends to imply a FITS header, which is over-specific. Perhaps this should be changed to meta and original_meta. Thoughts @ayshih @Cadair?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am in favour of meta rather than header

DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved

# Sanitize metadata values and instantiate class.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
if header is None:
header = {}
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
else:
header = dict(header)
super().__init__(header.items())
header_keys = header.keys()
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved

# Generate dictionary for comments.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
if comments is None:
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
self._comments = dict()
else:
comments = dict(comments)
if not set(comments.keys()).issubset(set(header_keys)):
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
raise ValueError(
"All comments must correspond to a value in header under the same key.")
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
self._comments = comments

# Define data shape.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
if data_shape is None:
self._data_shape = data_shape
else:
self._data_shape = np.asarray(data_shape, dtype=int)

# Generate dictionary for axes.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
if axes is None:
self._axes = dict()
else:
# Verify data_shape is set if axes is set.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
if not (isinstance(data_shape, collections.abc.Iterable) and
all([isinstance(i, numbers.Integral) for i in data_shape])):
raise TypeError("If axes is set, data_shape must be an iterable giving "
"the length of each axis of the assocated cube.")
axes = dict(axes)
if not set(axes.keys()).issubset(set(header_keys)):
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
raise ValueError(
"All axes must correspond to a value in header under the same key.")
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
self._axes = dict([(key, self._sanitize_axis_value(axis, header[key], key))
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
for key, axis in axes.items()])

def _sanitize_axis_value(self, axis, value, key):
if axis is None:
return None
if self.shape is None:
raise TypeError("Meta instance does not have a shape so new metadata "
"cannot be assigned to an axis.")
# Verify each entry in axes is an iterable of ints.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
if isinstance(axis, numbers.Integral):
axis = (axis,)
if not (isinstance(axis, collections.abc.Iterable) and all([isinstance(i, numbers.Integral)
for i in axis])):
raise TypeError("Values in axes must be an int or tuple of ints giving "
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
"the data axis/axes associated with the metadata.")
axis = np.asarray(axis)

# Confirm each axis-associated piece of metadata has the same shape
# as its associated axes.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
shape_error_msg = (f"{key} must have shape {tuple(self.shape[axis])} "
f"as it is associated with axes {axis}")
if len(axis) == 1:
if not hasattr(value, "__len__"):
raise TypeError(shape_error_msg)
meta_shape = (len(value),)
else:
if not hasattr(value, "shape"):
raise TypeError(shape_error_msg)
meta_shape = value.shape
if not all(meta_shape == self.shape[axis]):
raise ValueError(shape_error_msg)

return axis

@property
def comments(self):
return self._comments

@property
def axes(self):
return self._axes

@property
def shape(self):
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
return self._data_shape

def add(self, name, value, comment, axis, overwrite=False):
"""Add a new piece of metadata to instance.
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved

Parameters
----------
name: `str`
The name/label of the metadata.

value:
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
The value of the metadata. If axes input is not None, this must have the
same length/shape as those axes as defined by self.shape.
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved

comment: `str` or `None`
Any comment associated with this metadata. Set to None if no comment desired.

axis: `int`, iterable of `int`, or `None`
The axis/axes with which the metadata is linked. If not associated with any
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
axis, set this to None.

overwrite: `bool` (optional)
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
If True, overwrites the entry of the name name if already present.
"""
if name in self.keys() and overwrite is not True:
raise KeyError(f"'{name}' already exists. "
"To update an existing metadata entry set overwrite=True.")
if comment is not None:
self._comments[name] = comment
if axis is not None:
axis = self._sanitize_axis_value(axis, value, name)
self._axes[name] = axis
elif name in self._axes:
del self._axes[name]
self.__setitem__(name, value) # This must be done after updating self._axes otherwise it may error.
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved

def remove(self, name):
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
if name in self._comments:
del self._comments[name]
if name in self._axes:
del self._axes[name]
del self[name]

def __setitem__(self, key, val):
axis = self.axes.get(key, None)
if axis is not None:
recommendation = "We recommend using the 'add' method to set values."
if len(axis) == 1:
if not (hasattr(val, "__len__") and len(val) == self.shape[axis[0]]):
raise TypeError(f"{key} must have same length as associated axis, "
f"i.e. axis {axis[0]}: {self.shape[axis[0]]}\n"
f"{recommendation}")
else:
if not (hasattr(val, "shape") and all(val.shape == self.shape[axis])):
raise TypeError(f"{key} must have same shape as associated axes, "
f"i.e axes {axis}: {self.shape[axis]}\n"
f"{recommendation}")
super().__setitem__(key, val)

def __getitem__(self, item):
# There are two ways to slice:
# by key, or
# by typical python numeric slicing API,
# i.e. slice the each piece of metadata associated with an axes.

# If item is single string, slicing is simple.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
if isinstance(item, str):
return super().__getitem__(item)
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved

# Else, the item is assumed to be a typical slicing item.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
elif self.shape is None:
raise TypeError("Meta object does not have a shape and so cannot be sliced.")

else:
new_meta = copy.deepcopy(self)
# Convert item to array of ints and slices for consistent behaviour.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
if isinstance(item, (numbers.Integral, slice)):
item = [item]
item = np.array(list(item) + [slice(None)] * (len(self.shape) - len(item)),
dtype=object)

# Edit data shape and calculate which axis will be dropped.
dropped_axes = np.zeros(len(self.shape), dtype=bool)
new_shape = new_meta.shape
for i, axis_item in enumerate(item):
if isinstance(axis_item, numbers.Integral):
dropped_axes[i] = True
elif isinstance(axis_item, slice):
start = axis_item.start
if start is None:
start = 0
if start < 0:
start = self.shape[i] - start
stop = axis_item.stop
if stop is None:
stop = self.shape[i]
if stop < 0:
stop = self.shape[i] - stop
new_shape[i] = stop - start
else:
raise TypeError("Unrecognized slice type. "
"Must be an int, slice and tuple of the same.")
new_meta._data_shape = new_shape[np.invert(dropped_axes)]

# Calculate the cumulative number of dropped axes.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# Calculate the cumulative number of dropped axes.

cumul_dropped_axes = np.cumsum(dropped_axes)

# Slice all metadata associated with axes.
for key, value in self.items():
axis = self.axes.get(key, None)
if axis is not None:
DanRyanIrish marked this conversation as resolved.
Show resolved Hide resolved
new_item = tuple(item[axis])
if len(new_item) == 1:
new_value = value[new_item[0]]
else:
new_value = value[new_item]
new_axis = np.array([-1 if isinstance(i, numbers.Integral) else a
for i, a in zip(new_item, axis)])
new_axis -= cumul_dropped_axes[axis]
new_axis = new_axis[new_axis >= 0]
if len(new_axis) == 0:
new_axis = None
new_meta.add(key, new_value, self.comments.get(key, None), new_axis,
overwrite=True)

return new_meta
9 changes: 9 additions & 0 deletions ndcube/mixins/ndslicing.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,13 @@ def __getitem__(self, item):
sliced_cube._global_coords._internal_coords = self.global_coords._internal_coords
sliced_cube._extra_coords = self.extra_coords[item]

# Slice metadata if possible.
try:
sliced_cube.meta = self.meta[item]
except TypeError as err:
if "unhashable type" not in err.args[0]:
raise err
except KeyError:
pass

return sliced_cube
35 changes: 32 additions & 3 deletions ndcube/tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from numpy.testing import assert_equal

from ndcube import NDCube, NDCubeSequence
from ndcube.meta import Meta

__all__ = ['figure_test',
'get_hash_library_name',
Expand Down Expand Up @@ -89,10 +90,38 @@ def assert_extra_coords_equal(test_input, extra_coords):


def assert_metas_equal(test_input, expected_output):
if not (test_input is None and expected_output is None):
if type(test_input) is not type(expected_output):
raise AssertionError(
"input and expected are of different type. "
f"input: {type(test_input)}; expected: {type(expected_output)}")
multi_element_msg = "more than one element is ambiguous"
if isinstance(test_input, Meta) and isinstance(expected_output, Meta):
# Check keys are the same.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
assert test_input.keys() == expected_output.keys()
for key in list(test_input.keys()):
assert test_input[key] == expected_output[key]

# Check shapes are the same.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
if test_input.shape is None or expected_output.shape is None:
assert test_input.shape == expected_output.shape
else:
assert np.allclose(test_input.shape, expected_output.shape)

# Check values and axes are the same.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
for test_value, expected_value in zip(test_input.values(), expected_output.values()):
try:
assert test_value == expected_value
except ValueError as err:
if multi_element_msg in err.args[0]:
assert np.allclose(test_value, expected_value)
# Check axes are the same.
nabobalis marked this conversation as resolved.
Show resolved Hide resolved
for test_axis, expected_axis in zip(test_input.axes.values(),
expected_output.axes.values()):
assert ((test_axis is None and expected_axis is None) or
all(test_axis == expected_axis))
else:
if not (test_input is None and expected_output is None):
assert test_input.keys() == expected_output.keys()
for key in list(test_input.keys()):
assert test_input[key] == expected_output[key]


def assert_cubes_equal(test_input, expected_cube):
Expand Down
Loading