예제 #1
0
def plot_a(ax,
           age,
           flux,
           low=None,
           high=None,
           syms='o',
           colors='b',
           sizes=4,
           alphas=1.0,
           mecs='black',
           mews=0.5,
           line='',
           errorband=False,
           label='_nolegend_'):
    if low is not None:
        elow, ehigh = ebars(flux, low, high)
    else:
        elow = None
        ehigh = None
    fancy_plot(age,
               flux,
               yerror=elow,
               yerror_high=ehigh,
               syms=syms,
               colors=colors,
               sizes=sizes,
               alphas=alphas,
               mecs=mecs,
               errorband=errorband,
               line=line,
               mews=mews)
예제 #2
0
def plot_a(ax,age,flux,low=None,high=None,syms='o',colors='b',sizes=4,alphas=1.0,mecs='black',mews=0.5,line='',errorband=False,label='_nolegend_'):        
    if low is not None:
        elow,ehigh = ebars(flux,low,high)
    else:
        elow = None
        ehigh = None
    fancy_plot(age,flux,yerror=elow,yerror_high=ehigh,syms=syms,colors=colors,sizes=sizes,alphas=alphas,mecs=mecs,errorband=errorband,line=line,mews=mews)
예제 #3
0
    def make_plot(self):
        #plot solar wind speed
        self.ax[0].scatter(self.soho_df.index,
                           self.soho_df.SPEED,
                           color='black')
        self.ax[0].set_ylabel('$|\mathrm{V}|$ [km/s]')
        fancy_plot(self.ax[0])

        #plot solar wind density
        self.ax[1].scatter(self.soho_df.index, self.soho_df.Np, color='black')
        self.ax[1].set_ylabel('n$_\mathrm{p}$ [cm$^{-3}$]')
        self.ax[1].set_yscale('log')
        fancy_plot(self.ax[1])

        #Thermal Speed
        self.ax[2].scatter(self.soho_df.index, self.soho_df.Vth, color='black')
        self.ax[2].set_ylabel('w$_\mathrm{p}$ [km/s]')
        self.ax[2].set_xlabel('Time')
        fancy_plot(self.ax[2])

        #set plotting limit
        self.set_day_limit()
예제 #4
0
#--Initialize Plot--
ax1 = start_plot(xtitle='SN1987A Age [days]',
                 ytitle='Radius [arcsec]',
                 xmin=args.agemin,
                 xmax=args.agemax,
                 ymin=rmin,
                 ymax=rmax)

#----Plot----
fancy_plot(fitdata['age'],
           fitdata['R0'],
           yerror=fitdata['R0errl'],
           yerror_high=fitdata['R0erru'],
           syms=syms,
           colors=colors,
           sizes=sizes,
           alphas=alphas,
           mecs=mecs,
           mews=mews,
           errorband=False)

#----Plot Legend----
plot_legend(labels=leglabels,
            colors=legcolors,
            markers=legsyms,
            mecs=legmecs,
            mews=legmews,
            fontsize='small')

#--set top axis--
#get predictions for the Mission long CELIAS mission
if full_soho:
    full_df['predict'] = sh_rs.predict(full_df[use_cols])
    best_df = full_df[full_df.predict >= 0.90]
    best_df.to_csv('../soho/archive_shocks.csv', sep=';')

#create figure object
fig, ax = plt.subplots(figsize=(12, 7))

#plot solar wind speed
ax.scatter(sig_jump, sig_cnts, color='black')
ax.set_xlabel(r'N sigma training')
ax.set_ylabel(r'\# of Events (2016)')
ax.set_yscale('log')
ax.set_ylim([.5, 2E6])
fancy_plot(ax)

fig.savefig('../plots/soho_num_events_sig_cut.png',
            bbox_inches='tight',
            bbox_pad=0.1)
fig.savefig('../plots/soho_num_events_sig_cut.eps',
            bbox_inches='tight',
            bbox_pad=0.1)

###########
#BOKEH PLOT
#For the training set
###########
from bokeh.models import HoverTool, ColumnDataSource
from bokeh.plotting import figure, show, save
from bokeh.layouts import column, gridplot
예제 #6
0
    def main(self):
        ptype = self.ptype
        #format name of file to read
        fname = 'offset30{0}.dat'.format(ptype[0].lower())

        #read in trend values for given ccd
        dat = readsav(fname)
        #correct for different variable name formats
        aval = ''
        if self.ptype.lower() == 'nuv': aval = 'n'
        #put readsav arrays in defining variables
        time = dat['t{0}i'.format(aval)]  #seconds since Jan. 1st 1979
        port = dat['av{0}i'.format(aval)]
        errs = dat['sigmx']

        #cut spurious point from fit
        if self.cut:
            good, = np.where((time <= 1.175e+09) | (time >= 1.180e+09))
            time = time[good]
            port = port[good, :]
            errs = errs[good, :]

        print '      {0:10},{3:10},{2:15},{1:10},{4:10},{5:20},{6:20},{7:10}'.format(
            'Amp1', 'Phi1', 'P1', 'Amp2', 'Phi2', 'Trend', 'Quad', 'Offset')
        #loop over all ports
        for i in range(port.shape[1]):
            toff = self.t0dict['{0}{1:1d}'.format(ptype.lower(), i + 1)]
            dt0 = time - toff  #- 31556926.#makes times identical to the values taken in iris_trend_fix

            # init parameter guesses
            guess = self.gdict['{0}{1:1d}'.format(ptype.lower(), i + 1)]
            #fit with initial guesses
            if self.fit:
                popt, pcov = curve_fit(self.offset,
                                       dt0,
                                       port[:, i],
                                       p0=guess,
                                       sigma=errs[:, i])
            else:
                popt = guess
            #print '{0} {1:1d}'.format(self.ptype.upper(),i+1)
            if self.fit:
                print '{8}{9:1d}=[{0:^10.5f},{3:^10.5f},{2:^15.4e},{1:^10.5f},{4:^10.5f},{5:^20.9e},{6:^20.9e},{7:^10.5f}]'.format(
                    popt[0], popt[1], popt[2], popt[3], popt[4], popt[5],
                    popt[6], popt[7], self.ptype, i + 1)
            fig, ax = plt.subplots()
            ptim = np.linspace(dt0.min(), dt0.max() + 1e3, 500)
            #print dt0.max()
            #print self.offset(dt0.max(),*popt)
            #print self.offset(1.2041407e8,*popt)
            ptime = [self.startd + timedelta(seconds=j + toff) for j in ptim]
            dt1 = [self.startd + timedelta(seconds=j) for j in time]
            ax.set_title('{0} {1:1d}'.format(self.ptype.upper(), i + 1))
            ax.plot(ptim, self.offset(ptim, *popt), 'r--', label='fit')
            ax.scatter(dt0, port[:, i], color='black')
            ax.errorbar(dt0,
                        port[:, i],
                        yerr=errs[:, i],
                        color='black',
                        fmt='o')

            if self.fit:
                var = np.sqrt(
                    np.sum((port[:, i] - self.offset(dt0, *popt))**2.) /
                    float(dt0.size))
            else:
                var = np.sqrt(
                    np.sum((port[:, i] - self.offset(dt0, *guess))**2.) /
                    float(dt0.size))
            ax.text(dt0.min(), 8, r'$\sigma$(fit) = {0:6.5f}'.format(var))
            ax.set_ylim([-5., 15.])
            ax.set_xlabel('Epoch Time [s]', fontsize=18)
            ax.set_ylabel('Counts [ADU]', fontsize=18)
            fancy_plot(ax)

            #        plt.show()
            fig.savefig('plots/new_fits/{0}_port{1:1d}.png'.format(
                self.ptype, i + 1),
                        bbox_pad=.1,
                        bbox_inches='tight')
            if self.show: plt.show()
    def iris_dark_plot(self):
        """
        This function will plot and IRIS pedestal data and the best fit parameters for each port.

        Args
        ------
        self: class
            The GUI class in this module
   
        Returns
        --------
            None
        """
        #clear the plot axes
        for i in self.wplot.keys():

            #If a previous plot exists get x and y limits
            if self.lat_plot:
                #get previous x and y limits
                xlim = self.wplot[i].get_xlim()
                ylim = self.wplot[i].get_ylim()

            #clear previous plot
            self.wplot[i].clear()
            self.wplot[i].set_title(i.upper())
            self.wplot[i].set_xlabel('Offset Time [s]')
            self.wplot[i].set_ylabel('Pedestal Offset [ADU]')

            #If a previous plot exists set x and y limits
            if self.lat_plot:
                #set previous x and y limits
                self.wplot[i].set_xlim(xlim)
                self.wplot[i].set_ylim(ylim)

        #After first run through set lat(er)_plots to true
        self.lat_plot = True

        #best fit lines
        self.bline = {}
        #data scatter
        self.sdata = {}

        #plot data for all IRIS dark remaining pedestals
        for i in sorted(self.fdata.keys()):
            #Get plot associated with each port
            ax = self.wplot[i[:-1]]
            #Put data in temp array
            dat = self.fdata[i]

            #set ptype attribute for curvefit and offset model
            self.ptype = i[:-1]
            #set the current port variable
            self.cport = i

            #get variance in best fit model
            var = self.get_var(i, self.gdict[i])
            #get offset in last data point
            last = self.get_last(i, self.gdict[i])

            #Uploaded best fit
            #current dark time plus a few hours
            ptim = np.linspace(self.fdata[i][0].min(),
                               self.fdata[i][0].max() + 1e3, 500)
            #plot values currently in gdict for best fit values (store in dictionary for updating line)
            self.bline[i] = self.wplot[i[:-1]].plot(
                ptim,
                self.offset(ptim, *self.gdict[i]),
                color=self.fdata[i][3],
                label='{0}(Unc.) = {1:5.4f}'.format(i, var))

            #plot each port
            self.sdata[i] = ax.scatter(dat[0],
                                       dat[1],
                                       color=dat[3],
                                       marker=dat[4],
                                       label='{0}(last) = {1:3.2f}'.format(
                                           i, last))
            ax.errorbar(dat[0],
                        dat[1],
                        yerr=dat[2],
                        color=dat[3],
                        fmt=dat[4],
                        label=None)

        #add legend
        for i in self.wplot.keys():
            self.wplot[i].legend(loc='upper left', frameon=True)
            #add fancy plotting
            fancy_plot(self.wplot[i])

        self.canvas.draw()
