source: branches/trigger_burst_research/sketch.py@ 18293

Last change on this file since 18293 was 18293, checked in by dneise, 9 years ago
debugging, special treatment of old aux-files (continue), and progressbar
File size: 4.2 KB
Line 
1# coding: utf-8
2import progressbar
3import calendar
4import numpy as np
5from astropy.io import fits
6import pandas as pd
7from sqlalchemy import create_engine
8
9night_int = 20150721
10
11
12def fjd(datetime_inst):
13 """ convert datetime instance to FJD
14 """
15 return calendar.timegm(datetime_inst.utctimetuple()) / (24.*3600.)
16
17def create_DB_connection():
18 from ConfigParser import SafeConfigParser
19 config = SafeConfigParser()
20 config.optionxform = str # this make the parsing case sensitive
21 config.read('config.ini')
22
23 factdb = create_engine(
24 "mysql+mysqldb://{user}:{pw}@{host}/{db}".format(
25 user=config.get('database', 'user'),
26 pw=config.get('database', 'password'),
27 host=config.get('database', 'host'),
28 db=config.get('database', 'database'),
29 )
30 )
31
32 return factdb
33
34
35def get_all_data_runs_from_run_db(factdb):
36 keys = [
37 'fRunID',
38 'fNight',
39 'fRunStart',
40 'fRunStop',
41 ]
42
43 sql_query = """SELECT {comma_sep_keys}
44 FROM RunInfo WHERE fRunTypeKey=1 ORDER BY fNight;
45 """
46 sql_query = sql_query.format(
47 comma_sep_keys=', '.join(keys),
48 )
49
50 data_runs = pd.read_sql_query(
51 sql_query,
52 factdb,
53 parse_dates=['fRunStart', 'fRunStop'],
54 )
55
56 return data_runs
57
58
59
60def get_trigger_rates(night_int, base_path='/fact/aux/'):
61 night_string = str(night_int)
62 fits_file = fits.open(
63 base_path+'{y}/{m}/{d}/{n}.FTM_CONTROL_TRIGGER_RATES.fits'.format(
64 n=night_string,
65 y=night_string[0:4],
66 m=night_string[4:6],
67 d=night_string[6:8],
68 )
69 )
70 trigger_rates = fits_file[1].data
71 return trigger_rates
72
73
74def add_ratio_and_more_to_dataframe(data_runs):
75
76 # create new columns and pre-assign some hopefully good NULL-like-values
77 data_runs['number_of_measurements'] = 0
78 data_runs['median_of_board_rates'] = np.nan
79 data_runs['std_dev_of_board_rates'] = np.nan
80 data_runs['fBoardTriggerRateRatioAboveThreshold'] = np.nan
81
82 trigger_rates = None
83 last_night = None
84
85 progress = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ',
86 progressbar.Percentage(), ' ',
87 progressbar.ETA()])
88
89 for dataframe_index in progress(data_runs.index):
90 this_run = data_runs.ix[dataframe_index]
91 if last_night != this_run['fNight']:
92 try:
93 trigger_rates = get_trigger_rates(this_run['fNight'])
94 except (IOError, ValueError):
95 continue
96 last_night = this_run['fNight']
97
98 mask = (
99 (trigger_rates['Time'] > fjd(this_run['fRunStart'])) *
100 (trigger_rates['Time'] < fjd(this_run['fRunStop']))
101 )
102
103 if mask.sum() == 0:
104 continue
105 try:
106 this_board_rates = trigger_rates['BoardRate'][mask]
107 except KeyError:
108 continue
109
110 N = this_board_rates.shape[0]
111 data_runs.ix[dataframe_index, 'number_of_measurements'] = N
112
113 left, med, right = np.percentile(
114 this_board_rates,
115 [50-20, 50, 50+20])
116 something_like_width = (right - left)/2.
117 # 40% of the area of the normal distrubution
118 # fall between -0.52*sigma and +0.52*sigma.
119 # The estimation of sigma in a distorted CDF
120 # is less affected near the median. (but of course less accurate as well.)
121 std_dev = something_like_width / 0.52
122
123 median_board_rates = np.median(this_board_rates, axis=1)
124 over = (median_board_rates > med+3*std_dev).sum()
125
126 data_runs.ix[dataframe_index, 'median_of_board_rates'] = med
127 data_runs.ix[dataframe_index, 'std_dev_of_board_rates'] = std_dev
128 data_runs.ix[dataframe_index, 'fBoardTriggerRateRatioAboveThreshold'] = float(over)/N
129
130def main(night_int):
131 factdb = create_DB_connection()
132 data_runs = get_all_data_runs_from_run_db(factdb)
133 add_ratio_and_more_to_dataframe(data_runs)
134 return data_runs
135
136if __name__ == '__main__':
137 data_runs = main(night_int)
138 data_runs.to_csv('foo.bar', index=False)
Note: See TracBrowser for help on using the repository browser.