Ejemplo n.º 1
0
    def draw_neurons(self):
        if self.xs != self.xs_buffer:
            if self.xs.ndim == 1:
                self.xs = self.xs[np.newaxis, :]
            elif self.xs.shape[0] != 1:
                raise ValueError('Input data must only contain one sample')

            if self._network.reg == 'dropout':
                feed_dict = {self._network.data_placeholder: self.xs,
                             self._network.keep_prob_placeholder: self.keep_prob}
            elif self._network.reg == 'l2':
                feed_dict = {self._network.data_placeholder: self.xs,
                             self._network.l2_placeholder: self.l2_lambda}
            else:
                feed_dict = {self._network.data_placeholder: self.xs}

            layers_final_output = self._network.sess.run(
                self.network.layers_final_output, feed_dict)

            i = 0
            for neuron in range(self._network.n_inputs):
                self.neurons_vertex_list[i].colors = cm.cool(neuron[0]) * 4
                i += 1
            for layer in layers_final_output:
                for neuron in layer:
                    self.neurons_vertex_list[i].colors = cm.cool(neuron[0]) * 4
                    i += 1
            self.xs_buffer = self.xs
        else:
            pass
Ejemplo n.º 2
0
    def draw_neurons(self):
        if self.xs != self.xs_buffer:
            if self.xs.ndim == 1:
                self.xs = self.xs[np.newaxis, :]
            elif self.xs.shape[0] != 1:
                raise ValueError('Input data must only contain one sample')

            if self._network.reg == 'dropout':
                feed_dict = {
                    self._network.data_placeholder: self.xs,
                    self._network.keep_prob_placeholder: self.keep_prob
                }
            elif self._network.reg == 'l2':
                feed_dict = {
                    self._network.data_placeholder: self.xs,
                    self._network.l2_placeholder: self.l2_lambda
                }
            else:
                feed_dict = {self._network.data_placeholder: self.xs}

            layers_final_output = self._network.sess.run(
                self.network.layers_final_output, feed_dict)

            i = 0
            for neuron in range(self._network.n_inputs):
                self.neurons_vertex_list[i].colors = cm.cool(neuron[0]) * 4
                i += 1
            for layer in layers_final_output:
                for neuron in layer:
                    self.neurons_vertex_list[i].colors = cm.cool(neuron[0]) * 4
                    i += 1
            self.xs_buffer = self.xs
        else:
            pass
Ejemplo n.º 3
0
 def __init__(self,position,radius):
     self.x=asfarray(position)
     self.v=zeros(2,dtype=float)
     self.f=zeros(2,dtype=float)
     self.m=1.
     self.dt=0.03
     self.damp=0.999
     self.r=0.05 # scaling factor for random walk
     self.direc=2*pi*rand() # wants to move in that direction
     self.radius=radius
     self.color=color_mpl2pg(cm.cool(0.5*rand()))
     self.color2=color_mpl2pg(cm.cool(0.8+0.2*rand()))
     self.world=None
Ejemplo n.º 4
0
def plot_timeVfreq(date_operator, collection):
    if collection == "drop":
        field = "pickup_time"
    elif collection == "pickup":
        field = "drop_time"
    else:
        raise Exception(
            "Error: the collection arguments to timeVfreq are 'drop', or 'pickup'. Not",
            collection)
    graph_size = {"hour": (0, 23), "dayOfYear": (1, 366), "dayOfWeek": (1, 8)}
    if date_operator not in graph_size.keys():
        raise Exception(
            "Error: the date_operator argument to timeVfreq must be 'hour', 'dayOfWeek', or 'dayOfYear'. Not",
            date_operator)

    tvf = get_timeVfreq(date_operator, collection, field)

    min_freq = ndarray.min(tvf[1])
    max_freq = ndarray.max(tvf[1])

    fig = pyplot.figure(1, figsize=(7, 6))
    myplot = fig.add_subplot(111)
    myplot.set_xlim(graph_size[date_operator])

    norm = colors.Normalize(min_freq, max_freq)

    for i in range(len(tvf[0])):
        color = colors.rgb2hex(cm.cool(norm(tvf[1][i])))
        pyplot.bar(tvf[0][i], tvf[1][i], color=color, ec=color, align='edge')

    pyplot.xlabel(date_operator)
    pyplot.ylabel("# of rides")
    pyplot.savefig(date_operator + "_" + collection, dpi=180)
Ejemplo n.º 5
0
def animate_bloch(states, duration=0.1, save_all=False):

    b = Bloch()
    b.vector_color = ['r']
    b.view = [-40, 30]
    images = []
    try:
        length = len(states)
    except:
        length = 1
        states = [states]
    ## normalize colors to the length of data ##
    nrm = mpl.colors.Normalize(0, length)
    colors = cm.cool(nrm(
        range(length)))  # options: cool, summer, winter, autumn etc.

    ## customize sphere properties ##
    b.point_color = list(colors)  # options: 'r', 'g', 'b' etc.
    b.point_marker = ['o']
    b.point_size = [30]

    for i in tqdm(range(length)):
        b.clear()
        b.add_states(states[i])
        b.add_states(states[:(i + 1)], 'point')
        if save_all:
            b.save(dirc='tmp')  #saving images to tmp directory
            filename = "tmp/bloch_%01d.png" % i
        else:
            filename = 'temp_file.png'
            b.save(filename)
        images.append(imageio.imread(filename))
    imageio.mimsave('bloch_anim.gif', images, duration=duration)
Ejemplo n.º 6
0
def annotate_linked_features(V, feats, i):
    """ using the linked features dataframe feats, return an annotated image
    from float 0-1 single channel pims video V. 
    * feats is a dataframe containing 'x','y','particle','frame'."""
    import skimage as ski
    from skimage import draw
    import matplotlib.cm as cm
    # define colors, get frame and features
    colors = (cm.cool(np.linspace(0.0, 1.0, 10))[:, :3] * 255).astype('uint8')
    ifeats = feats[feats['frame'] == i]
    im = V[i]
    im = (255 * np.stack((im, ) * 3, -1)).astype('uint8')
    # draw on the frame
    words = wordmask('time {} s'.format(round(i / 190.0, 3)), (20, 20),
                     40)  #generate mask of the frame number
    im[words] = [0, 0, 240]

    # draw all features on the frame with circles..
    for _, vals in ifeats.iterrows():
        y = int(round(vals['x']))
        x = int(round(vals['y']))
        color = colors[int(vals['particle'] % 10)]
        p = vals['particle']
        row, col = ski.draw.circle_perimeter(x, y, 9, shape=(720, 1680))
        im[row, col] = color
        row, col = ski.draw.circle_perimeter(x, y, 10, shape=(720, 1680))
        im[row, col] = color
        row, col = ski.draw.circle_perimeter(x, y, 11, shape=(720, 1680))
        im[row, col] = color
        #also add the feature number of each object
        words = wordmask(str(int(p)), (y + 5, x + 5), size=30)
        im[words] = color
    return im
Ejemplo n.º 7
0
def pmf_t(temp):
    lam = [.1,.15,.2,.25,.3,.35,.4,.45,.5,.55]
    colors = cm.cool(numpy.linspace(0,1,len(lam)))
    plt.figure(8)
    plt.rc('text',usetex=True)
    direc = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface'
    for i,l in enumerate(lam):
        f = open('%s/lambda%s/pmf_%i.pkl' %(direc,str(l)[1::],int(temp)),'rb')
        temp = cPickle.load(f)
        bin_centers = cPickle.load(f)
        f_i = cPickle.load(f)
        df_i = cPickle.load(f)
        f.close()
        idx = numpy.argmin(f_i[int(.7*len(f_i))::]) + int(.7*len(f_i))
        f_i -= f_i[idx]
        plt.errorbar(bin_centers[1::],f_i[1::],numpy.array(df_i[0,:])[0,1::],label=r'$\lambda$ = %s' % l, color=colors[i])
    
    f = open('/home/edz3fz/proteinmontecarlo/results/1PGB/solution/pmf_%i.pkl' %(int(temp)),'rb')
    temp = cPickle.load(f)
    bin_centers = cPickle.load(f)
    f_i = cPickle.load(f)
    df_i = cPickle.load(f)
    f.close()
    idx = numpy.argmin(f_i[int(.7*len(f_i))::]) + int(.7*len(f_i))
    f_i -= f_i[idx]
    plt.errorbar(bin_centers[1::],f_i[1::],numpy.array(df_i[0,:])[0,1::],label='solution', color='k')
    
    plt.xlabel('Q')
    plt.ylabel('PMF (kcal/mol)')
    plt.title('T = %s K' % temp)
    plt.legend(loc=0, prop={'size':8})
Ejemplo n.º 8
0
def plot_timeVfreq(date_operator, collection):
    if collection == "drop":
         field = "pickup_time"
    elif collection == "pickup":
         field = "drop_time"
    else:
         raise Exception("Error: the collection arguments to timeVfreq are 'drop', or 'pickup'. Not", collection)
    graph_size = {"hour":(0, 23), "dayOfYear":(1,366), "dayOfWeek":(1,8)}
    if date_operator not in graph_size.keys():
        raise Exception("Error: the date_operator argument to timeVfreq must be 'hour', 'dayOfWeek', or 'dayOfYear'. Not", date_operator)

    tvf = get_timeVfreq(date_operator, collection, field)

    min_freq = ndarray.min(tvf[1])
    max_freq = ndarray.max(tvf[1])

    fig = pyplot.figure(1, figsize=(7, 6))
    myplot = fig.add_subplot(111)
    myplot.set_xlim(graph_size[date_operator])

    norm = colors.Normalize(min_freq, max_freq)

    for i in range(len(tvf[0])):
        color = colors.rgb2hex(cm.cool(norm(tvf[1][i])))
        pyplot.bar(tvf[0][i], tvf[1][i], color=color, ec=color, align='edge')

    pyplot.xlabel(date_operator)
    pyplot.ylabel("# of rides")
    pyplot.savefig(date_operator + "_" + collection, dpi=180)
