File: xsh_calib_interactive_common.py

package info (click to toggle)
cpl-plugin-xshoo 3.5.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 20,920 kB
  • sloc: ansic: 170,001; sh: 4,369; python: 2,391; makefile: 1,211
file content (709 lines) | stat: -rw-r--r-- 28,406 bytes parent folder | download | duplicates (2)
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
# import the needed modules
from __future__ import absolute_import
from __future__ import print_function
try:
#  import sys
  import numpy
  try:
    from astropy.io import fits as pyfits
  except:
    import pyfits

  import xsh_parameters_common
#  import wx
#  import matplotlib
  import reflex
  #from xsh_plot_common import *
  from reflex import parseSofJson,RecipeParameter
  from reflex_interactive_app import PipelineInteractiveApp
  from pipeline_product import PipelineProduct
  from pipeline_display import SpectrumDisplay, ImageDisplay, ScatterDisplay
#  matplotlib.use('WXAgg')
  import_sucess = 'true'
  import warnings
  warnings.simplefilter('ignore',UserWarning)

#NOTE for developers: 
# -If you want to modify the current script to cope
#  with different parameters, this is the function to modify:
#  setInteractiveParameters()
# -If you want to modify the current script to read different data from
#  the input FITS, these are the functions (class DataPlotterManager) to modify:
#  readFitsData()    to indicate what are the FITS input to plot
#  plotSpectrum()    to control 1D image product layout
#  plotImage()       to control 2D image product layout
#  plotTable()       to control 1D table product layout
#  oplotTable()      to control 1D table product overplots
#  setRecId()        to set rec id (used in parameter prefix)
#  getArmId()        to get arm id FITS header info
#
# -If you want to modify the current script to modify the plots (using the same
#  data),  this is the function to modify:
#  plotProductsGraphics()          (from class DataPlotterManager)
# -If you want to modify the text that appears in the "Help" button,
#  this is the function to modify:
#  setWindowHelp()
# -If you want to modify the title of the window, modify this function:
#  setWindowTitle()


  #This class deals with the specific details of data reading and final plotting.
  class DataPlotterManager:

    def paragraph(self,text, width=None):
       """ wrap text string into paragraph
           text:  text to format, removes leading space and newlines
           width: if not None, wraps text, not recommended for tooltips as
                  they are wrapped by wxWidgets by default
       """
       import textwrap
       #print 'width=',width,'Text=',text
       if width is None:
           return textwrap.dedent(text).replace('\n', ' ').strip()
       else:
           return textwrap.fill(textwrap.dedent(text), width=width) 


    #1D spectrum plots
    def plotSpectrum(self,data,errs,subplot,title,tooltip):
        data.readSpectrum(0)
        errs.readSpectrum(1)
        spectrum = SpectrumDisplay()
        spectrum.setLabels('Wavelength [nm]','Total Flux ['+data.bunit+']')
        spectrum.display(subplot,title,self.paragraph(tooltip),data.wave,data.flux,errs.flux, autolimits = True) 

    #2D image display
    def plotImage(self,obj,bpm,subplot,title,tooltip):

          obj.readImage(fits_extension=0)
          obj.read2DLinearWCS(fits_extension=0)
          img_obj = ImageDisplay()

          bpm.readImage(fits_extension=2)
          img_bpm = ImageDisplay()

          img_obj.setLabels('Wavelength [nm]','Position Along Slit [arcsec]')
          y_size, x_size = obj.image.shape

          img_obj.setXLinearWCSAxis(obj.crval1,obj.cdelt1,obj.crpix1)
          img_obj.setYLinearWCSAxis(obj.crval2,obj.cdelt2,obj.crpix2)

          #img_obj.setLimits((1,x_size),(0,y_size))
          img_obj.display(subplot, title, self.paragraph(tooltip),obj.image,bpm.image)

    def oplotImageScatter(self,img,tab,ext,binx,biny,Xcol,Ycol,subplot, marker = 'o', size = 10, color = 'blue' ):
          tab.readTableXYColumns(fits_extension=ext,xcolname=Xcol, ycolname=Ycol)


          py_to_FITS_off_x=0
          py_to_FITS_off_y=0
          label_off_x=0
          label_off_y=0
          #print 'offset=',label_off_x,label_off_y,py_to_FITS_off_x,py_to_FITS_off_y

          img.overplotScatter(tab.x_column/binx+py_to_FITS_off_x, tab.y_column/biny+py_to_FITS_off_y, marker, size, color)

    def prepImageScatter(self,img_disp,obj,bpm,Xlab,Ylab):

          obj.readImage(fits_extension=0)
          obj.read2DLinearWCS(fits_extension=0)

          bpm.readImage(fits_extension=2)
          img_bpm = ImageDisplay()

          img_disp.setLabels(Xlab,Ylab)
          y_size, x_size = obj.image.shape

          img_disp.setXLinearWCSAxis(obj.crval1,obj.cdelt1,obj.crpix1)
          img_disp.setYLinearWCSAxis(obj.crval2,obj.cdelt2,obj.crpix2)

          #self.img_obj.setLimits((0,x_size),(0,y_size))


    #2D image display
    def plotImageScatter1Col(self,obj,bpm,tab,ext,binx,biny,Xlab,Ylab,Xcol1,Ycol1,subplot,title,tooltip):

          img_disp = ImageDisplay()

          self.prepImageScatter(img_disp,obj,bpm,Xlab,Ylab)

          self.oplotImageScatter(img_disp,tab,ext,binx,biny,Xcol1,Ycol1,subplot, 'o', 10, 'green' )

          bpm_filt = ( (bpm.image.astype(int) & self.decode_bp) != 0 )
          img_disp.display(subplot, title, self.paragraph(tooltip),obj.image,bpm_filt)
          #as the scatter display add extra space round the image (not
          #to have points at edges) we force the bounds of the scatter
          #plot to be the same as the image size.
          #subplot.set_xbound(0,obj.image.shape[1])
          #subplot.set_ybound(0,obj.image.shape[0])

    #2D image display
    def plotImageScatter2Col(self,obj,bpm,tab,ext,binx,biny,Xlab,Ylab,Xcol1,Ycol1,Xcol2,Ycol2,subplot,title,tooltip):

          img_disp = ImageDisplay()

          self.prepImageScatter(img_disp,obj,bpm,Xlab,Ylab)

          self.oplotImageScatter(img_disp,tab,ext,binx,biny,Xcol1,Ycol1,subplot, 'o', 10, 'blue' )
          self.oplotImageScatter(img_disp,tab,ext,binx,biny,Xcol2,Ycol2,subplot, 'o', 10, 'yellow' )

          bpm_filt = ( (bpm.image.astype(int) & self.decode_bp) != 0 )
          img_disp.display(subplot, title, self.paragraph(tooltip),obj.image,bpm_filt)
          #as the scatter display add extra space round the image (not
          #to have points at edges) we force the bounds of the scatter
          #plot to be the same as the image size.
          #subplot.set_xbound(0,obj.image.shape[1])
          #subplot.set_ybound(0,obj.image.shape[0])

    #2D image display
    def plotImageScatter3Col(self,obj,bpm,tab,ext,binx,biny,Xlab,Ylab,Xcol1,Ycol1,Xcol2,Ycol2,Xcol3,Ycol3,subplot,title,tooltip):

          img_disp = ImageDisplay()

          self.prepImageScatter(img_disp,obj,bpm,Xlab,Ylab)


          self.oplotImageScatter(img_disp,tab,ext,binx,biny,Xcol1,Ycol1,subplot, 'o', 10, 'blue' )
          self.oplotImageScatter(img_disp,tab,ext,binx,biny,Xcol2,Ycol2,subplot, 'o', 10, 'yellow' )
          self.oplotImageScatter(img_disp,tab,ext,binx,biny,Xcol3,Ycol3,subplot, 'o', 10, 'green' )

