Example #1
0
def tan(self):
    if type(self) == Dual:
        return Dual(pl.tan(self.fun), self.der/(pl.cos(self.fun)**2))
    elif type(self) == Taylor:
        return sin(self)/cos(self)
    else:
        return pl.tan(self)
Example #2
0
def D(c,f,X):
    '''
    The derived elastica energy as in sharon
    E= a**2 etc.
    '''    
    # either c or f can be an array! not both
    # c: current bar orientation
    # f: flanker orientation
    # x: relative flanker distance and position orientation             
    x = X[0]
    y = X[1]

    ## 'Affinity' D
    # D = Ba^2 + Bb^2 -BaBb
    # Here Ba is the angle of the flanker with the line connecting it with the center
    # and Bb is the reverse for the center
    # See figure 5 in Leung & Malik (1998) for intuitive figure

    # flanker positional angles
    theta = pl.arctan2(x,y)
#        if theta > pi/2: theta-=pi   
#        if theta < -pi/2: theta+=pi

    # B values normalized within -pi to pi
    Ba = pl.arctan(pl.tan(0.5*(-f+theta)))*2     
    Bb = pl.arctan(pl.tan(0.5*(c-theta)))*2


    D = 4*(Ba**2 + Bb**2 - Ba*Bb)
    return D
Example #3
0
def cot(self):
    if type(self) == Dual:
        return Dual(1./pl.tan(self.fun), -1.*self.der/(pl.sin(self.fun)**2))
    elif type(self) == Taylor:
        return cos(self)/sin(self)
    else:
        return 1./pl.tan(self)
Example #4
0
def csc(self):
    if type(self) == Dual:
        return Dual(1./pl.sin(self.fun), -1.*self.der/(pl.tan(self.fun)*pl.sin(self.fun)))
    elif type(self) == Taylor:
        return 1./sin(self)
    else:
        return 1./pl.sin(self)
Example #5
0
def sec(self):
    if type(self) == Dual:
        return Dual(1./pl.cos(self.fun), self.der*pl.tan(self.fun)/pl.cos(self.fun))
    elif type(self) == Taylor:
        return 1./cos(self)
    else:
        return 1./pl.cos(self)
 def __init__(self, fc, dt):
     ita = 1./pl.tan(pl.pi*fc*dt)
     q = pl.sqrt(2)
     self.b = [1./(1+q*ita+ita*ita)]
     self.b.append(2*self.b[0])
     self.b.append(self.b[0])
     self.a = [2*(ita*ita - 1)*self.b[0], -(1-q*ita+ita*ita)*self.b[0]]
     self.reset()
Example #7
0
def plot_jp_tmax_surf(mu,c,phi,pmax,smax,ks):
    # @brief tau max based on varying slip rate, normal pressure
    s_dot = py.arange(0,smax,smax/100.)
    prange = py.arange(0,pmax,pmax/100.)
    kap = 1-py.exp(-s_dot/ks)   #  kappa
    
    TMAX = py.zeros((len(kap),len(prange)))
    tphi = py.tan(phi)  # keep tan(phi) handy
    for k_i in range(0,len(kap)):
        k_tmp = kap[k_i]    
        for p_j in range(0,len(prange)):
            p_tmp = prange[p_j]
            TMAX[k_i][p_j] = k_tmp*(c+p_tmp*tphi) + (1-k_tmp)*p_tmp*mu
            
    fig = plt.figure()           
    ax = fig.add_subplot(121)
    # should be ok to plot the surface
    S, P = py.meshgrid(s_dot, prange)
    CS = plt.contour(S,P,TMAX,8,colors='k',linewidths=1.5)
    plt.clabel(CS,inlne=1,fontsize=16)
    img = plt.imshow(TMAX, interpolation='bilinear', origin='lower',
                     cmap=cm.jet,extent=(min(s_dot),max(s_dot),min(prange),max(prange)))
    CBI = plt.colorbar(img, orientation='vertical',shrink=0.8)
    CBI.set_label(r'$\tau ,max $[psi]')
    ax.set_title(r'$\tau ,max = f(\sigma,\kappa), ks=%.2f $'%ks)
    ax.set_xlabel('slip rate [in/sec]')
    ax.set_ylabel(r'$\sigma_z $',size=24)
    
    # use twice ks, re-calc what's necessary, then replot
    ks2 = ks * 2
    kap2 = 1-py.exp(-s_dot/ks2)
    
    TMAX2 = py.zeros((len(kap2),len(prange)))
    # tphi = py.tan(phi)  # keep tan(phi) handy
    for k_i in range(0,len(kap2)):
        k2_tmp = kap2[k_i]    
        for p_j in range(0,len(prange)):
            p_tmp = prange[p_j]
            TMAX2[k_i][p_j] = k2_tmp*(c+p_tmp*tphi) + (1-k2_tmp)*p_tmp*mu
            
    
    #fig = plt.figure()           
    ax = fig.add_subplot(122)
    # should be ok to plot the surface
    # S, P = py.meshgrid(s_dot, prange)
    CS2 = plt.contour(S,P,TMAX2,8,colors='k',linewidths=1.5)
    plt.clabel(CS2,inlne=1,fontsize=16)
    img2 = plt.imshow(TMAX2, interpolation='bilinear', origin='lower',
                     cmap=cm.jet,extent=(min(s_dot),max(s_dot),min(prange),max(prange)))
    CBI2 = plt.colorbar(img2, orientation='vertical',shrink=0.8)
    CBI2.set_label(r'$\tau ,max $[psi]')
    ax.set_title(r'$\tau ,max = f(\sigma,\kappa), ks=%.2f $'%ks2)
    ax.set_xlabel('slip rate [in/sec]')
    ax.set_ylabel(r'$\sigma_z $',size=24)
Example #8
0
 def __init__(self, fc, dt):
     ita = 1. / pl.tan(pl.pi * fc * dt)
     q = pl.sqrt(2)
     self.b = [1. / (1 + q * ita + ita * ita)]
     self.b.append(2 * self.b[0])
     self.b.append(self.b[0])
     self.a = [
         2 * (ita * ita - 1) * self.b[0],
         -(1 - q * ita + ita * ita) * self.b[0]
     ]
     self.reset()
def main():
    # 3. Create a list A of 600 random numbers bound between (0:10)
    A = [random.random_integers(0, 10) for i in range(600)]
    print("\033[1mList A: \n\033[0m", A)

    # 4. Create an array B with with 500 elements bound in the range [-3*pi:2*pi]
    B = plb.linspace(-3 * plb.pi, 2 * plb.pi, 500, endpoint=True)
    print("\n\033[1mArray B: \n \033[0m", B)

    # 7. Return the result from the function to C
    C = functionOverwriter(A)
    print("\n\033[1mC: \033[0m", type(C))
    print(C)

    # 8. Cast C as an array
    C = array(C)
    print("\n\033[1mC: \033[0m", type(C))
    print(C)

    # 9. Add C to B (think of C as noise) and record the result in D
    D = B + C[:B.size]
    print("\n\033[1mD: \033[0m", D)

    # 10. Create a figure, give it a title and specify your own size and dpi
    plb.figure(figsize=(10, 6), dpi=120)
    plb.title("Sin(D)")

    # 11. Plot the sin of D, in the (2,1,1) location of the figure
    plb.subplot(2, 1, 1)
    plb.plot(plb.sin(D), color="r", label="Sin")

    # 12. Overlay a plot of cos using D, with different color, thickness and type of line
    plb.plot(plb.cos(D), color="b", linewidth=2, linestyle="-.", label="Cos")

    # 13. Create some space on top and bottom of the plot (on the y axis) and show the grid
    plb.ylim(min(plb.cos(D)) - .5, max(plb.cos(D)) + .5)
    plb.grid()

    # 14. Specify the following: title, Y-axis label and legend to fit in the best way
    plb.title("Sin(D) and Cos(D)")
    plb.legend()
    plb.ylabel("Y-axis")
    plb.legend(loc="upper right")

    # 15. Plot the tan of D, in location (2,1,2) with grid showing, X-axis label, Y-axis label
    # and legend on top right
    plb.subplot(2, 1, 2)
    plb.plot(plb.tan(D), color="g", label="Tan")
    plb.ylabel("Y-axis")
    plb.xlabel("X-axis")
    plb.legend(loc="upper right")

    plb.show()
