def draw(self,file=None):
        """
        Trace l'ensemble des lignes de champ passant par les points de départ 
        stockés dans Startpoints. Si un nom de fichier est donné, enregistre 
        la figure dans le fichier mais n'affiche rien à l'écran
        """

        def fun(P,t):
            B = self.B(P)
            Bx = B[0]
            By = B[1]
            B = np.sqrt(Bx*Bx+By*By)
            return [Bx/pow(B,4./3.),By/pow(B,4./3.)]

        t = np.linspace(0,self.k*self.maxint,self.numpoints/2)
        t2 = - t
        for P0 in self.startpoints:
            sol = odeint(fun,P0,t)
            x = sol[:,0]
            y = sol[:,1]
            pl.plot(x,y,'-',color='k')
            sol = odeint(fun,P0,t2)
            x = sol[1:,0]
            y = sol[1:,1]
            pl.plot(x,y,'-',color='k')
            pl.arrow(x[1],y[1],x[0]-x[1],y[0]-y[1],color='k')
        pl.title(self.title)
        pl.xlim([-self.size,self.size])
        pl.ylim([-self.size,self.size])
        if file:
            pl.savefig(file)
            pl.close()
        else:
            pl.show()
Exemplo n.º 2
0
def drawVectors(transformed_features, components_, columns, plt, scaled):
  if not scaled:
    return plt.axes() # No cheating ;-)

  num_columns = len(columns)

  # This funtion will project your *original* feature (columns)
  # onto your principal component feature-space, so that you can
  # visualize how "important" each one was in the
  # multi-dimensional scaling
  
  # Scale the principal components by the max value in
  # the transformed set belonging to that component
  xvector = components_[0] * max(transformed_features[:,0])
  yvector = components_[1] * max(transformed_features[:,1])

  ## visualize projections

  # Sort each column by it's length. These are your *original*
  # columns, not the principal components.
  important_features = { columns[i] : math.sqrt(xvector[i]**2 + yvector[i]**2) for i in range(num_columns) }
  important_features = sorted(zip(important_features.values(), important_features.keys()), reverse=True)
  print "Features by importance:\n", important_features

  ax = plt.axes()

  for i in range(num_columns):
    # Use an arrow to project each original feature as a
    # labeled vector on your principal component axes
    plt.arrow(0, 0, xvector[i], yvector[i], color='b', width=0.0005, head_width=0.02, alpha=0.75)
    plt.text(xvector[i]*1.2, yvector[i]*1.2, list(columns)[i], color='b', alpha=0.75)

  return ax
Exemplo n.º 3
0
def multiple_optima(gene_number=937, resolution=80, model_restarts=10, seed=10000, max_iters=300, optimize=True, plot=True):
    """
    Show an example of a multimodal error surface for Gaussian process
    regression. Gene 939 has bimodal behaviour where the noisy mode is
    higher.
    """

    # Contour over a range of length scales and signal/noise ratios.
    length_scales = np.linspace(0.1, 60., resolution)
    log_SNRs = np.linspace(-3., 4., resolution)

    try:import pods
    except ImportError:
        print('pods unavailable, see https://github.com/sods/ods for example datasets')
        return
    data = pods.datasets.della_gatta_TRP63_gene_expression(data_set='della_gatta',gene_number=gene_number)
    # data['Y'] = data['Y'][0::2, :]
    # data['X'] = data['X'][0::2, :]

    data['Y'] = data['Y'] - np.mean(data['Y'])

    lls = GPy.examples.regression._contour_data(data, length_scales, log_SNRs, GPy.kern.RBF)
    if plot:
        pb.contour(length_scales, log_SNRs, np.exp(lls), 20, cmap=pb.cm.jet)
        ax = pb.gca()
        pb.xlabel('length scale')
        pb.ylabel('log_10 SNR')

        xlim = ax.get_xlim()
        ylim = ax.get_ylim()

    # Now run a few optimizations
    models = []
    optim_point_x = np.empty(2)
    optim_point_y = np.empty(2)
    np.random.seed(seed=seed)
    for i in range(0, model_restarts):
        # kern = GPy.kern.RBF(1, variance=np.random.exponential(1.), lengthscale=np.random.exponential(50.))
        kern = GPy.kern.RBF(1, variance=np.random.uniform(1e-3, 1), lengthscale=np.random.uniform(5, 50))

        m = GPy.models.GPRegression(data['X'], data['Y'], kernel=kern)
        m.likelihood.variance = np.random.uniform(1e-3, 1)
        optim_point_x[0] = m.rbf.lengthscale
        optim_point_y[0] = np.log10(m.rbf.variance) - np.log10(m.likelihood.variance);

        # optimize
        if optimize:
            m.optimize('scg', xtol=1e-6, ftol=1e-6, max_iters=max_iters)

        optim_point_x[1] = m.rbf.lengthscale
        optim_point_y[1] = np.log10(m.rbf.variance) - np.log10(m.likelihood.variance);

        if plot:
            pb.arrow(optim_point_x[0], optim_point_y[0], optim_point_x[1] - optim_point_x[0], optim_point_y[1] - optim_point_y[0], label=str(i), head_length=1, head_width=0.5, fc='k', ec='k')
        models.append(m)

    if plot:
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
    return m # (models, lls)
Exemplo n.º 4
0
def show(model):
    spiral_x = []
    spiral_y = []
    model.calculate_spiral(spiral_x, spiral_y)
    print("sp")

    figure = plot.figure(1)
    plot.subplot2grid((1, 3), (0, 2), colspan=1)
    plot.title('Комплексная амплитуда волны E')
    plot.xlabel('Re(E)')
    plot.ylabel('Im(E)')

    #d = sqrt((spiral_x[1] - spiral_x[0])**2 + (spiral_y[1] - spiral_y[0])**2)
    d = 0.01
    w = d / 3
    h_w = w * 2
    h_l = d / 3

    plot.plot(spiral_x, spiral_y, color='r', linewidth=2)
    #for i in arange(0, len(spiral_x) - 1, 1):
    #    plot.arrow(spiral_x[i], spiral_y[i], spiral_x[i + 1] - spiral_x[i], spiral_y[i + 1] - spiral_y[i],
    #    width=w, head_width=h_w, head_length=h_l, length_includes_head=True, fc='r', ec='k')

    plot.arrow(0, 0, spiral_x[-1], spiral_y[-1],
               width=w*1.5, head_width=h_w*1.5, head_length=h_l*1.5, length_includes_head=True, fc='g', ec='k')


    plot.grid(True)
    mx = max(spiral_x)
    my = max(spiral_y)
    #plot.xlim([-mx - d, mx + d])
    #plot.ylim([-d, my + d])

    model.draw(figure)
Exemplo n.º 5
0
def plot_pick_and_place_stage(image_rgb, labeled_image, approximated_polygon, unfold_paths,
                              pick_point, place_point, to_file=None, show=True):
    plot_rgb(image_rgb, show=False)
    plt.imshow(labeled_image, cmap=plt.cm.RdGy, alpha=0.6)
    points = [tuple(point[0]) for point in approximated_polygon]
    # Plot polygon lines
    for (start_x, start_y), (end_x, end_y) in zip(points, points[1:]+points[0:1]):
        plt.plot( (start_x, end_x), (start_y, end_y), 'r-', linewidth=2.0 )
    # Plot polygon points
    for x, y in points:
        plt.plot(x, y, 'ro')
    #Plot unfold paths
    for path in unfold_paths:
        (start_x, start_y), (end_x, end_y) = path
        plt.plot( (start_x, end_x), (start_y, end_y), 'go-', linewidth=2.0 )
    # Plot arrow
    plt.arrow(pick_point[0], pick_point[1], place_point[0]-pick_point[0], place_point[1]-pick_point[1],
               head_width=15, head_length=15, fc='blue', ec='blue', lw=5, alpha=0.7)
    plt.axis('off')

    if to_file:
        plt.savefig(to_file, bbox_inches='tight')
        plt.close()
    elif show:
        plt.show()
Exemplo n.º 6
0
def plotTSP(path, points,data):
    
    # Unpack the primary TSP path and transform it into a list of ordered 
    # coordinates

    x = []; y = []
    x_all=[];y_all=[]
    for i in path:
        x.append(points[i][0])
        y.append(points[i][1])
    for i in range (data.shape[0]):
        x_all.append(data[i][0])
        y_all.append(data[i][1])
    plt.plot(x_all, y_all, 'co')

    # Set a scale for the arrow heads (there should be a reasonable default for this, WTF?)
    a_scale = float(max(x))/float(100)

        # Draw the primary path for the TSP problem
    plt.arrow(x[-2], y[-2], (x[0] - x[-2]), (y[0] - y[-2]), head_width = 10*a_scale, 
            color ='g', length_includes_head=True)
    for i in range(0,len(x)-2):
        plt.arrow(x[i], y[i], (x[i+1] - x[i]), (y[i+1] - y[i]), head_width = 10*a_scale,
                color = 'r', length_includes_head = True)

    #Set axis too slitghtly larger than the set of x and y
    plt.xlim(min(x_all)*1.1, max(x_all)*1.1)
    plt.ylim(min(y_all)*1.1, max(y_all)*1.1)
    plt.show()
Exemplo n.º 7
0
    def draw_arrow(pair, alpha=alpha, ec=ec, labelcolor=labelcolor):
        # set the length of the arrow
        if display == 'length':
            length = max_head_length + data[pair]/sf*(max_arrow_length -
                                                      max_head_length)
        else:
            length = max_arrow_length
        # set the transparency of the arrow
        if display == 'alph':
            alpha = min(data[pair]/sf, alpha)
        else:
            alpha = alpha
        # set the width of the arrow
        if display == 'width':
            scale = data[pair]/sf
            width = max_arrow_width*scale
            head_width = max_head_width*scale
            head_length = max_head_length*scale
        else:
            width = max_arrow_width
            head_width = max_head_width
            head_length = max_head_length

        fc = colors[pair]
        ec = ec or fc

        x_scale, y_scale = deltas[pair]
        x_pos, y_pos = positions[pair]
        plt.arrow(x_pos, y_pos, x_scale*length, y_scale*length,
              fc=fc, ec=ec, alpha=alpha, width=width, head_width=head_width,
              head_length=head_length, **arrow_params)

        # figure out coordinates for text
        # if drawing relative to base: x and y are same as for arrow
        # dx and dy are one arrow width left and up
        # need to rotate based on direction of arrow, use x_scale and y_scale
        # as sin x and cos x?
        sx, cx = y_scale, x_scale

        where = label_positions[pair]
        if where == 'left':
            orig_position = 3*np.array([[max_arrow_width, max_arrow_width]])
        elif where == 'absolute':
            orig_position = np.array([[max_arrow_length/2.0, 3*max_arrow_width]])
        elif where == 'right':
            orig_position = np.array([[length - 3*max_arrow_width,
                                    3*max_arrow_width]])
        elif where == 'center':
            orig_position = np.array([[length/2.0, 3*max_arrow_width]])
        else:
            raise ValueError("Got unknown position parameter %s" % where)

        M = np.array([[cx, sx], [-sx, cx]])
        coords = np.dot(orig_position, M) + [[x_pos, y_pos]]
        x, y = np.ravel(coords)
        orig_label = rate_labels[pair]
        label = '$%s_{_{\mathrm{%s}}}$' % (orig_label[0], orig_label[1:])

        plt.text(x, y, label, size=label_text_size, ha='center', va='center',
             color=labelcolor or fc)
def compareGraphs(imgOld, imgNew, POI, V):
	plt.imshow(imgNew,cmap = 'gray')
	# plt.scatter(POI[:,0,1],POI[:,0,0])
	for i in range(len(POI)):
		plt.arrow(POI[i,0,1],POI[i,0,0],V[i,1]*1,V[i,0]*1, color = 'red')
	# plt.arrow(POI[:,0,0],POI[:,0,1],0,-5)
	plt.show()
Exemplo n.º 9
0
            def animate(generation):
                chromosome = ts_ga.generation_fittest[generation]
                ax.clear()

                x, y = [], []
                for city_id, point in city_points.items():
                    x.append(point[0])
                    y.append(point[1])
                ax.plot(x, y, marker='s', linestyle='', label='cities', alpha=0.6)

                # plot optimal route
                chrom_city_ids = ts_ga.translator.translate_chromosome(chromosome)
                dist = round(ts_ga.calc_distance(chromosome), 2)

                ax.set_title("generation " + str(generation) + "\ndistance = " + str(dist))

                for i, start_city_id in enumerate(chrom_city_ids):
                    end_city_idx = i + 1

                    if end_city_idx == num_cities:
                        # distance from last city to first
                        end_city_idx = 0

                    end_city_id = chrom_city_ids[end_city_idx]

                    x1, y1 = city_points[start_city_id]
                    x2, y2 = city_points[end_city_id]
                    mid_x = (x2 - x1) / 2 + x1
                    mid_y = (y2 - y1) / 2 + y1

                    plt.arrow(x1, y1, x2 - x1, y2 - y1, head_width=1.5, fc='k', ec='k', alpha=0.7, linestyle='dotted', length_includes_head=True)
                    plt.text(mid_x, mid_y, str(i + 1))
Exemplo n.º 10
0
    def _fillPolarPlot(self, ax, drifter_id=0, printInfo=False):
        max_r = 0
        observedParticles = self.observeParticles()[:, drifter_id, :]
        if printInfo: print("observedParticles: \n" +str(observedParticles))
        for p in range(self.numParticles):
            u, v = observedParticles[p,0], observedParticles[p,1]
            r = np.sqrt(u**2 + v**2)
            max_r = max(max_r, r)
            theta = np.arctan(v/u)
            if (u < 0):
                theta += np.pi
            arr1 = plt.arrow(theta, 0, 0, r, alpha = 0.5, \
                             length_includes_head=True, \
                             edgecolor = 'green', facecolor = 'green', zorder = 5)

        obs_u = self.observeTrueState()[drifter_id, 2]
        obs_v = self.observeTrueState()[drifter_id, 3]
        if printInfo: print("observedTrueState: " + str((obs_u, obs_v)))
        obs_r = np.sqrt(obs_u**2 + obs_v**2)
        max_r = max(max_r, obs_r)
        obs_theta = np.arctan(obs_v/obs_u)
        if (obs_u < 0):
            obs_theta += np.pi
        arr1 = plt.arrow(obs_theta, 0, 0, obs_r, alpha = 0.5,\
                         length_includes_head=True, \
                         edgecolor = 'red', facecolor = 'red', zorder = 5)


        #ax.plot(theta, r, color='#ee8d18', lw=3)
        ax.set_rmax(max_r*1.2)
        plt.grid(True)
        plt.title("Observations from drifter " + str(drifter_id))