#          self.img_obj.setXLinearWCSAxis(img_obj.crval1,img_obj.cdelt1,img_obj.crpix1)

          bpm_filt = ( (bpm.image.astype(int) & self.decode_bp) != 0 )
          img_disp.display(subplot, title,self.paragraph(tooltip),obj.image,bpm_filt)
          #as the scatter display add extra space round the image (not
          #to have points at edges) we force the bounds of the scatter
          #plot to be the same as the image size.
          #subplot.set_xbound(0,obj.image.shape[1])
          #subplot.set_ybound(0,obj.image.shape[0])


    #1D spectrum table plots
    def plotTable(self,tab,Xcol,Ycol,Xlab,Ylab,subplot,title,tooltip,
    wave = None):

        tab.readTableXYColumns(fits_extension=1,xcolname=Xcol, ycolname=Ycol)
        spectrum = SpectrumDisplay()
        flux_plotmax = 1.2 * numpy.nanmax(tab.y_column)
        flux_plotmin = 0.0
        spectrum.setLabels(Xlab,Ylab)
        spectrum.flux_lim = flux_plotmin, flux_plotmax
        if wave is not None:
           spectrum.setWaveLimits((wave[0], wave[len(wave)-1]))

        spectrum.display(subplot,title,self.paragraph(tooltip),tab.x_column,tab.y_column) 

    #1D spectrum table over-plots
    def oplotTable(self,tab,Xcol,Ycol,Xlab,Ylab,subplot,color):

        tab.readTableXYColumns(fits_extension=1,xcolname=Xcol, ycolname=Ycol)
        spectrum = SpectrumDisplay()
        spectrum.overplot(subplot,tab.x_column,tab.y_column,color)


    def scatterPlotScatter(self, subplot, x, y):
        subplot.scatter(x, y, s=0.4, color='blue')
        subplot.ticklabel_format(style='sci',scilimits=(0,3))

    def scatterPlotLabels(self, subplot, x_label, y_label):
        subplot.set_xlabel(x_label, fontsize=12)
        subplot.set_ylabel(y_label, fontsize=12)

    def finalSetup(self, subplot, title, tooltip):
        subplot.grid(True)
        subplot.set_title(title, fontsize=12)
        subplot.tooltip = self.paragraph(tooltip)


    def scatterPlot(self, subplot, x, y, x_label, y_label, title, tooltip):

        self.scatterPlotScatter(subplot, x, y)
        self.scatterPlotLabels(subplot, x_label, y_label)
        self.scatterPlotLimits(subplot, x, y)
        self.finalSetup(subplot, title, self.paragraph(tooltip))

    def scatterPlotLimits(self, subplot, x, y):
        subplot.set_xlim(numpy.nanmin(x)-1, numpy.nanmax(x) + 1.)
        subplot.set_ylim(1.05 * numpy.nanmin(y), 1.05 * numpy.nanmax(y))



    #1D table scatter plots
    def plotTableScatter(self,tab,Xcol,Ycol,Xlab,Ylab,subplot,title,tooltip,ext_no=None):
        extno=1
        if ext_no != None :
           extno=ext_no

        tab.readTableXYColumns(fits_extension=extno,xcolname=Xcol,ycolname=Ycol)
        self.scatterPlotScatter(subplot, tab.x_column, tab.y_column)
        self.scatterPlotLabels(subplot, Xlab, Ylab)
        self.scatterPlotLimits(subplot, tab.x_column, tab.y_column)
        self.finalSetup(subplot, title, self.paragraph(tooltip))
        self.scatterPlot(subplot, tab.x_column, tab.y_column, Xlab, Ylab, title, tooltip)


    # This function will read all the columns, images and whatever is needed
    # from the products. The variables , self.plot_x, self.plot_y, etc...
    # are used later in function plotProductsGraphics().
    # Add/delete these variables as you need (only that plotProductsGraphics()
    # has to use the same names).
    # You can also create some additional variables (like statistics) after
    # reading the files.
    # If you use a control variable (self.xxx_found), you can modify 
    # later on the layout of the plotting window based on the presence of 
    # given input files. 
    # sof contains all the set of frames
    def readFitsData(self, fitsFiles):
      #Control variable to check if the interesting files where at the input
      prefix = "CAL_"
      self.resid_tab_found   = False
      self.edges_tab_found   = False
      self.mflat_found = False
      self.frameON_found      = False
      self.grid_back_found      = False
      self.sub_back_found   = False
      self.obj_sky2D_found   = False
      self.bpm_found   = False
      self.arm_uvb_found      = False
      self.arm_vis_found      = False
      self.arm_nir_found      = False
      self.nima = 0
      self.binx = 1
      self.biny = 1
      
      #Read all the products
      frames = dict()
      for frame in fitsFiles:
        if frame == '' :
          continue

        header = pyfits.open(frame.name)
        #Make sure to have only products from the same recipe
        #that used this (common) script 
        if 'ESO PRO REC1 ID' in header[0].header :
           rec_id = header[0].header['ESO PRO REC1 ID']
           if rec_id == self.rec_id :
              category = frame.category
              frames[category] = frame


      prefixes = [k.split('_')[0] for k in frames.keys()]
      if "FMTCHK" in prefixes and self.rec_id == "xsh_predict" :
        prefix = "FMTCHK_"
      elif "WAVE" in prefixes and self.rec_id == "xsh_2dmap":
        prefix = "WAVE_"
      elif "FLAT" in prefixes and self.rec_id == "xsh_mflat":
        prefix = "MFLAT_"
      elif "ORDERDEF" in prefixes and self.rec_id == "xsh_orderpos":
        prefix = "ORDERDEF_"
      elif "FLEX" in prefixes and self.rec_id == "xsh_flexcomp":
        prefix = "FLEX_"
 
      arm=self.seq_arm

      if arm == "UVB":
         self.arm_uvb_found = True
      if arm == "VIS":
         self.arm_vis_found = True
      if arm == "NIR":
         self.arm_nir_found = True

