Beispiel #1
0
def visualize_3d(data_in, title=None, save_file=None):
    data = data_in[:]
    data[data < 0.5] = 0

    non_zero_indices = data.nonzero()

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Axes3D.scatter(ax, non_zero_indices[0], non_zero_indices[1],
                   non_zero_indices[2])

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

    if title is not None:
        plt.title(title)

    if save_file:
        # fig.show()
        # import IPython
        # IPython.embed()
        plt.savefig(save_file)
        plt.close('all')
    else:
        fig.show()
Beispiel #2
0
def plot_cam_location(camera_list, n, fig=None, ax=None):
    FigSz = (8, 8)
    L = np.array([list(c.location[n]) for c in camera_list])
    x = L[:, 0]
    y = L[:, 1]
    z = L[:, 2]
    if not fig:
        fig = plt.figure(figsize=FigSz)
    #view1 = np.array([-85., 60.])
    if not ax:
        ax = Axes3D(fig)  #, azim=view1[0], elev=view1[1])
    Axes3D.scatter(ax, x, y, zs=z, color='k')
    zer = np.array
    Axes3D.scatter(ax, zer([0]), zer([0]), zs=zer([5]), color='r')
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    ax.set_ylim3d(-50, 50)
    ax.set_xlim3d(-50, 50)
    ax.set_zlim3d(0, 50)
    #if Flag['ShowPositions']:
    fig.show()
    #else:
    #	fig.savefig(fName)
    return ax, fig
Beispiel #3
0
def visualize_occupancygrid(data, title=None, save_file=None):

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

    occupied = data == 1
    non_zero_indices = occupied.nonzero()
    Axes3D.scatter(ax,
                   non_zero_indices[0],
                   non_zero_indices[1],
                   non_zero_indices[2],
                   c='b')

    occluded = data == 2
    non_zero_indices = occluded.nonzero()
    Axes3D.scatter(ax,
                   non_zero_indices[0],
                   non_zero_indices[1],
                   non_zero_indices[2],
                   c='r')

    if title is not None:
        plt.title(title)

    if save_file:
        plt.savefig(save_file)
    else:
        fig.show()
    def plot_system(system, parameters):

        x = []
        y = []
        z = []
        colours = []
        for i in range(len(system.particles)):
            x.append(system.particles[i].position[0])
            y.append(system.particles[i].position[1])
            z.append(system.particles[i].position[2])

            if parameters.charges[i] == 1:
                colours.append('b')
            elif parameters.charges[i] == -1:
                colours.append('g')

        ax = plt.axes(projection='3d')
        ax.set_xlim3d(0, system.neighbourlist.box_space[0])
        ax.set_ylim3d(0, system.neighbourlist.box_space[1])
        ax.set_zlim3d(0, system.neighbourlist.box_space[2])
        Axes3D.scatter(ax, x, y, z, c=colours)
        plt.title("System")
        #ax.legend(['Sodium','Chloride'], loc='upper right')

        plt.show()
Beispiel #5
0
def plot_cam_location(camera_list, n, fig=None, ax=None):
	FigSz = (8, 8)
	L = np.array([list(c.location[n]) for c in camera_list])
	x = L[:, 0]
	y = L[:, 1]
	z = L[:, 2]
	if not fig:
		fig = plt.figure(figsize=FigSz)
	#view1 = np.array([-85., 60.])
	if not ax:
		ax = Axes3D(fig) #, azim=view1[0], elev=view1[1])
	Axes3D.scatter(ax, x, y, zs=z, color='k')
	zer = np.array
	Axes3D.scatter(ax, zer([0]), zer([0]), zs=zer([5]), color='r')
	ax.set_xlabel('X')
	ax.set_ylabel('Y')
	ax.set_zlabel('Z')
	ax.set_ylim3d(-50, 50)
	ax.set_xlim3d(-50, 50)
	ax.set_zlim3d(0, 50)
	#if Flag['ShowPositions']:
	fig.show()
	#else:
	#	fig.savefig(fName)
	return ax, fig
Beispiel #6
0
def main():
    global rR
    global v
    #v = polynomial_surface2(rR)
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    v = [
        345.01147843, -731.53883648, 701.43498064, -333.41157482, 61.69405675,
        434.95848754, -734.92037163, 468.45066799, -108.66899203, 197.05683428,
        -229.38490931, 73.72852732, 38.62490216, -23.11704968, 2.79760705,
        1112.02959271, -1850.90352232, 1243.44148281, -301.1366546,
        1096.50133704, -1278.21349214, 419.17838208, 338.80540403,
        -201.95899053, 33.68403733, 1333.97626976, -1566.15905716, 552.3302448,
        922.09578713, -558.92492054, 145.7445413, 705.90344671, -442.88105472,
        259.89354682, 138.22604583
    ]
    #ax=implicit.plot_implicit(fn4,bbox=(-1.5,0,-3.5,-1.5,-2,1),rc=200,ns=30,colors='b', ax=ax)
    v = [
        2.18930311, 0.24260729, 57.46589779, 3.38543536, -9.56889825,
        34.36258001, -36.2221404, 4.86597348, 12.89329227, 21.10709896,
        -4.36372996, -5.89323474, 3.98227029, 0.9848254, 0.23593784,
        -36.46890674, -25.34400559, 81.86028261, 14.43120124, 44.89510312,
        -52.04801532, -9.90597384, 16.49023335, 2.29875215, 0.40597427,
        -55.46318028, -39.9563639, 26.95078929, 35.15384941, -18.2399162,
        5.13417155, -31.78519693, -14.89522473, 10.38829065, -6.66988281
    ]
    #ax=implicit.plot_implicit(fn4,bbox=(-1.5,0,-3.5,-1.5,-2,1),rc=200,ns=30,colors='r', ax=ax)
    #rR = tree_time.tree_time(rR,0.05)
    rR = array(rR)
    Axes3D.scatter(ax, rR[:, 0], rR[:, 1], rR[:, 2])
    Axes3D.scatter(ax, -0.87676517, -2.5211104, -0.76908632, color='green')
    plt.show()
def plotFiguresTemp(xSolid, ySolid, zSolid, xFFDDeform, yFFDDeform, zFFDDeform):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

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

    # Axes3D.plot_wireframe(ax, z, x, y)
    ax.set_xlabel('Z axis')
    ax.set_ylabel('X axis')
    ax.set_zlabel('Y axis')

    #ax.plot_trisurf(zSolid, xSolid, ySolid, cmap=cm.jet, linewidth=0.2)
    ax.plot_wireframe(zSolid, xSolid, ySolid, rstride = 1, cstride = 1, color="y")

    #Axes3D.scatter(ax, zSolid, xSolid, ySolid, s=10, c='b')
    Axes3D.scatter(ax, zFFDDeform, xFFDDeform, yFFDDeform, s=30, c='r')

    # Axes3D.set_ylim(ax, [-0.5,4.5])
    # Axes3D.set_xlim(ax, [-0.5,4.5])
    Axes3D.set_zlim(ax, [-0.7, 0.7])




    plt.show(block=True)
Beispiel #8
0
def visualize_multiple_3d(data0, data1, title=None, save_file=None):
    data0[data0 < 0.5] = 0
    data1[data1 < 0.5] = 0

    non_zero_indices0 = np.array(data0.nonzero()) - 0.1
    non_zero_indices1 = np.array(data1.nonzero())

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Axes3D.scatter(ax,
                   non_zero_indices0[0],
                   non_zero_indices0[1],
                   non_zero_indices0[2],
                   c='b')
    Axes3D.scatter(ax,
                   non_zero_indices1[0],
                   non_zero_indices1[1],
                   non_zero_indices1[2],
                   c='r')

    if title is not None:
        plt.title(title)

    if save_file:
        plt.savefig(save_file)
    else:
        fig.show()
 def volume_display(self, zstep = 3.00):
     """
     This is a daring attempt for 3-D plots of all the blobs in the brain. 
     Prerequisites: self.blobs_archive are established.
     The magnification of the microscope must be known.
     """
     fig3 = plt.figure(figsize = (10,6))
     ax_3d = fig3.add_subplot(111, projection = '3d')
     
     for n_frame in self.valid_frames:
         # below the coordinates of the cells are computed.
         blobs_list = self.c_list[n_frame] 
         ys = blobs_list[:,0]*magni_lateral
         xs = blobs_list[:,1]*magni_lateral 
         zs = np.ones(len(blobs_list))*n_frame*zstep
         ss = (np.sqrt(2)*blobs_list[:,2]*magni_lateral)**2*np.pi
         Axes3D.scatter(xs,ys, zs, zdir = 'z', s=ss, c='g')        
     
     
     
     ax_3d.set_xlabel('x (micron)', fontsize = 12)
     ax_3d.set_xlabel('y (micron)', fontsize = 12)
     
     return fig3
     
def plotFigures(xSolid,ySolid,zSolid,xFFDDeform,yFFDDeform,zFFDDeform, xsolidInitial,
               ysolidInitial, zsolidInitial, xFFDInitial, yFFDInitial, zFFDInitial):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')


    # Axes3D.plot_wireframe(ax, z, x, y)
    ax.set_xlabel('Z axis')
    ax.set_ylabel('X axis')
    ax.set_zlabel('Y axis')

#Axes3D.scatter(ax, zSolid, xSolid, ySolid, s=10, c='b')
    #Axes3D.plot_wireframe(ax, zSolid, xSolid, ySolid, rstride = 1, cstride = 1, color="b")
#Axes3D.scatter(ax, zFFDDeform, xFFDDeform, yFFDDeform, s=30, c='r')

    Axes3D.scatter(ax, zsolidInitial, xsolidInitial, ysolidInitial, s=10, c='b')
    #Axes3D.plot_wireframe(ax, zsolidInitial, xsolidInitial, ysolidInitial,rstride = 1, cstride = 1, color="y")
    Axes3D.scatter(ax, zFFDInitial, xFFDInitial, yFFDInitial, s=30, c='r')


    if (CONST_BodyType == "halfFuselage"):
        Axes3D.set_zlim(ax, [0, 4])
        Axes3D.set_ylim(ax, [0, 4])
        Axes3D.set_xlim(ax, [0, 12])
    else:
        #Axes3D.set_ylim(ax, [-0.5,4.5])
        #Axes3D.set_xlim(ax, [-0.5,4.5])
        Axes3D.set_zlim(ax, [-1.2, 1.2])

    plt.show(block=True)
def plotData(tuplesArray):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    
    x = []
    y = []
    z = []
    
    for point in tuplesArray:
        x.append(point[0])
        y.append(point[1])
        z.append(point[2])
    

    if (FILEInQuestion == "newsbp.fuselageZ.dat"):
        Axes3D.scatter(ax, x,y,z, s=30, c ='b')
        
        Axes3D.set_zlim(ax, [0, 1000])
        Axes3D.set_ylim(ax, [0, 3000])
        Axes3D.set_xlim(ax, [0, 3000])
        
        ax.set_xlabel('Z axis')
        ax.set_ylabel('X axis')
        ax.set_zlabel('Y axis')
    else:
        Axes3D.scatter(ax, z,x,y, s=30, c ='b')
        
        ax.set_xlabel('Z axis')
        ax.set_ylabel('X axis')
        ax.set_zlabel('Y axis')

    plt.show(block=True)
def plotData2files(tuplesArray1, tuplesArray2):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    
    x1 = []
    y1 = []
    z1 = []
    
    for point in tuplesArray1:
        x1.append(point[0])
        y1.append(point[1])
        z1.append(point[2])
    
    x2 = []
    y2 = []
    z2 = []
    
    for point in tuplesArray2:
        x2.append(point[0])
        y2.append(point[1])
        z2.append(point[2])
    
    Axes3D.scatter(ax, x1,y1,z1, s=30, c ='b')
    Axes3D.scatter(ax, x2,y2,z2, s=30, c ='r')

    Axes3D.set_xlim(ax, [0, 2000])
    Axes3D.set_ylim(ax, [0, 3000])
    Axes3D.set_zlim(ax, [0, 1000])

    plt.show(block=True)
Beispiel #13
0
def plotData2files(tuplesArray1, tuplesArray2):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    x1 = []
    y1 = []
    z1 = []

    for point in tuplesArray1:
        x1.append(point[0])
        y1.append(point[1])
        z1.append(point[2])

    x2 = []
    y2 = []
    z2 = []

    for point in tuplesArray2:
        x2.append(point[0])
        y2.append(point[1])
        z2.append(point[2])

    Axes3D.scatter(ax, x1, y1, z1, s=30, c='b')
    Axes3D.scatter(ax, x2, y2, z2, s=30, c='r')

    Axes3D.set_xlim(ax, [0, 2000])
    Axes3D.set_ylim(ax, [0, 3000])
    Axes3D.set_zlim(ax, [0, 1000])

    plt.show(block=True)
def plotFigures(xSolid,ySolid,zSolid,xFFDDeform,yFFDDeform,zFFDDeform, xsolidInitial,
               ysolidInitial, zsolidInitial, xFFDInitial, yFFDInitial, zFFDInitial):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')


    # Axes3D.plot_wireframe(ax, z, x, y)
    ax.set_xlabel('Z axis')
    ax.set_ylabel('X axis')
    ax.set_zlabel('Y axis')

    #Axes3D.scatter(ax, zSolid, xSolid, ySolid, s=10, c='b')
    Axes3D.plot_wireframe(ax, zSolid, xSolid, ySolid, rstride = 1, cstride = 1, color="b")
    Axes3D.scatter(ax, zFFDDeform, xFFDDeform, yFFDDeform, s=30, c='r')

    #Axes3D.scatter(ax, zsolidInitial, xsolidInitial, ysolidInitial, s=10, c='y')
    Axes3D.plot_wireframe(ax, zsolidInitial, xsolidInitial, ysolidInitial,rstride = 1, cstride = 1, color="y")
    Axes3D.scatter(ax, zFFDInitial, xFFDInitial, yFFDInitial, s=30, c='g')

    xZCross = []
    yZCross = []
    zZCross = []

    #plot the points for the limits of each cross section
    for zCrossSect in GLOBAL_zCrossSectionObjects:
        zCrossSectionObject = GLOBAL_zCrossSectionObjects[zCrossSect]

        #add to the arrays, for a fixed z, the following combinations
        # (xmax, ymax) (xmax, ymin) (xmin, ymin) (xmin, ymax)

        # (xmax, ymax)
        xZCross.append(zCrossSectionObject.getXMax())
        yZCross.append(zCrossSectionObject.getYMax())
        zZCross.append(zCrossSect)

        #(xmax, ymin)
        xZCross.append(zCrossSectionObject.getXMax())
        yZCross.append(zCrossSectionObject.getYMin())
        zZCross.append(zCrossSect)

        #(xmin, ymin)
        xZCross.append(zCrossSectionObject.getXMin())
        yZCross.append(zCrossSectionObject.getYMin())
        zZCross.append(zCrossSect)

        #(xmin, ymax)
        xZCross.append(zCrossSectionObject.getXMin())
        yZCross.append(zCrossSectionObject.getYMax())
        zZCross.append(zCrossSect)

    #Axes3D.plot_wireframe(ax, zZCross, xZCross, yZCross)



    #Axes3D.set_ylim(ax, [-0.5,4.5])
    #Axes3D.set_xlim(ax, [-0.5,4.5])
    Axes3D.set_zlim(ax, [-0.7, 0.7])

    plt.show(block=True)
