Exemple #1
0
    def __init__(
        self,
        description="",
        application={},
        coordinates_offset=None,
        origin_offset=None,
        quantity_name=None,
        period=None,
        label="",
        unit=None,
        **kwargs,
    ):
        r"""Instantiate a BaseIndependentVariable class."""

        self._description = description
        self._application = application
        self._coordinates_offset = ScalarQuantity(coordinates_offset,
                                                  unit).quantity
        self._origin_offset = ScalarQuantity(origin_offset, unit).quantity
        self._quantity_name = check_quantity_name(quantity_name, unit)

        value = ScalarQuantity(period, unit).quantity
        if value.value == 0.0:
            value = inf * value.unit
        self._period = value

        self.label = label
        self._unit = unit
        self._equivalencies = None
Exemple #2
0
    def _get_quantitative_dictionary(self):
        r"""Return the object as a python dictionary."""
        obj = {}

        # The description key is added at the child class level.
        if self._coordinates_offset.value != 0.0:
            obj["coordinates_offset"] = ScalarQuantity(
                self._coordinates_offset).format()

        if self._origin_offset.value != 0.0:
            obj["origin_offset"] = ScalarQuantity(self._origin_offset).format()

        if self._quantity_name not in [None, "unknown", "dimensionless"]:
            obj["quantity_name"] = self._quantity_name

        if self._period.value not in [0.0, inf]:
            obj["period"] = ScalarQuantity(self._period).format()

        if self.label.strip() != "":
            obj["label"] = self.label

        if self._application != {}:
            obj["application"] = self._application

        return obj
Exemple #3
0
 def _to(self, unit="", equivalencies=None):
     r"""Convert the unit to given value `unit`."""
     unit = validate(unit, "unit", str)
     if equivalencies is None:
         self._unit = ScalarQuantity(unit, self._unit).quantity.unit
     else:
         self._unit = ScalarQuantity(unit).quantity.unit
     self._equivalencies = equivalencies
Exemple #4
0
 def __init__(
     self,
     name="",
     unit="",
     quantity_name=None,
     encoding="none",
     numeric_type="float32",
     quantity_type="scalar",
     components=None,
     component_labels=None,
     description="",
     application={},
     **kwargs,
 ):
     r"""Instantiate a BaseDependentVariable class."""
     self.name = name
     self._unit = ScalarQuantity(f"1 {unit}").quantity.unit
     self._quantity_name = check_quantity_name(quantity_name, self._unit)
     self.encoding = encoding
     self._numeric_type = NumericType(numeric_type)
     self._quantity_type = QuantityType(quantity_type)
     self.set_component_labels(component_labels)
     self.description = description
     self.application = application
     self._components = components
Exemple #5
0
 def _get_coordinates(self, values):
     _unit = self._unit
     _value = [
         ScalarQuantity(item, _unit).quantity.to(_unit).value
         for item in values
     ]
     _value = np.asarray(_value, dtype=np.float64) * _unit
     self._count = _value.size
     self._values = values
     self._coordinates = _value
Exemple #6
0
    def __init__(self, values, **kwargs):
        """Instantiate a MonotonicDimension class."""
        self._unit = ScalarQuantity(values[0]).quantity.unit
        super(MonotonicDimension, self).__init__(unit=self._unit, **kwargs)

        _reciprocal_unit = self._unit**-1
        self.reciprocal = ReciprocalVariable(unit=_reciprocal_unit,
                                             **kwargs["reciprocal"])

        self._get_coordinates(values)
Exemple #7
0
    def period(self, value=None):
        if isinstance(value, Quantity):
            value = str(value)
        if not isinstance(value, str):
            raise TypeError(type_error(str, "period", value))

        lst = ["inf", "Inf", "infinity", "Infinity", "∞"]
        if value.strip().split()[0] in lst:
            value = inf * self._unit
            self._period = value
        else:
            self._period = ScalarQuantity(value, self._unit).quantity
Exemple #8
0
def _axis_label(
    label, unit, made_dimensionless=False, dimensionless_unit=None, label_type=""
):
    # if made_dimensionless:
    #     if dimensionless_unit != "":
    #         return "{0} / {1}".format(label, dimensionless_unit)
    #     return label

    if unit != "":
        if label_type == "":
            return "{0} / ({1})".format(label, ScalarQuantity(1 * unit).format("unit"))
        # if label_type == "latex":
        #     return "{0} / ({1})".format(label, unit.to_string("latex"))
    return label
