Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0bbdcc6

Browse files
authored
Merge pull request #250 from kaustubhmote/update_uc
A function to update the unit conversion object
2 parents 9246bfc + 986e985 commit 0bbdcc6

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

nmrglue/fileio/fileiobase.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,48 @@ def us_scale(self):
330330
__call__ = i # calling the object x is the same as x.i
331331

332332

333+
def update_uc(uc, **kwargs):
334+
"""
335+
Updates the unit_conversion object with new parameters
336+
and returns a new unit_conversion object
337+
338+
Parameters
339+
----------
340+
uc : unit_conversion
341+
unit_conversion object to update
342+
343+
Returns
344+
-------
345+
unit_conversion
346+
Updated unit_conversion object
347+
348+
Raises
349+
------
350+
TypeError
351+
If the provided uc is not a unit conversion object
352+
TypeError
353+
If the parameter to update is not a valid parameter.
354+
355+
"""
356+
if not isinstance(uc, unit_conversion):
357+
raise TypeError(f'{uc} is not a unit_conversion object.')
358+
359+
if not kwargs:
360+
return uc
361+
362+
params = ('size', 'cplx', 'sw', 'obs', 'car')
363+
new_params = {p: uc.__getattribute__(f'_{p}') for p in params}
364+
365+
for k, v in kwargs.items():
366+
if k in params:
367+
new_params[k] = v
368+
else:
369+
raise TypeError(
370+
f'{k} cannot be used to construct a unit conversion object. Acceptable keywords are {(params)}.')
371+
372+
return unit_conversion(*new_params.values())
373+
374+
333375
def uc_from_udic(udic, dim=-1):
334376
"""
335377
Create a unit conversion object from a Universal dictionary.

nmrglue/fileio/tests/test_fileiobase.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,14 @@ def test_uc_with_float_size():
4646
size=64.0, cplx=False, sw=1.0, obs=1.0, car=1.0)
4747
scale = uc.ppm_scale()
4848
assert len(scale) == 64
49+
50+
51+
def test_update_uc():
52+
uc = ng.fileiobase.unit_conversion(
53+
size=64.0, cplx=False, sw=1.0, obs=1.0, car=1.0)
54+
uc2 = ng.fileiobase.update_uc(uc, size=10, cplx=True, sw=2.0, car=5.2, obs=3.0)
55+
assert uc2._size == 10
56+
assert uc2._cplx is True
57+
assert abs(uc2._sw - 2.0) < 1e-5
58+
assert abs(uc2._car - 5.2) < 1e-5
59+
assert abs(uc2._obs - 3.0) < 1e-5

0 commit comments

Comments
 (0)