Exemple #1
0
   def test_polar_wrap( self ):
      """Test polar plots where data crosses 0 degrees."""

      fname = self.outFile( "polar_wrap_180.png" )

      D2R = npy.pi / 180.0

      fig = pylab.figure()

      #NOTE: resolution=1 really should be the default
      pylab.subplot( 111, polar=True, resolution=1 )
      pylab.polar( [179*D2R, -179*D2R], [0.2, 0.1], "b.-" )
      pylab.polar( [179*D2R,  181*D2R], [0.2, 0.1], "g.-" )
      pylab.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )

      fig.savefig( fname )
      self.checkImage( fname )


      fname = self.outFile( "polar_wrap_360.png" )

      fig = pylab.figure()

      #NOTE: resolution=1 really should be the default
      pylab.subplot( 111, polar=True, resolution=1 )
      pylab.polar( [2*D2R, -2*D2R], [0.2, 0.1], "b.-" )
      pylab.polar( [2*D2R,  358*D2R], [0.2, 0.1], "g.-" )
      pylab.polar( [358*D2R,  2*D2R], [0.2, 0.1], "r.-" )
      pylab.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )

      fig.savefig( fname )
      self.checkImage( fname )
Exemple #2
0
    def test_polar_wrap(self):
        """Test polar plots where data crosses 0 degrees."""

        fname = self.outFile("polar_wrap_180.png")

        D2R = npy.pi / 180.0

        fig = pylab.figure()

        #NOTE: resolution=1 really should be the default
        pylab.subplot(111, polar=True, resolution=1)
        pylab.polar([179 * D2R, -179 * D2R], [0.2, 0.1], "b.-")
        pylab.polar([179 * D2R, 181 * D2R], [0.2, 0.1], "g.-")
        pylab.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3])

        fig.savefig(fname)
        self.checkImage(fname)

        fname = self.outFile("polar_wrap_360.png")

        fig = pylab.figure()

        #NOTE: resolution=1 really should be the default
        pylab.subplot(111, polar=True, resolution=1)
        pylab.polar([2 * D2R, -2 * D2R], [0.2, 0.1], "b.-")
        pylab.polar([2 * D2R, 358 * D2R], [0.2, 0.1], "g.-")
        pylab.polar([358 * D2R, 2 * D2R], [0.2, 0.1], "r.-")
        pylab.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3])

        fig.savefig(fname)
        self.checkImage(fname)
Exemple #3
0
def iteraciones(planetas):

    for astro in planetas:
        astro.data = pylab.loadtxt('RT{}Error.dat'.format(astro.nombre))
        astro.r = astro.data[:, 0]
        astro.theta = astro.data[:, 1]
        if astro.nombre == "Hale":
            pylab.polar(astro.theta,
                        astro.r,
                        'r-',
                        label='HaleBopp',
                        linewidth=1)
        else:
            pylab.polar(astro.theta,
                        astro.r,
                        'b-',
                        label='HaleBopp',
                        linewidth=1)
        # Initial guesses for a, e
        p0 = (200, 0.8)
        plsq = optimize.leastsq(residuals,
                                p0,
                                Dfun=jac,
                                args=(astro.r, astro.theta),
                                col_deriv=True)
        print('Ecc.{} = {}'.format(astro.nombre, plsq[0]))
Exemple #4
0
 def plot(self, fig=None, col='-b', fill_mat=False, number=None):
     """
     Default plot method
     This method simply plot the nodes continuously
     Derived classes should override this method to get desired shape
     """
     if fig is None:
         fig = pl.figure()
     N_, _ = self.basisND(np.array([0.0, 0.0]))
     xt = np.zeros(self.Ndim, self.dtype)
     self.getX(xt, N_)
     if number is not None:
         pl.text(xt[1], xt[0], str(number))
     x = [n.getX()[0] for n in self.Nodes]
     if self.Ndim > 1:
         y = [n.getX()[1] for n in self.Nodes]
     #if self.Ndim == 3:
     #    z = [n.getX()[2] for n in self.Nodes]
     if self.Ndim == 1:
         return pl.polar(np.array(x), col), [n.getX() for n in self.Nodes]
     if self.Ndim == 2:
         return pl.polar(np.array(x),np.array(y),col),\
         [n.getX() for n in self.Nodes]
     if self.Ndim == 3:
         """
         Will be implemented later
         """
         return None
Exemple #5
0
 def plot_force_vector_comp_parallel_to_velocity(self, fig):
     '''速度ベクトルに平行な合力ベクトルの大きさを図化する'''
     ax = fig.add_subplot(self.row, self.col, self.pos, polar=True)
     rad_range = np.arange(0, 2 * np.pi, 0.01)
     force_lst = list(
         self.force_vector_comp_parallel_to_velocity_generator(rad_range))
     plt.polar(rad_range, force_lst)
     y_max = np.ceil(max(force_lst)) + 100
     ax.set_ylim([0, y_max])
def sunflower(n):
    phi = (1 + math.sqrt(5)) / 2
    theta = []
    r = []
    for n in range(1, n + 1):
        theta.append(n * 2 * math.pi / phi)
        r.append(math.sqrt(n))
    pylab.polar(theta, r, 'o', linewidth=5)
    pylab.show()
Exemple #7
0
    def plot_force_value(self, fig):
        '''合力ベクトルの大きさを図化する関数'''
        ax = fig.add_subplot(self.row, self.col, self.pos, polar=True)
        rad_range = np.arange(0, 2 * np.pi, 0.01)
        force_lst = [
            np.linalg.norm(force_vector)
            for force_vector in self.force_vector_generator(rad_range)
        ]
        plt.polar(rad_range, force_lst)

        y_max = np.ceil(max(force_lst)) + 100
        ax.set_ylim([0, y_max])
Exemple #8
0
def test_polar_units():
    import matplotlib.testing.jpl_units as units
    units.register()
    pi = np.pi
    deg = units.UnitDbl( 1.0, "deg" )
    x1 = [ pi/6.0, pi/4.0, pi/3.0, pi/2.0 ]
    x2 = [ 30.0*deg, 45.0*deg, 60.0*deg, 90.0*deg ]
    y1 = [ 1.0, 2.0, 3.0, 4.0]
    y2 = [ 4.0, 3.0, 2.0, 1.0 ]
    fig = pylab.figure()
    pylab.polar( x2, y1, color = "blue" )
    fig.savefig( 'polar_units' )
Exemple #9
0
def radialprofile_errors(odprofiles, angles, od_prof, od_cutoff, \
                         showfig=False, savefig_name=None, report=True):
    """Calculate errors in radial profiles as a function of angle

    **Inputs**

      * odprofiles: 2D array, containing radial OD profiles along angles
      * angles: 1D array, angles at which radial profiles are taken
                          (zero is postive x-axis)
      * od_prof: 1D array, radially averaged optical density
      * od_cutoff: integer, index of profiles at which maximum fit-OD is reached

    **Outputs**

      * av_err: float, sum of absolute values of errors in errsum

    **Optional inputs**

      * showfig: bool, determines if a figure is shown with density profile
                 and fit
      * report: bool, if True print the sums of the mean and rms errors
      * savefig_name: string, if not None and showfig is True, the figure is
                      not shown but saved as png with this string as filename.

    """

    err = (odprofiles[od_cutoff:, :].transpose() - \
           od_prof[od_cutoff:]).sum(axis=1)

    av_err = np.abs(err).mean()

    if report:
        print 'mean error is ', err.mean()
        print 'rms error is ', av_err

    if showfig:
        # angular plot of errors, red for positive, blue for negative values
        pylab.figure()
        poserr = pylab.find(err > 0)
        negerr = pylab.find(err < 0)

        pylab.polar(angles[negerr], np.abs(err[negerr]), 'ko', \
                    angles[poserr], np.abs(err[poserr]), 'wo')
        pylab.title('Angular dependence of fit error')
        pylab.text(np.pi/2+0.3, np.abs(err).max()*0.85, \
                   r'$\sum_{\phi}|\sum_r\Delta_{OD}|=%1.1f$'%av_err)
        if not savefig_name:
            pylab.show()
        else:
            pylab.savefig(''.join([os.path.splitext(savefig_name)[0], '.png']))

    return av_err
