Пример #1
0
    def plot_3d(self, ax_3d: Axes3D, n_angles: int = 30, **kwargs) -> None:
        """
        Plot the sphere in 3D.

        Parameters
        ----------
        ax_3d : Axes3D
            Instance of :class:`~mpl_toolkits.mplot3d.axes3d.Axes3D`.
        kwargs : dict, optional
            Additional keywords passed to :meth:`~mpl_toolkits.mplot3d.axes3d.Axes3D.plot_surface`.

        Examples
        --------
        .. plot::
            :include-source:

            >>> import matplotlib.pyplot as plt
            >>> from mpl_toolkits.mplot3d import Axes3D

            >>> from skspatial.objects import Sphere

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

            >>> sphere = Sphere([1, 2, 3], 2)

            >>> sphere.plot_3d(ax, alpha=0.2)
            >>> sphere.point.plot_3d(ax, s=100)

        """
        X, Y, Z = self.to_mesh(n_angles)

        ax_3d.plot_surface(X, Y, Z, **kwargs)
Пример #2
0
def plot_error_deform(nx, ny, delta1, dt1, dt_an):
    filename = 'output/'+str(nx) + '_' + str(ny) +  '_deform_heat_t5_delta' + delta1 + '_dt' + dt1 + '.txt'
    data = np.fromfile(filename, dtype=np.float32)  # np.genfromtxt(filename)#
    shape = [ny, nx]
    data = np.reshape(data, (int(shape[0]), int(shape[1])))


    filename_a = 'output/'+str(nx) + '_' + str(ny) +  '_deform_heat_t5_delta' + delta1 + '_dt' + dt_an + '.txt'
    data_a = np.fromfile(filename_a, dtype=np.float32)  # np.genfromtxt(filename)#
    shape_a = shape
    data_a = np.reshape(data_a, (int(shape[0]), int(shape[1])))
    error = np.divide(data , data_a)

    fig = plt.figure()
    xc = np.linspace(0, 2, int(shape[1]))
    yc = np.linspace(0, 1, int(shape[0]))

    fig = plt.figure()
    plt.pcolormesh(xc, yc, data, cmap='coolwarm')
    plt.colorbar()
    fig = plt.figure()
    plt.pcolormesh(xc, yc, data_a, cmap='coolwarm')
    plt.colorbar()
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    X,Y = np.meshgrid(xc,yc)
    Z = error
    ax.plot_surface(X,Y,Z)

    fig = plt.figure()
    plt.contourf(error)
    plt.show()
Пример #3
0
def add_bands_surface_plot(axes3d: Axes3D,
                           kpoints: numpy.ndarray,
                           eigenvalues: numpy.ndarray,
                           axis: int,
                           layer: int,
                           resolution: int,
                           band_indices: Union[List[int], range,
                                               numpy.ndarray],
                           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]
    triang = tri.Triangulation(x, y)

    x_linspace = numpy.linspace(min(x), max(x), resolution)
    y_linspace = numpy.linspace(min(y), max(y), resolution)

    for b in band_indices:
        interpolator = tri.LinearTriInterpolator(triang, zs[:, b])
        x_meshgrid, y_meshgrid = numpy.meshgrid(x_linspace, y_linspace)
        z_mesggrid = interpolator(x_meshgrid, y_meshgrid)
        axes3d.plot_surface(x_meshgrid,
                            y_meshgrid,
                            z_mesggrid,
                            cmap=pyplot.get_cmap("terrain"),
                            vmin=numpy.min(z_mesggrid),
                            vmax=numpy.max(z_mesggrid))
Пример #4
0
def _draw_plane(ax: Axes3D,
                plane: Plane,
                point: np.array,
                length: float,
                elem_num: int = 100,
                color: str = "blue",
                alpha: float = 0.5,
                draw_diagonals: bool = False,
                draw_borders: bool = False):
    rays = _get_orthogonal_rays(point, plane.n)
    corners = [rays[i].point(length) for i in range(4)]
    if draw_diagonals:
        for i in range(4):
            _draw_ray(ax, rays[i], length, color=color, line_style="--")
    if draw_borders:
        _draw_line(ax, corners[0], corners[1], color=color, line_style="-")
        _draw_line(ax, corners[1], corners[2], color=color, line_style="-")
        _draw_line(ax, corners[2], corners[3], color=color, line_style="-")
        _draw_line(ax, corners[3], corners[0], color=color, line_style="-")
    minimum = np.minimum.reduce(corners)
    maximum = np.maximum.reduce(corners)
    x = np.linspace(minimum[0], maximum[0], elem_num)
    y = np.linspace(minimum[1], maximum[1], elem_num)
    xx, yy = np.meshgrid(x, y)
    d = -plane.position.dot(plane.n)
    zz = (-plane.n[0] * xx - plane.n[1] * yy - d) / plane.n[2]
    ax.plot_surface(xx, yy, zz, color=color, alpha=alpha)
Пример #5
0
    def Spect(
            self
    ):  #, dimension):  # Dimension is unit type as V(olt) W(att), etc
        Axes3D.plot_surface(self.signalx, self.signaly, self.signalz)
        if self.signalx.shape == self.signaly.shape == self.signalz.shape:
            pass
        elif self.signalx.shape == (len(
                self.signalx), ) or self.signaly.shape == (len(
                    self.signaly), ):
            # Check for 1D array both
            if self.signalx.shape == (len(
                    self.signalx), ) and self.signaly.shape == (len(
                        self.signaly), ):
                self.signalx, self.signaly = np.meshgrid(
                    self.signalx, self.signaly)
                nx, mx = np.shape(self.signalx)
                nz, mz = np.shape(self.signalz)
                if nx == nz and mx == mz:
                    pass
                elif nx == mz and mx == nz:
                    self.signalz = np.rot90(self.signalz, 1)
                    # find out if it has to be 1 or 3
            elif self.signalx.shape == (len(self.signalx), ):
                pass
            elif self.signaly.shape == (len(self.signaly), ):
                pass
            if self.signalx.shape == self.signaly.shape != self.signalz.shape:
                nx, mx = np.shape(self.signalx)
                nz, mz = np.shape(self.signalz)
                if nx == nz and mx == mz:
                    pass
                elif nx == mz and mx == nz:
                    self.signalz = np.rot90(self.signalz, 1)
                    # find out if it has to be 1 or 3
            elif self.signalx.shape == self.signalz.shape != self.signaly.shape:
                nx, mx = np.shape(self.signalx)
                ny, my = np.shape(self.signalz)
                if nx == ny and mx == my:
                    pass
                elif nx == my and mx == ny:
                    self.signaly = np.rot90(self.signaly, 1)
                    # find out if it has to be 1 or 3
        elif self.signaly.shape == self.signalz.shape != self.signalx.shape:
            ny, my = np.shape(self.signaly)
            nx, mx = np.shape(self.signalx)
            if ny == nx and my == mx:
                pass
            elif ny == mx and my == nx:
                self.signalz = np.rot90(self.signalz, 1)
                # find out if it has to be 1 or 3
        else:
            raise MeasError.DataError(
                "No Valid data found in at least one of the axis")

        plt.xlabel('time [s]')  # Or Sample number
        plt.ylabel('Frequency [Hz]')  # Or Freq Bins number
        plt.zlabel('voltage [mV]')  # auto add unit here
        plt.title(' ')  # set title
        plt.grid(True)
        plt.show()
Пример #6
0
    def water(self, *argv):  # Dimension is unit type as V(olt) W(att), etc
#        http://matplotlib.org/examples/mplot3d/polys3d_demo.html
        Axes3D.plot_surface(self.signalx, self.signaly, self.signalz)  # till better funcion
        plt.xlabel('time [s]')  # Or Sample number
        plt.ylabel('Frequency [Hz]')  # Or Freq Bins number
        plt.zlabel('voltage [mV]')  # auto add unit here
        plt.title(' ')  # set title
        plt.grid(True)
        plt.show()
Пример #7
0
    def draw(self, axes: Axes3D):
        R = (self.orientation * (self.orientation_origin.get_inverse())).to_rot_matrix()

        xx = R[0, 0] * self.x + R[0, 1] * self.y + R[0, 2] * self.z
        yy = R[1, 0] * self.x + R[1, 1] * self.y + R[1, 2] * self.z
        zz = R[2, 0] * self.x + R[2, 1] * self.y + R[2, 2] * self.z

        axes.plot_surface(xx, yy, zz, rstride=4, cstride=4, color='b')
        return axes,
Пример #8
0
 def water(self, *argv):  # Dimension is unit type as V(olt) W(att), etc
     #        http://matplotlib.org/examples/mplot3d/polys3d_demo.html
     Axes3D.plot_surface(self.signalx, self.signaly,
                         self.signalz)  # till better funcion
     plt.xlabel('time [s]')  # Or Sample number
     plt.ylabel('Frequency [Hz]')  # Or Freq Bins number
     plt.zlabel('voltage [mV]')  # auto add unit here
     plt.title(' ')  # set title
     plt.grid(True)
     plt.show()
