Skip to content

utils

datetime_to_float(dates)

Convert a sequence of datetime objects to a float representation.

Output units are in days since the first item in dates.

Parameters:

Name Type Description Default
dates Sequence[DateOrDatetime]

List of datetime objects to convert to floats

required

Returns:

Name Type Description
date_arr np.array 1D

The float representation of the datetime objects

Source code in src/geepers/utils.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def datetime_to_float(dates: Sequence[DateOrDatetime]) -> np.ndarray:
    """Convert a sequence of datetime objects to a float representation.

    Output units are in days since the first item in `dates`.

    Parameters
    ----------
    dates : Sequence[DateOrDatetime]
        List of datetime objects to convert to floats

    Returns
    -------
    date_arr : np.array 1D
        The float representation of the datetime objects

    """
    sec_per_day = 60 * 60 * 24
    date_arr = np.asarray(dates).astype("datetime64[s]")
    # Reference the 0 to the first date
    date_arr = date_arr - date_arr[0]
    return date_arr.astype(float) / sec_per_day

decimal_year_to_datetime(decimal_year)

Convert a decimal year to a datetime object.

See https://geodesy.unr.edu/NGLStationPages/DecimalYearConvention for more information, or https://geodesy.unr.edu/NGLStationPages/decyr.txt for a mapping from decimal year to datetime (with hour precision).

Parameters:

Name Type Description Default
decimal_year float

Year expressed as a decimal (e.g., 2014.5).

required

Returns:

Type Description
datetime

Corresponding calendar datetime (approximate to nearest day).

Source code in src/geepers/utils.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def decimal_year_to_datetime(decimal_year: float) -> datetime.datetime:
    """Convert a decimal year to a datetime object.

    See https://geodesy.unr.edu/NGLStationPages/DecimalYearConvention for
    more information, or https://geodesy.unr.edu/NGLStationPages/decyr.txt
    for a mapping from decimal year to datetime (with hour precision).

    Parameters
    ----------
    decimal_year : float
        Year expressed as a decimal (e.g., 2014.5).

    Returns
    -------
    datetime.datetime
        Corresponding calendar datetime (approximate to nearest day).

    """
    start_year = 1990
    seconds_per_year = 365.25 * 24 * 3600
    return datetime.datetime(1990, 1, 1) + datetime.timedelta(
        seconds=(decimal_year - start_year) * seconds_per_year
    )

decimal_years_to_datetimes(decimal_years)

Vectorized version of decimal_year_to_datetime.

Parameters:

Name Type Description Default
decimal_years array-like of float

Years expressed as decimals (e.g., [2014.5, 2014.5027]).

required

Returns:

Type Description
DatetimeIndex

Corresponding calendar datetimes, using the same 365.25-day-year convention as decimal_year_to_datetime.

Source code in src/geepers/utils.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def decimal_years_to_datetimes(decimal_years) -> pd.DatetimeIndex:
    """Vectorized version of `decimal_year_to_datetime`.

    Parameters
    ----------
    decimal_years : array-like of float
        Years expressed as decimals (e.g., [2014.5, 2014.5027]).

    Returns
    -------
    pd.DatetimeIndex
        Corresponding calendar datetimes, using the same 365.25-day-year
        convention as `decimal_year_to_datetime`.

    """
    dy = np.asarray(decimal_years, dtype=float)
    seconds = (dy - 1990.0) * 365.25 * 24 * 3600
    return pd.Timestamp("1990-01-01") + pd.to_timedelta(seconds, unit="s")

get_cache_dir(force_posix=False, app_name='geepers')

Return the cache folder for the application.

The directory is used to store gps timeseries data. The default behavior is to return whatever is most appropriate for the OS.

the following folders could be returned: Mac OS X: ~/Library/Application Support/geepers Mac OS X (POSIX): ~/.geepers Unix: ~/.cache/geepers Unix (POSIX): ~/.geepers

Parameters:

Name Type Description Default
force_posix bool

If this is set to True then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin's application support folder.

False
app_name str

Name of the application (for naming the subfolder)

'geepers'

Returns:

Name Type Description
Path

Folder to store cached data.

