Beispiel #1
0
    def __init__(self,
                 name=None,
                 ctype=None,
                 units=None,
                 segment_lengths=None,
                 coord_ref_sys=None):
        """*Do not use.*"""

        if name is not None:
            self.name = name

        if ctype is not None:
            self.set_trait('ctype', ctype)

        if units is not None:
            self.set_trait('units', units)

        if coord_ref_sys is not None:
            self.set_trait('coord_ref_sys', coord_ref_sys)

        if segment_lengths is not None:
            if np.array(segment_lengths).ndim == 0:
                segment_lengths = make_coord_delta(segment_lengths)
            else:
                segment_lengths = make_coord_delta_array(segment_lengths)
                segment_lengths.setflags(write=False)

            self.set_trait('segment_lengths', segment_lengths)

        super(Coordinates1d, self).__init__()
Beispiel #2
0
    def _validate_boundary(self, d):
        val = d["value"]
        for dim, boundary in val.items():
            if dim not in VALID_DIMENSION_NAMES:
                raise ValueError("Invalid dimension '%s' in boundary" % dim)
            if np.array(boundary).ndim == 0:
                try:
                    delta = make_coord_delta(boundary)
                except ValueError:
                    raise ValueError(
                        "Invalid boundary for dimension '%s' ('%s' is not a valid coordinate delta)"
                        % (dim, boundary))

                if np.array(delta).astype(float) < 0:
                    raise ValueError(
                        "Invalid boundary for dimension '%s' (%s < 0)" %
                        (dim, delta))

            if np.array(boundary).ndim == 1:
                make_coord_delta_array(boundary)
                raise NotImplementedError(
                    "Non-centered boundary not yet supported for dimension '%s'"
                    % dim)

            if np.array(boundary).ndim == 2:
                for elem in boundary:
                    make_coord_delta_array(elem)
                raise NotImplementedError(
                    "Non-uniform boundary not yet supported for dimension '%s'"
                    % dim)

        return val
    def __init__(self, start, stop, step=None, size=None, name=None):
        """
        Create uniformly-spaced 1d coordinates from a `start`, `stop`, and `step` or `size`.

        Parameters
        ----------
        start : float or datetime64
            Start coordinate.
        stop : float or datetime64
            Stop coordinate.
        step : float or timedelta64
            Signed, nonzero step between coordinates (either step or size required).
        size : int
            Number of coordinates (either step or size required).
        name : str, optional
            Dimension name, one of 'lat', 'lon', 'time', or 'alt'.
        """

        if step is not None and size is not None:
            raise TypeError("only one of 'step' and 'size' is allowed")
        elif step is None and size is None:
            raise TypeError("'step' or 'size' is required")

        # validate and set start, stop, and step
        start = make_coord_value(start)
        stop = make_coord_value(stop)

        if step is not None:
            step = make_coord_delta(step)
        elif isinstance(size, (int, np.long, np.integer)) and not isinstance(size, np.timedelta64):
            step = divide_delta(stop - start, size - 1)
        else:
            raise TypeError("size must be an integer, not '%s'" % type(size))

        if isinstance(start, float) and isinstance(stop, float) and isinstance(step, float):
            fstep = step
        elif isinstance(start, np.datetime64) and isinstance(stop, np.datetime64) and isinstance(step, np.timedelta64):
            fstep = step.astype(float)
        else:
            raise TypeError(
                "UniformCoordinates1d mismatching types (start '%s', stop '%s', step '%s')."
                % (type(start), type(stop), type(step))
            )

        if fstep == 0:
            raise ValueError("Uniformcoordinates1d step cannot be zero")

        if fstep <= 0 and start < stop:
            raise ValueError("UniformCoordinates1d step must be greater than zero if start < stop.")

        if fstep >= 0 and start > stop:
            raise ValueError("UniformCoordinates1d step must be less than zero if start > stop.")

        self.set_trait("start", start)
        self.set_trait("stop", stop)
        self.set_trait("step", step)

        # set common properties
        super(UniformCoordinates1d, self).__init__(name=name)
 def _time_to_float(self, time, time_source, time_request):
     dtype0 = time_source.coordinates[0].dtype
     dtype1 = time_request.coordinates[0].dtype
     dtype = dtype0 if dtype0 > dtype1 else dtype1
     time = make_coord_delta(time)
     if isinstance(time, np.timedelta64):
         time1 = (time + np.datetime64("2000")).astype(dtype).astype(
             float) - (np.datetime64("2000").astype(dtype).astype(float))
     return time1
 def from_tuple(cls, items, **kwargs):
     if not isinstance(items, tuple) or len(items) != 3:
         raise ValueError(
             "UniformCoordinates1d.from_tuple expects a tuple of (start, stop, step/size), got %s" % (items,)
         )
     elif isinstance(items[2], int):
         return cls(items[0], items[1], size=items[2], **kwargs)
     else:
         step = make_coord_delta(items[2])
         return cls(items[0], items[1], step, **kwargs)
