Ejemplo n.º 1
0
def _counter_post_per_thread(Thread_list, Post_list, group_n):
    fig = plt.figure()
    ax = fig.add_subplot(111)

    for th_i in range(1, len(Thread_list) + 1):
        thread = Thread_list[th_i]
        print(" title", thread.title, th_i)
        x_times, y_nums = _extract_time(thread.pi_list, Post_list)
        if len(x_times) == 0:
            print("     this thread has not post from users.")
            continue
        if group_n == "ALPHA":
            ax.plot(x_times, y_nums, label=th_i, color=cm.spring((th_i - 1) / len(Thread_list)))
        elif group_n == "BRAVO":
            ax.plot(x_times, y_nums, label=th_i, color=cm.summer((th_i - 1) / len(Thread_list)))
        elif group_n == "CHARLIE":
            ax.plot(x_times, y_nums, label=th_i, color=cm.autumn((th_i - 1) / len(Thread_list)))
        else:
            ax.plot(x_times, y_nums, label=th_i, color=cm.winter((th_i - 1) / len(Thread_list)))

    minutes = mdates.MinuteLocator(interval=5)  # 5分間隔で描画
    timeFmt = mdates.DateFormatter('%H:%M')  # x軸の時刻表示フォーマットの設定
    ax.xaxis.set_major_locator(minutes)  # 上記の条件をグラフに設定
    ax.xaxis.set_major_formatter(timeFmt)  # 上記の条件をグラフに設定
    plt.xlim(start_t, finish_t)  # x軸の範囲を設定
    plt.ylim(0, 70)  # y軸の範囲を設定
    plt.title(group_n)
    # plt.legend(loc='upper left')  #データの名前を表示
    fig.autofmt_xdate()  # いい感じにx軸の時刻表示を調節
    plt.savefig(fn_path + group_n[0] + "_per_counter_post_no_legend" + ".png")
    plt.show()
Ejemplo n.º 2
0
def effects(User_list, Post_list,th_num ,agent_Type, save_f):
    start_t, finish_t = analysis_funcs._set_start_time(Post_list)
    finish_t = finish_t
    print(finish_t)

    fig = plt.figure()
    ax = fig.add_subplot(111)

    for u_i, u_n in enumerate(User_list.keys()):
        if u_n in ["facilitator", "kitkat"]:
            continue
        user = User_list[u_n]
        x_times, y_nums = _extract_time(user.pi_list, Post_list, u_i, len(User_list))

        ax.scatter(x_times, y_nums, s=1, label=user.name, color=cm.spring((u_i - 1) / len(User_list)))

    x_times, y_nums = _extract_time(User_list["facilitator"].pi_list, Post_list)
    ax.scatter(x_times, y_nums, s=1, label="facilitator", color="k")

    days = mdates.MinuteLocator(interval=120)
    daysFmt = mdates.DateFormatter('%H')
    ax.xaxis.set_major_locator(days)
    ax.xaxis.set_major_formatter(daysFmt)
    plt.xlim(start_t, finish_t)
    # plt.ylim(1, 13)
    plt.yticks(np.arange(1, th_num+1, 1))
    # plt.title(agent_Type)
    plt.hlines(list(range(1, th_num+1)), start_t, finish_t, "gray", linestyle=":", lw=0.1)  # グリット線の代わり

    # plt.legend(loc='upper left')  # ラベルの表示
    fig.autofmt_xdate()  # 時刻をいい感じに表示
    change_aspect_ratio(ax, 6)  # グラフの縦横比変更
    plt.savefig(str(save_f), dpi=500)
Ejemplo n.º 3
0
def counter_post_per_thread(Thread_list, Post_list, agent_Type, save_f):
    start_t, finish_t = _set_start_time(Post_list)

    fig = plt.figure()
    ax = fig.add_subplot(111)

    for th_i in range(1, len(Thread_list) + 1):
        thread = Thread_list[th_i]
        print(" title", th_i, thread.title)
        x_times, y_nums = _extract_time(thread.pi_list, Post_list)
        if len(x_times) == 0:
            print("     this thread has not post from users.")
            continue

        ax.plot(x_times,
                y_nums,
                label=th_i,
                color=cm.spring((th_i - 1) / len(Thread_list)))

    print(len(x_times))
    print(len(y_nums))
    minutes = mdates.MinuteLocator(interval=120)  # interval分間隔で描画
    timeFmt = mdates.DateFormatter('%H')  # x軸の時刻表示フォーマットの設定
    ax.xaxis.set_major_locator(minutes)  # 上記の条件をグラフに設定
    ax.xaxis.set_major_formatter(timeFmt)  # 上記の条件をグラフに設定
    plt.xlim(start_t, finish_t)  # x軸の範囲を設定
    plt.ylim(0, 30)  # y軸の範囲を設定
    # plt.title(agent_Type)
    plt.legend(loc='upper left')  # データの名前を表示
    fig.autofmt_xdate()  # いい感じにx軸の時刻表示を調節

    plt.savefig(str(save_f))
    # plt.show()
    print(save_f)
Ejemplo n.º 4
0
def getCO2Colour(_log, CO2):
    try:
        norm = matplotlib.colors.Normalize(vmin=0, vmax=2000)
        #rgba_color = cm.winter(norm(int(CO2)),bytes=True)
        rgba_color = cm.spring(norm(int(CO2)), bytes=True)
        c = Color(rgb=(rgba_color[0] / 255, rgba_color[1] / 255,
                       rgba_color[2] / 255))
    except:
        _log.error("Error in Fx getCO2Colour")
        c = '#0000FF'
    return c