Exemple #10
0
def radialprofile_errors(odprofiles, angles, od_prof, od_cutoff, \
                         showfig=False, savefig_name=None, report=True):
    """Calculate errors in radial profiles as a function of angle

    **Inputs**

      * odprofiles: 2D array, containing radial OD profiles along angles
      * angles: 1D array, angles at which radial profiles are taken
                          (zero is postive x-axis)
      * od_prof: 1D array, radially averaged optical density
      * od_cutoff: integer, index of profiles at which maximum fit-OD is reached

    **Outputs**

      * av_err: float, sum of absolute values of errors in errsum

    **Optional inputs**

      * showfig: bool, determines if a figure is shown with density profile
                 and fit
      * report: bool, if True print the sums of the mean and rms errors
      * savefig_name: string, if not None and showfig is True, the figure is
                      not shown but saved as png with this string as filename.

    """

    err = (odprofiles[od_cutoff:, :].transpose() - \
           od_prof[od_cutoff:]).sum(axis=1)

    av_err = np.abs(err).mean()

    if report:
        print 'mean error is ', err.mean()
        print 'rms error is ', av_err

    if showfig:
        # angular plot of errors, red for positive, blue for negative values
        pylab.figure()
        poserr = pylab.find(err > 0)
        negerr = pylab.find(err < 0)

        pylab.polar(angles[negerr], np.abs(err[negerr]), 'ko', \
                    angles[poserr], np.abs(err[poserr]), 'wo')
        pylab.title('Angular dependence of fit error')
        pylab.text(np.pi/2+0.3, np.abs(err).max()*0.85, \
                   r'$\sum_{\phi}|\sum_r\Delta_{OD}|=%1.1f$'%av_err)
        if not savefig_name:
            pylab.show()
        else:
            pylab.savefig(''.join([os.path.splitext(savefig_name)[0], '.png']))

    return av_err
Exemple #11
0
def show_normals_polar(n, w):
    X, Y, Z = n[:, :, 0], n[:, :, 1], n[:, :, 2]
    dx, dy, dz = lattice.project(X, Y, Z, R_oriented)
    cx, cy, cz = lattice.color_axis(dx, dy, dz, w)
    by = (w > 0) & (np.abs(dy) < 0.3)  # &blocks
    theta = np.arctan2(dz[by], dx[by]) * 4
    hist, edges = np.histogram(theta, 64, range=(-np.pi, np.pi), normed=True)
    pylab.figure(1)
    #pylab.clf()
    pylab.polar(edges[:-1], hist)
    figure(2)
    pylab.imshow(by)
    return theta, hist, edges, by
Exemple #12
0
 def test_polar_units( self ):
    """Test polar plots with unitized data."""
    fname = self.outFile( "polar_units.png" )
    pi = npy.pi
    deg = units.UnitDbl( 1.0, "deg" )
    x1 = [ pi/6.0, pi/4.0, pi/3.0, pi/2.0 ]
    x2 = [ 30.0*deg, 45.0*deg, 60.0*deg, 90.0*deg ]
    y1 = [ 1.0, 2.0, 3.0, 4.0]
    y2 = [ 4.0, 3.0, 2.0, 1.0 ]
    fig = pylab.figure()
    pylab.polar( x2, y1, color = "blue" )
    fig.savefig( fname )
    self.checkImage( fname )
Exemple #13
0
def show_normals_polar(n, w):
    X, Y, Z = n[:, :, 0], n[:, :, 1], n[:, :, 2]
    dx, dy, dz = lattice.project(X, Y, Z, R_oriented)
    cx, cy, cz = lattice.color_axis(dx, dy, dz, w)
    by = (w > 0) & (np.abs(dy) < 0.3)  # &blocks
    theta = np.arctan2(dz[by], dx[by]) * 4
    hist, edges = np.histogram(theta, 64, range=(-np.pi, np.pi), normed=True)
    pylab.figure(1)
    # pylab.clf()
    pylab.polar(edges[:-1], hist)
    figure(2)
    pylab.imshow(by)
    return theta, hist, edges, by
Exemple #14
0
    def plot(self, fig=None, col='-b', fill_mat=False, number=None):
        if fig is None:
            fig = pl.figure()

        X1 = self.Nodes[0].getX()
        X2 = self.Nodes[1].getX()
        xa1 = np.linspace(min(X1[1], X2[1]), max(X1[1], X2[1]), 20)
        xa2 = np.linspace(min(X1[0], X2[0]), max(X1[0], X2[0]), 20)
        pl.polar(xa1, xa2, col)

        X1 = self.Nodes[1].getX()
        X2 = self.Nodes[2].getX()
        xa1 = np.linspace(min(X1[1], X2[1]), max(X1[1], X2[1]), 20)
        xa2 = np.linspace(min(X1[0], X2[0]), max(X1[0], X2[0]), 20)
        pl.polar(xa1, xa2, col)

        X1 = self.Nodes[2].getX()
        X2 = self.Nodes[0].getX()
        xa1 = np.linspace(min(X1[1], X2[1]), max(X1[1], X2[1]), 20)
        xa2 = np.linspace(min(X1[0], X2[0]), max(X1[0], X2[0]), 20)
        pl.polar(xa1, xa2, col)

        nodes = self.Nodes
        for n in nodes:
            pl.polar(n.getX()[1], n.getX()[0], '.b')

        if number is not None:
            c = 0.5 * (nodes[4].getX() + nodes[5].getX())
            pl.text(c[0] * math.cos(c[1]), c[0] * math.sin(c[1]), str(number))

        return fig, [nodes[0], nodes[1], nodes[2]]
 def polarplot(self,slowtimes,title='none'):
     """
     Polar plot of the data vector.
     """
     startind = numpy.where(self.timevector<=slowtimes[0])[0][-1]
     stopind = numpy.where(self.timevector>=slowtimes[1])[0][0]
     center,tmp = processing.circlecenter(self.data[startind:stopind])
     radarvec = self.data[startind:stopind] #- center
     
     pylab.figure()
     pylab.polar(numpy.unwrap(numpy.angle(radarvec)),abs(radarvec))
     if title=='none':
         pylab.title(self.filename)
     else:
         pylab.title(title)
Exemple #16
0
def test_polar_wrap():
    D2R = np.pi / 180.0
    fig = pylab.figure()
    pylab.subplot( 111, polar=True, resolution=1 )
    pylab.polar( [179*D2R, -179*D2R], [0.2, 0.1], "b.-" )
    pylab.polar( [179*D2R,  181*D2R], [0.2, 0.1], "g.-" )
    pylab.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )
    fig.savefig( 'polar_wrap_180' )
    fig = pylab.figure()
    pylab.subplot( 111, polar=True, resolution=1 )
    pylab.polar( [2*D2R, -2*D2R], [0.2, 0.1], "b.-" )
    pylab.polar( [2*D2R,  358*D2R], [0.2, 0.1], "g.-" )
    pylab.polar( [358*D2R,  2*D2R], [0.2, 0.1], "r.-" )
    pylab.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )
    fig.savefig( 'polar_wrap_360' )
 def polarplot(self,tau,slowtimes,lim='tight',title='',altvec='None'):
     """
     Polar plot of the data vector.
     @param tau: The fast time in ns along which the data is plotted
     @param slowtimes: A two element list containing the start and stop slowtimes
     @param altvec: An alternative vector for plotting. Will be used instead of self.tauprofiles if not None.
     """
     startind = numpy.where(self.timevector<=slowtimes[0])[0][-1]
     stopind = numpy.where(self.timevector>=slowtimes[1])[0][0]
     pylab.figure()
     if altvec == 'None':
         tauind = numpy.where(self.tauvec>=tau)[0][0]
         center,tmp = processing.circlecenter(self.tauprofiles[startind:stopind,tauind])
         radarvec = self.tauprofiles[startind:stopind,tauind] - center
         pylab.polar(numpy.unwrap(numpy.angle(radarvec)),abs(radarvec))
     else:
         pylab.polar(numpy.unwrap(numpy.angle(altvec[startind:stopind])),abs(altvec[startind:stopind]))
     pylab.title(os.path.splitext(self.filename)[0])
