Example #1
0
 def reset(self, event):
     for slider in fx.fnsliders:
         slider.reset()
         
     params = [slider.val for slider in fx.fnsliders] 
 
     cp.curveM2.set_ydata(M2(freqs, *params))
Example #2
0
 def pre(self, event):
     global l
 
     if cp.plot_vers == 2:
         self.ax3.remove()
         if haveParam:
             for button in self.axbutton:
                 button.remove()
             self.axslider.remove()
             self.axauto.remove()
             self.mask_text.remove()
             self.slid_mask_text.remove()
         #fx.visual()
         self.ax2setup()
     
     if cp.plot_vers == 3:    
         self.ax4.remove()
         self.cbar2.remove()
         self.axslider2.remove()
         if haveParam:
             for button in self.axbutton:
                 button.remove()
             self.axslider.remove()
             self.axauto.remove()
             self.mask_text.remove()
             self.slid_mask_text.remove()
         #fx.visual()
         self.ax2setup()
 
     if cp.plot_vers != 1: 
         cp.plot_vers = 1
         
         if 'ix' not in globals():
             global ix, iy
             ix = spectra.shape[1]//2
             iy = spectra.shape[0]//2
             
         spec = np.array(spectra[iy][ix])
         
         self.ax1.scatter(ix, iy, s=200, marker='x', c='white', linewidth=2.5)
         
         self.ax2_title.set_text('Pixel (%ix , %iy): Spectra' % (ix, iy))
         self.curveSpec.set_ydata(spec)
     
         param = fx.paramSliders()
         
         self.curveM2.set_ydata(M2(freqs, *param))
         
         plt.text(0.05, 11.5, "*Using parameters found in: '%s'" % param_dir)
         
         self.axreload = plt.axes([0.83, 0.18, 0.05, 0.05])
         self.axsaveFig = plt.axes([0.83, 0.11, 0.05, 0.05])
         self.axreset = plt.axes([0.83, 0.04, 0.05, 0.05])
         
         self.breload = Button(self.axreload, 'Reload')
         self.breload.on_clicked(fx.reload)
         self.bsaveFig = Button(self.axsaveFig, 'Save')
         self.bsaveFig.on_clicked(fx.saveFig)
         self.breset = Button(self.axreset, 'Reset')
         self.breset.on_clicked(fx.reset)
Example #3
0
 def update2(self):
     params = np.zeros((len(fx.axsliders)))
 
     for i in range(len(fx.axsliders)):
         params[i] = fx.fnsliders[i].val
         fx.fnsliders[i].valtext.set_text(text[i] % params[i])
      
     cp.curveM2.set_ydata(M2(freqs, *params))
     cp.curveM1.set_ydata(M1(freqs, *params[:3]))
     cp.curveLorentz.set_ydata(m2(freqs, *params[3:6]))  
Example #4
0
def reset(event):
    for slider in fnsliders:
        slider.reset()
    c_m2.set_ydata(emptyLine)
    c_l2.set_ydata(emptyLine)
    params = [slider.val for slider in fnsliders]
    s = M2(freqs, *params)

    #l.set_ydata(s)
    curveM2.set_ydata(s)
Example #5
0
    def timeSeries(self, event):
        global slid_mask
    
        if cp.plot_vers == 1:
            for slider in fx.axsliders:
                slider.remove()
            for axesObj in [self.axreload, self.axsaveFig, self.axreset]:
                axesObj.remove()
            
        if cp.plot_vers == 2:  pass  # maybe just: if cp.plot_vers != 2:

        else:  
            if cp.plot_vers == 3:
                self.ax4.remove()
                self.cbar2.remove()
                self.axslider2.remove()
                #fx.visual()
            
            cp.plot_vers = 2
            
            if 'ix' not in globals():
                global ix, iy
                ix = spectra.shape[1]//2
                iy = spectra.shape[0]//2
            
            self.ax1.scatter(ix, iy, s=200, marker='x', c='white', linewidth=2.5)
            
            self.ax2setup()
            
            if haveImCube:
                # ax3: displays pixel timeseries
                self.ax3 = plt.subplot2grid((31,31),(22, 1), colspan=29, rowspan=8)
                self.ax3_title = self.ax3.set_title('Pixel (%ix , %iy): Timeseries' % (ix, iy), fontsize=fontSize)
                self.ax3.set_xlabel('Time', fontsize=fontSize, labelpad=5)
                self.ax3.set_ylabel('Intensity', fontsize=fontSize, labelpad=5)
                self.ax3.set_xlim(timestamps[0]-0.01*t_range, timestamps[-1]+0.01*t_range) 
                
                self.ts, = self.ax3.plot(timestamps, emptyTimeseries, 'k')
                
                timeseries = np.array(imCube[iy+1][ix+1] / exposures)
                  
                self.ts.set_ydata(timeseries)  
                self.ax3.set_ylim(timeseries.min()*0.9, timeseries.max()*1.1) 
                
            spec = np.array(spectra[iy][ix])
                
            self.ax2_title.set_text('Pixel (%ix , %iy): Spectra' % (ix, iy))
            self.curveSpec.set_ydata(spec)
            
            if haveParam:
                cp.curveM2.set_ydata(M2(freqs, *h_map[iy,ix,:6]))
                cp.curveM1.set_ydata(M1(freqs, *h_map[iy,ix,:3]))
                cp.curveLorentz.set_ydata(m2(freqs, *h_map[iy,ix,3:6]))
