Exemplo n.º 1
0
    def debug_plot(self, n=40, show_pdf=False, azim=210, elev=30):
        #Z = self.cdf(f.get_piecewise_cdf()(X), g.get_piecewise_cdf()(Y))
        #Z = self.jcdf(f, g, X, Y)
        if self.marginals is not None and len(self.marginals) > 1:
            f, g = self.marginals[:2]
            self.setMarginals((f, g))
        else:
            f, g = UniformDistr(), UniformDistr()

        Lf, Uf = f.ci(0.01)
        Lg, Ug = g.ci(0.01)
        deltaf = (Uf - Lf) / n
        deltag = (Ug - Lg) / n

        X, Y = meshgrid(arange(Lf, Uf, deltaf), arange(Lg, Ug, deltag))
        if not show_pdf:
            Z = self.cdf(X, Y)
            Z2 = self.pdf(X, Y)
            fig = figure(figsize=plt.figaspect(1))
            ax = fig.add_subplot(111, projection='3d', azim=azim, elev=elev)
            #ax = p3.Axes3D(fig)
            xf = arange(Lf, Uf, deltaf)
            xg = arange(Lg, Ug, deltag)
            cf = f.cdf(xf)
            cg = g.cdf(xg)
            ax.plot(xf, cf, zs=Ug, zdir='y', linewidth=3.0, color="k")
            ax.plot(xg, cg, zs=Uf, zdir='x', linewidth=3.0, color="k")
            cset = ax.contour(X, Y, Z, zdir='z', offset=0)
            ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1, color='k', antialiased=True)#cmap=cm.jet
            ax.set_xlabel('$X$')
            ax.set_xlim3d(Lf, Uf)
            ax.set_ylabel('$Y$')
            ax.set_ylim3d(Lg, Ug)
            ax.set_zlabel('$Z$')
            ax.set_zlim3d(0, 1)
            # wykres F(x)=G(Y)
        else:
            fig = figure(figsize=plt.figaspect(1))
            ax = fig.add_subplot(111, projection='3d')
            #ax = fig.add_subplot(122,  projection='3d')
            t = linspace(0.01, 0.99,40)
            X = f.quantile(t)
            Y = g.quantile(t)
            Z = f(X)*g(Y)
            cf = f.pdf(xf)
            cg = g.pdf(xg)
            ax.plot(xf, cf, zs=Ug, zdir='y', linewidth=3.0, color="k")
            ax.plot(xg, cg, zs=Uf, zdir='x', linewidth=3.0, color="k")
            ax.plot_surface(np.vstack([X,X]), np.vstack([Y,Y]), np.vstack([np.zeros_like(Z),Z]),
                        cstride = 1, rstride = 1,# cmap=cm.jet,
                        linewidth = -1, edgecolor="k", color = "c", alpha=0.7, antialiased = True)
            ax.axis((Lf, Uf, Lg, Ug))
            zlim = 1.01*np.max(array([max(Z), max(cf), max(cg)]))
            ax.set_zlim3d(0,zlim)
Exemplo n.º 2
0
    def debug_plot(self, n=40, show_pdf=False, azim=210, elev=30):
        #Z = self.cdf(f.get_piecewise_cdf()(X), g.get_piecewise_cdf()(Y))
        #Z = self.jcdf(f, g, X, Y)
        if self.marginals is not None and len(self.marginals) > 1:
            f, g = self.marginals[:2]
            self.setMarginals((f, g))
        else:
            f, g = UniformDistr(), UniformDistr()

        Lf, Uf = f.ci(0.01)
        Lg, Ug = g.ci(0.01)
        deltaf = (Uf - Lf) / n
        deltag = (Ug - Lg) / n
        X, Y = meshgrid(arange(Lf, Uf, deltaf), arange(Lg, Ug, deltag))
        if not show_pdf:
            Z = self.cdf(X, Y)
            fig = figure(figsize=plt.figaspect(1))
            ax = fig.add_subplot(111, projection='3d', azim=azim, elev=elev)
            #ax = p3.Axes3D(fig)
            xf = arange(Lf, Uf, deltaf)
            xg = arange(Lg, Ug, deltag)
            cf = f.cdf(xf)
            cg = g.cdf(xg)
            ax.plot(xf, cf, zs=Ug, zdir='y', linewidth=3.0, color="k")
            ax.plot(xg, cg, zs=Uf, zdir='x', linewidth=3.0, color="k")
            ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1, color='k', antialiased=True)#cmap=cm.jet
            cset = ax.contour(X, Y, Z, zdir='z', color='k', offset=0)
            ax.set_xlabel('$X$')
            ax.set_xlim3d(Lf, Uf)
            ax.set_ylabel('$Y$')
            ax.set_ylim3d(Lg, Ug)
            ax.set_zlabel('$Z$')
            ax.set_zlim3d(0, 1)
        else:
            fig = figure(figsize=plt.figaspect(1))
            ax2 = fig.add_subplot(111, projection='3d', azim=azim, elev=elev)
            Z2 = self.pdf(X, Y)
            xf = arange(Lf, Uf, deltaf)
            xg = arange(Lg, Ug, deltag)
            cf = f.pdf(xf)
            cg = g.pdf(xg)
            ax2.plot(xf, cf, zs=Ug, zdir='y', linewidth=3.0, color="k")
            ax2.plot(xg, cg, zs=Uf, zdir='x', linewidth=3.0, color="k")
            ax2.plot_wireframe(X, Y, Z2, rstride=1, cstride=1, color='k', antialiased=True)
            cset = ax2.contour(X, Y, Z2, color='k', zdir='z', offset=0)
            ax2.set_xlabel('$X$')
            ax2.set_xlim3d(Lf, Uf)
            ax2.set_ylabel('$Y$')
            ax2.set_ylim3d(Lg, Ug)
            ax2.set_zlabel('$Z$')
            zlim = 1.01*np.max(array([np.max(Z2), max(cf), max(cg)]))
            ax2.set_zlim3d(0,zlim)
Exemplo n.º 3
0
    def __init__(self, vars, title=None, figaspect=1.0, **kwlimits):
        """
        Create a `_MatplotlibViewer`.
        
        :Parameters:
          vars
            a `CellVariable` or tuple of `CellVariable` objects to plot
          title
            displayed at the top of the `Viewer` window
          figaspect
            desired aspect ratio of figure. If arg is a number, use that aspect
            ratio. If arg is an array, figaspect will determine the width and
            height for a figure that would fit array preserving aspect ratio.
          xmin, xmax, ymin, ymax, datamin, datamax
            displayed range of data. A 1D `Viewer` will only use `xmin` and
            `xmax`, a 2D viewer will also use `ymin` and `ymax`. All
            viewers will use `datamin` and `datamax`. Any limit set to a
            (default) value of `None` will autoscale.
        """
        if self.__class__ is _MatplotlibViewer:
            raise NotImplementedError, "can't instantiate abstract base class"
            
        _Viewer.__init__(self, vars=vars, title=title, **kwlimits)

        import pylab

        pylab.ion()

        w, h = pylab.figaspect(figaspect)
        fig = pylab.figure(figsize=(w, h))
        self.id = fig.number
        
        pylab.title(self.title)
Exemplo n.º 4
0
 def __init__(self,
              data,
              x,
              y,
              slice_idx,
              cmap=P.cm.gray,
              norm=None,
              interpolation="bilinear",
              extent=None):
     self.norm = norm
     self.cmap = cmap
     self.interpolation = interpolation
     self.slice_idx = slice_idx
     # extent should be static, so set it and leave it alone
     if not extent:
         y, x = data.shape[-2:]
         extent = [-x / 2., x / 2., -y / 2., y / 2.]
     self.extent = extent
     self.ylim = tuple(extent[2:])
     self.xlim = tuple(extent[:2])
     fig = P.Figure(figsize=P.figaspect(data), dpi=80)
     ax = fig.add_subplot(111)
     ax.yaxis.tick_right()
     ax.title.set_y(1.05)
     FigureCanvas.__init__(self, fig)
     self.setData(data)
     self._init_crosshairs(x, y)