Exemplo n.º 11
0
def draw_experiment_data(experiment, viewport=None, estimate=True, camera=True, truth=True, cov=False):
    with open('/home/cristi/Dropbox/FIRM/Experiments/iser_trials/experiment_data_{}.txt'.format(experiment), 'r') as fin:
        for line in fin:
            line = line.strip()
            if line.startswith('#'):
                pass
            elif line:
                data = dict(eval(line))
                if data.has_key('opti') and data.has_key('filter'):
                    plot_data = []
                    if estimate:
                        plot_data.append((data['x'], (1.0, 0, 0)))
                    if camera:
                        plot_data.append((data['filter'], (1, 1, 0)))
                    if truth:
                        plot_data.append((data['opti'], (0, 1, 0))) # TODO: colors 'g'
                    
                    for (x, y, yaw,), col in plot_data:
                        plt.arrow(x, y, 0.1*np.cos(yaw), 0.1*np.sin(yaw),
                                  hold=True, color=col)
                    
                    if cov:
                        viewport.add_patch( Mission.covariance_ellipse(
                            data['x'][:2], np.diag(data['cov'][:2]), color='b',
                            fill=False, lw=1, zorder=0))
Exemplo n.º 12
0
def draw_arrows(pos, side, direction, om, last=False):
    ARROW_WIDTH = 0.04
    FONTSIZE = 20
    alpha = 0.3 if last else None
    dx, dy = 0.5, 1
    npos = pos + 1
    if isinstance(om, int):
        txt = m(r'\omega_' + str(om))
    else:
        txt = m(r'k_{' + str(om) + r'}')
    if (side == 1 and direction == 'in') or (side == 0 and direction == 'out'):
        txt = r'$-' + txt[1:]
    else:
        txt = r'$+' + txt[1:]
    if direction == 'in':
        if side == 1:
            dx *= -1
        plt.arrow(side - dx, npos - dy, dx, dy,
            width=ARROW_WIDTH, length_includes_head=True, lw=0)
        plt.text(side - dx, npos - dy / 2., txt, fontsize=FONTSIZE,
            horizontalalignment='center')
    else:
        if side == 1:
            dx *= -1
        plt.arrow(side, npos, -dx, dy, width=ARROW_WIDTH,
            length_includes_head=True,
            lw=0, alpha=alpha)
        plt.text(side - dx, npos + dy / 3., txt, fontsize=FONTSIZE,
            horizontalalignment='center')
Exemplo n.º 13
0
    def plot_state(self, i, history):
        plt.clf()
        ax = plt.gca()
        w = float(self.width + 1)
        h = float(self.height + 1)

        minw = np.min(self.internal_weights)
        maxw = np.max(self.internal_weights)
        diffw = maxw - minw

        for n, neuron in enumerate(self.neurons):
            x, y = self.neuron_position(n)
            line_y = -history[i - 100:i:4, n]
            #line_y = history[max(i - 20, 0):i, n] + .25
            line_x = np.arange(len(line_y)) / 50.0
            #line_x = np.arange(len(line_y)) / 40.0
            line = mlines.Line2D((line_x + x + .75) / w, 1 - (line_y + y + 1) / h)
            ax.add_line(line)

            k = .2
            for dx, dy in DIRECTIONS:
                weight = self.internal_weights[self.neuron_index(x, y), self.neuron_index((x + dx) % self.width, (y + dy) % self.height)]

                plt.arrow(
                    (1 + x + (1 - k) / 2 * dx) / w,
                    1 - (1 + y + (1 - k) / 2 * dy) / h,
                    (k * dx) / w,
                    -(k * dy) / h,
                    width=.0002,
                    color=str(weight / maxw),
                )

        plt.draw()
Exemplo n.º 14
0
    def plot2d(self,ix=0,iy=1,clf=True):
        """
        Generates a 2-dimensional plot of the data set and principle components
        using matplotlib.

        ix specifies which p-dimension to put on the x-axis of the plot
        and iy specifies which to put on the y-axis (0-indexed)
        """
        import matplotlib.pyplot as plt
        x,y=self.N[:,ix],self.N[:,iy]
        if clf:
            plt.clf()
        plt.scatter(x,y)
        vals,evs=self.getEigensystem()
        #evx,evy=evs[:,ix],evs[:,iy]
        xl,xu=plt.xlim()
        yl,yu=plt.ylim()
        dx,dy=(xu-xl),(yu-yl)
        for val,vec,c in zip(vals,evs.T,self._colors):
            plt.arrow(0,0,val*vec[ix],val*vec[iy],head_width=0.05*(dx*dy/4)**0.5,fc=c,ec=c)
        #plt.arrow(0,0,vals[ix]*evs[ix,ix],vals[ix]*evs[iy,ix],head_width=0.05*(dx*dy/4)**0.5,fc='g',ec='g')
        #plt.arrow(0,0,vals[iy]*evs[ix,iy],vals[iy]*evs[iy,iy],head_width=0.05*(dx*dy/4)**0.5,fc='r',ec='r')
        if self.names is not None:
            plt.xlabel('$'+self.names[ix]+'/\\sigma$')
            plt.ylabel('$'+self.names[iy]+'/\\sigma$')
Exemplo n.º 15
0
def Velocities_2D(n):
    dim = 2
    fig = plt.figure(dim, figsize=(8, 8), facecolor='white')
    fig.clf()
    xmin, xmax, ymin, ymax = 1000, -1000, 1000, -1000
    e = .5
    for k in range((2*n+1)**dim):
        v = pylbm.stencil.Velocity(dim = dim, num = k)
        x = v.vx
        y = v.vy
        xmin = min(xmin, x)
        xmax = max(xmax, x)
        ymin = min(ymin, y)
        ymax = max(ymax, y)
        couleur_texte = 0.
        couleur_trait = 0.5
        plt.text(x, y, str(v.num), color=[couleur_texte]*3,
                 horizontalalignment='center',verticalalignment='center',
                 fontsize=15)
    for x in range(xmin, xmax+1):
        plt.plot([x, x], [ymin, ymax], ':', color=[couleur_trait]*3)
    for y in range(ymin, ymax+1):
        plt.plot([xmin, xmax], [y, y], ':', color=[couleur_trait]*3)
    plt.text(0., ymax+2*e, "Velocities numbering {0:1d}D".format(dim),fontsize=20,
        verticalalignment='center', horizontalalignment='center', color='b')
    plt.arrow(xmin-e, ymin-e, 1, 0, head_width=0.05*dim, head_length=0.1, fc='b', ec='b')
    plt.arrow(xmin-e, ymin-e, 0, 1, head_width=0.05*dim, head_length=0.1, fc='b', ec='b')
    plt.text(xmin-e+.5, ymin-1.5*e, 'x', color='b',
        verticalalignment='center', horizontalalignment='center')
    plt.text(xmin-1.5*e, ymin-e+.5, 'y', color='b',
        verticalalignment='center', horizontalalignment='center')
    plt.axis('off')
    plt.xlim(xmin-2*e, xmax+2*e)
    plt.ylim(ymin-2*e, ymax+2*e)
    plt.draw()
Exemplo n.º 16
0
def iaplot(Ylist, Xlist = [], arrows_list = [],text_list = [], ylabel='y', xlabel='x', title='',colors = 'rgbmycrgbm',shapes = '----------', axis = 'tight'):
    import numpy as np
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import ia636

    if isinstance(Ylist, np.ndarray):
        Ylist = [Ylist]
    if  Xlist == []:
       Xlist = [np.arange(len(i)) for i in Ylist]
    if isinstance(Xlist, np.ndarray):
        Xlist = [Xlist]

    fig = plt.figure()
    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    plt.title(title)
    for x,y, c,s in zip(Xlist, Ylist,colors[:len(Xlist)],shapes[:len(Xlist)]):
        plt.plot(x,y, c+s,markersize=9)

    for arrow in arrows_list:
        plt.arrow(arrow[0], arrow[1], arrow[2], arrow[3], fc="k", ec="k", head_width=0.15, head_length=0.2 )

    for text in text_list:
        plt.annotate(text[0],xy=(text[1], text[2]), xycoords='data',xytext=(text[1], text[2]), textcoords='data',)
    plt.grid()
    plt.axis(axis)
    return ia636.iafig2img(fig)
def plotarrows():
    COORDINATES = np.load(savebase + savefilename + '.npy')
    plt.figure()
    plt.rc('text', usetex=True)
    ypmin = 0
    ypmax = 100
    xpmin = 0
    xpmax = 70
        
    plt.xlim(xmin=xpmin, xmax=xpmax)
    plt.ylim(ymin=ypmin, ymax=ypmax)
    
    for i in range(0,len(COORDINATES)-1):
        lw = 0.1+COORDINATES[i,2]*100.
        if i%21==0:
            plt.arrow(COORDINATES[i,0], COORDINATES[i,1], (COORDINATES[i+1,0] - COORDINATES[i,0]), (COORDINATES[i+1,1] - COORDINATES[i,1]), fc="k", ec="k", head_width=1.5, head_length=1, linewidth=lw)
        else:
            plt.arrow(COORDINATES[i,0], COORDINATES[i,1], (COORDINATES[i+1,0] - COORDINATES[i,0]), (COORDINATES[i+1,1] - COORDINATES[i,1]), linewidth=lw)
    
    plt.gca().set_aspect('equal')    
    plt.title('Trajectory over time: ' + str(len(COORDINATES)*10))
    plt.xlabel('$x/r_g$')
    plt.ylabel('$z/r_g$')

    plt.show()
    plt.savefig(figbase+savefilename, bbox_inches='tight') 
Exemplo n.º 18
0
def drawArrow(x=.5, y=.7, dx=.2, dy=-0.3, fc="k", ec="k"):
    """wrapping the matplotlib.pyplot.arrow function
    """
    # plt.arrow( x, y, dx, dy, **kwargs )
    head_width = (dx**2 +dy**2)**.5 *0.05
    head_length = (dx**2 +dy**2)**.5 *0.1
    plt.arrow(x, y, dx, dy, fc=fc, ec=ec, head_width=head_width, head_length=head_length)
Exemplo n.º 19
0
def plot_loop():
    figure(figsize=(10.5, 4.5), frameon=False)
    gca().axis("off")
    xlim(0.5, 3.5)
    ylim(0.7, 2.2)
    arrow_params = {"head_length": 0.08, "head_width": 0.1, "ec": "k",
                    "fc": "k"}
    text_params = {"fontsize": 25, "horizontalalignment": "center",
                   "verticalalignment": "center"}
    arrow(0.5, 1, 0.85, 0, **arrow_params)  # EX_A
    arrow(1.5, 1, 0.425, 0.736, **arrow_params)  # v1
    arrow(2.04, 1.82, 0.42, -0.72, **arrow_params)  # v2
    arrow(2.4, 1, -0.75, 0, **arrow_params)  # v3
    arrow(2.6, 1, 0.75, 0, **arrow_params)
    # reaction labels
    text(0.9, 1.15, "EX_A", **text_params)
    text(1.6, 1.5, r"v$_1$", **text_params)
    text(2.4, 1.5, r"v$_2$", **text_params)
    text(2, 0.85, r"v$_3$", **text_params)
    text(2.9, 1.15, "DM_C", **text_params)
    # metabolite labels
    scatter(1.5, 1, s=250, color='#c994c7')
    text(1.5, 0.9, "A", **text_params)
    scatter(2, 1.84, s=250, color='#c994c7')
    text(2, 1.95, "B", **text_params)
    scatter(2.5, 1, s=250, color='#c994c7')
    text(2.5, 0.9, "C", **text_params)
Exemplo n.º 20
0
    def show(self):
        '''バイプロット表示関数
        '''

        #: 各国のプロット
        for i in xrange(len(self.biblot_data)):
            x, y = self.biblot_data[i]
            data_name = self.data_name[i].decode("utf-8")
            if data_name != self.JAPAN_NAME:
                plt.text(x, y, data_name, ha='center', va='center', fontsize=18)
            else:
                plt.text(x, y, data_name, ha='center', va='center', fontsize=18, color="r")

        #: 因子負荷量のプロット
        for i in xrange(len(self.LIST_DATA_COLUMN)):
            x = self.pca_comp[0, i] * self.pca_score[0]
            y = self.pca_comp[1, i] * self.pca_score[1]
            plt.arrow(0, 0, x, y, color='r',
                      width=0.002, head_width=0.04)
            plt.text(x * self.TEXT_MOVE_RATE,
                     y * self.TEXT_MOVE_RATE,
                     self.LIST_DATA_COLUMN[i],
                     color='b', ha='center', va='center', fontsize=18)

        #: 画像表示系の設定
        self._set_canvas()
        plt.show()
Exemplo n.º 21
0
 def plot_all():
     pylab.axes()
     x = [x0, x1, x2, x3, x4, x5, x6, x7, x8]
     y = [y0, y1, y2, y3, y4, y5, y6, y7, y8]
     plt.title('Retroreflective Sphere')
     plt.plot(x, y)
     plt.xlim(-0.1, 0.1)
     plt.ylim(-0.13, 0.1)
     plt.xlabel(u"[m]")
     plt.ylabel(u"[m]")
     point_num = 0
     for i, j in izip(x, y):
         if withCoords:
             plt.annotate("M%s\n" % point_num + "[%2.3e," % i + "%2.3e]" % j, xy=(i, j))
         point_num += 1
     if withArrows:
         for i in xrange(len(x) - 1):
             plt.arrow(x[i],
                       y[i],
                       x[i + 1] - x[i],
                       y[i + 1] - y[i],
                       head_width=0.005,
                       head_length=0.004,
                       fc="k",
                       ec="k",
                       width=0.00003)
Exemplo n.º 22
0
 def draw(self, show_normal=False, color='green'):
     for i, segment in enumerate(self.segments):
         plt.plot(segment[:, 0], segment[:, 1], color=color)
         if show_normal:
             normal = math2d.normal(segment)
             center = math2d.center(segment)
             plt.arrow(center[0], center[1], normal[0], normal[1], width=0.01, color=color)
Exemplo n.º 23
0
def visual_addition(vectors):
    x = 0
    y = 0
    for v in vectors:
        plt.arrow(x, y, v[0], v[1], head_width=0.1, head_length=0.1)
        x += v[0]
        y += v[1]
Exemplo n.º 24
0
def plotarrows():
    COORDINATES = np.load(savefilename)
    plt.figure()
    plt.rc('text', usetex=True)
    ypmin = 0
    ypmax = 100
    xpmin = 0
    xpmax = 70
        
    plt.xlim(xmin=xpmin, xmax=xpmax)
    plt.ylim(ymin=ypmin, ymax=ypmax)
    
    for i in range(0,len(COORDINATES)-1):
        lw = 1+COORDINATES[i,2]*10.
        if i%2==0:
            plt.arrow(COORDINATES[i,0], COORDINATES[i,1], (COORDINATES[i+1,0] - COORDINATES[i,0]), (COORDINATES[i+1,1] - COORDINATES[i,1]), fc="k", ec="k", head_width=1.5, head_length=1, linewidth=lw)
        else:
            plt.arrow(COORDINATES[i,0], COORDINATES[i,1], (COORDINATES[i+1,0] - COORDINATES[i,0]), (COORDINATES[i+1,1] - COORDINATES[i,1]), linewidth=lw)
    
    plt.gca().set_aspect('equal')    
    plt.title('Trajectory over time: ' + str(len(COORDINATES)*100))
    plt.xlabel('$r/r_g$')
    plt.ylabel('$r/r_g$')
    plt.show()
    plt.savefig('/Users/Anton/Dropbox/Aleksander/Figures/simavg0070-0134/particles/particle_'+ str(gSTART_INDEX) +'_'+ str(gSTART_x)+'_'+str(gSTART_y), bbox_inches='tight') 
