Exemple #1
0
def rand_next_time(t0, λfunc, λfunc_integral=None, λfunc_integral_inverse=None):
    a = -math.log(random.random())

    if λfunc_integral_inverse is None:
        if λfunc_integral is None:
            def L(t):
                y, abserr = integrate.quad(λfunc, t0, t)
                return y - a
        else:
            t0_integral = λfunc_integral(t0)

            def L(t):
                y = λfunc_integral(t) - t0_integral
                return y - a

        tol = 1e-4
        try:
            x = newtons_method(t0, L, λfunc, tol, 20)

        except OverflowError: # can happen when we use the interpolation thing
            inv_L = inversefunc(L, y_values=[0], accuracy=5)
            x = inv_L[0]
        else:
            if abs(L(x)) > tol:
                inv_L = inversefunc(L, y_values=[0], accuracy=5)
                x = inv_L[0]
        return x
    else:
        assert λfunc_integral is not None
        return λfunc_integral_inverse(λfunc_integral(t0) + a)
Exemple #2
0
def T0_bridge(l=2.0, g=9.8, rho=1.0, R=1.0, a=1.0, **kwargs):
    integrand = lambda x, T0: np.sqrt(1.0 + inversefunc(B,
                                                        args=(T0, g, R, rho),
                                                        y_values=x,
                                                        domain=[0, 5],
                                                        image=[0, 10],
                                                        open_domain=False)**2)
    l_fn = lambda T0: integrate.quad(integrand, 0, a, args=(T0, ))[0]
    result = inversefunc(l_fn,
                         y_values=l,
                         domain=[0.0, 10**3],
                         image=[0, 10**3],
                         open_domain=True)
    print('T0 bridge: ' + str(result))
    return result
def main():
    parser = argparse.ArgumentParser(
        description='Percolation for a random cube')
    parser.add_argument('n', type=int, help='number of rows')
    parser.add_argument(
        'p',
        type=float,
        help='probability for the cell be True in the matrix cube')
    parser.add_argument('--estimate-threshold',
                        help='estimate the threshold of percolates',
                        action='store_true')
    parser.add_argument(
        '--nb-trials',
        type=int,
        help='number of times the experiment must be carried out')
    args = parser.parse_args()
    n = args.n
    p = args.p
    nb_trials = args.nb_trials

    matr = rand_bool_matrix_3d(n, n, n, p)
    # pprint(matr)
    f = flow_hash(matr)
    # pprint(f)
    # print(percolates(matr))
    # pprint(matr)
    # res = flow_hash(matr)
    # pprint(res)
    if nb_trials is None:
        nb_trials = 100

    def perc_func(p):
        success = experiment(n, p, nb_trials)
        return success / nb_trials

    NBINTERV = 11
    prob_of_success = [0] * NBINTERV
    probs = np.linspace(0, 1, NBINTERV)
    for i, p in enumerate(probs):
        success = experiment(n, p, nb_trials)
        prob_of_success[i] = success / nb_trials
        print(success, nb_trials, success / nb_trials)
    print(prob_of_success)
    fig, ax = plt.subplots()
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    plt.title('Probability of percolation nb_sites :' + str(n) + '³' +
              ' nb_trials: ' + str(nb_trials))
    plt.xlabel('site vacancy probability')
    plt.ylabel('percolation probability')
    success_color = {True: 'green', False: 'red'}
    colors = [success_color[p > 0.5] for p in prob_of_success]
    plt.scatter(probs, prob_of_success, color=colors)
    plt.show()
    if args.estimate_threshold:
        print('Estimating threshold value...')
        a = inversefunc(perc_func, y_values=0.5, domain=[0.3, 0.8])
        b = inverse(perc_func, 0.5, 0.3, 0.8)
        print('Threshold value using pynverse', a)
        print('Threshold value is', b)