Exemplo n.º 5
0
def three_contributions():
    nx, ny = 200, 200
    E_inc, E_mixed, E_scat = generate_fields(nx, ny)

    # Generate the images of the three contributions.
    image_mixed = np.sum(E_mixed, axis=0).reshape(nx, ny)
    image_inc = image_field(E_inc, nx, ny)
    image_scat = image_field(E_scat, nx, ny)

    # Plot the images.
    fig, axes = pl.subplots(1, 3, figsize=pl.figaspect(0.33))
    for ax in axes:
        ax.axis('off')

    ax_einc = axes[0].imshow(image_inc,
                             cmap='gray',
                             interpolation='gaussian',
                             vmin=0,
                             vmax=1.5)
    ax_mixed = axes[1].imshow(image_mixed,
                              cmap='gray',
                              interpolation='gaussian')
    ax_scat = axes[2].imshow(image_scat, cmap='gray', interpolation='gaussian')
    #pl.show()

    filename = os.path.join('../../Figures/', 'hvm_three_contributions_02.png')
    pl.savefig(filename, dpi=200)
Exemplo n.º 6
0
def drawEllipsoid(coefs, center):
    '''doesn't work yet'''
    fig = pl.figure(figsize=pl.figaspect(1))  # Square figure
    ax = fig.add_subplot(111, projection='3d')
    
    # Radii corresponding to the coefficients:
    rx, ry, rz = [1/np.sqrt(coef) for coef in coefs]
    
    # Set of all spherical angles:
    u = np.linspace(0, 2 * np.pi, 100)
    v = np.linspace(0, np.pi, 100)
    
    # Cartesian coordinates that correspond to the spherical angles:
    # (this is the equation of an ellipsoid):
    x = center[0] + rx * np.outer(np.cos(u), np.sin(v))
    y = center[1] + ry * np.outer(np.sin(u), np.sin(v))
    z = center[2] + rz * np.outer(np.ones_like(u), np.cos(v))
    
    # Plot:
    ax.plot_wireframe(x, y, z, color='b')
    
    # Adjustment of the axes, so that they all have the same span:
    max_radius = max(rx, ry, rz)
    for axis in 'xyz':
        getattr(ax, 'set_{}lim'.format(axis))((-max_radius, max_radius))
        
    drawPoints(points, ax)
Exemplo n.º 7
0
def display_grain_map_3d(grain_ang,ang_max,ang_min,weight=None,title=None):
    """
    Function to display a grain map colour coded by two tilt angles
    """
    fig = pl.figure(3,figsize=pl.figaspect(1.0))
    ax = p3.Axes3D(fig)
    map = n.zeros((n.shape(grain_ang)[0],n.shape(grain_ang)[1],n.shape(grain_ang)[2],3))
    map[:,:,:,0:2] = (grain_ang[:,:,:]-ang_min[0:2])/(n.array(ang_max[0:2])-ang_min[0:2]) 
    map[:,:,:,2] = n.ones((n.shape(grain_ang)[0],n.shape(grain_ang)[1],n.shape(grain_ang)[2]))-n.maximum.reduce([map[:,:,:,0],map[:,:,:,1]])
    if weight != None:
	    map[:,:,:,0] = map[:,:,:,0]*weight[:,:,:]/n.max(weight)
	    map[:,:,:,1] = map[:,:,:,1]*weight[:,:,:]/n.max(weight)
	    map[:,:,:,2] = map[:,:,:,2]*weight[:,:,:]/n.max(weight)
    for ix in range(n.shape(grain_ang)[0]):
        for iy in range(n.shape(grain_ang)[1]):
            for iz in range(n.shape(grain_ang)[2]):
                cax=ax.scatter3D(ix,iy,iz,s=100,c=map[ix,iy,iz])
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    pl.title(title)
    pl.show()        


    
Exemplo n.º 8
0
    def __init__(self, vars, title=None, figaspect=1.0, cmap=None, colorbar=None, axes=None, **kwlimits):
        """
        Create a `_MatplotlibViewer`.
        
        :Parameters:
          vars
            a `CellVariable` or tuple of `CellVariable` objects to plot
          title
            displayed at the top of the `Viewer` window
          figaspect
            desired aspect ratio of figure. If arg is a number, use that aspect
            ratio. If arg is an array, figaspect will determine the width and
            height for a figure that would fit array preserving aspect ratio.
          xmin, xmax, ymin, ymax, datamin, datamax
            displayed range of data. A 1D `Viewer` will only use `xmin` and
            `xmax`, a 2D viewer will also use `ymin` and `ymax`. All
            viewers will use `datamin` and `datamax`. Any limit set to a
            (default) value of `None` will autoscale.
          cmap
            the colormap. Defaults to `matplotlib.cm.jet`
          colorbar
            plot a colorbar in specified orientation if not `None`
          axes
            if not `None`, `vars` will be plotted into this Matplotlib `Axes` object
        """
        if self.__class__ is _MatplotlibViewer:
            raise NotImplementedError, "can't instantiate abstract base class"
            
        _Viewer.__init__(self, vars=vars, title=title, **kwlimits)

        import pylab

        pylab.ion()

        if axes is None:
            w, h = pylab.figaspect(figaspect)
            fig = pylab.figure(figsize=(w, h))
            self.axes = pylab.gca()
        else:
            self.axes = axes
            fig = axes.get_figure()
            
        self.id = fig.number
        
        self.axes.set_title(self.title)
        
        import matplotlib
        # Set the colormap and norm to correspond to the data for which
        # the colorbar will be used.
        if cmap is None:
            self.cmap = matplotlib.cm.jet
        else:
            self.cmap = cmap

        if colorbar:
            self.colorbar = _ColorBar(viewer=self)
        else:
            self.colorbar = None
Exemplo n.º 9
0
def showweisskoff(theareas,thestddevs,theprojstddevs,thelabel):
    w, h = P.figaspect(1.0)
    roiplot = P.figure(figsize=(w,h))
    roiplot.subplots_adjust(hspace=0.35)
    roisubplot = roiplot.add_subplot(111)
    thestddevs=thestddevs+0.00000001
    roisubplot.loglog(theareas, thestddevs, 'r', theareas, theprojstddevs, 'k', basex=10)
    roisubplot.grid(True)
    #roiplot.title(thelabel)
    return()
Exemplo n.º 10
0
def showvals(xvecs,yvecs,legendvec,specvals,thelabel,dolegend):
    numxs=len(xvecs)
    numys=len(yvecs)
    numlegends=len(legendvec)
    numspecvals=len(specvals)
    if (numxs!=numys) or (numxs!=numlegends) or (numxs!=numspecvals):
	print "dimensions do not match"
	exit(1)
    w, h = P.figaspect(0.50)
    roiplot = P.figure(figsize=(w,h))
    roisubplot = roiplot.add_subplot(111)
    if numys==1:
        roisubplot.plot(xvecs[0], yvecs[0], specvals[0])
        hold(True)
        if dolegend:
            legend(legendvec)
        hold(False)
    if numys==2:
        roisubplot.plot(xvecs[0], yvecs[0], specvals[0], xvecs[1], yvecs[1], specvals[1])
        hold(True)
        if dolegend:
            legend(legendvec)
        hold(False)
    if numys==3:
        roisubplot.plot(xvecs[0], yvecs[0], specvals[0], xvecs[1], yvecs[1], specvals[1], xvecs[2], yvecs[2], specvals[2])
        hold(True)
        if dolegend:
            legend(legendvec)
        hold(False)
    if numys==4:
        roisubplot.plot(xvecs[0], yvecs[0], specvals[0], xvecs[1], yvecs[1], specvals[1], xvecs[2], yvecs[2], specvals[2], xvecs[3], yvecs[3], specvals[3])
        hold(True)
        if dolegend:
            legend(legendvec)
        hold(False)
    if numys==5:
        roisubplot.plot(xvecs[0], yvecs[0], specvals[0], xvecs[1], yvecs[1], specvals[1], xvecs[2], yvecs[2], specvals[2], xvecs[3], yvecs[3], specvals[3], xvecs[4], yvecs[4], specvals[4])
        hold(True)
        if dolegend:
            legend(legendvec)
        hold(False)
    if numys==6:
        roisubplot.plot(xvecs[0], yvecs[0], specvals[0], xvecs[1], yvecs[1], specvals[1], xvecs[2], yvecs[2], specvals[2], xvecs[3], yvecs[3], specvals[3], xvecs[4], yvecs[4], specvals[4], xvecs[5], yvecs[5], specvals[5])
        hold(True)
        if dolegend:
            legend(legendvec)
        hold(False)
    roisubplot.grid(True)
    for tick in roisubplot.xaxis.get_major_ticks():
        tick.label1.set_fontsize(20)
    for tick in roisubplot.yaxis.get_major_ticks():
        tick.label1.set_fontsize(20)
    roisubplot.set_title(thelabel,fontsize=30)
    return()
