Пример #1
0
def _prettyplot(df, prep, prepi, out_file, title=None, size=None):
    """Plot using prettyplot wrapper around matplotlib.
    """
    cats = ["concordant", "discordant-missing-total",
            "discordant-extra-total", "discordant-shared-total"]
    vtypes = df["variant.type"].unique()
    fig, axs = ppl.subplots(len(vtypes), len(cats))
    callers = sorted(df["caller"].unique())
    width = 0.8
    for i, vtype in enumerate(vtypes):
        ax_row = axs[i] if len(vtypes) > 1 else axs
        for j, cat in enumerate(cats):
            ax = ax_row[j]
            if i == 0:
                ax.set_title(cat_labels[cat], size=14)
            ax.get_yaxis().set_ticks([])
            if j == 0:
                ax.set_ylabel(vtype_labels[vtype], size=14)
            vals, labels, maxval = _get_chart_info(df, vtype, cat, prep, callers)
            ppl.bar(ax, np.arange(len(callers)), vals,
                    color=ppl.colors.set2[prepi], width=width)
            ax.set_ylim(0, maxval)
            if i == len(vtypes) - 1:
                ax.set_xticks(np.arange(len(callers)) + width / 2.0)
                ax.set_xticklabels([caller_labels.get(x, x).replace("__", "\n") if x else ""
                                    for x in callers], size=8, rotation=45)
            else:
                ax.get_xaxis().set_ticks([])
            _annotate(ax, labels, vals, np.arange(len(callers)), width)
    fig.text(.5, .95, prep_labels.get(prep, "") if title is None else title, horizontalalignment='center', size=16)
    fig.subplots_adjust(left=0.05, right=0.95, top=0.87, bottom=0.15, wspace=0.1, hspace=0.1)
    #fig.tight_layout()
    x, y = (10, 5) if size is None else size
    fig.set_size_inches(x, y)
    fig.savefig(out_file)
Пример #2
0
 def PLOT_MATRIX_SAMPLING(matrix,idx=None,sampling_size=None,colorm='jet'):
     from prettyplotlib import brewer2mpl
     import pylab
     red_purple = brewer2mpl.get_map('Blues', 'Sequential', 9).mpl_colormap
     green_purple = brewer2mpl.get_map('PRGn', 'diverging', 11).mpl_colormap
     if sampling_size == None:
         sampling_size = [1e0,1e1,1e2,1e3,1e4,1e300]
     
     fig,ax = ppl.subplots(nrows=2,ncols=3)
     for ss in range(len(sampling_size)):
         nn = sampling_size[ss]
         pmatrix = 1 - np.exp(-nn*matrix)
         aa = ax[ss/3,ss%3]
         
         #plt.subplot(2,3,ss+1)
         #GeneralPlotter.PLOT_MATRIX(pmatrix,axis=1)
         #print ss/3,ss%3
         pmatrix = GeneralPlotter.SORT_MATRIX(pmatrix,idx=idx,axis=1) 
         pmatrix = np.flipud(pmatrix)
         #im = aa.matshow(pmatrix, aspect='auto', origin='lower', cmap=pylab.cm.YlGnBu)
         #pp=aa.imshow(pmatrix,interpolation='nearest',cmap=colorm)    
         #fig.colorbar(pp,ax=aa)
         pcolormesh(fig,aa,pmatrix,center_value=0.5, ax_colorbar=aa,cmap=red_purple)
         aa.set_xticks([])
         aa.set_yticks([])
         
         aa.set_title(r'$n = %i$' % sampling_size[ss],fontsize=20)
         if ss==5:
             plt.title('$n = \infty$',fontsize=20)
Пример #3
0
def generate_plot(title, ylabel, x, y, width_in, height_in, plot_format):
    fig, ax = ppl.subplots(1, 1, figsize=(width_in, height_in))
    kwargs = dict(linewidth=1.0, alpha=0.7)
    date_list = num2date(x,
                         units='seconds since 1900-01-01 00:00:00',
                         calendar='gregorian')
    plot_time_series(fig,
                     ax,
                     date_list,
                     y,
                     title=title,
                     ylabel=ylabel,
                     title_font=title_font,
                     axis_font=axis_font,
                     **kwargs)

    buf = io.BytesIO()

    if plot_format not in ['svg', 'png']:
        plot_format = 'svg'
    plt.savefig(buf, format=plot_format)
    buf.seek(0)

    plt.clf()
    plt.cla()

    return buf
Пример #4
0
def _prettyplot(df, prep, prepi, out_file, title=None, size=None):
    """Plot using prettyplot wrapper around matplotlib.
    """
    cats = ["concordant", "discordant-missing-total", "discordant-extra-total", "discordant-shared-total"]
    vtypes = df["variant.type"].unique()
    fig, axs = ppl.subplots(len(vtypes), len(cats))
    callers = sorted(df["caller"].unique())
    width = 0.8
    for i, vtype in enumerate(vtypes):
        ax_row = axs[i] if len(vtypes) > 1 else axs
        for j, cat in enumerate(cats):
            ax = ax_row[j]
            if i == 0:
                ax.set_title(cat_labels[cat], size=14)
            ax.get_yaxis().set_ticks([])
            if j == 0:
                ax.set_ylabel(vtype_labels[vtype], size=14)
            vals, labels, maxval = _get_chart_info(df, vtype, cat, prep, callers)
            ppl.bar(ax, np.arange(len(callers)), vals, color=ppl.colors.set2[prepi], width=width)
            ax.set_ylim(0, maxval)
            if i == len(vtypes) - 1:
                ax.set_xticks(np.arange(len(callers)) + width / 2.0)
                ax.set_xticklabels(
                    [caller_labels.get(x, x).replace("__", "\n") if x else "" for x in callers], size=8, rotation=45
                )
            else:
                ax.get_xaxis().set_ticks([])
            _annotate(ax, labels, vals, np.arange(len(callers)), width)
    fig.text(0.5, 0.95, prep_labels.get(prep, "") if title is None else title, horizontalalignment="center", size=16)
    fig.subplots_adjust(left=0.05, right=0.95, top=0.87, bottom=0.15, wspace=0.1, hspace=0.1)
    # fig.tight_layout()
    x, y = (10, 5) if size is None else size
    fig.set_size_inches(x, y)
    fig.savefig(out_file)
Пример #5
0
    def _subplots(self, *args, **kwargs):
        if not kwargs:
            kwargs = dict()

        if 'figsize' not in kwargs:
                kwargs['figsize'] = self.DEFAULT_SIZE

        return ppl.subplots(*args, **kwargs)
Пример #6
0
def plot_hist_prettyplotlib(band, type, data):
    dim = data.shape
    print 'data dim ', dim
    fig, ax = ppl.subplots(1)
    ppl.pcolormesh(fig, ax, data, vmin=-0.0016, vmax=0.0016)
    plt.title('%s: band %s' % (type, band))
    plt.xlabel('buckets')
    plt.ylabel('time')
    fig.savefig("%s-histogram-%s.png" % (type, band))