Exemple #4
0
def prob(ball_r, balls_dist, angle_1, angle_2, cue_ball_angle, omega):

    min_in_angle = min(angle_1, angle_2)
    max_in_angle = max(angle_1, angle_2)

    def f(t):
        try:
            return asin(balls_dist * sin(t) /
                        (2 * ball_r)) - abs(t) + cue_ball_angle
        except:
            pass

    def pdf(x):
        var = 0.1  #* exp(-(balls_dist-ball_r*2))
        return pow(2 * pi * var, -0.5) * exp(-((x - omega)**2) / (2 * var))

    try:
        bound = asin(2 * ball_r / balls_dist)
    except:
        return 0

    f_image = [min_in_angle, max_in_angle]
    inv_f = inversefunc(f, domain=[-1 * bound, bound], image=f_image)

    return integrate.quad(pdf, inv_f(f_image[0]), inv_f(f_image[1]))[0]
Exemple #5
0
def test_inversefunc_vminclosedvmaxclosed():
    accuracy = 2
    cos = (lambda x: np.cos(x))
    invfunc = inversefunc(cos, domain=[0, np.pi])
    yval = [1, 0, -1]
    xvalexpected = [0., np.pi / 2, np.pi]
    assert_array_almost_equal(invfunc(yval), xvalexpected, accuracy)
Exemple #6
0
def test_inversefunc_with_y_values():
    accuracy = 2
    cube = (lambda x: x**3)
    yval = [-27, -8, -1, 0, 1, 8, 27]
    xvalexpected = [-3, -2, -1, 0, 1, 2, 3]
    xval = inversefunc(cube, y_values=yval)
    assert_array_almost_equal(xval, xvalexpected, accuracy)
Exemple #7
0
def test_inversefunc_vmaxclosed():
    accuracy = 2
    square = (lambda x: x**2)
    invfunc = inversefunc(square, domain=[None, 0])
    yval = [4, 16, 64]
    xvalexpected = [-2, -4, -8]
    assert_array_almost_equal(invfunc(yval), xvalexpected, accuracy)
Exemple #8
0
def test_inversefunc_vminclosed():
    accuracy = 2
    square = (lambda x: x**2)
    invfunc = inversefunc(square, domain=0)
    yval = [4, 16, 64]
    xvalexpected = [2, 4, 8]
    assert_array_almost_equal(invfunc(yval), xvalexpected, accuracy)
Exemple #9
0
class CPP_nBRW:
	# INPUT the number N
	def __init__(self, N):
		self.N = N
		self.currPos = [0]*N
		self.history = [self.currPos[:]]

	# INPUT nGen, the number of generations to run the N-BRW for. 
	# OUTPUT stores the N-BRW in the array self.history
	def run(self, nGen):
		for gen in range(nGen):
			print('Currently in generation {0}'.format(gen))
			self.currPos = self.branch_and_select()
			self.history += [self.currPos]

	# The rest of the class is made up of internal methods 
	# required to do the calculations

	
	def unnormalized_cdf(self, x, lower_bound):
		return self.primitive(x) - self.primitive(lower_bound)

	def primitive(self, x):
		if x == np.inf:
			return np.real(self.N * (np.exp(1j) + np.exp(-1j)) / 2)
		return np.real(sum([1j * np.exp(-1j) * (np.exp(2j)*expi(-(x-x0)-1j) 
					- expi(1j - (x-x0))) / (2*np.pi) for x0 in self.currPos]))

	def inverse_sample(self, lower_bound, upper_bound, normalizing_constant):
		cdf = lambda x: self.unnormalized_cdf(x, lower_bound) 
						/ normalizing_constant
		return inversefunc(cdf, stat.uniform.rvs(), 
							domain=[lower_bound, 
									min(upper_bound, lower_bound + 20)], 
							image=[0,1])
Exemple #10
0
def test_inversefunc_with_multargs():
    accuracy = 2
    func = (lambda x, y, z: x**3 + y + z)
    invfunc = inversefunc(func, args=(1, 2))
    yval = [-24, -5, 2, 3, 4, 11, 30]
    xvalexpected = [-3, -2, -1, 0, 1, 2, 3]
    assert_array_almost_equal(invfunc(yval), xvalexpected, accuracy)
