示例#1
0
def photogeneration(loc):
    arl = 0.10
    sep = 0.05
    arprop = dict(mutation_scale=10,
                  lw=1, arrowstyle="-|>", 
                  zorder=20)
    x, y, z = loc
    
    #electron
    electron, = ax.plot3D([x-sep/2], [y], [z],
                          c='c', marker='$-$', markersize=7, ls='none')
    v = ((x-sep/2,x-sep/2), (y,y), (z+0.02, z+arl))
    ar = Arrow3D(*v, color='c', **arprop)
    ax.add_artist(ar)
    
    #hole
    hole, = ax.plot3D([x+sep/2], [y], [z],
              c='r', marker='$+$', markersize=7, ls='none')
    v = ((x+sep/2,x+sep/2), (y,y), (z-0.02, z-arl))
    ar = Arrow3D(*v, color='r', **arprop)
    ax.add_artist(ar)
    
    #photon
    draw_photon(ax, (0,0,1), location=(x,y,z-0.35), length=0.3, amplitude=0.02)
    
    #encircle
    ell = Ellipse((x,y), 2.5*sep, 2.5*sep, ls=':', ec='y', fc='none', lw=1)
    art3d.pathpatch_2d_to_3d(ell, z, 'z')
    ell._path2d = ell._path
    ax.add_patch(ell)
    
    return electron, hole
示例#2
0
def plot_track(track_obj, dim):
    fig = plt.figure()
    
    
    if dim == '2d':
        ax = plt.plot(track_obj.x, track_obj.y)
    elif dim == '3d':
        #ax = fig.gca(projection = '3d') 
        #ax = fig.add_subplot(111, projection='3d')
        ax = Axes3D(fig)
        #Draw Runway
        rwy = Rectangle((-1250.529, 1166.953), 3021.95, 61, angle=-3, color='grey') #angle=350.12 angle=-9.88
        ax.add_patch(rwy)
        art3d.pathpatch_2d_to_3d(rwy, z=0,zdir="z")
        
        ax.plot(track_obj.x, track_obj.y, zs = track_obj.z)
    elif dim == '3da':
        ax = fig.gca(projection = '3d')
        u = 1; v = 1; w = 1;
        ax.quiver(track_obj.x, track_obj.y, track_obj.z, u, v, w, length = 100) #self.s)
    ax.set_aspect('equal')
    ax.set_xlim(-2000,20000)
    ax.set_ylim(-3000,5000)
    ax.set_zlim(0,1500)
    plt.show()
示例#3
0
def make_path_plot_3d():
    fig1 = plt.figure()
    ax = fig1.gca(projection='3d')

    for i in os.listdir(obstacleFolder):
        obstaclePath = obstacleFolder + i

        ob = np.loadtxt(obstaclePath)
        ob = np.vstack((ob, ob[0, :]))
        CH = Delaunay(ob).convex_hull
        x,y,z = ob[:,0],ob[:,1],ob[:,2]

        S = ax.plot_trisurf(x,y,z,triangles=CH,shade=True,cmap=cm.copper,lw=0.2)

    txt = np.loadtxt(rrtPath)
    start = txt[0,0:2]
    goal = txt[-1,0:2]

    startCircle = Circle(start,2,color='g')
    goalCircle = Circle(goal,2,color='r')
    ax.add_patch(startCircle)
    ax.add_patch(goalCircle)
    art3d.pathpatch_2d_to_3d(startCircle,z=txt[0,2],zdir='y')
    art3d.pathpatch_2d_to_3d(goalCircle,z=txt[-1,2],zdir='y')

    plt.plot(txt[:, 0], txt[:, 1], txt[:,2], 'bo-', markersize=10, linewidth=3)
示例#4
0
    def pitches_by_type(self, pitcher, pitch_type=None):
        pitch_types = self.db.get_pitch_types(pitcher_id=pitcher.pid)

        fig = plt.figure()
        ax = fig.add_subplot(111, projection="3d")

        pitch_count = 0
        sz_bot = self.db.get_average_for_pitches(entities.Pitch.sz_bot, pitcher.pid, pitch_type)[0]
        sz_top = self.db.get_average_for_pitches(entities.Pitch.sz_top, pitcher.pid, pitch_type)[0]

        for t in pitch_types:
            if pitch_type is not None and not t[0] == pitch_type:
                LOG.info("Type [%s] does not match selected type [%s]", t[0], pitch_type)
                continue

            pitches = self.db.get_pitches(
                pitcher_id=pitcher.pid, pitch_type=t[0])

            lines = []
            for pitch in pitches:
                if pitch.x0 is None or \
                                pitch.y0 is None or \
                                pitch.z0 is None or \
                                pitch.px is None or \
                                pitch.pz is None or \
                                pitch.vx0 is None or \
                                pitch.vy0 is None or \
                                pitch.vz0 is None or \
                                pitch.ax is None or \
                                pitch.ay is None or \
                                pitch.az is None:
                    continue

                t_to_catcher = (- pitch.vy0 - math.sqrt((pitch.vy0**2)-2*pitch.ay*(pitch.y0-0))) / pitch.ay
                pitch_line = [(pitch.x0 + pitch.vx0 * t + pitch.ax * t**2 / 2,
                               pitch.y0 + pitch.vy0 * t + pitch.ay * t**2 / 2,
                               pitch.z0 + pitch.vz0 * t + pitch.az * t**2 / 2)
                              for t in numpy.linspace(0, t_to_catcher)]
                lines.append(pitch_line)
            ax.add_collection(Line3DCollection(lines, label=t[0], linewidths=1, alpha=0.5, colors=next(ax._get_lines.prop_cycler)['color']))

            pitch_count += len(pitches)

        strikezone = patches.Rectangle((-0.7083, sz_bot), 0.7083 * 2, sz_top - sz_bot, fill=False, label="Strikezone")

        ax.add_patch(strikezone)
        art3d.pathpatch_2d_to_3d(strikezone, z=1.417, zdir="y")
        ax.set_xlim(-0.7083 * 4, 0.7083 * 4)
        ax.set_ylim(0, 50)
        ax.set_zlim(-1, sz_top * 2)
        ax.set_title("Pitch Location by type for " + str(pitcher))
        ax.legend()
        LOG.info("Evaluated [%i] pitches", pitch_count)
        plt.show(block=True)
示例#5
0
文件: tree.py 项目: ee08b397/hypy
 def scatter_plot(self, equators=True, tagging=True, depth_cap=None):
     if depth_cap is None:
         depth_cap = self.height
     fig = plt.figure(figsize=(12, 10))
     ax = fig.add_subplot(111, projection="3d")
     plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
     xs = [self.nodes[self.root].coord.x]
     ys = [self.nodes[self.root].coord.y]
     zs = [self.nodes[self.root].coord.z]
     plot_color_board = ["blue", "red", "yellow", "green", "black"]
     font0 = FontProperties()
     font0.set_size(8)
     current_generation = deque([self.root])
     next_generation = True
     while next_generation:
         next_generation = deque()
         while current_generation:
             n = current_generation.popleft()
             if self.nodes[n].depth <= depth_cap:
                 xs.append(self.nodes[n].coord.x)
                 ys.append(self.nodes[n].coord.y)
                 zs.append(self.nodes[n].coord.z)
                 if tagging:
                     ax.text(self.nodes[n].coord.x + 0.01,
                             self.nodes[n].coord.y + 0.01,
                             self.nodes[n].coord.z + 0.01,
                             ("n{0}".format(n)), fontproperties=font0)
             for child in self.nodes[n].children:
                 next_generation.append(child)
                 if self.nodes[n].depth <= depth_cap:
                     xe = [self.nodes[n].coord.x, self.nodes[child].coord.x]
                     ye = [self.nodes[n].coord.y, self.nodes[child].coord.y]
                     ze = [self.nodes[n].coord.z, self.nodes[child].coord.z]
                     ax.plot(xe, ye, ze, plot_color_board[self.nodes[n].depth % 5])
         current_generation = next_generation
     ax.scatter(xs, ys, zs, c="r", marker="o")
     global_radius = self.nodes[self.root].radius * 1.12
     if equators:
         for axis in ["x", "y", "z"]:
             circle = Circle((0, 0), global_radius * 1.1)
             circle.set_clip_box(ax.bbox)
             circle.set_edgecolor("gray")
             circle.set_alpha(0.3)
             circle.set_facecolor("none")  # "none" not None
             ax.add_patch(circle)
             art3d.pathpatch_2d_to_3d(circle, z=0, zdir=axis)
     ax.set_xlim([-1.2 * global_radius, 1.2 * global_radius])
     ax.set_ylim([-1.2 * global_radius, 1.2 * global_radius])
     ax.set_zlim([-1.2 * global_radius, 1.2 * global_radius])
     ax.set_xlabel("X Label")
     ax.set_ylabel("Y Label")
     ax.set_zlabel("Z Label")
     plt.show()
示例#6
0
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
    x, y, z = xyz
    if zdir == "y":
        xy1, z1 = (x, z), y
    elif zdir == "y":
        xy1, z1 = (y, z), x
    else:
        xy1, z1 = (x, y), z
    text_path = TextPath((0, 0), s, size=size, usetex=usetex)
    trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])
    p1 = PathPatch(trans.transform_path(text_path), **kwargs)
    ax.add_patch(p1)
    art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
    def show(self,label="Translations",label_q="Quaternions"):
        """
            Display the transforms on a 3d plot.
        """
        self.transform_transforms(self.plane_to_yz_transform)
        self.transform_transforms(self.flatten_transform)

        fig = plt.figure(label)
        fig2 = plt.figure(label_q)
        ax = fig.add_subplot(111,projection="3d",aspect=1)
        ax_quats = fig2.add_subplot(111,projection="3d",aspect=1)
        
        x = []; y = []; z = []
        q_x = []; q_y = []; q_z = []
        x_n = []; y_n = []; z_n = []
        for translation,transform in zip(self.translations,self.transforms)[0::self.skip]:
            if transform.is_valid:
                x.append(translation[0])
                y.append(translation[1])
                z.append(translation[2])
            if not transform.is_valid:
                x_n.append(translation[0])
                y_n.append(translation[1])
                z_n.append(translation[2])
            q_x.append(transform.q[0])
            q_y.append(transform.q[1])
            q_z.append(transform.q[2])
        ax.scatter(x,y,z,color="b",s=200)
        ax.scatter(x_n,y_n,z_n,color="r",s=200)
        ax_quats.scatter(q_x,q_y,q_z,color="g",s=200)

        if self.show_transform_axis:
            for t in self.transforms[0::self.skip]:
                a = Axis3D(t.transform)
                for arrow in a.arrows:
                    ax.add_artist(arrow)

        circle_axis = Arrow3D((0,self.circle.axis[0]),(self.circle.origin[1],self.circle.origin[1]+self.circle.axis[1]),(self.circle.origin[2],self.circle.origin[2]+self.circle.axis[2]),mutation_scale=20,lw=3,arrowstyle="-|>", color="g")
        ax.add_artist(circle_axis)

        circle = matplotlib.patches.Circle((self.circle.origin[1], self.circle.origin[2]), self.circle.radius,fill=False)
        ax.add_patch(circle)

        art3d.pathpatch_2d_to_3d(circle, z=0, zdir="x")
        ax.auto_scale_xyz([-.5, .5], [-.5, .5], [-0, 1])
        ax_quats.auto_scale_xyz([-.5, .5], [-.5, .5], [-0, 1])
        plt.show()

        self.transform_transforms(self.flatten_transform,inverse=True)
        self.transform_transforms(self.plane_to_yz_transform,inverse=True)
def plot_baseline_landscape_overlay(dlg, data, subj_id, trial_no):  
    dlp = dl_plotter.DLPlotter(elev=55, azim=-65)
        
    x_grid, y_grid, dl = dlg.get_model_dl(dlg.model.get_baseline_params()*4)
    x=(x_grid[1:]+x_grid[:-1])/2
    y=(y_grid[1:]+y_grid[:-1])/2
    f = interpolate.interp2d(x,y,dl,kind='cubic')
    
    ax = dlp.plot_surface(x_grid, y_grid, dl, cmap=cm.viridis, alpha=0.9)
    
    ax.set_xticks([-1, -0.5, 0, 0.5, 1])
    ax.set_yticks([0, 0.5, 1])
    
    ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
    ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
    ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
    
    ax.w_zaxis.set_ticklabels([])
    
    sns.set_style('white')
    
    cmap = cm.viridis
    traj_color = cmap(0.1)    
    trajectory = data.loc[subj_id, trial_no]
    z = f(trajectory.x.values, trajectory.y.values)
    if trajectory.x.values[-1]>0:
        z= np.diag(z)
    else:
        z=np.diag(np.fliplr(z))
    
    # plot trajectory on a surface
    ax.plot(trajectory.x.values, trajectory.y.values, z, color='black', alpha=0.5)
    
    # plot marble 
    ax.plot([0.], [0.], [0.], marker='o', markersize=15, color = 'black', alpha=0.7)
    ax.plot([trajectory.x.values[-1]], [trajectory.y.values[-1]], [z[-1]], 
            marker='o', markersize=15, color='black', alpha=0.7)
    
    # draw screen above the surface and choice options on it
    patches = get_choice_patches()
    for patch in patches:
        ax.add_patch(patch)
        art3d.pathpatch_2d_to_3d(patch, z=0, zdir='z')
        
    # plot trajectory on a screen
    ax.plot(trajectory.x, trajectory.y, zs=0, zdir='z', color=traj_color, ls='none', 
            alpha=1.0, marker='o', ms=15, markerfacecolor='none', markeredgewidth=2, 
            markeredgecolor=traj_color, label='Mouse trajectory')
    plt.savefig('figures/baseline_dlv.pdf')
示例#9
0
def _trimesh(ax, t, x, y, z, **kwargs):
    """Display a 3D triangular mesh.

    Ignores ax._hold.
    """
    from mpl_toolkits.mplot3d.art3d import pathpatch_2d_to_3d
    patches = []
    code = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]
    for f in t:
        bdry = np.take(f, range(4), mode='wrap')
        pp = PathPatch(Path(np.column_stack((x[bdry], y[bdry])), code),
                       **kwargs)
        ax.add_patch(pp)
        pathpatch_2d_to_3d(pp, z[bdry])
        patches.append(pp)
    return patches
示例#10
0
def plot_3D_cylinder(ax, radius, height, elevation=0, resolution=200, color='r', x_center=0, y_center=0):
    x = np.linspace(x_center - radius, x_center + radius, resolution)
    z = np.linspace(elevation, elevation + height, resolution)
    X, Z = np.meshgrid(x, z)

    Y = np.sqrt(radius ** 2 - (X - x_center) ** 2) + y_center  # Pythagorean theorem

    ax.plot_surface(X, Y, Z, linewidth=0, color=color)
    ax.plot_surface(X, (2 * y_center - Y), Z, linewidth=0, color=color)

    floor = Circle((x_center, y_center), radius, color=color)
    ax.add_patch(floor)
    art3d.pathpatch_2d_to_3d(floor, z=elevation, zdir="z")

    ceiling = Circle((x_center, y_center), radius, color=color)
    ax.add_patch(ceiling)
    art3d.pathpatch_2d_to_3d(ceiling, z=elevation + height, zdir="z")