Пример #7
0
def several_times(all_interval3, all_data3_3,
                  names3, p_title3, time_real_1,time_real_2,time_real_3,
                  delta_s,t_real, time_data, dycoms, fitting, s_point):


  fig, ax = ppl.subplots()
  color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors
  color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors
  #color_set_2 = brewer2mpl.get_map('Reds', 'sequential', 9).mpl_colors
  color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors
  

  shape= np.shape(all_interval3) 
  time_length=shape[1]

  print time_length

   
  k=2
  time_buffer=round(time_data[k]*t_real/60,2)
  print 'real time t3',time_buffer
  name_x='t='+str(time_buffer)
  ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1, label=name_x)
  k=6
  time_buffer=round(time_data[k]*t_real/60,2)
  print 'real time t3',time_buffer
  name_x='t='+str(time_buffer)
  ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[3],linewidth=l_w_1, label=name_x)
  k=12
  time_buffer=round(time_data[k]*t_real/60,2)
  print 'real time t3',time_buffer
  name_x='t='+str(time_buffer)
  ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[5],linewidth=l_w_1, label=name_x)
  k=15
  time_buffer=round(time_data[k]*t_real/60,2)
  print 'real time t3',time_buffer
  name_x='t='+str(time_buffer)
  ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[7],linewidth=l_w_1, label=name_x)
  k=32
  time_buffer=round(time_data[k]*t_real/60,2)
  print 'real time t3',time_buffer
  name_x='t='+str(time_buffer)
  ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[9],linewidth=l_w_1, label=name_x)



  ax.set_yscale('symlog')
  plt.xlabel('Liquid', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt
  plt.ylabel('Amount of cloud droplets', fontsize=size_axes)#,fontdict=font)
  plt.xlim(0,3)
  plt.ylim([10,10**8])
  plt.legend(loc=1, frameon=False)  


  plt.show()
Пример #8
0
def plot_data_compare(interval1,data1_1, data1_2, data1_3, 
                      interval2, data2_1, data2_2, data2_3,
                      interval3, data3_1, data3_2, data3_3,
                      names1, names2, names3):

  #COLORS FOR PLOTTING 
  fig, ax = ppl.subplots()
  color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors
  color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors
  color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors
 
  ########################################################################
  #Scale data
  ########################################################################
  data2_1=data2_1*30/18*1.3
  data2_2=data2_2*30/18*1.3
  data2_3=data2_3*30/18*1.3

  data3_1=data3_1*50/18*1.4 
  data3_2=data3_2*50/18*1.4
  data3_3=data3_3*50/18*1.4

  ########################################################################
  #Plot data
  ########################################################################
  ax.plot(interval1,data1_3, color=color_set[1],linewidth=l_w_1, label=names1[3])
  ax.plot(interval2,data2_3, color=color_set[3],linewidth=l_w_1, label=names2[3])
  ax.plot(interval3,data3_3, color=color_set[5],linewidth=l_w_1, label=names3[3])


  ########################################################################
  #Plot properties
  ########################################################################
  #GRID LINES
  #axes = plt.gca()
  #axes.grid(True)

  ax.set_yscale('symlog') #use 'symlog'= for symmetrical log  or 'log' for only positive values
  plt.xlabel(r'$M/M_r$', fontsize=size_axes) #the argument r allows for latex code
  plt.ylabel('Relative amount of droplets', fontsize=size_axes)

  plt.xlim(0.1,2.2)
  plt.ylim([10,10**8])
  plt.legend(loc=1, frameon=False) # set legend and the location 
  

  #Hide the right and top spines
  ax.spines['right'].set_visible(False)
  ax.spines['top'].set_visible(False)
  #Only show ticks on the left and bottom spines
  ax.yaxis.set_ticks_position('left')
  ax.xaxis.set_ticks_position('bottom')

  plt.show()
Пример #9
0
def test_legend():
    # Set the random seed for consistency
    np.random.seed(12)

    fig, ax = ppl.subplots(1)

    # Show the whole color range
    for i in range(8):
        x = np.random.normal(loc=i, size=1000)
        y = np.random.normal(loc=i, size=1000)
        ppl.scatter(ax, x, y, label=str(i))
    ppl.legend(ax)
Пример #10
0
def plot_meshless(args):
    npoints = args.npoints
    points = generate_2d_points(npoints, args.seed)

    x = np.arange(0., 1., .01)
    y = np.arange(0., 1., .01)
    xx, yy = np.meshgrid(x, y)

    import prettyplotlib as ppl
    fig, ax = ppl.subplots()

    for mypoint in points:
        dens = compute_meshless_density(xx, yy, points, mypoint, args.sigma)
        plt.contourf(xx, yy, dens, alpha=1. / npoints)

    ppl.scatter(ax, points[:, 0], points[:, 1], color='white')
    ax.autoscale(tight=True)
    plt.title(args.subtitle)
Пример #11
0
 def PLOT_CDF_SAMPLING(matrix, sampling_size = None):
     
     if sampling_size == None:
         sampling_size = [1e0,1e1,1e2,1e3,1e4,1e300]
     
     fig,ax = ppl.subplots(nrows=2,ncols=3)
     for ss in range(len(sampling_size)):
         nn = sampling_size[ss]
         pmatrix = 1 - np.exp(-nn*matrix)            
         
         #degrees = np.sum(pmatrix>0.8,axis=0) + np.sum(pmatrix>0.999,axis=1)
         degrees = np.round(np.sum(pmatrix,axis=0) + np.sum(pmatrix,axis=1))
         
     
         aa = ax[ss/3,ss%3]
         
         values = np.array(degrees)
         values.sort()
         
         elements = np.unique(values)
         elements = elements[::-1]
     
         counting = np.zeros([len(elements),1])
         
         for i in range(len(elements)):
             counting[i] = len(values[values==elements[i]])
         
         cdf = np.cumsum(1.0*counting)/np.sum(counting)
         
         
            
         aa.semilogy(elements[::-1], cdf[::-1],'bo')
         #plt.title('N = %i E= % i')
         aa.set_xlabel('# of trophic links')
         aa.set_ylabel('CDF value')
         
         aa.set_title(r'$n = %i$' % sampling_size[ss],fontsize=20)
         if ss==5:
             plt.title('$n = \infty$',fontsize=20)
Пример #12
0
def _plot_evaluation(df_csv):
    """Provide plot of evaluation metrics, stratified by event size.
    """
    if ppl is None:
        return None
    out_file = "%s.pdf" % os.path.splitext(df_csv)[0]
    if not utils.file_uptodate(out_file, df_csv):
        metrics = ["sensitivity", "precision"]
        df = pd.read_csv(df_csv).fillna("0%")
        fig, axs = ppl.subplots(len(_EVENT_SIZES), len(metrics))
        callers = sorted(df["caller"].unique())
        if "ensemble" in callers:
            callers.remove("ensemble")
            callers.append("ensemble")
        for i, size in enumerate(_EVENT_SIZES):
            size_label = "%s to %sbp" % size
            size = "%s-%s" % size
            for j, metric in enumerate(metrics):
                ax = axs[i][j]
                ax.get_xaxis().set_ticks([])
                ax.spines['bottom'].set_visible(False)
                ax.spines['left'].set_visible(False)
                ax.set_xlim(0, 100.0)
                if i == 0:
                    ax.set_title(metric, size=12, y=1.2)
                vals, labels = _get_plot_val_labels(df, size, metric, callers)
                ppl.barh(ax, np.arange(len(vals)), vals, yticklabels=callers)
                if j == 0:
                    ax.tick_params(axis='y', which='major', labelsize=8)
                    ax.text(80, 4.2, size_label, fontsize=10)
                else:
                    ax.get_yaxis().set_ticks([])
                for ai, (val, label) in enumerate(zip(vals, labels)):
                    ax.annotate(label, (val + 1, ai + 0.35),
                                va='center',
                                size=7)
        fig.set_size_inches(7, 6)
        fig.savefig(out_file)
    return out_file
Пример #13
0
    def PLOT_MATRIX_SAMPLING(matrix,
                             idx=None,
                             sampling_size=None,
                             colorm='jet'):
        from prettyplotlib import brewer2mpl
        import pylab
        red_purple = brewer2mpl.get_map('Blues', 'Sequential', 9).mpl_colormap
        green_purple = brewer2mpl.get_map('PRGn', 'diverging', 11).mpl_colormap
        if sampling_size == None:
            sampling_size = [1e0, 1e1, 1e2, 1e3, 1e4, 1e300]

        fig, ax = ppl.subplots(nrows=2, ncols=3)
        for ss in range(len(sampling_size)):
            nn = sampling_size[ss]
            pmatrix = 1 - np.exp(-nn * matrix)
            aa = ax[ss / 3, ss % 3]

            #plt.subplot(2,3,ss+1)
            #GeneralPlotter.PLOT_MATRIX(pmatrix,axis=1)
            #print ss/3,ss%3
            pmatrix = GeneralPlotter.SORT_MATRIX(pmatrix, idx=idx, axis=1)
            pmatrix = np.flipud(pmatrix)
            #im = aa.matshow(pmatrix, aspect='auto', origin='lower', cmap=pylab.cm.YlGnBu)
            #pp=aa.imshow(pmatrix,interpolation='nearest',cmap=colorm)
            #fig.colorbar(pp,ax=aa)
            pcolormesh(fig,
                       aa,
                       pmatrix,
                       center_value=0.5,
                       ax_colorbar=aa,
                       cmap=red_purple)
            aa.set_xticks([])
            aa.set_yticks([])

            aa.set_title(r'$n = %i$' % sampling_size[ss], fontsize=20)
            if ss == 5:
                plt.title('$n = \infty$', fontsize=20)
Пример #14
0
def _plot_evaluation(df_csv):
    """Provide plot of evaluation metrics, stratified by event size.
    """
    if ppl is None:
        return None
    out_file = "%s.pdf" % os.path.splitext(df_csv)[0]
    if not utils.file_uptodate(out_file, df_csv):
        metrics = ["sensitivity", "precision"]
        df = pd.read_csv(df_csv).fillna("0%")
        fig, axs = ppl.subplots(len(_EVENT_SIZES), len(metrics))
        callers = sorted(df["caller"].unique())
        if "ensemble" in callers:
            callers.remove("ensemble")
            callers.append("ensemble")
        for i, size in enumerate(_EVENT_SIZES):
            size_label = "%s to %sbp" % size
            size = "%s-%s" % size
            for j, metric in enumerate(metrics):
                ax = axs[i][j]
                ax.get_xaxis().set_ticks([])
                ax.spines['bottom'].set_visible(False)
                ax.spines['left'].set_visible(False)
                ax.set_xlim(0, 100.0)
                if i == 0:
                    ax.set_title(metric, size=12, y=1.2)
                vals, labels = _get_plot_val_labels(df, size, metric, callers)
                ppl.barh(ax, np.arange(len(vals)), vals, yticklabels=callers)
                if j == 0:
                    ax.tick_params(axis='y', which='major', labelsize=8)
                    ax.text(80, 4.2, size_label, fontsize=10)
                else:
                    ax.get_yaxis().set_ticks([])
                for ai, (val, label) in enumerate(zip(vals, labels)):
                    ax.annotate(label, (val + 1, ai + 0.35), va='center', size=7)
        fig.set_size_inches(7, 6)
        fig.savefig(out_file)
    return out_file
Пример #15
0
    def PLOT_CDF_SAMPLING(matrix, sampling_size=None):

        if sampling_size == None:
            sampling_size = [1e0, 1e1, 1e2, 1e3, 1e4, 1e300]

        fig, ax = ppl.subplots(nrows=2, ncols=3)
        for ss in range(len(sampling_size)):
            nn = sampling_size[ss]
            pmatrix = 1 - np.exp(-nn * matrix)

            #degrees = np.sum(pmatrix>0.8,axis=0) + np.sum(pmatrix>0.999,axis=1)
            degrees = np.round(
                np.sum(pmatrix, axis=0) + np.sum(pmatrix, axis=1))

            aa = ax[ss / 3, ss % 3]

            values = np.array(degrees)
            values.sort()

            elements = np.unique(values)
            elements = elements[::-1]

            counting = np.zeros([len(elements), 1])

            for i in range(len(elements)):
                counting[i] = len(values[values == elements[i]])

            cdf = np.cumsum(1.0 * counting) / np.sum(counting)

            aa.semilogy(elements[::-1], cdf[::-1], 'bo')
            #plt.title('N = %i E= % i')
            aa.set_xlabel('# of trophic links')
            aa.set_ylabel('CDF value')

            aa.set_title(r'$n = %i$' % sampling_size[ss], fontsize=20)
            if ss == 5:
                plt.title('$n = \infty$', fontsize=20)
Пример #16
0
        print 'no data, running again'
        for nd,delta in enumerate(deltas):
            y = eta**2/(2*gamma)
            print nd, " of ",len(deltas)
            for nphi,phi in enumerate(phis):
                fun = lambda x: f(x,gamma,eta,phi,alpha,thetas,tau,delta)
                y = opt.fsolve(fun, y)
                epss[nd,nphi] = y/(eta**2/(2*gamma))
                ls[nd,nphi] = lambdabar(thetas,gamma,eta,phi,alpha,tau,delta)
    
    strings = [r'$\tau\delta$ = '+str(i*tau) for i in deltas]
    
    #f = lambda i : plt.plot(alphas,epss[i,:],label=strings[i])
    #map(f,range(len(deltas)))
    fig, ax = ppl.subplots(1,figsize=(7,7))
    ppl.plot(ls[0,:],epss[0,:],label = strings[0], ax=ax)
    ppl.plot(ls[1,:],epss[1,:],label = strings[1], ax=ax)
    ppl.plot(ls[2,:],epss[2,:],label = strings[2], ax=ax)
    ppl.plot(ls[3,:],epss[3,:],label = strings[3], ax=ax)
    ppl.plot(ls[4,:],epss[4,:],label = strings[4], ax=ax)
    
    np.savez("../data/mean_field_ratedist.npz", eps = epss, ls=ls, phis = phis, deltas = deltas, tau = tau)
   
    ax.set_xlim([0.0,25.0])
    ax.set_xlabel(r'$\lambda$ in spikes/sec')
    ax.set_ylabel(r'MMSE/$\epsilon_0$')
    plt.title("Rate-Distortion Curve for Adaptive Neurons")
    ppl.legend(ax)
    plt.savefig("rate_distortion_mf_alpha.png")
    plt.savefig("rate_distortion_mf_alpha.eps")
Пример #17
0
print "stringing"
string = [r'$\phi$ = %.2f' % float(i) for i in data[3]]

maxmmse = np.max(data[0])

def f(x):
    line, = ppl.plot(data[2],data[0][:,x],label=string[x],axes=ax1)
    return line.get_color()

def get_min(data):
    minim = np.min(data)
    indmin = np.argmin(data)
    return minim,indmin

print "subplotting"
fig, ax1 = ppl.subplots(1)
ax1.set_title(r'Classification')

colors = map(f,range(data[3].size))

for i in range(data[3].size):
    mi,ind = get_min(data[0][:,i])
    ppl.plot(data[2][ind],mi,'o',color=colors[i],axes=ax1)

ppl.legend(ax1)

ax1.set_xlabel(r'$\alpha$')
ax1.set_ylabel(r'MMSE')

plt.savefig("mmse_classification.eps")
Пример #18
0
def generate_plot(data, plot_options):
    # Define some fonts
    title_font = {
        'fontname': 'Calibri',
        'size': '14',
        'color': 'black',
        'weight': 'bold'
    }

    axis_font = {'fontname': 'Calibri', 'size': '12', 'weight': 'bold'}

    tick_font = {'axis': 'both', 'labelsize': 8, 'width': 1, 'color': 'k'}

    # Get all the plot options
    plot_format = plot_options['plot_format']
    plot_layout = plot_options['plot_layout']
    plot_profile_id = plot_options['profileid']
    events = plot_options['events']
    width_in = plot_options['width_in']
    use_scatter = plot_options['use_scatter']
    plot_qaqc = plot_options['use_qaqc']

    # Generate the plot figure and axes
    if isinstance(data, dict):
        width = data['width']
        height = data['height']

        is_timeseries = False
        if "time" == data['x_field'][0]:
            data['x']['time'] = num2date(
                data['x']['time'],
                units='seconds since 1900-01-01 00:00:00',
                calendar='gregorian')
            is_timeseries = True
    else:
        width = data[0]['width']
        height = data[0]['height']
        for idx, dataset in enumerate(data):
            if "time" == dataset['x_field'][0]:
                data[idx]['x']['time'] = num2date(
                    data[idx]['x']['time'],
                    units='seconds since 1900-01-01 00:00:00',
                    calendar='gregorian')

    fig, ax = ppl.subplots(1, 1, figsize=(width, height))

    # Calculate the hypotenuse to determine appropriate font sizes
    hypot = np.sqrt(width**2 + height**2) - 4
    tick_font['labelsize'] = int(hypot)
    axis_font['size'] = int(hypot) + 3
    title_font['size'] = int(hypot) + 5

    # Check the plot type and generate the plot!
    if plot_layout == "timeseries":
        '''
        Plot time series data
        '''

        current_app.logger.debug('Plotting Time Series')

        # Define some plot parameters
        kwargs = dict(linewidth=1.5,
                      alpha=0.7,
                      linestyle='None',
                      marker=".",
                      markersize=10,
                      markeredgecolor='k')

        # First check if we have a multiple stream data
        if isinstance(data, list):
            current_app.logger.debug('Plotting Multiple Streams')
            ooi_plots.plot_multiple_streams(fig,
                                            ax,
                                            data,
                                            colors,
                                            title_font=title_font,
                                            axis_font=axis_font,
                                            tick_font=tick_font,
                                            width_in=width_in,
                                            plot_qaqc=plot_qaqc,
                                            **kwargs)

        # Check for a single time series plot
        elif len(data['x_field']) == 1 and len(data['y_field']) == 1:
            xlabel = data['x_field'][0]
            ylabel = data['y_field'][0]
            x = data['x'][xlabel]
            y = data['y'][ylabel]

            # QAQC logic
            if plot_qaqc >= 10:
                # Plot all of the qaqc flags results
                qaqc_data = data['qaqc'][ylabel]

            elif plot_qaqc >= 1:
                # This is a case where the user wants to plot just one of the 9 QAQC tests
                ind = np.where(data['qaqc'][ylabel] != plot_qaqc)
                data['qaqc'][ylabel][ind] = 0
                qaqc_data = data['qaqc'][ylabel]
            else:
                qaqc_data = []

            ooi_plots.plot_time_series(fig,
                                       is_timeseries,
                                       ax,
                                       x,
                                       y,
                                       title=data['title'],
                                       xlabel=xlabel,
                                       ylabel=ylabel + " (" +
                                       data['y_units'][0] + ")",
                                       title_font=title_font,
                                       axis_font=axis_font,
                                       tick_font=tick_font,
                                       scatter=use_scatter,
                                       events=events,
                                       qaqc=qaqc_data,
                                       **kwargs)

        # Must be a multiple yaxes plot, single stream
        else:
            xdata = {}
            xdata['time'] = data['x']['time']
            ydata = data['y']
            units = data['y_units']
            for ind, key in enumerate(ydata):
                xdata[key] = data['x']['time']
                # QAQC logic
                if plot_qaqc >= 10:
                    # Plot all of the qaqc flags results
                    pass
                elif plot_qaqc >= 1:
                    # This is a case where the user wants to plot just one of the 9 QAQC tests
                    ind = np.where(data['qaqc'][key] != plot_qaqc)
                    data['qaqc'][key][ind] = 0
                else:
                    data['qaqc'][key] = []

            ooi_plots.plot_multiple_yaxes(fig,
                                          ax,
                                          xdata,
                                          ydata,
                                          colors,
                                          title=data['title'],
                                          units=units,
                                          axis_font=axis_font,
                                          title_font=title_font,
                                          tick_font=tick_font,
                                          scatter=use_scatter,
                                          width_in=width_in,
                                          qaqc=data['qaqc'],
                                          **kwargs)

    elif plot_layout == "depthprofile":
        '''
        Plot depth profiles (overlay)
        '''

        current_app.logger.debug('Plotting Depth Profile')
        # Define some plot parameters
        kwargs = dict(linewidth=1.5, alpha=0.7)
        xlabel = data['x_field'] + " (" + request.args.get('x_units') + ")"
        ylabel = data['y_field'] + " (" + request.args.get('y_units') + ")"

        if plot_profile_id is None:

            for profile_id in range(0, np.shape(data['x'])[0]):
                # Remove the bad data
                qaqc_data = data['qaqc'][data['x_field']]

                ooi_plots.plot_profile(fig,
                                       ax,
                                       data['x'][profile_id],
                                       data['y'][profile_id],
                                       xlabel=xlabel,
                                       ylabel=ylabel,
                                       axis_font=axis_font,
                                       tick_font=tick_font,
                                       scatter=use_scatter,
                                       **kwargs)
        else:
            if int(plot_profile_id) < int(np.shape(data['x'])[0]):
                # get the profile selected
                ooi_plots.plot_profile(fig,
                                       ax,
                                       data['x'][int(plot_profile_id)],
                                       data['y'][int(plot_profile_id)],
                                       xlabel=xlabel,
                                       ylabel=ylabel,
                                       axis_font=axis_font,
                                       tick_font=tick_font,
                                       scatter=use_scatter,
                                       **kwargs)
            else:
                # return something
                ooi_plots.plot_profile(fig,
                                       ax,
                                       data['x'][0],
                                       data['y'][0],
                                       xlabel=xlabel,
                                       ylabel=ylabel,
                                       axis_font=axis_font,
                                       tick_font=tick_font,
                                       scatter=use_scatter,
                                       **kwargs)
        plt.gca().invert_yaxis()

    elif plot_layout == 'ts_diagram':
        '''
        Plot a Temperature-Salinity diagram
        '''

        current_app.logger.debug('Plotting T-S Diagram')

        # Define some plot parameters
        kwargs = dict(color='r', marker='o')

        # This should be used with 'real' data only (NO COUNTS!!)
        x = data['y'][data['y_field'][0]]
        y = data['y'][data['y_field'][1]]
        xlabel = data['y_field'][0] + " (" + data['y_units'][0] + ")"
        ylabel = data['y_field'][1] + " (" + data['y_units'][1] + ")"

        # # Mask the bad data
        # qaqc_x = data['qaqc'][data['y_field'][0]] < 1
        # qaqc_y = data['qaqc'][data['y_field'][1]] < 1
        # mask = qaqc_x & qaqc_y

        # x = x[mask]
        # y = x[mask]

        # if len(x) <= 0:
        #     raise(Exception('No good data avaliable!'))

        ooi_plots.plot_ts_diagram(ax,
                                  x,
                                  y,
                                  title=data['title'],
                                  xlabel=xlabel,
                                  ylabel=ylabel,
                                  title_font=title_font,
                                  axis_font=axis_font,
                                  tick_font=tick_font,
                                  **kwargs)

    elif plot_layout == 'quiver':
        '''
        Plot magnitude and direction as a time series on a quiver plot
        '''

        current_app.logger.debug('Plotting Quiver')
        # color='#0000FF',
        # edgecolors='#000000',
        kwargs = dict(units='y',
                      scale_units='y',
                      scale=1,
                      headlength=5,
                      headaxislength=5,
                      width=0.025,
                      alpha=0.5)

        time = mdates.date2num(data['x']['time'])
        start = plot_options['st_date']
        end = plot_options['ed_date']

        start_dt = mdates.date2num(
            datetime.strptime(start.split('.')[0], '%Y-%m-%dT%H:%M:%S'))
        end_dt = mdates.date2num(
            datetime.strptime(end.split('.')[0], '%Y-%m-%dT%H:%M:%S'))

        u = data['y'][data['y_field'][0]]
        v = data['y'][data['y_field'][1]]
        ylabel = data['y_field'][0] + " (" + data['y_units'][0] + ")"

        # # Mask the bad data
        # qaqc_u = data['qaqc'][data['y_field'][0]] < 1
        # qaqc_v = data['qaqc'][data['y_field'][1]] < 1
        # mask = qaqc_u & qaqc_v

        # u = u[mask]
        # v = v[mask]
        # time = time[mask]

        # if len(u) <= 0:
        #     raise(Exception('No good data avaliable!'))

        ooi_plots.plot_1d_quiver(fig,
                                 ax,
                                 time,
                                 u,
                                 v,
                                 title=data['title'] + '\n' + 'Quiver Plot',
                                 ylabel=ylabel,
                                 tick_font=tick_font,
                                 title_font=title_font,
                                 axis_font=axis_font,
                                 start=start_dt,
                                 end=end_dt,
                                 **kwargs)

    elif plot_layout == '3d_scatter':
        '''
        Plot 3d scatter plot
        '''

        current_app.logger.debug('Plotting 3D Scatter')

        time = data['x']['time']
        xlabel = data['y_field'][0]
        ylabel = data['y_field'][1]
        zlabel = data['y_field'][2]
        x = data['y'][xlabel]
        y = data['y'][ylabel]
        z = data['y'][zlabel]

        # # Mask the bad data
        # qaqc_x = data['qaqc'][xlabel] < 1
        # qaqc_y = data['qaqc'][ylabel] < 1
        # qaqc_z = data['qaqc'][zlabel] < 1
        # mask = qaqc_x & qaqc_y & qaqc_z

        # x = x[mask]
        # y = x[mask]

        # if len(x) <= 0:
        #     raise(Exception('No good data avaliable!'))

        ooi_plots.plot_3d_scatter(
            fig,
            ax,
            x,
            y,
            z,
            title=data['title'] + '\n' + '3D Scatter',
            xlabel=xlabel + " (" + data['y_units'][0] + ")",
            ylabel=ylabel + " (" + data['y_units'][1] + ")",
            zlabel=zlabel + " (" + data['y_units'][2] + ")",
            title_font=title_font,
            tick_font=tick_font,
            axis_font=axis_font)

    elif plot_layout == 'rose':
        '''
        Plot rose
        '''
        plt.close(fig)  # Need to create new fig and axes here
        current_app.logger.debug('Plotting Rose')

        xlabel = data['y_field'][0]
        ylabel = data['y_field'][1]
        magnitude = data['y'][xlabel]
        direction = data['y'][ylabel]

        # # Mask the bad data
        # qaqc_mag = data['qaqc'][xlabel] < 1
        # qaqc_dir = data['qaqc'][ylabel] < 1
        # mask = qaqc_mag & qaqc_dir

        # magnitude = magnitude[mask]
        # direction = direction[mask]

        # if len(magnitude) <= 0:
        #     raise(Exception('No good data avaliable!'))

        legend_title = xlabel + " (" + data['y_units'][0] + ")"
        size = height if height <= width else width
        size = 6 if size < 6 else size
        hypot = np.sqrt(size**2 + size**2) + 1
        fig = ooi_plots.plot_rose(magnitude,
                                  direction,
                                  figsize=size,
                                  bins=5,
                                  title=data['title'],
                                  title_font=title_font,
                                  legend_title=legend_title,
                                  fontsize=int(hypot) + 2)

    buf = io.BytesIO()

    # plt.tick_params(axis='both', which='major', labelsize=10)

    if plot_format not in ['svg', 'png']:
        plot_format = 'svg'
    plt.savefig(buf, format=plot_format)
    buf.seek(0)

    plt.close(fig)

    return buf
Пример #19
0
'''
Plot a counting Poisson process
'''

import prettyplotlib as ppl
from prettyplotlib import plt

import numpy

T = 10.
dt = 0.001

fig, ax, = ppl.subplots(1,figsize=(6,5));

Ns = numpy.zeros((int(T/dt),3))
la = [0.5,1.0,2.]

for i in range(3):
    for n in range(Ns.shape[0]):
        if numpy.random.rand()<la[i]*dt:
            Ns[n,i] = Ns[n-1,i]+1
        else:
            Ns[n,i] = Ns[n-1,i]
legends=[]
for i in la:
    legends.append(r'$\lambda = %.2lf$'%i)
for i in range(3):
    ppl.plot( numpy.arange(0.0,dt*Ns.shape[0],dt), Ns[:,i],label=legends[i], linewidth=1.5, ax=ax )
ppl.legend(ax,loc=2)
plt.savefig('../figures/figure_2_1.png',dpi=300)
plt.savefig('../figures/figure_2_1.pdf')
nlevels = len((contour_levels)) if len((contour_levels)) < 7 else 12

cmap = cm.jet

h = plt.contourf(freq, deg, spectrum, nlevels, cmap=cmap)
# h = plt.pcolor(freq, deg, spectrum)
# fig.colorbar(h, aspect=5)

ax.set_ylabel('Direction (deg)', **axis_font)
ax.set_xlabel('Frequency (Hz)', **axis_font)
ax.set_title('Contour 2D Spectrum', **title_font)

# <codecell>

# Now plot the wave heights
fig, ax = ppl.subplots(3, 1, figsize=(12, 18))

hs = nc.variables['hs'][:]
h = ppl.plot(ax[0], noutcdates, hs, linewidth=2.0, color='b')
ax[0].set_ylabel('Significant Wave Height (m)')
ax[0].set_title('Wave Height', **title_font)

# Now plot the wave period

tp = 1 / nc.variables['fp'][:]
h = ppl.plot(ax[1], noutcdates, tp, linewidth=2.0, color='r')
ax[1].set_ylabel('Peak Period (s)')
ax[1].set_title('Wave Period', **title_font)

# Now plot the wave direction
Пример #21
0
def plot_data_compare_2(interval1,data1_1, data1_2, data1_3, 
                      interval2, data2_1, data2_2, data2_3,
                      interval3, data3_1, data3_2, data3_3,
                      interval_flight, data_flight,
                      names1, style, p_title1, names2, p_title2, names3, p_title3,dycoms):

  close='all'
  if ( style == 0): 


    fig, ax = ppl.subplots()
    color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors
    color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors
    
    
    
#    ax.plot(interval1,data1_1, color='black', label=names1[1])
#    ax.plot(interval1,data1_2, color='red',  label=names1[2])
#    ax.plot(interval1,data1_3, color='blue',linestyle='-', label=names1[3])
    ax.plot(interval1,data1_3, color=color_set_2[4],linewidth=2, label=names1[3])

    data2_1=data2_1*30/18 # add the scaling factor
    data2_2=data2_2*30/18
    if (dycoms ==0):     
      data2_3=data2_3*30/18*1.9
    else: 
      data2_3=data2_3*30/18*2
#    ax.plot(interval2,data2_1, color='black',linestyle='--', label=names2[1])
#    ax.plot(interval2,data2_2, color='red',linestyle='--',  label=names2[2])
    ax.plot(interval2,data2_3, color=color_set_2[6],linewidth=2, label=names2[3])
    if (dycoms==0):
      data3_1=data3_1*50/18 # add the scaling factor
      data3_2=data3_2*50/18
      data3_3=data3_3*50/18*0.92
#     ax.plot(interval3,data3_1, color='black',linestyle=':',linewidth=2, label=names3[1])
#     ax.plot(interval3,data3_2, color='red',linestyle=':',linewidth=2,  label=names3[2])
      ax.plot(interval3,data3_3,color=color_set_2[8],linewidth=2, label=names3[3])

########################################################################
#playground
########################################################################
#    print interval1[0:34]
#    print data1_3[0:34]
#    size=1000000
#    dist_names = ['alpha', 'beta', 'arcsine',
#                  'weibull_min', 'weibull_max', 'rayleigh']
#    
#    for dist_name in dist_names:
#        dist = getattr(scipy.stats, dist_name)
#        param = dist.fit(data1_3[23:34])
#        pdf_fitted = dist.pdf(interval1[23:34], *param[:-2], loc=param[-2], scale=param[-1]) * size
#        ax.plot(pdf_fitted, label=dist_name)
#    plt.legend(loc='upper left')

#    beg=26
#    end=beg+34
#    beg_l=beg+1
#    end_l=beg_l+15
#    mirror=np.zeros(50)
#    dummy=np.zeros(16)
#    dummy[0:15]=data3_3[beg_l:end_l]
#    dummy=dummy[::-1]
#    mirror[0:16]=dummy[0:16]
#    mirror[16:50]=data3_3[beg:end]
    
#    integral_data= np.zeros(1)  
#    for i in np.arange(23,len(data3_3)):
#      integral_data=integral_data+data3_3[i]*0.05
      

#    approx_var_1= np.zeros(1)  
#    approx_var_2= np.zeros(1)  
#    j=0
#    for i in np.arange(21,len(data3_3)):
#      if (approx_var_2 < 1 ):
#        approx_var_1=approx_var_1+ data3_3[i]*0.05 
#        #approx_var_2=approx_var_1 -integral_data*2*0.3413
#        approx_var_2=approx_var_1 -np.std(mirror)
#        j=j+1
    if (dycoms ==0):     
      log_data= np.zeros(100)  
      log_interval= np.zeros(100) 
   
      for i in np.arange(len(data3_3)):
        if (data3_3[i] != 0):
          log_data[i] = np.log(data3_3[i])
        elif (data3_3[i] == 0):
          log_data[i]=data3_3[i]
      j=1
      max_val=max(log_data)   
      max_val_pos=len(log_data)+1 
      for i in np.arange(len(log_data)):
        if ( log_data[i] == max_val):
          max_val_pos=i
        if (i > max_val_pos):
          if (log_data[i] <= 0):
            end_pos=i
            break
            
  
      z = np.polyfit(interval3[24:end_pos+1], log_data[24:end_pos+1], 2)    
      print 'polyfit',z
      p = np.poly1d(z)
      #ax.plot(interval3[24:end_pos+1], np.exp(log_data[24:end_pos+1]), '.', color=color_set[4], label='Fiting points' )
  
      mean=z[1]/(-2*z[0])
      sigma_square=(1/(-2*z[0]))
      
      sigma_extrapolation=0.8**2
      a=-1/(2*sigma_extrapolation)
      mean_extrapolation=z[1]/(-2*a)
      
      x = np.linspace(0,mean+6,1000)
      print 'mean and sigma_square', mean, sigma_square 
      #y= (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) 
      y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) )
      y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) )
      
      #STATISTICS
      skewness=0
      for o in np.arange(len(x)):
        skewness=skewness +((x[0]-mean)/np.sqrt(sigma_square))**3
      skewness=skewness/len(x)
      print 'skewness', skewness
  
      ax.plot(x,y , color=color_set[2], label='Gaussian fit', linestyle='--', linewidth=2)
      ax.plot(x,y_extrapolation , color=color_set[5], label='Gaussian extrapolation t=60', linestyle='--', linewidth=2)
  
      data_flight=data_flight *5*10**7
      ax.plot(interval_flight,data_flight, color=color_set[9],linestyle='-', linewidth=3, label='Flight measurements')
 
    else:
      log_data= np.zeros(100)  
      log_interval= np.zeros(100) 
   
      for i in np.arange(len(data2_3)):
        if (data2_3[i] != 0):
          log_data[i] = np.log(data2_3[i])
        elif (data2_3[i] == 0):
          log_data[i]=data2_3[i]
      j=1
      max_val=max(log_data)   
      max_val_pos=len(log_data)+1 
      for i in np.arange(len(log_data)):
        if ( log_data[i] == max_val):
          max_val_pos=i
        if (i > max_val_pos):
          if (log_data[i] <= 0):
            end_pos=i
            break
            
       
      z = np.polyfit(interval2[24:end_pos+1], log_data[24:end_pos+1], 2)    
      print 'polyfit',z
      p = np.poly1d(z)
     #ax.plot(interval3[24:end_pos+1], np.exp(log_data[24:end_pos+1]), '.', color=color_set[4], label='Fiting points' )
  
      mean=z[1]/(-2*z[0])
      sigma_square=(1/(-2*z[0]))
      
      sigma_extrapolation=0.8**2
      a=-1/(2*sigma_extrapolation)
      mean_extrapolation=z[1]/(-2*a)
      
      x = np.linspace(0,mean+6,1000)
      print 'mean and sigma_square', mean, sigma_square 
      #y= (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) 
      y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) )
      y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) )
      
      ax.plot(x,y , color=color_set[3], label='Gaussian fit', linestyle='--', linewidth=2)