Beispiel #15
0
def plotFigures(xSolid,ySolid,zSolid,xFFDDeform,yFFDDeform,zFFDDeform, xsolidInitial,
               ysolidInitial, zsolidInitial, xFFDInitial, yFFDInitial, zFFDInitial):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')


    # Axes3D.plot_wireframe(ax, z, x, y)
    ax.set_xlabel('Z axis')
    ax.set_ylabel('X axis')
    ax.set_zlabel('Y axis')

    #Axes3D.scatter(ax, zSolid, xSolid, ySolid, s=10, c='b')
    Axes3D.plot_wireframe(ax, zSolid, xSolid, ySolid, rstride = 1, cstride = 1, color="b")
    Axes3D.scatter(ax, zFFDDeform, xFFDDeform, yFFDDeform, s=30, c='r')

    #Axes3D.scatter(ax, zsolidInitial, xsolidInitial, ysolidInitial, s=10, c='y')
    Axes3D.plot_wireframe(ax, zsolidInitial, xsolidInitial, ysolidInitial,rstride = 1, cstride = 1, color="y")
    Axes3D.scatter(ax, zFFDInitial, xFFDInitial, yFFDInitial, s=30, c='g')

    xZCross = []
    yZCross = []
    zZCross = []

    #plot the points for the limits of each cross section
    for zCrossSect in GLOBAL_zCrossSectionObjects:
        zCrossSectionObject = GLOBAL_zCrossSectionObjects[zCrossSect]

        #add to the arrays, for a fixed z, the following combinations
        # (xmax, ymax) (xmax, ymin) (xmin, ymin) (xmin, ymax)

        # (xmax, ymax)
        xZCross.append(zCrossSectionObject.getXMax())
        yZCross.append(zCrossSectionObject.getYMax())
        zZCross.append(zCrossSect)

        #(xmax, ymin)
        xZCross.append(zCrossSectionObject.getXMax())
        yZCross.append(zCrossSectionObject.getYMin())
        zZCross.append(zCrossSect)

        #(xmin, ymin)
        xZCross.append(zCrossSectionObject.getXMin())
        yZCross.append(zCrossSectionObject.getYMin())
        zZCross.append(zCrossSect)

        #(xmin, ymax)
        xZCross.append(zCrossSectionObject.getXMin())
        yZCross.append(zCrossSectionObject.getYMax())
        zZCross.append(zCrossSect)

    #Axes3D.plot_wireframe(ax, zZCross, xZCross, yZCross)



    #Axes3D.set_ylim(ax, [-0.5,4.5])
    #Axes3D.set_xlim(ax, [-0.5,4.5])
    Axes3D.set_zlim(ax, [-0.7, 0.7])

    plt.show(block=True)
Beispiel #16
0
 def custom_plot(self, additional):
     for k in additional:
         if(k == Simulation.DISCRETIZE):
             for i in range(self.examples.noutputs):
                 for j in range(self.nbr_epoch):
                     if(self.plots['discretize_div'][i][j] != 0):
                         self.plots['discretize'][i][j] /= (self.plots['discretize_div'][i][j] * (self.nbDiscre ** self.nbDiscre))
             
             colors = [(0.2, 0.8, 0.88), 'b', 'g', 'r', 'c', 'm', 'y', 'k', (0.8, 0.1, 0.8), (0., 0.2, 0.5)]
     
             fig = plt.figure()
             ax = fig.add_subplot(111, projection='3d')
             for j in range(self.examples.noutputs):
                 ax.scatter([self.plots['discretize'][j][k] for k in self.plots['discretize_valid'][j]], [j] * 
                             len(self.plots['discretize_valid'][j]), self.plots['discretize_valid'][j], color=colors[j], marker='x')
         
             ax.set_xlabel('DISCRETIZED VALUE')
             ax.set_ylabel('SHAPE')
             ax.set_zlabel('EPOCH')
             
             path = "/tmp/pyplot.%s.%s.png" % (sys.argv[0], time.strftime("%m-%d-%H-%M-%S", time.localtime()))
             plt.savefig(path)
             plt.show()
             
             
             plt.title('Discretize hidden layer')
             plt.ylabel('DISCRETIZED VALUE')
             plt.xlabel("EPOCHS")
             for j in range(self.examples.noutputs):
                 plt.plot(self.plots['discretize_valid'][j], [self.plots['discretize'][j][k] 
                                                              for k in self.plots['discretize_valid'][j]], '.', color=colors[j])
             path = "/tmp/pyplot.%s.%s.png" % (sys.argv[0], time.strftime("%m-%d-%H-%M-%S", time.localtime()))
             try:
                 plt.savefig(path)
             except ValueError:
                 print('Cannot save discretize_cloud')
             try:
                 plt.show()
             except ValueError:
                 print('Cannot display discretize_cloud')
         elif(k == Simulation.PROTOTYPE):
             lplot = [[0. for _ in range(self.examples.ninputs)] for _ in range(self.examples.noutputs)]
             for network in self.networks:
                 for i in range(len(self.examples.inputs)):
                     network['FoN'].calc_output(self.examples.inputs[i])
                     network['SoN'].calc_output(network['FoN'].stateHiddenNeurons)
                     
                     im = index_max(self.examples.outputs[i])
                     
                     for j in range(self.examples.ninputs):
                         lplot[im][j] += network['SoN'].stateOutputNeurons[j]
             
             fig = plt.figure()
             plt.clf()
             for i in range(self.examples.noutputs):
                 rpr.show_repr(lplot[i], self.width, fig, 250 + i, i)
             path = "/tmp/pyplot.%s.%s.png" % (sys.argv[0], time.strftime("%m-%d-%H-%M-%S", time.localtime()))
             plt.savefig(path)
             plt.show()
Beispiel #17
0
def plot():
    ax = implicit.plot_implicit(fn4,
                                bbox=(-5, 5, -5, 5, -5, 5),
                                rc=150,
                                ns=50,
                                colors='r')
    Axes3D.scatter(ax, rays[:, 0], rays[:, 1], rays[:, 2])
    plt.show()
def main():
    # initialize ros node
    rospy.init_node('compute_calibration')

    # get path to folder containing recorded data
    #filesPath = rospy.get_param('~files_path')
    filesPath =os.environ['HOME']+"/catkin_ws/src/panda_hand_eye_calibrate/config/"

    # load trajectories
    marker2camera = np.loadtxt('%smarker2camera' % (filesPath), delimiter=',')
    ee2base = np.loadtxt('%see2base' % (filesPath), delimiter=',')

    # compute absolute orientation
    kinectOut, rot, trans = absOrientation(marker2camera,ee2base)


    ########画出轨迹图###########
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    # plot the data
    Axes3D.scatter(ax, kinectOut[:,0], kinectOut[:,1], kinectOut[:,2], s=20, c='r')
    Axes3D.scatter(ax, ee2base[:,0],ee2base[:,1], ee2base[:,2], s=20, c='b')

    # add labels and title
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_zticks([])
    ax.set_xlabel('X-axis')
    ax.set_ylabel('Y-axis')
    ax.set_zlabel('Z-axis')
    plt.title('Kinect-Panda Calibration')
    plt.legend(['Kinect','Panda'])
    plt.show()


    # get rotation matrix as quaternion and euler angles
    euler = tf.transformations.euler_from_matrix(rot)
    quat = tf.transformations.quaternion_from_euler(*euler)

    # save results to yaml file  写base与kinect之间的关系
    f = open('%spanda2camera_calibration.yaml' % (filesPath), 'w')
    lines = ['trans: [', 'rot: [', 'rot_euler: [']

    for elem in trans: lines[0] += str(elem) + ', '  #trans
    lines[0] += ']\n'
    for elem in quat: lines[1] += str(elem) + ', '  #rot
    lines[1] += ']\n'
    for elem in euler: lines[2] += str(elem) + ', '  #rot_euler
    lines[2] += ']\n'

    lines.append('parent: /panda_link0\n')
    lines.append('child: /kinect2_link\n')

    f.writelines(lines)
    f.close()

    print ('Calibration Done !')
Beispiel #19
0
def plot3d(x, y, z, show=True, **kwds):
    from mpl_toolkits.mplot3d import Axes3D
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Axes3D.scatter(ax, xs=x, ys=y, zs=z)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    if show:
        plt.show()
Beispiel #20
0
def __draw_scatter_from_dict(ax: Axes3D, dict: Dict[Tuple[int, int], float],
                             color: str, marker: str, size: int):
    id_pairs = dict.keys()
    tested_ids = [id_pair[1] for id_pair in id_pairs]
    test_ids = [id_pair[0] for id_pair in id_pairs]
    predict_value = [value for value in dict.values()]
    zs = np.array(predict_value)
    xs = np.array(test_ids)
    ys = np.array(tested_ids)
    ax.scatter(xs, ys, zs, c=color, marker=marker, s=size)
Beispiel #21
0
def plot_skeleton_on_axes3d(skel,
                            skel_desc,
                            ax: Axes3D,
                            invert=True,
                            alpha=1.0):
    ax.set_xlabel('x')
    ax.set_ylabel('z')
    ax.set_zlabel('y')

    # NOTE: y and z axes are swapped
    xs = skel.narrow(-1, 0, 1).numpy()
    ys = skel.narrow(-1, 2, 1).numpy()
    zs = skel.narrow(-1, 1, 1).numpy()

    # Correct aspect ratio (https://stackoverflow.com/a/21765085)
    max_range = np.array(
        [xs.max() - xs.min(),
         ys.max() - ys.min(),
         zs.max() - zs.min()]).max() / 2.0
    mid_x = (xs.max() + xs.min()) * 0.5
    mid_y = (ys.max() + ys.min()) * 0.5
    mid_z = (zs.max() + zs.min()) * 0.5
    ax.set_xlim(mid_x - max_range, mid_x + max_range)
    ax.set_ylim(mid_y - max_range, mid_y + max_range)
    ax.set_zlim(mid_z - max_range, mid_z + max_range)
    ax.set_aspect('equal')

    if invert:
        ax.invert_zaxis()

    # Set starting view
    ax.view_init(elev=20, azim=-100)

    get_joint_metadata = _make_joint_metadata_fn(skel_desc)
    for joint_id, joint in enumerate(skel):
        meta = get_joint_metadata(joint_id)
        color = 'magenta'
        if meta['group'] == 'left':
            color = 'blue'
        if meta['group'] == 'right':
            color = 'red'
        parent = skel[meta['parent']]
        offset = parent - joint
        ax.quiver(
            [joint[0]],
            [joint[2]],
            [joint[1]],
            [offset[0]],
            [offset[2]],
            [offset[1]],
            color=color,
            alpha=alpha,
        )

    ax.scatter(xs, ys, zs, color='grey', alpha=alpha)
Beispiel #22
0
 def plotAgentVel(self, agent_num):
     vels = self.dataframe['velocity']
     fig = plt.figure()
     ax = fig.add_subplot(111, projection='3d')
     Axes3D.scatter(ax,
                    getWithout(vels[agent_num][:, 0], -1),
                    getWithout(vels[agent_num][:, 1], -1),
                    zs=np.arange(len(
                        vels[agent_num]))[vels[agent_num][:, 0] != -1],
                    s=3)
     plt.show()
Beispiel #23
0
 def plotAgentPos(self, agent_num):
     coords = self.dataframe['coordinates']
     fig = plt.figure()
     ax = fig.add_subplot(111, projection='3d')
     Axes3D.scatter(ax,
                    getWithout(coords[agent_num][:, 0], 1),
                    getWithout(coords[agent_num][:, 1], 1),
                    zs=np.arange(len(
                        coords[agent_num]))[coords[agent_num][:, 0] != 1],
                    s=3)
     plt.show()
Beispiel #24
0
def visualize_pointcloud(pc, subsample=False):
    pc = np.copy(pc)
    if subsample:
        mask = np.random.rand(pc.shape[0])
        pc = pc[mask < .1]

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Axes3D.scatter(ax, pc[:, 0], pc[:, 1], pc[:, 2])

    fig.show()