示例#11
0
def show_stars(dt, range, count_show_with_legend, plot_name, scatter=False):
    ax = plt.subplot(111, projection='3d')

    ax.plot((0,), (0,), (0,), 'o', color='orange', markersize=10, label='sun')

    ax.plot([0, range], [0, 0], [0, 0], label='to galaxy center')

    arc = Arc((27200, 0, 0), SUN_TO_CENTER_DISTANCE * 2, SUN_TO_CENTER_DISTANCE * 2,
              theta1=180 - np.degrees(range / SUN_TO_CENTER_DISTANCE),
              theta2=180 + np.degrees(range / SUN_TO_CENTER_DISTANCE))
    ax.add_patch(arc)
    art3d.pathpatch_2d_to_3d(arc, z=0)

    ax.plot([0, polaris["x"][0]], [0, polaris["y"][0]], [0, polaris["z"][0]], label='polaris')

    if scatter:
        ax.scatter(dt['x'], dt['y'], dt['z'], c=dt['vmag'], cmap=plt.cm.Spectral)
    else:
        counter = 0

        for r in dt:
            marker = mlines.Line2D.filled_markers[counter % mlines.Line2D.filled_markers.__len__()]

            if counter < count_show_with_legend:
                ax.plot([r["x"]], [r["y"]], [r["z"]], 'o',
                        label=r["name"] + " " + str(r["vmag"]) + " " + str(int(r["dist"])) + "ly",
                        markersize=5, marker=marker)
            else:
                ax.plot([r["x"]], [r["y"]], [r["z"]], '.', markersize=2)

            counter += 1

        try:
            ax.legend(numpoints=1, fontsize=10)  # call with fontsize fails on debian 7
        except:
            ax.legend(numpoints=1)


    ax.set_xlabel('ly')
    ax.set_ylabel('ly')
    ax.set_zlabel('ly')

    ax.auto_scale_xyz([-range, range], [-range, range], [-range, range])

    show_maximized_plot(plot_name)
示例#12
0
def angle(ax, angle_center=(0, 0, 0), starting_angle=0.0, ending_angle=75, angle_width=0.1, angle_height=0.1):
    p = Arc(angle_center[0:2], angle_width, angle_height, theta1=starting_angle, theta2=ending_angle)
    ax.add_patch(p)
    art3d.pathpatch_2d_to_3d(p, z=angle_center[-1], zdir="y")
#examples below:
#ellipsoid(ax, 10,20,10)
#cylinder(ax, length=10, color='g', direction='y')
#box(ax, 5,10,5)
#ellipse(ax, rad_x=2, direction='x')

## Angle example:
#add_arrow3d(ax, [0.5, 0.75], [1, 1], [0, 1])
#plane(ax, color='r')
#angle(ax, (0.5, 0, 1), angle_width=0.5, angle_height=0.5)


#ax.set_axis_off()
#plt.show()
示例#13
0
def _plot_grid3d(ax, grid, bbox, planes):
    """Plots a 3D LB lattice.

    :param ax: matplotlib Axes object to use for plotting
    :param grid: Sailfish grid object to illustrate
    :param bbox: if True, draw a blue 3D bounding box around the plot
    :param planes: if True, draws planes passing through the origin
    """
    assert grid.dim == 3
    bb = 0
    for ei in grid.basis[1:]:
        a = Arrow3D(
            *zip((0, 0, 0), [float(x) * 1.05 for x in ei]),
            color='k',
            arrowstyle='-|>',
            mutation_scale=10,
            lw=1)
        ax.add_artist(a)
        bb = max(bb, max([int(x) for x in ei]))

    for i in ('x', 'y', 'z'):
        c = Circle((0, 0), radius=0.05, color='k')
        ax.add_patch(c)
        art3d.pathpatch_2d_to_3d(c, z=0, zdir=i)

    ax.set_xlim(-bb, bb)
    ax.set_ylim(-bb, bb)
    ax.set_zlim(-bb, bb)

    if planes:
        p1 = [(-bb, -bb, 0), (bb, -bb, 0), (bb, bb, 0), (-bb, bb, 0)]
        p2 = [(0, -bb, -bb), (0, bb, -bb), (0, bb, bb), (0, -bb, bb)]
        p3 = [(-bb, 0, -bb), (bb, 0, -bb), (bb, 0, bb), (-bb, 0, bb)]

        ax.add_collection3d(
            Poly3DCollection([p1, p2, p3], facecolor='b', lw=0, alpha=0.1))

    if bbox:
        r = [-bb, bb]
        for s, e in combinations(np.array(list(product(r, r, r))), 2):
            if np.sum(np.abs(s - e)) == r[1] - r[0]:
                ax.plot3D(*zip(s, e), color='b', ls='--')
 def scatter_points( cloud, truth=None, ax=None ) :
     if ax is None :
         fig = plt.figure()
         ax = fig.add_subplot(111, projection='3d')
     
     if truth is not None :
         x,y,z = truth
         
         rad = np.linalg.norm([x,y])
         circ = patches.Circle( (0,0), rad, linestyle='dashed', fill=False )
         ax.add_patch( circ )
         art3d.pathpatch_2d_to_3d( circ, z )
         ax.plot( [ 0, x ], [ 0, y ], [ 0, z ] )
         
         ax.set_xlim3d(-rad,rad)
         ax.set_ylim3d(-rad,rad)
         
     cloud = np.vstack( cloud ).transpose()
     ax.scatter( cloud[0,:], cloud[1,:], cloud[2,:] )
     return ax
示例#15
0
def show_open_clusters(messier,data,box_size):
    ax = plt.subplot(111, projection='3d')
    
    ax.plot([0], [0], [0], 'o', color='orange', markersize=10, label='sun')

    circle = Circle((SUN_TO_CENTER_DISTANCE, 0, 0), SUN_TO_CENTER_DISTANCE, fill=False, color='blue')
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z=0)
    
    circle = Circle((SUN_TO_CENTER_DISTANCE, 0, 0), MILKY_WAY_RADIUS, fill=False, color='blue')
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z=0)

    if messier:
        counter = 0
        
        for r in data:
        
            marker = mlines.Line2D.filled_markers[counter % mlines.Line2D.filled_markers.__len__()]
        
            ax.plot([r["x"]], [r["y"]], [r["z"]], 'o', label=r["messier"] + "   " + str(int(r["dist"])) + " ly", markersize=5, marker=marker)
            
            counter += 1

        try:
            ax.legend(numpoints=1, fontsize=10)  # call with fontsize fails on debian 7
        except:
            ax.legend(numpoints=1)
        
    else:
        ax.scatter(data["x"], data["y"], data["z"])
    
    ax.set_xlabel('ly')
    ax.set_ylabel('ly')
    ax.set_zlabel('ly')
    
    ax.auto_scale_xyz([-box_size, box_size], [-box_size, box_size], [-box_size, box_size])
    
    show_maximized_plot('open clusters')
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
    '''
    Plots the string 's' on the axes 'ax', with position 'xyz', size 'size',
    and rotation angle 'angle'.  'zdir' gives the axis which is to be treated
    as the third dimension.  usetex is a boolean indicating whether the string
    should be interpreted as latex or not.  Any additional keyword arguments
    are passed on to transform_path.

    Note: zdir affects the interpretation of xyz.
    '''
    x, y, z = xyz
    if zdir == "y":
        xy1, z1 = (x, z), y
    elif zdir == "y":
        xy1, z1 = (y, z), x
    else:
        xy1, z1 = (x, y), z

    text_path = TextPath((0, 0), s, size=size, usetex=usetex)
    trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])

    p1 = PathPatch(trans.transform_path(text_path), **kwargs)
    ax.add_patch(p1)
    art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
示例#17
0
def draw_rectangular_prism(ax, x_min, x_max, y_min, y_max, z_min, z_max):
    alpha = 1
    back = Rectangle((y_min, z_min), y_max - y_min, z_max, alpha=alpha, fill=None, linestyle='dotted')
    ax.add_patch(back)
    art3d.pathpatch_2d_to_3d(back, z=x_min, zdir="x")

    front = Rectangle((y_min, z_min), y_max - y_min, z_max, alpha=alpha, fill=None, linestyle='dotted')
    ax.add_patch(front)
    art3d.pathpatch_2d_to_3d(front, z=x_max, zdir="x")

    floor = Rectangle((x_min, y_min), x_max, z_max, alpha=alpha, fill=None, linestyle='dotted')
    ax.add_patch(floor)
    art3d.pathpatch_2d_to_3d(floor, z=z_min, zdir="z")

    ceiling = Rectangle((x_min, y_min), x_max, z_max, alpha=alpha, fill=None, linestyle='dotted')
    ax.add_patch(ceiling)
    art3d.pathpatch_2d_to_3d(ceiling, z=z_max, zdir="z")
示例#18
0
文件: resection.py 项目: Trineon/lisa
    def __init__(self):
        win = gtk.Window()
        win.set_default_size(800,800)
        vbox = gtk.VBox()
        win.add(vbox)

        fig = Figure()
        canvas = FigureCanvas(fig)  # a gtk.DrawingArea
        ax = fig.add_subplot(111, projection='3d')

        a = np.array([[0,0],[10,0],[10,10],[0,10]])
        p = Polygon(a,fill=True)
        ax.add_patch(p)
        art3d.pathpatch_2d_to_3d(p, z=3)

        ax.set_xlim3d(0, 20)
        ax.set_ylim3d(0, 20)
        ax.set_zlim3d(0, 20)

        vbox.pack_start(canvas)
        win.show_all()

# Run the Gtk mainloop
        gtk.main()
示例#19
0
    def draw(self,ax,b,p,c):
        ax.add_patch(b)
        ax.add_patch(p)
        ax.add_patch(c)

        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_zlabel('z')

        art3d.pathpatch_2d_to_3d(b, z=0, zdir="x")
        art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")
        art3d.pathpatch_2d_to_3d(c, z=10, zdir="z")

        ax.set_xlim(0, 20)
        ax.set_ylim(0, 20)
        ax.set_zlim(0, 20)
示例#20
0
def show_globular_clusters(dt, messier):
    ax = plt.subplot(111, projection='3d')

    ax.plot((0,), (0,), (0,), 'o', color='orange', markersize=7, label='sun')

    circle = Circle((SUN_TO_CENTER_DISTANCE, 0, 0), SUN_TO_CENTER_DISTANCE, fill=False, color='blue')
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z=0)

    circle = Circle((SUN_TO_CENTER_DISTANCE, 0, 0), MILKY_WAY_RADIUS, fill=False, color='blue')
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z=0)

    circle = Circle((0, 0, 0), 1000, fill=False, color='red')
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z=0)

    if messier:
        counter = 0

        for r in dt:
            marker = mlines.Line2D.filled_markers[counter % mlines.Line2D.filled_markers.__len__()]

            if r["messier"] > 0:
                ax.plot([r["x"]], [r["y"]], [r["z"]], 'o', label="M" + str(r["messier"]) + "   " + str(int(r["dist"])), markersize=5, marker=marker)

            counter += 1
        
        try:
            ax.legend(numpoints=1, fontsize=10)  # call with fontsize fails on debian 7
        except:
            ax.legend(numpoints=1)
                
    else:
        ax.scatter(dt['x'], dt['y'], dt['z'])


    ax.set_xlabel('ly')
    ax.set_ylabel('ly')
    ax.set_zlabel('ly')

    ax.auto_scale_xyz([-35000, 85000], [-60000, 60000], [-60000, 60000])

    show_maximized_plot('globular clusters')
def show_globular_clusters(dt, messier):
    ax = plt.subplot(111, projection='3d')

    ax.plot((0,), (0,), (0,), 'o', color='orange', markersize=7, label='sun')

    circle = Circle((SUN_TO_CENTER_DISTANCE, 0, 0), SUN_TO_CENTER_DISTANCE, fill=False, color='blue')
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z=0)

    circle = Circle((SUN_TO_CENTER_DISTANCE, 0, 0), MILKY_WAY_RADIUS, fill=False, color='blue')
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z=0)

    circle = Circle((0, 0, 0), 1000, fill=False, color='red')
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z=0)

    if messier:
        counter = 0

        for r in dt:
            marker = mlines.Line2D.filled_markers[counter % mlines.Line2D.filled_markers.__len__()]

            if str(r["Name"]).startswith('M'):
                ax.plot([r["X"]], [r["Y"]], [r["Z"]], 'o', label=str(r["Name"]) + "   " + str(r["Rsun"]), markersize=5, marker=marker)

            counter += 1

        ax.legend(numpoints=1, fontsize=10)

    else:
        ax.scatter(dt['X'], dt['Y'], dt['Z'])

    ax.set_xlabel('ly')
    ax.set_ylabel('ly')
    ax.set_zlabel('ly')

    ax.auto_scale_xyz([-35000, 85000], [-60000, 60000], [-60000, 60000])

    show_maximized_plot('globular clusters')
示例#22
0
def generateHorseShoeAroundGoal(size):
    ObstacleIDs = []

    for i in range(int(-size - 0.5), int(size + 1.5)):
        ObstacleIDs.append(pbl.loadURDF('block.urdf',
                                        [i, 5 - size - 0.5, 0.5]))
        bbox = pbl.getAABB(ObstacleIDs[-1])
        dims = np.subtract(bbox[1], bbox[0])
        disk = Rectangle(bbox[0][0::2],
                         dims[0],
                         dims[2],
                         color='r',
                         fill=False)
        ax.add_patch(disk)
        art3d.pathpatch_2d_to_3d(disk, z=bbox[1][1], zdir='y')

    for i in range(int(5 - size + 0.5), int(5 - size + 3.5)):
        ObstacleIDs.append(
            pbl.loadURDF('block.urdf', [int(-size - 0.5), i, 0.5]))
        bbox = pbl.getAABB(ObstacleIDs[-1])
        dims = np.subtract(bbox[1], bbox[0])
        disk = Rectangle(bbox[0][1:], dims[0], dims[2], color='r', fill=False)
        ax.add_patch(disk)
        art3d.pathpatch_2d_to_3d(disk, z=bbox[1][0], zdir='x')

        ObstacleIDs.append(
            pbl.loadURDF('block.urdf', [int(size + 0.5), i, 0.5]))
        bbox = pbl.getAABB(ObstacleIDs[-1])
        dims = np.subtract(bbox[1], bbox[0])
        disk = Rectangle(bbox[0][1:], dims[0], dims[2], color='r', fill=False)
        ax.add_patch(disk)
        art3d.pathpatch_2d_to_3d(disk, z=bbox[0][0], zdir='x')

    ObstacleIDs.append(pbl.loadURDF('plane.urdf'))

    return ObstacleIDs
示例#23
0
    ax.text(-20, 20, 800, f"$\lambda={lmbda:.1f}$", fontsize=14)

    beta0 = np.linspace(-30, 30, 300)
    beta1 = np.linspace(-30, 30, 300)
    B0, B1 = np.meshgrid(beta0, beta1)
    Z1 = loss(B0, B1, a=1, b=1, c=0, cx=0, cy=0, lmbda=lmbda, yintercept=0)
    Z2 = loss(B0, B1, a=5, b=5, c=0, cx=cx, cy=cy, yintercept=0)
    Z = Z1 + Z2

    # minx_idx = np.argmin(Z, axis=0)[0]
    # miny_idx = np.argmin(Z, axis=1)[0]
    # minx, miny = beta0[minx_idx], beta1[miny_idx]

    origin = Circle(xy=(0, 0), radius=1, color='k')
    ax.add_patch(origin)
    art3d.pathpatch_2d_to_3d(origin, z=0, zdir="z")

    scale = 1.5
    vmax = 8000
    contr = ax.contour(B0,
                       B1,
                       Z,
                       levels=50,
                       linewidths=.5,
                       cmap='coolwarm',
                       zdir='z',
                       offset=0,
                       vmax=vmax)

    j = lmbda * scale
    b0 = (j, 20 - j)
plt.axis('off')

#draw sphere
def drawSphere(x=0,y=0,z=0,r=1):
    u, v = np.mgrid[0:2*np.pi:16j, 0:np.pi:11j]
    cx= x + np.cos(u)*np.sin(v) * r
    cy= y + np.sin(u)*np.sin(v) * r
    cz= z + np.cos(v) * r
    return ax.plot_wireframe(cx, cy, cz, color="grey", linestyle='dotted' )

drawSphere(r=2)

# draw projection
circle = Circle((0,0), radius=2, alpha=0.2, facecolor="black")
ax.add_patch(circle)
art3d.pathpatch_2d_to_3d(circle, z=0, zdir="x");


#earth
drawSphere(7,0,0,0.5)


class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs
    
    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