#      ax.plot(x,y_extrapolation , color=color_set[5], label='Gaussian extrapolation t=60', linestyle='--', linewidth=2)
    

#    ax.plot(interval1[beg-16:beg+34],mirror, color='red')


#    mean = 1.24
#    variance = 0.009
#    variance_arb = 0.001
#    sigma = np.sqrt(variance)
#    x = np.linspace(-3,5,1000)
#    y = mlab.normpdf(x,mean,sigma)
#    y = y*20000*(variance_arb/variance)
#    ax.plot(x,y, color='magenta')
########################################################################
#playground end
########################################################################

    #axes = plt.gca()
    #axes.grid(True)

    ax.set_yscale('symlog')
    #ax.set_title(p_title3)#,fontdict=font)
#    if (dycoms ==0):     
#      plt.title(p_title3, fontsize=size_title)#,fontdict=font)
#    else:
#      plt.title(p_title2, fontsize=size_title)#,fontdict=font)
    plt.xlabel('Liquid', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt
    plt.ylabel('Amount of particles', fontsize=size_axes)#,fontdict=font)
    plt.xlim(0,4)
    plt.ylim([10,10**8])
    plt.legend(loc=1, frameon=False)  
    
    plt.show()
        transform = np.linalg.eig(solver.H)[1] # utils.sorted_eig(solver.H)[1] #
        
        rearranged_basis_transform = np.zeros(transform.shape)
        
        for basis_vec in transform.T:
            if np.count_nonzero(basis_vec) == 1:
                rearranged_basis_transform[:,2] = basis_vec
            elif np.all(basis_vec >= 0) or np.all(basis_vec <= 0):
                rearranged_basis_transform[:,1] = basis_vec
            else:
                rearranged_basis_transform[:,0] = basis_vec
            
        site_exciton_transform[j,i] = rearranged_basis_transform
        exciton_steady_states[j,i] = np.dot(rearranged_basis_transform.T, np.dot(ss, rearranged_basis_transform))
        
fig,ax = ppl.subplots(ncols=2, nrows=2, figsize=(8,7))
lw = 2

# Fano factor
plt.sca(ax[0,0])
ax[0,0].axhline(1, ls='--', color='grey')
ax[0,0].text(-10, 1.25, 'a.')
for i in range(T_c_values.size):
    ppl.plot(bias_values, F2[i], linewidth=lw, label=r'$T_c = $' + str(T_c_values[i]), show_ticks=True)
ax[0,0].set_xlabel(r'$\epsilon / \Gamma_L$')
ax[0,0].set_ylabel('Fano factor')
#ax.set_ylim(0.3, 1.35)
ppl.legend(fontsize=10).draggable()

# coherence
plt.sca(ax[0,1])
Пример #23
0
def plot_fitting(interval3, data3_1, data3_2, data3_3):
    
  #COLORS FOR FIGURES
  fig, ax = ppl.subplots()
  color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors
  color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors

  #SCALE DATA
  data3_3=data3_3*50/18*0.92
  #ax.plot(interval3,data3_3,color=color_set_2[8],linewidth=l_w_1, label=names3[3])

  
  
  #!!!!!!!!!!!!!
  #Fitting
  #!!!!!!!!!!!!!
  log_data= np.zeros(100)  
  log_interval= np.zeros(100) 

  for i in np.arange(len(data3_3)):
    if (data3_3[i] != 0):
      log_data[i] = np.log(data3_3[i])
    elif (data3_3[i] == 0):
      log_data[i]=data3_3[i]
  j=1
  max_val=max(log_data)   
  max_val_pos=len(log_data)+1 
  for i in np.arange(len(log_data)):
    if ( log_data[i] == max_val):
      max_val_pos=i
    if (i > max_val_pos):
      if (log_data[i] <= 0):
        end_pos=i
        break
        
  begin_pos=s_point
  print 'mean is set to', interval3[begin_pos] 
  z = np.polyfit(interval3[begin_pos:end_pos+1], log_data[begin_pos:end_pos+1], 2)    
  print 'polyfit',z
  p = np.poly1d(z)
  ax.plot(interval3[begin_pos:end_pos+1], log_data[begin_pos:end_pos+1], marker='D', color=color_set[5], label='Fitting points' )
  ax.plot(interval3, log_data, '-', color=color_set_2[8],linewidth=l_w_1, label='Lagrange' )

  mean=z[1]/(-2*z[0])
  sigma_square=(1/(-2*z[0]))

  #!!!!!!!!
  #VERDI  CAREFULL OLD VALUE FOR SIGAM EXTRAPOLATION
  #!!!!!!!!
  sigma_extrapolation=0.8**2
  a=-1/(2*sigma_extrapolation)
  mean_extrapolation=z[1]/(-2*a)
  
  x = np.linspace(0,mean+6,1000)
  print 'mean and sigma_square', mean, sigma_square 
  y_log=( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) )
  y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) )
  y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) )
  
  ax.plot(x,y_log , color=color_set[2], label='Gaussian fit', linestyle='--', linewidth=l_w_2)
  
  #PLOT PROPERTIES
  plt.xlabel(r'$M/M_r$', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt
  plt.ylabel('Amount of cloud droplets', fontsize=size_axes)#,fontdict=font)
  plt.legend(loc=1, frameon=False)  
  
  plt.xlim(0,4)
  plt.ylim(0,20)
  plt.show()
Пример #24
0
    while dist > 1e-10:
        matern0 = matern1
        matern1 = IterateOnce(matern0, K_matern, dx,alpha =0.1)
        dist = SquaredDistance(matern0,matern1)
        print dist

    OU0 = K_ou(xs)
    OU1 = IterateOnce(OU0, K_ou, dx,alpha=0.1)
    dist = SquaredDistance(OU0,OU1)
    while dist > 1e-10:
        OU0 = OU1
        OU1 = IterateOnce(OU0, K_ou, dx,alpha =0.1)
        dist = SquaredDistance(OU0,OU1)
        print dist

    fig, (ax1,ax2,ax3) = ppl.subplots(3,1)
    #ax1 = plt.subplot(311)
    #ax2 = plt.subplot(312)
    #ax3 = plt.subplot(313)
    plt.gcf().suptitle("Posterior kernels")

    xs = xs[:6000]
    OU1 = OU1[:6000]
    matern1 = matern1[:6000]
    rbf1 = rbf1[:6000]

    ppl.plot(xs,K_ou(xs),label=r'OU prior kernel',ax=ax1)
    ppl.plot(xs,OU1,label = r'OU posterior kernel',ax=ax1)
    ppl.legend(ax1)
    ppl.plot(xs,K_matern(xs),label=r'Matern prior kernel',ax=ax2)
    ppl.plot(xs,matern1, label=r'Matern posterior kernel',ax=ax2)
Пример #25
0
  avg3_time=avg3_time*50/60
  avg5_time=avg5_time*50/60
  avg6_time=avg6_time*50/60

else:
  data_name='profile/dy_re800_general_avg_5s.dat'
  avg5_x, avg5_y = np.loadtxt(data_name, unpack=True)
  
  data_name='profile/dy_re800_general_avg_6s.dat'
  avg6_x, avg6_y = np.loadtxt(data_name, unpack=True)
########################################################################
#PLOT
########################################################################


fig, ax = ppl.subplots()
color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors
color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors

if (diff == 1):
  ax.plot(avg5_time,avg5_value , color=color_set[3], label='Parcel Liquid', linestyle='-',linewidth=l_w_1)
  ax.plot(avg6_time,avg6_value , color=color_set[5], label='Droplet Liquid', linestyle='-',linewidth=l_w_1)

else:
  avg5_x[:]=avg5_x[:]/np.max(avg5_x)
  avg6_x[:]=avg6_x[:]/np.max(avg6_x)
  ax.plot(avg5_y,avg5_x, color=color_set[3], label='Parcel Liquid', linestyle='-',linewidth=l_w_1)
  ax.plot(avg6_y,avg6_x , color=color_set[5], label='Droplet Liquid', linestyle='-',linewidth=l_w_1)


#plt.xlim(0.9,2.6)
mean = data['mean']

from scipy.interpolate import interp1d
int_bias_values = np.linspace(-20,20,2000)
int_F2 = interp1d(bias_values, F2, kind='cubic')

data_mode = np.load('../../data/DQD_exact_mode_mean_F2_data.npz')
bias_values_mode = data_mode['bias_values']
F2_mode = data_mode['F2']
mean_mode = data_mode['mean']

# temp_data = np.load('../../data/DQD_HEOM_mean_F2_bias_strong_coupling_UBO_N7_K3_data_temp.npz')
# temp_F2 = temp_data['F2'][2]
# temp_bias_values = temp_data['bias_values']

fig,ax = ppl.subplots(1, 2, figsize=(8,3.5))
lw = 2

plt.sca(ax[0])
plt.text(-20, 0.0184, 'a.')
ppl.plot(bias_values, mean, linewidth=lw, label='non-perturbative', show_ticks=True)
ppl.plot(bias_values_mode, mean_mode[0,0], linewidth=lw, label='coherent mode', show_ticks=True)
ax[0].set_xlabel(r'$\epsilon / \Gamma_L$')
ax[0].set_ylabel(r'current / e')
ppl.legend(fontsize=10).draggable()


plt.sca(ax[1])
plt.text(-20, 0.98, 'b.')
ppl.plot(bias_values, F2, linewidth=lw, label='non-perturbative', show_ticks=True)
ppl.plot(bias_values_mode, F2_mode[0,0], linewidth=lw, label='coherent mode', show_ticks=True)
Пример #27
0
def plot_data_compare_2(interval1,data1_1, data1_2, data1_3, 
                      interval2, data2_1, data2_2, data2_3,
                      interval3, data3_1, data3_2, data3_3,
                      interval_flight, data_flight,
                      names1, style, p_title1, names2, p_title2, names3, p_title3,
                      dycoms,extrapolation,extrapolation_2 , fitting,flight, only_last, s_point):
  close='all'
  if ( style == 0): 
    #COLORS FOR PLOTTING 
    fig, ax = ppl.subplots()
    color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors
    color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors
    #color_set_2 = brewer2mpl.get_map('Reds', 'sequential', 9).mpl_colors
    color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors
   
  #!!!!!!!!!!!!!
  #General
  #!!!!!!!!!!!!!
    
    
#    ax.plot(interval1,data1_1, color='black', linewidth=l_w_1,label=names1[1])
#    ax.plot(interval1,data1_2, color='red',  linewidth=l_w_1,label=names1[2])
#    ax.plot(interval1,data1_3, color='blue',linestyle='-', label=names1[3])

    if (only_last !=1):
      #ax.plot(interval1,data1_3, color=color_set_2[8],linewidth=l_w_1, label=names1[3])
      ax.plot(interval1,data1_3, color=color_set[1],linewidth=l_w_1, label=names1[3])

    if (dycoms ==0):     
      data2_1=data2_1*30/18*1.3
      data2_2=data2_2*30/18*1.3
      data2_3=data2_3*30/18*1.3
    else: 
      data2_1=data2_1*30/18*1.75
      data2_2=data2_2*30/18*1.75
      data2_3=data2_3*30/18*1.75
#    ax.plot(interval2,data2_1, color='red',linestyle='-', linewidth=l_w_1,label=names2[1])
#    ax.plot(interval2,data2_2, color='black',linestyle='-', linewidth=l_w_1, label=names2[2])
    if (dycoms==1):
      if (only_last !=1):
        #ax.plot(interval2,data2_3, color=color_set_2[6],linewidth=l_w_1, label=names2[3])
        ax.plot(interval2,data2_3, color=color_set[3],linewidth=l_w_1, label=names2[3])
      else:  
        ax.plot(interval2,data2_3, color=color_set[1],linewidth=l_w_1, label=names2[3])
    else:
     # ax.plot(interval2,data2_3, color=color_set_2[6],linewidth=l_w_1, label=names2[3])
      if (only_last !=1):
        ax.plot(interval2,data2_3, color=color_set[3],linewidth=l_w_1, label=names2[3])
    if (dycoms==0):
      data3_1=data3_1*50/18*1.4 # add the scaling factor
      data3_2=data3_2*50/18*1.4
      data3_3=data3_3*50/18*1.4
      #ax.plot(interval3,data3_1, color='black',linestyle='-',linewidth=l_w_1, label=names3[1])
      #ax.plot(interval3,data3_2, color='red',linestyle='-',linewidth=l_w_1,  label=names3[2])
      #ax.plot(interval3,data3_3,color=color_set_2[4],linewidth=l_w_1, label=names3[3])
      if (only_last !=1):
        ax.plot(interval3,data3_3,color=color_set[5],linewidth=l_w_1, label=names3[3])
      else:
        if( flight ==0):
          ax.plot(interval3,data3_3,color=color_set[1],linewidth=l_w_1, label=names3[3])
  
  #!!!!!!!!!!!!!
  #Fitting
  #!!!!!!!!!!!!!
    if (dycoms ==0):     
      log_data= np.zeros(100)  
      log_interval= np.zeros(100) 
   
      for i in np.arange(len(data3_3)):
        if (data3_3[i] != 0):
          log_data[i] = np.log(data3_3[i])
        elif (data3_3[i] == 0):
          log_data[i]=data3_3[i]
      j=1
      max_val=max(log_data)   
      max_val_pos=len(log_data)+1 
      for i in np.arange(len(log_data)):
        if ( log_data[i] == max_val):
          max_val_pos=i
        if (i > max_val_pos):
          if (log_data[i] <= 0):
            end_pos=i
            break
            
      begin_pos=s_point
      print 'mean is set to', interval3[begin_pos] 
      print 'end_pos', end_pos 
      z = np.polyfit(interval3[begin_pos:end_pos+1], log_data[begin_pos:end_pos+1], 2)    
      print 'polyfit',z
      p = np.poly1d(z)
      #ax.plot(interval3[begin_pos:end_pos+1], np.exp(log_data[begin_pos:end_pos+1]), '.', color=color_set[5],linewidth=l_w_1, label='Fitting points' )
  
      mean=z[1]/(-2*z[0])
      sigma_square=(1/(-2*z[0]))
      
      #VERDI  
      if( flight ==0):
        sigma_extrapolation=0.545**2  #after 40 min
      else:  
        #sigma_extrapolation=0.764**2  #after 50 min
        sigma_extrapolation=0.74**2  #after 50 min
      #sigma_extrapolation=0.91**2  #after 60 min
      a=-1/(2*sigma_extrapolation)
      mean_extrapolation=z[1]/(-2*a)
      
      x = np.linspace(0,mean+6,1000)
      print 'mean and sigma_square', mean, sigma_square 
      y_log=( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) )
      y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) )
      y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) )
      
  
      if (flight != 1): #no fligh data
        if (fitting == 1):  #if we want fit
          ax.plot(x,y , color=color_set_3[0], label='Gaussian fit', linestyle='--', linewidth=l_w_2)
      if (extrapolation == 1):  #if we want extrapolation
        if( flight ==0):  #if we want no fligh data
          ax.plot(x,y_extrapolation , color=color_set[5], label='Extrapolation t=40', linestyle='--', linewidth=l_w_2)
          if(extrapolation_2==1): #if we want second extrapolation
            #extrapolation for all times
            growing=[0.91, 1.80, 5.37, 10.7, 21.4]
            for k in np.arange(len(growing)):
              sigma_extrapolation=growing[k]**2
              print sigma_extrapolation 
              x = np.linspace(0,mean+115,1000)
              y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) )
              ax.plot(x,y_extrapolation , color=color_set[k],  linestyle='--',linewidth=l_w_2)
        else: #if we want extrapolation with flight data together
          ax.plot(x,y_extrapolation , color=color_set[5], label=r'Extrapolation t$\,\approx\,$50 [min]', linestyle='--', linewidth=l_w_2)
      
      #SCALE FLIGHT DATA 
      data_flight=data_flight *5.5*10**7
      
      if (flight == 1):
        ax.plot(interval_flight,data_flight, color=color_set[9],marker='.',linestyle='None',markersize=m_s+9 , label='Flight measurements')
 
      
    else: #if we want DYCOMS instead of verdi
      log_data= np.zeros(100)  
      log_interval= np.zeros(100) 
   
      for i in np.arange(len(data2_3)):
        if (data2_3[i] != 0):
          log_data[i] = np.log(data2_3[i])
        elif (data2_3[i] == 0):
          log_data[i]=data2_3[i]
      j=1
      max_val=max(log_data)   
      max_val_pos=len(log_data)+1 
      for i in np.arange(len(log_data)):
        if ( log_data[i] == max_val):
          max_val_pos=i
        if (i > max_val_pos):
          if (log_data[i] <= 0):
            end_pos=i
            break
            
       
      z = np.polyfit(interval2[s_point:end_pos+1], log_data[s_point:end_pos+1], 2)    
      print 'polyfit',z
      p = np.poly1d(z)
      #ax.plot(interval3[24:end_pos+1], np.exp(log_data[24:end_pos+1]), '.', color=color_set[4], label='Fiting points' )
  
      mean=z[1]/(-2*z[0])
      sigma_square=(1/(-2*z[0]))
     
      #DYCOMS 
      sigma_extrapolation=0.525**2
      a=-1/(2*sigma_extrapolation)
      mean_extrapolation=z[1]/(-2*a)
      print sigma_extrapolation
      
      x = np.linspace(0,mean+6,1000)
      print 'mean and sigma_square', mean, sigma_square 
      y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) )
      y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) )
      
      if (fitting == 1):
        ax.plot(x,y , color=color_set_3[0], label='Gaussian fit', linestyle='--', linewidth=l_w_2)
      if (extrapolation == 1):
        ax.plot(x,y_extrapolation , color=color_set[5], label='Extrapolation t=40', linestyle='--',linewidth=l_w_2)
        if(extrapolation_2==1):    
          #extrapolation for all times
          growing=[0.76, 1.49, 4.4, 8.75, 17.4]
          for k in np.arange(len(growing)):
            sigma_extrapolation=growing[k]**2
            print sigma_extrapolation 
            x = np.linspace(0,mean+100,1000)
            y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) )
            ax.plot(x,y_extrapolation , color=color_set[k],  linestyle='--',linewidth=l_w_2)
 


  #!!!!!!!!!!!!!
  #Plotting
  #!!!!!!!!!!!!!
    
    #GRID LINES
    #axes = plt.gca()
    #axes.grid(True)

    ax.set_yscale('symlog')
