-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathGeoCheck.py
More file actions
262 lines (214 loc) · 9.5 KB
/
GeoCheck.py
File metadata and controls
262 lines (214 loc) · 9.5 KB
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
import warnings
import xarray as xr
import numpy as np
import math
try:
import holoviews as hv
import hvplot.xarray
import skimage.draw
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm,Normalize
except (ModuleNotFoundError,ImportError):
warnings.warn('Could not import package for interactive integration utils. Install holoviews and scikit-image.',stacklevel=2)
import pandas as pd
import json
@xr.register_dataarray_accessor('geocheck')
class GeoCheck:
'''
Quick Utility to display a mask next to an image, to sanity check the orientation of e.g. an imported mask
'''
def __init__(self, xr_obj):
self._obj = xr_obj
self._pyhyper_type = 'reduced'
try:
self._chi_min = np.min(xr_obj.chi)
self._chi_max = np.max(xr_obj.chi)
self._chi_range = [self._chi_min, self._chi_max]
except AttributeError:
self._pyhyper_type = 'raw'
def checkMask(self,integrator,energy=None,img_min=1,img_max=10000,img_scaling='log',alpha=1):
'''
draw an overlay of the mask and an image
Args:
integrator: a PyHyper integrator object
img: a PyHyper raw image (single frame, please!) to draw
img_min: min value to display
img_max: max value to display
img_scaling: 'lin' or 'log'
'''
if energy == None:
if len(self._obj.shape) > 2:
try:
img = self._obj.isel(system=0)
except KeyError as e:
raise KeyError('This tool needs a single frame, not a stack! .sel down to a single frame before starting!') from e
else:
img = self._obj.sel(energy=energy)
if len(img.shape) > 2:
warnings.warn('This tool needs a single frame, not a stack! .sel down to a single frame before starting!',stacklevel=2)
fig,ax=plt.subplots(1,1)
if img_scaling == 'log':
norm=LogNorm(img_min,img_max)
else:
norm=Normalize(img_min,img_max)
img.plot(norm=norm,ax=ax)
ax.set_aspect(1)
ax.imshow(integrator.mask,origin='lower',alpha=alpha)
def checkCenter(self,integrator,energy=None,img_min=1,img_max=10000,img_scaling='log'):
'''
draw the beamcenter on an image
Args:
integrator: a PyHyper integrator object
img: a PyHyper raw image (single frame, please!) to draw
img_min: min value to display
img_max: max value to display
img_scaling: 'lin' or 'log'
'''
if energy == None:
if len(self._obj.shape) > 2:
try:
img = self._obj.isel(system=0)
except KeyError as e:
raise KeyError('This tool needs a single frame, not a stack! .sel down to a single frame before starting!') from e
else:
img = self._obj.sel(energy=energy)
if len(img.shape) > 2:
warnings.warn('This tool needs a single frame, not a stack! .sel down to a single frame before starting!',stacklevel=2)
fig,ax=plt.subplots()
if img_scaling == 'log':
norm=LogNorm(img_min,img_max)
else:
norm=Normalize(img_min,img_max)
img.plot(norm=norm,ax=ax)
ax.set_aspect(1)
beamcenter = plt.Circle((integrator.ni_beamcenter_x, integrator.ni_beamcenter_y), 5, color='lawngreen')
guide1 = plt.Circle((integrator.ni_beamcenter_x, integrator.ni_beamcenter_y), 50, color='lawngreen',fill=False)
guide2 = plt.Circle((integrator.ni_beamcenter_x, integrator.ni_beamcenter_y), 150, color='lawngreen',fill=False)
ax.add_patch(beamcenter)
ax.add_patch(guide1)
ax.add_patch(guide2)
def checkAll(self,integrator,energy=None,img_min=1,img_max=10000,img_scaling='log',alpha=1,d_inner=50,d_outer=150):
'''
draw the beamcenter and overlay mask on an image
Args:
integrator: a PyHyper integrator object
img: a PyHyper raw image (single frame, please!) to draw
img_min: min value to display
img_max: max value to display
img_scaling: 'lin' or 'log'
'''
if energy == None:
if len(self._obj.shape) > 2:
try:
img = self._obj.isel(system=0)
except KeyError as e:
raise KeyError('This tool needs a single frame, not a stack! .sel down to a single frame before starting!') from e
else:
img = self._obj.sel(energy=energy)
if len(img.shape) > 2:
warnings.warn('This tool needs a single frame, not a stack! .sel down to a single frame before starting!',stacklevel=2)
fig,ax=plt.subplots()
if img_scaling == 'log':
norm=LogNorm(img_min,img_max)
else:
norm=Normalize(img_min,img_max)
img.plot(norm=norm,ax=ax)
ax.set_aspect(1)
beamcenter = plt.Circle((integrator.ni_beamcenter_x, integrator.ni_beamcenter_y), 5, color='lawngreen')
guide1 = plt.Circle((integrator.ni_beamcenter_x, integrator.ni_beamcenter_y), d_inner, color='lawngreen',fill=False)
guide2 = plt.Circle((integrator.ni_beamcenter_x, integrator.ni_beamcenter_y), d_outer, color='lawngreen',fill=False)
ax.add_patch(beamcenter)
ax.add_patch(guide1)
ax.add_patch(guide2)
ax.imshow(integrator.mask,origin='lower',alpha=alpha)
@xr.register_dataarray_accessor('drawmask')
class DrawMask:
'''
Utility class for interactively drawing a mask in a Jupyter notebook.
Usage:
Instantiate a DrawMask object using a PyHyper single image frame.
Call DrawMask.ui() to generate the user interface
Call DrawMask.mask to access the underlying mask, or save/load the raw mask data with .save or .load
'''
def __init__(self,xr_obj):
'''
Construct a DrawMask object
Args:
frame (xarray): a single data frame with pix_x and pix_y axes
'''
self._obj = xr_obj
self._pyhyper_type = 'reduced'
try:
self._chi_min = np.min(xr_obj.chi)
self._chi_max = np.max(xr_obj.chi)
self._chi_range = [self._chi_min, self._chi_max]
except AttributeError:
self._pyhyper_type = 'raw'
def ui(self,energy):
'''
Draw the DrawMask UI in a Jupyter notebook.
Returns: the holoviews object
'''
if energy == None:
if len(self._obj.shape) > 2:
try:
img = self._obj.isel(system=0)
except KeyError as e:
raise KeyError('This tool needs a single frame, not a stack! .sel down to a single frame before starting!') from e
else:
img = self._obj.sel(energy=energy)
if len(img.shape) > 2:
warnings.warn('This tool needs a single frame, not a stack! .sel down to a single frame before starting!',stacklevel=2)
self.frame = img
self.fig = self.frame.hvplot(cmap='terrain',clim=(5,5000),logz=True,data_aspect=1)
self.poly = hv.Polygons([])
self.path_annotator = hv.annotate.instance()
print('Usage: click the "PolyAnnotator" tool at top right. DOUBLE CLICK to start drawing a masked object, SINGLE CLICK to add a vertex, then DOUBLE CLICK to finish. Click/drag individual vertex to adjust.')
return self.path_annotator(
self.fig * self.poly.opts(
width=self.frame.shape[0],
height=self.frame.shape[1],
responsive=False),
annotations=['Label'],
vertex_annotations=['Value'])
def save(self,fname):
'''
Save a parametric mask description as a json dump file.
Args:
fname (str): name of the file to save
'''
dflist = []
for i in range(len(self.path_annotator.annotated)):
dflist.append(self.path_annotator.annotated.iloc[i].dframe(['x','y']).to_json())
with open(fname, 'w') as outfile:
json.dump(dflist, outfile)
def load(self,fname):
'''
Load a parametric mask description from a json dump file.
Args:
fname (str): name of the file to read from
'''
with open(fname,'r') as f:
strlist = json.load(f)
print(strlist)
dflist = []
for item in strlist:
dflist.append(pd.read_json(item))
print(dflist)
self.poly = hv.Polygons(dflist)
self.path_annotator(
self.fig * self.poly.opts(
width=self.frame.shape[1],
height=self.frame.shape[0],
responsive=False),
annotations=['Label'],
vertex_annotations=['Value'])
@property
def mask(self):
'''
Render the mask as a numpy boolean array.
'''
mask = np.zeros(self.frame.shape).astype(bool)
for i in range(len(self.path_annotator.annotated)):
mask |= skimage.draw.polygon2mask(self.frame.shape,self.path_annotator.annotated.iloc[i].dframe(['x','y']))
return mask