Пример #9
0
    def draw(self, axes: Axes3D):
        R = (self.orientation *
             (self.orientation_origin.get_inverse())).to_rot_matrix()

        xx = R[0, 0] * self.x + R[0, 1] * self.y + R[0, 2] * self.z
        yy = R[1, 0] * self.x + R[1, 1] * self.y + R[1, 2] * self.z
        zz = R[2, 0] * self.x + R[2, 1] * self.y + R[2, 2] * self.z

        axes.plot_surface(xx, yy, zz, rstride=4, cstride=4, color='b')
        return axes,
Пример #10
0
def visualize_plane(plane_normal, ax: Axes3D, **kwargs):
    """
    Visualize a plane with 3d plot.
    """
    # Create plane for visualization
    xx, yy = np.meshgrid(np.linspace(-1, 1), np.linspace(-1, 1))
    d = -np.array([0, 0, 0]).dot(plane_normal)
    # Only for visualization purposes
    if plane_normal[2] == 0:
        plane_normal[2] = 0.00000000001
    zz = (-plane_normal[0] * xx - plane_normal[1] * yy - d) * 1.0 / plane_normal[2]
    ax.plot_surface(xx, yy, zz, alpha=0.2, **kwargs)
Пример #11
0
 def Spect(self):  #, dimension):  # Dimension is unit type as V(olt) W(att), etc
     Axes3D.plot_surface(self.signalx, self.signaly, self.signalz)
     if self.signalx.shape == self.signaly.shape == self.signalz.shape:
         pass
     elif self.signalx.shape == (len(self.signalx), ) or self.signaly.shape == (len(self.signaly), ):
     # Check for 1D array both
         if self.signalx.shape == (len(self.signalx), ) and self.signaly.shape == (len(self.signaly), ):
             self.signalx, self.signaly = np.meshgrid(self.signalx, self.signaly)
             nx, mx = np.shape(self.signalx)
             nz, mz = np.shape(self.signalz)
             if nx == nz and mx == mz:
                 pass
             elif nx == mz and mx == nz:
                 self.signalz = np.rot90(self.signalz, 1) 
                 # find out if it has to be 1 or 3
         elif self.signalx.shape == (len(self.signalx), ):
             pass
         elif self.signaly.shape == (len(self.signaly), ):
             pass
         if self.signalx.shape == self.signaly.shape != self.signalz.shape:
             nx, mx = np.shape(self.signalx)
             nz, mz = np.shape(self.signalz)
             if nx == nz and mx == mz:
                 pass
             elif nx == mz and mx == nz:
                 self.signalz = np.rot90(self.signalz, 1) 
                 # find out if it has to be 1 or 3
         elif self.signalx.shape == self.signalz.shape != self.signaly.shape:
             nx, mx = np.shape(self.signalx)
             ny, my = np.shape(self.signalz)
             if nx == ny and mx == my:
                 pass
             elif nx == my and mx == ny:
                 self.signaly = np.rot90(self.signaly, 1) 
                 # find out if it has to be 1 or 3
     elif self.signaly.shape == self.signalz.shape != self.signalx.shape:
         ny, my = np.shape(self.signaly)
         nx, mx = np.shape(self.signalx)
         if ny == nx and my == mx:
             pass
         elif ny == mx and my == nx:
             self.signalz = np.rot90(self.signalz, 1) 
             # find out if it has to be 1 or 3
     else:
         raise MeasError.DataError("No Valid data found in at least one of the axis")
     
     plt.xlabel('time [s]')  # Or Sample number
     plt.ylabel('Frequency [Hz]')  # Or Freq Bins number
     plt.zlabel('voltage [mV]')  # auto add unit here
     plt.title(' ')  # set title
     plt.grid(True)
     plt.show()
Пример #12
0
def surface_plot():
    from mpl_toolkits.mplot3d import Axes3D
    C = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]
    p = [2, 3, 4, 5, 6]
    Z = [[50.5, 50.5, 50.5, 90.4, 95.7, 96.7, 97.13, 97.13],
         [50.5, 50.5, 50.5, 92.3, 96.2, 96.7, 97.23, 97.23],
         [50.5, 50.5, 50.5, 93.12, 96.89, 97.33, 97.16, 97.16],
         [50.5, 50.5, 56.4, 93.7, 97.6, 97.4, 97.4, 97.4],
         [50.5, 50.5, 67.9, 94.3, 97.7, 97.3, 97.3, 97.3]]
    fig = plt.figure()
    ax = Axes3D(fig)
    Axes3D.plot_surface(ax, C, p, Z)
    plt.show()
Пример #13
0
    def plot_velocity(self):
        fig = plt.figure()
        ax = fig.add_subplot(111, projection="3d")
        Axes3D.plot_surface(ax, self._tt, self._yy, self._vv)
        ax.set_xlabel("Time [ns]")
        ax.set_ylabel("x [mm]")
        ax.set_zlabel("Velocity [km s-1]")

        fig = plt.figure()
        im = plt.pcolormesh(self._tt, self._yy, self._vv)
        cb = fig.colorbar(im)
        plt.xlabel("Time [ns]")
        plt.ylabel("x [mm]")
        cb.set_label("Velocity [km s-1]")
Пример #14
0
    def plot(self, axes: Axes3D, highlight_max=True):
        # Plot all unpicked relay positions
        unpicked = list(
            filter(lambda x: x not in self.relays, self.input.relays))
        rx = list(map(lambda r: r.x, unpicked))
        ry = list(map(lambda r: r.y, unpicked))
        rz = list(map(lambda r: r.height, unpicked))
        axes.scatter(rx, ry, rz, c='#a5b6d3', label='Potential positions.')

        # Highlight ground
        gx = np.arange(0, self.input.width + 10)
        gy = np.arange(0, self.input.height + 10)
        gx, gy = np.meshgrid(gx, gy)
        gz = gx * 0
        axes.plot_surface(gx, gy, gz, alpha=0.2, color='brown')

        # Plot assignments
        for rn, sns in self.relay_to_sensors.items():
            for sn in sns:
                tx, ty = self.interm_point(sn, rn)
                x = [rn.x, tx, sn.x]
                y = [rn.y, ty, sn.y]
                z = [rn.height, 0, -sn.depth]
                axes.plot(x, y, z, linewidth=0.5, c='#000000')

        # Highlight max pair
        if highlight_max:
            ms, mr = self.max_loss_pair
            tx, ty = self.interm_point(ms, mr)
            mx = [ms.x, tx, mr.x]
            my = [ms.y, ty, mr.y]
            mz = [-ms.depth, 0, mr.height]
            axes.plot(mx,
                      my,
                      mz,
                      c='tab:orange',
                      label='Max assignment (%.2f)' % self.max_loss)

        # 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')
Пример #15
0
    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()
 def plot_noise(self, Z):
     fig = plt.figure()
     X, Y = np.meshgrid(self.bits_expanded, self.bits_expanded)
     ax = fig.add_subplot(111, projection='3d')
     ax.set_zlim(0, 1.1)
     ax.set_xlim(0, 20)
     ax.set_ylim(0, 20)
     ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
     ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
     ax.view_init(35, 230)
     ax.set_xlabel('i')
     ax.set_ylabel('j')
     ax.set_zlabel('R(i,j)')
     ax.zaxis.set_rotate_label(False)
     Axes3D.plot_surface(ax, X, Y, Z, cmap=cm.coolwarm)
     fig.savefig('noise.png')
Пример #17
0
def Plot_surf(cost_list):  #画出曲面图
    ax = plt.figure().add_subplot(111, projection='3d')
    x = np.arange(min_s, max_s, 1)
    y = np.arange(min_S, max_S, 1)
    '''
    for i in range(s_range):
        for j in range(S_range):
            x.append(i)
            y.append(j)
    '''
    s, S = np.meshgrid(x, y)
    z = np.array(cost_list)
    Total_Cost = z.reshape(s.shape)
    surf = ax.plot_surface(s,
                           S,
                           Total_Cost,
                           rstride=1,
                           cstride=1,
                           cmap='coolwarm')
    plt.colorbar(surf, shrink=0.5, aspect=5)
    #ax.plot_trisurf(x,y,z)
    '''
    plt.pcolor(total_cost)
    plt.colorbar()
    plt.axis("tight")
    plt.title("Average total cost")
    plt.xlabel("bigs")
    plt.ylabel("smalls")
    '''
    plt.show()
Пример #18
0
def globe_map(hist: Union[Histogram2D, DirectionalHistogram],
              ax: Axes3D,
              *,
              show_zero: bool = True,
              **kwargs):
    """Heat map plotted on the surface of a sphere."""
    data = get_data(hist,
                    cumulative=False,
                    flatten=False,
                    density=kwargs.pop("density", False))

    cmap = _get_cmap(kwargs)
    norm, cmap_data = _get_cmap_data(data, kwargs)
    colors = cmap(cmap_data)
    lw = kwargs.pop("lw", 1)

    r = 1
    xs = r * np.outer(np.sin(hist.numpy_bins[0]), np.cos(hist.numpy_bins[1]))
    ys = r * np.outer(np.sin(hist.numpy_bins[0]), np.sin(hist.numpy_bins[1]))
    zs = r * np.outer(np.cos(hist.numpy_bins[0]), np.ones(hist.shape[1] + 1))

    for i in range(hist.shape[0]):
        for j in range(hist.shape[1]):
            if not show_zero and not data[i, j]:
                continue
            x = xs[i, j], xs[i, j + 1], xs[i + 1, j + 1], xs[i + 1, j]
            y = ys[i, j], ys[i, j + 1], ys[i + 1, j + 1], ys[i + 1, j]
            z = zs[i, j], zs[i, j + 1], zs[i + 1, j + 1], zs[i + 1, j]
            verts = [list(zip(x, y, z))]
            col = Poly3DCollection(verts)
            col.set_facecolor(colors[i, j])
            col.set_edgecolor("black")
            col.set_linewidth(lw)
            ax.add_collection3d(col)

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

    if matplotlib.__version__ < "2":
        ax.plot_surface([], [], [], color="b")
    ax.set_xlim(-1.1, 1.1)
    ax.set_ylim(-1.1, 1.1)
    ax.set_zlim(-1.1, 1.1)
    return ax