def main():
    # initialize ros node
    rospy.init_node('compute_calibration')

    # get path to folder containing recorded data
    filesPath = rospy.get_param('~files_path')

    # load trajectories
    kinectTraj = np.loadtxt('%skinect_trajectory' % (filesPath), delimiter=',')
    baxterTraj = np.loadtxt('%sbaxter_trajectory' % (filesPath), delimiter=',')

    # compute absolute orientation
    kinectOut, rot, trans = absOrientation(kinectTraj,baxterTraj)

    # plot both point sets together
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    # plot the data
    Axes3D.scatter(ax, kinectOut[:,0], kinectOut[:,1], kinectOut[:,2], s=20, c='r')
    Axes3D.scatter(ax, baxterTraj[:,0],baxterTraj[:,1], baxterTraj[:,2], s=20, c='b')

    # add labels and title
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_zticks([])
    ax.set_xlabel('X-axis')
    ax.set_ylabel('Y-axis')
    ax.set_zlabel('Z-axis')
    plt.title('Kinect-Baxter Calibration')
    plt.legend(['Kinect','Baxter'])
    plt.show()

    # get rotation matrix as quaternion and euler angles
    euler = tf.transformations.euler_from_matrix(rot)
    quat = tf.transformations.quaternion_from_euler(*euler)

    # save results to yaml file
    f = open('%skinect_calibration.yaml' % (filesPath), 'w')
    lines = ['trans: [', 'rot: [', 'rot_euler: [']

    for elem in trans: lines[0] += str(elem) + ', '
    lines[0] += ']\n'
    for elem in quat: lines[1] += str(elem) + ', '
    lines[1] += ']\n'
    for elem in euler: lines[2] += str(elem) + ', '
    lines[2] += ']\n'

    lines.append('parent: /base\n')
    lines.append('child: /kinect2_link\n')

    f.writelines(lines)
    f.close()
Beispiel #26
0
    def plot(self, axes: Axes3D, **kwargs):
        # Plot all sensors
        sx = list(map(lambda s: s.x, self.sensors))
        sy = list(map(lambda s: s.y, self.sensors))
        sz = list(map(lambda s: -s.depth, self.sensors))
        axes.scatter(sx, sy, sz, c='r', label='Sensors')

        # Plot all relays
        rx = list(map(lambda r: r.x, self.relays))
        ry = list(map(lambda r: r.y, self.relays))
        rz = list(map(lambda r: r.height, self.relays))
        axes.scatter(rx, ry, rz, c='b', label='Relays')
Beispiel #27
0
def plotPCA(proj3D, X_r, PCs, ligs, colors, csvPath, save_flag):
    """
    Plot the PCA data on 2D plot
    """

    # Main figure
    fig = plt.figure(figsize=(13, 12), dpi=100)

    if proj3D:
        ax = fig.add_subplot(111, projection="3d")
        for label, col, x, y, z in zip(ligs, colors,
                                       X_r[:, 0], X_r[:, 1], X_r[:, 2]):
            newCol = makeColor(col)
            Axes3D.scatter(ax, x, y, z, label=label, color=newCol,
                           marker="o", lw=1, s=800)
        ax.set_xlabel("PC1 (" + '{0:g}'.format(PCs[0]) + " %)", fontsize=30)
        ax.set_ylabel("PC2 (" + '{0:g}'.format(PCs[1]) + " %)", fontsize=30)
        ax.set_zlabel("PC3 (" + '{0:g}'.format(PCs[2]) + " %)", fontsize=30)
        ax.tick_params(axis="both", which="major", labelsize=20)
        pngPath = csvPath.replace(".csv", "_3D.png")
    else:
        ax = fig.add_subplot(111)
        for label, col, x, y in zip(ligs, colors, X_r[:, 0], X_r[:, 1]):
            newCol = makeColor(col)
            ax.scatter(x, y, label=label, color=newCol, marker="o", lw=1, s=800)
            # ax.annotate(label, xy=(x, y - 0.05), fontsize=10,
            #             ha='center', va='top')
        ax.set_xlabel("PC1 (" + '{0:g}'.format(PCs[0]) + " %)", fontsize=30)
        ax.set_ylabel("PC2 (" + '{0:g}'.format(PCs[1]) + " %)", fontsize=30)
        ax.tick_params(axis="both", which="major", labelsize=30)
        pngPath = csvPath.replace(".csv", "_2D.png")

    # figTitle = "PCA on " + csvPath + " (PC1=" + pcVals[0] + ", PC2=" +
    # pcVals[1] + ")"
    # ax.text(0.5, 1.04, figTitle, horizontalalignment="center", fontsize=30,
    #         transform=ax.transAxes)

    # Legend figure
    fig_legend = plt.figure(figsize=(13, 12), dpi=100)
    plt.figlegend(*ax.get_legend_handles_labels(), scatterpoints=1,
                  loc="center", fancybox=True,
                  shadow=True, prop={"size": 30})

    # Save figures if save flag was used
    if save_flag:
        print("\nSAVING figures\n")
        fig.savefig(pngPath, bbox_inches="tight")
        fig_legend.savefig(pngPath.replace(".png", "_legend.png"))
    # Otherwise show the plots
    else:
        print("\nSHOWING figures\n")
        plt.show()
Beispiel #28
0
    def plot_system(system):

        x = []
        y = []
        z = []
        for i in range(len(system.particles)):
            x.append(system.particles[i].position[0])
            y.append(system.particles[i].position[1])
            z.append(system.particles[i].position[2])

        ax = plt.axes(projection='3d')
        Axes3D.scatter(ax, x, y, z)
        plt.show()
Beispiel #29
0
    def plot_point_cloud(self, point_cloud):

        height = point_cloud.shape[0]

        point_cloud = point_cloud.reshape([height**2, 3])
        px = point_cloud[:, 0]
        py = point_cloud[:, 1]
        pz = point_cloud[:, 2]

        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        Axes3D.scatter(ax, px, py, pz)
        plt.show()
Beispiel #30
0
def show_pose(frame, highlight_marker=None):
    """
    Create 3D plot of marker positions
    :param frame: trajectory (1d numpy array: [markers])
    :param highlight_marker: order number of marker to be highlighted
    :return: True
    """
    show_frame = frame.reshape(int(frame.shape[0]/3), 3)

    fig = plt.figure(figsize=(10, 10))

    ax = fig.add_subplot(111, projection='3d')
    ax.set_xlim3d(-1000, 1000)
    ax.set_ylim3d(-1000, 1000)
    ax.set_zlim3d(-1000, 1000)

    if highlight_marker is None:
        Axes3D.scatter(ax, xs=show_frame[:, 0], ys=show_frame[:, 1], zs=show_frame[:, 2], c='b', marker='o')
    else:
        Axes3D.scatter(ax, xs=show_frame[:highlight_marker, 0], ys=show_frame[:highlight_marker, 1], zs=show_frame[:highlight_marker, 2], c='b', marker='o')
        Axes3D.scatter(ax, xs=show_frame[highlight_marker+1:, 0], ys=show_frame[highlight_marker+1:, 1], zs=show_frame[highlight_marker+1:, 2], c='b', marker='o')
        Axes3D.scatter(ax, xs=show_frame[highlight_marker, 0], ys=show_frame[highlight_marker, 1], zs=show_frame[highlight_marker, 2], c='r', marker='o', label='marker #{}'.format(highlight_marker))
        ax.legend()
    ax.set_xlabel('X Axis')
    ax.set_ylabel('Y Axis')
    ax.set_zlabel('Z Axis')
    # Axes3D.plot(ax, xs=trajectory[:, 0], ys=trajectory[:, 1], zs=trajectory[:, 2], c='k', linestyle='dashed')
    ax.view_init(90, -90)
    plt.show()
    return True
Beispiel #31
0
def add_bands_scatter_plot(axes3d: Axes3D,
                           kpoints: numpy.ndarray,
                           eigenvalues: numpy.ndarray,
                           axis: int,
                           layer: int,
                           band_indices: Union[List[int], range],
                           offset: Union[List[float], numpy.ndarray] = None):
    x, y, zs = get_x_y_zs(kpoints, eigenvalues, axis, layer)
    if offset is not None:
        x += offset[0]
        y += offset[1]
        zs += offset[2]
    for b in band_indices:
        axes3d.scatter(x, y, zs[:, b])
Beispiel #32
0
def check_output():
    fname = "data.txt"
    m, x, vx, y, vy, z, vz = np.loadtxt(fname, unpack=True)
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    maxsize = 30
    plt3d.scatter(ax,
                  x,
                  y,
                  z,
                  c='k',
                  s=maxsize * m / np.max(m),
                  label="Before")
    plt.show()
Beispiel #33
0
def point_cloud(df, columns=[0, 1, 2]):
    """3-D Point cloud for plotting things like mesh models of horses ;)"""
    df = df if isinstance(df, pd.DataFrame) else pd.DataFrame(df)
    if not all(c in df.columns for c in columns):
        columns = list(df.columns)[:3]

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')  # noqa
    Axes3D.scatter(*[df[columns[i]] for i in range(3)],
                   zdir='z',
                   s=20,
                   c=None,
                   depthshade=True)
    return ax
Beispiel #34
0
 def plotAgentVel(self, agent_num):
     agent = self.dataframe[agent_num]['velocity']
     fig = plt.figure()
     ax = fig.add_subplot(111, projection='3d')
     Axes3D.scatter(ax,
                    getWithout(agent[:, 0], -1),
                    getWithout(agent[:, 1], -1),
                    zs=np.arange(len(agent))[agent[:, 0] != -1],
                    s=3)
     plt.title("Example Velocity of Agent")
     plt.xlabel("x component")
     plt.ylabel("y component")
     plt.zlabel("Time")
     plt.show()
Beispiel #35
0
 def plotAgentPos(self, agent_num):
     agent = self.dataframe[agent_num]['coordinates']
     fig = plt.figure()
     ax = fig.add_subplot(111, projection='3d')
     Axes3D.scatter(ax,
                    getWithout(agent[:, 0], 1),
                    getWithout(agent[:, 1], 1),
                    zs=np.arange(len(agent))[agent[:, 0] != 1],
                    s=3)
     plt.title("Example Trajectory of Agent")
     plt.xlabel("x coordinate")
     plt.ylabel("y coordinate")
     plt.zlabel("Time")
     plt.show()
Beispiel #36
0
def plot_results():
    os.chdir("result")
    all_data = []
    maxt = -1
    for f in sorted(os.listdir("./")):
        all_data.append(np.loadtxt(f, unpack=True))
        maxt += 1
    d = np.array(all_data)
    shape = d.shape
    m = d[0, 0, :]
    maxsize = 20
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    maxxyz = 0
    minsep = 1e8
    maxsep = 0
    for t in range(shape[0]):
        maxxyz = max(
            maxxyz,
            max(np.max(np.abs(d[t, 1, :])), np.max(np.abs(d[t, 2, :])),
                np.max(np.abs(d[t, 3, :]))))
    # 	if t == maxt:
    # 		print "at last t"
    # 		for particle1 in range(shape[2]):
    # 			for particle2 in range(shape[2]):
    # 				if particle1 == particle2:
    # 					continue
    # 				minsep = min(minsep, dist(d[t,:,particle1], d[t,:,particle2]))
    # 				maxsep = max(maxsep, dist(d[t,:,particle1], d[t,:,particle2]))
    # print minsep, maxsep
    for t in range(shape[0]):
        # plt.scatter(d[t, 1, :], d[t, 3, :], s=maxsize*m/np.max(m))
        plt3d.scatter(ax,
                      d[t, 1, :],
                      d[t, 2, :],
                      d[t, 3, :],
                      c='k',
                      s=maxsize * m / np.max(m))
        plt.xlim([-maxxyz, maxxyz])
        plt.ylim([-maxxyz, maxxyz])
        ax.set_zlim([-maxxyz, maxxyz])
        fname = "graphic_result_%03d.png" % t
        sys.stdout.write("Writing " + fname + "\r")
        sys.stdout.flush()
        plt.savefig(fname)
        plt.cla()
        # plt.show()
    sys.stdout.write("\nDone!\n")
    sys.stdout.flush()
Beispiel #37
0
def check_tree():
    m, x, cx, y, cy, z, cz = np.loadtxt(inname, unpack=True)

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

    maxsize = 30
    plt3d.scatter(ax,
                  x,
                  y,
                  z,
                  c='r',
                  s=maxsize * m / np.max(m),
                  label="Particles")

    w, x, cx, y, cy, z, cz = np.loadtxt(outname, unpack=True)
    maxsize = 20
    # plt3d.scatter(ax, x, y, z, 'x', c='g', s=maxsize/4, label="Centers")
    # plt3d.scatter(ax, cz, cy, cz, c='hotpink', s=2*w/np.max(w), label="COMs")
    # for width, j, k, i in zip(w, x, y, z):
    for width, i, j, k in zip(w, x, y, z):
        # plt3d.scatter(ax, [i], [j], [k], c='r')
        for top in range(2):
            for side in range(2):
                plt3d.plot(ax, [i - width / 2, i + width / 2], [
                    j - width / 2 + side * width, j - width / 2 + side * width
                ], [k - width / 2 + top * width, k - width / 2 + top * width],
                           c='k',
                           linewidth=.2)
                plt3d.plot(
                    ax, [
                        i - width / 2 + side * width,
                        i - width / 2 + side * width
                    ], [j - width / 2, j + width / 2],
                    [k - width / 2 + top * width, k - width / 2 + top * width],
                    c='k',
                    linewidth=.2)
                plt3d.plot(ax, [
                    i - width / 2 + top * width, i - width / 2 + top * width
                ], [
                    j - width / 2 + side * width, j - width / 2 + side * width
                ], [k - width / 2, k + width / 2],
                           c='k',
                           linewidth=.2)
    plt.legend()
    plt.xlabel("X")
    plt.ylabel("Y")
    ax.set_zlabel("Z")
    plt.show()
def main():
    global rR
    global v
    #v = polynomial_surface2(rR)
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    v=[  345.01147843,  -731.53883648,   701.43498064,  -333.41157482,    61.69405675,   434.95848754,  -734.92037163,   468.45066799,  -108.66899203,   197.05683428,  -229.38490931,    73.72852732,    38.62490216,   -23.11704968,     2.79760705,  1112.02959271, -1850.90352232,  1243.44148281,  -301.1366546,   1096.50133704, -1278.21349214,   419.17838208,   338.80540403,  -201.95899053,    33.68403733,  1333.97626976, -1566.15905716,   552.3302448,    922.09578713,  -558.92492054,   145.7445413,    705.90344671, -442.88105472,   259.89354682,   138.22604583]
    #ax=implicit.plot_implicit(fn4,bbox=(-1.5,0,-3.5,-1.5,-2,1),rc=200,ns=30,colors='b', ax=ax)
    v=[  2.18930311,   0.24260729,  57.46589779,   3.38543536,  -9.56889825,  34.36258001, -36.2221404,    4.86597348,  12.89329227,  21.10709896,  -4.36372996,  -5.89323474,   3.98227029,   0.9848254,    0.23593784, -36.46890674, -25.34400559,  81.86028261,  14.43120124,  44.89510312, -52.04801532,  -9.90597384,  16.49023335,   2.29875215,   0.40597427, -55.46318028, -39.9563639,   26.95078929,  35.15384941, -18.2399162,   5.13417155, -31.78519693, -14.89522473,  10.38829065,  -6.66988281]
    #ax=implicit.plot_implicit(fn4,bbox=(-1.5,0,-3.5,-1.5,-2,1),rc=200,ns=30,colors='r', ax=ax)
    #rR = tree_time.tree_time(rR,0.05)
    rR=array(rR)
    Axes3D.scatter(ax,rR[:,0],rR[:,1],rR[:,2])
    Axes3D.scatter(ax,-0.87676517,-2.5211104,-0.76908632,color='green') 
    plt.show()
