rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
def __init__(self,cp,ifo):
def __init__(self,cp,ifo,timeref):
def __init__(self,cp,ifo): depIfoIniConfig = ifo+'config' self.depIfoDir = ifo+'_qscans_config' depQscanList = ['bg-rds-qscan', 'bg-seismic-qscan']
qscanConfig = string.strip(cp.get("fu-"+depQscan, depIfoIniConfig))
qscanConfig = self.fix_config_for_science_run( cp.get("fu-"+depQscan, depIfoIniConfig).strip(), timeref )
def __init__(self,cp,ifo): depIfoIniConfig = ifo+'config' self.depIfoDir = ifo+'_qscans_config' depQscanList = ['bg-rds-qscan', 'bg-seismic-qscan']
if opts.prepare_scan_ccin2p3: for ifo in cp.get("fu-remote-jobs","remote-ifos").strip().split(","): CCRemoteScans = prepareLyonRemoteScans(cp,ifo)
def __init__(self,cp,ifo): depIfoIniConfig = ifo+'config' self.depIfoDir = ifo+'_qscans_config' depQscanList = ['bg-rds-qscan', 'bg-seismic-qscan']
if ifo in cp.get("fu-remote-jobs","remote-ifos").strip().split(",") and timeListFile:
if ifo in cp.get("fu-remote-jobs","remote-ifos").strip().split(",") and timeListFile and CCRemoteScans:
def __init__(self,cp,ifo): depIfoIniConfig = ifo+'config' self.depIfoDir = ifo+'_qscans_config' depQscanList = ['bg-rds-qscan', 'bg-seismic-qscan']
if opts.prepare_scan_ccin2p3:
if opts.prepare_scan_ccin2p3 and CCRemoteScans:
def __init__(self,cp,ifo): depIfoIniConfig = ifo+'config' self.depIfoDir = ifo+'_qscans_config' depQscanList = ['bg-rds-qscan', 'bg-seismic-qscan']
frametype=__patchFrameTypeDef__(frametype,sngl.ifo,sngl.time)
def prepareChecklist(wikiFilename=None,wikiCoinc=None,wikiTree=None,file2URL=None): """ Method to prepare a checklist where data products are isolated in directory. """ endOfS5=int(875232014) wikiFileFinder=findFileType(wikiTree,wikiCoinc) # Check to see if wiki file with name already exists maxCount=0 while os.path.ex...
if int(gpstime)<=endOfS5:
if int(gpstime)<=endOfS5 or ifo=="V1":
def __patchFrameTypeDef__(frametype=None,ifo=None,gpstime=None): """ Temporary patch function, to adjust specfied frame type used in searching the filesystem for files to display in followup. """ if frametype == None: raise Exception, "input to __patchFrameTypeDef__ included a \ frametype argument specified as None\n" ...
tm = date.XLALGPSToUTC(date.LIGOTimeGPS(grb.time))
tm = date.XLALGPSToUTC(LIGOTimeGPS(grb.time))
coldef = create_col(coldict['nolong'])
if code>0:
if code>0 and len(err)>0:
def system_call(item, command, divert_output_to_log = True): """ Makes a system call. @params item: a text specifying the content of the text (e.g. number of the GRB the message is associated with) (see also 'info') @params command: the command to be executed on the bash @params divert_output_to_log: If this flag is se...
output, error = internal_call(cmdtmp)
code, output, error = external_call(cmdtmp)
def make_cvs_copy(self, files, dest_dir): """ Copies all the files given in the list 'files' to dest_dir and creates a file 'cvs_versions.txt' in dest_dir containing the actual CVS version of the files @param files: list of files to be copied from self.input_dir @param dest_dir: destination directory """
if cp.has_option('followup-plotmcmc','burnin'): burnin = string.strip(cp.get('followup-plotmcmc','burnin'))
if cp.has_option('fu-plotmcmc','burnin'): burnin = string.strip(cp.get('fu-plotmcmc','burnin'))
def __init__(self,job,coinc,cp,opts,dag,ifo,ifonames,p_nodes): pipeline.CondorDAGNode.__init__(self,job)
plot_routine = string.strip(cp.get('followup-plotmcmc','plot_routine')) executable = string.strip(cp.get('followup-plotmcmc','executable'))
plot_routine = string.strip(cp.get('fu-plotmcmc','plot_routine')) executable = string.strip(cp.get('fu-plotmcmc','executable'))
def __init__(self,job,coinc,cp,opts,dag,ifo,ifonames,p_nodes): pipeline.CondorDAGNode.__init__(self,job)
def fisher_rvs(mu, sigma, size=None):
def fisher_rvs(mu, sigma, size=1):
def fisher_rvs(mu, sigma, size=None): """ Return a random (polar, azimuthal) angle drawn from the Fisher distribution. Assume that the concentration parameter (kappa) is large so that we can use a Rayleigh distribution about the north pole and rotate it to be centered at the (polar, azimuthal) coordinate mu. Assume ka...
try: cPickle.dump(self.__backgroundDict__,file(pickleLocale,'w')) except: sys.stdout.write("Problem saving pickle of DQ information.") sys.stdout.write("Trying to place pickle in your home directory.")
if not backgroundPickle:
def createDQbackground(self,ifoEpochList=list(),pickleLocale=None): """ Two inputs a list of tuples (ifo,epochname) for each instrument. Also a place to save the potential pickle to for quick access later. """ if type(ifoEpochList) != type(list()): raise Exception, \ "Invalid input argument ifoEpochList,%s type(%s)"...
cPickle.dump(self.__backgroundDict__, file(home_dir()+"/"+os.path.basename(pickleLocale),'w'))
cPickle.dump(self.__backgroundDict__,file(pickleLocale,'w'))
def createDQbackground(self,ifoEpochList=list(),pickleLocale=None): """ Two inputs a list of tuples (ifo,epochname) for each instrument. Also a place to save the potential pickle to for quick access later. """ if type(ifoEpochList) != type(list()): raise Exception, \ "Invalid input argument ifoEpochList,%s type(%s)"...
sys.stdout.write("Really ignoring pickle generation now!\n")
sys.stdout.write("Problem saving pickle of DQ information.") sys.stdout.write("Trying to place pickle in your home directory.") try: cPickle.dump(self.__backgroundDict__, file(home_dir()+"/"+os.path.basename(pickleLocale),'w')) except: sys.stdout.write("Really ignoring pickle generation now!\n")
def createDQbackground(self,ifoEpochList=list(),pickleLocale=None): """ Two inputs a list of tuples (ifo,epochname) for each instrument. Also a place to save the potential pickle to for quick access later. """ if type(ifoEpochList) != type(list()): raise Exception, \ "Invalid input argument ifoEpochList,%s type(%s)"...
if paramnames(parnum)=='mchirp': return inj.mchirp if paramname(parnum)=='eta': return inj.eta if paramname(parnum)=='time': return inj.get_end() if paramname(parnum)=='phi0': return inj.phi0 if paramname(parnum)=='dist': return inj.distance if paramname(parnum)=='RA': return inj.longitude if paramname(parnum)=='dec': ...
if paramnames[parnum]=='mchirp': return inj.mchirp if paramnames[parnum]=='eta': return inj.eta if paramnames[parnum]=='time': return inj.get_end() if paramnames[parnum]=='phi0': return inj.phi0 if paramnames[parnum]=='dist': return inj.distance if paramnames[parnum]=='RA': return inj.longitude if paramnames[parnum]=='...
def getinjpar(inj,parnum): if paramnames(parnum)=='mchirp': return inj.mchirp if paramname(parnum)=='eta': return inj.eta if paramname(parnum)=='time': return inj.get_end() if paramname(parnum)=='phi0': return inj.phi0 if paramname(parnum)=='dist': return inj.distance if paramname(parnum)=='RA': return inj.longitude if...
if injection and getinjpar(injection,paramnames.index('mchirp'))<max(pos[:,paranmanes.index('mchirp')]) and getinjpar(injection,paramnames.index('mchirp'))>min(pos[:,paramnames.index('mchirp')]) and getinjpar(injection,paramnames.index('eta'))>min(pos[:,paramnames.index('eta')]) and getinjpar(injection,paramnames.index...
if injection and getinjpar(injection,paramnames.index('mchirp'))<max(pos[:,paramnames.index('mchirp')]) and getinjpar(injection,paramnames.index('mchirp'))>min(pos[:,paramnames.index('mchirp')]) and getinjpar(injection,paramnames.index('eta'))>min(pos[:,paramnames.index('eta')]) and getinjpar(injection,paramnames.index...
def plot2Dkernel(xdat,ydat,Nx,Ny): xax=linspace(min(xdat),max(xdat),Nx) yax=linspace(min(ydat),max(ydat),Ny) x,y=numpy.meshgrid(xax,yax) samp=array([xdat,ydat]) kde=stats.kde.gaussian_kde(samp) grid_coords = numpy.append(x.reshape(-1,1),y.reshape(-1,1),axis=1) z = kde(grid_coords.T) z = z.reshape(Nx,Ny) asp=xax.ptp()/y...
xmldoc,digest = ligolw_utils.load_fileobj(file)
xmldoc,digest = utils.load_fileobj(file)
def fromsegmentxml(file): """ Read a segmentlist from the file object file containing an xml segment table. """ xmldoc,digest = ligolw_utils.load_fileobj(file) seg_table = table.get_table(xmldoc,lsctables.SegmentTable.tableName) segs = segmentlist() for seg in seg_table: segs.append(segment(seg.start_time,seg.end_tim...
def fromsegmentcsvCSV(csvfile):
def fromsegmentcsv(csvfile):
def fromsegmentcsvCSV(csvfile): """ Read a segmentlist from the file object file containing a comma separated list of segments. """ def CSVLineToSeg(line): tstart, tend = map(int, line.split(',')) return segment(tstart, tend) segs = segmentlist([CSVLineToSeg(line) for line in csvfile]) return segs.coalesce()
exe = make_external_call('which ligolw_segment_query')[0] segment_cmd = ' '.join([exe,'--query-segments',\ '--database','--include-segments',flag,\ '--gps-start-time',str(start),\ '--gps-end-time',str(end)]) segxmlout,segerr = make_external_call(segment_cmd) segs = segmentlist() if not segerr: tmpfile = tempfile.Tem...
start = int(start) end = int(end) database_location = os.environ['S6_SEGMENT_SERVER'] connection = segmentdb_utils.setup_database(database_location) engine = query_engine.LdbdQueryEngine(connection) spec = flag.split(':') if len(spec) < 2 or len(spec) > 3: print >>sys.stderr, "Included segements...
def grab_segments(start,end,flag): """ Returns a segmentlist containing the segments during which the given flag was active in the given period. """ exe = make_external_call('which ligolw_segment_query')[0] #== construct segment query segment_cmd = ' '.join([exe,'--query-segments',\ '--database','--include-segments',fl...
print >>sys.stderr, "Warning: Call to ligolw_segment_query failed with "+\ "command:" print >>sys.stderr, "\n"+segment_cmd+"\n"
version = '*' segdefs = segmentdb_utils.expand_version_number(engine,(ifo,name,version,\ start,end,0,0)) segs = segmentdb_utils.query_segments(engine, 'segment', segdefs) segs = reduce(operator.or_, segs).coalesce()
def grab_segments(start,end,flag): """ Returns a segmentlist containing the segments during which the given flag was active in the given period. """ exe = make_external_call('which ligolw_segment_query')[0] #== construct segment query segment_cmd = ' '.join([exe,'--query-segments',\ '--database','--include-segments',fl...
"a60dt60dD": "real_4", "a90dt90dD": "real_4",
"a60rank": "real_4", "a90rank": "real_4",
def get_coincs_from_coire(self,files,stat='snr'): """ uses CoincInspiralUtils to get data from old-style (coire'd) coincs """ coincTrigs = CoincInspiralUtils.coincInspiralTable() inspTrigs = SnglInspiralUtils.ReadSnglInspiralFromFiles(files, \ mangle_event_id = True,verbose=None) statistic = CoincInspiralUtils.coincSta...
def populate_SkyLocTable(skyloctable,coinc,adt60,adt90,adt60dD60,adt90dD90,\
def populate_SkyLocTable(skyloctable,coinc,adt60,adt90,arank60,arank90,\
def populate_SkyLocTable(skyloctable,coinc,adt60,adt90,adt60dD60,adt90dD90,\ pt,grid_fname,skymap_fname=None): """ populate a row in a skyloctable """ row = skyloctable.RowType() row.end_time = coinc.time row.set_ifos(coinc.ifo_list) rhosquared = 0.0 for ifo in coinc.ifo_list: rhosquared += coinc.snr[ifo]*coinc.snr[if...
row.a60dt60dD = adt60dD60 row.a90dt90dD = adt90dD90
row.a60rank = arank60 row.a90rank = arank90
def populate_SkyLocTable(skyloctable,coinc,adt60,adt90,adt60dD60,adt90dD90,\ pt,grid_fname,skymap_fname=None): """ populate a row in a skyloctable """ row = skyloctable.RowType() row.end_time = coinc.time row.set_ifos(coinc.ifo_list) rhosquared = 0.0 for ifo in coinc.ifo_list: rhosquared += coinc.snr[ifo]*coinc.snr[if...
while True:
while areasize<len(np.asarray(toppoints)[:,3]):
def greedyBin2(posterior_array,par_bins,confidence_levels,par_names=None,injection=None): if par_names: par1_name,par2_name=par_names else: par1_name="Parameter 1" par2_name="Parameter 2" par1pos=posterior_array[:,0] par2pos=posterior_array[:,1] par1_bin,par2_bin=par_bins if injection: par1_injvalue,par2_injvalue=i...
self.coincs = [tuple(event.event_id for event in sorted(double, lambda a, b: cmp(a.ifo, b.ifo))) for double in CoincidentNTuples(eventlists, event_comparefunc, offset_instruments, thresholds, verbose = verbose)] self.coincs.sort()
self.coincs = sorted(tuple(event.event_id for event in sorted(double, lambda a, b: cmp(a.ifo, b.ifo))) for double in CoincidentNTuples(eventlists, event_comparefunc, offset_instruments, thresholds, verbose = verbose))
def get_coincs(self, eventlists, event_comparefunc, thresholds, verbose = False): # # has this node already been visited? if so, return the # answer we already know #
self.unused_coincs = reduce(lambda a, b: a & b, (component.unused_coincs for component in self.components)) | reduce(lambda a, b: a | b, (set(component.coincs) for component in self.components))
self.unused_coincs = reduce(lambda a, b: a | b, (set(component.get_coincs(eventlists, event_comparefunc, thresholds, verbose = verbose)) for component in self.components)) self.unused_coincs |= reduce(lambda a, b: a & b, (component.unused_coincs for component in self.components))
def get_coincs(self, eventlists, event_comparefunc, thresholds, verbose = False): # # has this node already been visited? if so, return the # answer we already know #
return re.sub(r"([+-]?[.0-9]+)[Ee]?([+-]?[0-9]+)", r"\1 \\times 10^{\2}", s)
m, e = floatpattern.match(s).groups() return r"%s \\times 10^{%d}" % (m, int(e))
def latexnumber(s): """ Convert a string of the form "d.dddde-dd" to "d.dddd \times 10^{-dd}" """ return re.sub(r"([+-]?[.0-9]+)[Ee]?([+-]?[0-9]+)", r"\1 \\times 10^{\2}", s)
mcmcfilelist += node.outputName'
mcmcfilelist += node.outputName
def __init__(self,job,coinc,cp,opts,dag,ifo,ifonames,p_nodes): pipeline.CondorDAGNode.__init__(self,job)
cp.set("fu-condor","mcmc", self.which("lalapps_spinspiral"))
cp.set("fu-condor","spinmcmc", self.which("lalapps_spinspiral"))
def __init__(self, configfile=None): cp = ConfigParser.ConfigParser() self.cp = cp self.time_now = "_".join([str(i) for i in time_method.gmtime()[0:6]]) self.ini_file=self.time_now + ".ini" home_base = home_dirs() # CONDOR SECTION NEEDED BY THINGS IN INSPIRAL.PY cp.add_section("condor") cp.set("condor","datafind",self...
cp.set("makeCheckListWiki","ini-file",self.ini_file)
cp.set("makeCheckListWiki","ini-file",os.path.abspath(self.ini_file))
def __init__(self, configfile=None): cp = ConfigParser.ConfigParser() self.cp = cp self.time_now = "_".join([str(i) for i in time_method.gmtime()[0:6]]) self.ini_file=self.time_now + ".ini" home_base = home_dirs() # CONDOR SECTION NEEDED BY THINGS IN INSPIRAL.PY cp.add_section("condor") cp.set("condor","datafind",self...
if trigger.chisq_h1 < 4 or trigger.chisq_l < 4:
if trigger.chisq_h1 < 4 or trigger.chisq_v < 4:
def get_signal_vetoes(trigger,bankq=0,bankn=0,autoq=0,auton=0,chiq=0,chin=0,sigmaVals = None,fResp = None): sbvs = {} q = bankq nhigh = bankn q2 = autoq nhigh2 = auton if trigger.chisq == 0: sbvs['BestNR1'] = 0 else: if trigger.chisq < 60: sbvs['BestNR1'] = trigger.snr else: sbvs['BestNR1'] = trigger.snr/((1 + (trigge...
df = float((event1.central_freq + 0.5*event1.bandwidth - event2.central_freq - 0.5*event2.bandwidth)/(event1.central_freq + 0.5*event1.bandwidth + event2.central_freq + 0.5*event2.bandwidth))
f_cut1 = event1.central_freq + event1.bandwidth / 2 f_cut2 = event2.central_freq + event2.bandwidth / 2 df = float((f_cut1 - f_cut2) / (f_cut1 + f_cut2))
def coinc_params_func(events, offsetvector): # # check for coincs that have been vetoed entirely # if len(events) < 2: return None params = {} # # zero-instrument parameters # params["nevents"] = (len(events),) # # one-instrument parameters # for event in events: prefix = "%s_" % event.ifo params["%ssnr2_chi2" %...
def get_coincparamsdistributions(xmldoc):
def get_coincparamsdistributions(xmldoc, seglists = None):
def get_coincparamsdistributions(xmldoc): coincparamsdistributions, process_id = ligolw_burca_tailor.coinc_params_distributions_from_xml(xmldoc, u"string_cusp_likelihood") return coincparamsdistributions
def load_likelihood_data(filenames, verbose = False):
def load_likelihood_data(filenames, seglists = None, verbose = False):
def load_likelihood_data(filenames, verbose = False): coincparamsdistributions = None for n, filename in enumerate(filenames): if verbose: print >>sys.stderr, "%d/%d:" % (n + 1, len(filenames)), xmldoc = utils.load_filename(filename, gz = (filename or "stdin").endswith(".gz"), verbose = verbose) if coincparamsdistribut...
coincparamsdistributions = get_coincparamsdistributions(xmldoc)
coincparamsdistributions = get_coincparamsdistributions(xmldoc, seglists = seglists)
def load_likelihood_data(filenames, verbose = False): coincparamsdistributions = None for n, filename in enumerate(filenames): if verbose: print >>sys.stderr, "%d/%d:" % (n + 1, len(filenames)), xmldoc = utils.load_filename(filename, gz = (filename or "stdin").endswith(".gz"), verbose = verbose) if coincparamsdistribut...
coincparamsdistributions += get_coincparamsdistributions(xmldoc)
coincparamsdistributions += get_coincparamsdistributions(xmldoc, seglists = seglists)
def load_likelihood_data(filenames, verbose = False): coincparamsdistributions = None for n, filename in enumerate(filenames): if verbose: print >>sys.stderr, "%d/%d:" % (n + 1, len(filenames)), xmldoc = utils.load_filename(filename, gz = (filename or "stdin").endswith(".gz"), verbose = verbose) if coincparamsdistribut...
pipeline.CondorDAGJob.__init__(self,self.__universe,self.__executable) self.setupJob(name=self.name,dir=dir,cp=cp,tag_base=tag_base)
self.setupJob(name=self.name,dir=dir,cp=cp,tag_base=tag_base)
def __init__(self,opts,cp,dir='',tag_base=''): """ """ self.__executable = string.strip(cp.get('fu-condor','plotmcmc')) self.name = os.path.split(self.__executable.rstrip('/'))[1] self.__universe = "vanilla"
os.path.join("bin", "search_volume_by_s1_s2"),
def run(self): # remove the automatically generated user env scripts for script in ["pylal-user-env.sh", "pylal-user-env.csh"]: log.info("removing " + script ) try: os.unlink(os.path.join("etc", script)) except: pass
self.FAR = -1
self.FAR = 99
def __init__(self): """ here are all the things we need """ #start with data needed for every coinc self.ifo_list = [] self.ifo_coincs = [] self.snr = {} self.gps = {} self.eff_distances = {} self.mass1 = {} self.mass2 = {} self.time = None self.FAR = -1 #this stuff is only needed for injections self.is_injection = ...
if ctab[0].false_alarm_rate is not None: coinc.set_FAR(ctab[0].false_alarm_rate)
def get_coincs_from_coinctable(self,files): """ read data from coinc tables (xml format) FIXME: currently assumes one coinc per file!!! """ for file in files: coinc = CoincData() xmldoc = utils.load_filename(file) sngltab = tab.get_table(xmldoc,lsctables.SnglInspiralTable.tableName) coinc.set_snr(dict((row.ifo, row.sn...
coincTrigs = CoincInspiralUtils.coincInspiralTable(inspTrigs,'snr')
statistic = CoincInspiralUtils.coincStatistic('snr',None,None) coincTrigs = CoincInspiralUtils.coincInspiralTable(inspTrigs,statistic)
def get_coincs_from_coire(self,files): """ uses CoincInspiralUtils to get data from old-style (coire'd) coincs """ coincTrigs = CoincInspiralUtils.coincInspiralTable() inspTrigs = SnglInspiralUtils.ReadSnglInspiralFromFiles(files, \ mangle_event_id = True,verbose=None) #note that it's hardcoded to use snr as the statis...
cacheSelected = cacheSelected.sieve(segment=segments.segment(math.floor(float(time)), math.ceil(float(time))))
if math.floor(float(time)) != math.ceil(float(time)): cacheSelected = cacheSelected.sieve(segment=segments.segment(math.floor(float(time)), math.ceil(float(time)))) else: cacheSelected = cacheSelected.sieve(segment=segments.segment(math.floor(float(time))-0.5, math.floor(float(time))+0.5))
def getParamsFromCache(fileName,type,ifo=None,time=None): qscanList = [] cacheList = lal.Cache.fromfile(open(fileName)) if not cacheList: return qscanList cacheSelected = cacheList.sieve(description=type,ifos=ifo) if time: cacheSelected = cacheSelected.sieve(segment=segments.segment(math.floor(float(time)), math.ceil(f...
if re.search( table_name+r'[.]', table_param ) is None:
if table_param.find( table_name+'.' ) == -1:
def __init__( self, table_name, table_param, param_ranges_opt, verbose = False ): """ Parse --param-ranges option. Creates self.param which is the table_name and the table_param appended together (with a '.') and self.param_ranges, which is a list of tuples that give the lower parameter value, whether it is an open or ...
def __init__(self, xmldoc, b_b_def, sb_b_def, si_b_def, sb_c_e_def, sb_c_n_def, si_c_e_def, si_c_n_def, process):
def __init__(self, xmldoc, b_b_def, sb_b_def, si_b_def, sb_c_e_def, sb_c_n_def, si_c_e_def, si_c_n_def, process, livetime_program):
def __init__(self, xmldoc, b_b_def, sb_b_def, si_b_def, sb_c_e_def, sb_c_n_def, si_c_e_def, si_c_n_def, process): # # store the process row #
self.burst_peak_time_window = 6.378140e6 / 299792458 * 1.25 if len(self.snglbursttable): self.burst_peak_time_window += max(self.snglbursttable.getColumnByName("duration")) self.coinc_peak_time_window = self.burst_peak_time_window + SimBurstUtils.burst_is_near_injection_window def bursts_near_peaktime(self,...
def bursts_near_peaktime(self, t, window):
def __init__(self, xmldoc, b_b_def, sb_b_def, si_b_def, sb_c_e_def, sb_c_n_def, si_c_e_def, si_c_n_def, process): # # store the process row #
within self.burst_peak_time_window of t.
within window seconds of t. This is not used to define any coincidences, only to provide a short list of burst events for use in more costly comparison tests.
def bursts_near_peaktime(self, t): """ Return a list of the burst events whose peak times are within self.burst_peak_time_window of t. """ return self.snglbursttable[bisect.bisect_left(self.snglbursttable, t - self.burst_peak_time_window):bisect.bisect_right(self.snglbursttable, t + self.burst_peak_time_window)]
return self.snglbursttable[bisect.bisect_left(self.snglbursttable, t - self.burst_peak_time_window):bisect.bisect_right(self.snglbursttable, t + self.burst_peak_time_window)] def coincs_near_peaktime(self, t):
return self.snglbursttable[bisect.bisect_left(self.snglbursttable, t - window):bisect.bisect_right(self.snglbursttable, t + window)] def coincs_near_peaktime(self, t, window):
def bursts_near_peaktime(self, t): """ Return a list of the burst events whose peak times are within self.burst_peak_time_window of t. """ return self.snglbursttable[bisect.bisect_left(self.snglbursttable, t - self.burst_peak_time_window):bisect.bisect_right(self.snglbursttable, t + self.burst_peak_time_window)]
which at least one burst event's peak time is within self.coinc_peak_time_window of t.
which at least one burst event's peak time is within window seconds of t. This is not used to define any coincidences, only to provide a short list of coinc events for use in more costly comparison tests.
def coincs_near_peaktime(self, t): """ Return a list of the (coinc_event_id, event list) tuples in which at least one burst event's peak time is within self.coinc_peak_time_window of t. """ # FIXME: this test does not consider the time slide # offsets that should be applied to the coinc, but for now # injections are d...
return [(coinc_event_id, events) for coinc_event_id, events in self.coincs if (t - self.coinc_peak_time_window <= events[-1].get_peak()) and (events[0].get_peak() <= t + self.coinc_peak_time_window)]
near_events = set(self.bursts_near_peaktime(t, window)) return [(coinc_event_id, events) for coinc_event_id, events in self.coincs if set(events) & near_events]
def coincs_near_peaktime(self, t): """ Return a list of the (coinc_event_id, event list) tuples in which at least one burst event's peak time is within self.coinc_peak_time_window of t. """ # FIXME: this test does not consider the time slide # offsets that should be applied to the coinc, but for now # injections are d...
Return False if the peak time of the injection sim lies within the time interval of burst. """ return SimBurstUtils.time_at_instrument(sim, burst.ifo) not in burst.get_period()
Return False (injection matches event) if an autocorrelation-width window centred on the injection is continuous with the time interval of the burst. """ tinj = SimBurstUtils.time_at_instrument(sim, burst.ifo) window = SimBurstUtils.stringcusp_autocorrelation_width / 2 return segments.segment(tinj - window, tinj + wind...
def StringCuspSnglCompare(sim, burst): """ Return False if the peak time of the injection sim lies within the time interval of burst. """ return SimBurstUtils.time_at_instrument(sim, burst.ifo) not in burst.get_period()
Return False if the peak time and centre frequency of sim lie within the time-frequency tile of burst. """ return StringCuspSnglCompare(sim, burst) or (sim.frequency not in burst.get_band())
Return False (injection matches event) if the peak time and centre frequency of sim lie within the time-frequency tile of burst. """ return (SimBurstUtils.time_at_instrument(sim, burst.ifo) not in burst.get_period()) or (sim.frequency not in burst.get_band())
def ExcessPowerSnglCompare(sim, burst): """ Return False if the peak time and centre frequency of sim lie within the time-frequency tile of burst. """ return StringCuspSnglCompare(sim, burst) or (sim.frequency not in burst.get_band())
Return False if the peak time and centre frequency of sim lie within the time-frequency tile of burst.
Return False (injection matches event) if the time of the sim and the peak time of the burst event differ by less than or equal to delta_t seconds.
def OmegaSnglCompare(sim, burst, delta_t = 10.0): """ Return False if the peak time and centre frequency of sim lie within the time-frequency tile of burst. """ return abs(float(SimBurstUtils.time_at_instrument(sim, burst.ifo) - burst.get_peak())) > delta_t
Return False if the peak time of the sim is "near" the burst event. """ return OmegaNearCoincCompare(sim, burst)
Return False (injection matches coinc) if the peak time of the sim is "near" the burst event. """ tinj = SimBurstUtils.time_at_instrument(sim, burst.ifo) window = SimBurstUtils.stringcusp_autocorrelation_width / 2 + SimBurstUtils.burst_is_near_injection_window return segments.segment(tinj - window, tinj + window).disjo...
def StringCuspNearCoincCompare(sim, burst): """ Return False if the peak time of the sim is "near" the burst event. """ return OmegaNearCoincCompare(sim, burst)
Return False if the peak time of the sim is "near" the burst event.
Return False (injection matches coinc) if the peak time of the sim is "near" the burst event.
def ExcessPowerNearCoincCompare(sim, burst): """ Return False if the peak time of the sim is "near" the burst event. """ return not SimBurstUtils.burst_is_near_injection(sim, burst.start_time, burst.start_time_ns, burst.duration, burst.ifo)
Return False if the peak time of the sim is "near" the burst event. """ start_time = burst.get_peak() - burst.duration / 2.0 return not SimBurstUtils.burst_is_near_injection(sim, start_time.seconds, start_time.nanoseconds, burst.duration, burst.ifo)
Return False (injection matches coinc) if the peak time of the sim is "near" the burst event. """ return OmegaSnglCompare(sim, burst, delta_t = 20.0 + burst.duration / 2)
def OmegaNearCoincCompare(sim, burst): """ Return False if the peak time of the sim is "near" the burst event. """ start_time = burst.get_peak() - burst.duration / 2.0 return not SimBurstUtils.burst_is_near_injection(sim, start_time.seconds, start_time.nanoseconds, burst.duration, burst.ifo)
def find_sngl_burst_matches(contents, sim, comparefunc): """ Scan the burst table for triggers matching sim. """ return [burst for burst in contents.bursts_near_peaktime(sim.get_time_geocent()) if not comparefunc(sim, burst)]
def find_sngl_burst_matches(contents, sim, comparefunc, sieve_window): """ Scan the burst table for triggers matching sim. sieve_window is used in a bisection search to quickly identify burst events within that many seconds of the injection's peak time at the geocentre; it should be larger than the greatest time diffe...
def find_sngl_burst_matches(contents, sim, comparefunc): """ Scan the burst table for triggers matching sim. """ return [burst for burst in contents.bursts_near_peaktime(sim.get_time_geocent()) if not comparefunc(sim, burst)]
def find_exact_coinc_matches(coincs, sim, comparefunc):
def find_exact_coinc_matches(coincs, sim, comparefunc, seglists):
def find_exact_coinc_matches(coincs, sim, comparefunc): """ Return a list of the coinc_event_ids of the burst<-->burst coincs in which all burst events match sim. """ # FIXME: this test does not consider the time slide offsets that # should be applied to the coinc, but for now injections are done # at zero lag so this...
in which all burst events match sim.
in which all burst events match sim and to which all instruments on at the time of the sim contributed events.
def find_exact_coinc_matches(coincs, sim, comparefunc): """ Return a list of the coinc_event_ids of the burst<-->burst coincs in which all burst events match sim. """ # FIXME: this test does not consider the time slide offsets that # should be applied to the coinc, but for now injections are done # at zero lag so this...
return [coinc_event_id for coinc_event_id, events in coincs if True not in (bool(comparefunc(sim, event)) for event in events)]
on_instruments = SimBurstUtils.on_instruments(sim, seglists) return set(coinc_event_id for coinc_event_id, events in coincs if on_instruments.issubset(set(event.ifo for event in events)) and not any(comparefunc(sim, event) for event in events))
def find_exact_coinc_matches(coincs, sim, comparefunc): """ Return a list of the coinc_event_ids of the burst<-->burst coincs in which all burst events match sim. """ # FIXME: this test does not consider the time slide offsets that # should be applied to the coinc, but for now injections are done # at zero lag so this...
return [coinc_event_id for coinc_event_id, events in coincs if False in (bool(comparefunc(sim, event)) for event in events)]
return set(coinc_event_id for coinc_event_id, events in coincs if not all(comparefunc(sim, event) for event in events))
def find_near_coinc_matches(coincs, sim, comparefunc): """ Return a list of the coinc_event_ids of the burst<-->burst coincs in which at least one burst event matches sim. """ # FIXME: this test does not consider the time slide offsets that # should be applied to the coinc, but for now injections are done # at zero la...
process = process
process = process, livetime_program = { "StringCusp": "StringSearch", "excesspower": "lalapps_power", "omega": None }[search]
si_c_n_def = si_c_n_def,
events = find_sngl_burst_matches(contents, sim, snglcomparefunc)
events = find_sngl_burst_matches(contents, sim, snglcomparefunc, burst_peak_time_window)
si_c_n_def = si_c_n_def,
coincs = contents.coincs_near_peaktime(sim.get_time_geocent()) coinc_event_ids = find_exact_coinc_matches(coincs, sim, snglcomparefunc) if coinc_event_ids: add_sim_coinc_coinc(contents, sim, coinc_event_ids, contents.sb_c_e_coinc_def_id) coinc_event_ids = find_near_coinc_matches(coincs, sim, nearcoinccomparefunc) if co...
coincs = contents.coincs_near_peaktime(sim.get_time_geocent(), coinc_peak_time_window) exact_coinc_event_ids = find_exact_coinc_matches(coincs, sim, snglcomparefunc, contents.seglists) near_coinc_event_ids = find_near_coinc_matches(coincs, sim, nearcoinccomparefunc) assert exact_coinc_event_ids.issubset(near_coinc_even...
si_c_n_def = si_c_n_def,
coincs = contents.coincs_near_peaktime(sim.get_time_geocent()) coinc_event_ids = find_exact_coinc_matches(coincs, sim, snglcomparefunc) if coinc_event_ids: add_sim_coinc_coinc(contents, sim, coinc_event_ids, contents.si_c_e_coinc_def_id) coinc_event_ids = find_near_coinc_matches(coincs, sim, nearcoinccomparefunc) if co...
coincs = contents.coincs_near_peaktime(sim.get_time_geocent(), coinc_peak_time_window) exact_coinc_event_ids = find_exact_coinc_matches(coincs, sim, snglcomparefunc, contents.seglists) near_coinc_event_ids = find_near_coinc_matches(coincs, sim, nearcoinccomparefunc) assert exact_coinc_event_ids.issubset(near_coinc_even...
si_c_n_def = si_c_n_def,
sys.stdout.write("Found: %s\n",publication_directory)
sys.stdout.write("Found: %s\n" %(publication_directory))
def __init__(self,type=None,ifo=None,time=None,snr=None,chisqr=None,mass1=None,mass2=None,mchirp=None): """ """ self.type=str(type) self.ifo=str(ifo) self.time=float(time) self.snr=float(snr) self.chisqr=float(chisqr) self.mass1=float(mass1) self.mass2=float(mass2) self.mchirp=float(mchirp)
sys.stdout.write("Found: %s\n",publication_url)
sys.stdout.write("Found: %s\n" %(publication_url))
def __init__(self,type=None,ifo=None,time=None,snr=None,chisqr=None,mass1=None,mass2=None,mchirp=None): """ """ self.type=str(type) self.ifo=str(ifo) self.time=float(time) self.snr=float(snr) self.chisqr=float(chisqr) self.mass1=float(mass1) self.mass2=float(mass2) self.mchirp=float(mchirp)
coincTrigs = CoincInspiralUtils.coincInspiralTable(inspTriggers,'snr')
coincTrigs = CoincInspiralUtils.coincInspiralTable(inspTrigs,'snr')
def get_coincs_from_coire(self,files): """ uses CoincInspiralUtils to get data from old-style (coire'd) coincs """ coincTrigs = CoincInspiralUtils.coincInspiralTable() inspTrigs = SnglInspiralUtils.ReadSnglInspiralFromFiles(files, \ mangle_event_id = True,verbose=None) #note that it's hardcoded to use snr as the statis...
CODEPOINTS = {\n\
def print_header(): print "\
print "],\nu'x%s':["%code[0],
if firsttime: firsttime = False print "CODEPOINTS = { \nu'x%s':["%code[0], else: print "],\nu'x%s':["%code[0],
def process_readings(): oucode = 0 olcode = 0 for line in open(source,'r'): items = line[:-1].split('\t') try: r = re.match(r'kKorea', items[1]) if r is not None: code = re.sub(r'U\+([0-9A-F]{2})([0-9A-F]{2})',r'\1\t\2',items[0]).split('\t') ucode = int(code[0],16) lcode = int(code[1],16) pron = items[2].split(' ')[0]...
print '"[?]",',
print "'',",
def process_readings(): oucode = 0 olcode = 0 for line in open(source,'r'): items = line[:-1].split('\t') try: r = re.match(r'kKorea', items[1]) if r is not None: code = re.sub(r'U\+([0-9A-F]{2})([0-9A-F]{2})',r'\1\t\2',items[0]).split('\t') ucode = int(code[0],16) lcode = int(code[1],16) pron = items[2].split(' ')[0]...
print '"'+pron+'",',
print "'"+pron+"',",
def process_readings(): oucode = 0 olcode = 0 for line in open(source,'r'): items = line[:-1].split('\t') try: r = re.match(r'kKorea', items[1]) if r is not None: code = re.sub(r'U\+([0-9A-F]{2})([0-9A-F]{2})',r'\1\t\2',items[0]).split('\t') ucode = int(code[0],16) lcode = int(code[1],16) pron = items[2].split(' ')[0]...
self.kakasi = CDLL("libkakasi")
self.kakasi = CDLL("\\kakasi\\lib\\kakasi")
def __init__(self): self.codepoints = CODEPOINTS self.codepoints.update(JACODES)
pmap = { ord(u'â'):'a',ord(u'à'):'a',ord(u'ắ'):'a',ord(u'ă'):'a',ord(u'ấ'):'a', ord(u'ü'):'u',ord(u'ụ'):'u',ord(u'ú'):'u',ord(u'ử'):'u',ord(u'ư'):'u', ord(u'ù'):'u', ord(u'é'):'e', ord(u'ọ'):'o',ord(u'ố'):'o',ord(u'ộ'):'o',ord(u'ơ'):'o',ord(u'ớ'):'o', ord(u'ớ'):'o', } r1 = re.compile(r'U\+([0-9A-F]{2})([0-9A-F]{2}\...
def process_readings(self, source, fout): oucode = 0
code = re.sub(r'U\+([0-9A-F]{2})([0-9A-F]{2}\b)',r'\1\t\2',items[0]).split('\t')
code = r1.sub(r'\1\t\2',items[0]).split('\t')
def process_readings(self, source, fout): oucode = 0
pron = items[2].split(' ')[0].capitalize() if not all(ord(c) < 128 for c in pron): pron = re.sub('[^\x00-\x7f]',lambda x: self.pmap[ord(x)], pron)
ptmp = items[2].split(' ')[0].capitalize() pron = re.sub('[^\00-\x7f]', lambda x: pmap[ord(x.group())], ptmp)
def process_readings(self, source, fout): oucode = 0
from ipdb import set_trace; set_trace() debug(title)
def main_upload(arguments): """Upload video to Youtube.""" usage = """Usage: %prog [OPTIONS] EMAIL PASSWORD FILE TITLE DESCRIPTION CATEGORY KEYWORDS Upload a video to youtube spliting it if necessary (uses ffmpeg).""" parser = optparse.OptionParser(usage, version=VERSION) parser.add_option('-c', '--get-categories', de...
password = (sys.stdin.read().strip() if password0 == "-" else password0)
password = (sys.stdin.readline().strip() if password0 == "-" else password0)
def main_upload(arguments): """Upload video to Youtube.""" usage = """Usage: %prog [OPTIONS] EMAIL PASSWORD FILE TITLE DESCRIPTION CATEGORY KEYWORDS Upload a video to youtube spliting it if necessary (uses ffmpeg).""" parser = optparse.OptionParser(usage, version=VERSION) parser.add_option('-c', '--get-categories', de...
sys.stderr.write("--- " + str(obj) + "\n")
string = str(obj.encode(get_encoding()) if isinstance(obj, unicode) else obj) sys.stderr.write("--- " + string + "\n") def get_encoding(): return sys.stdout.encoding or locale.getpreferredencoding()
def debug(obj): """Write obj to standard error.""" sys.stderr.write("--- " + str(obj) + "\n")
encoding = sys.stdout.encoding or locale.getpreferredencoding()
encoding = get_encoding()
def main_upload(arguments): """Upload video to Youtube.""" usage = """Usage: %prog [OPTIONS] EMAIL PASSWORD FILE TITLE DESCRIPTION CATEGORY KEYWORDS Upload a video to youtube spliting it if necessary (uses ffmpeg).""" parser = optparse.OptionParser(usage, version=VERSION) parser.add_option('-c', '--get-categories', de...
debug("kwargs = %s" % kwargs)
def main_upload(arguments): """Upload video to Youtube.""" usage = """Usage: %prog [OPTIONS] EMAIL PASSWORD FILE TITLE DESCRIPTION CATEGORY KEYWORDS Upload a video to youtube spliting it if necessary (uses ffmpeg).""" parser = optparse.OptionParser(usage, version=VERSION) parser.add_option('-c', '--get-categories', de...
status, v = STATUS.OK, specifier
status, v = STATUS.OK, obj.specifier
def execute_show_command (objs, db, tags, options): actions = { 'id': db.get_tag_value_by_id, 'about': db.get_tag_value_by_about, } for obj in objs: description = describe_by_mode (obj.specifier, obj.mode) print 'Object %s:' % description for tag in tags: fulltag = db.abs_tag_path (tag) if tag == '/id': if obj.mode ==...
o = db.create_object () self.assertEqual (type (o) != types.IntType, True) def testCreateObjectFail (self): bad = Credentials ('doesnotexist', 'certainlywiththispassword') db = FluidDB (bad) o = db.create_object ('DADGAD') self.assertEqual (o, STATUS.INTERNAL_SERVER_ERROR) def testCreateTag (self):
o = db.create_object() self.assertEqual(type(o) != types.IntType, True) def testCreateObjectFail(self): bad = Credentials('doesnotexist', 'certainlywiththispassword') db = FluidDB(bad) o = db.create_object('DADGAD') self.assertEqual(o, STATUS.UNAUTHORIZED) def testCreateTag(self):
def testCreateObjectNoAbout (self): db = self.db o = db.create_object () self.assertEqual (type (o) != types.IntType, True)
def frag_ranking(): global db_conn print """\ <a name=" <ol>\ """ curs = db_conn.cursor() curs.execute(''' select fragger, count(*) as frags from frags where fragger != fragged group by lower(fragger) order by count(*) desc, lower(fragger) asc ''') for row in curs: print " <li>%s (%s)</li>" % (row[0], row[1]) prin...
def frag_ranking(): global db_conn print """\ <a name="#3"><h2>Frag-based ranking</h2></a> <ol>\
<a name="
<a name="4"><h2>Frag/death ratio-based ranking</h2></a>
def fdratio_ranking(): global db_conn print """\ <a name="#4"><h2>Frag/death ratio-based ranking</h2></a> <ol>\
fdratio_ranking()
def main(): global db_conn if (len(sys.argv) < 2): sys.exit(1) create_db() if os.path.isdir(sys.argv[1]): for logrpath in os.listdir(sys.argv[1]): logfpath = ''.join([sys.argv[1], '/', logrpath]) parse_log(logfpath) else: parse_log(sys.argv[1]) print """\
ratios.append((players_row[0], float(frags_row[0]) / float(deaths_row[0])))
try: ratios.append((players_row[0], float(frags_row[0]) / float(deaths_row[0]))) except ZeroDivisionError: ratios.append((players_row[0], 666.0))
def fdratio_ranking(): global db_conn print """\ <a name="#4"><h2>Frag/death ratio-based ranking</h2></a> <ol>\
print " <li>%s (%i:%i:%i)</li>" % (row[0], int(row[1]) / 3600, int(row[1]) / 60, int(row[1]) % 60)
hours = int(row[1]) / 3600 minutes = (int(row[1]) - hours*3600) / 60 seconds = (int(row[1]) - minutes*60) % 60 print " <li>%s (%i:%i:%i)</li>" % (row[0], hours, minutes, seconds)
def presence_ranking(): global db_conn print """\ <a name="5"><h2>Presence-based ranking</h2></a> <ol>\
presence_ranking()
def main(): global db_conn if (len(sys.argv) < 2): sys.exit(1) create_db() if os.path.isdir(sys.argv[1]): for logrpath in os.listdir(sys.argv[1]): logfpath = ''.join([sys.argv[1], '/', logrpath]) parse_log(logfpath) else: parse_log(sys.argv[1]) print """\
db_conn.execute( '''update games set stop=? where player = ? and stop = -1''', (time, idd[m.group(3)])) del idd[m.group(3)]
try: db_conn.execute( '''update games set stop=? where player = ? and stop = -1''', (time, idd[m.group(3)])) del idd[m.group(3)] except KeyError: pass
def parse_log(logpath): global db_conn idd = {} logf = open(logpath, 'r') while 1: logline = logf.readline() if (not logline): break m = frag_prog.match(logline) if (m): # Update the frags table db_conn.execute( '''insert into frags values (?, ?, ?)''', (m.group(1), m.group(2), m.group(3))) continue m = playerjoins...
mime = self.getContentType() if mime.startswith("text"): return file(self._filePath, "r", BUFFER_SIZE)
def getContent(self): """Open content as a stream for reading. See DAVResource.getContent() """ assert not self.isCollection mime = self.getContentType() if mime.startswith("text"): return file(self._filePath, "r", BUFFER_SIZE) return file(self._filePath, "rb", BUFFER_SIZE)
object_to_etree(prop_set, set_props, namespace=namespace)
for p in set_props: prop_prop = ElementTree.SubElement(prop_set, '{DAV:}prop') object_to_etree(prop_prop, p, namespace=namespace)
def proppatch(self, path, set_props=None, remove_props=None, namespace='DAV:', headers=None): """Patch properties on a DAV resource. If namespace is not specified the DAV namespace is used for all properties""" root = ElementTree.Element('{DAV:}propertyupdate') if set_props is not None: prop_set = ElementTree.SubEleme...
object_to_etree(prop_remove, remove_props, namespace=namespace)
for p in remove_props: prop_prop = ElementTree.SubElement(prop_remove, '{DAV:}prop') object_to_etree(prop_prop, p, namespace=namespace)
def proppatch(self, path, set_props=None, remove_props=None, namespace='DAV:', headers=None): """Patch properties on a DAV resource. If namespace is not specified the DAV namespace is used for all properties""" root = ElementTree.Element('{DAV:}propertyupdate') if set_props is not None: prop_set = ElementTree.SubEleme...
lock["timeout"] = time.time() + timeout
if timeout < 0: lock["timeout"] = -1 else: lock["timeout"] = time.time() + timeout
def refresh(self, locktoken, timeout=None): """Set new timeout for lock, if existing and valid.""" if timeout is None: timeout = LockManager.LOCK_TIME_OUT_DEFAULT self._lock.acquireWrite() try: lock = self.getLock(locktoken) _logger.debug("refresh %s" % _lockString(lock)) if lock: lock["timeout"] = time.time() + timeou...
if (not self.wsgiSentHeaders):
if not self.wsgiSentHeaders:
def runWSGIApp (self, application, scriptName, pathInfo, query): logging.info ("Running application with SCRIPT_NAME %s PATH_INFO %s" % (scriptName, pathInfo)) if self.command == "PUT": pass # breakpoint env = {"wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": self.rfile, "wsgi.errors": sys.stderr, "ws...
def do_SHUTDOWN (self): """Send 200 OK response, and set server.stop to True. http://code.activestate.com/recipes/336012/ """ print "got SHUTDOWN" self.send_response(200) self.end_headers() self.server.stop = True
def do_SHUTDOWN (self): """Send 200 OK response, and set server.stop to True. http://code.activestate.com/recipes/336012/ """ print "got SHUTDOWN" self.send_response(200) self.end_headers() self.server.stop = True
assert hasattr(self, "stop"), "serve_forever_stoppable() must be called"
assert hasattr(self, "stop_request"), "serve_forever_stoppable() must be called before" assert not self.stop_request, "stop_serve_forever() must only be called once" self.stop_request = True time.sleep(.01) if self.stopped: return def _shutdownHandler(self): """Send 200 OK response, and set server.stop_request to ...
def stop_serve_forever(self): """Stop serve_forever_stoppable().""" assert hasattr(self, "stop"), "serve_forever_stoppable() must be called" (host, port) = self.server_address
self.stop = True print "stopping serve_forever_stoppable... Sending %s:%s/ SHUTDOWN" % (host, port)
def stop_serve_forever(self): """Stop serve_forever_stoppable().""" assert hasattr(self, "stop"), "serve_forever_stoppable() must be called" (host, port) = self.server_address
print "serve_forever_stoppable... stopped.", self.stop
assert self.stop_request
def stop_serve_forever(self): """Stop serve_forever_stoppable().""" assert hasattr(self, "stop"), "serve_forever_stoppable() must be called" (host, port) = self.server_address