Returns a |Timegrid| instance based on two date and one period
        information stored in the first 13 rows of a |numpy.ndarray| object.
492882
def from_array(cls, array):
        
        try:
            return cls(Date.from_array(array[:6]),
                       Date.from_array(array[6:12]),
                       Period.fromseconds(array[12]))
        except IndexError:
            raise IndexError(
                f'To define a Timegrid instance via an array, 13 '
                f'numbers are required.  However, the given array '
                f'consist of {len(array)} entries/rows only.')
21958
def date_range(start, end, length, time_unit='us'):
    
    step = (1./compute_density(start, end, length, time_unit))
    if pd and isinstance(start, pd.Timestamp):
        start = start.to_datetime64()
    step = np.timedelta64(int(round(step)), time_unit)
    return start+step/2.+np.arange(length)*step
355115
def iterdays(self, d1, d2):
        
        curr = datetime.datetime.combine(d1, datetime.time())
        end = datetime.datetime.combine(d2, datetime.time())
        if d1.date() == d2.date():
            yield curr
            return
        while curr < end:
            yield curr
            curr = curr + datetime.timedelta(days=1)
883959
def make2d(array, cols=None, dtype=None):
    '''
    

    '''
    if not len(array):
        if cols is None or dtype is None:
            raise RuntimeError(
                "cols and dtype must be specified for empty array"
            )
        return _np.empty((0, cols), dtype=dtype)
    return _np.vstack(array)
239107
def datetime2gtd(time: Union[str, datetime.datetime, np.datetime64],
                 glon: Union[float, List[float], np.ndarray] = np.nan) -> Tuple[int, float, float]:
    
# %%
    T = np.atleast_1d(time)
    glon = np.asarray(glon)
    doy = np.empty_like(T, int)
    utsec = np.empty_like(T, float)
    stl = np.empty((T.size, *glon.shape))

    for i, t in enumerate(T):
        if isinstance(t, str):
            t = parse(t)
        elif isinstance(t, np.datetime64):
            t = t.astype(datetime.datetime)
        elif isinstance(t, (datetime.datetime, datetime.date)):
            pass
        else:
            raise TypeError('unknown time datatype {}'.format(type(t)))
# %% Day of year
        doy[i] = int(t.strftime('%j'))
# %% seconds since utc midnight
        utsec[i] = datetime2utsec(t)

        stl[i, ...] = utsec[i] / 3600. + glon / 15.

    return doy, utsec, stl
715579
def period_break(dates, period):
    
    current = getattr(dates, period)
    previous = getattr(dates - 1 * dates.freq, period)
    return np.nonzero(current - previous)[0]
752451
def time_segments_aggregate(X, interval, time_column, method=['mean']):
    """"""
    if isinstance(X, np.ndarray):
        X = pd.DataFrame(X)

    X = X.sort_values(time_column).set_index(time_column)

    if isinstance(method, str):
        method = [method]

    start_ts = X.index.values[0]
    max_ts = X.index.values[-1]

    values = list()
    index = list()
    while start_ts <= max_ts:
        end_ts = start_ts + interval
        subset = X.loc[start_ts:end_ts - 1]
        aggregated = [
            getattr(subset, agg)(skipna=True).values
            for agg in method
        ]
        values.append(np.concatenate(aggregated))
        index.append(start_ts)
        start_ts = end_ts

    return np.asarray(values), np.asarray(index)
1112997
def datetime_range(start_dt, end_dt, unit,
                   n_units=1, inclusive_end=False):
    """"""

    def done(a, b, inclusive_end):
        if inclusive_end:
            return a <= b
        else:
            return a < b

    current = start_dt
    while done(current, end_dt, inclusive_end):
        yield current
        current += datetime.timedelta(**{unit: n_units})
336230
def demeshgrid(arr):
    
    dim = len(arr.shape)
    for i in range(dim):
        Slice1 = [0]*dim
        Slice2 = [1]*dim
        Slice1[i] = slice(None)
        Slice2[i] = slice(None)
        if (arr[tuple(Slice1)] == arr[tuple(Slice2)]).all():
            return arr[tuple(Slice1)]
1006483
def create_timedelta(timespec):
    """"""
    duration = timespec.split(':')
    seconds = int(duration[-1])
    minutes = 0
    hours = 0
    days = 0

    if len(duration) > 1:
        minutes = int(duration[-2])
    if len(duration) > 2:
        hours = int(duration[-3])
    if len(duration) > 3:
        days = int(duration[-4])

    return datetime.timedelta(days=days, seconds=seconds, minutes=minutes, hours=hours)
