Skip to content

Commit

Permalink
Merge pull request nanograv#1795 from dlakaplan/implicitpar
Browse files Browse the repository at this point in the history
Allow setting of parameter quantity/value implicitly
  • Loading branch information
abhisrkckl authored Jul 12, 2024
2 parents a2522a7 + 12b2d5a commit 7369be5
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG-unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ the released changes.
### Changed
### Added
- Type hints in `pint.derived_quantities`
- Doing `model.par = something` will try to assign to `par.quantity` or `par.value` but will give warning
### Fixed
### Removed
10 changes: 10 additions & 0 deletions src/pint/models/timing_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,16 @@ def __setattr__(self, name, value):
if isinstance(value, (Parameter, prefixParameter)) and name != value.name:
for p in ["quantity", "uncertainty", "frozen"]:
setattr(getattr(self, name), p, getattr(value, p))
elif isinstance(value, (u.Quantity, time.Time)):
log.warning(
f"Setting '{name}.quantity' to '{value}' although 'quantity' not specified"
)
getattr(self, name).quantity = value
elif isinstance(value, (float, str, bool, int)) and name != "name":
log.warning(
f"Setting '{name}.value' to '{value}' (assumed units '{getattr(self,name).units}') although 'value' not specified"
)
getattr(self, name).value = value
else:
super().__setattr__(name, value)

Expand Down
45 changes: 45 additions & 0 deletions tests/test_parchange.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from astropy import units as u, constants as c
from astropy.time import Time
import numpy as np
from pint.models import get_model_and_toas
import pytest
import os
from pinttestdata import datadir


@pytest.mark.parametrize(
"par,newvalue",
(
("PLANET_SHAPIRO", True),
("F1", 10 * u.Hz / u.s),
("F0", 20),
("PSR", "ABC-XYZ"),
("POSEPOCH", 53760.0),
("PEPOCH", Time(53760, format="mjd")),
),
)
def test_parchange(par, newvalue):
m, t = get_model_and_toas(
os.path.join(datadir, "NGC6440E.par"), os.path.join(datadir, "NGC6440E.tim")
)
setattr(m, par, newvalue)
if isinstance(newvalue, (u.Quantity, Time)):
assert m[par].quantity == newvalue
else:
assert m[par].value == newvalue


@pytest.mark.parametrize(
"par,newvalue",
(
("F1", 10 * u.Hz / u.s**2),
("F0", "abc"),
),
)
def test_parchange_fails(par, newvalue):
m, t = get_model_and_toas(
os.path.join(datadir, "NGC6440E.par"), os.path.join(datadir, "NGC6440E.tim")
)

with pytest.raises((ValueError, u.UnitConversionError)):
setattr(m, par, newvalue)

0 comments on commit 7369be5

Please sign in to comment.