Ejemplo n.º 5
0
def color_iter(num):
    num = int(num / 3) + 1
    x = np.arange(num)
    ys = [i + x + (i * x)**2 for i in range(num)]
    colormaps = cm.spring(np.linspace(0, 0.6, len(ys))), cm.plasma(
        np.linspace(0.35, 0.8,
                    len(ys))), cm.cool(np.linspace(0.2, 0.9, len(ys)))
    result = []
    for colormap in colormaps:
        for c in colormap:
            result.append(c)
    shuffle(result)
    return iter(result)
Ejemplo n.º 6
0
def _counter_post_per_user(User_list, Post_list, group_n):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    sort_uilist = sorted(User_list.keys())
    for u_i in sort_uilist:
        if u_i in except_usr_id:
            continue
        user = User_list[u_i]
        print(" user", user.name, u_i)
        x_times, y_nums = _extract_time(user.pi_list, Post_list)
        if len(x_times) == 0:
            print("     this thread has not post from users.")
            continue
        if group_n == "ALPHA":
            ax.plot(x_times, y_nums, label=user.name, color=cm.spring((u_i - 1) / len(User_list)))
            ax.plot(x_times[-1], y_nums[-1], marker='o', color=cm.spring((u_i - 1) / len(User_list)))
        elif group_n == "BRAVO":
            ax.plot(x_times, y_nums, label=user.name, color=cm.summer((u_i - 1) / len(User_list)))
            ax.plot(x_times[-1], y_nums[-1], marker='o', color=cm.summer((u_i - 1) / len(User_list)))
        elif group_n == "CHARLIE":
            ax.plot(x_times, y_nums, label=user.name, color=cm.autumn((u_i - 1) / len(User_list)))
            ax.plot(x_times[-1], y_nums[-1], marker='o', color=cm.autumn((u_i - 1) / len(User_list)))
        else:
            ax.plot(x_times, y_nums, label=user.name, color=cm.winter((u_i - 1) / len(User_list)))
            ax.plot(x_times[-1], y_nums[-1], marker='o', color=cm.winter((u_i - 1) / len(User_list)))

    days = mdates.MinuteLocator(interval=5)
    daysFmt = mdates.DateFormatter('%H:%M')
    ax.xaxis.set_major_locator(days)
    ax.xaxis.set_major_formatter(daysFmt)
    plt.xlim(start_t, finish_t)
    plt.ylim(0, 40)
    plt.title(group_n)
    plt.legend(loc='upper left')
    fig.autofmt_xdate()
    plt.savefig(fn_path + group_n[0] + "_per_user_post_counter" + ".png")
    plt.show()
