mpmath_special_functions_test_generator.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #!/usr/bin/env python3
  2. import mpmath as mp
  3. import mpmath_riccati_bessel as mrb
  4. import mpmath_input_arguments as mia
  5. import os.path
  6. class TestData:
  7. def __init__(self, list_to_parse, filetype):
  8. self.filetype = filetype
  9. if self.filetype == 'c++':
  10. self.cpp_parse(list_to_parse)
  11. else:
  12. raise NotImplementedError("Only C++ files *.hpp parsing was implemented")
  13. def cpp_parse(self, list_to_parse):
  14. self.comment = list_to_parse[0]
  15. if self.comment[:2] != '//': raise ValueError('Not a comment')
  16. self.typeline = list_to_parse[1]
  17. if 'std::vector' not in self.typeline: raise ValueError('Unexpected C++ container')
  18. self.testname = list_to_parse[2]
  19. self.opening = list_to_parse[3]
  20. if self.opening != '= {': raise ValueError('For C++ we expect opeing with = {');
  21. self.ending = list_to_parse[-1]
  22. if self.ending != '};': raise ValueError('For C++ we expect closing };')
  23. self.evaluated_data = list_to_parse[4:-1]
  24. def get_string(self):
  25. out_sting = self.comment + '\n' + self.typeline + '\n' + self.testname + '\n' + self.opening + '\n'
  26. for result in self.evaluated_data:
  27. out_sting += result + '\n'
  28. out_sting += self.ending + '\n'
  29. return out_sting
  30. class UpdateSpecialFunctionsEvaluations:
  31. def __init__(self, filename='default_out.hpp', complex_arguments=[],
  32. output_dps=16, max_num_elements_of_nlist=51):
  33. self.evaluated_data = []
  34. self.test_setup = []
  35. self.filename = filename
  36. self.read_evaluated_data()
  37. self.complex_arguments = complex_arguments
  38. self.output_dps = output_dps
  39. self.max_num_elements_of_nlist = max_num_elements_of_nlist
  40. def read_evaluated_data(self):
  41. self.filetype = 'undefined'
  42. if self.filename.endswith('.hpp'):
  43. self.filetype = 'c++'
  44. if self.filename.endswith('.f90'):
  45. self.filetype = 'fortran'
  46. if not os.path.exists(self.filename):
  47. print("WARNING! Found no data file:", self.filename)
  48. return
  49. with open(self.filename, 'r') as in_file:
  50. content = in_file.readlines()
  51. content = [x.strip() for x in content]
  52. while '' in content:
  53. record_end_index = content.index('')
  54. new_record = content[:record_end_index]
  55. content = content[record_end_index + 1:]
  56. self.add_record(new_record)
  57. self.add_record(content)
  58. def add_record(self, new_record):
  59. if len(new_record) == 0: return
  60. if len(new_record) < 6: raise ValueError('Not enough lines in record:', new_record)
  61. self.evaluated_data.append(TestData(new_record, self.filetype))
  62. def get_file_content(self):
  63. self.evaluated_data.sort(key=lambda x: x.testname) # , reverse=True)
  64. out_string = ''
  65. for record in self.evaluated_data:
  66. out_string += record.get_string() + '\n'
  67. return out_string[:-1]
  68. def remove(self, testname):
  69. for i, result in enumerate(self.evaluated_data):
  70. if result.testname == testname:
  71. del self.evaluated_data[i]
  72. def get_n_list(self, z, max_number_of_elements=10):
  73. nmax = mrb.LeRu_cutoff(z)
  74. factor = nmax ** (1 / (max_number_of_elements - 2))
  75. n_list = [int(factor ** i) for i in range(max_number_of_elements - 1)]
  76. n_list.append(0)
  77. n_set = set(n_list)
  78. return sorted(n_set)
  79. def get_test_data_nlist(self, z_record, output_dps, n, func):
  80. isNeedMoreDPS = False
  81. x = str(z_record[0])
  82. mr = str(z_record[1][0])
  83. mi = str(z_record[1][1])
  84. z_str = ''
  85. try:
  86. z = mp.mpf(x) * mp.mpc(mr, mi)
  87. if self.is_only_x: z = mp.mpf(x)
  88. D1nz = func(n, z)
  89. z_str = ('{{' +
  90. mp.nstr(z.real, output_dps * 2) + ',' +
  91. mp.nstr(z.imag, output_dps * 2) + '},' +
  92. str(n) + ',{' +
  93. mp.nstr(D1nz.real, output_dps) + ',' +
  94. mp.nstr(D1nz.imag, output_dps) + '},' +
  95. mp.nstr(mp.fabs(D1nz.real * 10 ** -output_dps), 2) + ',' +
  96. mp.nstr(mp.fabs(D1nz.imag * 10 ** -output_dps), 2) +
  97. '},')
  98. if mp.nstr(D1nz.real, output_dps) == '0.0' \
  99. or mp.nstr(D1nz.imag, output_dps) == '0.0':
  100. isNeedMoreDPS = True
  101. except:
  102. isNeedMoreDPS = True
  103. return z_str, isNeedMoreDPS
  104. def get_test_data(self, Du_test, output_dps, max_num_elements_of_n_list, func, funcname):
  105. output_list = ['// complex(z), n, complex(f(n,z)), abs_err_real, abs_err_imag',
  106. 'std::vector< std::tuple< std::complex<double>, int, std::complex<double>, double, double > >',
  107. str(funcname) + '_test_' + str(output_dps) + 'digits', '= {']
  108. for z_record in Du_test:
  109. x = str(z_record[0])
  110. mr = str(z_record[1][0])
  111. mi = str(z_record[1][1])
  112. mp.mp.dps = 20
  113. z = mp.mpf(x) * mp.mpc(mr, mi)
  114. n_list = self.get_n_list(z, max_num_elements_of_n_list)
  115. if z_record[4] == 'Yang': n_list = [0, 1, 30, 50, 60, 70, 75, 80, 85, 90, 99, 116, 130]
  116. print(z, n_list)
  117. failed_evaluations = 0
  118. for n in n_list:
  119. mp.mp.dps = 20
  120. old_z_string, isNeedMoreDPS = self.get_test_data_nlist(z_record, output_dps, n, func, )
  121. mp.mp.dps = 37
  122. new_z_string, isNeedMoreDPS = self.get_test_data_nlist(z_record, output_dps, n, func)
  123. while old_z_string != new_z_string \
  124. or isNeedMoreDPS:
  125. new_dps = int(mp.mp.dps * 1.41)
  126. if new_dps > 300: break
  127. mp.mp.dps = new_dps
  128. print("New dps = ", mp.mp.dps, 'n =', n, ' (max ', n_list[-1], ') for z =', z, ' ', end='')
  129. old_z_string = new_z_string
  130. new_z_string, isNeedMoreDPS = self.get_test_data_nlist(z_record, output_dps, n, func)
  131. if new_z_string != '':
  132. output_list.append(new_z_string)
  133. else:
  134. failed_evaluations += 1
  135. # break
  136. result_str = "All done!"
  137. if failed_evaluations > 0: result_str = " FAILED!"
  138. print("\n", result_str, "Failed evaluations ", failed_evaluations, ' of ', len(n_list))
  139. output_list.append('};')
  140. return output_list
  141. def run_test(self, func, funcname, is_only_x=False):
  142. self.is_only_x = is_only_x
  143. self.remove_argument_duplicates()
  144. out_list_result = self.get_test_data(self.complex_arguments, self.output_dps,
  145. self.max_num_elements_of_nlist,
  146. func, funcname)
  147. testname = str(funcname) + '_test_' + str(self.output_dps) + 'digits'
  148. self.remove(testname)
  149. self.add_record(out_list_result)
  150. def remove_argument_duplicates(self):
  151. print("Arguments in input: ", len(self.complex_arguments))
  152. mp.mp.dps = 20
  153. self.complex_arguments.sort()
  154. filtered_list = []
  155. filtered_list.append(self.complex_arguments[0])
  156. for i in range(1, len(self.complex_arguments)):
  157. # if x and m are the same: continue
  158. if (filtered_list[-1][0] == self.complex_arguments[i][0] and
  159. filtered_list[-1][1] == self.complex_arguments[i][1]):
  160. continue
  161. # argument list is sorted, so when only x is needed
  162. # the record with the largest m
  163. if (self.is_only_x
  164. and filtered_list[-1][0] == self.complex_arguments[i][0]):
  165. # continue
  166. del filtered_list[-1]
  167. filtered_list.append(self.complex_arguments[i])
  168. self.complex_arguments = filtered_list
  169. # print(self.complex_arguments)
  170. print("Arguments after filtering: ", len(self.complex_arguments))
  171. # exit(0)
  172. def main():
  173. sf_evals = UpdateSpecialFunctionsEvaluations(filename='test_spec_functions_data.hpp',
  174. complex_arguments=mia.complex_arguments,
  175. output_dps=16, max_num_elements_of_nlist=51)
  176. # output_dps=5, max_num_elements_of_nlist=3)
  177. # sf_evals.run_test(mrb.D1, 'D1')
  178. # sf_evals.run_test(mrb.D2, 'D2')
  179. # sf_evals.run_test(mrb.D3, 'D3')
  180. # sf_evals.run_test(mrb.psi, 'psi', is_only_x=True)
  181. # # In literature Zeta or Ksi denote the Riccati-Bessel function of third kind.
  182. # sf_evals.run_test(mrb.xi, 'xi', is_only_x=True)
  183. # sf_evals.run_test(mrb.ksi, 'zeta', is_only_x=True)
  184. # sf_evals.run_test(mrb.psi, 'psi')
  185. # sf_evals.run_test(mrb.psi_div_ksi, 'psi_div_ksi')
  186. sf_evals.run_test(mrb.psi_mul_ksi, 'psi_mul_zeta', is_only_x=True)
  187. # sf_evals.run_test(mrb.psi_div_xi, 'psi_div_xi')
  188. with open(sf_evals.filename, 'w') as out_file:
  189. out_file.write(sf_evals.get_file_content())
  190. main()