예제 #8
0
    alphas = [1.0]*nobs

print 'Markers Defined'

#----Set Up Plot File----
#pdffile = PdfPages(args.plotfile)

with PdfPages(args.plotfile) as pdffile:

    #----R0 vs age----

    #--Initialize Plot--
    ax1 = start_plot(xtitle='SN1987A Age [days]',ytitle='Radius [arcsec]',xmin=args.agemin,xmax=args.agemax,ymin=rmin,ymax=rmax)

    #----Plot----
    fancy_plot(ax1,fitdata['age'],fitdata['R0'],yerror=fitdata['R0errl'],yerror_high=fitdata['R0erru'],syms=syms,colors=colors,sizes=sizes,alphas=alphas,mecs=mecs,mews=mews,errorband=False)

    #----Plot broken-linear fits----
    if args.plotfit == 'yes':
        for bi in range(len(bands)):
            b = bands[bi]
            #--read best-fit model file--
            modeldata = np.genfromtxt(radiusfilename+'_'+b+'_mpfit_radii.txt',skip_header=0,names=True,comments='#',dtype=None)
            #--overplot model--
            fancy_plot(ax1,modeldata['age'],modeldata['radius'],yerror=modeldata['radiuslow'],yerror_high=modeldata['radiushigh'],syms='None',colors=bandcolors[bi],line='-',errorband=True) 

    #----Other noteable data points----
    # [age,radius(arcsec from center)]

    if args.plotextras != None:
예제 #9
0
def chi_min(p_mat,
            par,
            rgh_chi_t,
            plsm,
            k,
            ref_chi_t=pd.to_timedelta('10 minutes'),
            refine=True,
            n_fine=4,
            plot=False):
    """
    chi_min computes the chi^2 min. time for a given set of parameters

    p_mat: Pandas DataFrame
    Solar wind pandas DataFrame for a space craft roughly sampled

    par : list
    List of parameters to use in the Chi^2 minimization 

    rgh_chi_t: Pandas datetime delta object
    Time around a given time in p_mat to include in chi^2 minimization  

    ref_chi_t: Pandas datetime delta object
    Time around a given time in refined grid to include in chi^2 minimization  

    plsm: dict
    Dictionary of plasma DataFrames of plasma Dataframes
   
    k   : string
    Spacecraft name in plsm dictionary
   

    refine: boolean
    Whether to use a refined window (Default = True)

    n_fine : integer
    Number of chi^2 min values from the rough grid to check with the fine grid (Default = 4)

    plot  : boolean
    Plot Chi^2 minimization window (Default = False)

    RETURNS
    --------
    i_min : datetime index
    Datetime index of best fit Chi^2 time

    """

    #set up chisquared array in pandas object
    p_mat.loc[:, 'chisq'] = -99999.9
    for time in p_mat.index:
        #get a region around one of the best fit times
        com_slice = [time - rgh_chi_t, time + rgh_chi_t]
        c_mat = plsm[k].loc[com_slice[0]:com_slice[1]]

        #update the time index of the match array for comparision with training spacecraft (i=training spacecraft time)
        c_mat.index = c_mat.index + (i - time)

        #remove Speed fill values by interpolation
        c_mat.loc[c_mat.SPEED < 0., 'SPEED'] = np.nan
        c_mat.SPEED.interpolate('time', inplace=True)

        #get training spacecraft time range
        t_mat = plsm[trainer].loc[c_mat.index.min():c_mat.index.max()]

        #resample the matching (nontrained spacecraft to the trained spacecraft's timegrid and interpolate
        c_mat = c_mat.reindex(t_mat.index,
                              method='nearest').interpolate('time')

        #get median offset to apply to match spacecraft
        off_speed = c_mat.SPEED.median() - t_mat.SPEED.median()
        c_mat.SPEED = c_mat.SPEED - off_speed

        #compute chi^2 value for Wind and other spacecraft
        p_mat.loc[time, 'chisq'] = np.sqrt(
            np.sum(((c_mat.loc[:, par] - t_mat.loc[:, par])**2.).values))

        #create figure to check matchin
        if plot:
            ax.scatter(
                c_mat.index,
                c_mat.SPEED,
                label=time.to_pydatetime().strftime('%Y/%m/%dT%H:%M:%S') +
                ' chisq = {0:4.0f}'.format(p_mat.loc[time, 'chisq']))
            ax.plot(t_mat.index, t_mat.SPEED, label='', color='black')

    if plot:
        ax.legend(loc='upper left', frameon=False, scatterpoints=1)
        ax.set_xlim([t_mat.index.min(), t_mat.index.max()])
        ax.set_ylabel('Speed [km/s]')
        ax.set_xlabel('Time [UTC]')
        fancy_plot(ax)
        #ax.set_ylim([300,1000.])
        plt.show()

    #get the index of minimum chisq value
    i_min = p_mat['chisq'].idxmin()

    #use fine grid around observations to match time offset locally
    if refine:

        #Find 4 lowest chisq min times
        p_temp = p_mat.sort_values('chisq', ascending=True)[:n_fine]

        #get all values in top n_fine at full resolution
        p_mat = plsm[k].loc[p_temp.index.min() - rgh_chi_t:p_temp.index.max() +
                            rgh_chi_t]
        print(p_temp.index.min() - rgh_chi_t, p_temp.index.max() + rgh_chi_t)

        #loop over all indexes in refined time window
        for time in p_mat.index:
            #get a region around one of the best fit times
            com_slice = [time - ref_chi_t, time + ref_chi_t]
            c_mat = plsm[k].loc[com_slice[0]:com_slice[1]]

            #update the time index of the match array for comparision with training spacecraft (i=training spacecraft time)
            c_mat.index = c_mat.index + (i - time)

            #remove Speed fill values by interpolation
            c_mat.loc[c_mat.SPEED < 0., 'SPEED'] = np.nan
            c_mat.SPEED.interpolate('time', inplace=True)

            #get trainint spacecraft time range
            t_mat = plsm[trainer].loc[c_mat.index.min():c_mat.index.max()]

            #resample the matching (nontrained spacecraft to the trained spacecraft's timegrid and interpolate
            c_mat = c_mat.reindex(t_mat.index,
                                  method='nearest').interpolate('time')

            #get median offset to apply to match spacecraft
            off_speed = c_mat.SPEED.median() - t_mat.SPEED.median()
            c_mat.SPEED = c_mat.SPEED - off_speed

            #compute the chisq value in SPEED from the top ten probablilty array including the median offsets
            p_mat.loc[time, 'chisq'] = np.sqrt(
                np.sum(((c_mat.loc[:, par] - t_mat.loc[:, par])**2.).values))

        #get the index of minimum refined chisq value
        i_min = p_mat['chisq'].idxmin()

    return i_min