def plot_genome_alignments(g_length,Alignments,al_length=100):
	num_aligns = float(len(set([al[0] for al in Alignments])))
	x = []
	last = None
	i = 0
	for al in Alignments:
		if al[0] != last:
			if len(x) > 0:
				x = list(set(x))
				x.sort()
				pylab.polar(x,[1*(1 - i/num_aligns)]*len(x))
			i += 1
			x = []
			last = al[0]
			xi = int(al[1]) + al_length
		if int(al[1]) < xi:
			x.append(float(al[1])/g_length*2*pi)
		else:
			x = list(set(x))
			x.sort()
			pylab.polar(x,[1*(1 - i/num_aligns)]*len(x))
			x = []
		xi = int(al[1]) + al_length
	x = list(set(x))
	x.sort()
	pylab.polar(x,[1*(1 - i/num_aligns)]*len(x))
	all_aligns = [int(al[1]) for al in Alignments]
	all_aligns.sort()
	x = []
	xi = all_aligns[0] + al_length
	for al in all_aligns:
		if al < xi:
			x.append(float(al)/g_length*2*pi)
		else:
			x = list(set(x))
			x.sort()
			pylab.polar(x,[1.1]*len(x))
			x = []
		xi = al + al_length
	x = list(set(x))
	x.sort()
	pylab.polar(x,[1.1]*len(x))
	pylab.grid(False)
	pylab.show()
def test2():
    print "Test Bras"
    k = 0.2126
    r0 = 2.3

    rc1 = 3
    rc2 = 13

    theta0=0.
    
    theta1 = 1./k*N.log(rc1/r0) + theta0
    theta2 = 1./k*N.log(rc2/r0) + theta0
    theta = N.arange(theta1,theta2,0.1)
    r1 = FormeBras(theta,r0,0,k)

    pl.polar(theta, r1, theta-N.pi/2, r1, theta-N.pi, r1, theta-3*N.pi/2, r1)
    print "write file"
    pl.savefig('Bras.jpg')
    pl.close()
Exemple #20
0
def test_polar_units():
    import matplotlib.testing.jpl_units as units
    units.register()

    pi = np.pi
    deg = units.UnitDbl(1.0, "deg")

    x1 = [pi / 6.0, pi / 4.0, pi / 3.0, pi / 2.0]
    x2 = [30.0 * deg, 45.0 * deg, 60.0 * deg, 90.0 * deg]

    y1 = [1.0, 2.0, 3.0, 4.0]
    y2 = [4.0, 3.0, 2.0, 1.0]

    fig = pylab.figure()

    pylab.polar(x2, y1, color="blue")

    # polar( x2, y1, color = "red", xunits="rad" )
    # polar( x2, y2, color = "green" )

    fig.savefig('polar_units')
Exemple #21
0
    def plot(self, fig = None, col = '-b', fill_mat = False, number = None, \
             deformed = False, deformed_factor=1.0):
        if fig is None:
            fig = pl.figure()
        # deformed structure not implemented

        X1 = self.Nodes[0].getX(self.loop[0])
        X2 = self.Nodes[2].getX(self.loop[2])
        xa1 = np.linspace(min(X1[1], X2[1]), max(X1[1], X2[1]), 20)
        xa2 = np.linspace(min(X1[0], X2[0]), max(X1[0], X2[0]), 20)
        pl.polar(xa1, xa2, col)

        X1 = self.Nodes[2].getX(self.loop[2])
        X2 = self.Nodes[8].getX(self.loop[8])
        xa1 = np.linspace(min(X1[1], X2[1]), max(X1[1], X2[1]), 20)
        xa2 = np.linspace(min(X1[0], X2[0]), max(X1[0], X2[0]), 20)
        pl.polar(xa1, xa2, col)

        X1 = self.Nodes[8].getX(self.loop[8])
        X2 = self.Nodes[6].getX(self.loop[6])
        xa1 = np.linspace(min(X1[1], X2[1]), max(X1[1], X2[1]), 20)
        xa2 = np.linspace(min(X1[0], X2[0]), max(X1[0], X2[0]), 20)
        pl.polar(xa1, xa2, col)

        X1 = self.Nodes[6].getX(self.loop[6])
        X2 = self.Nodes[0].getX(self.loop[0])
        xa1 = np.linspace(min(X1[1], X2[1]), max(X1[1], X2[1]), 20)
        xa2 = np.linspace(min(X1[0], X2[0]), max(X1[0], X2[0]), 20)
        pl.polar(xa1, xa2, col)

        nodes = self.Nodes
        for n in nodes:
            pl.polar(n.getX()[1], n.getX()[0], '.b')

        if number is not None:
            c = 0.5 * (nodes[2].getX(self.loop[2]) +
                       nodes[6].getX(self.loop[6]))
            pl.text(c[1], c[0], str(number))

        return fig, [nodes[0], nodes[2], nodes[8], nodes[6]]
Exemple #22
0
def dots():   
    import pylab as P
    from matplotlib.transforms import offset_copy
    
    X = P.arange(7)
    Y = X**2
    
    fig = P.figure(figsize=(5,10))
    ax = P.subplot(2,1,1)
    
    # If we want the same offset for each text instance,
    # we only need to make one transform.  To get the
    # transform argument to offset_copy, we need to make the axes
    # first; the subplot command above is one way to do this.
    
    transOffset = offset_copy(ax.transData, fig=fig,
                                x = 0.05, y=0.10, units='inches')
    
    for x, y in zip(X, Y):
        P.plot((x,),(y,), 'ro')
        P.text(x, y, '%d, %d' % (int(x),int(y)), transform=transOffset)
    
    
    # offset_copy works for polar plots also.
    
    ax = P.subplot(2,1,2, polar=True)
    
    transOffset = offset_copy(ax.transData, fig=fig, y = 6, units='dots')
    
    for x, y in zip(X, Y):
        P.polar((x,),(y,), 'ro')
        P.text(x, y, '%d, %d' % (int(x),int(y)),
                    transform=transOffset,
                    horizontalalignment='center',
                    verticalalignment='bottom')
    
    
    P.show()
Exemple #23
0
    def test_polar_units(self):
        """Test polar plots with unitized data."""

        fname = self.outFile("polar_units.png")

        pi = npy.pi
        deg = units.UnitDbl(1.0, "deg")

        x1 = [pi / 6.0, pi / 4.0, pi / 3.0, pi / 2.0]
        x2 = [30.0 * deg, 45.0 * deg, 60.0 * deg, 90.0 * deg]

        y1 = [1.0, 2.0, 3.0, 4.0]
        y2 = [4.0, 3.0, 2.0, 1.0]

        fig = pylab.figure()

        pylab.polar(x2, y1, color="blue")

        # polar( x2, y1, color = "red", xunits="rad" )
        # polar( x2, y2, color = "green" )

        fig.savefig(fname)
        self.checkImage(fname)
Exemple #24
0
def test_polar_wrap():
    D2R = np.pi / 180.0

    fig = pylab.figure()

    #NOTE: resolution=1 really should be the default
    pylab.subplot(111, polar=True, resolution=1)
    pylab.polar([179 * D2R, -179 * D2R], [0.2, 0.1], "b.-")
    pylab.polar([179 * D2R, 181 * D2R], [0.2, 0.1], "g.-")
    pylab.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3])

    fig.savefig('polar_wrap_180')

    fig = pylab.figure()

    #NOTE: resolution=1 really should be the default
    pylab.subplot(111, polar=True, resolution=1)
    pylab.polar([2 * D2R, -2 * D2R], [0.2, 0.1], "b.-")
    pylab.polar([2 * D2R, 358 * D2R], [0.2, 0.1], "g.-")
    pylab.polar([358 * D2R, 2 * D2R], [0.2, 0.1], "r.-")
    pylab.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3])

    fig.savefig('polar_wrap_360')
