How to use the quantities.UncertainQuantity function in quantities

To help you get started, we’ve selected a few quantities 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 CINPLA / exdir / tests / test_quantities.py View on Github external
result = convert_quantities(np.array([1, 2, 3]))
    assert result == [1, 2, 3]

    result = convert_quantities(1)
    assert result == 1

    result = convert_quantities(2.3)
    assert result == 2.3

    pq_value = pq.UncertainQuantity([1, 2], "m", [3, 4])
    result = convert_quantities(pq_value)
    assert result == {"unit": "m", "uncertainty": [3, 4], "value": [1.0, 2.0]}

    pq_values = {"quantity": pq.Quantity(1, "m"),
                 "uq_quantity": pq.UncertainQuantity([1, 2], "m", [3, 4])}
    result = convert_quantities(pq_values)
    assert(result == {"quantity": {"unit": "m", "value": 1},
                      "uq_quantity": {"unit": "m", "uncertainty": [3, 4], "value": [1.0, 2.0]}})

    pq_values = {"list": [1, 2, 3], "quantity": pq.Quantity(1, "m")}
    pq_dict = {"list": [1, 2, 3], "quantity": {"unit": "m", "value": 1}}
    result = convert_quantities(pq_values)
    assert result == pq_dict
github JelteF / PyLaTeX / tests / test_quantities.py View on Github external
def test_quantity_uncertain():
    t = pq.UncertainQuantity(7., pq.second, 1.)
    q1 = Quantity(t)
    assert q1.dumps() == r'\SI{7.0 +- 1.0}{\second}'
github CINPLA / exdir / tests / test_quantities.py View on Github external
assert result == {"value": 1, "unit": "m"}

    pq_value = pq.Quantity([1, 2, 3], "m")
    result = convert_quantities(pq_value)
    assert result == {"value": [1, 2, 3], "unit": "m"}

    result = convert_quantities(np.array([1, 2, 3]))
    assert result == [1, 2, 3]

    result = convert_quantities(1)
    assert result == 1

    result = convert_quantities(2.3)
    assert result == 2.3

    pq_value = pq.UncertainQuantity([1, 2], "m", [3, 4])
    result = convert_quantities(pq_value)
    assert result == {"unit": "m", "uncertainty": [3, 4], "value": [1.0, 2.0]}

    pq_values = {"quantity": pq.Quantity(1, "m"),
                 "uq_quantity": pq.UncertainQuantity([1, 2], "m", [3, 4])}
    result = convert_quantities(pq_values)
    assert(result == {"quantity": {"unit": "m", "value": 1},
                      "uq_quantity": {"unit": "m", "uncertainty": [3, 4], "value": [1.0, 2.0]}})

    pq_values = {"list": [1, 2, 3], "quantity": pq.Quantity(1, "m")}
    pq_dict = {"list": [1, 2, 3], "quantity": {"unit": "m", "value": 1}}
    result = convert_quantities(pq_values)
    assert result == pq_dict
github CINPLA / exdir / exdir / core.py View on Github external
def convert_back_quantities(value):
    """
    Converts quantities back from dictionary
    """
    result = value
    if isinstance(value, dict):
        if "unit" in value and "value" in value and "uncertainty" in value:
            try:
                result = pq.UncertainQuantity(value["value"],
                                              value["unit"],
                                              value["uncertainty"])
            except Exception:
                pass
        elif "unit" in value and "value" in value:
            try:
                result = pq.Quantity(value["value"], value["unit"])
            except Exception:
                pass
        else:
            try:
                for key, value in result.items():
                    result[key] = convert_back_quantities(value)
            except AttributeError:
                pass