Example #10
0
File: Actor.py Project: ml4ai/b3
 def checkFOV(self, aOther_Pt):
     #Get Angle (in Radians) Limits (and their Slopes)
     nAngView = pylab.deg2rad(25)
     if self.nHeading == '-': return False
     aThis_Pt, aOther_Pt = list(self.aPos), list(aOther_Pt)
     nRad1, nRad2 = self.nHeading + nAngView, self.nHeading - nAngView
     nSlope1, nSlope2, nMaxSlope = pylab.tan(nRad1), pylab.tan(nRad2), 10000
     # @UnusedVariable
     aThis_Pt[1], aOther_Pt[1] = self.nFrm_Height - aThis_Pt[
         1], self.nFrm_Height - aOther_Pt[1]
     aOther_Pt[0], b = (aOther_Pt[0] - aThis_Pt[0]), aThis_Pt[1]
     nOtherX, nOtherY = aOther_Pt[0], aOther_Pt[1]
     #         #Avoid Multiplications where the Slope is close to Infinite
     #         if abs(nSlope1) >= nMaxSlope:
     #             y2 = nSlope2*nOtherX + b;
     #             if nRad2 < pylab.pi/2.0: return (nOtherX>=0) and (nOtherY>=y2);
     #             else: return (nOtherX<=0) and (nOtherY<=y2);
     #         if abs(nSlope2) >= nMaxSlope:
     #             y1 = nSlope1*nOtherX + b;
     #             if nRad1 > (3*pylab.pi)/2.0: return (nOtherX>=0) and (nOtherY<=y1);
     #             else: return (nOtherX<=0) and (nOtherY>=y1);
     #Check position of AngViews
     y1 = nSlope1 * nOtherX + b
     y2 = nSlope2 * nOtherX + b
     nUpLeft, nDownLeft = pylab.pi / 2.0, (3 * pylab.pi) / 2.0
     bAngView1_Left = (nRad1 > nUpLeft) and (nRad1 < nDownLeft)
     #AngView1 on Left Side
     bAngView2_Left = (nRad2 > nUpLeft) and (nRad2 < nDownLeft)
     #AngView2 on Left Side
     bBothLeft = (bAngView1_Left) and (bAngView2_Left)
     bBothRight = (bAngView1_Left == False) and (bAngView2_Left == False)
     bBothUp = (bAngView1_Left) and (bAngView2_Left == False)
     bBothDown = (bAngView1_Left == False) and (bAngView2_Left)
     if bBothLeft and (nOtherY >= y1) and (nOtherY <= y2): return True
     if bBothRight and (nOtherY <= y1) and (nOtherY >= y2): return True
     if bBothUp and (nOtherY >= y1) and (nOtherY >= y2): return True
     if bBothDown and (nOtherY <= y1) and (nOtherY <= y2): return True
     return False
Example #11
0
    def findE(self,c,f,X):
        ''' find E, the approximated sharon energy
        Inputss
        ----------
        - c: current bar orientation, relative to the vertical (can be double or array, if array D returns an array of D values)
        - f: flanker orientation, relative to the vertical  (double)
        - X: flanker position, relative to the current bar (x,y)

	So, as examples...
	findE(0,0,[0,1]) would be two vertical bars, positioned vertically in a line. 
	findE(pi/2,pi/2,[1,0]) would be two horizontal bars, positioned horizontally in a line.        
        '''
        # define x and y 
        x = X[0]
        y = X[1]      
        
        # flanker positional angle
        theta = pl.arctan2(x,y)
        
        # find and return D
        Ba = pl.arctan(tan(0.5*(-f+theta)))*2     
        Bb = pl.arctan(tan(0.5*(c-theta)))*2
        return  4*(Ba**2 + Bb**2 - Ba*Bb)
Example #12
0
def get_bursts(spikes, total_neurons, time_max, verbose=True):
    print 'Extracting bursts.'
    activity_hist, bins = calculate_activity_histogram(spikes, total_neurons,
                                                       bin=1.)
    # NB: BINS IN SECONDS!
    s_activity_hist = sorted(activity_hist, reverse=True)

    # Angle of touching line
    angle = pylab.pi * 3. / 4.
    s_activity_hist_deriv = smooth_data(ND(bins, s_activity_hist), 20)
    cutter = s_activity_hist[
        index_approx(s_activity_hist_deriv, pylab.tan(angle))]
    if verbose:
        print 'Burst threshold found at %f' % cutter

    s_activity_hist = [i if i > cutter else 0 for i in activity_hist]
    s_activity_hist = smooth_data(s_activity_hist, 20)

    bursts_indices_start = []
    bursts_indices_end = []

    for i in xrange(len(s_activity_hist)-1):
        if s_activity_hist[i+1] > 0 and s_activity_hist[i] == 0:
            bursts_indices_start.append(i+1)
        if s_activity_hist[i+1] == 0 and s_activity_hist[i] > 0:
            bursts_indices_end.append(i)

    if bins[bursts_indices_end[0]] < bins[bursts_indices_start[0]]:
        bursts_indices_end.pop(0)
    if bins[bursts_indices_end[-1]] < bins[bursts_indices_start[-1]]:
        bursts_indices_end.pop(-1)

    bursts_indices = []
    for i in xrange(len(bursts_indices_start)):
        activity_hist_buf = activity_hist[bursts_indices_start[i]:
                                          bursts_indices_end[i]]
        bursts_indices.append(
            bursts_indices_start[i] + activity_hist_buf.index(
                max(activity_hist_buf)))

    return (bins, activity_hist, [{'max': bursts_indices[i],
                                   'start': bursts_indices_start[i],
                                   'end': bursts_indices_end[i]}
                                  for i in xrange(len(bursts_indices))])
def tau_a(p, mu, c, phi, j, k):
    tS = 1 - py.exp(-j / k)
    t1 = c * p * py.tan(phi)
    t2 = mu * p
    t_out = min(t1, t2) * tS
    return t_out
def tau_max_soil(p, c, phi):
    return c + p * py.tan(phi)
def plot_jp_tmax_surf(mu, c, phi, pmax, smax, ks):
    # @brief tau max based on varying slip rate, normal pressure
    s_dot = py.arange(0, smax, smax / 100.)
    prange = py.arange(0, pmax, pmax / 100.)
    kap = 1 - py.exp(-s_dot / ks)  #  kappa

    TMAX = py.zeros((len(kap), len(prange)))
    tphi = py.tan(phi)  # keep tan(phi) handy
    for k_i in range(0, len(kap)):
        k_tmp = kap[k_i]
        for p_j in range(0, len(prange)):
            p_tmp = prange[p_j]
            TMAX[k_i][p_j] = k_tmp * (c + p_tmp * tphi) + (1 -
                                                           k_tmp) * p_tmp * mu

    fig = plt.figure()
    ax = fig.add_subplot(121)
    # should be ok to plot the surface
    S, P = py.meshgrid(s_dot, prange)
    CS = plt.contour(S, P, TMAX, 8, colors='k', linewidths=1.5)
    plt.clabel(CS, inlne=1, fontsize=16)
    img = plt.imshow(TMAX,
                     interpolation='bilinear',
                     origin='lower',
                     cmap=cm.jet,
                     extent=(min(s_dot), max(s_dot), min(prange), max(prange)))
    CBI = plt.colorbar(img, orientation='vertical', shrink=0.8)
    CBI.set_label(r'$\tau ,max $[psi]')
    ax.set_title(r'$\tau ,max = f(\sigma,\kappa), ks=%.2f $' % ks)
    ax.set_xlabel('slip rate [in/sec]')
    ax.set_ylabel(r'$\sigma_z $', size=24)

    # use twice ks, re-calc what's necessary, then replot
    ks2 = ks * 2
    kap2 = 1 - py.exp(-s_dot / ks2)

    TMAX2 = py.zeros((len(kap2), len(prange)))
    # tphi = py.tan(phi)  # keep tan(phi) handy
    for k_i in range(0, len(kap2)):
        k2_tmp = kap2[k_i]
        for p_j in range(0, len(prange)):
            p_tmp = prange[p_j]
            TMAX2[k_i][p_j] = k2_tmp * (c + p_tmp * tphi) + (
                1 - k2_tmp) * p_tmp * mu

    #fig = plt.figure()
    ax = fig.add_subplot(122)
    # should be ok to plot the surface
    # S, P = py.meshgrid(s_dot, prange)
    CS2 = plt.contour(S, P, TMAX2, 8, colors='k', linewidths=1.5)
    plt.clabel(CS2, inlne=1, fontsize=16)
    img2 = plt.imshow(TMAX2,
                      interpolation='bilinear',
                      origin='lower',
                      cmap=cm.jet,
                      extent=(min(s_dot), max(s_dot), min(prange),
                              max(prange)))
    CBI2 = plt.colorbar(img2, orientation='vertical', shrink=0.8)
    CBI2.set_label(r'$\tau ,max $[psi]')
    ax.set_title(r'$\tau ,max = f(\sigma,\kappa), ks=%.2f $' % ks2)
    ax.set_xlabel('slip rate [in/sec]')
    ax.set_ylabel(r'$\sigma_z $', size=24)
Example #16
0
 def eval(self,values,x):
   values[0] = - x[0] * tan(alpha) \
               - 1000.0 \
               + 500.0 * sin(2*pi*x[0]/L) * sin(2*pi*x[1]/L)
Example #17
0
def tau_a(p,mu,c,phi,j,k):
    tS = 1 -  py.exp(-j/k)
    t1 = c*p*py.tan(phi)
    t2 = mu*p
    t_out = min(t1,t2)*tS
    return t_out