示例#25
0
文件: proj3d.py 项目: xdf321/pyebsd
def plot_sproj3d(n=[1, 0, 1], offset=0., **kwargs):
    n = np.asarray(n) / np.linalg.norm(n)  # normalize n

    r = kwargs.pop('r', 1.)  # radius of the sphere
    p = kwargs.pop('p', r)  # z coordinate of the South pole
    bound = kwargs.pop('bound', 1.1)
    show = kwargs.pop('show', True)
    only_positive = kwargs.pop('only_positive', False)

    # Coordinates of the center of the circle expressed as a
    # translation along the direction n (i.e., C = O + n*T)
    C = np.zeros(3) + n * offset
    C = C.reshape(3, 1)
    r_prime = (r**2. - offset**2.)**.5  # Radius of the circle

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.set_aspect('equal')

    if (n[0] == 0.) & (n[1] == 0.):
        a = np.asarray([1, 0, 0]).reshape(3, 1)
        b = np.asarray([0, 1, 0]).reshape(3, 1)
    else:
        # parametrization of the circle
        # http://demonstrations.wolfram.com/ParametricEquationOfACircleIn3D/
        a = np.asarray([-n[1], n[0], 0]).reshape(3, 1)
        a = a / np.linalg.norm(a)
        b = np.asarray([-n[0] * n[2], -n[1] * n[2],
                        n[0]**2 + n[1]**2]).reshape(3, 1)
        b = b / np.linalg.norm(b)

    t1, t2 = 0., 2 * np.pi
    if only_positive == True:
        s = float(C[2] / (b[2] * r_prime))
        if np.abs(s) < 1.:
            t1, t2 = -np.arcsin(s), np.arcsin(s) + np.pi
            if np.sin((t1 + t2) / 2.) < 0.:
                t1 += 2 * np.pi

    t = np.linspace(t1, t2, 50)
    P = r_prime * np.cos(t) * a + r_prime * np.sin(t) * b + C
    ax.plot(P[0], P[1], P[2])  # plot circle

    Q = np.ndarray(P.shape)
    Q[0], Q[1], Q[2] = p * P[0] / (p + P[2]), p * P[1] / (
        p + P[2]), 0.  # stereographic projection of the circle (trace)
    sel = (np.abs(Q[0]) <= bound) & (np.abs(Q[1]) <= bound)
    Q = Q[:, sel]
    ax.plot(Q[0], Q[1], 'g.')  # plot trace of the circle
    ax.quiver(0, 0, 0, n[0], n[1], n[2], pivot='tail',
              length=r)  # draw an arrow corresponding to the vector n
    xp, yp = p * n[0] / (p + n[2]), p * n[1] / (
        p + n[2])  # stereographic projection of the pole
    ax.plot([xp], [yp], [0], 'go')

    m = Q.shape[1]
    x, y, z = np.ndarray(3 * m), np.ndarray(3 * m), np.ndarray(3 * m)
    x[::3], x[1::3], x[2::3] = 0, Q[0], P[0][sel]
    y[::3], y[1::3], y[2::3] = 0, Q[1], P[1][sel]
    z[::3], z[1::3], z[2::3] = -p, 0., P[2][sel]
    # draw [red] lines connecting the South pole to the circle and its stereographic projection
    ax.plot(x, y, z, color='r', linewidth=.25)

    # add patch corresponding to the plane z = 0
    plane = plt.Circle((0, 0), 1., color='g', alpha=.1)
    ax.add_patch(plane)
    art3d.pathpatch_2d_to_3d(plane, z=0, zdir='z')

    # draw a [red] line connecting the South pole to the pole
    ax.plot([0, xp, n[0]], [0, yp, n[1]], [-p, 0, n[2]],
            color='r',
            linewidth=.25)

    # # draw vertexes (vertices) of a cube
    # x, y, z = np.mgrid[-1:2:2, -1:2:2, -1:2:2]
    # ax.plot(bound*x.ravel(), bound*y.ravel(), bound*z.ravel(), lw=0)#'k.')
    ax.set_xlim(-bound, bound)
    ax.set_ylim(-bound, bound)
    ax.set_zlim(-bound, bound)

    # draw sphere
    # http://stackoverflow.com/questions/11140163/python-matplotlib-plotting-a-3d-cube-a-sphere-and-a-vector
    u, v = np.mgrid[0:2 * np.pi:20j, 0:np.pi:11j]
    x = r * np.cos(u) * np.sin(v)
    y = r * np.sin(u) * np.sin(v)
    z = r * np.cos(v)
    ax.plot_wireframe(x, y, z, color='k', linewidth=.1)

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')

    proj3d.persp_transformation = orthogonal_proj  # orthogonal projection

    if show == True:
        plt.show()

    return ax
示例#26
0
def plot_geometry(geo, angle=0):
    """
    Plots the given geometry.
    """
    import mpl_toolkits.mplot3d.art3d as art3d
    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(6,6))
    fig.suptitle('Cone Beam Compute Tomography geometry')
    ax = fig.add_subplot(111, projection='3d')
    ax.set_title('Current CBCT geometry, in scale')

    limXY = max(geo.DSO, geo.DSD-geo.DSO)
    limZ = geo.sVoxel[0]

    ax.set_box_aspect((limXY,limXY,limZ))

    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    ax.set_xlim3d(-limXY*1.2, limXY*1.2)
    ax.set_ylim3d(-limXY*1.2, limXY*1.2)
    ax.set_zlim3d(-limZ *1.2, limZ *1.2)

    # Trajectory of Source
    # https://matplotlib.org/devdocs/api/_as_gen/matplotlib.patches.Circle.htm
    circ = matplotlib.patches.Circle((0,0), geo.DSO, color='black', fill=False, ls='-.', lw=0.5)
    ax.add_patch(circ)
    art3d.pathpatch_2d_to_3d(circ, z=0, zdir="z")

    # Trajectory of Detector
    circ = matplotlib.patches.Circle((0,0), geo.DSD-geo.DSO, color='black', fill=False, ls='-.', lw=0.5)
    ax.add_patch(circ)
    art3d.pathpatch_2d_to_3d(circ, z=0, zdir="z")

    # Source
    # ax.scatter([0], [0], [0], color="g", s=100)
    sourcePos3D = [geo.DSO*np.cos(angle), geo.DSO*np.sin(angle), 0] # xyz
    ax.scatter([sourcePos3D[0]], [sourcePos3D[1]], [sourcePos3D[2]], color="steelblue", s=100)

    # Axes XYZ
    length_axis = geo.sVoxel[0]
    x_axis = Arrow3D([0, length_axis], [0, 0], [0, 0], mutation_scale=10, shrinkA=0, lw=1, arrowstyle="-|>", color="r")
    y_axis = Arrow3D([0, 0], [0, length_axis], [0, 0], mutation_scale=10, shrinkA=0, lw=1, arrowstyle="-|>", color="b")
    z_axis = Arrow3D([0, 0], [0, 0], [0, length_axis], mutation_scale=10, shrinkA=0, lw=1, arrowstyle="-|>", color="g")
    ax.add_artist(x_axis)
    ax.add_artist(y_axis)
    ax.add_artist(z_axis)

    # Detector
    print("sDetector = {}".format(geo.sDetector))
    alpha_detector = 0.7
    detectorPos3D = [
                        (geo.DSD-geo.DSO)*np.cos(angle+np.pi) + geo.offDetector[1]*np.sin(angle+np.pi),
                        (geo.DSD-geo.DSO)*np.sin(angle+np.pi) - geo.offDetector[1]*np.cos(angle+np.pi),
                         geo.offDetector[0]] # xyz
    detector = matplotlib.patches.Rectangle(
                    (-geo.sDetector[1]/2, -geo.sDetector[0]/2),
                    geo.sDetector[1], geo.sDetector[0], 
                    angle=0,#angle, 
                    color='maroon', 
                    fill=True, 
                    alpha=alpha_detector)
    print("detector={}".format(detector))
    ax.add_patch(detector)
    mat_rot = np.array([
        [-np.sin(angle), 0, np.cos(angle)],
        [ np.cos(angle), 0, np.sin(angle)],
        [ 0            , 1, 0            ]
    ])
    pathpatch_2d_to_3d_affine(detector, mat_rot, detectorPos3D)

    # Image FOV
    alpha_img = 0.1
    offOrigin = np.array([geo.offOrigin[2], geo.offOrigin[1], geo.offOrigin[0]])
    mat_rot_xy = np.array([
        [ 1, 0, 0],
        [ 0, 1, 0],
        [ 0, 0, 1]
    ], dtype=np.float)           
    for idx in range(2):
        img_face_xy = matplotlib.patches.Rectangle(
                        (-geo.sVoxel[2]/2, -geo.sVoxel[1]/2), # xy order
                        geo.sVoxel[2], geo.sVoxel[1], 
                        angle=0,#angle, 
                        color='black', 
                        fill=True, 
                        alpha=alpha_img)
        ax.add_patch(img_face_xy)
        pathpatch_2d_to_3d_affine(img_face_xy, mat_rot_xy, np.array([0, 0, -geo.sVoxel[0]/2 if idx == 0 else geo.sVoxel[0]/2])+offOrigin)

    mat_rot_yz = np.array([
        [ 0, 0, 1],
        [ 1, 0, 0],
        [ 0, 1, 0]
    ], dtype=np.float)           
    for idx in range(2):
        img_face_yz = matplotlib.patches.Rectangle(
                        (-geo.sVoxel[1]/2, -geo.sVoxel[0]/2), # xy order
                        geo.sVoxel[1], geo.sVoxel[0], 
                        angle=0,#angle, 
                        color='black', 
                        fill=True, 
                        alpha=alpha_img)
        ax.add_patch(img_face_yz)
        pathpatch_2d_to_3d_affine(img_face_yz, mat_rot_yz, np.array([-geo.sVoxel[2]/2 if idx == 0 else geo.sVoxel[2]/2, 0, 0])+offOrigin)

    mat_rot_zx = np.array([
        [ 0, 1, 0],
        [ 0, 0, 1],
        [ 1, 0, 0]
    ], dtype=np.float)           
    for idx in range(2):
        img_face_zx = matplotlib.patches.Rectangle(
                        (-geo.sVoxel[0]/2, -geo.sVoxel[2]/2), # xy order
                        geo.sVoxel[0], geo.sVoxel[2], 
                        angle=0,#angle, 
                        color='black', 
                        fill=True, 
                        alpha=alpha_img)
        ax.add_patch(img_face_zx)
        pathpatch_2d_to_3d_affine(img_face_zx, mat_rot_zx, np.array([0, -geo.sVoxel[1]/2 if idx == 0 else geo.sVoxel[1]/2, 0])+offOrigin)

    plt.show()
示例#27
0
## Formation of the focal plane objects ##
#########################################

## The plane ##

xs1 = np.linspace(-3000, 3000, 5)
ys1 = np.linspace(-3000, 3000, 5)
x1, y1 = np.meshgrid(xs1, ys1)
z1 = 0*x1 + 0*y1 + 4750
ax.plot_surface(x1, y1, z1, alpha=0.2)

## The circle ##

c1=Circle((0, 0), 1000, facecolor='none', edgecolor="blue", linewidth=10, alpha=1)
ax.add_patch(c1)
art3d.pathpatch_2d_to_3d(c1, z=4750, zdir="z")

## The dots ##

ax.scatter(t_df['x_dev_exp'], t_df['y_dev_exp'], 1000*t_df['f_exp'], color='red', s = 100, alpha=1);

#########################################################################################################
## Formation of the double-focal plane objects ##
################################################

## The plane ##

xs2 = np.linspace(-15000, 15000, 5)
ys2 = np.linspace(-15000, 15000, 5)
x2, y2 = np.meshgrid(xs2, ys2)
z2 = 0*x2 + 0*y2 + 9500
示例#28
0
    def plot3dcamera(self, verts, scale=None):
        fig = plt.figure()
        ax1 = fig.add_subplot(111, projection='3d')
        poly3d = Poly3DCollection(verts)
        if not scale:
            poly3d.set_array(
                np.array(self.total_scale) / max(self.total_scale))
        else:
            poly3d.set_array(np.array(scale) / max(scale))
        ax1.add_collection3d(poly3d)

        theta = np.linspace(0, 2 * np.pi, 90)
        r = -np.arange(0, self.fiducial_radius, 0.01)
        T, R = np.meshgrid(theta, r)
        X = R * np.cos(T)
        Y = R * np.sin(T)
        Z = -np.sqrt(X**2 + Y**2)
        u, v = np.mgrid[0:2 * np.pi:20j, 0:np.pi:10j]
        x = self.fiducial_radius * np.cos(u) * np.sin(v)
        y = self.fiducial_radius * np.sin(u) * np.sin(v)
        z = self.fiducial_radius * np.cos(v)
        ax1.plot_wireframe(self.lightsource_distance + Z *
                           (self.lightsource_distance / 0.2),
                           X + self.lightsource_x,
                           Y + self.lightsource_y,
                           alpha=0.1,
                           color='C0')
        ax1.plot_wireframe(x, y, z, color="C0", alpha=0.1)

        lim = max(self.geom.pix_x).value

        ax1.set_ylim3d(-lim, lim)
        ax1.set_zlim3d(-lim, lim)
        ax1.set_xlabel('Z')
        ax1.set_ylabel('X')
        ax1.set_zlabel('Y')
        fig.colorbar(poly3d, ax=ax1)

        colors = ['0.6', '0.5', '0.2', 'c', 'm', 'y']
        # for i, (z, zdir) in enumerate(product([self.lightsource_distance, self.lightsource_distance+0.3], ['x', 'y', 'z'])):
        side = Rectangle(
            (self.lightsource_distance, -0.01 + self.lightsource_x),
            0.1,
            0.02,
            facecolor=colors[0])
        ax1.add_patch(side)
        pathpatch_2d_to_3d(side, z=0.01 + self.lightsource_x, zdir='z')

        side = Rectangle(
            (self.lightsource_distance, -0.01 + self.lightsource_x),
            0.1,
            0.02,
            facecolor=colors[0])
        ax1.add_patch(side)
        pathpatch_2d_to_3d(side, z=-0.01 + self.lightsource_x, zdir='z')

        side = Rectangle(
            (self.lightsource_distance, -0.01 + self.lightsource_y),
            0.1,
            0.02,
            facecolor=colors[1])
        ax1.add_patch(side)
        pathpatch_2d_to_3d(side, z=0.01 + self.lightsource_x, zdir='y')

        side = Rectangle(
            (self.lightsource_distance, -0.01 + self.lightsource_y),
            0.1,
            0.02,
            facecolor=colors[1])
        ax1.add_patch(side)
        pathpatch_2d_to_3d(side, z=-0.01 + self.lightsource_x, zdir='y')

        side = Rectangle(
            (-0.01 + self.lightsource_x, -0.01 + self.lightsource_y),
            0.02,
            0.02,
            facecolor=colors[1])
        ax1.add_patch(side)
        pathpatch_2d_to_3d(side, z=self.lightsource_distance, zdir='x')

        side = Rectangle(
            (-0.01 + self.lightsource_x, -0.01 + self.lightsource_y),
            0.02,
            0.02,
            facecolor=colors[1])
        ax1.add_patch(side)
        pathpatch_2d_to_3d(side, z=self.lightsource_distance + 0.1, zdir='x')

        self.plot_values3d()
        "Figure (background)",
        "Axes (spines, ticks & labels)",
        "Patches (zorder=1)",
        "Lines (zorder=2)",
        "Text (zorder=3)",
        "Inset axes & legend (zorder=5)",
]):

    p = Rectangle((0, 0),
                  10,
                  10,
                  edgecolor="None",
                  facecolor="white",
                  alpha=0.5)
    ax.add_patch(p)
    art3d.pathpatch_2d_to_3d(p, z=i, zdir="z")

    p = Rectangle((0, 0), 10, 10, edgecolor="black", facecolor="None")
    ax.add_patch(p)
    art3d.pathpatch_2d_to_3d(p, z=i, zdir="z")

    text3d(
        ax,
        (-0.25, 0.25, i),
        text,
        zdir="z",
        size=0.5,
        angle=np.pi / 2,
        ec="none",
        fc="k",
    )