Ejemplo n.º 9
0
    def main_draw(self, ck, cks, alphas, points_F, points_coupe, F_label):
        axe = self.fig.add_subplot(111, projection="3d")

        axe.plot_surface(*points_F, alpha=0.4, color="gray")
        alphas = alphas / alphas.max()
        colors = cm.cool(alphas)
        axe.scatter(ck[:, 0], ck[:, 1], cks, c=colors, s=15)

        x, y, z = points_coupe
        axe.plot(x,
                 y,
                 z * np.ones(x.shape),
                 color="green",
                 alpha=1,
                 label="$F(x) = y_{obs}$")

        fake2Dline = matplotlib.lines.Line2D([0], [0],
                                             linestyle="none",
                                             c='gray',
                                             marker='s',
                                             alpha=0.4)
        gray_patch = matplotlib.patches.Patch(color="gray", alpha=0.4)

        fake2Dline2 = matplotlib.lines.Line2D([0], [0],
                                              linestyle="none",
                                              c='cyan',
                                              marker='o')
        axe.azim, axe.elev = 83, 21  # setup view for example
        handle, label = axe.get_legend_handles_labels()
        axe.legend([gray_patch, handle[0], fake2Dline2],
                   [f"$F$ : {F_label}", label[0], "$c_{k}^{*}$"],
                   bbox_to_anchor=[0.6, 0.15, 0.2, 0.3])
        pyplot.show()
Ejemplo n.º 10
0
def conv1(model):
    n1, n2, x, y, z = model.conv1.W.shape
    fig = plt.figure()
    for nn in range(0, n1):
        ax = fig.add_subplot(4, 5, nn + 1, projection='3d')
        ax.set_xlim(0.0, x)
        ax.set_ylim(0.0, y)
        ax.set_zlim(0.0, z)
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_zticklabels([])
        for xx in range(0, x):
            for yy in range(0, y):
                for zz in range(0, z):
                    max = np.max(model.conv1.W.data[nn, :])
                    min = np.min(model.conv1.W.data[nn, :])
                    step = (max - min) / 1.0
                    C = (model.conv1.W.data[nn, 0, xx, yy, zz] - min) / step
                    color = cm.cool(C)
                    C = abs(1.0 - C)
                    ax.plot(np.array([xx]),
                            np.array([yy]),
                            np.array([zz]),
                            "o",
                            color=color,
                            ms=7.0 * C,
                            mew=0.1)

    plt.savefig("result/graph_conv1.png")
Ejemplo n.º 11
0
    def __init__(self, I1, I2, positive=None, negative=None, **kwargs):
        """A visualizer for labelling positive and negative regions

        Args:
            I1, I2: The images to label

        Keyword Args:
            positive: The initial set of positive correspondences
            negative: The initial set of background examples
        """
        super(PNLabeller, self).__init__(I1, I2, **kwargs)
        self.positive = []
        self.negative = []
        self.mode = 'P'

        # initialize the colormaps
        self.pmap = cycle([cm.cool(i) for i in range(0, cm.cool.N, 16)])
        self.nmap = cycle([cm.autumn(i) for i in range(0, cm.autumn.N, 16)])
        self.cmap = self.pmap
        self.color = self.pmap.next()

        # redraw the initial set
        if positive is not None:
            for left, right in positive:
                left, right = tuple(left), tuple(right)
                self.positive.append((left, right))
                self.plot(left, right)

        if negative is not None:
            for left, self.color in zip(negative, self.nmap):
                left = tuple(left)
                self.negative.append(left)
                self.plot(left)