Exemple #9
0
def test_unit():
    a = ScalarQuantity("1 tr").quantity
    assert str(a) == "1.0 tr"
    assert str(a.to("cycle")) == "1.0 cycle"
    # assert ScalarQuantity(a).format() == '1.0 tr'

    a = ScalarQuantity("10 cm^-1/s")
    assert str(a) == "10.0 1 / (cm s)"
    assert ScalarQuantity(a).quantity == a.quantity

    a = ScalarQuantity("1 deg").quantity
    assert str(a) == "1.0 deg"
    assert ScalarQuantity(a).format() == "1.0 °"
    assert ScalarQuantity("1 deg").format() == "1.0 °"

    a = ScalarQuantity("(54.3/2) ppm").quantity
    assert str(a) == "27.15 ppm"
    assert ScalarQuantity(a).format() == "27.15 ppm"

    a = ScalarQuantity("(54.3/2) (µHz/Hz)").quantity
    assert str(a) == "27.15 uHz / Hz"
    assert ScalarQuantity(a).format() == "27.15 Hz^-1 * µHz"
    assert str(a.to("ppm")) == "27.15 ppm"

    a = ScalarQuantity("5 kg * m / s").quantity
    b = a * ScalarQuantity("1 m / s").quantity
    assert str(a) == "5.0 kg m / s"
    assert ScalarQuantity(a).format() == "5.0 kg * m * s^-1"
    assert ScalarQuantity(b).format() == "5.0 kg * m^2 * s^-2"
    assert ScalarQuantity(b).format("unit") == "kg * m^2 * s^-2"
    assert str(b.to("J")) == "5.0 J"

    a = ScalarQuantity("5e-7 s").quantity
    assert str(a) == "5e-07 s"
    assert ScalarQuantity(a).format() == "5e-07 s"
    assert ScalarQuantity(a.to("us")).format() == "0.5 µs"
    assert ScalarQuantity(a.to("us")).format("unit") == "µs"

    a = ScalarQuantity("5e-7 * 2 s").quantity
    assert str(a) == "1e-06 s"
    assert ScalarQuantity(a).format() == "1e-06 s"
    assert ScalarQuantity(a.to("us")).format() == "1.0 µs"
Exemple #10
0
    def _get_dictionary(self,
                        filename=None,
                        dataset_index=None,
                        for_display=False,
                        version=None):
        r"""Return a dictionary object of the base class."""
        obj = {}
        if self._description.strip() != "":
            obj["description"] = str(self._description)

        if self._name.strip() != "":
            obj["name"] = self._name

        if str(self._unit) != "":
            obj["unit"] = ScalarQuantity(1.0 * self._unit).format("unit")

        if self._quantity_name not in ["dimensionless", "unknown", None]:
            obj["quantity_name"] = self._quantity_name

        obj["encoding"] = str(self._encoding)
        obj["numeric_type"] = str(self._numeric_type)
        obj["quantity_type"] = str(self._quantity_type)

        # print_label = False
        for label in self._component_labels:
            if label.strip() != "":
                obj["component_labels"] = self._component_labels
                break

        # if print_label:
        #     obj["component_labels"] = self._component_labels

        if self._application != {}:
            obj["application"] = self._application

        if for_display:
            obj["components"] = reduced_display(self._components)
            del obj["encoding"]
            return obj

        c = self.ravel_data()

        if self.encoding == "none":
            obj["components"] = c.tolist()

        if self.encoding == "base64":
            obj["components"] = [
                base64.b64encode(item).decode("utf-8") for item in c
            ]

        if self.encoding == "raw":
            url_relative_path, absolute_path = get_relative_uri_path(
                dataset_index, filename)

            c.ravel().tofile(absolute_path)

            obj["type"] = "external"
            obj["components_url"] = url_relative_path
            del obj["encoding"]

        del c
        return obj
Exemple #11
0
 def origin_offset(self, value):
     allowed_types = (Quantity, str, ScalarQuantity)
     value = validate(value, "origin_offset", allowed_types)
     self._origin_offset = ScalarQuantity(value, self._unit).quantity
Exemple #12
0
 def coordinates_offset(self, value):
     allowed_types = (Quantity, str, ScalarQuantity)
     value = validate(value, "coordinates_offset", allowed_types)
     value = ScalarQuantity(value, self._unit).quantity
     self._coordinates_offset = value