Beispiel #39
0
def PCAChart(X_pca, alpha=0.2):
    n = X_pca.shape[
        1]  #second dimension is the number of colums which is the number of components
    if n == 2:
        plt.scatter(X_pca[:, 0], X_pca[:, 1], alpha=alpha)
    elif n == 3:
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        Axes3D.scatter(ax,
                       xs=X_pca[:, 0],
                       ys=X_pca[:, 1],
                       zs=X_pca[:, 2],
                       alpha=alpha)
    else:
        print("n should be either 2 or 3")
    def updatePlot(self, X, Y, Z, population=None):
        self.activePlot = (X,Y,Z)
        x, y = np.meshgrid(X,Y)

        if self.surface is not None:
            self.surface.remove()

        if self.scatter is not None:
            self.scatter.remove()

        # surface
        self.surface = Axes3D.plot_surface(
                self.axes,
                x, y, Z,
                rstride=1,
                cstride=1,
                cmap=cm.coolwarm,
                linewidth=0,
                antialiased=False,
                shade=False,
                alpha=0.5
        )

        # population
        if population is not None:
            self.activePopulation = population
            x, y, z = self.preparePopulationData(population)
            self.scatter = Axes3D.scatter(self.axes, x, y, z, c="r", marker="o")
            self.scatter.set_alpha(1.0)

        # Draw all
        self.canvas.draw()
        self.canvas.flush_events()
Beispiel #41
0
def plotFiguresTemp(xSolid, ySolid, zSolid, xFFDDeform, yFFDDeform, zFFDDeform):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    # Axes3D.plot_wireframe(ax, z, x, y)
    ax.set_xlabel('Z axis')
    ax.set_ylabel('X axis')
    ax.set_zlabel('Y axis')

    Axes3D.scatter(ax, zSolid, xSolid, ySolid, s=10, c='b')
    Axes3D.scatter(ax, zFFDDeform, xFFDDeform, yFFDDeform, s=30, c='r')

    # Axes3D.set_ylim(ax, [-0.5,4.5])
    # Axes3D.set_xlim(ax, [-0.5,4.5])
    Axes3D.set_zlim(ax, [-0.7, 0.7])

    plt.show(block=True)
def plotFiguresTemp(xSolid, ySolid, zSolid, xFFDDeform, yFFDDeform, zFFDDeform):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    # Axes3D.plot_wireframe(ax, z, x, y)
    ax.set_xlabel('Z axis')
    ax.set_ylabel('X axis')
    ax.set_zlabel('Y axis')

    Axes3D.scatter(ax, zSolid, xSolid, ySolid, s=10, c='b')
    Axes3D.scatter(ax, zFFDDeform, xFFDDeform, yFFDDeform, s=30, c='r')

    # Axes3D.set_ylim(ax, [-0.5,4.5])
    # Axes3D.set_xlim(ax, [-0.5,4.5])
    Axes3D.set_zlim(ax, [-0.7, 0.7])

    plt.show(block=True)
Beispiel #43
0
def visualize_pointclouds(pc0, pc1, subsample0=False, subsample1=False):
    pc0 = np.copy(pc0)
    pcl = np.copy(pc1)
    if subsample0:
        mask = np.random.rand(pc0.shape[0])
        pc0 = pc0[mask < .005]

    if subsample1:
        mask = np.random.rand(pc1.shape[0])
        pc1 = pc1[mask < .005]

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Axes3D.scatter(ax, pc0[:, 0], pc0[:, 1], pc0[:, 2], c='b')
    Axes3D.scatter(ax, pc1[:, 0], pc1[:, 1], pc1[:, 2], c='r')
    plt.xlabel('X')
    plt.ylabel('Y')
    fig.show()
Beispiel #44
0
def plotElements(PhysicalElementMatrix):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    # Axes3D.plot_wireframe(ax, z, x, y)
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')
    ax.set_zlabel('Z axis')
    

    xVector = []
    yVector = []
    zVector = []
    for i in range(CONST_DIMENSION_X):
        for j in range(CONST_DIMENSION_Y):
            for k in range(CONST_DIMENSION_Z):
                elementObject = PhysicalElementMatrix[i][j][k]
                for gridPointObject in elementObject.gridPointList:
                    xVector.append(gridPointObject.getX())
                    yVector.append(gridPointObject.getY())
                    zVector.append(gridPointObject.getZ())

    Axes3D.scatter(ax, xVector, yVector, zVector, s=30, c='r')

    #Axes3D.plot_wireframe(ax, zSolid, xSolid, ySolid, rstride = 1, cstride = 1, color="b")



    # create the lines around all the elements
    for i in range(CONST_DIMENSION_X):
        for j in range(CONST_DIMENSION_Y):
            for k in range(CONST_DIMENSION_Z):
                elementObject = PhysicalElementMatrix[i][j][k]
                ListXVectors,ListYVectors,ListZVectors = elementObject.getOuterLineVectors()
                for l in range(len(ListXVectors)):
                    plt.plot(ListXVectors[l],ListYVectors[l], ListZVectors[l], c = 'b')

    Axes3D.set_ylim(ax, [-10,10])
    Axes3D.set_xlim(ax, [-10,10])
    Axes3D.set_zlim(ax, [-10, 10])
    

    plt.show(block=True)
Beispiel #45
0
def addcurve( ax, path, endpoints, color ) :
  px = path[ :,0 ]
  py = path[ :,1 ]
  pz = path[ :,2 ]
  n = len(px) - 1
  q = Axes3D.plot(ax, px, py, zs=pz, c=color, linewidth=2 )
  px = endpoints[ :,0 ]
  py = endpoints[ :,1 ]
  pz = endpoints[ :,2 ]
  print px, py, pz
  q = Axes3D.scatter(ax, px,py, zs=pz, c=color, marker='o', s=60)
def plotInitialState(xsolidInitial,ysolidInitial, zsolidInitial,
                     xFFDInitial, yFFDInitial, zFFDInitial):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    # Axes3D.plot_wireframe(ax, z, x, y)
    ax.set_xlabel('Z axis')
    ax.set_ylabel('X axis')
    ax.set_zlabel('Y axis')
    
    Axes3D.scatter(ax, zsolidInitial, xsolidInitial, ysolidInitial, s=10, c='b')
    #Axes3D.plot_wireframe(ax, zsolidInitial, xsolidInitial, ysolidInitial,rstride = 1, cstride = 1, color="y")
    Axes3D.scatter(ax, zFFDInitial, xFFDInitial, yFFDInitial, s=30, c='r')
    
    
    #Axes3D.set_ylim(ax, [-0.5,4.5])
    #Axes3D.set_xlim(ax, [-0.5,4.5])
    Axes3D.set_zlim(ax, [-0.7, 0.7])
    
    plt.show(block=True)
    def updatePopulation(self, population):
        self.activePopulation = population
        x, y, z = self.preparePopulationData(population)

        if self.scatter is not None:
            self.scatter.remove()

        self.scatter = Axes3D.scatter(self.axes, x, y, z, c="r", marker="o")
        # self.surface.set_zorder(2)
        # self.scatter.set_zorder(100)
        self.scatter.set_alpha(1.0)
        self.canvas.draw()
        self.canvas.flush_events()
def plotElements(fig, ax, ElementsSbpData, ElementsFFDData, NumElements,c1,c2,\
                 c3,c4):
    
    for i in range(NumElements):
        xSolid = []
        ySolid = []
        zSolid = []
        
        xFFD = []
        yFFD = []
        zFFD = []
        
        #fill the Solid body points


        for SBPTuple in ElementsSbpData[i]:
            xSolid.append(SBPTuple[0][0])
            ySolid.append(SBPTuple[0][1])
            zSolid.append(SBPTuple[0][2])
        
        
        for FFDTuple in ElementsFFDData[i]:
            xFFD.append(FFDTuple[1][0])
            yFFD.append(FFDTuple[1][1])
            zFFD.append(FFDTuple[1][2])

        # element 1 is the fuselage whose x and z values were switched
        # to make z cross sections. So switch these back when plotting
        
        if(i == 0):
            #ax.plot_trisurf(zSolid, xSolid, ySolid, cmap=cm.jet, linewidth=0.2)
            Axes3D.scatter(ax, zSolid,xSolid, ySolid, s=20, c=c1)
            Axes3D.scatter(ax, zFFD, xFFD, yFFD, s=30, c= c2)
            #Axes3D.plot_wireframe(ax, zFFD, xFFD, yFFD)
        if(i == 1):
            #ax.plot_trisurf(xSolid, zSolid, ySolid, cmap=cm.jet, linewidth=0.2)
            Axes3D.scatter(ax, zSolid,xSolid, ySolid, s=20, c=c3)
            Axes3D.scatter(ax, zFFD, xFFD, yFFD, s=30, c= c4)
