示例#1
0
def plot_mesh(df):
    """
    Plot the FEM mesh from a .dsp file. Uses get_maxwell_boundary_data. May be slow for large files.
    :param df: File path of the FEM mesh.
    :return: None
    """
    # Load the data file
    elements, nodes, elem_solution, bounding_box = get_maxwell_boundary_data(df)

    # Detect what the orientation of this plane is:
    constant_coordinate = [len(unique(diff(nodes[:,k])))==1 for k in range(3)]

    # Select the non-constant coordinates:
    plot_coords = arange(0,3)[logical_not(constant_coordinate)]
    axes_labels = array(['x', 'y', 'z'])[logical_not(constant_coordinate)]

    # Filter out the repeating sequence 2, 3, 3, 0, 6 !! CAREFUL !! may be source of error
    structured_elements = delete(elements, concatenate((where(elements==0)[0], where(elements==0)[0]-3,
                                                        where(elements==0)[0]-2, where(elements==0)[0]-1,
                                                        where(elements==0)[0]+1)))[2:]
    # Each element consists of 6 points
    structured_elements = structured_elements.reshape((int(structured_elements.shape[0]/6), 6))

    plt.figure(figsize=(7.,5.))
    plt.title("Mesh elements for {:s}".format(os.path.split(df)[-1]))
    plt.plot(nodes[:,plot_coords[0]], nodes[:,plot_coords[1]], '.k', alpha=0.5)

    color.cycle_cmap(structured_elements.shape[0], cmap=plt.cm.Spectral)

    # Plot the mesh
    x = nodes[structured_elements-1,plot_coords[0]]
    y = nodes[structured_elements-1,plot_coords[1]]

    # Get the center of mass of each element
    xc = mean(x, axis=1)
    yc = mean(y, axis=1)

    for k in range(structured_elements.shape[0]):
        plt.plot([x[k,p] for p in [0,2,5,0]], [y[k,p] for p in [0,2,5,0]])

    plt.xlabel("{} (mm)".format(axes_labels[0]))
    plt.ylabel("{} (mm)".format(axes_labels[1]))

    # Make sure that the prefactors are right in + and - cases.
    #plt.xlim(array([0.95, 1.05])[int(np.min(x)<0)]*np.min(x),
    #         array([0.95, 1.05])[int(np.max(x)>0)]*np.max(x))
    #plt.ylim(array([0.95, 1.05])[int(np.min(y)<0)]*np.min(y),
    #         array([0.95, 1.05])[int(np.max(y)>0)]*np.max(y))

    plt.xlim(bounding_box[0], bounding_box[1])
    plt.ylim(bounding_box[2], bounding_box[3])
示例#2
0
def mkcirclepoints(z=2.0,
                   avrange=[0.0, 2.0],
                   colorselect=[0, 1],
                   source='hsiao',
                   **plotargs):
    import numpy as np
    from matplotlib import pyplot as pl
    from mpltools import color
    from matplotlib import cm
    import sncosmo
    from sncosmohst import hstbandpasses, ccsnmodels

    # load the O'Donnell 1994 dust model
    dust = sncosmo.OD94Dust()
    sn = sncosmo.Model(source='hsiao',
                       effects=[dust],
                       effect_names=['host'],
                       effect_frames=['rest'])

    avsteps = np.arange(avrange[0], avrange[1], 0.05)
    color.cycle_cmap(length=len(avsteps), cmap=cm.jet)

    f127m, f139m, f153m = [], [], []
    f125w, f140w, f160w = [], [], []
    for av in avsteps:
        sn.set(z=z, t0=0, hostr_v=3.1, hostebv=av / 3.1)
        f127m.append(sn.bandmag('wfc3f127m', 'ab', 0.))
        f139m.append(sn.bandmag('wfc3f139m', 'ab', 0.))
        f153m.append(sn.bandmag('wfc3f153m', 'ab', 0.))
        f125w.append(sn.bandmag('wfc3f125w', 'ab', 0.))
        f140w.append(sn.bandmag('wfc3f140w', 'ab', 0.))
        f160w.append(sn.bandmag('wfc3f160w', 'ab', 0.))
    med = np.array([f127m, f139m, f153m])
    broad = np.array([f125w, f140w, f160w])
    color = med - broad
    pl.plot(color[colorselect[0]], color[colorselect[1]], **plotargs)

    colorlabel = ['F127M-F125W', 'F139M-F140W', 'F153M-F160W']
    ax = pl.gca()
    ax.set_xlabel(colorlabel[colorselect[0]])
    ax.set_ylabel(colorlabel[colorselect[1]])

    labelcolors = ['darkmagenta', 'teal', 'darkorange']

    colorlabel = ['F127M-F125W', 'F139M-F140W', 'F153M-F160W']
    ax = pl.gca()
    ax.set_xlabel(colorlabel[colorselect[0]],
                  color=labelcolors[colorselect[0]])
    ax.set_ylabel(colorlabel[colorselect[1]],
                  color=labelcolors[colorselect[1]])