Beispiel #6
0
    def get_area_bounds(self, boundary):
        """
        Get low and high coordinate area bounds.

        Arguments
        ---------
        boundary : float, timedelta, array, None
            Boundary offsets in this dimension.

            * For a centered uniform boundary (same for every coordinate), use a single positive float or timedelta
                offset. This represents the "total segment length" / 2.
            * For a uniform boundary (segment or polygon same for every coordinate), use an array of float or
                timedelta offsets
            * For a fully specified boundary, use an array of boundary arrays (2-D array, N_coords x boundary spec),
                 one per coordinate. The boundary_spec can be a single number, two numbers, or an array of numbers.
            * For point coordinates, use None.

        Returns
        -------
        low: float, np.datetime64
            low area bound
        high: float, np.datetime64
            high area bound
        """

        # point coordinates
        if boundary is None:
            return self.bounds

        # empty coordinates
        if self.size == 0:
            return self.bounds

        if np.array(boundary).ndim == 0:
            # shortcut for uniform centered boundary
            boundary = make_coord_delta(boundary)
            lo_offset = -boundary
            hi_offset = boundary
        elif np.array(boundary).ndim == 1:
            # uniform boundary polygon
            boundary = make_coord_delta_array(boundary)
            lo_offset = min(boundary)
            hi_offset = max(boundary)
        else:
            L, H = self.argbounds
            lo_offset = min(make_coord_delta_array(boundary[L]))
            hi_offset = max(make_coord_delta_array(boundary[H]))

        lo, hi = self.bounds
        lo = add_coord(lo, lo_offset)
        hi = add_coord(hi, hi_offset)

        return lo, hi
    def __init__(self, start, stop, step=None, size=None, name=None, fix_stop_val=False):
        """
        Create uniformly-spaced 1d coordinates from a `start`, `stop`, and `step` or `size`.

        Parameters
        ----------
        start : float or datetime64
            Start coordinate.
        stop : float or datetime64
            Stop coordinate.
        step : float or timedelta64
            Signed, nonzero step between coordinates (either step or size required).
        size : int
            Number of coordinates (either step or size required).
        name : str, optional
            Dimension name, one of 'lat', 'lon', 'time', or 'alt'.
        fix_stop_val : bool, optional
            Default is False. If True, the constructor will modify the step to be consistent
            instead of the stop value. Otherwise, the stop value *may* be modified to ensure that
            stop = start + step * size

        Notes
        ------
        When the user specifies fix_stop_val, then `stop` will always be exact as specified by the user.

        For floating point coordinates, the specified `step` my be changed internally to satisfy floating point consistency.
        That is, for consistency `step = (stop - start)  / (size - 1)`
        """

        if step is not None and size is not None:
            raise TypeError("only one of 'step' and 'size' is allowed")
        elif step is None and size is None:
            raise TypeError("'step' or 'size' is required")

        # validate and set start, stop, and step
        start = make_coord_value(start)
        stop = make_coord_value(stop)

        if step is not None:
            step = make_coord_delta(step)
        elif isinstance(size, (int, np.compat.long, np.integer)) and not isinstance(size, np.timedelta64):
            step = divide_delta(stop - start, size - 1)
        else:
            raise TypeError("size must be an integer, not '%s'" % type(size))

        if isinstance(start, float) and isinstance(stop, float) and isinstance(step, float):
            fstep = step
        elif isinstance(start, np.datetime64) and isinstance(stop, np.datetime64) and isinstance(step, np.timedelta64):
            fstep = step.astype(float)
        else:
            raise TypeError(
                "UniformCoordinates1d mismatching types (start '%s', stop '%s', step '%s')."
                % (type(start), type(stop), type(step))
            )

        if fstep == 0:
            raise ValueError("Uniformcoordinates1d step cannot be zero")

        if fstep <= 0 and start < stop:
            raise ValueError("UniformCoordinates1d step must be greater than zero if start < stop.")

        if fstep >= 0 and start > stop:
            raise ValueError("UniformCoordinates1d step must be less than zero if start > stop.")

        self.set_trait("start", start)
        self.set_trait("stop", stop)
        self.set_trait("step", step)

        if not fix_stop_val:  # Need to make sure that 'stop' is consistent with self.coordinates[-1]
            self.set_trait("stop", add_coord(self.start, (self.size - 1) * self.step))

        # Make sure step is floating-point error consistent in all cases
        # This is only needed when the type is float
        if fstep == step and self.size > 1:
            step = divide_delta(self.stop - self.start, self.size - 1)
            self.set_trait("step", step)

        # set common properties
        super(UniformCoordinates1d, self).__init__(name=name)
