Beispiel #1
0
def _BrakeTime(x, v, xbound):
    [result, t] = _SolveAXMB(v, Mul(number('2'), Sub(xbound, x)), epsilon, 0, inf)
    if not result:
        log.debug("Cannot solve for braking time from the equation {0}*t - {1} = 0".\
                  format(mp.nstr(v, n=_prec), mp.nstr(Mul(number('2'), Sub(xbound, x)), n=_prec)))
        return 0
    return t
Beispiel #2
0
def figs(x, n=20, exp=0, sign=False):
  if (sign and x >= 0.0):
    s = ' '
  else:
    s = ''
  # mp always returns '0.0' for zero. Bypass it using standard formats
  if (x == 0.0):
    fmt = '{{0:.{0}f}}'.format(n)
    # python uses two-digit exponent, but mp uses the least amount. Hard code it for zero
    if (exp):
      fmt += 'e+'+'0'*exp
    return s+fmt.format(0.0)
  # Convert significant figures to decimal places:
  # With exponent, integer part should be 1 figure, so it's n+1
  # Without exponent, floor(log10(abs(x)))+1 gives the number of integer figures (except for zero)
  if (exp):
    tmp = s+mp.nstr(mp.mpf(x), n+1, strip_zeros=False, min_fixed=mp.inf, max_fixed=-mp.inf, show_zero_exponent=True)
    # Add zeros to the exponent if necessary
    exppos = tmp.find('e')+2
    diff = exp-(len(tmp)-exppos)
    if (diff > 0):
      tmp = tmp[:exppos] + '0'*diff + tmp[exppos:]
    return tmp
  else:
    return s+mp.nstr(mp.mpf(x), int(mp.floor(mp.log10(abs(x))))+n+1, strip_zeros=False, min_fixed=-mp.inf, max_fixed=mp.inf)
Beispiel #3
0
def _BrakeTime(x, v, xbound):
    [result, t] = _SolveAXMB(v, Mul(number('2'), Sub(xbound, x)), epsilon, 0,
                             inf)
    if not result:
        log.debug("Cannot solve for braking time from the equation {0}*t - {1} = 0".\
                  format(mp.nstr(v, n=_prec), mp.nstr(Mul(number('2'), Sub(xbound, x)), n=_prec)))
        return 0
    return t
Beispiel #4
0
def _BrakeAccel(x, v, xbound):
    coeff0 = Mul(number('2'), Sub(xbound, x))
    coeff1 = Sqr(v)
    [result, a] = _SolveAXMB(coeff0, Neg(coeff1), epsilon, -inf, inf)
    if not result:
        log.debug("Cannot solve for braking acceleration from the equation {0}*a + {1} = 0".\
                  format(mp.nstr(coeff0, n=_prec), mp.nstr(coeff1, n=_prec)))
        return 0
    return a
Beispiel #5
0
def _BrakeAccel(x, v, xbound):
    coeff0 = Mul(number('2'), Sub(xbound, x))
    coeff1 = Sqr(v)
    [result, a] = _SolveAXMB(coeff0, Neg(coeff1), epsilon, -inf, inf)
    if not result:
        log.debug("Cannot solve for braking acceleration from the equation {0}*a + {1} = 0".\
                  format(mp.nstr(coeff0, n=_prec), mp.nstr(coeff1, n=_prec)))
        return 0
    return a
Beispiel #6
0
def _CalculateLeastUpperBoundInoperativeInterval(x0, x1, v0, v1, vm, am):
    # All input must already be of mp.mpf type
    d = x1 - x0
    temp1 = Prod([
        number('2'),
        Neg(Sqr(am)),
        Sub(Prod([number('2'), am, d]), Add(Sqr(v0), Sqr(v1)))
    ])
    if temp1 < zero:
        T0 = number('-1')
        T1 = number('-1')
    else:
        term1 = mp.fdiv(Add(v0, v1), am)
        term2 = mp.fdiv(mp.sqrt(temp1), Sqr(am))
        T0 = Add(term1, term2)
        T1 = Sub(term1, term2)

    temp2 = Prod([
        number('2'),
        Sqr(am),
        Add(Prod([number('2'), am, d]), Add(Sqr(v0), Sqr(v1)))
    ])
    if temp2 < zero:
        T2 = number('-1')
        T3 = number('-1')
    else:
        term1 = Neg(mp.fdiv(Add(v0, v1), am))
        term2 = mp.fdiv(mp.sqrt(temp2), Sqr(am))
        T2 = Add(term1, term2)
        T3 = Sub(term1, term2)

    newDuration = max(max(T0, T1), max(T2, T3))
    if newDuration > zero:
        dStraight = Prod([pointfive, Add(v0, v1), newDuration])
        if Sub(d, dStraight) > 0:
            amNew = am
            vmNew = vm
        else:
            amNew = -am
            vmNew = -vm

        # import IPython; IPython.embed()

        vp = Mul(pointfive, Sum([Mul(newDuration, amNew), v0,
                                 v1]))  # the peak velocity
        if (Abs(vp) > vm):
            dExcess = mp.fdiv(Sqr(Sub(vp, vmNew)), am)
            assert (dExcess > 0)
            deltaTime = mp.fdiv(dExcess, vm)
            newDuration = Add(newDuration, deltaTime)

        newDuration = Mul(newDuration, number('1.01'))  # add 1% safety bound
        return newDuration
    else:
        log.debug('Unable to calculate the least upper bound: T0 = {0}; T1 = {1}; T2 = {2}; T3 = {3}'.\
                  format(mp.nstr(T0, n=_prec), mp.nstr(T1, n=_prec), mp.nstr(T2, n=_prec), mp.nstr(T3, n=_prec)))
        return number('-1')
Beispiel #7
0
def _CalculateLeastUpperBoundInoperativeInterval(x0, x1, v0, v1, vm, am):
    # All input must already be of mp.mpf type
    d = x1 - x0
    temp1 = Prod([number('2'), Neg(Sqr(am)), Sub(Prod([number('2'), am, d]), Add(Sqr(v0), Sqr(v1)))])
    if temp1 < zero:
        T0 = number('-1')
        T1 = number('-1')
    else:
        term1 = mp.fdiv(Add(v0, v1), am)
        term2 = mp.fdiv(mp.sqrt(temp1), Sqr(am))
        T0 = Add(term1, term2)
        T1 = Sub(term1, term2)

    temp2 = Prod([number('2'), Sqr(am), Add(Prod([number('2'), am, d]), Add(Sqr(v0), Sqr(v1)))])
    if temp2 < zero:
        T2 = number('-1')
        T3 = number('-1')
    else:
        term1 = Neg(mp.fdiv(Add(v0, v1), am))
        term2 = mp.fdiv(mp.sqrt(temp2), Sqr(am))
        T2 = Add(term1, term2)
        T3 = Sub(term1, term2)

    newDuration = max(max(T0, T1), max(T2, T3))
    if newDuration > zero:
        dStraight = Prod([pointfive, Add(v0, v1), newDuration])
        if Sub(d, dStraight) > 0:
            amNew = am
            vmNew = vm
        else:
            amNew = -am
            vmNew = -vm

        # import IPython; IPython.embed()

        vp = Mul(pointfive, Sum([Mul(newDuration, amNew), v0, v1])) # the peak velocity
        if (Abs(vp) > vm):
            dExcess = mp.fdiv(Sqr(Sub(vp, vmNew)), am)
            assert(dExcess > 0)
            deltaTime = mp.fdiv(dExcess, vm)
            newDuration = Add(newDuration, deltaTime)

        log.debug('Calculation successful: T0 = {0}; T1 = {1}; T2 = {2}; T3 = {3}'.format(mp.nstr(T0, n=_prec), mp.nstr(T1, n=_prec), mp.nstr(T2, n=_prec), mp.nstr(T3, n=_prec)))
        
        newDuration = Mul(newDuration, number('1.01')) # add 1% safety bound
        return newDuration
    else:
        if (FuzzyEquals(x0, x1, epsilon) and FuzzyZero(v0, epsilon) and FuzzyZero(v1, epsilon)):
            # t = 0 is actually a correct solution
            newDuration = 0
            return newDuration
        log.debug('Unable to calculate the least upper bound: T0 = {0}; T1 = {1}; T2 = {2}; T3 = {3}'.\
                  format(mp.nstr(T0, n=_prec), mp.nstr(T1, n=_prec), mp.nstr(T2, n=_prec), mp.nstr(T3, n=_prec)))
        return number('-1')
Beispiel #8
0
def z_Zolotarev_poly(N, m, interp_num=100, full=False):
    r"""
    Function to evaluate the polynomial coefficients of the Zolotarev polynomial.
    
    :param N:    Order of the Zolotarev polynomial
    :param m:    m is the elliptic parameter (not the modulus k and not the nome q)
    :param interp_num:    Number of points for interpolation
    :param full:    Switch determining nature of return value. When it is False (the default)
                    just the coefficients are returned, when True diagnostic information from 
                    the singular value decomposition is also returned.
                  
    :rtype:      Returns [polynomial_coef, polynomial_roots]
    """
    m = mpf(m)
    # Evaluating the polynomial at some discrete points (for polynomial fitting)   
    x = np.linspace(-1.04, 1.04, interp_num)
    y = []
    for i in range(len(x)):
        tmp = mp.nstr(z_Zolotarev(N, x[i], m), n=6)
        tmp = z_str2num(tmp)
        y.append(tmp)
    # Interpolating the data to fit to a Nth order polynomial
    coef = np.polyfit(x, y, N, full)
    roots = np.sort(np.roots(coef))
    return coef, roots
Beispiel #9
0
def entropy_pf(Lph,Tph,meas,G,prec=15,q=2,dps=200):
    
    # setting digit precision
    mp.dps = dps
    
    # =============================================================================
    # Evaluation of the entropy using partition function
    # Lph,Tph -- physical size (number of qubits) and time (circuit depth)
    # G -- (large) parameter controling the gap between relevant and irrelevant states
    # prec -- number of digits in the answer
    # q -- qudit dimension
    # =============================================================================
    
    # -- define effective inverse temperature
    beta = mp.log((q**2+1)/q)
    # -- dimension of the effective lattice
    L,T = int(Lph/2)+(Lph+1)%2,Tph+1
    # -- corresponding couplings for the numerator and denominator 
    J_matrix1,J_matrix2 = generate_lattice_couplings(L,T,meas,G,beta)
    # -- including the temperature
    J_matrix1 = -beta*mp.matrix(J_matrix1.tolist())
    J_matrix2 = -beta*mp.matrix(J_matrix2.tolist())
    # -- evaluation of the entropy
    entropy = -log_partition_function(J_matrix1,L,T).real\
              +log_partition_function(J_matrix2,L,T).real
    
    return mp.nstr(entropy,prec)
Beispiel #10
0
def z_Zolotarev_poly(N, m, interp_num=100, full=False):
    r"""
    Function to evaluate the polynomial coefficients of the Zolotarev polynomial.
    
    :param N:    Order of the Zolotarev polynomial
    :param m:    m is the elliptic parameter (not the modulus k and not the nome q)
    :param interp_num:    Number of points for interpolation
    :param full:    Switch determining nature of return value. When it is False (the default)
                    just the coefficients are returned, when True diagnostic information from 
                    the singular value decomposition is also returned.
                  
    :rtype:      Returns [polynomial_coef, polynomial_roots]
    """
    m = mpf(m)
    # Evaluating the polynomial at some discrete points (for polynomial fitting)
    x = np.linspace(-1.04, 1.04, interp_num)
    y = []
    for i in range(len(x)):
        tmp = mp.nstr(z_Zolotarev(N, x[i], m), n=6)
        tmp = z_str2num(tmp)
        y.append(tmp)
    # Interpolating the data to fit to a Nth order polynomial
    coef = np.polyfit(x, y, N, full)
    roots = np.sort(np.roots(coef))
    return coef, roots
Beispiel #11
0
 def Log10ProbPerBin(self, lessX, eqX):
     log10probX = _zeros_like(self.WaveDec_data)
     for l, level in enumerate(self.WaveDec_data):
         for j, coeff in enumerate(level):
             grteqX = 1 - lessX[l][j]
             log10pX = float(mp.nstr(mp.log10(grteqX), g_logdigits))
             log10probX[l][j] = log10pX
     return log10probX
Beispiel #12
0
 def NSigmaPerBin(self, lessX):
     nsigma = _zeros_like(self.WaveDec_data)
     for l, level in enumerate(self.WaveDec_data):
         for j, data_coeff in enumerate(level):
             hypo_coeff = self.WaveDec_hypo[l][j]
             sign = -1 if data_coeff < hypo_coeff else 1
             nsig = float(mp.nstr(sign * _nsigma(lessX[l][j]), g_logdigits))
             nsigma[l][j] = nsig
     return nsigma
Beispiel #13
0
def compare_mp(nb: mp.mpf, ref: mp.mpf, precision: int = 25) -> None:
    nb = mp.nstr(nb, precision)
    nb_len = len(nb)
    ref = mp.nstr(ref, precision)
    ref_len = len(ref)
    cursor = 0
    while cursor < nb_len and cursor < ref_len and nb[cursor] == ref[cursor]:
        cursor += 1
    print(nb, end='')
    if ref_len > nb_len:
        print('-' * (ref_len - nb_len), end='')
    print()
    print('*' * cursor, end='')
    if cursor < ref_len:
        print('#' * (ref_len - cursor), end='')
    if nb_len > ref_len:
        print('+' * (nb_len - ref_len), end='')
    print()
Beispiel #14
0
def VectToString(A):
    A_ = ConvertFloatArrayToMPF(A)
    separator = ""
    s = "["
    for a in A_:
        s += separator
        s += mp.nstr(a, n=_prec)
        separator = ", "
    return s
Beispiel #15
0
def VectToString(A):
    A_ = ConvertFloatArrayToMPF(A)
    separator = ""
    s = "["
    for a in A_:
        s += separator
        s += mp.nstr(a, n=_prec)
        separator = ", "
    return s
Beispiel #16
0
def dim_str(dim, units):
    """Format a dimension to a given unit."""
    dim = to_mm(dim, units, True)
    prefix = ""
    if units == "ft":
        if dim >= mp.mpf(1):
            prefix = str(int(mp.floor(dim))) + "'"
        units = "in"
        dim = mp.frac(dim) * 12
    dim = prefix + ("{:." + str(PRECS[units]) + "f}").format(float(mp.nstr(dim)))
    if units == "in":
        return dim + '"'

    return dim + " " + units
Beispiel #17
0
def z_Zolotarev_poly(N, m, interp_num=100, full=False):
    """
    Function to evaluate the polynomial coefficients of  the Zolotarev
    polynomial.
    """
    m = mpf(m)
    # Evaluating the polynomial at some discrete points
    x = np.linspace(-1.04, 1.04, interp_num)
    y = []
    for i in range(len(x)):
        tmp = mp.nstr(z_Zolotarev(N, x[i], m), n=6)
        tmp = z_str2num(tmp)
        y.append(tmp)
    # Interpolating the data to fit to a Nth order polynomial
    coef = np.polyfit(x, y, N, full)
    roots = np.sort(np.roots(coef))
    return coef, roots
Beispiel #18
0
def z_Zolotarev_poly(N, m, interp_num=100, full=False):
    """
    Function to evaluate the polynomial coefficients of  the Zolotarev
    polynomial.
    """
    m = mpf(m)
    # Evaluating the polynomial at some discrete points    
    x = np.linspace(-1.04, 1.04, interp_num)
    y = []
    for i in range(len(x)):
        tmp = mp.nstr(z_Zolotarev(N, x[i], m), n=6)
        tmp = z_str2num(tmp)
        y.append(tmp)
    # Interpolating the data to fit to a Nth order polynomial
    coef = np.polyfit(x, y, N, full)
    roots = np.sort(np.roots(coef))
    return coef, roots
Beispiel #19
0
    def calculate(self, expr, q):
        def safe_eval(expr, symbols={}):
            if expr.find("_") != -1:
                return None
            try:
                return eval(expr, dict(__builtins__=None), symbols)  # :(
            except:
                e = sys.exc_info()[0]
                return "Error de sintaxis o algo por el estilo: " + str(e)

        expr = expr.replace('^', '**')

        resp = safe_eval(expr, self.vrs)
        try:
            resp = mp.nstr(resp, mp.dps, min_fixed=-mp.inf)
        except:
            pass

        q.put(str(resp))
Beispiel #20
0
    def calculate(self, expr, q, bot, ev):
        def safe_eval(expr, symbols={}):
            if expr.find("_") != -1 or expr.find("=") != -1 or expr.find("'") != -1 or expr.find("\"") != -1:
                return None
            if expr.find("sys.") != -1 or expr.find("lambda") != -1 or expr.find("os.") != -1 or expr.find("import") != -1:
                return "u h4x0r"
            try:
                return eval(expr, dict(__builtins__=None), symbols)  # :(
            except:
                e = sys.exc_info()[0]
                return bot._(ev, self, "syntaxerror").format(str(e))

        expr = expr.replace('^', '**')

        resp = safe_eval(expr, self.vrs)
        try:
            resp = mp.nstr(resp, mp.dps, min_fixed=-mp.inf)
        except:
            pass

        q.put(str(resp))
Beispiel #21
0
    def calculate(self, expr, q, bot, ev):
        def safe_eval(expr, symbols={}):
            if expr.find("_") != -1 or expr.find("=") != -1 or expr.find(
                    "'") != -1 or expr.find("\"") != -1:
                return None
            if expr.find("sys.") != -1 or expr.find(
                    "lambda") != -1 or expr.find("os.") != -1 or expr.find(
                        "import") != -1:
                return "u h4x0r"
            try:
                return eval(expr, dict(__builtins__=None), symbols)  # :(
            except:
                e = sys.exc_info()[0]
                return bot._(ev, self, "syntaxerror").format(str(e))

        expr = expr.replace('^', '**')

        resp = safe_eval(expr, self.vrs)
        try:
            resp = mp.nstr(resp, mp.dps, min_fixed=-mp.inf)
        except:
            pass

        q.put(str(resp))
def perform_ss_rate_analysis(prefix,
                             ENs,
                             Evib=0.,
                             T=473,
                             p0=1,
                             N2_frac=0.25,
                             X=0.01,
                             site='step',
                             plot=True,
                             alkali_promotion=False,
                             use_alpha=False,
                             model='effective',
                             nlevels=1,
                             dist='Treanor',
                             Tv=3500,
                             metals=[],
                             Agg=False):
    if Agg:
        import matplotlib
        matplotlib.use('Agg')
    from mkm import NH3mkm

    Rs = []
    Rss = []
    thetas = []

    theta0 = np.zeros(4)  # [0, 0, 0, 0]
    for i, EN in enumerate(ENs):

        # print type(EN), EN
        mod = NH3mkm(T,
                     EN,
                     Evib,
                     p0,
                     N2_frac,
                     X=X,
                     site=site,
                     alkali_promotion=alkali_promotion,
                     model=model,
                     dist=dist,
                     Tv=Tv,
                     nlevels=nlevels,
                     use_alpha=use_alpha)

        Rds, rsab = mod.get_sabatier_rate()
        Rs.append(rsab)

        if i == 0:
            theta = mod.integrate_odes(theta0=theta0,
                                       h0=1e-24,
                                       rtol=1e-12,
                                       atol=1e-15,
                                       timespan=[0, 1e9],
                                       mxstep=200000)
        try:
            theta_ss = mod.find_steady_state_roots(theta)
        except:
            # If there is an issue re-solve ode
            theta = mod.integrate_odes(theta0=theta,
                                       h0=1e-24,
                                       rtol=1e-12,
                                       atol=1e-15,
                                       timespan=[0, 1e9],
                                       mxstep=200000)
            # Try one more time with reduced tolerance
            try:
                theta_ss = mod.find_steady_state_roots(theta, tol=1e-15)
            except:
                # set it to the ode theta
                theta_ss = theta

        # Now check if theta_ss has unphysical values
        if (np.array(theta) <= 1).all() and (np.array(theta) >= 0.).all():
            theta = theta_ss

        theta_and_empty = list(theta) + [1 - sum(theta)]
        theta_and_empty = [mp.nstr(t, 25) for t in theta_and_empty]

        r = mod.get_rates(theta)
        thetas.append(theta_and_empty)
        Rss.append(r[0])

    # This needs to be updated
    store_variables(prefix,
                    ENs,
                    Rs, [],
                    Rss, [],
                    thetas,
                    T,
                    p0,
                    N2_frac,
                    X,
                    site,
                    Evib,
                    metals=metals)

    if plot:
        plot_rates(ENs, Rs, [], Rss, prefix)
        plot_coverages(ENs, [], thetas, prefix)
Beispiel #23
0
    R = 10  # 'R' is the value of the peak within [-1,+1]

    # Getting the value of the parameter 'm' from a given 'R' (remember!, m=k^2)
    m = z_m_frm_R(N, R)
    print('m =', m)
    print(type(m))

    # Testing the side-lobe ratio (i.e., SLR in linear scale)
    R = z_Zolotarev_x2(N, m)
    print('R =', R)
    print('SLR =', 10 * mp.log10(R**2),
          '(dB)')  # SLR depends only on the magnitude of R here

    # x1, x2, x3 values ... just for the plotting purpose
    x1, x2, x3 = z_x123_frm_m(N, m)
    x11 = z_str2num(mp.nstr(x1, n=6))
    x22 = z_str2num(mp.nstr(x2, n=6))
    x33 = z_str2num(mp.nstr(x3, n=6))

    # Evaluating the polynomial at some discrete points
    x = np.linspace(-1.04, 1.04, num=500)
    y = []
    for i in range(len(x)):
        tmp = mp.nstr(z_Zolotarev(N, x[i], m), n=6)
        tmp = z_str2num(tmp)
        y.append(tmp)

    # Plotting the data obtained at those discrete points
    import matplotlib.pyplot as plt

    f1 = plt.figure(1)
