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

Save contour files to specified output directory #40

Merged
merged 4 commits into from
Dec 12, 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
68 changes: 36 additions & 32 deletions skyreader/plot/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,8 +626,7 @@ def bounding_box(ra, dec, theta, phi):
contour_colors,
contours_by_level
):
contour_label = contour_label + ' - area: {0:.2f} sqdeg'.format(
contour_area_sqdeg)
contour_label = contour_label + f' - area: {contour_area_sqdeg:.2f} sqdeg'
first = True
for contour in contours:
theta, phi = contour.T
Expand Down Expand Up @@ -746,7 +745,7 @@ def bounding_box(ra, dec, theta, phi):
# convert to square-degrees
bounding_contour_area *= (180.*180.)/(np.pi*np.pi)
contour_label = r'90% Bounding rectangle' + \
' - area: {0:.2f} sqdeg'.format(bounding_contour_area)
f' - area: {bounding_contour_area:.2f} sqdeg'
healpy.projplot(
bounding_theta,
bounding_phi,
Expand All @@ -755,30 +754,6 @@ def bounding_box(ra, dec, theta, phi):
linestyle='dashed',
label=contour_label
)
# Output contours in RA, dec instead of theta, phi
saving_contours: list = []
for contours in contours_by_level:
saving_contours.append([])
for contour in contours:
saving_contours[-1].append([])
theta, phi = contour.T
ras = phi
decs = np.pi/2 - theta
for tmp_ra, tmp_dec in zip(ras, decs):
saving_contours[-1][-1].append([tmp_ra, tmp_dec])
# Save the individual contours, send messages
for i, val in enumerate(["50", "90"]):
ras = list(np.asarray(saving_contours[i][0]).T[0])
decs = list(np.asarray(saving_contours[i][0]).T[1])
tab = {"ra (rad)": ras, "dec (rad)": decs}
savename = unique_id + ".contour_" + val + ".txt"
try:
LOGGER.info("Dumping to {savename}")
ascii.write(tab, savename, overwrite=True)
except OSError:
LOGGER.error(
"OS Error prevented contours from being written, "
"maybe a memory issue. Error is:\n{err}")

uncertainty = [(ra_minus, ra_plus), (dec_minus, dec_plus)]
fits_header = format_fits_header(
Expand Down Expand Up @@ -835,11 +810,6 @@ def bounding_box(ra, dec, theta, phi):
linestyle=cont_sty
)
plt.legend(fontsize=6, loc="lower left")
# Dump the whole contour
path = unique_id + ".contour.pkl"
print("Saving contour to", path)
with open(path, "wb") as f:
pickle.dump(saving_contours, f)

# save flattened map
equatorial_map, column_names = prepare_flattened_map(
Expand Down Expand Up @@ -878,6 +848,40 @@ def bounding_box(ra, dec, theta, phi):
bbox_inches='tight'
)

self._save_contours(contours_by_level, unique_id)
LOGGER.info("done.")

plt.close()

def _save_contours(self, contours_by_level, unique_id) -> None:
# Output contours in RA, dec instead of theta, phi
saving_contours: list = []
for contours in contours_by_level:
saving_contours.append([])
for contour in contours:
saving_contours[-1].append([])
theta, phi = contour.T
ras = phi
decs = np.pi/2 - theta
for tmp_ra, tmp_dec in zip(ras, decs):
saving_contours[-1][-1].append([tmp_ra, tmp_dec])

# Save the individual contours
for i, val in enumerate(["50", "90"]):
ras = list(np.asarray(saving_contours[i][0]).T[0])
decs = list(np.asarray(saving_contours[i][0]).T[1])
tab = {"ra (rad)": ras, "dec (rad)": decs}
savepath = self.output_dir / f"{unique_id}.contour_{val}.txt"
try:
LOGGER.info(f"Dumping to {savepath}")
ascii.write(tab, savepath, overwrite=True)
except OSError:
LOGGER.error(
"OS Error prevented contours from being written, "
"maybe a memory issue. Error is:\n{err}")

# Dump the whole contour
path = self.output_dir / f"{unique_id}.contour.pkl"
print("Saving contour to", path)
with open(path, "wb") as f:
pickle.dump(saving_contours, f)
6 changes: 3 additions & 3 deletions skyreader/plot/plotting_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def format_fits_header(
('EVENTID', event_id),
('SENDER', 'IceCube Collaboration'),
('EventMJD', mjd),
('I3TYPE', '%s'%event_type,'Alert Type'),
('I3TYPE', f'{event_type}','Alert Type'),
('RA', np.round(ra,2),'Degree'),
('DEC', np.round(dec,2),'Degree'),
('RA_ERR_PLUS', np.round(uncertainty[0][1],2),
Expand Down Expand Up @@ -99,12 +99,12 @@ def hp_ticklabels(zoom=False, lonra=None, latra=None, rot=None, bounds=None):
pe = [path_effects.Stroke(linewidth=1.5, foreground='white'),
path_effects.Normal()]
for _ in lats:
healpy.projtext(lon_offset, _, "{:.0f}$^\circ$".format(_),
healpy.projtext(lon_offset, _, f"{_:.0f}$^\\circ$",
lonlat=True, path_effects=pe, fontsize=10)
if zoom:
for _ in lons:
healpy.projtext(_, lat_offset,
"{:.0f}$^\circ$".format(_), lonlat=True,
f"{_:.0f}$^\\circ$", lonlat=True,
path_effects=pe, fontsize=10)
else:
ax.annotate(r"$\bf{-180^\circ}$", xy=(1.7, 0.625), size="medium")
Expand Down
Loading