0
0

elabelizer.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """
  2. The script is for corresponding the elabels from database and compton average measurements
  3. run it on cc-8 with the command:
  4. `python3 elabelizer.py`
  5. If this script is not working properly, try to setup environment firstly with the following command in shell:
  6. `source /sl/cmd3/cc8-64/Cmd3Off/tune.cmd3_runs_scripts.sh`
  7. """
  8. import os
  9. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings_read_all')
  10. import django
  11. django.setup()
  12. from cmdweb.apps.cmd3off.energypoints.models import EnergyPoint, Param, ParamData
  13. from urllib.request import urlopen
  14. def retrieve_elabels(startrun, stoprun):
  15. """Retrieves elabels from database
  16. Parameters:
  17. -----------
  18. startrun : int
  19. first run for retrieving
  20. stoprun : int
  21. last run for retrieving
  22. Returns:
  23. --------
  24. List[Tuple[str, int, int, float, datetime, datetime]
  25. list of elabels and information about them
  26. (elabel, firstrun, lastrun, nominal energy, starttime, stoptime, season)
  27. """
  28. elabels = []
  29. season = ""
  30. for e in EnergyPoint.objects.all():
  31. if (e.name).startswith('Season'):
  32. season = e.name[7:]
  33. if e.startrun >= startrun and e.endrun <= stoprun:
  34. elabel_info = (e.name, e.startrun, e.endrun, e.energy, e.starttime, e.endtime, season)
  35. if (e.name).startswith('Season'):
  36. continue
  37. elabels.append(elabel_info)
  38. return elabels
  39. def get_available_compton_seasons():
  40. tables_url = 'https://cmd.inp.nsk.su/~compton/gitlist/compton_tables/raw/dev/tables/'
  41. with urlopen(tables_url) as f:
  42. data = f.read().decode('utf-8')
  43. datarows = list(map(lambda x: x[:-4], filter(lambda x: x.endswith('.csv'), data.split('\n'))))
  44. return datarows
  45. def retrieve_comptons(seasons=None):
  46. """Retrieves compton measurements from tables
  47. Parameters:
  48. -----------
  49. seasons: Optional[List[str]]
  50. list of seasons for retrieving
  51. (default is None, it means retrieving all available seasons)
  52. Returns:
  53. --------
  54. List[Tuple[str, float, int, int, float]]
  55. list of compton means measurements
  56. (season, energy_point, first_run, last_run, mean_energy)
  57. first_run and last_run can be different from the corresponding energy points from elabels database
  58. """
  59. available_seasons = get_available_compton_seasons()
  60. if seasons is not None:
  61. for s in seasons:
  62. if s not in available_seasons:
  63. raise ValueError(f"Season {s} is not found. List of available seasons: {available_seasons}")
  64. else:
  65. seasons = available_seasons
  66. def parse_compton_row(row, season):
  67. items = row.split(',')
  68. return (season, float(items[0]), int(items[1]), int(items[2]), float(items[3]))
  69. def retrieve_compton_one_season(season):
  70. with urlopen(f'https://cmd.inp.nsk.su/~compton/gitlist/compton_tables/raw/dev/tables/{season}.csv') as f:
  71. r = f.read().decode('utf-8').strip()
  72. rows = list(map(lambda x: parse_compton_row(x, season), r.split('\n')[1:]))
  73. return rows
  74. datarows = []
  75. for s in seasons:
  76. seasonrows = retrieve_compton_one_season(s)
  77. datarows.extend(seasonrows)
  78. return datarows
  79. def combine_compton_elabel(epoints, comptonpoints):
  80. """Combines compton energy points and elabels from database
  81. Parameters:
  82. -----------
  83. epoints : List[Tuple[...]]
  84. list of energy points
  85. comptonpoints : List[Tuple[...]]
  86. list of compton points
  87. Returns:
  88. --------
  89. combpoints : List[Tuple[...]]
  90. list of combined points (outer join)
  91. """
  92. epoints_sorted = sorted(epoints, key=lambda x: x[1])
  93. cpoints_sorted = sorted(comptonpoints, key=lambda x: x[2])
  94. combined_data = []
  95. eidx, cidx = 0, 0
  96. while (eidx < len(epoints_sorted)) and (cidx < len(cpoints_sorted)):
  97. erow = epoints_sorted[eidx]
  98. crow = cpoints_sorted[cidx]
  99. cstart, cstop, cenergy, cseason = crow[2], crow[3], crow[4], crow[0]
  100. estart, estop, elabel, eseason = erow[1], erow[2], erow[0], erow[6]
  101. if (cstart >= estart) and (cstop <= estop):
  102. combrow = (eseason, elabel, cenergy)
  103. eidx += 1
  104. cidx += 1
  105. #print(combrow)
  106. elif (cstart > estop):
  107. combrow = (eseason, elabel, None)
  108. eidx += 1
  109. elif (estart > cstop):
  110. combrow = (cseason, None, cenergy)
  111. cidx += 1
  112. else:
  113. raise Exception("Something wrong")
  114. #print(combrow)
  115. combined_data.append(combrow)
  116. for i in range(eidx, len(epoints_sorted)):
  117. erow = epoints_sorted[i]
  118. elabel = erow[0]
  119. combrow = (None, elabel, None)
  120. combined_data.append(combrow)
  121. for i in range(cidx, len(cpoints_sorted)):
  122. crow = cpoints_sorted[i]
  123. cstart, cstop, cenergy, cseason = crow[2], crow[3], crow[4], crow[0]
  124. combrow = (cseason, None, cenergy)
  125. combined_data.append(combrow)
  126. return combined_data
  127. def elabelize():
  128. RUNLIMITS = (17405, 200000)
  129. SEASONS = None
  130. epoints = retrieve_elabels(*RUNLIMITS)
  131. comptonpoints = retrieve_comptons(SEASONS)
  132. combdata = combine_compton_elabel(epoints, comptonpoints)
  133. return combdata
  134. def main():
  135. combdata = elabelize()
  136. for c in combdata:
  137. season, elabel, energy = c
  138. if season is None:
  139. season = ''
  140. if elabel is None:
  141. elabel = ''
  142. print(f'{season:>15s}, {elabel:>13s}, {energy}')
  143. print('The number of not found points in compton is', len(list(filter(lambda x: x[2] is None, combdata))))
  144. if __name__=="__main__":
  145. main()