Skip to content

Commit

Permalink
Python >= 3.7 anno, src layout
Browse files Browse the repository at this point in the history
  • Loading branch information
scivision committed Dec 29, 2021
1 parent 4c33941 commit 8cfe354
Show file tree
Hide file tree
Showing 19 changed files with 88 additions and 180 deletions.
20 changes: 0 additions & 20 deletions .gitattributes

This file was deleted.

6 changes: 1 addition & 5 deletions .mypy.ini
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
[mypy]
files = sciencedates/
files = src/

ignore_missing_imports = True
strict_optional = False
allow_redefinition = True
show_error_context = False
show_column_numbers = True
warn_unreachable = False

[mypy-xarray]
follow_imports = skip
19 changes: 0 additions & 19 deletions archive/.appveyor.yml

This file was deleted.

35 changes: 0 additions & 35 deletions archive/.travis.yml

This file was deleted.

17 changes: 6 additions & 11 deletions date2doy.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,15 @@
#!/usr/bin/env python
#!/usr/bin/env python3
"""
command-line utility to convert date to day of year
"""
from argparse import ArgumentParser
from sciencedates import date2doy


def main():
p = ArgumentParser(description="convert date to day of year")
p.add_argument("date", help="yyyy-mm-dd")
P = p.parse_args()
p = ArgumentParser(description="convert date to day of year")
p.add_argument("date", help="yyyy-mm-dd")
P = p.parse_args()

doy, year = date2doy(P.date)
doy, year = date2doy(P.date)

print(doy.item())


if __name__ == "__main__":
main()
print(doy.item())
11 changes: 3 additions & 8 deletions findnearest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
import numpy as np
from bisect import bisect
import sciencedates as sd
Expand All @@ -13,11 +13,6 @@ def INCORRECTRESULT_using_bisect(x, X0): # pragma: no cover
return np.asanyarray(ind), x[ind]


def main():
print(sd.find_nearest([10, 15, 12, 20, 14, 33], [32, 12.01]))
print(sd.find_nearest([10, 15, 12, 20, 14, 33], [32, 12.01]))

print(INCORRECTRESULT_using_bisect([10, 15, 12, 20, 14, 33], [32, 12.01]))


if __name__ == "__main__": # pragma: no cover
main()
print(INCORRECTRESULT_using_bisect([10, 15, 12, 20, 14, 33], [32, 12.01]))
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
requires = ["setuptools", "wheel"]

