|
| 1 | +from __future__ import absolute_import |
| 2 | +import re |
| 3 | +from datetime import timedelta |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +import pandas as pd |
| 7 | + |
| 8 | +from xarray.core import pycompat |
| 9 | +from xarray.core.utils import is_scalar |
| 10 | + |
| 11 | + |
| 12 | +def named(name, pattern): |
| 13 | + return '(?P<' + name + '>' + pattern + ')' |
| 14 | + |
| 15 | + |
| 16 | +def optional(x): |
| 17 | + return '(?:' + x + ')?' |
| 18 | + |
| 19 | + |
| 20 | +def trailing_optional(xs): |
| 21 | + if not xs: |
| 22 | + return '' |
| 23 | + return xs[0] + optional(trailing_optional(xs[1:])) |
| 24 | + |
| 25 | + |
| 26 | +def build_pattern(date_sep='\-', datetime_sep='T', time_sep='\:'): |
| 27 | + pieces = [(None, 'year', '\d{4}'), |
| 28 | + (date_sep, 'month', '\d{2}'), |
| 29 | + (date_sep, 'day', '\d{2}'), |
| 30 | + (datetime_sep, 'hour', '\d{2}'), |
| 31 | + (time_sep, 'minute', '\d{2}'), |
| 32 | + (time_sep, 'second', '\d{2}')] |
| 33 | + pattern_list = [] |
| 34 | + for sep, name, sub_pattern in pieces: |
| 35 | + pattern_list.append((sep if sep else '') + named(name, sub_pattern)) |
| 36 | + # TODO: allow timezone offsets? |
| 37 | + return '^' + trailing_optional(pattern_list) + '$' |
| 38 | + |
| 39 | + |
| 40 | +_BASIC_PATTERN = build_pattern(date_sep='', time_sep='') |
| 41 | +_EXTENDED_PATTERN = build_pattern() |
| 42 | +_PATTERNS = [_BASIC_PATTERN, _EXTENDED_PATTERN] |
| 43 | + |
| 44 | + |
| 45 | +def parse_iso8601(datetime_string): |
| 46 | + for pattern in _PATTERNS: |
| 47 | + match = re.match(pattern, datetime_string) |
| 48 | + if match: |
| 49 | + return match.groupdict() |
| 50 | + raise ValueError('no ISO-8601 match for string: %s' % datetime_string) |
| 51 | + |
| 52 | + |
| 53 | +def _parse_iso8601_with_reso(date_type, timestr): |
| 54 | + default = date_type(1, 1, 1) |
| 55 | + result = parse_iso8601(timestr) |
| 56 | + replace = {} |
| 57 | + |
| 58 | + for attr in ['year', 'month', 'day', 'hour', 'minute', 'second']: |
| 59 | + value = result.get(attr, None) |
| 60 | + if value is not None: |
| 61 | + # Note ISO8601 conventions allow for fractional seconds. |
| 62 | + # TODO: Consider adding support for sub-second resolution? |
| 63 | + replace[attr] = int(value) |
| 64 | + resolution = attr |
| 65 | + |
| 66 | + return default.replace(**replace), resolution |
| 67 | + |
| 68 | + |
| 69 | +def _parsed_string_to_bounds(date_type, resolution, parsed): |
| 70 | + """Generalization of |
| 71 | + pandas.tseries.index.DatetimeIndex._parsed_string_to_bounds |
| 72 | + for use with non-standard calendars and cftime.datetime |
| 73 | + objects. |
| 74 | + """ |
| 75 | + if resolution == 'year': |
| 76 | + return (date_type(parsed.year, 1, 1), |
| 77 | + date_type(parsed.year + 1, 1, 1) - timedelta(microseconds=1)) |
| 78 | + elif resolution == 'month': |
| 79 | + if parsed.month == 12: |
| 80 | + end = date_type(parsed.year + 1, 1, 1) - timedelta(microseconds=1) |
| 81 | + else: |
| 82 | + end = (date_type(parsed.year, parsed.month + 1, 1) - |
| 83 | + timedelta(microseconds=1)) |
| 84 | + return date_type(parsed.year, parsed.month, 1), end |
| 85 | + elif resolution == 'day': |
| 86 | + start = date_type(parsed.year, parsed.month, parsed.day) |
| 87 | + return start, start + timedelta(days=1, microseconds=-1) |
| 88 | + elif resolution == 'hour': |
| 89 | + start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour) |
| 90 | + return start, start + timedelta(hours=1, microseconds=-1) |
| 91 | + elif resolution == 'minute': |
| 92 | + start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour, |
| 93 | + parsed.minute) |
| 94 | + return start, start + timedelta(minutes=1, microseconds=-1) |
| 95 | + elif resolution == 'second': |
| 96 | + start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour, |
| 97 | + parsed.minute, parsed.second) |
| 98 | + return start, start + timedelta(seconds=1, microseconds=-1) |
| 99 | + else: |
| 100 | + raise KeyError |
| 101 | + |
| 102 | + |
| 103 | +def get_date_field(datetimes, field): |
| 104 | + """Adapted from pandas.tslib.get_date_field""" |
| 105 | + return np.array([getattr(date, field) for date in datetimes]) |
| 106 | + |
| 107 | + |
| 108 | +def _field_accessor(name, docstring=None): |
| 109 | + """Adapted from pandas.tseries.index._field_accessor""" |
| 110 | + def f(self): |
| 111 | + return get_date_field(self._data, name) |
| 112 | + |
| 113 | + f.__name__ = name |
| 114 | + f.__doc__ = docstring |
| 115 | + return property(f) |
| 116 | + |
| 117 | + |
| 118 | +def get_date_type(self): |
| 119 | + return type(self._data[0]) |
| 120 | + |
| 121 | + |
| 122 | +def assert_all_valid_date_type(data): |
| 123 | + import cftime |
| 124 | + |
| 125 | + sample = data[0] |
| 126 | + date_type = type(sample) |
| 127 | + if not isinstance(sample, cftime.datetime): |
| 128 | + raise TypeError( |
| 129 | + 'CFTimeIndex requires cftime.datetime ' |
| 130 | + 'objects. Got object of {}.'.format(date_type)) |
| 131 | + if not all(isinstance(value, date_type) for value in data): |
| 132 | + raise TypeError( |
| 133 | + 'CFTimeIndex requires using datetime ' |
| 134 | + 'objects of all the same type. Got\n{}.'.format(data)) |
| 135 | + |
| 136 | + |
| 137 | +class CFTimeIndex(pd.Index): |
| 138 | + year = _field_accessor('year', 'The year of the datetime') |
| 139 | + month = _field_accessor('month', 'The month of the datetime') |
| 140 | + day = _field_accessor('day', 'The days of the datetime') |
| 141 | + hour = _field_accessor('hour', 'The hours of the datetime') |
| 142 | + minute = _field_accessor('minute', 'The minutes of the datetime') |
| 143 | + second = _field_accessor('second', 'The seconds of the datetime') |
| 144 | + microsecond = _field_accessor('microsecond', |
| 145 | + 'The microseconds of the datetime') |
| 146 | + date_type = property(get_date_type) |
| 147 | + |
| 148 | + def __new__(cls, data): |
| 149 | + result = object.__new__(cls) |
| 150 | + assert_all_valid_date_type(data) |
| 151 | + result._data = np.array(data) |
| 152 | + return result |
| 153 | + |
| 154 | + def _partial_date_slice(self, resolution, parsed): |
| 155 | + """Adapted from |
| 156 | + pandas.tseries.index.DatetimeIndex._partial_date_slice |
| 157 | +
|
| 158 | + Note that when using a CFTimeIndex, if a partial-date selection |
| 159 | + returns a single element, it will never be converted to a scalar |
| 160 | + coordinate; this is in slight contrast to the behavior when using |
| 161 | + a DatetimeIndex, which sometimes will return a DataArray with a scalar |
| 162 | + coordinate depending on the resolution of the datetimes used in |
| 163 | + defining the index. For example: |
| 164 | +
|
| 165 | + >>> from cftime import DatetimeNoLeap |
| 166 | + >>> import pandas as pd |
| 167 | + >>> import xarray as xr |
| 168 | + >>> da = xr.DataArray([1, 2], |
| 169 | + coords=[[DatetimeNoLeap(2001, 1, 1), |
| 170 | + DatetimeNoLeap(2001, 2, 1)]], |
| 171 | + dims=['time']) |
| 172 | + >>> da.sel(time='2001-01-01') |
| 173 | + <xarray.DataArray (time: 1)> |
| 174 | + array([1]) |
| 175 | + Coordinates: |
| 176 | + * time (time) object 2001-01-01 00:00:00 |
| 177 | + >>> da = xr.DataArray([1, 2], |
| 178 | + coords=[[pd.Timestamp(2001, 1, 1), |
| 179 | + pd.Timestamp(2001, 2, 1)]], |
| 180 | + dims=['time']) |
| 181 | + >>> da.sel(time='2001-01-01') |
| 182 | + <xarray.DataArray ()> |
| 183 | + array(1) |
| 184 | + Coordinates: |
| 185 | + time datetime64[ns] 2001-01-01 |
| 186 | + >>> da = xr.DataArray([1, 2], |
| 187 | + coords=[[pd.Timestamp(2001, 1, 1, 1), |
| 188 | + pd.Timestamp(2001, 2, 1)]], |
| 189 | + dims=['time']) |
| 190 | + >>> da.sel(time='2001-01-01') |
| 191 | + <xarray.DataArray (time: 1)> |
| 192 | + array([1]) |
| 193 | + Coordinates: |
| 194 | + * time (time) datetime64[ns] 2001-01-01T01:00:00 |
| 195 | + """ |
| 196 | + start, end = _parsed_string_to_bounds(self.date_type, resolution, |
| 197 | + parsed) |
| 198 | + lhs_mask = (self._data >= start) |
| 199 | + rhs_mask = (self._data <= end) |
| 200 | + return (lhs_mask & rhs_mask).nonzero()[0] |
| 201 | + |
| 202 | + def _get_string_slice(self, key): |
| 203 | + """Adapted from pandas.tseries.index.DatetimeIndex._get_string_slice""" |
| 204 | + parsed, resolution = _parse_iso8601_with_reso(self.date_type, key) |
| 205 | + loc = self._partial_date_slice(resolution, parsed) |
| 206 | + return loc |
| 207 | + |
| 208 | + def get_loc(self, key, method=None, tolerance=None): |
| 209 | + """Adapted from pandas.tseries.index.DatetimeIndex.get_loc""" |
| 210 | + if isinstance(key, pycompat.basestring): |
| 211 | + return self._get_string_slice(key) |
| 212 | + else: |
| 213 | + return pd.Index.get_loc(self, key, method=method, |
| 214 | + tolerance=tolerance) |
| 215 | + |
| 216 | + def _maybe_cast_slice_bound(self, label, side, kind): |
| 217 | + """Adapted from |
| 218 | + pandas.tseries.index.DatetimeIndex._maybe_cast_slice_bound""" |
| 219 | + if isinstance(label, pycompat.basestring): |
| 220 | + parsed, resolution = _parse_iso8601_with_reso(self.date_type, |
| 221 | + label) |
| 222 | + start, end = _parsed_string_to_bounds(self.date_type, resolution, |
| 223 | + parsed) |
| 224 | + if self.is_monotonic_decreasing and len(self): |
| 225 | + return end if side == 'left' else start |
| 226 | + return start if side == 'left' else end |
| 227 | + else: |
| 228 | + return label |
| 229 | + |
| 230 | + # TODO: Add ability to use integer range outside of iloc? |
| 231 | + # e.g. series[1:5]. |
| 232 | + def get_value(self, series, key): |
| 233 | + """Adapted from pandas.tseries.index.DatetimeIndex.get_value""" |
| 234 | + if not isinstance(key, slice): |
| 235 | + return series.iloc[self.get_loc(key)] |
| 236 | + else: |
| 237 | + return series.iloc[self.slice_indexer( |
| 238 | + key.start, key.stop, key.step)] |
| 239 | + |
| 240 | + def __contains__(self, key): |
| 241 | + """Adapted from |
| 242 | + pandas.tseries.base.DatetimeIndexOpsMixin.__contains__""" |
| 243 | + try: |
| 244 | + result = self.get_loc(key) |
| 245 | + return (is_scalar(result) or type(result) == slice or |
| 246 | + (isinstance(result, np.ndarray) and result.size)) |
| 247 | + except (KeyError, TypeError, ValueError): |
| 248 | + return False |
| 249 | + |
| 250 | + def contains(self, key): |
| 251 | + """Needed for .loc based partial-string indexing""" |
| 252 | + return self.__contains__(key) |
0 commit comments