示例#3
0
def plot_redshift_circle(z_range=[1.8, 2.2],
                         tobs=0,
                         medbandx='f139m',
                         medbandy='f127m',
                         source='salt2',
                         coloredaxislabels=True,
                         **plotargs):
    """  plot a color-color circle showing how the position of a SNIa in
    color-color space changes with redshift, using markers color-coded by z.
    :param z_range:
    :param tobs:
    :param medbandx:
    :param medbandy:
    :param source:
    :param coloredaxislabels:
    :param plotargs:
    :return:
    """
    from mpltools import color
    from matplotlib import cm
    from copy import copy

    plotargs10 = copy(plotargs)
    plotargs10.update(mec='w', marker='D', zorder=1000, ms=10)

    zsteps = np.arange(z_range[0], z_range[1] + 0.01, 0.01)
    color.cycle_cmap(length=len(zsteps), cmap=cm.jet)
    for z in zsteps:
        sn = sncosmo.Model(source=source)
        sn.set(z=z, t0=0)
        widebandx = medband_matching_filter(medbandx)
        widebandy = medband_matching_filter(medbandy)

        colorx = sn.bandmag(medbandx, 'ab', tobs) - sn.bandmag(
            widebandx, 'ab', tobs)
        colory = sn.bandmag(medbandy, 'ab', tobs) - sn.bandmag(
            widebandy, 'ab', tobs)

        if (int(np.round(z * 100)) % 10) == 0:
            pl.plot(colorx, colory, **plotargs10)
        else:
            pl.plot(colorx, colory, **plotargs)

    ax = pl.gca()
    ax.set_xlabel('%s - %s' % (medbandx.upper(), widebandx.upper()))
    ax.set_ylabel('%s - %s' % (medbandy.upper(), widebandy.upper()))
    return (ax)
示例#4
0
文件: stone.py 项目: srodney/medband
def plotzpoints(sn,simIa,dz=0.1):
    """  plot the
    :param sn:
    :param simIa:
    :param dz:
    :return:
    """
    from matplotlib import cm
    from mpltools import color
    from pytools import plotsetup

    if 'FLT' not in simIa.__dict__ :
        simIa.getLightCurves()
    zbins = np.arange( sn.z - sn.zerr, sn.z + sn.zerr + dz, dz )
    izbinarg = np.digitize( simIa.z, zbins, right=True )-1
    iQ = np.where( simIa.FLT=='Q' )
    iH = np.where( simIa.FLT=='H' )
    iP = np.where( simIa.FLT=='P' )
    iN = np.where( simIa.FLT=='N' )
    Q,H,P,N = simIa.MAG[iQ],simIa.MAG[iH],simIa.MAG[iP],simIa.MAG[iN]
    QH = Q-H
    PN = P-N

    plotsetup.fullpaperfig( 1, [5,5] )
    pl.clf()
    ax1 = pl.gca()
    # ax1.plot(QH,PN, ls=' ', marker='o',color='k', alpha=0.3 )
    color.cycle_cmap( len(zbins), cmap=cm.gist_rainbow_r, ax=ax1)
    for iz in range(len(zbins)-1) :
        z0, z1 = zbins[iz],zbins[iz+1]
        QHz = QH[izbinarg==iz]
        PNz = PN[izbinarg==iz]
        if dz>=0.1 : zmid = round(np.mean([z0,z1]),1)
        elif dz>=0.01 : zmid = round(np.mean([z0,z1]),2)
        ax1.plot(QHz,PNz, marker='o', alpha=0.3, ls=' ',mew=0,label='%.1f-%.1f'%(z0,z1) )
    ax1.legend(loc='upper left', ncol=2, numpoints=1, frameon=False,
               handletextpad=0.3, handlelength=0.2 )
    ax1.set_xlabel('F153M-F160W')
    ax1.set_ylabel('F139M-F140W')
    plotPhot(label=True)
    ax1.set_xlim(-0.35,0.53)
    ax1.set_ylim(-0.35,0.53)
    fig = pl.gcf()
    fig.subplots_adjust(bottom=0.12,left=0.16,right=0.95,top=0.95)
    pl.draw()