Example #6
0
def update2(val):
    params = np.zeros((len(axsliders)))

    for i in range(len(axsliders)):
        params[i] = fnsliders[i].val
        fnsliders[i].valtext.set_text(text[i] % params[i])
        """
        if i == 0:
            params[i] = 10**fnsliders[i].val
        else:
            params[i] = fnsliders[i].val
        if i == 4:
            fnsliders[i].valtext.set_text(text[i] % (1./(np.exp(params[4])*60.)))
        else:
            fnsliders[i].valtext.set_text(text[i] % params[i])
        """

    s = M2(freqs, *params)

    #l.set_ydata(s)
    curveM2.set_ydata(s)
    curveM1.set_ydata(M1(freqs, *params[:3]))
    curveLorentz.set_ydata(m2(freqs, *params[3:6]))
Example #7
0
def onclick(event):
    #global ix, iy
    ixx, iyy = event.xdata, event.ydata
    
    if event.inaxes == cp.ax1:
        global ix, iy
        del cp.ax1.collections[:]
        plt.draw()
        
        if cp.spec_hist == 'hist':
            cp.ax2setup()
            cp.spec_hist = 'spec'

        #print("location: (%fx, %fy)" % (ixx, iyy))        
        #print("location: (%ix, %iy)" % (ixx, iyy))
        ix = int(round(ixx))
        iy = int(round(iyy))
        
        s = np.array(spectra[iy][ix])
        
        if specVis_fit == True:
            # use 3x3 pixel-box std.dev. or adhoc method for fitting uncertainties
            if spec_unc == 'stddev':
                ds = np.array(stdDev[iy][ix])
            elif spec_unc == 'adhoc':
                ds = ds0
            specFit(s, ds)
        
        # update subplots
        cp.ax1.scatter(ix, iy, s=200, marker='x', c='white', linewidth=2.5)
        
        cp.ax2_title.set_text('Pixel (%ix , %iy): Spectra' % (ix, iy))

        cp.curveSpec.set_ydata(s)
        
        # update spectra and timeseries
        if cp.plot_vers == 2:
            if haveImCube:
                timeseries = np.array(imCube[iy+1][ix+1] / exposures)
                cp.ts.set_ydata(timeseries)  
                cp.ax3.set_ylim(timeseries.min()*0.9, timeseries.max()*1.1)  
                cp.ax3_title.set_text('Pixel (%ix , %iy): Timeseries' % (ix, iy))
            if haveParam:
                cp.curveM2.set_ydata(M2(freqs, *h_map[iy,ix,:6]))
                cp.curveM1.set_ydata(M1(freqs, *h_map[iy,ix,:3]))
                cp.curveLorentz.set_ydata(m2(freqs, *h_map[iy,ix,3:6]))
        
        # update spectra and model sliders
        if cp.plot_vers == 1:
            
            for slider in fx.axsliders:
                slider.remove()
            
            param = fx.paramSliders()
            
            plt.text(0.05, 11.5, "*Using parameters found in: '%s'" % param_dir)
            
            s = M2(freqs, *param)
            #l.set_ydata(s)
            cp.curveM2.set_ydata(s)
            cp.curveM1.set_ydata(M1(freqs, *param[:3]))
            cp.curveLorentz.set_ydata(m2(freqs, *param[3:6]))
