You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.7 KiB

10 months ago
  1. from parameterisations.utils.fit_linear_regression_model import (
  2. fit_linear_regression_model,
  3. )
  4. from parameterisations.utils.parse_regression_coef_to_array import (
  5. parse_regression_coef_to_array,
  6. )
  7. import uproot
  8. import argparse
  9. from pathlib import Path
  10. def parameterise_field_integral(
  11. input_file: str = "data/param_data_selected_all_p.root",
  12. tree_name: str = "Selected",
  13. ) -> Path:
  14. """Function to estimate parameters describing the magnetic field integral.
  15. Args:
  16. input_file (str, optional): Defaults to "data/param_data_selected_all_p.root".
  17. tree_name (str, optional): Defaults to "Selected".
  18. Returns:
  19. Path: Path to the parameters in cpp format.
  20. """
  21. input_tree = uproot.open({input_file: tree_name})
  22. # this is an event list of dictionaries containing awkward arrays
  23. array = input_tree.arrays()
  24. array["dSlope_fringe"] = array["tx_ref"] - array["tx"]
  25. array["poqmag_gev"] = 1.0 / (array["signed_rel_current"] * array["qop"] * 1000.0)
  26. array["B_integral"] = array["poqmag_gev"] * array["dSlope_fringe"]
  27. model_ref, poly_features_ref = fit_linear_regression_model(
  28. array,
  29. target_feat="B_integral",
  30. features=[
  31. "ty",
  32. "tx",
  33. "tx_ref",
  34. ],
  35. keep=[
  36. "ty^2",
  37. "tx^2",
  38. "tx tx_ref",
  39. "tx_ref^2",
  40. "ty^2 tx tx_ref",
  41. "ty^2 tx^2",
  42. "ty^2 tx_ref^2",
  43. "tx^4",
  44. "ty^4",
  45. "tx_ref^4",
  46. "tx^3 tx_ref",
  47. ],
  48. degree=5,
  49. fit_intercept=True,
  50. )
  51. cpp_ref = parse_regression_coef_to_array(
  52. model_ref,
  53. poly_features_ref,
  54. "fieldIntegralParamsRef",
  55. )
  56. outpath = Path("parameterisations/result/field_integral_params.hpp")
  57. outpath.parent.mkdir(parents=True, exist_ok=True)
  58. with open(outpath, "w") as result:
  59. result.writelines(cpp_ref)
  60. return outpath
  61. if __name__ == "__main__":
  62. parser = argparse.ArgumentParser()
  63. parser.add_argument(
  64. "--input-file",
  65. type=str,
  66. help="Path to the input file",
  67. required=False,
  68. )
  69. parser.add_argument(
  70. "--tree-name",
  71. type=str,
  72. help="Path to the input file",
  73. required=False,
  74. )
  75. args = parser.parse_args()
  76. args_dict = {arg: val for arg, val in vars(args).items() if val is not None}
  77. outfile = parameterise_field_integral(**args_dict)
  78. try:
  79. import subprocess
  80. # run clang-format for nicer looking result
  81. subprocess.run(
  82. [
  83. "clang-format",
  84. "-i",
  85. f"{outfile}",
  86. ],
  87. check=True,
  88. )
  89. except:
  90. pass