예제 #10
0
def plot_extras(names='all', agemin=4000, agemax=11000):
    """
	Author: Kari A. Frank
	Date: September 22, 2015
	Purpose: Plot lines on already open age vs Y plots (where Y is 
	      typically either radius or flux

	Input:
	 names : string
	     comma separated list of names of which extras to plot. 
	     default = 'all'. options are:
	     'plait1995'- plots position and width of the ER from 
	          Plait1995 (in this case Y must be radius)
	     'ng2013' - plots the radio break age day=7600 from the 
	          Ng2013 torus fits to radio images, as vertical line
	     'sugarman2002' - plots location of the ring from Sugarman 2002 
	          (in this case Y must be radius)
	     'hotspots' - plots the radius and day of appearance for the 
	          HST hot spots in Sugarman 2002
	     'larsson2014' - plots the age of transition from radioactive 
	         decay to X-ray heating as inner debris energy source
	      'chandrabroadbreak' - plot as vertical line the best fit 
	           age of the break point in expansion curve
	      'plaitwidth' - plot distance from chandrabroadbreak radius 
	           to width of plait ring

	Output:
	 - plots to an already open plot

	Usage Notes:
	 - will not add anything to the plot legend
	"""

    dummy_y = [0.00000001, 1000.]  #dummy y values for vertical lines
    dummy_sym = '.'

    if names == 'all' or 'hotspots' in names:
        # hot spot appearances in HST, Sugarman2002 table 1
        hotspot_ages = [
            2933, 4283, 4337, 4337, 4440, 4440, 4440, 4725, 4816, 4816, 4999,
            4999
        ]
        hotspot_radii = [
            0.56, 0.673, 0.607, 0.702, 0.565, 0.697, 0.707, 0.607, 0.535,
            0.629, 0.531, 0.713
        ]

        fancy_plot(hotspot_ages, hotspot_radii, syms='*', colors='white')
        #        legcolors+=['white'] #marker will look like border only
        #        leglabels+=['HST Hot Spots']
        #        legmecs+=['black']
        #        legmews+=[0.5]
        #        legsyms+=['*']

    if names == 'all' or 'larsson2014' in names:
        #Larsson2013 -- inner debris (HST) morphology transitioned
        #  from core to edge-brightened due to
        #  energy source shifting from radioactive decay to X-ray
        #  illumination
        debris_transition_age = [5500, 5500]
        debris_transition_radius = dummy_y  #plot vertical line

        fancy_plot(debris_transition_age,
                   debris_transition_radius,
                   colors='black',
                   line='--',
                   syms=dummy_sym)
        #legcolors+=[None] #marker will look like border only
        #leglabels+=['Debris Transition']
        #legmecs+=[None]
        #legmews+=[0.]
        #legsyms+=[None]

    if names == 'all' or 'plait1995' in names:
        # Width and location of optical ring from UV flash,
        #  Plait1995
        # plot horizontal band
        plaitwidth = np.array([0.121 / 2.0, 0.121 / 2.0])
        plait_radii = [0.86, 0.86]
        plait_ages = [agemin, agemax]
        fancy_plot(plait_ages,
                   plait_radii,
                   colors='gray',
                   syms=dummy_sym,
                   errorband=True,
                   yerror=plaitwidth)

    if names == 'all' or 'plaitwidth' in names:
        # width of Plait ring, from chandra break point
        plaitwidth = np.array([0.121 / 2.0, 0.121 / 2.0])
        plait_ages = [-1.0, 20000.0]
        chandrabreakradii = [0.73 + 0.121 / 2.0, 0.73 + 0.121 / 2.0]
        fancy_plot(plait_ages,
                   chandrabreakradii,
                   colors='purple',
                   syms=dummy_sym,
                   errorband=True,
                   yerror=plaitwidth)

    if names == 'all' or 'sugarman2002' in names:
        # Location of ring from Sugarman2002 (table 3)
        sugarman_radii = [0.829, 0.829]
        sugarman_ages = [agemin, agemax]
        fancy_plot(plait_ages,
                   plait_radii,
                   colors='gray',
                   syms=dummy_sym,
                   errorband=True,
                   yerror=plaitwidth)

    if names == 'all' or 'ng2013' in names:
        #Ng2013 Radio expansion measurements: using the torus
        #  model found the following all around day 7600:
        # - break in expansion (decrease in velocity)
        # - break in torus opening angle, from constant ~40deg
        #   to decreasing
        # - break in asymmetry; the morphology was ~40% asymmetric,
        #   but became steadily more symmetric at the break
        # - break in the light curve; the slope flattened,
        #   deviating from previous exponential growth
        radiobreak_radii = dummy_y  #plot vertical line
        radiobreak_age = [7600, 7600]

        fancy_plot(radiobreak_age,
                   radiobreak_radii,
                   syms=dummy_sym,
                   colors='black',
                   line=':')

    if names == 'all' or 'chandrabroadbreak' in names:
        # plot best fit age of the break in expansion from the
        #  300-8000 chandra images
        chandrabreak_radii = dummy_y  #plot vertical line
        chandrabreak_age = [5962.77, 5962.77]

        fancy_plot(chandrabreak_age,
                   chandrabreak_radii,
                   syms=dummy_sym,
                   colors='black',
                   line='--')

    if (names == 'all' or 'ng2013radii' in names or 'ng2013fluxes' in names):
        ngradiifile = ('/astro/research/kaf33/Dropbox/Research/SN1987A'
                       '/ng2013_ring_radii.txt')
        ng2013_ringfits = pd.read_table(ngradiifile,
                                        comment='#',
                                        header=0,
                                        names=[
                                            'age', 'flux', 'fluxerr',
                                            'majorradius', 'majorradiuserr',
                                            'minorradius', 'minorradiuserr',
                                            'asymmetry', 'asymmetryerr', 'phi',
                                            'phierr', 'chi2', 'dof'
                                        ],
                                        index_col=False)
        # columns: age(index)	     	flux	fluxerr		majorradius	majorradiuserr	minorradius	minorradiuserr	asymmetry	asymmetryerr	phi	phierr	chi2 dof

    if names == 'all' or 'ng2013radii' in names:

        #             plt.plot(ng2013_ringfits['age'],ng2013_ringfits[])
        fancy_plot(np.array(ng2013_ringfits['age']),
                   np.array(ng2013_ringfits['majorradius']),
                   yerror=np.array(ng2013_ringfits['majorradiuserr']),
                   colors='black',
                   syms='x')
        fancy_plot(np.array(ng2013_ringfits['age']),
                   np.array(ng2013_ringfits['minorradius']),
                   yerror=np.array(ng2013_ringfits['minorradiuserr']),
                   colors='black',
                   syms='x')

    if names == 'all' or 'ng2013fluxes' in names:
        ngradiifile = '~/Dropbox/Research/SN1987A/ng2013_ring_radii.txt'
        ng2013_ringfits = pd.read_table(ngradiifile,
                                        comment='#',
                                        header=0,
                                        names=[
                                            'age', 'flux', 'fluxerr',
                                            'majorradius', 'majorradiuserr',
                                            'minorradius', 'minorradiuserr',
                                            'asymmetry', 'asymmetryerr', 'phi',
                                            'phierr', 'chi2', 'dof'
                                        ],
                                        index_col=False)
        # columns: age(index)	     	flux	fluxerr		majorradius	majorradiuserr	minorradius	minorradiuserr	asymmetry	asymmetryerr	phi	phierr	chi2 dof

        #             plt.plot(ng2013_ringfits['age'],ng2013_ringfits[])
        fancy_plot(np.array(ng2013_ringfits['age']),
                   np.array(ng2013_ringfits['flux'] / 3.0),
                   yerror=np.array(ng2013_ringfits['fluxerr']),
                   colors='black',
                   syms='x')