Beispiel #49
0
def makeacluster(radius,charges = 0, distance =4,cadmium_term=False,
                 module = 'nwchem',
                 removehangeroners = True, surfacepassivation=True,_plot=True):
    """ Prepare an xyzfile of cluster of CdS or CdSe with a specified radius and a certain number of point charges around it"""

    
    #########cell vectors in angstroms
    a = array([4.16,0,0])
    b = 4.16*array([cos(radians(60)),sin(radians(60)),0])
    c = array([0,0,6.756])
    
    
    ###### cell vectors in angstroms for CdSe
    a = array([4.2985,0,0])
    b = 4.2985*array([cos(radians(60)),sin(radians(60)),0])
    c = array([0,0,7.0152])
        
        
    cellvectors = array([a,b,c])
    
    
    
    ##Atomic positions in fractional coordinates in cell
    ### For Wurtzite#####
    Cdcoord = array([[0,0,0],[0.33,0.333,0.5]])
    Scoord = array([[0,0,0.375],[0.3333,0.3333,0.875]])
    tetarray = array([[0,0,0.375],[-0.333,-0.333,-0.125],[0.6666,-0.3333,-0.125],[-0.3333,0.6666,-0.125]])
    Cdcoord= dot(Cdcoord,cellvectors)
    Scoord=dot(Scoord,cellvectors)
  

    Cdcoordlist1 = ndarray((0,3))
    Cdcoordlist2 = ndarray((0,3))
    Scoordlist1 = ndarray((0,3))
    Scoordlist2 = ndarray((0,3))
    OHcoordlist=ndarray((0,3))
    Hcoordlist=ndarray((0,3))
    
    numbertorepeat = int(radius/b[1])+2
    
    for p in itertools.product(range(-numbertorepeat,numbertorepeat+1),repeat=3):
        
        x= dot(array([p]),cellvectors)+Cdcoord[0]
        x2=dot(array([p]),cellvectors)+Cdcoord[1]
        y = dot(array([p]),cellvectors)+Scoord[0]
        y2 = dot(array([p]),cellvectors)+Scoord[1]
        
        Cdcoordlist1 = append(Cdcoordlist1,x,axis=0)
        Cdcoordlist2 = append(Cdcoordlist2,x2,axis=0)
        Scoordlist1 = append(Scoordlist1,y,axis=0)
        Scoordlist2 = append(Scoordlist2,y2,axis=0)
    
    
    
    tetcoord=array([[ -2.08208000e+00,   1.19968767e+00,  -8.44500000e-01],
                     [ -2.08000000e-03,  -2.40297801e+00 , -8.44500000e-01],
                     [  2.07792000e+00,   1.19968767e+00,  -8.44500000e-01],
                     [  0.00000000e+00,   0.00000000e+00,   2.53350000e+00]])#ndarray((0,3))

    tetcoord2 = array( [[ -2.06544000e+00,  -1.19968767e+00,  -8.44500000e-01],
                             [  1.43520000e-02,   1.08079970e-03,   2.53350000e+00],
                             [  1.45600000e-02,   2.40297801e+00,  -8.44500000e-01],
                             [  2.09456000e+00,  -1.19968767e+00,  -8.44500000e-01]])
    Cdtetcoord1=tetcoord*array([[1,1,-1]])
    Cdtetcoord2=tetcoord2*array([[1,1,-1]])
    
    extrashift = (a+b+c)/2

    Cdcoordlist1[:]+=extrashift#array([[radius+extrashift,radius+extrashift,radius+extrashift]])
    Scoordlist1[:]+=extrashift#array([[radius+extrashift,radius+extrashift,radius+extrashift]])
    Cdcoordlist2[:]+=extrashift#array([[radius+extrashift,radius+extrashift,radius+extrashift]])
    Scoordlist2[:]+=extrashift#array([[radius+extrashift,radius+extrashift,radius+extrashift]])
    
    x= where(numpy.sum(Cdcoordlist1**2,axis=1)<radius**2)[0]
    Cdcoordlist1=Cdcoordlist1[x]
    
    x= where(numpy.sum(Cdcoordlist2**2,axis=1)<radius**2)[0]
    Cdcoordlist2=Cdcoordlist2[x]
   
    
    
    Scoordlist1=Scoordlist1[numpy.sum(Scoordlist1**2,axis=1)<radius**2]
    Scoordlist2=Scoordlist2[numpy.sum(Scoordlist2**2,axis=1)<radius**2]
    
   
    extrashift = 10
    Cdcoordlist1[:]+=array([[radius+extrashift,radius+extrashift,radius+extrashift]])
    Scoordlist1[:]+=array([[radius+extrashift,radius+extrashift,radius+extrashift]])
    Cdcoordlist2[:]+=array([[radius+extrashift,radius+extrashift,radius+extrashift]])
    Scoordlist2[:]+=array([[radius+extrashift,radius+extrashift,radius+extrashift]])
                  

    print '--------------'


    if cadmium_term:
        """Cadmium Termination.  Still not working"""
        ### TODO implement this.  
        print 'terminating the surface with cadmium atoms'

                       
        for i in Scoordlist1:
            remove = array([])
            bondlength=1.83  ## angstroms
            x= append(Cdcoordlist1,Cdcoordlist2,axis=0)[numpy.sum((append(Cdcoordlist1,Cdcoordlist2,axis=0)[:]-i)**2,axis=1)<9]-i
            if x.shape[0]==4:
                pass
            else:
                
                for s in Cdtetcoord1:
                    if not any(sum((x[:]-s)**2,axis=1)<0.5):
                       print "    adding Cd1 Atom at",[i+s]
                       Cdcoordlist1= append(Cdcoordlist1,[i+s],axis=0)
             
        for i in Scoordlist2:
            bondlength=1.83 ## angstroms
            x= append(Cdcoordlist1,Cdcoordlist2,axis=0)[numpy.sum((append(Cdcoordlist1,Cdcoordlist2,axis=0)[:]-i)**2,axis=1)<9]-i
            if x.shape[0]==4:
                pass
            else:
                #print 'undercoordinated atom found'
                for s in Cdtetcoord2:
                    if not any(sum((x[:]-s)**2,axis=1)<0.5):
                       print "    adding Cd2 Atom at",[i+s]
                       Cdcoordlist2= append(Cdcoordlist2,[i+s],axis=0)
    
        
                       
    if removehangeroners:
        """removing Cd or S/Se atoms connected by only one bond"""
        print '--------------'  
        print "removing core atoms connected by only one bond"
        removefromCd1 = []
        removefromCd2 = []
        removefromS1 = []
        removefromS2 = []
        removefromS2_2 = array([])
        removefromCd1_2 = array([])
        for i in Cdcoordlist1:
        
            x= append(Scoordlist1,Scoordlist2,axis=0)[numpy.sum((append(Scoordlist1,Scoordlist2,axis=0)[:]-i)**2,axis=1)<9]-i
    
            if x.shape[0]==1:
                        removefromCd1 = append(removefromCd1,where(all(Cdcoordlist1==i,axis=1))[0])
        

        for i in Cdcoordlist2:
            x= append(Scoordlist1,Scoordlist2,axis=0)[numpy.sum((append(Scoordlist1,Scoordlist2,axis=0)[:]-i)**2,axis=1)<9]-i
            if x.shape[0]==1:
                removefromCd2 = append(removefromCd2,where(all(Cdcoordlist2==i,axis=1))[0])
                
                          
                           
            
        for i in Scoordlist1:
            x= append(Cdcoordlist1,Cdcoordlist2,axis=0)[numpy.sum((append(Cdcoordlist1,Cdcoordlist2,axis=0)[:]-i)**2,axis=1)<9]-i
            if x.shape[0]==1:
                removefromS1 = append(removefromS1,where(all(Scoordlist1==i,axis=1))[0])
            
        
               
        for i in Scoordlist2:
            x= append(Cdcoordlist1,Cdcoordlist2,axis=0)[numpy.sum((append(Cdcoordlist1,Cdcoordlist2,axis=0)[:]-i)**2,axis=1)<9]-i
            if x.shape[0]==1:
                removefromS2 = append(removefromS2,where(all(Scoordlist2==i,axis=1))[0])
                
        print "    removed", len(removefromCd1), "atoms from Cd1"
        print "    removed", len(removefromCd2), "atoms from Cd2"
        print "    removed", len(removefromS1), "atoms from S1"
        print "    removed", len(removefromS2), "atoms from S2"
        Cdcoordlist1 = delete(Cdcoordlist1,removefromCd1,axis=0)  
        Cdcoordlist2 = delete(Cdcoordlist2,removefromCd2,axis=0)  
        Scoordlist1 = delete(Scoordlist1,removefromS1,axis=0)  
        Scoordlist2 = delete(Scoordlist2,removefromS2,axis=0)  
        

    listofcoordlists = [Cdcoordlist1,Cdcoordlist2,Scoordlist1,Scoordlist2,OHcoordlist,Hcoordlist]
    alllists = ndarray((0,3))                                                                   
    surface_atoms_count = 0

    """Surface passivation with cations and anions"""
    if surfacepassivation:
        CdOHbondlength =2.7
        for i in Cdcoordlist1:
            bondlength=CdOHbondlength
            x= append(Scoordlist1,Scoordlist2,axis=0)[numpy.sum((append(Scoordlist1,Scoordlist2,axis=0)[:]-i)**2,axis=1)<9]-i
            
            if x.shape[0]==4:
                pass
            else:
                #print 'undercoordinated atom found'
                surface_atoms_count +=1
                for s in tetcoord:
                    if not any(sum((x[:]-s)**2,axis=1)<0.5):# and not any(sum((OHcoordlist[:]-(i+s/sqrt(sum(s**2))*bondlength))**2,axis=1)<0.5):
                       
                        OHcoordlist= append(OHcoordlist,[i+s/sqrt(sum(s**2))*bondlength],axis=0)
                     
                    else:
                         pass
                        # print min(sum((OHcoordlist[:]-(i+s/sqrt(sum(s**2))*bondlength))**2,axis=1))
    
        for i in Cdcoordlist2:
            bondlength=CdOHbondlength ## angstroms
            x= append(Scoordlist1,Scoordlist2,axis=0)[numpy.sum((append(Scoordlist1,Scoordlist2,axis=0)[:]-i)**2,axis=1)<9]-i
            if x.shape[0]==4:
                pass
            else:
                #print 'undercoordinated atom found'
                surface_atoms_count +=1
                for s in tetcoord2:
                    if not any(sum((x[:]-s)**2,axis=1)<0.5):# and not any(sum((OHcoordlist[:]-(i+s/sqrt(sum(s**2))*bondlength))**2,axis=1)<0.5):
                        
                        OHcoordlist= append(OHcoordlist,[i+s/sqrt(sum(s**2))*bondlength],axis=0)
                        
                    else:
                        pass#print min(sum((OHcoordlist[:]-(i+s/sqrt(sum(s**2))*bondlength))**2,axis=1))
    
        for i in Scoordlist1:
            remove = array([])
            bondlength=1.83  ## angstroms
            x= append(Cdcoordlist1,Cdcoordlist2,axis=0)[numpy.sum((append(Cdcoordlist1,Cdcoordlist2,axis=0)[:]-i)**2,axis=1)<9]-i
            if x.shape[0]==4:
                pass
            else:
                #print 'undercoordinated atom found'
                surface_atoms_count +=1
                for s in Cdtetcoord1:
                    if not any(sum((x[:]-s)**2,axis=1)<0.5) and not any(sum((Hcoordlist[:]-(i+s/sqrt(sum(s**2))*bondlength))**2,axis=1)<2):
                       
                       Hcoordlist= append(Hcoordlist,[i+s/sqrt(sum(s**2))*bondlength],axis=0)
                       
             
        for i in Scoordlist2:
            bondlength=1.83 ## angstroms
            x= append(Cdcoordlist1,Cdcoordlist2,axis=0)[numpy.sum((append(Cdcoordlist1,Cdcoordlist2,axis=0)[:]-i)**2,axis=1)<9]-i
            if x.shape[0]==4:
                pass
            else:
                #print 'undercoordinated atom found'
                surface_atoms_count +=1
                for s in Cdtetcoord2:
                    if not any(sum((x[:]-s)**2,axis=1)<0.5) and not any(sum((Hcoordlist[:]-(i+s/sqrt(sum(s**2))*bondlength))**2,axis=1)<2):
                       
                       Hcoordlist= append(Hcoordlist,[i+s/sqrt(sum(s**2))*bondlength],axis=0)
    
        
    
        listofcoordlists = [Cdcoordlist1,Cdcoordlist2,Scoordlist1,Scoordlist2,OHcoordlist,Hcoordlist]
     
     
     
    ###########Remove Duplicate Atoms 
    for i in listofcoordlists[0:4]:
       
        OHcoordlist = delete(OHcoordlist,checkduplicates(i,OHcoordlist)[1],axis=0)
        Hcoordlist = delete(Hcoordlist,checkduplicates(i,Hcoordlist)[1],axis=0)
    listofcoordlists = [Cdcoordlist1,Cdcoordlist2,Scoordlist1,Scoordlist2,OHcoordlist,Hcoordlist]
    
    for i in range(len(listofcoordlists)):
        for j in range(i,len(listofcoordlists)):
            
            
            x = checkduplicates(listofcoordlists[i],listofcoordlists[j],threshold=1)
           
            if x[0].size>0:
                if j==i:
#                    print i,j,x
#                    print listofcoordlists[i][x[0]]
#                    print  listofcoordlists[i][x[1]]
                    listofcoordlists[i]=delete(listofcoordlists[i],x[1],axis=0)
                    
                    
                    print 'duplicate atoms found in same list! THE DUPLICATE ATOMS WERE REMOVED'
                else:
                    print i,j,x
                    print 'duplicate atoms found! ERROR YOU NEED TO FIX THIS'
   
          
    (Cdcoordlist1,Cdcoordlist2,Scoordlist1,Scoordlist2,OHcoordlist,Hcoordlist)=listofcoordlists[:]

 
  ####################3 add charges aroundthe particls
    chargecoordlist=pointsonsphere(charges,radius+distance)+array([[radius,radius,radius]])

   ###############################    
    if _plot: 
        fig=figure()
        ax = fig.add_subplot(111, projection='3d')
            
                
        Axes3D.scatter(ax,Cdcoordlist1[:,0],Cdcoordlist1[:,1],Cdcoordlist1[:,2],c='b')
        Axes3D.scatter(ax,Cdcoordlist2[:,0],Cdcoordlist2[:,1],Cdcoordlist2[:,2],c='b')
        Axes3D.scatter(ax,Scoordlist1[:,0],Scoordlist1[:,1],Scoordlist1[:,2],c='r') 
        Axes3D.scatter(ax,Scoordlist2[:,0],Scoordlist2[:,1],Scoordlist2[:,2],c='r')    
        Axes3D.scatter(ax,OHcoordlist[:,0],OHcoordlist[:,1],OHcoordlist[:,2],c='y')
        Axes3D.scatter(ax,Hcoordlist[:,0],Hcoordlist[:,1],Hcoordlist[:,2],c='k')
        Axes3D.scatter(ax,chargecoordlist[:,0],chargecoordlist[:,1],chargecoordlist[:,2],c='k')



    numcoreatoms = Cdcoordlist1.shape[0]*1+Cdcoordlist2.shape[0]+Scoordlist1.shape[0]*1+Scoordlist2.shape[0]*1
    print 'cadmium atoms:',Cdcoordlist1.shape[0]*1+Cdcoordlist2.shape[0]
    print 'sulfur atoms:', Scoordlist1.shape[0]*1+Scoordlist2.shape[0]
    print 'negative cations:', OHcoordlist.shape[0]
    print 'positive cations:', Hcoordlist.shape[0]
    print 'number of core atoms', numcoreatoms
    numatoms= Cdcoordlist1.shape[0]*1+Cdcoordlist2.shape[0]+Scoordlist1.shape[0]*1+Scoordlist2.shape[0]*1+OHcoordlist.shape[0]*1+Hcoordlist.shape[0]*1
    
    print 'num electrons with ECP:', str(10*(Cdcoordlist1.shape[0]+Cdcoordlist2.shape[0])+
                                                8*(Scoordlist1.shape[0]+Scoordlist2.shape[0])+
                                                OHcoordlist.shape[0]*10+
                                                Hcoordlist.shape[0]*0)

    print 'num atoms:', numatoms, 'total charge:', str(Cdcoordlist1.shape[0]*2+Cdcoordlist2.shape[0]*2+
                                                Scoordlist1.shape[0]*-2+Scoordlist2.shape[0]*-2+
                                                OHcoordlist.shape[0]*-1+
                                                Hcoordlist.shape[0]*1)
    
    commentline = str('cadmium atoms: '+str(Cdcoordlist1.shape[0]*1+Cdcoordlist2.shape[0])+
                ', sulfur atoms: '+ str(Scoordlist1.shape[0]*1+Scoordlist2.shape[0])+
                ', total charge of cluster: '+ str(Cdcoordlist1.shape[0]*2+
                  +Cdcoordlist2.shape[0]*2
                                +Scoordlist1.shape[0]*-2
                                +Scoordlist2.shape[0]*-2
                                +OHcoordlist.shape[0]*-1
                                +Hcoordlist.shape[0]*1)+
                ', number of point charges:'+str(charges)+
                ' removehangeroners= '+str(removehangeroners)
                +'\n')
    print 'number of surface atoms counted', surface_atoms_count
    with open('/home/chris/Desktop/CdSParticle.xyz','wb') as f:#'+str(numcoreatoms)+'core'+str(charges)+'charges.xyz','wb') as f:
        f.write(str(numatoms)+'\n')
        f.write(commentline)
        
        
        for i in append(Cdcoordlist1,Cdcoordlist2,axis=0):
            f.write('Cd '+str(i[0])+' '+str(i[1])+' '+str(i[2])+'\n')
        for i in append(Scoordlist1,Scoordlist2,axis=0):
            f.write('S '+str(i[0])+' '+str(i[1])+' '+str(i[2])+'\n')
        for i in OHcoordlist:
            f.write('Cl '+str(i[0])+' '+str(i[1])+' '+str(i[2])+'\n')
        for i in Hcoordlist:
            f.write('H '+str(i[0])+' '+str(i[1])+' '+str(i[2])+'\n')
        for i in chargecoordlist:
            
            if module == 'nwchem':
                f.write('bq1 '+str(i[0])+' '+str(i[1])+' '+str(i[2])+' charge -1\n')
            elif module == 'orca':
                f.write('Q -1'+str(i[0])+' '+str(i[1])+' '+str(i[2])+'\n')
        f.close()
    return None