Example #18
0
def stereoplot(strike, dip, filename):    
    # Here is the stereonet plotting section
    
    bigr = 1.2
    phid = pylab.arange(2, 90, 2)  # Angular range for
    phir = phid * pylab.pi / 180
    omegad = 90 - phid 
    omegar = pylab.pi / 2 - phir
    
    # Set up for plotting great circles with centers along
    # positive x-axis
    
    x1 = bigr * pylab.tan(phir)
    y1 = pylab.zeros(pylab.size(x1))
    r1 = bigr / pylab.cos(phir)
    theta1ad = (180 - 80) * pylab.ones(pylab.size(x1))
    theta1ar = theta1ad * pylab.pi / 180
    theta1bd = (180 + 80) * pylab.ones(pylab.size(x1))
    theta1br = theta1bd * pylab.pi / 180
    
    # Set up for plotting great circles 
    # with centers along the negative x-axis
    x2 = -1 * x1
    y2 = y1
    r2 = r1
    theta2ad = -80 * pylab.ones(pylab.size(x2))
    theta2ar = theta2ad * pylab.pi / 180
    theta2bd = 80 * pylab.ones(pylab.size(x2))
    theta2br = theta2bd * pylab.pi / 180
    
    
    # Set up for plotting small circles
    # with centers along the positive y-axis
    y3 = bigr / pylab.sin(omegar)
    x3 = pylab.zeros(pylab.size(y3))
    r3 = bigr / pylab.tan(omegar)
    theta3ad = 3 * 90 - omegad
    theta3ar = 3 * pylab.pi / 2 - omegar
    theta3bd = 3 * 90 + omegad
    theta3br = 3 * pylab.pi / 2 + omegar
    
    # Set up for plotting small circles
    # with centers along the negative y-axis
    y4 = -1 * y3
    x4 = x3
    r4 = r3
    
    theta4ad = 90 - omegad
    theta4ar = pylab.pi / 2 - omegar
    theta4bd = 90 + omegad
    theta4br = pylab.pi / 2 + omegar
    
    
    # Group all x, y, r, and theta information for great cricles 
    phi = pylab.append(phid, phid, 0)
    x = pylab.append(x1, x2, 0)
    y = pylab.append(y1, y2, 0)
    r = pylab.append(r1, r2)
    
    thetaad = pylab.append(theta1ad, theta2ad, 0)
    thetaar = pylab.append(theta1ar, theta2ar, 0)
    thetabd = pylab.append(theta1bd, theta2bd, 0)
    thetabr = pylab.append(theta1br, theta2br, 0)
    
    # Plot portions of all great circles that lie inside the
    # primitive circle, with thick lines (1 pt.) at 10 degree increments
    
    for i in range(0, len(x)):
        thd = pylab.arange(thetaad[i], thetabd[i] + 1, 1)
        thr = pylab.arange(thetaar[i], thetabr[i] + pylab.pi / 180, pylab.pi / 180)
        xunit = x[i] + r[i] * pylab.cos(pylab.radians(thd))
        yunit = y[i] + r[i] * pylab.sin(pylab.radians(thd))
        # p = pylab.plot(xunit,yunit,'b',lw=.5) #commented out to remove small verticle lines
        pylab.hold(True)   
    
    
    # Now "blank out" the portions of the great circle cyclographic traces 
    # within 10 degrees of the poles of the primitive circle.
    rr = bigr / pylab.tan(80 * pylab.pi / 180)
    ang1 = pylab.arange(0, pylab.pi + pylab.pi / 180, pylab.pi / 180)
    xx = pylab.zeros(pylab.size(ang1)) + rr * pylab.cos(ang1)
    yy = bigr / pylab.cos(10 * pylab.pi / 180) * pylab.ones(pylab.size(ang1)) - rr * pylab.sin(ang1)
    p = pylab.fill(xx, yy, 'w')
    yy = -bigr / pylab.cos(10 * pylab.pi / 180) * pylab.ones(pylab.size(ang1)) + rr * pylab.sin(ang1)
    p = pylab.fill(xx, yy, 'w')
    
    for i in range(1, len(x)):
        thd = pylab.arange(thetaad[i], thetabd[i] + 1, 1)
        thr = pylab.arange(thetaar[i], thetabr[i] + pylab.pi / 180, pylab.pi / 180)
        xunit = x[i] + r[i] * pylab.cos(pylab.radians(thd))
        yunit = y[i] + r[i] * pylab.sin(pylab.radians(thd))
        
        if pylab.mod(phi[i], 10) == 0:
            p = pylab.plot(xunit, yunit, 'b', lw=1)
            angg = thetaad[i]
        pylab.hold(True)
    
    
    # Now "blank out" the portions of the great circle cyclographic traces 
    # within 2 degrees of the poles of the primitive circle.
    rr = bigr / pylab.tan(88 * pylab.pi / 180)
    ang1 = pylab.arange(0, pylab.pi + pylab.pi / 180, pylab.pi / 180)
    xx = pylab.zeros(pylab.size(ang1)) + rr * pylab.cos(ang1)
    yy = bigr / pylab.cos(2 * pylab.pi / 180) * pylab.ones(pylab.size(ang1)) - rr * pylab.sin(ang1)
    
    p = pylab.fill(xx, yy, 'w')
    yy = -bigr / pylab.cos(2 * pylab.pi / 180) * pylab.ones(pylab.size(ang1)) + rr * pylab.sin(ang1)
    p = pylab.fill(xx, yy, 'w')
    
    
    # Group all x, y, r, and theta information for small circles
    phi = pylab.append(phid, phid, 0)
    x = pylab.append(x3, x4, 0)
    y = pylab.append(y3, y4, 0)
    r = pylab.append(r3, r4)
    
    thetaad = pylab.append(theta3ad, theta4ad, 0)
    thetaar = pylab.append(theta3ar, theta4ar, 0)
    thetabd = pylab.append(theta3bd, theta4bd, 0)
    thetabr = pylab.append(theta3br, theta4br, 0)
    
    # Plot primitive circle
    thd = pylab.arange(0, 360 + 1, 1)
    thr = pylab.arange(0, 2 * pylab.pi + pylab.pi / 180, pylab.pi / 180)
    xunit = bigr * pylab.cos(pylab.radians(thd))
    
    yunit = bigr * pylab.sin(pylab.radians(thd))
    p = pylab.plot(xunit, yunit)
    pylab.hold(True)
        
    # Plot portions of all small circles that lie inside the
    # primitive circle, with thick lines (1 pt.) at 10 degree increments
    
    for i in range(0, len(x)):
        thd = pylab.arange(thetaad[i], thetabd[i] + 1, 1)
        thr = pylab.arange(thetaar[i], thetabr[i] + pylab.pi / 180, pylab.pi / 180)
        xunit = x[i] + r[i] * pylab.cos(pylab.radians(thd))
        yunit = y[i] + r[i] * pylab.sin(pylab.radians(thd))
        blug = pylab.mod(thetaad[i], 10)
        if pylab.mod(phi[i], 10) == 0:
            p = pylab.plot(xunit, yunit, 'b', lw=1)
            angg = thetaad[i]
        # else: #Commented out to remove the small horizontal lines
            # p = pylab.plot(xunit,yunit,'b',lw=0.5)
        pylab.hold(True)
    
    # Draw thick north-south and east-west diameters
    xunit = [-bigr, bigr]
    yunit = [0, 0]
    p = pylab.plot(xunit, yunit, 'b', lw=1)
    pylab.hold(True)
    xunit = [0, 0]
    yunit = [-bigr, bigr]
    p = pylab.plot(xunit, yunit, 'b', lw=1)
    pylab.hold(True)
    
    '''
    This is the plotting part'''
    
   
    trend1 = strike
    plunge1 = pylab.absolute(dip)
    # num = leng(lines1(:,1));
    trendr1 = [foo * pylab.pi / 180 for foo in trend1]
    
    plunger1 = [foo * pylab.pi / 180 for foo in plunge1]
    rho1 = [bigr * pylab.tan(pylab.pi / 4 - ((foo) / 2)) for foo in plunger1]
        # polarb plots ccl from 3:00, so convert to cl from 12:00
    # pylab.polar(pylab.pi/2-trendr1,rho1,'o')
    pylab.plot(9000, 90000, 'o', markerfacecolor="b", label='Positive Dip')
    pylab.plot(9000, 90000, 'o', markerfacecolor="w", label='Negative Dip')      
    pylab.legend(loc=1) 
    for n in range(0, len(strike)):
        if dip[n] > 0:
            pylab.plot(rho1[n] * pylab.cos(pylab.pi / 2 - trendr1[n]), rho1[n] * pylab.sin(pylab.pi / 2 - trendr1[n]), 'o', markerfacecolor="b", label='Positive Dip')
        else:
            pylab.plot(rho1[n] * pylab.cos(pylab.pi / 2 - trendr1[n]), rho1[n] * pylab.sin(pylab.pi / 2 - trendr1[n]), 'o', markerfacecolor="w", label='Negative Dip')
         
    '''above is self'''
    pylab.axis([-bigr, bigr, -bigr, bigr])
Example #19
0
def tau_d2(th,th_m,th1,th2,r,b,n,k1,k2,c,K,phi,slip):
    j_disp = jdriven(th,th1,r,slip)
    if( j_disp < 0):
       j_disp = -j_disp
    tau_out = (c+sig_2(th,th_m,th1,th2,r,b,n,k1,k2)*py.tan(phi))*(1.0-py.exp(-j_disp/K))
    return tau_out
Example #20
0
plb.plot(D, plb.cos(D), color="blue", linewidth=2, linestyle="--")