Beispiel #8
0
def test_make_coord_delta():
    # numbers
    assert make_coord_delta(10.5) == 10.5
    assert make_coord_delta(10) == 10.0
    assert make_coord_delta(np.array(10.5)) == 10.5
    assert make_coord_delta(np.array([10.5])) == 10.5

    assert type(make_coord_delta(10.5)) is float
    assert type(make_coord_delta(10)) is float
    assert type(make_coord_delta(np.array(10.5))) is float
    assert type(make_coord_delta(np.array([10.5]))) is float

    # timedelta
    td = np.timedelta64(2, 'D')
    assert make_coord_delta(td) == td
    assert make_coord_delta(td.item()) == td
    assert make_coord_delta('2,D') == td
    assert make_coord_delta(u'2,D') == td
    assert make_coord_delta(np.array(td)) == td
    assert make_coord_delta(np.array([td])) == td
    assert make_coord_delta(np.array('2,D')) == td
    assert make_coord_delta(np.array(['2,D'])) == td

    # arrays and lists
    with pytest.raises(TypeError, match="Invalid coordinate delta"):
        make_coord_delta(np.arange(5))

    with pytest.raises(TypeError, match="Invalid coordinate delta"):
        make_coord_delta(range(5))

    # invalid strings
    with pytest.raises(ValueError):
        make_coord_delta('not a valid timedelta')
Beispiel #9
0
    def __init__(self,
                 start,
                 stop,
                 step=None,
                 size=None,
                 name=None,
                 ctype=None,
                 units=None,
                 coord_ref_sys=None,
                 segment_lengths=None):
        """
        Create uniformly-spaced 1d coordinates from a `start`, `stop`, and `step` or `size`.

        Parameters
        ----------
        start : float or datetime64
            Start coordinate.
        stop : float or datetime64
            Stop coordinate.
        step : float or timedelta64
            Signed, nonzero step between coordinates (either step or size required).
        size : int
            Number of coordinates (either step or size required).
        segment_lengths: array, float, timedelta, optional
            When ctype is a segment type, the segment lengths for the coordinates. By defaul, the segment_lengths are
            equal the step.
        """

        if step is not None and size is not None:
            raise TypeError("only one of 'step' and 'size' is allowed")
        elif step is None and size is None:
            raise TypeError("'step' or 'size' is required")

        # validate and set start, stop, and step
        start = make_coord_value(start)
        stop = make_coord_value(stop)
        if step == 0:
            raise ValueError("step must be nonzero")
        elif step is not None:
            step = make_coord_delta(step)
        elif isinstance(size,
                        (int, np.long,
                         np.integer)) and not isinstance(size, np.timedelta64):
            step = divide_delta(stop - start, size - 1)
        else:
            raise TypeError("size must be an integer, not '%s'" % type(size))

        if isinstance(start, float) and isinstance(stop, float) and isinstance(
                step, float):
            fstep = step
        elif isinstance(start, np.datetime64) and isinstance(
                stop, np.datetime64) and isinstance(step, np.timedelta64):
            fstep = step.astype(float)
        else:
            raise TypeError(
                "UniformCoordinates1d mismatching types (start '%s', stop '%s', step '%s')."
                % (type(start), type(stop), type(step)))

        if fstep < 0 and start < stop:
            raise ValueError(
                "UniformCoordinates1d step must be less than zero if start > stop."
            )

        if fstep > 0 and start > stop:
            raise ValueError(
                "UniformCoordinates1d step must be greater than zero if start < stop."
            )

        self.set_trait('start', start)
        self.set_trait('stop', stop)
        self.set_trait('step', step)

        # set common properties
        super(UniformCoordinates1d,
              self).__init__(name=name,
                             ctype=ctype,
                             units=units,
                             segment_lengths=segment_lengths,
                             coord_ref_sys=coord_ref_sys)