Ejemplo n.º 7
0
def plot_codon_bias(db_fname):
    engine = sqlalchemy.create_engine('sqlite:///{}'.format(db_fname))
    matplotlib.style.use('ggplot')
    
    for ix, threshold in enumerate(THRESHOLDS):
        threshold_str_file = '%se-%d' % (re.search('([1-9])', str(threshold)).group(1), str(threshold).count('0'))
        print threshold_str_file
                
        n = len(os.listdir(os.path.join(OUTPUTDIR, dir, 'fasta_out_pangenome', threshold_str_file, 'unified')))
        threshold_str_sql = '%sEXPneg%d' % (re.search('([1-9])', str(threshold)).group(1), str(threshold).count('0'))
        stats_table_name = 'pangenome_%s_stats' % threshold_str_sql
        stats_table_df = pandas.read_sql_query('SELECT pangene_id, n_genomes, viral_flag, encp, fop, origin FROM {} WHERE paralog_flag=0'.format(stats_table_name), 
                                               engine, index_col='pangene_id')
        
        fig, axes = plt.subplots(2,5)
        plt.subplots_adjust(hspace=0.1)
        fig.suptitle('Distribution of Codon Bias Index Values per Pangenomic Bin for Fluidity Threshold %s\n(%d genomes, %d pangenes)' % 
                     (threshold_str_file, n, stats_table_df.index.size), fontsize=22)
        
        stats_table_df['bin'] = pandas.cut(stats_table_df['n_genomes'], bins=[0, 1, round(0.25*n, 0), round(0.75*n, 0), n-1, n], 
                                           #labels=['1_unique', '2_rare', '3_intermediate', '4_near-core', '5_core'])
                                           labels=[1, 2, 3, 4, 5])
        
        stats_table_df['origin_bin'] = stats_table_df['origin'].apply(lambda x: ['bacterial', 'viral', 'unknown'].index(x))
                
        for l, label in enumerate(['1_unique', '2_rare', '3_intermediate', '4_near-core', '5_core']):
            #plot_data = stats_table_df[stats_table_df['bin']=='1_unique']
            plot_data = stats_table_df[stats_table_df['bin']==l+1]
            
            plot_data.plot(ax=axes[0,l], kind='scatter', x='fop', y='encp', c='viral_flag', cmap='spring', edgecolor='k', colorbar=False, fontsize=12)        
            #plot_data[plot_data['viral_flag']==1].plot(ax=axes[ix], kind='scatter', x='fop', y='encp', color='DarkGreen', label='viral', fontsize=12)
                    
            axes[0,l].set_title('%s\n%d pangenes' % (label, plot_data.index.size), fontsize=14)
            axes[0,l].annotate('non viral: $\overline{FOP}=%.3f; \overline{ENC\'}=%.2f$\nviral: $\overline{FOP}=%.3f; \overline{ENC\'}=%.2f$' % 
                               (np.average(plot_data[plot_data['viral_flag']==0]['fop']),
                                np.average(plot_data[plot_data['viral_flag']==0]['encp']),
                                np.average(plot_data[plot_data['viral_flag']==1]['fop']),
                                np.average(plot_data[plot_data['viral_flag']==1]['encp'])),
                               (0.02, 0.04), size=10, xycoords="axes fraction", va="center", ha="left")
            
            plot_data.plot(ax=axes[1,l], kind='scatter', x='fop', y='encp', c='origin_bin', cmap='rainbow', edgecolor='k', colorbar=False, fontsize=12)
            axes[1,l].annotate('bacterial: $\overline{FOP}=%.3f; \overline{ENC\'}=%.2f$\nphage: $\overline{FOP}=%.3f; \overline{ENC\'}=%.2f$\nunknown: $\overline{FOP}=%.3f; \overline{ENC\'}=%.2f$' % 
                               (np.average(plot_data[plot_data['origin_bin']==0]['fop']),
                                np.average(plot_data[plot_data['origin_bin']==0]['encp']),
                                np.average(plot_data[plot_data['origin_bin']==1]['fop']),
                                np.average(plot_data[plot_data['origin_bin']==1]['encp']),
                                np.average(plot_data[plot_data['origin_bin']==2]['fop']),
                                np.average(plot_data[plot_data['origin_bin']==2]['encp'])),
                               (0.02, 0.06), size=10, xycoords="axes fraction", va="center", ha="left")
            
            '''print label
            print 'non viral: average fop: %.3f; average encp: %.2f' % (np.average(plot_data[plot_data['viral_flag']==0]['fop']), 
                                                                        np.average(plot_data[plot_data['viral_flag']==0]['encp']))
            print 'viral: average fop: %.3f; average encp: %.2f' % (np.average(plot_data[plot_data['viral_flag']==1]['fop']), 
                                                                    np.average(plot_data[plot_data['viral_flag']==1]['encp']))'''
        
        nonvirArtist = plt.Line2D((0,0),(0,0), color=cm.spring(0), marker='o', linestyle='')
        virArtist = plt.Line2D((0,0),(0,0), color=cm.spring(256), marker='o', linestyle='')
        fig.legend([nonvirArtist, virArtist], ['non viral', 'viral'], bbox_to_anchor=(0.1, 0.74), title='PhiSpy Category')
        
        bacArtist = plt.Line2D((0,0),(0,0), color=cm.rainbow(0), marker='o', linestyle='')
        phaArtist = plt.Line2D((0,0),(0,0), color=cm.rainbow(256//2), marker='o', linestyle='')
        unkArtist = plt.Line2D((0,0),(0,0), color=cm.rainbow(256), marker='o', linestyle='')
        fig.legend([bacArtist, phaArtist, unkArtist], ['bacteria', 'phage', 'unknown'], bbox_to_anchor=(0.1, 0.34), title='Origin by Annotation')
        
        plt.show()
    return
Ejemplo n.º 8
0
    def simulate(self, plot=False):
        """
        This runs the simulation.
        """
        # Initialising history lists for distribution of strategies

        # Some debugging
        # import pdb
        # pdb.set_trace()

        self.row_history = [[] for e in range(len(self.row_strategies))]
        self.col_history = [[] for e in range(len(self.col_strategies))]
        if plot:
            # If plot is true we plot the strategy distributions dynamically
            import matplotlib.pyplot as plt
            import matplotlib.cm as cm
            plt.ion()  # Turn interactive mode on (so that we can graph dynamically.
            plt.ylim(0, 1)  # Set ylim to have min 0 and max 1
            plt.xlabel("Generations (max=%s)" % self.generations)  # Label for x axis
            plt.ylabel("Probability")  # Label for y axis
            for k in range(len(self.row_strategies)):
                # Plot all row strategies
                c = cm.spring((k + 1) / len(self.row_strategies))
                plt.plot(self.row_history[k], color=c, label="Row strategy: %s" % (k + 1))
            for k in range(len(self.col_strategies)):
                # Plot all col strategies
                c = cm.winter((k + 1) / len(self.col_strategies))
                plt.plot(self.col_history[k], "--", color=c, label="Col strategy: %s" % (k + 1))

            plt.legend(loc="upper left")
            plt.draw()

        for g in range(self.generations):
            # In a loop for every generation
            print "\n----------------------"
            print "\nGeneration: %s of %s" % (g + 1, self.generations)
            for r in range(self.rounds_per_generation):
                # Loop to repeat tournament for each generation
                print "\tRound: %s of %s" % (r + 1, self.rounds_per_generation)
                # Reset all utilities before starting a tournament
                for k in range(self.number_of_agents):
                    self.row_agents[k].utility = 0
                    self.col_agents[k].utility = 0
                self.play_tournament()
            # Calculate distributions and update history
            self.row_distribution = return_current_strategy_distribution(self.row_agents, self.row_strategies)
            for k in range(len(self.row_strategies)):
                self.row_history[k].append(self.row_distribution[k])
            self.col_distribution = return_current_strategy_distribution(self.col_agents, self.col_strategies)
            for k in range(len(self.col_strategies)):
                self.col_history[k].append(self.col_distribution[k])
            print "\nRow players strategy distribution:"
            print "\t", self.row_distribution
            print "\nCol players strategy distribution:"
            print "\t", self.col_distribution
            # Reproduce
            self.reproduce()

            if plot:
                # Update the plot if plot is True
                for k in range(len(self.row_strategies)):
                    c = cm.spring((k + 1) / len(self.row_strategies))
                    plt.plot(self.row_history[k], color=c)
                for k in range(len(self.col_strategies)):
                    c = cm.winter((k + 1) / len(self.col_strategies))
                    plt.plot(self.col_history[k], "--", color=c)
                plt.draw()
        if plot:
            # Block plot at end of simulation
            plt.show(block=True)
Ejemplo n.º 9
0
    def solveIP(self,xe,Y):
        """
        Solve the Inverse Problem
        
        Arguments:
            xe {numpy array [n,Ne]} -- previous ensemble
            Y {numpy array [Ny,]} -- vector of measurements
        
        Returns:
            numpy array [n,Ne]  -- next ensemble
        """
        Ny = Y.shape[0]
        print(f"xe shape: {xe.shape}, Y shape: {Y.shape}")
        R = np.diag(np.ones(Y.size)*self.eta_0)
        xepast = xe

        xe_hist = []
        dt = 0.1


        for j in range(self.maxiter):
            
            xe_hist.append(xe)
            ubar = np.mean(xe,axis=1,keepdims=True) # keepdims so it can be substracted to xe
            Gxe = np.zeros((Ny,self.Ne))
            for i in range(self.Ne):
                Gxe[:,i] = self.G(xe[:,i])
            gbar = np.mean(Gxe,axis=1,keepdims=True)
            gubar = self.G(ubar)

            u_d = xe - ubar
            Gxe_d = Gxe - gbar
            Cuu = (u_d @ u_d.T)/self.Ne
            Cug = (   u_d @ Gxe_d.T )/self.Ne
            Cgg = ( Gxe_d @ Gxe_d.T)/self.Ne
            S = Cgg + R
            K = Cug @ np.linalg.inv(S) 

            tau0i = 
            
            debug = False
            if debug:
                plt.figure()
                plt.subplot(2,1,1,xlabel="Ns*(N+1)", ylabel="Ns*(N+1)")
                for i in range(self.Ne):
                    plt.plot(Gxe[:,i], linewidth=1,label=f'\\theta {xe[:,i]}')
                plt.plot(Y, linewidth=3,label=f'Measurement')                
                plt.xlabel("Time, x, then v")
                plt.ylabel("measurement difference")
                plt.grid()
                plt.legend()
                plt.title("Measurement for different ensembles")
                plt.subplot(2,1,2,xlabel="time", ylabel="K")
                plt.plot(K.T, linewidth=1,label=f'Measurement')  
                plt.grid()
                plt.legend()
                # plt.subplot(2,2,2,xlabel="U", ylabel=f"Cuu")
                # plt.imshow(Cuu,  interpolation='nearest', cmap=cm.Greys_r)
                # plt.subplot(2,2,3,xlabel="g", ylabel="Cgg")
                # plt.imshow(Cgg,  interpolation='nearest', cmap=cm.Greys_r)

                if self.n == 2:
                    plt.figure()
                    plt.scatter(xe[0,:],xe[1,:],color='b')
                    plt.grid()
                    plt.scatter(self.true_theta[0],self.true_theta[1],color='r')
                    plt.xlabel('B1')
                    plt.ylabel('B2')

                plt.show()
                plt.savefig(f"eki_debug_states.pdf", format='pdf', dpi=1200)
                print("test pring")

            #Cuu_new = Cuu - K @ S @ K.T# Update Cuu
            Yd = np.reshape(Y, (-1, 1)) + np.random.normal(size=(Y.size,self.Ne))*self.eta_0*0.
            
            ubar_new = np.squeeze(ubar) + K @ (Y - gubar)
            
            for i in range(self.Ne):            
                xe = xe + K @ (Yd - Gxe) + np.random.multivariate_normal(np.zeros(self.n), Cuu_new, self.Ne).T     
                xe = (np.eye(self.Nu)+dt*tau0i)
            
            #xe = ubar_new[:, np.newaxis] + np.random.multivariate_normal(np.zeros(self.n), Cuu_new, self.Ne).T     


            error_v = np.mean(xe,axis=1)-self.true_theta
            dtheta_change = xe-xepast
            #error_dtheta = np.sqrt(dtheta_change.dot(dtheta_change))
            xepast = xe.copy()
            error = np.sqrt(error_v.dot(error_v))
            print(f'Iteration EKI {j+1}/{self.maxiter}. Error {error:.2f}')
            print(f"xe {xe}")
            print(f"ubar {ubar}")



            #if (abs(error) < self.max_error):
            #    break
        self.ubar = ubar
        self.cov_theta = Cuu


        if self.n == 2:
            from matplotlib import cm
            #colors = [ cm.jet(x) for x in cm_subsection ]
            plt.figure()
            Nhist = len(xe_hist)
            for i in range(len(xe_hist)):
                plt.scatter(xe_hist[i][0,:],xe_hist[i][1,:],color=cm.spring(i/Nhist))
            plt.grid()
            plt.scatter(self.true_theta[0],self.true_theta[1],color='r')
            plt.xlabel('B1')
            plt.ylabel('B2')
            plt.show()

        return xe
Ejemplo n.º 10
0
    def simulate(self, plot=False):
        """
        This runs the simulation.
        """
        # Initialising history lists for distribution of strategies

        # Some debugging
        # import pdb
        # pdb.set_trace()

        self.row_history = [[] for e in range(len(self.row_strategies))]
        self.col_history = [[] for e in range(len(self.col_strategies))]
        if plot:
            # If plot is true we plot the strategy distributions dynamically
            import matplotlib.pyplot as plt
            import matplotlib.cm as cm
            plt.ion(
            )  # Turn interactive mode on (so that we can graph dynamically.
            plt.ylim(0, 1)  # Set ylim to have min 0 and max 1
            plt.xlabel("Generations (max=%s)" %
                       self.generations)  # Label for x axis
            plt.ylabel("Probability")  # Label for y axis
            for k in range(len(self.row_strategies)):
                # Plot all row strategies
                c = cm.spring((k + 1) / len(self.row_strategies))
                plt.plot(self.row_history[k],
                         color=c,
                         label="Row strategy: %s" % (k + 1))
            for k in range(len(self.col_strategies)):
                # Plot all col strategies
                c = cm.winter((k + 1) / len(self.col_strategies))
                plt.plot(self.col_history[k],
                         "--",
                         color=c,
                         label="Col strategy: %s" % (k + 1))

            plt.legend(loc="upper left")
            plt.draw()

        for g in range(self.generations):
            # In a loop for every generation
            print "\n----------------------"
            print "\nGeneration: %s of %s" % (g + 1, self.generations)
            for r in range(self.rounds_per_generation):
                # Loop to repeat tournament for each generation
                print "\tRound: %s of %s" % (r + 1, self.rounds_per_generation)
                # Reset all utilities before starting a tournament
                for k in range(self.number_of_agents):
                    self.row_agents[k].utility = 0
                    self.col_agents[k].utility = 0
                self.play_tournament()
            # Calculate distributions and update history
            self.row_distribution = return_current_strategy_distribution(
                self.row_agents, self.row_strategies)
            for k in range(len(self.row_strategies)):
                self.row_history[k].append(self.row_distribution[k])
            self.col_distribution = return_current_strategy_distribution(
                self.col_agents, self.col_strategies)
            for k in range(len(self.col_strategies)):
                self.col_history[k].append(self.col_distribution[k])
            print "\nRow players strategy distribution:"
            print "\t", self.row_distribution
            print "\nCol players strategy distribution:"
            print "\t", self.col_distribution
            # Reproduce
            self.reproduce()

            if plot:
                # Update the plot if plot is True
                for k in range(len(self.row_strategies)):
                    c = cm.spring((k + 1) / len(self.row_strategies))
                    plt.plot(self.row_history[k], color=c)
                for k in range(len(self.col_strategies)):
                    c = cm.winter((k + 1) / len(self.col_strategies))
                    plt.plot(self.col_history[k], "--", color=c)
                plt.draw()
        if plot:
            # Block plot at end of simulation
            plt.show(block=True)
plt.ylabel('VAF rate (Gt yr$^{-1}$)')
plt.grid()

# =========
print("Done setting up figure axes.")
# =========

# --- Define colors for lines ---
colors = []
#colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:olive', 'tab:cyan']
n150 = sum("amp150" in r for r in runs)
colors.extend([cm.autumn(x) for x in np.linspace(0.0, 1.0, n150)])
n300 = sum("amp300" in r for r in runs)
colors.extend([cm.winter(x) for x in np.linspace(0.0, 1.0, n300)])
n05 = sum("amp0." in r for r in runs)
colors.extend([cm.spring(x) for x in np.linspace(0.0, 1.0, n05)])
color_index = 0

# ================
# Loop over runs and plot data
# ================
runNumber = 0
for run in runs:
    print("Plotting run: " + run)

    thisRun = runData[run]
    # Pull needed data for plotting from this run
    # TODO: replace local variables below in plotting commands with reference to object variables
    yrs = thisRun.yrs
    melt = thisRun.melt
    totalmelt = thisRun.totalmelt
Ejemplo n.º 12
0
    def __init__(self):

        self.TARGET_FPS = 30
        cam_w, cam_h = (640, 480)
        timer_w = 640
        w, h = (cam_w + timer_w, cam_h)
        pygame.init()
        self.cam_w = cam_w
        self.cam_h = cam_h
        self.sounds = Sounds()
        # ISPIRO: Load goal image. Pygame handles png transparency gracefully
        self.goal_image = pygame.image.load("goal.png")
        self.goal_w = self.goal_image.get_width()
        self.goal_h = self.goal_image.get_height()

        try:
            assert options.objects is not None
        except:
            print "Make sure you define 1 or more vicon objects through -o"
            sys.exit(1)

        if options.vicon_file is not None:
            self.simulation_mode = True
        else:
            self.simulation_mode = False
            print "Running in live mode. " "Possession will hang here if you are not connected to a Vicon Proxy server"

        window = pygame.display.set_mode((w, h), DOUBLEBUF)

        # surface representing cam view
        self.camsurface = pygame.Surface((cam_w, cam_h))

        # ISPIRO: Need a mask image for blitting circles
        self.mask = pygame.Surface((cam_w, cam_h))
        # surface representing entire display
        self.screen = pygame.display.get_surface()

        self.cameras = []
        for c in options.cameras:
            self.cameras.append(Camera(c, fps=self.TARGET_FPS))

        if self.simulation_mode:
            self.f = open(options.vicon_file, "r")
            # should we read ahead?
            for i in xrange(options.line):
                self.f.readline()
        else:
            # Initialize the object...
            print "Waiting for Vicon..."
            self.vp = ViconProxy()

        self.balls = []
        for o in options.objects:
            self.balls.append(Ball(self.f if self.simulation_mode else self.vp, o))

        # set up team colors
        self.teamcolors = [cm.jet(x) for x in np.linspace(0.2, 0.8, options.numteams)]
        # set up object colors (using a different colormap)
        self.objectcolors = [cm.spring(x) for x in np.linspace(0, 1, len(options.objects))]

        self.score = [0] * options.numteams
        # self.update_score()

        self.accumulator = 0
        self.digit = options.game_time
        self.clock = pygame.time.Clock()
Ejemplo n.º 13
0
def main():
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5, .55, .6]
    files = [
        '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/dG_raw_varz_2.pkl'
        % str(x)[1::] for x in lam
    ]
    colors = cm.spring(numpy.linspace(0, 1, len(lam)))
    matplotlib.rc('font', family='serif')
    font = {'family': 'serif', 'size': 'larger'}

    dGf = numpy.zeros((len(lam), 13))
    dHf = numpy.zeros((len(lam), 11))
    dSf = numpy.zeros((len(lam), 11))
    dGu = numpy.zeros((len(lam), 13))
    dHu = numpy.zeros((len(lam), 11))
    dSu = numpy.zeros((len(lam), 11))
    ddGf = numpy.zeros((len(lam), 13))
    ddHf = numpy.zeros((len(lam), 11))
    ddSf = numpy.zeros((len(lam), 11))
    ddGu = numpy.zeros((len(lam), 13))
    ddHu = numpy.zeros((len(lam), 11))
    ddSu = numpy.zeros((len(lam), 11))

    for i in range(len(lam)):
        print 'Reading %s' % files[i]
        f = open(files[i], 'rb')
        target_temperatures = cPickle.load(f)
        bin_centers = cPickle.load(f)
        print 'The 4 states are centered at', bin_centers
        dG = cPickle.load(f)
        ddG = cPickle.load(f)
        f.close()

        # Free energies of adsorption
        dGads_folded = dG[:,
                          1] - dG[:,
                                  3]  # free energy of adsorption while adsorbed
        dGads_unfolded = dG[:,
                            0] - dG[:,
                                    2]  # free eneryg of adsorption while desorbed

        # Entropies of adsorption
        # dS(t) = -dG/dT = -(G[t+.5h] - G[t-.5h])/h
        dSads_folded = (dGads_folded[2::] -
                        dGads_folded[0:-2]) / -10  # finite difference
        dSads_unfolded = (dGads_unfolded[2::] - dGads_unfolded[0:-2]) / -10
        temp_sub = target_temperatures[1:-1]

        # Enthalpies of adsorption
        # dG = dH - TdS
        # dH = dG + TdS
        dHads_folded = dGads_folded[1:-1] + temp_sub * dSads_folded
        dHads_unfolded = dGads_unfolded[1:-1] + temp_sub * dSads_unfolded

        # Uncertainties - just propagation of error for now
        ddGads_folded = [numpy.sqrt(x[1, 0]) for x in ddG]
        ddGads_folded = numpy.array(ddGads_folded)
        ddSads_folded = (ddGads_folded[0:-2]**2 +
                         ddGads_folded[2::]**2)**.5 / 10
        ddHads_folded = (ddGads_folded[1:-1]**2 +
                         (temp_sub * ddSads_folded)**2)**.5

        ddGads_unfolded = [numpy.sqrt(x[3, 2]) for x in ddG]
        ddGads_unfolded = numpy.array(ddGads_unfolded)
        ddSads_unfolded = (ddGads_unfolded[0:-2]**2 +
                           ddGads_unfolded[2::]**2)**.5 / 10
        ddHads_unfolded = (ddGads_unfolded[1:-1]**2 +
                           (temp_sub * ddSads_unfolded)**2)**.5

        dGf[i, :] = dGads_folded
        dHf[i, :] = dHads_folded
        dSf[i, :] = dSads_folded
        dGu[i, :] = dGads_unfolded
        dHu[i, :] = dHads_unfolded
        dSu[i, :] = dSads_unfolded
        ddGf[i, :] = ddGads_folded
        ddHf[i, :] = ddHads_folded
        ddSf[i, :] = ddSads_folded
        ddGu[i, :] = ddGads_unfolded
        ddHu[i, :] = ddHads_unfolded
        ddSu[i, :] = ddSads_unfolded

        f = plt.figure(1)
        plt.rc('text', usetex=True)

        ax1 = plt.subplot(311)
        ax1.errorbar(target_temperatures,
                     dGads_folded,
                     ddGads_folded,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.xlim((300, 350))
        plt.ylabel(r'$\Delta$G_{adsorption}$')
        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.legend(prop={'size': 6})
        plt.title('Thermodynamics of adsorption, folded')

        ax2 = plt.subplot(312)
        plt.xlim((300, 350))
        ax2.errorbar(temp_sub,
                     dSads_folded,
                     ddSads_folded,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.ylabel(r'$\Delta$S_{adsorption}$')
        plt.legend(prop={'size': 6})

        ax3 = plt.subplot(313)
        plt.xlim((300, 350))
        ax3.errorbar(temp_sub,
                     dHads_folded,
                     ddHads_folded,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.xlabel(r'temperature (K)')
        plt.ylabel(r'$\Delta$H_{adsorption}$')
        plt.legend(prop={'size': 6})

        f.subplots_adjust(hspace=0)

        f = plt.figure(3)
        plt.rc('text', usetex=True)

        ax1 = plt.subplot(311)
        ax1.errorbar(target_temperatures,
                     dGads_folded - dGads_unfolded,
                     ddGads_unfolded,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.xlim((300, 350))
        plt.ylabel(r'$\Delta$G_{adsorption}$')
        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.legend(prop={'size': 6})
        #     plt.title('Relative thermodynamics of adsorption (folded-unfolded)')

        ax2 = plt.subplot(312)
        plt.xlim((300, 350))
        ax2.errorbar(temp_sub,
                     dSads_folded - dSads_unfolded,
                     ddSads_unfolded,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.ylabel(r'$\Delta$S_{adsorption}$')
        plt.yticks(numpy.arange(-.05, .15, .05))
        plt.legend(prop={'size': 6})

        ax3 = plt.subplot(313)
        plt.xlim((300, 350))
        ax3.errorbar(temp_sub,
                     dHads_folded - dHads_unfolded,
                     ddHads_unfolded,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.xlabel(r'temperature (K)')
        plt.ylabel(r'$\Delta$H_{adsorption}$')
        plt.yticks(numpy.arange(-10, 60, 10))
        plt.legend(prop={'size': 6})

        f.subplots_adjust(hspace=0)

        f = plt.figure(2)
        plt.rc('text', usetex=True)

        ax1 = plt.subplot(311)
        ax1.errorbar(target_temperatures,
                     dGads_unfolded,
                     ddGads_unfolded,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.xlim((300, 350))
        plt.ylabel(r'$\Delta$G_{adsorption}$')
        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.legend(prop={'size': 6})
        plt.title('Thermodynamics of adsorption, unfolded')

        ax2 = plt.subplot(312)
        plt.xlim((300, 350))
        ax2.errorbar(temp_sub,
                     dSads_unfolded,
                     ddSads_unfolded,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.ylabel(r'$\Delta$S_{adsorption}$')
        plt.legend(prop={'size': 6})

        ax3 = plt.subplot(313)
        plt.xlim((300, 350))
        ax3.errorbar(temp_sub,
                     dHads_unfolded,
                     ddHads_unfolded,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.xlabel(r'temperature (K)')
        plt.ylabel(r'$\Delta$H_{adsorption}$')
        plt.legend(prop={'size': 6})

        f.subplots_adjust(hspace=0)

    f = plt.figure(4)
    plt.rc('text', usetex=True)
    ax1 = plt.subplot(311)
    ax1.errorbar(lam, dGf[:, 6], ddGf[:, 6], label='folded')
    ax1.errorbar(lam, dGu[:, 6], ddGu[:, 6], label='unfolded')
    plt.ylabel(r'$\Delta$G_{adsorption}$')
    plt.setp(ax1.get_xticklabels(), visible=False)
    #plt.title('Thermodynamics of adsorption')
    plt.legend(prop={'size': 9})

    ax2 = plt.subplot(312)
    ax2.errorbar(lam, dSf[:, 5], ddSf[:, 5], label='folded')
    ax2.errorbar(lam, dSu[:, 5], ddSu[:, 5], label='unfolded')
    plt.setp(ax2.get_xticklabels(), visible=False)
    plt.ylabel(r'$\Delta$S_{adsorption}$')
    plt.legend(prop={'size': 9})
    plt.yticks(numpy.arange(-.2, .05, .05))

    ax3 = plt.subplot(313)
    ax3.errorbar(lam, dHf[:, 5], ddHf[:, 5], label='folded')
    ax3.errorbar(lam, dHu[:, 5], ddHu[:, 5], label='unfolded')
    plt.xlabel(r'$\lambda$')
    plt.ylabel(r'$\Delta$H_{adsorption}$')
    plt.legend(prop={'size': 9})
    plt.yticks(numpy.arange(-100, 20, 20))

    f.subplots_adjust(hspace=0)
Ejemplo n.º 14
0
def main():
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5, .55, .6]
    files = ['/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/dG_raw_varz_2.pkl' % str(x)[1::] for x in lam]
    colors = cm.spring(numpy.linspace(0,1,len(lam)))
    matplotlib.rc('font', family = 'serif')
    font = {'family' : 'serif',
            'size'   : 'larger'}

    dGf = numpy.zeros((len(lam),13))
    dHf = numpy.zeros((len(lam),11))
    dSf = numpy.zeros((len(lam),11))
    dGu = numpy.zeros((len(lam),13))
    dHu = numpy.zeros((len(lam),11))
    dSu = numpy.zeros((len(lam),11))
    ddGf = numpy.zeros((len(lam),13))
    ddHf = numpy.zeros((len(lam),11))
    ddSf = numpy.zeros((len(lam),11))
    ddGu = numpy.zeros((len(lam),13))
    ddHu = numpy.zeros((len(lam),11))
    ddSu = numpy.zeros((len(lam),11))

    for i in range(len(lam)):
        print 'Reading %s' % files[i]
        f = open(files[i],'rb')
        target_temperatures = cPickle.load(f)
        bin_centers = cPickle.load(f)
        print 'The 4 states are centered at', bin_centers
        dG = cPickle.load(f)
        ddG = cPickle.load(f)
        f.close()
    
        # Free energies of adsorption
        dGads_folded = dG[:,1] - dG[:,3] # free energy of adsorption while adsorbed
        dGads_unfolded = dG[:,0] - dG[:,2] # free eneryg of adsorption while desorbed
    
        # Entropies of adsorption
        # dS(t) = -dG/dT = -(G[t+.5h] - G[t-.5h])/h
        dSads_folded = (dGads_folded[2::] - dGads_folded[0:-2])/-10 # finite difference
        dSads_unfolded = (dGads_unfolded[2::] - dGads_unfolded[0:-2])/-10
        temp_sub = target_temperatures[1:-1]
    
        # Enthalpies of adsorption
        # dG = dH - TdS
        # dH = dG + TdS
        dHads_folded = dGads_folded[1:-1] + temp_sub*dSads_folded
        dHads_unfolded = dGads_unfolded[1:-1] + temp_sub*dSads_unfolded
    
        # Uncertainties - just propagation of error for now
        ddGads_folded = [numpy.sqrt(x[1,0]) for x in ddG]
        ddGads_folded = numpy.array(ddGads_folded)
        ddSads_folded = (ddGads_folded[0:-2]**2 + ddGads_folded[2::]**2)**.5/10
        ddHads_folded = (ddGads_folded[1:-1]**2 + (temp_sub*ddSads_folded)**2)**.5
    
        ddGads_unfolded = [numpy.sqrt(x[3,2]) for x in ddG]
        ddGads_unfolded = numpy.array(ddGads_unfolded)
        ddSads_unfolded = (ddGads_unfolded[0:-2]**2 + ddGads_unfolded[2::]**2)**.5/10
        ddHads_unfolded = (ddGads_unfolded[1:-1]**2 + (temp_sub*ddSads_unfolded)**2)**.5
     
        dGf[i,:] = dGads_folded        
        dHf[i,:] = dHads_folded        
        dSf[i,:] = dSads_folded        
        dGu[i,:] = dGads_unfolded        
        dHu[i,:] = dHads_unfolded        
        dSu[i,:] = dSads_unfolded        
        ddGf[i,:] = ddGads_folded        
        ddHf[i,:] = ddHads_folded        
        ddSf[i,:] = ddSads_folded        
        ddGu[i,:] = ddGads_unfolded        
        ddHu[i,:] = ddHads_unfolded        
        ddSu[i,:] = ddSads_unfolded        

        f=plt.figure(1)
        plt.rc('text',usetex=True)
        
        ax1 = plt.subplot(311)
        ax1.errorbar(target_temperatures,dGads_folded,ddGads_folded,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.xlim((300,350))
        plt.ylabel(r'$\Delta$G_{adsorption}$')
        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.legend(prop={'size':6})
        plt.title('Thermodynamics of adsorption, folded')        

        ax2 = plt.subplot(312)
        plt.xlim((300,350))
        ax2.errorbar(temp_sub,dSads_folded,ddSads_folded,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.ylabel(r'$\Delta$S_{adsorption}$')
        plt.legend(prop={'size':6})
        
        ax3 = plt.subplot(313)
        plt.xlim((300,350))
        ax3.errorbar(temp_sub,dHads_folded,ddHads_folded,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.xlabel(r'temperature (K)')
        plt.ylabel(r'$\Delta$H_{adsorption}$')
        plt.legend(prop={'size':6})
    
        f.subplots_adjust(hspace=0)

        f=plt.figure(3)
        plt.rc('text',usetex=True)
        
        ax1 = plt.subplot(311)
        ax1.errorbar(target_temperatures,dGads_folded-dGads_unfolded,ddGads_unfolded,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.xlim((300,350))
        plt.ylabel(r'$\Delta$G_{adsorption}$')
        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.legend(prop={'size':6})
   #     plt.title('Relative thermodynamics of adsorption (folded-unfolded)')        
        
        ax2 = plt.subplot(312)
        plt.xlim((300,350))
        ax2.errorbar(temp_sub,dSads_folded-dSads_unfolded,ddSads_unfolded,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.ylabel(r'$\Delta$S_{adsorption}$')
        plt.yticks(numpy.arange(-.05,.15,.05))
        plt.legend(prop={'size':6})
        
        ax3 = plt.subplot(313)
        plt.xlim((300,350))
        ax3.errorbar(temp_sub,dHads_folded-dHads_unfolded,ddHads_unfolded,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.xlabel(r'temperature (K)')
        plt.ylabel(r'$\Delta$H_{adsorption}$')
        plt.yticks(numpy.arange(-10,60,10))
        plt.legend(prop={'size':6})
    
        f.subplots_adjust(hspace=0)

        f=plt.figure(2)
        plt.rc('text',usetex=True)
        
        ax1 = plt.subplot(311)
        ax1.errorbar(target_temperatures,dGads_unfolded,ddGads_unfolded,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.xlim((300,350))
        plt.ylabel(r'$\Delta$G_{adsorption}$')
        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.legend(prop={'size':6})
        plt.title('Thermodynamics of adsorption, unfolded')        
        
        ax2 = plt.subplot(312)
        plt.xlim((300,350))
        ax2.errorbar(temp_sub,dSads_unfolded,ddSads_unfolded,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.ylabel(r'$\Delta$S_{adsorption}$')
        plt.legend(prop={'size':6})
        
        ax3 = plt.subplot(313)
        plt.xlim((300,350))
        ax3.errorbar(temp_sub,dHads_unfolded,ddHads_unfolded,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.xlabel(r'temperature (K)')
        plt.ylabel(r'$\Delta$H_{adsorption}$')
        plt.legend(prop={'size':6})
    
        f.subplots_adjust(hspace=0)

    f=plt.figure(4)
    plt.rc('text',usetex=True)
    ax1 = plt.subplot(311)
    ax1.errorbar(lam,dGf[:,6],ddGf[:,6],label='folded')    
    ax1.errorbar(lam,dGu[:,6],ddGu[:,6],label='unfolded')    
    plt.ylabel(r'$\Delta$G_{adsorption}$')
    plt.setp(ax1.get_xticklabels(), visible=False)
    #plt.title('Thermodynamics of adsorption')        
    plt.legend(prop={'size':9})

    ax2 = plt.subplot(312)
    ax2.errorbar(lam,dSf[:,5],ddSf[:,5],label='folded')    
    ax2.errorbar(lam,dSu[:,5],ddSu[:,5],label='unfolded')    
    plt.setp(ax2.get_xticklabels(), visible=False)
    plt.ylabel(r'$\Delta$S_{adsorption}$')
    plt.legend(prop={'size':9})
    plt.yticks(numpy.arange(-.2,.05,.05))

    ax3 = plt.subplot(313)
    ax3.errorbar(lam,dHf[:,5],ddHf[:,5],label='folded')    
    ax3.errorbar(lam,dHu[:,5],ddHu[:,5],label='unfolded')    
    plt.xlabel(r'$\lambda$')
    plt.ylabel(r'$\Delta$H_{adsorption}$')
    plt.legend(prop={'size':9})
    plt.yticks(numpy.arange(-100,20,20))

    f.subplots_adjust(hspace=0)