Exemple #13
0
def test_monotonic_new():
    data = cp.new()
    dim = {
        "type": "monotonic",
        "description": "Far far away.",
        "coordinates": ["1 m", "100 m", "1 km", "1 Gm", "0.25 lyr"],
    }
    data.add_dimension(dim)

    # description
    assert data.dimensions[0].description == "Far far away."
    data.dimensions[0].description = "A galaxy far far away."
    assert data.dimensions[0].description == "A galaxy far far away."

    error = "Expecting an instance of type"
    with pytest.raises(TypeError, match=".*{0}.*".format(error)):
        data.dimensions[0].description = 12

    # dimension type
    assert data.dimensions[0].type == "monotonic"

    # values
    assert data.dimensions[0].subtype._values == [
        "1 m",
        "100 m",
        "1 km",
        "1 Gm",
        "0.25 lyr",
    ]

    # increment
    error = "'MonotonicDimension' object has no attribute 'increment'"
    with pytest.raises(AttributeError, match=".*{0}.*".format(error)):
        data.dimensions[0].increment

    # label
    assert data.dimensions[0].label == ""
    data.dimensions[0].label = "some string"
    assert data.dimensions[0].label == "some string"

    error = "Expecting an instance of type"
    with pytest.raises(TypeError, match=".*{0}.*".format(error)):
        data.dimensions[0].label = {}

    # count
    assert data.dimensions[0].count == 5
    error = "Cannot set count,"
    with pytest.raises(ValueError, match=".*{0}.*".format(error)):
        data.dimensions[0].count = 12

    error = "Expecting an instance of type"
    with pytest.raises(TypeError, match=".*{0}.*".format(error)):
        data.dimensions[0].count = "12"

    # coordinates_offset
    error = "`MonotonicDimension` has no attribute `coordinates_offset`."
    with pytest.raises(AttributeError, match=".*{0}.*".format(error)):
        data.dimensions[0].coordinates_offset

    # origin offset
    assert str(data.dimensions[0].origin_offset) == "0.0 m"

    data.dimensions[0].origin_offset = ScalarQuantity("3.1415 m")
    assert str(data.dimensions[0].origin_offset) == "3.1415 m"

    data.dimensions[0].origin_offset = "1 lyr"
    assert str(data.dimensions[0].origin_offset) == "1.0 lyr"

    error = "Expecting an instance of type"
    with pytest.raises(TypeError, match=".*{0}.*".format(error)):
        data.dimensions[0].origin_offset = {"12 m"}

    # quantity_name
    assert data.dimensions[0].quantity_name == "length"

    error = "This attribute is not yet implemented"
    with pytest.raises(NotImplementedError, match=".*{0}.*".format(error)):
        data.dimensions[0].quantity_name = "area/length"

    # period
    assert str(data.dimensions[0].period) == "inf m"
    data.dimensions[0].period = "Infinity m"
    assert str(data.dimensions[0].period) == "inf m"
    data.dimensions[0].period = "20 m^2/m"
    assert str(data.dimensions[0].period) == "20.0 m"
    data.dimensions[0].period = "(1/0) m^5/m^4"
    assert str(data.dimensions[0].period) == "inf m"

    # fft output order
    error = "'MonotonicDimension' object has no attribute 'complex_fft'"
    with pytest.raises(AttributeError, match=".*{0}.*".format(error)):
        data.dimensions[0].complex_fft

    # coordinates
    assert np.allclose(
        data.dimensions[0].coordinates.value,
        np.asarray([
            1.00000000e00, 1.00000000e02, 1.00000000e03, 1.00000000e09,
            2.36518262e15
        ]),
    )

    # coordinates
    assert np.allclose(
        data.dimensions[0].absolute_coordinates.value,
        np.asarray([
            9.46073047e15, 9.46073047e15, 9.46073047e15, 9.46073147e15,
            1.18259131e16
        ]),
    )

    dict1 = {
        "csdm": {
            "version":
            "1.0",
            "dimensions": [{
                "type":
                "monotonic",
                "description":
                "A galaxy far far away.",
                "coordinates": ["1 m", "100 m", "1 km", "1 Gm", "0.25 lyr"],
                "origin_offset":
                "1.0 lyr",
                "quantity_name":
                "length",
                "label":
                "some string",
                "reciprocal": {
                    "quantity_name": "wavenumber"
                },
            }],
            "dependent_variables": [],
        }
    }
    assert data.data_structure == json.dumps(dict1,
                                             ensure_ascii=False,
                                             sort_keys=False,
                                             indent=2)
    assert data.dimensions[0].to_dict() == dict1["csdm"]["dimensions"][0]