Beispiel #24
0
def Interpolate1DFixedDuration(x0, x1, v0, v1, newDuration, vm, am):
    x0 = ConvertFloatToMPF(x0)
    x1 = ConvertFloatToMPF(x1)
    v0 = ConvertFloatToMPF(v0)
    v1 = ConvertFloatToMPF(v1)
    vm = ConvertFloatToMPF(vm)
    am = ConvertFloatToMPF(am)
    newDuration = ConvertFloatToMPF(newDuration)
    log.debug("\nx0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; newDuration = {6}".\
              format(mp.nstr(x0, n=_prec), mp.nstr(x1, n=_prec), mp.nstr(v0, n=_prec), mp.nstr(v1, n=_prec),
                     mp.nstr(vm, n=_prec), mp.nstr(am, n=_prec), mp.nstr(newDuration, n=_prec)))

    # Check inputs
    assert (vm > zero)
    assert (am > zero)

    if (newDuration < -epsilon):
        return ParabolicCurve()
    if (newDuration <= epsilon):
        # Check if this is a stationary trajectory
        if (FuzzyEquals(x0, x1, epsilon) and FuzzyEquals(v0, v1, epsilon)):
            ramp0 = Ramp(v0, 0, 0, x0)
            newCurve = ParabolicCurve(ramp0)
            return newCurve
        else:
            # newDuration is too short to any movement to be made
            return ParabolicCurve()

    d = Sub(x1, x0)

    # First assume no velocity bound -> re-interpolated trajectory will have only two ramps.
    # Solve for a0 and a1 (the acceleration of the first and the last ramps).
    #         a0 = A + B/t0
    #         a1 = A + B/(t - t0)
    # where t is the (new) total duration, t0 is the (new) duration of the first ramp, and
    #         A = (v1 - v0)/t
    #         B = (2d/t) - (v0 + v1).
    newDurInverse = mp.fdiv(one, newDuration)
    A = Mul(Sub(v1, v0), newDurInverse)
    B = Sub(Prod([mp.mpf('2'), d, newDurInverse]), Add(v0, v1))

    interval0 = iv.mpf([zero, newDuration])  # initial interval for t0

    # Now consider the interval(s) computed from a0's constraints
    sum1 = Neg(Add(am, A))
    sum2 = Sub(am, A)
    C = mp.fdiv(B, sum1)
    D = mp.fdiv(B, sum2)

    log.debug("\nA = {0}; \nB = {1}; \nC = {2}; \nD = {3}; \nsum1 = {4}; \nsum2 = {5};".\
              format(mp.nstr(A, n=_prec), mp.nstr(B, n=_prec), mp.nstr(C, n=_prec), mp.nstr(D, n=_prec),
                     mp.nstr(sum1, n=_prec), mp.nstr(sum2, n=_prec)))

    if (sum1 > zero):
        # This implied that the duration is too short
        log.debug("the given duration ({0}) is too short.".format(newDuration))
        return ParabolicCurve()
    if (sum2 < zero):
        # This implied that the duration is too short
        log.debug("the given duration ({0}) is too short.".format(newDuration))
        return ParabolicCurve()

    if IsEqual(sum1, zero):
        raise NotImplementedError  # not yet considered
    elif sum1 > epsilon:
        log.debug("sum1 > 0. This implies that newDuration is too short.")
        return ParabolicCurve()
    else:
        interval1 = iv.mpf([C, inf])

    if IsEqual(sum2, zero):
        raise NotImplementedError  # not yet considered
    elif sum2 > epsilon:
        interval2 = iv.mpf([D, inf])
    else:
        log.debug("sum2 < 0. This implies that newDuration is too short.")
        return ParabolicCurve()

    if Sub(interval2.a, interval1.b) > epsilon or Sub(interval1.a,
                                                      interval2.b) > epsilon:
        # interval1 and interval2 do not intersect each other
        return ParabolicCurve()
    # interval3 = interval1 \cap interval2 : valid interval for t0 computed from a0's constraints
    interval3 = iv.mpf(
        [max(interval1.a, interval2.a),
         min(interval1.b, interval2.b)])

    # Now consider the interval(s) computed from a1's constraints
    if IsEqual(sum1, zero):
        raise NotImplementedError  # not yet considered
    elif sum1 > epsilon:
        log.debug("sum1 > 0. This implies that newDuration is too short.")
        return ParabolicCurve()
    else:
        interval4 = iv.mpf([Neg(inf), Add(C, newDuration)])

    if IsEqual(sum2, zero):
        raise NotImplementedError  # not yet considered
    elif sum2 > epsilon:
        interval5 = iv.mpf([Neg(inf), Add(D, newDuration)])
    else:
        log.debug("sum2 < 0. This implies that newDuration is too short.")
        return ParabolicCurve()

    if Sub(interval5.a, interval4.b) > epsilon or Sub(interval4.a,
                                                      interval5.b) > epsilon:
        log.debug("interval4 and interval5 do not intersect each other")
        return ParabolicCurve()
    # interval6 = interval4 \cap interval5 : valid interval for t0 computed from a1's constraints
    interval6 = iv.mpf(
        [max(interval4.a, interval5.a),
         min(interval4.b, interval5.b)])

    # import IPython; IPython.embed()

    if Sub(interval3.a, interval6.b) > epsilon or Sub(interval6.a,
                                                      interval3.b) > epsilon:
        log.debug("interval3 and interval6 do not intersect each other")
        return ParabolicCurve()
    # interval7 = interval3 \cap interval6
    interval7 = iv.mpf(
        [max(interval3.a, interval6.a),
         min(interval3.b, interval6.b)])

    if Sub(interval0.a, interval7.b) > epsilon or Sub(interval7.a,
                                                      interval0.b) > epsilon:
        log.debug("interval0 and interval7 do not intersect each other")
        return ParabolicCurve()
    # interval8 = interval0 \cap interval7 : valid interval of t0 when considering all constraints (from a0 and a1)
    interval8 = iv.mpf(
        [max(interval0.a, interval7.a),
         min(interval0.b, interval7.b)])

    # import IPython; IPython.embed()

    # We choose the value t0 (the duration of the first ramp) by selecting the mid point of the
    # valid interval of t0.

    t0 = _SolveForT0(A, B, newDuration, interval8)
    if t0 is None:
        # The fancy procedure fails. Now consider no optimization whatsoever.
        # TODO: Figure out why solving fails.
        t0 = mp.convert(interval8.mid)  # select the midpoint
        # return ParabolicCurve()
    t1 = Sub(newDuration, t0)

    a0 = Add(A, Mul(mp.fdiv(one, t0), B))
    if (Abs(t1) < epsilon):
        a1 = zero
    else:
        a1 = Add(A, Mul(mp.fdiv(one, Neg(t1)), B))
    assert (Sub(Abs(a0), am) < epsilon
            )  # check if a0 is really below the bound
    assert (Sub(Abs(a1), am) < epsilon
            )  # check if a1 is really below the bound

    # import IPython; IPython.embed()

    # Check if the velocity bound is violated
    vp = Add(v0, Mul(a0, t0))
    if Abs(vp) > vm:
        vmnew = Mul(mp.sign(vp), vm)
        D2 = Prod([
            pointfive,
            Sqr(Sub(vp, vmnew)),
            Sub(mp.fdiv(one, a0), mp.fdiv(one, a1))
        ])
        # print "D2",
        # mp.nprint(D2, n=_prec)
        # print "vmnew",
        # mp.nprint(vmnew, n=_prec)
        A2 = Sqr(Sub(vmnew, v0))
        B2 = Neg(Sqr(Sub(vmnew, v1)))
        t0trimmed = mp.fdiv(Sub(vmnew, v0), a0)
        t1trimmed = mp.fdiv(Sub(v1, vmnew), a1)
        C2 = Sum([
            Mul(t0trimmed, Sub(vmnew, v0)),
            Mul(t1trimmed, Sub(vmnew, v1)),
            Mul(mp.mpf('-2'), D2)
        ])

        log.debug("\nA2 = {0}; \nB2 = {1}; \nC2 = {2}; \nD2 = {3};".format(
            mp.nstr(A2, n=_prec), mp.nstr(B2, n=_prec), mp.nstr(C2, n=_prec),
            mp.nstr(D2, n=_prec)))

        temp = Prod([A2, B2, B2])
        initguess = mp.sign(temp) * (Abs(temp)**(1. / 3.))
        root = mp.findroot(lambda x: Sub(Prod([x, x, x]), temp), x0=initguess)

        # import IPython; IPython.embed()
        log.debug("root = {0}".format(mp.nstr(root, n=_prec)))
        a0new = mp.fdiv(Add(A2, root), C2)
        if (Abs(a0new) > Add(am, epsilon)):
            if FuzzyZero(Sub(Mul(C2, a0new), A2), epsilon):
                # The computed a0new is exceeding the bound and its corresponding a1new is
                # zero. Therefore, there is no other way to fix this. This is probably because the
                # given newDuration is less than the minimum duration (x0, x1, v0, v1, vm, am) can
                # get.
                log.debug(
                    "abs(a0new) > am and a1new = 0; Cannot fix this case. This happens probably because the given newDuration is too short."
                )
                return ParabolicCurve()

            a0new = Mul(mp.sign(a0new), am)

        if (Abs(a0new) < epsilon):
            a1new = mp.fdiv(B2, C2)
            if (Abs(a1new) > Add(am, epsilon)):
                # Similar to the case above
                log.debug(
                    "a0new = 0 and abs(a1new) > am; Cannot fix this case. This happens probably because the given newDuration is too short."
                )
                return ParabolicCurve()

        else:
            if FuzzyZero(Sub(Mul(C2, a0new), A2), epsilon):
                # import IPython; IPython.embed()
                a1new = 0
            else:
                a1new = Mul(mp.fdiv(B2, C2),
                            Add(one, mp.fdiv(A2, Sub(Mul(C2, a0new), A2))))
                if (Abs(a1new) > Add(am, epsilon)):
                    a1new = Mul(mp.sign(a1new), am)
                    a0new = Mul(mp.fdiv(A2, C2),
                                Add(one, mp.fdiv(B2, Sub(Mul(C2, a1new), B2))))

        if (Abs(a0new) > Add(am, epsilon)) or (Abs(a1new) > Add(am, epsilon)):
            log.warn("Cannot fix acceleration bounds violation")
            return ParabolicCurve()

        log.debug(
            "\na0 = {0}; \na0new = {1}; \na1 = {2}; \na1new = {3};".format(
                mp.nstr(a0, n=_prec), mp.nstr(a0new, n=_prec),
                mp.nstr(a1, n=_prec), mp.nstr(a1new, n=_prec)))

        if (Abs(a0new) < epsilon) and (Abs(a1new) < epsilon):
            log.warn("Both accelerations are zero. Should we allow this case?")
            return ParabolicCurve()

        if (Abs(a0new) < epsilon):
            # This is likely because v0 is at the velocity bound
            t1new = mp.fdiv(Sub(v1, vmnew), a1new)
            assert (t1new > 0)
            ramp2 = Ramp(v0, a1new, t1new)

            t0new = Sub(newDuration, t1new)
            assert (t0new > 0)
            ramp1 = Ramp(v0, zero, t0new, x0)
            newCurve = ParabolicCurve([ramp1, ramp2])
            return newCurve

        elif (Abs(a1new) < epsilon):
            t0new = mp.fdiv(Sub(vmnew, v0), a0new)
            assert (t0new > 0)
            ramp1 = Ramp(v0, a0new, t0new, x0)

            t1new = Sub(newDuration, t0new)
            assert (t1new > 0)
            ramp2 = Ramp(ramp1.v1, zero, t1new)
            newCurve = ParabolicCurve([ramp1, ramp2])
            return newCurve

        else:
            # No problem with those new accelerations
            # import IPython; IPython.embed()
            t0new = mp.fdiv(Sub(vmnew, v0), a0new)
            if (t0new < 0):
                log.debug(
                    "t0new < 0. The given newDuration not achievable with the given bounds"
                )
                return ParabolicCurve()

            t1new = mp.fdiv(Sub(v1, vmnew), a1new)
            if (t1new < 0):
                log.debug(
                    "t1new < 0. The given newDuration not achievable with the given bounds"
                )
                return ParabolicCurve()

            if (Add(t0new, t1new) > newDuration):
                # Final fix. Since we give more weight to acceleration bounds, we make the velocity
                # bound saturated. Therefore, we set vp to vmnew.

                # import IPython; IPython.embed()
                if FuzzyZero(A, epsilon):
                    log.warn(
                        "(final fix) A is zero. Don't know how to fix this case"
                    )
                    return ParabolicCurve()

                t0new = mp.fdiv(Sub(Sub(vmnew, v0), B), A)
                if (t0new < 0):
                    log.debug("(final fix) t0new is negative")
                    return ParabolicCurve()

                t1new = Sub(newDuration, t0new)

                a0new = Add(A, Mul(mp.fdiv(one, t0new), B))
                a1new = Add(A, Mul(mp.fdiv(one, Neg(t1new)), B))
                ramp1 = Ramp(v0, a0new, t0new, x0)
                ramp2 = Ramp(ramp1.v1, a1new, t1new)
                newCurve = ParabolicCurve([ramp1, ramp2])

            else:
                ramp1 = Ramp(v0, a0new, t0new, x0)
                ramp3 = Ramp(ramp1.v1, a1new, t1new)
                ramp2 = Ramp(ramp1.v1, zero, Sub(newDuration,
                                                 Add(t0new, t1new)))
                newCurve = ParabolicCurve([ramp1, ramp2, ramp3])

                # import IPython; IPython.embed()

            return newCurve
    else:
        ramp1 = Ramp(v0, a0, t0, x0)
        ramp2 = Ramp(ramp1.v1, a1, t1)
        newCurve = ParabolicCurve([ramp1, ramp2])
        return newCurve
Beispiel #25
0
def mparr_to_npreal(mparr):
    arr = np.zeros(len(mparr))
    for i in range(len(mparr)):
        arr[i] = np.float(mp.nstr(mparr[i],17))
    return arr
Beispiel #26
0
def ReinterpolateNDFixedDuration(curves,
                                 vmVect,
                                 amVect,
                                 maxIndex,
                                 delta=zero,
                                 tryHarder=False):
    ndof = len(curves)
    assert (ndof == len(vmVect))
    assert (ndof == len(amVect))
    assert (maxIndex < ndof)

    # Convert all vector elements into mp.mpf (if necessary)
    vmVect_ = ConvertFloatArrayToMPF(vmVect)
    amVect_ = ConvertFloatArrayToMPF(amVect)

    newCurves = []

    if not tryHarder:
        newDuration = curves[maxIndex].duration
        for (idof, curve) in enumerate(curves):
            if idof == maxIndex:
                newCurves.append(curve)
                continue

            stretchedCurve = _Stretch1D(curve, newDuration, vmVect[idof],
                                        amVect[idof])
            if stretchedCurve.isEmpty:
                log.debug(
                    'ReinterpolateNDFixedDuration: dof {0} failed'.format(
                        idof))
                return ParabolicCurvesND()
            else:
                newCurves.append(stretchedCurve)

        assert (len(newCurves) == ndof)
        return ParabolicCurvesND(newCurves)

    else:
        # Try harder to re-interpolate this trajectory. This is guaranteed to have 100% success rate
        isPrevDurationSafe = False
        newDuration = zero
        for (idof, curve) in enumerate(curves):
            t = _CalculateLeastUpperBoundInoperativeInterval(
                curve.x0, curve.EvalPos(curve.duration), curve.v0,
                curve.EvalVel(curve.duration), vmVect[idof], amVect[idof])
            assert (t > zero)
            if t > newDuration:
                newDuration = t
        assert (not (newDuration == zero))
        if curves[maxIndex].duration > newDuration:
            # The duration of the slowest DOF is already safe
            newDuration = curves[maxIndex].duration
            isPrevDurationSafe = True

        for (idof, curve) in enumerate(curves):
            if (isPrevDurationSafe) and (idof == maxIndex):
                newCurves.append(curve)
                continue

            stretchedCurve = _Stretch1D(curve, newDuration, vmVect[idof],
                                        amVect[idof])
            if stretchedCurve.isEmpty:
                log.debug(
                    'ReinterpolateNDFixedDuration: dof {0} failed even when trying harder'
                    .format(idof))
                log.debug('x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; newDuration = {6}'.\
                          format(mp.nstr(curve.x0, n=_prec), mp.nstr(curve.EvalPos(curve.duration), n=_prec),
                                 mp.nstr(curve.v0, n=_prec), mp.nstr(curve.EvalVel(curve.duration), n=_prec),
                                 mp.nstr(vmVect[idof], n=_prec), mp.nstr(amVect[idof], n=_prec),
                                 mp.nstr(newDuration, n=_prec)))
                raise Exception(
                    'Something is wrong when calculating the least upper bound of inoperative intervals'
                )

            newCurves.append(stretchedCurve)

        assert (len(newCurves) == ndof)
        return ParabolicCurvesND(newCurves)
Beispiel #27
0
#    N = 10
    R = 10 # 'R' is the value of the peak within [-1,+1] 
    
    # Getting the value of the parameter 'm' from a given 'R' (remember!, m=k^2)
    m = z_m_frm_R(N, R)
    print 'm =', m
    print type(m)
    
    # Testing the side-lobe ratio (i.e., SLR in linear scale)
    R = z_Zolotarev_x2(N, m)
    print 'R =', R
    print 'SLR =', 10 * mp.log10(R ** 2), '(dB)' # SLR depends only on the magnitude of R here
    
    # x1, x2, x3 values ... just for the plotting purpose
    x1, x2, x3 = z_x123_frm_m(N, m)
    x11 = z_str2num(mp.nstr(x1, n=6))
    x22 = z_str2num(mp.nstr(x2, n=6))
    x33 = z_str2num(mp.nstr(x3, n=6))    
    
    # Evaluating the polynomial at some discrete points    
    x = np.linspace(-1.04, 1.04, num=500)
    y = []
    for i in range(len(x)):
        tmp = mp.nstr(z_Zolotarev(N, x[i], m), n=6)
        tmp = z_str2num(tmp)
        y.append(tmp)
    
    # Plotting the data obtained at those discrete points
    import matplotlib.pyplot as plt
    f1 = plt.figure(1)
    p1 = plt.subplot(111)
Beispiel #28
0
def ReinterpolateNDFixedDuration(curves, vmVect, amVect, maxIndex, delta=zero, tryHarder=False):
    ndof = len(curves)
    assert(ndof == len(vmVect))
    assert(ndof == len(amVect))
    assert(maxIndex < ndof)

    # Convert all vector elements into mp.mpf (if necessary)
    vmVect_ = ConvertFloatArrayToMPF(vmVect)
    amVect_ = ConvertFloatArrayToMPF(amVect)

    newCurves = []

    if not tryHarder:
        newDuration = curves[maxIndex].duration
        for (idof, curve) in enumerate(curves):
            if idof == maxIndex:
                newCurves.append(curve)
                continue

            stretchedCurve = _Stretch1D(curve, newDuration, vmVect[idof], amVect[idof])
            if stretchedCurve.isEmpty:
                log.debug('ReinterpolateNDFixedDuration: dof {0} failed'.format(idof))
                return ParabolicCurvesND()
            else:
                newCurves.append(stretchedCurve)

        assert(len(newCurves) == ndof)
        return ParabolicCurvesND(newCurves)

    else:
        # Try harder to re-interpolate this trajectory. This is guaranteed to have 100% success rate
        isPrevDurationSafe = False
        newDuration = zero
        for (idof, curve) in enumerate(curves):
            t = _CalculateLeastUpperBoundInoperativeInterval(curve.x0, curve.EvalPos(curve.duration), curve.v0, curve.EvalVel(curve.duration), vmVect[idof], amVect[idof])
            assert(t > zero)
            if t > newDuration:
                newDuration = t
        assert(not (newDuration == zero))
        if curves[maxIndex].duration > newDuration:
            # The duration of the slowest DOF is already safe
            newDuration = curves[maxIndex].duration
            isPrevDurationSafe = True

        for (idof, curve) in enumerate(curves):
            if (isPrevDurationSafe) and (idof == maxIndex):
                newCurves.append(curve)
                continue

            stretchedCurve = _Stretch1D(curve, newDuration, vmVect[idof], amVect[idof])
            if stretchedCurve.isEmpty:
                log.debug('ReinterpolateNDFixedDuration: dof {0} failed even when trying harder'.format(idof))
                log.debug('x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; newDuration = {6}'.\
                          format(mp.nstr(curve.x0, n=_prec), mp.nstr(curve.EvalPos(curve.duration), n=_prec),
                                 mp.nstr(curve.v0, n=_prec), mp.nstr(curve.EvalVel(curve.duration), n=_prec),
                                 mp.nstr(vmVect[idof], n=_prec), mp.nstr(amVect[idof], n=_prec),
                                 mp.nstr(newDuration, n=_prec)))
                raise Exception('Something is wrong when calculating the least upper bound of inoperative intervals')

            newCurves.append(stretchedCurve)

        assert(len(newCurves) == ndof)
        return ParabolicCurvesND(newCurves)
Beispiel #29
0
  f.write("\n")
  f.write("------------------------------------\n")
  f.write("Options for Boys function Fn(x):\n")
  f.write("    Max n: {}\n".format(maxn))
  f.write("    Max x: {}\n".format(maxx))
  f.write("  Spacing: {}\n".format(inc))
  f.write("  npoints: {}\n".format(npoints))
  f.write("      DPS: {}\n".format(args.dps))
  f.write("------------------------------------\n")
  f.write("*/\n\n")

  f.write("const double boys_shortgrid[{}][{}] = \n".format(npoints, maxn+1))
  f.write("{\n")

  for p,x in zip(F,pts):
    f.write("/* x = {:12}*/  {{".format(mp.nstr(x, 4)))
    for n in p:
      f.write("{:32}, ".format(mp.nstr(n, 18)))
    f.write("},\n")
  f.write("};\n")

with open(args.filename + ".h", 'w') as f: 
  f.write("#pragma once\n")
  f.write("\n")
  f.write("#define BOYS_SHORTGRID_MAXN {}\n".format(maxn))
  f.write("#define BOYS_SHORTGRID_MAXX {}\n".format(maxx))
  f.write("#define BOYS_SHORTGRID_SPACE {}\n".format(inc))
  f.write("#define BOYS_SHORTGRID_NPOINT {}\n".format(npoints))
  f.write("#define BOYS_SHORTGRID_LOOKUPFAC {}\n".format(1.0/inc))
  f.write("#define BOYS_SHORTGRID_LOOKUPFAC2 {}\n".format(0.5*inc))
  f.write("\n")
Beispiel #30
0
            # Compute asymptotic (x -> inf) Rys roots and weights
            # from the second half of the Hermite solution for degree 2n
            #   r_rys = r_h^2 / x
            #   w_rys = w_h / sqrt(x)
            y = one
            if (x != 0):
                y = one / x
            roots_asymp = [r * r * y for r in roots_herm[n:]]
            weights_asymp = [w * mp.sqrt(y) for w in weights_herm[n:]]

            # Compute maximum error in roots and weights, and stop when below accuracy
            error_roots = max(
                [abs(r1 - r2) / r2 for r1, r2 in zip(roots_asymp, roots)])
            error_weights = max(
                [abs(w1 - w2) / w2 for w1, w2 in zip(weights_asymp, weights)])
            error_tot = max(error_roots, error_weights)
            print('x = {0}: error = {1}'.format(figs(x, 2),
                                                figs(error_tot, 4, exp=True)))
            if (error_tot < acc):
                asymp.append(x)
                break

    # Take a step back for the next pass
    init = [a - s for a in asymp]

    print()
    print('Step: {0}'.format(mp.nstr(s)))
    for n, a in zip(order, asymp):
        print('n = {0}: x = {1}'.format(n, figs(a, 2)))
Beispiel #31
0
tin = 0.1
dt = 0.1
tfin = 2

Win = 0  #first amplitude of disorder
Wfin = 6  #last amplitude of disorder
dW = .2  #resolution of disorder amplitude

L = 64

t_vec = [mp.mpf(0.001)] + list(mp.arange(tin, tfin, dt))

W_vec = mp.arange(Win, Wfin, dW)

outputfile = "./BUMP_SD_length=" + str(L) + ".dat"
f1 = open(outputfile, "w")

for t in t_vec:

    for s in W_vec:
        print(t, s)
        inputfile = "./BUMP_SD_length=" + str(L) + "_t=" + mp.nstr(
            t, 3) + "_s=" + mp.nstr(s, 3) + ".dat"
        ND = np.genfromtxt(inputfile)  #,dtype=float, max_rows=250)
        ND = ND[~np.isnan(ND)]
        value = np.mean(ND)
        st = np.std(ND)
        f1.write("%.10f,%.10f,%.10f,%.10f,%i\n" % (t, s, value, st, len(ND)))

f1.close()
Beispiel #32
0
 def strF(dig, chop_=True, signifi_=9):
     if dig: dig = chop(dig)
     return mp.nstr(dig, signifi_)
Beispiel #33
0
 def __repr__(self):
     bmin, bmax = self.GetPeaks()
     return "x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; a = {4}; duration = {5}; bmin = {6}; bmax = {7}".\
         format(mp.nstr(self.x0, n=_prec), mp.nstr(self.x1, n=_prec),
                mp.nstr(self.v0, n=_prec), mp.nstr(self.v1, n=_prec), mp.nstr(self.a, n=_prec),
                mp.nstr(self.duration, n=_prec), mp.nstr(bmin, n=_prec), mp.nstr(bmax, n=_prec))
Beispiel #34
0
def mp_to_complex(mpcplx):
    mpreal = mp.re(mpcplx)
    mpimag = mp.im(mpcplx)
    flreal = np.float(mp.nstr(mpreal, mp.dps))
    flimag = np.float(mp.nstr(mpimag, mp.dps))
    return flreal + 1j * flimag
Beispiel #35
0
    while abs(f / g) > 10.0**(2 - prec):
        x0 = x0 - f / g
        f, g = poly(x0)
    xk[k] = x0
    wk[k] = gamma[n - 2] / (g * pa[n - 2])
    # Capture data for derivative matrix
    for kp in range(n - 1):
        z[k, kp] = pa[kp]
        zp[k, kp] = qa[kp]
        zpp[k, kp] = ra[kp]

zp = zp * mp.powm(z, -1) * b
zpp = zpp * mp.powm(z, -1) * b * b

# Write to datafile
fout = open('out.cgyro.egrid', 'w')
for k in range(n - 1):
    fout.write(
        mp.nstr(xk[k]**2, 17) + ' ' +
        mp.nstr(wk[k] * 4 / mp.sqrt(mp.pi) * xk[k]**2, 17) + '\n')
for k in range(n - 1):
    for kp in range(n - 1):
        fout.write(mp.nstr(zp[k, kp], 17) + ' ')
    fout.write('\n')
for k in range(n - 1):
    for kp in range(n - 1):
        fout.write(mp.nstr(zpp[k, kp], 17) + ' ')
    fout.write('\n')