Exemplo n.º 11
0
def showtc2(thexvals,theyvals,thefitvals,thelabel):
    w, h = P.figaspect(0.25)
    roiplot = P.figure(figsize=(w,h))
    roisubplot = roiplot.add_subplot(111)
    roisubplot.plot(thexvals, theyvals, 'b', thexvals, thefitvals, 'g')
    roisubplot.grid(True)
    #roisubplot.axes.Subplot.set_pad(0.1)
    for tick in roisubplot.xaxis.get_major_ticks():
        tick.label1.set_fontsize(20)
    for tick in roisubplot.yaxis.get_major_ticks():
        tick.label1.set_fontsize(20)
    roisubplot.set_title(thelabel,fontsize=30)
    return()
Exemplo n.º 12
0
    def _make_figure(self):
        num_sub_plots = len(self.sub_data)
        sub_rect = []
        if num_sub_plots ==0:
            fig = pylab.figure()
        if num_sub_plots == 1:
            w, h = pylab.figaspect(0.5)
            fig = pylab.figure(figsize=(w,h))
            main_rect = [0.20, 0.23, 0.78, 0.72]
            sub_rect.append([0.20, 0.09, 0.78, 0.12])
        if num_sub_plots == 2:
            w, h = 1.4*pylab.figaspect(0.7)
            fig = pylab.figure(figsize=(w,h))
            main_rect = [0.20, 0.35, 0.78, 0.62]
            sub_rect.append([0.20, 0.09, 0.78, 0.12])
            sub_rect.append([0.20, 0.22, 0.78, 0.12])
            

        fig = self._make_main_plot(fig, main_rect)
        if num_sub_plots > 0:
            fig = self._make_sub_plot(fig, sub_rect)
        self._add_text(fig)
Exemplo n.º 13
0
 def plot3Dgrains(data,
                  dim,
                  view=None,
                  label=None,
                  data2=None,
                  label2=None):
     """
 Plots xyz of grains in 3D
 Jette Oddershede March 4th 2009
 """
     if view == "z":
         elev = 90
         azim = 270
     elif view == "y":
         elev = 0
         azim = 270
     else:
         elev = 0
         azim = 0
     fig = pl.figure(figsize=pl.figaspect(1.0))
     ax = p3.Axes3D(fig)
     #plot data
     color = []
     for i in range(data.nrows):
         color.append([data.red[i], data.green[i], data.blue[i]])
     cax = ax.scatter3D(data.x, data.y, data.z, s=data.size, c=color)
     if data2 != None:
         color2 = []
         for i in range(data2.nrows):
             color2.append([data2.red[i], data2.green[i], data2.blue[i]])
         ax.scatter3D(data2.x, data2.y, data2.z, s=data2.size, c=color)
     ax.set_xlabel('x')
     ax.set_ylabel('y')
     ax.set_zlabel('z')
     ax.set_xlim3d(-dim, dim)
     ax.set_ylim3d(-dim, dim)
     ax.set_zlim3d(-dim, dim)
     ax.view_init(elev, azim)
     if label != None:
         for i in range(data.nrows):
             ax.text(data.x[i], data.y[i], data.z[i],
                     '%i' % (data.grainno[i]))
     if data2 != None:
         if label2 != None:
             for i in range(data2.nrows):
                 ax.text(data2.x[i], data2.y[i], data2.z[i],
                         '%i' % (data2.grainno[i]))
     pl.title('%s    %s' % (options.input, options.sym))
     pl.show()
Exemplo n.º 14
0
def main():
    '''Exemple d'utilisation de la fonction d'affichage d'un astre phase vue depuis la Terre'''
    w,h = pylab.figaspect(1.)
    fig = pylab.figure(figsize = (int(2. * w), int(2. * h)))
    ax = fig.add_subplot(111, axisbg = '0.1') # 0.1 c'est gris fonce
    pylab.xlabel('alt')
    pylab.ylabel('az')
    astre = ephem.Moon()
    obs = ephem.city('Paris')
    obs.date = '2013/3/16 21:000:00'
    astre.compute(obs)
    pylab.title('Moon Phase ('+str(astre.phase)+') - '+str(obs.date))
    # ra_dec = False : Apparent topocentric position represented by the properties : ra and dec, and alt and az.
    object_phase (ax, obs, False, astre, astre.alt * 180. / math.pi, astre.az * 180. / math.pi, astre.size / 1000., '0.2', '0.85')
    pylab.autoscale()
    pylab.show()
Exemplo n.º 15
0
def plot_all(x_outliers, y_outliers, x_model, y_model, data, counter):
    """Plotting the data. Outliers shown in red. Linear model shown as dotted
    line.

    :param x_outliers: list, outlier IDs (str)
    :param y_outliers: list, outlier IDs (str)
    :param x_model: array_like, linear model
    :param y_model: array_like, linear model
    :param data: np array, the data
    :param counter: int, counter keeping track of iterations
    :return: None
    """
    w, h = plt.figaspect(1.5)
    fig = plt.figure(figsize=(w, h))
    ax = fig.add_subplot(211)
    ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
    ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
    smooth_x = np.linspace(min(data["xval"]), max(data["xval"]), 1000)
    smooth_y = np.linspace(min(data["yval"]), max(data["yval"]), 1000)
    plt.plot(data["xval"], data["yval"], "ok", markersize=6)
    plt.plot(smooth_x, x_model(smooth_x), "--k", linewidth=2.5)
    for outlier in x_outliers:
        index = np.where(data["name"] == outlier)[0][0]
        plt.plot(data["xval"][index], data["yval"][index], "or", markersize=6)
    plt.tick_params(width=2, labelsize=14)
    plt.axis([0, 1.1 * max(data["xval"]), 0, 1.1 * max(data["yval"])])
    plt.xlabel("Independent Variables", fontsize=14)
    plt.ylabel("Dependent Variables", fontsize=14)
    ax = fig.add_subplot(212)
    ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
    ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))
    plt.plot(data["yval"], data["xval"], "ok", markersize=6)
    plt.plot(smooth_y, y_model(smooth_y), "--k", linewidth=2.5)
    for outlier in y_outliers:
        index = np.where(data["name"] == outlier)[0][0]
        plt.plot(data["yval"][index], data["xval"][index], "or", markersize=6)
    plt.tick_params(width=2, labelsize=14)
    plt.axis([0, 1.1 * max(data["yval"]), 0, 1.1 * max(data["xval"])])
    plt.xlabel("Independent Variables", fontsize=14)
    plt.ylabel("Dependent Variables", fontsize=14)
    plt.subplots_adjust(left=0.2, hspace=0.5)
    sns.despine()
    plt.savefig(os.getcwd() + "/" + "swap_round" + str(counter) + ".png")
Exemplo n.º 16
0
 def __init__(self, data, x, y, slice_idx, cmap=P.cm.gray,
              norm=None, interpolation="bilinear", extent=None):
     self.norm = norm
     self.cmap = cmap        
     self.interpolation=interpolation
     self.slice_idx = slice_idx
     # extent should be static, so set it and leave it alone
     if not extent:
         y,x = data.shape[-2:]
         extent = [-x/2., x/2., -y/2., y/2.]
     self.extent = extent
     self.ylim = tuple(extent[2:])
     self.xlim = tuple(extent[:2])
     fig = P.Figure(figsize=P.figaspect(data), dpi=80)
     ax = fig.add_subplot(111)
     ax.yaxis.tick_right()
     ax.title.set_y(1.05) 
     FigureCanvas.__init__(self, fig)
     self.setData(data)
     self._init_crosshairs(x, y)