#13. Create some space on top and bottom of the plot (on the y axis) and show the grid
plb.ylim(plb.sin(D).min() - 2, plb.sin(D).max() + 2)
plb.grid()


#14. Specify the following: Title, Y-axis label and legend to fit in the best way
plb.legend(loc='lower right')
plb.ylabel('amplitude', fontsize=10)
plb.title('sin and cos')

#15. Plot the tan of D, in location (2,1,2) with grid showing, X-axis label, Y-axis label 
# and legend on top right
plb.subplot(2,1,2)
plb.plot(D, plb.tan(D))
plb.grid()
plb.xlabel('period', fontsize=10)
plb.ylabel('amplitude', fontsize=10, )
plb.legend(loc='upper right')

#16. Organize your code: use each line from this HW as a comment line before coding each step
#17. Save these steps in a .py file and email it to me before next class. I will run it!
plb.show()

"""
LECTURE 

ADVANCED PLOTTING
"""
Example #21
0
def tau_t2(th,th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip):
    j_disp = j2(th,th0,r,slip)
    if j_disp < 0:
        j_disp = -j_disp
    tau_out = (c+ sig_2(th,th0,th1,th2,r,b,n,k1,k2,)*py.tan(phi))*(1.0-py.exp(-j_disp/K) )
    return tau_out
Example #22
0
 def contactAngleFunc(th0, i, phi):
     out = py.tan(degToRad(45.0)-phi/2.0) - (py.cos(th0) - (1.0/(1.0+i)) ) / py.sin(th0)
     return out
Example #23
0
    """ a blade with inclination angle from the vertical of beta
    Input:
        beta: angle from vertical
    Return:
        [Fp, Fn, Ft] the total, normal and tangent components of the blade force
    """
    return (gamma*nPhi*z**2)/2.0 + 2.*c*py.sqrt(nPhi)*z + nPhi*gamma*sur*z

def Ft_blade(z,nPhi,c,gamma,sur,beta)

# default font size
font = {'size' : 15}
plt.rc('font', **font)

# n_phi = tan(pi/4 + [0,pi/8])^2
nphi = py.tan(py.pi/4.+py.arange(0,py.pi/8.,py.pi/64.))**2
py.plot(py.arange(0,py.pi/4,py.pi/32.),nphi)
py.xlabel(r'$\phi$ [rad]')
py.ylabel(r'N$\phi$')
py.grid(True)

# soil properties
gamma = 100./(12.**3.)  # soil unit weight [lb/in3]
c = 2.9 # cohesion, [psi]
# variables to plot. b and Z can vary a lot, from 0 to ~1 foot
# range of phi, nphi is smaller
b = py.arange(1.0,10.0,0.2)    # blade width [in]
Z = py.arange(1.0,10.0,0.2)    # blade depth [in]
phi = py.arange(0,py.pi/4.,py.pi/128.)   # internal friction angle
nphi = py.tan(py.pi/4.+phi/2.0)**2  # flow value
def tau_b(p, mu, c, phi, j, k, kappa):
    tS = 1 - py.exp(-j / k)
    t1 = c * p * py.tan(phi)
    t2 = mu * p
    t_out = (kappa * t1 + (1 - kappa) * t2) * tS
    return t_out
import pylab

pylab.figure()
pylab.hold(True)

I = pylab.arange(6)

pylab.plot(I, pylab.sin(I), lw=4)

pylab.plot(I, pylab.cos(I), lw=2)

pylab.plot(I, pylab.tan(I), lw=1)

pylab.show()
Example #26
0
C = func_a_update()

C = asarray(C)

D = B + C[0:500]

plb.figure(figsize=(10, 6), dpi=120)

plb.subplot(2, 1, 1)
plb.title('Plot of sin, cos functions')
plb.plot(D, plb.sin(D), color="blue", linewidth=1.5, linestyle='-', label="sin")

plb.hold(True)
plb.plot(D, plb.cos(D), color="red", linewidth=1.2, linestyle='-.', label="cos")

plb.grid()

plb.ylabel('Y-Axis')
plb.legend(loc="lower right")

plb.subplot(2, 1, 2)
plb.title('Plot for tan functions')
plb.plot(D, plb.tan(D), color="red", linewidth=1.5, linestyle='-', label="tan")
plb.xlabel('X-axis')
plb.ylabel('Y-axis')
plb.grid()
plb.legend(loc="upper right")

plb.show()
Example #27
0
def setDiscGeo(geo, Type='Sanden', r2=0.001, **kwargs):
    """
    Sets the discharge geometry for the compressor based on the arguments.
    Also sets the radius of the wall that contains the scroll set
    
    Arguments:
        geo : geoVals class
            class containing the scroll compressor geometry
        Type : string
            Type of discharge geometry, options are ['Sanden'],'2Arc','ArcLineArc'
        r2 : float or string
            Either the radius of the smaller arc as a float or 'PMP' for perfect meshing
            If Type is 'Sanden', this value is ignored
    
    Keyword Arguments:
    
    ========     ======================================================================
    Value        Description
    ========     ======================================================================
    r1           the radius of the large arc for the arc-line-arc solution type
    ========     ======================================================================
    
    """

    #Recalculate the orbiting radius
    geo.ro = geo.rb * (pi - geo.phi_i0 + geo.phi_o0)
    if Type == 'Sanden':
        geo.x0_wall = 0.0
        geo.y0_wall = 0.0
        geo.r_wall = 0.065
        setDiscGeo(geo,
                   Type='ArcLineArc',
                   r2=0.003178893902,
                   r1=0.008796248080)
    elif Type == '2Arc':
        (x_is, y_is) = common_scroll_geo.coords_inv(geo.phi_is, geo, 0, 'fi')
        (x_os, y_os) = common_scroll_geo.coords_inv(geo.phi_os, geo, 0, 'fo')
        (nx_is, ny_is) = common_scroll_geo.coords_norm(geo.phi_is, geo, 0,
                                                       'fi')
        (nx_os, ny_os) = common_scroll_geo.coords_norm(geo.phi_os, geo, 0,
                                                       'fo')
        dx = x_is - x_os
        dy = y_is - y_os

        r2max = 0
        a = cos(geo.phi_os - geo.phi_is) + 1.0
        b = geo.ro * a - dx * (sin(geo.phi_os) - sin(geo.phi_is)) + dy * (
            cos(geo.phi_os) - cos(geo.phi_is))
        c = 1.0 / 2.0 * (2.0 * dx * sin(geo.phi_is) * geo.ro -
                         2.0 * dy * cos(geo.phi_is) * geo.ro - dy**2 - dx**2)
        if abs((geo.phi_os + pi) - geo.phi_is) < 1e-8:
            r2max = -c / b
        elif geo.phi_os - (geo.phi_is - pi) > 1e-12:
            r2max = (-b + sqrt(b**2 - 4.0 * a * c)) / (2.0 * a)
        else:
            print('error with starting angles phi_os %.16f phi_is-pi %.16f' %
                  (geo.phi_os, geo.phi_is - pi))

        if type(r2) is not float and r2 == 'PMP':
            r2 = r2max

        if r2 > r2max:
            print('r2 is too large, max value is : %0.5f' % (r2max))

        xarc2 = x_os + nx_os * r2
        yarc2 = y_os + ny_os * r2

        r1 = ((1.0 / 2 * dy**2 + 1.0 / 2 * dx**2 + r2 * dx * sin(geo.phi_os) -
               r2 * dy * cos(geo.phi_os)) /
              (r2 * cos(geo.phi_os - geo.phi_is) + dx * sin(geo.phi_is) -
               dy * cos(geo.phi_is) + r2))

        ## Negative sign since you want the outward pointing unit normal vector
        xarc1 = x_is - nx_is * r1
        yarc1 = y_is - ny_is * r1

        geo.xa_arc2 = xarc2
        geo.ya_arc2 = yarc2
        geo.ra_arc2 = r2
        geo.t1_arc2 = math.atan2(yarc1 - yarc2, xarc1 - xarc2)
        geo.t2_arc2 = math.atan2(y_os - yarc2, x_os - xarc2)
        while geo.t2_arc2 < geo.t1_arc2:
            geo.t2_arc2 = geo.t2_arc2 + 2.0 * pi

        geo.xa_arc1 = xarc1
        geo.ya_arc1 = yarc1
        geo.ra_arc1 = r1
        geo.t2_arc1 = math.atan2(y_is - yarc1, x_is - xarc1)
        geo.t1_arc1 = math.atan2(yarc2 - yarc1, xarc2 - xarc1)
        while geo.t2_arc1 < geo.t1_arc1:
            geo.t2_arc1 = geo.t2_arc1 + 2.0 * pi
        """ 
        line given by y=m*t+b with one element at the intersection
        point
        
        with b=0, m=y/t
        """
        geo.b_line = 0.0
        geo.t1_line = xarc2 + r2 * cos(geo.t1_arc2)
        geo.t2_line = geo.t1_line
        geo.m_line = (yarc2 + r2 * sin(geo.t1_arc2)) / geo.t1_line
        """ 
        Fit the wall to the chamber
        """
        geo.x0_wall = geo.ro / 2.0 * cos(geo.phi_ie - pi / 2 - pi)
        geo.y0_wall = geo.ro / 2.0 * sin(geo.phi_ie - pi / 2 - pi)
        (x, y) = common_scroll_geo.coords_inv(geo.phi_ie, geo, pi, 'fo')
        geo.r_wall = 1.03 * sqrt((geo.x0_wall - x)**2 + (geo.y0_wall - y)**2)
    elif Type == 'ArcLineArc':
        (x_is, y_is) = common_scroll_geo.coords_inv(geo.phi_is, geo, 0, 'fi')
        (x_os, y_os) = common_scroll_geo.coords_inv(geo.phi_os, geo, 0, 'fo')
        (nx_is, ny_is) = common_scroll_geo.coords_norm(geo.phi_is, geo, 0,
                                                       'fi')
        (nx_os, ny_os) = common_scroll_geo.coords_norm(geo.phi_os, geo, 0,
                                                       'fo')
        dx = x_is - x_os
        dy = y_is - y_os

        r2max = 0
        a = cos(geo.phi_os - geo.phi_is) + 1.0
        b = geo.ro * a - dx * (sin(geo.phi_os) - sin(geo.phi_is)) + dy * (
            cos(geo.phi_os) - cos(geo.phi_is))
        c = 1.0 / 2.0 * (2.0 * dx * sin(geo.phi_is) * geo.ro -
                         2.0 * dy * cos(geo.phi_is) * geo.ro - dy**2 - dx**2)
        if geo.phi_os - (geo.phi_is - pi) > 1e-12:
            r2max = (-b + sqrt(b**2 - 4.0 * a * c)) / (2.0 * a)
        elif geo.phi_os - (geo.phi_is - pi) < 1e-12:
            r2max = -c / b
        else:
            print('error with starting angles phi_os %.16f phi_is-pi %.16f' %
                  (geo.phi_os, geo.phi_is - pi))

        if type(r2) is not float and r2 == 'PMP':
            r2 = r2max

        if r2 > r2max:
            print('r2 is too large, max value is : %0.5f' % (r2max))

        xarc2 = x_os + nx_os * r2
        yarc2 = y_os + ny_os * r2

        if 'r1' not in kwargs:
            r1 = r2 + geo.ro
        else:
            r1 = kwargs['r1']

        ## Negative sign since you want the outward pointing unit normal vector
        xarc1 = x_is - nx_is * r1
        yarc1 = y_is - ny_is * r1

        geo.xa_arc2 = xarc2
        geo.ya_arc2 = yarc2
        geo.ra_arc2 = r2
        geo.t2_arc2 = math.atan2(y_os - yarc2, x_os - xarc2)

        geo.xa_arc1 = xarc1
        geo.ya_arc1 = yarc1
        geo.ra_arc1 = r1
        geo.t2_arc1 = math.atan2(y_is - yarc1, x_is - xarc1)

        alpha = math.atan2(yarc2 - yarc1, xarc2 - xarc1)
        d = sqrt((yarc2 - yarc1)**2 + (xarc2 - xarc1)**2)
        beta = math.acos((r1 + r2) / d)
        L = sqrt(d**2 - (r1 + r2)**2)
        t1 = alpha + beta

        (xint, yint) = (xarc1 + r1 * cos(t1) + L * sin(t1),
                        yarc1 + r1 * sin(t1) - L * cos(t1))
        t2 = math.atan2(yint - yarc2, xint - xarc2)

        geo.t1_arc1 = t1
        #        (geo.t1_arc1,geo.t2_arc1)=sortAnglesCW(geo.t1_arc1,geo.t2_arc1)

        geo.t1_arc2 = t2
        #        (geo.t1_arc2,geo.t2_arc2)=sortAnglesCCW(geo.t1_arc2,geo.t2_arc2)

        while geo.t2_arc2 < geo.t1_arc2:
            geo.t2_arc2 = geo.t2_arc2 + 2.0 * pi
        while geo.t2_arc1 < geo.t1_arc1:
            geo.t2_arc1 = geo.t2_arc1 + 2.0 * pi
        """ 
        line given by y=m*t+b with one element at the intersection
        point
        
        with b=0, m=y/t
        """
        geo.m_line = -1 / tan(t1)
        geo.t1_line = xarc1 + r1 * cos(geo.t1_arc1)
        geo.t2_line = xarc2 + r2 * cos(geo.t1_arc2)
        geo.b_line = yarc1 + r1 * sin(t1) - geo.m_line * geo.t1_line
        """ 
        Fit the wall to the chamber
        """
        geo.x0_wall = geo.ro / 2.0 * cos(geo.phi_ie - pi / 2 - pi)
        geo.y0_wall = geo.ro / 2.0 * sin(geo.phi_ie - pi / 2 - pi)
        (x, y) = common_scroll_geo.coords_inv(geo.phi_ie, geo, pi, 'fo')
        geo.r_wall = 1.03 * sqrt((geo.x0_wall - x)**2 + (geo.y0_wall - y)**2)