github JelteF / PyLaTeX / examples / quantities_ex.py View on Github external
options={'round-precision': 4, 'round-mode': 'figures'})
    math = Math(data=['F=', q1])
    subsection.append(math)
    section.append(subsection)

    subsection = Subsection('Scalars without units')
    world_population = 7400219037
    N = Quantity(world_population, options={'round-precision': 2,
                                            'round-mode': 'figures'},
                 format_cb="{0:23.17e}".format)
    subsection.append(Math(data=['N=', N]))
    section.append(subsection)

    subsection = Subsection('Scalars with uncertainties')
    width = pq.UncertainQuantity(7.0, pq.meter, .4)
    length = pq.UncertainQuantity(6.0, pq.meter, .3)
    area = Quantity(width * length, options='separate-uncertainty',
                    format_cb=lambda x: "{0:.1f}".format(float(x)))
    subsection.append(Math(data=['A=', area]))
    section.append(subsection)

    doc.append(section)
    doc.generate_pdf('quantities_ex', clean_tex=False)
github JelteF / PyLaTeX / pylatex / quantities.py View on Github external
if format_cb is None:
                try:
                    return np.array_str(val)
                except AttributeError:
                    return escape_latex(val)  # Python float and int
            else:
                return format_cb(val)

        if isinstance(quantity, pq.UncertainQuantity):
            magnitude_str = '{} +- {}'.format(
                _format(quantity.magnitude),
                _format(quantity.uncertainty.magnitude))
        elif isinstance(quantity, pq.Quantity):
            magnitude_str = _format(quantity.magnitude)

        if isinstance(quantity, (pq.UncertainQuantity, pq.Quantity)):
            unit_str = _dimensionality_to_siunitx(quantity.dimensionality)
            super().__init__(command='SI', arguments=(magnitude_str, unit_str),
                             options=options)
        else:
            super().__init__(command='num', arguments=_format(quantity),
                             options=options)

        self.arguments._escape = False  # dash in e.g. \num{3 +- 2}
        if self.options is not None:
            self.options._escape = False  # siunitx uses dashes in kwargs
github CINPLA / exdir / exdir / core.py View on Github external
def set_data(self, data):
        if self.io_mode == self.OpenMode.READ_ONLY:
            raise IOError("Cannot write data to file in read only ("r") mode")
        if isinstance(data, pq.Quantity):
            result = data.magnitude
            self.attrs["unit"] = data.dimensionality.string
            if isinstance(data, pq.UncertainQuantity):
                self.attrs["uncertainty"] = data.uncertainty
        else:
            result = data
        if result is not None:
            np.save(self.data_filename, result)
github CINPLA / exdir / exdir / plugins / quantities.py View on Github external
attrs = {}

        meta = dataset_data.meta

        if isinstance(data, pq.Quantity):
            # TODO consider adding a helper class that wraps defaultdict and converts back again
            if "plugins" not in meta:
                meta["plugins"] = {}

            if "quantities" not in meta["plugins"]:
                meta["plugins"]["quantities"] = {}

            meta["plugins"]["quantities"]["required"] = True
            result = data.magnitude
            attrs["unit"] = data.dimensionality.string
            if isinstance(data, pq.UncertainQuantity):
                attrs["uncertainty"] = data.uncertainty
        else:
            result = data

        dataset_data.data = data
        dataset_data.attrs = attrs
        dataset_data.meta = dict(meta)

        return dataset_data
github JelteF / PyLaTeX / pylatex / quantities.py View on Github external
import numpy as np
        import quantities as pq

        self.quantity = quantity
        self._format_cb = format_cb

        def _format(val):
            if format_cb is None:
                try:
                    return np.array_str(val)
                except AttributeError:
                    return escape_latex(val)  # Python float and int
            else:
                return format_cb(val)

        if isinstance(quantity, pq.UncertainQuantity):
            magnitude_str = '{} +- {}'.format(
                _format(quantity.magnitude),
                _format(quantity.uncertainty.magnitude))
        elif isinstance(quantity, pq.Quantity):
            magnitude_str = _format(quantity.magnitude)

        if isinstance(quantity, (pq.UncertainQuantity, pq.Quantity)):
            unit_str = _dimensionality_to_siunitx(quantity.dimensionality)
            super().__init__(command='SI', arguments=(magnitude_str, unit_str),
                             options=options)
        else:
            super().__init__(command='num', arguments=_format(quantity),
                             options=options)

        self.arguments._escape = False  # dash in e.g. \num{3 +- 2}
        if self.options is not None: