def ord_of_am(a, m):
    # a,m需互素
    if ext_gcd(a, m)[0] == 1:
        euler_ = euler(m)
        for _ in range(1, euler(m)):
            # 指数整除euler(m)
            if euler_ % _ == 0:
                mod = exp_mod(a, _, m)
                if mod == 1:
                    return _
        return euler(m)
Esempio n. 2
0
def main():
    dy = lambda x, y: y - 2 * x / y
    y = lambda x: math.sqrt(1 + 2 * x)
    x0 = 0
    y0 = 1
    n = 40
    h = 0.1

    x, y_e = euler(dy, x0, y0, n, h)
    x, y_i_e = improved_euler(dy, x0, y0, n, h)
    x, y_r_k = rung_kutta(dy, x0, y0, n, h)
    y_true = [y(xi) for xi in x]

    print("x\t\ty(4阶龙格)\ty(改进)\t\ty(欧拉)\t\ty(精确)")
    for i in range(10 if len(x) > 10 else len(x)):
        print(format(x[i], '.6f'),
              format(y_r_k[i], '.6f'),
              format(y_i_e[i], '.6f'),
              format(y_e[i], '.6f'),
              format(y_true[i], '.6f'),
              sep="\t")

    plt.plot(x, y_true)
    plt.plot(x, y_e)
    plt.plot(x, y_i_e)
    plt.plot(x, y_r_k)
    plt.legend(["Original", "Euler", "Improve Euler", "Rung Kutta"])
    plt.show()

    n = 20
    h = 0.2
    x, y_e = euler(dy, x0, y0, n, h)
    x, y_i_e = improved_euler(dy, x0, y0, n, h)
    x, y_r_k = rung_kutta(dy, x0, y0, n, h)
    y_true = [y(xi) for xi in x]
    plt.plot(x, y_true)
    plt.plot(x, y_e)
    plt.plot(x, y_i_e)
    plt.plot(x, y_r_k)
    plt.legend(["Original", "Euler", "Improve Euler", "Rung Kutta"])
    plt.show()

    n = 10
    h = 0.4
    x, y_e = euler(dy, x0, y0, n, h)
    x, y_i_e = improved_euler(dy, x0, y0, n, h)
    x, y_r_k = rung_kutta(dy, x0, y0, n, h)
    y_true = [y(xi) for xi in x]
    plt.plot(x, y_true)
    plt.plot(x, y_e)
    plt.plot(x, y_i_e)
    plt.plot(x, y_r_k)
    plt.legend(["Original", "Euler", "Improve Euler", "Rung Kutta"])
    plt.show()
Esempio n. 3
0
def inplanerot(rot=0, grains=None):
    import numpy as np
    if rot == 0: return grains
    from euler import euler
    arot = euler(ph=rot, th=0, tm=0, echo=False)
    for i in range(len(grains)):
        phi1, phi, phi2, wgt = grains[i]
        ag = euler(ph=phi1, th=phi, tm=phi2, echo=False)  # ca<-sa
        agg = np.dot(ag, arot)
        phi1, phi, phi2 = euler(a=agg, echo=False)
        grains[i][0] = phi1
        grains[i][1] = phi
        grains[i][2] = phi2
    return grains
Esempio n. 4
0
def test_find_euler():
    print("\nTask 4: Euler cycle:\n")
    G = [[0, 1, 1, 1, 0, 1], [1, 0, 1, 0, 0, 0], [1, 1, 0, 1, 0, 1],
         [1, 0, 1, 0, 1, 1], [0, 0, 0, 1, 0, 1], [1, 0, 1, 1, 1, 0]]

    matrix = np.array(G)
    graph = nx.from_numpy_matrix(matrix)

    euler_list = []
    euler(G, 0, euler_list)
    print(euler_list)

    plt.subplot(111)
    nx.draw(graph, with_labels=True, font_weight='bold')
    plt.show()
Esempio n. 5
0
def correct_vel(ra, dec, vel, vlsr=220):
	"""Corrects the proper motion for the speed of the Sun
	Arguments:
		ra - RA in deg
		dec -- Declination in deg
		pmra -- pm in RA in mas/yr
		pmdec -- pm in declination in mas/yr
		dist -- distance in kpc
	Returns:
		(pmra,pmdec) the tuple with the proper motions corrected for the Sun's motion
	"""
	
	
	l,b = euler.euler(ra, dec)
	l = np.deg2rad(l)
	b = np.deg2rad(b)
	usun,vsun,wsun = get_uvw_sun(vlsr=vlsr)

	delta = -usun*np.cos(l)*np.cos(b) + vsun * np.sin(l) * np.cos(b) + wsun * np.sin(b)
	# projection of the sun's velocity to the lign of sight vector
	# notice the first minus -- it is because the usun is in the coord system where 
	# X points towards anticenter

	#return the corrected velocity
	return vel + delta