示例#30
0
times = np.arange(0., 100. + dt, dt)

#create four initial conditions
IC = []
IC.append([[.9, 0, 0], [2.5, 0, 0], [1.25, 0, 0], [4, 0, 0]])
flattened = [val for sublist in IC for val in sublist]

#%%
myfig = plt.figure()
myax = Axes3D(myfig)

#plot the wire loop
p = Circle([0, 0], radius=1, fill=0)
q = Circle([0, 0], radius=1, fill=0)
myax.add_patch(p)
myax.add_patch(q)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")
art3d.pathpatch_2d_to_3d(q, z=0, zdir="y")

#%%

for i in flattened:
    #plot both the positive and negative solutions to complete the loops
    out_pos = odeint(Biot_Savart_time_dependent, i, times)
    myax.plot(out_pos[:, 0], out_pos[:, 1], out_pos[:, 2])
    myax.plot(-out_pos[:, 0], -out_pos[:, 1], -out_pos[:, 2])
myax.set_xlabel('x')
myax.set_ylabel('y')
myax.set_zlabel('z')
plt.show()
示例#31
0
def chipArray_graph(spot_df,
                    chip_name='IRIS chip',
                    sample_name='',
                    exo_toggle=False,
                    metric_str='',
                    version='',
                    savedir='/Users/dejavu/Desktop'):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    prescan = min(spot_df.scan_number)
    last_scan = max(spot_df.scan_number)
    spot_array = np.array(spot_df.spot_number[::last_scan])
    total_spots = max(spot_array)
    vhf_colormap = get_vhf_colormap()

    linx, liny = zip(*(spot_df.chip_coords_xy[::last_scan]))
    linx = np.array(linx, dtype='float') / 1000
    liny = np.array(liny, dtype='float') / 1000
    ax.plot(linx, liny, 0, color='k', linewidth=1, linestyle='--', alpha=0.5)
    for j, spot_num in enumerate(spot_array):
        ax.text(
            linx[j],
            liny[j],
            0,
            s=str(spot_num),
            fontsize=8,
            fontname='monospace',
            color='k',
            alpha=1,
            horizontalalignment='left',
            verticalalignment='top',
        )
    spot_type_list = []
    for val in spot_df.spot_type:
        if val not in spot_type_list:
            spot_type_list.append(val)

    zpos = 0
    for c, spot in enumerate(spot_type_list):
        prescan_df = spot_df[(spot_df.scan_number == prescan)
                             & (spot_df.spot_type == spot)].reset_index()

        xpos, ypos = zip(*(prescan_df.chip_coords_xy))
        dx = dy = 0.08
        offset = dx * 0.5

        xpos = np.array(xpos, dtype='float') * 0.001
        xpos_bar = xpos - offset

        ypos = np.array(ypos, dtype='float') * 0.001
        ypos_bar = ypos - offset

        rad_list = np.sqrt(
            np.array(prescan_df.area_sqmm, dtype='float') / np.pi)
        color = vhf_colormap[c]
        for i, r in enumerate(rad_list):
            Ab_spot = plt.Circle((xpos[i], ypos[i]),
                                 r,
                                 facecolor=color,
                                 edgecolor='k',
                                 alpha=0.75)
            ax.add_patch(Ab_spot)
            art3d.pathpatch_2d_to_3d(Ab_spot, z=0, zdir="z")

        dz_pre = np.array(prescan_df.kparticle_density)
        prebar = ax.bar3d(xpos_bar,
                          ypos_bar,
                          zpos,
                          dx,
                          dy,
                          dz_pre,
                          color='k',
                          edgecolor='k',
                          label=None,
                          alpha=0.15)

        prebar = _bugfix_bar3d(prebar)

        if last_scan > 1:
            scan_df = spot_df[(spot_df.scan_number == last_scan)
                              & (spot_df.spot_type == spot)].reset_index()
            dz = np.array(scan_df.normalized_density)
            dx = dy = 0.04
            offset = dx * 0.5
            xpos_bar = xpos - offset
            ypos_bar = ypos - offset

            bar = ax.bar3d(xpos_bar,
                           ypos_bar,
                           zpos,
                           dx,
                           dy,
                           dz,
                           color='red',
                           edgecolor='k',
                           label=spot,
                           alpha=0.75)

            bar = _bugfix_bar3d(bar)

    tri = Polygon(np.array([[-.25, -.5], [0, 0], [.25, -.5]]), color='k')
    ax.add_patch(tri)
    art3d.pathpatch_2d_to_3d(tri, z=0, zdir="z")

    ax.set_xlabel("Lat. Axis (mm)", fontsize=8)
    ax.set_ylabel("Long. Axis (mm)", fontsize=8)

    ax.set_zlabel("Particle Density (kparticles/mm" + r'$^2$' +
                  ")\n{}% Contrast".format(metric_str))
    ax.set_title("{} Microarray Bar Graph\n{}".format(chip_name, sample_name),
                 fontsize=14)
    ax.legend(loc='upper left')

    if exo_toggle == False:
        ax.set_xlim3d(-1.125, 1.125)
        ax.set_ylim3d(2.25, 4.50)
    else:
        ax.set_xlim3d(-1.75, 1.75)
        ax.set_ylim3d(0, 3.5)
    ax.set_zlim(0, )

    plt.tight_layout()
    plot_name = "{}_arrayplot.{}contrast.v{}.png".format(
        chip_name, metric_str, version)

    plt.savefig('{}/{}'.format(savedir, plot_name),
                bbox_inches='tight',
                pad_inches=0.1,
                dpi=300)
    print('File generated: {}'.format(plot_name))
    plt.show()
    plt.clf()
    def drawCenters(self, myCenters, h):

        self.fig.canvas.flush_events()
        for i in range(1):
            try:
                self.non_branch_points.remove()
            except Exception:
                pass

            try:
                self.vectors.remove()
            except Exception:
                pass
            try:
                for circle in self.circles:
                    circle.remove()
                self.circles = []
            except Exception:
                pass

            try:
                self.bridge_points.remove()
            except Exception:
                pass
            try:
                for connection in self.connections:
                    connection.pop(0).remove()
                self.connections = []
            except Exception:
                pass

            try:
                self.head_tail.remove()
            except Exception:
                pass

        branch_points = []
        non_branch_points = []
        branch_points_txt = []
        non_branch_points_txt = []
        eigen_vectors = []
        bridge_points = []
        bridge_point_txt = []
        head_tail = []
        head_tail_txt = []
        for center in myCenters:

            if center.label == "branch_point":
                if center.head_tail:
                    head_tail.append(center.center)
                    head_tail_txt.append(center.index)
                else:
                    branch_points.append(center.center)
                    branch_points_txt.append(center.index)

                for connection in center.connections:

                    points = np.array(
                        [center.center, myCenters[connection].center])

                    self.connections.append(
                        self.ax.plot(points[:, 0], points[:, 1], points[:, 2],
                                     'r-'))

            elif center.label == 'non_branch_point':
                non_branch_points.append(center.center)
                non_branch_points_txt.append(center.index)

            elif center.label == "bridge_point":
                bridge_point_txt.append(center.index)
                bridge_points.append(center.center)

            vector = tuple(center.center) + tuple(
                center.eigen_vectors[:, 0] / 10)
            eigen_vectors.append(vector)

        branch_points = np.array(branch_points)
        bridge_points = np.array(bridge_points)
        non_branch_points = np.array(non_branch_points)
        eigen_vectors = np.array(eigen_vectors)
        head_tail = np.array(head_tail)

        if branch_points.any():
            self.branch_points = self.ax.scatter(branch_points[:, 0],
                                                 branch_points[:, 1],
                                                 branch_points[:, 2],
                                                 color=[0, 0.8, 0, 1])

        if bridge_points.any():
            self.bridge_points = self.ax.scatter(bridge_points[:, 0],
                                                 bridge_points[:, 1],
                                                 bridge_points[:, 2],
                                                 color=[0, 0, .8, 1])

        if non_branch_points.any():
            self.non_branch_points = self.ax.scatter(non_branch_points[:, 0],
                                                     non_branch_points[:, 1],
                                                     non_branch_points[:, 2],
                                                     color=[0.8, 0, 0, 1])

        if head_tail.any():
            self.head_tail = self.ax.scatter(head_tail[:, 0],
                                             head_tail[:, 1],
                                             head_tail[:, 2],
                                             color=[1, 1, 0, 1])

            for center in non_branch_points[:5]:
                p = Circle((center[0], center[1]),
                           h,
                           fill=False,
                           color=[0.8, 0.4, 0, 0.2])
                self.circles.append(self.ax.add_patch(p))
                art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")

        #UNCOMMENT THIS TO PLOT THE INDICES OF THE CENTERS
        # if bridge_point_txt:
        #     if self.bridge_point_txt:
        #         for txt in self.bridge_point_txt:
        #             # txt.pop(0).remove()
        #             txt.remove()
        #         self.bridge_point_txt = []
        #     for i, txt in enumerate(bridge_point_txt):
        #         self.bridge_point_txt.append(self.ax.text(bridge_points[i,0], bridge_points[i,1], bridge_points[i,2], str(txt), None))

        # if branch_points_txt:
        #     if self.branch_points_txt:
        #         for txt in self.branch_points_txt:
        #             # txt.pop(0).remove()
        #             txt.remove()
        #         self.branch_points_txt=[]
        #     for i, txt in enumerate(branch_points_txt):
        #         self.branch_points_txt.append(self.ax.text(branch_points[i,0], branch_points[i,1], branch_points[i,2], str(txt), None))

        # if non_branch_points_txt:
        #     if self.non_branch_points_txt:
        #         for txt in self.non_branch_points_txt:
        #             # txt.pop(0).remove()
        #             txt.remove()
        #         self.non_branch_points_txt= []
        #     for i, txt in enumerate(non_branch_points_txt):
        #         self.non_branch_points_txt.append(self.ax.text(non_branch_points[i,0], non_branch_points[i,1], non_branch_points[i,2], str(txt), None))

        # if head_tail_txt:
        #     if self.head_tail_txt:
        #         for txt in self.head_tail_txt:
        #             # txt.pop(0).remove()
        #             txt.remove()
        #         self.head_tail_txt= []
        #     for i, txt in enumerate(head_tail_txt):
        #         self.head_tail_txt.append(self.ax.text(head_tail[i,0], head_tail[i,1], head_tail[i,2], str(txt), None))

        # X,Y,Z,U,V,W = zip(*eigen_vectors)
        # self.vectors = self.ax.quiver(X,Y,Z,U,V,W)

        plt.draw()  # redraw the canvas
示例#33
0
def text3d(ax, (x, y, z), s, zdir="z", size=None, angle=0, usetex=False,
           **kwargs):

    if zdir == "y":
        xy1, z1 = (x, z), y
    elif zdir == "y":
        xy1, z1 = (y, z), x
    else:
        xy1, z1 = (x, y), z

    text_path = TextPath((0, 0), s, size=size, usetex=usetex)
    trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])

    p1 = PathPatch(trans.transform_path(text_path), **kwargs)
    ax.add_patch(p1)
    art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)


fig = plt.figure()
ax = Axes3D(fig)

p = Circle((5, 5), 3)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")


text3d(ax, (4, -2, 0), "X-axis", zdir="z", size=.5, usetex=False,
       ec="none", fc="k")
text3d(ax, (12, 4, 0), "Y-axis", zdir="z", size=.5, usetex=False, angle=.5*3.14159,
       ec="none", fc="k")