Example #8
0
def specFit(s, ds):
    ## fit data to combined power law plus gaussian component model       
    try:
        m1_param = Fit(M1, freqs, s, p0=M1_guess, bounds=(M1_low, M1_high), 
                      sigma=ds, method='dogbox')[0]
      
    except RuntimeError: print("Error M1 - curve_fit failed")
    except ValueError: print("Error M1 - inf/NaN")
    
    A, n, C = m1_param  # unpack model parameters
     
   
    try:                                                          
        m2_param0 = Fit(M2, freqs, s, p0=M2_guess, bounds=(M2_low, M2_high), 
                       sigma=ds, method='dogbox', max_nfev=3000)[0]
    
    except RuntimeError: print("Error M2 - curve_fit failed")
    except ValueError: print("Error M2 - inf/NaN")

    
    #A2, n2, C2, P2, fp2, fw2 = m2_param0
    #print nlfit_gp
           
    try:   
        m2_param = Fit(M2, freqs, s, p0=m2_param0, bounds=(M2_low, M2_high),
                        sigma=ds, max_nfev=3000)[0]    
       
    except RuntimeError: print("Error M2 - curve_fit failed")
    except ValueError: print("Error M2 - inf/NaN")
    
    A22, n22, C22, P22, fp22, fw22 = m2_param     
    #print m2_param
                   
    # create models from parameters    
    m1_fit = M1(freqs, *m1_param)    
    lorentz = m2(freqs, P22, fp22, fw22)
    m2_fit2 = M2(freqs, *m2_param) 
    m1_fit2 = M1(freqs, A22, n22, C22)      
    
    """
    residsM1 = (s - m1_fit)
    chisqrM1 =  ((residsM1/ds)**2).sum() 
    
    residsM22 = (s - m2_fit2)
    chisqrM22 = ((residsM22/ds)**2).sum()
    redchisqrM22 = ((residsM22/ds)**2).sum()/float(freqs.size-6) 
          
    f_test2 = ((chisqrM1-chisqrM22)/(6-3))/((chisqrM22)/(freqs.size-6))
    
    dof1, dof2 = 3, 6  # degrees of freedom for model M1, M2
    #p_val = ff.sf(f_test2, dof1, dof2)
    
    # extract the lorentzian amplitude scaling factor
    amp_scale2 = M1(np.exp(fp22), A22, n22, C22)  
    """
    
    fwhm = (1. / (np.exp(fp22+fw22) - np.exp(fp22-fw22))) / 60.
    
    pLoc = (1./np.exp(fp22))/60.
    
    #curveM1A.set_ydata(m1_fit)
    curveM2.set_ydata(m2_fit2)
    curveM1.set_ydata(m1_fit2)
    curveLorentz.set_ydata(lorentz)
    
    p_index.set_text(r'$n$ = {0:0.2f}'.format(n22))
    p_amp.set_text(r'$\alpha$ = {0:0.2e}'.format(P22))
    p_loc.set_text(r'$\beta$ = {0:0.1f} [min]'.format(pLoc))
    p_wid.set_text(r'$FWHM$ = {0:0.1f} [min]'.format(fwhm))  