Пример #19
0
def cylinder_map(hist: Union[Histogram2D, CylinderSurfaceHistogram],
                 ax: Axes3D,
                 *,
                 show_zero: bool = True,
                 **kwargs):
    """Heat map plotted on the surface of a cylinder."""
    data = get_data(hist,
                    cumulative=False,
                    flatten=False,
                    density=kwargs.pop("density", False))

    cmap = _get_cmap(kwargs)
    norm, cmap_data = _get_cmap_data(data, kwargs)
    colors = cmap(cmap_data)

    if hasattr(hist, "radius"):
        r = kwargs.pop("radius", hist.radius)
    else:
        r = kwargs.pop("radius", 1)

    xs = r * np.outer(np.cos(hist.numpy_bins[0]), np.ones(hist.shape[1] + 1))
    ys = r * np.outer(np.sin(hist.numpy_bins[0]), np.ones(hist.shape[1] + 1))
    zs = np.outer(np.ones(hist.shape[0] + 1), hist.numpy_bins[1])

    for i in range(hist.shape[0]):
        for j in range(hist.shape[1]):
            if not show_zero and not data[i, j]:
                continue
            x = xs[i, j], xs[i, j + 1], xs[i + 1, j + 1], xs[i + 1, j]
            y = ys[i, j], ys[i, j + 1], ys[i + 1, j + 1], ys[i + 1, j]
            z = zs[i, j], zs[i, j + 1], zs[i + 1, j + 1], zs[i + 1, j]
            verts = [list(zip(x, y, z))]
            col = Poly3DCollection(verts)
            col.set_facecolor(colors[i, j])
            ax.add_collection3d(col)

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

    if matplotlib.__version__ < "2":
        ax.plot_surface([], [], [], color="b")
    ax.set_xlim(-r * 1.1, r * 1.1)
    ax.set_ylim(-r * 1.1, r * 1.1)
    ax.set_zlim(zs.min(), zs.max())
Пример #20
0
def plot_my_fun():
    def func(z, r):
        return 0.5*(z-r)/(r+z)+0.5

    data = np.zeros(shape=(3, 54))*np.nan
    i = 0
    X = np.arange(7)
    Y = np.arange(1, 10)
    X, Y = np.meshgrid(X, Y)
    Z = func(X, Y)
    # for z in range(7):
    #     for r in range(1, 10):
    #         data[:,i] = np.array([z,r,func(z,r)])

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    Axes3D.plot_surface(ax, X,Y,Z)
    plt.show()
def visualise(x,y):
    thetaval0 = np.linspace(-10,10,num=100)
    thetaval1 = np.linspace(-1,4,100)
    jval=np.zeros((100,100),dtype=int)

    for i in range(len(thetaval0)):
        for j in range(len(thetaval1)):
            th=np.array([thetaval0[i],thetaval1[j]])
            th.shape=(2,1)
            b=compute_costFunction(x,y,th)
            jval[i][j]=b

    np.transpose(jval)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Axes3D.plot_surface(ax,thetaval0, thetaval1, jval)
    plt.show()
Пример #22
0
def show_plot(approx_values, x_max, t_max, error, title=""):
    n = approx_values.shape[1] - 1
    m = approx_values.shape[0] - 1
    exact_values = count_exact_values(n, m, x_max, t_max)
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    Axes3D.plot_surface(ax,
                        *create_grid(x_max, t_max, n, m, exact_values),
                        color='royalblue')
    Axes3D.plot_surface(ax,
                        *create_grid(x_max, t_max, n, m, approx_values),
                        color='orangered')

    ax.set_xlabel('x')
    ax.set_ylabel('t')
    ax.set_title((f"{title}\n" if title != "" else "") +
                 f"n = {n}, m = {m}, Error is {error}")
    plt.show()
Пример #23
0
    def plot_3d(self,
                ax_3d: Axes3D,
                lims_x: array_like = (-1, 1),
                lims_y: array_like = (-1, 1),
                **kwargs) -> None:
        """
        Plot a 3D plane.

        Parameters
        ----------
        ax_3d : Axes3D
            Instance of :class:`~mpl_toolkits.mplot3d.axes3d.Axes3D`.
        lims_x, lims_y : (2,) tuple
            x and y limits of the plane.
            Tuple of form (min, max). The default is (-1, 1).
            The point on the plane is used as the origin.
        kwargs : dict, optional
            Additional keywords passed to :meth:`~mpl_toolkits.mplot3d.axes3d.Axes3D.plot_surface`.

        Examples
        --------
        .. plot::
            :include-source:

            >>> import matplotlib.pyplot as plt
            >>> from mpl_toolkits.mplot3d import Axes3D

            >>> from skspatial.objects import Plane

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

            >>> plane = Plane([5, 3, 1], [1, 0, 1])

            >>> plane.plot_3d(ax, alpha=0.2)
            >>> plane.point.plot_3d(ax, s=100)

        """
        X, Y, Z = self.to_mesh(lims_x, lims_y)

        ax_3d.plot_surface(X, Y, Z, **kwargs)
    def plot(self, Z, which, format_axis=True):
        fig = plt.figure()
        X, Y = np.meshgrid(self.bits_expanded, self.bits_expanded)
        ax = fig.add_subplot(111, projection='3d')
        if format_axis == True:
            ax.set_zlim(0, 2500000)
            ax.set_xlim(0, 20)
            ax.set_ylim(0, 20)
            ax.zaxis.set_major_formatter(
                FuncFormatter(lambda x, pos: '%dk' % int(x / 1000)))
        ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
        ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))

        ax.view_init(35, 230)
        ax.set_xlabel('i')
        ax.set_ylabel('j')
        ax.set_zlabel('Fitness')
        ax.zaxis.labelpad = 15
        ax.zaxis.set_rotate_label(False)
        Axes3D.plot_surface(ax, X, Y, Z, cmap=cm.coolwarm)
        fig.savefig(which)
Пример #25
0
def plot_error_ftle(nx, ny, delta1, dt1, dt_an):
        filename = 'output/'+str(nx) + '_' + str(ny) + '_ftle_heat_t5_delta' + delta1 + '_dt' + dt1 + '.txt'
        data = np.fromfile(filename, dtype=np.float32)  # np.genfromtxt(filename)#
        shape = [ny, nx]
        data = np.reshape(data, (int(shape[0]), int(shape[1])))

        filename_a ='output/'+ str(nx) + '_' + str(ny) + '_ftle_heat_t5_delta' + delta1 + '_dt' + dt_an + '.txt'
        data_a = np.fromfile(filename_a, dtype=np.float32)  # np.genfromtxt(filename)#
        shape_a = shape
        data_a = np.reshape(data_a, (int(shape[0]), int(shape[1])))
        difference = abs(data - data_a)
        error = difference / (abs(data_a) + 1 * 1e-15)
        print(np.min(abs(data_a[np.nonzero(data_a)])))
        xc = np.linspace(0, 2, int(shape[1]))
        yc = np.linspace(0, 1, int(shape[0]))
        sum_diff = np.sum(difference)
        sum_data_a = np.sum(abs(data_a))
        print(sum_diff / sum_data_a * 100)
        fig = plt.figure()
        plt.pcolormesh(xc, yc, data, cmap='GnBu', label=dt1)
        plt.title(dt1)
        plt.colorbar()
        fig = plt.figure()
        plt.pcolormesh(xc, yc, data_a, cmap='GnBu', label=dt_an)
        plt.title(dt_an)
        plt.colorbar()
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        X, Y = np.meshgrid(xc, yc)
        Z = error
        ax.plot_surface(X, Y, Z)
        #ax.set_zlim(bottom=-0, top=0.5, emit=True, auto=False)
        fig = plt.figure()
        square = 1;
        plt.show()
        plt.pcolormesh(xc[square:len(xc) - square], yc[square:len(yc) - square], error[square:len(yc) - square, square:len(xc) - square])
        plt.colorbar()
        plt.show()