text3d(ax, (12, 10, 4), "Z-axis", zdir="y", size=.5, usetex=False, angle=.5*3.14159,
示例#34
0
def double_focal_plane_objects_formation(table):

    #########################################################################################################
    ## Formation of the double-focal plane objects ##
    ################################################

    ## The plane ##

    xs2 = np.linspace(-2000, 2000, 2)
    ys2 = np.linspace(-2000, 2000, 2)
    x2, y2 = np.meshgrid(xs2, ys2)
    z2 = 0 * x2 + 0 * y2 + 9500
    ax.plot_surface(x2, y2, z2, alpha=0.2, cstride=1, rstride=1, shade=False)

    ## The circle ##

    #    c2=Circle((0, 0), 4000, facecolor='none', edgecolor="green", linewidth=10, alpha=1)
    #    ax.add_patch(c2)
    #    art3d.pathpatch_2d_to_3d(c2, z=9500, zdir="z")

    ## The tg_circle ##

    #    c3=Circle((0, 0), 9500*np.tan(np.radians(5)), facecolor='none', edgecolor="green", linewidth=5, alpha=1)
    #    ax.add_patch(c3)
    #    art3d.pathpatch_2d_to_3d(c3, z=9500, zdir="z")

    ## The dots ##

    ax.scatter(table[0], table[1], F2, color='green', s=200, alpha=1)

    ## Bad circles ##

    for i in ([3, 31, 0, 19, 32]):
        c = Circle((table[0][i], table[1][i]),
                   9500 * np.tan(np.radians(5)),
                   facecolor='none',
                   edgecolor="green",
                   linewidth=3,
                   alpha=1)
        ax.add_patch(c)
        art3d.pathpatch_2d_to_3d(c, z=9500, zdir="z")
    for i in ([19]):
        c = Circle((table[0][i], table[1][i]),
                   9500 * np.tan(np.radians(5 + 1)),
                   facecolor='none',
                   edgecolor="blue",
                   linewidth=1,
                   alpha=0.7)
        ax.add_patch(c)
        art3d.pathpatch_2d_to_3d(c, z=9500, zdir="z")
    for i in ([19]):
        c = Circle((table[0][i], table[1][i]),
                   9500 * np.tan(np.radians(5 + 2)),
                   facecolor='none',
                   edgecolor="blue",
                   linewidth=1,
                   alpha=0.6)
        ax.add_patch(c)
        art3d.pathpatch_2d_to_3d(c, z=9500, zdir="z")
    for i in ([32]):
        c = Circle((table[0][i], table[1][i]),
                   9500 * np.tan(np.radians(5 + 1)),
                   facecolor='none',
                   edgecolor="blue",
                   linewidth=1,
                   alpha=0.7)
        ax.add_patch(c)
        art3d.pathpatch_2d_to_3d(c, z=9500, zdir="z")
    for i in ([32]):
        c = Circle((table[0][i], table[1][i]),
                   9500 * np.tan(np.radians(5 + 2)),
                   facecolor='none',
                   edgecolor="blue",
                   linewidth=1,
                   alpha=0.6)
        ax.add_patch(c)
        art3d.pathpatch_2d_to_3d(c, z=9500, zdir="z")
    for i in ([32]):
        c = Circle((table[0][i], table[1][i]),
                   9500 * np.tan(np.radians(5 + 3)),
                   facecolor='none',
                   edgecolor="blue",
                   linewidth=1,
                   alpha=0.5)
        ax.add_patch(c)
        art3d.pathpatch_2d_to_3d(c, z=9500, zdir="z")
    for i in ([32]):
        c = Circle((table[0][i], table[1][i]),
                   9500 * np.tan(np.radians(5 + 4)),
                   facecolor='none',
                   edgecolor="blue",
                   linewidth=1,
                   alpha=0.4)
        ax.add_patch(c)
        art3d.pathpatch_2d_to_3d(c, z=9500, zdir="z")
    for i in ([32]):
        c = Circle((table[0][i], table[1][i]),
                   9500 * np.tan(np.radians(5 + 5)),
                   facecolor='none',
                   edgecolor="blue",
                   linewidth=1,
                   alpha=0.3)
        ax.add_patch(c)
        art3d.pathpatch_2d_to_3d(c, z=9500, zdir="z")
示例#35
0
def plotFrame3D(config, vectors, frame, output):
    '''Creates a plot of magnetization vectors in a 3D view.
    
    Args:
        config: configuration dictionary.
	vectors:    numpy array of size [nx, ny, nz, nComps, nIsochromats, 3, nFrames].
        frame:  which frame to plot.
        output: specification of desired output (dictionary from config).

    Returns:
        plot figure.

    '''
    nx, ny, nz, nComps, nIsoc = vectors.shape[:5]
    if config['collapseLocations']:
        xpos = np.zeros([nx])
        ypos = np.zeros([nx])
        zpos = np.zeros([nx])
    else:
        xpos = np.arange(nx)-nx/2+.5
        ypos = -(np.arange(ny)-ny/2+.5)
        zpos = -(np.arange(nz)-nz/2+.5)

    # Create 3D axes
    if nx*ny*nz==1 or config['collapseLocations']:
        aspect = .952 # figure aspect ratio
    elif nz==1 and ny==1 and nx>1:
        aspect = 0.6
    elif nz==1 and nx>1 and ny>1:
        aspect = .75
    else:
        aspect = 1
    figSize = 5 # figure size in inches
    canvasWidth = figSize
    canvasHeight = figSize*aspect
    fig = plt.figure(figsize=(canvasWidth, canvasHeight), dpi=output['dpi'])
    axLimit = max(nx,ny,nz)/2+.5
    if config['collapseLocations']:
        axLimit = 1.0
    ax = fig.gca(projection='3d', xlim=(-axLimit,axLimit), ylim=(-axLimit,axLimit), zlim=(-axLimit,axLimit), fc=colors['bg'])
    ax.set_aspect('equal')
    
    if nx*ny*nz>1 and not config['collapseLocations']:
        azim = -78 # azimuthal angle of x-y-plane
        ax.view_init(azim=azim) #ax.view_init(azim=azim, elev=elev)
    ax.set_axis_off()
    width = 1.65 # to get tight cropping
    height = width/aspect
    left = (1-width)/2
    bottom = (1-height)/2
    if nx*ny*nz==1 or config['collapseLocations']: # shift to fit legend
        left += .035
        bottom += -.075
    else:
        bottom += -.085
    ax.set_position([left, bottom, width, height])

    if output['drawAxes']:
        # Draw axes circles
        for i in ["x", "y", "z"]:
            circle = Circle((0, 0), 1, fill=True, lw=1, fc=colors['circle'])
            ax.add_patch(circle)
            art3d.pathpatch_2d_to_3d(circle, z=0, zdir=i)

        # Draw x, y, and z axes
        ax.plot([-1, 1], [0, 0], [0, 0], c=colors['axis'], zorder=-1)  # x-axis
        ax.text(1.08, 0, 0, r'$x^\prime$', horizontalalignment='center', color=colors['text'])
        ax.plot([0, 0], [-1, 1], [0, 0], c=colors['axis'], zorder=-1)  # y-axis
        ax.text(0, 1.12, 0, r'$y^\prime$', horizontalalignment='center', color=colors['text'])
        ax.plot([0, 0], [0, 0], [-1, 1], c=colors['axis'], zorder=-1)  # z-axis
        ax.text(0, 0, 1.05, r'$z$', horizontalalignment='center', color=colors['text'])

    # Draw title:
    fig.text(.5, 1, config['title'], fontsize=14, horizontalalignment='center', verticalalignment='top', color=colors['text'])

    # Draw time
    time_text = fig.text(0, 0, 'time = %.1f msec' % (config['clock'][frame%(len(config['clock'])-1)]), color=colors['text'], verticalalignment='bottom')

    # TODO: put isochromats in this order from start
    order = [int((nIsoc-1)/2-abs(m-(nIsoc-1)/2)) for m in range(nIsoc)]
    # Draw magnetization vectors
    for z in range(nz):
        for y in range(ny):
            for x in range(nx):
                for c in range(nComps):
                    for m in range(nIsoc):
                        col = colors['comps'][(c) % len(colors['comps'])]
                        M = vectors[x,y,z,c,m,:,frame]
                        Mnorm = np.linalg.norm(M)
                        alpha = 1.-2*np.abs((m+.5)/nIsoc-.5)
                        thres = 0.075*axLimit
                        if Mnorm>thres:
                            arrowScale = 20
                        else:
                            arrowScale = 20*Mnorm/thres # Shrink arrowhead close to origo
                        ax.add_artist(Arrow3D(  [xpos[x], xpos[x]+M[0]], 
                                                [ypos[y], ypos[y]+M[1]],
                                                [zpos[z], zpos[z]+M[2]], 
                                                mutation_scale=arrowScale,
                                                arrowstyle='-|>', shrinkA=0, shrinkB=0, lw=2,
                                                color=col, alpha=alpha, 
                                                zorder=order[m]+nIsoc*int(100*(1-Mnorm))))
        
    # Draw "spoiler" and "FA-pulse" text
    fig.text(1, .94, config['RFtext'][frame], fontsize=14, alpha=config['RFalpha'][frame],
            color=colors['RFtext'], horizontalalignment='right', verticalalignment='top')
    fig.text(1, .88, config['Gtext'][frame], fontsize=14, alpha=config['Galpha'][frame],
            color=colors['Gtext'], horizontalalignment='right', verticalalignment='top')
    fig.text(1, .82, 'spoiler', fontsize=14, alpha=config['spoilAlpha'][frame],
            color=colors['spoilText'], horizontalalignment='right', verticalalignment='top')
    
    # Draw legend:
    for c in range(nComps):
        col = colors['comps'][(c) % len(colors['comps'])]
        ax.plot([0, 0], [0, 0], [0, 0], '-', lw=2, color=col, alpha=1.,
                    label=config['components'][c]['name'])
    handles, labels = ax.get_legend_handles_labels()
    leg = fig.legend([plt.Line2D((0, 1), (0, 0), lw=2, color=colors['comps'][(c) %
                                len(colors['comps'])]) for c, handle in enumerate(
                                handles)], labels, loc=2, bbox_to_anchor=[
                                -.025, .94])
    leg.draw_frame(False)
    for text in leg.get_texts():
        text.set_color(colors['text'])
    
    return fig
示例#36
0
def plotTrajectory3D(M, fig, output_filename='motion.avi'):
    R = M[:, :3].T
    t = M[:, -1]

    rotMat = Rotation.from_matrix(R)  # Rotation object instance
    quat = rotMat.as_quat()
    quat = np.roll(quat, 1)
    transl = -R @ t

    # prelims
    plt.clf()
    # ax = fig.add_subplot(111, projection='3d')
    ax = plt.axes(projection='3d')
    camera = Camera(fig)
    ax.set(xlim=(-.1, .4), ylim=(-.2, .3), zlim=(-.3, 0))
    ax.set_xlabel('Z')
    ax.set_ylabel('X')
    ax.set_zlabel('Y')
    ax.scatter(-Pw_corners[:, 2], Pw_corners[:, 0],
               -Pw_corners[:, 1])  # draw given corners
    # draw rectangles at corners
    r = Rectangle((0, -.22),
                  width=.105,
                  height=.14,
                  color='blue',
                  fill=False,
                  hatch='/')
    ax.add_patch(r)
    art3d.pathpatch_2d_to_3d(r, z=0, zdir='x')
    r1 = Rectangle((.11, -.25),
                   width=.13,
                   height=.1,
                   color='red',
                   fill=False,
                   hatch='/')
    ax.add_patch(r1)
    art3d.pathpatch_2d_to_3d(r1, z=.2, zdir='y')
    r2 = Rectangle((.11, 0),
                   width=.13,
                   height=.11,
                   color='green',
                   fill=False,
                   hatch='/')
    ax.add_patch(r2)
    art3d.pathpatch_2d_to_3d(r2, z=-.265, zdir='z')

    # draw camera coordinate frame onto image
    rotMat = rotMat.as_matrix()
    ax.quiver(-transl[2],
              transl[0],
              -transl[1],
              -rotMat[2, 0],
              rotMat[0, 0],
              -rotMat[1, 0],
              color='red',
              length=.1)
    ax.quiver(-transl[2],
              transl[0],
              -transl[1],
              -rotMat[2, 1],
              rotMat[0, 1],
              -rotMat[1, 1],
              color='green',
              length=.1)
    ax.quiver(-transl[2],
              transl[0],
              -transl[1],
              -rotMat[2, 2],
              rotMat[1, 2],
              -rotMat[1, 2],
              color='blue',
              length=.1)
    # print([-transl[2], transl[0], -transl[1], -rotMat[2,0], rotMat[0,0], -rotMat[1,0]])
    camera.snap()
示例#37
0
def create_plots(robot, obstacles, dist_est, gt_grid, use3d=False):
    fig = plt.figure(figsize=(4 * 2 + 0.5, 4 * 1))
    # fig = plt.figure(figsize=(3*2+0.5, 3 * 1)) # temp
    plt.rcParams.update({
        "text.usetex": True,
        "font.family": "sans-serif",
        "font.sans-serif": ["Helvetica"]
    })
    gs = fig.add_gridspec(1, 3)
    ax = fig.add_subplot(gs[0, 0])
    ax.set_xlim(-8, 8)
    ax.set_ylim(-8, 8)
    ax.set_aspect('equal', adjustable='box')
    ax.set_xticks([-4, 0, 4])
    ax.set_yticks([-4, 0, 4])
    ax.set_xticklabels(['', '', ''])
    ax.set_yticklabels(['', '', ''])
    from matplotlib.cm import get_cmap
    cmap = get_cmap('RdBu_r')
    for obs in obstacles:
        if obs[0] == 'circle':
            ax.add_patch(
                Circle(obs[1],
                       obs[2],
                       path_effects=[path_effects.withSimplePatchShadow()
                                     ]))  #, color=cmaps[1](0.5)))
        elif obs[0] == 'rect':
            ax.add_patch(
                Rectangle((obs[1][0] - float(obs[2][0]) / 2,
                           obs[1][1] - float(obs[2][1]) / 2),
                          obs[2][0],
                          obs[2][1],
                          path_effects=[path_effects.withSimplePatchShadow()],
                          color=cmap(0.8)))  #, color=cmaps[0](0.5)))
            print((obs[1][0] - obs[2][0] / 2, obs[1][1] - obs[2][1] / 2))

    # Placeholder of the robot plot
    trans = ax.transData.transform
    lw = ((trans((1, robot.link_width)) - trans(
        (0, 0))) * 72 / ax.figure.dpi)[1]
    # q = torch.FloatTensor([-np.pi/8, -np.pi/4])#-np.pi/4])
    q = torch.ones(
        robot.dof) * np.pi / 6 * (torch.randint(0, 3, [robot.dof]) - 1)
    points = robot.fkine(q)[0]
    points = torch.cat([torch.zeros(1, 2), points], dim=0)

    link_plot, = ax.plot(
        points[:, 0],
        points[:, 1],
        color='orange',
        alpha=1,
        lw=lw,
        solid_capstyle='round',
        path_effects=[path_effects.SimpleLineShadow(),
                      path_effects.Normal()])
    joint_plot, = ax.plot(points[:-1, 0],
                          points[:-1, 1],
                          'o',
                          color='tab:red',
                          markersize=lw)
    eff_plot, = ax.plot(points[-1:, 0],
                        points[-1:, 1],
                        'o',
                        color='black',
                        markersize=lw)

    # ax.axis('off')
    # return None, None

    size = [400, 400]
    yy, xx = torch.meshgrid(torch.linspace(-np.pi, np.pi, size[0]),
                            torch.linspace(-np.pi, np.pi, size[1]))
    grid_points = torch.stack([xx, yy], axis=2).reshape((-1, 2))
    est_grid = dist_est(grid_points).reshape(size)
    gt_grid = gt_grid.reshape(size)
    # gt_grid = torch.from_numpy(ndimage.gaussian_filter(gt_grid, 15))
    # est_grid = torch.from_numpy(ndimage.gaussian_filter(est_grid, 3))

    c_axes = []
    with sns.axes_style('ticks'):
        for i, d in enumerate([gt_grid, est_grid], 1):
            # for i, d in enumerate([est_grid], 1): #TEMP
            # for i, d in enumerate([gt_grid], 1): # for clustering
            c_ax = fig.add_subplot(gs[0, i],
                                   projection='3d' if use3d else None)

            if use3d:
                from matplotlib import cm
                # c_ax.plot_wireframe(xx.numpy(), yy.numpy(), d.numpy(), alpha=1, #vmin=-d.max(), vmax=d.max(),
                #     rstride=10, cstride=10, linewidth=0.1, antialiased=False, edgecolor='black') # , 'RdBu_r'
                surf = c_ax.plot_surface(
                    xx.numpy(),
                    yy.numpy(),
                    d.numpy(),
                    alpha=1,  #vmin=-d.max(), vmax=d.max(), 
                    rstride=10,
                    cstride=10,
                    linewidth=0.1,
                    antialiased=True,
                    cmap='Greys_r',
                    edgecolor='black')  # , 'RdBu_r' cmap='Greys_r',
                # c_ax.plot_wireframe(xx.numpy(), yy.numpy(), d.numpy(), rstride=5, cstride=5, color='black')
                # surf._facecolors2d=surf._facecolor3d
                # surf._facecolors3d = 'face'
                # surf.set_edgecolor('none')
                # c_ax.contour3D(xx, yy, d, 50, linewidths=1, alpha=1)
                # c_ax.plot_surface(xx[::199, ::199], yy[::199, ::199].numpy(), np.zeros_like(yy[::199, ::199].numpy()), alpha=0.3) #, vmin=-torch.abs(d).max(), vmax=torch.abs(d).max()) #cmap='RdBu_r',
            else:
                color_mesh = c_ax.pcolormesh(
                    xx,
                    yy,
                    d,
                    cmap='RdBu_r',
                    vmin=-torch.abs(d).max(),
                    vmax=torch.abs(
                        d).max())  #, alpha=0.5) # binary shading='gouraud',
                c_ax.contour(xx, yy, d, levels=[0], linewidths=1,
                             alpha=0.4)  #-1.5, -0.75, 0, 0.3

            # ============arrows and configuration point========
            sparse_stride = 20
            sparse_score = d[5:-5:sparse_stride, 5:-5:sparse_stride]
            score_grad_x = -ndimage.sobel(sparse_score.numpy(), axis=1)
            score_grad_y = -ndimage.sobel(sparse_score.numpy(), axis=0)
            if use3d:
                score_grad = np.stack([
                    score_grad_x, score_grad_y,
                    -(score_grad_x**2 + score_grad_y**2)
                ],
                                      axis=2)
                score_grad /= np.linalg.norm(score_grad, axis=2, keepdims=True)
                score_grad_x, score_grad_y, score_grad_z = [
                    score_grad[:, :, dim] for dim in range(3)
                ]
            else:
                score_grad = np.stack([score_grad_x, score_grad_y], axis=2)
                score_grad /= np.linalg.norm(score_grad, axis=2,
                                             keepdims=True) / 10
                score_grad_x, score_grad_y = score_grad[:, :,
                                                        0], score_grad[:, :, 1]
            if use3d:
                # c_ax.quiver(xx[5:-5:sparse_stride, 5:-5:sparse_stride], yy[5:-5:sparse_stride, 5:-5:sparse_stride], sparse_score+0.05,
                #     score_grad_x, score_grad_y, score_grad_z,
                #     color='red') #width=1e-2, headwidth=2, headlength=5
                c_ax.set_aspect('auto', adjustable='box')
                nearest_gridpoint = np.argmin(
                    np.square(grid_points - q).sum(axis=1))
                print(
                    xx.reshape(-1)[nearest_gridpoint],
                    yy.reshape(-1)[nearest_gridpoint],
                )
                q_score = d.reshape(-1, 1)[nearest_gridpoint]
                # c_ax.scatter([q[0].item()], [q[1].item()], q_score+0.5, marker='o', s=40, c='orange', edgecolors='black', zorder=100)
                circle_patch = Circle([q[0].item(), q[1].item()],
                                      np.pi / 20,
                                      ec='k',
                                      fc="orange",
                                      alpha=1)
                c_ax.add_patch(circle_patch)
                from mpl_toolkits.mplot3d import art3d
                art3d.pathpatch_2d_to_3d(circle_patch, z=q_score, zdir="z")
                c_ax.view_init(60, 225)
                c_ax.set_facecolor('white')
                c_ax.w_xaxis.set_pane_color(ax.get_facecolor())
                c_ax.w_yaxis.set_pane_color(ax.get_facecolor())
                c_ax.w_zaxis.set_pane_color(ax.get_facecolor())
            else:
                c_ax.quiver(xx[5:-5:sparse_stride, 5:-5:sparse_stride],
                            yy[5:-5:sparse_stride, 5:-5:sparse_stride],
                            score_grad_x,
                            score_grad_y,
                            color='red',
                            width=1e-2,
                            headwidth=2,
                            headlength=5,
                            pivot='mid')
                c_ax.set_aspect('equal', adjustable='box')
                c_ax.scatter([q[0].item()], [q[1].item()],
                             marker='o',
                             s=40,
                             c='orange',
                             edgecolors='black')
            # fig.colorbar(color_mesh, ax=c_ax)

            # c_ax.axis('equal')
            c_ax.set_xlim(-np.pi, np.pi)
            c_ax.set_ylim(-np.pi, np.pi)
            c_ax.set_xticks([-np.pi, 0, np.pi])
            c_ax.set_xticklabels(['$-\pi$', '$0$', '$\pi$'])
            c_ax.set_yticks([-np.pi, 0, np.pi])
            c_ax.set_yticklabels(['$-\pi$', '$0$', '$\pi$'])
            c_axes.append(c_ax)
            c_ax.grid(False)

    return est_grid.reshape(-1), c_axes
示例#38
0
def grayimg_as_function(**kwargs):
    img_path = kwargs['img_path']

    # get viewing angle and num_slides args
    num_frames = 100
    if 'num_frames' in kwargs:
        num_frames = kwargs['num_frames']
    start_view = [90, 90]
    end_view = [-90, 270]
    if 'end_view' in kwargs:
        end_view = kwargs['end_view']
    plot_type = 'scatter'
    if 'plot_type' in kwargs:
        plot_type = kwargs['plot_type']
    shrink_factor = 0.1
    if 'shrink_factor' in kwargs:
        shrink_factor = kwargs['shrink_factor']

    # construct viewing angles
    view1 = np.linspace(start_view[0], end_view[0], num_frames)
    view2 = np.linspace(start_view[1], end_view[1], num_frames)

    img = Image.open(img_path)
    orig_img = img.copy()
    gray = np.array(img.convert('L'))
    img = img.resize((round(shrink_factor * np.shape(gray)[1]),
                      round(shrink_factor * np.shape(gray)[0])),
                     Image.ANTIALIAS)
    gray = np.array(img.convert('L'))

    # create figure to plot
    fig = plt.figure(num=None,
                     figsize=(7, 7),
                     dpi=80,
                     facecolor='w',
                     edgecolor='k')
    artist = fig

    ### create 3d plot in left panel
    ax2 = plt.subplot(111, projection='3d')
    ax2.axis('off')
    fig.subplots_adjust(left=0, right=1, bottom=0,
                        top=1)  # remove whitespace around 3d figure

    # setup 3d ground to plot over
    s = np.shape(gray)[0]
    t = np.shape(gray)[1]
    s = np.arange(0, s, 1)
    t = np.arange(0, t, 1)
    xpos, ypos = np.meshgrid(t, s)
    zpos = np.ones((np.shape(xpos)))

    # plot 3d surface
    if plot_type == 'continuous':
        ax2.plot_surface(xpos,
                         ypos,
                         gray,
                         cmap='gray',
                         antialiased=True,
                         edgecolor='w',
                         linewidth=0.15)
    if plot_type == 'scatter':
        ax2.scatter(xpos,
                    ypos,
                    gray.astype(float),
                    marker='s',
                    s=20,
                    c=1 - gray.astype(float) / float(255),
                    cmap=plt.cm.Greys,
                    alpha=1,
                    edgecolor='w',
                    linewidth=0.5)
        ax2.set_facecolor((1, 0.8, 1))
        ax2.set_aspect('auto')

        ax2.set_xlim(10, np.shape(gray)[1] - 0)
        ax2.set_ylim(10, np.shape(gray)[0] - 10)

    if plot_type == 'proto':
        ### plot surface in right panel
        max_color = max(gray.flatten())
        for i in range(gray.shape[1]):
            for j in range(gray.shape[0]):
                level = gray[j, gray.shape[1] - i - 1]
                col = float(level) / float(max_color)
                rec = Rectangle((i - 1, j - 1),
                                1,
                                1,
                                color=[col, col, col],
                                linewidth=0)
                ax2.add_patch(rec)
                art3d.pathpatch_2d_to_3d(rec, z=level, zdir='z')

        ax2.set_xlim([-8, gray.shape[0] + 8])
        ax2.set_ylim([-8, gray.shape[1] + 8])
        ax2.set_zlim([0, max_color + 1])

    print('starting animation rendering...')

    # animation sub-function
    def animate(k):
        # print rendering update
        if np.mod(k + 1, 25) == 0:
            print('rendering animation frame ' + str(k + 1) + ' of ' +
                  str(num_frames))
        if k == num_frames - 1:
            print('animation rendering complete!')
            time.sleep(1.5)
            clear_output()

        ax2.view_init(view1[k], view2[k])
        ax2.set_facecolor('white')

        return artist,

    anim = animation.FuncAnimation(fig,
                                   animate,
                                   frames=num_frames,
                                   interval=num_frames,
                                   blit=True)
    return (anim)
示例#39
0
# Priests, as highest members of the society, are circles.

import matplotlib.pyplot as plt
from matplotlib.patches import Circle
import mpl_toolkits.mplot3d.art3d as art3d

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
circle = Circle((0.5,0.5), 0.2, facecolor="none")
ax.add_patch(circle)
ax.view_init(elev=-2.7, azim=0) # bit annoying - for some reason, elev=0 doesn't work in this case.
art3d.pathpatch_2d_to_3d(circle, z=0, zdir="z")
plt.show()
示例#40
0
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

h = -1 #Altura (z)
b = 0.999999999 #Radio 2
cg = 0
c = 0.55191502449 #constante para mostrar un circulo

#Vaso del mortero (cuerpo)
for i in range(0, 65):
	if i == 0:
		p = Circle((0, 0), b, color="green", fill=True)
	else:
		p = Circle((0, 0), b, color="green", fill=False)
	ax.add_patch(p)
	art3d.pathpatch_2d_to_3d(p, z = h)

	if i<5:
		b = b + 0.1
	elif i<10:
		b = b - 0.1
	elif i<30:
		b = b + 0.1
	elif i<55:
		b= b
	elif i>55:
		b = b -0.1

	h = h + 0.02
h = h - (0.02)*5
#Generar con curvas de Bezier la salida del mortero
示例#41
0
    def draw(self, show=True):
        matplotlib.rcParams['legend.fontsize'] = 10
        fig = plt.figure(figsize=(8, 6))
        ax = fig.add_subplot(111, projection='3d')
        ax.set_title(self.__title)
        ax.set_xlabel('Station')
        ax.set_ylabel('X')
        ax.set_zlabel('Y')
        legends = {}
        if self.__draw_all_hits:
            for fake_hit in self.__fake_hits:
                ax.scatter(fake_hit[0],
                           fake_hit[1],
                           fake_hit[2],
                           c=self.__color_map[-1],
                           marker='o')

        if self.__draw_all_tracks_from_df:
            for adj_val in self.__adj_track_list:
                col, lab, tr_id = self.draw_edge(adj_val, ax)
                if int(tr_id) not in legends:
                    legends[int(tr_id)] = mpatches.Patch(color=col, label=lab)

        for adj_val in self.__reco_adj_list:
            col, lab, tr_id = self.draw_edge(adj_val, ax)
            if int(tr_id) not in legends:
                legends[int(tr_id)] = mpatches.Patch(color=col, label=lab)

        for ell_data in self.__nn_preds:
            ell = Ellipse(xy=ell_data[2],
                          width=ell_data[3][0],
                          height=ell_data[3][1],
                          color='red')
            ax.add_patch(ell)
            art3d.pathpatch_2d_to_3d(ell, z=ell_data[0], zdir="x")
            col, lab, tr_id = self.draw_edge_from_idx_to_pnt(
                ell_data[1], [ell_data[0], ell_data[2][0], ell_data[2][1]], ax)
            if int(tr_id) not in legends:
                legends[int(tr_id)] = mpatches.Patch(color=col, label=lab)

        for station_id, coord_planes in enumerate(self.__coord_planes):
            for rect_data in coord_planes:
                rect = Rectangle(xy=(rect_data[0] - rect_data[2] / 2,
                                     rect_data[1] - rect_data[3] / 2),
                                 width=rect_data[2],
                                 height=rect_data[3],
                                 linewidth=1,
                                 edgecolor='black',
                                 facecolor='none')
                ax.add_patch(rect)
                art3d.pathpatch_2d_to_3d(rect, z=station_id, zdir="x")

        fig.legend(handles=list(legends.values()))
        # for single_data, with_edges, with_pnts, title in self.__all_data:
        #     legends = {}
        #     for (fr_p, to_p, dist) in single_data:
        #         color, label, tr_id = self.generate_color_label(fr_p.track, to_p.track)
        #         if with_edges:
        #             ax.plot((fr_p.station, to_p.station), (fr_p.x, to_p.x), zs=(fr_p.y, to_p.y),
        #                     c=color)
        #         marker_1 = 'h' if fr_p.track == -1 else 'o'
        #         marker_2 = 'h' if to_p.track == -1 else 'o'
        #         if with_pnts:
        #             ax.scatter(fr_p.station, fr_p.x, fr_p.y, c =self.__color_map[int(fr_p.track)], marker=marker_1)
        #             ax.scatter(to_p.station, to_p.x, to_p.y, c =self.__color_map[int(to_p.track)], marker=marker_2)
        #         if int(tr_id) not in legends:
        #             legends[int(tr_id)] = mpatches.Patch(color=color, label=label)
        #     fig.legend(handles=list(legends.values()))

        plt.draw_all()
        plt.tight_layout()
        if show:
            plt.show()
        pass
示例#42
0
文件: odak.py 项目: kunguz/odak
 def PlotCircle(self,center,r,c='none'):
     # Method to plot circle.
     circle = Circle((center[0], center[1]), r, facecolor=c, edgecolor=(0,0,0), linewidth=4, alpha=1)
     self.ax.add_patch(circle)
     art3d.pathpatch_2d_to_3d(circle, z=center[2], zdir='z')
     return array([center,r])
示例#43
0
def plot_camera(ax):
    p = Rectangle((0, 0), 0.1, 0.1, ec="black", fill=False)
    ax.add_patch(p)
    art3d.pathpatch_2d_to_3d(p, z=0, zdir="y")
示例#44
0
# def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):

#     x, y, z = xyz
#     if zdir == "y":
#         xy1, z1 = (x, z), y
#     elif zdir == "y":
#         xy1, z1 = (y, z), x
#     else:
#         xy1, z1 = (x, y), z

#     text_path = TextPath((0, 0), s, size=size, usetex=usetex)
#     trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])

#     p1 = PathPatch(trans.transform_path(text_path), **kwargs)
#     ax.add_patch(p1)
#     art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

p = Circle((5, 5), 3)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")

ax.set_xlim3d(0, 10)
ax.set_ylim3d(0, 10)
ax.set_zlim3d(0, 10)

plt.show()
示例#45
0
def reveal_imgpatch(**kwargs):
    # grab user defined args
    img_path = kwargs['img_path']
    shrink_factor = 1
    if 'shrink_factor' in kwargs:
        shrink_factor = kwargs['shrink_factor']

    img = Image.open(img_path)
    gray = np.array(img.convert('L'))
    img = img.resize((round(shrink_factor * np.shape(gray)[1]),
                      round(shrink_factor * np.shape(gray)[0])),
                     Image.ANTIALIAS)
    gray = np.array(img.convert('L'))

    # setup figure
    fig = plt.figure(figsize=(18, 5))
    gs = gridspec.GridSpec(1,
                           3,
                           width_ratios=[1, 1, 1],
                           wspace=0.0,
                           hspace=0.0)
    ax1 = plt.subplot(gs[0])
    ax1.axis('off')
    ax2 = plt.subplot(gs[1])
    ax3 = plt.subplot(gs[2], projection='3d')

    ### plot raw image in left panel
    ax1.imshow(gray, cmap=plt.cm.gray)
    ax1.grid(False)
    ax1.axis('off')

    ### plot image with pixel numbering in middle panel
    ax2.imshow(gray, cmap=plt.cm.gray)

    # plot pixel values as numbers on top
    min_val, max_val = 0, gray.shape[0]
    diff = 1
    ind_array1 = np.arange(min_val, max_val, diff)
    min_val, max_val = 0, gray.shape[1]
    ind_array2 = np.arange(min_val, max_val, diff)

    x, y = np.meshgrid(ind_array1, ind_array2)

    for x_val, y_val in zip(x.flatten(), y.flatten()):
        c = int(gray[x_val, y_val])
        ax2.text(y_val,
                 x_val,
                 c,
                 va='center',
                 ha='center',
                 color='red',
                 fontsize=13)

    # set tickmarks and grid correctly
    ax2.set_xticks(np.arange(np.shape(gray)[1]), minor=False)
    ax2.set_yticks(np.arange(np.shape(gray)[0]), minor=False)
    ax2.set_xticks(np.arange(np.shape(gray)[1]) - 0.5, minor=True)
    ax2.set_yticks(np.arange(np.shape(gray)[0]) - 0.5, minor=True)
    ax2.grid(which='minor', color='w', linestyle='-', linewidth=2)

    ### plot surface in right panel
    max_color = max(gray.flatten())
    for i in range(gray.shape[1]):
        for j in range(gray.shape[0]):
            level = gray[j, gray.shape[1] - i - 1]
            col = float(level) / float(max_color)
            rec = Rectangle((i - 1, j - 1),
                            1,
                            1,
                            color=[col, col, col],
                            linewidth=0)
            ax3.add_patch(rec)
            art3d.pathpatch_2d_to_3d(rec, z=level, zdir='z')
    ax3.set_xlim([-1, gray.shape[0]])
    ax3.set_ylim([-1, gray.shape[1]])
    ax3.set_zlim([0, max_color + 1])
    ax3.view_init(20, -290)

    # set tickmarks correctly
    ax3.set_xticks(np.arange(np.shape(gray)[1]))
    ax3.set_xticklabels(np.flipud(np.arange(np.shape(gray)[1])), ha='center')
    ax3.set_yticks(np.arange(np.shape(gray)[0]))
    ax3.set_yticklabels(np.arange(np.shape(gray)[0]), ha='center')

    plt.show()
示例#46
0
def plot_embedding_distribution(W,
                                pi,
                                mu,
                                sigma,
                                labels=None,
                                N=100,
                                colors=None):

    # TODO : labels colors
    if (labels is None):
        # color depending from gaussian prob
        pass
    else:
        # color depending from labels given
        pass

    # plotting prior
    X = np.linspace(-1, 1, N)
    Y = np.linspace(-1, 1, N)
    X, Y = np.meshgrid(X, Y)
    # plotting circle
    X0, Y0, radius = 0, 0, 1
    r = np.sqrt((X - X0)**2 + (Y * Y0)**2)
    disc = r < 1

    Z = np.zeros((N, N))
    # compute the mixture
    for z_index in range(len(Z)):
        #    print(torch.Tensor(X[z_index]))
        x = torch.cat((torch.FloatTensor(X[z_index]).unsqueeze(-1),
                       torch.FloatTensor(Y[z_index]).unsqueeze(-1)), -1)
        zz = weighted_gmm_pdf(pi, x, mu, sigma, pf.distance)
        zz[zz != zz] = 0
        #    print(zz.size())
        #    print(zz)
        #    print(weighted_gmm_pdf(pi, mu, mu, sigma, pf.distance))
        Z[z_index] = zz.sum(-1).numpy()
    # print(Z.max())
    fig = plt.figure("Embedding-Distribution")
    ax = fig.add_subplot(111, projection='3d')
    ax = fig.gca(projection='3d')
    ax.plot_surface(X,
                    Y,
                    Z,
                    rstride=1,
                    cstride=1,
                    linewidth=1,
                    antialiased=True,
                    cmap=plt.get_cmap("viridis"))
    z_circle = -0.8
    p = Circle((0, 0), 1, edgecolor='b', lw=1, facecolor='none')
    ax.add_patch(p)
    art3d.pathpatch_2d_to_3d(p, z=z_circle, zdir="z")

    for q in range(len(W)):
        if (colors is not None):
            ax.scatter(W[q][0].item(),
                       W[q][1].item(),
                       z_circle,
                       c=[colors[q]],
                       marker='.')
        else:
            ax.scatter(W[q][0].item(),
                       W[q][1].item(),
                       z_circle,
                       c='b',
                       marker='.')
        #print('Print labels', labels[q])

    for j in range(len(mu)):
        ax.scatter(mu[j][0].item(),
                   mu[j][1].item(),
                   z_circle,
                   c='r',
                   marker='D')

    ax.set_xlim(-1.2, 1.2)
    ax.set_ylim(-1.2, 1.2)
    ax.set_zlim(-0.8, 0.4)

    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('P')

    plt.savefig("figures/embeddings_karate_node_distrib.pdf", format="pdf")

    return fig
#draw sphere
def drawSphere(x=0,y=0,z=0,r=1):
    u, v = np.mgrid[0:2*np.pi:16j, 0:np.pi:11j]
    cx= x + np.cos(u)*np.sin(v) * r
    cy= y + np.sin(u)*np.sin(v) * r
    cz= z + np.cos(v) * r
    return ax.plot_wireframe(cx, cy, cz, color="grey", linestyle='dotted' )

drawSphere(r=2)

# Draw lat, long arrows
theta = 35
for i in ["y", "z"]:
    arc = Arc((0,0), 4, 4, angle=0, theta1=0, theta2=theta)
    ax.add_patch(arc)
    art3d.pathpatch_2d_to_3d(arc, z=0, zdir=i)
    #arrow = Arrow(0, 0, 0.4, 0.4, 0.4)
    #ax.add_patch(arrow)
    #ßart3d.pathpatch_2d_to_3d(arrow, z=2, zdir=i)

#earth
drawSphere(10,0,0,0.5)


class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs
    
    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
示例#48
0
def pseudocolor(val, minval, maxval):
    # convert val in range minval..maxval to the range 0..120 degrees which
    # correspond to the colors red..green in the HSV colorspace
    h = (-1*(float(val-minval) / (maxval-minval)) * 120) % 360
    # convert hsv color (h,1,1) to its rgb equivalent
    # note: the hsv_to_rgb() function expects h to be in the range 0..1 not 0..360
    r, g, b = colorsys.hsv_to_rgb(h/360, 1., 1.)
    return r, g, b 


for f in filaments:
    c = pseudocolor(-f.current_1, -.30, .30)
    print str(c) + " " + str(f.current_1)
    p = Circle((0, 0), radius=f.r, color=c, linewidth=1.5, fill=False, alpha=0.5)
    ax.add_patch(p)
    art3d.pathpatch_2d_to_3d(p, z=f.z, zdir="z")

#for i in range(len(tokamak.VFR)):
#    p = Circle((0, 0), radius=tokamak.VFR[i], color='#8ffe09', linewidth=1.5, fill=False, alpha=0.5)
#    ax.add_patch(p)
#    art3d.pathpatch_2d_to_3d(p, z=tokamak.VFZ[i], zdir="z")


#for s in sensors:
#    name = s.name[0:2] + s.name[4:8]
#    text3d(ax, (s.x, s.y, s.z),
#           name,
#           zdir="y", size=0.07, usetex=False,
#           ec="none", fc="k")

lim = 0.8 
def calculate_loading_order(NUM_LOCAL, NUM_BOX, TRUCK_L, TRUCK_W, TRUCK_H,
                            inputBox, truck):
    # 각 지역별 상자의 개수만큼 check 생성(check에 각 상자의 적재 여부 저장)
    check = []
    for i in range(0, NUM_LOCAL):
        check.append([])
        for j in range(0, NUM_BOX[i]):
            check[i].append(0)
    sum_num_box = 0  # 각 지역별 적재 범위를 계산하기 위함
    finish = [0, 0, 0]  # 각 지역별 적재 완료된 상자의 개수를 저장할 변수
    ## 측정을 위한 변수
    count_W = 0  # 상자를 적재할 빈 공간의 너비를 측정하기 위한 변수
    count_L = 0  # 막힌 공간의 길이를 측정하기 위한 변수
    count_H = 0  # 막힌 공간의 높이를 측정하기 위한 변수
    ## Loading Box
    for i in range(NUM_LOCAL):  # 각 지역별로 수행
        floor = 0  # 현재 적재하고 있는 층수
        sum_num_box += NUM_BOX[i]  # 앞 지역부터 상자의 개수를 더함
        while True:
            if finish[i] == NUM_BOX[i]:  # 해당 지역 상자들의 적재가 끝나기 전까지 반복
                break

            # endOfL(현재 층에서 가장 작은 길이를 측정하기 위한 변수) 계산
            endOfL = TRUCK_L
            for j in range(TRUCK_W):  # 너비 방향으로 검사
                count_L = 0
                while truck[count_L][j][floor * BOX_H] != 0:  # 빈 공간이 나올때까지 반복
                    if count_L == TRUCK_L - 1:  # truck의 인덱스 끝까지 가면 탈출
                        break
                    count_L += 1  # endOfL을 계산하기 위해 count_L을 증가시킴
                if count_L == TRUCK_L - 1:  # count_L이 TRUCK_L-1이어서 위 while문을 탈출했다면
                    count_L += 1  # 실제 길이를 구하기 위해 1을 더함
                # endOfL은 길이의 최소값이므로 최소값을 구함
                if count_L < endOfL:
                    endOfL = count_L
            # 한 층에 각 지역에 할당된 길이만큼 적재되었거나 트럭 길이 끝까지 적재된 경우 층수 증가
            if endOfL >= TRUCK_L * (sum_num_box /
                                    sum(NUM_BOX)) or endOfL >= TRUCK_L:
                floor += 1
                if floor > TRUCK_H / BOX_H - 1:
                    floor = 0
            # 상자를 적재할 위치 계산
            min_L = TRUCK_L  # 적재된 상자들이 차지한 가장 작은 길이(최소값을 찾기 위해 큰 값으로 초기화)
            measureMode = 0  # 측정 모드 플래그: 비어있는 공간의 너비를 측정하고 있으면 1, 아니면 0
            for j in range(TRUCK_L):  # 길이 방향으로 검사
                count_W = 0
                for k in range(TRUCK_W):  # 너비 방향으로 검사
                    if truck[j][k][floor * BOX_H] == 0:  # 0이면(비어있는 공간이면)
                        if measureMode == 0:  # 측정 모드가 아니었다면
                            if j < min_L:  # 적재한 상자들이 차지하는 공간의 길이의 최소값이면
                                measureMode = 1  # 측정 모드로 전환
                                min_L = j  # 최소값 갱신
                                pos_X = j  # 상자를 적재할 x축 좌표 저장
                                pos_Y = k  # 상자를 적재할 y축 좌표 저장
                                pos_Z = floor * BOX_H
                                count_W = 1  # 빈 공간의 너비를 세기 시작함
                        else:  # 측정모드이면
                            count_W += 1  # 상자가 들어갈 수 있는 너비를 측정하기 위해 count_W를 증가
                    else:  # 1 또는 2이면(막혀있는 공간이면)
                        if measureMode == 1:  # 측정 모드였다면
                            measureMode = 0  # 측정 모드 해제
                if count_W > 0:  # 해당 줄에 빈 공간이 있었다면
                    break  # j에 대한 for 문 탈출
            # 적재할 상자 선택(5가지 조건 확인)
            max_box_W = 0  # count_W 너비 안에 들어갈 수 있는 최대 너비의 상자 너비
            for j in range(NUM_BOX[i]):
                cannot_load = 0
                if check[i][j] == 0 and j in inputBox[i]:
                    if inputBox[i][j][
                            'w'] <= count_W:  # 1. 아직 적재하지 않은 상자이고, 너비가 count_W 이하면
                        if inputBox[i][j][
                                'w'] > max_box_W:  # 2. 최대 너비를 가진 상자를 찾음
                            # 3. 해당 위치에 상자를 적재했을 때 트럭 높이를 넘지 않는지 확인
                            count_H = 0  # 해당 위치에 상자 적재 전 높이
                            while truck[pos_X][pos_Y][count_H] != 0:
                                count_H += 1
                            if count_H + inputBox[i][j]['h'] > TRUCK_H:
                                continue
                            # 4. 해당 위치에 상자를 적재했을 때 트럭 길이를 넘지 않는지 확인
                            count_L = 0
                            while truck[count_L][pos_Y][pos_Z] != 0:
                                count_L += 1
                            if count_L + inputBox[i][j]['l'] > TRUCK_L:
                                continue
                            # 5. 적재할 상자의 아래가 막혀있는지 확인
                            if pos_Z - 1 != -1:  # 가장 아래층인 경우 Z좌표가 -1이므로 따로 조건을 줌
                                for x in range(inputBox[i][j]['l']):
                                    for y in range(inputBox[i][j]['w']):
                                        if truck[pos_X + x][pos_Y + y][pos_Z -
                                                                       1] == 0:
                                            cannot_load = 1
                                            break
                                if cannot_load == 1:
                                    continue
                            boxIndex = j  # 이번에 적재할 상자 인덱스 저장
                            max_box_W = inputBox[i][j]['w']  # 최대 너비 갱신

            # 상자 적재 또는 빈 공간 채우기
            if max_box_W == 0:  # 해당 공간에 적재할 수 있는 상자가 없다면 빈공간 채우기
                # 2로 채움
                for y in range(count_W):
                    for z in range(BOX_H):
                        truck[pos_X][pos_Y + y][pos_Z + z] = 2
            else:  # 해당 공간에 적재할 수 있는 상자가 있다면 상자 적재
                for x in range(inputBox[i][boxIndex]['l']):
                    for y in range(inputBox[i][boxIndex]['w']):
                        for z in range(inputBox[i][boxIndex]['h']):
                            if i == 0:
                                truck[pos_X + x][pos_Y +
                                                 y][pos_Z +
                                                    z] = 3  # A 지역은 3 할당
                            elif i == 1:
                                truck[pos_X + x][pos_Y +
                                                 y][pos_Z +
                                                    z] = 4  # B 지역은 4 할당
                            else:
                                truck[pos_X + x][pos_Y +
                                                 y][pos_Z +
                                                    z] = 5  # C 지역은 5 할당
                finish[i] += 1  # 적재 완료된 상자 수 갱신
                check[i][boxIndex] = 1  # 적재 완료된 상자 체크
                # 상자의 시각화
                # 밑면
                side = Rectangle((pos_X, pos_Y),
                                 inputBox[i][boxIndex]['l'],
                                 inputBox[i][boxIndex]['w'],
                                 fill=True,
                                 facecolor=colors[i],
                                 edgecolor='black')
                ax.add_patch(side)
                art3d.pathpatch_2d_to_3d(side, z=pos_Z, zdir='z')
                # 윗면
                side = Rectangle((pos_X, pos_Y),
                                 inputBox[i][boxIndex]['l'],
                                 inputBox[i][boxIndex]['w'],
                                 fill=True,
                                 facecolor=colors[i],
                                 edgecolor='black')
                ax.add_patch(side)
                art3d.pathpatch_2d_to_3d(side,
                                         z=pos_Z + inputBox[i][boxIndex]['h'],
                                         zdir='z')
                # 뒷면
                side = Rectangle((pos_Y, pos_Z),
                                 inputBox[i][boxIndex]['w'],
                                 inputBox[i][boxIndex]['h'],
                                 fill=True,
                                 facecolor=colors[i],
                                 edgecolor='black')
                ax.add_patch(side)
                art3d.pathpatch_2d_to_3d(side, z=pos_X, zdir='x')
                # 앞면
                side = Rectangle((pos_Y, pos_Z),
                                 inputBox[i][boxIndex]['w'],
                                 inputBox[i][boxIndex]['h'],
                                 fill=True,
                                 facecolor=colors[i],
                                 edgecolor='black')
                ax.add_patch(side)
                art3d.pathpatch_2d_to_3d(side,
                                         z=pos_X + inputBox[i][boxIndex]['l'],
                                         zdir='x')
                # 왼쪽
                side = Rectangle((pos_X, pos_Z),
                                 inputBox[i][boxIndex]['l'],
                                 inputBox[i][boxIndex]['h'],
                                 fill=True,
                                 facecolor=colors[i],
                                 edgecolor='black')
                ax.add_patch(side)
                art3d.pathpatch_2d_to_3d(side, z=pos_Y, zdir='y')
                # 오른쪽
                side = Rectangle((pos_X, pos_Z),
                                 inputBox[i][boxIndex]['l'],
                                 inputBox[i][boxIndex]['h'],
                                 fill=True,
                                 facecolor=colors[i],
                                 edgecolor='black')
                ax.add_patch(side)
                art3d.pathpatch_2d_to_3d(side,
                                         z=pos_Y + inputBox[i][boxIndex]['w'],
                                         zdir='y')
                plt.draw()  # 화면에 plot
                plt.pause(0.0001)
                print("This Box is [%s%02d]" %
                      (chr(i + 65), boxIndex))  # 현재 적재한 상자의 정보를 화면에 출력
                input(
                    "Press Enter to load next box")  # Enter 키를 입력하면 다음 상자를 적재
    print("Finish loading all your boxes!")
    plt.draw()  # 마지막으로 plot
    plt.pause(60)  # 1분간 유지
示例#50
0
        y_globmin = y_min


    if (y_globmax < y_max):
        y_globmax = y_max


    rect = Rectangle(
        (x_min,y_min),   # (x,y)
        x_max-x_min,          # width
        y_max-y_min,          # height
        color=colors[i],
        alpha=0.3
    )
    ax.add_patch(rect)
    art3d.pathpatch_2d_to_3d(rect, z=(-0.5 + i/10.0), zdir="z")
    rects.append((x_globmin,x_globmax,y_globmin,y_globmax))

print "Boundaries are x in ",x_globmin,",",x_globmax,"; y in ",y_globmin,",",y_globmax

X = np.arange(math.floor(x_globmin),math.ceil(x_globmax),RES)
Y = np.arange(math.floor(y_globmin),math.ceil(y_globmax),RES)
print "X = ",X
print "Y = ",Y
Z = {}

for i in range(NUM_RECTS+1):
    Z[i] = []
print Z

for (k,rect) in enumerate(rects):
示例#51
0
文件: logo.py 项目: rmhilman/tacoma
    #if i == 0 or i == 5:
    if True:
        text3d(ax, (1.5, 0.7, x[i]),
               '$t_{%d}$' % (i),
               zdir="x",
               size=1.1,
               usetex=False,
               ec="None",
               fc="k")
    if i != 0 and i != 5:
        ax.plot([x[i], x[i]], [2.4, 4.1], [0.7, 0.7], ':', c=[0.7] * 3, lw=1)

p = Rectangle((2.7, 0.7), 6, 8, capstyle='round', fill=False)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")

p = Rectangle((2.7, 0.7), 6, 8, capstyle='round', fill=False)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=i * 2, zdir="x")