#        f=pylab.Figure
#        pylab.plot(x_os,y_os,'o')
#        x=geo.xa_arc1+geo.ra_arc1*cos(np.linspace(geo.t1_arc1,geo.t2_arc1,100))
#        y=geo.ya_arc1+geo.ra_arc1*sin(np.linspace(geo.t1_arc1,geo.t2_arc1,100))
#        pylab.plot(x,y)
#        x=geo.xa_arc2+geo.ra_arc2*cos(np.linspace(geo.t1_arc2,geo.t2_arc2,100))
#        y=geo.ya_arc2+geo.ra_arc2*sin(np.linspace(geo.t1_arc2,geo.t2_arc2,100))
#        pylab.plot(x,y)
#        x=np.linspace(geo.t1_line,geo.t2_line,100)
#        y=geo.m_line*x+geo.b_line
#        pylab.plot(x,y)
#        pylab.plot(xint,yint,'^')
#        pylab.show()
    else:
        print('Type not understood:', Type)
Example #28
0
def tau_b(p,mu,c,phi,j,k,kappa):
    tS = 1 - py.exp(-j/k)
    t1 = c*p*py.tan(phi)
    t2 = mu*p
    t_out = (kappa*t1 + (1-kappa)*t2)*tS
    return t_out
Example #29
0
def tau_max_soil(p,c,phi):
    return c + p*py.tan(phi)
Example #30
0
def tau_bek(th,th1,r,b,n,k1,k2,coh,phi,K,slip):
    j_disp = jdriven(th,th1,r,slip)
    tau_out = (coh +sig_bek(th,th1,r,b,n,k1,k2) *py.tan(phi) ) *(1.0 -py.exp(-j_disp /K) )
    return tau_out
Example #31
0
 def eval(self,values,x):
   values[0] = -x[0]*tan(alpha) - 1000.0