Exemple #11
0
def invertedFit(params, tval, vval):
    """
    Inverts the fit (from given parameters), and returns the times used for
    the fit.
    """
    k = params[0]
    phi = params[1]  #phase
    A = params[2]  #amplitude
    T = 1 / (k)  #period
    #print(T,v_off,phi,k,A)

    sine = (lambda t: A * np.sin(2 * np.pi * k * t - phi)
            )  #define sin as a function of time.

    t_list = np.linspace(tval - T / 2, tval + T / 2, 100)
    sine_vals = sine(t_list)
    a_max = np.argmax(sine_vals)
    a_min = np.argmin(sine_vals)

    t_max = t_list[a_max]
    t_min = t_list[a_min]

    if (t_min > t_max):
        minval = t_max
        t_max = t_min
        t_min = minval

    try:
        t_close = inversefunc(sine, y_values=vval, domain=[t_min, t_max])
    except ValueError:
        print(t_max, t_min, vval, tval)
        print(params)

    return (t_close - tval)  #used to be t_close-tval
Exemple #12
0
def test_inversefunc_infinite():
    accuracy = 2
    cube = (lambda x: x**3)
    invfunc = inversefunc(cube)
    yval = [-27, -8, -1, 0, 1, 8, 27]
    xvalexpected = [-3, -2, -1, 0, 1, 2, 3]
    assert_array_almost_equal(invfunc(yval), xvalexpected, accuracy)
Exemple #13
0
def test_inversefunc_vminclosedvmaxopen():
    accuracy = 2
    cos = (lambda x: np.cos(x))
    invfunc = inversefunc(cos, domain=[0, np.pi], open_domain=[False, True])
    yval = [1 / np.sqrt(2), 0, -1 / np.sqrt(2)]
    xvalexpected = [np.pi / 4, np.pi / 2, 3 * np.pi / 4]
    assert_array_almost_equal(invfunc(yval), xvalexpected, accuracy)
Exemple #14
0
def delay_mean_empiric(lmr, overhead=1.1, d_tot=None, n=100):
    '''return the simulated mean delay of the map phase, i.e., the average
    delay until d droplets have been computed and wait_for servers
    have become available. assumes that droplets are computed in
    optimal order.

    '''
    if d_tot is None:
        d_tot = lmr['nrows'] * lmr['nvectors'] / lmr['droplet_size'] * overhead
    result = 0.0
    max_drops = lmr['droplets_per_server'] * lmr['nvectors']
    if max_drops * lmr['nservers'] < d_tot:
        return math.inf
    dropletc = lmr['dropletc']  # cache this value
    a = np.zeros(lmr['nservers'])
    for _ in range(n):
        delays(0, lmr, out=a)
        t_servers = a[lmr['wait_for'] - 1]  # a is sorted
        f = lambda x: np.floor(
            np.minimum(np.maximum((x - a) / dropletc, 0), max_drops)).sum()
        t_droplets = inversefunc(f, y_values=d_tot)[0]
        result += max(t_servers, t_droplets)

    # average and add decoding delay
    result /= n
    result += lmr['decodingc']
    return result
def ej8():
	f, fda, e, v = exp_dist(0.01386)
	d = math.sqrt(v)
	print("a) P(X < 100) =","%.3f"%fda(100))
	print("   P(X < 100) =","%.3f"%fda(200))
	print("   P(100 < X < 200) =","%.3f"%(fda(200)-fda(100)))
	print("b) P(e+d*2 < X) =", "%.3f"%(1 - fda(e+d*2)))
	print("c) mediana(X) =", "%.3f"%(inversefunc(fda,0.5)))
def pressure_old(mu,T):
    '''Pressure at SVP in Pa as a function of chemical potential (in K) and
    temperature.
    '''
    P0 = pressure_SVP(T)
    Pmu = pynverse.inversefunc(chemical_potential, args=(T),domain=[1E-200,None], 
                               accuracy=8)
    return Pmu(mu)
