elabelizer.py 6.1 KB

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