Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernize Python code with ruff, CI, pre-commit #85

Merged
merged 5 commits into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/workflows/python-formatting.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name: check format using ruff
on: [push]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1
with:
args: format --check
8 changes: 8 additions & 0 deletions .github/workflows/python-linting.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
name: lint code using ruff
on: [push]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1
9 changes: 9 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.5.1
hooks:
# Run the linter.
- id: ruff
# Run the formatter.
- id: ruff-format
41 changes: 25 additions & 16 deletions calc_fluence_dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,27 @@
N_SAMP = 6


def get_fluences(filename='ACE_hourly_avg.npy'):
def get_fluences(filename="ACE_hourly_avg.npy"):
"""
Get P3 cumulative fluence values at 1 hour intervals for all data in the
ACE mission since 1997, using 1-hr average P3 values. Compute a fluence
prediction starting each 12 hours extending for 48 hours. Store each
48-point fluence prediction along with the index into the global ``BINS``
array corresponding to the starting P3 value.
Get P3 cumulative fluence values at 1 hour intervals.

This returns fluences for all data in the ACE mission since 1997, using 1-hr average
P3 values. Compute a fluence prediction starting each 12 hours extending for 48
hours. Store each 48-point fluence prediction along with the index into the global
``BINS`` array corresponding to the starting P3 value.
"""
dat = np.load(filename)

# Remove bad data points
ok = dat['p3'] > 1
ok = dat["p3"] > 1
dat = dat[ok]
p3s = dat['p3']
p3s = dat["p3"]

# Compute data times in hours
hrs = (dat['fp_year'] - 1997.0) * 24 * 365.25
hrs = (dat["fp_year"] - 1997.0) * 24 * 365.25

i0s = np.arange(0, len(p3s) - N_T, N_SAMP)
p3_samps = np.vstack([p3s[i:i + N_T] for i in i0s])
p3_samps = np.vstack([p3s[i : i + N_T] for i in i0s])
d_hrs = np.array([hrs[i + N_T] - hrs[i] - N_T for i in i0s])
ok = np.abs(d_hrs) < 0.15
p3_samps = p3_samps[ok]
Expand All @@ -36,8 +37,15 @@ def get_fluences(filename='ACE_hourly_avg.npy'):
return p_fits.T, p3_samps, fluences


def get_fluence_percentiles(p3_avg_now, p3_slope_now, p3_fits, p3_samps, fluences,
min_flux_samples, max_slope_samples):
def get_fluence_percentiles(
p3_avg_now,
p3_slope_now,
p3_fits,
p3_samps,
fluences,
min_flux_samples,
max_slope_samples,
):
"""
Compute the 10%, 50%, and 90% fluence time histories within each P3 bin.
"""
Expand All @@ -64,11 +72,12 @@ def get_fluence_percentiles(p3_avg_now, p3_slope_now, p3_fits, p3_samps, fluence
return hrs, fl10, fl50, fl90


if __name__ == '__main__':
if __name__ == "__main__":
p3_fits, p3_samps, fluences = get_fluences()
print('p3_avg_now', end=' ')
print("p3_avg_now", end=" ")
p3_avg_now = float(input())
print('p3_slope_now', end=' ')
print("p3_slope_now", end=" ")
p3_slope_now = float(input())
hrs, fl10, fl50, fl90 = get_fluence_percentiles(
p3_avg_now, p3_slope_now, p3_fits, p3_samps, fluences)
p3_avg_now, p3_slope_now, p3_fits, p3_samps, fluences
)
58 changes: 30 additions & 28 deletions get_ace.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
#!/usr/bin/env python

import sys
import urllib.request, urllib.error, urllib.parse
import argparse
import tables
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

import numpy as np
import tables
from astropy.io import ascii
from Chandra.Time import DateTime

parser = argparse.ArgumentParser(description='Get ACE data')
parser.add_argument('--h5',
default='ACE.h5',
help='HDF5 file name')
parser = argparse.ArgumentParser(description="Get ACE data")
parser.add_argument("--h5", default="ACE.h5", help="HDF5 file name")
args = parser.parse_args()

url = 'ftp://ftp.swpc.noaa.gov/pub/lists/ace/ace_epam_5m.txt'
url = "ftp://ftp.swpc.noaa.gov/pub/lists/ace/ace_epam_5m.txt"

colnames = ('year month dom hhmm mjd secs p1 p2 p3 '
'p4 p5 p6 p7 p8 p9 p10 p11').split()
colnames = (
"year month dom hhmm mjd secs p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11"
).split()

last_err = None
for _ in range(3):
Expand All @@ -31,47 +32,48 @@
last_err = err
time.sleep(5)
else:
print('Warning: failed to open URL {}: {}'.format(url, last_err))
print("Warning: failed to open URL {}: {}".format(url, last_err))
sys.exit(0)

colnames = ('year month dom hhmm mjd secs '
'destat de1 de4 pstat p1 p3 p5 p6 p7 anis_idx').split()
data_colnames = ('destat de1 de4 pstat p1 p3 p5 p6 p7').split()
colnames = (
"year month dom hhmm mjd secs destat de1 de4 pstat p1 p3 p5 p6 p7 anis_idx"
).split()
data_colnames = ("destat de1 de4 pstat p1 p3 p5 p6 p7").split()

try:
dat = ascii.read(urldat, guess=False, format="no_header",
data_start=3, names=colnames)
dat = ascii.read(
urldat, guess=False, format="no_header", data_start=3, names=colnames
)
except Exception as err:
print(('Warning: malformed ACE data so table read failed: {}'
.format(err)))
print(("Warning: malformed ACE data so table read failed: {}".format(err)))
sys.exit(0)

# Strip up to two rows at the end if any values are bad (i.e. negative)
for _ in range(2):
if any(dat[name][-1] < 0 for name in data_colnames):
dat = dat[:-1]

mjd = dat['mjd'] + dat['secs'] / 86400.
mjd = dat["mjd"] + dat["secs"] / 86400.0

secs = DateTime(mjd, format='mjd').secs
secs = DateTime(mjd, format="mjd").secs

descrs = dat.dtype.descr
descrs.append(('time', 'f8'))
descrs.append(("time", "f8"))
newdat = np.ndarray(len(dat), dtype=descrs)
for colname in colnames:
newdat[colname] = dat[colname]
newdat['time'] = secs
newdat["time"] = secs

h5 = tables.open_file(args.h5, mode='a',
filters=tables.Filters(complevel=5, complib='zlib'))
h5 = tables.open_file(
args.h5, mode="a", filters=tables.Filters(complevel=5, complib="zlib")
)
try:
table = h5.root.data
lasttime = table.col('time')[-1]
ok = newdat['time'] > lasttime
lasttime = table.col("time")[-1]
ok = newdat["time"] > lasttime
newdat = newdat[ok]
h5.root.data.append(newdat)
except tables.NoSuchNodeError:
table = h5.create_table(h5.root, 'data', newdat,
"ACE rates", expectedrows=2e7)
table = h5.create_table(h5.root, "data", newdat, "ACE rates", expectedrows=2e7)
h5.root.data.flush()
h5.close()
Loading