-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathHealpixCorrPlotter.py
270 lines (246 loc) · 9.82 KB
/
HealpixCorrPlotter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: Ampel-contrib-HU/ampel/contrib/hu/t3/HealpixCorrPlotter.py
# License: BSD-3-Clause
# Author: jn <[email protected]>
# Date: 16.12.2012
# Last Modified Date: 04.01.2022
# Last Modified By: jn <[email protected]>
import os
from collections.abc import Generator
from typing import Any, Literal
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from adjustText import adjust_text
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
from matplotlib.ticker import FormatStrFormatter, ScalarFormatter
from ampel.abstract.AbsPhotoT3Unit import AbsPhotoT3Unit
from ampel.struct.T3Store import T3Store
from ampel.types import T3Send
from ampel.view.TransientView import TransientView
from ampel.ztf.util.ZTFIdMapper import to_ztf_id
class HealpixCorrPlotter(AbsPhotoT3Unit):
"""
Compare healpix coordinate P-value with output from T2RunSncosmo.
"""
sncosmo_unit: str = "T2RunSncosmo"
model_name: str | None # Only use this model
time_parameter: str = (
"t0" # Name of the model parameter determining explosion / peak time
)
# What do we study
target_property: Literal["Abs fit peak mag", r"$\chi^2$ / d.o.f."] = (
"Abs fit peak mag"
)
target_range: list[float] = [-13.5, -17.5]
max_pvalue: float = 0.9
# Plot params
plotsize: tuple[float, float] = (6, 4)
# List of inclusive lower limit, non-inc upper limit, marker type, label
# marker_colors: list[str] = ["#E69F00", "#56B4E9", "#009E73", "#0072B2", "#D55E00", "#CC79A7", "#F0E442"]
# marker_colors: list[str] = ["#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#CC6677", "#882255", "#AA4499"]
marker_colors = matplotlib.colormaps.get_cmap("plasma")(np.linspace(0, 1, 5))
# marker_colors = [cm.get_cmap('summer', 3)(i) for i in range(3)]
background_color: str = "tab:green"
ndof_marker: list[Any] = [
[0, 0.5, "o", marker_colors[0], "0 dof"],
[1, 1.5, "^", marker_colors[1], "1 dof"],
[2, np.inf, "s", marker_colors[2], ">1 dof"],
]
debug_dir: None | str = None
def process(
self, gen: Generator[TransientView, T3Send, None], t3s: T3Store | None = None
) -> None:
self.logger.info("Printing transients info")
self.logger.info("=" * 80)
count = 0
table_rows: list[dict[str, Any]] = []
for tran_view in gen:
count += 1
self.logger.info(str(count))
# Stock info
tinfo = self._get_stock_info(tran_view)
# t2_info
t2docs = tran_view.get_raw_t2_body(unit=self.sncosmo_unit)
if t2docs is None:
continue
for t2info in t2docs:
assert isinstance(t2info, dict)
if self.model_name and t2info["model_name"] != self.model_name:
continue
if "fit_metrics" not in t2info:
continue
tinfo["z"] = t2info["z"]
if t2info["z_source"] in [
"AMPELz_group0",
"AMPELz_group1",
"AMPELz_group2",
"AMPELz_group3",
]:
tinfo["z_sharp"] = True
else:
tinfo["z_sharp"] = False
tinfo["zsource"] = t2info["z"]
tinfo["model"] = t2info["model_name"]
tinfo["model_peak_abs"] = t2info["fit_metrics"][
"restpeak_model_absmag_B"
]
tinfo["model_peak_obs"] = t2info["fit_metrics"]["obspeak_model_B"]
tinfo["ndof"] = t2info["sncosmo_result"]["ndof"]
tinfo["chisq"] = t2info["sncosmo_result"]["chisq"]
if t2info["sncosmo_result"]["ndof"] > 0:
tinfo["chisqndof"] = (
t2info["sncosmo_result"]["chisq"]
/ t2info["sncosmo_result"]["ndof"]
)
else:
tinfo["chisqndof"] = -1.0
tinfo["time"] = t2info["sncosmo_result"]["paramdict"][
self.time_parameter
]
self.logger.info(tinfo)
table_rows.append(tinfo)
self.logger.info("=" * 80)
self.logger.info(f"Printed info for {count} transients")
df = pd.DataFrame.from_dict(table_rows)
# figure
if self.target_property == "Abs fit peak mag":
df["target"] = df["model_peak_abs"]
elif self.target_property == r"$\chi^2$ / d.o.f.":
df["target"] = df["chisqndof"]
dy = self.target_range[1] - self.target_range[0]
plt.figure(figsize=self.plotsize, dpi=300)
ax = plt.gca()
plt.fill_between(
[0, self.max_pvalue],
self.target_range[0],
self.target_range[1],
alpha=0.5,
color=self.background_color,
)
plt.ylim([self.target_range[0] - dy, self.target_range[1] + dy])
# Iterate through all detections. Cumbersome, but could find no way to make batch Plotting
# while retaining PathCollection for adjustText and changing marker type.
annotations = []
targetpoints = []
for _, row in df.iterrows():
# Determine marker type (decided by d.o.f.)
marker = None
for minfo in self.ndof_marker:
if minfo[0] <= row["ndof"] < minfo[1]:
marker = minfo[2]
color = minfo[3]
if marker is None:
continue
# Determine outline (decided by redshift origin)
markeredgecolor = "None"
if row["z_sharp"]:
markeredgecolor = "k"
# Determine whether to annotate (decided target region)
if (
(row["pvalue"] <= self.max_pvalue)
& (np.abs(row["target"]) >= np.abs(self.target_range[0]))
& (np.abs(row["target"]) <= np.abs(self.target_range[1]))
):
annotations.append(plt.text(row["pvalue"], row["target"], row["name"]))
targetpoints.append(
plt.plot(
row["pvalue"],
row["target"],
marker,
ms=10,
color=color,
markeredgecolor=markeredgecolor,
)
)
else:
plt.plot(
row["pvalue"],
row["target"],
marker,
ms=10,
color=color,
markeredgecolor=markeredgecolor,
alpha=0.3,
)
plt.xscale("log")
ax.xaxis.set_major_formatter(FormatStrFormatter("%0.2f"))
ax.xaxis.set_minor_formatter(ScalarFormatter())
# adjust_text(annotations, arrowprops=dict(arrowstyle='->', color='red'), add_objects=targetpoints)
adjust_text(
annotations, arrowprops=dict(arrowstyle="->", color="darkslategrey")
)
# Create legend
# legend_elements = []
# for minfo in self.ndof_marker:
# legend_elements.append( Line2D([0], [0], marker=minfo[2], color=minfo[3], label=minfo[4], markeredgecolor='None' ) )
legend_elements = [
*(
Line2D(
[0],
[0],
marker=minfo[2],
color=minfo[3],
label=minfo[4],
markeredgecolor="None",
linewidth=0,
)
for minfo in self.ndof_marker
),
Line2D(
[0],
[0],
marker="o",
markerfacecolor="None",
label="Good z",
markeredgecolor="k",
linewidth=0,
),
Patch(
facecolor=self.background_color, edgecolor="None", label="Target region"
),
]
ax.legend(handles=legend_elements, loc="best", ncol=2)
# plt.legend(loc=3,ncol=2)
plt.xlabel("Healpix spatial P-value")
plt.ylabel(self.target_property)
# Determine titel (could be multiple?) from lists
channels = set()
for chlist in list(df["channel"]):
for ch in chlist:
channels.add(ch)
plt.title("{}".format(" ".join(channels)))
if self.debug_dir:
pdf = os.path.join(self.debug_dir, "test.pdf")
self.logger.info(f"Saving plot to {pdf}")
plt.savefig(pdf)
def _get_stock_info(self, tran: TransientView) -> dict[Any, Any]:
"""
Gather relevant information from stock document.
"""
assert isinstance(tran.id, int)
assert tran.stock
stockinfo = {
"id": tran.id,
"name": to_ztf_id(tran.id),
"channel": tran.stock["channel"],
}
# Could there be multiple healpix journal entries? I guess it cannot be ruled out
# FIXME: extra info should probably be in .extra, not mixed into the top level of JournalRecord
hpixs = [
el["healpix"] # type: ignore[typeddict-item]
for el in tran.stock["journal"]
if "healpix" in el
]
if len(hpixs) == 0:
self.logger.info("No healpix info")
return stockinfo
stockinfo.update(hpixs[0])
if len(hpixs) > 1:
for i, hpix in enumerate(hpixs[1:]):
stockinfo.update({k + str(i): v for k, v in hpix.items()})
self.logger.debug("Multiple healpix matches", extra=stockinfo)
return stockinfo