Example #32
0
File: plots.py Project: ibell/pdsim
def setDiscGeo(geo,Type='Sanden',r2=0.001,**kwargs):
    """
    Sets the discharge geometry for the compressor based on the arguments.
    Also sets the radius of the wall that contains the scroll set
    
    Arguments:
        geo : geoVals class
            class containing the scroll compressor geometry
        Type : string
            Type of discharge geometry, options are ['Sanden'],'2Arc','ArcLineArc'
        r2 : float or string
            Either the radius of the smaller arc as a float or 'PMP' for perfect meshing
            If Type is 'Sanden', this value is ignored
    
    Keyword Arguments:
    
    ========     ======================================================================
    Value        Description
    ========     ======================================================================
    r1           the radius of the large arc for the arc-line-arc solution type
    ========     ======================================================================
    
    """
    
    #Recalculate the orbiting radius
    geo.ro=geo.rb*(pi-geo.phi_i0+geo.phi_o0)
    if Type == 'Sanden':
        geo.x0_wall=0.0
        geo.y0_wall=0.0
        geo.r_wall=0.065
        setDiscGeo(geo,Type='ArcLineArc',r2=0.003178893902,r1=0.008796248080)
    elif Type == '2Arc':
        (x_is,y_is) = common_scroll_geo.coords_inv(geo.phi_is,geo,0,'fi') 
        (x_os,y_os) = common_scroll_geo.coords_inv(geo.phi_os,geo,0,'fo')
        (nx_is,ny_is) = common_scroll_geo.coords_norm(geo.phi_is,geo,0,'fi')
        (nx_os,ny_os) = common_scroll_geo.coords_norm(geo.phi_os,geo,0,'fo')
        dx=x_is-x_os
        dy=y_is-y_os
        
        r2max=0
        a=cos(geo.phi_os-geo.phi_is)+1.0
        b=geo.ro*a-dx*(sin(geo.phi_os)-sin(geo.phi_is))+dy*(cos(geo.phi_os)-cos(geo.phi_is))
        c=1.0/2.0*(2.0*dx*sin(geo.phi_is)*geo.ro-2.0*dy*cos(geo.phi_is)*geo.ro-dy**2-dx**2)
        if abs((geo.phi_os+pi)-geo.phi_is) < 1e-8:
            r2max=-c/b
        elif geo.phi_os-(geo.phi_is-pi)>1e-12:
            r2max=(-b+sqrt(b**2-4.0*a*c))/(2.0*a)
        else:
            print('error with starting angles phi_os %.16f phi_is-pi %.16f' %(geo.phi_os,geo.phi_is-pi))
            
        if type(r2) is not float and r2=='PMP':
            r2=r2max
            
        if r2>r2max:
            print('r2 is too large, max value is : %0.5f' %(r2max))
        
        xarc2 =  x_os+nx_os*r2
        yarc2 =  y_os+ny_os*r2
        
        r1=((1.0/2*dy**2+1.0/2*dx**2+r2*dx*sin(geo.phi_os)-r2*dy*cos(geo.phi_os))
               /(r2*cos(geo.phi_os-geo.phi_is)+dx*sin(geo.phi_is)-dy*cos(geo.phi_is)+r2))
        
        
        ## Negative sign since you want the outward pointing unit normal vector
        xarc1 =  x_is-nx_is*r1
        yarc1 =  y_is-ny_is*r1
                
        geo.xa_arc2=xarc2
        geo.ya_arc2=yarc2
        geo.ra_arc2=r2
        geo.t1_arc2=math.atan2(yarc1-yarc2,xarc1-xarc2)
        geo.t2_arc2=math.atan2(y_os-yarc2,x_os-xarc2)
        while geo.t2_arc2<geo.t1_arc2:
            geo.t2_arc2=geo.t2_arc2+2.0*pi;
    
        geo.xa_arc1=xarc1
        geo.ya_arc1=yarc1
        geo.ra_arc1=r1
        geo.t2_arc1=math.atan2(y_is-yarc1,x_is-xarc1)
        geo.t1_arc1=math.atan2(yarc2-yarc1,xarc2-xarc1)
        while geo.t2_arc1<geo.t1_arc1:
            geo.t2_arc1=geo.t2_arc1+2.0*pi;
        
        """ 
        line given by y=m*t+b with one element at the intersection
        point
        
        with b=0, m=y/t
        """
        geo.b_line=0.0
        geo.t1_line=xarc2+r2*cos(geo.t1_arc2)
        geo.t2_line=geo.t1_line
        geo.m_line=(yarc2+r2*sin(geo.t1_arc2))/geo.t1_line
        
        """ 
        Fit the wall to the chamber
        """
        geo.x0_wall=geo.ro/2.0*cos(geo.phi_ie-pi/2-pi)
        geo.y0_wall=geo.ro/2.0*sin(geo.phi_ie-pi/2-pi)
        (x,y)=common_scroll_geo.coords_inv(geo.phi_ie,geo,pi,'fo')
        geo.r_wall=1.03*sqrt((geo.x0_wall-x)**2+(geo.y0_wall-y)**2)
    elif Type=='ArcLineArc':
        (x_is,y_is) = common_scroll_geo.coords_inv(geo.phi_is,geo,0,'fi')
        (x_os,y_os) = common_scroll_geo.coords_inv(geo.phi_os,geo,0,'fo')
        (nx_is,ny_is) = common_scroll_geo.coords_norm(geo.phi_is,geo,0,'fi')
        (nx_os,ny_os) = common_scroll_geo.coords_norm(geo.phi_os,geo,0,'fo')
        dx=x_is-x_os
        dy=y_is-y_os
        
        r2max=0
        a=cos(geo.phi_os-geo.phi_is)+1.0
        b=geo.ro*a-dx*(sin(geo.phi_os)-sin(geo.phi_is))+dy*(cos(geo.phi_os)-cos(geo.phi_is))
        c=1.0/2.0*(2.0*dx*sin(geo.phi_is)*geo.ro-2.0*dy*cos(geo.phi_is)*geo.ro-dy**2-dx**2)
        if geo.phi_os-(geo.phi_is-pi)>1e-12:
            r2max=(-b+sqrt(b**2-4.0*a*c))/(2.0*a)
        elif geo.phi_os-(geo.phi_is-pi)<1e-12:
            r2max=-c/b
        else:
            print('error with starting angles phi_os %.16f phi_is-pi %.16f' %(geo.phi_os,geo.phi_is-pi))
            
        if type(r2) is not float and r2=='PMP':
            r2=r2max
                
        if r2>r2max:
            print('r2 is too large, max value is : %0.5f' %(r2max))
        
        xarc2 =  x_os+nx_os*r2
        yarc2 =  y_os+ny_os*r2
        
        if 'r1' not in kwargs:
            r1=r2+geo.ro
        else:
            r1=kwargs['r1']
        
        ## Negative sign since you want the outward pointing unit normal vector
        xarc1 =  x_is-nx_is*r1
        yarc1 =  y_is-ny_is*r1
                
        geo.xa_arc2=xarc2
        geo.ya_arc2=yarc2
        geo.ra_arc2=r2
        geo.t2_arc2=math.atan2(y_os-yarc2,x_os-xarc2)
    
        geo.xa_arc1=xarc1
        geo.ya_arc1=yarc1
        geo.ra_arc1=r1
        geo.t2_arc1=math.atan2(y_is-yarc1,x_is-xarc1)
                
        alpha=math.atan2(yarc2-yarc1,xarc2-xarc1)
        d=sqrt((yarc2-yarc1)**2+(xarc2-xarc1)**2)
        beta=math.acos((r1+r2)/d)
        L=sqrt(d**2-(r1+r2)**2)
        t1=alpha+beta
        
        (xint,yint)=(xarc1+r1*cos(t1)+L*sin(t1),yarc1+r1*sin(t1)-L*cos(t1))
        t2=math.atan2(yint-yarc2,xint-xarc2)
        
        geo.t1_arc1=t1
#        (geo.t1_arc1,geo.t2_arc1)=sortAnglesCW(geo.t1_arc1,geo.t2_arc1)
        
        geo.t1_arc2=t2
#        (geo.t1_arc2,geo.t2_arc2)=sortAnglesCCW(geo.t1_arc2,geo.t2_arc2)

        while geo.t2_arc2<geo.t1_arc2:
            geo.t2_arc2=geo.t2_arc2+2.0*pi;
        while geo.t2_arc1<geo.t1_arc1:
            geo.t2_arc1=geo.t2_arc1+2.0*pi;
        """ 
        line given by y=m*t+b with one element at the intersection
        point
        
        with b=0, m=y/t
        """
        geo.m_line=-1/tan(t1)
        geo.t1_line=xarc1+r1*cos(geo.t1_arc1)
        geo.t2_line=xarc2+r2*cos(geo.t1_arc2)
        geo.b_line=yarc1+r1*sin(t1)-geo.m_line*geo.t1_line
        
        """ 
        Fit the wall to the chamber
        """
        geo.x0_wall=geo.ro/2.0*cos(geo.phi_ie-pi/2-pi)
        geo.y0_wall=geo.ro/2.0*sin(geo.phi_ie-pi/2-pi)
        (x,y)=common_scroll_geo.coords_inv(geo.phi_ie,geo,pi,'fo')
        geo.r_wall=1.03*sqrt((geo.x0_wall-x)**2+(geo.y0_wall-y)**2)
        
#        f=pylab.Figure
#        pylab.plot(x_os,y_os,'o')
#        x=geo.xa_arc1+geo.ra_arc1*cos(np.linspace(geo.t1_arc1,geo.t2_arc1,100))
#        y=geo.ya_arc1+geo.ra_arc1*sin(np.linspace(geo.t1_arc1,geo.t2_arc1,100))
#        pylab.plot(x,y)
#        x=geo.xa_arc2+geo.ra_arc2*cos(np.linspace(geo.t1_arc2,geo.t2_arc2,100))
#        y=geo.ya_arc2+geo.ra_arc2*sin(np.linspace(geo.t1_arc2,geo.t2_arc2,100))
#        pylab.plot(x,y)
#        x=np.linspace(geo.t1_line,geo.t2_line,100)
#        y=geo.m_line*x+geo.b_line
#        pylab.plot(x,y)
#        pylab.plot(xint,yint,'^')
#        pylab.show()
    else:
        print('Type not understood:',Type)
Example #33
0
def lambert(r1vec,r2vec,tf,m,muC):
# original documentation:
# ·············································
#
# This routine implements a new algorithm that solves Lambert's problem. The
# algorithm has two major characteristics that makes it favorable to other
# existing ones.
#
# 1) It describes the generic orbit solution of the boundary condition
# problem through the variable X=log(1+cos(alpha/2)). By doing so the
# graph of the time of flight become defined in the entire real axis and
# resembles a straight line. Convergence is granted within few iterations
# for all the possible geometries (except, of course, when the transfer
# angle is zero). When multiple revolutions are considered the variable is
# X=tan(cos(alpha/2)*pi/2).
#
# 2) Once the orbit has been determined in the plane, this routine
# evaluates the velocity vectors at the two points in a way that is not
# singular for the transfer angle approaching to pi (Lagrange coefficient
# based methods are numerically not well suited for this purpose).
#
# As a result Lambert's problem is solved (with multiple revolutions
# being accounted for) with the same computational effort for all
# possible geometries. The case of near 180 transfers is also solved
# efficiently.
#
#  We note here that even when the transfer angle is exactly equal to pi
# the algorithm does solve the problem in the plane (it finds X), but it
# is not able to evaluate the plane in which the orbit lies. A solution
# to this would be to provide the direction of the plane containing the
# transfer orbit from outside. This has not been implemented in this
# routine since such a direction would depend on which application the
# transfer is going to be used in.
#
# please report bugs to [email protected]    
#
# adjusted documentation:
# ·······················
#
# By default, the short-way solution is computed. The long way solution
# may be requested by giving a negative value to the corresponding
# time-of-flight [tf].
#
# For problems with |m| > 0, there are generally two solutions. By
# default, the right branch solution will be returned. The left branch
# may be requested by giving a negative value to the corresponding
# number of complete revolutions [m].