Exemple #14
0
def test_linear_new():
    data = cp.new()
    dim = {
        "type": "linear",
        "increment": "10 m/s",
        "count": 10,
        "coordinates_offset": "5 m/s",
    }
    data.add_dimension(dim)

    assert data.dimensions[0].type == "linear"

    error = "can't set attribute"
    with pytest.raises(AttributeError, match=".*{0}.*".format(error)):
        data.dimensions[0].type = "monotonic"

    assert str(data.dimensions[0].increment) == "10.0 m / s"
    data.dimensions[0].increment = ScalarQuantity("20.0 m / s")
    assert str(data.dimensions[0].increment) == "20.0 m / s"
    data.dimensions[0].increment = 20.0 * u.Unit("m / s")
    assert str(data.dimensions[0].increment) == "20.0 m / s"

    error = "Expecting an instance of type"
    with pytest.raises(TypeError, match=".*{0}.*".format(error)):
        data.dimensions[0].increment = 10

    data.dimensions[0].increment = "20/2 m / s"
    assert str(data.dimensions[0].increment) == "10.0 m / s"

    assert data.dimensions[0].count == 10

    assert data.dimensions[0].application == {}
    data.dimensions[0].application = {"my_application": {}}
    assert data.dimensions[0].application == {"my_application": {}}
    error = "Expecting an instance of type"
    with pytest.raises(TypeError, match=".*{0}.*".format(error)):
        data.dimensions[0].application = "my_application"

    assert str(data.dimensions[0].coordinates_offset) == "5.0 m / s"

    error = "Expecting an instance of type"
    with pytest.raises(TypeError, match=".*{0}.*".format(error)):
        data.dimensions[0].coordinates_offset = 50

    data.dimensions[0].coordinates_offset = ScalarQuantity("5.0 m / s")
    assert str(data.dimensions[0].coordinates_offset) == "5.0 m / s"

    assert str(data.dimensions[0].origin_offset) == "0.0 m / s"
    assert data.dimensions[0].quantity_name == "speed"
    assert str(data.dimensions[0].period) == "inf m / s"
    assert data.dimensions[0].complex_fft is False
    assert np.all(
        data.dimensions[0].coordinates.value == np.arange(10) * 10.0 + 5.0)

    data.dimensions[0].count = 12
    assert data.dimensions[0].count == 12
    assert np.all(
        data.dimensions[0].coordinates.value == np.arange(12) * 10.0 + 5.0)
    assert np.all(
        data.dimensions[0].absolute_coordinates.value == np.arange(12) * 10.0 +
        5.0)

    data.dimensions[0].origin_offset = "1 km/s"
    assert str(data.dimensions[0].origin_offset) == "1.0 km / s"
    assert np.all(
        data.dimensions[0].coordinates.value == np.arange(12) * 10.0 + 5.0)

    test_with = np.arange(12) * 10.0 + 5.0 + 1000.0
    assert np.all(data.dimensions[0].absolute_coordinates.value == test_with)

    data.dimensions[0].increment = "20 m/s"
    assert str(data.dimensions[0].increment) == "20.0 m / s"
    assert np.all(
        data.dimensions[0].coordinates.value == np.arange(12) * 20.0 + 5.0)

    test_with = np.arange(12) * 20.0 + 5.0 + 1000.0
    assert np.all(data.dimensions[0].absolute_coordinates.value == test_with)

    data.dimensions[0].complex_fft = True
    assert data.dimensions[0].complex_fft is True
    assert np.all(
        data.dimensions[0].coordinates.value == (np.arange(12) - 6) * 20.0 +
        5.0)

    test_with = (np.arange(12) - 6) * 20.0 + 5.0 + 1000.0
    assert np.all(data.dimensions[0].absolute_coordinates.value == test_with)

    dict1 = {
        "csdm": {
            "version":
            "1.0",
            "dimensions": [{
                "type": "linear",
                "count": 12,
                "increment": "20.0 m * s^-1",
                "coordinates_offset": "5.0 m * s^-1",
                "origin_offset": "1.0 km * s^-1",
                "quantity_name": "speed",
                "application": {
                    "my_application": {}
                },
                "complex_fft": True,
            }],
            "dependent_variables": [],
        }
    }
    assert data.data_structure == json.dumps(dict1,
                                             ensure_ascii=False,
                                             sort_keys=False,
                                             indent=2)
    assert data.dimensions[0].to_dict() == dict1["csdm"]["dimensions"][0]