fout.close()
Beispiel #36
0
def _ImposeJointLimitFixedDuration(curve, xmin, xmax, vm, am):
    bmin, bmax = curve.GetPeaks()
    if (bmin >= Sub(xmin, epsilon)) and (bmax <= Add(xmax, epsilon)):
        # Joint limits are not violated
        return curve
    
    duration = curve.duration
    x0 = curve.x0
    x1 = curve.EvalPos(duration)
    v0 = curve.v0
    v1 = curve.v1

    bt0 = inf
    bt1 = inf
    ba0 = inf
    ba1 = inf
    bx0 = inf
    bx1 = inf
    if (v0 > zero):
        bt0 = _BrakeTime(x0, v0, xmax)
        bx0 = xmax
        ba0 = _BrakeAccel(x0, v0, xmax)
    elif (v0 < zero):
        bt0 = _BrakeTime(x0, v0, xmin)
        bx0 = xmin
        ba0 = _BrakeAccel(x0, v0, xmin)

    if (v1 < zero):
        bt1 = _BrakeTime(x1, -v1, xmax)
        bx1 = xmax
        ba1 = _BrakeAccel(x1, -v1, xmax)
    elif (v1 > zero):
        bt1 = _BrakeTime(x1, -v1, xmin)
        bx1 = xmin
        ba1 = _BrakeAccel(x1, -v1, xmin)

    # import IPython; IPython.embed()
        
    newCurve = ParabolicCurve()
    if ((bt0 < duration) and (Abs(ba0) < Add(am, epsilon))):
        # Case IIa
        log.debug("Case IIa")
        firstRamp = Ramp(v0, ba0, bt0, x0)
        if (Abs(Sub(x1, bx0)) < Mul(Sub(duration, bt0), vm)):
            tempCurve1 = Interpolate1D(bx0, x1, zero, v1, vm, am)
            if not tempCurve1.isEmpty:
                if (Sub(duration, bt0) >= tempCurve1.duration):
                    tempCurve2 = _Stretch1D(tempCurve1, Sub(duration, bt0), vm, am)
                    if not tempCurve2.isEmpty:
                        tempbmin, tempbmax = tempCurve2.GetPeaks()
                        if not ((tempbmin < Sub(xmin, epsilon)) or (tempbmax > Add(xmax, epsilon))):
                            log.debug("Case IIa successful")
                            newCurve = ParabolicCurve([firstRamp] + tempCurve2.ramps)
                                        

    if ((bt1 < duration) and (Abs(ba1) < Add(am, epsilon))):
        # Case IIb
        log.debug("Case IIb")
        lastRamp = Ramp(0, ba1, bt1, bx1)
        if (Abs(Sub(x0, bx1)) < Mul(Sub(duration, bt1), vm)):
            tempCurve1 = Interpolate1D(x0, bx1, v0, zero, vm, am)
            if not tempCurve1.isEmpty:
                if (Sub(duration, bt1) >= tempCurve1.duration):
                    tempCurve2 = _Stretch1D(tempCurve1, Sub(duration, bt1), vm, am)
                    if not tempCurve2.isEmpty:
                        tempbmin, tempbmax = tempCurve2.GetPeaks()
                        if not ((tempbmin < Sub(xmin, epsilon)) or (tempbmax > Add(xmax, epsilon))):
                            log.debug("Case IIb successful")
                            newCurve = ParabolicCurve(tempCurve2.ramps + [lastRamp])          
        

    if (bx0 == bx1):
        # Case III
        if (Add(bt0, bt1) < duration) and (max(Abs(ba0), Abs(ba1)) < Add(am, epsilon)):
            log.debug("Case III")
            ramp0 = Ramp(v0, ba0, bt0, x0)
            ramp1 = Ramp(zero, zero, Sub(duration, Add(bt0, bt1)))
            ramp2 = Ramp(zero, ba1, bt1)
            newCurve = ParabolicCurve([ramp0, ramp1, ramp2])
    else:
        # Case IV
        if (Add(bt0, bt1) < duration) and (max(Abs(ba0), Abs(ba1)) < Add(am, epsilon)):
            log.debug("Case IV")
            firstRamp = Ramp(v0, ba0, bt0, x0)
            lastRamp = Ramp(zero, ba1, bt1)
            if (Abs(Sub(bx0, bx1)) < Mul(Sub(duration, Add(bt0, bt1)), vm)):
                tempCurve1 = Interpolate1D(bx0, bx1, zero, zero, vm, am)
                if not tempCurve1.isEmpty:
                    if (Sub(duration, Add(bt0, bt1)) >= tempCurve1.duration):
                        tempCurve2 = _Stretch1D(tempCurve1, Sub(duration, Add(bt0, bt1)), vm, am)
                        if not tempCurve2.isEmpty:
                            tempbmin, tempbmax = tempCurve2.GetPeaks()
                            if not ((tempbmin < Sub(xmin, epsilon)) or (tempbmax > Add(xmax, epsilon))):
                                log.debug("Case IV successful")
                                newCurve = ParabolicCurve([firstRamp] + tempCurve2.ramps + [lastRamp])
        

    if (newCurve.isEmpty):
        log.warn("Cannot solve for a bounded trajectory")
        log.warn("x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; xmin = {4}; xmax = {5}; vm = {6}; am = {7}; duration = {8}".\
                 format(mp.nstr(curve.x0, n=_prec), mp.nstr(curve.EvalPos(curve.duration), n=_prec),
                        mp.nstr(curve.v0, n=_prec), mp.nstr(curve.EvalVel(curve.duration), n=_prec),
                        mp.nstr(xmin, n=_prec), mp.nstr(xmax, n=_prec),
                        mp.nstr(vm, n=_prec), mp.nstr(am, n=_prec), mp.nstr(duration, n=_prec)))
        return newCurve

    newbmin, newbmax = newCurve.GetPeaks()
    if (newbmin < Sub(xmin, epsilon)) or (newbmax > Add(xmax, epsilon)):
        log.warn("Solving finished but the trajectory still violates the bounds")
        # import IPython; IPython.embed()
        log.warn("x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; xmin = {4}; xmax = {5}; vm = {6}; am = {7}; duration = {8}".\
                 format(mp.nstr(curve.x0, n=_prec), mp.nstr(curve.EvalPos(curve.duration), n=_prec),
                        mp.nstr(curve.v0, n=_prec), mp.nstr(curve.EvalVel(curve.duration), n=_prec),
                        mp.nstr(xmin, n=_prec), mp.nstr(xmax, n=_prec),
                        mp.nstr(vm, n=_prec), mp.nstr(am, n=_prec), mp.nstr(duration, n=_prec)))
        return ParabolicCurve()

    log.debug("Successfully fixed x-bound violation")
    return newCurve
  f.write("Options for asymptotic Boys function factor sqrt(pi)*(2n-1)!!/(2**(n+1)):\n")
  f.write("    Max n: {}\n".format(maxn))
  f.write("      DPS: {}\n".format(args.dps))
  f.write("------------------------------------\n")
  f.write("*/\n\n")

  f.write("namespace psr_modules {\n")
  f.write("namespace integrals {\n")
  f.write("namespace lut {\n")
  f.write("\n")

  f.write("extern const double boys_longfac[{}] = \n".format(maxn+1))
  f.write("{\n")

  for i,n in enumerate(longfac):
      f.write("/* n = {:4} */  {:32},\n".format(i, mp.nstr(n, 18)))
  f.write("};\n")

  f.write("\n")
  f.write("} // closing namespace lut\n")
  f.write("} // closing namespace integrals\n")
  f.write("} // closing namespace psr_modules\n")
  f.write("\n")

with open(args.filename + ".hpp", 'w') as f: 
  f.write("#pragma once\n")
  f.write("\n")
  f.write("#define PSR_MODULES_BOYS_LONGFAC_MAXN {}\n".format(maxn))
  f.write("\n")
  f.write("namespace psr_modules {\n")
  f.write("namespace integrals {\n")