Exemple #25
0
def polar4fig6():
    # prob vs w (polar plot; not used)
    N = len(l)
    Ngr = 72
    vr = np.zeros(((N,Ngr,R))) # for reference
    for iN in range(N):
        for iM in range(Ngr):
            vr[iN,iM,:] = grid(x,l[iN],iM/float(Ngr),phsh=0.,gridmodel='gau',sig=sig)
    for iNp in [19]:
        pid = iNp
        vmodule = np.zeros((len(l),np.max(l)))
        for j in range(len(l)):
            vmodule[j,:np.max(l)] = np.dot(w[pid,j*Ng/len(l):(j+1)*Ng/len(l)],v[pid,j*Ng/len(l):(j+1)*Ng/len(l),:np.max(l)])
        vmodule -= np.min(vmodule) #nth*np.mean(vmodule)
        vmodule[vmodule<0] = 0
        vmodule /= np.max(vmodule)
        count = np.zeros((N,Ngr))
        for iN in range(N):
            for j in range(Ngr):
                temp = pylab.find(vr[iN,j,:]>0.95)
                for k in fid1d[pid]:
                    count[iN,j] += np.any(k==temp)
            count[iN,:] /= nf[pid]
        fig = pylab.figure(figsize=[8,6])
        for j in range(N):
            ax = fig.add_subplot(2,4,j+2, projection='polar')
            for iw in range(w.shape[1]/3):
                pylab.polar([p1d[pid,j*(w.shape[1]/3)+iw]*2*np.pi]*2,[0,w[pid,j*(w.shape[1]/3)+iw]/np.max(w[pid])],'#98FB98',label='weights') # pale green
            pylab.polar(np.append(np.arange(l[j])*2*np.pi/l[j],[0]),np.append(vmodule[j,:l[j]],vmodule[j,0]),'#008000',label='grid input sum') # green
            pylab.polar(np.append(np.arange(Ngr)*2*np.pi/Ngr,[0]),np.append(count[j,:],count[j,0]),'m',label='frac coincidence')
            #if j == 0:
            #pylab.legend((line1,line2,line3),('frac coincidence','weights','grid input sum'),frameon=False)
            pylab.title('$\lambda=$'+str(l[j]))
            pylab.ylim(0,1)
            pylab.xticks([])
            pylab.yticks([])
        pylab.legend(loc=1,frameon=False)
        ax = fig.add_subplot(223)
        for j in range(5):
            pylab.plot(range(l[0]),w[pid,j]*v[pid,j,:l[0]],'#98FB98')
            print w[pid,j],np.argmax(v[pid,j,:l[0]])
        pylab.plot(range(l[0]),np.dot(w[pid,:5],v[pid,:5,:l[0]]),'#008000')
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        pylab.savefig('temp'+str(pid)+'.svg')
Exemple #26
0
""" A cardioid is the plane figure described in polar coordinates by
r = 2a(1 + cos(θ)) for 0 <= θ <= 2π.
"""
import pylab

if __name__ == '__main__':
    θ = pylab.linspace(0, 2 * pylab.pi, 1000)
    a = 1.
    r = 2 * a * (1. + pylab.cos(θ))

    pylab.polar(θ, r)
    pylab.show()
    def create_plots(self):
        """Create per-rat and global figures of rotations, correlations, 
        correlation diagonals, and response change pie charts
        """
        from pylab import figure, axes, axis, subplot, polar, pie, rcParams
        from ..tools.images import tiling_dims
        
        self.figure = {}
        res = self.results
        rats = res['rats']
        rats.sort()
        r, c = tiling_dims(len(rats))
        rat_plots_size = 13, 9
        global_plots_size = 9, 9
        
        # Per-rat rotations/correlations polar cluster plots
        polar_kwargs = dict(marker='o', ms=10, mfc='b', mew=0, alpha=0.6,
            ls='', aa=True)
        deg_labels = [u'%d\xb0'%d for d in [-90,-45,0,45,90,135,180,-135]]
        if len(rats) > 1:
            rcParams['figure.figsize'] = rat_plots_size
            self.figure['rotcorr_rats'] = f = figure()
            f.set_size_inches(rat_plots_size)
            f.suptitle('Cluster Rotation and Peak Correlation', fontsize=16)
            for i,rat in enumerate(rats):
                ax = subplot(r, c, i+1, polar=True)
                rots, corrs = res['rotcorr_rat%d'%rat]
                polar((np.pi/180)*rots + np.pi/2, corrs, **polar_kwargs)
                ax.set_rmax(1.0)
                ax.set_xticklabels(deg_labels)
                ax.set_title('Rat %d'%rat)
            
        # Global polar cluster plot
        rcParams['figure.figsize'] = global_plots_size
        self.figure['rotcorr'] = f = figure()
        f.set_size_inches(global_plots_size)
        f.suptitle('Cluster Rotation and Peak Correlation (%d rats)'%len(rats), 
            fontsize=16)
        rots, corrs = res['rotcorr']
        polar_kwargs.update(ms=12)
        ax = subplot(111, polar=True)
        polar((np.pi/180)*rots + np.pi/2, corrs, **polar_kwargs)
        ax.set_rmax(1.0)
        ax.set_xticklabels(deg_labels)
        
        # Per-rat correlation diagonals plots
        diags_kwargs = dict(c='k', ls='-', aa=True, marker='')
        if len(rats) > 1:
            rcParams['figure.figsize'] = rat_plots_size
            self.figure['diags_rats'] = f = figure()
            f.set_size_inches(rat_plots_size)
            f.suptitle('Correlation Diagonals', fontsize=16)
            for i,rat in enumerate(rats):
                ax = subplot(r, c, i+1)
                d_STD = res['diags_STD_rat%d'%rat]
                d_MIS = res['diags_MIS_rat%d'%rat]
                ax.plot(*d_STD, lw=1, label='STD', **diags_kwargs)
                ax.plot(*d_MIS, lw=2, label='MIS', **diags_kwargs)
                ax.set_title('Rat %d'%rat)
                ax.set_xlim(d_STD[0][0], d_STD[0][-1])
                ax.set_ylim(0, 1)
                if i == 0:
                    ax.legend(fancybox=True)
                ax.text(0.03, 0.92, 'Angle = %.1f'%res['popshift_rat%d'%rat][0],
                    transform=ax.transAxes)
                ax.text(0.03, 0.87, 'Peak = %.3f'%res['popshift_rat%d'%rat][1],
                    transform=ax.transAxes)

        # Global diagonals plot
        rcParams['figure.figsize'] = global_plots_size
        self.figure['diags'] = f = figure()
        f.set_size_inches(global_plots_size)
        f.suptitle('Population Correlations (%d rats)'%len(rats), fontsize=16)
        ax = axes()
        d_STD = res['diags_STD']
        d_MIS = res['diags_MIS']
        ax.plot(*d_STD, lw=1.5, label='STD', **diags_kwargs)
        ax.plot(*d_MIS, lw=3, label='MIS', **diags_kwargs)
        ax.set_xlim(d_STD[0][0], d_STD[0][-1])
        ax.set_ylim(0, 1)
        ax.legend(fancybox=True)
        ax.text(0.03, 0.95, 'Angle = %.1f'%res['popshift'][0],
            transform=ax.transAxes)
        ax.text(0.03, 0.92, 'Peak = %.3f'%res['popshift'][1],
            transform=ax.transAxes)
        
        # Per-rat response change tally pie charts
        pie_kwargs = dict(labels=CL_LABELS, colors=CL_COLORS, autopct='%.1f', 
            pctdistance=0.8, labeldistance=100)
        if len(rats) > 1:
            rcParams['figure.figsize'] = rat_plots_size
            self.figure['response_tally_rats'] = f = figure()
            f.set_size_inches(rat_plots_size)
            f.suptitle('Response Changes', fontsize=16)
            for i,rat in enumerate(rats):
                ax = subplot(r, c, i+1)
                tally = [res['response_tallies_rat%d'%rat][k] for k in CL_LABELS]
                pie(tally, **pie_kwargs)
                axis('equal')
                ax.set_xlim(-1.04, 1.04) # fixes weird edge clipping
                ax.set_title('Rat %d (%d total)'%(rat, sum(tally)))
                if i == 0:
                    ax.legend(fancybox=True, loc='right', 
                        bbox_to_anchor=(0.0, 0.5))
        
        # Global response change tally pie chart
        rcParams['figure.figsize'] = global_plots_size
        self.figure['response_tally'] = f = figure()
        tally = [res['response_tallies'][k] for k in CL_LABELS]
        f.set_size_inches(global_plots_size)
        f.suptitle('Response Changes (%d total)'%sum(tally), fontsize=16)
        pie_kwargs.update(pctdistance=0.9)
        ax = axes()
        pie(tally, **pie_kwargs)
        axis('equal')
        ax.set_xlim(-1.04, 1.04) # fixes weird edge clipping
        ax.legend(fancybox=True, loc='upper left', bbox_to_anchor=(-0.11, 1.05))
        
        # Reset figure sizes
        rcParams['figure.figsize'] = 9, 9    
Exemple #28
0
ax = P.subplot(2,1,1)

# If we want the same offset for each text instance,
# we only need to make one transform.  To get the
# transform argument to offset_copy, we need to make the axes
# first; the subplot command above is one way to do this.

transOffset = offset_copy(ax.transData, fig=fig,
                            x=0.05, y=0.10, units='inches')

for x, y in zip(X, Y):
    P.plot((x,),(y,), 'ro')
    P.text(x, y, '%d, %d' % (int(x),int(y)), transform=transOffset)


# offset_copy works for polar plots also.

ax = P.subplot(2,1,2, polar=True)

transOffset = offset_copy(ax.transData, fig=fig, y=6, units='dots')