Exemplo n.º 17
0
    def TrialsSoFar(self, S):
        """
        Make a scatter plot of all the trials simulated so far (in terms of
        Jx / Jz and d / Jz
        """
        trialList = scipy.array([[key[1], key[3]] for key in self.x.keys() if key[0] == S])
        fig = pylab.figure(figsize=pylab.figaspect(0.5))

        x = trialList[:, 0]
        y = trialList[:, 1]
        m = max(max(abs(x)), max(abs(y)))

        #   All of them
        p = fig.add_subplot(121)
        p.vlines(0, -m, m, "k")
        p.hlines(0, -m, m, "k")
        p.plot(x, y, linestyle="", marker="o", color="b", mec="k", mew=2, ms=7)
        p.grid(True)
        p.set_xlim(-m, m)
        p.set_ylim(-m, m)
        p.set_xlabel("$J_x / J_z$")
        p.set_ylabel("$d / J_z$")
        p.set_title("All simulated trials")

        #   The small values
        p1 = fig.add_subplot(122)
        p1.vlines(0, -1.5, 1.5, "k")
        p1.hlines(0, -1.5, 1.5, "k")
        p1.plot(x, y, linestyle="", marker="o", color="b", mec="k", mew=2, ms=7)
        p1.grid(True)
        p1.set_xlim(-1.5, 1.5)
        p1.set_ylim(-1.5, 1.5)
        p1.set_xlabel("$J_x / J_z$")
        p1.set_ylabel("$d / J_z$")
        p1.set_title('"Small" trials')

        fig.show()
Exemplo n.º 18
0
    def debug_plot(self, n=40, show_pdf=False, azim=210, elev=30):
        #Z = self.cdf(f.get_piecewise_cdf()(X), g.get_piecewise_cdf()(Y))
        #Z = self.jcdf(f, g, X, Y)
        if self.marginals is not None and len(self.marginals) > 1:
            f, g = self.marginals[:2]
            self.setMarginals((f, g))
        else:
            f, g = UniformDistr(), UniformDistr()

        Lf, Uf = f.ci(0.01)
        Lg, Ug = g.ci(0.01)
        deltaf = (Uf - Lf) / n
        deltag = (Ug - Lg) / n
        X, Y = meshgrid(arange(Lf, Uf, deltaf), arange(Lg, Ug, deltag))
        if not show_pdf:
            Z = self.cdf(X, Y)
            fig = figure(figsize=plt.figaspect(1))
            ax = fig.add_subplot(111, projection='3d', azim=azim, elev=elev)
            #ax = p3.Axes3D(fig)
            xf = arange(Lf, Uf, deltaf)
            xg = arange(Lg, Ug, deltag)
            cf = f.cdf(xf)
            cg = g.cdf(xg)
            ax.plot(xf, cf, zs=Ug, zdir='y', linewidth=3.0, color="k")
            ax.plot(xg, cg, zs=Uf, zdir='x', linewidth=3.0, color="k")
            ax.plot_wireframe(X,
                              Y,
                              Z,
                              rstride=1,
                              cstride=1,
                              color='k',
                              antialiased=True)  #cmap=cm.jet
            cset = ax.contour(X, Y, Z, zdir='z', color='k', offset=0)
            ax.set_xlabel('$X$')
            ax.set_xlim3d(Lf, Uf)
            ax.set_ylabel('$Y$')
            ax.set_ylim3d(Lg, Ug)
            ax.set_zlabel('$Z$')
            ax.set_zlim3d(0, 1)
        else:
            fig = figure(figsize=plt.figaspect(1))
            ax2 = fig.add_subplot(111, projection='3d', azim=azim, elev=elev)
            Z2 = self.pdf(X, Y)
            xf = arange(Lf, Uf, deltaf)
            xg = arange(Lg, Ug, deltag)
            cf = f.pdf(xf)
            cg = g.pdf(xg)
            ax2.plot(xf, cf, zs=Ug, zdir='y', linewidth=3.0, color="k")
            ax2.plot(xg, cg, zs=Uf, zdir='x', linewidth=3.0, color="k")
            ax2.plot_wireframe(X,
                               Y,
                               Z2,
                               rstride=1,
                               cstride=1,
                               color='k',
                               antialiased=True)
            cset = ax2.contour(X, Y, Z2, color='k', zdir='z', offset=0)
            ax2.set_xlabel('$X$')
            ax2.set_xlim3d(Lf, Uf)
            ax2.set_ylabel('$Y$')
            ax2.set_ylim3d(Lg, Ug)
            ax2.set_zlabel('$Z$')
            zlim = 1.01 * np.max(array([np.max(Z2), max(cf), max(cg)]))
            ax2.set_zlim3d(0, zlim)
Exemplo n.º 19
0
# ax.plot_surface(X, Y, Z[:, 2].reshape(n_points_per_grid, n_points_per_grid))

# отрисовка каждой точки
# for z in np.vsplit(Z, n_points_per_grid):
#     ax.plot3D(z[:, 0], z[:, 1], z[:, 2])

# Z = f(np.dot(cartesian.T, w))
# # Z = np.sin(np.sqrt(X ** 2 + Y ** 2))
# Z = X * w[0] + Y * w[1] + 1 * w[2]
# Z = np.dot(X, w[0]) + np.dot(Y, w[1]) + np.dot(1, w[2])
# Z = np.einsum('ijk,jk->ij', np.array([X, Y, 1]), w)
# Z = f(np.dot(np.array([X, Y, 1]), w))

Z = f(X * w[0] + Y * w[1] + 1 * w[2])

fig = plt.figure(figsize=plt.figaspect(1 / 2.5))
ax1 = fig.add_subplot('121', projection='3d')

ax1.plot_surface(X, Y, Z, cmap=cm.coolwarm)

ax1.set_xlabel('x'), ax1.set_ylabel('y'), ax1.set_zlabel('z')

ax2 = fig.add_subplot('122', projection='3d')
ax2.plot_wireframe(X, Y, Z, rstride=10, cstride=3)

ax2.contour(X, Y, Z, zdir='z', offset=0, cmap=cm.coolwarm)
ax2.contour(X, Y, Z, zdir='x', offset=x_lim[0], cmap=cm.coolwarm)
ax2.contour(X, Y, Z, zdir='y', offset=y_lim[1], cmap=cm.coolwarm)

# ax = Axes3D(fig)
# ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2], color='g')
Exemplo n.º 20
0
    def SimpleSliceMeasurement_3D(
        self, sliceString, measurementToken, fixedVals, TwoToRNormalization=False, varRange="All", szSubset="All"
    ):
        """
        Given a sliceString option from:
            'S', 'Jx', 'd', or 'gen'
        and a measurementToken option from:
            SZ, SZ2, SIPSCM, SIMSCP, SIZSCZ, SIDOTSC
        plot the simple 1-d measurements for each spin value, as a 3D plot
        """
        if sliceString == "S":
            plotDic, keyList, varList = self.S_Slice(fixedVals)
        elif sliceString == "Jx":
            plotDic, keyList, varList = self.Jx_Slice(fixedVals)
        elif sliceString == "d":
            plotDic, keyList, varList = self.D_Slice(fixedVals)
        elif sliceString == "gen":
            plotDic, keyList, varList = self.Gen_Slice(fixedVals)
        else:
            raise ValueError, "Not an acceptable sliceString. Options are:\n\t'S'\n\t'Jx'\n\t'd'\n\t'gen'"

        #   To deal with normalization, we want to multiply the values of
        #   all two-point correlation functions by 2^R
        twoPointCorrIndices = [SIPSCM, SIMSCP, SIZSCZ, SIDOTSC]
        if measurementToken in twoPointCorrIndices:
            labelAppendText = "$\\times 2^R$"
        else:
            labelAppendText = ""

        #   We now have a dictionary of the type
        #       { trial : { gen : { sz : array, ... }, ... }, ... }
        #   pull it apart as requested.

        #   Let's make subplots for each Sz value represented, limited to those
        #   given in szSubset
        szList = []
        for key in plotDic:
            for sz in plotDic[key]:
                if sz not in szList:
                    szList.append(sz)
        szList = sorted(szList)

        if szSubset != "All":
            i = 0
            while i < len(szList):
                if szList[i] not in szSubset:
                    tossVal = szList.pop(i)
                else:
                    i += 1

        #   Plotting basics
        f = pylab.figure(figsize=pylab.figaspect(len(szList)))
        colorList = ["blue", "green", "red", "cyan", "magenta", "gold", "black"]
        lineStyleList = ["-", "--", "-.", ".."]
        markerList = ["o", "^", "+", "D", "v", "x", "s"]

        for i in range(len(szList)):
            axNow = Axes3D(f, rect=[0, float(i) / len(szList), 1, 1.0 / len(szList)])
            sz = szList[i]

            for j in range(len(keyList)):

                #   We saved all the keys in a sorted order in FOO_Slice()
                key = tuple(keyList[j])
                var = varList[j]

                if varRange != "All":
                    varMin, varMax = sorted(varRange)
                    continueBool = (varMin <= var) and (var <= varMax)
                else:
                    continueBool = True

                trial = key[:4]
                gen = key[4]

                if sz in plotDic[key] and continueBool:

                    A = plotDic[key][sz].copy()

                    try:
                        #   Formatting each trial / generation combo
                        #   distinctly (but the same across Sz values)
                        colorNow = colorList[j % len(colorList)]
                        markerNow = markerList[j % len(markerList)]
                        lineStyleNow = lineStyleList[(j / len(colorList)) % len(lineStyleList)]

                        if TwoToRNormalization and measurementToken in twoPointCorrIndices:
                            multArray = 2 ** A[:, R]
                        else:
                            multArray = scipy.ones(len(A))

                        varVal = var * scipy.ones(len(A))
                        axNow.plot(
                            varVal,
                            A[:, R],
                            multArray * A[:, measurementToken],
                            color=colorNow,
                            linewidth=2,
                            marker=markerNow,
                            mec=colorNow,
                            mfc="w",
                            mew=2,
                            linestyle=lineStyleNow,
                            label=sliceString + " = " + str(var),
                        )

                        if TwoToRNormalization and measurementToken in twoPointCorrIndices:
                            axNow.set_ylim(-2, 2)

                    except IndexError:
                        print LABEL_DIC[measurementToken] + " measurement not made for trial " + str(trial)

            axNow.set_xlabel(sliceString)
            axNow.set_ylabel("$R$")
            axNow.set_zlabel(TEX_LABEL_DIC[measurementToken] + labelAppendText)
            axNow.set_title(TEX_LABEL_DIC[measurementToken] + " in the $S^z = " + str(sz) + "$ sector")
            axNow.legend()