Exemple #17
0
def get_time_at_height_boost(y, theta, boost_amount):
    f = lambda x: get_height_at_time_boost(x, theta, boost_amount)
    f_max = min(scipy.optimize.fmin(lambda x: -f(x), 0, disp=False)[0], 1.4)
    f_inverse = inversefunc(f, domain=[0, f_max])
    if y < f(f_max):
        return f_inverse(y)
    else:
        return f_max
Exemple #18
0
def get_time_at_height(y):
    f = lambda x: get_height_at_time(x)
    f_max = min(scipy.optimize.fmin(lambda x: -f(x), 0, disp=False), 1.4)
    f_inverse = inversefunc(f, domain=[0, f_max])
    if y < f_max:
        return f_inverse(y)
    else:
        return f_max
def f_dp(x, alpha_aa, alpha_c, a_aa0, b_aa0, a_c0, b_c0, a_aa1, b_aa1, a_c1,
         b_c1):
    f_c = (lambda x_c: alpha_c * beta.cdf(x_c, a_c1, b_c1, 0, 1) +
           (1 - alpha_c) * beta.cdf(x_c, a_c0, b_c0, 0, 1))
    inv_f_c = inversefunc(f_c, domain=[0, 1], open_domain=[False, False])
    return float(
        inv_f_c(alpha_aa * beta.cdf(x, a_aa1, b_aa1) +
                (1 - alpha_aa) * beta.cdf(x, a_aa0, b_aa0)))
Exemple #20
0
 def inverse_sample(self, lower_bound, upper_bound, normalizing_constant):
     cdf = lambda x: self.unnormalized_cdf(x, lower_bound
                                           ) / normalizing_constant
     return inversefunc(
         cdf,
         stat.uniform.rvs(),
         domain=[lower_bound,
                 min(upper_bound, lower_bound + 20)],
         image=[0, 1])
def int_conf(x, d, n, conf):
    a = (1 + conf) / 2
    invz = inversefunc(auxz)
    z = invz(a)
    izq = "%.3f" % (x - z * d / math.sqrt(n))
    der = "%.3f" % (x + z * d / math.sqrt(n))
    ic = (float(izq), float(der))
    lon = ic[1] - ic[0]
    return ic, lon