Пример #26
0
    def plot_3d(self, ax_3d: Axes3D, n_along_axis: int = 100, n_angles: int = 30, **kwargs) -> None:
        """
        Plot a 3D cylinder.

        Parameters
        ----------
        ax_3d : Axes3D
            Instance of :class:`~mpl_toolkits.mplot3d.axes3d.Axes3D`.
        n_along_axis : int
            Number of intervals along the axis of the cylinder.
        n_angles : int
            Number of angles distributed around the circle.
        kwargs : dict, optional
            Additional keywords passed to :meth:`~mpl_toolkits.mplot3d.axes3d.Axes3D.plot_surface`.

        Examples
        --------
        .. plot::
            :include-source:

            >>> import matplotlib.pyplot as plt
            >>> from mpl_toolkits.mplot3d import Axes3D

            >>> from skspatial.objects import Cylinder

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

            >>> cylinder = Cylinder([5, 3, 1], [1, 0, 1], 2)

            >>> cylinder.plot_3d(ax, alpha=0.2)
            >>> cylinder.point.plot_3d(ax, s=100)

        """
        X, Y, Z = self.to_mesh(n_along_axis, n_angles)

        ax_3d.plot_surface(X, Y, Z, **kwargs)
Пример #27
0
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

a = np.arange(round(P[4, 0] - 500), round(P[4, 0] + 500))
b = np.arange(round(P[4, 1] - 500), round(P[4, 1] + 500))
teste = np.zeros([len(a), len(b)])
a, b = np.meshgrid(a, b)
v = np.zeros(4)

for k in range(1000):
    for j in range(1000):
        for i in range(4):
            v[i] = ((P[i, 0] - a[k, j])**2 + (P[i, 1] - b[k, j])**2)**0.5
        teste[k, j] = np.dot(v - dist[4, 0:4], v - dist[4, 0:4])

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

Axes3D.plot_surface(ax, a, b, teste)
Пример #28
0
def surface_map(hist,
                ax: Axes3D,
                *,
                show_zero: bool = True,
                x=(lambda x, y: x),
                y=(lambda x, y: y),
                z=(lambda x, y: 0),
                **kwargs):
    """Coloured-rectangle plot of 2D histogram, placed on an arbitrary surface.

    Each bin is mapped to a rectangle in 3D space using the x,y,z functions.

    Parameters
    ----------
    hist : Histogram2D
    show_zero : Optional[bool]
        Whether to show coloured box for bins with 0 frequency (otherwise background).
    x : function
        Function with 2 parameters used to map bins to spatial x coordinate
    y : function
        Function with 2 parameters used to map bins to spatial y coordinate
    z : function
        Function with 2 parameters used to map bins to spatial z coordinate

    Returns
    -------
    matplotlib.axes._subplots.Axes3DSubplot

    See Also
    --------
    map, cylinder_map, globe_map
    """
    data = get_data(hist,
                    cumulative=False,
                    flatten=False,
                    density=kwargs.pop("density", False))

    cmap = _get_cmap(kwargs)
    norm, cmap_data = _get_cmap_data(data, kwargs)
    colors = cmap(cmap_data)

    xs = np.ndarray((hist.shape[0] + 1, hist.shape[1] + 1), dtype=float)
    ys = np.ndarray((hist.shape[0] + 1, hist.shape[1] + 1), dtype=float)
    zs = np.ndarray((hist.shape[0] + 1, hist.shape[1] + 1), dtype=float)

    edges_x = hist.numpy_bins[0]
    edges_y = hist.numpy_bins[1]

    for i in range(hist.shape[0] + 1):
        for j in range(hist.shape[1] + 1):
            xs[i, j] = x(edges_x[i], edges_y[j])
            ys[i, j] = y(edges_x[i], edges_y[j])
            zs[i, j] = z(edges_x[i], edges_y[j])

    for i in range(hist.shape[0]):
        for j in range(hist.shape[1]):
            if not show_zero and not data[i, j]:
                continue
            x = xs[i, j], xs[i, j + 1], xs[i + 1, j + 1], xs[i + 1, j]
            y = ys[i, j], ys[i, j + 1], ys[i + 1, j + 1], ys[i + 1, j]
            z = zs[i, j], zs[i, j + 1], zs[i + 1, j + 1], zs[i + 1, j]
            verts = [list(zip(x, y, z))]
            col = Poly3DCollection(verts)
            col.set_facecolor(colors[i, j])
            ax.add_collection3d(col)

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

    if matplotlib.__version__ < "2":
        ax.plot_surface([], [], [], color="b")  # Dummy plot
    ax.set_xlim(xs.min(), xs.max())
    ax.set_ylim(ys.min(), ys.max())
    ax.set_zlim(zs.min(), zs.max())

    # ax.plot_surface(x, y, z, rstride=hist.shape[0], color="b")

    return ax
Пример #29
0
theta0_vals = np.linspace(-10, 10, 100)
theta1_vals = np.linspace(-1, 4, 100)

# initialize J_vals to a matrix of 0's
J_vals = np.zeros((len(theta0_vals),len(theta1_vals)))

# Fill out J_Vals 
# Note: There is probably a more efficient way to do this that uses
#	broadcasting instead of the nested for loops
for i in range(len(theta0_vals)):
    for j in range(len(theta1_vals)):
        t = np.array([theta0_vals[i],theta1_vals[j]])
        J_vals[i][j] = computeCost(X,y,t)


# Surface plot using J_Vals
fig = plt.figure()
ax = plt.subplot(111,projection='3d')
Axes3D.plot_surface(ax,theta0_vals,theta1_vals,J_vals,cmap=cm.coolwarm)
plt.show()

# Contour plot
# TO DO: Currently does not work as expected. Need to find a way to mimic
#	 the logspace option in matlab
fig = plt.figure()
ax = plt.subplot(111)
plt.contour(theta0_vals,theta1_vals,J_vals) 


# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Пример #30
0
    x = a
    step = (abs(a) + abs(b)) / n
    for i in range(n + 1):
        pointsX.append(x)
        pointsY.append(f(x))
        x += step

    return pointsX, pointsY


def generate3D(x, y, a, b, s):
    pointsX = []
    pointsY = []
    pointsZ = []
    s = int(s)
    step = (abs(a) + abs(b)) / s
    for i in range(s + 1):
        pointsX.append(f3d(x, y))
        pointsY.append(f3d(x, y))
        pointsZ.append(f3d(x, y))
        x += step
    return pointsX, pointsY, pointsZ


x, y, z = generate3D(1.1, math.sqrt(2), 0, 100, 100)
print(x, y)
print(z)

Axes3D.plot_surface(x, y, z)
plt.show()
Пример #31
0
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 20:56:55 2015

