-
Notifications
You must be signed in to change notification settings - Fork 18
Add the ability to convert from/to awkward array #108
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
Open
AreWeDreaming
wants to merge
20
commits into
iterorganization:develop
Choose a base branch
from
AreWeDreaming:awkward_array_support
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
4228cad
Add wrangler
AreWeDreaming 7faa192
Fix errors in test data and handle 2d ragged data
AreWeDreaming 17ad3b8
Extend tests to strings
AreWeDreaming 066a1ae
Update imas/wrangler.py
AreWeDreaming 098418c
Update imas/wrangler.py
AreWeDreaming 19c0f77
Make awkward import more selective
AreWeDreaming 2504a69
Merge branch 'awkward_array_support' of github.com:AreWeDreaming/IMAS…
AreWeDreaming e990c5f
Fix messed up indent
AreWeDreaming 1314972
Handle missing fields
AreWeDreaming 31bee40
Fix incorrect return type hint
AreWeDreaming b091f4f
Fix wrong check in test assertion
AreWeDreaming dda7533
Be verbose on what version means
AreWeDreaming bddaa9b
fixed issue with 2D data and blackify
prasad-sawantdesai 5ec40eb
version is not optional and convert_ids function when target_version …
prasad-sawantdesai 0b78428
Merge branch 'develop' into awkward_array_support
prasad-sawantdesai 694f588
added awkward as optional dependency
prasad-sawantdesai 88acc28
checked version before converting
prasad-sawantdesai 4367c85
fixed github actions -> readthedocs, tests and optional dependency in…
prasad-sawantdesai 82e1f03
Merge branch 'develop' into awkward_array_support
prasad-sawantdesai a442bf2
fixed naming of the methods
prasad-sawantdesai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| import pytest | ||
| import numpy as np | ||
| import awkward as ak | ||
|
|
||
| from imas.wrangler import wrangle, unwrangle | ||
| from imas.ids_factory import IDSFactory | ||
| from imas.util import idsdiffgen | ||
|
|
||
| @pytest.fixture | ||
| def test_data(): | ||
| data = {"equilibrium": {}} | ||
| data["equilibrium"]["N_time"] = 100 | ||
| data["equilibrium"]["N_radial"] = 100 | ||
| data["equilibrium"]["N_grid"] = 1 | ||
| data["equilibrium"]["time"] = np.linspace(0.0, 5.0, data["equilibrium"]["N_time"]) | ||
| data["equilibrium"]["psi_1d"] = np.linspace(0.0, 1.0, data["equilibrium"]["N_radial"]) | ||
| data["equilibrium"]["r"] = np.linspace(1.0, 2.0, data["equilibrium"]["N_radial"]) | ||
| data["equilibrium"]["z"] = np.linspace(-1.0, 1.0, data["equilibrium"]["N_radial"]) | ||
| r_grid, z_grid = np.meshgrid(data["equilibrium"]["r"], | ||
| data["equilibrium"]["z"], indexing="ij") | ||
| data["equilibrium"]["psi_2d"] = (r_grid - 1.5) ** 2 + z_grid**2 | ||
|
|
||
| data["thomson_scattering"] = {} | ||
| data["thomson_scattering"]["N_ch"] = (20,10) | ||
| N = data["thomson_scattering"]["N_ch"][0] + data["thomson_scattering"]["N_ch"][1] | ||
| data["thomson_scattering"]["identifier"] = np.asarray("channel_" + np.asarray(np.linspace(1,N+1,N, dtype=int),dtype="|U2"),dtype="|U10") | ||
| data["thomson_scattering"]["N_time"] = (100, 300) | ||
| data["thomson_scattering"]["r"] = np.concatenate([np.ones(data["thomson_scattering"]["N_ch"][0])*1.6, | ||
| np.ones(data["thomson_scattering"]["N_ch"][1])*1.7]) | ||
| data["thomson_scattering"]["z"] = np.concatenate([np.linspace(-1.0, 1.0, data["thomson_scattering"]["N_ch"][0]), | ||
| np.linspace(-1.0, 1.0, data["thomson_scattering"]["N_ch"][1])]) | ||
| data["thomson_scattering"]["t_e"] = data["thomson_scattering"]["z"]**2 * 5.e3 | ||
| data["thomson_scattering"]["n_e"] = data["thomson_scattering"]["z"]**2 * 5.e19 | ||
| data["thomson_scattering"]["time"] = (np.linspace(0,5.0, data["thomson_scattering"]["N_time"][0]), | ||
| np.linspace(0,5.0, data["thomson_scattering"]["N_time"][1])) | ||
| return data | ||
|
|
||
| @pytest.fixture | ||
| def flat(test_data): | ||
| flat = {} | ||
| # Equilibrium test data | ||
| flat["equilibrium.time"] = test_data["equilibrium"]["time"] | ||
| flat["equilibrium.time_slice.time"] = test_data["equilibrium"]["time"] | ||
| flat["equilibrium.ids_properties.homogeneous_time"] = 1 | ||
| flat["equilibrium.time_slice.profiles_1d.psi"] = np.zeros( | ||
| (test_data["equilibrium"]["N_time"], test_data["equilibrium"]["N_radial"]) | ||
| ) | ||
| flat["equilibrium.time_slice.profiles_1d.psi"][:] = test_data["equilibrium"]["psi_1d"] | ||
| flat["equilibrium.time_slice.profiles_2d.grid.dim1"] = np.zeros( | ||
| (test_data["equilibrium"]["N_time"], | ||
| test_data["equilibrium"]["N_grid"], | ||
| test_data["equilibrium"]["N_radial"]) | ||
| ) | ||
| flat["equilibrium.time_slice.profiles_2d.grid.dim1"][:] = test_data["equilibrium"]["r"][None, :] | ||
| flat["equilibrium.time_slice.profiles_2d.grid.dim2"] = np.zeros( | ||
| (test_data["equilibrium"]["N_time"], | ||
| test_data["equilibrium"]["N_grid"], | ||
| test_data["equilibrium"]["N_radial"]) | ||
| ) | ||
| flat["equilibrium.time_slice.profiles_2d.grid.dim2"][:] = test_data["equilibrium"]["z"][None, :] | ||
| flat["equilibrium.time_slice.profiles_2d.psi"] = np.zeros( | ||
| ( | ||
| test_data["equilibrium"]["N_time"], | ||
| test_data["equilibrium"]["N_grid"], | ||
| test_data["equilibrium"]["N_radial"], | ||
| test_data["equilibrium"]["N_radial"], | ||
| ) | ||
| ) | ||
| flat["equilibrium.time_slice.profiles_2d.psi"][:] = test_data["equilibrium"]["psi_2d"][None, ...] | ||
| # Thomson scattering test data (ragged) | ||
| flat["thomson_scattering.channel.identifier"] = test_data["thomson_scattering"]["identifier"] | ||
| flat["thomson_scattering.ids_properties.homogeneous_time"] = 0 | ||
| flat["thomson_scattering.channel.t_e.time"] = ak.concatenate([np.tile(test_data["thomson_scattering"]["time"][0], | ||
| (test_data["thomson_scattering"]["N_ch"][0], | ||
| 1)), | ||
| np.tile(test_data["thomson_scattering"]["time"][1], | ||
| (test_data["thomson_scattering"]["N_ch"][1], | ||
| 1))]) | ||
| flat["thomson_scattering.channel.t_e.data"] = ak.concatenate([np.repeat(test_data["thomson_scattering"]["t_e"][:test_data["thomson_scattering"]["N_ch"][0],None], | ||
| test_data["thomson_scattering"]["N_time"][0], axis=1), | ||
| np.repeat(test_data["thomson_scattering"]["t_e"][test_data["thomson_scattering"]["N_ch"][0]:,None], | ||
| test_data["thomson_scattering"]["N_time"][1], axis=1)]) | ||
| flat["thomson_scattering.channel.n_e.time"] = ak.concatenate([np.tile(test_data["thomson_scattering"]["time"][0], | ||
| (test_data["thomson_scattering"]["N_ch"][0], | ||
| 1)), | ||
| np.tile(test_data["thomson_scattering"]["time"][1], | ||
| (test_data["thomson_scattering"]["N_ch"][1], | ||
| 1))]) | ||
| flat["thomson_scattering.channel.n_e.data"] = ak.concatenate([np.repeat(test_data["thomson_scattering"]["n_e"][:test_data["thomson_scattering"]["N_ch"][0],None], | ||
| test_data["thomson_scattering"]["N_time"][0], axis=1), | ||
| np.repeat(test_data["thomson_scattering"]["n_e"][test_data["thomson_scattering"]["N_ch"][0]:,None], | ||
| test_data["thomson_scattering"]["N_time"][1], axis=1)]) | ||
| flat["thomson_scattering.channel.position.r"] = test_data["thomson_scattering"]["r"] | ||
| flat["thomson_scattering.channel.position.z"] = test_data["thomson_scattering"]["z"] | ||
| return flat | ||
|
|
||
| @pytest.fixture | ||
| def test_ids_dict(test_data): | ||
| factory = IDSFactory("3.41.0") | ||
| equilibrium = factory.equilibrium() | ||
| equilibrium.time = test_data["equilibrium"]["time"] | ||
| equilibrium.time_slice.resize(test_data["equilibrium"]["N_time"]) | ||
| equilibrium.ids_properties.homogeneous_time = 1 | ||
| for i in range(test_data["equilibrium"]["N_time"]): | ||
| equilibrium.time_slice[i].time = test_data["equilibrium"]["time"][i] | ||
| equilibrium.time_slice[i].profiles_1d.psi = test_data["equilibrium"]["psi_1d"] | ||
| equilibrium.time_slice[i].profiles_2d.resize(1) | ||
| equilibrium.time_slice[i].profiles_2d[0].grid.dim1 = test_data["equilibrium"]["r"] | ||
| equilibrium.time_slice[i].profiles_2d[0].grid.dim2 = test_data["equilibrium"]["z"] | ||
| equilibrium.time_slice[i].profiles_2d[0].psi = test_data["equilibrium"]["psi_2d"] | ||
|
|
||
| thomson_scattering = factory.thomson_scattering() | ||
| thomson_scattering.ids_properties.homogeneous_time = 0 | ||
| N = test_data["thomson_scattering"]["N_ch"][0] + test_data["thomson_scattering"]["N_ch"][1] | ||
| thomson_scattering.channel.resize(N) | ||
| index = 0 | ||
| for i in range(N): | ||
| if i == test_data["thomson_scattering"]["N_ch"][0]: | ||
| index = 1 | ||
| thomson_scattering.channel[i].identifier = test_data["thomson_scattering"]["identifier"][i] | ||
| thomson_scattering.channel[i].t_e.time = test_data["thomson_scattering"]["time"][index] | ||
| thomson_scattering.channel[i].t_e.data = np.tile(test_data["thomson_scattering"]["t_e"][i], | ||
| test_data["thomson_scattering"]["N_time"][index]) | ||
| thomson_scattering.channel[i].n_e.time = test_data["thomson_scattering"]["time"][index] | ||
| thomson_scattering.channel[i].n_e.data = np.tile(test_data["thomson_scattering"]["n_e"][i], | ||
| test_data["thomson_scattering"]["N_time"][index]) | ||
| thomson_scattering.channel[i].position.r = test_data["thomson_scattering"]["r"][i] | ||
| thomson_scattering.channel[i].position.z = test_data["thomson_scattering"]["z"][i] | ||
|
|
||
| return {"equilibrium":equilibrium, "thomson_scattering": thomson_scattering} | ||
|
|
||
|
|
||
| def test_wrangle(test_ids_dict, flat): | ||
| wrangled = wrangle(flat) | ||
| for key in test_ids_dict: | ||
| diff = idsdiffgen(wrangled[key],test_ids_dict[key]) | ||
| assert len(list(diff)) == 0, diff | ||
|
|
||
| def get_dtype(arr): | ||
| """Get dtype from either numpy or awkward array.""" | ||
| if isinstance(arr, ak.Array): | ||
| # This is the easiest way I found to extract the numpy dtype from an awkward array | ||
| return eval("np." + arr.typestr.split("*")[-1]) | ||
| if hasattr(arr, "dtype"): | ||
| return arr.dtype | ||
| else: | ||
| return type(arr) | ||
|
|
||
| def test_unwrangle(test_ids_dict, flat): | ||
| result = unwrangle(list(flat.keys()), test_ids_dict) | ||
| for key in flat.keys(): | ||
| if np.issubdtype(get_dtype(result[key]), np.floating): | ||
| assert ak.almost_equal(result[key], flat[key]) | ||
| else: | ||
| assert ak.array_equal(result[key], flat[key]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| from typing import Dict, List | ||
| import awkward as ak | ||
| import numpy as np | ||
| from . import IDSFactory | ||
| from .ids_toplevel import IDSToplevel | ||
| from .backends.netcdf.ids_tensorizer import IDSTensorizer | ||
|
|
||
| def recursively_put(location, value, ids): | ||
| # time_slice.profiles_1d.psi | ||
| if "." in location: | ||
| position, sub_location = location.split(".", 1) | ||
| sub_ids = getattr(ids, position) | ||
| if hasattr(sub_ids, "size"): | ||
| N = len(value) | ||
| if sub_ids.size == 0: | ||
| sub_ids.resize(N) | ||
| elif sub_ids.size != N: | ||
| raise ValueError( | ||
| f"""Inconsistent size across flat entries {location}, {N} (flat) vs. ids {sub_ids.size}! | ||
| """ | ||
| ) | ||
| # Need to iterate over indices (e.g. equilibrium.time_slice[:].) | ||
| for index in range(N): | ||
| recursively_put(sub_location, value[index], sub_ids[index]) | ||
| else: | ||
| # Need to set an attribute | ||
| # Now get the new substring, e.g. time_slice | ||
| position, sub_location = location.split(".", 1) | ||
| recursively_put(sub_location, value, sub_ids) | ||
| else: | ||
| setattr(ids, location, value) | ||
| return ids | ||
|
|
||
|
|
||
| def wrangle(flat: Dict, version="3.41.0") -> Dict[str, IDSToplevel]: | ||
|
AreWeDreaming marked this conversation as resolved.
Outdated
|
||
| wrangled = {} | ||
| factory = IDSFactory(version) | ||
|
AreWeDreaming marked this conversation as resolved.
Outdated
|
||
| for key in flat: | ||
| ids, location = key.split(".", 1) | ||
| if ids not in wrangled: | ||
| wrangled[ids] = getattr(factory, ids)() | ||
| wrangled[ids] = recursively_put(location, flat[key], wrangled[ids]) | ||
| return wrangled | ||
|
|
||
| def split_location_across_ids(locations: List[str]) -> Dict[str, List[str]]: | ||
| ids_locations = {} | ||
| for location in locations: | ||
| ids, path = location.split(".",1) | ||
| if ids not in ids_locations: | ||
| ids_locations[ids] = [] | ||
| ids_locations[ids].append(path.replace(".","/") ) | ||
| return ids_locations | ||
|
|
||
| def unwrangle( | ||
| locations: List[str], ids_dict: Dict[str, IDSToplevel], version="3.41.0" | ||
|
prasad-sawantdesai marked this conversation as resolved.
Outdated
|
||
| ) -> Dict[str, ak.Array | np.ndarray]: | ||
| flat = {} | ||
| ids_locations = split_location_across_ids(locations) | ||
| for key in ids_locations: | ||
| tensorizer = IDSTensorizer(ids_dict[key], ids_locations[key]) | ||
| tensorizer.include_coordinate_paths() | ||
| tensorizer.collect_filled_data() | ||
| tensorizer.determine_data_shapes() | ||
| # Add IDS conversion | ||
| for ids_location in ids_locations[key]: | ||
| location = key + "." + ids_location.replace("/", ".") | ||
| values = tensorizer.awkward_tensorize(ids_location) | ||
| if hasattr(values, "__getattr__"): | ||
| # Not a scalar, e.g. homogenous_time | ||
| try: | ||
| flat[location] = np.asarray(values) | ||
| except ValueError as e: | ||
| flat[location] = ak.Array(values) | ||
| else: | ||
| flat[location] = values | ||
| return flat | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.