Exemple #22
0
    def ppf(self, x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
        """The ppf (percent point function - the inverse of the cdf) evaluated at x.
        Since this is not analytically available, compute it with an inversefunc module.

        :param x: x values, where the ppf should be evaluated.

        :return: Corresponding value of ppf at x.
        """
        return inversefunc(self.cdf)(x)
Exemple #23
0
def T0_catenary(l=2.0, g=9.8, rho=1.0, a=1.0, **kwargs):
    l_fn = lambda T0: (T0 / (g * rho)) * np.sinh(((g * rho) / T0) * a)
    result = inversefunc(l_fn,
                         y_values=l,
                         domain=[0, 10**9],
                         image=[0, 10**9],
                         open_domain=True)
    print(result)
    return result
Exemple #24
0
    def to_points(self, num):
        def arclength(s):
            d_arc = lambda x: np.sqrt(1 + self.poly.grad_at(x)**2)
            return quad(d_arc, 0, s)[0]

        s1 = inversefunc(arclength, self.length).tolist()
        points = [(s, self.poly.eval_at(s), arclength(s))
                  for s in np.linspace(0, s1, num=num)]
        return self.rel_to_abs(points)
Exemple #25
0
def test_inversefunc_vminopenvmaxopen():
    accuracy = 2
    tan = (lambda x: np.tan(x))
    invfunc = inversefunc(tan,
                          domain=[-np.pi / 2, np.pi / 2],
                          open_domain=True)
    yval = [1, 0, -1]
    xvalexpected = [np.pi / 4, 0., -np.pi / 4]
    assert_array_almost_equal(invfunc(yval), xvalexpected, accuracy)
Exemple #26
0
def fp_lmfit(params, x, data, dt, I0, I_max, iter_step):
    # Gathering parameters
    k = params["k"]
    I_star = params["I_star"]

    #print("k={}, I_star={}".format(k, I_star))

    # Declaring the engine
    engine_nk = nk.cn_nekhoroshev(I_max, 1.0, I_star, 1 / (k * 2), 0, I0, dt)
    multiplier = 0.01 / integrate.simps(engine_nk.diffusion,
                                        np.linspace(0, I_max, len(I0)))

    while True:
        engine_nk = nk.cn_nekhoroshev(I_max, multiplier, I_star, 1 / (k * 2),
                                      0, I0, dt)
        # Allocating lists and counter
        t = []
        survival = []
        # Starting while loop for fitting procedure
        step = 0
        reached = True
        while (1.0 - engine_nk.get_particle_loss() >= data[-1]):
            # Append the data
            t.append(step * iter_step * dt * multiplier)
            survival.append(1.0 - engine_nk.get_particle_loss())
            # Iterate
            engine_nk.iterate(iter_step)
            # Evolve counter
            step += 1
            if step == 10000:
                #print("End not reached!")
                reached = False
                break
        # Append one last time
        t.append(step * iter_step * dt * multiplier)
        survival.append(1.0 - engine_nk.get_particle_loss())
        if len(t) > 10:
            break
        else:
            #print("decrease multiplier")
            multiplier /= 10

    # Post processing
    if reached:
        f = interp1d(t, survival, kind="cubic")
        inv_f = inversefunc(f,
                            domain=(t[0], t[-1]),
                            image=(survival[-1], survival[0]))
        point_t = inv_f(data[-1])
        point_s = inv_f(data[0])
        points_t = np.linspace(point_s, point_t, len(x))
        values_f = f(points_t)
    else:
        f = interp1d(t, survival, kind="cubic")
        points_t = np.linspace(0, t[-1], len(x))
        values_f = f(points_t) * 10
    return values_f - data
Exemple #27
0
def test_inversefunc_vmaxopen():
    accuracy = 2
    log = (lambda x: np.log10(-x))
    invfunc = inversefunc(log,
                          domain=[None, 0],
                          open_domain=True,
                          image=[-np.inf, None])
    yval = [-2., -3.]
    xvalexpected = [-0.01, -0.001]
    assert_array_almost_equal(invfunc(yval), xvalexpected, accuracy)
Exemple #28
0
def pressure_fit(μ_,T):
    '''Pressure at SVP in Pa as a function of chemical potential (in K) and
    temperature.
    '''

    import pynverse
    P0 = pressure_SVP(T)
    Pμ = pynverse.inversefunc(chemical_potential, args=(T),domain=[1E-200,None], 
                               accuracy=8)
    return Pμ(μ_)
Exemple #29
0
 def inv(value):
     if value >= Limit(bound):
         function = (lambda m: Limit(m))
         z = inversefunc(function, y_values=value)
     else:
         z = 0
         L = value
         while L - Limit(z) >= 10**(-4):
             z = z + 0.001
     return z
Exemple #30
0
def simple_resonant_frequency(L, C, Ic, beta_RF, fDC):
    # first, need to get dDC from fDC.
    fDC_func = (lambda x: (x + beta_RF * math.sin(x)) / (2 * math.pi))
    fDC_inv = inversefunc(fDC_func)  # function that goes from fDC to dDC
    dDC = fDC_inv(fDC)  # use that inverted function to get dDC value
    # dDC = fDC*2*math.pi
    Ljj = (2.068 * 1.e-15) / (2 * math.pi * Ic * math.cos(dDC))
    Ltot = (1 / L + 1 / Ljj)**(-1)  # parallel inductances
    resonant_frequency = (1 / (2 * math.pi)) * (Ltot * C)**(-.5)
    return np.real(resonant_frequency)
Exemple #31
0
 def transform_non_affine(self, a):
     
     inverseCumLogLaplaceVectorized = np.vectorize(inversefunc(cumLogLaplaceMaker(self.mu, \
         self.sigma), domain=[1e-5, float("Inf")]))
     
     return inverseCumLogLaplaceVectorized(a)