Beispiel #38
0
def Interpolate1DFixedDuration(x0, x1, v0, v1, newDuration, vm, am):
    x0 = ConvertFloatToMPF(x0)
    x1 = ConvertFloatToMPF(x1)
    v0 = ConvertFloatToMPF(v0)
    v1 = ConvertFloatToMPF(v1)
    vm = ConvertFloatToMPF(vm)
    am = ConvertFloatToMPF(am)
    newDuration = ConvertFloatToMPF(newDuration)
    log.debug("\nx0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; newDuration = {6}".\
              format(mp.nstr(x0, n=_prec), mp.nstr(x1, n=_prec), mp.nstr(v0, n=_prec), mp.nstr(v1, n=_prec),
                     mp.nstr(vm, n=_prec), mp.nstr(am, n=_prec), mp.nstr(newDuration, n=_prec)))
    
    # Check inputs
    assert(vm > zero)
    assert(am > zero)

    if (newDuration < -epsilon):
        log.info("duration = {0} is negative".format(newDuration))
        return ParabolicCurve()
    if (newDuration <= epsilon):
        # Check if this is a stationary trajectory
        if (FuzzyEquals(x0, x1, epsilon) and FuzzyEquals(v0, v1, epsilon)):
            log.info("stationary trajectory")
            ramp0 = Ramp(v0, 0, 0, x0)
            newCurve = ParabolicCurve(ramp0)
            return newCurve
        else:
            log.info("newDuration is too short for any movement to be made")
            return ParabolicCurve()

    # Correct small discrepancies if any
    if (v0 > vm):
        if FuzzyEquals(v0, vm, epsilon):
            v0 = vm
        else:
            log.info("v0 > vm: {0} > {1}".format(v0, vm))
            return ParabolicCurve()
    elif (v0 < -vm):
        if FuzzyEquals(v0, -vm, epsilon):
            v0 = -vm
        else:
            log.info("v0 < -vm: {0} < {1}".format(v0, -vm))
            return ParabolicCurve()
    if (v1 > vm):
        if FuzzyEquals(v1, vm, epsilon):
            v1 = vm
        else:
            log.info("v1 > vm: {0} > {1}".format(v1, vm))
            return ParabolicCurve()
    elif (v1 < -vm):
        if FuzzyEquals(v1, -vm, epsilon):
            v1 = -vm
        else:
            log.info("v1 < -vm: {0} < {1}".format(v1, -vm))
            return ParabolicCurve()

    d = Sub(x1, x0)

    # First assume no velocity bound -> re-interpolated trajectory will have only two ramps.
    # Solve for a0 and a1 (the acceleration of the first and the last ramps).
    #         a0 = A + B/t0
    #         a1 = A + B/(t - t0)
    # where t is the (new) total duration, t0 is the (new) duration of the first ramp, and
    #         A = (v1 - v0)/t
    #         B = (2d/t) - (v0 + v1).
    newDurInverse = mp.fdiv(one, newDuration)
    A = Mul(Sub(v1, v0), newDurInverse)
    B = Sub(Prod([mp.mpf('2'), d, newDurInverse]), Add(v0, v1))

    interval0 = iv.mpf([zero, newDuration]) # initial interval for t0

    # Now consider the interval(s) computed from a0's constraints
    sum1 = Neg(Add(am, A))
    sum2 = Sub(am, A)
    C = mp.fdiv(B, sum1)
    D = mp.fdiv(B, sum2)

    log.debug("\nA = {0}; \nB = {1}; \nC = {2}; \nD = {3}; \nsum1 = {4}; \nsum2 = {5};".\
              format(mp.nstr(A, n=_prec), mp.nstr(B, n=_prec), mp.nstr(C, n=_prec), mp.nstr(D, n=_prec),
                     mp.nstr(sum1, n=_prec), mp.nstr(sum2, n=_prec)))

    if (sum1 > zero):
        # This implied that the duration is too short
        log.debug("the given duration ({0}) is too short.".format(newDuration))
        return ParabolicCurve()
    if (sum2 < zero):
        # This implied that the duration is too short
        log.debug("the given duration ({0}) is too short.".format(newDuration))
        return ParabolicCurve()
    
    if IsEqual(sum1, zero):
        raise NotImplementedError # not yet considered
    elif sum1 > epsilon:
        log.debug("sum1 > 0. This implies that newDuration is too short.")
        return ParabolicCurve()
    else:
        interval1 = iv.mpf([C, inf])
        
    if IsEqual(sum2, zero):
        raise NotImplementedError # not yet considered
    elif sum2 > epsilon:
        interval2 = iv.mpf([D, inf])
    else:
        log.debug("sum2 < 0. This implies that newDuration is too short.")
        return ParabolicCurve()
        
    if Sub(interval2.a, interval1.b) > epsilon or Sub(interval1.a, interval2.b) > epsilon:
        # interval1 and interval2 do not intersect each other
        return ParabolicCurve()    
    # interval3 = interval1 \cap interval2 : valid interval for t0 computed from a0's constraints
    interval3 = iv.mpf([max(interval1.a, interval2.a), min(interval1.b, interval2.b)])
    
    # Now consider the interval(s) computed from a1's constraints
    if IsEqual(sum1, zero):
        raise NotImplementedError # not yet considered
    elif sum1 > epsilon:
        log.debug("sum1 > 0. This implies that newDuration is too short.")
        return ParabolicCurve()
    else:
        interval4 = iv.mpf([Neg(inf), Add(C, newDuration)])
        
    if IsEqual(sum2, zero):
        raise NotImplementedError # not yet considered
    elif sum2 > epsilon:
        interval5 = iv.mpf([Neg(inf), Add(D, newDuration)])
    else:
        log.debug("sum2 < 0. This implies that newDuration is too short.")
        return ParabolicCurve()

    if Sub(interval5.a, interval4.b) > epsilon or Sub(interval4.a, interval5.b) > epsilon:
        log.debug("interval4 and interval5 do not intersect each other")
        return ParabolicCurve()
    # interval6 = interval4 \cap interval5 : valid interval for t0 computed from a1's constraints
    interval6 = iv.mpf([max(interval4.a, interval5.a), min(interval4.b, interval5.b)])

    # import IPython; IPython.embed()

    if Sub(interval3.a, interval6.b) > epsilon or Sub(interval6.a, interval3.b) > epsilon:
        log.debug("interval3 and interval6 do not intersect each other")
        return ParabolicCurve()
    # interval7 = interval3 \cap interval6
    interval7 = iv.mpf([max(interval3.a, interval6.a), min(interval3.b, interval6.b)])

    if Sub(interval0.a, interval7.b) > epsilon or Sub(interval7.a, interval0.b) > epsilon:
        log.debug("interval0 and interval7 do not intersect each other")
        return ParabolicCurve()
    # interval8 = interval0 \cap interval7 : valid interval of t0 when considering all constraints (from a0 and a1)
    interval8 = iv.mpf([max(interval0.a, interval7.a), min(interval0.b, interval7.b)])

    # import IPython; IPython.embed()
    
    # We choose the value t0 (the duration of the first ramp) by selecting the mid point of the
    # valid interval of t0.
    
    t0 = _SolveForT0(A, B, newDuration, interval8)
    if t0 is None:
        # The fancy procedure fails. Now consider no optimization whatsoever.
        # TODO: Figure out why solving fails.
        t0 = mp.convert(interval8.mid) # select the midpoint
        # return ParabolicCurve()
    t1 = Sub(newDuration, t0)

    a0 = Add(A, Mul(mp.fdiv(one, t0), B))
    if (Abs(t1) < epsilon):
        a1 = zero
    else:
        a1 = Add(A, Mul(mp.fdiv(one, Neg(t1)), B))
    assert(Sub(Abs(a0), am) < epsilon) # check if a0 is really below the bound
    assert(Sub(Abs(a1), am) < epsilon) # check if a1 is really below the bound

    # import IPython; IPython.embed()
    
    # Check if the velocity bound is violated    
    vp = Add(v0, Mul(a0, t0))
    if Abs(vp) > vm:
        vmnew = Mul(mp.sign(vp), vm)
        D2 = Prod([pointfive, Sqr(Sub(vp, vmnew)), Sub(mp.fdiv(one, a0), mp.fdiv(one, a1))])
        # print("D2", end=' ')
        # mp.nprint(D2, n=_prec)
        # print("vmnew", end=' ')
        # mp.nprint(vmnew, n=_prec)
        A2 = Sqr(Sub(vmnew, v0))
        B2 = Neg(Sqr(Sub(vmnew, v1)))
        t0trimmed = mp.fdiv(Sub(vmnew, v0), a0)
        t1trimmed = mp.fdiv(Sub(v1, vmnew), a1)
        C2 = Sum([Mul(t0trimmed, Sub(vmnew, v0)), Mul(t1trimmed, Sub(vmnew, v1)), Mul(mp.mpf('-2'), D2)])

        log.debug("\nA2 = {0}; \nB2 = {1}; \nC2 = {2}; \nD2 = {3};".format(mp.nstr(A2, n=_prec), mp.nstr(B2, n=_prec), mp.nstr(C2, n=_prec), mp.nstr(D2, n=_prec)))
        
        temp = Prod([A2, B2, B2])
        initguess = mp.sign(temp)*(Abs(temp)**(1./3.))
        root = mp.findroot(lambda x: Sub(Prod([x, x, x]), temp), x0=initguess)

        # import IPython; IPython.embed()
        log.debug("root = {0}".format(mp.nstr(root, n=_prec)))
        a0new = mp.fdiv(Add(A2, root), C2)
        if (Abs(a0new) > Add(am, epsilon)):
            if FuzzyZero(Sub(Mul(C2, a0new), A2), epsilon):
                # The computed a0new is exceeding the bound and its corresponding a1new is
                # zero. Therefore, there is no other way to fix this. This is probably because the
                # given newDuration is less than the minimum duration (x0, x1, v0, v1, vm, am) can
                # get.
                log.debug("abs(a0new) > am and a1new = 0; Cannot fix this case. This happens probably because the given newDuration is too short.")
                return ParabolicCurve()
            
            a0new = Mul(mp.sign(a0new), am)

        if (Abs(a0new) < epsilon):
            a1new = mp.fdiv(B2, C2)
            if (Abs(a1new) > Add(am, epsilon)):
                # Similar to the case above
                log.debug("a0new = 0 and abs(a1new) > am; Cannot fix this case. This happens probably because the given newDuration is too short.")
                return ParabolicCurve()

        else:
            if FuzzyZero(Sub(Mul(C2, a0new), A2), epsilon):
                # import IPython; IPython.embed()
                a1new = 0
            else:
                a1new = Mul(mp.fdiv(B2, C2), Add(one, mp.fdiv(A2, Sub(Mul(C2, a0new), A2))))
                if (Abs(a1new) > Add(am, epsilon)):
                    a1new = Mul(mp.sign(a1new), am)
                    a0new = Mul(mp.fdiv(A2, C2), Add(one, mp.fdiv(B2, Sub(Mul(C2, a1new), B2))))

        if (Abs(a0new) > Add(am, epsilon)) or (Abs(a1new) > Add(am, epsilon)):
            log.warn("Cannot fix acceleration bounds violation")
            return ParabolicCurve()        

        log.debug("\na0 = {0}; \na0new = {1}; \na1 = {2}; \na1new = {3};".format(mp.nstr(a0, n=_prec), mp.nstr(a0new, n=_prec), mp.nstr(a1, n=_prec), mp.nstr(a1new, n=_prec)))
        
        if (Abs(a0new) < epsilon) and (Abs(a1new) < epsilon):
            log.warn("Both accelerations are zero. Should we allow this case?")
            return ParabolicCurve()

        if (Abs(a0new) < epsilon):
            # This is likely because v0 is at the velocity bound
            t1new = mp.fdiv(Sub(v1, vmnew), a1new)
            assert(t1new > 0)
            ramp2 = Ramp(v0, a1new, t1new)

            t0new = Sub(newDuration, t1new)
            assert(t0new > 0)
            ramp1 = Ramp(v0, zero, t0new, x0)
            newCurve = ParabolicCurve([ramp1, ramp2])
            return newCurve

        elif (Abs(a1new) < epsilon):
            t0new = mp.fdiv(Sub(vmnew, v0), a0new)
            assert(t0new > 0)
            ramp1 = Ramp(v0, a0new, t0new, x0)
            
            t1new = Sub(newDuration, t0new)
            assert(t1new > 0)
            ramp2 = Ramp(ramp1.v1, zero, t1new)
            newCurve = ParabolicCurve([ramp1, ramp2])
            return newCurve

        else:
            # No problem with those new accelerations
            # import IPython; IPython.embed()
            t0new = mp.fdiv(Sub(vmnew, v0), a0new)
            if (t0new < 0):
                log.debug("t0new < 0. The given newDuration not achievable with the given bounds")
                return ParabolicCurve()
            
            t1new = mp.fdiv(Sub(v1, vmnew), a1new)
            if (t1new < 0):
                log.debug("t1new < 0. The given newDuration not achievable with the given bounds")
                return ParabolicCurve()
            
            if (Add(t0new, t1new) > newDuration):
                # Final fix. Since we give more weight to acceleration bounds, we make the velocity
                # bound saturated. Therefore, we set vp to vmnew.

                # import IPython; IPython.embed()
                if FuzzyZero(A, epsilon):
                    log.warn("(final fix) A is zero. Don't know how to fix this case")
                    return ParabolicCurve()

                t0new = mp.fdiv(Sub(Sub(vmnew, v0), B), A)
                if (t0new < 0):
                    log.debug("(final fix) t0new is negative")
                    return ParabolicCurve()

                t1new = Sub(newDuration, t0new)
                
                a0new = Add(A, Mul(mp.fdiv(one, t0new), B))
                a1new = Add(A, Mul(mp.fdiv(one, Neg(t1new)), B))
                ramp1 = Ramp(v0, a0new, t0new, x0)
                ramp2 = Ramp(ramp1.v1, a1new, t1new)
                newCurve = ParabolicCurve([ramp1, ramp2])

            else:
                ramp1 = Ramp(v0, a0new, t0new, x0)
                ramp3 = Ramp(ramp1.v1, a1new, t1new)
                ramp2 = Ramp(ramp1.v1, zero, Sub(newDuration, Add(t0new , t1new)))
                newCurve = ParabolicCurve([ramp1, ramp2, ramp3])
                
                # import IPython; IPython.embed()
            
            return newCurve
    else:    
        ramp1 = Ramp(v0, a0, t0, x0)
        ramp2 = Ramp(ramp1.v1, a1, t1)
        newCurve = ParabolicCurve([ramp1, ramp2])
        return newCurve
Beispiel #39
0
# Set the dps option
mp.dps = 256

# Convert stuff to mpmath
inc = mp.mpf(args.spacing)
eps = mp.power(10, -args.eps)

cutoffs = [None] * (args.max_n+1)
cutoff_diffs = [None] * (args.max_n+1)

x = mp.mpf(0)
maxdiff = eps * 2.0 # force loop to run

while maxdiff > eps:
  x = x + inc

  F_real = BoysValue(args.max_n, x) 
  F_long = BoysValue_Asymptotic(args.max_n, x)

  diff = [ mp.fabs(F_real[i] - F_long[i]) for i in range(0, len(F_real)) ]
  maxdiff = max(diff)

  for idx,val in enumerate(diff):
      if not cutoffs[idx] and diff[idx] < eps:
          cutoffs[idx] = x
          cutoff_diffs[idx] = val

for idx,val in enumerate(cutoffs):
    print("{:4}  {}".format(idx, mp.nstr(val)))