Ejemplo n.º 12
0
def main():
    lam = [.1, .2, .3, .35, .4, .45, .5, .6, .7]
    lam = [.1, .2, .3, .4, .5, .675, .7]
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5]  #, .55, .6, .65, .7]
    files = [
        '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/foldingcurve_umbrella.npy'
        % str(x)[1::] for x in lam
    ]
    colors = cm.cool(numpy.linspace(0, 1, len(lam)))

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

    for i in range(len(lam)):
        data = numpy.load(files[i])
        x = 17
        plt.errorbar(data[0, -x::],
                     data[1, -x::],
                     data[2, -x::],
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/foldingcurve.npy'
    data = numpy.load(soln)
    plt.errorbar(data[0, :],
                 data[1, :],
                 data[2, :],
                 label='solution',
                 color='k')
    plt.xlabel('temperature (K)')
    plt.ylabel('Q')
    plt.legend(prop={'size': 8})
    plt.show()
Ejemplo n.º 13
0
def col_size(var,var_min=1.1):
    import matplotlib.cm as cm
    # Limit values in case they are not yet limited
    var = np.clip(var, var_min, None)
    color = cm.cool(np.log10(var)/np.max(np.log10(var)))
    size   = 100*np.log10(var)**2

    return color, size
Ejemplo n.º 14
0
	def scan(self,
			 propertyName,
			 minVal,
			 maxVal,
			 resolution,
			 function,
			 *args):

		vprint("Scanning %s by %s..." % (self.fileName, propertyName))
		#check that scanning range is valid and update if otherwise
		minVal, maxVal = scanAxesClampHelper(self, propertyName, minVal, maxVal)

		#Instantiate workbook for writing data from this function
		workBookName = "%s %s scan of %s vs %s by %s.xlsx" % (TCG.SAVE_DIRECTORY, self.fileName, args[0], args[1], propertyName)
		workbook = xlsxwriter.Workbook(workBookName, {'nan_inf_to_errors': True, 'in_memory': True})

		bins = np.linspace(minVal, maxVal, resolution+1)
		settings = args[2]
		title = "%s, %s vs %s scanned by %s" % (self.fileName , args[0], args[1], propertyName)
		legendStrings = []
		colorIndices = np.linspace(0, 1, resolution)
		fig = constructFig(self, title)
		
		writeData(self, workbook, "binData")

		keepOpen = True #flag for whether to close the excel workbook on the next write
		for index, colorIdx in zip (range(0, len(bins)-1), colorIndices):

			#get filter instance range
			lowerVal = bins[index]
			upperVal = bins[index+1]

			
			#copy data
			filtersCopy = {}
			filtersCopy[propertyName] = [[lowerVal, upperVal]]
			trackFileCopy = deepcopy(self)
			trackFileCopy.selectData(filtersCopy)

			#turn off settings new fig
			settings["show"] = False
			settings["newFig"] = False
			settings["save"] = False

			#get plot instance legend name
			legendString = "%.1f to %.1f" % (lowerVal, upperVal)
			legendStrings.append(legendString)

			if (index == len(bins)-1):
				keepOpen = False
			
			#plot
			P = function(trackFileCopy, *args, color = cm.cool(colorIdx), workbook = [workbook, legendString, keepOpen])
			P.legend(legendStrings, title=(self.fields[propertyName]).axisLabel, loc = settings['legendLoc'], prop = {'size': 9})

		savePlot(fig, title)
		P.close()
    def __init__(self, states, duration=0.1, save_all=False):
        # Defining a Bloch
        b = Bloch()
        b.vector_color = ['r']
        b.view = [-40, 30]
        images = []
        try:
            length = len(states)
        except:
            length = 1
            states = [states]

        # Normalise Colours
        norm = mpl.colors.Normalize(0, length)
        colors = cm.cool(norm(range(length)))  # cool, summer, winter, autumn

        # Sphere Properties
        b.point_color = list(colors)
        b.point_marker = ['x']
        b.point_size = [30]

        # Defining save destination
        dir = './blochsphere_images/'
        for i in range(length):
            b.clear()
            b.add_states(states[i])
            b.add_states(states[:(i + 1)], 'point')
            if save_all:
                b.save(dirc=dir)
                filename = "temp/bloch_{i}01d.png".format(i=i)
            else:
                filename = "temp_file.png"
                b.save(dir + filename)
            images.append(imageio.imread(dir + filename))
        imageio.mimsave(dir + 'gif/' + 'bloch_anim.gif',
                        images,
                        duration=duration)
        im = Image.open(dir + 'gif/' + 'bloch_anim.gif')

        animation = pyglet.image.load_animation(dir + 'gif/' +
                                                'bloch_anim.gif')
        sprite = pyglet.sprite.Sprite(animation)

        w = sprite.width
        h = sprite.height
        window = pyglet.window.Window(width=w, height=h)
        r, g, b, alpha = 0.5, 0.5, 0.8, 0.5
        pyglet.gl.glClearColor(r, g, b, alpha)

        @window.event
        def on_draw():
            window.clear()
            sprite.draw()

        pyglet.app.run()
Ejemplo n.º 16
0
def clustering(text_list):
    k = 4

    # see https://qiita.com/yuuki_1204_/items/3c0a298a521dc6e79615
    # TF-IDFの処理クラス
    vectorizer = TfidfVectorizer(min_df=1,
                                 stop_words=STOP_WORDS,
                                 tokenizer=mecab_analysis)
    # データのベクトル化
    tfidf_weighted_matrix = vectorizer.fit_transform(text_list)

    # k-means
    model = KMeans(n_clusters=k)
    model.fit(tfidf_weighted_matrix)
    # 2次元に圧縮 潜在意味解析(LSA)
    dim = TruncatedSVD(2)
    compressed_text_list = dim.fit_transform(tfidf_weighted_matrix)
    compressed_center_list = dim.fit_transform(model.cluster_centers_)

    # 描画
    FP = fm.FontProperties(fname=FONT, size=7)
    fig = plt.figure()
    axes = fig.add_subplot(111)
    # 3クラスタ
    for label in range(k):
        # ラベルごとに色を分ける
        color = cm.cool(float(label) / k)

        # ラベルの中心をプロット
        xc, yc = compressed_center_list[label]
        axes.plot(xc, yc, color=color, ms=6.0, zorder=3, marker='o')

        # クラスタのラベルもプロット
        axes.annotate(label, xy=(xc, yc), fontproperties=FP)

        for text_num, text_label in enumerate(model.labels_):
            if text_label == label:
                # labelが一致するテキストをプロット
                x, y = compressed_text_list[text_num]
                axes.plot(x, y, color=color, ms=5.0, zorder=2, marker="x")

                # テキストもプロット
                axes.annotate(text_list[text_num][:8],
                              xy=(x, y),
                              fontproperties=FP)

                # ラベルの中心点からの線をプロット
                axes.plot([x, xc], [y, yc],
                          color=color,
                          linewidth=0.5,
                          zorder=1,
                          linestyle="--")

    plt.axis('tight')
    plt.show()
Ejemplo n.º 17
0
def plot_all_bootstrap(boot_direc, a, b):
    colors = cm.cool(numpy.linspace(0, 1, len(boot_direc)))
    for i, direc in enumerate(boot_direc):
        f = open(direc, 'rb')
        temp = cPickle.load(f)
        bin = cPickle.load(f)
        dG = cPickle.load(f)
        ddG = cPickle.load(f)
        dGf = dG[:, a] - dG[:, b]
        ddGf = [numpy.sqrt(x[a, b]) for x in ddG]
        plt.errorbar(temp, dGf, ddGf, color=colors[i])
def set_color(c,n):
    if c == "rainbow":
        color = cm.rainbow(n/8.)
    elif c == "gnuplot":
        color = cm.gnuplot(n/8.)
    elif c == "autumn":
        color = cm.autumn(n/8.)
    elif c == "cool":
        color = cm.cool(n/8.)

    return color
Ejemplo n.º 19
0
def plot_all_bootstrap(boot_direc, a, b):
    colors = cm.cool(numpy.linspace(0,1,len(boot_direc)))
    for i,direc in enumerate(boot_direc):
        f = open(direc,'rb')
        temp = cPickle.load(f)
        bin = cPickle.load(f)
        dG = cPickle.load(f)
        ddG = cPickle.load(f)
        dGf = dG[:,a] - dG[:,b]
        ddGf = [numpy.sqrt(x[a,b]) for x in ddG]
        plt.errorbar(temp,dGf,ddGf,color=colors[i])
Ejemplo n.º 20
0
def plot_2D_labeled_data(X, y, fig_number, fig_title):
    # put plt.ioff() and plt.show() at end

    colors = cm.cool(y / max(y))

    plt.ion()
    f = plt.figure(fig_number)
    plt.scatter(X[:, 0], X[:, 1], c=y)
    # plt.axis('tight')
    plt.title(fig_title)
    f.show()
    return fig_number + 1
Ejemplo n.º 21
0
def plot_state(state):
    length = 1
    b = Bloch()
    b.vector_color = ['r']
    b.view = [-40, 30]
    nrm = mpl.colors.Normalize(0, length)
    colors = cm.cool(nrm(range(length)))
    b.point_color = list(colors)  # options: 'r', 'g', 'b' etc.
    b.point_marker = ['o']
    b.point_size = [30]
    b.add_states(state)
    return b
Ejemplo n.º 22
0
def main():
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5, .55, .6, .65, .7]
    Q_files = ['/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/foldingcurve_umbrella.npy' % str(x)[1::] for x in lam]
    Q_files[-3] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.6/foldingcurve.npy' 
    Q_files[-2] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.65/foldingcurve.npy' 
    Q_files[-1] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.7/foldingcurve.npy' 
    Cv_files = ['/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/heatcap_umbrella.npy' % str(x)[1::] for x in lam]
    Cv_files[-2] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.65/heatcap.npy' 
    Cv_files[-1] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.7/heatcap.npy' 
    colors = cm.cool(numpy.linspace(0,1,len(lam)))
    
    f = plt.figure(1,(7,8))
    plt.rc('text',usetex=True)
    matplotlib.rc('font', family = 'serif',size=20)
    font = {'family' : 'serif',
            'size'   : 20}
    ax1 = plt.subplot(211)
    for i in range(len(lam)):
        data = numpy.load(Q_files[i])
        if i < 10:
            x=30
            ax1.errorbar(data[0,-x::],data[1,-x::],data[2,-x::],label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        else:
            ax1.errorbar(data[0,:],data[1,:],data[2,:],label=r'$\lambda$ = %s' % lam[i], color=colors[i])
    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/foldingcurve.npy'
    data = numpy.load(soln)
    ax1.errorbar(data[0,:],data[1,:],data[2,:],label='solution', color='k')
    plt.ylabel('Q')
    plt.setp(ax1.get_xticklabels(), visible = False)
    plt.legend(bbox_to_anchor=(1.37,.5),prop={'size':12})
    plt.xlim((200,400))

    ax2 = plt.subplot(212)
    for i in range(len(lam)):
        data = numpy.load(Cv_files[i])
        if i < 11:
            x=30
            ax2.errorbar(data[0,-x::],data[1,-x::],data[2,-x::],label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        else:
            ax2.errorbar(data[0,:],data[1,:],data[2,:],label=r'$\lambda$ = %s' % lam[i], color=colors[i])
    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/heatcap.npy'
    data = numpy.load(soln)
    ax2.errorbar(data[0,:],data[1,:],data[2,:],label='solution', color='k')
    #plt.ylabel(r'$C_{v}  \textnormal{ (kcal/mol$\cdot$K)}$')
    f.text(.06,.3,r'$C_{v}  \textnormal{ (kcal/mol$\cdot$K)}$',ha='center',va='center',rotation='vertical')
    plt.xlabel('temperature (K)')
    #plt.legend(prop={'size':8})
    plt.xlim((200,400))
    plt.yticks(numpy.arange(0,4.5,.5))

    f.subplots_adjust(hspace=0, right=.75, left=.15)
    plt.savefig('/home/edz3fz/proteinmontecarlo/manuscripts/figures/Fig6_foldingcurve.eps')
    plt.show()
Ejemplo n.º 23
0
def main():
    lam = [.1, .15, .2, .25, .3, .35, .45, .5, .55, .6]  #, .65, .7]
    PMF_files = [
        '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/pmfQ_umbrella_325.pkl'
        % str(x)[1::] for x in lam
    ]
    PMF_files[
        -2] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.55/pmf_325.pkl'
    #PMF_files[-1] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.6/pmf_325.pkl'
    colors = cm.cool(numpy.linspace(0, 1, len(lam)))

    fig = plt.figure(1, (8.5, 6.5))
    plt.rc('text', usetex=True)
    matplotlib.rc('font', family='serif', size=20)
    for i in range(len(lam)):
        f = open(PMF_files[i], 'rb')
        temp = cPickle.load(f)
        bin_centers = cPickle.load(f)
        f_i = cPickle.load(f)
        df_i = cPickle.load(f)
        f.close()
        idx = numpy.argmin(f_i[int(.7 * len(f_i))::]) + int(.7 * len(f_i))
        f_i -= f_i[idx]
        plt.errorbar(bin_centers[1::],
                     f_i[1::],
                     numpy.array(df_i[0, :])[0, 1::],
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])

    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/pmf_325.pkl'
    f = open(soln, 'rb')
    temp = cPickle.load(f)
    bin_centers = cPickle.load(f)
    f_i = cPickle.load(f)
    df_i = cPickle.load(f)
    f.close()
    idx = numpy.argmin(f_i[int(.7 * len(f_i))::]) + int(.7 * len(f_i))
    f_i -= f_i[idx]
    plt.errorbar(bin_centers[1::],
                 f_i[1::],
                 numpy.array(df_i[0, :])[0, 1::],
                 label='solution',
                 color='k')

    fig.subplots_adjust(right=.8)

    plt.ylabel('PMF (kcal/mol)')
    plt.xlabel('Q')
    plt.legend(bbox_to_anchor=(1.29, .79), prop={'size': 14})
    plt.savefig(
        '/home/edz3fz/proteinmontecarlo/manuscripts/figures/Fig7_pmfQ.pdf')
    plt.show()
Ejemplo n.º 24
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.º 25
0
def draw_many_trajectories(im, trajs, indices):
    import matplotlib.cm as cm
    # define colors, get frame and features
    colors = (cm.cool(np.linspace(0.0, 1.0, 20))[:, :3] * 255).astype('uint8')
    img = np.array(im)
    if len(img.shape) != 3:
        img = (np.stack((img, ) * 3, -1) * 255).astype('uint8')
    j = 0
    for i, c in zip(indices, colors):
        j += 1
        traj = trajs[i]
        img = draw_trajectory(img, traj, color=colors[j % 20])
    return img
Ejemplo n.º 26
0
def makePlots(arr):
    clips = []
    clipi = []

    smooths = []
    smoothi = []
    for t in list(set(arr)):
        subset = stars[arr == t]

        clispec, clivar = sigclip_coadd(subset, sigLim=3.0)
        clips.append(clispec)
        clipi.append(clivar)

    for s, i in zip(clips, clipi):
        flux = Spectrum(lbin, s, ivar=i)
        flux.smooth(width=5, filtertype="gaussian", replace=True)
        smooths.append(flux.flux)
        smoothi.append(flux.ivar)

    uniqarr = list(set(arr))
    sortInd = np.argsort(uniqarr)
    n = len(uniqarr)

    fig = py.figure(1, (9, 14))
    ax = fig.add_subplot(111)

    offset = 0
    weight = np.ones(len(lbin))
    weight[(7550 < lbin) & (lbin < 7700)] = np.nan

    for i in sortInd[1:]:
        color = cmp.autumn(i / np.float(n))
        ax.plot(lbin, weight * smooths[i] + offset, lw=2.0, color=color)
        offset += 1

    ax.set_xlim(5500, 9500)
    ax.set_ylim(0, 21)
    ax.set_xlabel("$\lambda$")
    ax.axes.get_yaxis().set_visible(False)

    fig = py.figure(1, (15, 5))
    ax = fig.add_subplot(111)

    for i in sortInd:
        color = cmp.cool(i / float(n))
        ax.plot(lbin, weight * smooths[i], color=color)

    ax.set_xlim(5500, 9500)
Ejemplo n.º 27
0
def solution_pmf(direc):
    T = numpy.arange(300,355,5)
    colors = cm.cool(numpy.linspace(0,1,len(T)))
    plt.figure(7)
    for i,t in enumerate(T):
        f = open('%s/pmf_%i.pkl' %(direc,t),'rb')
        temp = cPickle.load(f)
        bin_centers = cPickle.load(f)
        f_i = cPickle.load(f)
        df_i = cPickle.load(f)
        f.close()
        idx = numpy.argmin(f_i[int(.7*len(f_i))::]) + int(.7*len(f_i))
        f_i -= f_i[idx]
        plt.errorbar(bin_centers[1::],f_i[1::],numpy.array(df_i[0,:])[0,1::],label='T = %i K' % t, color=colors[i])
    plt.xlabel('Q')
    plt.ylabel('PMF (kcal/mol)')
    plt.legend(loc=0, prop={'size':8})
Ejemplo n.º 28
0
def plot_tracks_wind_speed(hurricane_list,
                           m=None,
                           color_max_wind=120.0,
                           linewidth=2):
    if m == None:
        m = create_default_map()

    # color_max_wind is the highest wind speed which is displayed as its own color

    for hurricane in hurricane_list:
        for i in range(0, len(hurricane.track) - 1):
            x = [hurricane.track[i][0], hurricane.track[i + 1][0]]
            y = [hurricane.track[i][1], hurricane.track[i + 1][1]]
            c = cm.cool(hurricane.data[i].max_wind / color_max_wind)
            m.plot(x, y, latlon=True, color=c, linewidth=linewidth)

    plt.show()
Ejemplo n.º 29
0
def EBL_plot(att_list,
             zlist=0.1,
             elist=100 * u.GeV,
             tags="",
             ax=None,
             xsize=8,
             ysize=8,
             color=None,
             ls=None,
             debug=False,
             **kwargs):

    # If not a list but a single element
    if not isinstance(att_list, list): att_list = [att_list]
    if not isinstance(tags, list): tags = [tags]
    if not isinstance(zlist, numpy.ndarray): zlist = [zlist]
    if not isinstance(elist, numpy.ndarray): elist = [elist]

    lines = ["-", "--", "-.", ":"]  # A line style per attenuation model
    linecycler = cycle(lines)

    set_color = False
    set_line = False
    if ax == None: fig, ax = plt.subplots(figsize=(xsize, ysize))
    if color == None: set_color = True
    if ls == None: set_line = True

    with quantity_support():

        for att, tag in zip(att_list, tags):
            if set_line: ls = next(linecycler)
            for i, z in enumerate(zlist):
                if set_color:
                    color = cm.cool(i / len(zlist))  # One color per z
                ax.plot(elist,
                        att(elist, z),
                        label=tag + " z=" + str(round(z, 2)),
                        ls=ls,
                        color=color,
                        **kwargs)
        ax.set_xscale("log")
        ax.set_ylim(ymin=1e-2, ymax=2)

        single_legend(ax)
    return ax
Ejemplo n.º 30
0
def large_effect_mutations(myflu, ax=None, cols=None):
    from matplotlib import cm
    if ax is None:
        plt.figure(figsize=(figheight, figheight))
        ax = plt.subplot('111')
    if cols is None:
        cols = {}
    cutoff_freq = 0.25
    HI_cutoff = 0.3
    pivots = myflu.tree.seed_node.pivots
    dt = pivots[1] - pivots[0]
    y3 = int(3.0 / dt)
    y1 = int(1.0 / dt)
    color_cycle = 0
    for mut in myflu.mutation_effects:
        HI = myflu.mutation_effects[mut]
        if HI > HI_cutoff:
            mutlabel = mut[0] + ':' + mut[1][1:]
            if mutlabel in myflu.frequencies["mutations"]["global"]:
                mut_freq = np.array(
                    myflu.frequencies["mutations"]["global"][mutlabel])
            else:
                print("no frequencies for ", mut, 'HI', HI)
                continue

            if mut_freq[0] < cutoff_freq:
                print("Plotting ", mut, 'max: ', mut_freq.max(), 'HI', HI)
                if mut not in cols:
                    cols[mut] = colors[color_cycle % len(colors)]
                    color_cycle += 1

                c = cols[mut]
                ax.plot(pivots,
                        mut_freq,
                        lw=2,
                        ls='--' if mut_freq.max() > 0.9 else '-',
                        c=cm.cool(
                            min(np.sqrt(HI - HI_cutoff * 0.8), 1.5) / 1.5))

    ax.set_xlabel('time', fontsize=fs)
    ax.set_ylabel('frequency', fontsize=fs)
    #plt.xlim([-1,2])
    ax.set_ylim([-0.01, 1.1])
    ax.tick_params(axis='both', labelsize=fs)
    return cols
Ejemplo n.º 31
0
 def descent(self, vector_points, sample_point, depth=1):                
     """
     Recursively descent a Bezier curve for a given sample-point.
     
     Args:
         vector_points: A list of 2D-points defining the vectors a particular depth of the curve.
         interval_point: A float defining which sampling point we are descending.
         depth: Keeps track of the depth we're at.
         
     Returns:
         vector_points: A list of 2D-points that define the Bezier curve.
     """     
     
     # Use recursion as long as we can construct pairs of points between vectors.
     if len(vector_points) > 1:
         
         # First some variables for drawing the curve
         c_code = ((float(depth) - 1) / (len(self.control_points) - 2))
         zorder = depth - len(self.control_points) - 1
     
         if __name__ == '__main__':
             color = cm.cool(c_code) # @UndefinedVariable
         else:
             color = None
         
         spline_draw = depth==1 and not self.plotter.draw_level=='spline' and sample_point==1
         draw = True if self.plotter.draw_level=='bezier' or spline_draw else False
                     
         # Then the actual calculations
         recursion_points = []
         
         for i_line in xrange(len(vector_points) - 1):
             (x1,y1,x2,y2) = self.calc_line(vector_points, i_line, draw, color, zorder)
             
             dx = (x2 - x1) / self._params['interval']
             dy = (y2 - y1) / self._params['interval']       
             x = x1 + dx * sample_point
             y = y1 + dy * sample_point           
             recursion_points.append([x,y])
             
         # Do the same stuff with the newly calculated points and recursively return appended.
         return self.descent(recursion_points, sample_point, depth+1)
     # If we ran out of vectors, simply return the endpoint of the curve.
     else:
def plot_stretch(tt):
    fig = plt.figure(figsize=onecolumn_figsize)
    ax = plt.subplot(111)
    vmin, vmax = 0.5, 1.5  # color branches according to the rate deviation
    for n in tt.tree.find_clades():
        if n.up:
            n.color = [
                int(x * 255) for x in cm.cool(
                    (min(max(vmin, n.branch_length_interpolator.gamma), vmax) -
                     vmin) / (vmax - vmin))[:3]
            ]
        else:
            n.color = [200, 200, 200]

    ax.set_title("relaxed clock")
    Phylo.draw(tt.tree,
               axes=ax,
               show_confidence=False,
               label_func=lambda x: '')
Ejemplo n.º 33
0
def mcts_handicap_cdf_plot():
    fig = plt.figure()
    ax = plt.gca()
    cdf_plot_file(ax, ROOT + "di.mcts_low_128.npy", "--k", lw=2.0)

    labels = ["MCTS 128"]
    flavours = ["noflow", "noq"]
    B = len(flavours)
    colors = [cm.cool(x) for x in np.linspace(0, 1, B)]

    for (flavour, color) in zip(flavours, colors):
        cdf_plot_file(ax, ROOT + "di.mcts_{0}_128.npy".format(flavour), lw=2.0, color=color)
        labels.append("MCTS " + str(flavour))

    ax.set_xlabel("Discounted Cost")
    ax.set_title("MCTS with various handicaps")
    ax.legend(labels, loc="best")
    fig.savefig(IMAGES + "mcts_handicaps.png")
    plt.close()
Ejemplo n.º 34
0
def pmf_t(temp):
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5, .55]
    colors = cm.cool(numpy.linspace(0, 1, len(lam)))
    plt.figure(8)
    plt.rc('text', usetex=True)
    direc = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface'
    for i, l in enumerate(lam):
        f = open('%s/lambda%s/pmf_%i.pkl' % (direc, str(l)[1::], int(temp)),
                 'rb')
        temp = cPickle.load(f)
        bin_centers = cPickle.load(f)
        f_i = cPickle.load(f)
        df_i = cPickle.load(f)
        f.close()
        idx = numpy.argmin(f_i[int(.7 * len(f_i))::]) + int(.7 * len(f_i))
        f_i -= f_i[idx]
        plt.errorbar(bin_centers[1::],
                     f_i[1::],
                     numpy.array(df_i[0, :])[0, 1::],
                     label=r'$\lambda$ = %s' % l,
                     color=colors[i])

    f = open(
        '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/pmf_%i.pkl' %
        (int(temp)), 'rb')
    temp = cPickle.load(f)
    bin_centers = cPickle.load(f)
    f_i = cPickle.load(f)
    df_i = cPickle.load(f)
    f.close()
    idx = numpy.argmin(f_i[int(.7 * len(f_i))::]) + int(.7 * len(f_i))
    f_i -= f_i[idx]
    plt.errorbar(bin_centers[1::],
                 f_i[1::],
                 numpy.array(df_i[0, :])[0, 1::],
                 label='solution',
                 color='k')

    plt.xlabel('Q')
    plt.ylabel('PMF (kcal/mol)')
    plt.title('T = %s K' % temp)
    plt.legend(loc=0, prop={'size': 8})
