How to use Pint - 10 common examples

To help you get started, we’ve selected a few Pint examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nanograv / PINT / tests / test_fitter.py View on Github external
def test_ftest():
    """Test for fitter class F-test."""
    m = tm.get_model(os.path.join(datadir, "B1855+09_NANOGrav_9yv1.gls.par"))
    t = toa.get_TOAs(os.path.join(datadir, "B1855+09_NANOGrav_9yv1.tim"))
    f = fitter.WLSFitter(toas=t, model=m)
    f.fit_toas()
    # Test adding parameters
    FD4 = param.prefixParameter(
        parameter_type="float", name="FD4", value=0.0, units=u.s, frozen=False
    )
    ft = f.ftest(FD4, "FD", remove=False)
    assert isinstance(ft, float) or isinstance(ft, bool)
    # Test return the full output
    ft, r_rms, chi2, dof = f.ftest(FD4, "FD", remove=False, full_output=True)
    # Test removing parameter
    FD3 = param.prefixParameter(
        parameter_type="float", name="FD3", value=0.0, units=u.s, frozen=False
    )
    ft = f.ftest(FD3, "FD", remove=True)
    assert isinstance(ft, float) or isinstance(ft, bool)
github nanograv / PINT / pint / scripts / htest_optimize.py View on Github external
def main(argv=None):

    if len(argv)==3:
        eventfile, parfile, weightcol = sys.argv[1:]
    elif len(argv)==2:
        eventfile, parfile = sys.argv[1:]
        weightcol=None
    else:
        print("usage: htest_optimize eventfile parfile [weightcol]")
        sys.exit()

    # Read in initial model
    modelin = pint.models.get_model(parfile)
    # Remove the dispersion delay as it is unnecessary
    modelin.delay_funcs['L1'].remove(modelin.dispersion_delay)
    # Set the target coords for automatic weighting if necessary
    if 'ELONG' in modelin.params:
        tc = SkyCoord(modelin.ELONG.quantity,modelin.ELAT.quantity,
            frame='barycentrictrueecliptic')
    else:
        tc = SkyCoord(modelin.RAJ.quantity,modelin.DECJ.quantity,frame='icrs')

    target = tc if weightcol=='CALC' else None

    # TODO: make this properly handle long double
    if not (os.path.isfile(eventfile+".pickle") or
        os.path.isfile(eventfile+".pickle.gz")):
        # Read event file and return list of TOA objects
        tl = fermi.load_Fermi_TOAs(eventfile, weightcolumn=weightcol,
github nanograv / PINT / src / pint / scripts / htest_optimize.py View on Github external
def main(argv=None):

    if len(argv) == 3:
        eventfile, parfile, weightcol = sys.argv[1:]
    elif len(argv) == 2:
        eventfile, parfile = sys.argv[1:]
        weightcol = None
    else:
        print("usage: htest_optimize eventfile parfile [weightcol]")
        sys.exit()

    # Read in initial model
    modelin = pint.models.get_model(parfile)
    # Remove the dispersion delay as it is unnecessary
    modelin.delay_funcs.remove(modelin.dispersion_delay)
    # Set the target coords for automatic weighting if necessary
    if "ELONG" in modelin.params:
        tc = SkyCoord(
            modelin.ELONG.quantity,
            modelin.ELAT.quantity,
            frame="barycentrictrueecliptic",
        )
    else:
        tc = SkyCoord(modelin.RAJ.quantity, modelin.DECJ.quantity, frame="icrs")

    target = tc if weightcol == "CALC" else None

    # TODO: make this properly handle long double
    if not (
github hgrecco / pint / pint / testsuite / test_formatter.py View on Github external
# -*- coding: utf-8 -*-

from pint import formatting as fmt
from pint.testsuite import QuantityTestCase


class TestFormatter(QuantityTestCase):
    def test_join(self):
        for empty in (tuple(), []):
            self.assertEqual(fmt._join("s", empty), "")
        self.assertEqual(fmt._join("*", "1 2 3".split()), "1*2*3")
        self.assertEqual(fmt._join("{0}*{1}", "1 2 3".split()), "1*2*3")

    def test_formatter(self):
        self.assertEqual(fmt.formatter(dict().items()), "")
        self.assertEqual(fmt.formatter(dict(meter=1).items()), "meter")
        self.assertEqual(fmt.formatter(dict(meter=-1).items()), "1 / meter")
        self.assertEqual(
            fmt.formatter(dict(meter=-1).items(), as_ratio=False), "meter ** -1"
        )

        self.assertEqual(
            fmt.formatter(dict(meter=-1, second=-1).items(), as_ratio=False),
github hgrecco / pint / pint / testsuite / test_unit.py View on Github external
[ureg.Quantity(3.0, "kilogram")],
            ],
        )

    def test_parse_pattern_many_results_two_units(self):
        ureg = self.ureg
        self.assertEqual(
            ureg.parse_pattern("10'10 or 10'11", "{foot}'{inch}", many=True),
            [
                [ureg.Quantity(10.0, "foot"), ureg.Quantity(10.0, "inch")],
                [ureg.Quantity(10.0, "foot"), ureg.Quantity(11.0, "inch")],
            ],
        )


class TestCompatibleUnits(QuantityTestCase):
    FORCE_NDARRAY = False

    def setUp(self):
        super().setUp()
        self.ureg = UnitRegistry(force_ndarray=self.FORCE_NDARRAY)
        self.Q_ = self.ureg.Quantity
        self.U_ = self.ureg.Unit

    def _test(self, input_units):
        gd = self.ureg.get_dimensionality
        dim = gd(input_units)
        equiv = self.ureg.get_compatible_units(input_units)
        for eq in equiv:
            self.assertEqual(gd(eq), dim)
        self.assertEqual(equiv, self.ureg.get_compatible_units(dim))
github pymedusa / Medusa / ext / pint / testsuite / test_issues.py View on Github external
def test_issue54(self):
        ureg = UnitRegistry()
        self.assertEqual((1*ureg.km/ureg.m + 1).magnitude, 1001)
github hgrecco / pint / pint / testsuite / test_issues.py View on Github external
def test_issue170(self):
        Q_ = UnitRegistry().Quantity
        q = Q_("1 kHz") / Q_("100 Hz")
        iq = int(q)
        self.assertEqual(iq, 10)
        self.assertIsInstance(iq, int)
github suavecode / SUAVE / trunk / SUAVE / Plugins / pint / testsuite / test_issues.py View on Github external
def test_issue66b(self):
        ureg = UnitRegistry()
        self.assertEqual(ureg.get_base_units(ureg.degK.units),
                         (None, UnitsContainer({'degK': 1})))
        self.assertEqual(ureg.get_base_units(ureg.degC.units),
                         (None, UnitsContainer({'degK': 1})))
github hgrecco / pint / pint / testsuite / test_application_registry.py View on Github external
def setUp(self):
        super().setUp()
        self.ureg_bak = get_application_registry()
        self.ureg1 = UnitRegistry(None)
        self.ureg1.define("foo = [dim1]")
        self.ureg1.define("bar = foo / 2")
        self.ureg2 = UnitRegistry(None)
        self.ureg2.define("foo = [dim2]")
        self.ureg2.define("bar = foo / 3")
github hgrecco / pint / pint / testsuite / test_non_int.py View on Github external
value = self.NON_INT_TYPE("4.2")

        for args in (
            (value, "meter"),
            (value, UnitsContainer(meter=1)),
            (value, self.ureg.meter),
            ("4.2*meter",),
            ("4.2/meter**(-1)",),
            (self.Q_(value, "meter"),),
        ):
            x = self.Q_(*args)
            self.assertEqual(x.magnitude, value)
            self.assertEqual(x.units, self.ureg.UnitsContainer(meter=1))

        x = self.Q_(value, UnitsContainer(length=1))
        y = self.Q_(x)
        self.assertEqual(x.magnitude, y.magnitude)
        self.assertEqual(x.units, y.units)
        self.assertIsNot(x, y)

        x = self.Q_(value, None)
        self.assertEqual(x.magnitude, value)
        self.assertEqual(x.units, UnitsContainer())

        with self.capture_log() as buffer:
            self.assertEqual(
                value * self.ureg.meter,
                self.Q_(value, self.NON_INT_TYPE("2") * self.ureg.meter),
            )
            self.assertEqual(len(buffer), 1)