Beispiel #40
0
def _Stretch1D(curve, newDuration, vm, am):

    log.debug("\nx0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; vm = {4}; am = {5}; prevDuration = {6}; newDuration = {7}".\
              format(mp.nstr(curve.x0, n=_prec), mp.nstr(curve.EvalPos(curve.duration), n=_prec),
                     mp.nstr(curve.v0, n=_prec), mp.nstr(curve.EvalVel(curve.duration), n=_prec),
                     mp.nstr(vm, n=_prec), mp.nstr(am, n=_prec), mp.nstr(curve.duration, n=_prec),
                     mp.nstr(newDuration, n=_prec)))
    
    # Check types
    if type(newDuration) is not mp.mpf:
        newDuration = mp.mpf("{:.15e}".format(newDuration))
    if type(vm) is not mp.mpf:
        vm = mp.mpf("{:.15e}".format(vm))
    if type(am) is not mp.mpf:
        am = mp.mpf("{:.15e}".format(am))

    # Check inputs
    # assert(newDuration > curve.duration)
    assert(vm > zero)
    assert(am > zero)

    if (newDuration < -epsilon):
        return ParabolicCurve()
    if (newDuration <= epsilon):
        # Check if this is a stationary trajectory
        if (FuzzyEquals(curve.x0, curve.EvalPos(x1), epsilon) and FuzzyEquals(curve.v0, curve.v1, epsilon)):
            ramp0 = Ramp(curve.v0, 0, 0, curve.x0)
            newCurve = ParabolicCurve(ramp0)
            return newCurve
        else:
            # newDuration is too short to any movement to be made
            return ParabolicCurve()

    v0 = curve[0].v0
    v1 = curve[-1].v1
    d = curve.d

    # First assume no velocity bound -> re-interpolated trajectory will have only two ramps.
    # Solve for a0 and a1 (the acceleration of the first and the last ramps).
    #         a0 = A + B/t0
    #         a1 = A + B/(t - t0)
    # where t is the (new) total duration, t0 is the (new) duration of the first ramp, and
    #         A = (v1 - v0)/t
    #         B = (2d/t) - (v0 + v1).
    newDurInverse = mp.fdiv(one, newDuration)
    A = Mul(Sub(v1, v0), newDurInverse)
    B = Sub(Prod([mp.mpf('2'), d, newDurInverse]), Add(v0, v1))

    interval0 = iv.mpf([zero, newDuration]) # initial interval for t0

    # Now consider the interval(s) computed from a0's constraints
    sum1 = Neg(Add(am, A))
    sum2 = Sub(am, A)
    C = mp.fdiv(B, sum1)
    D = mp.fdiv(B, sum2)

    log.debug("\nA = {0}; \nB = {1}; \nC = {2}; \nD = {3}; \nsum1 = {4}; \nsum2 = {5};".\
              format(mp.nstr(A, n=_prec), mp.nstr(B, n=_prec), mp.nstr(C, n=_prec), mp.nstr(D, n=_prec),
                     mp.nstr(sum1, n=_prec), mp.nstr(sum2, n=_prec)))

    assert(not (sum1 > zero))
    assert(not (sum2 < zero))
    
    if IsEqual(sum1, zero):
        raise NotImplementedError # not yet considered
    elif sum1 > epsilon:
        log.debug("sum1 > 0. This implies that newDuration is too short.")
        return ParabolicCurve()
    else:
        interval1 = iv.mpf([C, inf])
        
    if IsEqual(sum2, zero):
        raise NotImplementedError # not yet considered
    elif sum2 > epsilon:
        interval2 = iv.mpf([D, inf])
    else:
        log.debug("sum2 < 0. This implies that newDuration is too short.")
        return ParabolicCurve()
        
    if Sub(interval2.a, interval1.b) > epsilon or Sub(interval1.a, interval2.b) > epsilon:
        # interval1 and interval2 do not intersect each other
        return ParabolicCurve()    
    # interval3 = interval1 \cap interval2 : valid interval for t0 computed from a0's constraints
    interval3 = iv.mpf([max(interval1.a, interval2.a), min(interval1.b, interval2.b)])
    
    # Now consider the interval(s) computed from a1's constraints
    if IsEqual(sum1, zero):
        raise NotImplementedError # not yet considered
    elif sum1 > epsilon:
        log.debug("sum1 > 0. This implies that newDuration is too short.")
        return ParabolicCurve()
    else:
        interval4 = iv.mpf([Neg(inf), Add(C, newDuration)])
        
    if IsEqual(sum2, zero):
        raise NotImplementedError # not yet considered
    elif sum2 > epsilon:
        interval5 = iv.mpf([Neg(inf), Add(D, newDuration)])
    else:
        log.debug("sum2 < 0. This implies that newDuration is too short.")
        return ParabolicCurve()

    if Sub(interval5.a, interval4.b) > epsilon or Sub(interval4.a, interval5.b) > epsilon:
        # interval4 and interval5 do not intersect each other
        return ParabolicCurve()
    # interval6 = interval4 \cap interval5 : valid interval for t0 computed from a1's constraints
    interval6 = iv.mpf([max(interval4.a, interval5.a), min(interval4.b, interval5.b)])

    # import IPython; IPython.embed()

    if Sub(interval3.a, interval6.b) > epsilon or Sub(interval6.a, interval3.b) > epsilon:
        # interval3 and interval6 do not intersect each other
        return ParabolicCurve()
    # interval7 = interval3 \cap interval6
    interval7 = iv.mpf([max(interval3.a, interval6.a), min(interval3.b, interval6.b)])

    if Sub(interval0.a, interval7.b) > epsilon or Sub(interval7.a, interval0.b) > epsilon:
        # interval0 and interval7 do not intersect each other
        return ParabolicCurve()
    # interval8 = interval0 \cap interval7 : valid interval of t0 when considering all constraints (from a0 and a1)
    interval8 = iv.mpf([max(interval0.a, interval7.a), min(interval0.b, interval7.b)])

    # import IPython; IPython.embed()
    
    # We choose the value t0 (the duration of the first ramp) by selecting the mid point of the
    # valid interval of t0.
    
    t0 = _SolveForT0(A, B, newDuration, interval8)
    if t0 is None:
        # The fancy procedure fails. Now consider no optimization whatsoever.
        # TODO: Figure out why solving fails.
        t0 = mp.convert(interval8.mid) # select the midpoint
        # return ParabolicCurve()
    t1 = Sub(newDuration, t0)

    a0 = Add(A, Mul(mp.fdiv(one, t0), B))
    if (Abs(t1) < epsilon):
        a1 = zero
    else:
        a1 = Add(A, Mul(mp.fdiv(one, Neg(t1)), B))
    assert(Sub(Abs(a0), am) < epsilon) # check if a0 is really below the bound
    assert(Sub(Abs(a1), am) < epsilon) # check if a1 is really below the bound

    # import IPython; IPython.embed()
    
    # Check if the velocity bound is violated    
    vp = Add(v0, Mul(a0, t0))
    if Abs(vp) > vm:
        vmnew = Mul(mp.sign(vp), vm)
        D2 = Prod([pointfive, Sqr(Sub(vp, vmnew)), Sub(mp.fdiv(one, a0), mp.fdiv(one, a1))])
        # print "D2",
        # mp.nprint(D2, n=_prec)
        # print "vmnew",
        # mp.nprint(vmnew, n=_prec)
        A2 = Sqr(Sub(vmnew, v0))
        B2 = Neg(Sqr(Sub(vmnew, v1)))
        t0trimmed = mp.fdiv(Sub(vmnew, v0), a0)
        t1trimmed = mp.fdiv(Sub(v1, vmnew), a1)
        C2 = Sum([Mul(t0trimmed, Sub(vmnew, v0)), Mul(t1trimmed, Sub(vmnew, v1)), Mul(mp.mpf('-2'), D2)])

        log.debug("\nA2 = {0}; \nB2 = {1}; \nC2 = {2}; \nD2 = {3};".format(mp.nstr(A2, n=_prec), mp.nstr(B2, n=_prec), mp.nstr(C2, n=_prec), mp.nstr(D2, n=_prec)))
        
        temp = Prod([A2, B2, B2])
        initguess = mp.sign(temp)*(Abs(temp)**(1./3.))
        root = mp.findroot(lambda x: Sub(Prod([x, x, x]), temp), x0=initguess)

        # import IPython; IPython.embed()
        log.debug("root = {0}".format(mp.nstr(root, n=_prec)))
        a0new = mp.fdiv(Add(A2, root), C2)
        if (Abs(a0new) > Add(am, epsilon)):
            a0new = Mul(mp.sign(a0new), am)

        if (Abs(a0new) < epsilon):
            a1new = mp.fdiv(B2, C2)
            if (Abs(a1new) > Add(am, epsilon)):
                log.warn("abs(a1new) > am; cannot fix this case")
                # Cannot fix this case
                return ParabolicCurve()

        else:
            if FuzzyZero(Sub(Mul(C2, a0new), A2), epsilon):
                # import IPython; IPython.embed()
                a1new = 0
            else:
                a1new = Mul(mp.fdiv(B2, C2), Add(one, mp.fdiv(A2, Sub(Mul(C2, a0new), A2))))
                if (Abs(a1new) > Add(am, epsilon)):
                    a1new = Mul(mp.sign(a1new), am)
                    a0new = Mul(mp.fdiv(A2, C2), Add(one, mp.fdiv(B2, Sub(Mul(C2, a1new), B2))))

        if (Abs(a0new) > Add(am, epsilon)) or (Abs(a1new) > Add(am, epsilon)):
            log.warn("Cannot fix acceleration bounds violation")
            return ParabolicCurve()        

        log.debug("\na0 = {0}; \na0new = {1}; \na1 = {2}; \na1new = {3};".format(mp.nstr(a0, n=_prec), mp.nstr(a0new, n=_prec), mp.nstr(a1, n=_prec), mp.nstr(a1new, n=_prec)))
        
        if (Abs(a0new) < epsilon) and (Abs(a1new) < epsilon):
            log.warn("Both accelerations are zero. Should we allow this case?")
            return ParabolicCurve()

        if (Abs(a0new) < epsilon):
            # This is likely because v0 is at the velocity bound
            t1new = mp.fdiv(Sub(v1, vmnew), a1new)
            assert(t1new > 0)
            ramp2 = Ramp(v0, a1new, t1new)

            t0new = Sub(newDuration, t1new)
            assert(t0new > 0)
            ramp1 = Ramp(v0, zero, t0new, curve.x0)
            newCurve = ParabolicCurve([ramp1, ramp2])
            return newCurve

        elif (Abs(a1new) < epsilon):
            t0new = mp.fdiv(Sub(vmnew, v0), a0new)
            assert(t0new > 0)
            ramp1 = Ramp(v0, a0new, t0new, curve.x0)
            
            t1new = Sub(newDuration, t0new)
            assert(t1new > 0)
            ramp2 = Ramp(ramp1.v1, zero, t1new)
            newCurve = ParabolicCurve([ramp1, ramp2])
            return newCurve

        else:
            # No problem with those new accelerations
            # import IPython; IPython.embed()
            t0new = mp.fdiv(Sub(vmnew, v0), a0new)
            assert(t0new > 0)
            t1new = mp.fdiv(Sub(v1, vmnew), a1new)
            assert(t1new > 0)
            if (Add(t0new, t1new) > newDuration):
                # Final fix. Since we give more weight to acceleration bounds, we make the velocity
                # bound saturated. Therefore, we set vp to vmnew.

                # import IPython; IPython.embed()
                t0new = mp.fdiv(Sub(Sub(vmnew, v0), B), A)
                t1new = Sub(newDuration, t0new)
                assert(t1new > zero)
                a0new = Add(A, Mul(mp.fdiv(one, t0new), B))
                a1new = Add(A, Mul(mp.fdiv(one, Neg(t1new)), B))
                ramp1 = Ramp(v0, a0new, t0new, curve.x0)
                ramp2 = Ramp(ramp1.v1, a1new, t1new)
                newCurve = ParabolicCurve([ramp1, ramp2])

            else:
                # t0new = mp.fdiv(Sub(vmnew, v0), a0new)
                # assert(t0new > 0)
                ramp1 = Ramp(v0, a0new, t0new, curve.x0)
                
                # t1new = mp.fdiv(Sub(v1, vmnew), a1new)
                # assert(t1new > 0)
                ramp3 = Ramp(ramp1.v1, a1new, t1new)
                # print "a1",
                # mp.nprint(a1, n=_prec)
                # print "a1new",
                # mp.nprint(a1new, n=_prec)
                
                # print "t0trimmed",
                # mp.nprint(t0trimmed, n=_prec)
                # print "t0new",
                # mp.nprint(t0new, n=_prec)
                # print "t1trimmed", 
                # mp.nprint(t1trimmed, n=_prec)
                # print "t1new", 
                # mp.nprint(t1new, n=_prec)
                # print "T", 
                # mp.nprint(newDuration, n=_prec)
                
                ramp2 = Ramp(ramp1.v1, zero, Sub(newDuration, Add(t0new , t1new)))
                newCurve = ParabolicCurve([ramp1, ramp2, ramp3])
                
                # import IPython; IPython.embed()
            
            return newCurve
    else:    
        ramp1 = Ramp(v0, a0, t0, curve.x0)
        ramp2 = Ramp(ramp1.v1, a1, t1)
        newCurve = ParabolicCurve([ramp1, ramp2])
        return newCurve
