File: interactive_window_science_process.py

package info (click to toggle)
cpl-plugin-vimos 4.1.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 28,228 kB
  • sloc: ansic: 169,271; cpp: 16,177; sh: 4,344; python: 3,678; makefile: 1,138; perl: 10
file content (849 lines) | stat: -rw-r--r-- 46,445 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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
from __future__ import with_statement
from __future__ import absolute_import
from __future__ import print_function
import sys


try:
    import numpy
    import reflex
    from pipeline_product import PipelineProduct
    import pipeline_display
    import reflex_plot_widgets

    from matplotlib import gridspec, pylab, pyplot, transforms
    import pdb  # for debugging
    from collections import defaultdict  # to make dictionary of lists
    import_success = True
    
except ImportError:
    import_success = False
    print("Error importing modules pyfits, wx, matplotlib, numpy")

# Median absolute deviation function; used to scale the images
def MAD(x):
    x=numpy.array(x)
    return numpy.median(numpy.abs(x-numpy.median(x)))


def paragraph(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
    if width is None:
        return textwrap.dedent(text).replace('\n', ' ').strip()
    else:
        return textwrap.fill(textwrap.dedent(text), width=width)


class DataPlotterManager(object):
    """
    This class must be added to the PipelineInteractiveApp with setPlotManager
    It must have following member functions which will be called by the app:
     - setInteractiveParameters(self)
     - readFitsData(self, fitsFiles):
     - addSubplots(self, figure):
     - plotProductsGraphics(self, figure, canvas)
    Following members are optional:
     - setWindowHelp(self)
     - setWindowTitle(self)
    """

    # static members
    
    recipe_name = "vimos_ima_science"
    img_cat = "BASIC_CALIBRATED_SCI" # individual calibrated frames 
    stk_cat = "JITTERED_IMAGE_SCI"  #  stacked image

    mstd_a_cat = "MATCHSTD_ASTROM"
    mstd_p_cat = "MATCHSTD_PHOTOM"
    std_zpoint = "OBJECT_CATALOGUE_STD"


    def setWindowTitle(self):
        return self.recipe_name+"_interactive"

    def setInteractiveParameters(self):
        """
        This function specifies which are the parameters that should be presented
        in the window to be edited.  Note that the parameter has to also be 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.
        """

        # Show all recipe params 
        # Only selected Recipe parameters are shown because list is too long
        # The selection shown ones likely to be wanted to be changed by user

        return [
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="savecat",
                                   group="vimos_ima_science", description="Save catalogue?. [FALSE]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="savemstd",
                                   group="vimos_ima_science", description="Save matched standard catalogues?. [FALSE]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="minphotom",
                                   group="vimos_ima_science", description="Minimum stars for photometry solution. [1]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="chop_crud",
                                   group="vimos_ima_science", description="Chop crud method. <none | lowconf_block | hardcoded | lowconf_pix | hardconf_pix> [hardconf_pix]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="cdssearch_astrom",
                                   group="vimos_ima_science", description="CDS astrometric catalogue. <none | 2mass | usnob | ppmxl | wise> [none]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="cdssearch_photom",
                                   group="vimos_ima_science", description="CDS photometric catalogue. <none | apass > [none]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="ignore_fringe",
                                   group="vimos_ima_science", 
                                   description="Ignore provided fringe frame?. [FALSE]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_cat_ipix",
                                   group="vimos_ima_science2", description="Minimum pixel area for each detected object. [10]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_cat_thresh",
                                   group="vimos_ima_science2", description="Detection threshold in sigma above sky. [1.5]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_cat_icrowd",
                                   group="vimos_ima_science2", description="Use deblending?. [TRUE]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_cat_rcore",
                                   group="vimos_ima_science2", description="Value of Rcore in pixels. [10.0]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_cat_nbsize",
                                   group="vimos_ima_science2", description="Background smoothing box size. [128]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_lthr",
                                   group="vimos_ima_science2", description="Low rejection threshold. [3.0]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_hthr",
                                   group="vimos_ima_science2", description="Upper rejection threshold. [3.0]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_method",
                                   group="vimos_ima_science2", description="Stacking method. <nearest | linear> [linear]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_seeing",
                                   group="vimos_ima_science2", description="Weight by seeing?. [FALSE]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_fast",
                                   group="vimos_ima_science2", description="Stack using fast algorithm?. <fast | slow | auto> [auto]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="stk_nfst",
                                   group="vimos_ima_science2", description="Nframes to stack in fast mode. [16]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="cacheloc",
                                   group="vimos_ima_science2", 
                                   description="Location for standard star cache [.]"),
            reflex.RecipeParameter(recipe=self.recipe_name, displayName="magerrcut",
                                   group="vimos_ima_science2", 
                                   description="Magnitude error cut [100.0]")
            ]

    def readFitsData(self, fitsFiles):
        """
        This function should be used to read and organize the raw fits files
        produced by the recipes.
        It receives as input a list of reflex.FitsFiles
        """

        # frames is a dict of keyword/list pairs where elements of list are PipelineProducts
        #  it contains all FITS files in the input parameter list

        self.sci_frames = defaultdict(list)
        self.stk_frames = defaultdict(list)

        for f in fitsFiles:
            if (f.category == self.img_cat):
                self.sci_frames[self.img_cat].append(PipelineProduct(f))
            if (f.category == self.mstd_a_cat):
                if ('IMATYPE' in PipelineProduct(f).all_hdu[0].header) and (PipelineProduct(f).all_hdu[0].header['IMATYPE'] == 'PAWPRINT'):
                    # If IMATYPE is equal 'PAWPRINT' then it is an stacked image
                    # note we are not doing the association here because the list can have any order
                    self.stk_frames[self.mstd_a_cat].append(PipelineProduct(f))
                else : 
                    # We assume that if IMATYPE is not present or it is present but is not PAWPRINT then it is an individual image
                    self.sci_frames[self.mstd_a_cat].append(PipelineProduct(f))
            if (f.category == self.stk_cat):
                self.stk_frames[self.stk_cat].append(PipelineProduct(f))
            if (f.category == self.mstd_p_cat):
                self.stk_frames[self.mstd_p_cat].append(PipelineProduct(f))
            if (f.category == self.std_zpoint):
                self.stk_frames[self.std_zpoint].append(PipelineProduct(f))

        # There's no need to sort the stk_frames because there should only be one catalogue for
        #   astrom, one for photom
        if (len(self.sci_frames[self.img_cat])) > 0:

            self.sci_img_found = True
            self.n_sci_frames = len(self.sci_frames[self.img_cat])
            self.cur_sci_frame = 0
            self.n_extn = len(self.sci_frames[self.img_cat][0].hdulist())-1  # number of extensions, assumed to be same for all fitsFiles

            # Don't read the individual calibrated science images in here 
            #   for memory/performance reasons. Read them in below as needed.
            #   There could be a lot of frames and user may not want to see all of them.

            if (len(self.sci_frames[self.mstd_a_cat])) > 0:
                self.sci_mstd_found = True

                if (len(self.sci_frames[self.img_cat]) != len(self.sci_frames[self.mstd_a_cat])):
                    raise RuntimeError("Number of science images != number of matched astrometric standard catalogues!")

                # Sort the sci frames and sci mstd_a frames using PIPEFILE keyword
                # This will implicitly associate the sci frames with the mstd frames by using indices
                #   e.g. the mstd astrom cat for self.sci_frames[self.img_cat][0] ("exp_1.fits") 
                #         is self.sci_frames[self.mstd_a_cat][0] ("exp_mstd_a0.fits")
            
                self.sci_frames[self.img_cat].sort(key=lambda foo: foo.all_hdu[0].header['PIPEFILE'])
                self.sci_frames[self.mstd_a_cat].sort(key=lambda foo: foo.all_hdu[0].header['PIPEFILE'])

                # Read in FITS binary data like this:
                # table = self.sci_frames[self.mstd_a_cat][i].all_hdu[i_ext+1].data
                # But do it only as needed
            else:
                self.sci_mstd_found = False


            self.stk_img_found = []  # a list of bools that indicates if image extension is present
            if (len(self.stk_frames[self.stk_cat])) > 0:

                if (len(self.stk_frames[self.stk_cat])) != 1:
                    raise RuntimeError("Error: Recipe produced more than one stacked image!")
                
                self.stk_name = self.stk_frames[self.stk_cat][0].fits_file.name
                self.stk_hdu = self.stk_frames[self.stk_cat][0].all_hdu
                self.stk_images = []

                for i in range(self.n_extn):
                    try:
                        self.stk_frames[self.stk_cat][0].readImage(i+1)
                        self.stk_images.append(self.stk_frames[self.stk_cat][0].image) 
                        self.stk_img_found.append(True)
                    except IndexError:
                        self.stk_img_found.append(False)
            else:
                self.stk_img_found = [False]*self.n_extn

            # re-define eso-rex's pipeline_display plotting functions to enable callbacks
            self._add_subplots = self._add_subplots
            self._plot = self._data_plot

            # Define radio button options
            self.left_opts = {'SCI frames':0,'Stacked frame':1} 
            self.mid_opts = {'Image':0,'Assess matched astrom stds':1,
                             'Histogram of matched astrom stds':2,
                             'Assess matched photom stds':3,
                             'Histogram of matched photom stds':4}

            self.right_opts = {"Click to\nadvance to\nnext item\n(if available)"}

            # Set the initial radio button selections (value 1 for left, 0 for mid)
            self.left_label = [key for key, value in iter(self.left_opts.items()) if value == 1][0]
            self.mid_label = [key for key, value in iter(self.mid_opts.items()) if value == 0][0]

        else:
            # Set the plotting functions to NODATA ones
            self._add_subplots = self._add_nodata_subplots
            self._plot = self._nodata_plot

    def addSubplots(self, figure):
        self._add_subplots(figure)

    def plotProductsGraphics(self):
        self._plot()

    def plotWidgets(self) :
        widgets = list()

        # Radio buttons 
        # Only show them if at least one sci frame and a stack is found
        if ((self.sci_img_found is True) and (True in self.stk_img_found)):
            # pull out the keys from the dict() of button options sorted by value
            left_labels = [key for key,value in sorted(self.left_opts.items(),key= lambda k: k[1])]
            self.radiobutton_left = reflex_plot_widgets.InteractiveRadioButtons(self.axradiobutton_left, 
                                                                                self.setRadioCallback_left, 
                                                                                left_labels,
                                                                                self.left_opts.get(self.left_label), 
                                                                                title='Select group:')
            widgets.append(self.radiobutton_left)

            # pull out the keys from the dict() of button options sorted by value
            mid_labels = [key for key,value in sorted(self.mid_opts.items(),key= lambda k: k[1])]
            self.radiobutton_mid = reflex_plot_widgets.InteractiveRadioButtons(self.axradiobutton_mid, 
                                                                               self.setRadioCallback_mid, 
                                                                               mid_labels,
                                                                               self.mid_opts.get(self.mid_label), 
                                                                               title='Select item in group :')
            widgets.append(self.radiobutton_mid)

            self.radiobutton_right = reflex_plot_widgets.InteractiveRadioButtons(self.axradiobutton_right, 
                                                                                 self.setRadioCallback_right, 
                                                                                 self.right_opts,
                                                                                 0, title='')
            widgets.append(self.radiobutton_right)

            # Adjust size of button boxes and font size of labels
            for i in range(len(widgets)):
                pos = widgets[i].rbuttons.ax.get_position()
                widgets[i].rbuttons.ax.set_position(transforms.Bbox([[pos.x0,pos.y0-0.01],[pos.x1, 0.97]]  ) )
                for j in range(len(widgets[i].rbuttons.labels)):
                    widgets[i].rbuttons.labels[j].set_fontsize(11)

        return widgets

    def setRadioCallback_left(self, label) :

        # Only do something if user changes the button
        if (label != self.left_label):
            self.left_label = label
            self._plot()

    def setRadioCallback_mid(self, label) :

        # Only do something if user changes the button
        if (label != self.mid_label):
            self.mid_label = label
            self._plot()

    def setRadioCallback_right(self, label) :

        # advance (or wrap) frame number if we are looking at science frames
        if (self.left_opts[self.left_label] == 0):
            self.cur_sci_frame += 1
            if (self.cur_sci_frame == (self.n_sci_frames)):
                self.cur_sci_frame = 0
        
        self._plot()

    def _add_subplots(self, figure):
      
        self.img_plot = []
        self.mstd_plot = []
        if ((self.sci_img_found is True) and (True in self.stk_img_found)):  # at least one sci and stk img found
            gs = gridspec.GridSpec(9, 4)
            gs.update(hspace=0.7)  # make space so axis labels dont overlap
            self.axradiobutton_left = figure.add_subplot(gs[0,0])
            self.axradiobutton_mid = figure.add_subplot(gs[0,1:3])
            self.axradiobutton_right = figure.add_subplot(gs[0,3])

            self.img_plot.append(figure.add_subplot(gs[1:5,0:2]))
            self.img_plot.append(figure.add_subplot(gs[1:5,2:4]))
            self.img_plot.append(figure.add_subplot(gs[5:9,2:4]))
            self.img_plot.append(figure.add_subplot(gs[5:9,0:2]))

            # Move ticks to rhs for readability
            self.img_plot[1].yaxis.tick_right()
            self.img_plot[2].yaxis.tick_right()

            self.mstd_plot.append(figure.add_subplot(gs[1:3,0:2]))
            self.mstd_plot.append(figure.add_subplot(gs[3:5,0:2]))
            self.mstd_plot.append(figure.add_subplot(gs[1:3,2:4]))
            self.mstd_plot.append(figure.add_subplot(gs[3:5,2:4]))
            self.mstd_plot.append(figure.add_subplot(gs[5:7,2:4]))
            self.mstd_plot.append(figure.add_subplot(gs[7:9,2:4]))
            self.mstd_plot.append(figure.add_subplot(gs[5:7,0:2]))
            self.mstd_plot.append(figure.add_subplot(gs[7:9,0:2]))

            # Move ticks to rhs for readability
            self.mstd_plot[2].yaxis.tick_right()
            self.mstd_plot[3].yaxis.tick_right()
            self.mstd_plot[4].yaxis.tick_right()
            self.mstd_plot[5].yaxis.tick_right()

            # Keep track if subplots have been repositioned
            self.mstd_repositioned = [False]*8
                                    
            # Initially, turn off tick labels for scatterplots
            for i in range(len(self.mstd_plot)):
                pylab.setp(self.mstd_plot[i].get_xticklabels(), visible = False)
                pylab.setp(self.mstd_plot[i].get_yticklabels(), visible = False)
                    
        else:
            gs = gridspec.GridSpec(2, 2)
            self.img_plot.append(figure.add_subplot(gs[0,0]))
            self.img_plot.append(figure.add_subplot(gs[0,1]))
            self.img_plot.append(figure.add_subplot(gs[1,0]))
            self.img_plot.append(figure.add_subplot(gs[1,1]))
            
    def _data_plot(self):


        for i in range(self.n_extn):

            # Get filter name from first extension of the stack and assume its same for all other products
            # If there is no stack, filt_name will be empty string
            try:
                for i_filt in range(1,4):
                    key1 = 'HIERARCH ESO INS FILT{} NAME'.format(i_filt)
                    if key1 in self.stk_hdu[1].header:
                        filt_name = self.stk_hdu[1].header.get(key1)
                    key2 = 'FILTER{}'.format(i_filt)  # alternate header keyword
                    if key2 in self.stk_hdu[1].header:
                        filt_name = self.stk_hdu[1].header.get(key2)
            except:
                filt_name = ''

            if (self.mid_opts[self.mid_label] == 0):  # show an image
                
                # turn off scatterplot axes visibility
                self.mstd_plot[2*i].cla()
                self.mstd_plot[2*i+1].cla()
                self.mstd_plot[2*i].tooltip = ''
                self.mstd_plot[2*i+1].tooltip = ''
                self.mstd_plot[2*i].set_visible(False)
                self.mstd_plot[2*i+1].set_visible(False)

                # clear image frame and make it visible
                self.img_plot[i].cla()  
                self.img_plot[i].tooltip = ''  
                self.img_plot[i].set_visible(True)  
                for j in range(len(self.img_plot)):
                    if (j==0 or j == 1):
                        self.img_plot[j].set_xlabel(' ')
                    if (j==1 or j == 2):
                        self.img_plot[j].set_ylabel(' ')
                    pylab.setp(self.img_plot[j].get_xticklabels(), visible = True)
                    pylab.setp(self.img_plot[j].get_yticklabels(), visible = True)

                # Setup the selected image and display it
                imgdisp = pipeline_display.ImageDisplay()
                imgdisp.setAspect('equal')
                imgdisp.setLabels('X', 'Y')
                
                if (self.left_opts[self.left_label] == 1):  # show the stack

                    chip_name = self.stk_hdu[i+1].header['EXTNAME']
                    title = "Stacked Image {} {}".format(filt_name,chip_name)
                    if (self.stk_img_found):
                        imgdisp.display(self.img_plot[i], title, "Stacked Image:\n"+self.stk_name, self.stk_images[i])
                    else:
                        self.img_plot[i].set_axis_off()
                        text_nodata = "No stacked image found\n for this chip/extension."
                        self.img_plot[i].text(0.1, 0.5, text_nodata, color='#11557c',
                                              fontsize=12, ha='left', va='center', alpha=1.0,
                                              transform = self.img_plot[i].transAxes)
                        self.img_plot[i].tooltip = 'No data found'

                elif (self.left_opts[self.left_label] == 0):  # show an individual sci frame

                    chip_name = self.sci_frames[self.img_cat][self.cur_sci_frame].all_hdu[i+1].header['EXTNAME']
                    title = "Cal. Sci Frame {} {}/{} {}".format(filt_name, self.cur_sci_frame+1,self.n_sci_frames,chip_name)
                    # Try reading image
                    try:
                        temp = self.sci_frames[self.img_cat][self.cur_sci_frame]
                        temp.readImage(i+1)
                        imgdisp.display(self.img_plot[i], title, "Calibrated Science Frame:\n" + 
                                        temp.fits_file.name, temp.image)
                    except IndexError:
                        self.img_plot[i].set_axis_off()
                        text_nodata = "No science image found\n for this chip/extension."
                        self.img_plot[i].text(0.1, 0.5, text_nodata, color='#11557c',
                                              fontsize=18, ha='left', va='center', alpha=1.0,
                                              transform = self.img_plot[i].transAxes)
                        self.img_plot[i].tooltip = 'No data found'
                        continue  # go to next extension

            elif ((self.mid_opts[self.mid_label] == 1) or 
                  (self.mid_opts[self.mid_label] == 2)):    # show matched astrom stds

                # If this is first request for mstd astrom, 
                #   reposition the subplots so that axes touch and we have more room
                # We have to do it here because windows aren't rendered inside the _add_subplots function
                if (self.mstd_repositioned[2*i] == False):
                    pos = self.mstd_plot[2*i].get_position()
                    pos_new = [pos.x0, pos.y0-0.1*pos.height, pos.width, pos.height]
                    self.mstd_plot[2*i].set_position(pos_new)
                    self.mstd_repositioned[2*i] = True
                if (self.mstd_repositioned[2*i+1] == False):
                    pos = self.mstd_plot[2*i+1].get_position()
                    pos_new = [pos.x0, pos.y0+0.1*pos.height, pos.width, pos.height]
                    self.mstd_plot[2*i+1].set_position(pos_new)
                    self.mstd_repositioned[2*i+1] = True

                self.img_plot[i].cla()  
                self.img_plot[i].tooltip=''
                self.img_plot[i].set_visible(False)  

                # Turn on scatterplot axes 
                self.mstd_plot[2*i].cla()
                self.mstd_plot[2*i+1].cla()
                self.mstd_plot[2*i].tooltip=''
                self.mstd_plot[2*i+1].tooltip=''
                self.mstd_plot[2*i].set_visible(True)
                self.mstd_plot[2*i+1].set_visible(True)
                for j in range(len(self.mstd_plot)):
                    if (j%2 == 1):
                        pylab.setp(self.mstd_plot[j].get_xticklabels(), visible = True)
                    else:
                        pylab.setp(self.mstd_plot[j].get_xticklabels(), visible = False)
                    pylab.setp(self.mstd_plot[j].get_yticklabels(), visible = True)

                # Define xtitle
                if ((self.mid_opts[self.mid_label]==1) and ((i == 2) or (i == 3))) :
                    xtitle = "Row number of matched standard"
                else:
                    xtitle = " "

                if (self.left_opts[self.left_label] == 0):  # show catalog associated with sci frame

                    chip_name = self.sci_frames[self.img_cat][self.cur_sci_frame].all_hdu[i+1].header['EXTNAME']
                    title = "Cal. Sci Frame {} {}/{} {}".format(filt_name,self.cur_sci_frame+1,self.n_sci_frames,chip_name)
                    try:
                        table = self.sci_frames[self.mstd_a_cat][self.cur_sci_frame].all_hdu[i+1].data
                        filename = self.sci_frames[self.mstd_a_cat][self.cur_sci_frame].fits_file.name
                    except IndexError:
                        text_nodata = "No matched astrom\nstandard catalog found\nfor this chip/extension."
                        for k in range(2):
                            self.mstd_plot[2*i+k].text(0.1, 0.5, text_nodata, color='#11557c',
                                                       fontsize=12, ha='left', va='center', alpha=1.0,
                                                       transform = self.mstd_plot[2*i+k].transAxes)
                            self.mstd_plot[2*i+k].tooltip = 'No data found'
                            self.mstd_plot[2*i+k].set_xlabel(xtitle)
                        continue # go to next extension

                    # Check to make sure there is at least one row
                    if (self.sci_frames[self.mstd_a_cat][self.cur_sci_frame].all_hdu[i+1].header['NAXIS2'] == 0):
                        text_nodata = "No valid matched astrom\nstandard catalog\nfound for this chip."
                        for k in range(2):
                            #self.mstd_plot[2*i+k].set_axis_off()
                            self.mstd_plot[2*i+k].text(0.1, 0.5, text_nodata, color='#11557c',
                                                       fontsize=12, ha='left', va='center', alpha=1.0,
                                                       transform=self.mstd_plot[2*i+k].transAxes)
                            self.mstd_plot[2*i+k].tooltip = 'No data found'
                            self.mstd_plot[2*i+k].set_xlabel(xtitle)
                        continue # go to next extension

                elif (self.left_opts[self.left_label] == 1):  # show catalog asocated with the stack

                    chip_name = self.stk_hdu[i+1].header['EXTNAME']
                    title = "Stacked Image {} {}".format(filt_name,chip_name)
                    try:
                        table = self.stk_frames[self.mstd_a_cat][0].all_hdu[i+1].data
                        filename = self.stk_frames[self.mstd_a_cat][0].fits_file.name
                    except IndexError:
                        text_nodata = "No valid matched astrom\nstandard catalog\nfound for this chip."
                        for k in range(2):
                            #self.mstd_plot[2*i+k].set_axis_off()
                            self.mstd_plot[2*i+k].text(0.1, 0.5, text_nodata, color='#11557c',
                                                       fontsize=12, ha='left', va='center', alpha=1.0,
                                                       transform=self.mstd_plot[2*i+k].transAxes)
                            self.mstd_plot[2*i+k].tooltip = 'No data found'
                            self.mstd_plot[2*i+k].set_xlabel(xtitle)
                        continue # go to next extension

                    # Check to make sure there is at least one row
                    if (self.stk_frames[self.mstd_a_cat][0].all_hdu[i+1].header['NAXIS2'] == 0):
                        text_nodata = "No valid matched astrom\nstandard catalog\nfound for this chip."
                        for k in range(2):
                            self.mstd_plot[2*i+k].text(0.1, 0.5, text_nodata, color='#11557c',
                                                       fontsize=12, ha='left', va='center', alpha=1.0,
                                                       transform=self.mstd_plot[2*i+k].transAxes)
                            self.mstd_plot[2*i+k].tooltip = 'No data found'
                            self.mstd_plot[2*i+k].set_xlabel(xtitle)
                        continue # go to next extension

                # Show scatter plot
                if (self.mid_opts[self.mid_label]==1):

                    # Configure and display top plot of delta RA, if the column exists
                    #  (if WCS fitting fails, then column is missing)
                    try:
                        x_top = numpy.linspace(1,len(table['diffRA']), num = len(table['diffRA']))
                        y_top = numpy.cos(table['Dec']*numpy.pi/180.0)*table['diffRA'] * 3600.0 # in arcseconds
                    except KeyError:
                        text_nodata = "No valid matched astrom\nstandard catalog\nfound for this chip."
                        self.mstd_plot[2*i].text(0.1, 0.5, text_nodata, color='#11557c',
                                                 fontsize=12, ha='left', va='center', alpha=1.0,
                                                 transform=self.mstd_plot[2*i+k].transAxes)
                        self.mstd_plot[2*i].tooltip = 'No data found'
                        self.mstd_plot[2*i].set_xlabel(xtitle)
                        continue # go to next extension

                    err_top = 0.0 * y_top
                
                    scat_top = pipeline_display.ScatterDisplay()
                    delta_x = max(x_top) - min(x_top)
                    scat_top.xLim = min(x_top)-0.11*delta_x, max(x_top)+0.11*delta_x
                    delta_y = max(y_top) - min(y_top)
                    scat_top.yLim = min(y_top)-0.11*delta_y, max(y_top)+0.11*delta_y
                    y_max = max([max(y_top),abs(min(y_top))])
                    if y_max > 1.0 : 
                        tool_tip = " WARNING: Difference in coord is > 1.0 arcsec!\n"
                    else:
                        scat_top.yLim = -1.1,1.1
                        tool_tip = "Matched astrometric standard catalogue:\n"
                    
                    scat_top.setLabels(" ",r'$\Delta\alpha*cos(\delta)$ ["]')
                    scat_top.display(self.mstd_plot[2*i],
                                     title, tool_tip + filename, 
                                     x_top, y_top, err_top)

                    # Configure and display top plot of delta Dec, if the column exists
                    #  (if WCS fitting fails, then column is missing)
                    try:
                        x_bot = numpy.linspace(1,len(table['diffDec']), num = len(table['diffDec']))
                        y_bot = table['diffDec'] * 3600.0 # in arcseconds
                    except KeyError:
                        text_nodata = "No valid matched astrom\nstandard catalog found\nfor this chip."
                        self.mstd_plot[2*i+1].text(0.1, 0.5, text_nodata, color='#11557c',
                                                   fontsize=12, ha='left', va='center', alpha=1.0,
                                                   transform=self.mstd_plot[2*i+k].transAxes)
                        self.mstd_plot[2*i+1].tooltip = 'No data found'
                        self.mstd_plot[2*i+1].set_xlabel(xtitle)
                        continue # go to next extension

                    err_bot = 0.0 * y_bot

                    scat_bot = pipeline_display.ScatterDisplay()
                    scat_bot.xLim = scat_top.xLim
                    delta_y = max(y_bot) - min(y_bot)
                    scat_bot.yLim = min(y_bot)-0.11*delta_y, max(y_bot)+0.11*delta_y
                    y_max = max([max(y_bot),abs(min(y_bot))])
                    if y_max > 1.0 : 
                        tool_tip = " WARNING: Difference in coord is > 1.0 arcsec! \n"
                    else:
                        scat_bot.yLim = -1.1,1.1
                        tool_tip = "Matched astrometric standard catalogue:\n"
                        
                    scat_bot.setLabels(xtitle,r'$\Delta\delta$ ["]')
                    scat_bot.display(self.mstd_plot[2*i+1],
                                     " ", tool_tip + filename, 
                                     x_bot, y_bot, err_bot)
                # Show histogram
                if (self.mid_opts[self.mid_label]==2):

                    self.mstd_plot[2*i].cla()
                    self.mstd_plot[2*i+1].cla()
                    self.mstd_plot[2*i].tooltip=''
                    self.mstd_plot[2*i+1].tooltip=''
                    self.mstd_plot[2*i].set_visible(False)
                    self.mstd_plot[2*i+1].set_visible(False)
                        
                    self.img_plot[i].cla()  
                    self.img_plot[i].tooltip = ''
                    self.img_plot[i].set_visible(True)  
                    for j in range(len(self.img_plot)):
                        pylab.setp(self.img_plot[j].get_xticklabels(), visible = True)
                        pylab.setp(self.img_plot[j].get_yticklabels(), visible = True)

                    try:
                        delta_dec = table['diffDec'] * 3600.0 # in arcseconds
                        delta_ra = numpy.cos(table['Dec']*numpy.pi/180.0)*table['diffRA'] * 3600.0 # in arcseconds
                    except KeyError:
                        text_nodata = "No valid matched astrom standard\ncatalog found for this chip."
                        for k in range(2):
                            self.mstd_plot[2*i+k].text(0.1, 0.5, text_nodata, color='#11557c',
                                                       fontsize=12, ha='left', va='center', alpha=1.0,
                                                       transform=self.mstd_plot[2*i+k].transAxes)
                            self.mstd_plot[2*i+k].tooltip = 'No data found'
                            self.mstd_plot[2*i+k].set_xlabel(xtitle)
                        continue # go to next extension

                    # some entries are NaN if reference catalog doesnt have valid coords
                    delta_ra_valid = delta_ra[(numpy.isfinite(delta_ra) & numpy.isfinite(delta_dec))]
                    delta_dec_valid = delta_dec[(numpy.isfinite(delta_ra) & numpy.isfinite(delta_dec))]

                    r = numpy.sqrt(delta_ra_valid**2 + delta_dec_valid**2)

                    med = numpy.median(r)
                    mad = MAD(r)
                    n, bins, patches = self.img_plot[i].hist(r)
                    self.img_plot[i].axis('tight')

                    if ((i ==0) or (i == 1)):
                        self.img_plot[i].set_xlabel('')
                    elif ((i == 2) or (i == 3)):
                        self.img_plot[i].set_xlabel(r'$\Delta\Theta=$'+r'$\sqrt{[cos(\delta)*\Delta\alpha]^2 + \Delta\delta^2}$'+' ["]')

                    self.img_plot[i].set_ylabel('Frequency')
                    self.img_plot[i].set_title(title,fontweight='semibold', fontsize=12)
                    self.img_plot[i].tooltip = "Histogram with 10 bins over entire data range\nNumbers in legend are for whole data sample"
                    self.img_plot[i].text(0.65,0.9,'Med:  {:8.2f}'.format(med), 
                                          transform=self.img_plot[i].transAxes,color='red')
                    self.img_plot[i].text(0.65,0.8,'Mean: {:8.2f}'.format(numpy.mean(r)), 
                                          transform=self.img_plot[i].transAxes,color='red')
                    self.img_plot[i].text(0.65,0.7,'MAD:  {:8.2f}'.format(mad), 
                                          transform=self.img_plot[i].transAxes,color='red')
                    self.img_plot[i].text(0.65,0.6,'RMS:  {:8.2f}'.format(numpy.std(r)), 
                                          transform=self.img_plot[i].transAxes,color='red')

            elif ((self.mid_opts[self.mid_label] == 3) or 
                  (self.mid_opts[self.mid_label] == 4)):    # show matched photom stds

                # Common text that is reused
                text_nodata_novalid = "No valid matched photom\nstandard ncatalog\nfound for this chip."
                text_nodata_zpointused = "STD star zeropoint used\nto calibrate science frame"

                # Whether the STD zpoint has been used
                std_zpoint_used = self.std_zpoint in self.stk_frames

                # there is just one scatter plot per chip, so use img_plot subplot

                self.mstd_plot[2*i].cla()
                self.mstd_plot[2*i+1].cla()
                self.mstd_plot[2*i].tooltip=''
                self.mstd_plot[2*i+1].tooltip=''
                self.mstd_plot[2*i].set_visible(False)
                self.mstd_plot[2*i+1].set_visible(False)

                self.img_plot[i].cla()  
                self.img_plot[i].tooltip=''
                self.img_plot[i].set_visible(True)  
                self.img_plot[i].axis('auto')
                for j in range(len(self.img_plot)):
                    pylab.setp(self.img_plot[j].get_xticklabels(), visible = True)
                    pylab.setp(self.img_plot[j].get_yticklabels(), visible = True)

                # Define xtitle
                if ((self.mid_opts[self.mid_label]==3) and ((i == 2) or (i == 3))) :
                    xtitle = "Row number of matched standard"
                else:
                    xtitle = " "

                if (self.left_opts[self.left_label] == 0):  # sci frame

                    # The recipe never creates a mstd photom for sci frames
                    text_nodata = "No matched photom standard\ncatalogues are created\nfor single science frames."
                    self.img_plot[i].text(0.1, 0.5, text_nodata, color='#11557c',
                                          fontsize=12, ha='left', va='center', alpha=1.0,
                                          transform = self.img_plot[i].transAxes)
                    self.img_plot[i].tooltip = 'No data found'
                    continue # go to next extension

                elif (self.left_opts[self.left_label] == 1):  # stk frame

                    chip_name = self.stk_hdu[i+1].header['EXTNAME']
                    title = "Stacked Image {} {}".format(filt_name,chip_name)
                    try:
                        table = self.stk_frames[self.mstd_p_cat][0].all_hdu[i+1].data
                        filename = self.stk_frames[self.mstd_p_cat][0].fits_file.name
                    except IndexError:
                        if std_zpoint_used:
                            text_nodata = text_nodata_zpointused
                        else:
                            text_nodata = text_nodata_novalid
                        self.img_plot[i].text(0.1, 0.5, text_nodata, color='#11557c',
                                              fontsize=12, ha='left', va='center', alpha=1.0,
                                              transform=self.img_plot[i].transAxes)
                        self.img_plot[i].tooltip = 'No data found'
                        self.img_plot[i].set_xlabel(xtitle)
                        continue # go to next extension

                    # Check to make sure there is at least one row in table
                    if (self.stk_frames[self.mstd_p_cat][0].all_hdu[i+1].header['NAXIS2'] == 0):
                        if std_zpoint_used:
                            text_nodata = text_nodata_zpointused
                        else:
                            text_nodata = text_nodata_novalid
                        self.img_plot[i].text(0.1, 0.5, text_nodata, color='#11557c',
                                              fontsize=12, ha='left', va='center', alpha=1.0,
                                              transform=self.img_plot[i].transAxes)
                        self.img_plot[i].tooltip = 'No data found'
                        self.img_plot[i].set_xlabel(xtitle)
                        continue
                
                # Show scatter plot
                if (self.mid_opts[self.mid_label]==3):
                    try:
                        x = numpy.linspace(1,len(table['dm5']), num = len(table['dm5']))
                        y = table['dm5']  # difference in magnitudes (measured - reference), use aper5
                    except KeyError:
                        if std_zpoint_used:
                            text_nodata = text_nodata_zpointused
                        else:
                            text_nodata = text_nodata_novalid
                        self.img_plot[i].text(0.1, 0.5, text_nodata, color='#11557c',
                                              fontsize=12, ha='left', va='center', alpha=1.0,
                                              transform=self.img_plot[i].transAxes)
                        self.img_plot[i].tooltip = 'No data found'
                        self.img_plot[i].set_xlabel(xtitle)
                        continue
                    
                    err = 0.0 * y
                
                    tool_tip = "Matched photometric standards catalogue:\n"
                    delta_x = max(x) - min(x)
                    scat.xLim = min(x)-0.11*delta_x, max(x)+0.11*delta_x

                    delta_y = max(y[numpy.isfinite(y)]) - min(y[numpy.isfinite(y)])
                    scat.yLim = min(y[numpy.isfinite(y)])-0.11*delta_y, max(y[numpy.isfinite(y)])+0.11*delta_y
                    
                    scat.setLabels(xtitle,'Magnitude zero point')
                    scat.display(self.img_plot[i],
                                 title, tool_tip + filename, 
                                 x, y, err)

                # Show histogram plot of non-NaN mag zpt entries in table
                elif (self.mid_opts[self.mid_label]==4):
                    try:
                        x = table['dm5']  # difference in magnitudes (measured - reference), use aper5
                    except KeyError:
                        if std_zpoint_used:
                            text_nodata = text_nodata_zpointused
                        else:
                            text_nodata = text_nodata_novalid
                        self.img_plot[i].text(0.1, 0.5, text_nodata, color='#11557c',
                                              fontsize=12, ha='left', va='center', alpha=1.0,
                                              transform=self.img_plot[i].transAxes)
                        self.img_plot[i].tooltip = 'No data found'
                        self.img_plot[i].set_xlabel(xtitle)
                        continue
                    
                    # some entries are NaN if reference catalog doesnt have mag in the same band as data being reduced
                    x = x[numpy.isfinite(x)]  
                    med = numpy.median(x)
                    mad = MAD(x)
                    n, bins, patches = self.img_plot[i].hist(x)
                    self.img_plot[i].axis('tight')

                    if ((i ==0) or (i == 1)):
                        self.img_plot[i].set_xlabel('')
                    elif ((i == 2) or (i == 3)):
                        self.img_plot[i].set_xlabel('MagZPT [mag]')

                    self.img_plot[i].set_ylabel('Frequency')
                    self.img_plot[i].tooltip = "Histogram with 10 bins over entire data range\nNumbers in legend are for whole data sample"
                    self.img_plot[i].set_title(title,fontweight='semibold', fontsize=12)
                    self.img_plot[i].text(0.05,0.9,'Med:  {:8.2f}'.format(med), 
                                          transform=self.img_plot[i].transAxes,color='red')
                    self.img_plot[i].text(0.05,0.8,'Mean: {:8.2f}'.format(numpy.mean(x)), 
                                          transform=self.img_plot[i].transAxes,color='red')
                    self.img_plot[i].text(0.05,0.7,'MAD:  {:8.2f}'.format(mad), 
                                          transform=self.img_plot[i].transAxes,color='red')
                    self.img_plot[i].text(0.05,0.6,'RMS:  {:8.2f}'.format(numpy.std(x)), 
                                          transform=self.img_plot[i].transAxes,color='red')

    def _add_nodata_subplots(self, figure):
        self.img_plot = figure.add_subplot(1,1,1)

    def _nodata_plot(self):
        # could be moved to reflex library?
        self.img_plot.set_axis_off()
        text_nodata = "Data not found. Input files should contain this" \
                       " type:\n%s" % self.img_cat
        self.img_plot.text(0.1, 0.6, text_nodata, color='#11557c',
                      fontsize=18, ha='left', va='center', alpha=1.0)
        self.img_plot.tooltip = 'No data found'


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


#This is the 'main' function
if __name__ == '__main__':
    from reflex_interactive_app import PipelineInteractiveApp

    # Create interactive application
    interactive_app = PipelineInteractiveApp()

    # get inputs from the command line
    interactive_app.parse_args()

    #Check if import failed or not
    if not import_success:
        interactive_app.setEnableGUI(False)

    #Open the interactive window if enabled
    if interactive_app.isGUIEnabled():
        #Get the specific functions for this window
        dataPlotManager = DataPlotterManager()

        interactive_app.setPlotManager(dataPlotManager)
        interactive_app.showGUI()
    else:
        interactive_app.set_continue_mode()

    #Print outputs. This is parsed by the Reflex python actor to
    #get the results. Do not remove
    interactive_app.print_outputs()
    sys.exit()