petal-qc 0.0.1__py3-none-any.whl → 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of petal-qc might be problematic. Click here for more details.

petal_qc/__init__.py CHANGED
@@ -1,5 +1,5 @@
1
1
  """petal_qc python module."""
2
- __version__ = "0.0.1"
2
+ __version__ = "0.0.2"
3
3
 
4
4
 
5
5
  def coreMetrology():
@@ -12,6 +12,7 @@ import os
12
12
  import pickle
13
13
  import struct
14
14
  import sys
15
+ from argparse import ArgumentParser
15
16
  from collections.abc import Iterable
16
17
  from pathlib import Path
17
18
 
@@ -719,13 +720,12 @@ def open_file(fname):
719
720
  return irbf
720
721
 
721
722
 
722
- if __name__ == "__main__":
723
+ def main():
723
724
  """Example of use of IRBFile.
724
725
 
725
- Shows all the images in a file.
726
+ Shows all the images in a file.
726
727
 
727
728
  """
728
- from argparse import ArgumentParser
729
729
  parser = ArgumentParser()
730
730
  parser.add_argument('files', nargs='*', help="Input files")
731
731
  parser.add_argument("--save", action="store_true",
@@ -743,7 +743,8 @@ if __name__ == "__main__":
743
743
  fig = None
744
744
  nimg = 0
745
745
  ratio = -1
746
- for img in IRfile.images():
746
+ for ximg in IRfile.images():
747
+ img = ximg[0]
747
748
  tmin = np.min(img.image)
748
749
  print("Tmin {:1f} - {}x{}".format(tmin, img.width, img.height))
749
750
  if ratio < 0:
@@ -766,3 +767,6 @@ if __name__ == "__main__":
766
767
  plt.pause(0.00001)
767
768
 
768
769
  plt.show()
770
+
771
+ if __name__ == "__main__":
772
+ main()
@@ -41,6 +41,7 @@ class IRCore(object):
41
41
  self.files = []
42
42
  self.results = [] if results is None else results # list of AnalysisResults. One per side
43
43
  self.golden = [] # list of Golden results. One per side.
44
+ self.inlet = -9999
44
45
 
45
46
  def set_files(self, files):
46
47
  """Set the input files."""
@@ -1,11 +1,29 @@
1
1
  """Encapsulates different data structure at DESY and IFIC.
2
2
  """
3
+ import sys
4
+ from pathlib import Path
5
+ import numpy as np
6
+
7
+ try:
8
+ import petal_qc
9
+
10
+ except ImportError:
11
+ cwd = Path(__file__).parent.parent.parent
12
+ sys.path.append(cwd.as_posix())
3
13
 
4
14
 
5
- import numpy as np
6
15
  from petal_qc.thermal import IRPetal
7
16
  from petal_qc.thermal import Petal_IR_Analysis
8
17
 
18
+ HAS_GRAPHANA = False
19
+ try:
20
+ from petal_qc.utils.readGraphana import ReadGraphana
21
+ HAS_GRAPHANA = True
22
+
23
+ except ImportError:
24
+ HAS_GRAPHANA = False
25
+
26
+
9
27
 
10
28
  class IRDataGetter(object):
11
29
  """BAse class defining the interface."""
@@ -101,6 +119,10 @@ class IRDataGetter(object):
101
119
  """Get the frame where we want to perform the analysis."""
102
120
  return None
103
121
 
122
+ def get_inlet_temperature(self):
123
+ """REturn the inlet temperature."""
124
+ return -9999
125
+
104
126
 
105
127
  class IRDataIFIC(IRDataGetter):
106
128
  """Gets data for IFIC analysis."""
@@ -108,6 +130,11 @@ class IRDataIFIC(IRDataGetter):
108
130
  def __init__(self) -> None:
109
131
  """Initialization."""
110
132
  super().__init__()
133
+ self.analysis_frame = None
134
+ if HAS_GRAPHANA:
135
+ self.DB = ReadGraphana("localhost")
136
+ else:
137
+ self.DB = None
111
138
 
112
139
  def find_reference_image(self, irbf, *args, **kargs):
113
140
  """Find first image in sequence with T < T_min.
@@ -236,7 +263,19 @@ class IRDataIFIC(IRDataGetter):
236
263
  min_T.append(np.min(img[0].image))
237
264
 
238
265
  indx = IRDataIFIC.find_minimum(min_T)
239
- return [irbf.getImage(indx[-1])]
266
+ self.analysis_frame = [irbf.getImage(indx[-1])]
267
+ return self.analysis_frame
268
+
269
+ def get_inlet_temperature(self):
270
+ """REturn the inlet temperature."""
271
+ if self.DB:
272
+ img = self.analysis_frame[0]
273
+ val = self.DB.get_temperature(img.timestamp, 10)
274
+ return val
275
+
276
+ else:
277
+ return -9999
278
+
240
279
 
241
280
 
242
281
  class IRDataDESY(IRDataGetter):
@@ -13,6 +13,13 @@ from scipy import ndimage
13
13
  from scipy.optimize import minimize
14
14
  from skimage import measure
15
15
 
16
+ try:
17
+ import petal_qc
18
+
19
+ except ImportError:
20
+ cwd = Path(__file__).parent.parent.parent
21
+ sys.path.append(cwd.as_posix())
22
+
16
23
  from petal_qc.thermal import contours
17
24
  from petal_qc.thermal import CSVImage
18
25
  from petal_qc.thermal import DebugPlot
@@ -1212,7 +1219,7 @@ def get_image_from_irb(irbf, frame, thrs):
1212
1219
  """
1213
1220
  img = None
1214
1221
  i_min = frame
1215
- if irbf.n_images() == 0:
1222
+ if irbf.nimages == 0:
1216
1223
  print("Input file does not contain images.")
1217
1224
 
1218
1225
  else:
@@ -1246,12 +1253,12 @@ def read_image(fnam, frame=-1, thrs=-20):
1246
1253
  ifile = Path(fnam).expanduser().resolve()
1247
1254
  if not ifile.exists():
1248
1255
  print("Input file does not exist.")
1249
- return None
1256
+ return None, None
1250
1257
 
1251
1258
  suffix = ifile.suffix.lower()
1252
- img = None
1259
+ img = None, None
1253
1260
  if suffix == ".csv":
1254
- img = CSVImage.CSVImage(ifile)
1261
+ img = CSVImage.CSVImage(ifile), 0
1255
1262
 
1256
1263
  elif suffix == ".irb":
1257
1264
  irbf = IRBFile.IRBFile(ifile)
@@ -1274,12 +1281,12 @@ def main(fnam, options):
1274
1281
  params.debug = False
1275
1282
 
1276
1283
  print("Open file")
1277
- img = read_image(fnam, options.frame, options.thrs)
1284
+ img, _ = read_image(fnam, options.frame, options.thrs)
1278
1285
  if img is None:
1279
1286
  sys.exit()
1280
1287
 
1281
1288
  # Show original Image
1282
- fig, ax = plt.subplots(1, 1, dpi=300)
1289
+ fig, ax = plt.subplots(1, 1)
1283
1290
  values = get_IR_data(img, False)
1284
1291
  min_T = np.min(values)
1285
1292
  fig.suptitle("Original image - Temp. {:.1f}".format(min_T))
@@ -1290,7 +1297,7 @@ def main(fnam, options):
1290
1297
  # Show rotated image
1291
1298
  values = get_IR_data(img, True)
1292
1299
  min_T = np.min(values)
1293
- fig, ax = plt.subplots(1, 1, dpi=300)
1300
+ fig, ax = plt.subplots(1, 1)
1294
1301
  fig.suptitle("Rotated image - Temp. {:.1f}".format(min_T))
1295
1302
  pcm = ax.imshow(values, origin='lower', cmap="jet")
1296
1303
  fig.colorbar(pcm, ax=ax)
@@ -13,7 +13,7 @@ class IRPetalParam(object):
13
13
 
14
14
  """
15
15
  self.institute = 'IFIC' # Either IFIC or DESY to treat the different files
16
- self.thrs = -20.0 # the threshold
16
+ self.thrs = -22.0 # the threshold
17
17
  self.tco2 = -35.0 # Inlet temperature
18
18
  self.gauss_size = 15 # Radius of gausian filtering
19
19
  self.grad_sigma = 2.5 # Sigma of grading calculation
@@ -26,6 +26,7 @@ class IRPetalParam(object):
26
26
  self.do_fit = True # True to fit the segment points.
27
27
  self.rotate = True # Rotate to have a vertical petal in mirror image
28
28
  self.debug = False # To debug
29
+ self.report = False #
29
30
 
30
31
  if values is not None:
31
32
  self.set_values(values)
@@ -71,3 +72,4 @@ class IRPetalParam(object):
71
72
  parser.add_argument("--contour_smooth", type=float, default=P.contour_smooth,
72
73
  help="Value to smooth contour")
73
74
  parser.add_argument("--debug", action="store_true", default=False, help="Show additional information.")
75
+ parser.add_argument("--report", action="store_true", default=False, help="True if figures kept for the report.")
@@ -511,6 +511,7 @@ class PipeFit(object):
511
511
  ax.legend()
512
512
  plt.draw()
513
513
  plt.pause(0.0001)
514
+ return fig, ax
514
515
 
515
516
 
516
517
  def main(data_file, opts):
@@ -166,11 +166,102 @@ def golden_from_json(js_golden):
166
166
  """Converst a JSon golden into a Golden object."""
167
167
  golden = [Petal_IR_Analysis.AnalysisResult() for i in range(2)]
168
168
  for i, G in enumerate(golden):
169
- G.path_length = js_golden[i]["path_length"]
170
- G.path_temp = js_golden[i]["path_temp"]
171
- G.path_spread = js_golden[i]["path_spread"]
172
- G.sensor_avg = js_golden[i]["sensor_avg"]
173
- G.sensor_std = js_golden[i]["sensor_std"]
169
+ G.path_length = np.array(js_golden[i]["path_length"])
170
+ G.path_temp = np.array(js_golden[i]["path_temp"])
171
+ G.path_spread = np.array(js_golden[i]["path_spread"])
172
+ G.sensor_avg = np.array(js_golden[i]["sensor_avg"])
173
+ G.sensor_std = np.array(js_golden[i]["sensor_std"])
174
+
175
+ return golden
176
+
177
+ def get_golden_axis(R, golden):
178
+ """Compute result on golden points."""
179
+ xvalues = [ [x for x in golden[i].path_length] for i in range(2) ]
180
+ R.golden = []
181
+ for iside in range(2):
182
+ G = Petal_IR_Analysis.AnalysisResult()
183
+ splnT = CubicSpline(R.results[iside].path_length, R.results[iside].path_temp)
184
+ splnS = CubicSpline(R.results[iside].path_length, R.results[iside].path_spread)
185
+ G.path_length = np.array(xvalues[iside])
186
+ G.path_temp = np.array([splnT(x) for x in G.path_length])
187
+ G.path_spread = np.array([splnS(x) for x in G.path_length])
188
+ G.sensor_avg = np.array(R.results[iside].sensor_avg)
189
+ G.sensor_std = np.array(R.results[iside].sensor_std)
190
+ R.golden.append(G)
191
+
192
+
193
+ def plot_profile_and_golden(golden, core, value):
194
+ """Plot petal core and golden average.
195
+
196
+ Args:
197
+ ----
198
+ resuls: results from create_golden_average
199
+ golden: golden values (from create_golgen_average)
200
+ value: value to show, ej path_temp, path_spread, sensor_avg, sensor_std
201
+
202
+ """
203
+ tick_labels = ["R0", "R1", "R2", "R3", "R3", "R4", "R4", "R5", "R5", "EoS"]
204
+ figures = []
205
+ factor = 1.0
206
+ if value.find("sensor") >= 0:
207
+ factor = 2.0
208
+
209
+ # Get acceptance band
210
+ band = get_acceptance_band()
211
+
212
+ for iside in range(2):
213
+ fig, ax = plt.subplots(2, 1, tight_layout=True, gridspec_kw={'height_ratios': (0.66, 0.34)})
214
+ figures.append(fig)
215
+ fig.suptitle("Petal core .vs. Golden for {} - side {}.".format(value, iside))
216
+ for a in ax:
217
+ a.grid()
218
+
219
+ if value.find("path") < 0:
220
+ for i in range(2):
221
+ ax[i].set_xticks(range(10), labels=tick_labels)
222
+
223
+ RS = core.results[iside]
224
+ # convert to golden X
225
+ # TODO: get X, Y from petal core. Move golden to this X axis and draw differences.
226
+ # This only happens for the "_path" values, not for the sensors.
227
+ if value.find("path") >= 0:
228
+ X = RS.path_length
229
+ Y = getattr(RS, value)
230
+ spln = CubicSpline(golden[iside].path_length, getattr(golden[iside], value))
231
+ gY = np.array([spln(x) for x in X])
232
+ else:
233
+ X = np.array([float(x) for x in range(10)])
234
+ Y = getattr(RS, value)
235
+ gY = getattr(golden[iside], value)
236
+
237
+ delta = Y - gY
238
+ ax[0].plot(X, Y, '-', label=core.aliasID, linewidth=1)
239
+ ax[1].plot(X, delta, '-', label=core.aliasID, linewidth=1)
240
+
241
+ # Draw golden line
242
+ ax[0].plot(X, gY, '-', label="Golden", linewidth=4, alpha=0.4, color="black")
243
+
244
+ Tmean = np.mean(Y)
245
+ Tband = factor*abs(Tmean)/3
246
+
247
+ ax[0].legend(ncol=3, fontsize="x-small")
248
+ ax[0].set_title("T$_{prof}$ values")
249
+ if value.find("temp") >= 0 or value.find("_avg") >= 0:
250
+ ax[0].set_ylim(Tmean-Tband, Tmean+Tband)
251
+ ax[0].fill_between(X, gY + band, gY - band,
252
+ facecolor="yellow", alpha=0.25,
253
+ label="Acceptance band")
254
+
255
+ ax[1].fill_between(X, band, -band,
256
+ facecolor="yellow", alpha=0.25,
257
+ label="Acceptance band")
258
+
259
+ ax[1].legend(ncol=4, fontsize="x-small")
260
+ ax[1].set_title("T$_{prof}$ - Golden avg.")
261
+ if value.find("temp") >= 0 or value.find("_avg") >= 0:
262
+ ax[1].set_ylim(-Tband, Tband)
263
+
264
+ return figures
174
265
 
175
266
  def show_golden_average(golden, results, value):
176
267
  """Create golden average.
@@ -284,10 +375,10 @@ def analyze_petal_cores(files, golden, options):
284
375
  files (list): List of input files
285
376
  golden: the golden object
286
377
  options: other options.
287
-
378
+
288
379
  Return:
289
380
  array with JSon objects corresponding to the PDB test.
290
-
381
+
291
382
  """
292
383
  output = []
293
384
  names = get_names(files)
@@ -371,10 +462,10 @@ def analyze_petal_cores(files, golden, options):
371
462
  json.dump(dbOut, fp, indent=3, cls=IRCore.NumpyArrayEncoder)
372
463
 
373
464
  output.append(dbOut)
374
-
465
+
375
466
  return output
376
467
 
377
- def analyze_IRCore(options):
468
+ def analyze_IRCore(options, show=True):
378
469
  """Main entry."""
379
470
  output = None
380
471
  if options.create_golden:
@@ -410,7 +501,9 @@ def analyze_IRCore(options):
410
501
 
411
502
  output = analyze_petal_cores(options.files, golden, options)
412
503
 
413
- plt.show()
504
+ if show:
505
+ plt.show()
506
+
414
507
  return output
415
508
 
416
509
 
@@ -425,6 +518,8 @@ if __name__ == "__main__":
425
518
  parser.add_argument("--golden", default=None, help="The golden to compare width")
426
519
  parser.add_argument("--prefix", default="golden", help="Prefix for figures")
427
520
  parser.add_argument("--debug", action="store_true", default=False, help="Set to debug")
521
+ parser.add_argument("--report", action="store_true", default=False, help="Set to produce plots for report")
522
+
428
523
  parser.add_argument("--out", default=None, help="File to store Golden.")
429
524
  parser.add_argument("--folder", default=None, help="Folder to store output files. Superseeds folder in --out")
430
525
 
@@ -4,90 +4,30 @@ import sys
4
4
  from pathlib import Path
5
5
  from argparse import ArgumentParser
6
6
  import json
7
- import numpy as np
8
- from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
9
- from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3 as NavigationToolbar
10
7
  import itkdb_gtk
11
8
  import itkdb_gtk.ITkDButils
12
9
  import itkdb_gtk.dbGtkUtils
13
10
  import itkdb_gtk.UploadTest
11
+
12
+
13
+ try:
14
+ import petal_qc
15
+
16
+ except ImportError:
17
+ cwd = Path(__file__).parent.parent.parent
18
+ sys.path.append(cwd.as_posix())
19
+
20
+
14
21
  from petal_qc.thermal.IRPetalParam import IRPetalParam
15
22
  from petal_qc.thermal.create_IRCore import create_IR_core
16
- from petal_qc.thermal.analyze_IRCore import analyze_IRCore, golden_from_json, show_golden_average
23
+ from petal_qc.thermal.analyze_IRCore import analyze_IRCore, golden_from_json, get_golden_axis, plot_profile_and_golden
17
24
  from petal_qc.utils.utils import output_folder
18
25
 
19
26
  import gi
20
27
  gi.require_version("Gtk", "3.0")
21
28
  from gi.repository import Gtk, GObject, Gio, GLib
22
29
 
23
-
24
- def create_canvas(fig, sx=400, sy=300):
25
- """Creates a canvas."""
26
- sw = Gtk.ScrolledWindow() # Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
27
- sw.set_border_width(10)
28
- sw.set_size_request(310, 310)
29
- canvas = FigureCanvas(fig) # a Gtk.DrawingArea
30
- canvas.set_size_request(sx, sy)
31
- sw.add(canvas)
32
- return sw
33
-
34
- class ShowThermalResults(Gtk.Window):
35
- """Show thermal results."""
36
- def __init__(self, golden, results):
37
- """Create the window."""
38
- super().__init__(title="Thermal Results")
39
-
40
- # Create main content box
41
- self.mainBox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
42
- self.add(self.mainBox)
43
-
44
- # The notebook
45
- self.notebook = Gtk.Notebook()
46
- self.notebook.set_tab_pos(Gtk.PositionType.LEFT)
47
- self.mainBox.pack_start(self.notebook, True, True, 20)
48
-
49
- # thermal path
50
- box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
51
- box.set_border_width(5)
52
- label = Gtk.Label(label="Path Temp,")
53
- self.notebook.append_page(box, label)
54
-
55
- figs = show_golden_average(golden, results, "path_temp")
56
- sw = create_canvas(figs[0])
57
- box.pack_start(sw, True, True, 0)
58
-
59
- sw = create_canvas(figs[q])
60
- box.pack_start(sw, True, True, 0)
61
-
62
- box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
63
- box.set_border_width(5)
64
- label = Gtk.Label(label="Sensor Avg,")
65
- self.notebook.append_page(box, label)
66
-
67
- figs = show_golden_average(golden, results, "sensor_avg")
68
- sw = create_canvas(figs[0])
69
- box.pack_start(sw, True, True, 0)
70
-
71
- sw = create_canvas(figs[q])
72
- box.pack_start(sw, True, True, 0)
73
-
74
-
75
-
76
- # The button box
77
- btnBox = Gtk.ButtonBox(orientation=Gtk.Orientation.HORIZONTAL)
78
-
79
- btn = Gtk.Button(label="Quit")
80
- btn.connect("clicked", self.quit)
81
- btnBox.add(btn)
82
-
83
- self.mainBox.pack_start(btnBox, False, True, 0)
84
-
85
- self.show_all()
86
-
87
- def quit(self, *args):
88
- """Close window."""
89
- self.hide()
90
- self.destroy()
30
+ from petal_qc.thermal.create_core_report import create_report
91
31
 
92
32
  class CoreThermal(itkdb_gtk.dbGtkUtils.ITkDBWindow):
93
33
  """Application window."""
@@ -146,7 +86,7 @@ class CoreThermal(itkdb_gtk.dbGtkUtils.ITkDBWindow):
146
86
  self.SN.connect("text-changed", self.on_SN_changed)
147
87
 
148
88
  self.run = Gtk.Button(label="Run")
149
- self.run.connect("clicked", self.run_analysis)
89
+ self.run.connect("clicked", self.create_report)
150
90
 
151
91
  self.btn_state = Gtk.Button(label="Undef")
152
92
  self.btn_state.set_name("btnState")
@@ -338,8 +278,8 @@ class CoreThermal(itkdb_gtk.dbGtkUtils.ITkDBWindow):
338
278
  return
339
279
  uploadW = itkdb_gtk.UploadTest.UploadTest(self.session, payload=self.outDB)
340
280
 
341
- def run_analysis(self, *args):
342
- """Run analysis."""
281
+ def create_report(self, *args):
282
+ """Creates the thermal report."""
343
283
  if self.irbfile is None:
344
284
  self.write_message("Missing IRB file\n")
345
285
  return
@@ -349,16 +289,13 @@ class CoreThermal(itkdb_gtk.dbGtkUtils.ITkDBWindow):
349
289
  self.param.alias = self.alternativeID
350
290
  self.param.SN = self.SN.get_text()
351
291
 
352
- core = create_IR_core(self.param)
353
-
354
- self.param.files[0] = output_folder(self.param.folder, self.param.out)
355
- self.param.out = None
356
- out = analyze_IRCore(self.param)
357
- self.outDB = out[0] if len(out) else None
358
- self.param.files = []
359
- self.write_message("Done\n")
292
+ self.param.tco2 = float(self.entryTemp.get_text())
293
+ self.param.distance = int(self.entryDist.get_text())
294
+ self.param.thrs = float(self.entryTHrs.get_text())
295
+ self.param.debug = False
296
+ self.param.report = True
360
297
 
361
- outW = ShowThermalResults(self.golden, [core, ])
298
+ self.outDB = create_report(self.param)
362
299
  if self.outDB:
363
300
  if len(self.outDB["defects"]) > 0:
364
301
  itkdb_gtk.dbGtkUtils.set_button_color(self.btn_state, "red", "white")
@@ -9,6 +9,13 @@ from pathlib import Path
9
9
  import dateutil
10
10
  import matplotlib.pyplot as plt
11
11
 
12
+ try:
13
+ import petal_qc
14
+
15
+ except ImportError:
16
+ cwd = Path(__file__).parent.parent.parent
17
+ sys.path.append(cwd.as_posix())
18
+
12
19
  from petal_qc.thermal import IRBFile
13
20
  from petal_qc.thermal import IRCore
14
21
  from petal_qc.thermal import IRPetal
@@ -50,8 +57,24 @@ def get_db_date(timestamp=None):
50
57
  return out
51
58
 
52
59
 
60
+ __figures__ = {}
61
+ def get_IRcore_plots():
62
+ """Return global list of figures."""
63
+ return __figures__
64
+
65
+ def clean_figures():
66
+ global __figures__
67
+ for key, fig in __figures__:
68
+ fig.clean()
69
+ plt.close(fig)
70
+
71
+ __figures__ = {}
72
+
53
73
  def create_IR_core(options):
54
74
  """Entry point."""
75
+ global __figures__
76
+ clean_figures()
77
+
55
78
  # Obtain the Data getter.
56
79
  try:
57
80
  getter = IRDataGetter.factory(options.institute, options)
@@ -76,8 +99,9 @@ def create_IR_core(options):
76
99
  min_T, i_min, values = getter.find_reference_image(irbf, params.thrs, nframes=10)
77
100
  print("Image size: {} x {}".format(values[0].shape[0], values[0].shape[1]))
78
101
 
79
- if options.debug:
80
- Petal_IR_Analysis.show_2D_image(values)
102
+ if options.debug or options.report:
103
+ fig, ax = Petal_IR_Analysis.show_2D_image(values)
104
+ __figures__["original"] = fig
81
105
 
82
106
  except LookupError as e:
83
107
  print(e)
@@ -99,8 +123,9 @@ def create_IR_core(options):
99
123
  pipe_order[i] = pipe_type
100
124
  PF = PipeFit.PipeFit(pipe_type)
101
125
  R = PF.fit_ex(pipes[i], factor=getter.factor)
102
- if options.debug:
103
- PF.plot()
126
+ if options.debug or options.report:
127
+ fig, _ =PF.plot()
128
+ __figures__["fit_{}".format(i)] = fig
104
129
 
105
130
  transforms[pipe_type] = R
106
131
  fitter[pipe_type] = PF
@@ -128,7 +153,7 @@ def create_IR_core(options):
128
153
 
129
154
  # get the framea from where extract the data
130
155
  # reorder if needed
131
- frames = getter.get_analysis_frame(irbf)
156
+ frames = getter.get_analysis_frame(irbf)
132
157
  if pipe_order[0]:
133
158
  tmp = frames[0]
134
159
  frames[0] = frames[1]
@@ -159,7 +184,7 @@ def create_IR_core(options):
159
184
 
160
185
  if options.debug:
161
186
  plt.show()
162
-
187
+
163
188
  return core
164
189
 
165
190
 
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env python3
2
+ """Creates the report of a core."""
3
+
4
+ import math
5
+ import sys
6
+ import json
7
+ from argparse import ArgumentParser
8
+ from pathlib import Path
9
+
10
+ import matplotlib.path as mplPath
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+
14
+
15
+ try:
16
+ import petal_qc
17
+
18
+ except ImportError:
19
+ cwd = Path(__file__).parent.parent.parent
20
+ sys.path.append(cwd.as_posix())
21
+
22
+ from petal_qc.thermal.IRPetalParam import IRPetalParam
23
+ from petal_qc.thermal.create_IRCore import create_IR_core, get_IRcore_plots
24
+ from petal_qc.thermal.analyze_IRCore import analyze_IRCore, golden_from_json, get_golden_axis, plot_profile_and_golden
25
+
26
+ import petal_qc.utils.docx_utils as docx_utils
27
+ import petal_qc.utils.utils as utils
28
+
29
+
30
+
31
+ def create_report(options):
32
+ """Create a writen report.
33
+ """
34
+ ifile = Path(options.files[0]).expanduser().resolve()
35
+ if not ifile.exists():
36
+ print("input file {} does not exist.".format(ifile))
37
+ return
38
+
39
+ goldenFile = Path(options.golden).expanduser().resolve()
40
+ if not goldenFile.exists():
41
+ print("I need a golden file.")
42
+
43
+ with open(goldenFile, "r", encoding='utf-8') as fp:
44
+ golden = golden_from_json(json.load(fp))
45
+
46
+
47
+
48
+ document = docx_utils.Document()
49
+ document.add_page_numbers()
50
+ document.styles['Normal'].font.name = "Calibri"
51
+ document.add_heading(options.SN, 0)
52
+
53
+ P = document.add_paragraph(ifile.name, "Subtitle")
54
+ P.alignment = docx_utils.paragraph_align_center()
55
+
56
+ P = document.add_paragraph("Golden: {}".format(goldenFile.name), "Subtitle")
57
+ P.alignment = docx_utils.paragraph_align_center()
58
+
59
+
60
+ core = create_IR_core(options)
61
+
62
+ figures = get_IRcore_plots()
63
+ document.add_heading('Original image', level=1)
64
+ document.add_picture(figures["original"], True, 14, caption="Original Thermal image.")
65
+
66
+ document.add_heading('Result of Pipe Fit', level=1)
67
+ document.add_picture(figures["fit_0"], True, 10, caption="Size 0 fit.")
68
+ document.add_picture(figures["fit_1"], True, 10, caption="Size 1 fit.")
69
+
70
+ options.add_attachments = True
71
+ options.create_golden = False
72
+
73
+ options.files[0] = utils.output_folder(options.folder, options.out)
74
+ options.out = None
75
+ out = analyze_IRCore(options, show=False)
76
+ outDB = out[0] if len(out) else None
77
+ options.files = []
78
+
79
+ get_golden_axis(core, golden)
80
+
81
+ figures = plot_profile_and_golden(golden, core, "path_temp")
82
+ document.add_heading('Temperature along path', level=1)
83
+ document.add_picture(figures[0], True, 12, caption="Petal core .vs. Golden (side 0).")
84
+ document.add_picture(figures[0], True, 12, caption="Petal core .vs. Golden (side 1).")
85
+
86
+ figures = plot_profile_and_golden(golden, core, "sensor_avg")
87
+ document.add_heading('Average Temperatur on sensors areas.', level=1)
88
+ document.add_picture(figures[0], True, 12, caption="Sensors .vs. Golden (side 0).")
89
+ document.add_picture(figures[0], True, 12, caption="Sensors .vs. Golden (side 1).")
90
+
91
+ ofile = utils.output_folder(options.folder, "{}-thermal.docx".format(options.SN))
92
+ document.save(ofile)
93
+
94
+ return outDB
95
+
96
+ if __name__ == "__main__":
97
+ P = IRPetalParam()
98
+ parser = ArgumentParser()
99
+ parser.add_argument('files', nargs='*', help="Input files")
100
+ parser.add_argument("--orig", action="store_true", default=False, help="plot the original image")
101
+ parser.add_argument('--frame', default=-1, type=int, help="Frame to analize")
102
+ parser.add_argument("--out", default="core.json", help="Output file name")
103
+ parser.add_argument("--alias", default="", help="Alias")
104
+ parser.add_argument("--SN", default="", help="serial number")
105
+ parser.add_argument("--folder", default=None, help="Folder to store output files. Superseeds folder in --out")
106
+ parser.add_argument("--add_attachments", action="store_true", default=False, help="If true add the attachments section os DB file.")
107
+ parser.add_argument("--golden", default=None, help="The golden to compare width")
108
+
109
+
110
+ IRPetalParam.add_parameters(parser)
111
+
112
+ options = parser.parse_args()
113
+
114
+ if len(options.files) == 0:
115
+ print("I need an input file")
116
+ sys.exit()
117
+ else:
118
+ ifile = options.files[0]
119
+
120
+ options.debug = False
121
+ options.report = True
122
+ create_report(options)
@@ -12,6 +12,14 @@ from pathlib import PurePath
12
12
  import matplotlib.pyplot as plt
13
13
  import matplotlib.ticker as ticker
14
14
  import numpy as np
15
+
16
+ try:
17
+ import petal_qc
18
+
19
+ except ImportError:
20
+ cwd = Path(__file__).parent.parent.parent
21
+ sys.path.append(cwd.as_posix())
22
+
15
23
  from petal_qc.thermal import contours
16
24
  from petal_qc.thermal import IRBFile
17
25
  from petal_qc.thermal import IRPetal
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env python3
2
+ """Test the connection with graphana to get the value at the peak."""
3
+ import sys
4
+ from pathlib import Path
5
+ import datetime
6
+ try:
7
+ import petal_qc
8
+
9
+ except ImportError:
10
+ cwd = Path(__file__).parent.parent.parent
11
+ sys.path.append(cwd.as_posix())
12
+
13
+ from petal_qc.utils.readGraphana import ReadGraphana
14
+ from petal_qc.thermal.IRDataGetter import IRDataGetter
15
+ from petal_qc.thermal.IRPetalParam import IRPetalParam
16
+ from petal_qc.thermal import IRBFile
17
+
18
+
19
+ options = IRPetalParam()
20
+ options.files = ["/Users/lacasta/tmp/thermal/PPC.007.irb"]
21
+ getter = IRDataGetter.factory(options.institute, options)
22
+ DB = ReadGraphana("localhost")
23
+ irbf = IRBFile.open_file(options.files)
24
+
25
+ frames = getter.get_analysis_frame(irbf)
26
+ print(frames[0].timestamp)
27
+ the_time = datetime.fromtimestamp(timestamp, timezone.utc)
28
+ val = DB.get_temperature(frames[0].timestamp, 10)
29
+
30
+ print(val)
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env python3
2
+ """Probando."""
3
+ import sys
4
+ import json
5
+ from pathlib import Path
6
+
7
+ try:
8
+ import petal_qc
9
+
10
+ except ImportError:
11
+ cwd = Path(__file__).parent.parent.parent
12
+ sys.path.append(cwd.as_posix())
13
+
14
+
15
+ import numpy as np
16
+ import matplotlib.pyplot as plt
17
+
18
+ from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
19
+ from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3 as NavigationToolbar
20
+
21
+ import petal_qc
22
+ from petal_qc.thermal.IRPetalParam import IRPetalParam
23
+ from petal_qc.thermal.create_IRCore import create_IR_core
24
+ from petal_qc.thermal.analyze_IRCore import analyze_IRCore, golden_from_json, get_golden_axis, plot_profile_and_golden
25
+ from petal_qc.utils.utils import output_folder
26
+
27
+
28
+ irbFile="/private/tmp/thermal/PPB08.irb"
29
+ goldenFIle = "/private/tmp/thermal/golden-PPB.json"
30
+ outFolder = "/private/tmp/thermal"
31
+
32
+ param = IRPetalParam()
33
+ param.alias = "PPB_008"
34
+ param.SN = "20USEBC1000028"
35
+ param.tco2 = -31.7
36
+ param.out = "{}.json".format(param.alias)
37
+ param.files = [irbFile, ]
38
+ param.golden = goldenFIle
39
+ param.folder = outFolder
40
+ param.create_golden = False
41
+ param.add_attachments = True
42
+
43
+ with open(goldenFIle, "r", encoding='utf-8') as fp:
44
+ golden = golden_from_json(json.load(fp))
45
+
46
+ core = create_IR_core(param)
47
+
48
+ param.files[0] = output_folder(outFolder, param.out)
49
+ param.out = None
50
+ out = analyze_IRCore(param)
51
+ outDB = out[0] if len(out) else None
52
+ param.files = []
53
+
54
+ get_golden_axis(core, golden)
55
+
56
+ plot_profile_and_golden(golden, core, "path_temp")
57
+
58
+ plt.show()
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env python3
2
+ """Class to access graphana data."""
3
+
4
+ import datetime
5
+ from dateutil.parser import parse
6
+ import influxdb
7
+ import numpy as np
8
+
9
+
10
+ class ReadGraphana(object):
11
+ """Connect to the GraphanaDB"""
12
+
13
+ def __init__(self, host="silab15.ific.uv.es", port=8086):
14
+ """Connect to Graphan server
15
+
16
+ Args:
17
+ host (str, optional): The IP of the server.
18
+ port (int, optional): The port to the server.
19
+ """
20
+ self.client = influxdb.InfluxDBClient(host=host, port=port,
21
+ username="matlab", password="matlab",
22
+ database="clean_room")
23
+
24
+ def get_temperature(self, the_time, window=10):
25
+ """REturns the temperature
26
+
27
+ Args:
28
+ teh_time: the time to query the DB.
29
+ window: the time window, in minutes, around the given time.
30
+ """
31
+ if not isinstance(the_time, datetime.datetime):
32
+ the_time = parse(the_time)
33
+
34
+ td = datetime.timedelta(minutes=window/2)
35
+ t1 = the_time - td # datetime.datetime(year=2024, month=5, day=22, hour=15)
36
+ t2 = the_time + td #datetime.datetime(year=2024, month=5, day=23, hour=15)
37
+
38
+ measure="Temp"
39
+ setup="MARTA_APP|MARTA_tt06"
40
+ query = "select location,value from {measure} where (location =~ /.*{location}*/ and time>'{t1}' and time < '{t2}') group by \"location\"".format(
41
+ measure=measure,
42
+ location=setup,
43
+ t1=t1.isoformat()+'Z',
44
+ t2=t2.isoformat()+'Z')
45
+
46
+ ss = self.client.query(query)
47
+ nitems = 0
48
+ for s in ss:
49
+ nitems += len(s)
50
+
51
+ if nitems==0:
52
+ raise ValueError(("No data found"))
53
+
54
+ T = []
55
+ for s in ss:
56
+ for v in s:
57
+ T.append(v['value'])
58
+
59
+
60
+ val = np.mean(T)
61
+ return val
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: petal_qc
3
- Version: 0.0.1
3
+ Version: 0.0.2
4
4
  Summary: A collection of scripts for Petal CORE QC.
5
5
  Author-email: Carlos Lacasta <carlos.lacasta@cern.ch>
6
6
  Project-URL: Homepage, https://gitlab.cern.ch/atlas-itk/sw/db/itk-pdb-gtk-gui-utils
@@ -1,4 +1,4 @@
1
- petal_qc/__init__.py,sha256=2q00gtEJFdw6a2_u6tM6FVJIlBYFKb1bQ8iqoEugWpA,337
1
+ petal_qc/__init__.py,sha256=qgmsBfB_EW96gEoFQLrZhf2KsTrIy3KffxsjNF_Cy5I,337
2
2
  petal_qc/dashBoard.py,sha256=aPugRYhCcAzEBPrCyh8A8QKYaB4Q-_T1q3r5A3J2eog,553
3
3
  petal_qc/BTreport/CheckBTtests.py,sha256=4hNP1V-zcFBN5UvWVbx9nAmittF8Jmb5J17L33t68Eg,9086
4
4
  petal_qc/BTreport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -24,32 +24,36 @@ petal_qc/metrology/testSummary.py,sha256=0BhcEd1BPz2Mbonzi8nyZOzNSzpUqowBFNl5cVu
24
24
  petal_qc/metrology/test_paralelism.py,sha256=_j__OdUwdXWM494_9HpGPuPHixMwwVphCcvHEfzWi_k,1981
25
25
  petal_qc/thermal/CSVImage.py,sha256=Vt2kYmUsZWkQvxcF8fDda3HO1Rb29kPQHnEoHFCqWYo,2038
26
26
  petal_qc/thermal/DebugPlot.py,sha256=OmREFwNDAKgoObDmcgHrB4d8m3bf2znfsKVGsb5rBGQ,2119
27
- petal_qc/thermal/IRBFile.py,sha256=zj82SdI-MDfZq1i0n47PuZMLLx_0oKpE-ZaykJZs6BU,22225
28
- petal_qc/thermal/IRCore.py,sha256=Iasus1wy1pDQvBMPhcPYN1gFHZGv7tO5KJlpJZGuck4,3029
29
- petal_qc/thermal/IRDataGetter.py,sha256=dX_FjeGc7qxinJ1JPC_4rSLSJlYtkKuAL31LURfv2a8,9662
30
- petal_qc/thermal/IRPetal.py,sha256=X6I7JmyWf_9mPHjTsuBztM-1b5wre2NW4VM-6dz4Gow,38208
31
- petal_qc/thermal/IRPetalParam.py,sha256=KlCJn0s9f0LSbQiUQG9aAJfwZ7EHApg2Aj665glZUr8,3516
27
+ petal_qc/thermal/IRBFile.py,sha256=gudyAMwYjBtfXhx-Kxbott9Lpbnfm4oKnizIE5vrkoE,22270
28
+ petal_qc/thermal/IRCore.py,sha256=y79YEQrq4q2hSdmYbOF7jjEA-wy50Qun0g_AmrRUmls,3056
29
+ petal_qc/thermal/IRDataGetter.py,sha256=cT20apD0xN9VCKY01yXQTx9cV1Pk4xjVy3sXR3ROHGQ,10580
30
+ petal_qc/thermal/IRPetal.py,sha256=8H1ltpahzJavM65De8OTSedvilXQkr3LkV8mRnTDhLQ,38334
31
+ petal_qc/thermal/IRPetalParam.py,sha256=hrQ9FevzWctvBVHeQ71G0WzllVEa5rYkJom2ezfFYHc,3674
32
32
  petal_qc/thermal/PetalColorMaps.py,sha256=6CvJHzRdojLHu3BROYSekHw8g_BJ1lJ_edyhovTIydU,3831
33
33
  petal_qc/thermal/Petal_IR_Analysis.py,sha256=8Deh_bJ5B7DdaUV18saboF7fXZ_8Bt1vkUlsk5RqVeo,3910
34
- petal_qc/thermal/PipeFit.py,sha256=qbNvi547U9EttfRxCaIrizK69Hw3mJOKuG4SGRQaHRk,17191
34
+ petal_qc/thermal/PipeFit.py,sha256=bipXxJGxrwlgbrFv8WJA1Ds7Kj4oUwEyqTIswpgni9o,17214
35
35
  petal_qc/thermal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
36
- petal_qc/thermal/analyze_IRCore.py,sha256=A2i6_O2XfS8uRCpaUXDRm_p8_1zTBS3DJJHC4kS5s90,14463
36
+ petal_qc/thermal/analyze_IRCore.py,sha256=6qV8q4yEJxB1hkhXi-SozI3fZXMh9zNHnwfjvpI380k,18086
37
37
  petal_qc/thermal/contours.py,sha256=ampCKm4byZYKb_4eJFjIkdFIl2bqVXD2mV13d2XUWlw,8244
38
- petal_qc/thermal/coreThermal.py,sha256=B4LAOaZ6DWWoRtqQ0WU3VyRCluKxvQWZ_1GWRmLOF6o,14428
39
- petal_qc/thermal/create_IRCore.py,sha256=u1sSSTX4nsBIW0bclu4O7tEvWL_bXlB97V8THJE_ppI,5638
38
+ petal_qc/thermal/coreThermal.py,sha256=q1e_8e19TPL3EeJzJKiMo04-nIdXAU6b_XSJNuF-zGU,12320
39
+ petal_qc/thermal/create_IRCore.py,sha256=3J6vj1xyjtwoe2OdHv8LbjTgo4I_vaiw_05DWidY9v4,6206
40
+ petal_qc/thermal/create_core_report.py,sha256=x3yx4CxbPARmLHqjpt5-yNZELRiHadEOufMpDFNEr5g,4239
40
41
  petal_qc/thermal/pipe_back.npz,sha256=yooZuVYtHU541HcV6Gh_5B0BqdYAVEvYAuVvMMSY7Jc,3632
41
42
  petal_qc/thermal/pipe_front.npz,sha256=DuwruG9C2Z1rLigqWMApY4Orsf1SGUQGKy0Yan8Bk8A,3697
42
43
  petal_qc/thermal/pipe_read.py,sha256=HrAtEbf8pMhJDETzkevodiTbuprIOh4yHv6PzpRoz7Q,5040
43
- petal_qc/thermal/show_IR_petal.py,sha256=PGAq7qiWmchYx4tGPgWJxeHi2N-pM_C1a4tmXYe0htY,13029
44
+ petal_qc/thermal/show_IR_petal.py,sha256=vKb8wm9Y7erAdCb93ODREv2qfSexNMfJpV-67wfOhBw,13159
45
+ petal_qc/thermal/test_Graphana.py,sha256=lr3JYC8XwwsZLfhGK2M1swOiIvDUTf5IYc6pqxZyCSA,878
46
+ petal_qc/thermal/test_coreThermal.py,sha256=YRPK3DGG7Tz66K4Kka3euXgUDzW_JlIqSYicMBhb96E,1516
44
47
  petal_qc/utils/Geometry.py,sha256=XwA_aojk880N-jC1_bnMYFK0bcD-L96JPS81NUerJf0,19765
45
48
  petal_qc/utils/Progress.py,sha256=gCti4n2xfCcOTlAff5GchabGE5BCwavvDZYYKdbEsXU,4064
46
49
  petal_qc/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
47
50
  petal_qc/utils/all_files.py,sha256=4ja_DkbTYPY3gUPBAZq0p7KB9lnXZx-OCnpTHg9tm4I,1044
48
51
  petal_qc/utils/docx_utils.py,sha256=Eye16PF8W0mPBVdQvgFKWxPYV7-hzBgANPDZtUEjzf8,5805
49
52
  petal_qc/utils/fit_utils.py,sha256=3KUGWpBMV-bVDkQHWBigXot8chOpjAVBJ5H5b5dbdjk,5349
53
+ petal_qc/utils/readGraphana.py,sha256=-l1iVazszGOgH2oUYAbjaIyxUvM8G4Bzoar491tsWjg,1862
50
54
  petal_qc/utils/utils.py,sha256=CqCsNIcEg6FQb3DN70tmqeLVLlQqsRfDzhfGevlnfBc,4035
51
- petal_qc-0.0.1.dist-info/METADATA,sha256=I0nY8IdvLJW9DEnt6pZ8TiRQWR-ammo41RonPXaPfpg,943
52
- petal_qc-0.0.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
53
- petal_qc-0.0.1.dist-info/entry_points.txt,sha256=ZsBmzA1gRvZSe4ZKcxlo0b-RBjySccqBhL6g_CJhNaM,92
54
- petal_qc-0.0.1.dist-info/top_level.txt,sha256=CCo1Xe6kLS79PruhsB6bk2CuL9VFtNdNpgJjYUs4jk4,9
55
- petal_qc-0.0.1.dist-info/RECORD,,
55
+ petal_qc-0.0.2.dist-info/METADATA,sha256=SPjkEowJUpsvFQv4FEoQ60BmJzg7Fj_zILlVDf0e2oo,943
56
+ petal_qc-0.0.2.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
57
+ petal_qc-0.0.2.dist-info/entry_points.txt,sha256=ZsBmzA1gRvZSe4ZKcxlo0b-RBjySccqBhL6g_CJhNaM,92
58
+ petal_qc-0.0.2.dist-info/top_level.txt,sha256=CCo1Xe6kLS79PruhsB6bk2CuL9VFtNdNpgJjYUs4jk4,9
59
+ petal_qc-0.0.2.dist-info/RECORD,,