def plotFFDPointsAndPlane(xsolidInitial,ysolidInitial, zsolidInitial, xFFDInitial, yFFDInitial, zFFDInitial,
                          LeadingEdgeX, LeadingEdgeY, LeadingEdgeZ):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    
    # Axes3D.plot_wireframe(ax, z, x, y)
    ax.set_xlabel('Z axis')
    ax.set_ylabel('X axis')
    ax.set_zlabel('Y axis')
    
    Axes3D.scatter(ax, zsolidInitial, xsolidInitial, ysolidInitial, s=10, c='y')
    #Axes3D.plot_wireframe(ax, zsolidInitial, xsolidInitial, ysolidInitial, rstride = 1, cstride = 1, color='y')
    #Axes3D.scatter(ax, LeadingEdgeZ, LeadingEdgeX, LeadingEdgeY, s=10, c='y')
    #Axes3D.plot_wireframe(ax, zSolid, xSolid, ySolid, rstride = 1, cstride = 1, color="b")
    Axes3D.scatter(ax, zFFDInitial, xFFDInitial, yFFDInitial, s=10, c='r')
    
    LeadingEdgeX1 = []
    LeadingEdgeY1 = []
    LeadingEdgeZ1 = []
    
    #Find all the leading edge points:
    for element in solidBoundaryPointArray:
        if((element.getLabel() == "LeadingEdge") or (element.getLabel() == "TrailingEdge")
           or (element.getLabel() == "WingTip") or (element.getLabel() == "WingRoot")):
            LeadingEdgeX1.append(element.getX())
            LeadingEdgeY1.append(element.getY())
            LeadingEdgeZ1.append(element.getZ())
    #Axes3D.scatter(ax, LeadingEdgeZ1, LeadingEdgeX1, LeadingEdgeY1, s=100, c='r')
    
    #plot the deformed wing and FFD point data
    
    xDeformed = []
    yDeformed = []
    zDeformed = []
    
    xFFDDeformed = []
    yFFDDeformed = []
    zFFDDeformed = []
    
    for element in solidBoundaryPointArray:
        xDeformed.append(element.getX())
        yDeformed.append(element.getY())
        zDeformed.append(element.getZ())
    
    # filling the FFD arrays
    for i in range(CONST_nXFDD):
        for j in range(CONST_nYFDD):
            for k in range(CONST_nZFDD):
                element = FFDPointArray[i][j][k]
                xFFDDeformed.append(element.getX())
                yFFDDeformed.append(element.getY())
                zFFDDeformed.append(element.getZ())
    """
        Axes3D.plot_wireframe(ax, zDeformed, xDeformed, yDeformed, rstride =1, cstride = 1, color='b')
        """
    Axes3D.scatter(ax, zDeformed, xDeformed, yDeformed, s=10, color='b')
    Axes3D.scatter(ax, zFFDDeformed, xFFDDeformed, yFFDDeformed, s=10, c='g')
    
    #takes a value for t,u,v. When a value is set to -1, then that parameter is free
    # to change while the one that is not set to -1 is the plane that needs to be drawn
    tuplesArray = plotIsoparametricLine(-1,-1,-1)
    xArray = []
    yArray = []
    zArray = []

    for a in tuplesArray:
        xArray.append(a[0])
        yArray.append(a[1])
        zArray.append(a[2])

    tuplesArray2 = plotIsoparametricLine(-1,-1,-1)
    xArray2 = []
    yArray2 = []
    zArray2 = []
    
    for a in tuplesArray2:
        xArray2.append(a[0])
        yArray2.append(a[1])
        zArray2.append(a[2])

    
    #Axes3D.scatter(ax, zArray, xArray, yArray, s=10, c='y')
    Axes3D.plot_wireframe(ax, zArray, xArray, yArray, rstride=1, cstride =1, color='g')
    Axes3D.plot_wireframe(ax, zArray2, xArray2, yArray2, rstride=1, cstride =1, color='g')

    #Axes3D.set_ylim(ax, [-0.5,4.5])
    #Axes3D.set_xlim(ax, [-0.5,4.5])
    Axes3D.set_zlim(ax, [-0.9, 0.9])
    plt.show(block=True)
Beispiel #51
0
plt.xlim([4, 8])
plt.title('Classified data')
#plt.legend(loc='best')

# Plot samples according to their original class
w0 = [6.5, 3]
plt.figure()
plt.plot(C1[0, :], C1[1, :], 'ro', label='Class 1')
plt.plot(C2[0, :], C2[1, :], 'go', label='Class 2')
plt.plot(C3[0, :], C3[1, :], 'bo', label='Class 3')
plt.plot([w0[0], w[0, 0] + w0[0]], [w0[1], w[0, 1] + w0[1]], '-r', label='1-2')
plt.plot([w0[0], w[1, 0] + w0[0]], [w0[1], w[1, 1] + w0[1]], '-g', label='1-3')
plt.plot([w0[0], w[2, 0] + w0[0]], [w0[1], w[2, 1] + w0[1]], '-b', label='2-3')
plt.ylim([1, 5])
plt.xlim([4, 8])
plt.title('Original classes')
plt.legend(loc='best')

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# plt.plot(C1_12.T, C1_13.T)
Axes3D.scatter(ax, C1_p[0, :], C1_p[1, :], zs=C1_p[2, :], c='r', label='Class 1')
Axes3D.scatter(ax, C2_p[0, :], C2_p[1, :], zs=C2_p[2, :], c='g', label='Class 2')
Axes3D.scatter(ax, C3_p[0, :], C3_p[1, :], zs=C3_p[2, :], c='b', label='Class 3')
plt.legend(loc='best')
ax.set_xlabel('Separating 1-2')
ax.set_ylabel('Separating 1-3')
ax.set_zlabel('Separating 2-3')

plt.show()
Beispiel #52
0
def plot():
    ax = implicit.plot_implicit(f3,bbox=(-5,5,-5,5,-5,5))
    Axes3D.scatter(ax,rays[:,0],rays[:,1],rays[:,2])
    plt.show()
Beispiel #53
0
nxarray = []
nyarray = []
nzarray = []
for nonFeasibleTReference in nonFeasibleTReferences:
    nxarray.append(nonFeasibleTReference[0])
    nyarray.append(nonFeasibleTReference[1])
    nzarray.append(nonFeasibleTReference[2])

xarray = []
yarray = []
zarray = []
for FeasibleTReference in FeasibleTReferences:
    xarray.append(FeasibleTReference[0])
    yarray.append(FeasibleTReference[1])
    zarray.append(FeasibleTReference[2])

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

Axes3D.scatter(ax, nxarray, nyarray, nzarray, c="r")
Axes3D.scatter(ax, xarray, yarray, zarray)
ax.axis("off")

savez_compressed("FeasibleTPoints0_HD.npz", array=FeasibleTPoints)
savez_compressed("FeasibleTAlphas0_HD.npz", array=FeasibleTAlphas)
savez_compressed("FeasibleTOmegas0_HD.npz", array=FeasibleTOmegas)
savez_compressed("FeasibleTThetas0_HD.npz", array=FeasibleTThetas)

plt.show()
Beispiel #54
0
# with open(filename, 'wb') as handle:
#   cPickle.dump([difficulties, generosities, ave_switches], handle)



#read
with open(filename, 'rb') as handle:
   data = cPickle.load(handle)


difficulties=data[0]
generosities=data[1]
ave_switches=data[2]
fig = plt.figure()
ax = Axes3D(fig)
Axes3D.scatter(ax, difficulties, generosities, ave_switches, cmap=cm.jet)
Axes3D.plot_trisurf(ax, difficulties, generosities, ave_switches, cmap=cm.jet)
plt.show()



print ave_switches


 # griddata and contour.     
xi = np.linspace(min(difficulties),max(difficulties),15)
yi = np.linspace(min(generosities),max(generosities),15)
xi = np.linspace(0,1,15)
yi = np.linspace(0,1,15)

print len(difficulties), len(generosities), len(ave_switches)
Beispiel #55
0
    current_point = seed
    for idx in xrange(0, N):
        ndx = rnd.randint(0, nVerts)
        vert = polygon[:, ndx]
        next_point = current_point + f*(vert-current_point)
        fractal[:,idx] = next_point
        current_point = next_point
    return fractal
    
    
seed_x = np.array([])