for x, y in zip(X, Y):
    P.polar((x,),(y,), 'ro')
    P.text(x, y, '%d, %d' % (int(x),int(y)),
                transform=transOffset,
                horizontalalignment='center',
                verticalalignment='bottom')


P.show()
Exemple #29
0
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 25 10:34:00 2012

@author: johannes
"""

import numpy as np
import pylab as plt

data = np.loadtxt('kerrtab.dat')

phi = data[:,0]/360*(2*np.pi);
I_lin = data[:,1]
I_zirk = data[:,2]
I_ellip = data[:,3]

plt.figure()
plt.polar(phi,I_lin,'r*-')
plt.polar(phi,I_zirk,'bo-')
plt.polar(phi,I_ellip,'kx-')

plt.title('Winkelabhaengigkeit der Intensitaet')
plt.legend(('linear','zirkular','elliptisch'))

#savefig muss vor show() ausgefuehrt werden
plt.savefig('winkelabhaengigkeit.eps',dpi=300)
plt.show()
Exemple #30
0
a, z = sympy.symbols("a z")
a0, z0 = 0, numpy.pi/2
epsilon = a*1e-15 + z*1e-15
order = 5
nSamples = 70
angles = numpy.arange(0,nSamples+1)*2*numpy.pi/nSamples
w = 2*math.pi*spectralRange/spectrumBins * numpy.arange(spectrumBins)

if False:
	print "Checking that the azimuthal formula is equivalent to the zenital formula"
	for l in xrange(0,order+1) :
	#	pattern1 = sum([sh_normalization2(l,m)*sympy.assoc_legendre(l,m,sympy.cos(z))*sympy.assoc_legendre(l,m,1) for m in xrange(0,l+1)])
	#	pattern1 = sh_normalization2(l,0)*sympy.assoc_legendre(l,0,sympy.cos(z))
		pattern1 = sh_normalization2(l,0)*sympy.legendre(l,sympy.cos(z))
		pylab.polar(angles, [ pattern1.subs(z,angle)/(2*l+1) for angle in angles ], label="Zenital %s"%l)

		pattern2 = sum([sh_normalization2(l,m)*sympy.cos(m*z)*sympy.assoc_legendre(l,m,0)**2 for m in xrange(0,l+1)])
		pylab.polar(angles, [ pattern2.subs(z,angle)/(2*l+1) for angle in angles ], label="Azimuthal %s"%l)
	pylab.title("Zenital vs Azimuthal variation",horizontalalignment='center', verticalalignment='baseline', position=(.5,-.1))
	pylab.rgrids(numpy.arange(.4,1,.2),angle=220)
	pylab.legend(loc=2)
	pylab.savefig(figurePath(__file__,"pdf"))
	pylab.show()
# We take the azimuthal formula which is faster
print "Computing component patterns"
patternComponents = [
	sh_normalization2(l,0)*sympy.legendre(l,sympy.cos(z))
	for l in xrange(0,order+1)
	]
for l, pattern in enumerate(patternComponents) :
Exemple #31
0
            for i, d in enumerate(COLORS):
                worldTotals = numpy.concatenate((worldTotals,totals[d]+ROTATIONS[d]))
            
            M[fNum]=circmean(worldTotals*numpy.pi/180)
            V[fNum]=circvar(worldTotals*numpy.pi/180)
            #pylab.figure()
            pylab.subplot(4,5,fNum+1,polar=True)
            plotArgs = dict(color='k',linewidth=2)
            orw,n,b,bc,ax = flypod.rose(worldTotals,plotArgs=plotArgs)
            pylab.hold('on')
            
            for i, d in enumerate(COLORS):
                plotArgs = dict(color=COLORS[d],linewidth=.5)
                flypod.rose(totals[d]+ROTATIONS[d],plotArgs=plotArgs)

            pylab.polar([0,numpy.pi/2-M[fNum]],[0,ax.get_rmax()*(1-V[fNum])],color='k')
            ax.set_rmax(.15)
            ax.set_rgrids([1],'')
            ax.set_thetagrids([0,90,180,270],['E','N','W','S'])
            pylab.title(fly['dirName'])
            

    pylab.suptitle(baseDir)
    circVar[baseDir] = numpy.copy(V)
    pylab.draw()

pylab.figure()
pylab.hold('on')
ax = pylab.gca()
for b, baseDir in enumerate(baseDirs):
    pylab.scatter((numpy.random.rand(len(circVar[baseDir]))-.5)/3+b,circVar[baseDir],marker='+')
Exemple #32
0
	sampleDelaysPI.append(delayWithMinimumPhaseCorrelation(data,filterFreq=20000, interpolate=True))
	if elevation == 0 :
		azimutalPI.append(sampleDelaysPI[-1])
		degrees.append(azimuthDegrees)


r=1.4
R=0.075 # interaural distance
R=0.088 # equivalent sphere
a0 = math.acos(R/r)
c=344

if True :
	radians = numpy.array([math.radians(a) for a in degrees])
	analytic = numpy.array([samplingRate/c*(sphericalHeadDelay(math.radians(a), R, r)) for a in degrees])
	pylab.polar(radians, numpy.array(azimutalPI)-min(azimutalPI), label='HRTF delay (empirical)')
	pylab.polar(radians, analytic-min(analytic), label='HRTF delay (analytic)')
	pylab.title("Analytic spherical head vs. KEMAR (horizontal plane)")
	pylab.legend()
	pylab.show()

if True :
	pylab.title("HRTF Delay histogram")
	for label, sampleDelays in (
		("Number of points",sampleDelaysPI),
		) :
		histogram,edges=numpy.histogram(sampleDelays,range=(0,512),bins=512)
		pylab.plot(histogram[0:100], label=label)
	pylab.legend()
	pylab.show()
# Python 3.7.4 program for plotting lobes
# Works with Anconda3 (5.2.0) using VS Python Suport
# Source code can be used in Spyder also

from numpy import arange, sin, cos, pi
from pylab import figure, polar, show

t = arange(0, 2, 1. / 180) * pi
figure(1)
polar(t, sin(t * 2))
figure(2)
polar(t, sin(t * 3))
figure(3)
polar(t, sin(t * 4))
figure(4)
polar(t, sin(t * 5))
show()
import pylab
from numpy import *

# angmin, angmax, splitPoints
a = 0
b = 14 * pi
n = 8763

angs = linspace(a, b, n)

rs = sin(8 * angs / 7)

pylab.polar(angs, rs, lw=5, label="8theta/7")

pylab.title("Polar Bear!", color='g')
# pylab.legend()
# pylab.grid()

pylab.show()
Exemple #35
0
def plot_hodograph(wind_dir, wind_spd, altitude, rms_error, img_title, img_file_name, parameters={}, storm_motion=()):
    param_names = {
        'shear_mag_1km':"0-1 km Bulk Shear",
        'shear_mag_3km':"0-3 km Bulk Shear",
        'shear_mag_6km':"0-6 km Bulk Shear",
        'srh_1km':"0-1 km Storm-Relative Helicity",
        'srh_3km':"0-3 km Storm-Relative Helicity",
    }

    param_units = {
        'shear_mag_1km':"kt",
        'shear_mag_3km':"kt",
        'shear_mag_6km':"kt",
        'srh_1km':"m$^2$ s$^{-2}$",
        'srh_3km':"m$^2$ s$^{-2}$",
    }

    pylab.clf()
    pylab.axes((0.05, 0.05, 0.65, 0.85), polar=True)

    rms_error_colors = ['c', 'g', 'y', 'r', 'm']
    rms_error_thresh = [0, 2, 6, 10, 14, 999]
    wind_dir = np.pi * wind_dir / 180

    u = -wind_spd * np.sin(wind_dir)
    v = -wind_spd * np.cos(wind_dir)

    u_marker = np.interp(np.arange(16, dtype=float), altitude, u, left=np.nan, right=np.nan)
    v_marker = np.interp(np.arange(16, dtype=float), altitude, v, left=np.nan, right=np.nan)
    ws_marker = np.hypot(u_marker, v_marker)
    wd_marker = np.arctan2(-u_marker, -v_marker)

    u_avg = (u[1:] + u[:-1]) / 2
    v_avg = (v[1:] + v[:-1]) / 2

    wind_spd_avg = np.hypot(u_avg, v_avg)
    wind_dir_avg = np.arctan2(-u_avg, -v_avg)

    color_index = np.where((rms_error[0] >= rms_error_thresh[:-1]) & (rms_error[0] < rms_error_thresh[1:]))[0][0]
    pylab.polar([ wind_dir[0], wind_dir_avg[0] ], [ wind_spd[0], wind_spd_avg[0] ], color=rms_error_colors[color_index], lw=1.5)

    for idx in range(1, len(wind_dir) - 1):
        color_index = np.where((rms_error[idx] >= rms_error_thresh[:-1]) & (rms_error[idx] < rms_error_thresh[1:]))[0][0]
        pylab.polar([ wind_dir_avg[idx - 1], wind_dir[idx], wind_dir_avg[idx] ], [ wind_spd_avg[idx - 1], wind_spd[idx], wind_spd_avg[idx] ], color=rms_error_colors[color_index], lw=1.5)

    color_index = np.where((rms_error[-1] >= rms_error_thresh[:-1]) & (rms_error[-1] < rms_error_thresh[1:]))[0][0]
    pylab.polar([ wind_dir_avg[-1], wind_dir[-1] ], [ wind_spd_avg[-1], wind_spd[-1] ], color=rms_error_colors[color_index], lw=1.5)

    pylab.polar(wd_marker, ws_marker, ls='None', mec='k', mfc='k', marker='o', ms=4)

    if storm_motion != ():
        storm_direction, storm_speed = storm_motion
        pylab.plot(np.pi * storm_direction / 180., storm_speed, 'k+')

    pylab.gca().set_theta_direction(-1)
    pylab.gca().set_theta_zero_location('S')
    pylab.gca().set_thetagrids(np.arange(0, 360, 30), labels=np.arange(0, 360, 30), frac=1.05)
    pylab.gca().set_rgrids(np.arange(10, 80, 10), labels=np.arange(10, 70, 10), angle=15)
    pylab.ylim((0, 70))

    pylab.text(wind_dir[0], wind_spd[0], "%3.1f" % altitude[0], size='small', weight='bold')
    pylab.text(wind_dir[-1], wind_spd[-1], "%3.1f" % altitude[-1], size='small', weight='bold')

    start_x = 1.07
    start_y = 0.62

    for idx, param_key in enumerate(sorted(parameters.keys())):
        if np.isnan(parameters[param_key]):
            param_text = "%s\n  %f" % (param_names[param_key], parameters[param_key])
        else:
            param_text = "%s\n  %.1f %s" % (param_names[param_key], parameters[param_key], param_units[param_key])

        pylab.text(start_x, start_y - idx * 0.075, param_text, transform=pylab.gca().transAxes, size='x-small', weight='bold')

    start_y = 0.25

    pylab.text(start_x, start_y, "RMS Errors:", transform=pylab.gca().transAxes, size='x-small', weight='bold')

    for idx, color in enumerate(rms_error_colors):
        line = Line2D([start_x, start_x + 0.05], [start_y + 0.012 - (idx + 1) * 0.0375, start_y + 0.012 - (idx + 1) * 0.0375], color=color, clip_on=False, lw=1.5, transform=pylab.gca().transAxes)
        pylab.gca().add_line(line)
        if rms_error_thresh[idx + 1] == 999:
            legend_text = "%d kt+" % rms_error_thresh[idx]
        else:
            legend_text = "%d-%d kt" % (rms_error_thresh[idx], rms_error_thresh[idx + 1])
        pylab.text(start_x + 0.075, start_y - (idx + 1) * 0.0375, legend_text, transform=pylab.gca().transAxes, size='x-small', weight='bold')

    pylab.suptitle(img_title)
    pylab.savefig(img_file_name)
    return
data = np.fromfile(FILENAME, dtype=int)
data = data.reshape((data.size/3, 3))
N = data.shape[0]
print "Received %g points of data." % (N*2)

direction = data[:,0]
left = data[:,1]
right = data[:,2]

low = min(direction)
high = max(direction)
print "Data scanned from %g to %g and %g to %g." % (low, high, low+180, high+180)

# scan_range = np.arange(low,high+1)
# scan_data = []
# for pos in scan_range:
#   vals = data[direction==pos]
#   avg = sum(vals)/len(vals)
#   # print pos, ":", avg
#   scan_data.append(avg)

#######
# pylab.plot(scan_range, scan_data, 'b')
# pylab.polar(scan_range * np.pi / 180.0, scan_data, 'b')
# pylab.axes([0.025, 0.025, 0.95, 0.95], polar=True)
pylab.polar(direction * np.pi / 180.0, left, 'b,', (direction+180) * np.pi / 180.0, right, 'r,')
# pylab.xlabel('Position')
# pylab.ylabel('Distance (mm)')
pylab.title('Ultrasonic Sensor Distance Scan Test')
pylab.show()
Exemple #37
0
r = []
for i in range(1, k):

    def Fibonacci(n):
        if n < 0:
            print("Incorrect input")
    # First Fibonacci number is 0
        elif n == 1:
            return 0

    # Second Fibonacci number is 1
        elif n == 2:
            return 1
        else:
            return Fibonacci(n - 1) + Fibonacci(n - 2)

    theta.append(Fibonacci(i))
    r.append(Fibonacci(i))

#theta=range(10000)

#r=range(10000)

print(r)
print(theta)
pylab.polar(theta, r, ls='', marker='o')
pylab.show()

#pylab.plot(range(10), linestyle='', marker='o', color='b')
#pylab.show()
Exemple #38
0
def cardioidncos(a, b):
    t = arange(0, 2 * pi, .01)
    polar(t, a + (b * -cos(t)))
    heading = "%s + %s * -cos(t)" % (a, b)
    title(heading)
Exemple #39
0
# -*- coding: utf-8 -*-
"""
Created on Sat May  2 02:27:05 2015