# Authors
# .·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.
# Name       : Dr. Dario Izzo
# E-mail     : [email protected]
# Affiliation: ESA / Advanced Concepts Team (ACT)

# Made readible and optimized for speed by Rody P.S. Oldenhuis
# Code available in MGA.M on   http://www.esa.int/gsp/ACT/inf/op/globopt.htm

# last edited 12/Dec/2009

# ADJUSTED FOR EML-COMPILATION 24/Dec/2009
    
    # initial values        
    tol = 1e-12
    bad = False
    days = 1

    # work with non-dimensional units
    r1 = norm(r1vec) #sqrt(r1vec*r1vec.');  r1vec = r1vec/r1;
    r1vec = r1vec / r1
    r2vec = r2vec / r1
    
    V = sqrt(muC/r1)     
    T = r1/V              
    tf= tf*days/T # also transform to seconds

    # relevant geometry parameters (non dimensional)
    mr2vec = norm(r2vec)
    # make 100# sure it's in (-1 <= dth <= +1)
    dth = arccos( max(-1, min(1, (r1vec.dot(r2vec)/mr2vec))))  
    
        
    # decide whether to use the left or right branch (for multi-revolution
    # problems), and the long- or short way    
    leftbranch = sign(m)
    longway = sign(tf)
    m = abs(m)
    tf = abs(tf)
    if (longway < 0):
        dth = 2*pi - dth  

    # derived quantities        
    c      = sqrt(1.0 + mr2vec**2 - 2*mr2vec*cos(dth)) # non-dimensional chord
    s      = (1.0 + mr2vec + c)/2.0                    # non-dimensional semi-perimeter
    a_min  = s/2.0                              # minimum energy ellipse semi major axis
    Lambda = sqrt(mr2vec)*cos(dth/2.0)/s              # lambda parameter (from BATTIN's book)

    crossprd = cross(r1vec,r2vec)

    mcr       = norm(crossprd)           # magnitues thereof
    nrmunit   = crossprd/mcr                        # unit vector thereof
    
    # Initial values
    # ·························································

    # ELMEX requires this variable to be declared OUTSIDE the IF-statement
    logt = log(tf); # avoid re-computing the same value
    
    # single revolution (1 solution)
    if (m == 0):

        # initial values        
        inn1 = -0.5233      # first initial guess
        inn2 = +0.5233      # second initial guess
        x1   = log(1 + inn1)# transformed first initial guess
        x2   = log(1 + inn2)# transformed first second guess

        # multiple revolutions (0, 1 or 2 solutions)
        # the returned soltuion depends on the sign of [m]
    else:          
        # select initial values
        if (leftbranch < 0):
            inn1 = -0.5234 # first initial guess, left branch
            inn2 = -0.2234 # second initial guess, left branch
        else:
            inn1 = +0.7234 # first initial guess, right branch
            inn2 = +0.5234 # second initial guess, right branch
        x1 = tan(inn1*pi/2)# transformed first initial guess
        x2 = tan(inn2*pi/2)# transformed first second guess
    

    # since (inn1, inn2) < 0, initial estimate is always ellipse
    xx   = array([inn1, inn2])
    aa = a_min/(1 - xx**2)
    
    bbeta = longway * 2*arcsin(sqrt((s-c)/2./aa))
    # make 100.4% sure it's in (-1 <= xx <= +1)
    if xx[0] > 1: xx[0] = 1
    if xx[0] < -1: xx[0] = -1
    if xx[1] > 1: xx[1] = 1
    if xx[1] < -1: xx[1] = -1
    aalfa = 2*arccos( xx )

    # evaluate the time of flight via Lagrange expression
    y12  = aa*sqrt(aa)*((aalfa - sin(aalfa)) - (bbeta-sin(bbeta)) + 2*pi*m)

    # initial estimates for y
    if m == 0:
        y1 = log(y12[0]) - logt
        y2 = log(y12[1]) - logt
    else:
        y1 = y12[0] - tf
        y2 = y12[1] - tf
    

    # Solve for x
    # ·························································
    
    # Newton-Raphson iterations
    # NOTE - the number of iterations will go to infinity in case
    # m > 0  and there is no solution. Start the other routine in 
    # that case
    
    err = 1e99  
    iterations = 0
    xnew = 0
    while (err > tol):
        # increment number of iterations
        iterations += 1
        # new x
        xnew = (x1*y2 - y1*x2) / (y2-y1);
        # copy-pasted code (for performance)
        if m == 0:
            x = exp(xnew) - 1
        else:
            x = arctan(xnew)*2/pi
            
        a = a_min/(1 - x**2);
        if (x < 1): # ellipse
            beta = longway * 2*arcsin(sqrt((s-c)/2/a))
            # make 100.4% sure it's in (-1 <= xx <= +1)
            alfa = 2*arccos( max(-1, min(1, x)) )
        else: # hyperbola
            alfa = 2*arccosh(x);
            beta = longway * 2*arcsinh(sqrt((s-c)/(-2*a)))
        
        # evaluate the time of flight via Lagrange expression
        if (a > 0):
            tof = a*sqrt(a)*((alfa - sin(alfa)) - (beta-sin(beta)) + 2*pi*m)
        else:
            tof = -a*sqrt(-a)*((sinh(alfa) - alfa) - (sinh(beta) - beta))
        
        # new value of y
        if m ==0:
            ynew = log(tof) - logt
        else:
            ynew = tof - tf
        # save previous and current values for the next iterarion
        # (prevents getting stuck between two values)
        x1 = x2;  x2 = xnew;
        y1 = y2;  y2 = ynew;
        # update error
        err = abs(x1 - xnew);
        # escape clause
        if (iterations > 15):
            bad = True 
            break
    
    
  
    
    # If the Newton-Raphson scheme failed, try to solve the problem
    # with the other Lambert targeter. 
    if bad:
        # NOTE: use the original, UN-normalized quantities
        #[V1, V2, extremal_distances, exitflag] = ...
        #    lambert_high_LancasterBlanchard(r1vec*r1, r2vec*r1, longway*tf*T, leftbranch*m, muC);
        print "FAILZ0r"
        return
    
    
    # convert converged value of x
    if m==0:
        x = exp(xnew) - 1
    else:
        x = arctan(xnew)*2/pi
    
    #{
    #      The solution has been evaluated in terms of log(x+1) or tan(x*pi/2), we
    #      now need the conic. As for transfer angles near to pi the Lagrange-
    #      coefficients technique goes singular (dg approaches a zero/zero that is
    #      numerically bad) we here use a different technique for those cases. When
    #      the transfer angle is exactly equal to pi, then the ih unit vector is not
    #      determined. The remaining equations, though, are still valid.
    #}

    # Solution for the semi-major axis
    a = a_min/(1-x**2);

    # Calculate psi
    if (x < 1): # ellipse
        beta = longway * 2*arcsin(sqrt((s-c)/2/a))
        # make 100.4# sure it's in (-1 <= xx <= +1)
        alfa = 2*arccos( max(-1, min(1, x)) )
        psi  = (alfa-beta)/2
        eta2 = 2*a*sin(psi)**2/s
        eta  = sqrt(eta2);
    else:       # hyperbola
        beta = longway * 2*arcsinh(sqrt((c-s)/2/a))
        alfa = 2*arccosh(x)
        psi  = (alfa-beta)/2
        eta2 = -2*a*sinh(psi)**2/s
        eta  = sqrt(eta2)
    

    # unit of the normalized normal vector
    ih = longway * nrmunit;

    # unit vector for normalized [r2vec]
    r2n = r2vec/mr2vec;

    # cross-products
    # don't use cross() (emlmex() would try to compile it, and this way it
    # also does not create any additional overhead)
    #crsprd1 = [ih(2)*r1vec(3)-ih(3)*r1vec(2),...
    #           ih(3)*r1vec(1)-ih(1)*r1vec(3),...
    #           ih(1)*r1vec(2)-ih(2)*r1vec(1)];    
    crsprd1 = cross(ih,r1vec)
    #crsprd2 = [ih(2)*r2n(3)-ih(3)*r2n(2),...
    #           ih(3)*r2n(1)-ih(1)*r2n(3),...
    #           ih(1)*r2n(2)-ih(2)*r2n(1)];
    crsprd2 = cross(ih,r2n)

    # radial and tangential directions for departure velocity
    Vr1 = 1/eta/sqrt(a_min) * (2*Lambda*a_min - Lambda - x*eta)
    Vt1 = sqrt(mr2vec/a_min/eta2 * sin(dth/2)**2)

    # radial and tangential directions for arrival velocity
    Vt2 = Vt1/mr2vec
    Vr2 = (Vt1 - Vt2)/tan(dth/2) - Vr1
    
    # terminal velocities
    V1 = (Vr1*r1vec + Vt1*crsprd1)*V
    V2 = (Vr2*r2n + Vt2*crsprd2)*V
    
    # exitflag
    #exitflag = 1 # (success)
    #print "V1:",V1
    #print "V2:",V2
    return V1,V2