if __name__ == '__main__':
    n = 4
    N = int(1e4)
    f = 1.0/2.0
    seed = [0.5,0.5,0.5]
    #nGon = get_regular_polygon(n)
    nGon =  np.array([[0,1,1/2,1/2],
            [0,0,np.sqrt(3)/2, np.sqrt(3)/4],
            [0,0,0, np.sqrt(3)/2]]) 
    fractal = chaos_game(nGon, seed, N, f)
    
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Axes3D.scatter(ax, fractal[0,:], fractal[1,:], fractal[2,:])
    plt.show()
    #plt.plot(fractal[0,:], fractal[1,:], 'b.')
    #plt.grid()
    #plt.show()
    def run(self):

        nat = 4  # number of atoms first and last mimic walls.
        x0 = zeros(nat)
        y0 = zeros(nat)
        xm = zeros(nat)
        t = 0.0

        #--------- potential setting
        epsilon = 1
        eps = zeros(nat-1)
        eps[0] = epsilon*self.frac_stif
        eps[1] = epsilon
        eps[2] = epsilon*self.frac_stif
        sig = 1
        d_eq = sig*2.0**(1./6.0)     # vdW eq. distance
        mass = 2.0  # mass of each atom
        red_mass = mass/2.0  # reduced mass (mass of the optical oscillator)
        aco_mass = mass*2.0  # mass of the acoustic oscillator

        period = (2.0*pi*sig/(6.0*2.**(1./3)))*(red_mass/epsilon)**0.5                 #--------- period of a free LJ dimer

        if self.i_potential == "stiffer_lj":
            per_opt = (2.0*pi*sig/(6.0*2.**(1./3)))*(red_mass/((0.5*eps[0])+eps[1]))**0.5    #--------- period of the optical mode (stiffer single backbond)
            per_aco = (2.0*pi*sig/(6.0*2.**(1./3)))*(aco_mass/(2.0*eps[0]))**0.5           #--------- period of the acoustic mode

        elif self.i_potential == "triple_back":
            per_opt = (2.0*pi*sig/(6.0*2.**(1./3)))*(red_mass/(0.5*eps[0]/3.+eps[1]))**0.5    #--------- period of the optical mode
            per_aco = (2.0*pi*sig/(6.0*2.**(1./3)))*(aco_mass/(2.*eps[0]/3.))**0.5

        speed_of_sound = 6.0*(2.*epsilon/mass)**0.5

        w_lj = 2*pi/period        # --------- angular frequencies
        w_opt = 2*pi/per_opt
        w_aco = 2*pi/per_aco

        # --------- opening velocity & time step

        vel = self.frac_vel * speed_of_sound    # velocity  as fraction of the speed of sound of a LJ 1D lattice
        dt = self.frac_tim * period            # time step as fraction of the period of a LJ dimer

        works = []
        en_mask = 0
        pos1 = []
        pos2 = []
        pos0 = []
        pos3 = []
        times = []
        eq = []
        disp = []
        maxes = []

        for i_sample in range(0, self.nconfig):

            if i_sample == 0:
                start_time = time.time()

            # ---------equilibrium atoms positions
            if self.i_potential == "stiffer_lj":
                for i in range(nat):
                    x0[i] = (-float(nat-1)/2.0 + float(i))*d_eq
            elif self.i_potential == "triple_back":
                    x0[1] = -0.5*d_eq
                    x0[2] = 0.5*d_eq
                    x0[0] = x0[1]-d_eq/3.
                    x0[3] = x0[2]+d_eq/3.

            # PHONON SETUPS

            en_opt = self.frac_opt*epsilon   # ---------energy of the opt phonon in units of epsilon
            en_aco = self.frac_aco*epsilon   # ---------energy of the opt phonon in units of epsilon

            # -------------

            dis_opt = (2.0*en_opt/(red_mass * w_opt**2))**0.5  # displacement for the opt phonon to have that energy
            dis_aco = (2.0*en_aco/(2.*mass * w_aco**2))**0.5   # displacement for the opt phonon to have that energy

            phs_opt = 2.0*pi*rand()    # Present positions in relative phon coord (with random phases)
            xopt = dis_opt*cos(w_opt*t + phs_opt)
            xoptm = dis_opt*cos(w_opt*(t-dt) + phs_opt)

            phs_aco = 2.0*pi*rand()   # past positions in relative phon coord (with random phases)
            xaco = dis_aco*cos(w_aco*t + phs_aco)
            xacom = dis_aco*cos(w_aco*(t-dt) + phs_aco)

            xdtot=zeros(2)  # total current displ vector in relative phon coord
            xdtot[0]=+xopt/2.0 + xaco
            xdtot[1]=-xopt/2.0 + xaco

            xdmtot=zeros(2) # total past displ vector in relative phon coords
            xdmtot[0]=+xoptm/2.0 + xacom
            xdmtot[1]=-xoptm/2.0 + xacom

            # setting up atomic positions in absolute coords

            xm[:] = x0[:]

            x0[1] = x0[1]+xdtot[0]   # present
            x0[2] = x0[2]+xdtot[1]
            xm[1] = xm[1]+xdmtot[0]   # past time step
            xm[2] = xm[2]+xdmtot[1]

            delxd = zeros(2)

            delxd[0] = xm[1]-x0[1]
            delxd[1] = xm[2]-x0[2]

            # correction section for anharmonicity essentially this will be microcanonic dynamics with kin + pot fixed at the desired target
            # while epot and ekin won't necessarily be equal, so that half the target does not immediately give temperature (just a very good estimate)
            #
            # estimated potential: -(eps[0]+eps[1]+eps[2]) + phonon energy

            if self.i_potential == "stiffer_lj":
                e_bottom = -(eps[0]+eps[1]+eps[2])

            elif self.i_potential == "triple_back":
                e_bottom = -(3.0*eps[0]+eps[1]+3.*eps[2])

            e_est = 0.5*red_mass*w_opt**2*xopt**2 + 0.5*aco_mass*w_aco**2*xaco**2
            epot, fc = self.en_and_for(x0, nat, sig, eps)

            #print("estimated and real epots: ",e_est,epot + (eps[0]+eps[1]+eps[2]))

            for i in range(1, 7):  # iterative trick.

                rat_corr = e_est/(epot - e_bottom)
                x0[1] = x0[1]-xdtot[0]  # present
                x0[2] = x0[2]-xdtot[1]

                xdtot[:] = xdtot[:]*rat_corr**0.5

                x0[1] = x0[1]+xdtot[0]
                x0[2] = x0[2]+xdtot[1]

                epot, fc = self.en_and_for(x0, nat, sig, eps)
                #print("estimated and real epots: ",e_est,epot + (eps[0]+eps[1]+eps[2]))

            xm[1] = x0[1] + delxd[0]
            xm[2] = x0[2] + delxd[1]

            #nstep = 10000
            nstep = int(self.n_sigmas*sig/(vel*dt))
            work = 0.0

            veldrift = zeros(4)
            veldrift[0] = -vel/2.
            veldrift[1] = -vel/2.
            veldrift[2] = vel/2.
            veldrift[3] = vel/2.

            clf()

            ekin_total = 0
            epot_total = 0

            for i in range(1, nstep):

                epot, fc = self.en_and_for(x0, nat, sig, eps)
                # current_time = dt*float(i)
                # tau = 0.2*period
                # vell = self.velocity(current_time, tau, vel)
                xp, dwork = self.verlet(x0, xm, dt, fc, mass, nat, vel)

                work += dwork
                velo = (xp - xm)/(2.0*dt)
                ekin = 0.5*mass*(velo[1]**2+velo[2]**2)

                etot = epot + ekin
                #   ekinotto = ekinotto + epot + 0.25*mass*vel**2 + eps[0]+eps[2] -en_opt - en_aco
                #
                #  A DEFINITION OF WORK DONE BY THE TWO FORCES:

                if (abs(x0[1]-x0[0]) < 3.0*sig):    # left atom drifting left with left wall
                    veldrift[1]=-vel/2.
                    if(abs(x0[2]-x0[1]) < 3.0*sig): # right atom drifting left with left atom
                        veldrift[2]= -vel/2.

                if (abs(x0[3]-x0[2]) < 3.0*sig):    # right atom drifting right with right wall
                    veldrift[2]= vel/2.
                    if(abs(x0[2]-x0[1]) < 3.0*sig):   # left atom drifting right with right atom
                        veldrift[1]= vel/2.

                if( (abs(x0[1]-x0[0]) > 3.0*sig) or (abs(x0[3]-x0[2]) > 3.0*sig)): # non standard event
                    en_mask = 1    # flagged for later use

                ekinotto = 0.5*mass*((velo[1]-veldrift[1])**2 + (velo[2]-veldrift[2])**2)   # kinetic energy of the two oscillating fragments
                                                                                            # in the translating ref. frames
                ekinotto += (epot - e_bottom)                  # total oscillator energy in the translating ref. frame
                ekinotto -= (en_opt + en_aco)                  # ..minus the initial oscillator energy before the pull
                ekinotto -= eps[1]                             # ..minus the energy it took to break the central bond
                                                               #   (this correction can be excluded as as an offset)
                #   ekinotto =  ekinotto + 2.*(0.5*mass*(vel/2.)**2)  # ..plus translation kin. energy of the two atoms
                                                                      #  (this last correction is temperature independent and
                                                                      #  could be excluded from the definition)

                # so this is the energy to break the bond at the net of the static bond energy and the translational kinetic energy
                # it can be negative (in which case, initial oscillations helped the bond breaking)
                # or positive (in which case, initial oscillations -temperature- made the bond breaking more difficult)
                # or zero (typical of zero initial oscillation and fracture at very low velocity)

                #if i%1000==1: print(("%6d"+"%12.8f"*6) % (i,ekin,epot,etot, work, etot + work, ekinotto))

                if i % 1 == 0:
                    pos1.append(x0[1])
                    pos2.append(x0[2])

                    pos0.append(x0[0])
                    pos3.append(x0[3])
                    times.append(t)

                    i = len(pos1)

                    disp.append((pos1[i - 1]) - (pos2[i - 1]))
                    #print(pos1[i - 1], eq[i - 1], disp[i - 1])

                    if i > 3:
                        if pos1[i - 3] < pos1[i - 2] > pos1[i - 1]:
                            maxes.append(t)

                xm[:] = x0[:]
                x0[:] = xp[:]
                t += dt

            if ((x0[2]-x0[1]) > sig*(float(self.n_sigmas)-3.0)) :
                print('LOST COHERENCE at frac_vel,frac_opt,frac_aco', self.frac_vel, self.frac_opt, self.frac_aco)

            if(  ((x0[1] < 0) and (x0[2] < 0)) or ((x0[1] > 0) and (x0[2] > 0)) ):    # a stiff, not a weak bond was broken
                print('STIFF BOND BROKEN, POSITIONS: ',x0)


            elif(  ((x0[1] < 0) and (x0[2] > 0)) or ((x0[1] > 0) and (x0[2] < 0)) ):  # TWO stiff bonds were broken
                if(  ((x0[1]-x0[0]) > 2*sig) and ((x0[3]-x0[2]) > 2*sig)):                # (making sure)
                    print('TWO STIFF BONDS BROKEN, POSITIONS: ',x0)

            else:
                print('DISASTER, POSITIONS: ',x0)
                sys.exit(0)

            periods = []
            prev = 0
            for t in maxes:
                periods.append(t - prev)
                prev = t
            print(statistics.mean(periods), statistics.pstdev(periods))

            # plt.plot(times, pos1, ls="none", marker="+", color=(0, 0.5, 0.5))
            # plt.plot(times, disp, ls="none", marker="+", color=(0.5, 0, 0.5))

            # fit = []
            #
            # def sin_fit(tl, amp, freq, phase, offset):
            #     q = []
            #     for t in tl:
            #         q.append(amp*math.sin((freq*t) + phase) - offset)
            #     return q
            #
            # #p0 = [0.05, 10, -0.5, 1.125]
            # p0 = [1, (2*pi/statistics.mean(periods)), 1, 1]
            #
            #
            # parms, cov = curve_fit(sin_fit, times, disp, p0)
            #
            # print(parms)
            # for t in times:
            #     fit.append(parms[0]*math.sin((parms[1]*t) + parms[2]) - parms[3])
            #
            # plt.plot(times, fit, ls="none", marker="+", color=(0.5, 0, 0.5))
            # plt.show()

            param_string = "Optical Mode: f_opt = 0.005, Stiffness = 1.0"
            fig = plt.figure()
            ax = fig.add_axes([0, 0, 1, 1], projection='3d')
            plt.xlabel("x")
            plt.ylabel("y")
            #ax.axis('off')
            fig.suptitle(param_string, fontsize=12)
            x_init = [-0.5*d_eq, 0.5*d_eq]
            y0 = [0, 0]
            z0 = [0, 0]
            d_lat = d_eq*(2/3)*(2**0.5)
            x_bb_rel = [-d_lat/3, -d_lat/3, -d_lat/3, d_lat/3, d_lat/3, d_lat/3]
            y_bb_rel = [d_lat, -d_lat, 0, -d_lat, d_lat, 0]
            z_bb_rel = [-d_lat, -d_lat, d_lat, d_lat, d_lat, -d_lat]

            # Set up figure & 3D axis for animation

            ax.set_xlim((-5, 5))
            ax.set_ylim((-3, 3))
            ax.set_zlim((-3, 3))

            atom_colours = [(0, 0.5, 0.5), (0, 0.5, 0.5),
                            (0.5, 0.5, 0), (0.5, 0.5, 0), (0.5, 0.5, 0),
                            (0.5, 0.5, 0), (0.5, 0.5, 0), (0.5, 0.5, 0)]
            atoms = Axes3D.scatter(ax, [], [], [], c=atom_colours, s=200, depthshade=False)

            bonds = [ax.plot([], [], ls="--", lw=2, color=(0, 1, 0.5), zorder=-1)]
            back_bonds = [ax.plot([], [], ls="-", lw=2, color=(1, 0, 0.5), zorder=-1)]
            for q in range(5):
                back_bonds.append(ax.plot([], [], ls="-", lw=2, color=(1, 0, 0.5), zorder=-1))

            ax.view_init(25, 100)
            self.broken = False
            text = True
            speed_factor = 5

            if text:
                time_text = ax.text(4.9, -3, 3, "")
                theoretical_period = ax.text(4.9, -3, 2.6, "Theoretical Period = " + str(round(per_opt, 3)))
                period_text = ax.text(4.9, -3, 2.2, "")

            def init():
                elements = []

                for bond in bonds:
                    bond = bond[0]
                    bond.set_data([], [])
                    bond.set_3d_properties([])
                    elements.append(bond)

                for bond in back_bonds:
                    bond = bond[0]
                    bond.set_data([], [])
                    bond.set_3d_properties([])
                    elements.append(bond)

                atoms._offsets3d = ([], [], [])
                elements.append(atoms)

                if text:
                    time_text.set_text('')
                    period_text.set_text('')
                    elements.append(time_text)
                    elements.append(period_text)

                return elements

            def animate(i):

                if i == 0:
                    self.broken = False
                i *= speed_factor
                elements = []

                bondx = []
                bondy = []
                bondz = []
                for q in range(len(bonds)):
                    bondx.append([pos1[i], pos2[i]])
                    bondy.append([y0[q], y0[q]])
                    bondz.append([z0[q], z0[q]])
                for bond in bonds:
                    q = bonds.index(bond)
                    bond = bond[0]
                    if abs(bondx[0][0] - bondx[0][1]) < 3 and not self.broken:
                        bond.set_data(bondx[q], bondy[q])
                        bond.set_3d_properties(bondz[q])
                        elements.append(bond)
                    else:
                        bond.set_data(0, 0)
                        bond.set_3d_properties(0)
                        self.broken = True

                x_bb = []
                y_bb = []
                z_bb = []
                for q in range(len(back_bonds)):
                    if q < 3:
                        x_bb.append(pos0[i])
                        y_bb.append(y_bb_rel[q] + y0[0])
                        z_bb.append(z_bb_rel[q] + z0[0])
                    else:
                        x_bb.append(pos3[i])
                        y_bb.append(y_bb_rel[q] + y0[1])
                        z_bb.append(z_bb_rel[q] + z0[1])
                bondx = []
                bondy = []
                bondz = []
                for q in range(len(back_bonds)):
                    if q < 3:
                        bondx.append([x_bb[q], pos1[i]])
                        bondy.append([y_bb[q], y0[0]])
                        bondz.append([z_bb[q], z0[0]])
                    else:
                        bondx.append([x_bb[q], pos2[i]])
                        bondy.append([y_bb[q], y0[1]])
                        bondz.append([z_bb[q], z0[1]])
                for bond in back_bonds:
                    q = back_bonds.index(bond)
                    bond = bond[0]
                    bond.set_data(bondx[q], bondy[q])
                    bond.set_3d_properties(bondz[q])
                    elements.append(bond)

                atomx = []
                atomy = []
                atomz = []
                for q in range(8):
                    if q == 0:
                        atomx.append(pos1[i])
                        atomy.append(y0[0])
                        atomz.append(z0[0])
                    elif q == 1:
                        atomx.append(pos2[i])
                        atomy.append(y0[1])
                        atomz.append(z0[1])
                    elif 1 < q > 4:
                        atomx.append(pos3[i])
                        atomy.append(y_bb_rel[q - 2] + y0[1])
                        atomz.append(z_bb_rel[q - 2] + z0[1])
                    else:
                        atomx.append(pos0[i])
                        atomy.append(y_bb_rel[q - 2] + y0[0])
                        atomz.append(z_bb_rel[q - 2] + z0[0])

                atoms._offsets3d = (atomx, atomy, atomz)
                elements.append(atoms)

                if text:
                    time_text.set_text("Time = " + format(times[i], ".3f"))
                    c_time = times[i]
                    c_max = 0
                    for max_i in range(len(maxes)):
                        q = len(maxes) - max_i - 1
                        if c_time <= maxes[q]:
                            c_max = max_i
                    period_text.set_text("Period = " + format(periods[c_max], ".3f"))
                    elements.append(time_text)
                    elements.append(period_text)

                #ax.view_init(25, 125 - 60*(i/len(pos1)))
                fig.canvas.draw()
                return elements

            n_frames = int(len(pos1)/speed_factor)
            anim = animation.FuncAnimation(fig, animate, init_func=init,
                                           frames=n_frames, interval=1, blit=True)
            print(n_frames, n_frames/60)
            #anim.save('optical_3D_15.mp4', fps=60, extra_args=['-vcodec', 'libx264'])
            plt.show()
colors = [out1, out1_HSV, out1_HLS, out1_Lab, out1_Luv, out1_YCrCb]

out1_colors = {}
i=0
for color in colors:
    X = color.reshape((-1,3))
    df = pd.DataFrame(X)
    out1_colors['%s_uniq' % colors_name[i]] = df.drop_duplicates().values #get unique color value
    i=i+1
  
#3-D plot

fig = plt.figure()
fig.suptitle('RGB', fontsize=20)
ax = fig.add_subplot(111, projection='3d')
Axes3D.scatter(ax, xs=out1_colors["out1_uniq"][:,0], ys=out1_colors["out1_uniq"][:,1], zs=out1_colors["out1_uniq"][:,2], zdir='z', s=20, c='cyan', depthshade=True)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.view_init(30,220)
plt.show()

fig = plt.figure()
fig.suptitle('HSV', fontsize=20)
ax = fig.add_subplot(111, projection='3d')
Axes3D.scatter(ax, xs=out1_colors["out1_HSV_uniq"][:,0], ys=out1_colors["out1_HSV_uniq"][:,1], zs=out1_colors["out1_HSV_uniq"][:,2], zdir='z', s=20, c='yellow', depthshade=True)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.view_init(30,220)
plt.show()
            Max.append(amax(t[j]))
            xarray.append(alltriopoints[i][0][0][0])
            yarray.append(alltriopoints[i][0][0][1])
            zarray.append(alltriopoints[i][0][0][2])
            io = 0
            break
    if io:
        nMax.append(amin(t))
        xnarray.append(alltriopoints[i][0][0][0])
        ynarray.append(alltriopoints[i][0][0][1])
        znarray.append(alltriopoints[i][0][0][2])

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