@author: alumno
"""

import pylab as m

m.polar(m.arange(360) * m.pi / 180., m.rand(360))
m.thetagrids(m.arange(0, 90, 10), labels=None, fmt='%d', frac=1.1)
m.rgrids([1, 2, 3], labels=None, angle=22.5)
m.show()
Exemple #40
0
	sys.exit()
decodingName=sys.argv[1]
polarPattern = decoding=decodings[decodingName]
title = dict(
	maxre = "Max $r_E$",
	maxrv = "Max $r_V$",
	inphase = "In-phase",
	)[decodingName]

ordersToShow = [1,3,9,35]
if  sys.argv[-1:1:-1] : ordersToShow = [int(a) for a in sys.argv[2:]]

def figurePath(file, infix, extension) :
	return os.path.join('figures', os.path.splitext(os.path.basename(file))[0] + infix + "." + extension)

N*=2
azimuths = numpy.arange(0,361,360/N)
radiansAzimuths = [math.radians(degrees) for degrees in azimuths]
pylab.rcParams['figure.figsize']=(5,5)
for order in ordersToShow :
	paternValues = numpy.array([sum(polarPattern(azimuth, order))/(order+1) for azimuth in radiansAzimuths])
	paternValues /= max(paternValues)
	pylab.polar(radiansAzimuths, paternValues, label='Order %s'%order )
pylab.rgrids(numpy.arange(.4,1,.2),angle=220)
pylab.legend(loc=2)
pylab.title(title,horizontalalignment='center', verticalalignment='baseline', position=(.5,-.13))
pylab.savefig(figurePath(__file__,"-"+decodingName,"pdf"))
pylab.show()


# Python 3.7.4 program for plotting Sinus functions
# Works with Anconda3 (5.2.0) using VS Python Suport
# Source code can be used in Spyder also

from numpy import arange, sin, cos, pi
from pylab import figure, polar, show

t = arange(0, 2, 1. / 180) * pi
figure(1)
polar(t, sin(t))
figure(2)
polar(t, -sin(t))
figure(3)
polar(t, cos(t))
figure(4)
polar(t, -cos(t))
show()
Exemple #42
0
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 20 07:41:22 2012

@author: johannes
"""

import numpy as np
import pylab as plt

rad = 6
N = 120
x = np.linspace(-rad,rad,N/2)
y = np.sqrt(rad**2-x**2)
y = np.append(y,-y)
phi = np.linspace(0,2*np.pi,N)

fig = plt.figure()
plt.plot(np.append(x,x),y,'r*')
plt.polar(phi,rad*np.ones(N),'bo')
plt.axis('equal')
plt.show()
Exemple #43
0
# The data to fit
data = pylab.loadtxt('NewtonTierra.dat', dtype=float)  
r = data[:,0]
theta = data[:,1]


def residuals(p, r, theta):
    """ Return the observed - calculated residuals using f(theta, p). """
    return r - f(theta, p)

