def get_settings_by_date(date_start, date_end): beamline = Beamline(url='http://cdb.mice.rl.ac.uk') channel = CoolingChannel(url='http://cdb.mice.rl.ac.uk') channel_data_dates = channel.get_all_coolingchannels() print "Getting cooling channel keys" for key in channel_data_dates.keys(): print type(key), key return print_heading() bl_data_dates = beamline.get_beamlines_for_dates(start_date, end_date) for run in range(run_start, run_end): channel_data, bl_data = None, None n_tries = 0 while channel_data == None and n_tries < 5: try: channel_data = channel.get_coolingchannel_for_run(run) except (cdb._exceptions.CdbPermanentError, KeyError, urllib2.URLError): n_tries += 1 time.sleep(5) continue while bl_data == None: try: bl_data = beamline.get_beamline_for_run(run)[run] except (cdb._exceptions.CdbPermanentError, KeyError, urllib2.URLError): n_tries += 1 time.sleep(5) continue if not is_channel_okay(bl_data, channel_data): continue print_run(bl_data, channel_data)
def get_settings_by_run(run_start, run_end, run_step, output, do_header = True): beamline = Beamline(url='http://cdb.mice.rl.ac.uk') channel = CoolingChannel(url='http://cdb.mice.rl.ac.uk') if do_header: print_heading(output) for run in range(run_start, run_end, run_step): #: channel_data, bl_data = None, None n_tries = 0 while channel_data == None and n_tries < 5: try: channel_data = channel.get_coolingchannel_for_run(run) print ".", sys.stdout.flush() except (cdb._exceptions.CdbPermanentError, KeyError, urllib2.URLError): print "Failed to get channel data for run", run, "... trying again", n_tries n_tries += 1 time.sleep(0.1) continue while bl_data == None and n_tries < 5: try: bl_data = beamline.get_beamline_for_run(run)[run] except (cdb._exceptions.CdbPermanentError, KeyError, urllib2.URLError): print "Failed to get bl data for run", run, "... trying again", n_tries n_tries += 1 time.sleep(0.1) continue if not is_channel_okay(bl_data, channel_data): print "Channel not okay for run", run continue print_run(bl_data, channel_data, output) sys.stdout.flush() time.sleep(1)
def __init__(self, args_in): self._BL = Beamline(_R_SERVER) # print self._BL self._CC = CoolingChannel(_R_SERVER) self.run_number = args_in.run_number self.ssu_on = args_in.ssu_on self.ssd_on = args_in.ssd_on self.both_ss = args_in.both_ss self.pretty = pprint.PrettyPrinter(indent=4) self.oldstd = sys.stdout self.pout = open(os.devnull, 'w')
class TrigInfo(): def __init__(self): self._bl = Beamline(_cdbServerUrl) self.beenin = False def get_trigger_counts(self, run_min, run_max): trigdict = {} blrunmin = self._bl.get_beamline_for_run(run_min) oldrunts = blrunmin[run_min]['start_time'] old_run_date = oldrunts.day #oldrunts = None run = run_min while run < run_max: try: blrun = self._bl.get_beamline_for_run(run) blscalers = blrun[run]['scalars'] runts = blrun[run]['start_time'] # date for this run run_date = runts.day print '++ RTS: N: O ',runts, type(runts), run_date, old_run_date
class QueryCDB: """ Handles CDB requuests """ def __init__(self, args_in): self._BL = Beamline(_R_SERVER) # print self._BL self._CC = CoolingChannel(_R_SERVER) self.run_number = args_in.run_number self.ssu_on = args_in.ssu_on self.ssd_on = args_in.ssd_on self.both_ss = args_in.both_ss self.pretty = pprint.PrettyPrinter(indent=4) self.oldstd = sys.stdout self.pout = open(os.devnull, 'w') def process_request(self): # if run number is specified, then just get the info for the run if self.run_number > 0: self.get_beamline_for_run() self.get_cc_for_run() # if cooling channel match is requested, then find runs if self.ssu_on or self.ssd_on or self.both_ss: self.get_runs_for_cc() def get_beamline_for_run(self): print '===== Beamline for Run# ', self.run_number blrun = self._BL.get_beamline_for_run(self.run_number) self.pretty.pprint(blrun) def get_cc_for_run(self): print '===== Cooling Channel for Run# ', self.run_number sys.stdout = self.pout ccrun = self._CC.get_coolingchannel_for_run(self.run_number) sys.stdout = None self.pretty.pprint(ccrun) def get_runs_for_cc(self): runlist = sorted(self._BL.get_run_numbers()) #### No cooling channel before run ~7100, so don't bother for run in runlist: if run < 7400: continue sys.stdout = self.pout ccrun = self._CC.get_coolingchannel_for_run(run) sys.stdout = self.oldstd for mag in ccrun: if mag['name'] == 'SSU': ssu_coils = mag['coils'] for coil in ssu_coils: if coil['name'] == 'SSU-C': ssu_c_current = coil['iset'] if mag['name'] == 'SSD': ssu_coils = mag['coils'] for coil in ssu_coils: if coil['name'] == 'SSD-C': ssd_c_current = coil['iset'] if self.ssu_on and ssu_c_current > 10.0: print '++++ SSU ON. Run# ', run self.pretty.pprint(ccrun) if self.ssd_on and ssd_c_current > 10.0: print '++++ SSD ON. Run# ', run self.pretty.pprint(ccrun) if self.both_ss and ssd_c_current > 10.0 and ssu_c_current > 10.0: print '++++ SSU and SSD ON. Run# ', run self.pretty.pprint(ccrun)
# Function to help collate infomation later: def add_key(dict, key, value): if not key in dict: dict[key] = value else: dict[key] += value ############################################################################### # Load CDB elements ############################################################################### print " Loading Beamline...", try: beamline = Beamline() except: print " ERROR" sys.exit() else: print " OK" print " Loading Cooling Channel...", try: channel = CoolingChannel() except: print " ERROR" sys.exit() else: print " OK"
import sys sys.path.insert(1, "/home/mice/MAUS/CDB/mice.cdb.client.api-python/src/") from cdb import Beamline from cdb import CoolingChannel from pprint import pprint from collections import defaultdict _BL = Beamline("http://cdb.mice.rl.ac.uk") _CC = CoolingChannel("http://cdb.mice.rl.ac.uk") _RUNMIN = int(sys.argv[1]) _RUNMAX = int(sys.argv[2]) print 'min: ', _RUNMIN, 'max: ', _RUNMAX tot_npart_26a = 0 tot_npart_26b = 0 tot_npart_26c = 0 tot_npart_27a = 0 tot_npart_27b = 0 tot_npart_27c = 0 tot_npart_28a = 0 tot_npart_28b = 0 tot_npart_28c = 0 tot_npart_29a = 0 tot_npart_29b = 0 tot_npart_29c = 0 tot_npart_14a = 0 tot_npart_14b = 0 tot_npart_14c = 0 tot_npart_14d = 0 tot_npart_14c = 0
def run(): """Fetch information from the configuration database This script will show you how to fetch information from the configuration database. It will run you through many of the steps so you can use this within your own macro. You will need to be able to see the configuration database, usually requiring an internet connection, to run this script. """ # This is used to nicely print python dictionaries pretty_print = pprint.PrettyPrinter(indent=4) print """ ********************************************************* ** Welcome to the verbose configuration DB demo script ** ********************************************************* First let's take a peak at what run information looks like for one run. Let's choose run 2873 since that's included within MAUS. We do this by first setting up the configuration DB interface: \tbeamline = Beamline() """ try: beamline = Beamline() calibration = Calibration() print """ which was easy enough. You can check that the beamline class was set up correctly by running: get_status()' which should return OK (returns: %s).' % beamline.get_status() So now let's get something useful. How about the setup our run: print beamline.get_beamline_for_run(2873) """ pretty_print.pprint(beamline.get_beamline_for_run(2873)) print """ """ print calibration.get_calibration_for_run('TOF1', 2873, 'tw') print """ We can also ask what the runs were for a certain date range: date0 = datetime.strptime("2009-01-01", "%Y-%m-%d") date1 = datetime.strptime("2010-12-12", "%Y-%m-%d") run_info = beamline.get_beamlines_for_dates(date0, date1) print run_info.keys() """ date0 = datetime.strptime("2011-12-02", "%Y-%m-%d") date1 = datetime.strptime("2011-12-12", "%Y-%m-%d") run_info = beamline.get_beamlines_for_dates(date0, date1) print run_info.keys() print """ where the .keys() stuff only prints the run number since the data- type is a dictionary. Let's say you want the magnet current for a certain run:" my_runs = beamline.get_beamline_for_run(2873)" print my_runs[2873]['magnets']['d1']['set_current']" """ my_runs = beamline.get_beamline_for_run(2873) print my_runs[2873]['magnets']['d1']['set_current'] print """ Lastly you can search by target pulses:' get_beamlines_for_pulses(565665,565864).keys() """ print beamline.get_beamlines_for_pulses(565665, 565864).keys() print """ and you can find more information about the configuration DB' interface by checking the interactive help on the python command line help(cdb) """ except cdb.CdbTemporaryError: sys.excepthook(*sys.exc_info()) print """
start_date = datetime.strptime("2016-12-04", "%Y-%m-%d") end_date = datetime.strptime("2016-12-07", "%Y-%m-%d") # Function to help collate infomation later: def add_key(dict, key, value): if not key in dict: dict[key] = value else: dict[key] += value ############################################################################### # Load CDB elements ############################################################################### print " Loading Beamline...", try: beamline = Beamline() except: print " ERROR" sys.exit() else: print " OK" print " Loading Cooling Channel...", try: channel = CoolingChannel() except: print " ERROR" sys.exit() else: print " OK"
import cdb from cdb import Beamline from pprint import pprint ########## MASTER CDB _MASTER_CDB = "http://172.16.246.25:8080" _PROD_CDB = "http://172.16.246.25:8080" #_BL = Beamline(_PROD_CDB) _BL = Beamline(_MASTER_CDB) ########## PREPROD CDB #_PREPROD_CDB = "http://preprodcdb.mice.rl.ac.uk" #_BL = BeamlineSuperMouse(_PREPROD_CDB) tags_list = _BL.list_tags() print "++++ List of Beamline Tags" pprint(sorted(tags_list)) #for _tag in ['PionReference-DS', '3-200+M3--Test1']: for _tag in sorted(tags_list): print print print tags_list.index( _tag), _tag #, _BL.get_beamline_for_tag(_tag).keys().index(_tag) settings = _BL.get_beamline_for_tag(_tag)[_tag] for key in settings: if key == 'magnets': mags = settings['magnets'] for a_mag in sorted(mags.keys()): print ' ', a_mag.ljust(5), str(mags[a_mag]).ljust(5) else: print key.ljust(20), str(settings[key]).ljust(5)
def __init__(#pylint: disable=C0103, R0903, R0912, R0913, R0914, R0915 self,newline='', file_path='', theta=0, deltaz=0, path_g4bl='', output_path='', run_number=0, \ get_magnet_currents_pa_cdb='', random_seed=0): """ - particles will be a dictionary filled by G4BL - pdgid masses are input to calculate total energy, masses are in MeV/C^2 """ self.particles = 0 self.pdgid_mass = {} self.pdgid_mass = {'211':139.5700, '-211':139.5700, '2212':938.27231, \ '-13':105.6584, '13':105.6584, '11':0.5109906, '-11':0.5109906, \ '22':0, '2112':939.5653, '14':0, '-14':0, '12':0, '-12':0, \ '1000010020':1875.6, '1000010030':2808.9, '1000020030':2808.30665, \ '1000080160':14895.10000, '1000020040':3727.417000, \ '1000060140':13043.93400, '1000030070': 6535.36500, \ '1000060120':11174.90000, '1000050100':9326.98900, \ '1000060130':12112.54500, '1000050110':10255.10100} #pylint: disable=C0103 try: off = open(file_path+'/MAY09-B1B2-positives.in',"r") except IOError as err: raise IOError(err) text = off.read() if str(get_magnet_currents_pa_cdb) in ['True']: try: beamline = Beamline() sf3 = open(output_path+'/key.txt',"w") sf3.close() for k, v in beamline.get_beamline_for_run(run_number).iteritems(): #pylint: disable = C0301 for k, v in v.iteritems(): if k == 'magnets': for k, v in v.iteritems(): newlines = str(k)+'\n' sff = open(output_path+'/key.txt',"r") text5 = sff.read() sff.close() sf2 = open(output_path+'/key.txt',"w") sf2.write(text5) sf2.write(newlines) sf2.close() if k == 'proton_absorber_thickness': newlines = str(k)+'\n' sff = open(output_path+'/key.txt',"r") text5 = sff.read() sff.close() sf2 = open(output_path+'/key.txt',"w") sf2.write(text5) sf2.write(newlines) sf2.close() line = [] for row in fileinput.input([output_path+'/key.txt']): line.append(row[:-1]) sf2.close() sf4 = open(output_path+'/value.txt',"w") sf4.close() for k, v in beamline.get_beamline_for_run(run_number).iteritems(): #pylint: disable = C0301 for k, v in v.iteritems(): if k == 'magnets': for k, v in v.iteritems(): if k in ['q1', 'q3']: for k, v in v.iteritems(): if k == 'set_current': v = v / 96 newlines = str(v)+'\n' sf5 = open(output_path+'/value.txt',"r") #pylint: disable = C0301 text6 = sf5.read() sf5.close() sf6 = open(output_path+'/value.txt',"w") #pylint: disable = C0301 sf6.write(text6) sf6.write(newlines) sf6.close() if k in ['q2']: for k, v in v.iteritems(): if k == 'set_current': v = - v / 96 newlines = str(v)+'\n' sf5 = open(output_path+'/value.txt',"r") #pylint: disable = C0301 text6 = sf5.read() sf5.close() sf6 = open(output_path+'/value.txt',"w") #pylint: disable = C0301 sf6.write(text6) sf6.write(newlines) sf6.close() if k in ['d2']: #pylint: disable = W0631 for k, v in v.iteritems(): #pylint: disable = W0631, C0301 if k == 'set_current': coeff = [39.59, -55.998, 256.914, -v] #pylint: disable = C0301 roots = numpy.roots(coeff) root = roots[2] newlines = str(root)[1:-4]+'\n' sf5 = open(output_path+'/value.txt',"r") #pylint: disable = C0301 text6 = sf5.read() sf5.close() sf6 = open(output_path+'/value.txt',"w") #pylint: disable = C0301 sf6.write(text6) sf6.write(newlines) sf6.close() if k in ['ds']: for k, v in v.iteritems(): if k == 'set_current': v = v / 174 newlines = str(v)+'\n' sf5 = open(output_path+'/value.txt',"r") #pylint: disable = C0301 text6 = sf5.read() sf5.close() sf6 = open(output_path+'/value.txt',"w") #pylint: disable = C0301 sf6.write(text6) sf6.write(newlines) sf6.close() if k in ['d1']: for k, v in v.iteritems(): if k == 'set_current': coeff = [39.59, -55.998, 256.914, -v] #pylint: disable = C0301 roots = numpy.roots(coeff) root = roots[2] newlines = str(root)[1:-4]+'\n' sf5 = open(output_path+'/value.txt',"r") #pylint: disable = C0301 text6 = sf5.read() sf5.close() sf6 = open(output_path+'/value.txt',"w") #pylint: disable = C0301 sf6.write(text6) sf6.write(newlines) sf6.close() if k == 'proton_absorber_thickness': newlines = str(v)+'\n' sf5 = open(output_path+'/value.txt',"r") text6 = sf5.read() sf5.close() sf6 = open(output_path+'/value.txt',"w") sf6.write(text6) sf6.write(newlines) sf6.close() line2 = [] for row in fileinput.input([output_path+'/value.txt']): line2.append(row[:-1]) sf6.close() sf7 = open(output_path+'/magnet_currents.txt',"w") sf7.close() for c, d in zip(line, line2): text2 = 'param {0}={1}'.format(c, d)+'\n' sf8 = open(output_path+'/magnet_currents.txt',"r") text10 = sf8.read() sf8.close() sf9 = open(output_path+'/magnet_currents.txt',"w") sf9.write(text10) sf9.write(text2) sf9.close() sf8 = open(output_path+'/magnet_currents.txt',"r") text3 = sf8.read() os.remove(output_path+'/key.txt') os.remove(output_path+'/value.txt') except cdb.CdbTemporaryError: sys.excepthook(*sys.exc_info()) print """ Failed to run - check network connection! """ try: sf = open(output_path+'/MAY09-B1B2-positives-param.in', "w") except IOError as err: raise IOError(err) sf.write(newline) sf.write('param random_seed='+str(random_seed)+'\n') sf.write(text3) sf.write(text) sf.close() off.close() else: try: sf = open(output_path+'/MAY09-B1B2-positives-param.in', "w") except IOError as err: raise IOError(err) sf.write(newline) sf.write('param random_seed='+str(random_seed)) sf.write(text) sf.close() off.close() g4bl_command_line_input = path_g4bl + '/g4bl ' + output_path + '/MAY09-B1B2-positives-param.in' #pylint: disable = C0301 try: call(g4bl_command_line_input, shell=True) except Exception: #pylint: disable = W0703 print('Error: Cannot execute G4Beamline.') try: of = open(output_path+'/G4BLoutput.txt',"r") except IOError as err: raise IOError(err) line = [] for row in fileinput.input([output_path+'/G4BLoutput.txt']): line.append(row) of.close() for i in range(3): line.pop(0) random.shuffle(line) self.particles = {} theta = math.radians(theta) for i in range(0, len(line)): element = [] for word in line[i].split(' '): element.append(word) px = float(element[3]) py = float(element[4]) pz = float(element[5]) rest_mass = self.pdgid_mass[str(element[7])] part_energy = math.sqrt(px**2+py**2+pz**2+rest_mass**2) try: key = 'entry'+str(i) self.particles[key] = dict(spin = dict(\ x = float(element[21]), y = float(element[22]), z = float(element[23]))) self.particles[key].update(position = dict(\ # x = math.cos(theta) * float(element[0]) + 392.39, # x = math.cos(theta) * float(element[0]) + 99.92, x = math.cos(theta) * float(element[0]), y = float(element[1]), z = math.sin(theta) * float(element[0]) + deltaz + 26.21)) self.particles[key].update(momentum = dict(\ x = math.cos(theta) * float(element[3]) - math.sin(theta) * float(element[5]), #pylint: disable = C0301 y = float(element[4]), z = math.sin(theta) * float(element[3]) + math.cos(theta) * float(element[5]))) #pylint: disable = C0301 self.particles[key].update(time = float(element[6]), \ particle_id = int(element[7])) self.particles[key].update(random_seed = random_seed+i, \ energy = part_energy) except IOError as err: print('Bad G4beamline file, not enough elements or empty file') raise IOError(err) with open('maus_beam_output.txt', 'w') as outfile: json.dump(self.particles, outfile) # for i in range(0, len(line)): # for j in range(i + 1, len(line)): ### if self.particles['entry' + str(i)]['random_seed']\ # == self.particles['entry' + str(j)]['random_seed']: # self.particles['entry' + str(j)]['random_seed']\ # =self.particles['entry' + str(j)]['random_seed']\ # +1 if(os.path.exists(output_path + '/magnet_currents.txt') == True): os.remove(output_path + '/magnet_currents.txt')
#from cdb import CoolingChannelSuperMouse from cdb import CoolingChannel from cdb import Beamline #_TEST_CDB = "http://preprodcdb.mice.rl.ac.uk" _R_CDB = "http://cdb.mice.rl.ac.uk" cc = CoolingChannel(_R_CDB) #_MASTER_CDB = "http://172.16.246.25:8080" #cc = CoolingChannelSuperMouse(_MASTER_CDB) bl = Beamline(_R_CDB) #print cc, help(cc), cc.get_name(), cc.get_server_host_name(), cc.get_version() ############################################################################ #print 'List' #rint cc.list_absorber_tags() #print 'Get' #print cc.get_absorber_for_tag('ABS-SOLID-EMPTY') print 'Get CCrun' print cc.get_coolingchannel_for_run(7929) print 'Get Absrun' print cc.get_absorber_for_run(7929) #print 'Get Beamline' #print bl.get_beamline_for_run(7929)
def __init__(self): self._bl = Beamline(_cdbServerUrl) self.beenin = False