Axes3D.scatter(ax, xnarray, ynarray, znarray, c="r")
Axes3D.scatter(ax, xarray, yarray, zarray)
ax.axis("off")
plt.show()


def scatter3d(x, y, z, cs, colorsMap="jet"):
    cm = plt.get_cmap(colorsMap)
    cNorm = clr.Normalize(vmin=min(cs), vmax=max(cs))
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.scatter(x, y, z, c=scalarMap.to_rgba(cs))
    scalarMap.set_array(cs)
    fig.colorbar(scalarMap)
    ax.axis("off")
Beispiel #59
0
def prepdftcharged(charges,chargemag,totalcharge,d=0):
    """used to create input files for nwchem for Cd29S29 clusters with point charges"""
    z=array([[3.73479929,4.70148859,1.08453093],
    [-0.45777444,5.46389693,1.42922813],
    [3.99256744,1.42776590,0.17101104],
    [-3.23253881,2.73557278,0.17389669],
    [0.00277074,-0.00738694,-0.25202305],
    [0.00013075,-0.01651818,6.38550475],
    [4.95224596, -2.34187282,1.40722903],
    [-5.94120956,0.87524543,1.07437676],
    [-4.49880283,-3.12964705,1.41125120],
    [-0.75991343,-4.18114040,0.15674939],
    [2.20650584,-5.59236598,1.05533723],
    [0.96252338,4.36198028,-1.42717920],
    [4.81764990,3.19485539,-2.77622069],
    [-1.73138701,4.16471485,-3.46626689],
    [-2.55306625,2.91594904,4.51767596],
    [1.50206160,1.89218763,-4.09811156],
    [0.98329346,2.34564526,3.5974529],
    [4.46454220,-0.56369361,-3.47475802],
    [3.80849139,0.73094006,4.51682402],
    [-5.17525966,2.60395011,-2.77772471],
    [-2.37975873,0.36837952,-4.07698444],
    [-2.53045715,-0.33540920,3.59449188],
    [0.88144546,-2.23348348,-4.09931249],
    [1.54175224,-2.03600240,3.58132334],
    [3.31038688,-3.02228474,-1.45695989],
    [-4.27528734,-1.35796536,-1.44852313],
    [-2.72513737,-3.56991001,-3.48209886],
    [-1.25794100,-3.68787964,4.50492503],
    [0.35261163,-5.75579556,-2.79552608],
    [0.74123700,4.43697518,-4.02956973],
    [-0.64622546,4.44077927,3.74595547],
    [4.18920378,1.70873805,-4.66166552],
    [3.47773976,2.51701231,2.54165082],
    [-3.55947851,2.79106662,-4.65228042],
    [-3.92545305,1.73860005,2.54076867],
    [-0.00271263,0.01013464,-5.02518153],
    [-0.00332939,-0.00785361,2.48730355],
    [3.46776368,-2.83946171,-4.05736012],
    [4.17115409,-1.67896151,3.73089394],
    [-4.20196677,-1.57060486,-4.04933515],
    [-3.53060015,-2.79614465,3.73504438],
    [-0.62463325,-4.46372023,-4.67635054],
    [0.44748177,-4.28341329,2.52481152],
    [1.79334057,6.15314947,0.33208226],
    [5.55303831,3.65754425,-0.46937522],
    [-1.77455171,4.68869481,-0.74204629],
    [1.74568849,1.79694051,-1.26045912],
    [1.94632660,1.65173243,6.00004182],
    [4.95599592,-0.80678637,-0.75922862],
    [-5.94441654,2.98322195,-0.46759778],
    [-2.43853084,0.59877699,-1.25432294],
    [-2.41524712,0.83987083,5.99734552],
    [0.69721678,-2.42073954,-1.26854049],
    [0.46924459,-2.53096433,5.98775239],
    [4.43666586,-4.63906404,0.30520008],
    [-6.23050849,-1.53090073,0.31876024],
    [-3.17891818,-3.89146035,-0.76368896],
    [0.38866467,-6.64405085,-0.49626228]])
    print z.shape
 #   z = numpy.loadtxt('/home/chris/Desktop/q16_cd29/Cd29.xyz',skiprows = 2, usecols = (1,2,3), delimiter = ' ',unpack=False)
    chargemag = float(totalcharge)/charges
   
    print "number of charges",charges
    print 'total charge', totalcharge
    print 'magnitude of each charge', chargemag
    (x1,y1,z1) = tuple(numpy.mean(z,axis=0))
    center =  numpy.mean(z,axis=0)
    minradius = max(sqrt(sum((z[:]-center)**2,axis = 1)))
    radius = minradius + d
    chargecoordlist = pointsonsphere(charges,radius) + center

#    with open('/home/chris/Desktop/q16_cd29/Cd29.xyz','rb') as r:
#        xyzcoords = r.read()[3:]
#        r.close()
        
    totalcharge = str(totalcharge)
    print totalcharge
    newfolder = 'Q'+totalcharge+'d'+str(charges)+'r'+str(d)+'_Cd29S29'
    try:
        os.mkdir('/home/chris/Desktop/charges/'+newfolder)
    except:
        pass
    outputfilename = str('/home/chris/Desktop/charges/'+newfolder+'/'+newfolder+'.nw')
    newfolder = 'Q'+totalcharge+'d'+str(charges)+'r'+str(d)+'_Cd29S29'
    print "newfolder name", newfolder
    print "saving as", outputfilename
    with open(outputfilename,'wb') as f:
        f.write('''start "'''+newfolder+'''"
echo

memory total 4096 mb

charge 0
geometry
Cd 3.73479929 4.70148859 1.08453093
Cd -0.45777444 5.46389693 1.42922813
Cd 3.99256744 1.42776590 0.17101104
Cd -3.23253881 2.73557278 0.17389669
Cd 0.00277074 -0.00738694 -0.25202305
Cd 0.00013075 -0.01651818 6.38550475
Cd 4.95224596 -2.34187282 1.40722903
Cd -5.94120956 0.87524543 1.07437676
Cd -4.49880283 -3.12964705 1.41125120
Cd -0.75991343 -4.18114040 0.15674939
Cd 2.20650584 -5.59236598 1.05533723
Cd 0.96252338 4.36198028 -1.42717920
Cd 4.81764990 3.19485539 -2.77622069
Cd -1.73138701 4.16471485 -3.46626689
Cd -2.55306625 2.91594904 4.51767596
Cd 1.50206160 1.89218763 -4.09811156
Cd 0.98329346 2.34564526 3.59745292
Cd 4.46454220 -0.56369361 -3.47475802
Cd 3.80849139 0.73094006 4.51682402
Cd -5.17525966 2.60395011 -2.77772471
Cd -2.37975873 0.36837952 -4.07698444
Cd -2.53045715 -0.33540920 3.59449188
Cd 0.88144546 -2.23348348 -4.09931249
Cd 1.54175224 -2.03600240 3.58132334
Cd 3.31038688 -3.02228474 -1.45695989
Cd -4.27528734 -1.35796536 -1.44852313
Cd -2.72513737 -3.56991001 -3.48209886
Cd -1.25794100 -3.68787964 4.50492503
Cd 0.35261163 -5.75579556 -2.79552608
S 0.74123700 4.43697518 -4.02956973
S -0.64622546 4.44077927 3.74595547
S 4.18920378 1.70873805 -4.66166552
S 3.47773976 2.51701231 2.54165082
S -3.55947851 2.79106662 -4.65228042
S -3.92545305 1.73860005 2.54076867
S -0.00271263 0.01013464 -5.02518153
S -0.00332939 -0.00785361 2.48730355
S 3.46776368 -2.83946171 -4.05736012
S 4.17115409 -1.67896151 3.73089394
S -4.20196677 -1.57060486 -4.04933515
S -3.53060015 -2.79614465 3.73504438
S -0.62463325 -4.46372023 -4.67635054
S 0.44748177 -4.28341329 2.52481152
S 1.79334057 6.15314947 0.33208226
S 5.55303831 3.65754425 -0.46937522
S -1.77455171 4.68869481 -0.74204629
S 1.74568849 1.79694051 -1.26045912
S 1.94632660 1.65173243 6.00004182
S 4.95599592 -0.80678637 -0.75922862
S -5.94441654 2.98322195 -0.46759778
S -2.43853084 0.59877699 -1.25432294
S -2.41524712 0.83987083 5.99734552
S 0.69721678 -2.42073954 -1.26854049
S 0.46924459 -2.53096433 5.98775239
S 4.43666586 -4.63906404 0.30520008
S -6.23050849 -1.53090073 0.31876024
S -3.17891818 -3.89146035 -0.76368896
S 0.38866467 -6.64405085 -0.49626228
end 

bq\n''')
            
        for i in chargecoordlist:
                
               
                f.write(str(i[0])+' '+str(i[1])+' '+str(i[2])+' ' +str(chargemag) + '\n')
                
        f.write('''
end

basis
Cd library "LANL2DZ ECP"
S library "LANL2DZ ECP"

end

ecp
   Cd library "LANL2DZ ECP"
   S library "LANL2DZ ECP"

end

dft
  xc b3lyp
  direct
  mult 1
  iterations 200
  convergence	energy 1E-5 	density 5E-6	gradient 5e-5 ncysh 200
end

dplot
  TITLE LUMO
  GAUSSIAN
  vectors ./'''+newfolder+'''.movecs
   LimitXYZ
 -10 10 50 
 -10 10 50
 -10  10  50
  orbitals view;1;262
  output lumo.cube
end
task tddft gradient
task dplot

dplot
  TITLE H**O
  GAUSSIAN
  vectors ./'''+newfolder+'''.movecs
   LimitXYZ
 -10 10 50 
 -10 10 50
 -10  10  50
  orbitals view;1;261
  output h**o.cube
end
task dplot''')
        f.close()
    if False: 
        fig=figure()
        ax = fig.add_subplot(111, projection='3d')
            
                
        Axes3D.scatter(ax,z[:,0],z[:,1],z[:,2],c='b')
        
        Axes3D.scatter(ax,chargecoordlist[:,0],chargecoordlist[:,1],chargecoordlist[:,2],c='r')
    return None
Beispiel #60
0
def CdSetddftcharged(charges,chargemag,totalcharge,d=0):  

    #### d distance of charges from surface in is in angstrom

    z = numpy.loadtxt('/home/chris/Desktop/CdSe29_finalgeometry.xyz',skiprows = 2, usecols = (1,2,3), delimiter = ' ',unpack=False)
    if z.shape[0]!=58:
        return 0
    chargemag = float(totalcharge)/charges
   
    print "number of charges",charges
    print 'total charge', totalcharge
    print 'magnitude of each charge', chargemag
    (x1,y1,z1) = tuple(numpy.mean(z,axis=0))
    center =  numpy.mean(z,axis=0)
    minradius = max(sqrt(sum((z[:]-center)**2,axis = 1)))
    radius = minradius + d
    chargecoordlist = pointsonsphere(charges,radius) + center

#    with open('/home/chris/Desktop/CdSe29_finalgeometry.xyz','rb') as r:
#        xyzcoords = r.read()[3:]
#        r.close()
        
    totalcharge = str(totalcharge)
    print totalcharge
    newfolder = 'tddftQ'+totalcharge+'d'+str(charges)+'r'+str(d)+'_Cd29Se29'
    try:
        os.mkdir('/home/chris/Desktop/charges/'+newfolder)
    except:
        pass
    outputfilename = str('/home/chris/Desktop/charges/'+newfolder+'/'+newfolder+'.nw')
    newfolder = 'tddftQ'+totalcharge+'d'+str(charges)+'r'+str(d)+'_Cd29Se29'
    print "newfolder name", newfolder
    print "saving as", outputfilename
    with open(outputfilename,'wb') as f:
        f.write('''start "'''+newfolder+'''"
echo

memory total 4096 mb

charge 0
geometry
symmetry c1\n''')
        for i in range(z.shape[0]):
            if i<29: f.write('Cd '+str(z[i,0])+' '+str(z[i,1])+' '+str(z[i,2])+'\n')
            elif i>30: f.write('Se '+str(z[i,0])+' '+str(z[i,1])+' '+str(z[i,2])+'\n')
        f.write('''end 

bq\n''')
            
        for i in chargecoordlist:
    
                f.write(str(i[0])+' '+str(i[1])+' '+str(i[2])+' ' +str(chargemag) + '\n')
                
        f.write('''
end

basis
Cd library "LANL2DZ ECP"
Se library "LANL2DZ ECP"

end

ecp
   Cd library "LANL2DZ ECP"
   Se library "LANL2DZ ECP"

end

dft
  xc b3lyp
  direct
  mult 1
  iterations 200
  convergence	energy 1E-5 	density 5E-6	gradient 5e-5 ncysh 200
end

tddft
    nroots 10
    civecs
    notriplet

end

dplot
  TITLE LUMO
  GAUSSIAN
  vectors ./'''+newfolder+'''.movecs
   LimitXYZ
 -10 10 50 
 -10 10 50
 -10  10  50
  orbitals view;1;262
  output lumo.cube
end
task tddft energy
task dplot

dplot
  TITLE H**O
  GAUSSIAN
  vectors ./'''+newfolder+'''movecs
   LimitXYZ
 -10 10 50 
 -10 10 50
 -10  10  50
  orbitals view;1;261
  output h**o.cube
end
task dplot''')
        f.close()
    if False: 
        fig=figure()
        ax = fig.add_subplot(111, projection='3d')
            
                
        Axes3D.scatter(ax,z[:,0],z[:,1],z[:,2],c='b')
        
        Axes3D.scatter(ax,chargecoordlist[:,0],chargecoordlist[:,1],chargecoordlist[:,2],c='r')
    return None