def jac(p, r, theta):
    """ Calculate and return the Jacobian of residuals. """
    a, e = p
    da = (1 - e**2)/(1 - e*np.cos(theta))
    de = (-2*a*e*(1-e*np.cos(theta)) + a*(1-e**2)*np.cos(theta))/(1 -e*np.cos(theta))**2
    return -da,  -de
    return np.array((-da, -de)).T

# Initial guesses for a, e
p0 = (1, 0.1)
plsq = optimize.leastsq(residuals, p0, Dfun=jac, args=(r, theta), col_deriv=True)
print(plsq)

pylab.polar(theta, r, 'b-')
theta_grid = np.linspace(0, 2*np.pi, 200)
pylab.polar(theta_grid, f(theta_grid, plsq[0]), lw=2)
plt.rgrids((0.5, 1))
pylab.savefig('FitTierra.pdf')
pylab.show()
Exemple #44
0
def main():
    viewable = []
    lines = open('geo.txt','r').read().splitlines()
    for i in xrange(0, len(lines), 3):
        tle = lines[i+0], lines[i+1], lines[i+2]
        if tle[0].find('INMARSAT') == tle[0].find('ALPHASAT') == tle[0].find('MTSAT') == -1:
            continue
        #print  '===================',tle[0],'==================='
        sat = ephem.readtle(*tle)

        sat_alt, sat_az = [], []
        #-36.02,88.57
        o = ephem.Observer()
        o.lat, o.lon = map(numpy.deg2rad,(-36,89))
        o.date = datetime.datetime.now()
        #print dir(o)

        start = datetime.datetime(2014,3,8,0,19)
        for d in [start]:
            o.date = d
            sat.compute(o)
            #print dir(sat), sat.elevation
            lat, lon, azi = map(numpy.rad2deg,(sat.sublat, sat.sublong,sat.alt))
            if azi > 10.0:
                cosparYY = tle[1].split(' ')[2]
                # [20-int((t+50)/100) for t in map(int,[("%03d" % i)[1:] for i in range(49,151)])]
                cosparYYYY = str(20-int((int(cosparYY[0:2])+50)/100)) + cosparYY[0:2] + '-' + cosparYY[2:]
                name = tle[0].strip()
                mtsat1 = 'MTSAT-1R'
                if name.find(mtsat1) >= 0: name = mtsat1
                elif name == 'ALPHASAT': name += ' 4A-F4'

                #print sat.range_velocity, sat.range, lat, lon
                viewable.append((azi, cosparYYYY.strip(),name,lon))
                #print `viewable[-1]`
            continue

            sat_alt.append(numpy.rad2deg(inmarsat_3f1.alt))
            deg = numpy.rad2deg(inmarsat_3f1.az)
            if deg > 180.:
                deg -= 360.
            sat_az.append((deg))

    #print sat_az
    #print dir(inmarsat_3f1)
    print 'elevation,identifier,name,satsublon'
    for p in sorted(viewable,key=operator.itemgetter(0),reverse=True):
        print "%.1f,%s,%s,%.2f" % p

    return

    pylab.subplot2grid((2,4), (0,0), colspan=2)
    pylab.plot(dt, sat_az)
    pylab.ylabel("Azimuth (deg)")
    pylab.xticks(rotation=15)
    pylab.subplot2grid((2,4), (1,0), colspan=2)
    pylab.plot(dt, sat_alt)
    pylab.ylabel("Altitude (deg)")
    pylab.xticks(rotation=15)

    pylab.subplot2grid((2,4), (0,2), rowspan=2, colspan=2, polar=True)
    pylab.axes(polar=True).set_theta_zero_location("N")
    pylab.axes(polar=True).set_theta_direction(-1)
    pylab.polar(numpy.deg2rad(sat_az), 90-numpy.array(sat_alt))
    pylab.axes(polar=True).annotate(u"64.5°E",
                    xy=(0, 0),
                    horizontalalignment='center',
                    verticalalignment='center')
    pylab.axes(polar=True).annotate('\n'.join((tle[0],str(start))),
                    xy=(math.pi, 1),
                    horizontalalignment='center',
                    verticalalignment='center')
    for t, az, alt in zip(dt, numpy.deg2rad(sat_az), 90-numpy.array(sat_alt)):
        if t.minute == 0:
            ts = t.strftime('%H:%M')
            if az <= 0.01: h = 'right'
            else: h = 'left'
            pylab.axes(polar=True).annotate(ts,
                    xy=(az, alt),
                    xytext=(az*3-0.03, alt),
                    horizontalalignment=h,
                    verticalalignment='bottom')
    pylab.ylim(0,2)
    pylab.axes(polar=True).set_xticklabels(['N', '', 'E', '', 'S', '', 'W', ''])
    pylab.axes(polar=True).set_yticklabels(['', '', '', ''])

    pylab.savefig('positions.pdf')
    pylab.show()
Exemple #45
0
tvtkGrid = vis.tvtkGrid(grid)
vis.plotScalarData(tvtkGrid, None, tvtkU)

# Export the results into a VTK file

from tvtk.api import write_data
write_data(tvtkU, "u.vts")

# PART 6: Evaluate the far-field pattern of the scattered field ################

# Create the necessary potential operators

slFfPot = lib.createHelmholtz3dFarFieldSingleLayerPotentialOperator(context, kExt)
dlFfPot = lib.createHelmholtz3dFarFieldDoubleLayerPotentialOperator(context, kExt)

# Define a set of points on the unit sphere and evaluate the potentials

theta = np.linspace(0, 2*np.pi, 361)
points = np.vstack([np.cos(theta), np.sin(theta), 0. * theta])

farFieldPattern = (- slFfPot.evaluateAtPoints(uScDeriv, points, evalOptions)
                   + dlFfPot.evaluateAtPoints(uSc, points, evalOptions))
farFieldPattern = farFieldPattern.ravel()

# Display the graph

import pylab
pylab.polar(theta, abs(farFieldPattern))
pylab.title("Scattered field pattern")
pylab.show()
Exemple #46
0
           [1.530, 0.0,   "Mars"],
         ]

def mktransit(a0,a1):
    m,M = min(a0,a1), max(a0,a1)
    return [ (a0+a1)/2., (1.-m/M) / (1.+m/M) ]

params.append(mktransit(params[2][0], 4.0)          + ['Uninhabitable'])
params.append(mktransit(params[0][0], 0.5)          + ['Uninhabitable'])
params.append(mktransit(params[1][0], params[2][0]) + ['Transit'])
params.append(mktransit(params[1][0], params[0][0]) + ['Transit'])

figure(figsize=(12,12), facecolor='cyan', edgecolor='green')

for a,e,label in params:
    theta = linspace(0,2*pi, 100)
    r = a * (1-e**2) / (1 - e*cos(theta))
    polar(theta, r, label=label)

gca().fill_between(linspace(0.0, 2*pi,100), 0.65*ones(100), color='yellow')

gca().xaxis.set_major_locator(NullLocator())
gca().yaxis.set_major_locator(NullLocator())
#gca().set_ylim(0,1.8)
legend(loc='lower left', bbox_to_anchor = (-0.1, -0.0))

savefig('orbits-big.pdf', facecolor='cyan')

show()

Exemple #47
0
# Make some datetimes
midnight = datetime.datetime.replace(datetime.datetime.now(), hour=0)
dt = [midnight + datetime.timedelta(minutes=20 * x) for x in range(0, 24 * 3)]

# Compute satellite locations at each datetime
sat_alt, sat_az = [], []
for date in dt:
    oxford.date = date
    iss.compute(oxford)
    sat_alt.append(np.rad2deg(iss.alt))
    sat_az.append(np.rad2deg(iss.az))
    sat_lat.append(np.rad2deg(iss.lat))
    sat_az.append(np.rad2deg(iss.lon))

# Plot satellite tracks
'''plt.subplot(211)
plt.plot(dt, sat_alt)
plt.ylabel("Altitude (deg)")
plt.xticks(rotation=25)
plt.subplot(212)
plt.plot(dt, sat_az)
plt.ylabel("Azimuth (deg)")
plt.xticks(rotation=25)
plt.show()'''