Exemplo n.º 25
0
def plotArrow(p0, p1, headWidth=.1):
    
    dx = p1[0] - p0[0]
    dy = p1[1] - p0[1]
    
    plt.arrow(p0[0], p0[1], dx, dy, head_width=headWidth, 
                  length_includes_head = True)
Exemplo n.º 26
0
def open_spline_chain_main():
    #x = [0, 3, -20, -10]
    #y = [0, 30, -5, -3]
    #th = [np.pi/2., np.pi, -np.pi/2., 0.]
    x = np.cos(np.deg2rad(135.))*np.array([-10., 1., 50.])
    y = np.sin(np.deg2rad(135.))*np.array([-10., 1., 50.])
    th = [np.deg2rad(135.), np.deg2rad(135.), np.deg2rad(135.)]
    X = np.column_stack((x, y))
    # Random desired discretization along the splines for demonstration purposes
    Ns = np.random.random_integers(100., 200., (X.shape[0]-1,))  # one less spline than waypoints.
    sx, sy, sth, length, u, coeffs = PiazziSpline.splineOpenChain(X, th, Ns)

    plt.plot(sx, sy, 'k-', linewidth=2.0)
    #test_x = 3.0
    #test_y = 30.01
    test_x = 0.013
    test_y = 0.008
    u_star, closest, distance = closestPointOnSpline2D(length, sx, sy, test_x, test_y, u, coeffs, guess=None)
    print "closest X = {:.3f}, {:.3f},  u* = {}".format(closest[0], closest[1], u_star)

    # Figure out the LOS controller using this example
    tangent_th = np.interp(u_star, u, sth)
    print "tangent th = {:.3f} deg".format(tangent_th*180.0/np.pi)
    lookAhead = 0.1  # how far forward in u
    lookaheadState = splineToEuclidean2D(coeffs, min(u_star + lookAhead, u[-1]))
    print "lookahead X = {:.3f}, {:.3f}".format(lookaheadState[0], lookaheadState[1])
    dx_global = lookaheadState[0] - closest[0]
    dy_global = lookaheadState[1] - closest[1]
    print "dx_global = {:.3f}, dy_global = {:.3f}".format(dx_global, dy_global)
    dx_frenet = dx_global*math.cos(tangent_th) + dy_global*math.sin(tangent_th)
    dy_frenet = dx_global*math.sin(tangent_th) - dy_global*math.cos(tangent_th)
    print "y error = {:.3f}, dx_frenet = {:.3f}, dy_frenet = {:.3f}".format(distance, dx_frenet, dy_frenet)

    # need sign of distance to spline to change
    # look at sign of cross product to determine "handed-ness"
    angle_from_closest_to_test = math.atan2(closest[1] - test_y, closest[0] - test_x)
    print "angle from closest to test = {:.3f} deg".format(angle_from_closest_to_test*180./np.pi)
    sign_test = np.cross([math.cos(tangent_th), math.sin(tangent_th)], [math.cos(angle_from_closest_to_test), math.sin(angle_from_closest_to_test)])
    distance *= np.sign(sign_test)
    print "distance to spline after sign update = {:.3f}".format(distance)

    # resulting triangle
    relative_angle = math.atan2((distance - dy_frenet), dx_frenet)
    global_angle = tangent_th + relative_angle
    print "relative angle = {:.3f} deg, global angle = {:.3f} deg".format(relative_angle*180./np.pi, global_angle*180./np.pi)

    # plot
    plt.plot(test_x, test_y, 'r+', markersize=12., markeredgewidth=2.0)
    plt.plot(closest[0], closest[1], 'gx', markersize=12., markeredgewidth=2.0)
    plt.plot(lookaheadState[0], lookaheadState[1], 'go', markersize=12., markeredgewidth=2.0)
    result_line = np.array([[test_x, test_y], closest])
    lookAhead_line = np.array([closest, lookaheadState])
    plt.plot(result_line[:, 0], result_line[:, 1], 'b-')
    plt.plot(lookAhead_line[:, 0], lookAhead_line[:, 1], 'g-')
    plt.arrow(closest[0], closest[1], 10.*math.cos(tangent_th), 10.*math.sin(tangent_th), linestyle='dashed')
    d = math.sqrt(math.pow(lookaheadState[0] - test_x, 2) + math.pow(lookaheadState[1] - test_y, 2))
    plt.arrow(test_x, test_y, d*math.cos(global_angle), d*math.sin(global_angle), linestyle='dotted')
    plt.axis('equal')
    plt.title("length = {:.2f}, u = {:.4f}, distance = {:.2f}".format(length[-1], u_star, distance))
    plt.show()
Exemplo n.º 27
0
def matrix2png(matrixname, savedfolder, xlim, ylim, arrows):
    matrix = open(matrixname, 'r').readlines()
    matrix = [i.split() for i in matrix]
    matrix = [[float(j) for j in i] for i in matrix]

    matrix_t = transposed(matrix)

    y = []

    for col in range(0,len(matrix_t)):
        y.append(matrix_t[col])

    longitud = len(y)

    for i in range(0, len(y[1])):
        for j in range(0, longitud/2):                    
            plt.plot(y[j*2][i],y[j*2+1][i],'o')
        
        for a in arrows:
            ao = a[0] - 1
            ai = a[1] - 1
            plt.arrow(y[ao*2][i], y[ao*2+1][i], y[ai*2][i]-y[ao*2][i],y[ai*2+1][i]-y[ao*2+1][i])        

        #Limites de los ejes
        plt.xlim(xlim[0], xlim[1])
        plt.ylim(ylim[0], ylim[1])
        plt.savefig(savedfolder + str(i).zfill(5) + '.png')
        plt.clf()
        
    plt.close()
Exemplo n.º 28
0
def phaseportrait(fs,inits,t=(-5,5),n=100, head_width = 0.13, head_length = 0.3, **kw):
    """
    plots phase portrait of the differential equation (\dot x,\dot y)=fs(x,y)

    f  -- must accept an array of X and t=0, and return a 2D array of \dot y and \dot x
    inits -- list of vectors representing inital conditions
    t -- time interval
    n -- number of points

    Example
    =======
    
    from itertools import product
    phaseportrait(lambda X, t=0: array([X[0],2*X[1]]), product(linspace(-4,4,15),linspace(-4,4,15)), [-2,0.3], n=20)
    """
    assert(t[0]<t[1] and t[1]>0)
    X=[]
    Y=[]
    for x0 in inits:
        x0=np.array(x0)
        if t[0]<0:
            segments=[np.linspace(0,t[0],n),np.linspace(0,t[1],n)]
        else:
            segments=[np.linspace(t[0],t[1],2*n)]
        for s in segments:
            points=integrate.odeint(fs,x0,s)
            for i,Z in enumerate([X,Y]):
                Z.extend(points[:,i])
                Z.append(None)
        direction = fs(x0)
        direction = direction / scipy.linalg.norm(direction) * 0.01
        plt.arrow(x0[0]-direction[0],x0[1]-direction[1],direction[0],direction[1],
              head_width=head_width, head_length=head_length, lw=0.0, **kw)
    plt.plot(X,Y,**kw)
Exemplo n.º 29
0
def plotWindVectorsOnMap(date, showIt=True):
     from mpl_toolkits.basemap import Basemap
     import matplotlib.pyplot as plt
     import wUUtils as Util
     # setup Lambert Conformal basemap.
     m = Basemap(width=3200000,height=2500000,projection='lcc',
            resolution='i',lat_1=45.,lat_0=43.6,lon_0=-80.)
     # draw coastlines.
     m.drawcoastlines()
     m.drawcountries()
     m.drawstates()
     # draw a boundary around the map, fill the background.
     # this background will end up being the ocean color, since
     # the continents will be drawn on top.
     m.drawmapboundary(fill_color='aqua')
     # fill continents, set lake color same as ocean color.
     m.fillcontinents(color='wheat',lake_color='aqua')
     # get city locations (Toronto, Montreal, Detroit)
     cityName = Util.getStationList()
     lon, lat = Util.getStationLonLat(cityName)
     # convert to map projection coords.
     # Note that lon,lat can be scalars, lists or numpy arrays.
     xpt,ypt = m(lon,lat)
     m.plot(xpt,ypt,'bo')  # plot a blue dot there
     # compute wind vectors
     windX = Util.loadDailyVariable(cityName, date, 'WindMeanX')
     windY = Util.loadDailyVariable(cityName, date, 'WindMeanY')
     for icity in range(len(cityName)):
          stretch = 20000
          dx, dy = stretch*windX[icity], stretch*windY[icity]
          plt.arrow(xpt[icity],ypt[icity],dx,dy,color='r',width=12000,head_length=40000,head_width=40000)
          plt.text(xpt[icity]+30000,ypt[icity]+20000,cityName[icity], size='large')
     plt.title("Daily-mean wind: " + date)
     if showIt:
          plt.show()
def display_velocity( q , p ,mu , mu2 = None):
 W = 5*SIGMA
 res = 30
 N_nodes = res**2
 store = np.outer( np.linspace(-W,W , res), np.ones(res) )
 nodes = np.zeros( [N_nodes , DIM] )
 nodes[:,0] = np.reshape( store , N_nodes )
 nodes[:,1] = np.reshape( store.T , N_nodes )
 K,DK,D2K,D3K = jpf.derivatives_of_kernel(nodes , q)
 vel_field = np.einsum('ijab,jb->ia',K,p) - np.einsum('ijabc,jbc->ia',DK,mu)
 if mu2 != None:
  vel_field = vel_field + np.einsum('ijabcd,jbcd->ia',D2K,mu2)

 U = vel_field[:,0]
 V = vel_field[:,1]
 plt.figure()
 plt.quiver( nodes[:,0] , nodes[:,1] , U , V , scale=10 )
 plt.plot(q[:,0],q[:,1],'ro')
 for i in range(0,N):
     if np.linalg.norm(p[i]) < 1e-4: continue
     plt.arrow(q[i,0], q[i,1], p[i,0], p[i,1], head_width=0.1, head_length=0.2, lw = 4.0, fc='b', ec='b')
     plt.arrow(q[i,0], q[i,1], p[i,0], p[i,1], head_width=0.1, head_length=0.2, lw = 2.0, fc='w', ec='w')
 plt.axis('equal')
 plt.axis([- W, W,- W, W ])
 return plt.gcf()
# -*- coding: utf-8 -*-
"""
Listing 2-13. 2DROTCIRCLE2
"""

import matplotlib.pyplot as plt
import numpy as np

plt.axis([-10, 150, 100, -10])
plt.axis('on')
plt.grid(True)

#--------------------------------------------------------------------------axes
plt.arrow(0, 0, 40, 0, head_length=4, head_width=2, color='b')
plt.arrow(0, 0, 0, 40, head_length=4, head_width=2, color='b')
plt.text(30, -3, 'Xg', color='b')
plt.text(-8, 34, 'Yg', color='b')

xc = 80  #--------------------center of rotation
yc = 30
plt.plot([xc - 50, xc + 60], [yc, yc], linewidth=1, color='grey')  #----X
plt.plot([xc, xc], [yc - 35, yc + 60], linewidth=1, color='grey')  #----Y
plt.text(xc + 50, yc - 2, 'X')
plt.text(xc - 5, yc + 55, 'Y')

plt.scatter(xc, yc, s=20, color='k')  #---plot center of rotation
plt.text(xc - 5, yc - 3, 'c')