Starting source:
https //github.com/pallets/click/blob/ca5e1c3d75e95cbc70fa6ed51ef263592e9ac0d0/src/click/utils.py#L32
Source code in src/geepers/utils.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def get_cache_dir(force_posix=False, app_name="geepers") -> Path:
    """Return the cache folder for the application.

    The directory is used to store gps timeseries data.
    The default behavior is to return whatever is most appropriate for the OS.


    the following folders could be returned:
    Mac OS X:
      ``~/Library/Application Support/geepers``
    Mac OS X (POSIX):
      ``~/.geepers``
    Unix:
      ``~/.cache/geepers``
    Unix (POSIX):
      ``~/.geepers``

    Parameters
    ----------
    force_posix : bool
        If this is set to `True` then on any POSIX system the folder will be stored
        in the home folder with a leading dot instead of the XDG config home or darwin's
        application support folder.
    app_name : str
        Name of the application (for naming the subfolder)

    Returns
    -------
    Path
        Folder to store cached data.

    Starting source:
    https://github.com/pallets/click/blob/ca5e1c3d75e95cbc70fa6ed51ef263592e9ac0d0/src/click/utils.py#L32

    """
    if force_posix:
        return Path(f"~/.{app_name}").expanduser()
    if sys.platform == "darwin":
        return Path("~/Library/Application Support").expanduser() / app_name
    else:
        base_path = Path(
            os.environ.get("XDG_CACHE_HOME", Path("~/.cache").expanduser())
        )
        return base_path / app_name

get_dates(filename, fmt=DATE_FORMAT)

Search for dates in the stem of filename matching fmt.

Excludes dates that are not in the stem of filename (in the directories).

Parameters:

Name Type Description Default
filename Path or str

Path or string to search for dates.

required
fmt str

Format of date to search for. Default is %Y%m%d

DATE_FORMAT

Returns:

Type Description
list[datetime]

list of dates found in the stem of filename matching fmt.

Examples:

>>> get_dates("/path/to/20191231.slc.tif")
[datetime.datetime(2019, 12, 31, 0, 0)]
>>> get_dates("S1A_IW_SLC__1SDV_20191231T000000_20191231T000000_032123_03B8F1_1C1D.nc")
[datetime.datetime(2019, 12, 31, 0, 0), datetime.datetime(2019, 12, 31, 0, 0)]
>>> get_dates("/not/a/date_named_file.tif")
[]
Source code in src/geepers/utils.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def get_dates(filename: Path | str, fmt: str = DATE_FORMAT) -> list[datetime.datetime]:
    """Search for dates in the stem of `filename` matching `fmt`.

    Excludes dates that are not in the stem of `filename` (in the directories).

    Parameters
    ----------
    filename : Path or str
        Path or string to search for dates.
    fmt : str, optional
        Format of date to search for. Default is %Y%m%d

    Returns
    -------
    list[datetime.datetime]
        list of dates found in the stem of `filename` matching `fmt`.

    Examples
    --------
    >>> get_dates("/path/to/20191231.slc.tif")
    [datetime.datetime(2019, 12, 31, 0, 0)]
    >>> get_dates("S1A_IW_SLC__1SDV_20191231T000000_20191231T000000_032123_03B8F1_1C1D.nc")
    [datetime.datetime(2019, 12, 31, 0, 0), datetime.datetime(2019, 12, 31, 0, 0)]
    >>> get_dates("/not/a/date_named_file.tif")
    []

    """  # noqa: E501
    path = _get_path_from_gdal_str(filename)
    pattern = _date_format_to_regex(fmt)
    date_list = re.findall(pattern, path.name)
    if not date_list:
        return []
    return [datetime.datetime.strptime(d, fmt) for d in date_list]

read_geo_csv(filename)

Read a CSV file with a geometry column.

Source code in src/geepers/utils.py
176
177
178
179
def read_geo_csv(filename: Path | str) -> gpd.GeoDataFrame:
    """Read a CSV file with a geometry column."""
    df = gpd.read_file(filename)  # This just returns a pandas DataFrame
    return gpd.GeoDataFrame(df, geometry=gpd.GeoSeries.from_wkt(df.geometry))