@author: jderoo
"""

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

#D is a vector from 0 to 3, 100 spaces in between
D = np.linspace(0,3,100)
#U is a vector from 0 to 3, 100 spaces in between
U = np.linspace(0,3,100)
#A is a blank matrix/list
A = []

#for loop that ranges i from 0 to 100 steps of 1
for i in range(0,100,1):
    #for loop that ranges j from 0 to 100 steps of 1
    for j in range(0,100,1):
#The base equation we were given in the homework
      r = ((3*D[i]*(U[j])^.7)/(1 + D[i]^.95 + U[j])^.3)
 #in cell location i,j place the calced value of r     
      A[i,j] = r
#3D plot D, U, and the now filled matrix A
Axes3D.plot_surface(D,U,A)
Пример #32
0
import math
import numpy as np
from numpy import exp
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

mask = [[1, 2, 1], [2, 4, 2], [1, 2, 1]]

transformed = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

K = M = 3
L = N = 3

for k in range(K):
    for l in range(L):
        accum = 0
        for m in range(M):
            for n in range(N):
                accum += mask[m][n] * exp(-2j * math.pi * k * m / K) * exp(
                    -2j * math.pi * l * n / L)
        complexAccum = accum / 16
        transformed[k][l] = accum / 16

mask_dft = np.fft.fft2(mask)
print(mask_dft)

Axes3D.plot_surface(transformed)
plt.show()
Пример #33
0
def saveoutput(Ec, Ne, Ie, Ne_sub, E_sub, Te_sub, converge, Vd_temp):
    transport_model = transportmodel.value
    N_sd = Nsd1.value
    N_body = Nbody1.value
    fermi_flag = fermiflag1.value
    Vd = Vdc.value
    # Rohit- N_dos, Trans and E

    ###########################################################
    #SPECIFY XI, YI, Vg_bias, and Vd_bias for plotting use only
    ###########################################################

    Nx = round((2 * Lsd + Lg_top) / dx) + 1
    XI = np.linspace(-(Lsd + Lg_top / 2) * 1e9, (Lsd + Lg_top / 2) * 1e9,
                     Nx)  # in nanometers
    Ny = round((t_top + t_bot + t_si) / dy) + 1
    YI = np.linspace(-t_top * 1e9, (t_si + t_bot) * 1e9, Ny)
    Vg_bias = np.linspace(Vg1, Vg1 + Vg_step * Ng_step, Ng_step + 1)
    Vd_bias = np.linspace(Vd_temp, Vd_temp + Vd_step * Nd_step, Nd_step + 1)

    ###########################################################
    #       POST PROCESSING
    ###########################################################
    MEc = np.reshape(Ec[Nd_step, :, Ng_step], (Ny, Nx)).transpose()
    trMEc = MEc.transpose()
    MNe = np.reshape(Ne[Nd_step, :, Ng_step], (Ny, Nx)).transpose()
    trMNe = MNe.transpose()

    #mkdir(dirname)
    #cd(dirname)

    #raw_data is always stored!!!!!
    #--------------------------------------------------
    #save output_rawdata
    #Save convergence data in a file
    #save DOS.dat N_dos -ascii
    Trans = globvars.Trans
    #save trans.dat Trans -ascii
    E = globvars.E
    #save E.dat E -ascii
    N_dos = globvars.N_dos

    fid = open("convergence.dat", "w")

    fid.write(
        '****************************************************************\n')
    fid.write('*******You ran a Nanomos simulation on the %s *********\n' %
              datetime.datetime.now())
    fid.write(
        '********************* Using Nanomos 2.0 ************************\n')
    fid.write(
        '********** The input file you used  was the following **********\n')
    fid.write(
        '****************************************************************\n')

    #cd ..
    # fid1=fopen(filename,'r')
    #     while 1
    #         tline = fgetl(fid1)
    #         if ~ischar(tline), break, end
    #         count=fprintf(fid,'%s\n',tline);
    #     end
    # status=fclose(fid1)
    # cd(dirname)

    fid.write(
        '****************************************************************\n')
    fid.write(
        '********** Convergence data for simulated bias points **********\n')
    fid.write(
        '****************************************************************\n')

    for i in np.arange(0, Ng_step + 1):
        for j in np.arange(0, Nd_step + 1):
            fid.write('\n')
            fid.write('**** Gate voltage = %f ****Drain voltage = %f' %
                      (Vg_bias[i], Vd_bias[j]))
            fid.write('\n')
            for item in converge[i, j]:
                fid.write('%e\n' % item)

    fid.write(
        '****************************************************************')
    fid.write(
        '********** The end of the convergence data file*****************')
    fid.write(
        '****************************************************************')

    fid.close()

    ############################################# IV plots ##############################################
    if plot_IV == 1:
        # ID-VD CHARACTERISTICS (A/m), SAVED TO "id_vd.dat"
        # -------------------------------------------------
        if (Ng_step >= 1 and Nd_step >= 1):
            Ng = np.size(Ie, 0)
            figure(1)
            plot(Vd_bias, Ie[0, :], 'o-')
            grid(True)
            hold(True)
            for i in np.arange(1, Ng):
                plot(Vd_bias, Ie[i, :], 'o-')

            xlabel('$V_{DS}$ [V]')
            ylabel('$I_{DS}$ $[\mu A/\mu m]$')
            title('$I_{DS}$ vs. $V_{DS}$')
            savefig('ID_VD.png')

            temmm = Vd_bias
            Ie2 = Ie.transpose()
            fid = open('ID_VD.dat', 'w')
            ind = 0
            for item1 in temmm:
                fid.write("%e " % item1)
                for item2 in Ie2[ind, :]:
                    fid.write("%e " % item2)
                fid.write('\n')
                ind += 1
            fid.close()

    # ID-VG CHARACTERISTICS (A/m), SAVED TO "id_vg.dat"
    # -------------------------------------------------
    if (Ng_step >= 1 and Nd_step == 0):
        figure(1)
        semilogy(Vg_bias, Ie[:, 0], 'o-')
        grid(True)
        xlabel('$V_{GS}$ [V]')
        ylabel('$I_{DS} [\mu A/\mu m]$')
        title('$I_{DS}$ vs. $V_{GS}$')
        savefig('ID_VG.png')

        #temmm=[Vg_bias, Ie[:,0]]
        #np.savetxt( 'ID_VG.dat', temmm, fmt='%e', delimiter=';')
        temmm = Vg_bias
        Ie2 = Ie.transpose()
        fid = open('ID_VG.dat', 'w')
        ind = 0
        for item1 in temmm:
            fid.write("%e " % item1)
            for item2 in Ie2[:, ind]:
                fid.write("%e " % item2)
            fid.write('\n')
            ind += 1
        fid.close()

    # ID-VD CHARACTERISTICS (A/m), SAVED TO "id_vd.dat"
    # -------------------------------------------------
    if (Nd_step >= 1 and Ng_step == 0):
        figure(1)
        plot(Vd_bias, Ie[0, :], 'o-')
        grid(True)
        xlabel('$V_{DS}$ [V]')
        ylabel('$I_{DS} [\mu A/\mu m]$')
        title('$I_{DS}$ vs. $V_{DS}$')
        savefig('ID_VD.png')

        #temmm = [Vd_bias, Ie[0,:]]
        #np.savetxt('ID_VD.dat', temmm, fmt='%e', delimiter=';')
        temmm = Vd_bias
        Ie2 = Ie.transpose()
        fid = open('ID_{VD}.dat', 'w')
        ind = 0
        for item1 in temmm:
            fid.write("%e " % item1)
            for item2 in Ie2[ind, :]:
                fid.write("%e " % item2)
            fid.write('\n')
            ind += 1
        fid.close()
    #if plot_Iv==1 end

    #***************************************************************************************
    # Ec(X,Y)
    # -------------------------------------------
    if plot_Ec3d == 1:
        figure(6)
        [X, Y] = np.meshgrid(XI, YI)
        Z = trMEc
        ax = gca(projection='3d')
        surf = ax.plot_surface(X,
                               Y,
                               Z,
                               rstride=3,
                               cstride=3,
                               cmap=cm.coolwarm,
                               linewidth=0.5,
                               antialiased=True)

        #surf(XI,YI,trMEc)
        #shading interp commented out to reduce size of the .ps file
        title('3D Conduction band edge potential profile')
        ax.set_xlabel('X [nm]')
        ax.set_ylabel('Y [nm]')
        ax.set_zlabel('Ec [eV]')
        ax.view_init(elev=60, azim=50)
        ax.dist = 8
        savefig('Ec_X_Y.png')

        XII = (0, XI)
        tem1 = (YI, trMEc)
        tem2 = (XII, tem1)
        #np.savetxt('Ec_X_Y.dat', tem2, fmt='%e', delimiter=';')
        #f1 = open('Ec_X_Y','w')
        #writer = csv.writer(f1, delimiter = ',')
        #writer.writerows(tem2)

#*******************************************************************************************
    if (plot_Ecsub == 1 and max_subband >= 1):
        figure(8)
        for iii in np.arange(0, max_subband):
            plot(XI, E_sub[0, Ng_step, Nd_step, :, iii], 'r-')
            hold(True)
            grid(True)
            if (t_vall == 3):
                plot(XI, E_sub[1, Ng_step, Nd_step, :, iii], 'k-')
                plot(XI, E_sub[2, Ng_step, Nd_step, :, iii], '-')

        title('The Subbands energy profile along the channel')
        xlabel('X [nm]')
        ylabel('E_{SUB} [eV]')
        savefig('Ec_sub_X.png')

    ############################################################################################
    if (plot_Nesub == 1 and max_subband >= 1):
        figure(9)
        for iii in np.arange(0, max_subband):
            semilogy(XI, Ne_sub[0, Ng_step, Nd_step, :, iii], 'r-')
            hold(True)
            grid(True)
            if (t_vall == 3):
                semilogy(XI, Ne_sub[1, Ng_step, Nd_step, :, iii], 'k-')
                semilogy(XI, Ne_sub[2, Ng_step, Nd_step, :, iii], '-')
        title('2D electron density of the subbands along the channel ')
        xlabel('X [nm]')
        ylabel('N2D [cm^{-2}]')

        savefig('Ne_sub_X.png')

    if (Ng_step == 0 and Nd_step == 0):
        #	PLOT the graph of Transmission coefficient versus Energy
        #------------------------------------------------------------------
        if transport_model == 4:
            figure(11)
            plot(Trans, E)
            xlabel('Transmission Coefficient')
            ylabel('Energy (eV)')
            savefig('Trans.png')
            colorbar()
        #	PLOT the Density of states versus energy along the device
        #------------------------------------------------------------------
        if transport_model == 4:
            figure(12)
            pcolor(XI, E, np.sqrt(N_dos[:, 0:len(E)].transpose()))
            #shading interp
            # Square root of the DOS to get better visualization
            xlabel('Distance along the device (nm)')
            ylabel('Energy (eV)')
            colorbar()
            savefig('DOS.png')
            #print -depsc2 DOS.ps
        #	PLOT the Density of states versus energy along the device
        #------------------------------------------------------------------
        if transport_model == 5:
            figure(12)
            pcolor(XI, E, np.sqrt(abs(N_dos[:, 0:len(E)]).transpose()))
            #shading interp;
            # Square root of the DOS to get better visualization
            xlabel('Distance along the device (nm)')
            ylabel('Energy (eV)')
            colorbar()
            savefig('DOS.jpg')

    ################################################################################################
    if plot_Ne_IV == 1:
        # SUBBAND CHARGE DENSITY (/cm^2) vs X for Diff. Vg
        # --------------------------------------------------------------
        if (Ng_step >= 1 or (Ng_step == 0 and Nd_step == 0)):

            figure(2)
            for iii in np.arange(0, Ng_step + 1):
                Ne1_temp = np.squeeze(Ne_sub[:, iii, Nd_step, :, :])
                #if len(np.shape(Ne1_temp)) == 1:
                Ne1 = Ne1_temp
                #else:
                #    Ne1 = np.sum(Ne1_temp,0)
                Ne2 = np.zeros((len(Ne1), Ng_step + 1))
                Ne2[:, iii] = (Ne1) * 1e-4
                plot(XI, Ne2[:, iii], 'r-')
                hold(True)
                grid(True)

            if Ng_step >= 1:
                title('2D electron density along the channel at different Vg')
            elif Ng_step == 0:
                title('2D electron density along the channel')
            xlabel('X [nm]')
            ylabel('N2D $[cm^{-2}]$')
            savefig('N2D_X1.png')

            #figure(11)
            #Ne1=sum(squeeze(Ne_sub(:,:,:,1,Nd_step+1)),3);
            #Ne2(:,1)=sum(Ne1,2)*1e-4;
            #semilogy(XI',Ne2(:,1),'r-');
            #hold on
            #grid on
            #if Ng_step>0
            #  for iii=2:Ng_step+1
            #    Ne1=sum(squeeze(Ne_sub(:,:,:,iii,Nd_step+1)),3);
            #    Ne2(:,iii)=sum(Ne1,2)*1e-4;
            #    semilogy(XI',Ne2(:,iii),'r-');
            #  end
            #end
            #title('2D electron density along the channel @Diff. VG');
            #xlabel('X [nm]');
            #ylabel('N2D [cm^{-2}]');
            #print -depsc ./output/LOG_N2D_X.ps

            temmm = [XI, Ne2]
            Ne2 = np.squeeze(Ne_sub[0, Ng_step, :, :, 0])
            Ne2 = Ne2 * 1e-4
            fid = open('N2D_X1.dat', 'w')
            ind = 0
            print np.shape(XI)
            print np.shape(Ne2)
            for item1 in XI:
                fid.write("%e " % item1)
                item2 = Ne2[ind]
                fid.write("%e " % item2)
                fid.write('\n')
                ind += 1
            fid.close()
            #save N2D_X1.dat temmm -ascii;

    # SUBBAND CHARGE DENSITY (/cm^2) vs X for Diff. Vd
    # --------------------------------------------------------------
        if Nd_step >= 1:
            figure(3)
            for iii in np.arange(0, Nd_step + 1):
                Ne1_temp = np.squeeze(Ne_sub[:, Ng_step, iii, :, :])
                #if len(np.size(Ne1_temp)) == 1:
                Ne1 = Ne1_temp
                #else:
                #Ne1 = np.sum(Ne1_temp,0)
                Ne2 = np.zeros((len(Ne1), Nd_step + 1))
                Ne2[:, iii] = (Ne1) * 1e-4
                plot(XI, Ne2[:, iii], 'r-')
                hold(True)
                grid(True)
            title('2D electron density along the channel at different Vd')
            xlabel('X [nm]')
            ylabel('N2D [$cm^{-2}$]')
            savefig('N2D_X2.png')

            temmm = [XI, Ne2]
            Ne2 = np.squeeze(Ne_sub[0, Ng_step, :, :, 0])
            Ne2 = Ne2 * 1e-4
            fid = open('N2D_X2.dat', 'w')
            ind = 0
            print np.shape(XI)
            print np.shape(Ne2)
            for item1 in XI:
                fid.write("%e " % item1)
                for item2 in Ne2[:, ind]:
                    fid.write("%e " % item2)
                fid.write('\n')
                ind += 1
            fid.close()
        #save N2D_X2.dat temmm -ascii

    #******************************************************************************************
    if plot_Ec_IV == 1:
        # The First SUBBAND ENERGY PROFILE vs X for Diff. Vg
        # ------------------------------------------------------

        if (Ng_step >= 1 or (Ng_step == 0 and Nd_step == 0)):
            figure(4)
            for iii in np.arange(0, Ng_step + 1):
                plot(XI, E_sub[0, iii, Nd_step, :, 0], 'r-')
                hold(True)
                grid(True)

            if Ng_step >= 1:
                title(
                    'The First Subband energy profile along the channel at different Vg'
                )
            elif Ng_step == 0:
                title('The First Subband energy profile along the channel')
            xlabel('X [nm]')
            ylabel('E_{SUB} [eV]')
            savefig('Ec_X1.png')

            tem = E_sub[0, iii, Nd_step, :, 0]
            sq_tem = np.squeeze(tem)
            print np.shape(sq_tem)
            temmm = [XI, sq_tem]
            fid = open('Ec_X1.dat', 'w')
            ind = 0
            for item1 in XI:
                fid.write("%e " % item1)
                item2 = sq_tem[ind]
                fid.write("%e " % item2)
                fid.write('\n')
                ind += 1
            fid.close()
            #save Ec_X1.dat temmm -ascii

    # The First SUBBAND ENERGY PROFILE vs X for Diff. Vd
    # ------------------------------------------------------

        if Nd_step >= 1:
            figure(5)
            for iii in np.arange(0, Nd_step + 1):
                plot(XI, E_sub[0, Ng_step, iii, :, 0], 'r-')
                hold(True)
                grid(True)

            title(
                'The First Subband energy profile along the channel at different Vd'
            )
            xlabel('X [nm]')
            ylabel('$E_{SUB}$ [eV]')
            savefig('Ec_X2.png')

            tem = E_sub[0, Ng_step, :, :, 0]
            sq_tem = np.squeeze(tem)
            fid = open('Ec_X2.dat', 'w')
            ind = 0
            for item1 in XI:
                fid.write("%e " % item1)
                for item2 in sq_tem[:, ind]:
                    fid.write("%e " % item2)
                fid.write('\n')
                ind += 1
            fid.close()
            #temmm = [XI,sq_tem]
            #save Ec_X2.dat temmm -ascii

    # 3D CHARGE DENSITY N(X,Y)
    # ------------------------------------------------------------
    if plot_Ne3d == 1:
        figure(7)
        #surf(XI,YI,trMNe)
        #shading interp commented out to reduce size of the .ps file
        [X, Y] = np.meshgrid(XI, YI)
        Z = trMNe
        ax = gca(projection='3d')
        surf = ax.plot_surface(X,
                               Y,
                               Z,
                               rstride=3,
                               cstride=3,
                               cmap=cm.coolwarm,
                               linewidth=0.5,
                               antialiased=True)

        title('3D Electron density profile')
        ax.set_xlabel('X [nm]')
        ax.set_ylabel('Y [nm]')
        ax.set_zlabel('Ne [$m^{-3}$]')
        ax.view_init(elev=60, azim=50)
        ax.dist = 8
        savefig('Ne_X_Y.png')

        XII = [0, XI]
        tem1 = [YI, trMNe]
        tem2 = [XII, tem1]
        #save Ne_X_Y.dat tem2 -ascii

    return
Пример #34
0
def saveoutput(Ec,Ne,Ie,Ne_sub,E_sub,Te_sub,converge,Vd_temp):
    transport_model = transportmodel.value
    N_sd = Nsd1.value
    N_body = Nbody1.value
    fermi_flag = fermiflag1.value
    Vd = Vdc.value
    # Rohit- N_dos, Trans and E

    ###########################################################
    #SPECIFY XI, YI, Vg_bias, and Vd_bias for plotting use only
    ###########################################################

    Nx = round((2*Lsd+Lg_top)/dx)+1
    XI = np.linspace(-(Lsd+Lg_top/2)*1e9, (Lsd+Lg_top/2)*1e9, Nx)  # in nanometers
    Ny = round((t_top+t_bot+t_si)/dy)+1
    YI = np.linspace(-t_top*1e9, (t_si+t_bot)*1e9, Ny)
    Vg_bias = np.linspace(Vg1, Vg1+Vg_step*Ng_step, Ng_step+1)
    Vd_bias = np.linspace(Vd_temp, Vd_temp+Vd_step*Nd_step, Nd_step+1)

    ###########################################################
    #       POST PROCESSING
    ###########################################################
    MEc = np.reshape(Ec[Nd_step, :, Ng_step], (Ny, Nx)).transpose()
    trMEc = MEc.transpose()
    MNe = np.reshape(Ne[Nd_step, :, Ng_step], (Ny, Nx)).transpose()
    trMNe = MNe.transpose()

    #mkdir(dirname)
    #cd(dirname)

    #raw_data is always stored!!!!!
    #--------------------------------------------------
    #save output_rawdata
    #Save convergence data in a file
    #save DOS.dat N_dos -ascii
    Trans  = globvars.Trans
    #save trans.dat Trans -ascii
    E = globvars.E
    #save E.dat E -ascii
    N_dos = globvars.N_dos

    fid = open("convergence.dat", "w")

    fid.write('****************************************************************\n')
    fid.write('*******You ran a Nanomos simulation on the %s *********\n' % datetime.datetime.now())
    fid.write('********************* Using Nanomos 2.0 ************************\n')
    fid.write('********** The input file you used  was the following **********\n')
    fid.write('****************************************************************\n')

    #cd ..
    # fid1=fopen(filename,'r')
    #     while 1
    #         tline = fgetl(fid1)
    #         if ~ischar(tline), break, end
    #         count=fprintf(fid,'%s\n',tline);
    #     end
    # status=fclose(fid1)
    # cd(dirname)

    fid.write('****************************************************************\n')
    fid.write('********** Convergence data for simulated bias points **********\n')
    fid.write('****************************************************************\n')

    for i in np.arange(0,Ng_step+1):
        for j in np.arange(0,Nd_step+1):
            fid.write('\n')
            fid.write('**** Gate voltage = %f ****Drain voltage = %f' % (Vg_bias[i], Vd_bias[j]))
            fid.write('\n')
            for item in converge[i,j]:
                fid.write('%e\n' % item)

    fid.write('****************************************************************')
    fid.write('********** The end of the convergence data file*****************')
    fid.write('****************************************************************')

    fid.close()

    ############################################# IV plots ##############################################
    if plot_IV == 1:
    # ID-VD CHARACTERISTICS (A/m), SAVED TO "id_vd.dat"
    # -------------------------------------------------
        if (Ng_step>=1 and Nd_step>=1):
            Ng = np.size(Ie,0)
            figure(1)
            plot(Vd_bias,Ie[0,:],'o-')
            grid(True)
            hold(True)
            for i in np.arange(1,Ng):
                plot(Vd_bias, Ie[i, :], 'o-')

            xlabel('$V_{DS}$ [V]')
            ylabel('$I_{DS}$ $[\mu A/\mu m]$')
            title('$I_{DS}$ vs. $V_{DS}$')
            savefig('ID_VD.png')

            temmm = Vd_bias
            Ie2 = Ie.transpose()
            fid = open('ID_VD.dat','w')
            ind = 0
            for item1 in temmm:
                fid.write("%e " % item1)
                for item2 in Ie2[ind,:]:
                    fid.write("%e " % item2)
                fid.write('\n')
                ind += 1
            fid.close()

    # ID-VG CHARACTERISTICS (A/m), SAVED TO "id_vg.dat"
    # -------------------------------------------------
    if (Ng_step>=1 and Nd_step==0):
        figure(1)
        semilogy(Vg_bias, Ie[:,0],'o-')
        grid(True)
        xlabel('$V_{GS}$ [V]')
        ylabel('$I_{DS} [\mu A/\mu m]$')
        title('$I_{DS}$ vs. $V_{GS}$')
        savefig('ID_VG.png')

        #temmm=[Vg_bias, Ie[:,0]]
        #np.savetxt( 'ID_VG.dat', temmm, fmt='%e', delimiter=';')
        temmm = Vg_bias
        Ie2 = Ie.transpose()
        fid = open('ID_VG.dat','w')
        ind = 0
        for item1 in temmm:
            fid.write("%e " % item1)
            for item2 in Ie2[:,ind]:
                fid.write("%e " % item2)
            fid.write('\n')
            ind += 1
        fid.close()

    # ID-VD CHARACTERISTICS (A/m), SAVED TO "id_vd.dat"
    # -------------------------------------------------
    if (Nd_step>=1 and Ng_step==0):
        figure(1)
        plot(Vd_bias, Ie[0,:], 'o-')
        grid(True)
        xlabel('$V_{DS}$ [V]')
        ylabel('$I_{DS} [\mu A/\mu m]$')
        title('$I_{DS}$ vs. $V_{DS}$')
        savefig('ID_VD.png')

        #temmm = [Vd_bias, Ie[0,:]]
        #np.savetxt('ID_VD.dat', temmm, fmt='%e', delimiter=';')
        temmm = Vd_bias
        Ie2 = Ie.transpose()
        fid = open('ID_{VD}.dat','w')
        ind = 0
        for item1 in temmm:
            fid.write("%e " % item1)
            for item2 in Ie2[ind,:]:
                fid.write("%e " % item2)
            fid.write('\n')
            ind += 1
        fid.close()
    #if plot_Iv==1 end

    #***************************************************************************************
    # Ec(X,Y)
    # -------------------------------------------
    if plot_Ec3d == 1:
        figure(6)
        [X, Y] = np.meshgrid(XI, YI)
        Z = trMEc
        ax = gca(projection = '3d')
        surf = ax.plot_surface(X, Y, Z, rstride=3, cstride=3, cmap=cm.coolwarm, linewidth=0.5, antialiased = True)

        #surf(XI,YI,trMEc)
        #shading interp commented out to reduce size of the .ps file
        title('3D Conduction band edge potential profile')
        ax.set_xlabel('X [nm]')
        ax.set_ylabel('Y [nm]')
        ax.set_zlabel('Ec [eV]')
        ax.view_init(elev=60, azim=50)
        ax.dist=8
        savefig('Ec_X_Y.png')

        XII = (0, XI)
        tem1 = (YI, trMEc)
        tem2 = (XII, tem1)
        #np.savetxt('Ec_X_Y.dat', tem2, fmt='%e', delimiter=';')
        #f1 = open('Ec_X_Y','w')
        #writer = csv.writer(f1, delimiter = ',')
        #writer.writerows(tem2)



   #*******************************************************************************************
    if (plot_Ecsub==1 and max_subband>=1):
        figure(8)
        for iii in np.arange(0,max_subband):
            plot(XI, E_sub[0, Ng_step, Nd_step, :, iii],'r-')
            hold(True)
            grid(True)
            if (t_vall==3):
                plot(XI, E_sub[1, Ng_step, Nd_step, :,iii],'k-')
                plot(XI, E_sub[2, Ng_step, Nd_step, :,iii],'-')

        title('The Subbands energy profile along the channel')
        xlabel('X [nm]')
        ylabel('E_{SUB} [eV]')
        savefig('Ec_sub_X.png')

    ############################################################################################
    if (plot_Nesub==1 and max_subband>=1):
        figure(9)
        for iii in np.arange(0,max_subband):
            semilogy(XI, Ne_sub[0, Ng_step, Nd_step, :, iii],'r-')
            hold(True)
            grid(True)
            if (t_vall==3):
                semilogy(XI, Ne_sub[1, Ng_step, Nd_step, :, iii],'k-')
                semilogy(XI, Ne_sub[2, Ng_step, Nd_step, :, iii],'-')
        title('2D electron density of the subbands along the channel ')
        xlabel('X [nm]')
        ylabel('N2D [cm^{-2}]')

        savefig('Ne_sub_X.png')

    if (Ng_step==0 and Nd_step==0):
        #	PLOT the graph of Transmission coefficient versus Energy
        #------------------------------------------------------------------
        if transport_model==4:
            figure(11)
            plot(Trans, E)
            xlabel('Transmission Coefficient')
            ylabel('Energy (eV)')
            savefig('Trans.png')
            colorbar()
        #	PLOT the Density of states versus energy along the device
        #------------------------------------------------------------------
        if transport_model==4:
            figure(12)
            pcolor(XI, E, np.sqrt(N_dos[:,0:len(E)].transpose()))
            #shading interp
            # Square root of the DOS to get better visualization
            xlabel('Distance along the device (nm)')
            ylabel('Energy (eV)')
            colorbar()
            savefig('DOS.png')
            #print -depsc2 DOS.ps
        #	PLOT the Density of states versus energy along the device
        #------------------------------------------------------------------
        if transport_model==5:
            figure(12)
            pcolor(XI,E,np.sqrt(abs(N_dos[:,0:len(E)]).transpose()))
            #shading interp;
	        # Square root of the DOS to get better visualization
            xlabel('Distance along the device (nm)')
            ylabel('Energy (eV)')
            colorbar()
            savefig('DOS.jpg')

    ################################################################################################
    if plot_Ne_IV==1:
    # SUBBAND CHARGE DENSITY (/cm^2) vs X for Diff. Vg
    # --------------------------------------------------------------
        if (Ng_step>=1 or (Ng_step==0 and Nd_step==0)):

            figure(2)
            for iii in np.arange(0,Ng_step+1):
                Ne1_temp = np.squeeze(Ne_sub[:, iii, Nd_step, :, :])
                #if len(np.shape(Ne1_temp)) == 1:
                Ne1 = Ne1_temp
                #else:
                #    Ne1 = np.sum(Ne1_temp,0)
                Ne2 = np.zeros((len(Ne1), Ng_step+1))
                Ne2[:,iii]=(Ne1)*1e-4
                plot(XI, Ne2[:, iii], 'r-')
                hold(True)
                grid(True)

            if Ng_step>=1:
                title('2D electron density along the channel at different Vg')
            elif Ng_step==0:
                title('2D electron density along the channel')
            xlabel('X [nm]')
            ylabel('N2D $[cm^{-2}]$')
            savefig('N2D_X1.png')

    #figure(11)
    #Ne1=sum(squeeze(Ne_sub(:,:,:,1,Nd_step+1)),3);
    #Ne2(:,1)=sum(Ne1,2)*1e-4;
    #semilogy(XI',Ne2(:,1),'r-');
    #hold on
    #grid on
    #if Ng_step>0
    #  for iii=2:Ng_step+1
    #    Ne1=sum(squeeze(Ne_sub(:,:,:,iii,Nd_step+1)),3);
    #    Ne2(:,iii)=sum(Ne1,2)*1e-4;
    #    semilogy(XI',Ne2(:,iii),'r-');
    #  end
    #end
    #title('2D electron density along the channel @Diff. VG');
    #xlabel('X [nm]');
    #ylabel('N2D [cm^{-2}]');
    #print -depsc ./output/LOG_N2D_X.ps

            temmm=[XI,Ne2]
            Ne2 = np.squeeze(Ne_sub[0,Ng_step,:,:,0])
            Ne2 = Ne2*1e-4
            fid = open('N2D_X1.dat','w')
            ind = 0
            print np.shape(XI)
            print np.shape(Ne2)
            for item1 in XI:
                fid.write("%e " % item1)
                item2 = Ne2[ind]
                fid.write("%e " % item2)
                fid.write('\n')
                ind += 1
            fid.close()
            #save N2D_X1.dat temmm -ascii;


    # SUBBAND CHARGE DENSITY (/cm^2) vs X for Diff. Vd
    # --------------------------------------------------------------
        if Nd_step>=1:
            figure(3)
            for iii in np.arange(0,Nd_step+1):
                Ne1_temp = np.squeeze(Ne_sub[:, Ng_step, iii, :, :])
                #if len(np.size(Ne1_temp)) == 1:
                Ne1 = Ne1_temp
                #else:
                #Ne1 = np.sum(Ne1_temp,0)
                Ne2 = np.zeros((len(Ne1), Nd_step+1))
                Ne2[:, iii] = (Ne1)*1e-4
                plot(XI, Ne2[:, iii], 'r-')
                hold(True)
                grid(True)
            title('2D electron density along the channel at different Vd')
            xlabel('X [nm]')
            ylabel('N2D [$cm^{-2}$]')
            savefig('N2D_X2.png')

            temmm=[XI,Ne2]
            Ne2 = np.squeeze(Ne_sub[0,Ng_step,:,:,0])
            Ne2 = Ne2*1e-4
            fid = open('N2D_X2.dat','w')
            ind = 0
            print np.shape(XI)
            print np.shape(Ne2)
            for item1 in XI:
                fid.write("%e " % item1)
                for item2 in Ne2[:,ind]:
                    fid.write("%e " % item2)
                fid.write('\n')
                ind += 1
            fid.close()
        #save N2D_X2.dat temmm -ascii

    #******************************************************************************************
    if plot_Ec_IV==1:
    # The First SUBBAND ENERGY PROFILE vs X for Diff. Vg
    # ------------------------------------------------------

        if (Ng_step>=1 or (Ng_step==0 and Nd_step==0)):
            figure(4)
            for iii in np.arange(0,Ng_step+1):
                plot(XI, E_sub[0, iii, Nd_step, :, 0],'r-')
                hold(True)
                grid(True)

            if Ng_step>=1:
                title('The First Subband energy profile along the channel at different Vg')
            elif Ng_step==0:
                title('The First Subband energy profile along the channel')
            xlabel('X [nm]')
            ylabel('E_{SUB} [eV]')
            savefig('Ec_X1.png')

            tem = E_sub[0,iii, Nd_step, :, 0]
            sq_tem = np.squeeze(tem)
            print np.shape(sq_tem)
            temmm = [XI, sq_tem]
            fid = open('Ec_X1.dat','w')
            ind = 0
            for item1 in XI:
                fid.write("%e " % item1)
                item2 = sq_tem[ind]
                fid.write("%e " % item2)
                fid.write('\n')
                ind += 1
            fid.close()
            #save Ec_X1.dat temmm -ascii

    # The First SUBBAND ENERGY PROFILE vs X for Diff. Vd
    # ------------------------------------------------------

        if Nd_step>=1:
            figure(5)
            for iii in np.arange(0,Nd_step+1):
                plot(XI,E_sub[0,Ng_step,iii, :, 0],'r-')
                hold(True)
                grid(True)

            title('The First Subband energy profile along the channel at different Vd')
            xlabel('X [nm]')
            ylabel('$E_{SUB}$ [eV]')
            savefig('Ec_X2.png')

            tem = E_sub[0, Ng_step, :, :, 0]
            sq_tem = np.squeeze(tem)
            fid = open('Ec_X2.dat','w')
            ind = 0
            for item1 in XI:
                fid.write("%e " % item1)
                for item2 in sq_tem[:,ind]:
                    fid.write("%e " % item2)
                fid.write('\n')
                ind += 1
            fid.close()
            #temmm = [XI,sq_tem]
            #save Ec_X2.dat temmm -ascii

    # 3D CHARGE DENSITY N(X,Y)
    # ------------------------------------------------------------
    if plot_Ne3d==1:
        figure(7)
        #surf(XI,YI,trMNe)
        #shading interp commented out to reduce size of the .ps file
        [X, Y] = np.meshgrid(XI, YI)
        Z = trMNe
        ax = gca(projection = '3d')
        surf = ax.plot_surface(X, Y, Z, rstride=3, cstride=3, cmap=cm.coolwarm, linewidth=0.5, antialiased = True)

        title('3D Electron density profile')
        ax.set_xlabel('X [nm]')
        ax.set_ylabel('Y [nm]')
        ax.set_zlabel('Ne [$m^{-3}$]')
        ax.view_init(elev=60, azim=50)
        ax.dist=8
        savefig('Ne_X_Y.png')

        XII = [0, XI]
        tem1 = [YI, trMNe]
        tem2 = [XII, tem1]
        #save Ne_X_Y.dat tem2 -ascii

    return
Пример #35
0
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 27 20:10:40 2016

@author: Bhuti
"""
import pandas as pd
pd.set_option('display.max_row', 1000)
pd.set_option('display.max_columns', 50)

