def testScaleInfo01(self): dim = 4 domain = [[0,1],[0,1]] scl = ScaleInfo(dim, domain) a = (mpmath.mpf(0), mpmath.mpf(1)) self.assertTrue(scl.domain == [a,a]) self.assertTrue( numpy.all(scl.x[0] == mpmath.linspace(0,1, dim, endpoint=False)) ) self.assertTrue( numpy.all(scl.x[1] == mpmath.linspace(0,1, dim, endpoint=False)) ) self.assertTrue(scl.h == mpmath.mpf("0.25"))
def make_bessel_j1_vals(): from mpmath import besselj x = linspace(-5, 15, 21) j1 = [besselj(1, val) for val in x] return make_special_vals('bessel_j1_vals', ('x', x), ('j1', j1))
def make_bessel_j0_vals(): from mpmath import besselj x = linspace(-5, 15, 21) j0 = [besselj(0, val) for val in x] return make_special_vals('bessel_j0_vals', ('x', x), ('j0', j0))
def nodes(n): left = mp.mpf(0) right = mp.mpf(n+(n-1)*sqrt(n)*1.01) i = 2 factor = 2 while True: l = [ (x,mp.laguerre(n,0,x)) for x in mp.linspace(left,right,n*factor**i)] intervals = [] for j in range(len(l)-1): prod = l[j][1]*l[j+1][1] if prod < 0: intervals.append([l[j][0], l[j+1][0]]) if len(intervals) == n: break i += 1 roots = [] f = lambda x: mp.laguerre(n,0,x) for ab in intervals: a,b = ab try: z = mp.findroot(f, (a, b), tol=1e-50, solver='bisect') except: z = bisect(f, a, b, tol=1e-50) roots.append( z ) return roots
def make_lgamma_vals(): from mpmath import loggamma x = [mpf('0.01')] + linspace(mpf('0.1'), 10, 100) + [mpf(20), mpf(30)] lga = [loggamma(val) for val in x] return make_special_vals('lgamma_vals', ('x', x), ('lga', lga))
def make_gamma_vals(): from mpmath import gamma x = [-mpf('0.5'), -mpf('0.01'), mpf('0.01')] + linspace(mpf('0.1'), 10, 100) + [mpf(20), mpf(30)] ga = [gamma(val) for val in x] return make_special_vals('gamma_vals', ('x', x), ('ga', ga))
def __get_medial_axis_polynomial_function_symbolic(self): if self.polynomial_function_symbolic is not None: return self.polynomial_function_symbolic curve_path = self.__medial_axis_computer.get_medial_axis_img() if not Curve.is_valid_curve(curve_path): curve_path = self.__medial_axis_computer.get_bin_inv_img_path() self.medial_axis_curve = Curve(curve_path, grade=CURVE_POLYNOMIAL_FUNCTION_GRADE) self.polynomial_function_symbolic, self.symbol = self.medial_axis_curve.compute_polynomial_function_symbolic( ) potential_x_points = [ round(i) for i in linspace(0, self.orig_threshold_img.shape[0] - 1, self.orig_threshold_img.shape[0]) ] for potential_x_point in potential_x_points: potential_y_point = int( round( self.medial_axis_curve.polynomial_function( potential_x_point))) if potential_y_point < self.orig_threshold_img.shape[1]: if self.orig_threshold_img[potential_x_point][ potential_y_point] == 255: self.function_x_points.append(potential_x_point) self.function_y_points.append(potential_y_point) return self.polynomial_function_symbolic
def nodes(n): left = mp.mpf(0) right = mp.mpf(n + (n - 1) * sqrt(n) * 1.01) i = 2 factor = 2 while True: l = [(x, mp.laguerre(n, 0, x)) for x in mp.linspace(left, right, n * factor**i)] intervals = [] for j in range(len(l) - 1): prod = l[j][1] * l[j + 1][1] if prod < 0: intervals.append([l[j][0], l[j + 1][0]]) if len(intervals) == n: break i += 1 roots = [] f = lambda x: mp.laguerre(n, 0, x) for ab in intervals: a, b = ab try: z = mp.findroot(f, (a, b), tol=1e-50, solver='bisect') except: z = bisect(f, a, b, tol=1e-50) roots.append(z) return roots
def PlotVariance(): plt.figure(figsize=(13.0, 10.0)) plt.suptitle("Variances d'erreur sur le filtre") t = linspace(0, 1, ekf_variances.length()) graph_x = plt.subplot(3, 1, 1) sigmaX = ekf_variances.p11 troisSigma = 3 * sigmaX graph_x.plot(t, sigmaX) graph_x.plot(t, troisSigma, 'g') graph_x.plot(t, -troisSigma, 'g') graph_y = plt.subplot(3, 2, 1) sigmaY = ekf_variances.p22 troisSigma = 3 * sigmaY graph_y.plot(t, sigmaY) graph_y.plot(t, troisSigma, 'g') graph_y.plot(t, -troisSigma, 'g') graph_theta = plt.subplot(3, 3, 1) sigmaTh = ekf_variances.p33 troisSigma = 3 * sigmaTh graph_theta.plot(t, sigmaTh) graph_theta.plot(t, troisSigma, 'g') graph_theta.plot(t, -troisSigma, 'g')
def forbidden_index_search(self, x, q): with workdps(self.dps): x_big = [mpf(el) * self.gamma**self.k for el in x] eps = mpf('1') / (self.gamma - 1) intervals = mp.linspace(mpf('0'), mpf('1'), self.gamma) length = mpf('1.0') * (self.gamma - 2) / (self.gamma - 1) x_big_frac = [mp.frac(el) for el in x_big] ineq = [mp.frac(el + q*eps) <= length for el in x_big_frac] # Determine i-s ord_val = eps * q * self.gamma**self.k mod_val = ord_val - length indices = [int(mp.floor(el + ord_val)) if ineq[i] else int(mp.floor(el + mod_val)) for i, el in enumerate(x_big)] multipliers = [1]*len(x_big) for i in xrange(len(x_big)): if not ineq[i]: indices[i] = [indices[i], indices[i] + 1] #multipliers[i] = [mpf('0.5'), mpf('0.5')] multipliers[i] = [(indices[i][0] + eps - (x_big[i] + mod_val))/eps, (x_big[i] + mod_val - indices[i][0])/eps] # Now we have indices, where indices[i] may be number, or a pair of numbers (if x[i] lay between intervals) return indices, multipliers
def make_bessel_y1_vals(): from mpmath import bessely x = [mpf('0.1')] + linspace(1, 15, 15) y1 = [bessely(1, val) for val in x] return make_special_vals('bessel_y1_vals', ('x', x), ('y1', y1))
def linspace(start, stop, num=50): """Linearly spaced points. Points are computed with :func:`mpmath.linspace` but the output (a ``list``) is converted back to a :class:`numpy.ndarray`. """ return np.array(mpmath.linspace(start, stop, num))
def Lm_func(mv,Rv,alphav): ''' eqn. 12.106 The 'gauss-legendre' quadrature method is used here as it provides more accurate output, even with increasing m&n indices. ''' return mpmath.quad(lambda thetav: Lm_term(mv,Rv,alphav, thetav), mpmath.linspace(0,alphav,2), method='gauss-legendre')
def a_test_mp(self, a0, a1, b1, b0): r = self.example.f__r w1_knots = mpmath.linspace(b1, b0, r + 1) w1_values = [self.example.fun_mp(x) for x in w1_knots] w1_coeffs = divided_diff_coeffs_all_mpmath(w1_knots, w1_values) w2_knots = mpmath.linspace(a0, a1, r + 1) w2_values = [self.example.fun_mp(x) for x in w2_knots] w2_coeffs = divided_diff_coeffs_all_mpmath(w2_knots, w2_values) z_arr = mpmath.linspace(a1, b1, r + 1) w1_values_new = newton_poly_mpmath(w1_coeffs, w1_knots, z_arr) w2_values_new = newton_poly_mpmath(w2_coeffs, w2_knots, z_arr) test_values = [mpmath.fabs(w1_values_new[j] - w2_values_new[j]) for j in range(r + 1)] return max(test_values)
def questao2a(): data_lambda = linspace(0.01, 2.99, 100) data_x = [ponto_fixo(lambda x: iter_proc(x, l), 0.1) for l in data_lambda] my_plot(data_lambda, data_x, xlabel='Lambda', ylabel='Ponto fixo x*', title='Lambda versus Ponto fixo', filename='questao2a.png')
def linspace(a, b, num): """ This function calls ``numpy.linspace(…)`` or ``mpmath.linspace(…)``, because ``numpy.linspace`` function does not work with mpmath. """ if (needsMpmathAtN(1)): import mpmath return mpmath.linspace(a, b, num) else: import numpy return numpy.linspace(a, b, num=num)
def make_legendre_p_vals(): from mpmath import legendre l = range(5) x = linspace('-0.99', '0.99', 67) l, x = zip(*outer(l, x)) p = [legendre(*vals) for vals in zip(l, x)] return make_special_vals('legendre_p_vals', ('l', l), ('x', x), ('p', p))
def make_legendre_p_vals(): from mpmath import legendre l = list(range(5)) x = linspace('-0.99', '0.99', 67) l, x = zip(*outer(l, x)) p = [legendre(*vals) for vals in zip(l, x)] return make_special_vals('legendre_p_vals', ('l', l), ('x', x), ('p', p))
def make_assoc_legendre_p_vals(): from mpmath import legenp l = range(5) m = range(-4, 5) x = linspace('-0.99', '0.99', 67) l, m, x = zip(*(vals for vals in outer(l, m, x) if abs(vals[1]) <= vals[0])) p = [legenp(*vals, zeroprec = 1024) for vals in zip(l, m, x)] return make_special_vals('assoc_legendre_p_vals', ('l', l), ('m', m), ('x', x), ('p', p))
def make_assoc_legendre_p_vals(): from mpmath import legenp l = list(range(5)) m = list(range(-4, 5)) x = linspace('-0.99', '0.99', 67) l, m, x = zip(*(vals for vals in outer(l, m, x) if abs(vals[1]) <= vals[0])) p = [legenp(*vals, zeroprec = 1024) for vals in zip(l, m, x)] return make_special_vals('assoc_legendre_p_vals', ('l', l), ('m', m), ('x', x), ('p', p))
def plotArea(base, humerus, radius): angleMin = mpf(minAngle * mpmath.pi / 180) angleMax = mpf(maxAngle * mpmath.pi / 180) anglesL = mpmath.linspace(angleMin, angleMax, nPoints) anglesR = mpmath.linspace(angleMin, angleMax, nPoints) plt.style.use('seaborn-whitegrid') fig, ax = plt.subplots() title = 'base = ' + str(base) + ' humerous = ' + str( humerus) + ' radius = ' + str(radius) fig.suptitle(title) plt.grid(True) for angleL in anglesL: for angleR in anglesR: if forward(base, humerus, radius, angleL, angleR): [x, y] = forward(base, humerus, radius, angleL, angleR) if x >= base / 2: ax.plot(x, y, 'o', color='blue') ax.plot(base - x, y, 'o', color='blue')
def brot_gen_parallel(re_lim, im_lim, depth): re_span = mpmath.linspace(re_lim[0], re_lim[1], res[0]) im_span = mpmath.linspace(im_lim[0], im_lim[1], res[1]) start = time.time() split_re_span = np.array_split(re_span, cpuNum) packages = [(sec, im_span) for sec in split_re_span] print("Generating set between", re_lim, "and", im_lim, "at depth", depth, "with", cpuNum, "processes...") pool = mp.Pool(cpuNum) results = pool.starmap(brot_gen, [(package, depth) for package in packages]) pool.close() mset = np.concatenate(list(results), axis=1) print("Set generated in", time.time() - start) return mset
def make_airy_vals(): from mpmath import airyai, airybi x = linspace(-5, 15, 21) ai = [airyai(val) for val in x] aip = [airyai(val, 1) for val in x] bi = [airybi(val) for val in x] bip = [airybi(val, 1) for val in x] aibi = list(zip(list(zip(ai, aip)), list(zip(bi, bip)))) return make_special_vals('airy_vals', ('x', x), ('aibi', aibi))
def make_airy_vals(): from mpmath import airyai, airybi x = linspace(-5, 15, 21) ai = [airyai(val) for val in x] aip = [airyai(val, 1) for val in x] bi = [airybi(val) for val in x] bip = [airybi(val, 1) for val in x] aibi = zip(zip(ai, aip), zip(bi, bip)) return make_special_vals('airy_vals', ('x', x), ('aibi', aibi))
def main(): # Initialise initial conditions mpm.dps = 32 # Quadruple precision calculations #T = 2. * mpm.mpf(1.657935803684451) #x0 = mpm.matrix([1.006057199440406, 0.0, 0.0, 0.022036094262319]) #x0 = mpm.matrix([1.009433860747752, 0.0, 0.0, 0.003760276142823]) x0 = mpm.matrix([ 1.0060556387918027, 2.4281528205782993e-06, -8.1318569756237198e-06, 0.022040604156795093 ]) # Velocities have been inverted (+ -> -) to spoof reverse time # T = mpm.mpf(2 * 3.061660616555952) x_des = mpm.matrix([ 1.0039053449563018, 0.0024706864707973696, -0.012281740632575283, 0.024133313701580495 ]) # Call the Taylor integrator f = mpm.odefun(PCR3BP, 0.0, x0, tol=1e-30, degree=100, verbose=True) #for i in range(4): # print(f(T)[i] - f(0.0)[i]) print(mpm.pi) min_dist = 10. with open('output.dat', 'w+') as fiyul: for time in mpm.linspace(0., 2 * mpm.pi, 1000): temp = f(time) distance = mpm.sqrt((temp[0] - x_des[0])**mpm.mpf(2.0) + (temp[1] - x_des[1])**mpm.mpf(2.0)) print("Distance between desired point: %s" % (distance)) if distance < min_dist: min_dist = distance fiyul.write("%s, %s, %s, %s\n" % (temp[0], temp[1], temp[2], temp[3])) print("Minimum distance was %s" % min_dist) return None
def questao10(): print '%3s %20s %20s %20s' % ('n', 'Ti', 't0', 't*') data_Ti = linspace(0.1, 49.9, 10) data_y = [] for Ti in data_Ti: t0 = chute_temp(Ti=Ti) valor, n_iter = newton(lambda t: temp(t, Ti=Ti), lambda t: temp_t(t, Ti=Ti), x0=t0, max_iter=50, erro=0.000001, valor=50.0) data_y.append(valor) print '%3s %20f %20f %20f' % (n_iter, Ti, t0, valor) my_plot(data_Ti, data_y, u'Tempo necessário versus Temperatura inicial', u'Ti', u'Tempo necessário (t*)', filename='questao10.png')
def questao9b(): print '%3s %20s %20s %20s' % ('n', 'a', 't0', 't*') data_a = linspace(1, 10, 10) data_y = [] for a in data_a: t0 = chute_temp(A=a) valor, n_iter = newton(lambda t: temp(t, A=a), lambda t: temp_t(t, A=a), x0=t0, max_iter=50, erro=0.000001, valor=50.0) data_y.append(valor) print '%3s %20f %20f %20f' % (n_iter, a, t0, valor) my_plot(data_a, data_y, u'Tempo necessário versus parâmetro Alpha', u'Alpha', u'Tempo necessário (t*)', filename='questao9b.png')
def questao9a(): print '%3s %20s %20s %20s' % ('n', 'q', 't0', 't*') data_q = linspace(1, 10, 10) data_y = [] for q in data_q: t0 = chute_temp(Q=q) valor, n_iter = newton(lambda t: temp(t, Q=q), lambda t: temp_t(t, Q=q), x0=t0, max_iter=50, erro=0.000001, valor=50.0) data_y.append(valor) print '%3s %20f %20f %20f' % (n_iter, q, t0, valor) my_plot(data_q, data_y, u'Tempo necessário versus parâmetro Q', u'Q', u't*', filename='questao9a.png')
def questao8(): print '%3s %20s %20s %20s' % ('n', 'x', 't0', 't*') data_x = linspace(1, 5, 10) data_y = [] for x in data_x: t0 = chute_temp(x=x) valor, n_iter = newton(lambda t: temp(t, x=x), lambda t: temp_t(t, x=x), x0=t0, max_iter=50000, erro=0.000001, valor=50.0) data_y.append(valor) print '%3s %20f %20f %20f' % (n_iter, x, t0, valor) my_plot(data_x, data_y, u'Posição versus Tempo necessário', u'x', u't*', filename='questao8.png')
def test_mpArray_index(self): n = random.randint(1,5000) x = mpmath.linspace(0,1,n) arr = mpArray.mpArray(x) start = time.clock() index1 = [xx < 0.5 for xx in x] t1 = time.clock() - start start = time.clock() index2 = arr < 0.5 t2 = time.clock() - start self.assertTrue(numpy.all(index1==index2)) if self.verbose: print("-----------------------") print("x < 0.5:","number of",n,"data serarch(list)", t1) print("x < 0.5:","number of",n,"data serarch(mpArray)", t1)
def scanRoots(self, numSteps): found = [] coords = mp.linspace(-1.0, 1.0, numSteps) for ndx in range(len(coords) - 1): ax = coords[ndx] bx = coords[ndx + 1] aerr = self.evalEstimate(ax) - self.evalFunc(ax) berr = self.evalEstimate(bx) - self.evalFunc(bx) #print(f'bucket: {ax} <{aerr}>') #print(f' to: {bx} <{berr}>') if mp.sign(aerr) != mp.sign(berr): (rx, rerr) = self.findRoot(ax, bx, aerr, berr) #print(f' root in range: [{ax}, {bx}]: {rx} <{rerr}>') found.append((ax, bx, rx, rerr)) return found
def _icdf_mpmath(self, y, method='solver', N=10000, output='float', **kwargs): if output == 'float': return np.float64( self._icdf_mpmath(y, output='mpf', method=method, N=N, **kwargs)) if mp.almosteq(y, 0, 1e-8): a_min = np.min(self.a) if isinstance(a_min, np.int32): a_min = int(a_min) return mp.mpf(a_min) elif mp.almosteq(y, 1, 1e-8): a_max = np.max(self.a) if isinstance(a_max, np.int32): a_max = int(a_max) return mp.mpf(a_max) elif y < 0 or y > 1: return mp.nan if method == 'solver': f = lambda t: y - 1 + self.sf(t) x0 = (np.min(self.a), np.max(self.a)) kwargs.setdefault('solver', 'bisect') return mp.findroot(f, x0, **kwargs) elif method == 'interpolation': if self._icdf_grid_x is None or len(self._icdf_grid_x) != N: self._icdf_grid_y = mp.linspace(min(self.a), max(self.a), N) self._icdf_grid_x = self.cdf(self._icdf_grid_y) self._icdf_interpolator = interp1d_mpmath(self._icdf_grid_x, self._icdf_grid_y, assume_sorted=True, copy=False, fill_value=mp.nan) return self._icdf_interpolator(y).item() else: raise Exception('Invalid method')
def index_search(self, x): with workdps(self.dps): def q_estimate_from_many(ns): qs_mask = np.ones(2 * self.N + 1, dtype=np.bool) for n in ns: if n != self.gamma - 2 and n >= self.gamma - 2 - 2*self.N: qs_mask[self.gamma - 2 - n] = False return qs_mask x_big = [mpf(el) * self.gamma**self.k for el in x] eps = mpf('1') / (self.gamma - 1) intervals = mp.linspace(mpf('0'), mpf('1'), self.gamma) x_big_frac = [mp.frac(el) for el in x_big] numbers_of_intervals = [mp.floor(el / eps) for el in x_big_frac] qs_mask = q_estimate_from_many(numbers_of_intervals) #print qs qs = np.array(range(2 * self.N + 1))[qs_mask] return [([mp.floor(el + eps * q * self.gamma**self.k) for el in x_big], q) for q in qs], qs_mask
def get_perpendiculars_array(self, intersection_points_nr): self.perpendiculars_array = list() self.tangents_array = list() deriv_function = np.polyder(self.medial_axis_curve.polynomial_function, 1) intersection_points_indexes = linspace(0, len(self.function_x_points) - 1, intersection_points_nr) intersection_points_list = list( zip(self.function_x_points, self.function_y_points)) for i in intersection_points_indexes: x0, y0 = intersection_points_list[round(i)] tg_m = deriv_function(x0) perpendicular = np.poly1d([tg_m, -tg_m * x0 + y0]) self.tangents_array.append(((x0, y0), perpendicular)) m = -1 / tg_m perpendicular = np.poly1d([m, -m * x0 + y0]) self.perpendiculars_array.append(((x0, y0), perpendicular)) return self.perpendiculars_array
def __init__(self, example: ExampleFunction, n_knots): self.example = example self.m = n_knots self.t = mpmath.linspace(self.example.f__a, self.example.f__b, self.m + 1) self.h = mpmath.mpmathify((self.example.f__b - self.example.f__a) / self.m) temp_d = mpmath.power(self.h, (self.example.f__r + self.example.f__rho)) # we use float64 precision limit, because final approximation is based on "standard" floats # and it will neglect more precise calculation self.d = temp_d if temp_d > 1e-14 else 1e-14 # following values could be local, but they are defined as class values # to make monitoring of algorithm easier self.step1_a = None self.step1_b = None self.is_interval_found = False self.b_set = None self.m_set = None self.fun_evaluations_counter = self.m + self.m * 2 * self.example.f__r
def make_sph_bessel_y0_vals(): x = linspace(1, 15, 15) y0 = [sphbessely(0, val) for val in x] return make_special_vals('sph_bessel_y0_vals', ('x', x), ('y0', y0))
def make_sph_bessel_j0_vals(): x = linspace(0, 15, 16) j0 = [sphbesselj(0, val) for val in x] return make_special_vals('sph_bessel_j0_vals', ('x', x), ('j0', j0))
""" Test program for Arbitrary Precision fft First test: compares FFT of sin(x) to exact FFT Second test: compares IFFT(FFT(sin(x))) to sin(x) Third test: compares IFFT(FFT(sin(x)) * 1j * fftfreq(N)) to cos(x) """ # set precsion to 100 digits mp.mp.dps = 100 # set size of transform to test N = 16 # construct x = mp.linspace( mp.mpf(0), mp.mpf(2.0)*mp.pi, 16, endpoint=False ) y = apfft.tools.sin( x ) # take the fft yh = apfft.fft(y) # check to make sure we got the correct transform true_transform = apfft.tools.czeros(N) true_transform[1] = -mp.mpc(0,N/2) true_transform[-1] = mp.mpc(0,N/2) diff = float(np.max(np.abs(yh-true_transform))) print 'Test 1:', '{:0.2e}'.format(diff) # now take the ifft ya = apfft.ifft(yh) # check vs the original solution diff = float(np.max(np.abs(ya - y)))
###################### ### SCRIPT ### ###################### #Parameters chosen for calculation dico0 = params.dom dico1 = params.dom1 # if dico1['qRe'] != 0 and condU =='Inviscid': # print("error Inviscid fluid incompatible with qRe != 0") print(dico1) lenvar = 1 Press = np.zeros((4,lenvar), dtype = np.complex) #Choose what parameter you want to vary for K,eta in enumerate(mp.linspace(-1,4,lenvar)): saveO = zeros(7,1) # save variable for speed, pressure and magnetic field (7 scalar) saveO_m = 0*C.i # magnetic field for the mantle part KXs = params.KXs KYs = params.KYs # Create the total topography and its normal vector topo_sum =0 for kxx,kyy in zip(KXs,KYs): topo_sum += e*(zeta*(exp(I*(kxx*x+kyy*y))))/len(KXs) delfsum = de(z-topo_sum) nsum = delfsum/sqrt((delfsum&C.i)**2+(delfsum&C.j)**2+(delfsum&C.k)**2) nsum = nsum.xreplace({**dico0,**dico1}).doit().xreplace({**dico0,**dico1}) # Calculus for each Fourier component of the topography for KX,KY in zip(KXs,KYs):
final_d_0 = (2 / kv**2 * Rv**2) * (brackets_term1 + brackets_term2 + brackets_term3) return final_d_0 if __name__ == '__main__': import numpy as np import matplotlib.pyplot as plt wavelength = (mpmath.mpf(330.0) / mpmath.mpf(50000)) ka = 10 k_v = 2 * mpmath.pi / wavelength a_v = ka / k_v alpha_v = mpmath.pi / 3 R_v = a_v / sin(alpha_v) #mpmath.mpf(0.01) angles = mpmath.linspace(0, mpmath.pi, 50) at_angles = mpmath.matrix(1, len(angles)) for i, angle in enumerate(angles): at_angles[i] = d_theta(k_v, R_v, alpha_v, angle) on_axis = d_zero(k_v, R_v, alpha_v, angle) rato = [20 * mpmath.log10(abs(each / on_axis)) for each in at_angles] plt.figure() a0 = plt.subplot(111, projection='polar') plt.plot(np.array(angles), rato) plt.ylim(-40, 10) plt.yticks(np.arange(-40, 20, 10)) plt.xticks(np.arange(0, 2 * np.pi, np.pi / 6)) import pandas as pd df = pd.read_csv('fig12-17.csv') plt.plot(np.radians(df['deg']),
# The value is admittedly a 'data-free' choice, and perhaps the actual effective # 'sphere' is really the inside of the mouth cavity!! paramv = {} paramv['R'] = R # This is admittedly a 'data-free' choice paramv['alpha'] = alpha paramv['k'] = k a_calc = paramv['R'] * mpmath.sin(paramv['alpha']) paramv[ 'a'] = a_calc # about 2 mm, which broadly matches the 5mm diameter in Jakobsen, Ratcliffee, Surlykke # %% # Let's now run the model, and plot the results. angles = mpmath.linspace(0, 2 * mpmath.pi, 100) An_51khz, beamshape_51khz = beamshapes.piston_in_sphere_directivity( angles, paramv) #%% # Let's also run the same for the next harmonic t 102 kHz - by doubling the `k` value. k_2ndharmonic = k * 2 paramv['k'] = k_2ndharmonic An_102khz, beamshape_102khz = beamshapes.piston_in_sphere_directivity( angles, paramv) #%% # Bat-inspired piston in a sphere beamshape # -----------------------------------------
fig, ax = plt.subplots() title = 'base = ' + str(base) + ' humerous = ' + str( humerus) + ' radius = ' + str(radius) fig.suptitle(title) plt.grid(True) for angleL in anglesL: for angleR in anglesR: if forward(base, humerus, radius, angleL, angleR): [x, y] = forward(base, humerus, radius, angleL, angleR) if x >= base / 2: ax.plot(x, y, 'o', color='blue') ax.plot(base - x, y, 'o', color='blue') baselineX = mpmath.linspace(0, 10, 100) baselineY = mpmath.zeros(100, 1) xMin = -10 xMax = 15 yMin = -5 yMax = 30 plotArea(10, 5, 10) ax.plot(baselineX, baselineY, color='black') plt.xlim([xMin, xMax]) plt.ylim([yMin, yMax]) plt.show() plotArea(10, 10, 5) ax.plot(baselineX, baselineY, color='black')
def linspace(cls, min, max, num, endpoint=False): return mpArray(mpmath.linspace(min, max, num, endpoint=endpoint))
from ToyModel import getCDFNIC, normalizePDF import mpmath as mp import pylab as p from ExponentsAlternative import getDistributionOfEks from nicePsevdoPDF import getPDFNice #dejanski program: start = -100 stop = 100 pdfSize = 10000 size = 30000 xOs, pdf = getDistributionOfEks(size, pdfSize, low=start, high=stop, printOn=1) cdf = getCDFNIC(pdf) pdf[0] = pdf[1] #pdf=normalizePDF(pdf) l = mp.linspace(start, stop, pdfSize) xOs = [mp.power(10, x) for x in l] pdf = fl.gaussian_filter(pdf, 10) save(xOs, pdf, "L with laplace") save(xOs, cdf, "L with laplace cdf") #cdf = getCDFNIC(pdf) pdfNice = getPDFNice(xOs, pdf) print("done") #save(xOs, pdfNice , "pdfNice 200") #plt.xscale('log') #plt.plot(xOs, pdfNice, 'blue', label = 'pdfNice' )
for j in range(interpolatingSize): newLF[i][j] = optimize.brentq( LF.rootfinding, 1e30, 1e50, args=(LF.luminosityParameterHa(grid[1][i]), mpgrid[j]) ) z = (z + 1) * (5007.0 / 6563.0) - 1 newLum = interpolate.interpn([grid[1], mpgrid], newLF, np.array([z[it], oldLF]).T, bounds_error=False, fill_value=0.0) for i in np.where(oldLF < -5)[0]: newLum[i] = optimize.brentq(LF.rootfinding, 1e30, 1e50, args=(LF.luminosityParameterHa(z[it][i]), oldLF[i])) z = (z + 1) * (6563.0 / 5007.0) - 1 Ha[it] = newLum / (4 * np.pi * (dl ** 2)) print "Calibrating OIIIb line" newLumO3b = [0.0 for x in range((it.shape[0]))] grid = np.array([[0.0 for i in range(interpolatingSize)] for i in range(2)]) mpgrid = mpmath.linspace(oldLF[oldLF < -2.7].max(), oldLF.max(), interpolatingSize) grid[1] = np.ogrid[0 : 6 : interpolatingSize * 1j] newLF = np.array([[0.0 for i in range(interpolatingSize)] for i in range(interpolatingSize)]) for i in range(interpolatingSize): for j in range(interpolatingSize): newLF[i][j] = optimize.brentq( LF.rootfinding, 1e30, 1e50, args=(LF.luminosityParameterO3b(grid[1][i]), mpgrid[j]) ) z = (z + 1) * (5007.0 / 6563.0) - 1 newLumO3b = interpolate.interpn( [grid[1], mpgrid], newLF, np.array([z[it], oldLF]).T, bounds_error=False, fill_value=0.0 ) for i in np.where(oldLF < -2.7)[0]: newLumO3b[i] = optimize.brentq(LF.rootfinding, 1e30, 1e50, args=(LF.luminosityParameterO3b(z[it][i]), oldLF[i])) z = (z + 1) * (6563.0 / 5007.0) - 1
import mpmath from mpArray import mpArray twopi = mpmath.mpf("2")*mpmath.pi class StandardMap(object): def __init__(self, k): if not isinstance(k,mpmath.mpf) and not isinstance(k,int): raise TypeError("parameter k is expected mpmath.mpf or int type") self.k = k def ifunc0(self, x): return mpArray([self.k*mpmath.cos( twopi * xx )/(twopi*twopi) for xx in x ]) def ifunc1(self, x): return mpArray([xx*xx/mpmath.mpf("2") for xx in x]) if __name__ == '__main__': mpmath.mp.dps=40 mpmath.mp.pretty=True map = StandardMap(2) x = mpmath.linspace(0, 1, 10) print(x) print(map.ifunc0(x)) print(map.ifunc1(x))