Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
x = np.arange(11) - 5.
y = np.linspace(0, 10, 51)
xx, yy = np.meshgrid(x, y, indexing='ij')
zz = np.sin(yy) + xx
zz_ref_avg_y = np.sin(yy) - np.sin(yy).mean()
data = MeshgridDataDict(
x = dict(values=xx),
y = dict(values=yy),
z = dict(values=zz, axes=['x', 'y'])
)
assert data.validate()
fc.setInput(dataIn=data)
assert num.arrays_equal(
zz,
fc.outputValues()['dataOut'].data_vals('z')
)
node.averagingAxis = 'y'
assert num.arrays_equal(
zz_ref_avg_y,
fc.outputValues()['dataOut'].data_vals('z'),
)
data = MeshgridDataDict(
x = dict(values=xx),
y = dict(values=yy),
z = dict(values=zz, axes=['x', 'y'])
)
assert data.validate()
fc.setInput(dataIn=data)
assert num.arrays_equal(
zz,
fc.outputValues()['dataOut'].data_vals('z')
)
node.averagingAxis = 'y'
assert num.arrays_equal(
zz_ref_avg_y,
fc.outputValues()['dataOut'].data_vals('z'),
)
a=dict(values=aa.reshape(-1)),
b=dict(values=bb.reshape(-1)),
z=dict(values=zz.reshape(-1), axes=['a', 'b']),
__info__='some info',
)
dd2 = datadict_to_meshgrid(dd, target_shape=(5, 11),
inner_axis_order=['b', 'a'])
assert DataDictBase.same_structure(dd, dd2)
assert num.arrays_equal(dd2.data_vals('a'), np.transpose(aa, (1, 0)))
assert num.arrays_equal(dd2.data_vals('z'), np.transpose(zz, (1, 0)))
dd2 = datadict_to_meshgrid(dd, target_shape=None)
assert DataDictBase.same_structure(dd, dd2)
assert num.arrays_equal(dd2.data_vals('a'), np.transpose(aa, (1, 0)))
assert num.arrays_equal(dd2.data_vals('z'), np.transpose(zz, (1, 0)))
def test_add_data():
"""Testing simple adding of data"""
# make base data
dd = DataDict(
x=dict(values=[1, 2, 3]),
y=dict(values=np.arange(6).reshape(3, 2), axes=['x']),
)
assert dd.validate()
# test bad data insertion
with pytest.raises(ValueError):
dd.add_data(x=[4, ])
assert num.arrays_equal(
dd.data_vals('x'),
np.array([1, 2, 3]),
)
# this should work!
dd.add_data(x=[4, ], y=[[6, 7], ])
assert num.arrays_equal(
dd.data_vals('x'),
np.array([1, 2, 3, 4])
)
assert num.arrays_equal(
dd.data_vals('y'),
np.arange(8).reshape(4, 2)
)
data = MeshgridDataDict(
x=dict(values=xx),
y=dict(values=yy),
z=dict(values=zz),
vals=dict(values=vals, axes=['x', 'y', 'z'])
)
assert data.validate()
fc.setInput(dataIn=data)
# this should return None, because no x/y axes were set.
assert fc.outputValues()['dataOut'] is None
# now select two axes, and test that the other one is correctly selected
node.xyAxes = ('x', 'y')
assert num.arrays_equal(
fc.outputValues()['dataOut'].data_vals('vals'),
vals[:,:,0]
)
# try a different reduction on the third axis
node.reductions = {'z': (ReductionMethod.average, [], {})}
assert num.arrays_equal(
fc.outputValues()['dataOut'].data_vals('vals'),
vals.mean(axis=-1)
)
# Test transposing the data by flipping x/y
node.xyAxes = ('y', 'x')
assert num.arrays_equal(
fc.outputValues()['dataOut'].data_vals('vals'),
vals.mean(axis=-1).transpose((1, 0))
x = np.arange(5.0)
y = np.linspace(0, 1, 5)
z = np.arange(4.0, 6.0, 1.0)
xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')
vals = xx * yy * zz
data = MeshgridDataDict(
x=dict(values=xx),
y=dict(values=yy),
z=dict(values=zz),
vals=dict(values=vals, axes=['x', 'y', 'z'])
)
assert data.validate()
fc.setInput(dataIn=data)
assert num.arrays_equal(
fc.outputValues()['dataOut'].data_vals('vals'),
vals
)
node.reductions = {'y': (np.mean, [], {})}
out = fc.outputValues()['dataOut']
assert num.arrays_equal(
vals.mean(axis=1),
out.data_vals('vals')
)
assert out.axes('vals') == ['x', 'z']
node.reductions = {
'y': (ReductionMethod.elementSelection, [], {'index': 0}),
'z': (ReductionMethod.average,)
y = np.linspace(0, 1, 5)
z = np.arange(4.0, 6.0, 1.0)
xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')
vv = xx * yy * zz
x1d, y1d, z1d = xx.flatten(), yy.flatten(), zz.flatten()
v1d = vv.flatten()
data = DataDict(
x=dict(values=x1d),
y=dict(values=y1d),
z=dict(values=z1d),
vals=dict(values=v1d, axes=['x', 'y', 'z'])
)
assert data.validate()
fc.setInput(dataIn=data)
assert num.arrays_equal(
fc.outputValues()['dataOut'].data_vals('vals'),
v1d,
)
node.grid = GridOption.guessShape, dict()
assert num.arrays_equal(
fc.outputValues()['dataOut'].data_vals('vals'),
vv,
)
node.grid = GridOption.specifyShape, dict(shape=(5, 5, 2))
assert num.arrays_equal(
fc.outputValues()['dataOut'].data_vals('vals'),
vv,
)
def test_array_equality():
"""Test if two arrays are correctly identified as having equal content"""
a = np.arange(2 * 4).astype(object).reshape(4, 2)
a[2, 0] = None
b = np.arange(2 * 4).astype(np.complex128).reshape(4, 2)
b[2, 0] = np.nan
assert num.arrays_equal(a, b)
a = np.arange(2 * 4).astype(object).reshape(4, 2)
a[2, 0] = 0
b = np.arange(2 * 4).astype(np.complex128).reshape(4, 2)
b[2, 0] = np.nan
assert not num.arrays_equal(a, b)
for dn, dv in self.data_items():
# print(dn)
if dn not in [dnn for dnn, dvv in other.data_items()]:
# print(f"{dn} not in {other}")
return False
if self[dn].get('unit', '') != other[dn].get('unit', ''):
# print(f"different units for {dn}")
return False
if self[dn].get('axes', []) != other[dn].get('axes', []):
# print(f"different axes for {dn}")
return False
if not num.arrays_equal(
np.array(self.data_vals(dn)),
np.array(other.data_vals(dn)),
):
# print(f"different data for {dn}")
return False
for k, v in self.meta_items(dn):
if k not in [kk for kk, vv in other.meta_items(dn)]:
# print(f"{dn}: {k} not in {other}")
return False
elif v != other.meta_val(k, dn):
# print(f"{v} != {other.meta_val(k, dn)}")
return False
for dn, dv in other.data_items():
# print(dn)
def guess_shape_from_datadict(data: DataDict) -> \
Dict[str, Union[None, Tuple[List[str], Tuple[int]]]]:
"""
Try to guess the shape of the datadict dependents from the axes values.
:param data: dataset to examine.
:return: a dictionary with the dependents as keys, and inferred shapes as
values. value is None, if the shape could not be inferred.
"""
shapes = {}
for d in data.dependents():
axnames = data.axes(d)
axes = {a: data.data_vals(a) for a in axnames}
shapes[d] = num.guess_grid_from_sweep_direction(**axes)
return shapes