コード例 #1
0
ファイル: time_series.py プロジェクト: kkikori/10_analysis
def counter_post_per_user(User_list, Post_list, agent_Type, save_f):
    start_t, finish_t = _set_start_time(Post_list)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    sort_uilist = sorted(User_list.keys())
    for u_i, u_n in enumerate(sort_uilist):
        if u_n in ["facilitator", "kitkat"]:
            continue
        user = User_list[u_n]
        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

        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)))

    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(0, 25)
    # plt.title(agent_Type)
    plt.legend(loc='upper left')
    fig.autofmt_xdate()
    plt.savefig(str(save_f))
コード例 #2
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()
コード例 #3
0
ファイル: PaperFigs.py プロジェクト: xueke-li/drought-atlas
def get_dataset_color(dataset,depth=None):
    """Set the colors to ensure a uniform scheme for each dataset """
    dataset=string.lower(dataset)
    d={}
    d["dai"]=cm.Blues(.5)
    d["tree"]=cm.summer(.3)
    d["cru"]=cm.Blues(.9)

    #models
    d["picontrol"]=cm.Purples(.8)
    d["h85"]="k"
    d["tree_noise"]=cm.PiYG(.2)
    
    #Soil moisture
    
    d["merra2"]={}
    d["merra2"]["30cm"]=cm.copper(.3)
    d["merra2"]["2m"]=cm.copper(.3)
    d["gleam"]={}
    d["gleam"]["30cm"]=cm.Reds(.3)
    d["gleam"]["2m"]=cm.Reds(.7)
    if depth is None:
        return d[dataset]
    else:
        return d[dataset][depth]
コード例 #4
0
ファイル: painter.py プロジェクト: anonslou/zabbixGraph
 def _get_color(self, legend):
     if 'IN' in legend:
         self._summer += 80
         return cm.summer(self._summer)
     if 'OUT' in legend:
         self._spring += 80
         return cm.winter(self._spring)
コード例 #5
0
def main():
    lam = [.1, .2, .3, .4, .5, .525, .55, .6, .625, .675, .7]
    lam = [.1, .2, .3, .35, .4, .45, .5, .6, .7]
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5, .55, .6]
    files = ['/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/dG_raw.pkl' % str(x)[1::] for x in lam]
    colors = cm.summer(numpy.linspace(0,1,len(lam)))
    for i in range(len(lam)):
        plot_dG.main(files[i],lam[i],colors[i])
    for i in range(1,7):
        plt.figure(i)
        plt.legend()
    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/dG_raw.pkl'
    plot_dG_solution.solution(soln)
    plt.show()
コード例 #6
0
ファイル: plotters.py プロジェクト: Leanderrr/fruitvliegen
def initplot(genes):
    """
    Starts a figure and initiates colors
    :param genes:
    :return: axis handle, colors for the genome values and colors for the lines
    """
    cm_subsection = linspace(0, 1, len(genes[0]) + 2)
    colors = [cm.summer(x) for x in cm_subsection]
    colors2 = [cm.Reds(x) for x in cm_subsection]

    fig = plt.figure(figsize=(10, 15))
    ax = fig.add_subplot(111)

    return ax, colors, colors2
コード例 #7
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()
コード例 #8
0
def plot_precision_recall_range(APs,
                                iou_thresholds,
                                precisions,
                                recalls,
                                save_fig=False,
                                title=""):
    """Draw the precision-recall curve over range of IOUs.

    precisions: list of precision values
    recalls: list of recall values
    """
    # Plot the Precision-Recall curve
    _, ax = plt.subplots(1, figsize=(7, 5))
    #ax.set_title("Precision-Recall Curve")
    ax.set_ylabel("precision", fontsize=14)
    ax.set_xlabel("recall", fontsize=14)
    ax.set_title(title, fontsize=16)
    ax.set_ylim(0, 1.1)
    ax.set_xlim(0, 1.1)
    colors = cm.summer(np.linspace(0, 1, len(recalls)))
    for i, r in enumerate(recalls):
        p = precisions[i]
        iou = iou_thresholds[i]
        AP = APs[i]
        _ = ax.plot(r,
                    p,
                    label="AP@{:.2f} = {:.3f}".format(iou, AP),
                    c=colors[i])
    # Shrink current axis by 20%
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    # Put a legend to the right of the current axis
    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.subplots_adjust(right=.7, left=0.1, top=.9, bottom=.1)
    np.save("./precision_recall_" + title, APs)
    if save_fig:
        plt.savefig("./precision_recall_" + title + ".eps", fmt="eps")