Example #9
0
def onclick(event):
    #global ix, iy
    global fnsliders
    global axsliders
    ixx, iyy = event.xdata, event.ydata

    if event.inaxes == ax1:
        global ix, iy
        del ax1.collections[:]
        plt.draw()

        #print("location: (%fx, %fy)" % (ixx, iyy))
        #print("location: (%ix, %iy)" % (ixx, iyy))
        ix = int(round(ixx))
        iy = int(round(iyy))

        #print(spectra)
        s = np.array(spectra[iy][ix])

        if specVis_fit == True:
            # use 3x3 pixel-box std.dev. or adhoc method for fitting uncertainties
            if spec_unc == 'stddev':
                ds = np.array(stdDev[iy][ix])
            elif spec_unc == 'adhoc':
                ds = ds0
            specFit(s, ds)

        # update subplots
        ax1.scatter(ix, iy, s=200, marker='x', c='white', linewidth=2.5)

        title.set_text('Pixel (%ix , %iy): Spectra' % (ix, iy))

        curveSpec.set_ydata(s)

        timeseries = np.array(imCube[iy + 1][ix + 1] / exposures)

        if toggle3 == 2:
            ts.set_ydata(timeseries)
            ax3.set_ylim(timeseries.min() * 0.9, timeseries.max() * 1.1)
            title3.set_text('Pixel (%ix , %iy): Timeseries' % (ix, iy))
            if haveParam:
                curveM2.set_ydata(M2(freqs, *h_map[iy, ix, :6]))
                curveM1.set_ydata(M1(freqs, *h_map[iy, ix, :3]))
                curveLorentz.set_ydata(m2(freqs, *h_map[iy, ix, 3:6]))

        if toggle3 == 1:

            for slider in axsliders:
                slider.remove()

            axsliders = []
            fnsliders = []

            if haveParam:
                param = h_map[iy, ix, :6]
            else:
                param = (np.array(M2_low) + np.array(M2_high)) / 2

            # make parameter sliders
            for i, M2_label in enumerate(M2_labels):
                axsliders.append(plt.axes([0.15, 0.23 - (0.04 * i), 0.6,
                                           0.02]))
                fnsliders.append(
                    Slider(axsliders[i], M2_label, M2_low[i], M2_high[i],
                           param[i]))
                fnsliders[i].on_changed(update2)
                fnsliders[i].valtext.set_text(text[i] % param[i])

            plt.text(0.05, 11.5,
                     "*Using parameters found in: '%s'" % param_dir)

            s = M2(freqs, *param)
            #l.set_ydata(s)
            curveM2.set_ydata(s)
            curveM1.set_ydata(M1(freqs, *param[:3]))
            curveLorentz.set_ydata(m2(freqs, *param[3:6]))
Example #10
0
def setPre():
    global toggle3
    global l, c_m2, c_l2
    global axsaveFig, axreset, axreload, bsaveFig, breset, breload
    global axsliders, fnsliders

    if toggle3 == 2:
        ax3.remove()
        if haveParam:
            for button in axbutton:
                button.remove()
            axslider.remove()
        visual()

    if toggle3 == 3:
        ax4.remove()
        cbar2.remove()
        axslider2.remove()
        if haveParam:
            for button in axbutton:
                button.remove()
            axslider.remove()
        visual()

    if toggle3 != 1:
        toggle3 = 1

        emptyLine = [0 for i in range(len(freqs))]

        if 'ix' not in globals():
            global ix, iy
            ix = spectra.shape[1] // 2
            iy = spectra.shape[0] // 2

        ##have so that if no param file, then maybe load middle of param bounds
        spec = np.array(spectra[iy][ix])

        title.set_text('Pixel (%ix , %iy): Spectra' % (ix, iy))

        curveSpec.set_ydata(spec)

        ax1.scatter(ix, iy, s=200, marker='x', c='white', linewidth=2.5)

        axsliders = []
        fnsliders = []

        if haveParam:
            param = h_map[iy, ix, :6]
        else:
            global curveM2
            param = (np.array(M2_low) + np.array(M2_high)) / 2
            curveM2, = ax2.loglog(freqs, emptyLine, c='r', lw=1.5, label='M2')

        #s = M2(freqs, *h_map[iy,ix,:6])
        s = M2(freqs, *param)

        # make parameter sliders
        for i, M2_label in enumerate(M2_labels):
            axsliders.append(plt.axes([0.15, 0.23 - (0.04 * i), 0.6, 0.02]))
            fnsliders.append(
                Slider(axsliders[i], M2_label, M2_low[i], M2_high[i],
                       param[i]))
            fnsliders[i].on_changed(update2)
            fnsliders[i].valtext.set_text(text[i] % param[i])

        curveM2.set_ydata(s)
        #l, = ax2.loglog(freqs, s, lw=1.5, color='red')
        c_m2, = ax2.loglog(freqs,
                           emptyLine,
                           'b',
                           linewidth=1.3,
                           label='M2 - Lorentz')
        c_l2, = ax2.loglog(freqs,
                           emptyLine,
                           'b--',
                           linewidth=1.3,
                           label='Lorentz')

        plt.text(0.05, 11.5, "*Using parameters found in: '%s'" % param_dir)

        axreload = plt.axes([0.83, 0.18, 0.05, 0.05])
        axsaveFig = plt.axes([0.83, 0.11, 0.05, 0.05])
        axreset = plt.axes([0.83, 0.04, 0.05, 0.05])

        # add callbacks to each button - linking corresponding action
        callback = Index()

        breload = Button(axreload, 'Reload')
        breload.on_clicked(callback.reload)
        bsaveFig = Button(axsaveFig, 'Save')
        bsaveFig.on_clicked(callback.saveFig)
        breset = Button(axreset, 'Reset')
        breset.on_clicked(reset)