#-----------------------------------------------------define rotation matrix Rz
def rotz(xp, yp, rz):
Exemplo n.º 32
0
def main(scene_idx):
    scene_name = Test_Scenes[scene_idx]
    #scene_file_addr = '/home/reza/Datasets/GibsonEnv/my_code/visual_servoing/sample_image_pairs_test/{}'.format(scene_name)
    scene_file_addr = '/home/reza/Datasets/GibsonEnv/my_code/visual_servoing/sample_image_pairs_test_longer_dist/{}'.format(
        scene_name)

    #scene_name = Train_Scenes[scene_idx]
    #scene_file_addr = '/home/reza/Datasets/GibsonEnv/my_code/visual_servoing/sample_image_pairs_train/{}'.format(scene_name)
    create_folder(scene_file_addr)

    ## rrt functions
    ## first figure out how to sample points from rrt graph
    rrt_directory = '/home/reza/Datasets/GibsonEnv/gibson/assets/dataset/{}_for_rrt'.format(
        scene_name)
    path_finder = rrt.PathFinder(rrt_directory)
    path_finder.load()
    num_nodes = len(path_finder.nodes_x)
    free = cv2.imread(
        '/home/reza/Datasets/GibsonEnv/gibson/assets/dataset/{}_for_rrt/free.png'
        .format(scene_name), 0)

    ## GibsonEnv setup
    config_file = os.path.join(
        '/home/reza/Datasets/GibsonEnv/my_code/CVPR_workshop', 'env_yamls',
        '{}_navigate.yaml'.format(scene_name))
    env = HuskyNavigateEnv(config=config_file, gpu_count=1)
    obs = env.reset(
    )  ## this line is important otherwise there will be an error like 'AttributeError: 'HuskyNavigateEnv' object has no attribute 'potential''

    def get_obs(current_pose):
        pos, orn = func_pose2posAndorn(current_pose,
                                       mapper_scene2z[scene_name])
        env.robot.reset_new_pose(pos, orn)
        obs, _, _, _ = env.step(4)
        obs_rgb = obs['rgb_filled']
        obs_depth = obs['depth']
        return obs_rgb.copy(), obs_depth.copy()

    left_pose_list = mapper_scene2points[scene_name]
    right_pose_list = []
    #for p_idx, p in enumerate(left_pose_list):
    for p_idx in range(0, 1):
        p = left_pose_list[p_idx]
        list_whole = []
        x0, y0, theta0 = p
        left_pose = [x0, y0, theta0]

        point_file_addr = '{}/point_{}'.format(scene_file_addr, p_idx)
        create_folder(point_file_addr)
        current_pose = left_pose
        left_rgb, left_depth = get_obs(current_pose)
        cv2.imwrite('{}/left_img.png'.format(point_file_addr),
                    left_rgb[:, :, ::-1])
        np.save('{}/left_img_depth.npy'.format(point_file_addr), left_depth)
        ## add left_img to list_whole
        current_dict = {}
        current_dict['img_name'] = 'left_img'
        current_dict['pose'] = left_pose
        list_whole.append(current_dict)

        for i in range(len(theta_list)):
            if i == 0 or i == 6:
                len_dist_list = 2
            elif i == 1 or i == 5:
                len_dist_list = 3
            elif i == 2 or i == 4:
                len_dist_list = 10  #4
            elif i == 3:
                len_dist_list = 10  #6
            print('len_dist_list = {}'.format(len_dist_list))
            for j in range(len_dist_list):

                location_theta = plus_theta_fn(theta0, theta_list[i])
                location_dist = dist_list[j]
                x1 = x0 + location_dist * math.cos(location_theta)
                y1 = y0 + location_dist * math.sin(location_theta)

                left_pixel = path_finder.point_to_pixel(left_pose)
                right_pixel = path_finder.point_to_pixel((x1, y1))

                # check the line
                flag = rrt.line_check(left_pixel, right_pixel, free)
                if not flag:
                    print('j = {}, obstacle'.format(j))
                else:
                    for diff_theta_idx in range(len(diff_theta_list)):
                        diff_theta = diff_theta_list[diff_theta_idx]
                        theta1 = plus_theta_fn(theta0, diff_theta)
                        right_pose = [x1, y1, theta1]

                        current_pose = right_pose
                        right_rgb, right_depth = get_obs(current_pose)

                        ## check if there is common space between left img and right img
                        kp1, kp2 = sample_gt_dense_correspondences(
                            left_depth,
                            right_depth,
                            left_pose,
                            right_pose,
                            gap=32,
                            focal_length=128,
                            resolution=256,
                            start_pixel=31)
                        if kp1.shape[1] > 2:
                            cv2.imwrite(
                                '{}/right_img_dist_{}_theta_{}_heading_{}.png'.
                                format(point_file_addr, mapper_dist[j],
                                       mapper_theta[i],
                                       mapper_theta[diff_theta_idx]),
                                right_rgb[:, :, ::-1])
                            np.save(
                                '{}/right_img_dist_{}_theta_{}_heading_{}_depth.npy'
                                .format(point_file_addr, mapper_dist[j],
                                        mapper_theta[i],
                                        mapper_theta[diff_theta_idx]),
                                right_depth)
                            right_pose_list.append(right_pose)
                            ## add right_img to list_whole
                            current_dict = {}
                            current_dict[
                                'img_name'] = 'right_img_dist_{}_theta_{}_heading_{}'.format(
                                    mapper_dist[j], mapper_theta[i],
                                    mapper_theta[diff_theta_idx])
                            current_dict['pose'] = right_pose
                            list_whole.append(current_dict)
                        else:
                            print('No common space')

        ## save list_whole
        np.save('{}/point_{}_poses.npy'.format(scene_file_addr, p_idx),
                list_whole)

    # plot the pose graph
    pose_file_addr = '{}'.format(scene_file_addr)
    img_name = '{}_sampled_poses.jpg'.format(scene_name)
    print('img_name = {}'.format(img_name))
    ## plot the poses
    free = cv2.imread(
        '/home/reza/Datasets/GibsonEnv/gibson/assets/dataset/{}_for_rrt/free.png'
        .format(scene_name), 1)
    rows, cols, _ = free.shape
    plt.imshow(free)
    for m in range(len(left_pose_list)):
        pose = left_pose_list[m]
        x, y = path_finder.point_to_pixel((pose[0], pose[1]))
        theta = pose[2]
        plt.arrow(x, y, cos(theta), sin(theta), color='r', \
            overhang=1, head_width=0.1, head_length=0.15, width=0.001)
    for m in range(len(right_pose_list)):
        pose = right_pose_list[m]
        x, y = path_finder.point_to_pixel((pose[0], pose[1]))
        theta = pose[2]
        plt.arrow(x, y, cos(theta), sin(theta), color='b', \
            overhang=1, head_width=0.1, head_length=0.15, width=0.001)
    plt.axis([0, cols, 0, rows])
    plt.xticks([])
    plt.yticks([])
    plt.savefig('{}/{}'.format(pose_file_addr, img_name),
                bbox_inches='tight',
                dpi=(400))
    plt.close()
