Skip to content

Commit

Permalink
Format with ruff and enable formating in pre-commit (#116)
Browse files Browse the repository at this point in the history
* Format with ruff and enable formating in pre-commit
  • Loading branch information
samaloney authored May 17, 2024
1 parent ba3b71f commit 8867c2d
Show file tree
Hide file tree
Showing 21 changed files with 236 additions and 180 deletions.
2 changes: 2 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ repos:
hooks:
- id: ruff
args: ["--fix"]
# Run the formatter.
- id: ruff-format
- repo: https://github.com/PyCQA/isort
rev: 5.13.2
hooks:
Expand Down
1 change: 1 addition & 0 deletions changelog/116.trivial.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Format code with ruff and turn on ruff format in pre-commit.
6 changes: 3 additions & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
author = "STIX Team"

from pathlib import Path

# The full version, including alpha/beta/rc tags
from stixpy import __version__

release = __version__
is_development = ".dev" in release

Expand Down Expand Up @@ -89,9 +91,7 @@
html_theme = "pydata_sphinx_theme"

html_theme_options = {
"logo": {
"text": "stixpy"
},
"logo": {"text": "stixpy"},
}

# Add any paths that contain custom static files (such as style sheets) here,
Expand Down
49 changes: 32 additions & 17 deletions examples/imaging_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@
# Set time and energy ranges which will be considered for the science and the background file

time_range_sci = ["2021-09-23T15:21:00", "2021-09-23T15:24:00"]
time_range_bkg = ["2021-09-23T09:00:00", "2021-09-23T12:00:00"] # Set this range larger than the actual observation time
time_range_bkg = [
"2021-09-23T09:00:00",
"2021-09-23T12:00:00",
] # Set this range larger than the actual observation time
energy_range = [28, 40]

###############################################################################
Expand All @@ -75,9 +78,12 @@
###############################################################################
# Perform background subtraction

meta_pixels_bkg_subtracted = {"abcd_rate_kev_cm": meta_pixels_sci["abcd_rate_kev_cm"] - meta_pixels_bkg["abcd_rate_kev_cm"],
"abcd_rate_error_kev_cm": np.sqrt( meta_pixels_sci["abcd_rate_error_kev_cm"]**2 +
meta_pixels_bkg["abcd_rate_error_kev_cm"]**2)}
meta_pixels_bkg_subtracted = {
"abcd_rate_kev_cm": meta_pixels_sci["abcd_rate_kev_cm"] - meta_pixels_bkg["abcd_rate_kev_cm"],
"abcd_rate_error_kev_cm": np.sqrt(
meta_pixels_sci["abcd_rate_error_kev_cm"] ** 2 + meta_pixels_bkg["abcd_rate_error_kev_cm"] ** 2
),
}

###############################################################################
# Create visibilites from the meta pixels
Expand All @@ -89,8 +95,8 @@

# Extra phase calibration not needed with these
uv_data = get_uv_points_data()
vis.u = uv_data['u']
vis.v = uv_data['v']
vis.u = uv_data["u"]
vis.v = uv_data["v"]

cal_vis = calibrate_visibility(vis)

Expand Down Expand Up @@ -121,16 +127,18 @@

bp_image = vis_to_image(stix_vis, imsize, pixel_size=pixel)

date_avg = Time('2021-09-23T15:22:30')
date_avg = Time("2021-09-23T15:22:30")
roll, solo_xyz, pointing = get_hpc_info(date_avg)

solo = HeliographicStonyhurst(*solo_xyz, obstime=date_avg, representation_type='cartesian')
coord = STIXImaging(0*u.arcsec, 0*u.arcsec, obstime='2021-09-23T15:22:30', observer=solo)
header = make_fitswcs_header(bp_image, coord, telescope='STIX', observatory='Solar Orbiter', scale=[10,10]*u.arcsec/u.pix)
solo = HeliographicStonyhurst(*solo_xyz, obstime=date_avg, representation_type="cartesian")
coord = STIXImaging(0 * u.arcsec, 0 * u.arcsec, obstime="2021-09-23T15:22:30", observer=solo)
header = make_fitswcs_header(
bp_image, coord, telescope="STIX", observatory="Solar Orbiter", scale=[10, 10] * u.arcsec / u.pix
)
fd_bp_map = Map((bp_image, header))

hpc_ref = coord.transform_to(Helioprojective(observer=solo, obstime=fd_bp_map.date)) # Center of STIX pointing in HPC
header_hp = make_fitswcs_header(bp_image, hpc_ref, scale=[10, 10]*u.arcsec/u.pix, rotation_angle=90*u.deg+roll)
header_hp = make_fitswcs_header(bp_image, hpc_ref, scale=[10, 10] * u.arcsec / u.pix, rotation_angle=90 * u.deg + roll)
hp_map = Map((bp_image, header_hp))
hp_map_rotated = hp_map.rotate()

Expand Down Expand Up @@ -160,17 +168,24 @@
# Use estimated flare location to create more accurate visibilities

meta_pixels_sci = create_meta_pixels(
cpd_sci, time_range=time_range_sci, energy_range=energy_range, phase_center=[max_hpc.Tx, max_hpc.Ty], no_shadowing=True
cpd_sci,
time_range=time_range_sci,
energy_range=energy_range,
phase_center=[max_hpc.Tx, max_hpc.Ty],
no_shadowing=True,
)

meta_pixels_bkg_subtracted = {"abcd_rate_kev_cm": meta_pixels_sci["abcd_rate_kev_cm"] - meta_pixels_bkg["abcd_rate_kev_cm"],
"abcd_rate_error_kev_cm": np.sqrt( meta_pixels_sci["abcd_rate_error_kev_cm"]**2 +
meta_pixels_bkg["abcd_rate_error_kev_cm"]**2)}
meta_pixels_bkg_subtracted = {
"abcd_rate_kev_cm": meta_pixels_sci["abcd_rate_kev_cm"] - meta_pixels_bkg["abcd_rate_kev_cm"],
"abcd_rate_error_kev_cm": np.sqrt(
meta_pixels_sci["abcd_rate_error_kev_cm"] ** 2 + meta_pixels_bkg["abcd_rate_error_kev_cm"] ** 2
),
}

vis = create_visibility(meta_pixels_bkg_subtracted)
uv_data = get_uv_points_data()
vis.u = uv_data['u']
vis.v = uv_data['v']
vis.u = uv_data["u"]
vis.v = uv_data["v"]
cal_vis = calibrate_visibility(vis, [max_hpc.Tx, max_hpc.Ty])

###############################################################################
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from itertools import chain

from setuptools import setup # isort:skip

try:
# Recommended for setuptools 61.0.0+
# (though may disappear in the future)
Expand Down
2 changes: 1 addition & 1 deletion stixpy/calibration/detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from stixpy.calibration.transmission import Transmission
from stixpy.io.readers import read_energy_channel_index, read_sci_energy_channels

__all__ = ['get_srm','get_pixel_srm','get_sci_channels']
__all__ = ["get_srm", "get_pixel_srm", "get_sci_channels"]

SCI_INDEX = None
SCI_CHANNELS = {}
Expand Down
2 changes: 1 addition & 1 deletion stixpy/calibration/energy.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from stixpy.product import Product
from stixpy.utils.rebining import rebin_proportional

__all__ = ['get_elut','correct_counts']
__all__ = ["get_elut", "correct_counts"]


def get_elut(date):
Expand Down
3 changes: 2 additions & 1 deletion stixpy/calibration/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
import numpy as np
from astropy.table import Table

__all__ = ["get_grid_transmission","_calculate_grid_transmission"]
__all__ = ["get_grid_transmission", "_calculate_grid_transmission"]


def get_grid_transmission(xy_flare):
r"""
Expand Down
10 changes: 5 additions & 5 deletions stixpy/calibration/livetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,13 @@ def pileup_correction_factor():
"""

subc_str = read_subc_params()
large_pixel_area = (subc_str['L Pixel Xsize'] * subc_str['L Pixel Ysize'])[0]
small_pixel_area = (subc_str['S Pixel Xsize'] * subc_str['S Pixel Ysize'])[0]
large_pixel_area = (subc_str["L Pixel Xsize"] * subc_str["L Pixel Ysize"])[0]
small_pixel_area = (subc_str["S Pixel Xsize"] * subc_str["S Pixel Ysize"])[0]
# half a small pixel overlaps each big pixel
large_pixel_area_corrected = large_pixel_area - 0.5 * small_pixel_area
detector_area = (subc_str['Detect Xsize'] * subc_str['Detect Ysize'])[0]
big_pixel_fraction = large_pixel_area_corrected/detector_area
prob_diff_pix = (2/big_pixel_fraction - 1)/(2/big_pixel_fraction)
detector_area = (subc_str["Detect Xsize"] * subc_str["Detect Ysize"])[0]
big_pixel_fraction = large_pixel_area_corrected / detector_area
prob_diff_pix = (2 / big_pixel_fraction - 1) / (2 / big_pixel_fraction)

return prob_diff_pix

Expand Down
47 changes: 30 additions & 17 deletions stixpy/calibration/tests/test_visibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,46 @@
@pytest.fixture
@pytest.mark.remote_data
def flare_cpd():
return Product('https://pub099.cs.technik.fhnw.ch/fits/L1/2022/08/28/SCI/solo_L1_stix-sci-xray-cpd_20220828T154401-20220828T161600_V02_2208284257-61808.fits')
return Product(
"https://pub099.cs.technik.fhnw.ch/fits/L1/2022/08/28/SCI/"
"solo_L1_stix-sci-xray-cpd_20220828T154401-20220828T161600_V02_2208284257-61808.fits"
)


@pytest.fixture
@pytest.mark.remote_data
def background_cpd():
return Product('https://pub099.cs.technik.fhnw.ch/fits/L1/2022/08/24/SCI/solo_L1_stix-sci-xray-cpd_20220824T140037-20220824T145017_V02_2208242079-61784.fits')
return Product(
"https://pub099.cs.technik.fhnw.ch/fits/L1/2022/08/24/SCI/"
"solo_L1_stix-sci-xray-cpd_20220824T140037-20220824T145017_V02_2208242079-61784.fits"
)


def test_get_uv_points_data():
uv_data = get_uv_points_data()
assert uv_data['u'][0] == -0.03333102271709666 / u.arcsec
assert uv_data['v'][0] == 0.005908224739704219 / u.arcsec
assert uv_data['isc'][0] == 1
assert uv_data['label'][0] == '3c'
assert uv_data["u"][0] == -0.03333102271709666 / u.arcsec
assert uv_data["v"][0] == 0.005908224739704219 / u.arcsec
assert uv_data["isc"][0] == 1
assert uv_data["label"][0] == "3c"


def test_create_meta_pixels(background_cpd):
time_range = ['2022-08-24T14:00:37.271', '2022-08-24T14:50:17.271']
time_range = ["2022-08-24T14:00:37.271", "2022-08-24T14:50:17.271"]
energy_range = [20, 76]
meta_pixels = create_meta_pixels(background_cpd, time_range=time_range, energy_range=energy_range,
phase_center=[0,0]*u.arcsec, no_shadowing=True)

assert_quantity_allclose([0.17628464, 0.17251869,
0.16275495, 0.19153585] * u.ct / (u.keV * u.cm ** 2 * u.s),
meta_pixels['abcd_rate_kev_cm'][0, :])

assert_quantity_allclose([0.18701911, 0.18205339,
0.18328145, 0.17945563] * u.ct / (u.keV * u.cm ** 2 * u.s),
meta_pixels['abcd_rate_kev_cm'][-1, :])
meta_pixels = create_meta_pixels(
background_cpd,
time_range=time_range,
energy_range=energy_range,
phase_center=[0, 0] * u.arcsec,
no_shadowing=True,
)

assert_quantity_allclose(
[0.17628464, 0.17251869, 0.16275495, 0.19153585] * u.ct / (u.keV * u.cm**2 * u.s),
meta_pixels["abcd_rate_kev_cm"][0, :],
)

assert_quantity_allclose(
[0.18701911, 0.18205339, 0.18328145, 0.17945563] * u.ct / (u.keV * u.cm**2 * u.s),
meta_pixels["abcd_rate_kev_cm"][-1, :],
)
41 changes: 25 additions & 16 deletions stixpy/calibration/visibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@
from stixpy.calibration.livetime import get_livetime_fraction
from stixpy.io.readers import read_subc_params

__all__ = ["get_subcollimator_info",
"create_meta_pixels",
"create_visibility",
"get_uv_points_data",
"calibrate_visibility",
"sas_map_center"]
__all__ = [
"get_subcollimator_info",
"create_meta_pixels",
"create_visibility",
"get_uv_points_data",
"calibrate_visibility",
"sas_map_center",
]


def get_subcollimator_info():
r"""
Expand Down Expand Up @@ -160,7 +163,7 @@ def create_meta_pixels(pixel_data, time_range, energy_range, phase_center, no_sh
e_cor_high, e_cor_low = get_elut_correction(e_ind, pixel_data)

counts = pixel_data.data["counts"].astype(float)
count_errors = np.sqrt(pixel_data.data["counts_comp_err"].astype(float).value**2 + counts.value) * u.ct
count_errors = np.sqrt(pixel_data.data["counts_comp_err"].astype(float).value ** 2 + counts.value) * u.ct
ct = counts[t_ind][..., e_ind]
ct[..., 0:8, 0] = ct[..., 0:8, 0] * e_cor_low[..., 0:8]
ct[..., 0:8, -1] = ct[..., 0:8, -1] * e_cor_high[..., 0:8]
Expand All @@ -170,7 +173,7 @@ def create_meta_pixels(pixel_data, time_range, energy_range, phase_center, no_sh

lt = (livefrac * pixel_data.data["timedel"].reshape(-1, 1).to("s"))[t_ind].sum(axis=0)

ct_summed = ct.sum(axis=(0, 3))#.astype(float)
ct_summed = ct.sum(axis=(0, 3)) # .astype(float)
ct_error_summed = np.sqrt(np.sum(ct_error**2, axis=(0, 3)))

if not no_shadowing:
Expand All @@ -179,7 +182,9 @@ def create_meta_pixels(pixel_data, time_range, energy_range, phase_center, no_sh
ct_error_summed = ct_error_summed / grid_shadowing.reshape(-1, 1) / 4

abcd_counts = ct_summed.reshape(ct_summed.shape[0], -1, 4)[:, [0, 1], :].sum(axis=1)
abcd_count_errors = np.sqrt((ct_error_summed.reshape(ct_error_summed.shape[0], -1, 4)[:, [0, 1], :] ** 2).sum(axis=1))
abcd_count_errors = np.sqrt(
(ct_error_summed.reshape(ct_error_summed.shape[0], -1, 4)[:, [0, 1], :] ** 2).sum(axis=1)
)

abcd_rate = abcd_counts / lt.reshape(-1, 1)
abcd_rate_error = abcd_count_errors / lt.reshape(-1, 1)
Expand Down Expand Up @@ -297,7 +302,7 @@ def create_visibility(meta_pixels):


@u.quantity_input
def get_uv_points_data(d_det: u.Quantity[u.mm] = 47.78 * u.mm, d_sep:u.Quantity[u.mm] = 545.30 * u.mm):
def get_uv_points_data(d_det: u.Quantity[u.mm] = 47.78 * u.mm, d_sep: u.Quantity[u.mm] = 545.30 * u.mm):
r"""
Return the STIX (u,v) points coordinates defined in [1], ordered with respect to the detector index.
Expand Down Expand Up @@ -339,17 +344,21 @@ def get_uv_points_data(d_det: u.Quantity[u.mm] = 47.78 * u.mm, d_sep:u.Quantity[
front_unit_vector_comp = (((d_det + d_sep) / subc_imaging["Front Pitch"]) / u.rad).to(1 / u.arcsec)
rear_unit_vector_comp = ((d_det / subc_imaging["Rear Pitch"]) / u.rad).to(1 / u.arcsec)

uu = np.cos(subc_imaging["Front Orient"].to("deg")) * front_unit_vector_comp - np.cos(
subc_imaging["Rear Orient"].to("deg")) * rear_unit_vector_comp
vv = np.sin(subc_imaging["Front Orient"].to("deg")) * front_unit_vector_comp - np.sin(
subc_imaging["Rear Orient"].to("deg")) * rear_unit_vector_comp
uu = (
np.cos(subc_imaging["Front Orient"].to("deg")) * front_unit_vector_comp
- np.cos(subc_imaging["Rear Orient"].to("deg")) * rear_unit_vector_comp
)
vv = (
np.sin(subc_imaging["Front Orient"].to("deg")) * front_unit_vector_comp
- np.sin(subc_imaging["Rear Orient"].to("deg")) * rear_unit_vector_comp
)

uu = -uu * phase_sense
vv = -vv * phase_sense

uv_data = {
"isc": isc, # sub-collimator indices
"label": label, # sub-collimator labels
"isc": isc, # sub-collimator indices
"label": label, # sub-collimator labels
"u": uu,
"v": vv,
}
Expand Down
Loading

0 comments on commit 8867c2d

Please sign in to comment.