示例#5
0
def set_color_palette(n=8, name = 'viridis'):
    """ 
    name: 
        husl - like a rainbow
        cubehelix - colorblind, black-white printing
    """
    
    if name == "husl":
        MM = color.LinearColormap('snsmap', color_palette("husl"))
        color.cycle_cmap(length = n, cmap = MM)

    elif name == 'cubehelix':
        MM = color.LinearColormap('snsmap', cubehelix_palette(n, start=.5, rot=-.75))
        color.cycle_cmap(length = n, cmap = MM)
        
    else:
        cmap = plt.get_cmap(name)
        cgen = (cmap(1.*i/n) for i in range(n))
        matplotlib.rc('axes', prop_cycle = cycler('color', cgen)) 
示例#6
0
    this_data.update(polya_mouse_cpm_n.iteritems())
    this_data.update(ffpe_cpm_n.iteritems())

    ax = log_cpm_ecdf_plot(
        this_data,
        units='cpm',
        label_dict=first_label,
        style_dict=plot_style,
        min_cpm=min_cpm
    )
    ax.figure.savefig(os.path.join(outdir, "ecdf_polya_ffpe_tmm.png"), dpi=200)

    # 2a) same, just for mouse samples

    # set the colour cycle to distinguish the samples more easily
    color.cycle_cmap(our_mouse_obj.meta.shape[0], cmap='jet')

    # set the order because it makes it easier to distinguish samples
    this_data = collections.OrderedDict([
        (c, polya_mouse_counts[c]) for c in our_mouse_obj.meta.index
    ])

    ax = log_cpm_ecdf_plot(
        this_data,
        label_dict=dict([(k, k) for k in this_data]),
        min_cpm=min_cpm,
    )

    # overlay human samples in grey
    this_data = dict(our_patient_obj.data.iteritems())
    this_plot_style = dict([
示例#7
0
===========================

``cycle_cmap`` provides a simple way to set the color cycle to evenly-spaced
intervals of a given colormap. By default, it alters the default color cycle,
but if you pass it a plot axes, only the color cycle for the axes is altered.

"""
import numpy as np
import matplotlib.pyplot as plt

from mpltools import layout
from mpltools import color

n_lines = 10

# Change default color cycle for all new axes
color.cycle_cmap(n_lines)

figsize = layout.figaspect(aspect_ratio=0.5)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=figsize)

# Change color cycle specifically for `ax2`
color.cycle_cmap(n_lines, cmap='pink', ax=ax2)

x = np.linspace(0, 10)
for shift in np.linspace(0, np.pi, n_lines):
    ax1.plot(x, np.sin(x - shift), linewidth=2)
    ax2.plot(x, np.sin(x - shift), linewidth=2)

plt.show()
示例#8
0
``cycle_cmap`` provides a simple way to set the color cycle to evenly-spaced
intervals of a given colormap. By default, it alters the default color cycle,
but if you pass it a plot axes, only the color cycle for the axes is altered.

"""
import numpy as np
import matplotlib.pyplot as plt

from mpltools import layout
from mpltools import color


n_lines = 10

# Change default color cycle for all new axes
color.cycle_cmap(n_lines)

figsize = layout.figaspect(aspect_ratio=0.5)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=figsize)

# Change color cycle specifically for `ax2`
color.cycle_cmap(n_lines, cmap='pink', ax=ax2)

x = np.linspace(0, 10)
for shift in np.linspace(0, np.pi, n_lines):
    ax1.plot(x, np.sin(x - shift), linewidth=2)
    ax2.plot(x, np.sin(x - shift), linewidth=2)

plt.show()

示例#9
0
    eps_r = eps_files[:, 1]
    eps_I = eps_files[:, 2]
    Qspp = eps_r**2 / eps_I * 0.001
    total_data = [eps_r, eps_I, Qspp]
    QQ[i] = Qspp[319]

    a = [
        '$\epsilon_{r}$', '$\epsilon_{I}$',
        '$Q_{spp} = (\epsilon_{r}^2/ \epsilon_{I}) x 10^{-3}$'
    ]
    # a = ['$\epsilon_{r}$','$\epsilon_{I}$','$Q_{spp} = (\epsilon_{r}^2/ \epsilon_{I})$']

    for count in range(len(total_data)):
        max_total_data = np.max(total_data[count])
        min_total_data = np.min(total_data[count])
        color.cycle_cmap(len(sample_Au), cmap='jet')
        plt.subplot(1, 3, count + 1)
        plt.plot(wavelength,
                 total_data[count],
                 linewidth=2,
                 label=legend_AuAg[i])  #'{}'.format(label_name))
        plt.ylabel(a[count])
        plt.ylim(y_lim[count])
        #plt.ylim(0, 600)
        plt.xlim(200, 1000)
        plt.xlabel('$\lambda(nm)$')
        plt.legend(loc='upper left', prop={'size': 12})

plt.tight_layout()
plt.show()
示例#10
0
def main():
    
    thEn = {'90.9':[],'91.3':[],'90.7':[],'91.9':[],'91.1':[],'92.1':[],
    '91.5':[],'92.3':[],'92.5':[],'92.7':[],'92.9':[],'91.7':[],'90.5':[],'90.1':[]}
    
    fList = ['maxInfo_en_17.5_th_All_phi_All_xd_25.dat',
    'maxInfo_en_18_th_All_phi_All_xd_25.dat',
    'maxInfo_en_18.5_th_All_phi_All_xd_25.dat']
    en = [17.5,18,18.5]

    n_lines = 3
    color.cycle_cmap(n_lines, cmap='gnuplot')
    plt.figure(figsize=figsize)
    
    for fName in fList:
        idx = fList.index(fName)
        print fName
        cData = np.loadtxt(fName)
        for x in cData:
            thEn['{:4.1f}'.format(180-x[1])].append([en[idx],x[2]])
        
        plt.plot([180-x for x in cData[:,1]],cData[:,2],marker='o',ls='',ms=8,label='{}'.format(en[idx]))
    plt.grid()
    plt.legend(title=r'{\rm $\log{E_v}$}')
    plt.yscale("log", nonposy='clip')
    plt.xlabel(r'$\theta\ [deg]$')
    plt.ylabel(r'$E_{max}\ [V/m]$')
    plt.savefig('eMaxTh.pdf')
    
    ##########
    
    n_lines = len(thEn)
    color.cycle_cmap(n_lines, cmap='gnuplot')
    plt.figure(figsize=figsize)
    
    for key in sorted(thEn.keys()):
        print(key)
        plt.plot([x[0] for x in thEn[key]],[x[1] for x in thEn[key]],lw=1.5,label='{}'.format(key))
    
    plt.grid()
    plt.legend(title=r'{\rm $\theta\ [deg]$}',loc=2,ncol=4,fontsize=14)
    plt.yscale("log", nonposy='clip')
    plt.xlabel(r'$\log{E_v}$')
    plt.ylabel(r'$E_{max}\ [V/m]$')
    plt.savefig('eMaxThEv.pdf')
    
    
    ##########
    xdEn = {' 75':[],'  0':[],'100':[],' 25':[],' 50':[],'200':[],'150':[]
    ,'300':[]}
    
    fList = ['maxInfo_en_17.5_th_89.5_phi_All_xd_All.dat',
    'maxInfo_en_18_th_89.5_phi_All_xd_All.dat',
    'maxInfo_en_18.5_th_89.5_phi_All_xd_All.dat']
    en = [17.5,18,18.5]

    n_lines = 3
    color.cycle_cmap(n_lines, cmap='gnuplot')
    plt.figure(figsize=figsize)
    
    for fName in fList:
        idx = fList.index(fName)
        print fName
        cData = np.loadtxt(fName)
        for x in cData:
            xdEn['{:3g}'.format(x[1])].append([en[idx],x[2]])
            
        plt.plot(cData[:,1],cData[:,2],marker='o',ls='',ms=8,label='{}'.format(en[idx]))
        
    plt.grid()
    plt.legend(title=r'{\rm $\log{E_v}$}')
    plt.yscale("log", nonposy='clip')
    plt.xlabel(r'$x_d\ [m]$')
    plt.ylabel(r'$E_{max}\ [V/m]$')
    plt.savefig('eMaxXd.pdf')
    
    ##########
    
    n_lines = len(xdEn)
    color.cycle_cmap(n_lines, cmap='gnuplot')
    plt.figure(figsize=figsize)
    
    for key in sorted(xdEn.keys()):
        print(key)
        plt.plot([x[0] for x in xdEn[key]],[x[1] for x in xdEn[key]],lw=1.5,label='{}'.format(key))
    
    plt.grid()
    plt.legend(title=r'{\rm $x_d [m]$}',loc=2,ncol=2,fontsize=16)
    plt.yscale("log", nonposy='clip')
    plt.xlabel(r'$\log{E_v}$')
    plt.ylabel(r'$E_{max}\ [V/m]$')
    plt.savefig('eMaxXdEv.pdf')
    
    
    plt.show()
        
    
    return 0
示例#11
0
# ## Plot time traces at select wavelengths

# In[7]:

print star['tau_aero'].shape
print star['w'].shape
iw = find_closest(star['w'][0],np.array([380,400,430,500,515,635,875,1000,1140,1200,1600])/1000.0)
print star['w'][0].shape
print iw


# In[8]:

plt.figure()
color.cycle_cmap(len(iw)+1,cmap=plt.cm.gist_ncar)
for i in iw:
    plt.plot(star['utc'][star['good']],star['tau_aero'][star['good'],i], label=str('%.3f $\mu$m' % star['w'][0,i]))
plt.xlabel('UTC [h]')
plt.ylabel('AOD')
plt.legend(bbox_to_anchor=[1,0.1],loc=3)
plt.savefig(fp+datestr+filesep+'AOD_time.png',dpi=600)


# ## Start animation of full spectral aod

# In[16]:

from IPython.display import HTML

def display_animation(anim):
no1s_entries, _ = np.histogram(no1stsuccess_distances, bins)
curve3, = plt.plot(bins[:-1],
                   no1s_entries / (fly_release_density_per_bin),
                   '-o',
                   label='Didn\'t succeed first time when first entered here',
                   alpha=0.5)

plt.xlim(0, max_trap_distance)
plt.xlabel('Distance from Trap (m)')
plt.ylabel('Fraction')
text = ax.text(0.2, 1, '0 s', transform=ax.transAxes)
plt.legend(bbox_to_anchor=(1., 1.4))

ax2 = plt.subplot(3, 1, 2)
color.cycle_cmap(3, cmap='Dark2', ax=ax2)

#(4)--------
surging_distances = collector.compute_plume_distance(
    swarm.x_position[swarm.mode == Mode_FlyUpWind],
    swarm.y_position[swarm.mode == Mode_FlyUpWind])

n_surging, _ = np.histogram(surging_distances, bins)
curve4, = plt.plot(bins[:-1],
                   n_surging / (fly_release_density_per_bin),
                   '-o',
                   label='Currently surging here',
                   alpha=0.5)

#(5)--------
casting_distances = collector.compute_plume_distance(
示例#13
0
def subtract_traces(dfs, gains, freqlim, Qs=1.54, f0s=4.552, Z12s=31.58, leg=None, ylim=None, psd_units=True):
    """
    dfs: a list of filepaths. Subtract second from the 1st file.
    gains: a float
    freqlim: list [fmin, fmax]
    Q, f0, Z12 optional
    """
    from mpltools import color

    fig = plt.figure(figsize=(12., 4.))
    common.configure_axes(13)
    color.cycle_cmap(len(dfs), cmap=plt.cm.jet)

    for i, df in enumerate(dfs):
        try:
            string = leg[i]
        except:
            string = ''

        if isinstance(Qs, (float)):
            Q = Qs
        elif isinstance(Qs, (list, np.ndarray)) and len(Qs) == len(dfs):
            Q = Qs[i]
        else:
            print("Qs must have the same length as dfs or must be a float.")

        if isinstance(f0s, (float)):
            f0 = f0s
        elif isinstance(f0s, (list, np.ndarray)) and len(f0s) == len(dfs):
            f0 = f0s[i]
        else:
            print("f0s must have the same length as dfs or must be a float.")

        if isinstance(Z12s, (float)):
            Z12 = Z12s
        elif isinstance(Z12s, (list, np.ndarray)) and len(Z12s) == len(dfs):
            Z12 = Z12s[i]
        else:
            print("Z12s must have the same length as dfs or must be a float.")

        if isinstance(gains, (float)):
            G = gains
        elif isinstance(gains, (list, np.ndarray)) and len(gains) == len(dfs):
            G = gains[i]
        else:
            print("f0s must have the same length as dfs or must be a float.")

        if i == 0:
            f, cal0 = get_geophone_spectrum(df, G, freqlim=freqlim, Q=Q, f0=f0, Z12=Z12, do_imshow=False,
                                       do_plot=False, ret=True, name=leg[i], do_meters_per_sqrt_Hz=psd_units)
        else:
            f, cal = get_geophone_spectrum(df, G, freqlim=freqlim, Q=Q, f0=f0, Z12=Z12, do_imshow=False,
                                           do_plot=False, ret=True, name=leg[i], do_meters_per_sqrt_Hz=psd_units)
            plt.plot(f, cal-cal0, label=string)

    plt.xlabel('FFT frequency (Hz)')
    plt.yscale('log')
    plt.xlim(freqlim)
    fig.patch.set_facecolor('white')

    if leg is not None:
        common.legend_outside(prop={'size': 10})
    if ylim is not None:
        plt.ylim(ylim)
示例#14
0
def compare_traces(dfs, gains, freqlim, Qs=1.54, f0s=4.552, Z12s=31.58, leg=None, ylim=None, psd_units=True):
    """
    Compare traces side by side in a figure.
    :param dfs: a list of filepaths
    :param gains: float, or list of floats with same length as dfs
    :param freqlim: list [fmin, fmax]
    :param Qs: float, or list of floats with same length as dfs
    :param f0s: float, or list of floats with same length as dfs
    :param Z12s: float, or list of floats with same length as dfs
    :param leg: list of string containing labels for the legend
    :param ylim: limits for the y-axis
    :param psd_units: True/False
    :return: None
    """
    from mpltools import color

    fig = plt.figure(figsize=(12., 4.))
    common.configure_axes(13)
    color.cycle_cmap(len(dfs), cmap=plt.cm.jet)

    for i, df in enumerate(dfs):
        try:
            string = leg[i]
        except:
            string = ''

        if isinstance(Qs, (float)):
            Q = Qs
        elif isinstance(Qs, (list, np.ndarray)) and len(Qs) == len(dfs):
            Q = Qs[i]
        else:
            print("Qs must have the same length as dfs or must be a float.")

        if isinstance(f0s, (float)):
            f0 = f0s
        elif isinstance(f0s, (list, np.ndarray)) and len(f0s) == len(dfs):
            f0 = f0s[i]
        else:
            print("f0s must have the same length as dfs or must be a float.")

        if isinstance(Z12s, float):
            Z12 = Z12s
        elif isinstance(Z12s, (list, np.ndarray)) and len(Z12s) == len(dfs):
            Z12 = Z12s[i]
        else:
            print("Z12s must have the same length as dfs or must be a float.")

        if isinstance(gains, (float)):
            G = gains
        elif isinstance(gains, (list, np.ndarray)) and len(gains) == len(dfs):
            G = gains[i]
        else:
            print("f0s must have the same length as dfs or must be a float.")

        f, cal = get_geophone_spectrum(df, G, freqlim=freqlim, Q=Q, f0=f0, Z12=Z12, do_imshow=False,
                                       do_plot=False, ret=True, name=leg[i], do_meters_per_sqrt_Hz=psd_units)
        plt.plot(f, cal, label=string)

    plt.xlabel('FFT frequency (Hz)')
    plt.yscale('log')
    plt.xlim(freqlim)
    fig.patch.set_facecolor('white')

    if leg is not None:
        common.legend_outside(prop={'size': 10})
    if ylim is not None:
        plt.ylim(ylim)
示例#15
0
文件: anal.py 项目: gkoolstra/Common
def plot_alazar_sweep(fft_freq, fft, drivepts, min_fft_freq, savepath=None, threshold=-100, do_imshow=True,
                      ylim=None, xlim=None, do_colorbar=False, do_dumb=True, do_plot_2omega=False, do_plot_1omega=False):
    """
    fft_freq:       1D array with FFT frequencies, obtained from alazar_sweep.
    fft:            2D array containing FFT**2, from alazar_sweep
    drivepts:       Drive frequencies of the source
    min_fft_freq:   Minimum FFT frequency you would like to display in your plots in Hz.
    savepath:       Datapath, where to save the figures. Default: None
    threshold:      Determines the threshold in dBm/Hz for traces to be marked as interesting. Interesting traces are
                    plot separately.
    do_imshow:      Plot the 2d array "fft"
    ylim:           List of color limits for the colorplot and for the interesting traces. Ex: [-120, 90]. Default: None
    do_colorbar:    Plot a colorbar for the 2d colorplot. Takes up a little more space, so can be disabled by setting
                    do_colorbar=False.
    """
    selected_fft = 10 * np.log10(fft)[:,np.logical_and(fft_freq>xlim[0]*1E3, fft_freq<xlim[1]*1E3)]
    #print np.shape(selected_fft)

    print "Delta f = {} Hz".format(fft_freq[1]-fft_freq[0])

    if do_imshow:
        fig2 = plt.figure(figsize=(16., 8.), facecolor='white')
        common.configure_axes(13)
        plt.imshow(selected_fft, aspect='auto', interpolation='none',
                   extent=[xlim[0], xlim[1], drivepts[-1]/1E3, drivepts[0]/1E3],
                   vmin=ylim[0], vmax=ylim[1])
        if do_colorbar:
            plt.colorbar()
        plt.title('Power spectral density (dBm/Hz)')
        plt.xlabel('FFT frequency (kHz)')
        plt.ylabel('Drive frequency (kHz)')

        if ylim is not None and do_colorbar:
            plt.clim(ylim)
        if xlim is not None:
            plt.xlim(xlim)

        if do_plot_2omega:
            plt.plot(2*drivepts/1E3, drivepts/1E3, '-', color='white', alpha=0.25, lw = 5)
        if do_plot_1omega:
            plt.plot(drivepts/1E3, drivepts/1E3, '-', color='white', alpha=0.25, lw = 5)

        if savepath is not None:
            fig2.savefig(os.path.join(savepath, 'fig2.png'), dpi=200)
        #plt.xlim([fft_freq[0], fft_freq[-1]]);

    above_noise = np.where(selected_fft > threshold)
    # A trace is marked interesting when there's a a frequency bin with value > threshold dB
    # That frequency may not be the 0 Hz
    if min_fft_freq == 0:
        interesting_traces = np.unique(above_noise[0][np.where(above_noise[1] > 0)])
    else:
        interesting_traces = np.unique(above_noise[0])

    from mpltools import color

    if do_dumb:
        fig4 = plt.figure(figsize=(8.,6.), facecolor='white')
        color.cycle_cmap(length=np.shape(selected_fft)[0], cmap=plt.cm.jet)
        ax = plt.gca()
        for idx, i in enumerate(range(np.shape(selected_fft)[0])):
            ax.plot(fft_freq[np.logical_and(fft_freq>xlim[0]*1E3, fft_freq<xlim[1]*1E3)] / 1E3, selected_fft[i,:])
            plt.ylim(ylim)
            plt.xlim(xlim)
        plt.xlabel('FFT frequency (kHz)')
        plt.ylabel('PSD (dBm/Hz)')

    nrows = np.ceil(len(interesting_traces)/4.)
    fig3 = plt.figure(figsize=(16, 2*nrows), facecolor='white')
    for idx,INT in enumerate(interesting_traces):
        plt.subplot(nrows, 4, idx)
        plt.plot(fft_freq[np.logical_and(fft_freq>xlim[0]*1E3, fft_freq<xlim[1]*1E3)] / 1E3, selected_fft[INT, :])
        plt.ylim(ylim)
        plt.xlim(xlim)
        plt.annotate('%.0f kHz'%(drivepts[INT]/1E3) , xy=(1, 1), xycoords='axes fraction', fontsize=16,
                horizontalalignment='right', verticalalignment='top', color='r')

    #plt.xlabel('FFT frequency (kHz)')
    #plt.ylabel('PSD (dBm/Hz)')

    if ylim is not None:
        plt.ylim(ylim)
    if xlim is not None:
        plt.xlim(xlim)

    if savepath is not None:
        fig3.savefig(os.path.join(savepath, 'fig3.png'), dpi=200)

    print "There are %d interesting traces" % len(interesting_traces)

    return interesting_traces
示例#16
0
# <codecell>

for ir,rr in enumerate(r):
    for iv,v in enumerate(wavelen_ice):
        m = pmie.Mie(x=2*pi/v*rr,m=complex(refre_ice[iv],refim_ice[iv]))
        qext_ice[ir,iv] = m.qext()
    for iv,v in enumerate(wavelen_liq):
        m = pmie.Mie(x=2*pi/v*rr,m=complex(refre_liq[iv],refim_liq[iv]))
        qext_liq[ir,iv] = m.qext()

# <codecell>

fig,ax = plt.subplots(1,2,figsize=(10,5))
ax = ax.ravel()
color.cycle_cmap(len(r),cmap=plt.cm.gist_ncar,ax=ax[0])
color.cycle_cmap(len(r),cmap=plt.cm.gist_ncar,ax=ax[1])
for ir,rr in enumerate(r):
    ax[0].plot(wavelen_liq,qext_liq[ir,:],label='%2.0f $\mu$m' % rr)
    ax[1].plot(wavelen_ice,qext_ice[ir,:],label='%2.0f $\mu$m' % rr)
#plt.legend(frameon=True,)
ax[0].set_xlabel('Wavelength [$\mu$m]')
ax[0].set_ylabel('$Q_{ext}$')
ax[0].set_xlim([0.4,1.7])
ax[0].set_title('Extinction efficiency for liquid particles')
ax[1].set_xlabel('Wavelength [$\mu$m]')
ax[1].set_ylabel('$Q_{ext}$')
ax[1].set_xlim([0.4,1.7])
ax[1].set_title('Extinction efficiency for ice particles')

scalarmap = plt.cm.ScalarMappable(cmap=plt.cm.gist_ncar)
示例#17
0
print lut.ref
print lut.sp[0,400,0,23,10]
print lut.sp[1,400,0,:,10]
print lut.par.shape

# <markdowncell>

# Now plot the resulting lut of parameters

# <codecell>

fig3,ax3 = plt.subplots(5,3,sharex=True,figsize=(15,8))
ax3 = ax3.ravel()

for i in range(lut.npar-1):
    color.cycle_cmap(len(lut.ref[lut.ref<30]),cmap=plt.cm.RdBu,ax=ax3[i])
    for j in xrange(len(lut.ref)):
        ax3[i].plot(lut.tau,lut.par[0,j,:,i])
    ax3[i].set_title('Parameter '+str(i))
    ax3[i].grid()
    ax3[i].set_xlim([0,100])
    if i > 11: 
        ax3[i].set_xlabel('Tau')

fig3.tight_layout()
plt.suptitle('Liquid')
plt.subplots_adjust(top=0.93,right=0.93)

cbar_ax = fig3.add_axes([0.95,0.10,0.02,0.8])
scalarmap = plt.cm.ScalarMappable(cmap=plt.cm.RdBu,norm=plt.Normalize(vmin=0,vmax=1))
scalarmap.set_array(lut.ref[lut.ref<30])
def frmt(x,pos):
    return '{:5.2f}'.format(x)


# In[310]:


len(range(23000,25000,50))


# In[356]:


plt.figure(figsize=(10,3))
color.cycle_cmap(41,cmap=plt.cm.plasma,ax=plt.gca())
for j in xrange(23000,25000,50):
    plt.plot(sr.wvl,sr.norm[j,:])
scalarmap = plt.cm.ScalarMappable(cmap=plt.cm.plasma)
scalarmap.set_array(sr.utc[range(23000,25000,50)])
cba = plt.colorbar(scalarmap,format=ticker.FuncFormatter(frmt))
cba.set_label('UTC [h]')
plt.ylim(0,1)
plt.xlim(340,1750)
plt.title('SASZe normalized spectra, Ascension Island, 2016-08-14')
plt.xlabel('Wavelength [nm]')
plt.ylabel('Normalized Radiance')
plt.tight_layout()
#plt.plot(lut.wvl,lut.norm[0,:,0,8,20],'k-',lw=3,
#         label='Modeled, $\\tau$={:2.1f}, r$_{{eff}}$={:2.0f}$\\mu$m'.format(lut.tau[20],lut.ref[8]))
plt.plot(lut.wvl,lut.norm[0,:,0,4,16],'-',color='k',lw=3,alpha=0.8,
示例#19
0
        expt_frequency = scaled_cavity_frequency
    else:
        expt_frequency = np.vstack((expt_frequency, scaled_cavity_frequency))

    noof_electrons.append(N_electrons)

    # Here we plot the scaled cavity frequency shift vs. the resonator voltage.
    # fig6 = plt.figure(figsize=(6., 4.))
    # plt.plot(Vres, scaled_cavity_frequency / 1E9, 'o', **common.plot_opt('red', msize=4))
    # plt.ylabel("Scaled cavity frequency $\omega_0/2\pi$ (GHz)")
    # plt.xlabel("Resonator voltage (V)")

    # if save:
    #     common.save_figure(fig6, save_path=os.path.join(save_path, sub_dir))

color.cycle_cmap(len(sub_dirs), cmap=plt.cm.Spectral)
fig = plt.figure(figsize=(8., 4.))
common.configure_axes(12)
for r in range(len(sub_dirs)):
    plt.plot(Vres,
             expt_frequency[r, :] / 1E9,
             '.-',
             label="N = %d" % noof_electrons[r])

plt.ylabel("Scaled cavity frequency $\omega_0/2\pi$ (GHz)")
plt.xlabel("Resonator voltage (V)")
plt.ylim(7.95, 8.0)
plt.legend(loc=0, prop={'size': 10})

if save:
    common.save_figure(fig, save_path=os.path.join(save_path, sub_dirs[-1]))