Ejemplo n.º 35
0
def main():
    lam = [.1, .2, .3, .35, .4, .45, .5, .6, .7]
    lam = [.1, .2, .3, .4, .5, .675, .7]
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5, .55, .6, .65, .7]
    files = ['/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda%s/foldingcurve.npy' % str(x)[1::] for x in lam]
    colors = cm.cool(numpy.linspace(0,1,len(lam)))
    
    plt.figure(1)
    plt.rc('text',usetex=True)
    
    for i in range(len(lam)):
        data = numpy.load(files[i])
        plt.errorbar(data[0,:],data[1,:],data[2,:],label=r'$\lambda$ = %s' % lam[i], color=colors[i])
    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/foldingcurve.npy'
    data = numpy.load(soln)
    plt.errorbar(data[0,:],data[1,:],data[2,:],label='solution', color='k')
    plt.xlabel('temperature (K)')
    plt.ylabel('Q')
    plt.legend(prop={'size':8})
    plt.show()
Ejemplo n.º 36
0
def plot_resp_on_sort_shapes(ax, shapes, resp, top=25, fs=20, shrink=.5,):
    c_imgs = np.zeros(np.shape(shapes) + (4,))
    respsc = (resp - resp.min())
    respsc = respsc/respsc.max()
    
    scale = cm.cool(respsc)
    resp_sort_inds = np.argsort(resp)[::-1]
    
    for i, a_color in enumerate(scale):
        c_imgs[i, np.nonzero(shapes[i])[0], np.nonzero(shapes[i])[1],:] = a_color
    
    im = ax.imshow(np.tile(respsc,(2,1)), cmap=cm.cool, interpolation='nearest')