コード例 #9
0
from sklearn.metrics import precision_recall_fscore_support as score

precision, recall, fscore, support = score(y_validation, predictions)
Metrics = pd.DataFrame([precision, recall, support],
                       index=['precision', 'recall', 'support'])
Metrics.columns = y_validation.columns
Metrics

# Trying to show recall increases with sample size, but its hard to see all the small sample points because they are so clustered. Basically, recall for sample size less than 2000 is generally poor, so we will focus on those samples.

# In[20]:

#Plot recall by sample size
# to show sample size thresh where recall is ok

colors = cm.summer(np.linspace(0, 1, len(Metrics.ix['support'])))
plt.scatter(Metrics.ix['support'], Metrics.ix['recall'], c=colors, alpha=0.5)
plt.show()

# ## Diagnostics

# In[21]:

probs = rf.predict_proba(X_validation)

# ROC curves visualize performance of a class/binary classifier. Visualization of how predicted probabilities compare to the truth.

# In[22]:

from sklearn import metrics
コード例 #10
0
ファイル: game.py プロジェクト: gosha1128/NYU
    def __init__(self):

        self.TARGET_FPS = 30
        cam_w,cam_h=(640,480)
        timer_w=480
        self.resolution = (cam_w+timer_w,cam_h)
        pygame.init()
        pygame.mouse.set_visible(False)

        self.sounds = Sounds()

        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)
        #window = pygame.display.set_mode((w,h), FULLSCREEN)
        if options.startfullscreen:
            window = pygame.display.set_mode(self.resolution,pygame.FULLSCREEN) 
            self.fullscreen = 1
        else:
            window = pygame.display.set_mode(self.resolution) # do not start full
            self.fullscreen = 0
        
        # surface representing cam view
        self.camsurface = 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
        if options.boygirl:
            # we know there are only two teams
            self.teamcolors = [cm.hsv(0.61),cm.hsv(0.86)]
        else:
            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.objectcolors = [cm.summer(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()
        self.update_digit()
コード例 #11
0
            counter += 1.0

    p_ab = counter / len(d_['countries'])

    return p_ab


if __name__ == "__main__":

    colors = ['orange', 'blue', 'green', 'yellow', 'pink', 'magenta']
    colors_ = []
    TOP_X = 15
    YEAR = 1989

    for i in np.arange(TOP_X):
        c = cm.summer(i / float(TOP_X), 1)
        colors_.append(c)

    x = np.arange(TOP_X)

    db1 = sys.argv[1]
    db2 = sys.argv[2]

    df = pd.read_table(sys.argv[1],
                       delim_whitespace=True,
                       names=('doi', 'journal', 'year', 'country'),
                       comment='#',
                       header=None)
    dat_ = df[df['year'] > YEAR].groupby(
        ['country']).size().sort_values(ascending=False)
コード例 #12
0
c_p_fid = change_basis(c_ij_fid, metric, e_o)
c_p_dfn = change_basis(c_ij_dfn, metric, e_o)

#Plot power spectrum of K-L modes
if plot_stuff:
    plt.figure()
    ax = plt.gca()
    ax.imshow([[0., 1.], [0., 1.]],
              extent=[700, 1600, 140, 200],
              interpolation='bicubic',
              cmap=cm.summer,
              aspect='auto')
    plt.text(220, 160, '$p\\in[1,16]$', {'fontsize': 16})
    for i in np.arange(nbins):
        c = c_p_fid[:, i]
        col = cm.summer((i + 0.5) / nbins)
        plt.plot(larr, c, color=col, lw=2)
    plt.ylabel("$D_\\ell^p$", fontsize=16)
    plt.xlabel("$\\ell$", fontsize=16)
    plt.xlim([2, 2000])
    plt.ylim([0.5, 300])
    plt.loglog()
    plt.savefig('../Draft/Figs/d_p_wl.pdf', bbox_inches='tight')

#Tomography, 1 bin
msk1 = np.zeros(nbins)
msk1[:] = 1
f1 = ndens * msk1 / np.sqrt(np.sum((ndens * msk1)**2))
f_tm1 = f1[None, :, None] * np.ones([LMAX + 1, nbins, 1])
#Tomograpy, 2 bins
msk1 = np.zeros(nbins)
コード例 #13
0
S_Ba     = []


# SampleID = ["",ID,ID,ID,ID,ID]#,ID,ID]
#
# FileID   = ["C0_E0_0.csv","_E0_0.csv", "_E10_0.csv", "_E20_0.csv", "_E60_0.csv", "_E60B*_0.csv"]#, "_E60B*_0.csv","_E60B*_0.csv"]
# Names    = ["Control","O min Exp", "10 min Exp", "30 min Exp", "60 min Exp", "Ba"]# "Ba","Ba"]
# Times    = [S_control,S_0E ,S_5E ,S_10E ,S_20E ,S_30E]#, S_30E30L,S_Ba]

SampleID = ["",ID,ID,ID,ID]#,ID,ID,ID]

FileID   = ["MG_E0_0.csv","_E0_0.csv", "_E10_0.csv", "_E20_0.csv", "_E20W1_0.csv"]#, "_E60B*_0.csv"]#, "_E60B*_0.csv","_E60B*_0.csv"]
Names    = ["Control","O min Exp", "10 min Exp", "30 min Exp", "+ 1 week"]#, "Ba"]# "Ba","Ba"]
Times    = [S_control,S_0E ,S_5E ,S_10E ,S_20E]# ,S_30E]#, S_30E30L,S_Ba]

cols     = ['black', cm.summer(1/100), cm.summer(2/15), cm.summer(4/15), cm.summer(6/15), 'hotpink', 'hotpink','hotpink','xkcd:bubblegum pink']

mark=['s','s','v','v','v',"^","d","^",'d','d']

# <codecell>

# # Print all file names for each exp time
for iCurve,Curves in enumerate(Times):
    print(iCurve)

# Figure for all curves
fig,ax = plt.subplots(figsize=(10,10))

# To keep data from the control sample & the t=0
IatT_0, Icontrol = [],[]
コード例 #14
0
#cols     = ['black', cm.summer(1/100), cm.summer(2/15), cm.summer(4/15), cm.summer(6/15), cm.summer(8/15), cm.summer(12/15),'hotpink','xkcd:bubblegum pink']

# My Calcium Green Data files... still can't open this
FileID = [
    "C0*_0.csv", "Ca_E0_*.csv", "Ca_E10_*.csv", "Ca_E20_*.csv", "Ca_E60_*.csv",
    "Ca_E60B*.csv", "Ca_E60B*.csv", "Ca_E60B*.csv"
]
Names = [
    "Control", "O min Exp", "10 min Exp", "30 min Exp", "60 min Exp", "Ba",
    "Ba", "Ba"
]
Times = [S_control, S_0E, S_5E, S_10E, S_20E, S_30E, S_30E30L, S_Ba]

cols = [
    'black',
    cm.summer(1 / 100),
    cm.summer(2 / 15),
    cm.summer(4 / 15),
    cm.summer(6 / 15),
    cm.summer(8 / 15), 'hotpink', 'hotpink', 'xkcd:bubblegum pink'
]

mark = ['s', 's', 'v', 'v', 'v', 'v', "d", "^", 'd', 'd']

# <codecell>

# # Print all file names for each exp time
for iCurve, Curves in enumerate(Times):
    print(iCurve)

# Figure for all curves
コード例 #15
0
from matplotlib.patheffects import withStroke
from matplotlib import cm, colorbar
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np
from matplotlib import ticker

from matplotlib import rc
rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})
rc('text', usetex=True)
plt.rcParams['text.usetex'] = True
matplotlib.rcParams.update({'font.size': 26})
fig = figure(num=None, figsize=(20, 6.45), dpi=80)
gs = gridspec.GridSpec(1, 2, width_ratios=[1, 1])
ax2 = plt.subplot(gs[0])
colors = cm.summer(np.linspace(0, 1, 75))