def lecture_5_exercise():
    #  Work with only these imports:
    from numpy import matrix, array, random, min, max
    import pylab as plb
    print('''\n
    only using imports:
    from numpy import matrix, array, random, min, max
    import pylab as plb\n''')

    print('Part #1: Create the Data\n')
    #  Create a list A of 600 random numbers bound between [0:10)
    a = list(random.random(600) * 10)
    print('Create a list A of 600 random numbers bound between [0:10):\n{0}\n'.
          format(a))

    #  Create an array B with with 500 elements bound in the range [-3*pi:2*pi]
    b = plb.linspace(3 * plb.pi, 2 * plb.pi, 500, endpoint=True)
    print(
        'Create an array B with with 500 elements bound in the range [-3*pi:2*pi]:\n{0}\n'
        .format(b))

    #  Using if, for or while, create a func4on that overwrites every element in A that falls outside of the interval [2:9)
    print('''\n
    Using if, for or while, create a func4on that overwrites every element in A that falls outside of the interval [2:9)
    overwrite that element with the average between the smallest and largest element in A
    Normalize each list element to be bound between [0:0.1]

    def replace_values(x):
        avg = (min(x) + max(x)) / 2
        for i in x:
            if i < 2 or i > 9:
                x[i] = avg
        x = [(float(y)/max(x) * 0.1) for y in x]
        return x\n''')

    def replace_values(x):
        for index, val in enumerate(x, start=0):
            if val < 2 or val > 9:
                #  overwrite that element with the average between the smallest and largest element in A
                x[index] = (min(x) + max(x)) / 2
                #  Normalize each list element to be bound between [0:0.1]
            x[index] = x[index] / 10
        return x

    #  Return the result from the function to C
    c = replace_values(a)
    print('Return the result from the function to C:\n{0}\n'.format(c))

    #  Cast C as an array
    c = array(c)
    print('Cast C as an array\n')
    print('Type of c: {0}'.format(type(c)))

    #  Add C to B (think of C as noise) and record the result in D
    d = c[0:len(b)] + b
    print(
        'Add C to B (think of C as noise) and record the result in D:\n{0}\n'.
        format(d))

    print('Part #2: Plotting\n')

    #  Create a figure, give it a title and specify your own size and dpi
    fig = plb.figure(figsize=(6, 5), dpi=160)
    fig.canvas.set_window_title('Lecture 5 Class Exercise')

    #  Plot the sin of D, in the (2,1,1) location of the figure
    plb.subplot(2, 1, 1)
    plb.plot(d,
             plb.sin(d),
             color="green",
             linewidth=.5,
             linestyle='-',
             label='sin curve')

    #  Overlay a plot of cos using D, with different color, thickness and type of line
    plb.plot(d,
             plb.cos(d),
             color="grey",
             linewidth=.5,
             linestyle="--",
             label='cos line')

    #  Create some space on top and bottom of the plot (on the y axis) and show the grid
    plb.ylim(plb.sin(d).min() - 1, plb.sin(d).max() + 1)
    plb.grid()

    #  Specify the following: Title, Y-axis label and legend to fit in the best way
    plb.legend(loc='upper right')
    plb.ylabel('Fig 1', fontsize=10)
    plb.title('D sin & cos')

    #  Plot the tan of D, in location (2,1,2) with grid showing, X-axis label, Y-axis label
    # and legend on top right
    plb.subplot(2, 1, 2)
    plb.plot(d, plb.tan(d), color='cyan', linewidth=0.5, label='tan line')
    plb.grid()
    plb.xlabel('label for x axis', fontsize=8)
    plb.ylabel(
        'Fig 2',
        fontsize=9,
    )
    plb.legend(loc='upper left')

    #  Organize your code: use each line from this HW as a comment line before coding each step
    #  Save these steps in a .py file and email it to me before next class. I will run it!
    plb.show()
Example #35
0
 def eval(self,values,x):
     values[0] = -x[0]*pylab.tan(alpha)
Example #36
0
 # 3 = metal, 4 = firm, 5 = medium, 6 = soft
 nuVect = py.array([3.0, 4.0, 5.0, 6.0])
 Fvect = py.array([1650./4.0, 0.0, 1650])
 platesize = 137.5             # p0 = Fz/platesize
 # minimum sum_stress to consider the contribution of cerruti as a percent of the sum
 min_sum_stress_cutoff = 2.0
 # in this case, p0 = 12 psi
 # set the plotting limits. Think of [r,z] as [x,y], ...
 rlim = py.array([0.2,12.])
 zlim = py.array([1.0,12.0]) # z is positive down in VTTI
 rz_rez = 0.2                # grid dim of SMASH
 R = py.arange(rlim[0],rlim[1]+rz_rez,rz_rez)
 Z = py.arange(zlim[0],zlim[1]+rz_rez,rz_rez)
 Rm,Zm = py.meshgrid(R,Z)    # get a meshgrid rep of R,Z          
 angDeg = 45 * py.pi/180.0   # cone angle off the horizontal, in degrees
 slope = py.tan(angDeg)
 for i in range(0, len(nuVect)):
     # current value of Frolich paramter, nu
     nu = nuVect[i]
     # Compute sigma_z for boussinesq and Cerruti
     BousMat = BC.get_BousPlateMat(Fvect,R,Z,nu,platesize,slope)
     # Question: is sigma_z negative when cos(theta) for the applied
     #   surface force, H, is > pi [rad] ???
     CerrMat = BC.get_CerrMat(Fvect,R,Z,platesize,slope)
     # figure out what sign Cerr. is to be, and superimpose
     # with bous
     superPosMat = BousMat + CerrMat
     # cerruti as a percent of the total stress. Note, avoid entries
     # with zero total stress
     cerrPercentMat = py.zeros((len(Z),len(R)))
     for row in range(0,len(Z)):
Example #37
0
 def eval(self,values,x):
     values[0] = -x[0]*pylab.tan(alpha) - 1000.0 + 500.0*pylab.sin(2*pylab.pi*x[0]/L)*pylab.sin(2*pylab.pi*x[1]/L)
ax = fig.add_subplot(1, 1, 1)  # An Axes object is what you see as a plot.

ax.plot(x, y)  # Axes commands are what you use for plotting
ax.set_title("More general way")  # and decorating the plot. Many Axes commands
ax.set_xlabel("x")  # with `set_*` have a counterpart in the
ax.set_ylabel("y")  # pyplot namespace (e.g. `set_title`, `title`)

plt.show()

### Third way: pylab
# Less standard, so less recommended. Can be convenient though.

del x, y  # clear data variables from earlier; they will soon be born again

import pylab as pl  # matplotlib + numpy in one namespace

# This is the same as the first example, but it is a bit more MATLAB-y because
# all the numpy and plotting commands are available under pylab (pl).
x = pl.linspace(0, 4 * pl.pi, 101)
y = pl.tan(x)

pl.plot(x, y)
pl.title("pylab")
pl.xlabel("x")
pl.ylabel("y")

pl.show()

print("foo")
         color='blue',
         linewidth=2.5,
         linestyle='--',
         label='cos')

# Create some space on top and boZom of the plot (on the y axis) and show the grid
plb.ylim(-1.5, 1.5)
plb.grid()

# Specify the following: title, Y-axis label and legend to fit in the best way
plb.legend(loc='best')

# Plot the tan of D, in location (2,1,2) with grid showing, X-axis label, Y-axis label and legend on top right
plb.subplot(2, 1, 2)
plb.plot(D,
         plb.tan(D),
         color='red',
         linewidth=1.5,
         linestyle='-.',
         label='tan')
plb.xlabel('X Axis',
           fontsize=9,
           position=(0.65, 0),
           rotation=6,
           color='gray',
           alpha=0.75)
plb.ylabel('Y Axis', fontsize=9, position=(0, 0.75), color='gray', alpha=0.75)
plb.legend(loc='upper right')
plb.grid()

plb.show()
Example #40
0
import pylab

pylab.figure()
pylab.hold(True)

I = pylab.arange(6)

pylab.plot(I,pylab.sin(I),lw=4)

pylab.plot(I,pylab.cos(I), lw=2)

pylab.plot(I,pylab.tan(I), lw=1)



pylab.show()

    return my_list


C = array(my_overwrite(A))
# print(C)

D = B + C[:500]
# print(D)

# fig = plb.figure()
fig, axes = plb.subplots(nrows=2, ncols=1, figsize=(6, 4), dpi=100)

axes[0].plot(plb.sin(D), color='red', lw=3, ls=' -- ', label='Sin of D')
axes[0].plot(plb.cos(D), color='blue', lw=2, ls='-.', label='Cos of D')

axes[0].grid()

axes[0].set_ylabel('Y Axis')
axes[0].set_xlabel('X Axis')
axes[0].set_title('Signals')
axes[0].legend(loc=0)

axes[1].plot(plb.tan(D), label='Tan')
axes[1].grid()
axes[1].set_xlabel('X Axis')
axes[1].set_ylabel('Y Axis')
axes[1].legend(loc=0)

print("Show me the Figure\n")
plb.show()