got = pd.read_csv ('/Users/Bhuti/Desktop/war_of_the_five_kings_dataset-master/5kings_battles_v1.csv')
got = pd.DataFrame(got)
# print(got['attacker_size'])
print(got['defender_king'].value_counts())
got['defender_king'].value_counts().plot(kind='bar')

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = got['year']
y = got['battle_number']
z = got['attacker_size']
# Axes3D.plot_surface('defender_1','battle_number','attacker_outcome')
Axes3D.plot_surface(x,y,z)
Пример #36
0
# Grid over which we will calculate J
theta0_vals = np.linspace(-10, 10, 100)
theta1_vals = np.linspace(-1, 4, 100)

# initialize J_vals to a matrix of 0's
J_vals = np.zeros((len(theta0_vals), len(theta1_vals)))

# Fill out J_Vals
# Note: There is probably a more efficient way to do this that uses
#	broadcasting instead of the nested for loops
for i in range(len(theta0_vals)):
    for j in range(len(theta1_vals)):
        t = np.array([theta0_vals[i], theta1_vals[j]])
        J_vals[i][j] = computeCost(X, y, t)

# Surface plot using J_Vals
fig = plt.figure()
ax = plt.subplot(111, projection='3d')
Axes3D.plot_surface(ax, theta0_vals, theta1_vals, J_vals, cmap=cm.coolwarm)
plt.show()

