noSQL_db_Prisma.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import datetime
  2. import pandas as pd
  3. import pymongo
  4. from config_info.config import *
  5. from file_reader.file_reader import FileReader
  6. # noinspection DuplicatedCode
  7. class NoSQLPrisma:
  8. __DB_URL = DB_URL
  9. __db_client = pymongo.MongoClient(__DB_URL)
  10. __prisma_db = __db_client["prisma-32_db"]
  11. def __init__(self, cluster, single_date):
  12. self.cluster = cluster
  13. if self.cluster == 1:
  14. self.cluster_n = ""
  15. else:
  16. self.cluster_n = '2'
  17. self.single_date = single_date
  18. self.__PATH_TO_PRISMA_N_DATA = f"D:\\PRISMA20\\P{self.cluster}"
  19. self.__PATH_TO_PRISMA_7d_DATA = f"D:\\PRISMA20\\P{self.cluster}\\n7"
  20. self.__PATH_TO_PRISMA_T_DATA = f"D:\\PRISMA20\\P{self.cluster}\\t\\"
  21. self.file_reader = FileReader(cluster=self.cluster, single_date=self.single_date,
  22. path_to_files=self.__PATH_TO_PRISMA_N_DATA,
  23. path_to_files_7d=self.__PATH_TO_PRISMA_7d_DATA)
  24. def __del__(self):
  25. pass
  26. def t_file_converter(self, path_to_t_file):
  27. """Converter for PRISMA t-files"""
  28. with open(
  29. f'{path_to_t_file}{self.cluster_n}t_{self.single_date.month:02}-{self.single_date.day:02}.{self.single_date.year - 2000:02}') as f:
  30. raw_data = f.readlines()
  31. raw_data = [line.rstrip() for line in raw_data]
  32. # Убираем переводы строки
  33. event_list = []
  34. main_list = []
  35. sep = 0
  36. for i in range(len(raw_data)):
  37. if raw_data[i] == '*#*':
  38. main_list.append(raw_data[sep].split(' '))
  39. event_list.append(raw_data[sep + 1:i])
  40. sep = i + 1
  41. unit_delay = []
  42. for item in event_list:
  43. delay_per_event = []
  44. for line in item:
  45. step = line.split(' ')
  46. for i in range(1, 17):
  47. if int(step[i]) != 0:
  48. delay_per_event.append([round(int(step[0]) * (10 ** (-4)), 4), i, int(step[i])])
  49. unit_delay.append(delay_per_event)
  50. plural_data_list = []
  51. for i in unit_delay:
  52. time_list = []
  53. detector_list = []
  54. neut_quantity_list = []
  55. for j in i:
  56. time_list.append(j[0])
  57. detector_list.append(j[1])
  58. neut_quantity_list.append(j[2])
  59. plural_data_list.append([time_list, detector_list, neut_quantity_list])
  60. for i in range(len(main_list)):
  61. main_list[i].extend(plural_data_list[i])
  62. t_file_df = pd.DataFrame(main_list,
  63. columns=['time', 'number', 'sum_n', 'trigger', 'time_delay', 'detectors',
  64. 'n_per_step'])
  65. t_file_df = t_file_df.astype({"time": float, "number": int, "sum_n": int, "trigger": int})
  66. return t_file_df
  67. def dinods_data_copier(self, event_datetime, trigger, det_params, dinode):
  68. try:
  69. new_record = {
  70. '_id': f'{event_datetime.date()}_{self.cluster:02}_{dinode:02}d_{int(event_datetime.hour):02}:' +
  71. f'{int(event_datetime.minute):02}:{int(event_datetime.second):02}.' +
  72. f'{str(event_datetime.microsecond)[:3]}.000.000',
  73. 'time_ns': int((int(event_datetime.hour) * 3600 + int(event_datetime.minute) * 60 + int(
  74. event_datetime.second)) * 10e8 + int(event_datetime.microsecond) * 1000),
  75. 'cluster': self.cluster,
  76. 'trigger': int(trigger),
  77. 'detectors': det_params
  78. }
  79. collection_prisma = NoSQLPrisma.__prisma_db[f'{str(event_datetime.date())}_{dinode}d']
  80. ins_result = collection_prisma.insert_one(new_record)
  81. print(f'Copied - {ins_result.inserted_id}')
  82. except pymongo.errors.DuplicateKeyError:
  83. print(f'Ошибка - {event_datetime.date()}-{event_datetime.time()}')
  84. def prisma_12d_past_data_copier(self):
  85. t_file = self.t_file_converter(path_to_t_file=self.__PATH_TO_PRISMA_T_DATA)
  86. n_file_today = self.file_reader.n_file_today.merge(t_file)
  87. self.make_parameters_from_df_12_d(n_file_today, self.single_date)
  88. if any(self.file_reader.n_file_day_after):
  89. n_file_day_after = self.file_reader.n_file_day_after.merge(t_file)
  90. self.make_parameters_from_df_12_d(n_file_day_after,
  91. self.single_date + datetime.timedelta(
  92. days=1))
  93. def prisma_7d_past_data_copier(self):
  94. self.make_parameters_from_df_7_d(self.file_reader.n7_file_today, self.single_date)
  95. if any(self.file_reader.n7_file_day_after):
  96. self.make_parameters_from_df_7_d(self.file_reader.n7_file_day_after,
  97. self.single_date + datetime.timedelta(days=1))
  98. def make_parameters_from_df_12_d(self, df, date):
  99. for index in range(len(df.index)):
  100. params = list(df.iloc[index])
  101. event_time = str(datetime.timedelta(seconds=params[0]))
  102. event_datetime = datetime.datetime(date.year, date.month, date.day,
  103. int(event_time.split(':')[0]),
  104. int(event_time.split(':')[1]), int(float(event_time.split(':')[2])),
  105. int(round(
  106. float(event_time.split(':')[2]) - int(
  107. float(event_time.split(':')[2])),
  108. 2) * 10 ** 6)) - datetime.timedelta(hours=4)
  109. trigger = params[3]
  110. amp = [int(params[j]) for j in range(4, 36, 2)]
  111. n = [int(params[j]) for j in range(5, 37, 2)]
  112. n_time_delay = params[36]
  113. detector = params[37]
  114. n_in_step = params[38]
  115. det_params = {}
  116. for i in range(1, 17):
  117. n_time_delay_by_det = []
  118. detector_index = [ind for ind, v in enumerate(detector) if v == i]
  119. for j in detector_index:
  120. n_time_delay_by_det.extend([n_time_delay[j]] * int(n_in_step[j]))
  121. # В БД будут оставаться пустые списки при нуле нейтронов, надо ли это фиксить?
  122. det_params[f'det_{i:02}'] = {
  123. 'amplitude': amp[i - 1],
  124. 'neutrons': n[i - 1],
  125. 'time_delay': n_time_delay_by_det
  126. }
  127. self.dinods_data_copier(event_datetime=event_datetime, trigger=trigger,
  128. det_params=det_params, dinode=12)
  129. return None
  130. def make_parameters_from_df_7_d(self, df, date):
  131. for index in range(len(df.index)):
  132. params = list(df.iloc[index])
  133. event_time = str(datetime.timedelta(seconds=params[0])) # перевод в utc-формат
  134. event_datetime = datetime.datetime(date.year, date.month, date.day,
  135. int(event_time.split(':')[0]),
  136. int(event_time.split(':')[1]), int(float(event_time.split(':')[2])),
  137. int(round(
  138. float(event_time.split(':')[2]) - int(
  139. float(event_time.split(':')[2])),
  140. 2) * 10 ** 6)) - datetime.timedelta(hours=4)
  141. trigger = params[2]
  142. amp = [int(params[j]) for j in range(3, 19)]
  143. det_params = {}
  144. for i in range(1, 17):
  145. det_params[f'det_{i:02}'] = {
  146. 'amplitude': amp[i - 1]
  147. }
  148. self.dinods_data_copier(event_datetime=event_datetime, trigger=trigger,
  149. det_params=det_params, dinode=7)
  150. return None
  151. # for index in range(len(n_file_today.index)):
  152. # params = list(n_file_today.iloc[index])
  153. # event_time = str(datetime.timedelta(seconds=params[0]))
  154. # event_datetime = datetime.datetime(self.single_date.year, self.single_date.month, self.single_date.day,
  155. # int(event_time.split(':')[0]),
  156. # int(event_time.split(':')[1]), int(float(event_time.split(':')[2])),
  157. # int(round(
  158. # float(event_time.split(':')[2]) - int(
  159. # float(event_time.split(':')[2])),
  160. # 2) * 10 ** 6)) - datetime.timedelta(hours=4)
  161. # if index >= bad_end_time_index:
  162. # new_date = self.single_date + datetime.timedelta(days=1)
  163. # event_datetime = datetime.datetime(new_date.year, new_date.month, new_date.day,
  164. # int(event_time.split(':')[0]),
  165. # int(event_time.split(':')[1]), int(float(event_time.split(':')[2])),
  166. # int(round(
  167. # float(event_time.split(':')[2]) - int(
  168. # float(event_time.split(':')[2])),
  169. # 2) * 10 ** 6)) - datetime.timedelta(hours=4)
  170. # trigger = params[3]
  171. # amp = [int(params[j]) for j in range(4, 36, 2)]
  172. # n = [int(params[j]) for j in range(5, 37, 2)]
  173. #
  174. # n_time_delay = params[36]
  175. # detector = params[37]
  176. # n_in_step = params[38]
  177. #
  178. # det_params = {}
  179. # for i in range(1, 17):
  180. # n_time_delay_by_det = []
  181. # detector_index = [ind for ind, v in enumerate(detector) if v == i]
  182. # for j in detector_index:
  183. # n_time_delay_by_det.extend([n_time_delay[j]] * int(n_in_step[j]))
  184. # # В БД будут оставаться пустые списки при нуле нейтронов, надо ли это фиксить?
  185. # det_params[f'det_{i:02}'] = {
  186. # 'amplitude': amp[i - 1],
  187. # 'neutrons': n[i - 1],
  188. # 'time_delay': n_time_delay_by_det
  189. # }