ax.plot([0, 0], [6, 7], [6, 7], '-k')
ax.plot([10, 10], [5.8, 6.9], [4.5, 3.7], '-k')

ax.plot([10, 10], [6, 7.3], [6, 5.4], '-k')
ax.plot([10, 10], [7, 7.3], [7, 5.4], '-k')
ax.plot([10, 10], [6, 7], [6, 7], '-k')

p = Circle((7, 7), 0.2, color='w', ec='k')
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")
示例#52
0
                         cstride=1,
                         rstride=1)
    ax_grad.contour(X,
                    Y,
                    Z,
                    zdir='z',
                    offset=-50,
                    cmap=cm.coolwarm,
                    levels=np.linspace(0, 30, 30))

    plt.tight_layout()
    for t in range(len(opt_traj)):
        mu, logstd, dmu, dlogstd, kl_score = opt_traj[t]

        # Plot new fit
        xs = np.linspace(-10, 10, 800)
        ys = stats.norm.pdf(xs, mu, np.exp(logstd))
        ax_fit.set_title("$\mathcal{D}_{KL} = $" + "{0:.4f}".format(kl_score))
        fit_artist[0].set_data(xs, ys)

        # Plot gradient step
        grad_step = Arrow(mu, logstd, -dmu, -dlogstd, width=0.5)
        if len(ax_grad.patches) > 0:
            ax_grad.patches.pop()
        ax_grad.add_patch(grad_step)
        art3d.pathpatch_2d_to_3d(grad_step, z=-50, zdir="z")
        # Save images in order to export a video with:
        # ffmpeg -r 25 -i %04d_kl_normal.png kl_normal.webm
        plt.savefig("figs/{0:04d}_kl_normal.png".format(t))
        plt.pause(0.001)
