def Merge(self, prec=epsilon): """ Merge merges consecutive ramp(s) if they have the same acceleration """ if not self.isEmpty: if Abs((Abs(mp.log10(prec)) - (Abs(mp.floor(mp.log10(prec)))))) < Abs((Abs(mp.log10(prec)) - (Abs(mp.ceil(mp.log10(prec)))))): precexp = mp.floor(mp.log10(prec)) else: precexp = mp.ceil(mp.log10(prec)) aCur = self.ramps[0].a nmerged = 0 # the number of merged ramps for i in xrange(1, len(self.ramps)): j = i - nmerged if (Abs(self.ramps[j].a) > 1): if Abs((Abs(mp.log10(Abs(self.ramps[j].a))) - (Abs(mp.floor(mp.log10(Abs(self.ramps[j].a))))))) < Abs((Abs(mp.log10(Abs(self.ramps[j].a))) - (Abs(mp.ceil(mp.log10(Abs(self.ramps[j].a))))))): threshold = 10**(precexp + mp.floor(mp.log10(Abs(self.ramps[j].a))) + 1) else: threshold = 10**(precexp + mp.ceil(mp.log10(Abs(self.ramps[j].a))) + 1) else: threshold = 10**(precexp) if Abs(Sub(self.ramps[j].a, aCur)) < threshold: # merge ramps redundantRamp = self.ramps.pop(j) newDur = Add(self.ramps[j - 1].duration, redundantRamp.duration) self.ramps[j - 1].UpdateDuration(newDur) # merge switchpointsList self.switchpointsList.pop(j) nmerged += 1 else: aCur = self.ramps[j].a
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)
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
# parameters of the 'Zolotarev' polynomial n = 9 N = 2 * n + 1 # 'N' is the order of the polynomial # 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)
# Integration sol_BDF = solve_ivp( fun=system, t_span=t_span, y0=init_cond, method="BDF", dense_output=True, rtol=1e-6, atol=1e-8, first_step=(t_end - t_start) * 1e-5, args=params, ) t = np.logspace(start=-5, stop=np.log10(t_end), num=int(1e4)) y = sol_BDF.sol(t) # Save data in file data = np.stack((t, y[0], y[1], y[2], y[3], y[4]), axis=1) np.savetxt( join(dirname(abspath(__file__)), "plots/python.dat"), data, header="t \t i(t) \t a(t) \t m(t) \t z(t) \t s(t) \n", ) num = y[4][-1] ndigits = 3 - (int(mp.floor(mp.log10(abs(num)))) + 1 ) # Only works for numbers < 1. print("Stellar density after", t_end, "Gyr:", round(num, ndigits), "Mₒpc^(-2)")
if __name__ == '__main__': # parameters of the 'Zolotarev' polynomial n = 9; N = 2 * n + 1 # 'N' is the order of the polynomial # 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)
def tanh_sinh_lr(f_left, f_right, alpha, eps, max_steps=10): '''Integrate a function `f` between `a` and `b` with accuracy `eps`. The function `f` is given in terms of two functions * `f_left(s) = f(a + s)`, i.e., `f` linearly scaled such that `f_left(0) = a`, `f_left(b-a) = b`, * `f_right(s) = f(b - s)`, i.e., `f` linearly scaled such that `f_right(0) = b`, `f_left(b-a) = a`. Implemented are Bailey's enhancements plus a few more tricks. David H. Bailey, Karthik Jeyabalan, and Xiaoye S. Li, Error function quadrature, Experiment. Math., Volume 14, Issue 3 (2005), 317-329, <https://projecteuclid.org/euclid.em/1128371757>. David H. Bailey, Tanh-Sinh High-Precision Quadrature, 2006, <http://www.davidhbailey.com/dhbpapers/dhb-tanh-sinh.pdf>. ''' num_digits = int(-mp.log10(eps) + 1) mp.dps = num_digits alpha2 = alpha / mp.mpf(2) # What's a good initial step size `h`? # The larger `h` is chosen, the fewer points will be part of the # evaluation. However, we don't want to choose the step size too large # since that means less accuracy for the quadrature overall. The idea would # then be too choose `h` such that it is just large enough for the first # tanh-sinh-step to contain only one point, the midpoint. The expression # # j = mp.ln(-2/mp.pi * mp.lambertw(-tau/h/2, -1)) / h # # hence needs to just smaller than 1. (Ideally, one would actually like to # get `j` from the full tanh-sinh formula, but the above approximation is # good enough.) One gets # # 0 = pi/2 * exp(h) - h - ln(h) - ln(pi/tau) # # for which there is no analytic solution. One can, however, approximate # it. Since pi/2 * exp(h) >> h >> ln(h) (for `h` large enough), one can # either forget about both h and ln(h) to get # # h0 = ln(2/pi * ln(pi/tau)) # # or just scratch ln(h) to get # # h1 = ln(tau/pi) - W_{-1}(-tau/2). # # Both of these suggestions underestimate and `j` will be too large. An # approximation that overestimates is obtained by replacing `ln(h)` by `h`, # # h2 = 1/2 - log(sqrt(pi/tau)) - W_{-1}(-sqrt(exp(1)*pi*tau) / 4). # # Application of Newton's method will improve all of these approximations # and will also always overestimate such that `j` won't exceed 1 in the # first step. Nice! # TODO since we're doing Newton iterations anyways, use a more accurate # representation for j, and consequently for h h = _solve_expx_x_logx(eps**2, tol=1.0e-10) last_error_estimate = None success = False for level in range(max_steps + 1): # We would like to calculate the weights until they are smaller than # tau, i.e., # # h * pi/2 * cosh(h*j) / cosh(pi/2 * sinh(h*j))**2 < tau. # # (TODO Newton on this expression to find tau?) # # To streamline the computation, j is estimated in advance. The only # assumption we're making is that h*j>>1 such that exp(-h*j) can be # neglected. With this, the above becomes # # tau > h * pi/2 * exp(h*j)/2 / cosh(pi/2 * exp(h*j)/2)**2 # # and further # # tau > h * pi * exp(h*j) / exp(pi/2 * exp(h*j)). # # Calling z = - pi/2 * exp(h*j), one gets # # tau > -2*h*z * exp(z) # # This inequality is fulfilled exactly if z = W(-tau/h/2) with W being # the (-1)-branch of the Lambert-W function IF exp(1)*tau < 2*h (which # we can assume since `tau` will generally be small). We finally get # # j > ln(-2/pi * W(-tau/h/2)) / h. # # We do require j to be positive, so -2/pi * W(-tau/h/2) > 1. This # translates to the slightly stricter requirement # # tau * exp(pi/2) < pi * h, # # i.e., h needs to be about 1.531 times larger than tau (not only 1.359 # times as the previous bound suggested). # # Note further that h*j is ever decreasing as h decreases. assert eps**2 * mp.exp(mp.pi / 2) < mp.pi * h j = int(mp.ln(-2 / mp.pi * mp.lambertw(-eps**2 / h / 2, -1)) / h) # At level 0, one only takes the midpoint, for all greater levels every # other point. The value estimation is later completed with the # estimation from the previous level which. if level == 0: t = [0] else: t = h * numpy.arange(1, j + 1, 2) sinh_t = mp.pi / 2 * numpy.array(list(map(mp.sinh, t))) cosh_t = mp.pi / 2 * numpy.array(list(map(mp.cosh, t))) cosh_sinh_t = numpy.array(list(map(mp.cosh, sinh_t))) # y = alpha/2 * (1 - x) # x = [mp.tanh(v) for v in u2] exp_sinh_t = numpy.array(list(map(mp.exp, sinh_t))) y0 = alpha2 / exp_sinh_t / cosh_sinh_t y1 = -alpha2 * cosh_t / cosh_sinh_t**2 weights = -h * y1 fly = numpy.array([f_left[0](yy) for yy in y0]) fry = numpy.array([f_right[0](yy) for yy in y0]) lsummands = fly * weights rsummands = fry * weights # Perform the integration. if level == 0: # The root level only contains one node, the midpoint; function # values of f_left and f_right are equal here. Deliberately take # lsummands here. value_estimates = list(lsummands) else: value_estimates.append( # Take the estimation from the previous step and half the step # size. Fill the gaps with the sum of the values of the current # step. value_estimates[-1] / 2 + mp.fsum(lsummands) + mp.fsum(rsummands)) # error estimation if 1 in f_left and 2 in f_left: assert 1 in f_right and 2 in f_right error_estimate = _error_estimate1(h, sinh_t, cosh_t, cosh_sinh_t, y0, y1, fly, fry, f_left, f_right, alpha, last_error_estimate) last_error_estimate = error_estimate else: error_estimate = _error_estimate2(eps, value_estimates, lsummands, rsummands) if abs(error_estimate) < eps: success = True break h /= 2 assert success return value_estimates[-1], error_estimate
# parameters of the 'Zolotarev' polynomial n = 9 N = 2 * n + 1 # 'N' is the order of the polynomial # 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)
from __future__ import absolute_import import numpy as np import scipy.special as spf from scipy.optimize import curve_fit import math from mpmath import mp from ..w_transform import HaarTransform, wh_alj from .analysistools import * __all__ = ['ExactMethod'] dummy = 1000 g_nsigmamax = 10 g_pmin = mp.erfc(g_nsigmamax * mp.sqrt(0.5)) g_digits = int(math.ceil(-1 * mp.log10(g_pmin))) g_logdigits = 17 #for nsigma and log10p output mp.dps = g_digits + 2 #a bit extra class ExactMethod: def __init__(self, data, hypothesis): """ Parameters ---------- ::data:: array_like ::hypothesis:: array_like """ self.WaveDec_data = HaarTransform(data, Normalize=False) self.WaveDec_hypo = HaarTransform(hypothesis, Normalize=False)
from mpmath import mp from .argparser import args DPS = args.dps DPS_BUFFER = args.buffer + int(mp.log10(DPS)) # set mpmath decimal precision mp.dps = DPS + DPS_BUFFER
params = None # Integration sol_BDF = solve_ivp( fun=system, t_span=t_span, y0=init_cond, method="BDF", dense_output=True, rtol=1e-6, atol=1e-8, first_step=(t_end - t_start) * 1e-5, args=params, ) t = np.logspace(start=-5, stop=np.log10(t_end), num=int(1e4)) y = sol_BDF.sol(t) # Save data in file data = np.stack((t, y[0], y[1], y[2], y[3], y[4]), axis=1) np.savetxt( join(dirname(abspath(__file__)), "plots/python.dat"), data, header="t \t i(t) \t a(t) \t m(t) \t z(t) \t s(t) \n", ) num = y[4][-1] ndigits = 3 - (int(mp.floor(mp.log10(abs(num)))) + 1) # Only works for numbers < 1. print("Stellar density after", t_end, "Gyr:", round(num, ndigits), "Mₒpc^(-2)")
def _format_mantissa(self, fmt, x, sig, parenth=False): try: if isnan(x): return 'nan' if isinf(x) and x > 0: if fmt == 'html': return '∞' if fmt == 'latex': return r'\infty' if fmt == 'ascii': return 'inf' return '\u221E' if isinf(x) and x < 0: if fmt == 'html': return '-∞' if fmt == 'latex': return r'-\infty' if fmt == 'ascii': return '-inf' return '-\u221E' except: pass ellipses = '' if isinstance(x, Rational) and sig is None: if x == int(x): s = str(int(x)) else: xf = float(x) e = 15 - _floor(log10(abs(xf))) if e < 0: e = 0 n = 10**e * x if int(n) != n: ellipses = '...' s = str(round(xf, e)) elif sig is None: s = str(x) else: if x != 0 and self.max_digits is not None: if mpf is not None and isinstance(x, mpf): em = _floor(mp.log10(abs(x))) else: em = _floor(log10(abs(float(x)))) e = self.max_digits - em if e < 0: e = 0 if sig > e and sig > 0: ellipses = '...' sig = e if sig < 0: sig = 0 if mpf is not None and isinstance(x, mpf): s = mp.nstr(x, n=sig + 1, strip_zeros=False) else: s = round(float(x), sig) s = ('{:.' + str(sig) + 'f}').format(s) if parenth: s = s.replace('.', '') s = s.lstrip('0') if len(s) == 0: s = '0' return s elif self.thousand_spaces: # Now insert spaces every three digits if fmt == 'html': sp = ' ' elif fmt == 'latex': sp = r'\,' else: sp = ' ' d = s.find('.') if d != -1: i = d + 1 while i < len(s) and s[i].isdigit(): i += 1 nr = i - d - 1 else: nr = 0 d = len(s) i = d - 1 while i > 0 and s[i].isdigit(): i -= 1 nl = d - i - 1 if nr <= 4 and nl <= 4: return s + ellipses s = list(s) if nr > 4: for i in range(int(nr / 3)): s.insert(d + i + (i + 1) * 3 + 1, sp) if nl > 4: for i in range(int(nl / 3)): s.insert(d - (i + 1) * 3, sp) s = ''.join(s) if s.endswith(sp): s = s[:-(len(sp))] return s + ellipses
def check_score_of_hash_list_func(input_hash_list, difficulty_level, list_of_2_digits_chunks, list_of_mpmath_functions, list_of_mpmath_function_names, previous_block_final_hash_as_string_reversed_leading_zeros_stripped, use_verbose): hash_is_valid = 0 list_of_hash_integers = list() for current_hash in input_hash_list: list_of_hash_integers.append(mpf(int(current_hash, 16))) list_of_hashes_in_size_order = sorted(list_of_hash_integers) input_hash_list_sorted = sort_list_based_on_another_list_func(input_hash_list, list_of_hash_integers) list_of_hash_types = ['SHA-256 + (Repeated again in reverse)', 'SHA3-256 + (Repeated again in reverse)', 'SHA3-512', 'BLAKE2S + (Repeated again in reverse)', 'BLAKE2B'] list_of_hash_types_sorted = sort_list_based_on_another_list_func(list_of_hash_types, list_of_hash_integers) smallest_hash = list_of_hashes_in_size_order[0] second_smallest_hash = list_of_hashes_in_size_order[1] middle_hash = list_of_hashes_in_size_order[2] second_largest_hash = list_of_hashes_in_size_order[-2] largest_hash = list_of_hashes_in_size_order[-1] list_of_hashes_by_name = [smallest_hash, largest_hash, middle_hash, second_smallest_hash, second_largest_hash] list_of_hash_name_strings = ['smallest_hash', 'largest_hash', 'middle_hash', 'second_smallest_hash', 'second_largest_hash'] last_k_digits_to_extract_from_each_intermediate_result = difficulty_level*5 list_of_intermediate_results_last_k_digits = list() if use_verbose: printc('Previous final hash: ' + str(previous_block_final_hash),'b') printc('After being reversed and removing leading zeros: '+ previous_block_final_hash_as_string_reversed_leading_zeros_stripped + '\n\n','b') for cnt, current_formula in enumerate(list_of_mpmath_functions): current_formula_name = list_of_mpmath_function_names[cnt] two_digit_hash_chunk = list_of_2_digits_chunks[cnt] hash_index = cnt%len(list_of_hashes_by_name) current_hash_value = list_of_hashes_by_name[hash_index] current_hash_value_rescaled = mp.frac(mp.log10(current_hash_value)) current_hash_name_string = list_of_hash_name_strings[hash_index] current_intermediate_result = current_formula(current_hash_value_rescaled) current_intermediate_result_as_string = str(current_intermediate_result) current_intermediate_result_as_string_decimal_point_and_leading_zeros_stripped = current_intermediate_result_as_string.replace('.','').lstrip('0') current_intermediate_result_as_string_decimal_point_and_leading_zeros_stripped_last_k_digits = current_intermediate_result_as_string_decimal_point_and_leading_zeros_stripped[-last_k_digits_to_extract_from_each_intermediate_result:] list_of_intermediate_results_last_k_digits.append(int(current_intermediate_result_as_string_decimal_point_and_leading_zeros_stripped_last_k_digits)) if use_verbose: printc('Current 2-digit chunk of reversed previous hash: '+str(two_digit_hash_chunk),'m') printc('Corresponding mathematical formula for index '+str(two_digit_hash_chunk)+' (out of 100 distinct formulas from mpmath): y =' + current_formula_name,'r') printc('Current hash value to use in the formula: ' + list_of_hash_types_sorted[cnt] + ': ' + input_hash_list_sorted[cnt] + ')','y') printc('Hash Value as an Integer (i.e., whole number): ' + current_hash_name_string + ' = ' + str(int(current_hash_value)),'y') printc('Rescaled hash value (i.e., x = fractional_part( log(hash_value) ) in the formula): ' + str(current_hash_value_rescaled),'g') printc('Output from formula: (i.e., y in the formula): ' + str(current_intermediate_result),'g') printc('Output as string with decimal point and leading zeros removed: ' + str(current_intermediate_result_as_string_decimal_point_and_leading_zeros_stripped),'g') printc('Last '+str(last_k_digits_to_extract_from_each_intermediate_result)+' digits of rescaled output (these are multiplied together to produce the final hash): ' + str(current_intermediate_result_as_string_decimal_point_and_leading_zeros_stripped_last_k_digits)+'\n\n','c') final_hash = 1 for current_k_digit_chunk in list_of_intermediate_results_last_k_digits: final_hash = final_hash*current_k_digit_chunk difficulty_string = construct_difficulty_string_func(difficulty_level) number_of_matching_leading_characters = get_number_of_matching_leading_characters_in_string_func(final_hash, difficulty_string) if number_of_matching_leading_characters >= difficulty_level: hash_is_valid = 1 if use_verbose: print('\n') printc(make_text_indented_func('Final Hash (product of all the k-digit chunks): '+str(final_hash),5),'c') printc('\nDifficulty Level: ' + str(difficulty_level),'r') printc('Difficulty String: ' + difficulty_string,'r') if hash_is_valid: if difficulty_level == 1: digit_text = 'digit' else: digit_text = str(difficulty_level)+' digits' print_mining_congratulations_message_func() printc('\nSince the first ' + digit_text + ' of the final hash match all of the digits in the difficulty string, the hash is valid!', 'b') else: printc('\nHash is invalid, sorry!\n', 'b') if SLOWDOWN: sleep(0.1) return number_of_matching_leading_characters, hash_is_valid, final_hash
from jinja2 import Environment, FileSystemLoader class str_item: 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")