Exemplo n.º 33
0
def draw_neural_net(ax,
                    left,
                    right,
                    bottom,
                    top,
                    layer_sizes,
                    coefs_,
                    intercepts_,
                    line_width=0.5):
    '''
    Draw a neural network cartoon using matplotilb.
    
    :usage:
        >>> fig = plt.figure(figsize=(12, 12))
        >>> draw_neural_net(fig.gca(), .1, .9, .1, .9, [4, 7, 2])
    
    :parameters:
        - ax : matplotlib.axes.AxesSubplot
            The axes on which to plot the cartoon (get e.g. by plt.gca())
        - left : float
            The center of the leftmost node(s) will be placed here
        - right : float
            The center of the rightmost node(s) will be placed here
        - bottom : float
            The center of the bottommost node(s) will be placed here
        - top : float
            The center of the topmost node(s) will be placed here
        - layer_sizes : list of int
            List of layer sizes, including input and output dimensionality
    '''
    ax.axis('off')
    n_layers = len(layer_sizes)
    v_spacing = (top - bottom) / float(max(layer_sizes))
    h_spacing = (right - left) / float(len(layer_sizes) - 1)

    # Input-Arrows
    layer_top_0 = v_spacing * (layer_sizes[0] - 1) / 2. + (top + bottom) / 2.
    for m in range(layer_sizes[0]):
        plt.arrow(left - 0.18,
                  layer_top_0 - m * v_spacing,
                  0.12,
                  0,
                  lw=0.1,
                  head_width=0.01,
                  head_length=0.02)

    # Nodes
    for n, layer_size in enumerate(layer_sizes):
        layer_top = v_spacing * (layer_size - 1) / 2. + (top + bottom) / 2.
        for m in range(layer_size):
            circle = plt.Circle(
                (n * h_spacing + left, layer_top - m * v_spacing),
                v_spacing / 8.,
                color='w',
                ec='k',
                zorder=4)
            if n == 0:
                plt.text(left - 0.125,
                         layer_top - m * v_spacing,
                         r'$X_{' + str(m + 1) + '}$',
                         fontsize=15)
            elif (n_layers == 3) & (n == 1):
                plt.text(n * h_spacing + left + 0.00,
                         layer_top - m * v_spacing +
                         (v_spacing / 8. + 0.01 * v_spacing),
                         r'$a_{' + str(m + 1) + '}$',
                         fontsize=15)
            elif n == n_layers - 1:
                # plt.text(n*h_spacing + left+0.10, layer_top - m*v_spacing, r' $\hat{p}_{'+str(m+1)+'}$=sigmoid($h_{'+str(m+1)+'}$)', fontsize=15)
                plt.text(n * h_spacing + left + 0.10,
                         layer_top - m * v_spacing,
                         r' $h_{' + str(m + 1) + '}$',
                         fontsize=15)
            ax.add_artist(circle)
    # Bias-Nodes
    for n, layer_size in enumerate(layer_sizes):
        if n < n_layers - 1:
            x_bias = (n + 0.5) * h_spacing + left
            y_bias = top + 0.005
            circle = plt.Circle((x_bias, y_bias),
                                v_spacing / 8.,
                                color='w',
                                ec='k',
                                zorder=4)
            plt.text(x_bias - (v_spacing / 8. + 0.10 * v_spacing + 0.01),
                     y_bias,
                     r'$1$',
                     fontsize=15)
            ax.add_artist(circle)
    # Edges
    # Edges between nodes
    for n, (layer_size_a,
            layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
        layer_top_a = v_spacing * (layer_size_a - 1) / 2. + (top + bottom) / 2.
        layer_top_b = v_spacing * (layer_size_b - 1) / 2. + (top + bottom) / 2.
        for m in range(layer_size_a):
            for o in range(layer_size_b):
                line = plt.Line2D(
                    [n * h_spacing + left, (n + 1) * h_spacing + left],
                    [layer_top_a - m * v_spacing, layer_top_b - o * v_spacing],
                    c='k',
                    lw=line_width)
                ax.add_artist(line)
                xm = (n * h_spacing + left)
                xo = ((n + 1) * h_spacing + left)
                ym = (layer_top_a - m * v_spacing)
                yo = (layer_top_b - o * v_spacing)
                rot_mo_rad = np.arctan((yo - ym) / (xo - xm))
                rot_mo_deg = rot_mo_rad * 180. / np.pi
                xm1 = xm + (v_spacing / 8. + 0.05) * np.cos(rot_mo_rad)
                if n == 0:
                    if yo > ym:
                        ym1 = ym + (v_spacing / 8. + 0.12) * np.sin(rot_mo_rad)
                    else:
                        ym1 = ym + (v_spacing / 8. + 0.05) * np.sin(rot_mo_rad)
                else:
                    if yo > ym:
                        ym1 = ym + (v_spacing / 8. + 0.12) * np.sin(rot_mo_rad)
                    else:
                        ym1 = ym + (v_spacing / 8. + 0.04) * np.sin(rot_mo_rad)
                # print(n, m, o, str(coefs_[n][m, o]))
                plt.text( xm1, ym1,\
                         str(coefs_[n][m, o]),\
                         rotation = rot_mo_deg, \
                         fontsize = 12)
    # Edges between bias and nodes

    for n, (layer_size_a,
            layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
        if n < n_layers - 1:
            layer_top_a = v_spacing * (layer_size_a - 1) / 2. + (top +
                                                                 bottom) / 2.
            layer_top_b = v_spacing * (layer_size_b - 1) / 2. + (top +
                                                                 bottom) / 2.
        x_bias = (n + 0.5) * h_spacing + left
        y_bias = top + 0.005
        for o in range(layer_size_b):
            line = plt.Line2D([x_bias, (n + 1) * h_spacing + left],
                              [y_bias, layer_top_b - o * v_spacing],
                              c='k',
                              lw=line_width)
            ax.add_artist(line)
            xo = ((n + 1) * h_spacing + left)
            yo = (layer_top_b - o * v_spacing)
            rot_bo_rad = np.arctan((yo - y_bias) / (xo - x_bias))
            rot_bo_deg = rot_bo_rad * 180. / np.pi
            xo2 = xo - (v_spacing / 8. + 0.01) * np.cos(rot_bo_rad)
            yo2 = yo - (v_spacing / 8. + 0.01) * np.sin(rot_bo_rad)
            xo1 = xo2 - 0.05 * np.cos(rot_bo_rad)
            yo1 = yo2 - 0.05 * np.sin(rot_bo_rad)
            plt.text( xo1, yo1,\
                 str(intercepts_[n][o]),\
                 rotation = rot_bo_deg, \
                 fontsize = 12)

    # Output-Arrows
    layer_top_0 = v_spacing * (layer_sizes[-1] - 1) / 2. + (top + bottom) / 2.
    for m in range(layer_sizes[-1]):
        plt.arrow(right + 0.015,
                  layer_top_0 - m * v_spacing,
                  0.16 * h_spacing,
                  0,
                  lw=1,
                  head_width=0.01,
                  head_length=0.02)
Exemplo n.º 34
0
def plot_workspace_data():
    plot = True
    safe_plot = True
    print_aep_median = False

    files = None
    if sys.argv[1] == "-dir":
        files = os.listdir(sys.argv[2])
        files.sort(key=lambda x: os.path.getmtime(sys.argv[2] + "/" + x),
                   reverse=False)
        print(files)
    elif len(sys.argv) == 2:
        files = [sys.argv[1]]
    else:
        print(
            "wrong parameters provide data-filename or -dir directory with files"
        )
        exit()

    average_step_length_overall = [0, 0, 0, 0, 0, 0]
    average_step_length_overall_counter = [0, 0, 0, 0, 0, 0]
    leg_names = ['lf', 'lm', 'lr', 'rr', 'rm', 'rf']
    leg_step_length = [[], [], [], [], [], []]
    run = 0
    for file in files:
        if plot:
            fig, axs = plt.subplots()
            plt.xlim(-0.35, 0.3)
            plt.ylim(-0.4, 0.4)

            # img = mpimg.imread('/home/jsimmering/plots_masterthesis/images/forPlots/widowX-body.png')
            img = mpimg.imread(
                '/home/jsimmering/plots_masterthesis/images/forPlots/body.png')
            axs.imshow(img,
                       alpha=1.0,
                       aspect='equal',
                       extent=(-0.1378, 0.1378, -0.1164, 0.1164))

        legs = [[[]], [[]], [[]], [[]], [[]], [[]]]
        steps = [0, 0, 0, 0, 0, 0]
        last_state_swing = [False, False, False, False, False, False]
        first_line = True

        file_name = None
        if len(sys.argv) > 2:
            file_name = sys.argv[2] + "/" + str(file)
        else:
            file_name = str(file)
        for line in open(str(file_name), 'r'):
            if first_line:
                first_line = False
                pass
            else:
                # Clear old plot
                # plt.clf()

                line = line.rstrip("\n")
                values = [float(s) for s in line.split(";")]

                for i in range(1, 19, 3):
                    if values[i] != 0.0 and values[i + 1] != 0.0:
                        # print("i = {}, (i-1)//3 = {}, steps[{}] = {}, leg[{}] len = {}".format(i, (i-1)//3, (i-1)//3, steps[(i-1)//3], (i-1)//3, len(legs[(i - 1) // 3])))
                        legs[(i - 1) // 3][steps[(i - 1) // 3]].append(
                            [values[i], values[i + 1]])
                        last_state_swing[(i - 1) // 3] = False
                    else:
                        if not last_state_swing[(i - 1) // 3]:
                            steps[(i - 1) // 3] += 1
                            legs[(i - 1) // 3].append([])
                            last_state_swing[(i - 1) // 3] = True

        if plot:
            lf_shoulder = np.matrix([0.1248, 0.06164]).T
            axs.plot(lf_shoulder.T[:, 0],
                     lf_shoulder.T[:, 1],
                     'x',
                     color='gray')
            lm_shoulder = np.matrix([0, 0.1034]).T
            axs.plot(lm_shoulder.T[:, 0],
                     lm_shoulder.T[:, 1],
                     'x',
                     color='gray')
            lr_shoulder = np.matrix([-0.1248, 0.06164]).T
            axs.plot(lr_shoulder.T[:, 0],
                     lr_shoulder.T[:, 1],
                     'x',
                     color='gray')
            rf_shoulder = np.matrix([0.1248, -0.06164]).T
            axs.plot(rf_shoulder.T[:, 0],
                     rf_shoulder.T[:, 1],
                     'x',
                     color='gray')
            rm_shoulder = np.matrix([0, -0.1034]).T
            axs.plot(rm_shoulder.T[:, 0],
                     rm_shoulder.T[:, 1],
                     'x',
                     color='gray')
            rr_shoulder = np.matrix([-0.1248, -0.06164]).T
            axs.plot(rr_shoulder.T[:, 0],
                     rr_shoulder.T[:, 1],
                     'x',
                     color='gray')

        # leg value mapping: ([0, 1, 2, 3, 4, 5], ['lf', 'lm', 'lr', 'rr', 'rm', 'rf'])
        counter = 0
        for leg in legs:
            #print("leg = " + str(leg_names[legs.index(leg)]))
            step_length = []
            first_step = True
            for stance in leg:
                X = [point[0] for point in stance]
                Y = [point[1] for point in stance]
                if stance and not first_step:
                    # print("stance = " + str(stance))
                    # print("beginning = stance[0] = " + str(stance[0]))
                    # print("end = stance[len(stance) - 1] = " + str(stance[len(stance) - 1]))
                    # step_length.append(np.linalg.norm(np.array(stance[len(stance) - 1]) - np.array(stance[0])))
                    length = 0
                    start_pos_x = None
                    start_pos_y = None
                    for i in range(1, len(stance)):
                        length += np.linalg.norm(
                            np.array(stance[i]) - np.array(stance[i - 1]))
                    # step_length.append(np.linalg.norm(np.array(stance[len(stance) - 1]) - np.array(stance[0])))
                    step_length.append(length)
                    #print("step length = " + str(length))
                if first_step:
                    first_step = False
                if plot:
                    axs.plot(X, Y)
            if [] in leg:
                leg.remove([])

            if print_aep_median:
                #print("{} leg".format(leg_names[counter]))
                aeps = [stance[0] for stance in leg]
                # aeps.sort(key=operator.itemgetter(0, 1))
                # print("aeps = " + str(aeps))
                # print("aeps length = " + str(len(aeps)))
                # print("aep lower middle value {} = {}".format(len(aeps)//2, aeps[len(aeps)//2]))
                # print("aep upper middle value {} = {}".format(len(aeps) // 2 + 1, aeps[len(aeps) // 2 + 1]))
                print("aep length = {}; / 2 = {}".format(
                    len(aeps),
                    len(aeps) / 2))
                if len(aeps) % 2 == 0:
                    aeps.sort(key=operator.itemgetter(0))
                    print("aep x lower middle value {} = {}".format(
                        len(aeps) // 2, aeps[len(aeps) // 2]))
                    aeps.sort(key=operator.itemgetter(1))
                    print("aep y lower middle value {} = {}".format(
                        len(aeps) // 2, aeps[len(aeps) // 2]))
                else:
                    aeps.sort(key=operator.itemgetter(0))
                    print("aep x lower middle value {} = {}".format(
                        len(aeps) // 2, aeps[len(aeps) // 2]))
                    print("aep x upper middle value {} = {}".format(
                        len(aeps) // 2 + 1, aeps[len(aeps) // 2 + 1]))
                    aeps.sort(key=operator.itemgetter(1))
                    print("aep y lower middle value {} = {}".format(
                        len(aeps) // 2, aeps[len(aeps) // 2]))
                    print("aep y upper middle value {} = {}".format(
                        len(aeps) // 2 + 1, aeps[len(aeps) // 2 + 1]))

            if len(step_length) > 0:
                average_step_length = np.sum(step_length) / len(step_length)
                if average_step_length:
                    #print("no average_step_length")
                    leg_step_length[counter].append(average_step_length)
                    average_step_length_overall[counter] += average_step_length
                    average_step_length_overall_counter[counter] += 1
            else:
                leg_step_length[counter].append(float('nan'))
            counter += 1

        if plot:
            # A = [point[0] for point in polygon_list[4]]
            # A.append(polygon_list[4][0][0])
            # A2 = [point[1] for point in polygon_list[4]]
            # A2.append(polygon_list[4][0][1])
            # axs.plot(A, A2)

            # plt.xlim(-0.3, 0.3)
            # plt.ylim(-0.4, 0.4)

            # plt.draw()
            # plt.pause(0.0001)
            # axs.axvline(x=0.25, color='b', lw=1)
            # axs.axvline(x=0.05, color='b', lw=1)
            # axs.axvline(x=-0.17, color='b', lw=1)
            axs.plot(0.25, 0.24, 'x', color='b', markersize=16)
            axs.plot(0.05, (0.24 + 0.04176), 'x', color='b', markersize=16)
            axs.plot((-0.17), 0.24, 'x', color='b', markersize=16)
            axs.plot(0.25, -0.24, 'x', color='b', markersize=16)
            axs.plot(0.05, -(0.24 + 0.04176), 'x', color='b', markersize=16)
            axs.plot(-0.17, -0.24, 'x', color='b', markersize=16)

            # circle = plt.Circle((0.25, 0.24), 0.08, color='g', fill=False)
            # axs.add_patch(circle)
            # circle = plt.Circle((0.05, 0.24 + 0.04176), 0.08, color='g', fill=False)
            # axs.add_patch(circle)
            # circle = plt.Circle((-0.17, 0.24), 0.08, color='g', fill=False)
            # axs.add_patch(circle)
            # circle = plt.Circle((0.25, -0.24), 0.08, color='g', fill=False)
            # axs.add_patch(circle)
            # circle = plt.Circle((0.05, -(0.24 + 0.04176)), 0.08, color='g', fill=False)
            # axs.add_patch(circle)
            # circle = plt.Circle((-0.17, -0.24), 0.08, color='g', fill=False)
            # axs.add_patch(circle)

            # WIDOWX
            # axs.plot(0.27, 0.18, 'x', color='b', markersize=16)
            # axs.plot(0.055, (0.18 + 0.035), 'x', color='b', markersize=16)
            # axs.plot((-0.17), 0.18, 'x', color='b', markersize=16)
            # axs.plot(0.27, -0.18, 'x', color='b', markersize=16)
            # axs.plot(0.055, -(0.18 + 0.035), 'x', color='b', markersize=16)
            # axs.plot(-0.17, -0.18, 'x', color='b', markersize=16)
            # circle = plt.Circle((0.27, 0.18), 0.08, color='g', fill=False)
            # axs.add_patch(circle)
            # circle = plt.Circle((0.055, 0.18 + 0.035), 0.08, color='g', fill=False)
            # axs.add_patch(circle)
            # circle = plt.Circle((-0.17, 0.18), 0.08, color='g', fill=False)
            # axs.add_patch(circle)
            # circle = plt.Circle((0.27, -0.18), 0.08, color='g', fill=False)
            # axs.add_patch(circle)
            # circle = plt.Circle((0.055, -(0.18 + 0.035)), 0.08, color='g', fill=False)
            # axs.add_patch(circle)
            # circle = plt.Circle((-0.17, -0.18), 0.08, color='g', fill=False)
            # axs.add_patch(circle)

            # axs.axvline(x=0.25 - 0.08, ymin=0, ymax=0.5, color='g', lw=1)
            # axs.axvline(x=0.05 - 0.08, ymin=0, ymax=0.5, color='g', lw=1)
            # axs.axvline(x=-0.17 - 0.08, ymin=0, ymax=0.5, color='g', lw=1)

            # walk direction
            split = re.findall(r"[^/_,]+", sys.argv[2], re.ASCII)
            print(split)
            # velocity = float(split[-1][:-1])
            # counter_damping_fact = (-141.5 * velocity) + 35.5
            # stance_speed = (velocity * counter_damping_fact)/35
            stance_speed = 0.045
            # print("stance speed = " + str(stance_speed))
            direction = 0.0
            for s in split:
                if 'dir' in s:
                    direction = float(s.replace('dir', ''))
            # WidowX
            # if direction == 0.0:
            #     for s in split:
            #         if 'rad' in s and 'radii' != s:
            #             direction = float(s.replace('rad', ''))
            print("direction = " + str(direction))
            # arrow = plt.arrow(0.111, 0.0, 0.046, 0.0)
            # axs.add_patch(arrow)
            # plot_pull_vector([0.111, 0.0], [stance_speed * math.cos(i), stance_speed * math.sin(i)], axs, colors[directions.index(i)])
            arrow = plt.arrow(0.111,
                              0.0,
                              stance_speed * math.cos(direction),
                              stance_speed * math.sin(direction),
                              color='r',
                              head_width=0.01,
                              overhang=0.25)
            # print("arrow length = " + str(math.sqrt(pow(stance_speed * math.cos(direction), 2) + pow(stance_speed * math.sin(direction), 2))))
            axs.add_patch(arrow)

            stance_diff = -pow(0.28 * (direction - 0.9), 2) + 0.02
            print("stance diff = " + str(stance_diff))
            if stance_diff < 0:
                stance_diff = 0
            print("stance diff = " + str(stance_diff))

            # axs.axvline(x=(0.25 - 0.08) + stance_diff, ymin=0.5, ymax=1, color='g', lw=1)
            # axs.axvline(x=(0.05 - 0.08) + stance_diff, ymin=0.5, ymax=1, color='g', lw=1)
            # axs.axvline(x=(-0.17 - 0.08) + stance_diff, ymin=0.5, ymax=1, color='g', lw=1)

            circle = plt.Circle((0.25, 0.24),
                                0.08 - stance_diff,
                                color='g',
                                fill=False)
            axs.add_patch(circle)
            circle = plt.Circle((0.05, 0.24 + 0.04176),
                                0.08 - stance_diff,
                                color='g',
                                fill=False)
            axs.add_patch(circle)
            circle = plt.Circle((-0.17, 0.24),
                                0.08 - stance_diff,
                                color='g',
                                fill=False)
            axs.add_patch(circle)
            circle = plt.Circle((0.25, -0.24), 0.08, color='g', fill=False)
            axs.add_patch(circle)
            circle = plt.Circle((0.05, -(0.24 + 0.04176)),
                                0.08,
                                color='g',
                                fill=False)
            axs.add_patch(circle)
            circle = plt.Circle((-0.17, -0.24), 0.08, color='g', fill=False)
            axs.add_patch(circle)

            plt.tick_params(labelsize=35)
            plt.grid()
            plt.axis('scaled')
            # plt.gca().set_aspect('equal', adjustable='box')
            if safe_plot:
                plt.subplots_adjust(top=2,
                                    bottom=0,
                                    right=2,
                                    left=0,
                                    hspace=1,
                                    wspace=1)
                plt.margins(1, 1)

                # split = [i.split("_") for i in files]
                split = re.findall(r"[^/_,]+", file_name, re.ASCII)
                # print("split = " + str(split))
                name = "_".join(split[(split.index("stability") + 4):])
                # print("name = " + name)
                print(
                    "single file: " +
                    "/home/jsimmering/plots_masterthesis/workspace/workspace_"
                    + name + ".svg")
                plt.savefig(
                    "/home/jsimmering/plots_masterthesis/workspace/workspace_"
                    + name + ".svg",
                    bbox_inches='tight',
                    pad_inches=0,
                    format='svg',
                    transparent=True)

                # sc.Figure("13.9cm", "15.75cm",
                #         # plt.rcParams["figure.figsize"][0], plt.rcParams["figure.figsize"][1],
                #         sc.Panel(sc.SVG("/home/jsimmering/plots_masterthesis/body.svg").scale(0.03175).move(4.35, 5.1)),
                #         sc.Panel(sc.SVG("/home/jsimmering/plots_masterthesis/workspace/workspace_" + name + ".svg").scale(0.022))
                # ).save("/home/jsimmering/plots_masterthesis/workspace/robot_workspace_" + name + ".svg")
                # SVG("/home/jsimmering/plots_masterthesis/workspace/robot_workspace_" + name + ".svg")
            else:
                plt.show()
        print("")

        run += 1

    # print("length collected = " + str(leg_step_length))
    sqrt_errors = []
    #print("leg_step_length = " + str(leg_step_length))
    print("average_step_length_overall = " + str([
        average_step_length_overall[i] / average_step_length_overall_counter[i]
        for i in range(0, len(average_step_length_overall))
    ]))
    for i in range(0, len(files)):
        # for each run
        sqrt_error = 0
        error_counter = 0
        for j in range(0, 6):
            # for each leg
            #print("sqrt_error += ({} - {})^2 = {}".format(leg_step_length[j][i], average_step_length_overall[j]/average_step_length_overall_counter[j], pow(leg_step_length[j][i] - average_step_length_overall[j]/average_step_length_overall_counter[j], 2)))
            if average_step_length_overall_counter[j] != 0:
                error = pow(
                    leg_step_length[j][i] - average_step_length_overall[j] /
                    average_step_length_overall_counter[j], 2)
                if not math.isnan(error):
                    sqrt_error += error
                    error_counter += 1
        #print("sqrt_errors.append {}/{} = {}".format(sqrt_error, error_counter, sqrt_error / error_counter))
        sqrt_errors.append(sqrt_error / error_counter)
    min_idx = sqrt_errors.index(min(sqrt_errors))
    print("errors = " + str(sqrt_errors) +
          " idx of min (starting at idx 1) = " + str(min_idx + 1))
    print("\n\n")
    print("**workspace:** run " + str(min_idx + 1))
    print("")

    file_name = None
    if len(sys.argv) > 2:
        file_name = sys.argv[2] + "/" + str(files[min_idx])
    else:
        file_name = str(files[min_idx])
    split = re.findall(r"[^/_,]+", file_name, re.ASCII)
    name = "_".join(split[(split.index("stability") + 4):])
    print("workspace_" + name + ".png")

    print("**average step length over all runs:**")
    #print("average_step_length_overall = " + str(average_step_length_overall))
    for i in [0, 5, 1, 4, 2, 3]:
        # print("{} leg = {}".format(leg_names[i], round(average_step_length_overall[i] / len(files), 5)))
        try:
            print(str(
                round(
                    average_step_length_overall[i] /
                    average_step_length_overall_counter[i], 3)) + " & ",
                  end="")
        except ZeroDivisionError:
            print(" nan & ", end="")
    print("")
    print("")

    for i in [0, 5, 1, 4, 2, 3]:
        # print("{} leg = {}".format(leg_names[i], round(average_step_length_overall[i] / len(files), 5)))
        try:
            print(str(average_step_length_overall[i] /
                      average_step_length_overall_counter[i]) + " ",
                  end="")
        except ZeroDivisionError:
            print(" nan ", end="")
    print("")
    print("")

    print([
        round(
            average_step_length_overall[i] /
            average_step_length_overall_counter[i], 3)
        for i in [0, 5, 1, 4, 2, 3]
    ])
    print("")
    print("")
Exemplo n.º 35
0
def plot_contours(Xdata, ydata, model, loss_fn, traces=None):
    Xvar = Variable(torch.from_numpy(Xdata)).float()
    yvar = Variable(torch.from_numpy(ydata)).float()

    x = np.arange(-8.0, 6.1, 0.1)
    y = np.arange(-2.0, 8.1, 0.1)
    # x = np.arange(-2.5, 5.6, 0.1)
    # y = np.arange(-1.0, 3.6, 0.1)
    X, Y = np.meshgrid(x, y)
    Z = np.empty_like(X)
    for i in range(X.shape[0]):
        for j in range(X.shape[1]):
            model.fc.weight.data = torch.FloatTensor([[X[i, j], Y[i, j]]])
            output = model(Xvar)
            loss = loss_fn(output, yvar)
            Z[i, j] = float(loss.data)
    # fig = plt.figure(figsize=(4, 3))
    fig, ax = plt.subplots(figsize=(4, 3))
    CS = ax.contour(X,
                    Y,
                    Z,
                    levels=[0.1, 0.25, 0.5, 1.0, 2.0, 4.0, 6.0, 8.0, 10.0])
    ax.clabel(CS, inline=1, fontsize=10, fmt='%1.2f')

    cind = 0
    colors = ['black', 'red', 'blue', 'green', 'gray']
    label_map = dict(sgd="SGD",
                     ngd="NGD",
                     natural_adam="FANG-Adam",
                     natural_amsgrad="FANG-Ams",
                     natural_adagrad="FANG-Ada")
    if traces is not None:
        for k, v in traces.items():
            lines = []
            tr = v
            for i in range(len(tr) - 1):
                lines.append([tr[i], tr[i + 1]])

            # ax.scatter(*zip(*tr), marker='o', c=colors[cind], s=4, label=label_map[k])

            # This is not visible but used to get legend
            lc = mc.LineCollection(lines,
                                   color=colors[cind],
                                   linewidths=1.0,
                                   label=label_map[k],
                                   visible=False)
            ax.add_collection(lc)

            for line in lines:
                arrow = plt.arrow(line[0][0],
                                  line[0][1],
                                  line[1][0] - line[0][0],
                                  line[1][1] - line[0][1],
                                  color=colors[cind],
                                  length_includes_head=True,
                                  head_width=0.1,
                                  head_length=0.1,
                                  zorder=1000)

            cind += 1

    plt.tick_params(
        axis='x',  # changes apply to the x-axis
        which='both',  # both major and minor ticks are affected
        bottom=False,  # ticks along the bottom edge are off
        top=False,  # ticks along the top edge are off
        labelbottom=False)  # labels along the bottom edge are off
    plt.tick_params(
        axis='y',  # changes apply to the x-axis
        which='both',  # both major and minor ticks are affected
        left=False,  # ticks along the bottom edge are off
        top=False,  # ticks along the top edge are off
        labelleft=False)  # labels along the bottom edge are off

    plt.legend()
    plt.tight_layout()

    plt.savefig('contour_large.pdf')
Exemplo n.º 36
0
def sgr_xyz_plots(stripes, params):
    """ Plots stream positions & directions in galactic XYZ"""
    positions = sc.zeros((len(stripes), 3))
    vectors = sc.zeros((len(stripes), 3))
    for i, stripe in enumerate(stripes):
        positions[i, 0], positions[i, 1], positions[i, 2] = coor.GC2xyz(
            eval(params[i][4]), 0.0, eval(params[i][5]), stripe)
        if stripe == 9 or stripe == 22 or stripe == 82:
            theta, phi = (ma.pi - eval(params[i][6])), (eval(params[i][7]) +
                                                        ma.pi)
        else:
            theta, phi = eval(params[i][6]), eval(params[i][7])
        theta, phi = coor.angle_bounds3(theta * deg, phi * deg, phi_max=180.0)
        theta, phi = theta * rad, phi * rad
        print stripe, theta, phi
        vectors[i, 0] = ma.sin(theta) * ma.cos(phi)
        vectors[i, 1] = ma.sin(theta) * ma.sin(phi)
        vectors[i, 2] = ma.cos(theta)
    off = 1.0
    """ Plot xy """
    plt.figure(1)
    #ax = plt.subplot(111)
    plt.scatter(GC[0],
                GC[1],
                s=40,
                edgecolor="k",
                marker="o",
                facecolor="black")
    plt.text(GC[0] + off, GC[1] + off, "GC", fontsize=10)
    plt.scatter(sun[0],
                sun[1],
                s=20,
                edgecolor="k",
                marker=(8, 2, 0),
                facecolor="white")
    plt.text(sun[0] + off, sun[1] + off, "Sun", fontsize=10)
    plt.scatter(Sgr[0],
                Sgr[1],
                s=20,
                edgecolor="k",
                marker="o",
                facecolor="black")
    plt.text(Sgr[0] + off, Sgr[1] + off, "Sgr Core", fontsize=10)
    t = sc.arange(0.0, 2.0 * ma.pi, 0.01)
    plt.plot(30.0 * sc.cos(t), 30.0 * sc.sin(t), "k:")
    offset_x = [
        0.0, 0.0, 0.0, -1.0, -2.0, -1.0, -1.0, 0.0, 0.0, 0.0, -1.0, -2.0, -3.2,
        -3.0, 0.5, 0.0, 0.0, -1.0
    ]
    offset_y = [
        0.0, 0.0, -1.0, -1.9, 0.2, 0.5, 0.5, -1.0, -2.0, -3.0, -3.0, -2.9,
        -2.5, 0.5, 0.5, -2.0, -2.0, -2.25
    ]
    for i in range(len(stripes)):
        #plt.annotate(str(stripes[i]), xy=(positions[i,0], positions[i,1]),
        #            xytext=( (positions[i,0]+(vectors[i,0]*100.0)), (positions[i,1]+(vectors[i,1]*100.0)) ),
        #            arrowprops=dict(facecolor='black', arrowstyle="->") )
        if stripes[i] < 75: color = 'white'
        else: color = 'black'
        plt.arrow(positions[i, 0],
                  positions[i, 1],
                  vectors[i, 0] * 10.0,
                  vectors[i, 1] * 10.0,
                  width=0.20,
                  head_width=1.5,
                  facecolor=color)
        if stripes[i] < 20 or stripes[i] > 19:
            plt.text(positions[i, 0] + offset_x[i],
                     positions[i, 1] + offset_y[i],
                     r"$" + str(stripes[i]) + r"$",
                     fontsize=10)
    plt.xlabel(r"$X_{GC}$ (kpc)")
    plt.ylabel(r"$Y_{GC}$ (kpc)")
    plt.axis('equal')
    plt.ylim(-30, 30)
    plt.xlim(-30, 30)
    locs, labels = plt.xticks()
    for i in range(len(labels)):
        labels[i] = r"$" + str(locs[i]) + r"$"
    plt.xticks(locs, labels, fontsize=12)
    locs, labels = plt.yticks()
    for i in range(len(labels)):
        labels[i] = r"$" + str(locs[i]) + r"$"
    plt.yticks(locs, labels, fontsize=12)
    """ Plot xz """
    plt.figure(2)
    #ax = plt.subplot(111)
    plt.scatter(GC[0],
                GC[2],
                s=40,
                edgecolor="k",
                marker="o",
                facecolor="black")
    plt.text(GC[0] + off, GC[2] + off, r"GC", fontsize=10)
    plt.scatter(sun[0],
                sun[2],
                s=20,
                edgecolor="k",
                marker=(8, 2, 0),
                facecolor="white")
    plt.text(sun[0] + off, sun[2] + off, "Sun", fontsize=10)
    plt.scatter(Sgr[0],
                Sgr[2],
                s=20,
                edgecolor="k",
                marker="o",
                facecolor="black")
    plt.text(Sgr[0] + off, Sgr[2] + off, "Sgr Core", fontsize=10)
    plt.plot([-30.0, 30.0], [0.0, 0.0], "k:")
    offset_x = [
        0.2, 0.0, 0.0, -0.2, 0.0, 0.0, 0.0, -0.5, 1.0, 1.0, 0.5, 0.75, 0.0,
        0.0, 0.5, 0.0, 0.0, 0.0
    ]
    offset_z = [
        0.0, 0.0, 0.0, -2.5, 0.0, 0.0, -2.0, 0.5, -1.0, -1.0, 0.25, -1.0, -0.5,
        0.0, -0.5, 0.0, 0.5, 0.5
    ]
    for i in range(len(stripes)):
        #plt.annotate(str(stripes[i]), xytext=(positions[i,0], positions[i,2]),
        #            xy=( (positions[i,0]+(vectors[i,0]*10.0)), (positions[i,2]+(vectors[i,2]*10.0)) ),
        #            arrowprops=dict(facecolor='black', arrowstyle="->") )
        if stripes[i] < 75: color = 'white'
        else: color = 'black'
        plt.arrow(positions[i, 0],
                  positions[i, 2],
                  vectors[i, 0] * 10.0,
                  vectors[i, 2] * 10.0,
                  width=0.25,
                  head_width=2.0,
                  facecolor=color)
        if stripes[i] < 20 or stripes[i] > 19:
            plt.text(positions[i, 0] + offset_x[i],
                     positions[i, 2] + offset_z[i],
                     r"$" + str(stripes[i]) + r"$",
                     fontsize=10)
    plt.xlabel(r"$X_{GC}$ (kpc)")
    plt.ylabel(r"$Z_{GC}$ (kpc)")
    plt.axis('equal')
    plt.xlim(-45, 45)
    plt.ylim(-40, 50)
    locs, labels = plt.xticks()
    for i in range(len(labels)):
        labels[i] = r"$" + str(locs[i]) + r"$"
    plt.xticks(locs, labels, fontsize=12)
    locs, labels = sc.arange(-40.0, 50.0, 20.0), []
    for i in range(len(locs)):
        labels.append(r"$" + str(locs[i]) + r"$")
    plt.yticks(locs, labels, fontsize=12)
    # done
    plt.show()
Exemplo n.º 37
0
def twoBody():
    # state for each body is [x, y] for position, [u, v] for speed
    # total state is [x1,y1,u1,v1,x2,y2,u2,v2]

    m1 = 1; m2 = 1; G = 1
    x0 = np.array([0., 0., 0., -1., 1, 0., 0.2, 0.2])
    # returns gravitational force from first object on second according
    # Newton's law of gravitation
    def gForce(x):
        r = x[0:2] - x[4:6]
        return (G * m1 * m2 / ((r[0]**2 + r[1]**2) ** (1.5))) * r

    def dx(t, x):
        r = gForce(x)
        return np.array([
            x[2],
            x[3],
            -r[0]/m1,
            -r[1]/m1,
            x[6],
            x[7],
            r[0]/m2,
            r[1]/m2,
        ])

    ode = ODE(0, x0)
    ode.dx = dx
    dt = 0.001
    iters = 6000
    method = "rk4"
    res = [deepcopy(ode)]
    for _ in range(iters):
        ode.evolve(dt, method=method)
        res.append(deepcopy(ode))
    x1s = [o.x[0] for o in res]
    y1s = [o.x[1] for o in res]
    x2s = [o.x[4] for o in res]
    y2s = [o.x[5] for o in res]
    ts = [o.t for o in res]
    plt.plot(x1s, y1s, '.-', markersize=0.7, linewidth=0.4, color='orange')
    plt.plot(x2s, y2s, '.-', markersize=0.7, linewidth=0.2, color='blue')

    X = res[0].x
    plt.arrow(X[0], X[1], X[2], X[3], color="orange", head_width=0.05)
    plt.arrow(X[4], X[5], X[6], X[7], color="blue", head_width=0.05)
    plt.text(X[0], X[1], r"$t=0$" +
                        "\n"
                        "$position=({},{})$".format(X[0], X[1])+
                        "\n" +
                        "$velocity=({},{})$".format(X[2], X[3]), fontsize=12,
                        color = "orange",
                        horizontalalignment='right',
                        verticalalignment='top')
    plt.text(X[4], X[6], r"$t=0$" +
                        "\n"
                        "$position=({},{})$".format(X[4], X[5]) +
                        "\n" +
                        "$velocity=({},{})$".format(X[6], X[7]), fontsize=12,
                        color = "blue",
                        horizontalalignment='left',
                        verticalalignment='bottom')
    plt.xlim(-3, 3)
    plt.ylim(-3, 3)
    legend1 = "Mass: {}, method: {}".format(m1, method)
    legend2 = "Mass: {}, ".format(m2) + r"$\Delta t=$" + "${}$".format(dt)
    plt.legend([legend1, legend2])
    plt.xlabel("$x$")
    plt.ylabel("$y$")
    plt.title(r"Two Body Motion for $t \in " + "[{}, {}]$".format(res[0].t, iters*dt))
    #plt.savefig("twoBody5.svg", format='svg')
    plt.show()
Exemplo n.º 38
0
y_random_position = [0, 0,  L1 * s1, L1 * s1 + L2 * s12, L1 * s1 + L2 * s12 + L3 * s123]
x_random_position = [0, L0, L0 + L1 * c1, L0 + L1 * c1 + L2 * c12, L0 + L1 * c1 + L2 * c12 + L3 * c123]

plt.plot(y_random_position, x_random_position, marker='o')
'''
#plt.grid()

#y_current = [L1 * s1 + L2 * s12 + L3 * s123, L1 * s1 + L2 * s12 + 170 * s123]
#x_current = [L0 + L1 * c1 + L2 * c12 + L3 * c123, L0 + L1 * c1 + L2 * c12 + 170 * c123]



#plt.plot(y_current, x_current)
plt.arrow(L1 * s1 + L2 * s12 + L3 * s123, L0 + L1 * c1 + L2 * c12 + L3 * c123,
          -(L1 * s1 + L2 * s12 + L3 * s123) + (L1 * s1 + L2 * s12 + 200 * s123),
          -(L0 + L1 * c1 + L2 * c12 + L3 * c123) + (L0 + L1 * c1 + L2 * c12 + 200 * c123),
         width = 5,
         head_length = 20)

print(Q1)
print(Q2)

plot_man_ik(Q1, Q2)



plt.xlim(-453.75, 453.75)
plt.ylim(0, 497.11)

plt.show()
Exemplo n.º 39
0
def plot_with_CFD_score(df, out_folder, guide):
    # Remove targets with mm+bul<=1 since they are probably on-target introduced by variants
    df = df.loc[df["Mismatches+bulges_(highest_CFD)"] > 1]

    # sort values to have highest scored target on top
    df.sort_values('CFD_score_(highest_CFD)', ascending=False, inplace=True)
    # keep top1000 targets
    df = df.head(1000)
    # Make index column that numbers the OTs starting from 1
    df.reset_index(inplace=True)
    index_count = 1
    for index in df.index:
        df.loc[index, 'index'] = index_count
        index_count += 1

    # If prim_AF = 'n', then it's a ref-nominated site, so we enter a fake numerical AF
    # This will cause a warning of invalid sqrt later on, but that's fine to ignore
    df["Variant_MAF_(highest_CFD)"] = df["Variant_MAF_(highest_CFD)"].fillna(
        -1)

    # If multiple AFs (haplotype with multiple SNPs), take min AF
    # Approximation until we have haplotype frequencies
    df["AF"] = df["Variant_MAF_(highest_CFD)"].astype(str).str.split(',')
    df["AF"] = df["AF"].apply(lambda x: min(x))
    df["AF"] = pd.to_numeric(df["AF"])

    # Adjustments for plotting purposes
    # so haplotypes that got rounded down to AF = 0 (min AF = 0.01) still appear in the plot
    df["plot_AF"] = df["AF"] + 0.001
    df["plot_AF"] *= 1000  # make points larger
    df["plot_AF"] = np.sqrt(df["plot_AF"])  # so size increase is linear

    # Calculate ref_AF as (1 – alt_AF)
    # Not precisely correct because there can be other non-ref haplotypes, but approximation should be accurate in most cases
    df["ref_AF"] = 1 - df["AF"]
    df["ref_AF"] *= 1000  # make points larger
    df["ref_AF"] = np.sqrt(df["ref_AF"])  # so size increase is linear

    # Transparent colors
    transparent_red = mcolors.colorConverter.to_rgba("red", alpha=0.5)
    transparent_blue = mcolors.colorConverter.to_rgba("blue", alpha=0.5)
    transparent_gray = mcolors.colorConverter.to_rgba("gray", alpha=0.5)
    """
    # Linear, annotated, top 100 (for supplement)
    # """

    # # Size legend
    s1 = mlines.Line2D([], [],
                       marker='o',
                       label='1',
                       linestyle='None',
                       markersize=math.sqrt(math.sqrt((1 + 0.001) * 1000)),
                       color='black')
    s01 = mlines.Line2D([], [],
                        marker='o',
                        label='0.1',
                        linestyle='None',
                        markersize=math.sqrt(math.sqrt((0.1 + 0.001) * 1000)),
                        color='black')
    s001 = mlines.Line2D([], [],
                         marker='o',
                         label='0.01',
                         linestyle='None',
                         markersize=math.sqrt(math.sqrt(
                             (0.01 + 0.001) * 1000)),
                         color='black')
    """
    Log, ref/alt, top 1000: for main text
    """
    # matplotlib plot settings
    plt.rcParams["figure.dpi"] = 600
    plt.rcParams["figure.figsize"] = 7.5, 2.25
    plt.rcParams.update({'font.size': 7})
    plt.rcParams['pdf.fonttype'] = 42
    plt.rcParams['ps.fonttype'] = 42

    # Plot data CFD SCORE
    ax = df.plot.scatter(x="index",
                         y="CFD_score_REF_(highest_CFD)",
                         s="ref_AF",
                         c=transparent_red,
                         zorder=1)
    # ax = df.plot.scatter(x="index", y="highest_CFD_score(ref)", s="ref_AF", c=transparent_red, zorder=1, ax=ax)
    df.plot.scatter(x="index",
                    y="CFD_score_ALT_(highest_CFD)",
                    s="plot_AF",
                    c=transparent_blue,
                    zorder=2,
                    ax=ax)
    ax.set_xscale("log")

    plt.xlabel("Candidate off-target site")
    plt.ylabel("CFD score")

    # Boundaries
    plt.xlim(xmin=0.9, xmax=1000)
    plt.ylim(ymin=0, ymax=1)

    # Arrows
    for x, y, z in zip(
            df["index"], df["CFD_score_REF_(highest_CFD)"],
            df["CFD_score_ALT_(highest_CFD)"] -
            df["CFD_score_REF_(highest_CFD)"]):
        plt.arrow(x,
                  y + 0.02,
                  0,
                  z - 0.04,
                  color='gray',
                  head_width=(x * (10**0.005 - 10**(-0.005))),
                  head_length=0.02,
                  length_includes_head=True,
                  zorder=0,
                  alpha=0.5)
        # +/- to avoid overlap of arrow w/ points, head_width calculated to remain constant despite log scale of x-axis

    # Size legend
    plt.gca().add_artist(
        plt.legend(handles=[s1, s01, s001],
                   title="Allele frequency",
                   ncol=3,
                   loc=9))

    # Color legend
    red = mpatches.Patch(color=transparent_red, label="Reference")
    blue = mpatches.Patch(color=transparent_blue, label="Alternative")
    plt.legend(handles=[red, blue])

    # Save
    plt.tight_layout()
    plt.savefig(out_folder +
                f"CRISPRme_CFD_top_1000_log_for_main_text_{guide}.png")
    plt.clf()
Exemplo n.º 40
0
def electre_i_v(dataset, V, W, remove_cycles=False, c_hat=0.75, graph=True):
    kernel = []
    dominated = []
    concordance = concordance_matrix(dataset, W)
    discordance = discordance_matrix(dataset, V)
    dominance = dominance_matrix(concordance,
                                 discordance,
                                 c_hat=c_hat,
                                 d_hat=0.5)
    if (remove_cycles == True):
        dominance = johnson_algorithm_cycles(dominance)
    row_sum = np.sum(dominance, axis=0)
    kernel = np.where(row_sum == 0)[0].tolist()
    for j in range(0, dominance.shape[1]):
        for i in range(0, len(kernel)):
            if (dominance[kernel[i], j] == 1):
                if (j not in dominated):
                    dominated.append(j)
    limit = len(kernel)
    for j in range(0, dominance.shape[1]):
        for i in range(0, limit):
            if (dominance[kernel[i], j] == 0
                    and np.sum(dominance[:, j], axis=0) > 0):
                if (j not in dominated and j not in kernel):
                    kernel.append(j)
    kernel = ['a' + str(alt + 1) for alt in kernel]
    dominated = ['a' + str(alt + 1) for alt in dominated]
    if (graph == True):
        for i in range(0, dominance.shape[0]):
            radius = 1
            node_x = radius * math.cos(math.pi * 2 * i / dominance.shape[0])
            node_y = radius * math.sin(math.pi * 2 * i / dominance.shape[0])
            if ('a' + str(i + 1) in kernel):
                plt.text(node_x,
                         node_y,
                         'a' + str(i + 1),
                         size=12,
                         ha='center',
                         va='center',
                         bbox=dict(
                             boxstyle='round',
                             ec=(0.0, 0.0, 0.0),
                             fc=(0.8, 1.0, 0.8),
                         ))
            else:
                plt.text(node_x,
                         node_y,
                         'a' + str(i + 1),
                         size=12,
                         ha='center',
                         va='center',
                         bbox=dict(
                             boxstyle='round',
                             ec=(0.0, 0.0, 0.0),
                             fc=(1.0, 0.8, 0.8),
                         ))
        for i in range(0, dominance.shape[0]):
            for j in range(0, dominance.shape[1]):
                node_xi = radius * math.cos(
                    math.pi * 2 * i / dominance.shape[0])
                node_yi = radius * math.sin(
                    math.pi * 2 * i / dominance.shape[0])
                node_xj = radius * math.cos(
                    math.pi * 2 * j / dominance.shape[0])
                node_yj = radius * math.sin(
                    math.pi * 2 * j / dominance.shape[0])
                if (dominance[i, j] == 1):
                    if ('a' + str(i + 1) in kernel):
                        plt.arrow(node_xi,
                                  node_yi,
                                  node_xj - node_xi,
                                  node_yj - node_yi,
                                  head_width=0.01,
                                  head_length=0.2,
                                  overhang=0.0,
                                  color='black',
                                  linewidth=0.9,
                                  length_includes_head=True)
                    else:
                        plt.arrow(node_xi,
                                  node_yi,
                                  node_xj - node_xi,
                                  node_yj - node_yi,
                                  head_width=0.01,
                                  head_length=0.2,
                                  overhang=0.0,
                                  color='red',
                                  linewidth=0.9,
                                  length_includes_head=True)
        axes = plt.gca()
        axes.set_xlim([-radius, radius])
        axes.set_ylim([-radius, radius])
        plt.axis('off')
        plt.show()
    return concordance, discordance, dominance, kernel, dominated
Exemplo n.º 41
0
    def render(self, mode='human', title=None):

        color_map = "gist_ncar"

        if title is None:
            title = self.env_name

        r, c = self.agent_location
        x2, y2 = 0, 0
        if self.agent_facing_str == 'NORTH':
            x2, y2 = 0, -0.01
        elif self.agent_facing_str == 'SOUTH':
            x2, y2 = 0, 0.01
        elif self.agent_facing_str == 'WEST':
            x2, y2 = -0.01, 0
        elif self.agent_facing_str == 'EAST':
            x2, y2 = 0.01, 0

        plt.figure(title, figsize=(9, 5))
        plt.imshow(self.map, cmap=color_map, vmin=0, vmax=len(self.items_id))
        plt.arrow(c, r, x2, y2, head_width=0.7, head_length=0.7, color='white')
        plt.title('NORTH', fontsize=10)
        plt.xlabel('SOUTH')
        plt.ylabel('WEST')
        plt.text(self.map_width, self.map_width // 2, 'EAST', rotation=90)
        # plt.text(self.map_size, self.map_size // 2, 'EAST', rotation=90)
        # plt.colorbar()
        # plt.grid()

        info = '\n'.join([
            "               Info:             ", "Env: " + self.env_name,
            "Steps: " + str(self.step_count),
            "Agent Facing: " + self.agent_facing_str,
            "Action: " + self.action_str[self.last_action],
            "Reward: " + str(self.last_reward), "Done: " + str(self.last_done)
        ])
        props = dict(boxstyle='round', facecolor='w', alpha=0.2)
        plt.text(-(self.map_width // 2) - 0.5,
                 2.25,
                 info,
                 fontsize=10,
                 bbox=props)  # x, y

        # plt.text(-(self.map_size // 2) - 0.5, 2.25, info, fontsize=10, bbox=props)  # x, y

        if self.last_done:
            you_win = "YOU WIN " + self.env_name + "!!!"
            props = dict(boxstyle='round', facecolor='w', alpha=1)
            # plt.text(0 - 0.1, (self.map_size // 2), you_win, fontsize=18, bbox=props)
            plt.text(0 - 0.1, (self.map_width // 2),
                     you_win,
                     fontsize=18,
                     bbox=props)

        cmap = get_cmap(color_map)

        legend_elements = [
            Line2D([0], [0],
                   marker="^",
                   color='w',
                   label='agent',
                   markerfacecolor='w',
                   markersize=12,
                   markeredgewidth=2,
                   markeredgecolor='k'),
            Line2D([0], [0], color='w', label="INVENTORY:")
        ]
        for item in sorted(self.inventory_items_quantity):
            rgba = cmap(self.items_id[item] / len(self.items_id))
            legend_elements.append(
                Line2D([0], [0],
                       marker="s",
                       color='w',
                       label=item + ': ' +
                       str(self.inventory_items_quantity[item]),
                       markerfacecolor=rgba,
                       markersize=16))
        plt.legend(handles=legend_elements,
                   bbox_to_anchor=(1.55, 1.02))  # x, y

        plt.tight_layout()
        plt.pause(0.01)
        plt.clf()
Exemplo n.º 42
0
def plot_with_MMvBUL(df, out_folder, guide):
    # Remove targets ref with mm+bul<=1 for on-targets and on-targets variant-induced
    df = df.loc[df["Mismatches+bulges_(fewest_mm+b)"] > 1]

    # new col to store the scoring value for non-SpCas9 targets
    df['Mismatches+bulges_REF_(fewest_mm+b)'] = 0
    df['Mismatches+bulges_ALT_(fewest_mm+b)'] = 0

    # compute analysis to reference_count_analysis
    df = df.apply(reference_count_analysis, axis=1)
    # df = df.apply(
    #     lambda row: reference_count_analysis(row), axis=1)

    # if col is alt calculate score for ref and alt, if ref skip
    # for index in df.index:
    #     if df.loc[index, 'REF/ALT_origin_(fewest_mm+b)'] == 'alt':
    #         refTarget = str(
    #             df.loc[index, 'Aligned_protospacer+PAM_REF_(fewest_mm+b)'])
    #         countMM = 0
    #         for nt in refTarget:
    #             if nt.islower():
    #                 countMM += 1
    #         df.loc[index, 'Mismatches+bulges_REF_(fewest_mm+b)'] = countMM + \
    #             int(df.loc[index, 'Bulges_(fewest_mm+b)'])
    #         df.loc[index, 'Mismatches+bulges_ALT_(fewest_mm+b)'] = df.loc[index,
    #                                                                       'Mismatches+bulges_(fewest_mm+b)']
    #     else:
    #         df.loc[index, 'Mismatches+bulges_REF_(fewest_mm+b)'] = df.loc[index,
    #                                                                       'Mismatches+bulges_(fewest_mm+b)']
    #         df.loc[index, 'Mismatches+bulges_ALT_(fewest_mm+b)'] = df.loc[index,
    #                                                                       'Mismatches+bulges_(fewest_mm+b)']

    # sort in order to have highest REF mm+bul on top
    df.sort_values('Mismatches+bulges_(fewest_mm+b)',
                   ascending=True,
                   inplace=True)
    # top1000 targets
    df = df.head(1000)
    # Make index column that numbers the OTs starting from 1
    df.reset_index(inplace=True)
    index_count = 1
    for index in df.index:
        df.loc[index, 'index'] = index_count
        index_count += 1
    # If prim_AF = 'n', then it's a ref-nominated site, so we enter a fake numerical AF
    # This will cause a warning of invalid sqrt later on, but that's fine to ignore
    # df["prim_AF"] = df["prim_AF"].fillna(-1)
    df["Variant_MAF_(fewest_mm+b)"] = df["Variant_MAF_(fewest_mm+b)"].fillna(
        -1)

    # If multiple AFs (haplotype with multiple SNPs), take min AF
    # Approximation until we have haplotype frequencies
    df["AF"] = df["Variant_MAF_(fewest_mm+b)"].astype(str).str.split(',')
    df["AF"] = df["AF"].apply(lambda x: min(x))
    df["AF"] = pd.to_numeric(df["AF"])

    # Adjustments for plotting purposes
    # so haplotypes that got rounded down to AF = 0 (min AF = 0.01) still appear in the plot
    df["plot_AF"] = df["AF"] + 0.001
    df["plot_AF"] *= 1000  # make points larger
    df["plot_AF"] = np.sqrt(df["plot_AF"])  # so size increase is linear

    # Calculate ref_AF as (1 – alt_AF)
    # Not precisely correct because there can be other non-ref haplotypes, but approximation should be accurate in most cases
    df["ref_AF"] = 1 - df["AF"]
    df["ref_AF"] *= 1000  # make points larger
    df["ref_AF"] = np.sqrt(df["ref_AF"])  # so size increase is linear

    # Transparent colors
    transparent_red = mcolors.colorConverter.to_rgba("red", alpha=0.5)
    transparent_blue = mcolors.colorConverter.to_rgba("blue", alpha=0.5)
    transparent_gray = mcolors.colorConverter.to_rgba("gray", alpha=0.5)

    # # Size legend
    s1 = mlines.Line2D([], [],
                       marker='o',
                       label='1',
                       linestyle='None',
                       markersize=math.sqrt(math.sqrt((1 + 0.001) * 1000)),
                       color='black')
    s01 = mlines.Line2D([], [],
                        marker='o',
                        label='0.1',
                        linestyle='None',
                        markersize=math.sqrt(math.sqrt((0.1 + 0.001) * 1000)),
                        color='black')
    s001 = mlines.Line2D([], [],
                         marker='o',
                         label='0.01',
                         linestyle='None',
                         markersize=math.sqrt(math.sqrt(
                             (0.01 + 0.001) * 1000)),
                         color='black')
    """
    Log, ref/alt, top 1000: for main text
    """
    # matplotlib plot settings
    plt.rcParams["figure.dpi"] = 600
    plt.rcParams["figure.figsize"] = 7.5, 2.25
    plt.rcParams.update({'font.size': 7})
    plt.rcParams['pdf.fonttype'] = 42
    plt.rcParams['ps.fonttype'] = 42

    # Plot data
    ax = df.plot.scatter(x="index",
                         y="Mismatches+bulges_REF_(fewest_mm+b)",
                         s="ref_AF",
                         c=transparent_red,
                         zorder=1)

    # ax = df.plot.scatter(x="index", y="highest_CFD_score(ref)", s="ref_AF", c=transparent_red, zorder=1, ax=ax)
    df.plot.scatter(x="index",
                    y="Mismatches+bulges_ALT_(fewest_mm+b)",
                    s="plot_AF",
                    c=transparent_blue,
                    zorder=2,
                    ax=ax)

    ax.set_xscale("log")
    # plt.title("Top CRISPRme-identified sites for sgRNA 1617")
    plt.xlabel("Candidate off-target site")
    plt.ylabel("Mismatches+Bulges")

    # Boundaries
    plt.xlim(xmin=0.9, xmax=1000)
    # plt.ylim(ymin=0, ymax=1)

    # Arrows
    for x, y, z in zip(
            df["index"], df["Mismatches+bulges_REF_(fewest_mm+b)"],
            df["Mismatches+bulges_ALT_(fewest_mm+b)"] -
            df["Mismatches+bulges_REF_(fewest_mm+b)"]):
        plt.arrow(x,
                  y + 0.02,
                  0,
                  z - 0.04,
                  color='gray',
                  head_width=(x * (10**0.005 - 10**(-0.005))),
                  head_length=0.02,
                  length_includes_head=True,
                  zorder=0,
                  alpha=0.5)
        # +/- to avoid overlap of arrow w/ points, head_width calculated to remain constant despite log scale of x-axis

    # Size legend
    plt.gca().add_artist(
        plt.legend(handles=[s1, s01, s001],
                   title="Allele frequency",
                   ncol=3,
                   loc=9))

    # Color legend
    red = mpatches.Patch(color=transparent_red, label="Reference")
    blue = mpatches.Patch(color=transparent_blue, label="Alternative")
    plt.legend(handles=[red, blue])

    # Save
    plt.tight_layout()
    plt.savefig(out_folder +
                f"CRISPRme_fewest_top_1000_log_for_main_text_{guide}.png")
    plt.clf()
Exemplo n.º 43
0
# Train random forest classifier, calibrate on validation data and evaluate
# on test data
clf = RandomForestClassifier(n_estimators=25)
clf.fit(X_train, y_train)
clf_probs = clf.predict_proba(X_test)
sig_clf = CalibratedClassifierCV(clf, method="sigmoid", cv="prefit")
sig_clf.fit(X_valid, y_valid)
sig_clf_probs = sig_clf.predict_proba(X_test)
sig_score = log_loss(y_test, sig_clf_probs)

# Plot changes in predicted probabilities via arrows
plt.figure()
colors = ["r", "g", "b"]
for i in range(clf_probs.shape[0]):
    plt.arrow(clf_probs[i, 0], clf_probs[i, 1],
              sig_clf_probs[i, 0] - clf_probs[i, 0],
              sig_clf_probs[i, 1] - clf_probs[i, 1],
              color=colors[y_test[i]], head_width=1e-2)

# Plot perfect predictions
plt.plot([1.0], [0.0], 'ro', ms=20, label="Class 1")
plt.plot([0.0], [1.0], 'go', ms=20, label="Class 2")
plt.plot([0.0], [0.0], 'bo', ms=20, label="Class 3")

# Plot boundaries of unit simplex
plt.plot([0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], 'k', label="Simplex")

# Annotate points on the simplex
plt.annotate(r'($\frac{1}{3}$, $\frac{1}{3}$, $\frac{1}{3}$)',
             xy=(1.0/3, 1.0/3), xytext=(1.0/3, .23), xycoords='data',
             arrowprops=dict(facecolor='black', shrink=0.05),
             horizontalalignment='center', verticalalignment='center')
Exemplo n.º 44
0
plt.xticks([], [])
plt.yticks([], [])
plt.axis("off")
plt.gca().set_aspect("equal")
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())

# draw arrows
hw = 0.020
hl = 0.02
c = axis_color
plt.arrow(0,
          0,
          1.05,
          0,
          head_width=hw,
          head_length=hl,
          length_includes_head=True,
          ec=c,
          fc=c)
plt.arrow(0,
          0,
          -1.05,
          0,
          head_width=hw,
          head_length=hl,
          length_includes_head=True,
          ec=c,
          fc=c)

# draw ticks
Exemplo n.º 45
0
ax.plot(X1_ellipse, X2_ellipse_2, 'r')
# Plot the points found during the iterations
ax.plot(points_x, points_y, 'b')
# Plot the point that minimized the function (analitycally found)
ax.plot(veps[0, idx], veps[1, idx], 'go')
# Save the current figure
plt.savefig('../Images/03-pca-analysis-numerical.png')

# Create a new figure
fig = plt.figure()
# Split the figure in 1*1 (nrows*ncols) subaxes and create a new suplot positioned at 1 (plot_number)
nrows = 1
ncols = 1
plot_number = 1
ax = fig.add_subplot(nrows, ncols, plot_number)
# Set the labels for the axes
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
# Plot the samples
ax.plot(c1[:, 0], c1[:, 1], 'r.')
# Plot the eigenvector related to the maximum eigenvalue
plt.arrow(np.mean(c1[:, 0]),
          np.mean(c1[:, 1]),
          vaps[idx] * veps[0, idx],
          vaps[idx] * veps[1, idx],
          0.5,
          linewidth=1,
          head_width=0.1,
          color='blue')
# Save the current figure
plt.savefig('../Images/03-pca-analysis-scatterplot.png')
Exemplo n.º 46
0
    def render_scene(self):

        while True:

            yield self.env.timeout(1)
            number_agvs = len(self.global_robot_list.items)
            ax = plt.subplot2grid((1, number_agvs + 3), (0, 0), colspan=3)
            plt.subplots_adjust(wspace=1.5, hspace=0.4)
            plt.title("agv Layout")
            plt.style.use('dark_background')

            # Plot Graph
            self.graph.plot(ax)

            # Plot AGVs
            for robot in self.global_robot_list.items:
                color = self.colors[robot.ID - 1]
                plt.plot(robot.robot_location[0],
                         robot.robot_location[1],
                         color=color,
                         marker='o',
                         ms=10)
                plt.arrow(robot.robot_location[0],
                          robot.robot_location[1],
                          math.cos(robot.heading_direction),
                          math.sin(robot.heading_direction),
                          width=0.3,
                          color=color)
                plt.text(robot.robot_location[0] + 0.5,
                         robot.robot_location[1] + 1.5,
                         str("agv" + str(robot.ID)))

                # Plot path
                if robot.path:
                    node_pos = self.kb['graph'].nodes[robot.path[0]].pos
                    plt.plot([robot.robot_location[0], node_pos[0]],
                             [robot.robot_location[1], node_pos[1]],
                             color=color,
                             lw=3.5)
                    for i in range(len(robot.path)):
                        node_pos = self.kb['graph'].nodes[robot.path[i]].pos
                        plt.plot(node_pos[0],
                                 node_pos[1],
                                 color=color,
                                 marker='.',
                                 ms=15)
                        if i < len(robot.path) - 1:
                            node_pos_ = self.kb['graph'].nodes[robot.path[
                                i + 1]].pos
                            plt.plot([node_pos[0], node_pos_[0]],
                                     [node_pos[1], node_pos_[1]],
                                     color=color,
                                     lw=3.5)

                # Plot total path
                if robot.total_path:
                    for i in range(len(robot.total_path)):
                        node_pos = self.kb['graph'].nodes[
                            robot.total_path[i]].pos
                        plt.plot(node_pos[0],
                                 node_pos[1],
                                 color=color,
                                 marker='.',
                                 ms=15)
                        if i < len(robot.total_path) - 1:
                            node_pos_ = self.kb['graph'].nodes[
                                robot.total_path[i + 1]].pos
                            plt.plot([node_pos[0], node_pos_[0]],
                                     [node_pos[1], node_pos_[1]],
                                     color=color,
                                     lw=1.5)

                # Plot assigned tasks
                for key in self.kb.keys():
                    if key == 'local_task_list_R' + str(robot.ID):
                        list_ = self.kb[key]
                        for item in list_.items:
                            node_pos = self.kb['graph'].nodes[item.pos_A].pos
                            plt.plot(node_pos[0], node_pos[1], 'bs', ms=7)
                            plt.text(node_pos[0] - 1, node_pos[1] + 1.5,
                                     str(item.order_number))
                            plt.plot([robot.robot_location[0], node_pos[0]],
                                     [robot.robot_location[1], node_pos[1]],
                                     color=color,
                                     lw=0.5)

            # Plot tasks executing
            for task in self.tasks_executing.items:
                node_pos = self.kb['graph'].nodes[task.pos_A].pos
                plt.plot(node_pos[0], node_pos[1], 'rs', ms=7)
                plt.text(node_pos[0] - 1, node_pos[1] + 1.5,
                         str(task.order_number))

            # Plot tasks in global task list
            for task in self.global_task_list.items:
                node_pos = self.kb['graph'].nodes[task.pos_A].pos
                plt.plot(node_pos[0], node_pos[1], 'gs', ms=7)
                plt.text(node_pos[0] - 1, node_pos[1] + 1.5,
                         str(task.order_number))

            # Plot
            plt.draw()
            plt.pause(0.0001)
            plt.clf()
            plt.tight_layout()
Exemplo n.º 47
0
import matplotlib.pyplot as plt
import numpy as np
import math

a = np.loadtxt("/home/ljq/qt/RS_Lib/1.txt")
f = plt.figure()
ax = f.add_subplot(111)
ax.set(xlim=[0, 10], ylim=[0, 10])

plt.plot(a[0, 0], a[0, 1], 'ro')
plt.arrow(a[0, 0],
          a[0, 1],
          1.0 * math.cos(a[0, 2]),
          1.0 * math.sin(a[0, 2]),
          fc="r",
          ec="k",
          head_width=0.5,
          head_length=0.5)
plt.plot(a[len(a) - 1, 0], a[len(a) - 1, 1], 'yo')
plt.arrow(a[len(a) - 1, 0],
          a[len(a) - 1, 1],
          1.0 * math.cos(a[len(a) - 1, 2]),
          1.0 * math.sin(a[len(a) - 1, 2]),
          fc="r",
          ec="k",
          head_width=0.5,
          head_length=0.5)
plt.plot(a[:, 0], a[:, 1], '-')
plt.show()
Exemplo n.º 48
0
def main(arg):
    if (len(arg)) == 1:
        print "Usage: {0} input\n".format(arg[0])
        exit()
    
    p = 1
    fig = plt.figure(figsize=(7, 7))
    for file_in in arg[1:]:
        
        avg = []
        # try:
        with open(file_in, "r") as csvfile:
            #sorry to use blah, but I blanked on a name for this latest temp
            dialect = csv.excel
            dialect.skipinitialspace = True
            blah = csv.reader(csvfile, dialect=dialect)

            for row in blah:
                r = map(float, row)
                avg.append(100.0*r[0])

        if (len(avg) == 0):
            continue
        print len(avg)
        if (p <= 28):
            if (len(arg) == 2):
                ax = plt.subplot(1,1, p)
            else:
                ax = plt.subplot(7,4, p)
            #ax = plt.subplot(2,2, p)
            #plt.ylim(0,24)
            box = ax.get_position()
            ax.set_position([box.x0, box.y0, box.width, box.height*0.8])
            x_val = range(0, (len(avg)))
            x_val_exp = []
            for x in x_val:
                x_val_exp.append(math.pow(2, x+10))
            plt.plot(x_val_exp, avg)
            if (len(arg) == 2):
                plt.xticks(fontsize=12)
                plt.yticks(fontsize=12)
                plt.rc('font', size=12)
            else:
                plt.xticks(fontsize=5)
                plt.yticks(fontsize=5)
                plt.rc('font', size=5)
                ax.set_xscale('log', basex=2)
                #plt.ticklabel_format(axis='x', style='plain')
                for tick in ax.xaxis.get_major_ticks():
                    tick.label.set_rotation('vertical')
            
            if 0 == 1:
                #Approach 2 - Project points based on a uniformly decreasing line
                ideal_m = (avg[-1] - avg[0]) / len(avg)
                culum = avg[0]
                proj = []
                for a in avg:
                    proj.append(a - culum)
                    culum += ideal_m
                accel = []
                last = 0
                for pr in proj:
                    accel.append(pr - last)
                    last = pr
                #plt.plot(range(10,10 + (len(avg))), proj)
                #plt.plot(range(10,10 + (len(avg))), accel)
                i = 0
                last = 0
                first_green = 0
                first_red = 0
                for a in accel:
                    if i == 0:
                        i += 1
                        last = a
                        continue
                    if last / a < 0: #is last > 0 and a < 0 or vis versa
                        if (a > 0):
                            c = 'r'
                            if (first_red == 0):
                                first_red = i
                        else:
                            c = 'g'
                            if (first_green == 0):
                                first_green = i
                      #  plt.axvline(i - 1 + 10, linewidth=1.25, color=c)
                    last = a
                    i += 1
                
                arrow_pt = 0
                if (first_green == 0 or first_red < first_green):
                    arrow_pt = first_red
                else:
                    arrow_pt = first_green
                    
                if (arrow_pt < 3):
                    arrow_pt = 3
                arrow_val = avg[arrow_pt]
                arrow_pt = math.pow(2, arrow_pt)
                
                plt.arrow(arrow_pt, arrow_val, arrow_pt, arrow_val + 1)
                plt.axvline(arrow_pt, linewidth=1.25, color='r')
            
            harmony_l = file_in.split('/')
            file_in = harmony_l[-1]
            harmony_l = file_in.split('.')
            file_in = harmony_l[-2]
            plt.title(file_in, fontsize=5)
        p += 1
#    plt.subplots_adjust(left=0.1, right =(0.1*max_threads))
    plt.savefig( "temp.pdf")
    plt.savefig( "temp.png")