0
0

compton_combiner.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. """Script to combine compton measurements with runs and process these data
  2. """
  3. import argparse
  4. from configparser import ConfigParser
  5. from datetime import datetime, timedelta, timezone
  6. import logging
  7. import os
  8. import sys
  9. import sqlite3
  10. from typing import Union, Tuple, Optional
  11. from compton_filter import CalibrdbHandler
  12. from iminuit import Minuit
  13. import matplotlib.dates as mdates
  14. import matplotlib.pyplot as plt
  15. from mysql.connector import connect, Error
  16. import numpy as np
  17. import pandas as pd
  18. from tqdm import tqdm
  19. SEASONS = {
  20. 'name': ['RHO2013', 'BRK2013/16', 'HIGH2017', 'RHO2018', 'HIGH2019', 'LOW2020', 'HIGH2020', 'HIGH2021', 'NNBAR2021'],
  21. 'start_run': [18809, 32076, 36872, 48938, 70014, 85224, 89973, 98116, 107342, None],
  22. }
  23. class RunsDBHandler():
  24. def __init__(self, host: str = 'cmddb', database: str = 'online', user: str = None, password: str = None):
  25. self.conn = connect(host = host, database = database, user = user, password = password)
  26. self.cur = self.conn.cursor()
  27. self.cur.execute("SET time_zone = '+07:00';")
  28. @property
  29. def fields(self) -> list:
  30. """Returns a list of available columns in the RunsDB
  31. """
  32. self.cur.execute("""DESCRIBE Runlog""")
  33. return self.cur.fetchall()
  34. def load_tables(self, range: Union[Tuple[int, Optional[int]], Tuple[datetime, datetime]], energy_point: Optional[float] = None, select_bad_runs: bool = False):
  35. """
  36. Returns a slice of the table with following fields: run, starttime, stoptime, energy, luminosity
  37. Parameters
  38. ----------
  39. range : Union[Tuple[int, Optional[int]], Tuple[datetime, datetime]]
  40. selection range
  41. int range defines an interval in runs
  42. datetime range defines a time interval (NSK: +7:00 time)
  43. energy_point : Optional[float]
  44. energy point name, MeV (default is None)
  45. select_bad_runs : bool
  46. select runs with labels except (Y) (default is False)
  47. """
  48. cond = ""
  49. if isinstance(range[0], int):
  50. cond = f" AND run >= {range[0]} "
  51. if range[1] is not None:
  52. cond += f" AND run <= {range[1]} "
  53. elif isinstance(range[0], datetime):
  54. cond = f" AND starttime >= %s "
  55. if range[1] is not None:
  56. cond += " AND stoptime <= %s"
  57. else:
  58. range = (range[0], )
  59. energy_cond = ""
  60. if energy_point is not None:
  61. energy_cond = f" AND energy = {energy_point}"
  62. quality_cond = ' quality = "Y" '
  63. if select_bad_runs:
  64. quality_cond = ' quality <> "Y" '
  65. sql_query = f"""
  66. SELECT
  67. run,
  68. starttime,
  69. stoptime,
  70. energy,
  71. luminosity
  72. FROM Runlog
  73. WHERE
  74. {quality_cond}
  75. {cond}
  76. {energy_cond}
  77. AND luminosity > 0
  78. AND stoptime > starttime
  79. AND nevent > 0
  80. ORDER BY run DESC"""
  81. if isinstance(range[0], datetime):
  82. self.cur.execute(sql_query, range)
  83. else:
  84. self.cur.execute(sql_query)
  85. field_names = [i[0] for i in self.cur.description]
  86. res = self.cur.fetchall()
  87. return res, field_names
  88. def __del__(self):
  89. self.conn.close()
  90. class Combiner():
  91. """Combines a dataframe with runs and a dataframe with compton measurements together
  92. """
  93. def __init__(self, runsdb: Tuple[list, list], clbrdb: Tuple[list, list]):
  94. """
  95. Parameters
  96. ----------
  97. runsdb : Tuple[list, list]
  98. table of runs (rows and field names)
  99. clbrdb : Tuple[list, list]
  100. table of compton measurements (rows and field names)
  101. """
  102. rdb_rows, r_fld = runsdb
  103. cdb_rows, c_fld = clbrdb
  104. self.conn = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
  105. self.cur = self.conn.cursor()
  106. self.cur.execute(f"CREATE table runs (run, elabel, starttime timestamp, stoptime timestamp, luminosity)")
  107. self.cur.execute(f"CREATE table compton (begintime timestamp, endtime timestamp, e_mean, e_std, spread_mean, spread_std)")
  108. run_row_generator = map(lambda x: (x[r_fld.index("run")], x[r_fld.index("energy")],
  109. x[r_fld.index("starttime")], x[r_fld.index("stoptime")],
  110. x[r_fld.index("luminosity")]), rdb_rows)
  111. c_data_idx = c_fld.index("data")
  112. compton_row_generator = map(lambda x: (x[c_fld.index("begintime")], x[c_fld.index("endtime")],
  113. float(x[c_data_idx][0]), float(x[c_data_idx][1]),
  114. float(x[c_data_idx][2]), float(x[c_data_idx][3])), cdb_rows)
  115. self.cur.executemany(f"""INSERT into runs VALUES ({','.join(['?']*5)})""", run_row_generator)
  116. self.cur.executemany(f"""INSERT into compton VALUES ({','.join(['?']*6)})""", compton_row_generator)
  117. self.__create_combined_table()
  118. def __create_combined_table(self):
  119. create_combined_query = """
  120. CREATE TABLE combined_table AS
  121. SELECT
  122. runs.run AS run,
  123. runs.elabel AS elabel,
  124. runs.starttime as "run_start [timestamp]",
  125. runs.stoptime AS "run_stop [timestamp]",
  126. compton.begintime AS "compton_start [timestamp]",
  127. compton.endtime AS "compton_stop [timestamp]",
  128. runs.luminosity, compton.e_mean, compton.e_std, compton.spread_mean, compton.spread_std
  129. FROM runs, compton
  130. WHERE
  131. (runs.starttime BETWEEN compton.begintime AND compton.endtime)
  132. OR (runs.stoptime BETWEEN compton.begintime AND compton.endtime)
  133. OR (compton.begintime BETWEEN runs.starttime AND runs.stoptime)
  134. OR (compton.endtime BETWEEN runs.starttime AND runs.stoptime);
  135. """
  136. self.cur.execute(create_combined_query)
  137. return
  138. def combined_table(self) -> pd.DataFrame:
  139. """Returns combined dataframe
  140. """
  141. sql_query = """
  142. SELECT * FROM combined_table;
  143. """
  144. df = pd.read_sql(sql_query, self.conn)
  145. df['common_duration'] = df[['run_stop', 'compton_stop']].min(axis=1) - df[['run_start', 'compton_start']].max(axis=1)
  146. df['run_duration'] = df['run_stop'] - df['run_start']
  147. df['run_in_measurement'] = df['common_duration']/df['run_duration']
  148. df = df.sort_values(by='run_in_measurement', ascending=False).drop_duplicates(subset='run').sort_values(by='run')
  149. df = df.drop(['run_duration', 'common_duration'], axis=1) #, 'run_start', 'run_stop'
  150. return df
  151. def __del__(self):
  152. self.conn.close()
  153. class Likelihood():
  154. """
  155. Likelihood function
  156. """
  157. def __init__(self, means: np.array, sigmas: np.array, weights: np.array):
  158. """
  159. Parameters
  160. ----------
  161. means : np.array
  162. array of means, [MeV]
  163. sigmas : np.array
  164. array of standard deviations, [MeV]
  165. weights : np.array
  166. array of luminosities
  167. """
  168. self.means = means
  169. self.sigmas = sigmas
  170. self.weights = weights/weights.mean()
  171. def __call__(self, mean: float, sigma: float):
  172. """
  173. Calls likelihood calculation
  174. Parameters
  175. ----------
  176. mean : float
  177. expected mean
  178. sigma : float
  179. expected standard deviation
  180. """
  181. sigma_total = np.sqrt(sigma**2 + self.sigmas**2)
  182. ln_L = -np.sum( self.weights*( ((mean - self.means)**2)/(2*(sigma_total**2)) + np.log(sigma_total) ) )
  183. return -ln_L
  184. def __estimate_point_with_closest(comb_df: pd.DataFrame, runs_df: pd.DataFrame, compton_df: pd.DataFrame):
  185. # estimate energy by the nearest points
  186. min_run_time = runs_df[runs_df.run == comb_df.iloc[0].at['run_first']].iloc[0].at['starttime']
  187. max_run_time = runs_df[runs_df.run == comb_df.iloc[0].at['run_last']].iloc[0].at['stoptime']
  188. nearest_row_before = compton_df.iloc[pd.Index(compton_df.endtime).get_loc(min_run_time, 'nearest')]
  189. nearest_row_after = compton_df.iloc[pd.Index(compton_df.begintime).get_loc(max_run_time, 'nearest')]
  190. # regulatization
  191. nearest_row_before['data'][1] = max(nearest_row_before['data'][3], 1e-3)
  192. nearest_row_after['data'][3] = max(nearest_row_after['data'][3], 1e-3)
  193. nearest_row_before['data'][1] = max(nearest_row_before['data'][1], 1e-3)
  194. nearest_row_after['data'][3] = max(nearest_row_after['data'][3], 1e-3)
  195. mean_energy = (nearest_row_before['data'][0] + nearest_row_after['data'][0])/2
  196. mean_spread = (nearest_row_before['data'][2] + nearest_row_after['data'][2])/2
  197. std_energy = np.sqrt(1/(1/(nearest_row_before['data'][1])**2 + 1/(nearest_row_after['data'][1])**2))
  198. std_spread = np.sqrt(1/(1/(nearest_row_before['data'][3])**2 + 1/(nearest_row_after['data'][3])**2))
  199. sys_energy = np.std([nearest_row_before['data'][0], nearest_row_after['data'][0]])
  200. return {
  201. 'energy_point': comb_df.elabel.min(),
  202. 'first_run': comb_df.run_first.min(),
  203. 'last_run': comb_df.run_last.max(),
  204. 'mean_energy': mean_energy,
  205. 'mean_energy_stat_err': std_energy,
  206. 'mean_energy_sys_err': sys_energy,
  207. 'mean_spread': mean_spread,
  208. 'mean_spread_stat_err': std_spread,
  209. 'used_lum': 0,
  210. 'comment': 'indirect measurement #2',
  211. }, pd.DataFrame([])
  212. def averager_on_lums(df: pd.DataFrame) -> dict:
  213. """Averaging as <E> = \frac{\sum{L_i E_i}{\sum{L_i}},
  214. \deltaE^2 = \frac{\sum{(L_i \delta E_i)^2}}{(\sum L_i)^2}
  215. Attention: I think it's incorrect way of avaraging.
  216. Parameters
  217. ----------
  218. df : pd.DataFrame
  219. input dataframe containg means and spreads
  220. Returns
  221. -------
  222. dict
  223. averaged mean and spread
  224. """
  225. mean_en = (df.e_mean * df.luminosity).sum() / df.luminosity.sum()
  226. sys_err = df.e_mean.std()
  227. stat_err = np.sqrt( np.sum((df.luminosity * df.e_std)**2) ) / df.luminosity.sum()
  228. mean_spread = (df.spread_mean * df.luminosity).sum() / df.luminosity.sum()
  229. std_spread = np.sqrt( np.sum((df.luminosity * df.spread_std)**2) ) / df.luminosity.sum()
  230. return {
  231. 'mean_energy': mean_en,
  232. 'mean_energy_stat_err': stat_err,
  233. 'mean_energy_sys_err': sys_err,
  234. 'mean_spread': mean_spread,
  235. 'mean_spread_stat_err': std_spread,
  236. }
  237. def ultimate_averager(df: pd.DataFrame) -> dict:
  238. """Complete averager for estimation of mean energy and energy spread
  239. Parameters
  240. ----------
  241. df : pd.DataFrame
  242. input dataframe containing means and spreads
  243. Returns
  244. -------
  245. dict
  246. averaged mean and spread
  247. """
  248. m = Minuit(Likelihood(df.e_mean, df.e_std, df.luminosity), mean=df.e_mean.mean(), sigma=df.e_mean.std(ddof=0))
  249. m.errordef = 0.5
  250. m.limits['sigma'] = (0, None)
  251. m.migrad();
  252. # print(m.migrad())
  253. sys_err = m.values['sigma']
  254. mean_en = m.values['mean']
  255. mean_spread = np.sum(df.spread_mean*df.luminosity/(df.spread_std**2))/np.sum(df.luminosity/(df.spread_std**2))
  256. std_spread = np.sqrt(1/np.sum((df.luminosity/df.luminosity.mean())/df.spread_std**2))
  257. return {
  258. 'mean_energy': mean_en,
  259. 'mean_energy_stat_err': m.errors['mean'],
  260. 'mean_energy_sys_err': sys_err,
  261. 'mean_spread': mean_spread,
  262. 'mean_spread_stat_err': std_spread,
  263. }
  264. def calculate_point(comb_df: pd.DataFrame, runs_df: pd.DataFrame, compton_df: pd.DataFrame, rdb, averager: callable = ultimate_averager) -> dict:
  265. """Calculates parameters of the energy (mean, std, spread) in this dataFrame
  266. Parameters
  267. ----------
  268. comb_df : pd.DataFrame
  269. table of the measurements linked with runs
  270. runs_df : pd.DataFrame
  271. table of the runs
  272. compton_df : pd.DataFrame
  273. table of the comptons
  274. averager : callable
  275. function for averaging (ultimate_averager or averager_on_lums)
  276. Returns
  277. -------
  278. dict, pd.DataFrame
  279. average parameters on this DataFrame, clean dataFrame
  280. """
  281. if (len(comb_df) == 1) and pd.isnull(comb_df.iloc[0].at['compton_start']):
  282. # no direct measurements of the compton during data runs
  283. min_Yruntime = runs_df[runs_df.run == comb_df.iloc[0].at['run_first']].iloc[0].at['starttime']
  284. max_Yruntime = runs_df[runs_df.run == comb_df.iloc[0].at['run_last']].iloc[0].at['stoptime']
  285. dlt0 = timedelta(days=1)
  286. # assymetric time because energy can be stable only after
  287. runs_df_with_bads = rdb.load_tables((min_Yruntime, max_Yruntime + dlt0), energy_point = comb_df.iloc[0].at['elabel'], select_bad_runs = True)
  288. if len(runs_df_with_bads[0]) == 0:
  289. return __estimate_point_with_closest(comb_df, runs_df, compton_df)
  290. runs_df_with_bads_df = pd.DataFrame(runs_df_with_bads[0], columns = runs_df_with_bads[1])
  291. min_run_time, max_run_time = min(min_Yruntime, runs_df_with_bads_df.starttime.min()), max(max_Yruntime, runs_df_with_bads_df.stoptime.max())
  292. compton_meas = compton_df.query('((begintime>=@min_run_time)&(begintime<=@max_run_time))|((endtime>=@min_run_time)&(endtime<=@max_run_time))').copy()
  293. if len(compton_meas) == 0:
  294. # no compton measurements
  295. raise Exception("No measurement in this point. Pass it.")
  296. res_df = pd.DataFrame(list(map(lambda x: {
  297. 'compton_start': x[1]['begintime'],
  298. 'compton_stop': x[1]['endtime'],
  299. 'e_mean': float(x[1]['data'][0]),
  300. 'e_std': float(x[1]['data'][1]),
  301. 'spread_mean': float(x[1]['data'][2]),
  302. 'spread_std': float(x[1]['data'][3]),
  303. }, compton_meas.iterrows())))
  304. res_df = res_df.query(f'abs(e_mean -{comb_df.iloc[0].at["elabel"]})<5')
  305. if len(res_df) == 0:
  306. return __estimate_point_with_closest(comb_df, runs_df, compton_df)
  307. return {
  308. 'energy_point': comb_df.elabel.min(),
  309. 'first_run': comb_df.run_first.min(),
  310. 'last_run': comb_df.run_last.max(),
  311. 'mean_energy': res_df.e_mean.mean(),
  312. 'mean_energy_stat_err': np.sqrt(1/np.sum(1/(res_df.e_std)**2)),
  313. 'mean_energy_sys_err': np.abs(comb_df.iloc[0].at['elabel'] - res_df.e_mean.mean()),
  314. 'mean_spread': res_df.spread_mean.mean(),
  315. 'mean_spread_stat_err':np.sqrt(1/np.sum(1/(res_df.spread_std)**2)),
  316. 'used_lum': 0,
  317. 'comment': 'indirect measurement #1',
  318. }, res_df
  319. comb_df = comb_df.reset_index()
  320. df = comb_df.loc[~comb_df.compton_start.isna()].copy()
  321. df.spread_std = np.where(df.spread_std < 1e-4, 1e-4, df.spread_std)
  322. df = df[df.e_std > 0]
  323. mean_energy = np.sum(df.e_mean*df.luminosity/(df.e_std**2))/np.sum(df.luminosity/(df.e_std**2))
  324. good_criterion = np.abs((df.e_mean - mean_energy)/np.sqrt(df.e_mean.std(ddof=0)**2 + df.e_std**2)) < 5
  325. # print('WTF:', df[~good_criterion].index)
  326. df = df[good_criterion]
  327. df['accepted'] = 1
  328. averages = averager(df)
  329. res_dict = {
  330. 'energy_point': comb_df.elabel.min(),
  331. 'first_run': comb_df.run_first.min(),
  332. 'last_run': comb_df.run_last.max(),
  333. 'mean_energy': averages['mean_energy'],
  334. 'mean_energy_stat_err': averages['mean_energy_stat_err'],
  335. 'mean_energy_sys_err': averages['mean_energy_sys_err'],
  336. 'mean_spread': averages['mean_spread'],
  337. 'mean_spread_stat_err': averages['mean_spread_stat_err'],
  338. 'used_lum': df.luminosity.sum()/comb_df.luminosity_total.sum(),
  339. 'comment': '',
  340. }
  341. comb_df['accepted'] = 0
  342. comb_df.loc[df.index, 'accepted'] = 1
  343. return res_dict, comb_df.set_index('point_idx')
  344. def process_intersected_compton_meas(combined_df: pd.DataFrame) -> pd.DataFrame:
  345. """Replaces compton measurements writed on the border of two energy points on NaNs
  346. """
  347. energy_point_borders = combined_df[['point_idx', 'elabel', 'run_start', 'run_stop']].groupby(['point_idx'], dropna=True).agg(
  348. elabel_start_time=('run_start', 'min'), elabel_stop_time=('run_stop', 'max'),
  349. )
  350. df_comb = combined_df.set_index('point_idx').join(energy_point_borders, how='left')
  351. df_comb['comptonmeas_in_elabel'] = (df_comb[['elabel_stop_time', 'compton_stop']].min(axis=1) - df_comb[['elabel_start_time', 'compton_start']].max(axis=1))/(df_comb['compton_stop'] - df_comb['compton_start'])
  352. df_comb = df_comb.query('comptonmeas_in_elabel < 0.7')
  353. border_comptons = df_comb.compton_start.values
  354. combined_df.loc[combined_df.compton_start.isin(border_comptons),
  355. ['compton_start', 'compton_stop', 'e_mean', 'e_std', 'spread_mean', 'spread_std', 'luminosity']] = np.nan
  356. return combined_df
  357. def process_combined(combined_df: pd.DataFrame, runs_df: pd.DataFrame, compton_df: pd.DataFrame, pics_folder: Optional[str] = None, rdb: Optional[RunsDBHandler] = None, old_averager: bool = False, energy_point_csv_folder: Optional[str] = None) -> pd.DataFrame:
  358. if pics_folder is not None:
  359. plt.ioff()
  360. plt.style.use('ggplot')
  361. locator = mdates.AutoDateLocator(minticks=5)
  362. formatter = mdates.ConciseDateFormatter(locator)
  363. formatter.formats = ['%y', '%b', '%d', '%H:%M', '%H:%M', '%S.%f', ]
  364. formatter.zero_formats = [''] + formatter.formats[:-1]
  365. formatter.zero_formats[3] = '%d-%b'
  366. formatter.offset_formats = ['', '%Y', '%b %Y', '%d %b %Y', '%d %b %Y', '%d %b %Y %H:%M', ]
  367. runs_df = runs_df.rename({'luminosity': 'luminosity_full', 'energy': 'elabel'}, axis=1)
  368. combined_df = pd.merge(combined_df.drop(['elabel'], axis=1), runs_df[['run', 'elabel', 'luminosity_full']], how='outer')
  369. combined_df = combined_df.sort_values(by='run')
  370. combined_df['point_idx'] = np.cumsum(~np.isclose(combined_df.elabel, combined_df.elabel.shift(1), atol=1e-4))
  371. combined_df = process_intersected_compton_meas(combined_df)
  372. combined_df['luminosity'] = combined_df['luminosity'].fillna(0)
  373. # combined_df.to_csv('file.csv')
  374. combined_df = combined_df.groupby(['point_idx', 'compton_start'], dropna=False).agg(
  375. elabel=('elabel', 'min'), elabel_test=('elabel', 'max'),
  376. run_first=('run', 'min'), run_last=('run', 'max'),
  377. luminosity=('luminosity', 'sum'), luminosity_total=('luminosity_full', 'sum'),
  378. compton_stop=('compton_stop', 'min'), compton_stop_test=('compton_stop', 'max'),
  379. e_mean=('e_mean', 'min'), e_mean_test=('e_mean', 'max'),
  380. e_std=('e_std', 'min'), e_std_test=('e_std', 'max'),
  381. spread_mean=('spread_mean', 'min'), spread_mean_test=('spread_mean', 'max'),
  382. spread_std=('spread_std', 'min'), spread_std_test=('spread_std', 'max'),
  383. ).reset_index().set_index('point_idx')
  384. #return combined_df
  385. result_df = pd.DataFrame(columns=['energy_point', 'first_run', 'last_run', 'mean_energy', 'mean_energy_stat_err', 'mean_energy_sys_err', 'mean_spread', 'mean_spread_stat_err', 'used_lum', 'comment'])
  386. for i, table in tqdm(combined_df.groupby('point_idx', dropna=False)):
  387. try:
  388. res_dict, good_df = calculate_point(table, runs_df, compton_df, rdb, averager_on_lums if old_averager else ultimate_averager)
  389. if energy_point_csv_folder is not None:
  390. save_columns = ['elabel', 'run_first', 'run_last', 'luminosity', 'compton_start', 'compton_stop', 'e_mean', 'e_std', 'spread_mean', 'spread_std', 'accepted']
  391. save_csv(good_df[save_columns].dropna(), f'{energy_point_csv_folder}/{res_dict["energy_point"]}_{res_dict["first_run"]}.csv', update_current=False)
  392. good_df = good_df.query('accepted==1')
  393. except Exception:
  394. continue
  395. result_df = result_df.append(res_dict, ignore_index=True)
  396. if pics_folder is not None:
  397. plt_table = good_df.dropna()
  398. if len(plt_table) == 0:
  399. continue
  400. total_error = np.sqrt(res_dict["mean_energy_stat_err"]**2 + res_dict["mean_energy_sys_err"]**2)
  401. half_timedelta = (plt_table.compton_stop - plt_table.compton_start)/2
  402. time = plt_table.compton_start + half_timedelta
  403. dlt0, total_time = timedelta(days=1), plt_table.compton_stop.max() - plt_table.compton_stop.min()
  404. timelim = [plt_table.compton_start.min() - 0.05*total_time, plt_table.compton_stop.max() + 0.05*total_time]
  405. fig, ax = plt.subplots(1, 1, dpi=120, tight_layout=True)
  406. ax.errorbar(time, plt_table.e_mean, xerr=half_timedelta, yerr=plt_table.e_std, fmt='.')
  407. ax.axhline(res_dict['mean_energy'], color='black', zorder=3, label='Mean')
  408. ax.fill_between(timelim,
  409. [res_dict['mean_energy'] - total_error]*2,
  410. [res_dict['mean_energy'] + total_error]*2, color='green', zorder=1, alpha=0.4)
  411. ax.tick_params(axis='x', labelrotation=45)
  412. ax.xaxis.set_major_locator(locator)
  413. ax.xaxis.set_major_formatter(formatter)
  414. ax.set(title=f'{res_dict["energy_point"]}, E = {res_dict["mean_energy"]:.3f} ± {res_dict["mean_energy_stat_err"]:.3f} ± {res_dict["mean_energy_sys_err"]:.3f} MeV',
  415. xlabel='Time, NSK', ylabel='Energy, [MeV]', xlim=timelim)
  416. plt.savefig(f'{pics_folder}/{res_dict["first_run"]}_{res_dict["energy_point"]}.png', transparent=True)
  417. plt.close()
  418. return result_df
  419. def final_table_to_clbrdb(df: pd.DataFrame, clbrdb: CalibrdbHandler, runs_df: pd.DataFrame, season: str):
  420. """Write good values from the averaged table into clbrdb
  421. """
  422. good_values = (df.comment=='')|((df.comment!='')&((df.mean_energy.astype(float) - df.energy_point).abs()<5))
  423. df_clbrdb = df.loc[good_values].drop(['comment', 'used_lum'], axis=1)
  424. df_clbrdb = pd.merge(df_clbrdb, runs_df[['run', 'starttime']], how='left', left_on='first_run', right_on='run').drop(['run'], axis=1)
  425. df_clbrdb = pd.merge(df_clbrdb, runs_df[['run', 'stoptime']], how='left', left_on='last_run', right_on='run').drop(['run'], axis=1)
  426. df_clbrdb = df_clbrdb.assign(writetime=lambda df: df['stoptime'])
  427. df_clbrdb = df_clbrdb[['writetime', 'starttime', 'stoptime',
  428. 'energy_point', 'first_run', 'last_run', 'mean_energy',
  429. 'mean_energy_stat_err', 'mean_energy_sys_err', 'mean_spread', 'mean_spread_stat_err']].values.tolist()
  430. clbrdb.insert(df_clbrdb, 'Misc', 'RunHeader', 'Compton_run_avg', 'Default', comment = season)
  431. clbrdb.commit()
  432. def save_csv(df: pd.DataFrame, filepath: str, update_current: bool = True):
  433. """Saves csv file. Updates current file in filepath if exists"""
  434. if (os.path.isfile(filepath) and update_current):
  435. df_current = pd.read_csv(filepath)
  436. df_current = df_current.append(df, ignore_index=True)
  437. df_current = df_current.drop_duplicates(subset=['energy_point', 'first_run'], keep='last')
  438. df = df_current
  439. df.to_csv(filepath, index=False, float_format='%g')
  440. return
  441. # python scripts/compton_combiner.py -s NNBAR2021 -c database.ini --csv_dir . --clbrdb
  442. def main():
  443. log_format = '[%(asctime)s] %(levelname)s: %(message)s'
  444. logging.basicConfig(stream=sys.stdout, format=log_format, level=logging.INFO) #"filename=compton_combiner.log"
  445. logging.info("compton_combiner is started")
  446. parser = argparse.ArgumentParser(description = 'Mean compton energy measurements from clbrdb')
  447. parser.add_argument('-s', '--season', help = 'Name of the season')
  448. parser.add_argument('-c', '--config', help = 'Config file containing information for access to databases')
  449. parser.add_argument('--csv_dir', help = 'Save csv file with data in the folder or not if skip it')
  450. parser.add_argument('--clbrdb', action = 'store_true', help = 'Update Compton_run_avg clbrdb or not')
  451. parser.add_argument('--pics_folder', help = 'Path to the directory for saving the pictures')
  452. parser.add_argument('--energy_point_csv_folder', help = 'Path to the directory for saving the result in detail for each energy point')
  453. parser.add_argument('--only_last', action = 'store_true', help = 'Compute values of the last (in Compton_run_avg clbrdb) and new points only')
  454. parser.add_argument('--old_averaging', action = 'store_true', help = 'Use old incomplete <E> = \frac{\sum{L_i E_i}{\sum{L_i}} averaging')
  455. args = parser.parse_args()
  456. logging.info(f"""Arguments: season {args.season}, config {args.config}, csv_dir {args.csv_dir}, save_to_clbrdb {args.clbrdb},
  457. pics_folder {args.pics_folder}, detailed_csv_folder {args.energy_point_csv_folder}, only_last {args.only_last}, old_average: {args.old_averaging}""")
  458. parser = ConfigParser()
  459. parser.read(args.config);
  460. rdb = RunsDBHandler(**parser['cmdruns'])
  461. clbrdb = CalibrdbHandler(**parser['clbrDB'])
  462. idx = SEASONS['name'].index(args.season)
  463. runs_range = (SEASONS['start_run'][idx], SEASONS['start_run'][idx+1])
  464. if args.only_last:
  465. res_avg = clbrdb.load_table('Misc', 'RunHeader', 'Compton_run_avg', num_last_rows = 1)
  466. if len(res_avg[0]) != 0:
  467. begintime = res_avg[0][0][res_avg[1].index("begintime")]
  468. runs_range = (begintime, None)
  469. res_rdb = rdb.load_tables(runs_range)
  470. runs_df = pd.DataFrame(res_rdb[0], columns=res_rdb[1])
  471. tdlt0 = timedelta(days=2)
  472. time_range = (runs_df.starttime.min() - tdlt0, runs_df.stoptime.max() + tdlt0)
  473. res_clbrdb = clbrdb.load_table('Misc', 'RunHeader', 'Compton_run', num_last_rows = None, timerange = time_range)
  474. cb = Combiner(res_rdb, res_clbrdb)
  475. comb_df = cb.combined_table()
  476. compton_df = pd.DataFrame(res_clbrdb[0], columns=res_clbrdb[1])
  477. cdf = process_combined(comb_df, runs_df, compton_df, args.pics_folder, rdb, args.old_averaging, args.energy_point_csv_folder)
  478. if args.csv_dir is not None:
  479. csv_path = os.path.join(args.csv_dir, f'{args.season}.csv')
  480. save_csv(cdf, csv_path)
  481. # cdf.to_csv(f'{args.season}.csv', index=False, float_format='%g')
  482. if args.clbrdb:
  483. final_table_to_clbrdb(cdf, clbrdb, runs_df, args.season)
  484. return
  485. if __name__ == "__main__":
  486. main()