302662
def read(self, ncfile, timegrid_data) -> None:
        
        array = query_array(ncfile, self.name)
        subdev2index = self.query_subdevice2index(ncfile)
        for subdevice, sequence in self.sequences.items():
            idx = subdev2index.get_index(subdevice)
            values = array[self.get_slices(idx, sequence.shape)]
            sequence.series = sequence.adjust_series(
                timegrid_data, values)
1336950
def get_current(self, item=None, raw=False, start=None, end=None):
        
        item_indexer = slice(None)
        if item:
            item_indexer = self.items.get_loc(item)

        start_index = self._start_index
        end_index = self._pos

        # get inital date window
        where = slice(start_index, end_index)
        current_dates = self.date_buf[where]

        def convert_datelike_to_long(dt):
            if isinstance(dt, pd.Timestamp):
                return dt.asm8
            if isinstance(dt, datetime.datetime):
                return np.datetime64(dt)
            return dt

        # constrict further by date
        if start:
            start = convert_datelike_to_long(start)
            start_index += current_dates.searchsorted(start)

        if end:
            end = convert_datelike_to_long(end)
            _end = current_dates.searchsorted(end, 'right')
            end_index -= len(current_dates) - _end

        where = slice(start_index, end_index)

        values = self.buffer.values[item_indexer, where, :]
        current_dates = self.date_buf[where]

        if raw:
            # return copy so we can change it without side effects here
            return values.copy()

        major_axis = pd.DatetimeIndex(deepcopy(current_dates), tz='utc')
        if values.ndim == 3:
            return pd.Panel(values, self.items, major_axis, self.minor_axis,
                            dtype=self.dtype)

        elif values.ndim == 2:
            return pd.DataFrame(values, major_axis, self.minor_axis,
                                dtype=self.dtype)
1129411
def f_rollup(items, times, freq):
    
    rollup = [np.sum(item for __, item in ts)
              for _, ts in groupby_freq(items, times, freq)]
    return np.array(rollup)
164469
def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None):
        

        # algos.take_nd dispatches for DatetimeTZBlock, CategoricalBlock
        # so need to preserve types
        # sparse is treated like an ndarray, but needs .get_values() shaping

        values = self.values
        if self.is_sparse:
            values = self.get_values()

        if fill_tuple is None:
            fill_value = self.fill_value
            new_values = algos.take_nd(values, indexer, axis=axis,
                                       allow_fill=False, fill_value=fill_value)
        else:
            fill_value = fill_tuple[0]
            new_values = algos.take_nd(values, indexer, axis=axis,
                                       allow_fill=True, fill_value=fill_value)

        if new_mgr_locs is None:
            if axis == 0:
                slc = libinternals.indexer_as_slice(indexer)
                if slc is not None:
                    new_mgr_locs = self.mgr_locs[slc]
                else:
                    new_mgr_locs = self.mgr_locs[indexer]
            else:
                new_mgr_locs = self.mgr_locs

        if not is_dtype_equal(new_values.dtype, self.dtype):
            return self.make_block(new_values, new_mgr_locs)
        else:
            return self.make_block_same_class(new_values, new_mgr_locs)
1191665
def _format_return_timestamps(self, return_timestamps=None):
        
        if return_timestamps is None:
            # Build based upon model file Start, Stop times and Saveper
            # Vensim's standard is to expect that the data set includes the `final time`,
            # so we have to add an extra period to make sure we get that value in what
            # numpy's `arange` gives us.
            return_timestamps_array = np.arange(
                self.components.initial_time(),
                self.components.final_time() + self.components.saveper(),
                self.components.saveper(), dtype=np.float64
            )
        elif inspect.isclass(range) and isinstance(return_timestamps, range):
            return_timestamps_array = np.array(return_timestamps, ndmin=1)
        elif isinstance(return_timestamps, (list, int, float, np.ndarray)):
            return_timestamps_array = np.array(return_timestamps, ndmin=1)
        elif isinstance(return_timestamps, _pd.Series):
            return_timestamps_array = return_timestamps.as_matrix()
        else:
            raise TypeError('`return_timestamps` expects a list, array, pandas Series, '
                            'or numeric value')
        return return_timestamps_array
835615
def extract_tendency_grid(self, model_grid):
        
        var_name = model_grid.variable + "-tendency"
        self.attributes[var_name] = []
        timesteps = np.arange(self.start_time, self.end_time + 1)
        for ti, t in enumerate(timesteps):
            t_index = t - model_grid.start_hour
            self.attributes[var_name].append(
                model_grid.data[t_index, self.i[ti], self.j[ti]] - model_grid.data[t_index - 1, self.i[ti], self.j[ti]]
                )
872446
def query_timeseries(self, query, from_time=None, to_time=None, by_post=False):
    
    return timeseries.query_timeseries(self, query, from_time, to_time, by_post=by_post)