#    if (dycoms ==0):     
#      plt.title(p_title3, fontsize=size_title)#,fontdict=font)
#    else:
#      plt.title(p_title2, fontsize=size_title)#,fontdict=font)
    plt.xlabel(r'$M/M_r$', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt
    plt.ylabel('Relative amount of droplets', fontsize=size_axes)#,fontdict=font)
    if (extrapolation == 1):
      plt.xlim(0.9,5.2)
      plt.xlim(0.8,4.5)
      #plt.xlim(1.3,5.2)
      if(extrapolation_2==1):    
        plt.xlim(0.9,115)
      elif(flight == 1):
        ax2 = ax.twiny()
        ax2.set_xlabel(r"Radius [$\mu m$]", fontsize=size_axes)
        tick_locs = [1,2,3,4,5]
        tick_lbls = [10.3,13,14.9,16.4,17.7]
          
        ax2.set_xticks(tick_locs)
        ax2.set_xticklabels(tick_lbls)
        #ax2.set_xlim(1.3,5.2)
        ax2.set_xlim(0.8,4.5)
        ax.legend(loc=0, frameon=False)
    elif(fitting == 1):
      plt.xlim(0.9,2.6)
    else:
      plt.xticks([0.1,0.5,1,1.5,2.0,2.5,3.0,3.5,4.0]) 
      plt.xlim(0.1,2.2)
    plt.ylim([10,10**8])
    #plt.ylim([10**3,10**9])
    #plt.xlim([0.9,3.0])
    plt.legend(loc=1, frameon=False)  
    

    #Hide the right and top spines
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    #Only show ticks on the left and bottom spines
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')
  
    plt.show()
Пример #28
0
def several_fits(all_interval3, all_data3_3,
                  names3, p_title3, time_real_1,time_real_2,time_real_3,
                  delta_s,t_real, time_data, dycoms, fitting, s_point):


  #SETUP COLORS FOR PLOTTING
  fig, ax = ppl.subplots()
  color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors
  color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors
  #color_set_2 = brewer2mpl.get_map('Reds', 'sequential', 9).mpl_colors
  color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors
  
  #scale data  
  if (dycoms == 0):
    all_data3_3=all_data3_3*50/18*0.92
  else:
    all_data3_3=all_data3_3*30/18*1.75

  #DECIDE ABOUT PLOTTING STEPS
  time_real_data=np.zeros(len(time_data))
  for i in np.arange(len(time_data)): 
    time_real_data[i]=round(time_data[i]*t_real/60,2)
  if (dycoms==0):  
    steps=[9, 14, 22, 35]
  else:
    steps=[10, 20, 28, 35]
  c=1 #for color code

  #CONSTRUCT DATA FROM WHERE TO FIT (TAIL) AND PLOT DIFFERENT STEPS
  for k in steps:
    label_name='t=' + str(time_real_data[k]) + ' [min]'
    ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[c],linewidth=l_w_1, label=label_name)

    log_data= np.zeros(100)  
    log_interval= np.zeros(100) 
    for i in np.arange(len(all_data3_3[:,k])):
      if (all_data3_3[i,k] != 0):
        log_data[i] = np.log(all_data3_3[i,k])
      elif (all_data3_3[i,k] == 0):
        log_data[i]=all_data3_3[i,k]
    j=1
    max_val=max(log_data)   
    max_val_pos=len(log_data)+1 
    for i in np.arange(len(log_data)):
      if ( log_data[i] == max_val):
        max_val_pos=i
      if (i > max_val_pos):
        if (log_data[i] <= 0):
          end_pos=i
          break
          
    #CONSTRUCT FITS FOR SIMULATION STEPS
    z = np.polyfit(all_interval3[s_point:end_pos+1,k], log_data[s_point:end_pos+1], 2)    
    print 'point where fitting starts', all_interval3[s_point,k], np.exp(log_data[s_point])
    print 'polyfit',z
    p = np.poly1d(z)

    mean=z[1]/(-2*z[0])
    sigma_square=(1/(-2*z[0]))
   
    x = np.linspace(0,mean+6,1000)
    print 'mean and sigma_square', mean, sigma_square 
    y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) )

    print x[210]
    ax.plot(x[0:len(x)],y[0:len(y)] , color=color_set[c], linestyle='--', linewidth=l_w_2)

    c=c+2 #for color code


  #PLOTTING PROPERTIES
  ax.set_yscale('symlog')
  plt.xlabel(r'$M/M_r$', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt
  plt.ylabel('Amount of cloud droplets', fontsize=size_axes)#,fontdict=font)
  if(dycoms==0):
    plt.xlim(1.4,2.7)
  else:
    plt.xlim(1.4,2.3)
  plt.ylim([10,5*10**6])
  plt.legend(loc=1, frameon=False)  


  plt.show()
    transform = np.linalg.eig(H)[1]
    
    rearranged_basis_transform = rearrange_transform(transform)
    ss = site_steady_states[0,i]
    ss.shape = 3,3
    new_site_steady_states[0,i] = ss
    exciton_steady_states[0,i] = np.dot(rearranged_basis_transform.T, np.dot(ss, rearranged_basis_transform))
    
    for j,B in enumerate(beta_values):
        rearranged_basis_transform = rearrange_transform(transform)
        ss = site_steady_states[j+1,i]
        ss.shape = 3,3
        new_site_steady_states[j+1,i] = ss
        exciton_steady_states[j+1,i] = np.dot(rearranged_basis_transform.T, np.dot(ss, rearranged_basis_transform))

fig,ax = ppl.subplots(2,2, figsize=(8,7))
lw = 2

plt.sca(ax[0,0])
plt.axhline(1, ls='--', color='grey')
ppl.plot(bias_values, F2[0], linewidth=lw, ls='--', color='k', show_ticks=True)
for i in range(1,4):
    ppl.plot(bias_values, F2[i], linewidth=lw, label=r'$\beta = '+str(beta_values[i-1])+'$', show_ticks=True)
ppl.legend(fontsize=10).draggable()
ax[0,0].set_xlabel(r'$\epsilon / \Gamma_L$')
ax[0,0].set_ylabel(r'Fano factor')

plt.sca(ax[0,1])
ppl.plot(bias_values, np.abs(site_steady_states[0,:,5]), linewidth=lw, ls='--', color='k', show_ticks=True)
for i in range(1,4):
    ppl.plot(bias_values, np.abs(site_steady_states[i,:,5]), linewidth=lw, label=r'$\beta = '+str(beta_values[i-1])+'$', show_ticks=True)
Пример #30
0
def generate_plot(data, plot_options):
    # Define some fonts
    title_font = {'fontname': 'Calibri',
                  'size': '14',
                  'color': 'black',
                  'weight': 'bold'}

    axis_font = {'fontname': 'Calibri',
                 'size': '12',
                 'weight': 'bold'}

    tick_font = {'axis': 'both',
                 'labelsize': 8,
                 'width': 1,
                 'color': 'k'}

    # Get all the plot options
    plot_format = plot_options['plot_format']
    plot_layout = plot_options['plot_layout']
    plot_profile_id = plot_options['profileid']
    events = plot_options['events']
    width_in = plot_options['width_in']
    use_scatter = plot_options['use_scatter']
    plot_qaqc = plot_options['use_qaqc']

    # Generate the plot figure and axes
    if isinstance(data, dict):
        width = data['width']
        height = data['height']

        is_timeseries = False
        if "time" == data['x_field'][0]:
            data['x']['time'] = num2date(data['x']['time'], units='seconds since 1900-01-01 00:00:00', calendar='gregorian')
            is_timeseries = True
    else:
        width = data[0]['width']
        height = data[0]['height']
        for idx, dataset in enumerate(data):
            if "time" == dataset['x_field'][0]:
                data[idx]['x']['time'] = num2date(data[idx]['x']['time'], units='seconds since 1900-01-01 00:00:00', calendar='gregorian')

    fig, ax = ppl.subplots(1, 1, figsize=(width, height))

    # Calculate the hypotenuse to determine appropriate font sizes
    hypot = np.sqrt(width**2 + height**2) - 4
    tick_font['labelsize'] = int(hypot)
    axis_font['size'] = int(hypot) + 3
    title_font['size'] = int(hypot) + 5

    # Check the plot type and generate the plot!
    if plot_layout == "timeseries":
        '''
        Plot time series data
        '''

        current_app.logger.debug('Plotting Time Series')

        # Define some plot parameters
        kwargs = dict(linewidth=1.5,
                      alpha=0.7,
                      linestyle='None',
                      marker=".",
                      markersize=10,
                      markeredgecolor='k')

        # First check if we have a multiple stream data
        if isinstance(data, list):
            current_app.logger.debug('Plotting Multiple Streams')
            ooi_plots.plot_multiple_streams(fig, ax, data, colors,
                                            title_font=title_font,
                                            axis_font=axis_font,
                                            tick_font=tick_font,
                                            width_in = width_in,
                                            plot_qaqc=plot_qaqc,
                                            **kwargs)

        # Check for a single time series plot
        elif len(data['x_field']) == 1 and len(data['y_field']) == 1:
            xlabel = data['x_field'][0]
            ylabel = data['y_field'][0]
            x = data['x'][xlabel]
            y = data['y'][ylabel]

            # QAQC logic
            if plot_qaqc >= 10:
                # Plot all of the qaqc flags results
                qaqc_data = data['qaqc'][ylabel]

            elif plot_qaqc >= 1:
                # This is a case where the user wants to plot just one of the 9 QAQC tests
                ind = np.where(data['qaqc'][ylabel] != plot_qaqc)
                data['qaqc'][ylabel][ind] = 0
                qaqc_data = data['qaqc'][ylabel]
            else:
                qaqc_data = []

            ooi_plots.plot_time_series(fig, is_timeseries, ax, x, y,
                                       title=data['title'],
                                       xlabel=xlabel,
                                       ylabel=ylabel + " (" + data['y_units'][0] + ")",
                                       title_font=title_font,
                                       axis_font=axis_font,
                                       tick_font=tick_font,
                                       scatter=use_scatter,
                                       events=events,
                                       qaqc=qaqc_data,
                                       **kwargs)

        # Must be a multiple yaxes plot, single stream
        else:
            xdata = {}
            xdata['time'] = data['x']['time']
            ydata = data['y']
            units = data['y_units']
            for ind, key in enumerate(ydata):
                xdata[key] = data['x']['time']
                # QAQC logic
                if plot_qaqc >= 10:
                    # Plot all of the qaqc flags results
                    pass
                elif plot_qaqc >= 1:
                    # This is a case where the user wants to plot just one of the 9 QAQC tests
                    ind = np.where(data['qaqc'][key] != plot_qaqc)
                    data['qaqc'][key][ind] = 0
                else:
                    data['qaqc'][key] = []

            ooi_plots.plot_multiple_yaxes(fig, ax,
                                          xdata,
                                          ydata,
                                          colors,
                                          title=data['title'],
                                          units=units,
                                          axis_font=axis_font,
                                          title_font=title_font,
                                          tick_font=tick_font,
                                          scatter = use_scatter,
                                          width_in = width_in,
                                          qaqc=data['qaqc'],
                                          **kwargs)

    elif plot_layout == "depthprofile":
        '''
        Plot depth profiles (overlay)
        '''

        current_app.logger.debug('Plotting Depth Profile')
        # Define some plot parameters
        kwargs = dict(linewidth=1.5, alpha=0.7)
        xlabel = data['x_field'] + " (" + request.args.get('x_units') + ")"
        ylabel = data['y_field'] + " (" + request.args.get('y_units') + ")"

        if plot_profile_id is None:

            for profile_id in range(0, np.shape(data['x'])[0]):
                # Remove the bad data
                qaqc_data = data['qaqc'][data['x_field']]

                ooi_plots.plot_profile(fig,
                                       ax,
                                       data['x'][profile_id],
                                       data['y'][profile_id],
                                       xlabel=xlabel,
                                       ylabel=ylabel,
                                       axis_font=axis_font,
                                       tick_font=tick_font,
                                       scatter=use_scatter,
                                       **kwargs)
        else:
            if int(plot_profile_id) < int(np.shape(data['x'])[0]):
                # get the profile selected
                ooi_plots.plot_profile(fig,
                                       ax,
                                       data['x'][int(plot_profile_id)],
                                       data['y'][int(plot_profile_id)],
                                       xlabel=xlabel,
                                       ylabel=ylabel,
                                       axis_font=axis_font,
                                       tick_font=tick_font,
                                       scatter=use_scatter,
                                       **kwargs)
            else:
                # return something
                ooi_plots.plot_profile(fig,
                                       ax,
                                       data['x'][0],
                                       data['y'][0],
                                       xlabel=xlabel,
                                       ylabel=ylabel,
                                       axis_font=axis_font,
                                       tick_font=tick_font,
                                       scatter=use_scatter,
                                       **kwargs)
        plt.gca().invert_yaxis()

    elif plot_layout == 'ts_diagram':
        '''
        Plot a Temperature-Salinity diagram
        '''

        current_app.logger.debug('Plotting T-S Diagram')

        # Define some plot parameters
        kwargs = dict(color='r', marker='o')

        # This should be used with 'real' data only (NO COUNTS!!)
        x = data['y'][data['y_field'][0]]
        y = data['y'][data['y_field'][1]]
        xlabel = data['y_field'][0] + " (" + data['y_units'][0] + ")"
        ylabel = data['y_field'][1] + " (" + data['y_units'][1] + ")"

        # # Mask the bad data
        # qaqc_x = data['qaqc'][data['y_field'][0]] < 1
        # qaqc_y = data['qaqc'][data['y_field'][1]] < 1
        # mask = qaqc_x & qaqc_y

        # x = x[mask]
        # y = x[mask]

        # if len(x) <= 0:
        #     raise(Exception('No good data avaliable!'))

        ooi_plots.plot_ts_diagram(ax, x, y,
                                  title=data['title'],
                                  xlabel=xlabel,
                                  ylabel=ylabel,
                                  title_font=title_font,
                                  axis_font=axis_font,
                                  tick_font=tick_font,
                                  **kwargs)

    elif plot_layout == 'quiver':
        '''
        Plot magnitude and direction as a time series on a quiver plot
        '''

        current_app.logger.debug('Plotting Quiver')
        # color='#0000FF',
        # edgecolors='#000000',
        kwargs = dict(units='y',
                      scale_units='y',
                      scale=1,
                      headlength=1.0,
                      headaxislength=1.0,
                      width=0.002,
                      alpha=0.5)

        time = mdates.date2num(data['x']['time'])
        start = plot_options['st_date']
        end = plot_options['ed_date']

        start_dt = mdates.date2num(datetime.strptime(start.split('.')[0], '%Y-%m-%dT%H:%M:%S'))
        end_dt = mdates.date2num(datetime.strptime(end.split('.')[0], '%Y-%m-%dT%H:%M:%S'))

        u = np.array(data['y'][data['y_field'][0]])
        v = np.array(data['y'][data['y_field'][1]])
        ylabel = "Velocity" + " (" + data['y_units'][0] + ")"

        # # Mask the bad data
        # qaqc_u = data['qaqc'][data['y_field'][0]] < 1
        # qaqc_v = data['qaqc'][data['y_field'][1]] < 1
        # mask = qaqc_u & qaqc_v

        # u = u[mask]
        # v = v[mask]
        # time = time[mask]

        # if len(u) <= 0:
        #     raise(Exception('No good data avaliable!'))

        ooi_plots.plot_1d_quiver(fig, ax, time, u, v,
                                 title=data['title']+'\n'+'Quiver Plot',
                                 ylabel=ylabel,
                                 tick_font=tick_font,
                                 title_font=title_font,
                                 axis_font=axis_font,
                                 start=start_dt,
                                 end=end_dt,
                                 key_units = data['y_units'][0],
                                 **kwargs)

    elif plot_layout == 'stacked':
        '''
        Plot colored stacked time series
        '''

        current_app.logger.debug('Plotting Stacked')

        time = mdates.date2num(data['x']['time'])
        z = np.array(data['y'][data['y_field'][0]])
        label = data['y_field'][0] + " (" + data['y_units'][0] + ")"

        ooi_plots.plot_stacked_time_series(fig, ax, time, np.arange(len(z[0]))[::-1], z.transpose(),
                                           title=data['title']+'\n'+'Stacked Time Series Plot',
                                           ylabel='bin',
                                           cbar_title=label,
                                           title_font=title_font,
                                           axis_font=axis_font,
                                           tick_font=tick_font)

    elif plot_layout == '3d_scatter':
        '''
        Plot 3d scatter plot
        '''

        current_app.logger.debug('Plotting 3D Scatter')

        time = data['x']['time']
        xlabel = data['y_field'][0]
        ylabel = data['y_field'][1]
        zlabel = data['y_field'][2]
        x = np.array(data['y'][xlabel])
        y = np.array(data['y'][ylabel])
        z = np.array(data['y'][zlabel])

        # # Mask the bad data
        # qaqc_x = data['qaqc'][xlabel] < 1
        # qaqc_y = data['qaqc'][ylabel] < 1
        # qaqc_z = data['qaqc'][zlabel] < 1
        # mask = qaqc_x & qaqc_y & qaqc_z

        # x = x[mask]
        # y = x[mask]

        # if len(x) <= 0:
        #     raise(Exception('No good data avaliable!'))

        ooi_plots.plot_3d_scatter(fig, ax, x, y, z,
                                  title=data['title']+'\n'+'3D Scatter',
                                  xlabel=xlabel + " (" + data['y_units'][0] + ")",
                                  ylabel=ylabel + " (" + data['y_units'][1] + ")",
                                  zlabel=zlabel + " (" + data['y_units'][2] + ")",
                                  title_font=title_font,
                                  tick_font=tick_font,
                                  axis_font=axis_font)

    elif plot_layout == 'rose':
        '''
        Plot rose
        '''
        plt.close(fig)  # Need to create new fig and axes here
        current_app.logger.debug('Plotting Rose')

        xlabel = data['y_field'][0]
        ylabel = data['y_field'][1]
        magnitude = np.array(data['y'][xlabel])
        direction = np.array(data['y'][ylabel])

        # # Mask the bad data
        # qaqc_mag = data['qaqc'][xlabel] < 1
        # qaqc_dir = data['qaqc'][ylabel] < 1
        # mask = qaqc_mag & qaqc_dir

        # magnitude = magnitude[mask]
        # direction = direction[mask]

        # if len(magnitude) <= 0:
        #     raise(Exception('No good data avaliable!'))

        legend_title = xlabel + " (" + data['y_units'][0] + ")"
        size = height if height <= width else width
        size = 6 if size < 6 else size
        hypot = np.sqrt(size**2 + size**2) + 1
        fig = ooi_plots.plot_rose(magnitude, direction,
                                  figsize=size,
                                  bins=5,
                                  title=data['title'],
                                  title_font=title_font,
                                  legend_title=legend_title,
                                  fontsize=int(hypot)+2)

    buf = io.BytesIO()

    # plt.tick_params(axis='both', which='major', labelsize=10)

    if plot_format not in ['svg', 'png']:
        plot_format = 'svg'
    plt.savefig(buf, format=plot_format)
    buf.seek(0)

    plt.close(fig)

    return buf
Пример #31
0
    def make_hists(self, num_bins=None, use_prettyplotlib=True):

        if use_prettyplotlib:
            try:
                import prettyplotlib as plt
            except ImportError:
                import matplotlib.pyplot as plt
                use_prettyplotlib = False
                print "prettyplotlib not installed. Using matplotlib..."
        else:
            import matplotlib.pyplot as plt

        # Setup subplots if plotting together
        if self.subplot:
          num = len(self.columns)
          if num <= 3:
            ncols = 1
            nrows = num
          elif num <= 8:
            ncols = 2
            nrows = num / 2
          else:  # Max columns right now is 12
            ncols = 3
            nrows = num / 3
          # Check if we need an extra row.
          if num % ncols != 0:
            nrows += 1

          # Make the objects
          fig, axes = plt.subplots(nrows=nrows, ncols=ncols)

          # This is a bit awkward to get the indices, but my matplotlib version
          # doesn't use the same object type as prettyplotlib creates.
          posns = np.indices(axes.shape)
          x, y = posns[0].ravel(), posns[1].ravel()

        # Keep the mean, median, std.
        data_stats = {}
        for i, column in enumerate(self.columns):
          data = self.dataframe[column]
          data = data[np.isfinite(data)]
          if num_bins is None:
            num_bins = np.sqrt(len(data))

          data_stats[column] = [nanmean(data), nanstd(data), nanmedian(data)]

          if self.subplot:
            if use_prettyplotlib:
              plt.hist(axes[x[i], y[i]],data, num_bins, grid="y")
            else:
              axes[x[i], y[i]].hist(data, num_bins)
            axes[x[i], y[i]].set_xlabel(column)  # ADD UNITS!
          else:
            fig, axes = plt.subplots(1)
            axes.hist(data, num_bins)
            axes.set_xlabel(column)  # ADD UNITS!

          if self.verbose and not self.subplot:
            print column+" Stats: %s" % (data_stats[column])
            p.show()

          elif not self.subplot:
            fig.savefig(self.save_name+"_"+column+"."+self.save_type)
            p.close()

        if self.subplot:
          p.tight_layout()
          if self.verbose:
            for column in self.columns:
              print column+" Stats: %s" % (data_stats[column])
            p.show()
          else:
            fig.savefig(self.save_name+"_hists."+self.save_type)
Пример #32
0
def extrapolation_sigma(all_interval1, all_data1_3, all_interval2, all_data2_3,
                        all_interval3, all_data3_3,
                        names1,names2,names3, p_title3, time_real_1,time_real_2,time_real_3,
                        delta_s,t_real, dycoms, fitting, s_point):

  sp=5  #part of determination of first timestep of sigma calculation

  fig, ax = ppl.subplots()
  color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors

  #WE WILL ANALYZE THE DIFFERENT RE-NUMBER RUNS 

  #DATA RE800 
  if (dycoms == 1):
    cf=5
  else:
    cf=3
  shape= np.shape(all_interval1) 
  time_length=shape[1]
  
  data1_3= np.zeros(100)
  interval1= np.zeros(100)
  sigma_vector_1= np.zeros(time_length)

  for k in np.arange(sp+cf,time_length):
    data1_3[:] = all_data1_3[:,k]
    interval1[:] = all_interval1[:,k]
    log_data= np.zeros(100)  
   
    for i in np.arange(len(data1_3)):
      if (data1_3[i] != 0):
        log_data[i] = np.log(data1_3[i])
      elif (data1_3[i] == 0):
        log_data[i]=data1_3[i]
    j=1
    max_val=max(log_data)   
    max_val_pos=len(log_data)+1 
    for i in np.arange(len(log_data)):
      if ( log_data[i] == max_val):
        max_val_pos=i
      if (i > max_val_pos):
        if (log_data[i] <= 0):
          end_pos=i
          break
   
    z = np.polyfit(interval1[s_point:end_pos+1], log_data[s_point:end_pos+1], 2)    
    
    sigma_square=(1/(-2*z[0]))
    sigma_vector_1[k]= np.sqrt(sigma_square)
  sigma_fit_1 = np.polyfit(time_real_1[sp+cf:time_length], sigma_vector_1[sp+cf:time_length], 1)
  
  ax.plot(time_real_1[sp+cf:time_length],sigma_vector_1[sp+cf:time_length] , color=color_set[1],marker='.',
linestyle='None',markersize=m_s ,  label=names1[3])
  x_fit = np.linspace(0,60,1000)
  p = sigma_fit_1[0]*x_fit + sigma_fit_1[1] 
#  if (dycoms != 0): 
#    ax.plot(x_fit,p ,linestyle='--', color=color_set[2], label='Fiting', linewidth=l_w_1)


  #DATA RE400
  cf=3
  if (dycoms == 1):
    cf=5
  shape= np.shape(all_interval2) 
  time_length=shape[1]
  time_length_re400=shape[1]
  
  mean_fits400=np.zeros(50)
  data2_3= np.zeros(100)
  interval2= np.zeros(100)
  sigma_vector_2= np.zeros(time_length)
  for k in np.arange(sp+cf,time_length):
    data2_3[:] = all_data2_3[:,k]
    interval2[:] = all_interval2[:,k]

    log_data= np.zeros(100)  
   
    for i in np.arange(len(data2_3)):
      if (data2_3[i] != 0):
        log_data[i] = np.log(data2_3[i])
      elif (data2_3[i] == 0):
        log_data[i]=data2_3[i]
    j=1
    max_val=max(log_data)   
    max_val_pos=len(log_data)+1 
    for i in np.arange(len(log_data)):
      if ( log_data[i] == max_val):
        max_val_pos=i
      if (i > max_val_pos):
        if (log_data[i] <= 0):
          end_pos=i
          break
   
  
    mean_fits400[k]=log_data[s_point]
    z = np.polyfit(interval2[s_point:end_pos+1], log_data[s_point:end_pos+1], 2)    
    
    sigma_square=(1/(-2*z[0]))
    sigma_vector_2[k]= np.sqrt(sigma_square)
    #print sigma_square, z[0]
  sigma_fit_2 = np.polyfit(time_real_2[sp+cf:time_length], sigma_vector_2[sp+cf:time_length], 1)
  ax.plot(time_real_2[sp+cf:time_length],sigma_vector_2[sp+cf:time_length] , color=color_set[3],marker='.',linestyle='None',markersize=m_s,  label=names2[3])
  if (dycoms != 0): 
    #LIQUID AFTER SPECIFIED TIME  
    #1 hour
    x_fit = np.linspace(0,60,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=60: ', p[len(p)-1]
    #2 hour
    x_fit = np.linspace(0,120,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=120: ', p[len(p)-1]
    #6 hour
    x_fit = np.linspace(0,360,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=360: ', p[len(p)-1]
    #12 hour
    x_fit = np.linspace(0,720,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=720: ', p[len(p)-1]
    #24 hour
    x_fit = np.linspace(0,1440,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=1440: ', p[len(p)-1]
    #48 hour
    x_fit = np.linspace(0,2880,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=2880: ', p[len(p)-1]
    
    x_fit = np.linspace(0,40,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'Verschiebung: ', sigma_fit_2[1], 'Steigung: ', sigma_fit_2[0]
  if (dycoms != 0): 
    if (fitting == 1):
      print 'sigma at x=40: ', p[len(p)-1]
      ax.plot(x_fit,p ,linestyle='--', color=color_set[3], label='Fitting', linewidth=l_w_2)
      

  if (dycoms == 0):
    #DATA RE200
    cf=0
    shape= np.shape(all_interval3) 
    time_length=shape[1]
    
    data3_3= np.zeros(100)
    interval3= np.zeros(100)
    sigma_vector= np.zeros(time_length)
    #print sigma_vector[9]

    c= np.zeros(time_length)
  
    mean_fits200=np.zeros(50)
    for k in np.arange(sp+cf,time_length):
      data3_3[:] = all_data3_3[:,k]
      interval3[:] = all_interval3[:,k]
  
      log_data= np.zeros(100)  
      log_interval= np.zeros(100) 
     
      for i in np.arange(len(data3_3)):
        if (data3_3[i] != 0):
          log_data[i] = np.log(data3_3[i])
        elif (data3_3[i] == 0):
          log_data[i]=data3_3[i]
      j=1
      max_val=max(log_data)   
      max_val_pos=len(log_data)+1 
      for i in np.arange(len(log_data)):
        if ( log_data[i] == max_val):
          max_val_pos=i
        if (i > max_val_pos):
          if (log_data[i] <= 0):
            end_pos=i
            break

      mean_fits200[k]=log_data[s_point]

      z = np.polyfit(interval3[s_point:end_pos+1], log_data[s_point:end_pos+1], 2)    
      
      sigma_square=(1/(-2*z[0]))
      sigma_vector[k]= np.sqrt(sigma_square)
     
    sigma_fit = np.polyfit(time_real_3[sp+cf:time_length], sigma_vector[sp+cf:time_length], 1)
    #print 'sigma_fit', sigma_fit 
    #LIQUID AFTER SPECIFIED TIME  
    #30 min
    x_fit = np.linspace(0,30,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=30: ', p[len(p)-1]
    #40 min
    x_fit = np.linspace(0,40,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=40: ', p[len(p)-1]
    #40 min
    x_fit = np.linspace(0,41,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=41: ', p[len(p)-1]
    #50 min
    x_fit = np.linspace(0,50,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=50: ', p[len(p)-1]
    #1 hour
    x_fit = np.linspace(0,60,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=60: ', p[len(p)-1]
    #2 hour
    x_fit = np.linspace(0,120,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=120: ', p[len(p)-1]
    #6 hour
    x_fit = np.linspace(0,360,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=360: ', p[len(p)-1]
    #12 hour
    x_fit = np.linspace(0,720,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=720: ', p[len(p)-1]
    #24 hour
    x_fit = np.linspace(0,1440,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=1440: ', p[len(p)-1]
    #48 hour
    x_fit = np.linspace(0,2880,10000)
    p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
    print 'sigma at x=2880: ', p[len(p)-1]
  
    x_fit = np.linspace(0,40,10000)
    p =  sigma_fit[0]*x_fit + sigma_fit[1] 
    print 'Verschiebung: ', sigma_fit[1], 'Steigung: ', sigma_fit[0]
  
    ax.plot(time_real_3[sp+cf:time_length],sigma_vector[sp+cf:time_length] , color=color_set[5],marker='.',linestyle='None',markersize=m_s,  label=names3[3])
    if (fitting == 1):
      print 'sigma at x=40: ', p[len(p)-1]
      ax.plot(x_fit,p , color=color_set[5],linestyle='--', linewidth=l_w_2, label='Fitting')
    

  #GENERAL PLOT SETTINGS
#  if(dycoms == 0):
#    plt.title(r'VERDI - Growth of $\sigma$ in time', fontsize=size_title)#,fontdict=font)
#  else:
#    plt.title(r'DYCOMS-II - Growth of $\sigma$ in time', fontsize=size_title)#,fontdict=font)

  plt.xlabel('t [min]')#, fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt
  plt.ylabel(r'\textbf{$\sigma$}', fontsize=90)#, fontsize=size_axes)#,fontdict=font)
  #plt.xlim(0,40)
  if (fitting == 1):
    plt.ylim(0,0.35)
    plt.xlim(0,25)
  else:
    plt.ylim(0,0.35)
    plt.xlim(2,22)
  plt.legend(loc=2, frameon=False)  
  
  plt.show()
  plt.clf()

  fig, ax = ppl.subplots()
  if(dycoms == 0):
    print 'after plot', time_real_3 , sp+cf, time_length
    print 'first time step', time_real_3[sp+cf]
    print mean_fits200
    print 'first', mean_fits200[sp+cf], 'at point', sp+cf
  

  if(dycoms == 0):
    ax.plot(time_real_3[sp+cf:time_length],(mean_fits200[sp+cf:time_length]/mean_fits200[sp+cf]), color=color_set[5],linestyle='--',linewidth=l_w_2, label='Droplet number')
  else:
    ax.plot(time_real_2[sp+cf:time_length_re400],(mean_fits400[sp+cf:time_length_re400]/mean_fits400[sp+cf]), color=color_set[5],linestyle='--',linewidth=l_w_2, label='Droplet number')
   
  plt.xlabel('t [min]')#, fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt
  plt.ylabel(r'$N_{1.35}(t) / N_{1.35}(t_{0})$')#, fontsize=size_axes)#,fontdict=font)
  #ax.set_yscale('symlog')
  #plt.ylim(0.98,1.02)
  #plt.legend(loc=1, frameon=False)

  plt.show()
nlevels = len((contour_levels)) if len((contour_levels)) < 7 else 12

cmap = cm.jet

h = plt.contourf(freq, deg, spectrum, nlevels, cmap=cmap)
# h = plt.pcolor(freq, deg, spectrum)
# fig.colorbar(h, aspect=5)

ax.set_ylabel('Direction (deg)', **axis_font)
ax.set_xlabel('Frequency (Hz)', **axis_font)
ax.set_title('Contour 2D Spectrum', **title_font)

# <codecell>

# Now plot the wave heights
fig, ax = ppl.subplots(3, 1, figsize=(12, 18))

hs = nc.variables['hs'][:]
h = ppl.plot(ax[0], noutcdates, hs, linewidth=2.0, color='b')
ax[0].set_ylabel('Significant Wave Height (m)')
ax[0].set_title('Wave Height', **title_font)

# Now plot the wave period

tp = 1/nc.variables['fp'][:]
h = ppl.plot(ax[1], noutcdates, tp, linewidth=2.0, color='r')
ax[1].set_ylabel('Peak Period (s)')
ax[1].set_title('Wave Period', **title_font)

# Now plot the wave direction
Пример #34
0
def several_times_and_flight(all_interval3, all_data3_3,
                  names3, p_title3, time_real_1,time_real_2,time_real_3,
                  delta_s,t_real, time_data, dycoms, fitting, s_point, 
                  interval_flight, data_flight,data3_3, interval3):

  #setup colors
  fig, ax1  = plt.subplots()
  color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors
  color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors
  #color_set_2 = brewer2mpl.get_map('Reds', 'sequential', 9).mpl_colors
  color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors
  

  shape= np.shape(all_interval3) 
  time_length=shape[1]

  #scale data  
  all_data3_3=all_data3_3*50/18*0.92

  
  ########################################################################
  #Plot the flight data
  ########################################################################
  data_flight=data_flight*2.25*10**7#alberto
  #data_flight=data_flight*5.0*10**7
  #ax1.plot(interval_flight,data_flight, color=color_set[9],marker='.',linestyle='None',markersize=m_s+9 , label='Flight measurements')
  #alberto
  #ax1.plot(interval_flight,data_flight, color=color_set[9],marker='.',linestyle='None',markersize=m_s+9 )
  ax1.plot(interval_flight,data_flight, color=color_set[9],marker='.',linestyle='None',markersize=m_s+9 , label='Flight measurements')

  ########################################################################
  #Plot the data+fit
  ########################################################################
 
  time_real_data=np.zeros(len(time_data))
  for i in np.arange(len(time_data)): 
    time_real_data[i]=round(time_data[i]*t_real/60,2)
  #print time_real_data 
  #steps=np.array([12,23, 35])
  steps= np.arange(12,36)
  print 'here steps', steps
  c=1
  l=0
  b_new = np.zeros(len(steps)) 
  a_new = np.zeros(len(steps)) 
  sigma_square_new = np.zeros(len(steps)) 
  x_max = np.zeros(len(steps)) 
  for k in steps:
    time_real_data[k]=round(time_real_data[k],0)
    label_name='t=' + str(int(time_real_data[k])) + ' min'
    #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[c],linewidth=l_w_1, label='Simulation ' + label_name)
    #alberto
    #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[c],linewidth=l_w_1)
    if (k==12):
      #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1)
      ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1, label='Simulation ' + label_name)
    elif (k==35):
      #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1)
      ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1, label='Simulation ' + label_name)
    log_data= np.zeros(100)  
    log_interval= np.zeros(100) 
    for i in np.arange(len(all_data3_3[:,k])):
      if (all_data3_3[i,k] != 0):
        log_data[i] = np.log(all_data3_3[i,k])
      elif (all_data3_3[i,k] == 0):
        log_data[i]=all_data3_3[i,k]
    j=1
    max_val=max(log_data)   
    max_val_pos=len(log_data)+1 
    for i in np.arange(len(log_data)):
      if ( log_data[i] == max_val):
        max_val_pos=i
      if (i > max_val_pos):
        if (log_data[i] <= 0):
          end_pos=i
          break
          

    #POLYNOMIAL FIT       
    z = np.polyfit(all_interval3[s_point:end_pos+1,k], log_data[s_point:end_pos+1], 2)    
    #print 'point where fitting starts', all_interval3[s_point,k], np.exp(log_data[s_point])
    #print 'polyfit',z
    p = np.poly1d(z)
    #ax1.plot(interval3[24:end_pos+1], np.exp(log_data[24:end_pos+1]), '.', color=color_set[4], label='Fiting points' )

    mean=z[1]/(-2*z[0])
    sigma_square=(1/(-2*z[0]))
   
    #x = np.linspace(0,mean+6,1000)
    x = np.linspace(1.75,mean+6,1000) #alberto
    #print 'FIT: mean and sigma_square', mean, sigma_square 
    #print 'k', k
    y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) )

    #print x[210]
    #ax1.plot(x[0:len(x)],y[0:len(y)] , color=color_set[c], linestyle='--', linewidth=l_w_2)
    if (k==12):
      ax1.plot(x[0:len(x)],y[0:len(y)] , color=color_set[1], linestyle='--', linewidth=l_w_2)
    elif (k==35):
      ax1.plot(x[0:len(x)],y[0:len(y)] , color=color_set[1], linestyle='--', linewidth=l_w_2)
    c=c+2


    #CURVE FITTIN

    x_zero=1.75
    def pol_func(x,a,b,c):
      return a*(x-x_zero)**2+b*(x-x_zero)+c
      #return a*(x)**2+b*(x)+c

    fitpars, covmat = so.curve_fit(pol_func,all_interval3[s_point:end_pos+1,k], log_data[s_point:end_pos+1])
   
    mean_new=fitpars[1]/(-2*fitpars[0])
    sigma_square_calc=(1/(-2*fitpars[0]))
    
    #NEW Y WITH x=x-x_zero

    c_fixed=13.2
    y_new=np.exp( (c_fixed+fitpars[1]**2/(4*-fitpars[0]))-((((x-x_zero)-mean_new)**2)/(2*sigma_square_calc)) )
    print 'CURVE FIT fitpars', fitpars
    print 'CURVE FIT corresponding mean and sigma', mean_new, sigma_square_calc
    #ax1.plot(x[0:len(x)],y_new[0:len(y)] , color=color_set[7], linestyle='--', linewidth=l_w_2-3)
    a_new[l]=fitpars[0]
    b_new[l]=fitpars[1]
    x_max[l]=x_zero-b_new[l]/(2*a_new[l])
    sigma_square_new[l]=-1/(2*fitpars[0])
    l=l+1
    
    
  #LINEAR FIT FOR a AND x_max FOR b
  def lin_func(x,a,b):
    return a*(x)+b
  
  def pol2_func(x,a,b,c):
    return a*(x)**2+b*x+c
  def tanh_func(x,a,b,c):
    return c+a*np.tanh(x+b)
  def sqrt_func(x,a,b,c):
    return c+a*np.sqrt(x+b)
  def asympt_func(x,a,b,c):
    return c+b/x+a/(x**2)
  #fitpars_2, covmat_2 = so.curve_fit(lin_func,steps,a_new)
  fitpars_2, covmat_2 = so.curve_fit(asympt_func,steps,a_new)
  #fitpars_2, covmat_2 = so.curve_fit(tanh_func,steps,a_new)
  #fitpars_2, covmat_2 = so.curve_fit(sqrt_func,steps,a_new)
  #fitpars_2, covmat_2 = so.curve_fit(pol2_func,steps,a_new)
  fitpars_3, covmat_3 = so.curve_fit(lin_func,steps,x_max)
  #fitpars_3, covmat_3 = so.curve_fit(pol2_func,steps,x_max)
  fitpars_4, covmat_3 = so.curve_fit(lin_func,steps,b_new)
  fitpars_5, covmat_3 = so.curve_fit(lin_func,steps,sigma_square_new)
  time_part=np.arange(0,len(time_real_3))
  fitpars_time, covmat_3 = so.curve_fit(lin_func,time_part,time_real_3)

  #USING ACTUAL FIT FOR time
  x = np.linspace(5,90,100)
  
  time_extrapol=fitpars_time[0]*x+fitpars_time[1] 
  steps_time=fitpars_time[0]*steps+fitpars_time[1] 
  
  #USING ACTUAL FIT FOR x_max 
  x_max_fit = fitpars_3[0]*x+fitpars_3[1]
  #x_max_fit = fitpars_3[0]*x**2+fitpars_3[1]*x+fitpars_3[2]
  
  #USING ACTUAL FIT FOR b 
  test_b  = fitpars_4[0]*x+fitpars_4[1]
  
  #USING ACTUAL FIT FOR a 
  #a_fit = fitpars_2[0]*x+fitpars_2[1]
  a_fit = fitpars_2[0]*(1.0/x**2)+fitpars_2[1]*(1.0/x)+fitpars[2]
  #a_fit = fitpars_2[2]+fitpars_2[0]*np.tanh(x+fitpars_2[1])
  #a_fit = fitpars_2[2]+fitpars_2[0]*np.sqrt(x+fitpars_2[1])
  #a_fit = fitpars_2[0]*x**2+fitpars_2[1]*x + fitpars_2[2]
  
  #USING ACTUAL FIT FOR b 
  sigma_square_new_fit  = fitpars_5[0]*x+fitpars_5[1]
  

  #SEVERAL TIME STEPS
  several_x = np.array([30, 35, 50 ,60 ,70 ,80,100,120, 250])
  several_times=fitpars_time[0]*several_x+fitpars_time[1] 
  
  several_x_max = fitpars_3[0]*several_x+fitpars_3[1]
  #several_x_max = fitpars_3[0]*several_x**2+fitpars_3[1]*several_x+fitpars_3[2]
  
  several_test_b = fitpars_4[0]*several_x+fitpars_4[1]

  #several_a = fitpars_2[0]*several_x+fitpars_2[1]
  several_a = fitpars_2[0]*(1.0/several_x**2)+fitpars_2[1]*(1.0/several_x)+fitpars_2[2]
  #several_a = fitpars_2[2]+fitpars_2[0]*np.tanh(several_x+fitpars_2[1])
  #several_a = fitpars_2[2]+fitpars_2[0]*np.sqrt(several_x+fitpars_2[1])
  #several_a = fitpars_2[0]*several_x**2+fitpars_2[1]*several_x +fitpars_2[2]
 
  several_sigma_square_new = fitpars_5[0]*several_x+fitpars_5[1]
  
  several_b = (several_x_max-x_zero)*(-2*several_a)
   
  print 'several times', several_times
  print 'corresponding x_max', several_x_max
  print 'corresponding a', several_a
  print 'calculated b', several_b
  print 'test b', several_test_b
  print 'several_sigma_new', several_sigma_square_new

  #NEW EXTRAPOLATION
  m=8
  x_plot = np.linspace(1.75,6,100) #alberto
  #new_mean=-several_test_b[m]/(2*several_a[m])
  #new_mean=several_test_b[m]*sigma_square_new[m]
  #new_mean=x_zero-several_b[m]/(2*several_a[m])
  new_sigma=(1/(-2*several_a[m]))
  #c_calc=np.log(1/(np.sqrt(several_sigma_square_new[m])*sqrt(2*3.14)))
  #new_y_extrapolation=np.exp(13+several_test_b[m]**2/(4*several_a[m])+several_test_b[m]*(x_plot-x_zero)+several_a[m]*(x_plot-x_zero)**2)
  #new_y_extrapolation=np.exp(13+several_test_b[0]*(x_plot-x_zero)+several_a[m]*(x_plot-x_zero)**2)
  
  #with direct b
  new_y_extrapolation=np.exp(13+several_test_b[0]*(x_plot-x_zero)-(1/(2*several_sigma_square_new[m])*(x_plot-x_zero)**2))
  
  #indirect b
  new_y_extrapolation_2=np.exp(13+(-2)*(x_plot-x_zero)-(1/(2*several_sigma_square_new[m])*(x_plot-x_zero)**2))

  ax1.plot(x_plot,new_y_extrapolation , color=color_set[5], label=r'Extrapolation t$\,\approx\,$80 min ',  linestyle='--', linewidth=l_w_2)
  ax1.plot(x_plot,new_y_extrapolation_2 , color=color_set[7], label=r'Extrapolation t$\,\approx\,$80 min ',  linestyle='--', linewidth=l_w_2)
  ########################################################################
  #use one of the latest time-steps to extrapolate data
  ########################################################################
  data3_3=data3_3*50/18*0.92
  log_data= np.zeros(100)  
  log_interval= np.zeros(100) 
  
  for i in np.arange(len(data3_3)):
    if (data3_3[i] != 0):
      log_data[i] = np.log(data3_3[i])
    elif (data3_3[i] == 0):
      log_data[i]=data3_3[i]
  j=1
  max_val=max(log_data)   
  max_val_pos=len(log_data)+1 
  for i in np.arange(len(log_data)):
    if ( log_data[i] == max_val):
      max_val_pos=i
    if (i > max_val_pos):
      if (log_data[i] <= 0):
        end_pos=i
        break
        
  begin_pos=s_point
  print 'mean is set to', interval3[begin_pos]
  #print 'end_pos', end_pos 
  z = np.polyfit(interval3[begin_pos:end_pos+1], log_data[begin_pos:end_pos+1], 2)    
  #print 'polyfit',z
  p = np.poly1d(z)
  #ax1.plot(interval3[begin_pos:end_pos+1], np.exp(log_data[begin_pos:end_pos+1]), '.', color=color_set[5],linewidth=l_w_1, label='Fitting points' )
  
  mean=z[1]/(-2*z[0])
  sigma_square=(1/(-2*z[0]))
  
  

 
  #for 30min=0.434 40min=0.586 and 50min=0.74
  #attetntion we will use growing**2
  #growing=[0.2, 0.434, 0.586, 0.74]
  #growing=[0.53]#alberto
  #growing=[0.74]#50 min
  growing=[0.21, 0.434, 0.74]
  #growing=[0.21, 0.434, 0.74, 0.9, 1.2]
  #l=0
  #M_max_all= np.zeros(len(growing)) 
  #test= np.zeros(len(growing)) 
  sigma_extrapolation_all= np.zeros(len(growing)) 
  for k in np.arange(len(growing)):
    sigma_extrapolation=growing[k]**2  #after certain time
    a=-1/(2*sigma_extrapolation) #only for testing
    #mean_extrapolation=z[1]/(-2*a) #only for testing
  
    #x = np.linspace(0,mean+6,1000)
    x = np.linspace(1.75,mean+6,1000) #alberto
    print 'EXTRAPOLATION: mean  and sigma_square_extra', mean, sigma_extrapolation 
    
    #OLD extrapolation
    #y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) )
    y_extrapolation=np.exp( 1/(growing[k]*np.log(2*3.14))-(((x-mean)**2)/(2*sigma_extrapolation)) )
    
    #M_max=-(z[1]/(2*a))
    #M_max_all[l]=M_max 
    #sigma_extrapolation_all[l]=sigma_extrapolation
    #print 'M_max verschiebung', M_max
    ##test[l]=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((M_max-mean)**2)/(2*sigma_extrapolation)) )
    #test[l]=a*x**2+z[1]+z[2]
    #print 'test', test[l]
    #print 'a and b', a, z[1]
    #
    #l=l+1

 
    ###if (k==0):
      ###ax1.plot(x,y_extrapolation , color=color_set[5], label=r'Extrapolation t$\,\approx\,$30 \& 50 [min] ', linestyle='--', linewidth=l_w_2)
      #alberto
      #ax1.plot(x,y_extrapolation , color=color_set[5], label=r'Extrapolation t$\,\approx\,$60 min ', linestyle='--', linewidth=l_w_2)
      ###ax1.plot(x,y_extrapolation , color=color_set[5], linestyle='--', linewidth=l_w_2)
    ###elif (k==1):
      ###ax1.plot(x,y_extrapolation , color=color_set[5],  linestyle='--', linewidth=l_w_2)
    #ax1.plot(x,y_extrapolation , color=color_set[5], linestyle='--', linewidth=l_w_2)
 
  #GRID LINES
  axes = plt.gca()
  axes.grid(True)

  ax1.set_yscale('symlog')
  #ax1.set_xlabel(r'$M/M_r$', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt
  #alberto
  ax1.set_xlabel('Droplet mass', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt
  ax1.set_ylabel('Amount of cloud droplets', fontsize=size_axes)#,fontdict=font)
  #ax1.set_xticks([0.1,0.5,1,1.5,2.0,2.5,3.0,3.5,4.0]) 
  #ax1.set_xlim(1.5,5)
  ax1.set_xlim(0.8,4)#alberto
  ax1.set_ylim([10**2,10**8])
  
#  ax12 = ax1.twiny()
#  ax12.set_xlabel(r"Radius [$\mu m$]", fontsize=size_axes)
  if (dycoms==0):
    tick_locs = [0.5,1,1.5,2.0,2.5,3.0,3.5,4.0]
    tick_lbls = [8.2,10.3,11.8,13,14,14.9,15.7,16.4]
  else:
    tick_locs = [0.5,1,1.5,2.0,2.5,3.0,3.5,4.0]
    tick_lbls = [8.9,11,12.8,14,15.2,16.1,17,17.7]
    
#  ax12.set_xticks(tick_locs)
#  ax12.set_xticklabels(tick_lbls)
#  ax12.set_xlim(0.1,3)
  ax1.legend(loc=0, frameon=False)
  
  plt.legend(loc=1, frameon=False)  


  ########################################################################
  #plot a with time
  ########################################################################

  fig, ax2 = ppl.subplots()


  ax2.plot(steps_time,a_new, color=color_set[5],marker='.',linestyle='None',markersize=m_s+9 )
  ax2.plot(time_extrapol,a_fit , color=color_set[5],linestyle='--', linewidth=l_w_2)


  ########################################################################
  #plot b with time
  ########################################################################

  fig, ax3 = ppl.subplots()


  ax3.plot(steps_time,b_new, color=color_set[3],marker='.',linestyle='None',markersize=m_s+9 )
  ax3.plot(time_extrapol,test_b , color=color_set[3],linestyle='--', linewidth=l_w_2)


  ########################################################################
  #plot sigma_square with time
  ########################################################################
  fig, ax4 = ppl.subplots()

  ax4.plot(steps_time,sigma_square_new, color=color_set[1],marker='.',linestyle='None',markersize=m_s+9 )
  ax4.plot(time_extrapol,sigma_square_new_fit , color=color_set[7],linestyle='--', linewidth=l_w_2)



  ########################################################################
  #plot m_max with time
  ########################################################################

  #fig, ax5 = ppl.subplots()


  #ax5.plot(steps_time,x_max, color=color_set[7],marker='.',linestyle='None',markersize=m_s+9 )
  #ax5.plot(time_extrapol,x_max_fit , color=color_set[7],linestyle='--', linewidth=l_w_2)










  plt.show()
Пример #35
0
    def make_scatter(self, use_prettyplotlib=True, hists=True, num_bins=None):
        '''
        Plot two columns against each other. If self.subplot is enabled,
        all comparisons returned in a triangle collection. Inspiration for
        this form came from the package ![triangle.py](https://github.com/dfm/triangle.py).
        Small snippets to set the labels and figure size came from triangle.py.
        '''

        if use_prettyplotlib:
            try:
                import prettyplotlib as plt
            except ImportError:
                import matplotlib.pyplot as plt
                use_prettyplotlib = False
                print "prettyplotlib not installed. Using matplotlib..."
        else:
            import matplotlib.pyplot as plt

        # Setup subplots if plotting together
        if self.subplot:
          # Make the objects
          num = len(self.columns)
          factor = 2.0 # size of one side of one panel
          lbdim = 0.5 * factor # size of left/bottom margin
          trdim = 0.3 * factor # size of top/right margin
          whspace = 0.05 # w/hspace size
          plotdim = factor * num + factor * (num - 1.) * whspace
          dim = lbdim + plotdim + trdim
          fig, axes = plt.subplots(nrows=num, ncols=num, figsize=(dim, dim))

          lb = lbdim / dim
          tr = (lbdim + plotdim) / dim
          fig.subplots_adjust(left=lb, bottom=lb, right=tr, top=tr,
                              wspace=whspace, hspace=whspace)

        for i, column1 in enumerate(self.columns):
          for j, column2 in enumerate(self.columns):

            data1 = self.dataframe[column1]
            data2 = self.dataframe[column2]

            # Get rid of nans
            nans = np.isnan(data1) + np.isnan(data2)
            data1 = data1[~nans]
            data2 = data2[~nans]

            if self.subplot:
              ax = axes[i, j]
              if j > i: # Don't bother plotting duplicates
                ax.set_visible(False)
                ax.set_frame_on(False)
              else:

                if j == i: # Plot histograms
                  # Set number of bins
                  if num_bins is None:
                      num_bins = np.sqrt(len(data1))
                  if hists == True:
                    if use_prettyplotlib:
                      plt.hist(ax, data1, num_bins, grid="y")
                    else:
                      ax.hist(data1, num_bins)
                      ax.grid(True)
                  else:
                    ax.set_visible(False)
                    ax.set_frame_on(False)

                  ax.set_xticklabels([])
                  ax.set_yticklabels([])

                if j != i:
                  if use_prettyplotlib:
                    plt.scatter(ax, data2, data1)
                  else:
                    ax.scatter(data2, data1)
                  ax.grid(True)
                  ax.xaxis.set_major_locator(MaxNLocator(5))
                  ax.yaxis.set_major_locator(MaxNLocator(5))

                if i < num - 1:
                    ax.set_xticklabels([])
                else:
                    [l.set_rotation(45) for l in ax.get_xticklabels()]
                    ax.set_xlabel(column2)
                    ax.xaxis.set_label_coords(0.5, -0.3)

                if j > 0:
                    ax.set_yticklabels([])
                else:
                    [l.set_rotation(45) for l in ax.get_yticklabels()]
                    ax.set_ylabel(column1)
                    ax.yaxis.set_label_coords(-0.3, 0.5)

            else:
              if j < i:
                fig, axes = plt.subplots(1)
                if use_prettyplotlib:
                  plt.scatter(axes, data2, data1, grid="y")
                else:
                  axes.scatter(data2, data1)
                  axes.grid(True)
                axes.set_xlabel(column2)  # ADD UNITS!
                axes.set_ylabel(column1)  # ADD UNITS!

                if self.verbose:
                  p.show()
                else:
                  fig.savefig(self.save_name+"_"+column1+"_"+column2+"."+self.save_type)
                  p.close()

        if self.subplot:
          # p.tight_layout()
          if self.verbose:
            p.show()
          else:
            fig.savefig(self.save_name+"_"+"scatter"+"."+self.save_type)
Пример #36
0
def extrapolation_sigma(all_interval1, all_data1_3, all_interval2, all_data2_3,
                        all_interval3, all_data3_3,
                        names3, p_title3, time_real_1,time_real_2,time_real_3,delta_s,t_real, dycoms):

  close='all'
 
  fig, ax = ppl.subplots()
  color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors

  #DATA RE800
  shape= np.shape(all_interval1) 
  time_length=shape[1]
  
  data1_3= np.zeros(100)
  interval1= np.zeros(100)
  sigma_vector_1= np.zeros(time_length)

  for k in np.arange(time_length):
    data1_3[:] = all_data1_3[:,k]
    interval1[:] = all_interval1[:,k]

    log_data= np.zeros(100)  
   
    for i in np.arange(len(data1_3)):
      if (data1_3[i] != 0):
        log_data[i] = np.log(data1_3[i])
      elif (data1_3[i] == 0):
        log_data[i]=data1_3[i]
    j=1
    max_val=max(log_data)   
    max_val_pos=len(log_data)+1 
    for i in np.arange(len(log_data)):
      if ( log_data[i] == max_val):
        max_val_pos=i
      if (i > max_val_pos):
        if (log_data[i] <= 0):
          end_pos=i
          break
   
  
    z = np.polyfit(interval1[24:end_pos+1], log_data[24:end_pos+1], 2)    
    
    sigma_square=(1/(-2*z[0]))
    sigma_vector_1[k]= np.sqrt(sigma_square)
 
  sigma_fit_1 = np.polyfit(time_real_1, sigma_vector_1, 1)
  
  ax.plot(time_real_1,sigma_vector_1 , color=color_set[3],linewidth=2,  label='Data Re800')
  x_fit = np.linspace(0,60,1000)
  p = sigma_fit_1[0]*x_fit + sigma_fit_1[1] 
  #p = sigma_fit_2[0]*x_fit**2 + sigma_fit_2[1]*x_fit + sigma_fit_2[2] 
#  if (dycoms != 0): 
#    ax.plot(x_fit,p ,linestyle='--', color=color_set[2], label='Fiting', linewidth=2)


  #DATA RE400
  shape= np.shape(all_interval2) 
  time_length=shape[1]
  
  data2_3= np.zeros(100)
  interval2= np.zeros(100)
  sigma_vector_2= np.zeros(time_length)

  for k in np.arange(time_length):
    data2_3[:] = all_data2_3[:,k]
    interval2[:] = all_interval2[:,k]

    log_data= np.zeros(100)  
   
    for i in np.arange(len(data2_3)):
      if (data2_3[i] != 0):
        log_data[i] = np.log(data2_3[i])
      elif (data2_3[i] == 0):
        log_data[i]=data2_3[i]
    j=1
    max_val=max(log_data)   
    max_val_pos=len(log_data)+1 
    for i in np.arange(len(log_data)):
      if ( log_data[i] == max_val):
        max_val_pos=i
      if (i > max_val_pos):
        if (log_data[i] <= 0):
          end_pos=i
          break
   
  
    z = np.polyfit(interval2[24:end_pos+1], log_data[24:end_pos+1], 2)    
    
    sigma_square=(1/(-2*z[0]))
    sigma_vector_2[k]= np.sqrt(sigma_square)
 
  sigma_fit_2 = np.polyfit(time_real_2, sigma_vector_2, 1)
  
  ax.plot(time_real_2,sigma_vector_2 , color=color_set[5],linewidth=2,  label='Data Re400')
  
  x_fit = np.linspace(0,60,1000)
  p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] 
  #p = sigma_fit_2[0]*x_fit**2 + sigma_fit_2[1]*x_fit + sigma_fit_2[2] 
#  if (dycoms != 0): 
#    ax.plot(x_fit,p ,linestyle='--', color=color_set[4], label='Fitting', linewidth=2)

  if (dycoms == 0):
    #DATA RE200
    shape= np.shape(all_interval3) 
    time_length=shape[1]
    
    data3_3= np.zeros(100)
    interval3= np.zeros(100)
    sigma_vector= np.zeros(time_length)
    print sigma_vector[9]

    c= np.zeros(time_length)
  
    for k in np.arange(time_length):
      data3_3[:] = all_data3_3[:,k]
      interval3[:] = all_interval3[:,k]
  
      log_data= np.zeros(100)  
      log_interval= np.zeros(100) 
     
      for i in np.arange(len(data3_3)):
        if (data3_3[i] != 0):
          log_data[i] = np.log(data3_3[i])
        elif (data3_3[i] == 0):
          log_data[i]=data3_3[i]
      j=1
      max_val=max(log_data)   
      max_val_pos=len(log_data)+1 
      for i in np.arange(len(log_data)):
        if ( log_data[i] == max_val):
          max_val_pos=i
        if (i > max_val_pos):
          if (log_data[i] <= 0):
            end_pos=i
            break
     
      z = np.polyfit(interval3[24:end_pos+1], log_data[24:end_pos+1], 2)    
      
      sigma_square=(1/(-2*z[0]))
      sigma_vector[k]= np.sqrt(sigma_square)
   
    sigma_fit = np.polyfit(time_real_3, sigma_vector, 1)
    print 'sigma_fit', sigma_fit 
  
    x_fit = np.linspace(0,60,1000)
    #p = sigma_fit[0]*x_fit**2 + sigma_fit[1]*x_fit + sigma_fit[2] 
    p =  sigma_fit[0]*x_fit + sigma_fit[1] 
  
    ax.plot(time_real_3,sigma_vector , color=color_set[1],linewidth=2,  label='Data Re200')
    ax.plot(x_fit,p , color=color_set[0],linestyle='--', linewidth=2, label='Fitting')
    
    tau=t_real/delta_s
    print len(time_real_3), len(sigma_vector)
    for l in np.arange(len(time_real_3)):
      c[l] = sigma_vector[l]*tau/time_real_3[l]
    print np.mean(c), sigma_fit[0]
    #p_test=np.mean(c)*x_fit
    #ax.plot(x_fit,p_test ,color=color_set[9],linewidth=2,  label='bla')

  #GENERAL PLOT SETTINGS
#  if(dycoms == 0):
#    plt.title(r'VERDI - Growth of $\sigma$ in time', fontsize=size_title)#,fontdict=font)
#  else:
#    plt.title(r'DYCOMS-II - Growth of $\sigma$ in time', fontsize=size_title)#,fontdict=font)

  plt.xlabel('t [min]')#, fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt
  plt.ylabel(r'\textbf{$\sigma$}')#, fontsize=size_axes)#,fontdict=font)
  #plt.xlim(0,4)
  plt.ylim(0)
  plt.legend(loc=2, frameon=False)  
  
  plt.show()
Пример #37
0
#!/usr/bin/python
# encoding=utf-8

import prettyplotlib as ppl
import numpy as np

# prettyplotlib imports
import matplotlib.pyplot as plt
import matplotlib as mpl
from prettyplotlib import brewer2mpl

# Set the random seed for consistency
np.random.seed(12)

fig, ax = ppl.subplots(1)

# Show the whole color range
for i in range(8):
    y = np.random.normal(size=1000).cumsum()
    x = np.arange(1000)

    # For now, you need to specify both x and y :(
    # Still figuring out how to specify just one
    ppl.plot(ax, x, y, label=str(i), linewidth=0.75)

ppl.legend(ax)

fig.show()
Пример #38
0
ax1.plot(times,m-st,'gray',times,m+st,'gray')
#ax2 = plt.gcf().add_subplot(1,2,2)
#ax2.plot(times,s)
plt.xlabel('Time (in seconds)')
plt.ylabel('Space (in cm)')
plt.legend()
plt.title('State Estimation in a Diffusion System')



if plotting:
    
    #matplotlib.rcParams['font.size']=10
    
    if gaussian:
        fig, (ax1,ax2) = ppl.subplots(1,2,figsize = (12,6))
    else:
        fig, ax2 = ppl.subplots(1)
    times = np.arange(0.0,dt*timewindow,dt)
    if gaussian:    
        if sum(sum(spsg)) !=0:
            (ts,neurs) = np.where(spsg == 1)
            spiketimes = times[ts]
            thetas = [code.neurons[i].theta for i in neurs]
        else:
            spiketimes = []
            thetas = []
        
        l4, = ax1.plot(times,sg,label='True State')
        l2, = ax1.plot(times,mg,label='Posterior Mean')
        l1, = ax1.plot(spiketimes,thetas,'o',label='Observed Spikes')
Пример #39
0
    def make_scatter(self, use_prettyplotlib=True, hists=True, num_bins=None):
        '''
        Plot two columns against each other. If self.subplot is enabled,
        all comparisons returned in a triangle collection. Inspiration for
        this form came from the package ![triangle.py](https://github.com/dfm/triangle.py).
        Small snippets to set the labels and figure size came from triangle.py.
        '''

        if use_prettyplotlib:
            try:
                import prettyplotlib as plt
            except ImportError:
                import matplotlib.pyplot as plt
                use_prettyplotlib = False
                print "prettyplotlib not installed. Using matplotlib..."
        else:
            import matplotlib.pyplot as plt

        # Setup subplots if plotting together
        if self.subplot:
            # Make the objects
            num = len(self.columns)
            factor = 2.0  # size of one side of one panel
            lbdim = 0.5 * factor  # size of left/bottom margin
            trdim = 0.3 * factor  # size of top/right margin
            whspace = 0.05  # w/hspace size
            plotdim = factor * num + factor * (num - 1.) * whspace
            dim = lbdim + plotdim + trdim
            fig, axes = plt.subplots(nrows=num, ncols=num, figsize=(dim, dim))

            lb = lbdim / dim
            tr = (lbdim + plotdim) / dim
            fig.subplots_adjust(left=lb,
                                bottom=lb,
                                right=tr,
                                top=tr,
                                wspace=whspace,
                                hspace=whspace)

        for i, column1 in enumerate(self.columns):
            for j, column2 in enumerate(self.columns):

                data1 = self.dataframe[column1]
                data2 = self.dataframe[column2]

                # Get rid of nans
                nans = np.isnan(data1) + np.isnan(data2)
                data1 = data1[~nans]
                data2 = data2[~nans]

                if self.subplot:
                    ax = axes[i, j]
                    if j > i:  # Don't bother plotting duplicates
                        ax.set_visible(False)
                        ax.set_frame_on(False)
                    else:

                        if j == i:  # Plot histograms
                            # Set number of bins
                            if num_bins is None:
                                num_bins = np.sqrt(len(data1))
                            if hists == True:
                                if use_prettyplotlib:
                                    plt.hist(ax, data1, num_bins, grid="y")
                                else:
                                    ax.hist(data1, num_bins)
                                    ax.grid(True)
                            else:
                                ax.set_visible(False)
                                ax.set_frame_on(False)

                            ax.set_xticklabels([])
                            ax.set_yticklabels([])

                        if j != i:
                            if use_prettyplotlib:
                                plt.scatter(ax, data2, data1)
                            else:
                                ax.scatter(data2, data1)
                            ax.grid(True)
                            ax.xaxis.set_major_locator(MaxNLocator(5))
                            ax.yaxis.set_major_locator(MaxNLocator(5))

                        if i < num - 1:
                            ax.set_xticklabels([])
                        else:
                            [l.set_rotation(45) for l in ax.get_xticklabels()]
                            ax.set_xlabel(column2)
                            ax.xaxis.set_label_coords(0.5, -0.3)

                        if j > 0:
                            ax.set_yticklabels([])
                        else:
                            [l.set_rotation(45) for l in ax.get_yticklabels()]
                            ax.set_ylabel(column1)
                            ax.yaxis.set_label_coords(-0.3, 0.5)

                else:
                    if j < i:
                        fig, axes = plt.subplots(1)
                        if use_prettyplotlib:
                            plt.scatter(axes, data2, data1, grid="y")
                        else:
                            axes.scatter(data2, data1)
                            axes.grid(True)
                        axes.set_xlabel(column2)  # ADD UNITS!
                        axes.set_ylabel(column1)  # ADD UNITS!

                        if self.verbose:
                            p.show()
                        else:
                            fig.savefig(self.save_name + "_" + column1 + "_" +
                                        column2 + "." + self.save_type)
                            p.close()

        if self.subplot:
            # p.tight_layout()
            if self.verbose:
                p.show()
            else:
                fig.savefig(self.save_name + "_" + "scatter" + "." +
                            self.save_type)
Пример #40
0
except:

    p = mp.Pool(mp.cpu_count())
    results = p.map(run_filters,zip(range(dthetas.size),dthetas))

    for r in results:
        i,dense,sparse,part = r
        dense_eps[i] = dense
        sparse_eps[i] = sparse
        particle_eps[i] = part

    with open(filename,"wb") as f:
        pic.dump({'dense_eps':dense_eps,
                  'sparse_eps':sparse_eps,
                  'particle_eps':particle_eps,
                  'dthetas':dthetas},
                  f)

if plotting:
    
    #matplotlib.rcParams['font.size']=10
    fig, ax = ppl.subplots(1,figsize=(5,5))

    ppl.plot(dthetas,sparse_eps,ax=ax,label='Full ADF')
    ppl.plot(dthetas,dense_eps,ax=ax,label='Dense ADF')
    ppl.plot(dthetas,particle_eps,ax=ax,label='Particle Filter')

    ppl.legend(ax)

    plt.show()
Пример #41
0
                lamb = phi*np.sqrt(2*np.pi*alpha)
                eps[n,m] = get_eq_eps( gamma, eta, alpha, lamb )
                stoc_eps[n,m] =  np.mean(full_stoc_sigma(0.01, dt, N, -gamma,
                                               eta, alpha, lamb, 200,
                                               discard=discard))

        with open("figure_5_3.pik","w") as fi:
            print "Writing pickle to figure_5_3.pik"
            pic.dump({'alphas':alphas,'phis':phis,'mean_field':eps,'stochastic':stoc_eps},fi)

    print "Plotting..."
    
    font = {'size':12}
    plt.rc('font',**font)

    fig, (ax1,ax2) = ppl.subplots(1,2,figsize = (12,5))
    
    alphas2,phis2 = np.meshgrid(np.arange(alphas.min(),alphas.max()+dalpha,dalpha)-dalpha/2,
                                np.arange(phis.min(),phis.max()+dphi,dphi)-dphi/2)

    yellorred = brewer2mpl.get_map('YlOrRd','Sequential',9).mpl_colormap

    p = ax1.pcolormesh(alphas2,phis2,eps.T,cmap=yellorred, rasterized=True)
    ax1.axis([alphas2.min(),alphas2.max(),phis2.min(),phis2.max()])

    #xticks = np.arange(alphas.min(),alphas.max(),0.5)
    #xlabels = np.arange(alphas.min(),alphas.max(),0.5)-alphas.min()

    #yticks = np.arange(phis.min(),phis.max(),0.5)
    #ylabels = np.arange(phis.min(),phis.max(),0.5)-phis.min()
Пример #42
0
    def make_hists(self, num_bins=None, use_prettyplotlib=True):

        if use_prettyplotlib:
            try:
                import prettyplotlib as plt
            except ImportError:
                import matplotlib.pyplot as plt
                use_prettyplotlib = False
                print "prettyplotlib not installed. Using matplotlib..."
        else:
            import matplotlib.pyplot as plt

        # Setup subplots if plotting together
        if self.subplot:
            num = len(self.columns)
            if num <= 3:
                ncols = 1
                nrows = num
            elif num <= 8:
                ncols = 2
                nrows = num / 2
            else:  # Max columns right now is 12
                ncols = 3
                nrows = num / 3
            # Check if we need an extra row.
            if num % ncols != 0:
                nrows += 1

            # Make the objects
            fig, axes = plt.subplots(nrows=nrows, ncols=ncols)

            # This is a bit awkward to get the indices, but my matplotlib version
            # doesn't use the same object type as prettyplotlib creates.
            posns = np.indices(axes.shape)
            x, y = posns[0].ravel(), posns[1].ravel()

        # Keep the mean, median, std.
        data_stats = {}
        for i, column in enumerate(self.columns):
            data = self.dataframe[column]
            data = data[np.isfinite(data)]
            if num_bins is None:
                num_bins = np.sqrt(len(data))

            data_stats[column] = [
                np.nanmean(data),
                np.nanstd(data),
                np.nanmedian(data)
            ]

            if self.subplot:
                if use_prettyplotlib:
                    plt.hist(axes[x[i], y[i]], data, num_bins, grid="y")
                else:
                    axes[x[i], y[i]].hist(data, num_bins)
                axes[x[i], y[i]].set_xlabel(column)  # ADD UNITS!
            else:
                fig, axes = plt.subplots(1)
                axes.hist(data, num_bins)
                axes.set_xlabel(column)  # ADD UNITS!

            if self.verbose and not self.subplot:
                print column + " Stats: %s" % (data_stats[column])
                p.show()

            elif not self.subplot:
                fig.savefig(self.save_name + "_" + column + "." +
                            self.save_type)
                p.close()

        if self.subplot:
            p.tight_layout()
            if self.verbose:
                for column in self.columns:
                    print column + " Stats: %s" % (data_stats[column])
                p.show()
            else:
                fig.savefig(self.save_name + "_hists." + self.save_type)