code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
macro = self.__bad_macro_chars.sub( r'', opt ) self.__opts['macro' + macro] = value self.__job.add_var_opt(opt,short)
def add_var_opt(self,opt,value,short=False)
Add a variable (macro) option for this node. If the option specified does not exist in the CondorJob, it is added so the submit file will be correct when written. @param opt: option name. @param value: value of the option for this node in the DAG.
14.654724
13.765989
1.06456
self.add_var_opt(opt,filename) if file_is_output_file: self.add_output_file(filename) else: self.add_input_file(filename)
def add_file_opt(self,opt,filename,file_is_output_file=False)
Add a variable (macro) option for this node. If the option specified does not exist in the CondorJob, it is added so the submit file will be correct when written. The value of the option is also added to the list of input files for the DAX. @param opt: option name. @param value: value of the option ...
2.455683
2.831261
0.867346
self.__args.append(arg) self.__job.add_var_arg(self.__arg_index) self.__arg_index += 1
def add_var_arg(self, arg)
Add a variable (or macro) argument to the condor job. The argument is added to the submit file and a different value of the argument can be set for each node in the DAG. @param arg: name of option to add.
4.229405
5.4252
0.779585
if isinstance(self.job(),CondorDAGManJob): # create an external subdag from this dag fh.write( ' '.join( ['SUBDAG EXTERNAL', self.__name, self.__job.get_sub_file()]) ) if self.job().get_dag_directory(): fh.write( ' DIR ' + self.job().get_dag_directory() ) else: # wri...
def write_job(self,fh)
Write the DAG entry for this node's job to the DAG file descriptor. @param fh: descriptor of open DAG file.
4.764735
4.757197
1.001585
if self.__macros.keys() or self.__opts.keys() or self.__args: fh.write( 'VARS ' + self.__name ) for k in self.__macros.keys(): fh.write( ' ' + str(k) + '="' + str(self.__macros[k]) + '"' ) for k in self.__opts.keys(): fh.write( ' ' + str(k) + '="' + str(self.__opts[k]) + '"' ) if ...
def write_vars(self,fh)
Write the variable (macro) options and arguments to the DAG file descriptor. @param fh: descriptor of open DAG file.
2.533703
2.408108
1.052155
for parent in self.__parents: fh.write( 'PARENT ' + str(parent) + ' CHILD ' + str(self) + '\n' )
def write_parents(self,fh)
Write the parent/child relations for this job to the DAG file descriptor. @param fh: descriptor of open DAG file.
4.786353
4.737715
1.010266
if self.__pre_script: fh.write( 'SCRIPT PRE ' + str(self) + ' ' + self.__pre_script + ' ' + ' '.join(self.__pre_script_args) + '\n' )
def write_pre_script(self,fh)
Write the pre script for the job, if there is one @param fh: descriptor of open DAG file.
4.584785
4.90026
0.935621
if self.__post_script: fh.write( 'SCRIPT POST ' + str(self) + ' ' + self.__post_script + ' ' + ' '.join(self.__post_script_args) + '\n' )
def write_post_script(self,fh)
Write the post script for the job, if there is one @param fh: descriptor of open DAG file.
5.05795
5.307136
0.953047
for f in self.__input_files: print >>fh, "## Job %s requires input file %s" % (self.__name, f)
def write_input_files(self, fh)
Write as a comment into the DAG file the list of input files for this DAG node. @param fh: descriptor of open DAG file.
6.409336
6.551511
0.978299
for f in self.__output_files: print >>fh, "## Job %s generates output file %s" % (self.__name, f)
def write_output_files(self, fh)
Write as a comment into the DAG file the list of output files for this DAG node. @param fh: descriptor of open DAG file.
6.920681
6.856596
1.009347
if not isinstance(node, (CondorDAGNode,CondorDAGManNode) ): raise CondorDAGNodeError, "Parent must be a CondorDAGNode or a CondorDAGManNode" self.__parents.append( node )
def add_parent(self,node)
Add a parent to this node. This node will not be executed until the parent node has run sucessfully. @param node: CondorDAGNode to add as a parent.
5.672045
4.259669
1.331569
# pattern to find DAGman macros pat = re.compile(r'\$\((.+)\)') argpat = re.compile(r'\d+') # first parse the options and replace macros with values options = self.job().get_opts() macros = self.get_opts() cmd_list = [] for k in options: val = options[k] m = pat.matc...
def get_cmd_tuple_list(self)
Return a list of tuples containg the command line arguments
2.460484
2.423735
1.015162
cmd = "" cmd_list = self.get_cmd_tuple_list() for argument in cmd_list: cmd += ' '.join(argument) + " " return cmd
def get_cmd_line(self)
Return the full command line that will be used when this node is run by DAGman.
5.549968
4.806186
1.154755
self.__maxjobs_categories.append((str(categoryName),str(maxJobsNum)))
def add_maxjobs_category(self,categoryName,maxJobsNum)
Add a category to this DAG called categoryName with a maxjobs of maxJobsNum. @param node: Add (categoryName,maxJobsNum) tuple to CondorDAG.__maxjobs_categories.
5.89253
3.94176
1.494898
if not isinstance(node, CondorDAGNode): raise CondorDAGError, "Nodes must be class CondorDAGNode or subclass" if not isinstance(node.job(), CondorDAGManJob): node.set_log_file(self.__log_file_path) self.__nodes.append(node) if self.__integer_node_names: node.set_name(str(self.__no...
def add_node(self,node)
Add a CondorDAGNode to this DAG. The CondorJob that the node uses is also added to the list of Condor jobs in the DAG so that a list of the submit files needed by the DAG can be maintained. Each unique CondorJob will be added once to prevent duplicate submit files being written. @param node: CondorDAGNo...
3.936541
3.506867
1.122524
fh.write( 'MAXJOBS ' + str(category[0]) + ' ' + str(category[1]) + '\n' )
def write_maxjobs(self,fh,category)
Write the DAG entry for this category's maxjobs to the DAG file descriptor. @param fh: descriptor of open DAG file. @param category: tuple containing type of jobs to set a maxjobs limit for and the maximum number of jobs of that type to run at once.
4.670476
4.037293
1.156834
if not self.__nodes_finalized: for node in self.__nodes: node.finalize() if not self.is_dax(): for job in self.__jobs: job.write_sub_file()
def write_sub_files(self)
Write all the submit files used by the dag to disk. Each submit file is written to the file name set in the CondorJob.
6.656119
5.66252
1.175469
if not self.__dag_file_path: raise CondorDAGError, "No path for DAG file" try: dagfile = open( self.__dag_file_path, 'w' ) except: raise CondorDAGError, "Cannot open file " + self.__dag_file_path for node in self.__nodes: node.write_job(dagfile) node.write_vars(dagfile...
def write_concrete_dag(self)
Write all the nodes in the DAG to the DAG file.
2.615949
2.457552
1.064453
if not self.__nodes_finalized: for node in self.__nodes: node.finalize() self.write_concrete_dag() self.write_abstract_dag()
def write_dag(self)
Write either a dag or a dax.
6.889574
6.10043
1.129359
if not self.__dag_file_path: raise CondorDAGError, "No path for DAG file" try: dfp = self.__dag_file_path outfilename = ".".join(dfp.split(".")[:-1]) + ".sh" outfile = open(outfilename, "w") except: raise CondorDAGError, "Cannot open file " + self.__dag_file_path for ...
def write_script(self)
Write the workflow to a script (.sh instead of .dag). Assuming that parents were added to the DAG before their children, dependencies should be handled correctly.
3.411317
3.229747
1.056218
return string.strip(self.__cp.get(sec,opt))
def get_config(self,sec,opt)
Get the configration variable in a particular section of this jobs ini file. @param sec: ini file section. @param opt: option from section sec.
9.958549
19.282688
0.51645
if pass_to_command_line: self.add_var_opt('gps-start-time',time) self.__start = time self.__data_start = time
def set_start(self,time,pass_to_command_line=True)
Set the GPS start time of the analysis node by setting a --gps-start-time option to the node when it is executed. @param time: GPS start time of job. @bool pass_to_command_line: add gps-start-time as variable option.
7.758195
5.00241
1.550891
if pass_to_command_line: self.add_var_opt('gps-end-time',time) self.__end = time self.__data_end = time
def set_end(self,time,pass_to_command_line=True)
Set the GPS end time of the analysis node by setting a --gps-end-time option to the node when it is executed. @param time: GPS end time of job. @bool pass_to_command_line: add gps-end-time as variable option.
8.194068
5.119496
1.600561
if pass_to_command_line: self.add_var_opt('trig-start-time',time) self.__trig_start = time
def set_trig_start(self,time,pass_to_command_line=True)
Set the trig start time of the analysis node by setting a --trig-start-time option to the node when it is executed. @param time: trig start time of job. @bool pass_to_command_line: add trig-start-time as a variable option.
5.776732
4.130532
1.398544
if pass_to_command_line: self.add_var_opt('trig-end-time',time) self.__trig_end = time
def set_trig_end(self,time,pass_to_command_line=True)
Set the trig end time of the analysis node by setting a --trig-end-time option to the node when it is executed. @param time: trig end time of job. @bool pass_to_command_line: add trig-end-time as a variable option.
5.806355
4.165947
1.393766
self.__input = filename if pass_to_command_line: self.add_var_opt('input', filename) self.add_input_file(filename)
def set_input(self,filename,pass_to_command_line=True)
Add an input to the node by adding a --input option. @param filename: option argument to pass as input. @bool pass_to_command_line: add input as a variable option.
4.976873
3.661685
1.359175
self.__output = filename if pass_to_command_line: self.add_var_opt('output', filename) self.add_output_file(filename)
def set_output(self,filename,pass_to_command_line=True)
Add an output to the node by adding a --output option. @param filename: option argument to pass as output. @bool pass_to_command_line: add output as a variable option.
5.017277
3.796753
1.321465
self.__ifo = ifo if self.job().channel(): self.add_var_opt('channel-name', ifo + ':' + self.job().channel())
def set_ifo(self,ifo)
Set the ifo name to analyze. If the channel name for the job is defined, then the name of the ifo is prepended to the channel name obtained from the job configuration file and passed with a --channel-name option. @param ifo: two letter ifo code (e.g. L1, H1 or H2).
12.285216
8.069546
1.522417
self.__ifo_tag = ifo_tag if pass_to_command_line: self.add_var_opt('ifo-tag', ifo_tag)
def set_ifo_tag(self,ifo_tag,pass_to_command_line=True)
Set the ifo tag that is passed to the analysis code. @param ifo_tag: a string to identify one or more IFOs @bool pass_to_command_line: add ifo-tag as a variable option.
3.907333
2.874672
1.359227
self.__user_tag = usertag if pass_to_command_line: self.add_var_opt('user-tag', usertag)
def set_user_tag(self,usertag,pass_to_command_line=True)
Set the user tag that is passed to the analysis code. @param user_tag: the user tag to identify the job @bool pass_to_command_line: add user-tag as a variable option.
4.527868
3.29073
1.375947
if isinstance( filename, str ): # the name of a lal cache file created by a datafind node self.add_var_opt('frame-cache', filename) self.add_input_file(filename) elif isinstance( filename, list ): # we have an LFN list self.add_var_opt('glob-frame-data',' ') # only add t...
def set_cache(self,filename)
Set the LAL frame cache to to use. The frame cache is passed to the job with the --frame-cache argument. @param filename: calibration file to use.
6.677631
6.44308
1.036403
if self.__ifo and self.__start > 0: cal_path = self.job().get_config('calibration','path') # check if this is S2: split calibration epochs if ( self.__LHO2k.match(self.__ifo) and (self.__start >= 729273613) and (self.__start <= 734367613) ): if self.__start < int( ...
def calibration_cache_path(self)
Determine the path to the correct calibration cache file to use.
7.183987
7.084875
1.013989
# figure out the name of the calibration cache files # as specified in the ini-file self.calibration_cache_path() if self.job().is_dax(): # new code for DAX self.add_var_opt('glob-calibration-data','') cache_filename=self.get_calibration() pat = re.compile(r'(file://.*)') ...
def calibration(self)
Set the path to the calibration cache file for the given IFO. During S2 the Hanford 2km IFO had two calibration epochs, so if the start time is during S2, we use the correct cache file.
6.363748
6.311714
1.008244
time_left = self.dur() - (2 * pad_data) start = self.start() + pad_data increment = length - overlap while time_left >= length: end = start + length if (not play) or (play and (((end-sl-excl_play-729273613) % 6370) < (600+length-2*excl_play))): if (play == 2): # ...
def make_chunks(self,length=0,overlap=0,play=0,sl=0,excl_play=0,pad_data=0)
Divides the science segment into chunks of length seconds overlapped by overlap seconds. If the play option is set, only chunks that contain S2 playground data are generated. If the user has a more complicated way of generating chunks, this method should be overriden in a sub-class. Any data at the end ...
4.890753
4.308412
1.135164
self.__chunks.append(AnalysisChunk(start,end,trig_start,trig_end))
def add_chunk(self,start,end,trig_start=0,trig_end=0)
Add an AnalysisChunk to the list associated with this ScienceSegment. @param start: GPS start time of chunk. @param end: GPS end time of chunk. @param trig_start: GPS start time for triggers from chunk
5.091681
4.135523
1.231206
self.__dur += self.__start - t self.__start = t
def set_start(self,t)
Override the GPS start time (and set the duration) of this ScienceSegment. @param t: new GPS start time.
11.701377
11.523734
1.015415
self.__dur -= self.__end - t self.__end = t
def set_end(self,t)
Override the GPS end time (and set the duration) of this ScienceSegment. @param t: new GPS end time.
12.700169
9.658842
1.314875
self.__filename = filename octothorpe = re.compile(r'\A#') for line in open(filename): if not octothorpe.match(line) and int(line.split()[3]) >= min_length: (id,st,en,du) = map(int,line.split()) # slide the data if doing a background estimation if slide_sec > 0: ...
def read(self,filename,min_length,slide_sec=0,buffer=0)
Parse the science segments from the segwizard output contained in file. @param filename: input text file containing a list of science segments generated by segwizard. @param min_length: only append science segments that are longer than min_length. @param slide_sec: Slide each ScienceSegment by:: ...
4.675964
4.314055
1.083891
self.__filename = filename for line in open(filename): columns = line.split() id = int(columns[0]) start = int(math.ceil(float(columns[3]))) end = int(math.floor(float(columns[4]))) dur = end - start x = ScienceSegment(tuple([id, start, end, dur])) self.__sci_segs...
def tama_read(self,filename)
Parse the science segments from a tama list of locked segments contained in file. @param filename: input text file containing a list of tama segments.
4.484526
4.31828
1.038498
for seg in self.__sci_segs: seg.make_chunks(length,overlap,play,sl,excl_play,pad_data)
def make_chunks(self,length,overlap=0,play=0,sl=0,excl_play=0,pad_data=0)
Divide each ScienceSegment contained in this object into AnalysisChunks. @param length: length of chunk in seconds. @param overlap: overlap between segments. @param play: if true, only generate chunks that overlap with S2 playground data. @param sl: slide by sl seconds before determining playground ...
4.152901
4.320646
0.961176
for seg in self.__sci_segs: # if there is unused data longer than the minimum chunk length if seg.unused() > min_length: end = seg.end() - pad_data start = end - length if (not play) or (play and (((end-sl-excl_play-729273613)%6370) < (600+length-2*excl_play))): ...
def make_chunks_from_unused(self,length,trig_overlap,play=0,min_length=0, sl=0,excl_play=0,pad_data=0)
Create an extra chunk that uses up the unused data in the science segment. @param length: length of chunk in seconds. @param trig_overlap: length of time start generating triggers before the start of the unused data. @param play: - 1 : only generate chunks that overlap with S2 playground...
4.489138
4.186742
1.072227
for seg in self.__sci_segs: if seg.unused() > min_length: start = seg.end() - seg.unused() - overlap end = seg.end() length = start - end if (not play) or (play and (((end-sl-excl_play-729273613)%6370) < (600+length-2*excl_play))): seg.add_chunk(start, en...
def make_short_chunks_from_unused( self,min_length,overlap=0,play=0,sl=0,excl_play=0)
Create a chunk that uses up the unused data in the science segment @param min_length: the unused data must be greater than min_length to make a chunk. @param overlap: overlap between chunks in seconds. @param play: if true, only generate chunks that overlap with S2 playground data. @param sl: slide ...
7.437428
7.009162
1.061101
for seg in self.__sci_segs: # pad data if requested seg_start = seg.start() + pad_data seg_end = seg.end() - pad_data if seg.unused() > max_length: # get number of max_length chunks N = (seg_end - seg_start)/max_length # split into chunks of max_length ...
def make_optimised_chunks(self, min_length, max_length, pad_data=0)
Splits ScienceSegments up into chunks, of a given maximum length. The length of the last two chunks are chosen so that the data utilisation is optimised. @param min_length: minimum chunk length. @param max_length: maximum chunk length. @param pad_data: exclude the first and last pad_data seconds of ...
3.407112
3.094042
1.101185
# we only deal with the case of two lists here length1 = len(self) length2 = len(other) # initialize list of output segments ostart = -1 outlist = [] iseg2 = -1 start2 = -1 stop2 = -1 for seg1 in self: start1 = seg1.start() stop1 = seg1.end() id = seg1.i...
def intersection(self, other)
Replaces the ScienceSegments contained in this instance of ScienceData with the intersection of those in the instance other. Returns the number of segments in the intersection. @param other: ScienceData to use to generate the intersection
3.908082
3.685652
1.06035
# we only deal with the case of two lists here length1 = len(self) length2 = len(other) # initialize list of output segments ostart = -1 seglist = [] i1 = -1 i2 = -1 start1 = -1 start2 = -1 id = -1 while 1: # if necessary, get a segment from list 1 if...
def union(self, other)
Replaces the ScienceSegments contained in this instance of ScienceData with the union of those in the instance other. Returns the number of ScienceSegments in the union. @param other: ScienceData to use to generate the intersection
3.110172
3.022725
1.02893
# check for an empty list if len(self) == 0: return 0 # sort the list of science segments self.__sci_segs.sort() # coalesce the list, checking each segment for validity as we go outlist = [] ostop = -1 for seg in self: start = seg.start() stop = seg.end() ...
def coalesce(self)
Coalesces any adjacent ScienceSegments. Returns the number of ScienceSegments in the coalesced list.
3.918746
3.324692
1.178679
# check for an empty list if len(self) == 0: # return a segment representing all time self.__sci_segs = ScienceSegment(tuple([0,0,1999999999,1999999999])) # go through the list checking for validity as we go outlist = [] ostart = 0 for seg in self: start = seg.start() ...
def invert(self)
Inverts the ScienceSegments in the class (i.e. set NOT). Returns the number of ScienceSegments after inversion.
3.75096
3.540337
1.059492
length = len(self) # initialize list of output segments ostart = -1 outlist = [] begin_s2 = 729273613 play_space = 6370 play_len = 600 for seg in self: start = seg.start() stop = seg.end() id = seg.id() # select first playground segment which ends after s...
def play(self)
Keep only times in ScienceSegments which are in the playground
5.775907
5.032286
1.14777
self.intersection(second) self.intersection(third) self.coalesce() return len(self)
def intersect_3(self, second, third)
Intersection routine for three inputs. Built out of the intersect, coalesce and play routines
6.818575
6.285823
1.084755
self.intersection(second) self.intersection(third) self.intersection(fourth) self.coalesce() return len(self)
def intersect_4(self, second, third, fourth)
Intersection routine for four inputs.
4.711135
4.732342
0.995519
outlist=[] for seg in self: start = seg.start() stop = seg.end() id = seg.id() while start < stop: tmpstop = start + dt if tmpstop > stop: tmpstop = stop elif tmpstop + dt > stop: tmpstop = int( (start + stop)/2 ) x = ScienceSegme...
def split(self, dt)
Split the segments in the list is subsegments at least as long as dt
5.057031
4.586995
1.102471
return itertools.izip(*[itertools.islice(lst, i, None, n) for i in range(n)])
def group(self, lst, n)
Group an iterable into an n-tuples iterable. Incomplete tuples are discarded
2.866298
3.286714
0.872086
path = self.__path cache = self.cache if type_regex: type_filter = re.compile(type_regex) else: type_filter = None f = open(path, 'r') # holds this iteration of the cache gwfDict = {} # parse each line in the cache file for line in f: # ignore lines that don...
def parse(self,type_regex=None)
Each line of the frame cache file is like the following: /frames/E13/LHO/frames/hoftMon_H1/H-H1_DMT_C00_L2-9246,H,H1_DMT_C00_L2,1,16 1240664820 6231 {924600000 924646720 924646784 924647472 924647712 924700000} The description is as follows: 1.1) Directory path of files 1.2) Site 1.3) Type 1....
4.664785
4.116253
1.13326
if self.__start and self.__end and self.__observatory and self.__type: self.__output = os.path.join(self.__job.get_cache_dir(), self.__observatory + '-' + self.__type +'_CACHE' + '-' + str(self.__start) + '-' + str(self.__end - self.__start) + '.lcf') self.set_output(self.__output)
def __set_output(self)
Private method to set the file to write the cache to. Automaticaly set once the ifo, start and end times have been set.
5.507526
4.254567
1.294498
if pad: self.add_var_opt('gps-start-time', int(time)-int(pad)) else: self.add_var_opt('gps-start-time', int(time)) self.__start = time self.__set_output()
def set_start(self,time,pad = None)
Set the start time of the datafind query. @param time: GPS start time of query.
5.467052
5.42152
1.008398
self.add_var_opt('gps-end-time', time) self.__end = time self.__set_output()
def set_end(self,time)
Set the end time of the datafind query. @param time: GPS end time of query.
17.262398
13.070239
1.320741
self.add_var_opt('observatory',obs) self.__observatory = str(obs) self.__set_output()
def set_observatory(self,obs)
Set the IFO to retrieve data for. Since the data from both Hanford interferometers is stored in the same frame file, this takes the first letter of the IFO (e.g. L or H) and passes it to the --observatory option of LSCdataFind. @param obs: IFO to obtain data for.
9.362496
11.379093
0.822781
self.add_var_opt('type',str(type)) self.__type = str(type) self.__set_output()
def set_type(self,type)
sets the frame type that we are querying
9.180828
9.652483
0.951136
if self.__dax: # we are a dax running in grid mode so we need to resolve the # frame file metadata into LFNs so pegasus can query the RLS if self.__lfn_list is None: if self.job().lsync_cache(): # get the lfns from the lsync cache object if self.__lfn_list is None...
def get_output(self)
Return the output file, i.e. the file containing the frame cache data. or the files itself as tuple (for DAX)
3.603511
3.5225
1.022998
if self.get_database() is None: raise ValueError, "no database specified" self.add_file_opt('extract', xml_file) self.__xml_output = xml_file
def set_xml_output(self, xml_file)
Tell ligolw_sqlite to dump the contents of the database to a file.
8.63958
7.70028
1.121983
if self.__xml_output: return self.__xml_output elif self.get_database(): return self.get_database() else: raise ValueError, "no output xml file or database specified"
def get_output(self)
Override standard get_output to return xml-file if xml-file is specified. Otherwise, will return database.
6.455957
4.205483
1.535129
contents = read(os.path.join(PATH_BASE, 'srptools', '__init__.py')) version = re.search('VERSION = \(([^)]+)\)', contents) version = version.group(1).replace(', ', '.').strip() return version
def get_version()
Reads version number. This workaround is required since __init__ is an entry point exposing stuff from other modules, which may use dependencies unavailable in current environment, which in turn will prevent this application from install.
4.715425
5.068604
0.93032
try: coincdeftable = lsctables.CoincDefTable.get_table(xmldoc) except ValueError: # table not found if not create_new: raise # FIXME: doesn't work if the document is stored in a # database. coincdeftable = lsctables.New(lsctables.CoincDefTable) xmldoc.childNodes[0].appendChild(coincdeftable) # ma...
def get_coinc_def_id(xmldoc, search, coinc_type, create_new = True, description = u"")
Wrapper for the get_coinc_def_id() method of the CoincDefiner table class in pycbc_glue.ligolw.lsctables. This wrapper will optionally create a new coinc_definer table in the document if one does not already exist.
3.764613
3.35257
1.122904
pattern = re.compile(r"-([\d.]+)-([\d.]+)\.[\w_+#]+\Z") l = segments.segmentlist() for name in filenames: [(s, d)] = pattern.findall(name.strip().rstrip(".gz")) s = coltype(s) d = coltype(d) l.append(segments.segment(s, s + d)) return l
def fromfilenames(filenames, coltype = int)
Return a segmentlist describing the intervals spanned by the files whose names are given in the list filenames. The segmentlist is constructed by parsing the file names, and the boundaries of each segment are coerced to type coltype. The file names are parsed using a generalization of the format described in Tec...
5.023582
4.444285
1.130346
return segments.segmentlist(lal.CacheEntry(l, coltype = coltype).segment for l in cachefile)
def fromlalcache(cachefile, coltype = int)
Construct a segmentlist representing the times spanned by the files identified in the LAL cache contained in the file object file. The segmentlist will be created with segments whose boundaries are of type coltype, which should raise ValueError if it cannot convert its string argument. Example: >>> from pycbc_...
16.688629
18.046688
0.924747
commentpat = re.compile(r"\s*([#;].*)?\Z", re.DOTALL) twocolsegpat = re.compile(r"\A\s*([\d.+-eE]+)\s+([\d.+-eE]+)\s*\Z") threecolsegpat = re.compile(r"\A\s*([\d.+-eE]+)\s+([\d.+-eE]+)\s+([\d.+-eE]+)\s*\Z") fourcolsegpat = re.compile(r"\A\s*([\d]+)\s+([\d.+-eE]+)\s+([\d.+-eE]+)\s+([\d.+-eE]+)\s*\Z") format = Non...
def fromsegwizard(file, coltype = int, strict = True)
Read a segmentlist from the file object file containing a segwizard compatible segment list. Parsing stops on the first line that cannot be parsed (which is consumed). The segmentlist will be created with segment whose boundaries are of type coltype, which should raise ValueError if it cannot convert its string a...
2.066205
2.013635
1.026107
if header: print >>file, "# seg\tstart \tstop \tduration" for n, seg in enumerate(seglist): print >>file, "%d\t%s\t%s\t%s" % (n, str(coltype(seg[0])), str(coltype(seg[1])), str(coltype(abs(seg))))
def tosegwizard(file, seglist, header = True, coltype = int)
Write the segmentlist seglist to the file object file in a segwizard compatible format. If header is True, then the output will begin with a comment line containing column names. The segment boundaries will be coerced to type coltype and then passed to str() before output.
3.009413
2.981226
1.009455
segmentpat = re.compile(r"\A\s*\S+\s+\S+\s+\S+\s+([\d.+-eE]+)\s+([\d.+-eE]+)") l = segments.segmentlist() for line in file: try: [tokens] = segmentpat.findall(line) l.append(segments.segment(map(coltype, tokens[0:2]))) except ValueError: break return l
def fromtama(file, coltype = lal.LIGOTimeGPS)
Read a segmentlist from the file object file containing TAMA locked-segments data. Parsing stops on the first line that cannot be parsed (which is consumed). The segmentlist will be created with segments whose boundaries are of type coltype, which should raise ValueError if it cannot convert its string argument. ...
4.468139
3.971426
1.125071
# preallocate segmentlist segs = segments.segmentlist([None] * len(ranges)) # iterate over strings for i, range in enumerate(ranges): parts = range.split(":") if len(parts) == 1: parts = boundtype(parts[0]) segs[i] = segments.segment(parts, parts) continue if len(parts) != 2: raise ValueError(r...
def from_range_strings(ranges, boundtype = int)
Parse a list of ranges expressed as strings in the form "value" or "first:last" into an equivalent pycbc_glue.segments.segmentlist. In the latter case, an empty string for "first" and(or) "last" indicates a (semi)infinite range. A typical use for this function is in parsing command line options or entries in conf...
2.1941
2.255303
0.972863
# preallocate the string list ranges = [None] * len(seglist) # iterate over segments for i, seg in enumerate(seglist): if not seg: ranges[i] = str(seg[0]) elif (seg[0] is segments.NegInfinity) and (seg[1] is segments.PosInfinity): ranges[i] = ":" elif (seg[0] is segments.NegInfinity) and (seg[1] is n...
def to_range_strings(seglist)
Turn a segment list into a list of range strings as could be parsed by from_range_strings(). A typical use for this function is in machine-generating configuration files or command lines for other programs. Example: >>> from pycbc_glue.segments import * >>> segs = segmentlist([segment(0, 10), segment(35, 35), ...
1.814654
1.955955
0.927758
return "/".join(["%s=%s" % (str(key), ",".join(to_range_strings(value))) for key, value in seglists.items()])
def segmentlistdict_to_short_string(seglists)
Return a string representation of a segmentlistdict object. Each segmentlist in the dictionary is encoded using to_range_strings() with "," used to delimit segments. The keys are converted to strings and paired with the string representations of their segmentlists using "=" as a delimiter. Finally the key=value ...
5.337222
3.848293
1.386906
d = segments.segmentlistdict() for token in s.strip().split("/"): key, ranges = token.strip().split("=") d[key.strip()] = from_range_strings(ranges.strip().split(","), boundtype = boundtype) return d
def segmentlistdict_from_short_string(s, boundtype = int)
Parse a string representation of a set of named segmentlists into a segmentlistdict object. The string encoding is that generated by segmentlistdict_to_short_string(). The optional boundtype argument will be passed to from_range_strings() when parsing the segmentlist objects from the string. Example: >>> segm...
4.261818
3.878368
1.098869
bitstream = iter(bitstream) i = 0 while 1: if bitstream.next(): # found start of True block; find the end j = i + 1 try: while bitstream.next(): j += 1 finally: # make sure StopIteration doesn't kill final segment if j - i >= minlen: yield segments.segment(start + i * dt, start + j...
def from_bitstream(bitstream, start, dt, minlen = 1)
Convert consecutive True values in a bit stream (boolean-castable iterable) to a stream of segments. Require minlen consecutive True samples to comprise a segment. Example: >>> list(from_bitstream((True, True, False, True, False), 0, 1)) [segment(0, 2), segment(3, 4)] >>> list(from_bitstream([[], [[]], [[]], []...
4.729568
4.23718
1.116206
lo = int(extent[0]) lo -= (lo - 729273613) % 6370 hi = int(extent[1]) + 1 return segments.segmentlist(segments.segment(t, t + 600) for t in range(lo, hi, 6370)) & segments.segmentlist([extent])
def S2playground(extent)
Return a segmentlist identifying the S2 playground times within the interval defined by the segment extent. Example: >>> from pycbc_glue import segments >>> S2playground(segments.segment(874000000, 874010000)) [segment(874000013, 874000613), segment(874006383, 874006983)]
7.958113
6.680253
1.191289
n = 1 b = start while True: a, b = b, start + n * period if b > stop: break yield segments.segment(a, b) n += 1
def segmentlist_range(start, stop, period)
Analogous to Python's range() builtin, this generator yields a sequence of continuous adjacent segments each of length "period" with the first starting at "start" and the last ending not after "stop". Note that the segments generated do not form a coalesced list (they are not disjoint). start, stop, and period ca...
3.48043
3.578401
0.972622
for seg in seglist2: yield (seglist1 & segments.segmentlist([seg])).shift(-seg[0])
def Fold(seglist1, seglist2)
An iterator that generates the results of taking the intersection of seglist1 with each segment in seglist2 in turn. In each result, the segment start and stop values are adjusted to be with respect to the start of the corresponding segment in seglist2. See also the segmentlist_range() function. This has use in...
10.964566
13.432073
0.816297
# check for no-op if n < 1: return segments.segmentlist() # digest the segmentlists into an ordered sequence of off-on and # on-off transitions with the vote count for each transition # FIXME: this generator is declared locally for now, is it useful # as a stand-alone generator? def pop_min(l): # remov...
def vote(seglists, n)
Given a sequence of segmentlists, returns the intervals during which at least n of them intersect. The input segmentlists must be coalesced, the output is coalesced. Example: >>> from pycbc_glue.segments import * >>> w = segmentlist([segment(0, 15)]) >>> x = segmentlist([segment(5, 20)]) >>> y = segmentlist([...
3.661258
3.716932
0.985022
# load the proxy from path try: proxy = M2Crypto.X509.load_cert(path) except Exception, e: msg = "Unable to load proxy from path %s : %s" % (path, e) raise RuntimeError(msg) # make sure the proxy is RFC 3820 compliant try: proxy.get_ext("proxyCertInfo") exce...
def validate_proxy(path)
Validate the users X509 proxy certificate Tests that the proxy certificate is RFC 3820 compliant and that it is valid for at least the next 15 minutes. @returns: L{True} if the certificate validates @raises RuntimeError: if the certificate cannot be validated
4.239997
3.933972
1.07779
rfc_proxy_msg = ("Could not find a RFC 3820 compliant proxy credential." "Please run 'grid-proxy-init -rfc' and try again.") # use X509_USER_PROXY from environment if set if os.environ.has_key('X509_USER_PROXY'): filePath = os.environ['X509_USER_PROXY'] if validat...
def find_credential()
Locate the users X509 certificate and key files This method uses the C{X509_USER_CERT} and C{X509_USER_KEY} to locate valid proxy information. If those are not found, the standard location in /tmp/ is searched. @raises RuntimeError: if the proxy found via either method cannot ...
2.73094
2.491545
1.096083
if os.environ.has_key(_server_env): host = os.environ[_server_env] port = None if re.search(':', host): host, port = host.split(':', 1) if port: port = int(port) return host, port else: raise RuntimeError("Environment variable...
def find_server()
Find the default server host from the environment This method uses the C{LIGO_DATAFIND_SERVER} variable to construct a C{(host, port)} tuple. @returns: C{(host, port)}: the L{str} host name and L{int} port number @raises RuntimeError: if the C{LIGO_DATAFIND_SERVER} environment variable ...
2.919298
2.687825
1.086119
try: self.request(method, url) response = self.getresponse() except Exception,e: raise RuntimeError("Unable to query server %s: %s\n\n" "Perhaps you need a valid proxy credential?\n" % (self.host, ...
def _requestresponse(self, method, url, body=None, headers={})
Internal method to perform request and verify reponse. @param method: name of the method to use (e.g. 'GET') @param url : remote URL to query @type method: L{str} @type url : L{str} @returns: L{str} response from server query @raises RuntimeError: if query is un...
3.520233
3.469559
1.014605
url = "%s/gwf.json" % _url_prefix response = self._requestresponse("GET", url) sitelist = sorted(set(decode(response.read()))) if match: regmatch = re.compile(match) sitelist = [site for site in sitelist if regmatch.search(site)] return sitelist
def find_observatories(self, match=None)
Query the LDR host for observatories. Use match to restrict returned observatories to those matching the regular expression. Example: >>> connection.find_observatories() ['AGHLT', 'G', 'GHLTV', 'GHLV', 'GHT', 'H', 'HL', 'HLT', 'L', 'T', 'V', 'Z'] >>> connection...
5.926875
7.091966
0.835717
if site: url = "%s/gwf/%s.json" % (_url_prefix, site[0]) else: url = "%s/gwf/all.json" % _url_prefix response = self._requestresponse("GET", url) typelist = sorted(set(decode(response.read()))) if match: regmatch = re.compile(match) ...
def find_types(self, site=None, match=None)
Query the LDR host for frame types. Use site to restrict query to given observatory prefix, and use match to restrict returned types to those matching the regular expression. Example: >>> connection.find_types("L", "RDS") ['L1_RDS_C01_LX', 'L1_RDS_C02_LX', 'L1...
3.943206
4.468084
0.882527
if gpsstart and gpsend: url = ("%s/gwf/%s/%s/segments/%s,%s.json" % (_url_prefix, site, frametype, gpsstart, gpsend)) else: url = ("%s/gwf/%s/%s/segments.json" % (_url_prefix, site, frametype)) response = self._requestrespon...
def find_times(self, site, frametype, gpsstart=None, gpsend=None)
Query the LDR for times for which frames are avaliable Use gpsstart and gpsend to restrict the returned times to this semiopen interval. @returns: L{segmentlist<pycbc_glue.segments.segmentlist>} @param site: single-character name of site to match @param frametype: ...
3.64783
3.61997
1.007696
if on_missing not in ("warn", "error", "ignore"): raise ValueError("on_missing must be 'warn', 'error', or 'ignore'.") framefile = os.path.basename(framefile) # parse file name for site, frame type try: site,frametype,_,_ = framefile.split("-") ex...
def find_frame(self, framefile, urltype=None, on_missing="warn")
Query the LDR host for a single framefile @returns: L{Cache<pycbc_glue.lal.Cache>} @param frametype: name of frametype to match @param urltype: file scheme to search for (e.g. 'file') @param on_missing: what to do when the requested frame isn't found...
5.113819
4.727964
1.081611
if on_gaps not in ("warn", "error", "ignore"): raise ValueError("on_gaps must be 'warn', 'error', or 'ignore'.") url = ("%s/gwf/%s/%s/%s,%s" % (_url_prefix, site, frametype, gpsstart, gpsend)) # if a URL type is specified append it to the path if urlty...
def find_frame_urls(self, site, frametype, gpsstart, gpsend, match=None, urltype=None, on_gaps="warn")
Find the framefiles for the given type in the [start, end) interval frame @param site: single-character name of site to match @param frametype: name of frametype to match @param gpsstart: integer GPS start time of query @param gpsend: ...
5.040274
4.941009
1.02009
for child in elem.childNodes: yield child for elem in WalkChildren(child): yield elem
def WalkChildren(elem)
Walk the XML tree of children below elem, returning each in order.
3.031852
2.796874
1.084014
parser = sax.make_parser() parser.setContentHandler(handler) parser.setFeature(sax.handler.feature_namespaces, True) parser.setFeature(sax.handler.feature_validation, False) parser.setFeature(sax.handler.feature_external_ges, False) return parser
def make_parser(handler)
Convenience function to construct a document parser with namespaces enabled and validation disabled. Document validation is a nice feature, but enabling validation can require the LIGO LW DTD to be downloaded from the LDAS document server if the DTD is not included inline in the XML. This requires a working conne...
1.747859
1.707878
1.02341
self.childNodes.append(child) child.parentNode = self self._verifyChildren(len(self.childNodes) - 1) return child
def appendChild(self, child)
Add a child to this element. The child's parentNode attribute is updated, too.
3.545719
3.462947
1.023902
for i, childNode in enumerate(self.childNodes): if childNode is refchild: self.childNodes.insert(i, newchild) newchild.parentNode = self self._verifyChildren(i) return newchild raise ValueError(refchild)
def insertBefore(self, newchild, refchild)
Insert a new child node before an existing child. It must be the case that refchild is a child of this node; if not, ValueError is raised. newchild is returned.
3.127913
3.029131
1.032611
for i, childNode in enumerate(self.childNodes): if childNode is child: del self.childNodes[i] child.parentNode = None return child raise ValueError(child)
def removeChild(self, child)
Remove a child from this element. The child element is returned, and it's parentNode element is reset. If the child will not be used any more, you should call its unlink() method to promote garbage collection.
2.697259
2.704301
0.997396
self.parentNode = None for child in self.childNodes: child.unlink() del self.childNodes[:]
def unlink(self)
Break internal references within the document tree rooted on this element to promote garbage collection.
4.301995
3.960409
1.08625
# .index() would use compare-by-value, we want # compare-by-id because we want to find the exact object, # not something equivalent to it. for i, childNode in enumerate(self.childNodes): if childNode is oldchild: self.childNodes[i].parentNode = None self.childNodes[i] = newchild newchild.paren...
def replaceChild(self, newchild, oldchild)
Replace an existing node with a new node. It must be the case that oldchild is a child of this node; if not, ValueError is raised. newchild is returned.
5.244353
4.962486
1.0568
l = reduce(lambda l, e: l + e.getElements(filter), self.childNodes, []) if filter(self): l.append(self) return l
def getElements(self, filter)
Return a list of elements below and including this element for which filter(element) returns True.
3.470957
3.367101
1.030844
if self.pcdata is not None: self.pcdata += content else: self.pcdata = content
def appendData(self, content)
Add characters to the element's pcdata.
3.451885
2.175099
1.587001
fileobj.write(self.start_tag(indent)) fileobj.write(u"\n") for c in self.childNodes: if c.tagName not in self.validchildren: raise ElementError("invalid child %s for %s" % (c.tagName, self.tagName)) c.write(fileobj, indent + Indent) if self.pcdata is not None: fileobj.write(xmlescape(self.pcdata...
def write(self, fileobj = sys.stdout, indent = u"")
Recursively write an element and it's children to a file.
2.487735
2.440626
1.019302
return u"%s<%s%s/>" % (indent, self.tagName, u"".join(u" %s=\"%s\"" % keyvalue for keyvalue in self.attributes.items()))
def start_tag(self, indent)
Generate the string for the element's start tag.
3.91978
3.498531
1.120407
fileobj.write(self.start_tag(indent)) fileobj.write(u"\n")
def write(self, fileobj = sys.stdout, indent = u"")
Recursively write an element and it's children to a file.
4.050239
3.993608
1.01418
self = cls() if Name is not None: self.Name = Name self.pcdata = datetime.datetime.utcnow() return self
def now(cls, Name = None)
Instantiate a Time element initialized to the current UTC time in the default format (ISO-8601). The Name attribute will be set to the value of the Name parameter if given.
4.922803
4.25298
1.157495
self = cls(AttributesImpl({u"Type": u"GPS"})) if Name is not None: self.Name = Name self.pcdata = gps return self
def from_gps(cls, gps, Name = None)
Instantiate a Time element initialized to the value of the given GPS time. The Name attribute will be set to the value of the Name parameter if given. Note: the new Time element holds a reference to the GPS time, not a copy of it. Subsequent modification of the GPS time object will be reflected in what ge...
8.80128
11.1724
0.78777