#    cbar = ax.get_figure().colorbar(im, ax=ax, shrink=shrink, 
#            ticks=[np.min(respsc), np.max(respsc)], aspect=10)
#    cbar.ax.set_yticklabels([]) 
    #cbar.ax.set_ylabel('Normalized\nResponse', rotation='horizontal', fontsize=fs/1.5, ha='left')
    
    data, im = vis_square(ax, c_imgs[resp_sort_inds][:top])
    ax.imshow(data, interpolation='nearest')
    #beautify(ax, ['top','right','left','bottom'])
    return data
Ejemplo n.º 37
0
def mcts_noflow_cdf_plot():
    fig = plt.figure()
    ax = plt.gca()
    cdf_plot_file(ax, ROOT + "di.rollout.npy", "--k", lw=2.0)
    cdf_plot_file(ax, ROOT + "di.q_low.npy", "--b", lw=2.0)
    cdf_plot_file(ax, ROOT + "di.q_ref.npy", "--r", lw=2.0)

    labels = ["rollout", "16x16", "64x64"]
    budgets = [4, 8, 16, 32, 64, 128, 256]
    B = len(budgets)
    colors = [cm.cool(x) for x in np.linspace(0, 1, B)]

    for (budget, color) in zip(budgets, colors):
        cdf_plot_file(ax, ROOT + "di.mcts_noflow_{0}.npy".format(budget), lw=2.0, color=color)
        labels.append("MCTS " + str(budget))

    ax.set_xlabel("Discounted Cost")
    ax.set_title("No flow MCTS with various budgets")
    ax.legend(labels, loc="best")
    fig.savefig(IMAGES + "mcts_noflow.png")
    plt.close()
Ejemplo n.º 38
0
def main():
    lam = [.1, .15, .2, .25, .3, .35, .45, .5, .55, .6]#, .65, .7]
    PMF_files = ['/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/pmfQ_umbrella_325.pkl' % str(x)[1::] for x in lam]
    PMF_files[-2] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.55/pmf_325.pkl'
    #PMF_files[-1] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.6/pmf_325.pkl'
    colors = cm.cool(numpy.linspace(0,1,len(lam)))
    
    fig = plt.figure(1,(8.5,6.5))
    plt.rc('text',usetex=True)
    matplotlib.rc('font', family = 'serif', size=20)
    for i in range(len(lam)):
        f = open(PMF_files[i],'rb')
        temp = cPickle.load(f)
        bin_centers = cPickle.load(f)
        f_i = cPickle.load(f)
        df_i = cPickle.load(f)
        f.close()
        idx = numpy.argmin(f_i[int(.7*len(f_i))::]) + int(.7*len(f_i))
        f_i -= f_i[idx]
        plt.errorbar(bin_centers[1::],f_i[1::],numpy.array(df_i[0,:])[0,1::],label=r'$\lambda$ = %s' % lam[i], color=colors[i])
 
    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/pmf_325.pkl'
    f = open(soln,'rb')
    temp = cPickle.load(f)
    bin_centers = cPickle.load(f)
    f_i = cPickle.load(f)
    df_i = cPickle.load(f)
    f.close()
    idx = numpy.argmin(f_i[int(.7*len(f_i))::]) + int(.7*len(f_i))
    f_i -= f_i[idx]
    plt.errorbar(bin_centers[1::],f_i[1::],numpy.array(df_i[0,:])[0,1::],label='solution', color='k')

    fig.subplots_adjust(right=.8)
 
    plt.ylabel('PMF (kcal/mol)')
    plt.xlabel('Q')
    plt.legend(bbox_to_anchor=(1.29,.79),prop={'size':14})
    plt.savefig('/home/edz3fz/proteinmontecarlo/manuscripts/figures/Fig7_pmfQ.pdf')
    plt.show()
Ejemplo n.º 39
0
def mcts_noflow_cdf_plot():
    fig = plt.figure()
    ax = plt.gca()
    cdf_plot_file(ax,ROOT + 'hillcar.rollout.npy','--k',lw=2.0)
    cdf_plot_file(ax,ROOT + 'hillcar.q_low.npy','--b',lw=2.0)
    cdf_plot_file(ax,ROOT + 'hillcar.q_ref.npy','--r',lw=2.0)

    labels = ['rollout','16x16','64x64']
    budgets = [4,8,16,32,64,128,256,512]
    B = len(budgets)
    colors = [cm.cool(x) for x in np.linspace(0,1,B)]
    
    for (budget,color) in zip(budgets,colors):
        cdf_plot_file(ax,ROOT + 'hillcar.mcts_noflow_{0}.npy'.format(budget),
                      lw=2.,color=color)
        labels.append('MCTS ' +str(budget))

    ax.set_xlabel('Discounted Cost')
    ax.set_title('Noflow MCTS with various budgets')
    ax.legend(labels,loc='best')
    fig.savefig(IMAGES + 'mcts_noflow.png')
    plt.close()
Ejemplo n.º 40
0
def mcts_handicap_cdf_plot():
    fig = plt.figure()
    ax = plt.gca()
    cdf_plot_file(ax,ROOT + 'hillcar.mcts_low_128.npy','--k',lw=2.0)

    labels = ['MCTS 128']
    flavours = ['noflow',
              'noq_opt',
              'noq_pes']
    B = len(flavours)
    colors = [cm.cool(x) for x in np.linspace(0,1,B)]
    
    
    for (flavour,color) in zip(flavours,colors):
        cdf_plot_file(ax,ROOT + 'hillcar.mcts_{0}_128.npy'.format(flavour),
                      lw=2.0,color=color)
        labels.append('MCTS ' +str(flavour))

    ax.set_xlabel('Discounted Cost')
    ax.set_title('MCTS with various handicaps')
    ax.legend(labels,loc='best')
    fig.savefig(IMAGES + 'mcts_handicaps.png')
    plt.close()
Ejemplo n.º 41
0
		time,wave,step = squarepulse(0.0,1.0,3e-9,1e-12)

		## Plot the results
		fig = plt.figure(figsize=(10,8))
		ax1 = fig.add_axes([0.1, 0.1, 0.7, 0.8])
		ax1.plot(time, wave, "k--", label="$V(t)$")
		l = ax1.legend()
		l.draw_frame(True) 
		ax1.set_xlabel('Time $(s)$')
		ax1.set_ylabel('Diode Voltage $(V_D)$')

		## Set up a list of time steps
		tlist = list(np.linspace(1e-12,4e-10,8))
		for i,t in enumerate(tlist[::-1]):
			time,wave,step = squarepulse(0.0,1.0,3e-9,t)
			c = cm.cool(float(i)/len(tlist),1)
			f = transient(wave,step,0.005)
			f.trapezoid(0.0)
			ax1.plot(time,f.result,color= c)
			ax1.set_ylim(0,1.1)

		ax1.set_title("Trapezoidal")
		## Fancy colorbar 
		cmap = mpl.cm.cool_r
		norm = mpl.colors.Normalize(min(tlist)/1e-12,max(tlist)/1e-12)
		ax2 = fig.add_axes([0.85, 0.1, 0.03, 0.8])
		cb1 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap,
										norm=norm,
										orientation='vertical')

		cb1.set_label('Time Step $(ps)$')
Ejemplo n.º 42
0
    if (pop.generation % 200 == 0):
        print "generation:", pop.generation, 'out of', maxgen

        # update fitness function
        selection_coefficients[m*np.random.randint(0,25)] = 0.01
        pop.set_trait_additive(selection_coefficients)

# convert to an array to enable slicing
allele_frequencies = np.array(allele_frequencies)

# plot the allele frequency trajectories
plt.figure()

# plot the selected mutations
for locus in xrange(0,pop.L,m):
    plt.plot(tp, allele_frequencies[:,locus], c=cm.cool(locus),lw=2, ls='--')

# plot some neutral sites
for locus in xrange(5,pop.L,50):
    plt.plot(tp, allele_frequencies[:,locus], c=cm.cool(locus), lw=2)

plt.title('Drift and draft')
plt.xlabel('Time [generations]')
plt.ylabel('Allele frequencies')
plt.text(100,0.85, "neutral alleles: solid")
plt.text(100,0.9, "sweeping alleles: dashed")
plt.text(100,0.765, "color indicates position \non the genome")

plt.ion()
plt.show()
Ejemplo n.º 43
0
def plot_line(path, label, ratio):
    x = []
    y = []
    x, y = load_fene(path)
    plt.plot(x, y, lw=2, marker='o', label=label, color=cm.cool(ratio))
Ejemplo n.º 44
0
province = []
number_occurence = []

csvfile = open("/Users/leoniekruger/CencusData/Data/CrimeNumberProvince.csv",
               "r")
csvReader = csv.reader(csvfile)