fs = 26


def main():

    data = []
    datafinal = []

    for i in range(101):
        data.append([])

    for i in range(100):
        datafinal.append([])
コード例 #16
0
ファイル: combo.py プロジェクト: gosha1128/NYU
    def __init__(self):

        self.TARGET_FPS = 30
        cam_w,cam_h=(640,480)
        timer_w=480
        # self.resolution = (cam_w+timer_w,cam_h)
        
        pygame.init()
        pygame.mouse.set_visible(False)

        # get resolution
        # OVERRIDE - THIS IS SUDDENLY SUPER BUGGY ON MY MACHINE (BUT NOT IAN'S)???
        # self.fullresolution = (int(pygame.display.Info().current_w), int(pygame.display.Info().current_h))
        # self.smallresolution = (int(pygame.display.Info().current_w*2/3), int(pygame.display.Info().current_h*2/3))
        self.fullresolution = (1024,768)
        self.smallresolution = (int(self.fullresolution[0]*2.0/3),int(self.fullresolution[1]*2.0/3))


        #window = pygame.display.set_mode((w,h), DOUBLEBUF)
        #window = pygame.display.set_mode((w,h), FULLSCREEN)
        if options.startfullscreen:
            self.resolution = self.fullresolution
            window = pygame.display.set_mode(self.resolution,pygame.FULLSCREEN) 
            self.fullscreen = 1

        else:
            self.resolution = self.smallresolution
            window = pygame.display.set_mode(self.resolution) # do not start full
            self.fullscreen = 0

        print self.fullresolution    
        print self.resolution

        self.sounds = Sounds()

        #ISPIRO: Load goal image. Pygame handles png transparency gracefully
        self.ball = pygame.image.load("img/gray.png")
        self.ball_w = self.ball.get_width()
        self.ball_h = self.ball.get_height()

        self.brush = pygame.image.load("img/small.png")
        self.brush_w = self.brush.get_width()
        self.brush_h = self.brush.get_height()

        self.vortex = pygame.image.load("img/vortex.png");
        self.vortex_w = self.vortex.get_width()
        self.vortex_h = self.vortex.get_height()
        
        self.sum_surface = pygame.Surface((10,10))

        self.font = pygame.font.SysFont(None,80)

        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"

        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()

        if options.objects is None:
            print "Automatic object detection mode"
            while options.objects is None:
                print "Looking for objects..."
                options.objects = self.lookfor_objects()
                # Handle events
                self.handle_events()
        else:
            print "Objects are defined on command line"

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

        self.set_surfaces()

        # ISPIRO: Need a mask image for blitting circles
        # original mask to match camera
        self.mask = pygame.Surface((options.camerawidth,options.cameraheight))
        # resized mask
        self.bigmask = pygame.Surface((self.camsurface_w,self.camsurface_h))
        
        self.cameras = []
        for c in options.cameras:
            self.cameras.append(Camera(c,img_size = (options.camerawidth,options.cameraheight),fps=self.TARGET_FPS,mirrored=options.mirrored))

        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
        if options.boygirl:
            # we know there are only two teams
            self.teamcolors = [cm.hsv(0.61),cm.hsv(0.86)]
        else:
            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.objectcolors = [cm.summer(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()
コード例 #17
0
            self.inhabitants.append(new)  # accepting a single planet
            new.world=self

    def draw_inhabitants(self):
        for thing in self.inhabitants:
            thing.show_up()
    
    def one_step(self):
        stop = False
        self.events = pg.event.get()
        for event in self.events:
            if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
                stop = True
        for thing in self.inhabitants:
            thing.one_step()
        self.canvas.fill(self.BG_colour)
        self.draw_inhabitants()
        pg.display.flip()
        return stop
    
w = World()

for i in xrange(10):
    dot = Amoeb(2*rand(2)-1,0.2*rand())
    dot.color = color_mpl2pg(cm.summer(rand()))  # find other colormaps here: http://matplotlib.org/examples/color/colormaps_reference.html
    w.add_inhabitants(dot)

stop_flag = False
while not stop_flag:
    stop_flag = w.one_step()
コード例 #18
0
def visualize_distance(solution_object, output_file_name,
                       max_number_of_solutions, is_descending, is_enabled_create_mst):
    '''
    Visualize Manhattan distance for each solutions pair as a heatmap.
    '''
    # Summary
    name = solution_object['name']
    number_of_variables = solution_object['number_of_variables']
    number_of_constraints = solution_object['number_of_constraints']

    # Sort solutions.
    solutions = solution_object['solutions']
    if is_descending:
        solutions.sort(key=lambda x: -x['objective'])
    else:
        solutions.sort(key=lambda x: x['objective'])

    number_of_solutions = len(solutions)

    # Compute Manhattan distance for each solutions pair.
    distances = np.zeros(
        (number_of_solutions, number_of_solutions))

    for i in range(number_of_solutions):
        for j in range(i+1, number_of_solutions):
            distance = compute_distance(
                solutions[i]['variables'],
                solutions[j]['variables'])
            distances[i, j] = distance
            distances[j, i] = distance

    # Plot the Manhattan distances as a heatmap.
    title = 'Manhattan distance between 2 solutions \n (Instance: %s, #Var.: %d, #Cons.: %d)' \
        % (name, number_of_variables, number_of_constraints)
    if is_descending:
        footnote_text = '* The solutions are sorted in descending order of objective function value.'
    else:
        footnote_text = '* The solutions are sorted in ascending order of objective function value.'

    plt.title(title)
    plt.imshow(distances)
    plt.xlabel('Solution No.')
    plt.ylabel('Solution No.')
    plt.text(-0.1 * number_of_solutions,
             1.19 * number_of_solutions,
             footnote_text)

    plt.grid(False)
    plt.colorbar()
    plt.subplots_adjust(bottom=0.15)
    plt.savefig(output_file_name)

    # Create the minimum spanning tree (Optional)
    if is_enabled_create_mst:
        graph = nx.Graph()
        label = 'Solution network: The minimum spanning tree of a complete graph where nodes denote solutions. \\n' \
            + 'An edge connecting 2 nodes is weighted by Manhattan distance between the solutions. \\n' \
            + '(Instance: %s, #Var.: %d, #Cons.: %d)' \
            % (name, number_of_variables, number_of_constraints)
        graph.graph['graph'] = {
            'label': label,
            'labelloc': 't'}
        edges = []
        for i in range(number_of_solutions):
            for j in range(i+1, number_of_solutions):
                edges.append((i, j, distances[i, j]))

        graph.add_weighted_edges_from(edges)
        mst = nx.minimum_spanning_tree(graph)

        objectives = [solution['objective'] for solution in solutions]
        min_objective = np.min(objectives)
        max_objective = np.max(objectives)

        for i in range(number_of_solutions):
            color = cm.summer(
                np.sqrt(objectives[i] - min_objective) / np.sqrt(max_objective - min_objective))
            red = int(np.floor(color[0] * 255))
            green = int(np.floor(color[1] * 255))
            blue = int(np.floor(color[2] * 255))
            alpha = 127
            fillcolor = '#' + format(red, '02x') + format(green, '02x') + \
                format(blue, '02x') + format(alpha, '02x')

            mst.nodes[i]['label'] = objectives[i]
            mst.nodes[i]['penwidth'] = 0.1
            mst.nodes[i]['fillcolor'] = fillcolor
            mst.nodes[i]['style'] = 'filled, rounded'

        for (i, j) in mst.edges:
            mst.edges[i, j]['penwidth'] = 0.3

        nx.drawing.nx_agraph.write_dot(mst, 'distance.dot')
コード例 #19
0
ファイル: rss.py プロジェクト: MunskyGroup/rSNAPsim
    def kymograph(self,ssa_obj,n_traj,bg_intense=True,show_intense = True,tag = 0, show_col=True,col_size = 1.5, custom_fig = None, facecolor='black', *args,**kwargs):
        '''
        Constructs a kymograph of ribosome locations
        '''
        startfrags = 0
        for i in range(n_traj):
            startfrags += ssa_obj.frag_per_traj[i]
            
        endfrags = startfrags + ssa_obj.frag_per_traj[n_traj]
        fragments = ssa_obj.fragments[startfrags:endfrags]

        

        time = ssa_obj.time#[0:len(ssa_obj.time_rec)-1]
        

        
        
        
        
        if len(ssa_obj.intensity_vec.shape) ==3:
            ivec = ssa_obj.intensity_vec[tag][n_traj]
        else:        
            ivec = ssa_obj.intensity_vec[n_traj]
        ftimes = ssa_obj.fragtimes[startfrags:startfrags+endfrags]


        nfrag = fragments.shape[0]
        maxlen= fragments.shape[1]

        
        #plt.figure(figsize=(5,10))
        if show_intense == True:
            gs = gridspec.GridSpec(1, 2, custom_fig, width_ratios=[3, 1]) 
        else:
            gs = gridspec.GridSpec(1, 1)
        
        plt.subplot(gs[0])
        lenplot = np.max(fragments)
        maxin = np.max(ivec)
        ax = plt.gca()
        ax.set_facecolor(facecolor)

        if bg_intense == True:
            for i in range(len(time)):
                plt.plot([0,lenplot],[time[i],time[i]],color = cm.summer(1.*ivec[i]/maxin),lw=1)
            
        for i in range(nfrag):
            
            
            
            if maxlen <= np.where(fragments[i] > 0 )[0][-1]:       
                timeseg = time[ftimes[i]:ftimes[i]+maxlen]
                
                plt.plot(fragments[i][0:len(timeseg)] ,timeseg[::-1] )
                
            else:
                timeseg = time[ftimes[i]:]
                
                stop = np.where(fragments[i] > 0 )[0][-1]
                timelen = len(fragments[i][0:stop]) 

                plt.plot(fragments[i][0:stop]   ,timeseg[0:timelen],**kwargs )

        plt.xlabel('Ribosome position')
        plt.ylabel('Time (sec)')
        segtime = ssa_obj.time[0:len(ssa_obj.time_rec)]
        plt.ylim(ssa_obj.time_rec[-1], ssa_obj.time_rec[0])
                
        if show_col == True:
            try:
                col = ssa_obj.col_points[n_traj]

                plt.plot(col[:,0],col[:,1],color='#00ff00',markersize=col_size,linestyle='none',marker='o')
            except:
                pass

        if show_intense == True:
            plt.subplot(gs[1])
            ax = plt.gca()
            ax.set_facecolor(facecolor)
 
            plt.plot(ivec.T/ np.sum(ssa_obj.probe),segtime,**kwargs)
            plt.xlabel('Intensity (ump)')
            plt.xlim(0,30)
            plt.ylim(segtime[-1], segtime[0])
            
        
            
            plt.tight_layout()
コード例 #20
0
ファイル: hist_stab.py プロジェクト: TensorDuck/project_tools
def plot_energy_density_map(protein, iteration_number ,current_dir, select_path):

    colors = [('white')] + [(cm.jet(i)) for i in xrange(1,256)]
    new_map = mpl.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)

    colors_low = [('white')] + [(cm.winter(i)) for i in xrange(1,256)]
    low_map = mpl.colors.LinearSegmentedColormap.from_list('low_map', colors_low, N=256)

    colors_high = [('white')] + [(cm.summer(i)) for i in xrange(1,256)]
    high_map = mpl.colors.LinearSegmentedColormap.from_list('high_map', colors_high, N=256)
  
    print "  Loading BeadBead.dat"
    beadbead = np.loadtxt(select_path+"BeadBead.dat",dtype=str)
    sigij = beadbead[:,5].astype(float)
    epsij = beadbead[:,6].astype(float)
    deltaij = beadbead[:,7].astype(float)
    interaction_numbers = beadbead[:,4].astype(str)
    pairs = beadbead[:,:2].astype(int)
    pairs -= np.ones(pairs.shape,int)
    native = beadbead[:,4].astype(int)

    pairs = pairs[ native != 0 ]
    epsij = epsij[ native != 0 ]
    pairs_low = pairs[ epsij<1. ]
    epsij_low = epsij[ epsij<1. ]
    pairs_high = pairs[ epsij>=1. ]
    epsij_high = epsij[ epsij>=1. ]
    
    Qref = np.loadtxt(current_dir+'/'+protein+"/Qref_cryst.dat")
    C = np.zeros(Qref.shape,float)
    C_low = np.zeros(Qref.shape,float)
    C_high = np.zeros(Qref.shape,float)

    print len(pairs_low), len(pairs_high)

    for k in range(len(pairs)):
        C[pairs[k][0],pairs[k][1]] = epsij[k]

    # C_low                                                                                                                      
    for k in range(len(pairs_low)):
        C_low[pairs_low[k][0],pairs_low[k][1]] = epsij_low[k]

    # C_high
    for k in range(len(pairs_high)):
        C_high[pairs_high[k][0],pairs_high[k][1]] = epsij_high[k]

    print "  Plotting..."
    plt.figure()
    plt.subplot(1,1,1,aspect=1)
    ax = plt.subplot(1,1,1,aspect=1)
    plt.pcolor(C,cmap=new_map, vmin=0, vmax=3)
    plt.xlim(0,len(Qref))
    plt.ylim(0,len(Qref))               
    ax = plt.gca()
    cbar = plt.colorbar()
#    cbar.set_clim(0,4)
    cbar.set_label("Contact energy density map",fontsize=20)
    cbar.ax.tick_params(labelsize=20)
    plt.xlabel("Residue i",fontsize=20)
    plt.ylabel("Residue j",fontsize=20)
    plt.title('Contact energy density map for '+protein+', iteration '+iteration_number)
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(15)
    print "  Saving..."
    plt.savefig(current_dir+'/metrics/stability/'+protein+"_contact_energy_density_map.pdf")
    plt.clf()

    print "  Plotting..."
    plt.figure()
    plt.subplot(1,1,1,aspect=1)
    ax = plt.subplot(1,1,1,aspect=1)
    plt.pcolor(C_low,cmap=low_map)
    plt.xlim(0,len(Qref))
    plt.ylim(0,len(Qref))
    ax = plt.gca()
    cbar = plt.colorbar()
    #    cbar.set_clim(0,4)                                                                                                           
    cbar.set_label("Contact energy density map",fontsize=20)
    cbar.ax.tick_params(labelsize=20)
    plt.xlabel("Residue i",fontsize=20)
    plt.ylabel("Residue j",fontsize=20)
    plt.title('Contact energy density map for '+protein+', iteration '+iteration_number+', eps<1')
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(15)
    print "  Saving..."
    plt.savefig(current_dir+'/metrics/stability/'+protein+"_low_contact_energy_density_map.pdf")
    plt.clf()
    
    print "  Plotting..."
    plt.figure()
    plt.subplot(1,1,1,aspect=1)
    ax = plt.subplot(1,1,1,aspect=1)
    plt.pcolor(C_high,cmap=high_map, vmin=1, vmax=3)
    plt.xlim(0,len(Qref))
    plt.ylim(0,len(Qref))
    ax = plt.gca()
    cbar = plt.colorbar()
    cbar.set_label("Contact energy density map",fontsize=20)
    cbar.ax.tick_params(labelsize=20)
    plt.xlabel("Residue i",fontsize=20)
    plt.ylabel("Residue j",fontsize=20)
    plt.title('Contact energy density map for '+protein+', iteration '+iteration_number+', eps>=1')
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(15)
    print "  Saving..."
    plt.savefig(current_dir+'/metrics/stability/'+protein+"_high_contact_energy_density_map.pdf")
    plt.clf()
コード例 #21
0
import numpy as np  # pylint:   disable=E1101

import tables
import matplotlib.pyplot as mpl
import matplotlib.cm as cm

from combinato import SortingManagerGrouped, get_regions, artifact_id_to_name

print(artifact_id_to_name)

FIGSIZE = (7, 6)

REGIONS = ('A', 'AH', 'MH', 'PH', 'EC', 'PHC', 'I')

LEFT_COLORS = cm.spectral(np.linspace(0, 1, len(REGIONS)))
RIGHT_COLORS = cm.summer(np.linspace(0, 1, len(REGIONS)))
NUM_COLORS = cm.winter(np.linspace(0, 1, 8))

COLORDICT = {}

for i, region in enumerate(REGIONS):
    COLORDICT['L' + region] = LEFT_COLORS[i]
    COLORDICT['R' + region] = RIGHT_COLORS[i]

for i in range(1, 9):
    COLORDICT[str(i)] = NUM_COLORS[i - 1]
JOBS = ('thr', 'arti')


def plotthr(thrplot, fireplot, thr, times, color='r'):
    """
コード例 #22
0
import tables
import matplotlib.pyplot as mpl
import matplotlib.cm as cm

from combinato import SortingManagerGrouped, get_regions, artifact_id_to_name

print(artifact_id_to_name)


FIGSIZE = (7, 6)

REGIONS = ("A", "AH", "MH", "PH", "EC", "PHC", "I")

LEFT_COLORS = cm.spectral(np.linspace(0, 1, len(REGIONS)))
RIGHT_COLORS = cm.summer(np.linspace(0, 1, len(REGIONS)))
NUM_COLORS = cm.winter(np.linspace(0, 1, 8))

COLORDICT = {}

for i, region in enumerate(REGIONS):
    COLORDICT["L" + region] = LEFT_COLORS[i]
    COLORDICT["R" + region] = RIGHT_COLORS[i]

for i in range(1, 9):
    COLORDICT[str(i)] = NUM_COLORS[i - 1]
JOBS = ("thr", "arti")


def plotthr(thrplot, fireplot, thr, times, color="r"):
    """