示例#53
0
def plot_situation(tracks, n_tracks=6*3, n_dcs=50, tcz_volume=0.524e9/400,
    min_distance=0, min_distance_std=200/10, zoom=1, t_detail=None, save=False,
    context='notebook'):
    """Plot some T cell tracks, DC positions and T cell zone volume"""
    sns.set(style='ticks', context=context)

    _ = plt.figure(figsize=(8, 5.5))
    gs = gridspec.GridSpec(2,3)
    space_ax = plt.subplot(gs[:,:-1], projection='3d')
    time_ax = plt.subplot(gs[0,-1])
    reach_ax = plt.subplot(gs[1,-1])
    plt.locator_params(nbins=6)

    space_ax.set_title('{} T Cell Tracks & {} DCs'.format(n_tracks, n_dcs))

    n_conditions = len(tracks['Condition'].unique())
    palette = itertools.cycle(sns.color_palette())

    if min_distance_std != 0:
        moved_tracks = tracks.copy()
        for id in tracks['Track_ID'].unique():
            moved_tracks.loc[moved_tracks['Track_ID'] == id, ['X', 'Y', 'Z']] += \
                np.random.randn(3)*min_distance_std
    else:
        moved_tracks = tracks

    for i, (cond, cond_tracks) in enumerate(moved_tracks.groupby('Condition')):
        choice = np.random.choice(cond_tracks['Track_ID'].unique(),
            n_tracks/n_conditions)
        chosen_tracks = cond_tracks[cond_tracks['Track_ID'].isin(choice)]
        for _, track in chosen_tracks.groupby(track_identifiers(chosen_tracks)):
            if t_detail:
                track = track[track['Time'] <= t_detail*60]
            if n_conditions > 1:
                color = sns.color_palette(n_colors=i+1)[-1]
            else:
                color = next(palette)
            space_ax.plot(track['X'].values, track['Y'].values, track['Z'].values,
                color=color)

    tcz_radius = (3*tcz_volume/(4*np.pi))**(1/3)
    ratio = (min_distance/tcz_radius)**3
    r = tcz_radius*(ratio + (1 - ratio)*np.random.rand(n_dcs))**(1/3)
    theta = np.random.rand(n_dcs)*2*np.pi
    phi = np.arccos(2*np.random.rand(n_dcs) - 1)
    dcs = pd.DataFrame({
        'X': r*np.sin(theta)*np.sin(phi),
        'Y': r*np.cos(theta)*np.sin(phi),
        'Z': r*np.cos(phi)})
    space_ax.scatter(dcs['X'], dcs['Y'], dcs['Z'], c='y')

    r = (3*tcz_volume/(4*np.pi))**(1/3)
    for i in ['x', 'y', 'z']:
        circle = Circle((0, 0), r, fill=False, linewidth=2)
        space_ax.add_patch(circle)
        art3d.pathpatch_2d_to_3d(circle, z=0, zdir=i)

    time_ax.set_xlabel('Time within Lymph Node [h]')
    time_ax.set_ylabel('Probab. Density')

    reach_ax.set_xlabel(r'Maximal Reach [$\mu$m]')
    reach_ax.set_ylabel('Probab. Density')

    def residence_time(track): return track['Time'].diff().mean()/60*len(
        track[np.linalg.norm(track[['X', 'Y', 'Z']], axis=1) < r])

    for i, (cond, cond_tracks) in enumerate(moved_tracks.groupby('Condition')):
        color = sns.color_palette(n_colors=i+1)[-1]
        residence_times = [residence_time(track)
            for _, track in cond_tracks.groupby('Track_ID')]
        if not all(time == residence_times[0] for time in residence_times):
            sns.distplot(residence_times, kde=False, norm_hist=True, ax=time_ax,
                label=cond, color=color)
        max_reaches = [max(np.linalg.norm(track[['X', 'Y', 'Z']], axis=1))
            for _, track in cond_tracks.groupby('Track_ID')]
        sns.distplot(max_reaches, kde=False, norm_hist=True, ax=reach_ax,
            label=cond, color=color)

    time_ax.set_yticks([])
    time_ax.axvline(np.median(residence_times), c='0', ls=':')
    sns.despine(ax=time_ax)
    reach_ax.set_yticks([])
    reach_ax.legend()
    reach_ax.axvline(tcz_radius, c='0', ls=':')
    sns.despine(ax=reach_ax)
    equalize_axis3d(space_ax, zoom)
    plt.tight_layout()

    if save == True:
        save = 'situation.png'

    if save:
        plt.savefig(save, dpi=300)
    else:
        plt.show()