with open('/Users/leoniekruger/CencusData/Data/CrimeNumberProvince.csv',
          'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        province.append(row[0])
        type_of_crime.append(row[1])
        number_occurence.append(int(row[2]) * 10)
    # y.append(float(row[1]))

# create data

colors = cm.cool(np.random.rand(10))

# Use those colors as the color argument
plt.scatter(province, type_of_crime, s=number_occurence, color=colors)

# Add titles (main and on axis)

plt.xlabel("Province")
plt.ylabel("CrimeType")
plt.title("Crime South Africa")

plt.show()
Ejemplo n.º 45
0
def main():
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5, .55, .6]
    #lam = [.1, .15, .2, .25, .3, .35, .4]
    files = ['/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/dG_raw_varz.pkl' % str(x)[1::] for x in lam]
    files = ['/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/dG_raw_noint_2.pkl' % str(x)[1::] for x in lam]
    colors = cm.cool(numpy.linspace(0,1,len(lam)))
    plt.rc('text',usetex=True)
    matplotlib.rc('font', family = 'serif')
    font = {'family' : 'serif',
            'size'   : 'larger'}
    fig=plt.figure(1,(7,10))
    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/dG_raw.pkl'
    plot_dG_solution.solution(soln)
    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 folding
        dGf = dG[:,1] - dG[:,0] # free energy of folding while adsorbed
        dGf_des = dG[:,3] - dG[:,2] # free eneryg of folding while desorbed
    
        # Entropies of folding
        # dS(t) = -dG/dT = -(G[t+.5h] - G[t-.5h])/h
        dSf = (dGf[2::] - dGf[0:-2])/-10 # finite difference
        dSf_des = (dGf_des[2::] - dGf_des[0:-2])/-10
        temp_sub = target_temperatures[1:-1]
    
        # Enthalpies of folding
        # dG = dH - TdS
        # dH = dG + TdS
        dHf = dGf[1:-1] + temp_sub*dSf
        dHf_des = dGf_des[1:-1] + temp_sub*dSf_des
    
        # Uncertainties - just propagation of error for now
        ddGf = [numpy.sqrt(x[1,0]) for x in ddG]
        ddGf = numpy.array(ddGf)
        ddSf = (ddGf[0:-2]**2 + ddGf[2::]**2)**.5/10
        ddHf = (ddGf[1:-1]**2 + (temp_sub*ddSf)**2)**.5
    
        ddGf_des = [numpy.sqrt(x[3,2]) for x in ddG]
        ddGf_des = numpy.array(ddGf_des)
        ddSf_des = (ddGf_des[0:-2]**2 + ddGf_des[2::]**2)**.5/10
        ddHf_des = (ddGf_des[1:-1]**2 + (temp_sub*ddSf_des)**2)**.5
     
        fig.subplots_adjust(hspace=0)
        
        ax1 = plt.subplot(311)
        ax1.errorbar(target_temperatures,dGf,ddGf,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.xlim((300,350))
        plt.ylabel(r'$\Delta$G_{folding}$')
        box = ax1.get_position()
        ax1.set_position([box.x0,box.y0,box.width*.82,box.height])
        plt.setp(ax1.get_xticklabels(), visible=False)
        
        ax3 = plt.subplot(313)
        plt.xlim((300,350))
        ax3.errorbar(temp_sub,dHf,ddHf,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.xlabel(r'temperature (K)')
        plt.ylabel(r'$\Delta$H_{folding}$')
        plt.yticks(numpy.arange(-100,-10,10))
        box = ax3.get_position()
        ax3.set_position([box.x0,box.y0,box.width*.82,box.height])
       
        ax2 = plt.subplot(312)
        plt.xlim((300,350))
        ax2.errorbar(temp_sub,dSf,ddSf,label=r'$\lambda$ = %s' % lam[i], color=colors[i])
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.ylabel(r'$\Delta$S_{folding}$')
        box = ax2.get_position()
        ax2.set_position([box.x0,box.y0,box.width*.82,box.height])
        lgd = ax2.legend(bbox_to_anchor=(1.29, .98), prop={'size':10})
        

    fig.savefig('/home/edz3fz/proteinmontecarlo/manuscripts/figures/Fig8_dGf.pdf')
    plt.show()
Ejemplo n.º 46
0
def large_effect_mutations(myflu, ax=None, cols = None):
    from matplotlib import cm
    if ax is None:
        plt.figure(figsize=(figheight, figheight))
        ax = plt.subplot('111')
    if cols is None:
        cols = {}
    cutoff_freq = 0.25
    HI_cutoff = 0.3
    pivots = myflu.tree.seed_node.pivots
    dt = pivots[1]-pivots[0]
    y3 = int(3.0/dt)
    y1 = int(1.0/dt)
    color_cycle=0
    for mut in myflu.mutation_effects:
        HI = myflu.mutation_effects[mut]
        if HI>HI_cutoff:
            mutlabel = mut[0]+':'+mut[1][1:]
            if mutlabel in myflu.frequencies["mutations"]["global"]:
                mut_freq = np.array(myflu.frequencies["mutations"]["global"][mutlabel])
            else:
                print("no frequencies for ",mut, 'HI', HI)
                continue

            if mut_freq[0]<cutoff_freq:
                print("Plotting ",mut, 'max: ',mut_freq.max(), 'HI', HI)
                if mut not in cols:
                    cols[mut] = colors[color_cycle%len(colors)]
                    color_cycle+=1

                c = cols[mut]
                ax.plot(pivots, mut_freq, lw=2, ls = '--' if mut_freq.max()>0.9 else '-',c=cm.cool(min(np.sqrt(HI-HI_cutoff*0.8),1.5)/1.5))

    ax.set_xlabel('time', fontsize=fs)
    ax.set_ylabel('frequency', fontsize=fs)
    #plt.xlim([-1,2])
    ax.set_ylim([-0.01,1.1])
    ax.tick_params(axis='both', labelsize=fs)
    return cols
Ejemplo n.º 47
0
    null = pd.concat([open_cnn_analysis(fns[3], layer_label)[-1], null_v4], axis=0)
    cnn_an = pd.concat([alt, null, init, shuf ], 
              axis=0, keys=['resp', 's. resp', 'init. net', 's. layer wts'], names=['cond','layer_label','unit'])
#%%
plt.figure(figsize=(10, 10))
ax_dumb = plt.subplot(111)
ax = plt.subplot(111)
resp = v4_resp_apc[:,0]
#m, data = plot_resp_on_shapes(ax, no_blank_image, resp, image_square=20)
#beautify(ax, ['top','right','left','bottom'])
#cbar = plt.gcf().colorbar(im, ax=ax, shrink=0.5)
c_imgs = np.zeros(np.shape(no_blank_image) + (4,))
respsc = (resp - resp.min())
respsc = respsc/respsc.max()

scale = cm.cool(respsc)

for i, a_color in enumerate(scale):
    c_imgs[i, np.nonzero(no_blank_image[i])[0], np.nonzero(no_blank_image[i])[1],:] = a_color

im = ax_dumb.imshow(np.tile(respsc,(2,1)), cmap=cm.cool, interpolation='nearest')

cbar = plt.gcf().colorbar(im, ax=ax, shrink=0.5, ticks=[np.min(respsc), np.mean(respsc), np.max(respsc)])
cbar.ax.set_yticklabels([str(np.round(np.min(respsc).values,1)) 
,'$\mu$',
str(np.round(np.max(respsc).values,1))], fontsize=20) 
cbar.ax.set_ylabel('Normalized\nResponse', rotation='horizontal', fontsize=15, ha='left')

data, im = vis_square(ax, c_imgs)
ax.imshow(data, interpolation='nearest')
beautify(ax, ['top','right','left','bottom'])
Ejemplo n.º 48
0
def main():
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5, .55, .6, .65, .7]
    Q_files = [
        '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/foldingcurve_umbrella.npy'
        % str(x)[1::] for x in lam
    ]
    Q_files[
        -3] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.6/foldingcurve.npy'
    Q_files[
        -2] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.65/foldingcurve.npy'
    Q_files[
        -1] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.7/foldingcurve.npy'
    Cv_files = [
        '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/heatcap_umbrella.npy'
        % str(x)[1::] for x in lam
    ]
    Cv_files[
        -2] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.65/heatcap.npy'
    Cv_files[
        -1] = '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/lambda.7/heatcap.npy'
    colors = cm.cool(numpy.linspace(0, 1, len(lam)))

    f = plt.figure(1, (7, 8))
    plt.rc('text', usetex=True)
    matplotlib.rc('font', family='serif', size=20)
    font = {'family': 'serif', 'size': 20}
    ax1 = plt.subplot(211)
    for i in range(len(lam)):
        data = numpy.load(Q_files[i])
        if i < 10:
            x = 30
            ax1.errorbar(data[0, -x::],
                         data[1, -x::],
                         data[2, -x::],
                         label=r'$\lambda$ = %s' % lam[i],
                         color=colors[i])
        else:
            ax1.errorbar(data[0, :],
                         data[1, :],
                         data[2, :],
                         label=r'$\lambda$ = %s' % lam[i],
                         color=colors[i])
    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/foldingcurve.npy'
    data = numpy.load(soln)
    ax1.errorbar(data[0, :],
                 data[1, :],
                 data[2, :],
                 label='solution',
                 color='k')
    plt.ylabel('Q')
    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.legend(bbox_to_anchor=(1.37, .5), prop={'size': 12})
    plt.xlim((200, 400))

    ax2 = plt.subplot(212)
    for i in range(len(lam)):
        data = numpy.load(Cv_files[i])
        if i < 11:
            x = 30
            ax2.errorbar(data[0, -x::],
                         data[1, -x::],
                         data[2, -x::],
                         label=r'$\lambda$ = %s' % lam[i],
                         color=colors[i])
        else:
            ax2.errorbar(data[0, :],
                         data[1, :],
                         data[2, :],
                         label=r'$\lambda$ = %s' % lam[i],
                         color=colors[i])
    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/heatcap.npy'
    data = numpy.load(soln)
    ax2.errorbar(data[0, :],
                 data[1, :],
                 data[2, :],
                 label='solution',
                 color='k')
    #plt.ylabel(r'$C_{v}  \textnormal{ (kcal/mol$\cdot$K)}$')
    f.text(.06,
           .3,
           r'$C_{v}  \textnormal{ (kcal/mol$\cdot$K)}$',
           ha='center',
           va='center',
           rotation='vertical')
    plt.xlabel('temperature (K)')
    #plt.legend(prop={'size':8})
    plt.xlim((200, 400))
    plt.yticks(numpy.arange(0, 4.5, .5))

    f.subplots_adjust(hspace=0, right=.75, left=.15)
    plt.savefig(
        '/home/edz3fz/proteinmontecarlo/manuscripts/figures/Fig6_foldingcurve.eps'
    )
    plt.show()
Ejemplo n.º 49
0
        Vd = pa.sweepVoltage(0.0,1.0,0.05,"40E-3")

        fig = plt.figure(figsize=(10,8))
        ax1 = fig.add_axes([0.1, 0.1, 0.70, 0.8])
        ax2 = ax1.twinx()
        for n,vg in enumerate(vgx):
            # time.sleep(1)
            pa.stepVoltage(vg,0.0,1,"30E-3")
            pa.setOutput()
            pa.measureData()
            Id = pa.getDataIdVd()
            g0 = [xx/w for xx in  list(ndfit.derivative(Id,Vd))]
         
            print "%s %f"%("Vg =", vg)

            c = cm.cool(float(n)/len(vgx),1)
            ax1.plot(Vd, Id,color=c)
            ax2.plot(Vd, g0,color=c,linestyle='--')

        ax1.set_ylim(0.0, max(Id)+0.001)
        ax2.set_ylim(0.0, max(g0)+100)
        ax1.set_xlabel(r"Drain Voltage $(V_d)$")
        ax1.set_ylabel(r"Drain Current $(I_d)$")
        ax2.set_ylabel(r"Output Conductance $(g_0)$")

        ## Fancy Colorbar
        cmap = mpl.cm.cool
        norm = mpl.colors.Normalize(min(vgx),max(vgx))
        ax2 = fig.add_axes([0.90, 0.1, 0.03, 0.8])
        cb1 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap,
                                        norm=norm,
Ejemplo n.º 50
0
def main():
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5, .55, .6]
    #lam = [.1, .15, .2, .25, .3, .35, .4]
    files = ['/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/dG_raw_varz.pkl' % str(x)[1::] for x in lam]
    files = ['/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/dG_raw_noint_2.pkl' % str(x)[1::] for x in lam]
    colors = cm.cool(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))

    fig = plt.figure(10,(7,10))
    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,3]) 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[0,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        

        plt.rc('text',usetex=True)
        
        fig.subplots_adjust(hspace=0)
        
        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}$')
        box = ax1.get_position()
        ax1.set_position([box.x0,box.y0,box.width*.82,box.height])
        plt.setp(ax1.get_xticklabels(), visible=False)
        
        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,50,10))
        box = ax3.get_position()
        ax3.set_position([box.x0,box.y0,box.width*.82,box.height])
        
        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))
        box = ax2.get_position()
        ax2.set_position([box.x0,box.y0,box.width*.82,box.height])
        lgd = ax2.legend(bbox_to_anchor=(1.29,.95),prop={'size':10})
    

    plt.savefig('/home/edz3fz/proteinmontecarlo/manuscripts/figures/Fig10_ddGads.pdf')

    f=plt.figure(9,(.85*7,10))
    f.subplots_adjust(hspace=0)
    plt.rc('text',usetex=True)
    
    ax1 = plt.subplot(311)
    i=6
    ax1.errorbar(lam,dGf[:,i],ddGf[:,i],color='k',label='folded')    
    ax1.errorbar(lam,dGu[:,i],ddGu[:,i],color='k',ls='--',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})