예제 #11
0
    #--Initialize Plot--
    ax1 = start_plot(xtitle='SN1987A Age [days]',
                     ytitle='Radius [arcsec]',
                     xmin=args.agemin,
                     xmax=args.agemax,
                     ymin=rmin,
                     ymax=rmax)

    #----Plot----
    fancy_plot(ax1,
               fitdata['age'],
               fitdata['R0'],
               yerror=fitdata['R0errl'],
               yerror_high=fitdata['R0erru'],
               syms=syms,
               colors=colors,
               sizes=sizes,
               alphas=alphas,
               mecs=mecs,
               mews=mews,
               errorband=False)

    #----Plot broken-linear fits----
    if args.plotfit == 'yes':
        for bi in range(len(bands)):
            b = bands[bi]
            #--read best-fit model file--
            modeldata = np.genfromtxt(radiusfilename + '_' + b +
                                      '_mpfit_radii.txt',
                                      skip_header=0,
                                      names=True,
예제 #12
0
broaddf = pd.concat([broaddf,obsinfo],join='inner',axis=1)

#-load data from the broken linear fit-
fitdf = pd.read_table('radii_fits_official_300-8000_mpfit_line.txt',sep='\t',comment='#',na_values=None)
#fit2df = pd.read_table('radii_fits_300-8000_300-8000_mpfit_line.txt',sep='\t',comment='#',na_values=None)
#fitdf = pd.read_table('radii_fits_official_300-8000_mpfit_line.txt',sep='\t',comment='#',na_values=None)

#-load data from Svet's density profile fit-
svetdf = pd.read_table('sn1987a_chandra_2016_density_expansion_fit.txt',header=6,sep=r'\s+',engine='python')

#-plot stuff-
pdffile=PdfPages('radius_vs_age_broad.pdf')

fig,ax=snplt.standard_age_plot(broaddf,'R0',ytitle='Radius [arcsec]',yerrlow='R0errl',yerrhigh='R0erru',errinterval=False,gratings='grating',ymin=ymin,ymax=ymax,agemin=agemin,agemax=agemax)

fancy_plot(ax,fitdf['age'],fitdf['radius'],colors='black',line='-',errorband=False,sizes=0.0000)
#fancy_plot(ax,fit2df['age'],fit2df['radius'],colors='black',line='--',errorband=False,sizes=0.0000)

#fancy_plot(ax,svetdf['age'],svetdf['fitradius'],colors='black',line='--',errorband=False,sizes=0.0000)

# legend
legsyms = ['s','d','o'] #square for each band, shape for each grating and for PN
leglabels = ['0.3-8 keV','ACIS (no grating)','ACIS (w/HETG)']
legcolors = ['black','white','white']
legmecs = ['black','black','black']
leg1 = snplt.plot_legend(ax,labels=leglabels,colors=legcolors,markers=legsyms,mecs=legmecs,fontsize='small',location='upper left')

# velocities annotation
v1 = 'v$_{early}='+str(int(round(broadparamdf['v_early'][0])))+'\pm'+str(int(round(broadparamdf['v_early'][1])))+'$ km s$^{-1}$'
v2 = 'v$_{late}~='+str(int(round(broadparamdf['v_late'][0])))+'\pm'+str(int(round(broadparamdf['v_late'][1])))+'$ km s$^{-1}$'
ax.annotate(v1+'\n'+v2,xycoords='figure fraction',textcoords='figure fraction',xy=(0.9,0.1),xytext=(0.5,0.22))
예제 #13
0
    fax[1, 1].plot(t_mat[t_mat['By'] > -9990.0].index,
                   t_mat[t_mat['By'] > -9990.0].By,
                   color=color[trainer],
                   linewidth=2)

if len(t_mat[t_mat['Bz'] > -9990.0]) > 0:
    fax[2, 1].scatter(t_mat[t_mat['Bz'] > -9990.0].index,
                      t_mat[t_mat['Bz'] > -9990.0].Bz,
                      marker=marker[trainer],
                      color=color[trainer])
    fax[2, 1].plot(t_mat[t_mat['Bz'] > -9990.0].index,
                   t_mat[t_mat['Bz'] > -9990.0].Bz,
                   color=color[trainer],
                   linewidth=2)

fancy_plot(fax[0, 0])
fancy_plot(fax[1, 0])
fancy_plot(fax[2, 0])
fancy_plot(fax[0, 1])
fancy_plot(fax[1, 1])
fancy_plot(fax[2, 1])
i = pd.to_datetime("2016/12/21 08:43:12")
offset = pd.to_timedelta('30 minutes')

fax[0, 0].set_ylabel('Np [cm$^{-3}$]', fontsize=20)
fax[1, 0].set_ylabel('Th. Speed [km/s]', fontsize=20)
fax[2, 0].set_ylabel('Flow Speed [km/s]', fontsize=20)
fax[2, 0].set_xlabel('Time [UTC]', fontsize=20)

fax[0, 1].set_ylabel('Bx [nT]', fontsize=20)
fax[1, 1].set_ylabel('By [nT]', fontsize=20)
    ax[0].plot(n.med_l, n.dis, color=d[1], linestyle=d[3], label=d[4])
    ax[1].plot(-s.med_l, 1. - s.dis, color=d[1], linestyle=d[3], label=d[4])

    ax2[j].plot(np.abs(n.med_l), n.dis, color='red', label='Nothern')
    ax2[j].plot(np.abs(s.med_l),
                1. - s.dis,
                color='black',
                linestyle='--',
                label='Southern')
    if ad[-1] < 1.0:
        ax2[j].text(5, .8, 'p(A-D) = {0:5.4f}'.format(ad[-1]), fontsize=18)
    ax2[j].text(5, .75, 'p(KS2) = {0:5.4f}'.format(k2[-1]), fontsize=18)
    ax2[j].set_title(d[4])
    ax2[j].set_xlabel(r"$|$Med. Latitude$|$ [Deg.]")
    ax2[j].set_xlim([0, 90])
    fancy_plot(ax2[j])

    #do the camparision for stable filaments vs no stable
    if i == 'fil1':
        #setup for combined 1 and 2 categories
        d = fil_dict['fil12']
        d[0] = d[0][~d[0].index.duplicated(keep='first')]

        n = d[0][d[0].north == 1]
        s = d[0][d[0].north == 0]
        n = setup_dis(n)
        s = setup_dis(s)

        #setup for combined 1, 2, and 3 categories
        e = fil_dict['fil123']
        e[0] = e[0][~e[0].index.duplicated(keep='first')]
예제 #15
0
def plot_filament_track(i):
    global dat

    dpi = 200
    good, = np.where(dat['track_id'].values == i)

    #get start time of track for filename
    ofname = '{0}_track{1:6d}'.format(dat['event_starttime'][good[0]],
                                      i).replace(' ', '0').replace(':', '_')

    #create figure and add sun
    fig, ax = plt.subplots(figsize=(7, 7), dpi=dpi)
    rs = plt.Circle((0., 0.),
                    radius=1000.,
                    color='gray',
                    fill=False,
                    linewidth=5,
                    zorder=0)
    ax.add_patch(rs)

    #plot track polygons for given id
    for j in good:
        inc = 'red'
        if dat['obs_observatory'].values[j] == 'HA2': inc = 'blue'
        poly = plt.Polygon(loads(dat['hpc_bbox'].values[j]).exterior,
                           color=inc,
                           linewidth=0.5,
                           fill=None)
        ax.add_patch(poly)
#over plot rotation track
#ax = plot_rotation(dat['hpc_coord'].values[j],dat['event_starttime_dt'][j],dat['event_endtime_dt'][j],dat['track_id'].values[j],ax,linestyle='--',dh=12,color='red')

#find other nearby events in time
    nearbyh = 12.  # hours
    nearbya = 10.  # arcsec
    nearstartt = np.abs(dat['event_starttime_dt'][good[0]] -
                        dat['event_endtime_dt']) <= datetime.timedelta(
                            hours=nearbyh)
    nearendt = np.abs(dat['event_endtime_dt'][good[-1]] -
                      dat['event_starttime_dt']) <= datetime.timedelta(
                          hours=nearbyh)

    nearstartp = np.sqrt(
        (dat['meanx'].values[good[0]] - dat['meanx'].values)**2 +
        (dat['meany'].values[good[0]] - dat['meany'].values)**2) <= nearbya
    nearendp = np.sqrt(
        (dat['meanx'].values[good[-1]] - dat['meanx'].values)**2 +
        (dat['meany'].values[good[-1]] - dat['meany'].values)**2) <= nearbya

    #:   nearby, = np.where((nearstartt & nearstartp) | (nearendt & nearendp))
    nearby, = np.where((nearendp & nearendt))
    print dat['meanx'].values[good[-1]]
    print dat['meanx'][nearby]

    #plot within time tracks
    for j in nearby:
        poly = plt.Polygon(loads(dat['hpc_bbox'].values[j]).exterior,
                           color='black',
                           linewidth=0.5,
                           fill=None)
        ax.add_patch(poly)
        ax = plot_rotation(dat['hpc_coord'].values[j],
                           dat['event_starttime_dt'][j],
                           dat['event_endtime_dt'][j],
                           dat['track_id'].values[j],
                           ax,
                           dh=48)


#Setup plots
    fancy_plot(ax)
    ticks = [-1000., -500., 0., 500., 1000.]
    lim = [-1200., 1200.]
    ax.set_xlim(lim)
    ax.set_ylim(lim)
    ax.set_xticks(ticks)
    ax.set_yticks(ticks)
    ax.set_xlabel('Solar X [arcsec]')
    ax.set_ylabel('Solar Y [arcsec]')

    #save fig
    fig.savefig('track_plots/' + ofname,
                bbox_pad=.1,
                bbox_inches='tight',
                dpi=dpi)
    fig.clear()
    plt.close()

    return
예제 #16
0
    fax[0, 0].set_xlim(
        [i - pd.to_timedelta('25 minutes'), i + pd.to_timedelta('25 minutes')])

    fax[0, 0].set_ylabel('Np [cm$^{-3}$]', fontsize=20)
    fax[1, 0].set_ylabel('Th. Speed [km/s]', fontsize=20)
    fax[2, 0].set_ylabel('Flow Speed [km/s]', fontsize=20)
    fax[2, 0].set_xlabel('Time [UTC]', fontsize=20)

    fax[0, 1].set_ylabel('Bx [nT]', fontsize=20)
    fax[1, 1].set_ylabel('By [nT]', fontsize=20)
    fax[2, 1].set_ylabel('Bz [nT]', fontsize=20)
    fax[2, 1].set_xlabel('Time [UTC]', fontsize=20)

    #make fancy plot
    for pax in fax.ravel():
        fancy_plot(pax)
    #ax.set_ylim([300,1000.])
    bfig.savefig(
        '../plots/spacecraft_events/event_{0:%Y%m%d_%H%M%S}_zoom.png'.format(
            i.to_pydatetime()),
        bbox_pad=.1,
        bbox_inches='tight')

    fax[0, 0].set_xlim([
        i - pd.to_timedelta('180 minutes'), i + pd.to_timedelta('180 minutes')
    ])
    bfig.savefig(
        '../plots/spacecraft_events/event_{0:%Y%m%d_%H%M%S}_bigg.png'.format(
            i.to_pydatetime()),
        bbox_pad=.1,
        bbox_inches='tight')
예제 #17
0
def standard_age_plot(df,
                      y,
                      ages='age',
                      gratings=None,
                      simoffsets=None,
                      agemin=4400,
                      agemax=10600,
                      ymin=0.0,
                      ymax=None,
                      plotextras=None,
                      clean=True,
                      color='black',
                      overplot=False,
                      ax=None,
                      symsize=8,
                      ytitle=None,
                      sym='o',
                      yerrlow=None,
                      yerrhigh=None,
                      errinterval=True,
                      ylog=False,
                      errorband=False,
                      line='',
                      linewidth=1,
                      figsize=None,
                      mews=None,
                      mecs=None,
                      alphas=1.0,
                      mealphas=None,
                      linecolor=None,
                      **kwargs):
    """
     Create a standard plot of age vs Y for SN1987A data
     
     Author: Kari A. Frank
     Date: 2015-12-18

     Input

     df : pd.DataFrame
       dataframe containing columns for, at a minimum, observation ages and
       y values
     ages : string
       name of the column in df containing the observation ages
     y : string
       name of the column in df containing the y values to be plotted
     yerrlow, yerrhigh : string
       name of the columns containing the upper and lower errors on y
     errinterval : bool
       if True, then assume errors are the lower and upper endpoints of the 
       error interval and convertthem to error bars before plotting.
     gratings : string
       name of the column in df specifying the gratings used for each 
       observation represented in x (and y). if provided, each grating
       type will be plotted with a different symbol
     simoffsets : string
       name of column in df specifying detector sim offsets for each 
       observation. if provided, the symbol outlines for these 
       observations will be gray instead of the usual black
     agemin,agemax : numerical
       minimum and maximum ages, in days for the x-axis
     ymin, ymax : numerical
       optionally specify the minimum and/or maximum values for the y-axis
     plotextras : string
       comma separated list of names for the extras to plot (passed directly
       to plot_extras)
     clean : bool
       if False, will plot x ticks and a vertical line across the plot at 
       every data point to more easily associate specific observations with 
       a specific data point
     color : string
       specify a color for all the points. to plot with more than one color,
       call this function again with different y and overplot=True.
     overplot : bool
       if True, will skip creating a new figure and just plot the 
       provided x and y on the current figure. must also provide 
       the ax argument.
     ax : axis object
       used only if overplot=True, to make sure it overplotted on 
       the correct axis
     sym : string
       specify the symbol to use (will be ignored if gratings is given)
     symsize : numerical
       specify the size of the symbols (default 8 is good for 
       presentations, use 4 to more clearly see error bars)
     ylog : bool
       plot the y axix on log scale if True (default=False)
     errorband : bool
       if True will plot the errors as a shaded band rather than bars 
       (passed directly to fancy_plot). default=False
     line : string
       format of the line to connect data points. same as in pyplot.plot 
       and fancy_plot. default = '' (no line)
     linewidth : numeric
       width of the line to connect data points. same as in pyplot.plot 
       and fancy_plot. default = 1
     linecolor : string
       color of the line to connect data points. same as in pyplot.plot 
       and fancy_plot. default = None
     figsize : 2-element numerical tuple
       tuple of the form (5,3) to specify the size of the plot in 
       inches (x,y)
     mews : numerical
       passed to fancy_plot to set the markeredge width
     mecs : string
       passed to fancy_plot to set the markeredge color
     alphas : numerical
       passed directly to fancy_plot to set the symbol alpha
     mealphas : numerical
       passed directly to fancy_plot to set the markeredge alpha. default
       is to be the same as the marker (face) alpha
     Notes
     - In future, may add ability to also specify plotting a second 
       column as y values, optionally with a different color and symbols
     - To save the plot to a pdf file, initialize the pdffile before calling
       this function, e.g.:

       from matplotlib.backends.backend_pdf import PdfPages
       pdffile = PdfPages(plotfile)
       
       and close it afterwards:
       pdffile.savefig()
       plt.close()
       pdffile.close()

     """

    #----Set up symbols----
    if gratings is not None:
        df['symbols'] = 'd'
        # change according to grating
        df.loc[(df[gratings].values == 'HETG'), 'symbols'] = 'o'
        df.loc[(df[gratings].values == 'LETG'), 'symbols'] = '*'

    #----Set up marker edge colors and widths----
    if mews is None:
        df['mews'] = 0.5
    else:
        df['mews'] = mews
    if mecs is None:
        df['mecs'] = color
    else:
        df['mecs'] = mecs
    if mealphas is None:
        mealphas = alphas
#     if simoffsets is not None:
#          # make sure column is strings
#          df[simoffsets] = pd.Series([str(off) for off in df[simoffsets]])
#          df['mecs'][df[simoffsets] == '-8.42'] = 'gray'
#     mecs = df['mecs'].values

#----Set plot fonts----
    set_plot_fonts()

    #----Initialize Plot----
    if overplot is False:
        if ytitle is None:
            ytitle = y  # label it with the column name
        fig, ax1 = start_plot(xtitle='SN1987A Age [days]',
                              ytitle=ytitle,
                              xmin=agemin,
                              xmax=agemax,
                              ymin=ymin,
                              ymax=ymax,
                              ylog=ylog,
                              clean=clean,
                              figsize=figsize)
    else:
        ax1 = ax

    #----Drop rows with missing y data----
    df = df.dropna(subset=[y])

    if gratings is not None:
        sym = df['symbols'].values

    #----Convert Error Intervals to Error Bars----
    if errinterval is True:
        if yerrlow is not None:
            yerrlow = df[y] - df[yerrlow]
        if yerrhigh is not None:
            yerrhigh = df[yerrhigh] - df[y]
    else:
        if yerrlow is not None:
            yerrlow = df[yerrlow]
        if yerrhigh is not None:
            yerrhigh = df[yerrhigh]

    #----Plot the data----
    fancy_plot(ax1,
               df[ages],
               df[y],
               yerror=yerrlow,
               yerror_high=yerrhigh,
               syms=sym,
               mecs=df['mecs'].values,
               mews=df['mews'].values,
               line=line,
               linewidth=linewidth,
               errorband=errorband,
               colors=color,
               sizes=symsize,
               linealpha=1.0,
               bandalpha=0.1,
               alphas=alphas,
               ealphas=mealphas,
               mealphas=mealphas)

    #----Plot Extras----
    if plotextras is not None:
        plot_extras(names=plotextras)

    #----Plot Legend----
    # if overplotting, then need to plot the legend separately after all
    # calls to standard_age_plot
#     plot_legend(labels=leglabels,colors=legcolors,markers=legsyms,mecs=legmecs,
#                mews=legmews,fontsize='small')

#----Plot Top Year Axis---
    if overplot is False:
        top_year_axis(ax1, agemin=agemin, agemax=agemax)

    #----Return----
    if overplot is False:
        return fig, ax1
    else:
        return None
예제 #18
0
def test_dtw_example():
    """
    Test using code
    """
    #Wind to get DTW solution
    window = pd.to_timedelta(1. * 3600., unit='s')

    #Setup format for datetime string to pass to my_dtw later
    dfmt = '{0:%Y/%m/%d %H:%M:%S}'

    #twind4 = pd.to_datetime('2016/12/09 04:45:29')
    #start_t4 = dfmt.format(twind4-2.5*window)
    #end_t4 = dfmt.format(twind4+3.5*window)
    twind4 = pd.to_datetime('2016/12/21 08:43:12')
    start_t4 = dfmt.format(twind4 - 2.5 * window)
    end_t4 = dfmt.format(twind4 + 3.5 * window)
    #my_dtw4 = mtr.dtw_plane(start_t4,end_t4,nproc=4,penalty=True,events=7,earth_craft=['THEMIS_B'],par=['Bt'],speed_pen=500,mag_pen=100.2)
    my_dtw4 = mtr.dtw_plane(start_t4,
                            end_t4,
                            nproc=4,
                            penalty=True,
                            events=7,
                            par=['Bt'],
                            earth_craft=['THEMIS_B'],
                            speed_pen=500,
                            mag_pen=100.2)
    my_dtw4.init_read()
    my_dtw4.iterate_dtw()

    #my_dtw4.pred_earth()
    #mtr.omni_plot(my_dtw4)

    sc1 = 'Wind'
    sc2 = 'SOHO'

    x1 = np.array(my_dtw4.plsm[sc1].SPEED.ffill().bfill().values,
                  dtype=np.double)
    x2 = np.array(my_dtw4.plsm[sc2].SPEED.ffill().bfill().values,
                  dtype=np.double)

    #Example DTW plot
    p1, p2, cost1 = md.dtw_path_single(x1, x2, 300, 30, 500.0, 0.0, 0.5, 1)
    #p1,p2,cost = md.dtw_path_single(x2,x2],2700,2700/2,0.0,0.01,1)
    #mlpy example path
    dist, costa, path = mlpy.dtw_std(x1, x2, dist_only=False)
    pa, pb = path[0], path[1]

    #create multi panel diagnostic plot 2018/11/26 J. Prchlik
    fig, ax = plt.subplots(nrows=2,
                           ncols=2,
                           gridspec_kw={
                               'height_ratios': [2, 1],
                               'width_ratios': [1, 2]
                           },
                           figsize=(8, 8))
    fig.subplots_adjust(hspace=0.05, wspace=0.05)
    #turn off bottom left axis
    ax[1, 0].axis('off')
    lims = mdates.date2num([
        my_dtw4.plsm[sc1].index.min(), my_dtw4.plsm[sc1].index.max(),
        my_dtw4.plsm[sc2].index.min(), my_dtw4.plsm[sc2].index.max()
    ])
    v_max, v_min = np.percentile(costa, [95, 15])
    ax[0, 1].imshow(costa,
                    extent=lims,
                    origin='lower',
                    cmap=plt.cm.gray.reversed(),
                    vmin=v_min,
                    vmax=v_max,
                    aspect='auto')
    #ax.imshow(cost,extent=[0,x2.size,0,x2[::2].size],origin='lower')
    ax[0, 1].plot(my_dtw4.plsm[sc1].iloc[p1, :].index,
                  my_dtw4.plsm[sc2].iloc[p2, :].index,
                  '--',
                  color='black')
    ax[0, 1].plot(my_dtw4.plsm[sc1].iloc[pa, :].index,
                  my_dtw4.plsm[sc2].iloc[pb, :].index,
                  '-',
                  color='red')
    ax[0, 1].xaxis_date()
    ax[0, 1].yaxis_date()
    date_format = mdates.DateFormatter('%H:%M')

    #plot the plasma values on the off axes
    ax[1, 1].plot(my_dtw4.plsm[sc1].index, x1, color='blue')
    ax[0, 0].plot(x2, my_dtw4.plsm[sc2].index, color='teal')

    #set up axis formats
    ax[1, 1].xaxis_date()
    ax[0, 0].yaxis_date()

    #force limits to be the same as the cost matrxi
    ax[1, 1].set_xlim(lims[:2])
    ax[0, 0].set_ylim(lims[2:])

    #Format the printed dates
    ax[1, 1].xaxis.set_major_formatter(date_format)
    ax[0, 0].yaxis.set_major_formatter(date_format)

    #Add label time
    ax[1, 1].set_xlabel(sc1 + ' Time [UTC]')
    ax[0, 0].set_ylabel(sc2 + ' Time [UTC]')

    #Add label for Speeds
    ax[1, 1].set_ylabel('Flow Speed [km/s]')
    ax[0, 0].set_xlabel('Flow Speed [km/s]')

    #turn off y-tick labels in center plot
    ax[0, 1].set_xticklabels([])
    ax[0, 1].set_yticklabels([])

    #set Wind and SOHO to have the same plasma paramter limits
    pls_lim = [420., 675.]
    ax[0, 0].set_xlim(pls_lim)
    ax[1, 1].set_ylim(pls_lim)

    #copy y-axis labels from Wind plot to SOHO plot
    ax[0, 0].set_xticks(ax[1, 1].get_yticks())
    ax[0, 0].set_xlim(pls_lim)
    ax[1, 1].set_ylim(pls_lim)
    ##ax[0,0].set_xlabel('Flow Speed [km/s]')

    #clean up the axes with plasma data
    fancy_plot(ax[0, 0])
    fancy_plot(ax[1, 1])

    # This simply sets the x-axis data to diagonal so it fits better.
    #fig.autofmt_xdate()
    fig.savefig('../plots/example_dtw_path.png',
                bbox_pad=.1,
                bbox_inches='tight')
    fig.savefig('../plots/example_dtw_path.eps',
                bbox_pad=.1,
                bbox_inches='tight')
    return x1, x2, my_dtw4
예제 #19
0
def create_fc_grid_plot(fcs,waeff=3.8e6,log_plot=False,ylim=None):
    """
    Plot multiple FC on one grid of plots

    Parameters
    ----------
    fcs: dictionary
        Dictionary of FC measurements
    waeff: float, optional
        Effective array of FC  (Default = 3.8e6 #cm^3/km, Wind). This only comes into effect
        if a 'cont' keyword does not exist in the fcs dictionary. The 'cont' keyword will exist if 
        read in the observations using the read_fmt_obs module.
    log_plot: boolean
        Plot the velocity distributions in log space (Default = False)
    ylim: list
        A two value list to set the plot limits (Default = None). The first component is 
        the minimum value, while the last component is the maximum value.

    Return
    -------
    fig, ax: Figure Object, Axis Object
        The created plots figure and axis objects
    """




    #elemetary charge
    q0  = 1.6021892e-7 # picocoulombs


    #create a square as possible plot
    nrows = int(np.sqrt(len(fcs.keys())))
    ncols = len(fcs.keys())/nrows
    #add an extra column if needed
    if nrows*ncols < len(fcs.keys()): 
        ncols += 1
       
    
    #create figure to plot
    fig, axs = plt.subplots(ncols=ncols,nrows=nrows,sharex=True,sharey=True,figsize=(3*ncols,3*nrows))
    fig.subplots_adjust(wspace=0.01,hspace=0.01)
    counter = 0
    for k,ax in zip(range(len(fcs.keys())),axs.ravel()):
        key = 'fc_{0:1d}'.format(k)

        #first column of x_measure is the velocity grid
        grid_v = fcs[key]['x_meas'][0,:]
        dv    =  fcs[key]['x_meas'][1,:]

        #check to see if a constant value is already defined fcs dictionary
        if 'cont' in fcs[key]:
            #Switching to constant value that is in the fcs dictionary
            cont = fcs[key]['cont'].ravel()
        #Otherwise set a constant value equal using the constant effective area used above
        else:
            cont  = 1.e12/(waeff*q0*dv*grid_v)


        #sort by the velocity values when plotting
        sort = np.argsort(grid_v)

        #removed to test improving Gaussian fit
        #add checks to plot only variables that are defined
        #Plot best fit model
        if 'dis_cur' in fcs[key]:
            ax.plot(grid_v[sort],fcs[key]['dis_cur'].ravel()[sort]*cont,label='Best Mod.',color='black',linewidth=3)
        #Plot measurements from the FC
        if 'rea_cur' in fcs[key]:
            ax.plot(grid_v[sort].ravel(),fcs[key]['rea_cur'].ravel()[sort]*cont,'-.b',label='Input',linewidth=3)
        #plot error in measurements
        if 'unc' in fcs[key]:
            ax.errorbar(grid_v[sort],fcs[key]['rea_cur'].ravel()[sort]*cont,yerr=fcs[key]['unc'][sort]*cont,fmt='o',label=None,color='blue')
        
        #ax.plot(grid_v,rea_cur.ravel()*cont,'-.b',label='Input',linewidth=3)
        if 'init_guess' in fcs[key]:
            ax.plot(grid_v[sort],fcs[key]['init_guess'].ravel()[sort]*cont,':',color='purple',label='Init. Guess',linewidth=3)
        ax.text(0.05,0.8,'$\Phi$={0:2.1f}$^\circ$\n$\Theta$={1:2.1f}$^\circ$'.format(*np.degrees(fcs[key]['x_meas'][[2,3],0])),transform=ax.transAxes)
        #ax.plot(grid_v, gaus(grid_v,*popt),'--',marker='o',label='Gauss Fit',linewidth=3)
        fancy_plot(ax)

        #set the scale to log if log keyword set
        if log_plot:
            ax.set_yscale('log')

        #set the y-limit to the ylim if the value is set
        if ylim is not None:
            ax.set_ylim(ylim)



        #only plot x-label if in the last row
        if counter >= (nrows-1)*(ncols):
           ax.set_xlabel('Speed [km/s]')
        #set ylabel on the left edge
        if np.isclose(float(counter)/ncols - int(counter/ncols),0):
            ax.set_ylabel('p/cm$^{-3}$/(km/s)')
        #put legend only on the first plot
        if counter == 0:
            ax.legend(loc='best',frameon=False)
        counter += 1

    #Need to put this outside loop
    #pad 20% x-lim for angle labels on plot
    x_lim = np.array(ax.get_xlim())
    x_lim[0] -= 0.2*(x_lim[1]-x_lim[0])
    ax.set_xlim(x_lim)

    return fig,axs
예제 #20
0
fig, ax = snplt.standard_age_plot(broaddf,
                                  'R0',
                                  ytitle='Radius [arcsec]',
                                  yerrlow='R0errl',
                                  yerrhigh='R0erru',
                                  errinterval=False,
                                  gratings='grating',
                                  ymin=ymin,
                                  ymax=ymax,
                                  agemin=agemin,
                                  agemax=agemax)

fancy_plot(ax,
           fitdf['age'],
           fitdf['radius'],
           colors='black',
           line='-',
           errorband=False,
           sizes=0.0000)
#fancy_plot(ax,fit2df['age'],fit2df['radius'],colors='black',line='--',errorband=False,sizes=0.0000)

#fancy_plot(ax,svetdf['age'],svetdf['fitradius'],colors='black',line='--',errorband=False,sizes=0.0000)

# legend
legsyms = ['s', 'd',
           'o']  #square for each band, shape for each grating and for PN
leglabels = ['0.3-8 keV', 'ACIS (no grating)', 'ACIS (w/HETG)']
legcolors = ['black', 'white', 'white']
legmecs = ['black', 'black', 'black']
leg1 = snplt.plot_legend(ax,
                         labels=leglabels,
예제 #21
0
def plot_extras(names='all',agemin=4000,agemax=11000):
	"""
	Author: Kari A. Frank
	Date: September 22, 2015
	Purpose: Plot lines on already open age vs Y plots (where Y is 
	      typically either radius or flux

	Input:
	 names : string
	     comma separated list of names of which extras to plot. 
	     default = 'all'. options are:
	     'plait1995'- plots position and width of the ER from 
	          Plait1995 (in this case Y must be radius)
	     'ng2013' - plots the radio break age day=7600 from the 
	          Ng2013 torus fits to radio images, as vertical line
	     'sugarman2002' - plots location of the ring from Sugarman 2002 
	          (in this case Y must be radius)
	     'hotspots' - plots the radius and day of appearance for the 
	          HST hot spots in Sugarman 2002
	     'larsson2014' - plots the age of transition from radioactive 
	         decay to X-ray heating as inner debris energy source
	      'chandrabroadbreak' - plot as vertical line the best fit 
	           age of the break point in expansion curve
	      'plaitwidth' - plot distance from chandrabroadbreak radius 
	           to width of plait ring

	Output:
	 - plots to an already open plot

	Usage Notes:
	 - will not add anything to the plot legend
	"""

        dummy_y = [0.00000001,1000.] #dummy y values for vertical lines
        dummy_sym = '.'
        
        if names == 'all' or 'hotspots' in names:
                # hot spot appearances in HST, Sugarman2002 table 1
                hotspot_ages = [2933,4283,4337,4337,4440,4440,4440,4725,
				4816,4816,4999,4999]
                hotspot_radii = [0.56,0.673,0.607,0.702,0.565,0.697,0.707,
				 0.607,0.535,0.629,0.531,0.713]

                fancy_plot(hotspot_ages,hotspot_radii,syms='*',
			   colors='white')
                #        legcolors+=['white'] #marker will look like border only
                #        leglabels+=['HST Hot Spots']
                #        legmecs+=['black']
                #        legmews+=[0.5]
                #        legsyms+=['*']

        if names == 'all' or 'larsson2014' in names:
                #Larsson2013 -- inner debris (HST) morphology transitioned 
		#  from core to edge-brightened due to
                #  energy source shifting from radioactive decay to X-ray 
		#  illumination
                debris_transition_age = [5500,5500] 
                debris_transition_radius = dummy_y#plot vertical line

                fancy_plot(debris_transition_age,debris_transition_radius,
			   colors='black',line='--',syms=dummy_sym)
                #legcolors+=[None] #marker will look like border only
                #leglabels+=['Debris Transition']
                #legmecs+=[None]
                #legmews+=[0.]
                #legsyms+=[None]

        if names == 'all' or 'plait1995' in names:
                # Width and location of optical ring from UV flash, 
		#  Plait1995
                # plot horizontal band
                plaitwidth = np.array([0.121/2.0,0.121/2.0])
                plait_radii = [0.86,0.86]
                plait_ages = [agemin,agemax]
                fancy_plot(plait_ages,plait_radii,colors='gray',
			   syms=dummy_sym,errorband=True,yerror=plaitwidth)

        if names == 'all' or 'plaitwidth' in names:
                # width of Plait ring, from chandra break point
                plaitwidth = np.array([0.121/2.0,0.121/2.0])
                plait_ages = [-1.0,20000.0]
                chandrabreakradii = [0.73+0.121/2.0,0.73+0.121/2.0]
                fancy_plot(plait_ages,chandrabreakradii,colors='purple',
			   syms=dummy_sym,errorband=True,yerror=plaitwidth)
                
        if names == 'all' or 'sugarman2002' in names:
                # Location of ring from Sugarman2002 (table 3)
                sugarman_radii = [0.829,0.829]
                sugarman_ages = [agemin,agemax]
                fancy_plot(plait_ages,plait_radii,colors='gray',
			   syms=dummy_sym,errorband=True,yerror=plaitwidth)
                
        if names == 'all' or 'ng2013' in names:
                #Ng2013 Radio expansion measurements: using the torus 
		#  model found the following all around day 7600:
                # - break in expansion (decrease in velocity)
                # - break in torus opening angle, from constant ~40deg 
		#   to decreasing
                # - break in asymmetry; the morphology was ~40% asymmetric,
		#   but became steadily more symmetric at the break
                # - break in the light curve; the slope flattened, 
		#   deviating from previous exponential growth
                radiobreak_radii = dummy_y #plot vertical line
                radiobreak_age = [7600,7600]

                fancy_plot(radiobreak_age,radiobreak_radii,syms=dummy_sym,
			   colors='black',line=':')

        if names == 'all' or 'chandrabroadbreak' in names:
                # plot best fit age of the break in expansion from the 
		#  300-8000 chandra images
                chandrabreak_radii = dummy_y #plot vertical line
                chandrabreak_age = [5962.77,5962.77]

                fancy_plot(chandrabreak_age,chandrabreak_radii,
			   syms=dummy_sym,colors='black',line='--')

        if (names == 'all' or 'ng2013radii' in names or 'ng2013fluxes' 
	    in names):
            ngradiifile = ('/astro/research/kaf33/Dropbox/Research/SN1987A'
			   '/ng2013_ring_radii.txt')
            ng2013_ringfits = pd.read_table(ngradiifile,comment='#',
					    header=0,names=
					    ['age','flux','fluxerr','majorradius',
					     'majorradiuserr','minorradius',
					     'minorradiuserr','asymmetry',
					     'asymmetryerr','phi','phierr','chi2',
					     'dof'],index_col=False)
             # columns: age(index)	     	flux	fluxerr		majorradius	majorradiuserr	minorradius	minorradiuserr	asymmetry	asymmetryerr	phi	phierr	chi2 dof                        
                
        if names == 'all' or 'ng2013radii' in names:

#             plt.plot(ng2013_ringfits['age'],ng2013_ringfits[])
            fancy_plot(np.array(ng2013_ringfits['age']),
		       np.array(ng2013_ringfits['majorradius']),
		       yerror=np.array(ng2013_ringfits['majorradiuserr']),
		       colors='black',syms='x')
            fancy_plot(np.array(ng2013_ringfits['age']),
		       np.array(ng2013_ringfits['minorradius']),
		       yerror=np.array(ng2013_ringfits['minorradiuserr']),
		       colors='black',syms='x')
    
        if names == 'all' or 'ng2013fluxes' in names:
            ngradiifile = '~/Dropbox/Research/SN1987A/ng2013_ring_radii.txt'
            ng2013_ringfits = pd.read_table(ngradiifile,comment='#',
					    header=0,names=
					    ['age','flux','fluxerr','majorradius',
					     'majorradiuserr','minorradius',
					     'minorradiuserr','asymmetry',
					     'asymmetryerr','phi','phierr','chi2',
					     'dof'],index_col=False)
             # columns: age(index)	     	flux	fluxerr		majorradius	majorradiuserr	minorradius	minorradiuserr	asymmetry	asymmetryerr	phi	phierr	chi2 dof

#             plt.plot(ng2013_ringfits['age'],ng2013_ringfits[])
            fancy_plot(np.array(ng2013_ringfits['age']),
		       np.array(ng2013_ringfits['flux']/3.0),
		       yerror=np.array(ng2013_ringfits['fluxerr']),
		       colors='black',syms='x')
예제 #22
0
shock_df['counts'] = 1

#Resample at one month using the mean
df_bin = shock_df.resample('A').sum()
df_spb = sunsp_df.resample('A').sum()
df_cme = cmect_df.resample('A').sum()

fig, ax = plt.subplots(figsize=(24, 8), ncols=2)

ax[0].scatter(df_bin.index[1:], df_bin.counts[1:], color='black')
ax[0].scatter(df_cme.index, df_cme.counts, color='red', marker='D')
ax[0].scatter(df_cme.index, df_cme.h_cnts, color='blue', marker='s')
ax[0].plot(df_spb.index[1:], df_spb.SN[1:] * 2., color='black')
ax[0].set_ylabel('Number of Shock Events')
ax[0].set_xlabel('Year')
fancy_plot(ax[0])
ax[0].set_xlim([datetime(1995, 1, 1), datetime(2017, 1, 1)])

ax[1].scatter(df_bin.counts[1:], df_spb.SN[1:], color='black')
ax[1].scatter(df_bin.counts[1:], df_cme.counts, color='red', marker='D')
ax[1].scatter(df_bin.counts[1:], df_cme.h_cnts, color='blue', marker='s')
ax[1].set_xlabel('Number of Shock Events')
ax[1].set_ylabel('Number of Sun Spots')

r, p = pearsonr(df_bin.counts[1:], df_cme.h_cnts)
print r, p
ax[1].text(3000., 2000., 'r={0:4.3f}'.format(r))
fancy_plot(ax[1])

plt.show()
예제 #23
0
def standard_age_plot(df,y,ages='age',gratings=None,simoffsets=None,
                      agemin=4400,agemax=10600,ymin=0.0,ymax=None,
                      plotextras=None,clean=True,color='black',
                      overplot=False,ax=None,symsize=8,ytitle=None,
                      sym='o',yerrlow=None,yerrhigh=None,errinterval=True,
                      ylog=False,errorband=False,line='',linewidth=1,
                      figsize=None,mews=None,mecs=None,alphas=1.0,
                      mealphas=None,linecolor=None,
                      **kwargs):
     """
     Create a standard plot of age vs Y for SN1987A data
     
     Author: Kari A. Frank
     Date: 2015-12-18

     Input

     df : pd.DataFrame
       dataframe containing columns for, at a minimum, observation ages and
       y values
     ages : string
       name of the column in df containing the observation ages
     y : string
       name of the column in df containing the y values to be plotted
     yerrlow, yerrhigh : string
       name of the columns containing the upper and lower errors on y
     errinterval : bool
       if True, then assume errors are the lower and upper endpoints of the 
       error interval and convertthem to error bars before plotting.
     gratings : string
       name of the column in df specifying the gratings used for each 
       observation represented in x (and y). if provided, each grating
       type will be plotted with a different symbol
     simoffsets : string
       name of column in df specifying detector sim offsets for each 
       observation. if provided, the symbol outlines for these 
       observations will be gray instead of the usual black
     agemin,agemax : numerical
       minimum and maximum ages, in days for the x-axis
     ymin, ymax : numerical
       optionally specify the minimum and/or maximum values for the y-axis
     plotextras : string
       comma separated list of names for the extras to plot (passed directly
       to plot_extras)
     clean : bool
       if False, will plot x ticks and a vertical line across the plot at 
       every data point to more easily associate specific observations with 
       a specific data point
     color : string
       specify a color for all the points. to plot with more than one color,
       call this function again with different y and overplot=True.
     overplot : bool
       if True, will skip creating a new figure and just plot the 
       provided x and y on the current figure. must also provide 
       the ax argument.
     ax : axis object
       used only if overplot=True, to make sure it overplotted on 
       the correct axis
     sym : string
       specify the symbol to use (will be ignored if gratings is given)
     symsize : numerical
       specify the size of the symbols (default 8 is good for 
       presentations, use 4 to more clearly see error bars)
     ylog : bool
       plot the y axix on log scale if True (default=False)
     errorband : bool
       if True will plot the errors as a shaded band rather than bars 
       (passed directly to fancy_plot). default=False
     line : string
       format of the line to connect data points. same as in pyplot.plot 
       and fancy_plot. default = '' (no line)
     linewidth : numeric
       width of the line to connect data points. same as in pyplot.plot 
       and fancy_plot. default = 1
     linecolor : string
       color of the line to connect data points. same as in pyplot.plot 
       and fancy_plot. default = None
     figsize : 2-element numerical tuple
       tuple of the form (5,3) to specify the size of the plot in 
       inches (x,y)
     mews : numerical
       passed to fancy_plot to set the markeredge width
     mecs : string
       passed to fancy_plot to set the markeredge color
     alphas : numerical
       passed directly to fancy_plot to set the symbol alpha
     mealphas : numerical
       passed directly to fancy_plot to set the markeredge alpha. default
       is to be the same as the marker (face) alpha
     Notes
     - In future, may add ability to also specify plotting a second 
       column as y values, optionally with a different color and symbols
     - To save the plot to a pdf file, initialize the pdffile before calling
       this function, e.g.:

       from matplotlib.backends.backend_pdf import PdfPages
       pdffile = PdfPages(plotfile)
       
       and close it afterwards:
       pdffile.savefig()
       plt.close()
       pdffile.close()

     """
     
     #----Set up symbols----
     if gratings is not None:
        df['symbols'] = 'd'
        # change according to grating
        df.loc[(df[gratings].values=='HETG'),'symbols']='o'
        df.loc[(df[gratings].values=='LETG'),'symbols']='*'
            
     #----Set up marker edge colors and widths----
     if mews is None:
         df['mews'] = 0.5
     else:
         df['mews'] = mews
     if mecs is None:
         df['mecs'] = color
     else:
         df['mecs'] = mecs
     if mealphas is None:
         mealphas = alphas
#     if simoffsets is not None:
#          # make sure column is strings
#          df[simoffsets] = pd.Series([str(off) for off in df[simoffsets]])
#          df['mecs'][df[simoffsets] == '-8.42'] = 'gray'
#     mecs = df['mecs'].values

     #----Set plot fonts----
     set_plot_fonts()

     #----Initialize Plot----
     if overplot is False:
        if ytitle is None:
           ytitle = y # label it with the column name
        fig,ax1 = start_plot(xtitle = 'SN1987A Age [days]',ytitle=ytitle,
                         xmin=agemin,xmax=agemax,ymin=ymin,ymax=ymax,
                         ylog=ylog,clean=clean,figsize=figsize)
     else:
        ax1 = ax

     #----Drop rows with missing y data----
     df = df.dropna(subset=[y])

     if gratings is not None:
         sym = df['symbols'].values

     #----Convert Error Intervals to Error Bars----
     if errinterval is True:
        if yerrlow is not None:
            yerrlow = df[y] - df[yerrlow]
        if yerrhigh is not None: 
            yerrhigh = df[yerrhigh] - df[y]
     else:
        if yerrlow is not None:
            yerrlow = df[yerrlow]
        if yerrhigh is not None:
            yerrhigh = df[yerrhigh]

     #----Plot the data----
     fancy_plot(ax1,df[ages],df[y],yerror=yerrlow,yerror_high=yerrhigh,
                syms=sym,mecs=df['mecs'].values,mews=df['mews'].values,
                line=line,linewidth=linewidth,errorband=errorband,
                colors=color,sizes=symsize,linealpha=1.0,bandalpha=0.1,
                alphas=alphas,ealphas=mealphas,mealphas=mealphas)


     #----Plot Extras----
     if plotextras is not None:
          plot_extras(names=plotextras)

     #----Plot Legend----
     # if overplotting, then need to plot the legend separately after all
     # calls to standard_age_plot
#     plot_legend(labels=leglabels,colors=legcolors,markers=legsyms,mecs=legmecs,
#                mews=legmews,fontsize='small')
     
     #----Plot Top Year Axis---
     if overplot is False:
          top_year_axis(ax1,agemin=agemin,agemax=agemax)

     #----Return----
     if overplot is False:
        return fig,ax1
     else:
        return None
예제 #24
0
def plot_a(ax,age,flux,flux_low,flux_high,syms='o',colors='b',sizes=4,alphas=1,mecs='black'):        
    elow,ehigh = ebars(flux,flux_low,flux_high)
    fancy_plot(age,flux,yerror=elow,yerror_high=ehigh,syms=syms,colors=colors,sizes=sizes,alphas=alphas,mecs=mecs)
예제 #25
0
    alphas = [1.0]*nobs

print 'Markers Defined'

#----Set Up Plot File----
#pdffile = PdfPages(args.plotfile)

#with PdfPages(args.plotfile) as pdffile:

#----R0 vs age----

#--Initialize Plot--
ax1 = start_plot(xtitle='SN1987A Age [days]',ytitle='Radius [arcsec]',xmin=args.agemin,xmax=args.agemax,ymin=rmin,ymax=rmax)

#----Plot----
fancy_plot(fitdata['age'],fitdata['R0'],yerror=fitdata['R0errl'],yerror_high=fitdata['R0erru'],syms=syms,colors=colors,sizes=sizes,alphas=alphas,mecs=mecs,mews=mews,errorband=False)

#----Plot Legend----
plot_legend(labels=leglabels,colors=legcolors,markers=legsyms,mecs=legmecs,mews=legmews,fontsize='small')

#--set top axis--
set_axis(ax1,x=topx,twin=True,title=toptitle,xlab=toplab)

#--save and close plot--
plt.show()
#pdffile.savefig()
#plt.close()

print 'Radius vs Age plotted'

#---------------------------------------