Beispiel #41
0
def _ImposeJointLimitFixedDuration(curve, xmin, xmax, vm, am):
    bmin, bmax = curve.GetPeaks()
    if (bmin >= Sub(xmin, epsilon)) and (bmax <= Add(xmax, epsilon)):
        # Joint limits are not violated
        return curve

    duration = curve.duration
    x0 = curve.x0
    x1 = curve.EvalPos(duration)
    v0 = curve.v0
    v1 = curve.v1

    bt0 = inf
    bt1 = inf
    ba0 = inf
    ba1 = inf
    bx0 = inf
    bx1 = inf
    if (v0 > zero):
        bt0 = _BrakeTime(x0, v0, xmax)
        bx0 = xmax
        ba0 = _BrakeAccel(x0, v0, xmax)
    elif (v0 < zero):
        bt0 = _BrakeTime(x0, v0, xmin)
        bx0 = xmin
        ba0 = _BrakeAccel(x0, v0, xmin)

    if (v1 < zero):
        bt1 = _BrakeTime(x1, -v1, xmax)
        bx1 = xmax
        ba1 = _BrakeAccel(x1, -v1, xmax)
    elif (v1 > zero):
        bt1 = _BrakeTime(x1, -v1, xmin)
        bx1 = xmin
        ba1 = _BrakeAccel(x1, -v1, xmin)

    # import IPython; IPython.embed()

    newCurve = ParabolicCurve()
    if ((bt0 < duration) and (Abs(ba0) < Add(am, epsilon))):
        # Case IIa
        log.debug("Case IIa")
        firstRamp = Ramp(v0, ba0, bt0, x0)
        if (Abs(Sub(x1, bx0)) < Mul(Sub(duration, bt0), vm)):
            tempCurve1 = Interpolate1D(bx0, x1, zero, v1, vm, am)
            if not tempCurve1.isEmpty:
                if (Sub(duration, bt0) >= tempCurve1.duration):
                    tempCurve2 = _Stretch1D(tempCurve1, Sub(duration, bt0), vm,
                                            am)
                    if not tempCurve2.isEmpty:
                        tempbmin, tempbmax = tempCurve2.GetPeaks()
                        if not ((tempbmin < Sub(xmin, epsilon)) or
                                (tempbmax > Add(xmax, epsilon))):
                            log.debug("Case IIa successful")
                            newCurve = ParabolicCurve([firstRamp] +
                                                      tempCurve2.ramps)

    if ((bt1 < duration) and (Abs(ba1) < Add(am, epsilon))):
        # Case IIb
        log.debug("Case IIb")
        lastRamp = Ramp(0, ba1, bt1, bx1)
        if (Abs(Sub(x0, bx1)) < Mul(Sub(duration, bt1), vm)):
            tempCurve1 = Interpolate1D(x0, bx1, v0, zero, vm, am)
            if not tempCurve1.isEmpty:
                if (Sub(duration, bt1) >= tempCurve1.duration):
                    tempCurve2 = _Stretch1D(tempCurve1, Sub(duration, bt1), vm,
                                            am)
                    if not tempCurve2.isEmpty:
                        tempbmin, tempbmax = tempCurve2.GetPeaks()
                        if not ((tempbmin < Sub(xmin, epsilon)) or
                                (tempbmax > Add(xmax, epsilon))):
                            log.debug("Case IIb successful")
                            newCurve = ParabolicCurve(tempCurve2.ramps +
                                                      [lastRamp])

    if (bx0 == bx1):
        # Case III
        if (Add(bt0, bt1) < duration) and (max(Abs(ba0), Abs(ba1)) < Add(
                am, epsilon)):
            log.debug("Case III")
            ramp0 = Ramp(v0, ba0, bt0, x0)
            ramp1 = Ramp(zero, zero, Sub(duration, Add(bt0, bt1)))
            ramp2 = Ramp(zero, ba1, bt1)
            newCurve = ParabolicCurve([ramp0, ramp1, ramp2])
    else:
        # Case IV
        if (Add(bt0, bt1) < duration) and (max(Abs(ba0), Abs(ba1)) < Add(
                am, epsilon)):
            log.debug("Case IV")
            firstRamp = Ramp(v0, ba0, bt0, x0)
            lastRamp = Ramp(zero, ba1, bt1)
            if (Abs(Sub(bx0, bx1)) < Mul(Sub(duration, Add(bt0, bt1)), vm)):
                tempCurve1 = Interpolate1D(bx0, bx1, zero, zero, vm, am)
                if not tempCurve1.isEmpty:
                    if (Sub(duration, Add(bt0, bt1)) >= tempCurve1.duration):
                        tempCurve2 = _Stretch1D(tempCurve1,
                                                Sub(duration, Add(bt0, bt1)),
                                                vm, am)
                        if not tempCurve2.isEmpty:
                            tempbmin, tempbmax = tempCurve2.GetPeaks()
                            if not ((tempbmin < Sub(xmin, epsilon)) or
                                    (tempbmax > Add(xmax, epsilon))):
                                log.debug("Case IV successful")
                                newCurve = ParabolicCurve([firstRamp] +
                                                          tempCurve2.ramps +
                                                          [lastRamp])

    if (newCurve.isEmpty):
        log.warn("Cannot solve for a bounded trajectory")
        log.warn("x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; xmin = {4}; xmax = {5}; vm = {6}; am = {7}; duration = {8}".\
                 format(mp.nstr(curve.x0, n=_prec), mp.nstr(curve.EvalPos(curve.duration), n=_prec),
                        mp.nstr(curve.v0, n=_prec), mp.nstr(curve.EvalVel(curve.duration), n=_prec),
                        mp.nstr(xmin, n=_prec), mp.nstr(xmax, n=_prec),
                        mp.nstr(vm, n=_prec), mp.nstr(am, n=_prec), mp.nstr(duration, n=_prec)))
        return newCurve

    newbmin, newbmax = newCurve.GetPeaks()
    if (newbmin < Sub(xmin, epsilon)) or (newbmax > Add(xmax, epsilon)):
        log.warn(
            "Solving finished but the trajectory still violates the bounds")
        # import IPython; IPython.embed()
        log.warn("x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; xmin = {4}; xmax = {5}; vm = {6}; am = {7}; duration = {8}".\
                 format(mp.nstr(curve.x0, n=_prec), mp.nstr(curve.EvalPos(curve.duration), n=_prec),
                        mp.nstr(curve.v0, n=_prec), mp.nstr(curve.EvalVel(curve.duration), n=_prec),
                        mp.nstr(xmin, n=_prec), mp.nstr(xmax, n=_prec),
                        mp.nstr(vm, n=_prec), mp.nstr(am, n=_prec), mp.nstr(duration, n=_prec)))
        return ParabolicCurve()

    log.debug("Successfully fixed x-bound violation")
    return newCurve
Beispiel #42
0
 def __repr__(self):
     bmin, bmax = self.GetPeaks()
     return "x0 = {0}; x1 = {1}; v0 = {2}; v1 = {3}; a = {4}; duration = {5}; bmin = {6}; bmax = {7}".\
         format(mp.nstr(self.x0, n=_prec), mp.nstr(self.EvalPos(self.duration), n=_prec),
                mp.nstr(self.v0, n=_prec), mp.nstr(self.v1, n=_prec), mp.nstr(self.a, n=_prec),
                mp.nstr(self.duration, n=_prec), mp.nstr(bmin, n=_prec), mp.nstr(bmax, n=_prec))
Beispiel #43
0
    longfac[n] = longfac[n - 1] * 0.5 * (2.0 * n - 1)

# Output to file
with open(args.filename + ".h", 'w') as f:
    f.write("/*\n")
    f.write(" Generated with:\n")
    f.write("   " + " ".join(sys.argv[:]))
    f.write("\n")
    f.write("------------------------------------\n")
    f.write(
        "Options for long Boys function factor sqrt(pi)*(2n-1)!!/(2**(n+1)):\n"
    )
    f.write("    Max n: {}\n".format(maxn))
    f.write("      DPS: {}\n".format(args.dps))
    f.write("------------------------------------\n")
    f.write("*/\n\n")

    f.write("#pragma once\n")

    f.write("\n")
    f.write("#define BOYS_LONGFAC_MAXN {}\n\n".format(maxn))

    f.write("static const double boys_longfac[BOYS_LONGFAC_MAXN + 1] = \n")
    f.write("{\n")

    for i, n in enumerate(longfac):
        f.write("/* n = {:4} */  {:32},\n".format(i, mp.nstr(n, 18)))
    f.write("};\n")

    f.write("\n")
Beispiel #44
0
            mp.log(mp.mpf(1.0) + mp.exp(-x)) + mp.fdiv(x,
                                                       mp.exp(x) + mp.mpf(1.0))
            for x in EH_eigval
        ]))
    return (S)


minLen = 8
maxLen = 67
pace = 4
r_vec = [1.5]
L_vec = range(minLen, maxLen, pace)
ClosedLoop = False

for r in r_vec:
    outputfile = "./SD_of_L_r=" + mp.nstr(r, 2) + ".dat"
    f1 = open(outputfile, "w")

    Sq = np.zeros(len(L_vec))
    iteration = 0
    R = r
    for L in L_vec:  # L is chain length
        print(R, L)
        mp.dps = L * 4.0  # sets the digits of the decimal numbers

        N = int(L / 2)
        Np = N
        A = list(range(int(L / 4)))
        B = list(range(int(L / 4), int(L / 2)))
        D = list(range(int(L / 2), int(3 * L / 4)))
        C = list(range(int(3 * L / 4), L))
Beispiel #45
0
  def __init__(self, n, l):
    self.number = n
    self.log10 = l[0:2] + "\,".join([l[i:i+3] for i in range(2, len(l), 3)])

if __name__ == "__main__":
  input_dps = 5
  output_dps = 60
  rows_per_page = 50
  mp.dps = output_dps + 10
  
  table_raw = []
  for number in mp.arange(1.0, 10.0, mp.power(10, -(input_dps-1))):
    table_raw.append([number, mp.log10(number)])
  
  table_str = []
  table_str = [str_item(mp.nstr(row[0], input_dps), mp.nstr(row[1], output_dps)) for row in table_raw]

  pages = [table_str[i:i+rows_per_page] for i in range(0, len(table_str), rows_per_page)]
  
  latex_renderer = Environment(
    block_start_string = "%{",
    block_end_string = "%}",
    line_statement_prefix = "%#",
    variable_start_string = "%{{",
    variable_end_string = "%}}",
    loader = FileSystemLoader("."))
  template = latex_renderer.get_template("template.tex")
  
  with open("log_table.tex", mode="w") as f:
    f.write(template.render(pages=pages))
def perform_rate_analysis(prefix,
                          ENs,
                          Evib=0.,
                          T=473,
                          p0=1,
                          N2_frac=0.25,
                          X=0.01,
                          site='step',
                          plot=True,
                          alkali_promotion=False,
                          use_alpha=False,
                          model='effective',
                          nlevels=1,
                          dist='Treanor',
                          Tv=3500,
                          metals=[],
                          Agg=False):

    if Agg:
        import matplotlib
        matplotlib.use('Agg')
    from mkm import NH3mkm

    Rs = []
    Ro = []
    Rss = []
    thetao = []
    thetass = []

    theta0 = np.zeros(4)
    for i, EN in enumerate(ENs):

        mod = NH3mkm(T,
                     EN,
                     Evib,
                     p0,
                     N2_frac,
                     X=X,
                     site=site,
                     alkali_promotion=alkali_promotion,
                     model=model,
                     dist=dist,
                     Tv=Tv,
                     nlevels=nlevels,
                     use_alpha=use_alpha)

        Rds, rsab = mod.get_sabatier_rate()
        Rs.append(rsab)

        theta = mod.integrate_odes(theta0=theta0,
                                   h0=1e-24,
                                   rtol=1e-12,
                                   atol=1e-15,
                                   timespan=[0, 1e9],
                                   mxstep=200000)
        if not len(metals) == 0:
            theta0 = theta

        r = mod.get_rates(theta)
        theta_and_empty = list(theta) + [1 - sum(theta)]
        thetao.append(theta_and_empty)
        Ro.append(r[0])

        try:
            theta = mod.find_steady_state_roots(theta0=theta)
            theta_and_empty = list(theta) + [1 - sum(theta)]
            theta_and_empty = [mp.nstr(t, 25) for t in theta_and_empty]
            if (np.array(theta) > 1).any() or (np.array(theta) < 0.).any():
                theta_and_empty = [np.nan] * 5
        except ValueError:
            # In case there is a tolerance issue
            theta_and_empty = [np.nan] * 5

        thetass.append(theta_and_empty)

        r = mod.get_rates(theta)

        Rss.append(r[0])

    store_variables(prefix,
                    ENs,
                    Rs,
                    Ro,
                    Rss,
                    thetao,
                    thetass,
                    T,
                    p0,
                    N2_frac,
                    X,
                    site,
                    Evib,
                    metals=metals)

    if not len(metals) and plot:
        plot_rates(ENs, Rs, Ro, Rss, prefix)
        plot_coverages(ENs, thetao, thetass, prefix)