#    box = ax1.get_position()
#    ax1.set_position([box.x0,box.y0,box.width*.82,box.height])
    plt.xlim((.1,.6))

    ax2 = plt.subplot(312)
    i -= 1
    ax2.errorbar(lam,dSf[:,i],ddSf[:,i],color='k',label='folded')    
    ax2.errorbar(lam,dSu[:,i],ddSu[:,i],color='k',ls='--',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))
#    box = ax2.get_position()
#    ax2.set_position([box.x0,box.y0,box.width*.82,box.height])
    plt.xlim((.1,.6))

    ax3 = plt.subplot(313)
    ax3.errorbar(lam,dHf[:,i],ddHf[:,i],color='k',label='folded')    
    ax3.errorbar(lam,dHu[:,i],ddHu[:,i],color='k',ls='--',label='unfolded')    
    plt.xlabel(r'$\lambda$')
    plt.ylabel(r'$\Delta$H_{adsorption}$')
#    lgd = plt.legend(prop={'size':9})
    plt.yticks(numpy.arange(-100,20,20))
#    lgd = ax2.legend(bbox_to_anchor=(.5,-.1),prop={'size':10},ncol=2)
#    box = ax3.get_position()
#    ax3.set_position([box.x0,box.y0,box.width*.82,box.height])

    plt.xlim((.1,.6))
    
    plt.savefig('/home/edz3fz/proteinmontecarlo/manuscripts/figures/Fig9_dGads.pdf')