Exemplo n.º 21
0
    def read(file, sym, minimum, maximum, step):
        data = ic.columnfile('%s.gff' % file)
        #grain sizes
        if "grainno" not in data.titles:
            data.addcolumn(data.grain_id, 'grainno')
        if "grainvolume" in data.titles:
            scale = max(data.grainvolume**0.3333)
            data.addcolumn(data.grainvolume**0.3333 / scale * 100, 'size')
        else:
            data.addcolumn(100. * np.ones(data.nrows), 'size')
        rodx = []
        rody = []
        rodz = []
        if "rodx" not in data.titles:
            for i in range(data.nrows):
                U = np.array([[data.U11[i], data.U12[i], data.U13[i]],
                              [data.U21[i], data.U22[i], data.U23[i]],
                              [data.U31[i], data.U32[i], data.U33[i]]])
                rod = tools.u_to_rod(U)
                rodx.append(rod[0])
                rody.append(rod[1])
                rodz.append(rod[2])
            data.addcolumn(np.array(rodx), 'rodx')
            data.addcolumn(np.array(rody), 'rody')
            data.addcolumn(np.array(rodz), 'rodz')
        if sym == "standard":
            #grain colours, so that all orientations in Cubic space are allowed
            maxhx = 62.8 * 3.14 / 180
            minhx = -62.8 * 3.14 / 180
            maxhy = 62.8 * 3.14 / 180
            minhy = -62.8 * 3.14 / 180
            maxhz = 62.8 * 3.14 / 180
            minhz = -62.8 * 3.14 / 180
            rr = data.rodx**2 + data.rody**2 + data.rodz**2
            rr = np.sqrt(rr)
            theta = 2 * np.arctan(rr)
            r1 = data.rodx / rr
            r2 = data.rody / rr
            r3 = data.rodz / rr
            # normalise colours
            red = (r1 * theta - minhx) / (maxhx - minhx)
            green = (r2 * theta - minhy) / (maxhy - minhy)
            blue = (r3 * theta - minhz) / (maxhz - minhz)
        elif sym == "orthorhombic":
            # Fill orthorhombic stereographic triangle
            red = []
            green = []
            blue = []
            fig = pl.figure(10, frameon=False, figsize=pl.figaspect(1.0))
            ax = pl.Axes(fig, [.2, .2, .7, .7])
            ax.set_axis_off()
            fig.add_axes(ax)
            #plot triangle
            xa = np.zeros((101))
            ya = np.zeros((101))
            for i in range(101):
                xa[i] = np.cos(i * np.pi / 200.)
                ya[i] = np.sin(i * np.pi / 200.)
            pl.plot(xa, ya, 'black')  # Curved edge
            pl.plot([0, 1], [0, 0], 'black', linewidth=2)  #lower line
            pl.plot([0, 0], [1, 0], 'black', linewidth=2)  #left line
            pl.text(-0.02, -0.04, '[001]')
            pl.text(0.95, -0.04, '[100]')
            pl.text(-0.02, 1.01, '[010]')
            # Grains
            for i in range(data.nrows):
                U = tools.rod_to_u([data.rodx[i], data.rody[i], data.rodz[i]])
                axis = abs(U[2, :])
                colour = np.zeros((3))
                colour[0] = (2 * np.arcsin(abs(axis[2])) / np.pi)**1
                colour[1] = (2 * np.arcsin(abs(axis[0])) / np.pi)**1
                colour[2] = (2 * np.arcsin(abs(axis[1])) / np.pi)**1
                mx = max(colour)
                colour = colour / mx
                red.append(colour[0])
                green.append(colour[1])
                blue.append(colour[2])
                X = axis[0] / (1 + axis[2])
                Y = axis[1] / (1 + axis[2])
                pl.plot(X, Y, 'o', color=colour)
            pl.xlim()
        elif sym == "cubic":
            # Fill cubic stereographic triangle
            red = []
            green = []
            blue = []
            fig = pl.figure(10, frameon=False, figsize=pl.figaspect(.9))
            ax = pl.Axes(fig, [.2, .2, .7, .7])
            ax.set_axis_off()
            fig.add_axes(ax)
            #plot triangle
            xa = np.zeros((21))
            ya = np.zeros((21))
            for i in range(21):
                ua = np.array([i / 20., 1., 1.])
                UA = np.linalg.norm(ua)
                za = ua[2] + UA
                xa[i] = ua[1] / za
                ya[i] = ua[0] / za
            pl.plot(xa, ya, 'black')  # Curved edge
            pl.plot([0, xa[0]], [0, 0.0001], 'black', linewidth=2)  #lower line
            pl.plot([xa[20], 0], [ya[20], 0], 'black')  # upper line
            pl.text(-0.01, -0.02, '[100]')
            pl.text(xa[0] - 0.01, -0.02, '[110]')
            pl.text(xa[-1] - 0.01, ya[-1] + 0.005, '[111]')
            # Grains
            for i in range(data.nrows):
                U = tools.rod_to_u([data.rodx[i], data.rody[i], data.rodz[i]])
                axis = abs(U[2, :])
                colour = np.zeros((3))
                for j in range(3):
                    for k in range(j + 1, 3):
                        if (axis[j] > axis[k]):
                            colour[0] = axis[j]
                            axis[j] = axis[k]
                            axis[k] = colour[0]
                rr = np.sqrt(axis[0] * axis[0] / ((axis[2] + 1)) /
                             ((axis[2] + 1)) + (axis[1] / (axis[2] + 1) + 1) *
                             (axis[1] / (axis[2] + 1) + 1))
                if axis[1] == 0:
                    beta = 0
                else:
                    beta = np.arctan(axis[0] / axis[1])
                colour[0] = ((np.sqrt(2.0) - rr) / (np.sqrt(2.0) - 1))**.5
                colour[1] = ((1 - 4 * beta / np.pi) * ((rr - 1) /
                                                       (np.sqrt(2.0) - 1)))**.5
                colour[2] = (4 * beta / np.pi * ((rr - 1) /
                                                 (np.sqrt(2.0) - 1)))**.5
                mx = max(colour)
                colour = colour / mx
                red.append(colour[0])
                green.append(colour[1])
                blue.append(colour[2])
                X = axis[1] / (1 + axis[2])
                Y = axis[0] / (1 + axis[2])
                pl.plot(X, Y, 'o', color=colour)
            pl.xlim()
        elif sym == "hexagonal":

            ## Fill hexagonal stereographic triangle
            A = np.array([[0, 1, 0], [0, -np.sqrt(3), 1], [1, 0, 0]])

            a0 = 1. / np.sqrt(3.)
            a1 = 1.
            a2 = 1.

            red = []
            green = []
            blue = []

            fig = pl.figure(10, frameon=False, figsize=pl.figaspect(0.5))
            ax = pl.Axes(fig, [0.2, .2, 0.6, 0.6])
            ax.set_axis_off()
            fig.add_axes(ax)

            ## Plot triangle
            ya = np.array(list(range(51))) / 100.
            xa = np.sqrt(1 - ya**2)
            pl.plot(xa, ya, 'black')  # Curved edge
            pl.plot([0, xa[0]], [0, 0.0001], 'black', linewidth=2)  #lower line
            pl.plot([xa[-1], 0], [ya[-1], 0], 'black')  # upper line

            ## Label crystalographic directions
            pl.text(-0.01, -0.02, '[0001]')
            pl.text(xa[0] - 0.03, -0.02, '[2-1-10]')
            pl.text(xa[-1] - 0.03, ya[-1] + 0.005, '[10-10]')

            ## Grains
            r = symmetry.rotations(6)

            for i in range(data.nrows):

                U = tools.rod_to_u([data.rodx[i], data.rody[i], data.rodz[i]])

                square = 1
                angle = 0
                frac = 1. / np.sqrt(3.)

                for k in range(len(r)):

                    g = np.dot(U, r[k])
                    a = np.arccos((np.trace(g) - 1) / 2)

                    if g[2, 2] > 0:
                        uvw = g[2, :]
                    else:
                        uvw = -g[2, :]

                    ## needed to switch these indices to get correct color and inv pf location
                    switch1 = uvw[0]
                    switch2 = uvw[1]
                    uvw[0] = switch2
                    uvw[1] = switch1

                    x = uvw[0] / (1 + uvw[2])
                    y = uvw[1] / (1 + uvw[2])

                    f = y / x
                    s = x * x + y * y

                    ## Finds r (symmetry) which plots grain into triangle
                    if f <= frac and s <= square and x >= 0 and y >= 0:
                        angle = a
                        frac = f
                        square = s
                        UVW = uvw
                        X = x
                        Y = y

                colour = np.dot(np.transpose(A), np.transpose(UVW))**0.7

                colour[0] = colour[0] / a2
                colour[1] = colour[1] / a1
                colour[2] = colour[2] / a0
                mx = max(colour)
                colour = colour / mx

                red.append(colour[0])
                green.append(colour[1])
                blue.append(colour[2])

                pl.plot(X, Y, 'o', color=colour)
            pl.xlim()
        elif sym == "e11":
            try:
                colourbar(minimum, maximum, step, 'e-3')
                norm = colors.normalize(minimum * 1e-3, maximum * 1e-3)
            except:
                colourbar(-1, 1, 1, 'e-3')
                norm = colors.normalize(-1e-3, 1e-3)
            color = cm.jet(norm(data.eps11_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "transverse strain:",
                np.sum(data.grainvolume * data.eps11_s) /
                np.sum(data.grainvolume))
        elif sym == "e22":
            try:
                colourbar(minimum, maximum, step, 'e-3')
                norm = colors.normalize(minimum * 1e-3, maximum * 1e-3)
            except:
                colourbar(-1, 1, 1, 'e-3')
                norm = colors.normalize(-1e-3, 1e-3)
            color = cm.jet(norm(data.eps22_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "transverse strain:",
                np.sum(data.grainvolume * data.eps22_s) /
                np.sum(data.grainvolume))
        elif sym == "e33":
            try:
                colourbar(minimum, maximum, step, 'e-3')
                norm = colors.normalize(minimum * 1e-3, maximum * 1e-3)
            except:
                colourbar(-1, 1, 1, 'e-3')
                norm = colors.normalize(-1e-3, 1e-3)
            color = cm.jet(norm(data.eps33_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "axial strain:",
                np.sum(data.grainvolume * data.eps33_s) /
                np.sum(data.grainvolume))
        elif sym == "e12":
            try:
                colourbar(minimum, maximum, step, 'e-3')
                norm = colors.normalize(minimum * 1e-3, maximum * 1e-3)
            except:
                colourbar(-1, 1, 1, 'e-3')
                norm = colors.normalize(-1e-3, 1e-3)
            color = cm.jet(norm(data.eps12_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "shear strain:",
                np.sum(data.grainvolume * data.eps12_s) /
                np.sum(data.grainvolume))
        elif sym == "e13":
            try:
                colourbar(minimum, maximum, step, 'e-3')
                norm = colors.normalize(minimum * 1e-3, maximum * 1e-3)
            except:
                colourbar(-1, 1, 1, 'e-3')
                norm = colors.normalize(-1e-3, 1e-3)
            color = cm.jet(norm(data.eps13_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "shear strain:",
                np.sum(data.grainvolume * data.eps13_s) /
                np.sum(data.grainvolume))
        elif sym == "e23":
            try:
                colourbar(minimum, maximum, step, 'e-3')
                norm = colors.normalize(minimum * 1e-3, maximum * 1e-3)
            except:
                colourbar(-1, 1, 1, 'e-3')
                norm = colors.normalize(-1e-3, 1e-3)
            color = cm.jet(norm(data.eps23_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "shear strain:",
                np.sum(data.grainvolume * data.eps23_s) /
                np.sum(data.grainvolume))
        elif sym == "s33":
            try:
                colourbar(minimum, maximum, step, 'MPa')
                norm = colors.normalize(minimum, maximum)
            except:
                colourbar(-50, 150, 50, 'MPa')
                norm = colors.normalize(-50, 150)
            color = cm.jet(norm(data.sig33_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "axial stress:",
                np.sum(data.grainvolume * data.sig33_s) /
                np.sum(data.grainvolume), "MPa")
        elif sym == "s11":
            try:
                colourbar(minimum, maximum, step, 'MPa')
                norm = colors.normalize(minimum, maximum)
            except:
                colourbar(-50, 150, 50, 'MPa')
                norm = colors.normalize(-50, 150)
            color = cm.jet(norm(data.sig11_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "transverse s11 stress:",
                np.sum(data.grainvolume * data.sig11_s) /
                np.sum(data.grainvolume), "MPa")
        elif sym == "s22":
            try:
                colourbar(minimum, maximum, step, 'MPa')
                norm = colors.normalize(minimum, maximum)
            except:
                colourbar(-50, 150, 50, 'MPa')
                norm = colors.normalize(-50, 150)
            color = cm.jet(norm(data.sig22_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "transverse s22 stress:",
                np.sum(data.grainvolume * data.sig22_s) /
                np.sum(data.grainvolume), "MPa")
        elif sym == "s12":
            try:
                colourbar(minimum, maximum, step, 'MPa')
                norm = colors.normalize(minimum, maximum)
            except:
                colourbar(-50, 50, 50, 'MPa')
                norm = colors.normalize(-50, 50)
            color = cm.jet(norm(data.sig12_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "shear s12 stress:",
                np.sum(data.grainvolume * data.sig12_s) /
                np.sum(data.grainvolume), "MPa")
        elif sym == "s13":
            try:
                colourbar(minimum, maximum, step, 'MPa')
                norm = colors.normalize(minimum, maximum)
            except:
                colourbar(-50, 50, 50, 'MPa')
                norm = colors.normalize(-50, 50)
            color = cm.jet(norm(data.sig13_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "shear s13 stress:",
                np.sum(data.grainvolume * data.sig13_s) /
                np.sum(data.grainvolume), "MPa")
        elif sym == "s23":
            try:
                colourbar(minimum, maximum, step, 'MPa')
                norm = colors.normalize(minimum, maximum)
            except:
                colourbar(-50, 50, 50, 'MPa')
                norm = colors.normalize(-50, 50)
            color = cm.jet(norm(data.sig23_s))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(
                "shear s23 stress:",
                np.sum(data.grainvolume * data.sig23_s) /
                np.sum(data.grainvolume), "MPa")
        elif sym == "latt_rot":
            norm = colors.normalize(0, 0.5)
            color = cm.jet(norm(data.latt_rot))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            colourbar(0.0, 0.5, 0.1, 'deg')
        elif sym == "tz":
            norm = colors.normalize(-0.1, 0.1)
            color = cm.jet(norm(data.tz))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
        elif sym == "vol":
            norm = colors.normalize(0, 10)
            color = cm.jet(norm(data.grainvolume / data.d_grainvolume))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
        elif sym == "tth":
            norm = colors.normalize(0.007, 0.009)
            color = cm.jet(norm(data.sig_tth / data.grainvolume**.2))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(min(data.sig_tth / data.grainvolume**.2),
                  max(data.sig_tth / data.grainvolume**.2))
#        pl.figure(8)
#        pl.plot(np.log(data.grainvolume),np.log(data.sig_tth),'.')
        elif sym == "eta":
            norm = colors.normalize(0.08, 0.15)
            color = cm.jet(norm(data.sig_eta / data.grainvolume**.2))
            red = color[:, 0]
            green = color[:, 1]
            blue = color[:, 2]
            print(min(data.sig_eta / data.grainvolume**.2),
                  max(data.sig_eta / data.grainvolume**.2))
#        pl.figure(8)
#        pl.plot(np.log(data.grainvolume),np.log(data.sig_eta),'.')
        else:
            np.random.seed(0)
            red = np.random.rand(data.nrows)
            np.random.seed(1)
            green = np.random.rand(data.nrows)
            np.random.seed(2)
            blue = np.random.rand(data.nrows)
        data.addcolumn(red, 'red')
        data.addcolumn(green, 'green')
        data.addcolumn(blue, 'blue')
        return (data)
for i in m_sender:
    
    X.append( m_data['times'][(m_data['senders'] == i)])
    Y.append( (np.ones((1,len(m_time)))*i -pl.amin(z)).tolist()[0] )
    Z.append( m_data['V_m'][(m_data['senders'] == i)])
    G = Gauss(pl.arange(-20,20,resl),1.2)
    smooth = np.convolve(m_data['V_m'][(m_data['senders'] == i)]-E_L,G,'same')
    Z_conv.append(smooth+E_L)

X,Y,Z,Z_conv= np.array(X),np.array(Y),np.array(Z) ,np.array(Z_conv)

from mpl_toolkits.mplot3d import Axes3D


fig=pl.figure(2,figsize=pl.figaspect(0.5))
#---- First subplot
ax= fig.add_subplot(121,projection='3d')
surf = ax.plot_surface(X,Y,Z,cmap=pl.cm.jet,linewidth=0,rstride=5, )
fig.colorbar(surf)
pl.xlim([0.0,1000.])
pl.ylim([0,pop])
ax.set_zlim(-70.,-40.)
ax.view_init(azim=0, elev=90) # set view angle normal to X-Y plane
ax.set_xlabel('ms')
ax.set_ylabel('neuron id ')
ax.set_zlabel('V_m')
pl.title('V_m')

#---- Second subplot
ax2 = fig.add_subplot(122, projection='3d')
Exemplo n.º 23
0
    def __init__(self,
                 vars,
                 title=None,
                 figaspect=1.0,
                 cmap=None,
                 colorbar=None,
                 axes=None,
                 log=False,
                 **kwlimits):
        """
        Create a `AbstractMatplotlibViewer`.
        
        :Parameters:
          vars
            a `CellVariable` or tuple of `CellVariable` objects to plot
          title
            displayed at the top of the `Viewer` window
          figaspect
            desired aspect ratio of figure. If arg is a number, use that aspect
            ratio. If arg is an array, figaspect will determine the width and
            height for a figure that would fit array preserving aspect ratio.
          xmin, xmax, ymin, ymax, datamin, datamax
            displayed range of data. A 1D `Viewer` will only use `xmin` and
            `xmax`, a 2D viewer will also use `ymin` and `ymax`. All
            viewers will use `datamin` and `datamax`. Any limit set to a
            (default) value of `None` will autoscale.
          cmap
            the colormap. Defaults to `matplotlib.cm.jet`
          colorbar
            plot a colorbar in specified orientation if not `None`
          axes
            if not `None`, `vars` will be plotted into this Matplotlib `Axes` object
          log
            whether to logarithmically scale the data
        """
        if self.__class__ is AbstractMatplotlibViewer:
            raise NotImplementedError("can't instantiate abstract base class")

        AbstractViewer.__init__(self, vars=vars, title=title, **kwlimits)

        import pylab

        pylab.ion()

        if axes is None:
            w, h = pylab.figaspect(self.figaspect(figaspect))
            fig = pylab.figure(figsize=(w, h))
            self.axes = pylab.gca()
        else:
            self.axes = axes
            fig = axes.get_figure()

        self.id = fig.number

        self.axes.set_title(self.title)

        import matplotlib
        # Set the colormap and norm to correspond to the data for which
        # the colorbar will be used.
        if cmap is None:
            self.cmap = matplotlib.cm.jet
        else:
            self.cmap = cmap

        if colorbar:
            self.colorbar = _ColorBar(viewer=self)
        else:
            self.colorbar = None

        self.norm = None
        self.log = log
Exemplo n.º 24
0
# conditions
n_runs = 1
t_max = 100
t_steps = 10001
dt = t_max / t_steps
t = np.linspace(0, t_max, t_steps)   # time grid
position = R_p
position = [10,10,30]
#position = [random.uniform(-20, 20), random.uniform(-30, 30), random.uniform(0, 50)]
delta_max = 10 ** (-6)

# PLOTTING
plt.close('all')

# SUBPLOT 1: Trajectories and separation in x
fig1 = plt.figure(figsize=plt.figaspect(0.75))
fig1.suptitle('Lorentz model')
# trajectories
ax = fig1.add_subplot(111, projection = '3d')
qs = []
for i in range(n_runs):
    if n_runs == 1:
        q0 = position                                   # use 'position' as point
    else:
        q0 = direct_sphere(position, delta_max)        #sampling a point with d(q0, position) < delta_max
    q = odeint(f, q0, t, Dfun=Dfun).transpose()
    qs.append(q)
    ax.plot(qs[i][0], qs[i][1], qs[i][2])
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
Exemplo n.º 25
0
def three_contributions_3d():

    nx, ny = 200, 200
    E_inc, E_mixed, E_scat = generate_fields(nx, ny)

    # Generate the final image.
    E_total = E_inc + E_scat
    image = image_field(E_total, nx, ny)

    # Generate the images of the three contributions.

    image_mixed = np.sum(E_mixed, axis=0).reshape(nx, ny)
    image_inc = image_field(E_inc, nx, ny)
    image_scat = image_field(E_scat, nx, ny)

    # Plot Figure.
    X = np.arange(nx)
    Y = np.arange(ny)
    X, Y = np.meshgrid(X, Y)
    fig = pl.figure(figsize=pl.figaspect(0.33))
    cmap = 'plasma'
    vmin, vmax = -0.5, 1.0

    # Plot all three image surfaces.
    ax1 = fig.add_subplot(1, 3, 1, projection='3d')

    surf1 = ax1.plot_surface(X,
                             Y,
                             image_inc,
                             rstride=1,
                             cstride=1,
                             cmap=cmap,
                             linewidth=0,
                             antialiased=False)

    # set up the axes for the second plot
    ax2 = fig.add_subplot(1, 3, 2, projection='3d')

    surf2 = ax2.plot_surface(X,
                             Y,
                             image_mixed,
                             rstride=1,
                             cstride=1,
                             cmap=cmap,
                             linewidth=0,
                             antialiased=False)

    # set up the axes for the second plot
    ax3 = fig.add_subplot(1, 3, 3, projection='3d')

    surf3 = ax3.plot_surface(X,
                             Y,
                             image_scat,
                             rstride=1,
                             cstride=1,
                             cmap=cmap,
                             linewidth=0,
                             antialiased=False)

    # Fix views and limits.
    ax1.zaxis.set_rotate_label(False)  # disable automatic rotation
    ax1.set_zlabel('Intensity [arb]', rotation=90)
    ax1.zaxis.labelpad = 10
    for ax in [ax1, ax2, ax3]:
        ax.set_zlim(-1.0, 1.2)
        ax.view_init(elev=7.5, azim=45)

        # Get rid of colored axes planes
        ax.xaxis.pane.fill = False
        ax.yaxis.pane.fill = False
        ax.zaxis.pane.fill = False

        # Now set color to white (or whatever is "invisible")
        ax.xaxis.pane.set_edgecolor('w')
        ax.yaxis.pane.set_edgecolor('w')
        ax.zaxis.pane.set_edgecolor('w')

        ax.set_xlabel('X [pixel]')
        ax.set_ylabel('Y [pixel]')
        ax.yaxis.labelpad = 10
        ax.xaxis.labelpad = 10
        ax.set_xticks([0, 100, 200])
        ax.set_yticks([0, 100])
        ax.set_zticks([-0.5, 0.0, 0.5, 1.0])

    filename = os.path.join('../../Figures/', 'hvm_three_contributions_03.png')
    pl.savefig(filename, dpi=200)
        acc = performClassification(PPFX[:, [17, 60, 67]], PPFy,
                                    SVC(kernel='rbf', C=cval, gamma=gval),
                                    'RBF', False)
        R_PPF[c][g] = acc

        acc = performClassification(ConnX[:, [2307, 4722]], ConnY,
                                    SVC(kernel='rbf', C=cval, gamma=gval),
                                    'RBF', False)
        R_CONN[c][g] = acc

        acc = performClassification(CombX, CombY,
                                    SVC(kernel='rbf', C=cval, gamma=gval),
                                    'RBF', False)
        R_COMB[c][g] = acc

w, h = pl.figaspect(1.)
pl.figure(figsize=(w, h))
pl.subplots_adjust(left=0.15, right=0.95, bottom=0.15, top=0.95)
pl.title('C and Gamma for CCF')
pl.imshow(R_CCF, interpolation='nearest', cmap=pl.cm.spectral)
pl.xlabel('gamma')
pl.ylabel('C')
pl.colorbar()
pl.xticks(np.arange(NUMCOLS), GAMMARANGE, rotation=45)
pl.yticks(np.arange(NUMROWS), CRANGE, rotation=45)
pl.savefig('hyperparameters_estimate_plots/CCF_RBF_SET1.png')

pl.figure(figsize=(8, 8))
pl.subplots_adjust(left=0.15, right=0.95, bottom=0.15, top=0.95)
pl.title('C and Gamma for EBC')
pl.imshow(R_EBC, interpolation='nearest', cmap=pl.cm.spectral)
Exemplo n.º 27
0
    def debug_plot(self, n=40, show_pdf=False, azim=210, elev=30):
        #Z = self.cdf(f.get_piecewise_cdf()(X), g.get_piecewise_cdf()(Y))
        #Z = self.jcdf(f, g, X, Y)
        if self.marginals is not None and len(self.marginals) > 1:
            f, g = self.marginals[:2]
            self.setMarginals((f, g))
        else:
            f, g = UniformDistr(), UniformDistr()

        Lf, Uf = f.ci(0.01)
        Lg, Ug = g.ci(0.01)
        deltaf = (Uf - Lf) / n
        deltag = (Ug - Lg) / n

        X, Y = meshgrid(arange(Lf, Uf, deltaf), arange(Lg, Ug, deltag))
        if not show_pdf:
            Z = self.cdf(X, Y)
            Z2 = self.pdf(X, Y)
            fig = figure(figsize=plt.figaspect(1))
            ax = fig.add_subplot(111, projection='3d', azim=azim, elev=elev)
            #ax = p3.Axes3D(fig)
            xf = arange(Lf, Uf, deltaf)
            xg = arange(Lg, Ug, deltag)
            cf = f.cdf(xf)
            cg = g.cdf(xg)
            ax.plot(xf, cf, zs=Ug, zdir='y', linewidth=3.0, color="k")
            ax.plot(xg, cg, zs=Uf, zdir='x', linewidth=3.0, color="k")
            cset = ax.contour(X, Y, Z, zdir='z', offset=0)
            ax.plot_wireframe(X,
                              Y,
                              Z,
                              rstride=1,
                              cstride=1,
                              color='k',
                              antialiased=True)  #cmap=cm.jet
            ax.set_xlabel('$X$')
            ax.set_xlim3d(Lf, Uf)
            ax.set_ylabel('$Y$')
            ax.set_ylim3d(Lg, Ug)
            ax.set_zlabel('$Z$')
            ax.set_zlim3d(0, 1)
            # wykres F(x)=G(Y)
        else:
            fig = figure(figsize=plt.figaspect(1))
            ax = fig.add_subplot(111, projection='3d')
            #ax = fig.add_subplot(122,  projection='3d')
            t = linspace(0.01, 0.99, 40)
            X = f.quantile(t)
            Y = g.quantile(t)
            Z = f(X) * g(Y)
            cf = f.pdf(xf)
            cg = g.pdf(xg)
            ax.plot(xf, cf, zs=Ug, zdir='y', linewidth=3.0, color="k")
            ax.plot(xg, cg, zs=Uf, zdir='x', linewidth=3.0, color="k")
            ax.plot_surface(
                np.vstack([X, X]),
                np.vstack([Y, Y]),
                np.vstack([np.zeros_like(Z), Z]),
                cstride=1,
                rstride=1,  # cmap=cm.jet,
                linewidth=-1,
                edgecolor="k",
                color="c",
                alpha=0.7,
                antialiased=True)
            ax.axis((Lf, Uf, Lg, Ug))
            zlim = 1.01 * np.max(array([max(Z), max(cf), max(cg)]))
            ax.set_zlim3d(0, zlim)
Exemplo n.º 28
0
    #    tar_ = utils.filter_data(tar_, window=5, order=2)
    #    out_ = utils.filter_data(out_, window=5, order=2)

    tar.append(tar_)
    out.append(out_)

tar = np.concatenate(tar, axis=1)
out = np.concatenate(out, axis=1)

#combine cameras
#tar = average_cameras(tar)
#out = average_cameras(out)
#print(tar.shape)

# Set up a figure
fig = plt.figure(figsize=plt.figaspect(1))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
ax = fig.add_subplot(111, projection='3d')
ax.view_init(elev=30, azim=25)

writer = FFMpegWriter(fps=10)
with writer.saving(fig, "LiftPose3D_prediction.mp4", 100):
    for t in tqdm(range(900)):
        pos_pred, pos_tar = [], []

        ax.cla()

        thist = 7
        pos_pred, pos_tar = [], []
        for j in range(out.shape[1] // 3):
            tmin = max(0, t - thist + 1)
import math
import pylab as plt 
import numpy as np

def U(Q, q):
    return(0.5 * (Q ** 2 + q ** 2) + (Q ** 2) * q - q ** 3 / 3)

# Contour plot of potential
Q_lim = [-1.5, 1.5]
q_lim = [-1.5, 2.]
q_steps = 1001
Qs = np.linspace(Q_lim[0], Q_lim[1], q_steps)
qs = np.linspace(q_lim[0], q_lim[1], q_steps)
Q, q = np.meshgrid(Qs, qs)
outer = np.arange(5., 1., -0.5)
inner = [1 /(math.factorial(i)) for i in range(1, 10)]
levels = np.concatenate((outer, inner))


fig1 = plt.figure(figsize=plt.figaspect(0.5))
fig1.suptitle("Henon-Heiles system: Contour plot of potential")
ax = fig1.add_subplot(111)
cont = ax.contour(Q, q, U(Q, q), levels)
ax.clabel(cont, inline=1, fontsize=10)
ax.set_xlabel('Q')
ax.set_ylabel('q')
fig1_name = 'henon_heiles_pot_contour.png'
fig1.savefig(fig1_name)
fig1.show()
Exemplo n.º 30
0
	#Y = numpy.arange(data[['Col6']].min(), data[['Col6']].max(), (data[['Col6']].max()-data[['Col6']].min())/80)
	#Z = numpy.arange(data[['Col5']].min(), data[['Col5']].max(), (data[['Col5']].max()-data[['Col5']].min())/80)
	
	#continuousData = pandas.DataFrame(X)
	#continuousData.insert(len(continuousData.columns), 'Col5', Z)
	#continuousData.insert(len(continuousData.columns), 'Col6', Y)
	#continuousData.rename(columns={0:'Col3', 1:'Col5', 2:'Col6'}, inplace=True)
	
	#labels = gmm.predict(continuousData)
	
	#clusterData = pandas.DataFrame(continuousData)
	#clusterData.insert(len(clusterData.columns), 'Label', labels)
	
	sample = gmm.sample(3425)
	
	figure = pylab.figure(figsize=pylab.figaspect(0.5))
	axes = figure.add_subplot(1, 2, 1, projection='3d')
	
	axes.set_title('Question 3 - Data')
	axes.set_xlabel('Hora')
	axes.set_ylabel('Latencia')
	axes.set_zlabel('Vazao')
	
	axes.view_init(elev=30., azim=22)
	axes.scatter(data.Col3, data.Col5, data.Col6, c='green')
	
	axes = figure.add_subplot(1, 2, 2, projection='3d')
	
	axes.set_title('Question 3 - Gaussian Mixture - d = '+str(d))
	axes.set_xlabel('Hora')
	axes.set_ylabel('Latencia')