# Contour plot
# TO DO: Currently does not work as expected. Need to find a way to mimic
#	 the logspace option in matlab
fig = plt.figure()
ax = plt.subplot(111)
plt.contour(theta0_vals, theta1_vals, J_vals)

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Пример #37
0
predict2 = np.dot([1, 7], theta)
print('For population = 70,000, we predict a profit of ', predict2 * 10000)
input('Program paused. Press enter to continue.\n')
print('Visualizing J(theta_0, theta_1) ...\n')

# Grid over which we will calculate J
theta0_vals = np.linspace(-10, 10, 100)
theta1_vals = np.linspace(-1, 4, 100)
J_vals = np.zeros((len(theta0_vals), len(theta1_vals)))

for i in range(len(theta0_vals)):
    for j in range(len(theta1_vals)):
        t = np.array([theta0_vals[i], theta1_vals[j]])
        J_vals[i][j] = computeCost(X, y, t)
"""
# Surface plot using J_Vals
fig = plt.figure()
ax = plt.subplot(111,projection='3d')
Axes3D.plot_surface(ax,theta0_vals,theta1_vals,J_vals,cmap=cm.coolwarm)
plt.show()

fig = plt.figure()
ax = plt.subplot(111)
plt.contour(theta0_vals,theta1_vals,J_vals) 
"""
print('Loading data ...', '\n')
print('Plotting Data ...', '\n')
data = pd.read_csv("ex1data2.txt", names=["size", "bedrooms", "price"])
s = np.array(data.size)
r = np.array(data.bedrooms)
Пример #38
0
    # form a finer level initial guess
    n2 = n*2
    x0 = np.random.random(4*n2)
    x0[0:n*2]   = res.x[0:n*2]
    x0[n*4:n*5] = res.x[n*2:n*3]
    x0[n*6:n*7] = res.x[3*n:4*n]
    x0[n*7:n*8] = np.zeros(n)
    n = n2

# call a minimizer to find a global min for the finest level
opt = {'ftol':1E-8, 'maxiter':500, 'disp': True}
res = minimize(F, x0, method='SLSQP', options=opt)
#res = minimize(F, x0, method='SLSQP', jac=JacF, options=opt)
sol = res.x

time_end = time()
print( 'CPU time used:', time_end-time_start, 'seconds' )
np.save('data_abd.npy', sol)

# output final energy and plot the solution
npt = 100
tpt1 = np.arange(-1,1,2.0/npt)
tpt2 = np.arange(-1,1,2.0/npt)
a = sol[0:2*n].reshape(n,2)
b = sol[2*n:3*n]
c = sol[3*n:4*n]
ypt = phi(tpt1, tpt2, a, b, d)
Axes3D.plot_surface(tpt1,tp2,ypt,'r:')
plt.title( 'Solution with n = ' + str(n) )
plt.show()