Ejemplo n.º 51
0
def main():
    lam = [.1, .15, .2, .25, .3, .35, .4, .45, .5, .55, .6]
    #lam = [.1, .15, .2, .25, .3, .35, .4]
    files = [
        '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/dG_raw_varz.pkl'
        % str(x)[1::] for x in lam
    ]
    files = [
        '/home/edz3fz/proteinmontecarlo/results/1PGB/surface/umbrella_lambda%s/dG_raw_noint_2.pkl'
        % str(x)[1::] for x in lam
    ]
    colors = cm.cool(numpy.linspace(0, 1, len(lam)))
    plt.rc('text', usetex=True)
    matplotlib.rc('font', family='serif')
    font = {'family': 'serif', 'size': 'larger'}
    fig = plt.figure(1, (7, 10))
    soln = '/home/edz3fz/proteinmontecarlo/results/1PGB/solution/dG_raw.pkl'
    plot_dG_solution.solution(soln)
    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 folding
        dGf = dG[:, 1] - dG[:, 0]  # free energy of folding while adsorbed
        dGf_des = dG[:, 3] - dG[:, 2]  # free eneryg of folding while desorbed

        # Entropies of folding
        # dS(t) = -dG/dT = -(G[t+.5h] - G[t-.5h])/h
        dSf = (dGf[2::] - dGf[0:-2]) / -10  # finite difference
        dSf_des = (dGf_des[2::] - dGf_des[0:-2]) / -10
        temp_sub = target_temperatures[1:-1]

        # Enthalpies of folding
        # dG = dH - TdS
        # dH = dG + TdS
        dHf = dGf[1:-1] + temp_sub * dSf
        dHf_des = dGf_des[1:-1] + temp_sub * dSf_des

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

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

        fig.subplots_adjust(hspace=0)

        ax1 = plt.subplot(311)
        ax1.errorbar(target_temperatures,
                     dGf,
                     ddGf,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.xlim((300, 350))
        plt.ylabel(r'$\Delta$G_{folding}$')
        box = ax1.get_position()
        ax1.set_position([box.x0, box.y0, box.width * .82, box.height])
        plt.setp(ax1.get_xticklabels(), visible=False)

        ax3 = plt.subplot(313)
        plt.xlim((300, 350))
        ax3.errorbar(temp_sub,
                     dHf,
                     ddHf,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.xlabel(r'temperature (K)')
        plt.ylabel(r'$\Delta$H_{folding}$')
        plt.yticks(numpy.arange(-100, -10, 10))
        box = ax3.get_position()
        ax3.set_position([box.x0, box.y0, box.width * .82, box.height])

        ax2 = plt.subplot(312)
        plt.xlim((300, 350))
        ax2.errorbar(temp_sub,
                     dSf,
                     ddSf,
                     label=r'$\lambda$ = %s' % lam[i],
                     color=colors[i])
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.ylabel(r'$\Delta$S_{folding}$')
        box = ax2.get_position()
        ax2.set_position([box.x0, box.y0, box.width * .82, box.height])
        lgd = ax2.legend(bbox_to_anchor=(1.29, .98), prop={'size': 10})

    fig.savefig(
        '/home/edz3fz/proteinmontecarlo/manuscripts/figures/Fig8_dGf.pdf')
    plt.show()
Ejemplo n.º 52
0
def SpectroPlot(data,nx=100,ny=100,ylabel='incidence angle',zlabel='Amplification',yscale='lin',cmap='rainbow'):
    import scipy.interpolate
    from matplotlib.colors import LogNorm
    from matplotlib.ticker import MaxNLocator
    
    if data['sensitivity']==False:
        raise IOError("Sensitivity calculation hasn't been performed! Please do so.")
    
    x = np.asarray(data['x'])
    y = np.asarray(data['y'])
    z = np.asarray(data['z'])

    xi,yi = np.logspace(np.log10(x.min()),np.log10(x.max()),nx), np.linspace(y.min(),y.max(),ny)
    xi,yi = np.meshgrid(xi,yi)
    
    # interpolation
    zi = scipy.interpolate.griddata((x,y),z,(xi,yi),method='linear')
    
    # plot the data
    f = plt.figure(figsize=(10.,5.),dpi=300)
    
    # plot velocity profile   
    a2= f.add_subplot(1,5,5)
    if type(data['hl'][0])==float:
        xmin = []
        xmax = []
        # plot vp
        if data['modeID']>=5:
            if type(data['vp'][0])==list:
                lvp = len(data['vp'][0])
                clistvp = cm.cool(np.arange(lvp))
                for i in range(len(data['vp'][0])):
                    vptemp = np.concatenate(([data['vp'][0][i]],data['vp'][1:]))
                    depthtemp = np.concatenate(([0.],np.cumsum(data['hl'])))
                    
                    depth = [0.]
                    vp = [vptemp[0]/1000.]
                    for j in range(1,len(depthtemp)-1):
                        depth.append(depthtemp[j])
                        vp.append(vptemp[j-1]/1000.)
                        depth.append(depthtemp[j])
                        vp.append(vptemp[j]/1000.)   
                    depth.append(depth[-1]+0.1*depth[-1])
                    vp.append(vp[-1])                    
                    
                    a2.plot(vp,depth,color=clistvp[i])
                    xmax.append(np.max(vp))
            else:
                vptemp = data['vp']
                depthtemp = np.concatenate(([0.],np.cumsum(data['hl'])))
                
                depth = [0.]
                vp = [vptemp[0]/1000.]
                for j in range(1,len(depthtemp)-1):
                    depth.append(depthtemp[j])
                    vp.append(vptemp[j-1]/1000.)
                    depth.append(depthtemp[j])
                    vp.append(vptemp[j]/1000.)   
                depth.append(depth[-1]+0.1*depth[-1])
                vp.append(vp[-1])                
                
                a2.plot(vp,depth,color='b')
                xmax.append(np.max(vp))
        # plot vs
        if type(data['vs'][0])==list:
            lvs = len(data['vs'][0])
            clistvs = cm.hot(np.arange(lvs))
            for i in range(len(data['vs'][0])):
                vstemp = np.concatenate(([data['vs'][0][i]],data['vs'][1:]))
                depthtemp = np.concatenate(([0.],np.cumsum(data['hl'])))
                
                depth = [0.]
                vs = [vstemp[0]/1000.]
                for j in range(1,len(depthtemp)-1):
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j-1]/1000.)
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j]/1000.)   
                depth.append(depth[-1]+0.1*depth[-1])
                vs.append(vs[-1])                     
                
                a2.plot(vs,depth,color=clistvs[i])
                xmin.append(np.min(vs))
                xmax.append(np.max(vs))
        else:
            vstemp = data['vs']
            depthtemp = np.concatenate(([0.],np.cumsum(data['hl'])))
            
            depth = [0.]
            vs = [vstemp[0]/1000.]
            for j in range(1,len(depthtemp)-1):
                depth.append(depthtemp[j])
                vs.append(vstemp[j-1]/1000.)
                depth.append(depthtemp[j])
                vs.append(vstemp[j]/1000.)   
            depth.append(depth[-1]+0.1*depth[-1])
            vs.append(vs[-1])             

            a2.plot(vs,depth,color='r')
            xmin.append(np.min(vs))
            xmax.append(np.max(vs))
        a2.set_xlim(np.min(xmin)-0.05,np.max(xmax)+0.05)
        a2.set_ylim(np.min(depth),np.max(depth))
    else:
        if data['modeID']>=5:
            ld = len(data['hl'][0])
            clistvp = cm.cool(np.arange(ld))
            clistvs = cm.hot(np.arange(ld))
            for i in range(len(data['hl'][0])):
                hl = np.concatenate(([data['hl'][0][i]],data['hl'][1:]))
                depthtemp = np.concatenate(([0.],np.cumsum(hl)))
                vptemp = data['vp']
                vstemp = data['vs']
                depth = [0.]
                vs = [vstemp[0]/1000.]
                vp = [vptemp[0]/1000.]
                for j in range(1,len(hl)):
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j-1]/1000.)
                    vp.append(vptemp[j-1]/1000.)
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j]/1000.)  
                    vp.append(vptemp[j]/1000.)   
                depth.append(depth[-1]+0.1*depth[-1])
                vs.append(vs[-1])
                vp.append(vp[-1])

                a2.plot(vp,depth,color=clistvp[i])
                a2.plot(vs,depth,color=clistvs[i])
                a2.set_xlim(np.min(vs)-0.05,np.max(vp)+0.05)
                a2.set_ylim(np.min(depth),np.max(depth))
        else:
            ld = len(data['hl'][0])
            clistvs = cm.hot(np.arange(ld))
            for i in range(len(data['hl'][0])):
                hl = np.concatenate(([data['hl'][0][i]],data['hl'][1:]))
                vstemp = data['vs']
                depthtemp = np.concatenate(([0.],np.cumsum(hl)))
                depth = [0.]
                vs =[vstemp[0]/1000.]
                for j in range(1,len(hl)):
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j-1]/1000.)
                    depth.append(depthtemp[j])
                    vs.append(vstemp[j]/1000.)     
                depth.append(depth[-1]+0.1*depth[-1])
                vs.append(vs[-1])
                a2.plot(vs,depth,color=clistvs[i])
                a2.set_xlim(np.min(vs)-0.05,np.max(vs)+0.05)
                a2.set_ylim(np.min(depth),np.max(depth))
    
    a2.invert_yaxis()
    a2.set_xlabel('Velocity (km/s)')
    a2.set_ylabel('Depth (m)')
    a2.set_title('Velocity profile')
    plt.xticks(rotation='vertical') 
    
    # plot data
    a = f.add_subplot(1,5,(1,4))
    #zi = np.log10(zi)
    #z = np.log10(z)
    
    am = a.imshow(zi, vmin=0.1, vmax=z.max(), origin='lower', extent=[x.min(), x.max(), y.min(), y.max()],
             aspect = 'auto',norm=LogNorm())
    
    a.set_xlabel('Frequency (Hz)')
    a.set_ylabel(ylabel)
    a.set_xscale('log')
    if yscale=='log':
        print yscale
        a.set_yscale('log')
    a.minorticks_on()
    a.tick_params(axis='x', which='major', labelsize=11, labelcolor='k')
    a.tick_params(axis='x', which='minor', labelsize=10, labelcolor='grey')
    for axis in [a.xaxis]:
        axis.set_major_formatter(FuncFormatter(majortickformat))
        axis.set_minor_formatter(FuncFormatter(minortickformat))
    cb = plt.colorbar(am,label=zlabel)
    cb.locator = MaxNLocator(10)
#    cb.formatter = ScalarFormatter()
    cb.formatter = FuncFormatter(cbtickformat)
    cb.update_ticks()
    f.tight_layout()
Ejemplo n.º 53
0
def plot_all(phys_surf, calc_surf, phys_umat, calc_umat, E_b, E_s, normals, path = '', show = False):
    
    phi_slice               =   0
    
    X_init, Y_init, Z_init  =   get_coord(phys_surf) #init_surf)
    X, Y, Z                 =   get_coord(phys_surf + phys_umat) #deform(init_surf, ue))
    X_ss, Y_ss, Z_ss        =   get_coord(calc_surf + calc_umat) #deform(e_surf, ue))    
    
    # PLOT BEGINS!
    
    if np.amax(E_s) != 0:
        N_s = E_s/np.amax(E_s)
    else:
        N_s = E_s
    
    if np.amax(E_b) != 0:
        N_b = E_b/np.amax(E_b)
    else:
        N_b = E_b
        
    
    x, y, nx, ny, nz, nr = [],[],[],[],[], []
    
    r = np.zeros(len(calc_surf[:,phi_slice]))
    
    for ik, k in enumerate(np.array(calc_surf[:,phi_slice] + calc_umat[:,phi_slice])): 
        r[ik]   =   k[0] 
    
    z           =   Z_ss[:,phi_slice]
    
    
    for i in X_ss:
        for j in i:
            x.append(j)
    for i in Y_ss:
        for j in i:
            y.append(j)

    n = 0
    
    for i in range(normals.shape[0]):
        for j in range(normals.shape[1]):
            normal      =   normals[i,j]
            if abs(normal[0]**2 + normal[1]**2 + normal[2]**2 - 1) > 0.00001 :
                print 'ALERT ALERT!1' 
            nx.append(normal[0])
            ny.append(normal[1])
            nnr = x[n]/np.sqrt(x[n]**2 + y[n]**2)*normal[0] + y[n]/np.sqrt(x[n]**2 + y[n]**2)*normal[1]            
            if j == phi_slice:
                nr.append(nnr)
                nz.append(normal[2]) 
            n += 1

    limits          =   [np.amin([np.amin(X),np.amin(Y),np.amin(Z)]), np.amax([np.amax(X),np.amax(Y),np.amax(Z)])]
        
    fig             =   plt.figure(figsize=plt.figaspect(0.5)*1.5)
    
    #1
    ax              =   fig.add_subplot(121, projection='3d')
    
    vv              =   max(int(len(X)/30), 1)
    
    ax.plot_surface(X_init, Y_init, Z_init, alpha = 0.2, rstride = 4*vv, cstride = 4*vv) 
    ax.plot_surface(X, Y, Z, rstride = vv, cstride = vv, \
                    alpha = 1., facecolors=cm.cool(N_b), shade=False) #OrRd
    ax.auto_scale_xyz(limits, limits, limits)
    
    
    
    #2
    ax1 = fig.add_subplot(122, projection='3d')
    ax1.plot_surface(X_init, Y_init, Z_init, alpha = 0.2, rstride = 4*vv, cstride = 4*vv) 
    ax1.plot_surface(X, Y, Z, rstride = vv, cstride = vv, \
                    alpha = 1., facecolors=cm.cool(N_s), shade=False)
    ax1.auto_scale_xyz(limits, limits, limits)
    
    if path != '':
        if not exists(path + 'pictures/'):
            makedirs(path + 'pictures/')
        
        plt.savefig(path + 'pictures/ener_surf.png')
     
    fig2 = plt.figure(figsize=plt.figaspect(0.5)*1.5)
    
    #3
    ax2 = fig2.add_subplot(131)
    ax2.quiver(x, y, nx, ny, scale=3.2) #, units='width')
    ax2.axis('equal')
    
    ax3 = fig2.add_subplot(132)
    ax3.scatter(X, Y, marker = "+") #, units='width')
    ax3.axis('equal')
    
    
    #4
    ax4 = fig2.add_subplot(133)
    ax4.plot(r,z)
    ax4.quiver(r, z, nr, nz, scale=2.8) #, units='width')
    ax4.axis('equal')

    if path != '':
        plt.savefig(path + 'pictures/normals.png')
    
    if show:
        plt.show()