示例#54
0
文件: figtools.py 项目: frsong/pyrl
 def zcircle(self, center, r, z0, **kwargs):
     circle = mpl.patches.Circle(center, r, **kwargs)
     patch  = self.add_patch(circle)
     art3d.pathpatch_2d_to_3d(patch, z=z0)
def plot_frame3D(vectors, frame, output):
    """
    Creates a plot of magnetization vectors in a 3D view.

    Args:
        frame: which frame to plot.
        vectors: numpy array of size [3, nFrames].
        output: specification of desired output (dictionary from config).
    Returns:
        plot figure.
    """
    # Create 3D axes
    aspect = .952
    figSize = 5  # figure size in inches
    canvasWidth = figSize
    canvasHeight = figSize * aspect
    fig = plt.figure(figsize=(canvasWidth, canvasHeight), dpi=output['dpi'])
    ax = fig.gca(projection='3d',
                 xlim=(-1, 1),
                 ylim=(-1, 1),
                 zlim=(-1, 1),
                 fc=colors['bg'])
    ax.set_axis_off()
    width = 1.65  # to get tight cropping
    height = width / aspect
    left = (1 - width) / 2
    bottom = (1 - height) / 2

    bottom += -.075

    ax.set_position([left, bottom, width, height])

    if output['drawAxes']:
        # Draw axes circles
        for i in ["x", "y", "z"]:
            circle = Circle((0, 0), 1, fill=True, lw=1, fc=colors['circle'])
            ax.add_patch(circle)
            art3d.pathpatch_2d_to_3d(circle, z=0, zdir=i)

        # Draw x, y, and z axes
        ax.plot([-1, 1], [0, 0], [0, 0], c=colors['axis'], zorder=-1)  # x-axis
        ax.text(1.08,
                0,
                0,
                r'$x^\prime$',
                horizontalalignment='center',
                color=colors['text'])
        ax.plot([0, 0], [-1, 1], [0, 0], c=colors['axis'], zorder=-1)  # y-axis
        ax.text(0,
                1.12,
                0,
                r'$y^\prime$',
                horizontalalignment='center',
                color=colors['text'])
        ax.plot([0, 0], [0, 0], [-1, 1], c=colors['axis'], zorder=-1)  # z-axis
        ax.text(0,
                0,
                1.05,
                r'$z$',
                horizontalalignment='center',
                color=colors['text'])

    pos = [0, 0, 0]
    # Draw magnetization vectors
    M = vectors[frame]

    ax.add_artist(
        Arrow3D([pos[0], pos[0] + M[0]], [-pos[1], -pos[1] + M[1]],
                [-pos[2], -pos[2] + M[2]],
                mutation_scale=20,
                arrowstyle='-|>',
                shrinkA=0,
                shrinkB=0,
                lw=2,
                color=colors['comps'][0],
                alpha=1,
                zorder=1))
    return fig
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from matplotlib.text import TextPath
from matplotlib.transforms import Affine2D
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import
import mpl_toolkits.mplot3d.art3d as art3d

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')

# blue hex colors: #14b4ff #008ed1 #076794
# green hex colors: #b8d6b4 #a2bd9f #758a72

p = Circle((50, 50), 30, color='#14b4ff', fill=True)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=100, zdir="z")

p = Circle((50, 50), 40, color='#008ed1', fill=True)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=50, zdir="z")

p = Circle((50, 50), 30, color='#076794', fill=True)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")

ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))

ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
def track_clusters_3d(outfile, coords, end_frames, labels, title=None):
    """
    Show clusters of trajectories in 3d.

    Parameters
    ----------
    outfile : str
    coords : array, shape (n_tracks, track_length, 2)
        The x and y coordinates of the trajectories.
    end_frames :
    labels : array, shape (n_tracks,)
        Cluster label for each trajectory. The label -1 is used when a
        trajectory does not belong to any cluster.

    Returns
    -------
    None
    """
    if not (len(coords) == len(labels) == len(end_frames)):
        raise ValueError('number of trajectories must match number of labels')

    labels_uniq, labels_cnt = np.unique(labels, return_counts=True)
    colors = sns.hls_palette(len(labels_uniq))

    with PdfPages(outfile) as pdf:
        # set up figure and 3d axis
        fig, ax = plt.subplots(tight_layout=True, figsize=(16, 9),
                               subplot_kw={'projection': '3d'})
        if title:
            ax.set_title(title)

        # plot trajectories in each cluster
        for l, c in zip(labels_uniq, colors):
            indices = np.flatnonzero(labels == l)
            for idx, (xy, end) in enumerate(zip(coords[indices], end_frames[indices])):
                ax.plot(xy[:, 0], xy[:, 1], np.arange(end+1-len(xy), end+1), '-o',
                        zdir='y', lw=0.7, ms=1.5, color=c)

        # show legend
        ax.legend(handles=[Patch(color=c, label=str(cnt)) for c, cnt in zip(colors, labels_cnt)])

        # mimic video frames
        xy = (coords[:, :, 0].min(), coords[:, :, 1].min())
        w = coords[:, :, 0].max() - coords[:, :, 0].min()
        h = coords[:, :, 1].max() - coords[:, :, 1].min()
        for z in range(0, end_frames.max(), 50):
            rect = Rectangle(xy, w, h, fill=False, color='black',
                             alpha=0.3, lw=0.3)
            ax.add_patch(rect)
            art3d.pathpatch_2d_to_3d(rect, z=z, zdir='y')

        # set axis limits
        pad = 0.5
        ax.set_xlim3d(coords[:, :, 0].min()-pad, coords[:, :, 0].max()+pad)
        ax.set_ylim3d(0, end_frames.max()+1)
        ax.set_zlim3d(coords[:, :, 1].min()-pad, coords[:, :, 1].max()+pad)

        ax.set_xlabel('Video width')
        ax.set_ylabel('Video frames')
        ax.set_zlabel('Video height')

        ax.view_init(elev=20, azim=12)
        _set_axes_equal(ax)

        pdf.savefig()
        plt.close(fig)
示例#58
0
def drawCube(pos, color):
    r1 = Rectangle((pos[1],pos[2]), 1, 1, fc=color, ec=None)
    r2 = Rectangle((pos[1],pos[2]), 1, 1, fc=color, ec=None)
    r3 = Rectangle((pos[0],pos[2]), 1, 1, fc=color, ec=None)
    r4 = Rectangle((pos[0],pos[2]), 1, 1, fc=color, ec=None)
    r5 = Rectangle((pos[0],pos[1]), 1, 1, fc=color, ec=None)
    r6 = Rectangle((pos[0],pos[1]), 1, 1, fc=color, ec=None)
    rs = [r1, r2, r3, r4, r5, r6]
    for r in rs:
        ax.add_patch(r)
    art3d.pathpatch_2d_to_3d(r1, z=pos[0], zdir='x')
    art3d.pathpatch_2d_to_3d(r2, z=pos[0] + 1, zdir='x')
    art3d.pathpatch_2d_to_3d(r3, z=pos[1], zdir='y')
    art3d.pathpatch_2d_to_3d(r4, z=pos[1] + 1, zdir='y')
    art3d.pathpatch_2d_to_3d(r5, z=pos[2], zdir='z')
    art3d.pathpatch_2d_to_3d(r6, z=pos[2] + 1, zdir='z')
    y_grid = radius * np.sin(theta_grid) + center_y
    return x_grid, y_grid, z_grid


fig_1 = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
ax = Axes3D(fig_1)

Xc, Yc, Zc = data_for_cylinder_along_z(1, 1, 3, 5)
ax.plot_surface(Xc, Yc, Zc, alpha=0.5)  #alpha - прозрачность
ax.scatter(Xc, Yc, Zc, color='red')

#top\bottom
top = Circle((1, 1), 3, alpha=0.5)
ax.add_patch(top)
art3d.pathpatch_2d_to_3d(top, 5)

floor = Circle((1, 1), 3, alpha=0.5)
ax.add_patch(floor)
art3d.pathpatch_2d_to_3d(floor, 0)

ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")

bar1 = FigureCanvasTkAgg(fig_1, master=f_top)
bar1.get_tk_widget().pack(side=LEFT, fill=BOTH)
# /////////////////////////////////////////////////////////

#пsurface
fig_2 = plt.figure()
示例#60
0
def subplot_embedding_distribution(ax,
                                   W,
                                   pi,
                                   mu,
                                   sigma,
                                   labels=None,
                                   N=100,
                                   colors=None):
    # plotting prior
    X = np.linspace(-1, 1, N)
    Y = np.linspace(-1, 1, N)
    X, Y = np.meshgrid(X, Y)
    # plotting circle
    X0, Y0, radius = 0, 0, 1
    r = np.sqrt((X - X0)**2 + (Y * Y0)**2)
    disc = r < 1

    Z = np.zeros((N, N))
    # compute the mixture
    for z_index in range(len(Z)):
        x = torch.cat((torch.FloatTensor(X[z_index]).unsqueeze(-1),
                       torch.FloatTensor(Y[z_index]).unsqueeze(-1)), -1)
        zz = weighted_gmm_pdf(pi, x, mu, sigma, pf.distance)
        zz[zz != zz] = 0
        Z[z_index] = zz.sum(-1).numpy()

    ax.plot_surface(X,
                    Y,
                    Z,
                    rstride=1,
                    cstride=1,
                    linewidth=1,
                    antialiased=True,
                    cmap=plt.get_cmap("viridis"))
    z_circle = -0.8
    p = Circle((0, 0), 1, edgecolor='b', lw=1, facecolor='none')
    ax.add_patch(p)
    art3d.pathpatch_2d_to_3d(p, z=z_circle, zdir="z")

    for q in range(len(W)):
        if (colors is not None):
            ax.scatter(W[q][0].item(),
                       W[q][1].item(),
                       z_circle,
                       c=[colors[q]],
                       marker='.')
        else:
            ax.scatter(W[q][0].item(),
                       W[q][1].item(),
                       z_circle,
                       c='b',
                       marker='.')
        #print('Print labels', labels[q])

    for j in range(len(mu)):
        ax.scatter(mu[j][0].item(),
                   mu[j][1].item(),
                   z_circle,
                   c='r',
                   marker='D')

    ax.set_xlim(-1.2, 1.2)
    ax.set_ylim(-1.2, 1.2)
    ax.set_zlim(-0.8, 0.4)

    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('P')