Example #11
0
def specFit(subcube, subcube_StdDev):

    params = np.zeros((subcube.shape[0], subcube.shape[1], 9))

    start_sub = timer()
    T1 = 0

    for l in range(subcube.shape[0]):
        for m in range(subcube.shape[1]):

            f = freqs
            s = subcube[l][m]

            # ---- use pixel-box std.dev. or adhoc method as fitting uncertainties
            if spec_unc == 'stddev':
                ds = subcube_StdDev[l][m]
            elif spec_unc in ['adhoc', 'constant']:
                ds = subcube_StdDev

            # ---- fit models to spectra using SciPy's Levenberg-Marquart method
            try:
                m1_param = Fit(M1,
                               f,
                               s,
                               p0=M1_guess,
                               bounds=(M1_low, M1_high),
                               sigma=ds,
                               method='dogbox')[0]

            except RuntimeError:
                pass
            except ValueError:
                pass

            # ---- first fit M2 model using 'dogbox' method
            try:
                m2_param0 = Fit(M2,
                                f,
                                s,
                                p0=M2_guess,
                                bounds=(M2_low, M2_high),
                                sigma=ds,
                                method='dogbox',
                                max_nfev=3000)[0]

            except RuntimeError:
                pass
            except ValueError:
                pass

            # ---- next fit M2 model using default 'trf' method
            try:
                m2_param = Fit(M2,
                               f,
                               s,
                               p0=m2_param0,
                               bounds=(M2_low, M2_high),
                               sigma=ds,
                               max_nfev=3000)[0]

            except RuntimeError:
                pass
            except ValueError:
                pass

            # ---- create model functions from fitted parameters
            m1_fit = M1(f, *m1_param)
            m2_fit = M2(f, *m2_param)

            #weights = subcube_StdDev[l][m]

            residsM1 = (s - m1_fit)
            chisqrM1 = ((residsM1 / ds)**2).sum()
            redchisqrM1 = chisqrM1 / float(f.size - 3)

            residsM2 = (s - m2_fit)
            chisqrM2 = ((residsM2 / ds)**2).sum()
            redchisqrM2 = chisqrM2 / float(f.size - 6)

            f_test = ((chisqrM1 - chisqrM2) / (6 - 3)) / ((chisqrM2) /
                                                          (f.size - 6))

            # ---- extract the lorentzian-amplitude scaling factor
            amp_scale = m2_param[3] / M1(np.exp(m2_param[4]), *m2_param[:3])

            if chisqrM1 > chisqrM2:
                # populate array with M2 parameters
                params[l][m][:6] = m2_param
                params[l][m][6] = f_test
                params[l][m][7] = amp_scale
                params[l][m][8] = redchisqrM2

            else:
                # populate array with M1 parameters
                params[l][m][:3] = m1_param
                params[l][m][3:8] = np.NaN
                params[l][m][8] = redchisqrM1

        # ---- estimate time remaining and print to screen
        T = timer()
        T2 = T - T1
        if l == 0:
            T_init = T - start_sub
            T_est = T_init * (subcube.shape[0])
        else:
            T_est = T2 * (subcube.shape[0] - l)
        T_min, T_sec = divmod(T_est, 60)
        T_hr, T_min = divmod(T_min, 60)
        if l == 0:
            start_time = (T_hr, T_min, T_sec)

        print("Thread %i on row %i/%i, ETR: %i:%.2i:%.2i" %
              (rank, l, subcube.shape[0], T_hr, T_min, T_sec),
              flush=True)
        T1 = T

    # ---- print estimated and total program time to screen
    print("Beginning est. time = %i:%.2i:%.2i" % start_time, flush=True)
    T_act = timer() - start_sub
    T_min, T_sec = divmod(T_act, 60)
    T_hr, T_min = divmod(T_min, 60)
    print("Actual total time = %i:%.2i:%.2i" % (T_hr, T_min, T_sec),
          flush=True)

    return params