# For any arm search a list of input frames
      #print "arm=",arm , "prefix=",prefix 
      #print frames
      key = prefix+"RESID_TAB_LINES_"+arm
      if key in frames :
        self.resid_tab_found = True
        hdulist = frames[prefix+"RESID_TAB_LINES_"+arm]
        self.resid_tab = PipelineProduct(hdulist)
        #self.resid_tab_2plot = PlotableResidLineTable(hdulist,1)
        #self.nima += 1
        #print "found resid tab"

      key = "ORDERPOS_RESID_TAB_"+arm
      if key in frames :
        self.resid_tab_found = True
        hdulist = frames["ORDERPOS_RESID_TAB_"+arm]
        self.resid_tab = PipelineProduct(hdulist)
        #self.resid_tab_2plot = PlotableResidLineTable(hdulist,1)
        #self.nima += 1
        #print "found orderpos resid tab"


      key = "ORDER_TAB_EDGES_SLIT_"+arm
      if key in frames :
        self.edges_tab_found = True
        hdulist = frames["ORDER_TAB_EDGES_SLIT_"+arm]
        self.edges_tab = PipelineProduct(hdulist)
        #self.nima += 1
        #print "found edges tab"

      key = "ORDER_TAB_EDGES_IFU_"+arm
      if key in frames :
        self.edges_tab_found = True
        hdulist = frames["ORDER_TAB_EDGES_IFU_"+arm]
        self.edges_tab = PipelineProduct(hdulist)
        #self.nima += 1
        #print "found edges tab"
        
      key = prefix+"ON_"+arm
      if key in frames :
        self.frameON_found = True
        hdulist = frames[prefix+"ON_"+arm]
        self.bpm = PipelineProduct(hdulist)
        self.frameON = PipelineProduct(hdulist)
        #self.nima += 1
        #print "found on frame"

      key = "MASTER_FLAT_SLIT_"+arm
      if key in frames :
        self.mflat_found = True
        fitsfile = frames["MASTER_FLAT_SLIT_"+arm]
        self.bpm = PipelineProduct(fitsfile)
        self.mflat = PipelineProduct(fitsfile)
        hdulist = pyfits.open(fitsfile.name)
        #print "found mflat frame",self.mflat_found
        #print "Bin setting",self.binx,self.biny

      key = "MASTER_FLAT_IFU_"+arm
      if key in frames :
        self.mflat_found = True
        fitsfile = frames["MASTER_FLAT_IFU_"+arm]
        self.bpm = PipelineProduct(fitsfile)
        self.mflat = PipelineProduct(fitsfile)
        hdulist = pyfits.open(fitsfile.name)
        #print "found mflat frame",self.mflat_found
        #print "Bin setting",self.binx,self.biny


      key = prefix+"GRID_BACK_SLIT_"+arm
      if key in frames :
        self.grid_back_found = True
        hdulist = frames[prefix+"GRID_BACK_SLIT_"+arm]
        self.grid_back = PipelineProduct(hdulist)
        #print "found grid background"

      key = prefix+"GRID_BACK_IFU_"+arm
      if key in frames :
        self.grid_back_found = True
        hdulist = frames[prefix+"GRID_BACK_IFU_"+arm]
        self.grid_back = PipelineProduct(hdulist)
        #print "found grid background"

      key = prefix+"SUB_BACK_SLIT_"+arm
      if key in frames :
        self.sub_back_found = True
        hdulist = frames[prefix+"SUB_BACK_SLIT_"+arm]
        self.sub_back = PipelineProduct(hdulist)
        #print "found background subtracted frame"

      #print "monitor mflat",self.mflat_found

    #Set rec id (to have proper recipe parameters prefix)
    def setRecId(self, rec_id):
      #Recipe ID variable to properly define params
      self.rec_id = rec_id

    #Get arm setting
    def getArmId(self, sof):
      #Recipe ID variable to properly define params
      self.rec_id = "xsh_predict"
      self.seq_arm = "UVB"
      nf = 0

      frames = dict()
      files = sof.files
      for f in files:
        frame=f.name
        if frame == '' :
          continue
        else :
           nf += 1
           hdulist = pyfits.open(frame)
           rec_id_list = hdulist[0].header['ESO PRO REC1 ID']
           arm_list = hdulist[0].header['ESO SEQ ARM']
      if nf != 0 :
         self.rec_id = rec_id_list[0:]
         self.seq_arm = arm_list[0:]

      if self.seq_arm == "UVB":
         self.arm_uvb_found = True

      if self.seq_arm == "VIS":
         self.arm_uvb_found = True

      if self.seq_arm == "NIR":
         self.arm_uvb_found = True

      if self.rec_id == "xsh_predict":
         self.rec_subtitle = "Spectral Format. "
      if self.rec_id == "xsh_orderpos":
         self.rec_subtitle = "Order Position. "
      if self.rec_id == "xsh_mflat":
         self.rec_subtitle = "Master Flat Creation. "
      if self.rec_id == "xsh_2dmap":
         self.rec_subtitle = "2D Geometry. "
      self.decode_bp = int(hdulist[0].header['ESO PRO REC1 PARAM4 VALUE'])
      
    # This function creates all the subplots. It is responsible for the plotting 
    # layouts. 
    # There can different layouts, depending on the availability of data
    # Note that subplot(I,J,K) means the Kth plot in a IxJ grid 
    # Note also that the last one is actually a box with text, no graphs.
    def addSubplots(self, figure):
      nrows=self.nima
      row=1;
      #print "nrows=",nrows,row
      #print "resid_tab_found",self.resid_tab_found, "frameON_found",self.frameON_found
      if self.resid_tab_found == True and self.frameON_found == True:
        #self.subplot_frameON  = figure.add_subplot(nrows,1,row)
        #self.subplot_resid_tab  = figure.add_subplot(nrows,2,row+1)
        self.subplot_frameON  = figure.add_subplot(2,1,1)
        self.subplot_resid_x_tab  = figure.add_subplot(2,2,3)
        self.subplot_resid_y_tab  = figure.add_subplot(2,2,4)
        row +=1

      elif self.edges_tab_found == True and self.mflat_found == True:
        #self.subplot_mflat  = figure.add_subplot(nrows,1,row)
        self.subplot_mflat  = figure.add_subplot(1,1,1)
        row +=1
        
        #print "monitor mflat",self.mflat_found

      else : 
        self.subtext_nodata    = figure.add_subplot(1,1,1)
        #print "found no spectrum data"
      #print "nrows=",nrows,row

          
    # This is the function that makes the plots.
    # Add new plots or delete them using the given scheme.
    # The data has been already stored in self.plot_x, self.plot_xdif, etc ...
    # It is mandatory to add a tooltip variable to each subplot.
    # One might be tempted to merge addSubplots() and plotProductsGraphics().
    # There is a reason not to do it: addSubplots() is called only once at
    # startup, while plotProductsGraphics() is called always there is a resize.
    def plotProductsGraphics(self):
      #print "arc check:",  self.resid_tab_found, self.frameON_found
      #print "mfat check:",  self.edges_tab_found, self.mflat_found
      if (self.resid_tab_found == True and self.frameON_found == True) or (self.edges_tab_found == True and self.mflat_found == True): 
        #and self.lineguess_found == True 
        title_pref = 'Linear-extracted and Merged Spectrum.'          

        tooltip_spectrum ="""\
        Plot of the linear-extracted and merged spectrum of the object 
        (blue line) as total flux (ADU) versus wavelength (nm). 
        The  +-1 sigma uncertainties are plotted as upper and lower
        red curves. Note that this spectrum is not flux calibrated.
        """


        if self.arm_uvb_found == True:
          title_spectrum   = title_pref

        if self.arm_vis_found == True:
          title_spectrum   = title_pref

        if self.arm_nir_found == True:
          title_spectrum   = title_pref
           
           
        #Display ON frame

        #Overplot initial list of lines
        #Overplot gauss list of lines
        #Overplot final list of lines

        #Scatter plot ResidX(lambda)
        #Scatter plot ResidY(lambda)

        #Scatter plot X(lambda)
        #Scatter plot Y(lambda)


        #Image
        spec_frameON   = ''
        if self.rec_id[4:12] == "predict" or self.rec_id[4:9] == "2dmap" :

           spec_frameON   = 'Arc lamp pinhole '
           tooltip_frameON ="""\
           Bias (and dark) corrected arc lamp pinhole
           image. Blue points are the predicted positions of the arc lines
           in the reference arc line list using the initial physical
           model. Yellow points are the positions of those predicted
           lines that are successfully found and fitted by a two-dimensional
           Gaussian. Green points are the line positions which remain after
           thresholding the Gaussian fits for signal-to-noise and
           refining the physical model fit.  
           A red hue corresponds to flagged pixels, which
           may be good or bad.
          """

        elif self.rec_id[4:12] == "orderpos" :
           spec_frameON   = 'Flat lamp pinhole '
           tooltip_frameON ="""\
           Bias (and dark) corrected flat lamp pinhole
           image. Green points trace each detected order. 
           A red hue corresponds to flagged pixels, which
           may be good or bad.
           """
        
        title_frameON   = spec_frameON+'Image'

        title_mflat   = 'Master flat frame'
        tooltip_mflat ="""\
                Image of the bias (dark) corrected master flat
                frame. Over are displayed order central traces (blue), and
                order detected  edges (left-yellow, right-green). 
                A red hue corresponds to flagged pixels, which
                may be good or bad.
                """


        title_plot_residX   = 'X Residual vs wavelength ' 
        tooltip_plot_residX ="""\
                             X Residual vs wavelength."""

        title_plot_residY   = 'Y Residual vs wavelength ' 
        tooltip_plot_residY ="""\
                             Y Residual vs wavelength."""

        title_plot_X   = 'X vs wavelength ' 
        tooltip_plot_X ="""\
                        X vs wavelength."""

        title_plot_Y   = 'Y vs wavelength ' 
        tooltip_plot_Y ="""\
                        Y vs wavelength."""


        #2D frame PRE format (predict/orderpos/2dmap/wavecal/flexcomp)
        #print "arc check:",  self.resid_tab_found, self.frameON_found
        if self.resid_tab_found == True and self.frameON_found == True:
           if self.rec_id[4:12] == "predict" or self.rec_id[4:9] == "2dmap" :
              self.plotImageScatter3Col(self.frameON,self.bpm,self.resid_tab,1, self.binx,self.biny,'X [pix]', 'Y [pix]', 'Xthpre', 'Ythpre', 'XGauss', 'YGauss', 'Xthanneal', 'Ythanneal', self.subplot_frameON,title_frameON,tooltip_frameON)

           if self.rec_id[4:12] == "orderpos" :

              self.plotImageScatter1Col(self.frameON,self.bpm,self.resid_tab,1, self.binx,self.biny,'X [pix]', 'Y [pix]', 'X', 'Y', self.subplot_frameON,title_frameON,tooltip_frameON)


        #2D master flat (mflat (slit/ifu))
        #print "mfat check:",  self.edges_tab_found, self.mflat_found
        if self.edges_tab_found == True and self.mflat_found  == True :
             self.plotImageScatter3Col(self.mflat,self.bpm,self.edges_tab,
        2, self.binx, self.biny,'X [pix]', 'Y [pix]', 'CENTER_X', 'CENTER_Y', 'EDG_LO_X', 'CENTER_Y','EDG_UP_X', 'CENTER_Y', self.subplot_mflat,title_mflat,tooltip_mflat)


        #print 'edges_found',self.edges_tab_found,'resid_tab_found',self.resid_tab_found,'rec_id',self.rec_id,'arm_uvb_found',self.arm_uvb_found
        #Scatter plot: set titles and labels
        if self.resid_tab_found == True  and \
          (self.rec_id[4:12] == "predict" or \
           self.rec_id[4:9] == "2dmap") :

           title_resid_x_tab   = 'Line X residuals.' 
           tooltip_resid_x_tab ="""\
                Plot of the line position residuals in X versus wavelength."""

           title_resid_y_tab   = 'Line Y residuals.' 
           tooltip_resid_y_tab ="""\
                 Plot of the line position residuals in Y versus wavelength."""

        elif self.resid_tab_found == True  and \
             self.rec_id[4:13] == "orderpos" :

           title_resid_x_tab   = 'Trace X residuals vs X' 
           tooltip_resid_x_tab ="""\
                                Plot of trace position X residuals versus X."""
           title_resid_y_tab   = 'Trace X residuals vs Y' 
           tooltip_resid_y_tab ="""\
                                Plot of trace position X residuals versus Y."""

        #Scatter plot: make the plot
        if self.resid_tab_found == True  and \
          (self.rec_id[4:12] == "predict" or \
           self.rec_id[4:9] == "2dmap" or \
           self.rec_id[4:13] == "orderpos") :
            if self.rec_id[4:12] == "predict" or self.rec_id[4:9] == "2dmap" :
               #print "resid tab"
               self.plotTableScatter(self.resid_tab,
        'Wavelength','ResidXModel', 'Wavelength [nm]','Line position residuals in X [pix]',self.subplot_resid_x_tab,title_resid_x_tab, tooltip_resid_x_tab)
               self.plotTableScatter(self.resid_tab, 'Wavelength','ResidYModel', 'Wavelength [nm]','Line position residuals in Y [pix]',self.subplot_resid_y_tab,title_resid_y_tab, tooltip_resid_y_tab)
            elif self.rec_id[4:13] == "orderpos" :
               self.plotTableScatter(self.resid_tab, 'X','RESX', 'X Position [pix]','X Residuals [pix]',self.subplot_resid_x_tab,title_resid_x_tab, tooltip_resid_x_tab)
               self.plotTableScatter(self.resid_tab, 'Y','RESX', 'Y Position [pix]','X Residuals [pix]',self.subplot_resid_y_tab,title_resid_y_tab, tooltip_resid_y_tab)
 
      else :
        #Data not found info
        self.subtext_nodata.set_axis_off()
        self.text_nodata = """\
                           ON-frame, Residual table 
                           (PRO.CATG=PREF_ON_ARM,PREF_RESID_ARM, 
                           where PREF=FMTCHK, ORDEF, FLAT, or WAVE, 
                           ARM=UVB,VIS or NIR) not found in the products. 
                           This may be due to a recipe failure. 
                           Check your input parameter values, 
                           correct possibly typos and
                           press 'Re-run recipe' button."""
        self.subtext_nodata.text(0.1, 0.6, self.text_nodata, color='#11557c', 
                                 fontsize=18, ha='left', va='center', alpha=1.0)
        self.subtext_nodata.tooltip="""\
                                    Merged spectrum not found in the products"""
        #print "found no spectrum data"
 
  
    # This function specifies which are the parameters that should be presented
    # in the window to be edited.
    # Note that the parameter has to be also in the in_sop port (otherwise it 
    # won't appear in the window) 
    # The descriptions are used to show a tooltip. They should match one to one
    # with the parameter list 
    # Note also that parameters have to be prefixed by the 'recipe name:'

    def setInteractiveParameters(self):
      paramList = list()
      rec_id=self.rec_id
      self.par = xsh_parameters_common.Parameters()
      self.par.setGeneralCalibParameters(paramList,rec_id)
  
      if rec_id[4:11] == "predict" :
         self.par.setDetectArclinesParameters(paramList,rec_id)
         self.par.setModelParameters(paramList,rec_id)

      elif rec_id[4:12] == "orderpos" :
         self.par.setDetectContinuumParameters(paramList,rec_id)

      elif rec_id[4:9] == "mflat" :
         self.par.setStackParameters(paramList,rec_id)
         self.par.setDetectOrderParameters(paramList,rec_id)
         self.par.setBackgroundParameters(paramList,rec_id)

      elif rec_id[4:9] == "2dmap" :
         self.par.setDetectArclinesParameters(paramList,rec_id)
         self.par.setModelParameters(paramList,rec_id)

      elif rec_id[4:11] == "wavecal" :
         print("found wavecal params")

      elif rec_id[4:12] == "flexcomp" :
         print("found flexcomp params")
      else :
         print("recipe" ,rec_id,  "not supported")

      return paramList

    def setWindowHelp(self):
      help_text = """
This is an interactive window which help asses the quality of the execution of a recipe.
"""
      return help_text

    def setWindowTitle(self):
      title = 'X-shooter Interactive ' + self.rec_subtitle + self.seq_arm + ' Arm. ' 
      return title

except ImportError:
  import_sucess = 'false'
  print("Error importing modules pyfits, wx, matplotlib, numpy")
  raise