Esempio n. 6
0
    def __init__(self, screen_x, screen_y):

        self.x, self.y = 0.0, 0.0
        self.dx, self.dy = 0.0, 0.0
        self.w, self.h = screen_x, screen_y
        self.margin = point(self.w // 4, self.h // 4)
        self.e = euler(0.0, 0.0)
Esempio n. 7
0
def correct_vel(ra, dec, vel, vlsr=vlsr0):
    """Corrects the proper motion for the speed of the Sun
    Arguments:
        ra - RA in deg
        dec -- Declination in deg
        pmra -- pm in RA in mas/yr
        pmdec -- pm in declination in mas/yr
        dist -- distance in kpc
    Returns:
        (pmra,pmdec) the tuple with the proper motions corrected for the Sun's motion
    """

    l, b = euler.euler(ra, dec)
    l = np.deg2rad(l)
    b = np.deg2rad(b)
    usun, vsun, wsun = get_uvw_sun(vlsr)

    delta = -usun * np.cos(l) * np.cos(b) + vsun * np.sin(l) * np.cos(
        b) + wsun * np.sin(b)
    # projection of the sun's velocity to the lign of sight vector
    # notice the first minus -- it is because the usun is in the coord system where
    # X points towards anticenter

    #return the corrected velocity
    return vel + delta
Esempio n. 8
0
def main(ngrains=100,
         sigma=15.,
         c2a=1.6235,
         mu=0.,
         prc='cst',
         isc=False,
         tilt_1=0.,
         tilts_about_ax1=0.,
         tilts_about_ax2=0.):
    """
    Arguments
    =========
    ngrains = 100
    sigma   = 15.
    c2a     = 1.6235
    prc     = 'cst' or 'ext'
    tilts_about_ax1   = 0.   -- Systematic tilting abount axis 1
    tilts_about_ax2   = 0.   -- Systematic tilting abount axis 2
    tilt_1  = 0.   -- Tilt in the basis pole. (systematic tilting away from ND)
    """
    if isc:
        h = mmm()
    else:
        h = np.array([np.identity(3)])
    gr = []
    for i in xrange(ngrains):
        dth = random.uniform(-180., 180.)
        if prc == 'cst':
            g = gen_gr_fiber(th=dth, sigma=sigma, mu=mu, tilt=tilt_1,
                             iopt=0)  # Basal//ND
        elif prc == 'ext':
            g = gen_gr_fiber(th=dth, sigma=sigma, mu=mu, tilt=tilt_1,
                             iopt=1)  # Basal//ED
        else:
            raise IOError, 'Unexpected option'
        for j in xrange(len(h)):
            temp = np.dot(g, h[j].T)

            ## tilts_about_ax1
            if abs(tilts_about_ax1) > 0:
                g_tilt = rd_rot(tilts_about_ax1)
                temp = np.dot(temp, g_tilt.T)
            ## tilts_about_ax2?
            elif abs(tilts_about_ax2) > 0:
                g_tilt = td_rot(tilts_about_ax2)
                temp = np.dot(temp, g_tilt.T)
            elif abs(tilts_about_ax2) > 0 and abs(tilts_about_ax2) > 0:
                raise IOError, 'One tilt at a time is allowed.'

            phi1, phi, phi2 = euler(a=temp, echo=False)
            gr.append([phi1, phi, phi2, 1. / ngrains])

    mypf = upf.polefigure(grains=gr, csym='hexag', cdim=[1, 1, c2a])
    mypf.pf_new(poles=[[0, 0, 0, 2], [1, 0, -1, 0]],
                cmap='jet',
                ix='TD',
                iy='RD')
    return np.array(gr)
Esempio n. 9
0
File: app.py Progetto: dtang1/DiffEq
def euler():
        if request.method == "GET":
                return render_template("euler.html")
        else:
                points = request.form["points"]
                step = request.form["step"]
                end = request.form["end"]
                input = request.form["input"]
                return render_template("euler.html", output = euler.euler(points,step,end,input))
Esempio n. 10
0
def key():
    p = int(input("Enter p: "))
    q = int(input("Enter q: "))
    n = p * q
    pn = eu.euler(n)
    e = int(input("Enter e: "))
    ei = ex.exe(e, pn)
    d = ei % pn
    return (e, d, n)
Esempio n. 11
0
    def rot(self,r):
        """
        Given rotation matrix that transform the sample axes to another sample axes,
        apply to the all constituent grains in the aggregate.

        Argument
        --------
        r
        """
        from euler import euler
        for i in xrange(len(self.rve)):
            a1,a2,a3 = self.rve[i][:3]
            rot = euler(a1,a2,a3,echo=False) ## CA<-SA(old)
            rt = rot.T        ## SA<-CA
            rt = np.dot(r,rt) ## SA`<-SA<-CA
            rot = rt.T         ## CA<-SA`
            a1,a2,a3 = euler(a=rot,echo=False)
            self.rve[i][:3]=a1,a2,a3
def all_primitive_roots(p):
    root = primitive_root(p)
    euler_ = euler(p)
    root_list = []
    for _ in range(2, euler_):
        # 指数与euler(m)互素
        if ext_gcd(_, euler_)[0] == 1:
            root_list.append(_)
            # print(_, end=',')
    return root_list
Esempio n. 13
0
def multy_orders(m):
    f = euler(m)
    divisors = get_divisors(f)
    orders = {}
    for i in range(2, f + 1):
        for divisor in divisors:
            if (i ** divisor) % m == 1:
                orders[i] = divisor
                break
    return orders
Esempio n. 14
0
def get_euler(pdb1, pdb2):
  atoms1 = read_pdb(pdb1)
  atoms2 = read_pdb(pdb2)

  if len(atoms1) != len(atoms2):
    raise Exception("Different atom numbers: %s: %d, %s: %d" % (pdb1, len(atoms1), pdb2, len(atoms2)))

  atoms1 = numpy.array(atoms1)
  atoms2 = numpy.array(atoms2)

  return euler.euler(atoms1, atoms2)
Esempio n. 15
0
def miller2euler(hkl, uvw):
    """
    RD // uvw  // 1
    ND // hkl  // 3

    3 x 1 = 2
    """
    from euler import euler
    # mat [ca<-sa]
    mat = miller2mat(hkl, uvw)
    phi1, phi, phi2 = euler(a=mat, echo=False)
    return phi1, phi, phi2
Esempio n. 16
0
def coveragemap(nside=64, nyears=5, galactic=False, nthreads=24):
    # returns the number of visits of the healpix map of given resolution
    # as well as the times of observations for a given healpixel
    # The healpixes are in the NESTED scheme
    tottime = nyears * 365.25  # 5yrs
    step = 0.00005  # days
    times = np.arange(tottime / step) * step
    ntimes = len(times)
    nchunks = 10
    pool = mp.Pool(nthreads)

    #vecs =  scanninglaw(times)
    xtimes = [
        times[i * (ntimes // nthreads + 1):(i + 1) * (ntimes // nthreads + 1)]
        for i in range(nthreads)
    ]
    xvecs = pool.map(scanninglaw, xtimes)
    pool.close()
    pool.join()

    _tmp1 = np.hstack([_[0] for _ in xvecs])
    _tmp2 = np.hstack([_[1] for _ in xvecs])
    vecs = _tmp1, _tmp2
    cosd = lambda x: np.cos(np.deg2rad(x))
    sind = lambda x: np.sin(np.deg2rad(x))
    getxyz = lambda r, d: [cosd(r) * cosd(d), sind(r) * cosd(d), sind(d)]

    tree1 = scipy.spatial.cKDTree(vecs[0].T)
    tree2 = scipy.spatial.cKDTree(vecs[1].T)

    si.tree1 = tree1
    si.tree2 = tree2
    si.times = times

    ipixes = np.arange(12 * nside**2)
    if galactic:
        ls, bs = pix2radec(nside, ipixes)
        ras, decs = euler.euler(ls, bs, 2)
    else:
        ras, decs = pix2radec(nside, ipixes)
    ra0 = 18 * 15
    dec0 = 66 + 33 / 60. + 38.55 / 3600.  # pole of the ecliptic
    eclipra, eclipdec = sphere_rotate.sphere_rotate(ras, decs, ra0, dec0, 0)
    eclipra = (eclipra + 360) % 360
    pool = mp.Pool(nthreads)

    res = pool.map(numcovers, np.array(getxyz(eclipra, eclipdec)).T, nchunks)
    #res = map(numcovers,np.array(getxyz(eclipra,eclipdec)).T)
    pool.close()
    pool.join()
    poss = np.array([_[0] for _ in res])
    obstimes = [_[1] for _ in res]
    return poss, obstimes
Esempio n. 17
0
def miller2euler(hkl, uvw):
    """
    RD // uvw  // 1
    ND // hkl  // 3

    3 x 1 = 2
    """
    from euler import euler
    # mat [ca<-sa]
    mat = miller2mat(hkl, uvw)
    phi1, phi, phi2 = euler(a=mat, echo=False)
    return phi1, phi, phi2
Esempio n. 18
0
def sample_mmm(fn=None):
    """
    Apply the orthorhombic sample symmetry 2/m 2/m 2/m (shortened as mmm)
    360/2 = 180 rotation

    mmm contains: 4 operators (itself, m, m, m)
    """
    import numpy as np
    from euler import euler

    m0 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    m1 = [[1, 0, 0], [0, -1, 0], [0, 0, -1]]
    m2 = [[-1, 0, 0], [0, 1, 0], [0, 0, -1]]
    m3 = [[-1, 0, 0], [0, -1, 0], [0, 0, 1]]

    mmm = [m1, m2, m3]

    grains = np.loadtxt(fn, skiprows=4)
    grains_t = grains.T
    wgt = grains_t[-1][::]
    grains_t[-1] = grains_t[-1] / sum(wgt)
    grains = grains_t.T
    grains_new = []
    for i in range(len(grains)):
        amat = euler(ph=grains[i][0],
                     th=grains[i][1],
                     tm=grains[i][2],
                     echo=None)  # ca<-sa
        amat0 = [amat]
        #amat0.append(np.dot(amat, m1))
        for j in range(len(mmm)):
            #n = len(amat0)
            #for k in range(n):
            #amat0.append(np.dot(amat0[k],mmm[j]))
            amat0.append(np.dot(amat0[0], mmm[j]))

        for j in range(len(amat0)):
            phi1, phi, phi2 = euler(a=amat0[j], echo=False)
            grains_new.append([phi1, phi, phi2, grains[i][-1] / len(amat0)])
    return grains_new
Esempio n. 19
0
File: prec.py Progetto: r-owen/RO
def prec(begEpoch, endEpoch):
    """
    Return the matrix of precession between two epochs
    (IAU 1976, FK5)
    
    Inputs:
    - begEpoch  beginning Julian epoch (e.g. 2000 for J2000)
    - endEpoch  ending Julian epoch
    
    Returns:
    - pMat      the precession matrix as a 3x3 numpy.array,
                where pos(endEpoch) = rotMat * pos(begEpoch)
    
    Based on Pat Wallace's PREC. His notes follow:
    - The epochs are TDB (loosely ET) Julian epochs.
    - Though the matrix method itself is rigorous, the precession
    angles are expressed through canonical polynomials which are
    valid only for a limited time span.  There are also known
    errors in the IAU precession rate.  The absolute accuracy
    of the present formulation is better than 0.1 arcsec from
    1960AD to 2040AD, better than 1 arcsec from 1640AD to 2360AD,
    and remains below 3 arcsec for the whole of the period
    500BC to 3000AD.  The errors exceed 10 arcsec outside the
    range 1200BC to 3900AD, exceed 100 arcsec outside 4200BC to
    5600AD and exceed 1000 arcsec outside 6800BC to 8200AD.
    The routine PRECL implements a more elaborate model
    which is suitable for problems spanning several thousand years.
    
    References:
    Lieske,J.H., 1979. Astron.Astrophys.,73,282.
    equations (6) & (7), p283.
    Kaplan,G.H., 1981. USNO circular no. 163, pA2.
    """
    # Interval between basic epoch J2000.0 and beginning epoch (JC)
    t0 = (begEpoch-2000.0)/100.0

    # Interval over which precession required (JC)
    dt = (endEpoch-begEpoch)/100.0

    # Euler angles
    tas2r = dt*RO.PhysConst.RadPerArcSec
    w = 2306.2181+(1.39656-0.000139*t0)*t0

    zeta = (w+((0.30188-0.000344*t0)+0.017998*dt)*dt)*tas2r
    z = (w+((1.09468+0.000066*t0)+0.018203*dt)*dt)*tas2r
    theta = ((2004.3109+(-0.85330-0.000217*t0)*t0)  \
        +((-0.42665-0.000217*t0)-0.041833*dt)*dt)*tas2r

    # Rotation matrix
    return euler([(2, -zeta), (1, theta), (2, -z)])
Esempio n. 20
0
def prec(begEpoch, endEpoch):
    """
    Return the matrix of precession between two epochs
    (IAU 1976, FK5)
    
    Inputs:
    - begEpoch  beginning Julian epoch (e.g. 2000 for J2000)
    - endEpoch  ending Julian epoch
    
    Returns:
    - pMat      the precession matrix as a 3x3 numpy.array,
                where pos(endEpoch) = rotMat * pos(begEpoch)
    
    Based on Pat Wallace's PREC. His notes follow:
    - The epochs are TDB (loosely ET) Julian epochs.
    - Though the matrix method itself is rigorous, the precession
    angles are expressed through canonical polynomials which are
    valid only for a limited time span.  There are also known
    errors in the IAU precession rate.  The absolute accuracy
    of the present formulation is better than 0.1 arcsec from
    1960AD to 2040AD, better than 1 arcsec from 1640AD to 2360AD,
    and remains below 3 arcsec for the whole of the period
    500BC to 3000AD.  The errors exceed 10 arcsec outside the
    range 1200BC to 3900AD, exceed 100 arcsec outside 4200BC to
    5600AD and exceed 1000 arcsec outside 6800BC to 8200AD.
    The routine PRECL implements a more elaborate model
    which is suitable for problems spanning several thousand years.
    
    References:
    Lieske,J.H., 1979. Astron.Astrophys.,73,282.
    equations (6) & (7), p283.
    Kaplan,G.H., 1981. USNO circular no. 163, pA2.
    """
    # Interval between basic epoch J2000.0 and beginning epoch (JC)
    t0 = (begEpoch - 2000.0) / 100.0

    # Interval over which precession required (JC)
    dt = (endEpoch - begEpoch) / 100.0

    # Euler angles
    tas2r = dt * RO.PhysConst.RadPerArcSec
    w = 2306.2181 + (1.39656 - 0.000139 * t0) * t0

    zeta = (w + ((0.30188 - 0.000344 * t0) + 0.017998 * dt) * dt) * tas2r
    z = (w + ((1.09468 + 0.000066 * t0) + 0.018203 * dt) * dt) * tas2r
    theta = ((2004.3109+(-0.85330-0.000217*t0)*t0)  \
        +((-0.42665-0.000217*t0)-0.041833*dt)*dt)*tas2r

    # Rotation matrix
    return euler([(2, -zeta), (1, theta), (2, -z)])
Esempio n. 21
0
def find_euler_random(n):
    while True:
        el = np.array([random.randint(0, 4) * 2 for x in range(n + 1)])
        try:
            g = Graph.from_sequence(el)
            choose_biggest_comp(g)
            if g.adjacency.shape[0] != n: continue
            print(g.adjacency)
            # Randomize graph
            for i in range(el.shape[0] * 3):
                g.randomize_edges()
            print(g.adjacency)

            graph = nx.from_numpy_matrix(g.adjacency)
            euler_list = []
            euler(g.adjacency.tolist(), 0, euler_list)
            print(euler_list)

            plt.subplot(111)
            nx.draw(graph, with_labels=True, font_weight='bold')
            plt.show()
            break
        except NotGraphicSequenceException:
            continue
Esempio n. 22
0
def rk2_int(function, x0, x1, y, n):
    old_y = y
    h = (x1 - x0) / float(n)
    old_x = x0
    for i in range(1, n + 1):
        new_x = old_x + h

        temp = function(old_x, old_y) + function(
            old_x, euler(function, old_x, new_x, old_y, n))

        new_y = old_y + 0.5 * h * temp
        old_x = new_x
        old_y = new_y

    return new_y
Esempio n. 23
0
def shooting(f, l, mu1, mu2, h, theta0):
    def y0(theta):
        return np.array([mu1, theta])

    def F(t, u):
        print(u.shape)
        return np.array([u[:, 0], f(t, u[:, 1])])

    def R(theta):
        y, x = euler(F, [y0(theta)], h, l)
        print(y0(theta))
        r = y[-1, 0] - mu2
        return r

    theta = optimize.fsolve(R, theta0)
    y, x = euler(F, [y0(theta)], h, l)
    return y[:, 0], x
Esempio n. 24
0
def rk2_tuple(function, x0, x1, y, n):
    old_y = y
    h = (x1 - x0) / float(n)
    old_x = x0
    for i in range(1, n + 1):
        new_x = old_x + h

        temp = add_two_tuples(function(old_x, old_y),
                              function(old_x, euler(function, old_x,
                                                    new_x, old_y)))

        new_y = add_two_tuples(old_y, multi_tuple(0.5 * h, (temp)))

        old_x = new_x
        old_y = new_y

    return new_y
Esempio n. 25
0
def main(ngrains=100,sigma=15.,c2a=1.6235,mu=0.,
         prc='cst',isc=False,tilt_1=0.,
         tilts_about_ax1=0.,tilts_about_ax2=0.):
    """
    Arguments
    =========
    ngrains = 100
    sigma   = 15.
    c2a     = 1.6235
    prc     = 'cst' or 'ext'
    tilts_about_ax1   = 0.   -- Systematic tilting abount axis 1
    tilts_about_ax2   = 0.   -- Systematic tilting abount axis 2
    tilt_1  = 0.   -- Tilt in the basis pole. (systematic tilting away from ND)
    """
    if isc:
        h  = mmm()
    else:
        h=np.array([np.identity(3)])
    gr = []
    for i in xrange(ngrains):
        dth = random.uniform(-180., 180.)
        if prc=='cst':   g = gen_gr_fiber(th=dth,sigma=sigma,mu=mu,tilt=tilt_1,iopt=0) # Basal//ND
        elif prc=='ext': g = gen_gr_fiber(th=dth,sigma=sigma,mu=mu,tilt=tilt_1,iopt=1)  # Basal//ED
        else:
            raise IOError, 'Unexpected option'
        for j in xrange(len(h)):
            temp = np.dot(g,h[j].T)

            ## tilts_about_ax1
            if abs(tilts_about_ax1)>0:
                g_tilt = rd_rot(tilts_about_ax1)
                temp = np.dot(temp,g_tilt.T)
            ## tilts_about_ax2?
            elif abs(tilts_about_ax2)>0:
                g_tilt = td_rot(tilts_about_ax2)
                temp = np.dot(temp,g_tilt.T)
            elif abs(tilts_about_ax2)>0 and abs(tilts_about_ax2)>0:
                raise IOError, 'One tilt at a time is allowed.'

            phi1,phi,phi2 = euler(a=temp, echo=False)
            gr.append([phi1,phi,phi2,1./ngrains])

    mypf=upf.polefigure(grains=gr,csym='hexag',cdim=[1,1,c2a])
    mypf.pf_new(poles=[[0,0,0,2],[1,0,-1,0]],cmap='jet',ix='TD',iy='RD')
    return np.array(gr)
Esempio n. 26
0
def randomGrain(phi1,phi2,phi):
    """
    Generate a single 'randomly' oriented
    grain and return its 'rotation' matrix

    Argument
    --------
    ## maximum bounds of the thee euler angles.
    phi1
    phi2
    phi
    """
    from euler import euler
    cp1 = rand() * phi1  #phi1
    cp2 = rand() * phi2  #phi2
    cp = rand() # 0~1
    cp = math.acos(cp) * 180./math.pi
    return euler(ph=cp1,th=cp,tm=cp2,echo=False)
Esempio n. 27
0
def main(ngrains=100, sigma=5.0, iopt=1, ifig=1):
    """
    arguments
    =========
    ngrains = 100
    sigma   = 5.
    iopt    = 1 (1: gauss (recommended); 2: expov; 3: logno; 4: norma)
    ifig    = 1
    """
    import upf
    import matplotlib.pyplot as plt

    h = mmm()
    gr = []
    for i in range(ngrains):
        dth = random.uniform(-180.0, 180.0)
        g = gen_gamma_gr(dth, sigma, iopt=iopt)
        for j in range(len(h)):
            temp = np.dot(g, h[j].T)
            phi1, phi, phi2 = euler(a=temp, echo=False)
            gr.append([phi1, phi, phi2, 1.0 / ngrains])

    fn = "gam_fib_ngr%s_sigma%s.cmb" % (str(len(gr)).zfill(5), str(sigma).zfill(3))
    f = open(fn, "w")
    f.writelines("Artificial gamma fibered polycrystal aggregate\n")
    f.writelines("var_gam_fiber.py python script\n")
    f.writelines("distribution: %s")
    if iopt == 1:
        f.writelines(" gauss")
    if iopt == 2:
        f.writelines(" expov")
    if iopt == 3:
        f.writelines(" logno")
    if iopt == 4:
        f.writelines(" norma")
    f.writelines("\n")
    f.writelines("B %i\n" % ngrains)
    for i in range(len(gr)):
        f.writelines("%7.3f %7.3f %7.3f %13.4e\n" % (gr[i][0], gr[i][1], gr[i][2], 1.0 / len(gr)))

    upf.cubgr(gr=gr, ifig=ifig)
    plt.figure(ifig).savefig("%s.pdf" % (fn.split(".cmb")[0]))

    return np.array(gr)
Esempio n. 28
0
def predictor_corrector(fp, b, t, h, p):
	"""
	tuple b   = coordinates of boundary condition (x0, y0)
	float h   = step
	int t     = number of steps
	lambda fp = dy/dx
	int p     = significant digits after x values
	"""
	
	ret = euler.euler(fp,b, 1, h, p)
	x = b[0]
	
	for i in range(1, t):
		x = round(x + h, p)
		yt = predictor(fp, x, ret[i][1], ret[i-1][1], h)
		y  = predictor(fp, x, ret[i][1], yt, h)
		ret.append((x,y))
	
	return ret
Esempio n. 29
0
    def __init__(self,
                 x,
                 y,
                 max_speed,
                 acceleration,
                 deceleration,
                 width,
                 height,
                 dx=0,
                 dy=0):

        self.e = euler(acceleration, deceleration)

        self.x, self.y, self.dx, self.dy = x, y, dx, dy
        self.w, self.h = width, height
        self.max_speed = max_speed

        self.up, self.down, self.left, self.right = False, False, False, False

        self.old = point(self.x, self.y)
Esempio n. 30
0
def main(ngrains=100,sigma=5.,iopt=1,ifig=1):
    """
    arguments
    =========
    ngrains = 100
    sigma   = 5.
    iopt    = 1 (1: gauss (recommended); 2: expov; 3: logno; 4: norma)
    ifig    = 1
    """
    import upf
    import matplotlib.pyplot as plt
    h = mmm()
    gr = []
    for i in range(ngrains):
        dth = random.uniform(-180., 180.)
        g = gen_gamma_gr(dth, sigma, iopt=iopt)
        for j in range(len(h)):
            temp = np.dot(g,h[j].T)
            phi1,phi,phi2 = euler(a=temp, echo=False)
            gr.append([phi1,phi,phi2,1./ngrains])

    fn = 'gam_fib_ngr%s_sigma%s.cmb'%(str(len(gr)).zfill(5),str(sigma).zfill(3))
    f = open(fn,'w')
    f.writelines('Artificial gamma fibered polycrystal aggregate\n')
    f.writelines('var_gam_fiber.py python script\n')
    f.writelines('distribution: %s')
    if iopt==1: f.writelines(' gauss')
    if iopt==2: f.writelines(' expov')
    if iopt==3: f.writelines(' logno')
    if iopt==4: f.writelines(' norma')
    f.writelines('\n')
    f.writelines('B %i\n'%ngrains)
    for i in range(len(gr)):
        f.writelines('%7.3f %7.3f %7.3f %13.4e\n'%(
            gr[i][0], gr[i][1], gr[i][2], 1./len(gr)))

    upf.cubgr(gr=gr,ifig=ifig)
    plt.figure(ifig).savefig('%s.pdf'%(fn.split('.cmb')[0]))

    return np.array(gr)
Esempio n. 31
0
def prebn(bep0, bep1):
    """
    Generate the matrix of precession between two epochs,
    using the old, pre-IAU1976, Bessel-Newcomb model,
    using Kinoshita's formulation.
    
    Inputs:
    - bep0      beginning Besselian epoch
    - bep1      ending Besselian epoch
    
    Returns:
    - pMat      the precession matrix, a 3x3 numpy.array
    
    The matrix is in the sense  p(bep1)  =  pMat * p(bep0)
    
    Reference:
    Kinoshita, H. (1975) 'Formulas for precession', SAO Special
    Report No. 364, Smithsonian Institution Astrophysical
    Observatory, Cambridge, Massachusetts.
    """
    # Interval between basic epoch b1850.0 and beginning epoch,
    # in tropical centuries
    bigt = (bep0 - 1850.0) / 100.0

    # Interval over which precession required, in tropical centuries
    t = (bep1 - bep0) / 100.0

    # Euler angles
    tas2r = t * RO.PhysConst.RadPerArcSec
    w = 2303.5548 + (1.39720 + 0.000059 * bigt) * bigt

    zeta = (w + (0.30242 - 0.000269 * bigt + 0.017996 * t) * t) * tas2r
    z = (w + (1.09478 + 0.000387 * bigt + 0.018324 * t) * t) * tas2r
    theta = (2005.1125+(-0.85294-0.000365*bigt)*bigt+  \
        (-0.42647-0.000365*bigt-0.041802*t)*t)*tas2r

    # Rotation matrix
    return euler([(2, -zeta), (1, theta), (2, -z)])
Esempio n. 32
0
File: prebn.py Progetto: r-owen/RO
def prebn(bep0, bep1):
    """
    Generate the matrix of precession between two epochs,
    using the old, pre-IAU1976, Bessel-Newcomb model,
    using Kinoshita's formulation.
    
    Inputs:
    - bep0      beginning Besselian epoch
    - bep1      ending Besselian epoch
    
    Returns:
    - pMat      the precession matrix, a 3x3 numpy.array
    
    The matrix is in the sense  p(bep1)  =  pMat * p(bep0)
    
    Reference:
    Kinoshita, H. (1975) 'Formulas for precession', SAO Special
    Report No. 364, Smithsonian Institution Astrophysical
    Observatory, Cambridge, Massachusetts.
    """
    # Interval between basic epoch b1850.0 and beginning epoch,
    # in tropical centuries
    bigt = (bep0-1850.0)/100.0

    # Interval over which precession required, in tropical centuries
    t = (bep1-bep0)/100.0

    # Euler angles
    tas2r = t*RO.PhysConst.RadPerArcSec
    w = 2303.5548+(1.39720+0.000059*bigt)*bigt

    zeta = (w+(0.30242-0.000269*bigt+0.017996*t)*t)*tas2r
    z = (w+(1.09478+0.000387*bigt+0.018324*t)*t)*tas2r
    theta = (2005.1125+(-0.85294-0.000365*bigt)*bigt+  \
        (-0.42647-0.000365*bigt-0.041802*t)*t)*tas2r

    # Rotation matrix
    return euler([(2, -zeta), (1, theta), (2, -z)])
Esempio n. 33
0
File: nut.py Progetto: r-owen/RO
def nut(tdb):
    """
    Form the matrix of nutation for a given TDB - IAU 1980 theory
    (double precision)
    
    References:
    Final report of the IAU Working Group on Nutation,
    chairman P.K.Seidelmann, 1980.
    Kaplan,G.H., 1981, USNO circular no. 163, pA3-6.
    
    Inputs:
    - TDB   TDB date (loosely et) as Modified Julian Date

    Returns the nutation matrix as a 3x3 numpy.array
    
    The matrix is in the sense  V(true)  =  rmatn * V(mean)
    """
    # Nutation components and mean obliquity
    dpsi, deps, eps0 = nutc(tdb)

    # Rotation matrix
    return euler((
        (0, eps0), (2, -dpsi), (0, -(eps0+deps))
    ))
Esempio n. 34
0
## Import all of my methods
import euler
import rk2
import rk4
import se1
import se2
import sho1

import numpy as np
import matplotlib.pyplot as plt

## Execute the calculations of each one
euler.euler(euler.x, euler.v)
rk2.rk2(rk2.x, rk2.v)
rk4.rk4(rk4.x, rk4.v)
se1.se1(se1.x, se1.p)
se2.se2(se2.x, se2.p)

methods = [euler, rk2, rk4, se1, se2]
colors = ["r-", "y-", "g-", "b-", "c-"]

## Graphing area
for i, method in enumerate(methods):
    plt.plot(method.t_points, method.e_points, colors[i], label=method.name)
    plt.legend()
    plt.xlabel("t")
    plt.ylabel("total energy")
    plt.title("Energy Conservation")

plt.plot(sho1.t_points, sho1.e_points, "r--", label=sho1.name)
plt.show()
Esempio n. 35
0
 def test_euler_6(self):
     self.number = 6
     result = euler.euler(self.number)[self.number - 1]
     self.assertEqual(result, 13)
Esempio n. 36
0
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 18:57:49 2015

@author: elsa
"""
from euler import euler

with open("1000digit.txt", encoding="utf-8") as doc:
    digit = doc.read().replace("\n", "")
    digitlist = list([int(x) for x in digit])
    print(euler(digitlist))
Esempio n. 37
0
    def sample_sym_ortho(self):
        """
        Application of sample symmetry

        'mmm' operation (orthorhombic sample symmetry operation
        """
        from euler import euler

        m0 = [[  1,  0,  0],  [  0,  1,  0],  [  0,  0,  1]]
        m1 = [[  1,  0,  0],  [  0, -1,  0],  [  0,  0, -1]]
        m2 = [[ -1,  0,  0],  [  0,  1,  0],  [  0,  0, -1]]
        m3 = [[ -1,  0,  0],  [  0, -1,  0],  [  0,  0,  1]]
        mmm = [m1,m2,m3]

        # # Rmir0 = self.reflect(th=0.) # RD-ND
        # # Rmir1 = self.reflect(th=90.) # TD-ND
        # # Rmir2 = np.zeros((3,3))
        # # Rmir2[0,0] = 1; Rmir2[1,1] = 1; Rmir2[2,2] = -1

        # print Rmir0
        # print Rmir1
        # print Rmir2
        # # raw_input()
        # # Rmir2  rotate Rmir0 by x axis 90 degree

        # if iopt==0:
        #     Rm = [Rmir0]
        # elif iopt==1:
        #     Rm = [Rmir0,Rmir1]
        # elif iopt==2:
        #     Rm = [Rmir0,Rmir1,Rmir2]
        # else: raise IOError, 'Wrong option'

        gr = [] # new grains
        for i in range(len(self.rve)):
            tempgr=[]
            # itself
            tempgr.append([self.rve[i][0],self.rve[i][1],self.rve[i][2],
                       self.rve[i][3]])
            cRs = euler(self.rve[i][0],self.rve[i][1],self.rve[i][2],
                        echo=False) # R (ca<-sa)
            for j in range(len(mmm)):
                R0 = np.dot(cRs, mmm[j]) # (ca<-sa<-sa)
                phi1, phi, phi2 = euler(a=R0, echo=False)
                tempgr.append([phi1,phi,phi2,self.rve[i][3]])

            for j in range(len(tempgr)):
                gr.append(tempgr[j])


            # R0 = np.dot(cRs, Rm[0]) # RD-TD
            # phi1, phi, phi2 = euler(a=R0, echo=False)
            # tempgr.append([phi1,phi,phi2,self.rve[i][3]])

            # #
            # for i in range(len(Rm)):
            #     np.dot(cRs, Rm[i]
            # if iopt>0:
            #     n = len(tempgr)
            #     for j in range(n):
            #         cRs = euler(tempgr[j][0],tempgr[j][1],tempgr[j][2],
            #                     echo=False)
            #         R0 = np.dot(cRs, Rm[1])
            #         phi1,phi,phi2 = euler(a=R0, echo=False)
            #         tempgr.append([phi1,phi,phi2,self.rve[i][3]])

            # if iopt>1:
            #     n = len(tempgr)
            #     for j in range(n):
            #         cRs = euler(tempgr[j][0], tempgr[j][1], tempgr[j][2],
            #                     echo=False)
            #         R0 = np.dot(cRs, Rm[2])
            #         phi1,phi,phi2 = euler(a=R0, echo=False)
            #         tempgr.append([phi1,phi,phi2,self.rve[i][3]])

            # for j in range(len(tempgr)):
            #     gr.append(tempgr[j])


        self.rve = np.array(gr)

        wgt = self.rve.T[-1]
        twgt = wgt.sum()
        self.rve[:,3] = self.rve[:,3]/twgt
Esempio n. 38
0
def rve_ortho(cod, rve):
    """
    Apply the orthonormal sample symmetry to the given discrete
    crystallographic orientation distribution (COD)

    Orthonormal (phi1 = 90)
    Monoclinic (phi1=180)
    None (Triclinic) (phi1=360)
    """
    from euler import euler

    codt = cod.transpose()
    ## information ------------------
    p1max = max(codt[0])  #phi1
    print 'p1max: %4.1f'%p1max
    # phi1 = codt[0]
    # phi2 = codt[1]
    # phi = cot[2]
    ## ------------------------------

    if p1max==90: ssym="Orth"
    elif p1max==180: ssym="Mono"
    elif p1max==360: ssym="Tric"
    else: raise IOError, "Unexpected maximum phi1 anlge"
    print 'symmetry: %s'%ssym

    new_rve = [ ]
    for igr in range(len(rve)):
        ## Phi1, Phi, Phi2 angles and volume fraction
        p1 = rve[igr][0]; p = rve[igr][1]
        p2 = rve[igr][2]; vf = rve[igr][3]

        ## rotation matrix of the current grain
        amat = euler(p1, p, p2, echo=False)
        amat_t = amat.transpose()
        amat_new = []
        if ssym=="Orth": # rolling sample symmetry: mmm
            ## multiplication of the matrix according to the symmetry

            # x-mirror
            oldt = amat_t.copy()
            oldt[1] = oldt[1]*-1
            oldt[2] = oldt[2]*-1
            amat_new.append(oldt.transpose())

            # y-mirror
            oldt = amat_t.copy()
            oldt[0] = oldt[0]*-1
            oldt[2] = oldt[2]*-1
            amat_new.append(oldt.transpose())

            # x and y-mirror
            oldt = amat_t.copy()
            oldt[0] = oldt[0]*-1
            oldt[1] = oldt[1]*-1
            amat_new.append(oldt.transpose())

            nvol = 4
            pass

        elif ssym=="Mono":
            # x-mirror (along TD)
            oldt = amat_t.copy()
            oldt[1] = oldt[1]*-1
            oldt[2] = oldt[2]*-1
            amat_new.append(oldt.transpose())
            nvol = 2

            pass

        elif ssym=="Tric":
            nvol=1
            #no mirror axis
            pass

        ## assigns the newly multiplied A-matrix to the new_rve
        temp = rve[igr].copy(); temp[3] = vf/nvol
        new_rve.append(temp)
        for i in range(len(amat_new)):
            ph1, ph, ph2 = euler(a=amat_new[i],echo=False)
            new_rve.append([ph1,ph,ph2,vf/nvol])
            pass
        pass
    return np.array(new_rve)
Esempio n. 39
0
def euler_timing(func, exp, times=200, iterations=200):
    diff = 0
    for n in range(times):
        start_time = time()
        func(exp, iterations)
        diff += time() - start_time
    return diff


def correct_euler(exp, num_iterations=200):
    y = 1
    fac = 1
    x_n = 1

    for n in range(1, num_iterations + 1):
        x_n *= exp
        fac *= n
        y += x_n / fac

    return y


# Berechne alle Werte von e^x von 0 bis 10
for x in range(20):
    correct = e ** x
    offset = correct / 10000000
    result = euler(x)


Esempio n. 40
0
 def R(theta):
     y, x = euler(F, [y0(theta)], h, l)
     print(y0(theta))
     r = y[-1, 0] - mu2
     return r
 def _start_euler(self):
     self.points = [[],[]]
     self.points_i = [[],[]]
     # Inputs: endtime, starttime, matrix with start voltage and start currency, timesteps, figure to plot
     euler(300., 0, np.matrix('0;0'), 0.1, self)
Esempio n. 42
0
def c2e(component='cube', ngrain=100, w0=10, ifig=1, mode='contour'):
    """
    Provided (hkl)// ND and [uvw]//RD,

    arguments
    =========
    component = 'cube'
    ngrain    = 100
    w0        = 10
    ifig      = 1
    mode      = 'contour'
    """
    import numpy as np
    from euler import euler
    import upf
    comp = component.lower()
    print comp
    if comp=='cube':
        hkl=[1,0,0]
        uvw=[0,1,0]
    elif comp=='copper':
        hkl=[1,1,2]
        uvw=[-1,-1,1]
    elif comp=='goss':
        hkl=[1,1,0]
        uvw=[0,0,1]
    elif comp=='rbrass':
        hkl=[-1,1,0]
        uvw=[1,1,1]

    print 'hkl',hkl
    print 'uvw',uvw,'\n'

    # mat0: trasformation matrix that converts
    # sample axes to crystal ones [ca<-sa]
    mat0 = miller2mat(hkl=map(round, hkl), uvw=map(round, uvw))

    print 'mat0'
    for i in range(len(mat0)):
        for j in range(len(mat0[i])):
            print '%5.1f '%mat0[i][j],
        print ''

    # Mirror reflection by RD and TD in the sample coordinate system.
    # mat0[ca<-sa]
    RD, TD = orthogonal()
    mat1 = np.dot(mat0, RD)
    mat2 = np.dot(mat0, TD)
    mat3 = np.dot(np.dot(mat0, RD), TD)
    print 'mat1'
    for i in range(len(mat1)):
        for j in range(len(mat1[i])):
            print '%5.1f '%mat1[i][j],
        print ''
    print 'mat2'
    for i in range(len(mat2)):
        for j in range(len(mat2[i])):
            print '%5.1f '%mat2[i][j],
        print ''
    print 'mat3'
    for i in range(len(mat3)):
        for j in range(len(mat3[i])):
            print '%5.1f '%mat3[i][j],
        print ''


    ang0 = euler(a=mat0, echo=False)
    ang1 = euler(a=mat1, echo=False)
    ang2 = euler(a=mat2, echo=False)
    ang3 = euler(a=mat3, echo=False)

    angs = [ang0, ang1, ang2, ang3]

    for i in range(len(angs)):
        for j in iter(angs[i]):
            print '%5.1f '%j,
        print ''

    xtal = []
    for i in range(4):
        phi1, p, phi2 = angs[i]
        myx = textur(p1=phi1,p=p, p2=phi2, w0=w0, ngrain = ngrain/4,
                     filename='dum', iplot=False)

        for j in range(len(myx.gr)):
            xtal.append(myx.gr[j])

    mypf = upf.polefigure(grains=xtal,csym='cubic')
    mypf.pf(pole=[[1,0,0],[1,1,0],[1,1,1]], mode=mode, ifig=ifig)

    ## Write
    gr2f(gr=xtal, header='module: %s,   w0: %i'%('ce2', w0),
         filename='%i%s%i_%s.cmb'%(len(xtal), component, w0, 'ce2'))
    return xtal
Esempio n. 43
0
 def test_euler_10001(self):
     self.number = 10001
     result = euler.euler(self.number)[self.number - 1]
     self.assertEqual(result, 104743)
     print("Result: {0}".format(result))
Esempio n. 44
0
def main(ngrains=100,sigma=5.,iopt=1,ifig=1,fiber='gamma',
         iexit=False,ipfplot=False):
    """
    Arguments
    =========
    ngrains = 100
    sigma   = 5.
    iopt    = 1 (1: gauss (recommended); 2: expov; 3: logno; 4: norma)
    ifig    = 1
    fiber   = 'gamma', 'alpha', 'eta', 'epsilon', 'sigma', 'random'
    ipfplot = False

    Returns
    -------
    It returns the poly-crystal aggregate in the form of numpy's ndarray.
    """
    import upf
    import matplotlib.pyplot as plt
    import cmb
    # h = mmm() ## m-m-m sample symmetry is applied.
    h = [np.identity(3)]
    gr = []
    for i in xrange(ngrains):
        dth = random.uniform(-180., 180.)
        if fiber in ['gamma','alpha', 'eta', 'epsilon', 'sigma']:
            g = gen_gr_fiber(dth,sigma,iopt,fiber)
        elif fiber=='random':
            g = cmb.randomGrain(360,360,360)

        for j in xrange(len(h)):
            temp = np.dot(g,h[j].T)
            phi1,phi,phi2 = euler(a=temp, echo=False)
            gr.append([phi1,phi,phi2,1./ngrains])

    if iexit: return np.array(gr)

    fn = '%s_fib_ngr%s_sigma%s.cmb'%(fiber,str(len(gr)).zfill(5),str(sigma).zfill(3))
    f = open(fn,'w')
    f.writelines('Artificial %s fibered polycrystal aggregate\n'%fiber)
    f.writelines('bcc_rolling_fiber.py python script\n')
    f.writelines('distribution: ')
    if iopt==1: f.writelines(' gauss')
    if iopt==2: f.writelines(' expov')
    if iopt==3: f.writelines(' logno')
    if iopt==4: f.writelines(' norma')
    f.writelines('\n')
    f.writelines('B %i\n'%ngrains)
    for i in xrange(len(gr)):
        f.writelines('%+7.3f %+7.3f %+7.3f %+13.4e\n'%(
            gr[i][0], gr[i][1], gr[i][2], 1./len(gr)))

    if ipfplot:
        mypf1 = upf.polefigure(grains=gr,csym='cubic')
        mypf1.pf_new(poles=[[1,0,0],[1,1,0],[1,1,1]],ix='RD',iy='TD')
        fig=plt.gcf()
        fig.tight_layout()
        print 'aggregate saved to %s'%fn
        fig.savefig(
            '%s_contf.pdf'%(fn.split('.cmb')[0]),
            bbox_inches='tight')
        fig.savefig(
            '%s_contf.png'%(fn.split('.cmb')[0]),
            bbox_inches='tight')
        fig.clf()
        plt.close(fig)

    return np.array(gr),fn