# Plot satellite track in polar coordinates
plt.polar(np.deg2rad(sat_az), 90 - np.array(sat_alt))
plt.ylim(0, 90)
plt.show()
Exemple #48
0
    # adjust y-axis
    a = pylab.axis()
    pylab.axis([0.0, 3.5, -10.0, 4.0])
    # draw grid
    pylab.gca().xaxis.grid(color='gray', linestyle='dashed')
    pylab.gca().yaxis.grid(color='gray', linestyle='dashed')

  # plot of Harmonoise/Imagine directivity patterns as polar plot
  if 0:
    warnings.simplefilter('ignore', UserWarning)
    cat = 1
    f = 2000.0
    pylab.figure()
    iplot = 0
    for h in [0.01, 0.30, 0.75]:
      for phi in [0.0, 30.0, 60.0, 90.0]:
        directivity = ImagineDirectivity(cat = cat, h = h)
        thetas = numpy.arange(0.0, 360.0)
        Lcorrs = [directivity(theta = theta, phi = phi, f = f) for theta in thetas] # level corrections
        iplot += 1
        pylab.subplot(3, 4, iplot, polar = True)
        pylab.polar((numpy.pi/180.0)*thetas, numpy.zeros(360), color = 'black', linestyle = '--') # draw the zero line
        pylab.polar((numpy.pi/180.0)*thetas, Lcorrs)
        pylab.ylim(-10.0, 4.0)


  try:
    pylab.show()
  except:
    pass
Exemple #49
0
def petalsncos(a, b):
    t = arange(0, 2 * pi, .01)
    polar(t, a * -cos(t * n))
    heading = "%s * -cos(t * %s)" % (a, n)
    title(heading)
Exemple #50
0
def main():
    lines = open('sat23839.txt','r').read().splitlines()
    tle = lines[1].lstrip(), lines[7], lines[8]
    inmarsat_3f1 = ephem.readtle(*tle)
    print `inmarsat_3f1`

    sat_alt, sat_az = [], []
    o = ephem.Observer()
    o.lat = numpy.deg2rad(0)
    o.lon = numpy.deg2rad(64.5)
    o.date = datetime.datetime.now()
    print dir(o)

    start = datetime.datetime(2014,03,07,16,00)
    dt = [start + datetime.timedelta(minutes=minute_step*x) for x in range(0, int(8.5*60/minute_step))]
    for d in dt:
        o.date = d
        inmarsat_3f1.compute(o)
        print inmarsat_3f1.range_velocity, inmarsat_3f1.range, map(numpy.rad2deg,(inmarsat_3f1.sublat, inmarsat_3f1.sublong))
        sat_alt.append(numpy.rad2deg(inmarsat_3f1.alt))
        deg = numpy.rad2deg(inmarsat_3f1.az)
        if deg > 180.:
            deg -= 360.
        sat_az.append((deg))
    #print sat_az
    #print dir(inmarsat_3f1)

    pylab.subplot2grid((2,4), (0,0), colspan=2)
    pylab.plot(dt, sat_az)
    pylab.ylabel("Azimuth (deg)")
    pylab.xticks(rotation=15)
    pylab.subplot2grid((2,4), (1,0), colspan=2)
    pylab.plot(dt, sat_alt)
    pylab.ylabel("Altitude (deg)")
    pylab.xticks(rotation=15)

    pylab.subplot2grid((2,4), (0,2), rowspan=2, colspan=2, polar=True)
    pylab.axes(polar=True).set_theta_zero_location("N")
    pylab.axes(polar=True).set_theta_direction(-1)
    pylab.polar(numpy.deg2rad(sat_az), 90-numpy.array(sat_alt))
    pylab.axes(polar=True).annotate(u"64.5°E",
                    xy=(0, 0),
                    horizontalalignment='center',
                    verticalalignment='center')
    pylab.axes(polar=True).annotate('\n'.join((tle[0],str(start))),
                    xy=(math.pi, 1),
                    horizontalalignment='center',
                    verticalalignment='center')
    for t, az, alt in zip(dt, numpy.deg2rad(sat_az), 90-numpy.array(sat_alt)):
        if t.minute == 0:
            ts = t.strftime('%H:%M')
            if az <= 0.01: h = 'right'
            else: h = 'left'
            pylab.axes(polar=True).annotate(ts,
                    xy=(az, alt),
                    xytext=(az*3-0.03, alt),
                    horizontalalignment=h,
                    verticalalignment='bottom')
    pylab.ylim(0,2)
    pylab.axes(polar=True).set_xticklabels(['N', '', 'E', '', 'S', '', 'W', ''])
    pylab.axes(polar=True).set_yticklabels(['', '', '', ''])

    pylab.savefig('positions.pdf')
    pylab.show()
Exemple #51
0
def petalspsin(a, b):
    t = arange(0, 2 * pi, .01)
    polar(t, a * sin(t * n))
    heading = "%s * sin(t * %s)" % (a, n)
    title(heading)
	def plotMultipleAnglePolarPattern(title, azimuths, polarPattern, ordersToShow) :
		pylab.title(title)
		for order in ordersToShow :
			pattern = [ polarPattern(azimuth, order) for azimuth in azimuths]
			pylab.polar(azimuths, numpy.abs(pattern), label=str(order))
		pylab.show()
Exemple #53
0
P.figure(2)
x = P.linspace(-N.pi,N.pi,64)
P.plot(x,N.sin(x))
P.savefig('sinplot.svg')

P.figure(3)
P.plot(x,N.sin(x),'ro',markersize=5)
P.savefig('sinplot_dots.svg')

P.figure(4)
x = P.linspace(0,500,10000)
P.plot(x,N.exp(-x/100)*N.sin(x))
P.title(u'Una función cualquiera')
P.xlabel('Tiempo')
P.ylabel('Amplitud')
P.savefig('labels.svg')

P.figure(5)
x = P.linspace(-N.pi,N.pi,100)
P.plot(x,N.sinh(x),x,N.cosh(x))
P.legend([u'Seno hiperbólico',u'Coseno hiperbólico'])
P.savefig('legend.svg')

P.figure(6)
theta = P.linspace(-N.pi,N.pi,100)
p1 = P.polar(theta,N.cos(2*theta))
P.savefig('polar.svg')


P.show()
Exemple #54
0
def fazy():
	pha,amp=rob_liste_fazy(o1_sty)
	py.figure()
	py.polar(pha,amp,'o')
	py.savefig(os.getcwd()+'/result/'+NAZWA[-15:]+'faz.png')
Exemple #55
0
def cardioidpsin(a, b):
    t = arange(0, 2 * pi, .01)
    polar(t, a + (b * sin(t)))
    heading = "%s + %s * sin(t)" % (a, b)
    title(heading)
Exemple #56
0
import pylab as py
from numpy import *

a,b,n = 0 , 100*py.pi , 10000
ang = linspace(a,b,n)
rs = cos(py.pi*ang)
py.polar(ang,rs,lw=1,color='b')
py.fill(ang,rs,color = 'w')
py.title("graph of cos(pi x) for x in [0,100pi] using 10000 points",color='r')
py.show()
                     rotatorStateForPlots = sky['rotatorState'][i]
                 else:
                     rotatorStateForPlots = 'R'
                 totals[rotatorStateForPlots] = numpy.concatenate((totals[rotatorStateForPlots],ors))
                 
         for i, d in enumerate(COLORS):
             ax = fig.add_subplot(i+1,numFlies,1+fNum,polar=True)
             if MOD_180:
                 m = (circmean(totals[d]*2.0*numpy.pi/180.0)*180.0/numpy.pi)/2.0
                 m = mod(m,180)
             else:
                 m = circmean(totals[d]*numpy.pi/180.0)*180.0/numpy.pi
             #m=circmean(totals[d]*numpy.pi/180.0)*180.0/numpy.pi
             v=circvar(totals[d]*numpy.pi/180)
             orw,n,b,bc,ax = flypod.rose(totals[d],360)
             pylab.polar([0,numpy.pi/2-m*numpy.pi/180],[0,ax.get_rmax()*(1-v)])
             ax.set_rmax(.15)
             ax.set_rgrids([1],'')
             ax.set_thetagrids([0,90,180,270],['','','',''])
             pylab.title(str(int(round(m))))
             ax.axesPatch.set_facecolor(COLORS[d])
             ax.axesPatch.set_alpha(0.2)
             meanAngle[fNum,i] = m.copy()
             varAngle[fNum,i] = v.copy()
 mA[bd] = meanAngle.copy()
 vA[bd] = varAngle.copy()
 nS[bd] = numStops.copy()
 
 if MOD_180:
     diffAngles = abs(angleDiffDegrees(mA[bd][:,1],mA[bd][:,0]))
     diffAngles[diffAngles>90] = 180 - diffAngles[diffAngles>90]