[tool.black]
line-length = 132
line-length = 100
15 changes: 5 additions & 10 deletions randomdate.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
"""
generate a random date (month and day) in a year.
Michael Hirsch, Ph.D.
Expand All @@ -8,13 +8,8 @@
from sciencedates import randomdate


def main():
p = ArgumentParser(description="generate random date in year")
p.add_argument("year", type=int, nargs="?", default=date.today().year)
P = p.parse_args()
p = ArgumentParser(description="generate random date in year")
p.add_argument("year", type=int, nargs="?", default=date.today().year)
P = p.parse_args()

print(randomdate(P.year))


if __name__ == "__main__":
main()
print(randomdate(P.year))
15 changes: 9 additions & 6 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = sciencedates
version = 1.5.0
version = 1.5.1
author = Michael Hirsch, Ph.D.
author_email = [email protected]
url = https://github.com/geospace-code/sciencedates
Expand All @@ -21,22 +21,25 @@ long_description = file: README.md
long_description_content_type = text/markdown

[options]
python_requires = >= 3.5
python_requires = >= 3.7
packages = find:
scripts =
date2doy.py
findnearest.py
randomdate.py
install_requires =
numpy
python-dateutil
package_dir=
=src

[options.packages.find]
where=src

[options.extras_require]
tests =
pytest
lint =
flake8
mypy
types-pytz
types-python-dateutil
plot =
xarray
matplotlib
Expand Down
File renamed without changes.
12 changes: 8 additions & 4 deletions sciencedates/dec.py → src/sciencedates/dec.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from __future__ import annotations
import typing as T
import numpy as np
import datetime
import dateutil.parser
import numpy as np


__all__ = ["datetime2utsec", "datetime2yeardec", "yeardec2datetime"]


def datetime2utsec(t: T.Union[str, datetime.date, datetime.datetime, np.datetime64]) -> float:
def datetime2utsec(t: T.Any) -> float | np.ndarray:
"""
input: datetime
output: float utc seconds since THIS DAY'S MIDNIGHT
Expand All @@ -20,7 +22,9 @@ def datetime2utsec(t: T.Union[str, datetime.date, datetime.datetime, np.datetime
elif isinstance(t, str):
t = dateutil.parser.parse(t)

return datetime.timedelta.total_seconds(t - datetime.datetime.combine(t.date(), datetime.datetime.min.time()))
return datetime.timedelta.total_seconds(
t - datetime.datetime.combine(t.date(), datetime.datetime.min.time())
)


def yeardec2datetime(atime: float) -> datetime.datetime:
Expand Down Expand Up @@ -54,7 +58,7 @@ def yeardec2datetime(atime: float) -> datetime.datetime:
return time


def datetime2yeardec(time: T.Union[str, datetime.datetime, datetime.date]) -> float:
def datetime2yeardec(time: str | datetime.datetime | datetime.date) -> float:
"""
Convert a datetime into a float. The integer part of the float should
represent the year.
Expand Down
26 changes: 15 additions & 11 deletions sciencedates/doy.py → src/sciencedates/doy.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import annotations
import typing as T
import datetime
import numpy as np
Expand All @@ -8,7 +9,7 @@
__all__ = ["datetime2yeardoy", "yeardoy2datetime", "date2doy", "datetime2gtd"]


def datetime2yeardoy(time: T.Union[str, datetime.datetime]) -> T.Tuple[int, float]:
def datetime2yeardoy(time: T.Any) -> tuple[int, float]:
"""
Inputs:
T: Numpy 1-D array of datetime.datetime OR string for dateutil.parser.parse
Expand All @@ -33,7 +34,7 @@ def datetime2yeardoy(time: T.Union[str, datetime.datetime]) -> T.Tuple[int, floa
return yd.squeeze()[()], utsec.squeeze()[()]


def yeardoy2datetime(yeardate: int, utsec: T.Union[float, int] = None) -> datetime.datetime:
def yeardoy2datetime(yeardate: int, utsec: float | int = 0) -> datetime.datetime:
"""
Parameters
Expand All @@ -51,10 +52,10 @@ def yeardoy2datetime(yeardate: int, utsec: T.Union[float, int] = None) -> dateti
http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date
"""
if isinstance(yeardate, (tuple, list, np.ndarray)):
if utsec is None:
return np.asarray([yeardoy2datetime(y) for y in yeardate])
elif isinstance(utsec, (tuple, list, np.ndarray)):
if isinstance(utsec, (tuple, list, np.ndarray)):
return np.asarray([yeardoy2datetime(y, s) for y, s in zip(yeardate, utsec)])
else:
return np.asarray([yeardoy2datetime(y, utsec) for y in yeardate])

yeardate = int(yeardate)

Expand All @@ -65,15 +66,16 @@ def yeardoy2datetime(yeardate: int, utsec: T.Union[float, int] = None) -> dateti
year = int(yd[:4])
assert 0 < year < 3000, "year not in expected format"

dt = datetime.datetime(year, 1, 1) + datetime.timedelta(days=int(yd[4:]) - 1)

if utsec is not None:
dt += datetime.timedelta(seconds=utsec)
dt = (
datetime.datetime(year, 1, 1)
+ datetime.timedelta(days=int(yd[4:]) - 1)
+ datetime.timedelta(seconds=utsec)
)

return dt


def date2doy(time: T.Union[str, datetime.datetime]) -> T.Tuple[int, int]:
def date2doy(time: T.Any) -> tuple[np.ndarray, np.ndarray]:
"""
< 366 for leap year too. normal year 0..364. Leap 0..365.
"""
Expand All @@ -94,7 +96,9 @@ def date2doy(time: T.Union[str, datetime.datetime]) -> T.Tuple[int, int]:
return doy, year


def datetime2gtd(time: T.Union[str, datetime.datetime, np.datetime64], glon: np.ndarray = np.nan) -> T.Tuple[int, float, float]:
def datetime2gtd(
time: T.Any, glon: float | np.ndarray = np.nan
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Parameters
Expand Down
14 changes: 10 additions & 4 deletions sciencedates/findnearest.py → src/sciencedates/findnearest.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from typing import Tuple, Any
from __future__ import annotations
import typing as T
import numpy as np
import datetime


def find_nearest(x, x0) -> Tuple[int, Any]:
def find_nearest(x, x0) -> tuple[int, T.Any]:
"""
This find_nearest function does NOT assume sorted input
Expand Down Expand Up @@ -34,9 +35,14 @@ def find_nearest(x, x0) -> Tuple[int, Any]:

# NOTE: not trapping IndexError (all-nan) becaues returning None can surprise with slice indexing
for i, xi in enumerate(x0):
if xi is not None and (isinstance(xi, (datetime.datetime, datetime.date, np.datetime64)) or np.isfinite(xi)):
if xi is not None and (
isinstance(xi, (datetime.datetime, datetime.date, np.datetime64)) or np.isfinite(xi)
):
ind[i] = np.nanargmin(abs(x - xi))
else:
raise ValueError("x0 must NOT be None or NaN to avoid surprising None return value")

return ind.squeeze()[()], x[ind].squeeze()[()] # [()] to pop scalar from 0d array while being OK with ndim>0
return (
ind.squeeze()[()],
x[ind].squeeze()[()],
) # [()] to pop scalar from 0d array while being OK with ndim>0
2 changes: 1 addition & 1 deletion sciencedates/random.py → src/sciencedates/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


def randomdate(year: int) -> datetime.date:
""" gives random date in year"""
"""gives random date in year"""
if calendar.isleap(year):
doy = random.randrange(366)
else:
Expand Down
Loading

0 comments on commit 8cfe354

Please sign in to comment.