repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
gwastro/pycbc-glue | pycbc_glue/pipeline.py | CondorDAG.write_dag | def write_dag(self):
"""
Write either a dag or a dax.
"""
if not self.__nodes_finalized:
for node in self.__nodes:
node.finalize()
self.write_concrete_dag()
self.write_abstract_dag() | python | def write_dag(self):
"""
Write either a dag or a dax.
"""
if not self.__nodes_finalized:
for node in self.__nodes:
node.finalize()
self.write_concrete_dag()
self.write_abstract_dag() | [
"def",
"write_dag",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__nodes_finalized",
":",
"for",
"node",
"in",
"self",
".",
"__nodes",
":",
"node",
".",
"finalize",
"(",
")",
"self",
".",
"write_concrete_dag",
"(",
")",
"self",
".",
"write_abstract_... | Write either a dag or a dax. | [
"Write",
"either",
"a",
"dag",
"or",
"a",
"dax",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2146-L2154 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | CondorDAG.write_script | 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.
"""
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 node in self.__nodes:
outfile.write("# Job %s\n" % node.get_name())
# Check if this is a DAGMAN Node
if isinstance(node,CondorDAGManNode):
outfile.write("condor_submit_dag %s\n\n" % (node.job().get_dag()))
else:
outfile.write("%s %s\n\n" % (node.job().get_executable(),
node.get_cmd_line()))
outfile.close()
os.chmod(outfilename, os.stat(outfilename)[0] | stat.S_IEXEC) | python | 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.
"""
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 node in self.__nodes:
outfile.write("# Job %s\n" % node.get_name())
# Check if this is a DAGMAN Node
if isinstance(node,CondorDAGManNode):
outfile.write("condor_submit_dag %s\n\n" % (node.job().get_dag()))
else:
outfile.write("%s %s\n\n" % (node.job().get_executable(),
node.get_cmd_line()))
outfile.close()
os.chmod(outfilename, os.stat(outfilename)[0] | stat.S_IEXEC) | [
"def",
"write_script",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__dag_file_path",
":",
"raise",
"CondorDAGError",
",",
"\"No path for DAG file\"",
"try",
":",
"dfp",
"=",
"self",
".",
"__dag_file_path",
"outfilename",
"=",
"\".\"",
".",
"join",
"(",
... | 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. | [
"Write",
"the",
"workflow",
"to",
"a",
"script",
"(",
".",
"sh",
"instead",
"of",
".",
"dag",
")",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2156-L2182 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | CondorDAG.prepare_dax | def prepare_dax(self,grid_site=None,tmp_exec_dir='.',peg_frame_cache=None):
"""
Sets up a pegasus script for the given dag
"""
dag=self
log_path=self.__log_file_path
# this function creates the following three files needed by pegasus
peg_fh = open("pegasus_submit_dax", "w")
pegprop_fh = open("pegasus.properties", "w")
sitefile = open( 'sites.xml', 'w' )
# write the default properties
print >> pegprop_fh, PEGASUS_PROPERTIES % (os.getcwd())
# set up site and dir options for pegasus-submit-dax
dirs_entry='--relative-dir .'
if grid_site:
exec_site=grid_site
exec_ssite_list = exec_site.split(',')
for site in exec_ssite_list:
# if virgo sites are being used, then we don't have a shared fs
if site == 'nikhef':
dirs_entry += ' --staging-site nikhef=nikhef-srm'
else:
dirs_entry += ' --staging-site %s=%s' % (site,site)
if site == 'nikhef' or site == 'bologna':
print >> pegprop_fh, \
"""
###############################################################################
# Data Staging Configuration
# Pegasus will be setup to execute jobs on an execution site without relying
# on a shared filesystem between the head node and the worker nodes. If this
# is set, specify staging site ( using --staging-site option to pegasus-plan)
# to indicate the site to use as a central storage location for a workflow.
pegasus.data.configuration=nonsharedfs
"""
else:
exec_site='local'
# write the pegasus_submit_dax and make it executable
print >> peg_fh,PEGASUS_SCRIPT % ( tmp_exec_dir, os.getcwd(),
dag.get_dax_file().replace('.dax','') + '-0.dag',
dag.get_dax_file(), dirs_entry, exec_site )
peg_fh.close()
os.chmod("pegasus_submit_dax",0755)
# if a frame cache has been specified, write it to the properties
# however note that this is overridden by the --cache option to pegasus
if peg_frame_cache:
print >> pegprop_fh, "pegasus.catalog.replica.file=%s" % (os.path.join(os.getcwd(),os.path.basename(peg_frame_cache)))
pegprop_fh.close()
# write a shell script that can return the basedir and uber-concrete-dag
basedir_fh = open("pegasus_basedir", "w")
print >> basedir_fh, PEGASUS_BASEDIR_SCRIPT % ( tmp_exec_dir, dag.get_dax_file().replace('.dax','') + '-0.dag' )
basedir_fh.close()
os.chmod("pegasus_basedir",0755)
# write the site catalog file which is needed by pegasus
pwd = os.getcwd()
try:
hostname = socket.gethostbyaddr(socket.gethostname())[0]
except:
hostname = 'localhost'
print >> sitefile, """\
<?xml version="1.0" encoding="UTF-8"?>
<sitecatalog xmlns="http://pegasus.isi.edu/schema/sitecatalog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pegasus.isi.edu/schema/sitecatalog http://pegasus.isi.edu/schema/sc-4.0.xsd" version="4.0">
<site handle="local" arch="x86_64" os="LINUX">
<grid type="gt2" contact="%s/jobmanager-fork" scheduler="Fork" jobtype="auxillary" total-nodes="50"/>
<grid type="gt2" contact="%s/jobmanager-condor" scheduler="Condor" jobtype="compute" total-nodes="50"/>
<directory path="%s" type="shared-scratch" free-size="null" total-size="null">
<file-server operation="all" url="file://%s">
</file-server>
</directory>
<directory path="%s" type="shared-storage" free-size="null" total-size="null">
<file-server operation="all" url="file://%s">
</file-server>
</directory>
<replica-catalog type="LRC" url="rlsn://smarty.isi.edu">
</replica-catalog>
""" % (hostname,hostname,pwd,pwd,pwd,pwd)
try:
print >> sitefile, """ <profile namespace="env" key="GLOBUS_LOCATION">%s</profile>""" % os.environ['GLOBUS_LOCATION']
except:
pass
try:
print >> sitefile, """ <profile namespace="env" key="LD_LIBRARY_PATH">%s</profile>""" % os.environ['LD_LIBRARY_PATH']
except:
pass
try:
print >> sitefile, """ <profile namespace="env" key="PYTHONPATH">%s</profile>""" % os.environ['PYTHONPATH']
except:
pass
try:
print >> sitefile, """ <profile namespace="env" key="PEGASUS_HOME">%s</profile>""" % os.environ['PEGASUS_HOME']
except:
pass
try:
print >> sitefile, """ <profile namespace="env" key="LIGO_DATAFIND_SERVER">%s</profile>""" % os.environ['LIGO_DATAFIND_SERVER']
except:
pass
try:
print >> sitefile, """ <profile namespace="env" key="S6_SEGMENT_SERVER">%s</profile>""" % os.environ['S6_SEGMENT_SERVER']
except:
pass
print >> sitefile, """\
<profile namespace="env" key="JAVA_HEAPMAX">4096</profile>
<profile namespace="pegasus" key="style">condor</profile>
<profile namespace="condor" key="getenv">True</profile>
<profile namespace="condor" key="should_transfer_files">YES</profile>
<profile namespace="condor" key="when_to_transfer_output">ON_EXIT_OR_EVICT</profile>
</site>
"""
print >> sitefile, """\
<!-- Bologna cluster -->
<site handle="bologna" arch="x86_64" os="LINUX">
<grid type="cream" contact="https://ce01-lcg.cr.cnaf.infn.it:8443/ce-cream/services/CREAM2" scheduler="LSF" jobtype="compute" />
<grid type="cream" contact="https://ce01-lcg.cr.cnaf.infn.it:8443/ce-cream/services/CREAM2" scheduler="LSF" jobtype="auxillary" />
<directory type="shared-scratch" path="/storage/gpfs_virgo4/virgo4/%s/">
<file-server operation="all" url="srm://storm-fe-archive.cr.cnaf.infn.it:8444/srm/managerv2?SFN=/virgo4/%s/"/>
</directory>
<profile namespace="pegasus" key="style">cream</profile>
<profile namespace="globus" key="queue">virgo</profile>
</site>
""" % (os.path.basename(tmp_exec_dir),os.path.basename(tmp_exec_dir))
print >> sitefile, """\
<!-- Nikhef Big Grid -->
<site handle="nikhef" arch="x86_64" os="LINUX">
<grid type="cream" contact="https://klomp.nikhef.nl:8443/ce-cream/services/CREAM2" scheduler="PBS" jobtype="compute" />
<grid type="cream" contact="https://klomp.nikhef.nl:8443/ce-cream/services/CREAM2" scheduler="PBS" jobtype="auxillary" />
<profile namespace="pegasus" key="style">cream</profile>
<profile namespace="globus" key="queue">medium</profile>
</site>
<!-- Nikhef Stage in Site -->
<site handle="nikhef-srm" arch="x86_64" os="LINUX">
<directory type="shared-scratch" path="/%s/">
<file-server operation="all" url="srm://tbn18.nikhef.nl:8446/srm/managerv2?SFN=/dpm/nikhef.nl/home/virgo/%s/" />
</directory>
</site>
""" % (os.path.basename(tmp_exec_dir),os.path.basename(tmp_exec_dir))
try:
stampede_home = subprocess.check_output(
['gsissh','-o','BatchMode=yes','-p','2222','stampede.tacc.xsede.org','pwd'])
stampede_home = stampede_home.split('/')
stampede_magic_number = stampede_home[2]
stampede_username = stampede_home[3]
shared_scratch = "/work/%s/%s/ihope-workflow/%s" % (
stampede_magic_number,stampede_username,os.path.basename(tmp_exec_dir))
print >> sitefile, """\
<!-- XSEDE Stampede Cluster at TACC Development Queue -->
<site handle="stampede-dev" arch="x86_64" os="LINUX">
<grid type="gt5" contact="login5.stampede.tacc.utexas.edu/jobmanager-fork" scheduler="Fork" jobtype="auxillary"/>
<grid type="gt5" contact="login5.stampede.tacc.utexas.edu/jobmanager-slurm" scheduler="unknown" jobtype="compute"/>
<directory type="shared-scratch" path="%s">
<file-server operation="all" url="gsiftp://gridftp.stampede.tacc.xsede.org%s"/>
</directory>
<profile namespace="env" key="PEGASUS_HOME">/usr</profile>
<profile namespace="globus" key="queue">development</profile>
<profile namespace="globus" key="maxwalltime">180</profile>
<profile namespace="globus" key="host_count">1</profile>
<profile namespace="globus" key="count">16</profile>
<profile namespace="globus" key="jobtype">single</profile>
<profile namespace="globus" key="project">TG-PHY140012</profile>
</site>
""" % (shared_scratch,shared_scratch)
print >> sitefile, """\
<!-- XSEDE Stampede Cluster at TACC Development Queue -->
<site handle="stampede" arch="x86_64" os="LINUX">
<grid type="gt5" contact="login5.stampede.tacc.utexas.edu/jobmanager-fork" scheduler="Fork" jobtype="auxillary"/>
<grid type="gt5" contact="login5.stampede.tacc.utexas.edu/jobmanager-slurm" scheduler="unknown" jobtype="compute"/>
<directory type="shared-scratch" path="%s">
<file-server operation="all" url="gsiftp://gridftp.stampede.tacc.xsede.org%s"/>
</directory>
<profile namespace="env" key="PEGASUS_HOME">/usr</profile>
<profile namespace="globus" key="queue">development</profile>
<profile namespace="globus" key="maxwalltime">540</profile>
<profile namespace="globus" key="host_count">32</profile>
<profile namespace="globus" key="count">512</profile>
<profile namespace="globus" key="jobtype">single</profile>
<profile namespace="globus" key="project">TG-PHY140012</profile>
</site>
""" % (shared_scratch,shared_scratch)
except:
print >> sitefile, """\
<!-- XSEDE Stampede Cluster disabled as gsissh to TACC failed-->
"""
print >> sitefile, """\
</sitecatalog>"""
sitefile.close()
# Write a help message telling the user how to run the workflow
print
print "Created a workflow file which can be submitted by executing"
print """
./pegasus_submit_dax
in the analysis directory on a condor submit machine.
From the analysis directory on the condor submit machine, you can run the
command
pegasus-status --long -t -i `./pegasus_basedir`
to check the status of your workflow. Once the workflow has finished you
can run the command
pegasus-analyzer -t -i `./pegasus_basedir`
to debug any failed jobs.
""" | python | def prepare_dax(self,grid_site=None,tmp_exec_dir='.',peg_frame_cache=None):
"""
Sets up a pegasus script for the given dag
"""
dag=self
log_path=self.__log_file_path
# this function creates the following three files needed by pegasus
peg_fh = open("pegasus_submit_dax", "w")
pegprop_fh = open("pegasus.properties", "w")
sitefile = open( 'sites.xml', 'w' )
# write the default properties
print >> pegprop_fh, PEGASUS_PROPERTIES % (os.getcwd())
# set up site and dir options for pegasus-submit-dax
dirs_entry='--relative-dir .'
if grid_site:
exec_site=grid_site
exec_ssite_list = exec_site.split(',')
for site in exec_ssite_list:
# if virgo sites are being used, then we don't have a shared fs
if site == 'nikhef':
dirs_entry += ' --staging-site nikhef=nikhef-srm'
else:
dirs_entry += ' --staging-site %s=%s' % (site,site)
if site == 'nikhef' or site == 'bologna':
print >> pegprop_fh, \
"""
###############################################################################
# Data Staging Configuration
# Pegasus will be setup to execute jobs on an execution site without relying
# on a shared filesystem between the head node and the worker nodes. If this
# is set, specify staging site ( using --staging-site option to pegasus-plan)
# to indicate the site to use as a central storage location for a workflow.
pegasus.data.configuration=nonsharedfs
"""
else:
exec_site='local'
# write the pegasus_submit_dax and make it executable
print >> peg_fh,PEGASUS_SCRIPT % ( tmp_exec_dir, os.getcwd(),
dag.get_dax_file().replace('.dax','') + '-0.dag',
dag.get_dax_file(), dirs_entry, exec_site )
peg_fh.close()
os.chmod("pegasus_submit_dax",0755)
# if a frame cache has been specified, write it to the properties
# however note that this is overridden by the --cache option to pegasus
if peg_frame_cache:
print >> pegprop_fh, "pegasus.catalog.replica.file=%s" % (os.path.join(os.getcwd(),os.path.basename(peg_frame_cache)))
pegprop_fh.close()
# write a shell script that can return the basedir and uber-concrete-dag
basedir_fh = open("pegasus_basedir", "w")
print >> basedir_fh, PEGASUS_BASEDIR_SCRIPT % ( tmp_exec_dir, dag.get_dax_file().replace('.dax','') + '-0.dag' )
basedir_fh.close()
os.chmod("pegasus_basedir",0755)
# write the site catalog file which is needed by pegasus
pwd = os.getcwd()
try:
hostname = socket.gethostbyaddr(socket.gethostname())[0]
except:
hostname = 'localhost'
print >> sitefile, """\
<?xml version="1.0" encoding="UTF-8"?>
<sitecatalog xmlns="http://pegasus.isi.edu/schema/sitecatalog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pegasus.isi.edu/schema/sitecatalog http://pegasus.isi.edu/schema/sc-4.0.xsd" version="4.0">
<site handle="local" arch="x86_64" os="LINUX">
<grid type="gt2" contact="%s/jobmanager-fork" scheduler="Fork" jobtype="auxillary" total-nodes="50"/>
<grid type="gt2" contact="%s/jobmanager-condor" scheduler="Condor" jobtype="compute" total-nodes="50"/>
<directory path="%s" type="shared-scratch" free-size="null" total-size="null">
<file-server operation="all" url="file://%s">
</file-server>
</directory>
<directory path="%s" type="shared-storage" free-size="null" total-size="null">
<file-server operation="all" url="file://%s">
</file-server>
</directory>
<replica-catalog type="LRC" url="rlsn://smarty.isi.edu">
</replica-catalog>
""" % (hostname,hostname,pwd,pwd,pwd,pwd)
try:
print >> sitefile, """ <profile namespace="env" key="GLOBUS_LOCATION">%s</profile>""" % os.environ['GLOBUS_LOCATION']
except:
pass
try:
print >> sitefile, """ <profile namespace="env" key="LD_LIBRARY_PATH">%s</profile>""" % os.environ['LD_LIBRARY_PATH']
except:
pass
try:
print >> sitefile, """ <profile namespace="env" key="PYTHONPATH">%s</profile>""" % os.environ['PYTHONPATH']
except:
pass
try:
print >> sitefile, """ <profile namespace="env" key="PEGASUS_HOME">%s</profile>""" % os.environ['PEGASUS_HOME']
except:
pass
try:
print >> sitefile, """ <profile namespace="env" key="LIGO_DATAFIND_SERVER">%s</profile>""" % os.environ['LIGO_DATAFIND_SERVER']
except:
pass
try:
print >> sitefile, """ <profile namespace="env" key="S6_SEGMENT_SERVER">%s</profile>""" % os.environ['S6_SEGMENT_SERVER']
except:
pass
print >> sitefile, """\
<profile namespace="env" key="JAVA_HEAPMAX">4096</profile>
<profile namespace="pegasus" key="style">condor</profile>
<profile namespace="condor" key="getenv">True</profile>
<profile namespace="condor" key="should_transfer_files">YES</profile>
<profile namespace="condor" key="when_to_transfer_output">ON_EXIT_OR_EVICT</profile>
</site>
"""
print >> sitefile, """\
<!-- Bologna cluster -->
<site handle="bologna" arch="x86_64" os="LINUX">
<grid type="cream" contact="https://ce01-lcg.cr.cnaf.infn.it:8443/ce-cream/services/CREAM2" scheduler="LSF" jobtype="compute" />
<grid type="cream" contact="https://ce01-lcg.cr.cnaf.infn.it:8443/ce-cream/services/CREAM2" scheduler="LSF" jobtype="auxillary" />
<directory type="shared-scratch" path="/storage/gpfs_virgo4/virgo4/%s/">
<file-server operation="all" url="srm://storm-fe-archive.cr.cnaf.infn.it:8444/srm/managerv2?SFN=/virgo4/%s/"/>
</directory>
<profile namespace="pegasus" key="style">cream</profile>
<profile namespace="globus" key="queue">virgo</profile>
</site>
""" % (os.path.basename(tmp_exec_dir),os.path.basename(tmp_exec_dir))
print >> sitefile, """\
<!-- Nikhef Big Grid -->
<site handle="nikhef" arch="x86_64" os="LINUX">
<grid type="cream" contact="https://klomp.nikhef.nl:8443/ce-cream/services/CREAM2" scheduler="PBS" jobtype="compute" />
<grid type="cream" contact="https://klomp.nikhef.nl:8443/ce-cream/services/CREAM2" scheduler="PBS" jobtype="auxillary" />
<profile namespace="pegasus" key="style">cream</profile>
<profile namespace="globus" key="queue">medium</profile>
</site>
<!-- Nikhef Stage in Site -->
<site handle="nikhef-srm" arch="x86_64" os="LINUX">
<directory type="shared-scratch" path="/%s/">
<file-server operation="all" url="srm://tbn18.nikhef.nl:8446/srm/managerv2?SFN=/dpm/nikhef.nl/home/virgo/%s/" />
</directory>
</site>
""" % (os.path.basename(tmp_exec_dir),os.path.basename(tmp_exec_dir))
try:
stampede_home = subprocess.check_output(
['gsissh','-o','BatchMode=yes','-p','2222','stampede.tacc.xsede.org','pwd'])
stampede_home = stampede_home.split('/')
stampede_magic_number = stampede_home[2]
stampede_username = stampede_home[3]
shared_scratch = "/work/%s/%s/ihope-workflow/%s" % (
stampede_magic_number,stampede_username,os.path.basename(tmp_exec_dir))
print >> sitefile, """\
<!-- XSEDE Stampede Cluster at TACC Development Queue -->
<site handle="stampede-dev" arch="x86_64" os="LINUX">
<grid type="gt5" contact="login5.stampede.tacc.utexas.edu/jobmanager-fork" scheduler="Fork" jobtype="auxillary"/>
<grid type="gt5" contact="login5.stampede.tacc.utexas.edu/jobmanager-slurm" scheduler="unknown" jobtype="compute"/>
<directory type="shared-scratch" path="%s">
<file-server operation="all" url="gsiftp://gridftp.stampede.tacc.xsede.org%s"/>
</directory>
<profile namespace="env" key="PEGASUS_HOME">/usr</profile>
<profile namespace="globus" key="queue">development</profile>
<profile namespace="globus" key="maxwalltime">180</profile>
<profile namespace="globus" key="host_count">1</profile>
<profile namespace="globus" key="count">16</profile>
<profile namespace="globus" key="jobtype">single</profile>
<profile namespace="globus" key="project">TG-PHY140012</profile>
</site>
""" % (shared_scratch,shared_scratch)
print >> sitefile, """\
<!-- XSEDE Stampede Cluster at TACC Development Queue -->
<site handle="stampede" arch="x86_64" os="LINUX">
<grid type="gt5" contact="login5.stampede.tacc.utexas.edu/jobmanager-fork" scheduler="Fork" jobtype="auxillary"/>
<grid type="gt5" contact="login5.stampede.tacc.utexas.edu/jobmanager-slurm" scheduler="unknown" jobtype="compute"/>
<directory type="shared-scratch" path="%s">
<file-server operation="all" url="gsiftp://gridftp.stampede.tacc.xsede.org%s"/>
</directory>
<profile namespace="env" key="PEGASUS_HOME">/usr</profile>
<profile namespace="globus" key="queue">development</profile>
<profile namespace="globus" key="maxwalltime">540</profile>
<profile namespace="globus" key="host_count">32</profile>
<profile namespace="globus" key="count">512</profile>
<profile namespace="globus" key="jobtype">single</profile>
<profile namespace="globus" key="project">TG-PHY140012</profile>
</site>
""" % (shared_scratch,shared_scratch)
except:
print >> sitefile, """\
<!-- XSEDE Stampede Cluster disabled as gsissh to TACC failed-->
"""
print >> sitefile, """\
</sitecatalog>"""
sitefile.close()
# Write a help message telling the user how to run the workflow
print
print "Created a workflow file which can be submitted by executing"
print """
./pegasus_submit_dax
in the analysis directory on a condor submit machine.
From the analysis directory on the condor submit machine, you can run the
command
pegasus-status --long -t -i `./pegasus_basedir`
to check the status of your workflow. Once the workflow has finished you
can run the command
pegasus-analyzer -t -i `./pegasus_basedir`
to debug any failed jobs.
""" | [
"def",
"prepare_dax",
"(",
"self",
",",
"grid_site",
"=",
"None",
",",
"tmp_exec_dir",
"=",
"'.'",
",",
"peg_frame_cache",
"=",
"None",
")",
":",
"dag",
"=",
"self",
"log_path",
"=",
"self",
".",
"__log_file_path",
"# this function creates the following three file... | Sets up a pegasus script for the given dag | [
"Sets",
"up",
"a",
"pegasus",
"script",
"for",
"the",
"given",
"dag"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2184-L2409 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisJob.get_config | 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.
"""
return string.strip(self.__cp.get(sec,opt)) | python | 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.
"""
return string.strip(self.__cp.get(sec,opt)) | [
"def",
"get_config",
"(",
"self",
",",
"sec",
",",
"opt",
")",
":",
"return",
"string",
".",
"strip",
"(",
"self",
".",
"__cp",
".",
"get",
"(",
"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. | [
"Get",
"the",
"configration",
"variable",
"in",
"a",
"particular",
"section",
"of",
"this",
"jobs",
"ini",
"file",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2434-L2441 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.set_start | 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.
"""
if pass_to_command_line:
self.add_var_opt('gps-start-time',time)
self.__start = time
self.__data_start = time | python | 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.
"""
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",
")",
":",
"if",
"pass_to_command_line",
":",
"self",
".",
"add_var_opt",
"(",
"'gps-start-time'",
",",
"time",
")",
"self",
".",
"__start",
"=",
"time",
"self",
".",
"_... | 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. | [
"Set",
"the",
"GPS",
"start",
"time",
"of",
"the",
"analysis",
"node",
"by",
"setting",
"a",
"--",
"gps",
"-",
"start",
"-",
"time",
"option",
"to",
"the",
"node",
"when",
"it",
"is",
"executed",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2481-L2491 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.set_end | 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.
"""
if pass_to_command_line:
self.add_var_opt('gps-end-time',time)
self.__end = time
self.__data_end = time | python | 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.
"""
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",
")",
":",
"if",
"pass_to_command_line",
":",
"self",
".",
"add_var_opt",
"(",
"'gps-end-time'",
",",
"time",
")",
"self",
".",
"__end",
"=",
"time",
"self",
".",
"__data_... | 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. | [
"Set",
"the",
"GPS",
"end",
"time",
"of",
"the",
"analysis",
"node",
"by",
"setting",
"a",
"--",
"gps",
"-",
"end",
"-",
"time",
"option",
"to",
"the",
"node",
"when",
"it",
"is",
"executed",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2501-L2511 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.set_trig_start | 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.
"""
if pass_to_command_line:
self.add_var_opt('trig-start-time',time)
self.__trig_start = time | python | 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.
"""
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",
")",
":",
"if",
"pass_to_command_line",
":",
"self",
".",
"add_var_opt",
"(",
"'trig-start-time'",
",",
"time",
")",
"self",
".",
"__trig_start",
"=",
"time"
] | 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. | [
"Set",
"the",
"trig",
"start",
"time",
"of",
"the",
"analysis",
"node",
"by",
"setting",
"a",
"--",
"trig",
"-",
"start",
"-",
"time",
"option",
"to",
"the",
"node",
"when",
"it",
"is",
"executed",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2558-L2567 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.set_trig_end | 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.
"""
if pass_to_command_line:
self.add_var_opt('trig-end-time',time)
self.__trig_end = time | python | 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.
"""
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",
")",
":",
"if",
"pass_to_command_line",
":",
"self",
".",
"add_var_opt",
"(",
"'trig-end-time'",
",",
"time",
")",
"self",
".",
"__trig_end",
"=",
"time"
] | 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. | [
"Set",
"the",
"trig",
"end",
"time",
"of",
"the",
"analysis",
"node",
"by",
"setting",
"a",
"--",
"trig",
"-",
"end",
"-",
"time",
"option",
"to",
"the",
"node",
"when",
"it",
"is",
"executed",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2575-L2584 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.set_input | 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.
"""
self.__input = filename
if pass_to_command_line:
self.add_var_opt('input', filename)
self.add_input_file(filename) | python | 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.
"""
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",
")",
":",
"self",
".",
"__input",
"=",
"filename",
"if",
"pass_to_command_line",
":",
"self",
".",
"add_var_opt",
"(",
"'input'",
",",
"filename",
")",
"self",
".",
... | 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. | [
"Add",
"an",
"input",
"to",
"the",
"node",
"by",
"adding",
"a",
"--",
"input",
"option",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2592-L2601 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.set_output | 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.
"""
self.__output = filename
if pass_to_command_line:
self.add_var_opt('output', filename)
self.add_output_file(filename) | python | 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.
"""
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",
")",
":",
"self",
".",
"__output",
"=",
"filename",
"if",
"pass_to_command_line",
":",
"self",
".",
"add_var_opt",
"(",
"'output'",
",",
"filename",
")",
"self",
"."... | 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. | [
"Add",
"an",
"output",
"to",
"the",
"node",
"by",
"adding",
"a",
"--",
"output",
"option",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2609-L2618 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.set_ifo | 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).
"""
self.__ifo = ifo
if self.job().channel():
self.add_var_opt('channel-name', ifo + ':' + self.job().channel()) | python | 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).
"""
self.__ifo = ifo
if self.job().channel():
self.add_var_opt('channel-name', ifo + ':' + self.job().channel()) | [
"def",
"set_ifo",
"(",
"self",
",",
"ifo",
")",
":",
"self",
".",
"__ifo",
"=",
"ifo",
"if",
"self",
".",
"job",
"(",
")",
".",
"channel",
"(",
")",
":",
"self",
".",
"add_var_opt",
"(",
"'channel-name'",
",",
"ifo",
"+",
"':'",
"+",
"self",
".",... | 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). | [
"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",
"co... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2626-L2635 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.set_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.
"""
self.__ifo_tag = ifo_tag
if pass_to_command_line:
self.add_var_opt('ifo-tag', ifo_tag) | python | 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.
"""
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",
")",
":",
"self",
".",
"__ifo_tag",
"=",
"ifo_tag",
"if",
"pass_to_command_line",
":",
"self",
".",
"add_var_opt",
"(",
"'ifo-tag'",
",",
"ifo_tag",
")"
] | 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. | [
"Set",
"the",
"ifo",
"tag",
"that",
"is",
"passed",
"to",
"the",
"analysis",
"code",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2643-L2651 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.set_user_tag | 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.
"""
self.__user_tag = usertag
if pass_to_command_line:
self.add_var_opt('user-tag', usertag) | python | 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.
"""
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",
")",
":",
"self",
".",
"__user_tag",
"=",
"usertag",
"if",
"pass_to_command_line",
":",
"self",
".",
"add_var_opt",
"(",
"'user-tag'",
",",
"usertag",
")"
] | 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. | [
"Set",
"the",
"user",
"tag",
"that",
"is",
"passed",
"to",
"the",
"analysis",
"code",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2659-L2667 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.set_cache | 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.
"""
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 the LFNs that actually overlap with this job
# XXX FIXME this is a very slow algorithm
if len(filename) == 0:
raise CondorDAGNodeError, \
"LDR did not return any LFNs for query: check ifo and frame type"
for lfn in filename:
a, b, c, d = lfn.split('.')[0].split('-')
t_start = int(c)
t_end = int(c) + int(d)
if (t_start <= (self.get_data_end()+self.get_pad_data()+int(d)+1) \
and t_end >= (self.get_data_start()-self.get_pad_data()-int(d)-1)):
self.add_input_file(lfn)
# set the frame type based on the LFNs returned by datafind
self.add_var_opt('frame-type',b)
else:
raise CondorDAGNodeError, "Unknown LFN cache format" | python | 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.
"""
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 the LFNs that actually overlap with this job
# XXX FIXME this is a very slow algorithm
if len(filename) == 0:
raise CondorDAGNodeError, \
"LDR did not return any LFNs for query: check ifo and frame type"
for lfn in filename:
a, b, c, d = lfn.split('.')[0].split('-')
t_start = int(c)
t_end = int(c) + int(d)
if (t_start <= (self.get_data_end()+self.get_pad_data()+int(d)+1) \
and t_end >= (self.get_data_start()-self.get_pad_data()-int(d)-1)):
self.add_input_file(lfn)
# set the frame type based on the LFNs returned by datafind
self.add_var_opt('frame-type',b)
else:
raise CondorDAGNodeError, "Unknown LFN cache format" | [
"def",
"set_cache",
"(",
"self",
",",
"filename",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"# the name of a lal cache file created by a datafind node",
"self",
".",
"add_var_opt",
"(",
"'frame-cache'",
",",
"filename",
")",
"self",
".",... | 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. | [
"Set",
"the",
"LAL",
"frame",
"cache",
"to",
"to",
"use",
".",
"The",
"frame",
"cache",
"is",
"passed",
"to",
"the",
"job",
"with",
"the",
"--",
"frame",
"-",
"cache",
"argument",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2675-L2703 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.calibration_cache_path | def calibration_cache_path(self):
"""
Determine the path to the correct calibration cache file to use.
"""
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(
self.job().get_config('calibration','H2-cal-epoch-boundary')):
cal_file = self.job().get_config('calibration','H2-1')
else:
cal_file = self.job().get_config('calibration','H2-2')
else:
# if not: just add calibration cache
cal_file = self.job().get_config('calibration',self.__ifo)
cal = os.path.join(cal_path,cal_file)
self.__calibration_cache = cal
else:
msg = "IFO and start-time must be set first"
raise CondorDAGNodeError, msg | python | def calibration_cache_path(self):
"""
Determine the path to the correct calibration cache file to use.
"""
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(
self.job().get_config('calibration','H2-cal-epoch-boundary')):
cal_file = self.job().get_config('calibration','H2-1')
else:
cal_file = self.job().get_config('calibration','H2-2')
else:
# if not: just add calibration cache
cal_file = self.job().get_config('calibration',self.__ifo)
cal = os.path.join(cal_path,cal_file)
self.__calibration_cache = cal
else:
msg = "IFO and start-time must be set first"
raise CondorDAGNodeError, msg | [
"def",
"calibration_cache_path",
"(",
"self",
")",
":",
"if",
"self",
".",
"__ifo",
"and",
"self",
".",
"__start",
">",
"0",
":",
"cal_path",
"=",
"self",
".",
"job",
"(",
")",
".",
"get_config",
"(",
"'calibration'",
",",
"'path'",
")",
"# check if this... | Determine the path to the correct calibration cache file to use. | [
"Determine",
"the",
"path",
"to",
"the",
"correct",
"calibration",
"cache",
"file",
"to",
"use",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2705-L2728 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | AnalysisNode.calibration | 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.
"""
# 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://.*)')
f = open(cache_filename, 'r')
lines = f.readlines()
# loop over entries in the cache-file...
for line in lines:
m = pat.search(line)
if not m:
raise IOError
url = m.group(1)
# ... and add files to input-file list
path = urlparse.urlparse(url)[2]
calibration_lfn = os.path.basename(path)
self.add_input_file(calibration_lfn)
else:
# old .calibration for DAG's
self.add_var_opt('calibration-cache', self.__calibration_cache)
self.__calibration = self.__calibration_cache
self.add_input_file(self.__calibration) | python | 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.
"""
# 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://.*)')
f = open(cache_filename, 'r')
lines = f.readlines()
# loop over entries in the cache-file...
for line in lines:
m = pat.search(line)
if not m:
raise IOError
url = m.group(1)
# ... and add files to input-file list
path = urlparse.urlparse(url)[2]
calibration_lfn = os.path.basename(path)
self.add_input_file(calibration_lfn)
else:
# old .calibration for DAG's
self.add_var_opt('calibration-cache', self.__calibration_cache)
self.__calibration = self.__calibration_cache
self.add_input_file(self.__calibration) | [
"def",
"calibration",
"(",
"self",
")",
":",
"# 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 DA... | 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. | [
"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",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2730-L2762 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceSegment.make_chunks | 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 of the ScienceSegment that is too short to contain a
chunk is ignored. The length of this unused data is stored and can be
retrieved with the unused() method.
@param length: length of chunk in seconds.
@param overlap: overlap between chunks in seconds.
@param play: 1 : only generate chunks that overlap with S2 playground data.
2 : as play = 1 plus compute trig start and end times to
coincide with the start/end of the playground
@param sl: slide by sl seconds before determining playground data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground.
@param pad_data: exclude the first and last pad_data seconds of the segment
when generating chunks
"""
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):
# calculate the start of the playground preceeding the chunk end
play_start = 729273613 + 6370 * \
math.floor((end-sl-excl_play-729273613) / 6370)
play_end = play_start + 600
trig_start = 0
trig_end = 0
if ( (play_end - 6370) > start ):
print "Two playground segments in this chunk:",
print " Code to handle this case has not been implemented"
sys.exit(1)
else:
if play_start > start:
trig_start = int(play_start)
if play_end < end:
trig_end = int(play_end)
self.__chunks.append(AnalysisChunk(start,end,trig_start,trig_end))
else:
self.__chunks.append(AnalysisChunk(start,end))
start += increment
time_left -= increment
self.__unused = time_left - overlap | python | 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 of the ScienceSegment that is too short to contain a
chunk is ignored. The length of this unused data is stored and can be
retrieved with the unused() method.
@param length: length of chunk in seconds.
@param overlap: overlap between chunks in seconds.
@param play: 1 : only generate chunks that overlap with S2 playground data.
2 : as play = 1 plus compute trig start and end times to
coincide with the start/end of the playground
@param sl: slide by sl seconds before determining playground data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground.
@param pad_data: exclude the first and last pad_data seconds of the segment
when generating chunks
"""
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):
# calculate the start of the playground preceeding the chunk end
play_start = 729273613 + 6370 * \
math.floor((end-sl-excl_play-729273613) / 6370)
play_end = play_start + 600
trig_start = 0
trig_end = 0
if ( (play_end - 6370) > start ):
print "Two playground segments in this chunk:",
print " Code to handle this case has not been implemented"
sys.exit(1)
else:
if play_start > start:
trig_start = int(play_start)
if play_end < end:
trig_end = int(play_end)
self.__chunks.append(AnalysisChunk(start,end,trig_start,trig_end))
else:
self.__chunks.append(AnalysisChunk(start,end))
start += increment
time_left -= increment
self.__unused = time_left - overlap | [
"def",
"make_chunks",
"(",
"self",
",",
"length",
"=",
"0",
",",
"overlap",
"=",
"0",
",",
"play",
"=",
"0",
",",
"sl",
"=",
"0",
",",
"excl_play",
"=",
"0",
",",
"pad_data",
"=",
"0",
")",
":",
"time_left",
"=",
"self",
".",
"dur",
"(",
")",
... | 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 of the ScienceSegment that is too short to contain a
chunk is ignored. The length of this unused data is stored and can be
retrieved with the unused() method.
@param length: length of chunk in seconds.
@param overlap: overlap between chunks in seconds.
@param play: 1 : only generate chunks that overlap with S2 playground data.
2 : as play = 1 plus compute trig start and end times to
coincide with the start/end of the playground
@param sl: slide by sl seconds before determining playground data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground.
@param pad_data: exclude the first and last pad_data seconds of the segment
when generating chunks | [
"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",... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2917-L2965 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceSegment.add_chunk | 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
"""
self.__chunks.append(AnalysisChunk(start,end,trig_start,trig_end)) | python | 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
"""
self.__chunks.append(AnalysisChunk(start,end,trig_start,trig_end)) | [
"def",
"add_chunk",
"(",
"self",
",",
"start",
",",
"end",
",",
"trig_start",
"=",
"0",
",",
"trig_end",
"=",
"0",
")",
":",
"self",
".",
"__chunks",
".",
"append",
"(",
"AnalysisChunk",
"(",
"start",
",",
"end",
",",
"trig_start",
",",
"trig_end",
"... | 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 | [
"Add",
"an",
"AnalysisChunk",
"to",
"the",
"list",
"associated",
"with",
"this",
"ScienceSegment",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2967-L2974 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceSegment.set_start | def set_start(self,t):
"""
Override the GPS start time (and set the duration) of this ScienceSegment.
@param t: new GPS start time.
"""
self.__dur += self.__start - t
self.__start = t | python | def set_start(self,t):
"""
Override the GPS start time (and set the duration) of this ScienceSegment.
@param t: new GPS start time.
"""
self.__dur += self.__start - t
self.__start = t | [
"def",
"set_start",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"__dur",
"+=",
"self",
".",
"__start",
"-",
"t",
"self",
".",
"__start",
"=",
"t"
] | Override the GPS start time (and set the duration) of this ScienceSegment.
@param t: new GPS start time. | [
"Override",
"the",
"GPS",
"start",
"time",
"(",
"and",
"set",
"the",
"duration",
")",
"of",
"this",
"ScienceSegment",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3006-L3012 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceSegment.set_end | def set_end(self,t):
"""
Override the GPS end time (and set the duration) of this ScienceSegment.
@param t: new GPS end time.
"""
self.__dur -= self.__end - t
self.__end = t | python | def set_end(self,t):
"""
Override the GPS end time (and set the duration) of this ScienceSegment.
@param t: new GPS end time.
"""
self.__dur -= self.__end - t
self.__end = t | [
"def",
"set_end",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"__dur",
"-=",
"self",
".",
"__end",
"-",
"t",
"self",
".",
"__end",
"=",
"t"
] | Override the GPS end time (and set the duration) of this ScienceSegment.
@param t: new GPS end time. | [
"Override",
"the",
"GPS",
"end",
"time",
"(",
"and",
"set",
"the",
"duration",
")",
"of",
"this",
"ScienceSegment",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3014-L3020 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.read | 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::
delta > 0:
[s,e] -> [s+delta,e].
delta < 0:
[s,e] -> [s,e-delta].
@param buffer: shrink the ScienceSegment::
[s,e] -> [s+buffer,e-buffer]
"""
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:
st += slide_sec
elif slide_sec < 0:
en += slide_sec
du -= abs(slide_sec)
# add a buffer
if buffer > 0:
st += buffer
en -= buffer
du -= 2*abs(buffer)
x = ScienceSegment(tuple([id,st,en,du]))
self.__sci_segs.append(x) | python | 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::
delta > 0:
[s,e] -> [s+delta,e].
delta < 0:
[s,e] -> [s,e-delta].
@param buffer: shrink the ScienceSegment::
[s,e] -> [s+buffer,e-buffer]
"""
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:
st += slide_sec
elif slide_sec < 0:
en += slide_sec
du -= abs(slide_sec)
# add a buffer
if buffer > 0:
st += buffer
en -= buffer
du -= 2*abs(buffer)
x = ScienceSegment(tuple([id,st,en,du]))
self.__sci_segs.append(x) | [
"def",
"read",
"(",
"self",
",",
"filename",
",",
"min_length",
",",
"slide_sec",
"=",
"0",
",",
"buffer",
"=",
"0",
")",
":",
"self",
".",
"__filename",
"=",
"filename",
"octothorpe",
"=",
"re",
".",
"compile",
"(",
"r'\\A#'",
")",
"for",
"line",
"i... | 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::
delta > 0:
[s,e] -> [s+delta,e].
delta < 0:
[s,e] -> [s,e-delta].
@param buffer: shrink the ScienceSegment::
[s,e] -> [s+buffer,e-buffer] | [
"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",
".",
"@para... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3068-L3105 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.tama_read | 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.
"""
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.append(x) | python | 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.
"""
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.append(x) | [
"def",
"tama_read",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"__filename",
"=",
"filename",
"for",
"line",
"in",
"open",
"(",
"filename",
")",
":",
"columns",
"=",
"line",
".",
"split",
"(",
")",
"id",
"=",
"int",
"(",
"columns",
"[",
"... | 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. | [
"Parse",
"the",
"science",
"segments",
"from",
"a",
"tama",
"list",
"of",
"locked",
"segments",
"contained",
"in",
"file",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3111-L3126 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.make_chunks | 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 data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground.
"""
for seg in self.__sci_segs:
seg.make_chunks(length,overlap,play,sl,excl_play,pad_data) | python | 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 data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground.
"""
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",
")",
":",
"for",
"seg",
"in",
"self",
".",
"__sci_segs",
":",
"seg",
... | 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 data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground. | [
"Divide",
"each",
"ScienceSegment",
"contained",
"in",
"this",
"object",
"into",
"AnalysisChunks",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3129-L3141 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.make_chunks_from_unused | 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 data.
- 2 : as 1 plus compute trig start and end times to coincide
with the start/end of the playground
@param min_length: the unused data must be greater than min_length to make a
chunk.
@param sl: slide by sl seconds before determining playground data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground.
@param pad_data: exclude the first and last pad_data seconds of the segment
when generating chunks
"""
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))):
trig_start = end - seg.unused() - trig_overlap
if (play == 2):
# calculate the start of the playground preceeding the chunk end
play_start = 729273613 + 6370 * \
math.floor((end-sl-excl_play-729273613) / 6370)
play_end = play_start + 600
trig_end = 0
if ( (play_end - 6370) > start ):
print "Two playground segments in this chunk"
print " Code to handle this case has not been implemented"
sys.exit(1)
else:
if play_start > trig_start:
trig_start = int(play_start)
if (play_end < end):
trig_end = int(play_end)
if (trig_end == 0) or (trig_end > trig_start):
seg.add_chunk(start, end, trig_start, trig_end)
else:
seg.add_chunk(start, end, trig_start)
seg.set_unused(0) | python | 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 data.
- 2 : as 1 plus compute trig start and end times to coincide
with the start/end of the playground
@param min_length: the unused data must be greater than min_length to make a
chunk.
@param sl: slide by sl seconds before determining playground data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground.
@param pad_data: exclude the first and last pad_data seconds of the segment
when generating chunks
"""
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))):
trig_start = end - seg.unused() - trig_overlap
if (play == 2):
# calculate the start of the playground preceeding the chunk end
play_start = 729273613 + 6370 * \
math.floor((end-sl-excl_play-729273613) / 6370)
play_end = play_start + 600
trig_end = 0
if ( (play_end - 6370) > start ):
print "Two playground segments in this chunk"
print " Code to handle this case has not been implemented"
sys.exit(1)
else:
if play_start > trig_start:
trig_start = int(play_start)
if (play_end < end):
trig_end = int(play_end)
if (trig_end == 0) or (trig_end > trig_start):
seg.add_chunk(start, end, trig_start, trig_end)
else:
seg.add_chunk(start, end, trig_start)
seg.set_unused(0) | [
"def",
"make_chunks_from_unused",
"(",
"self",
",",
"length",
",",
"trig_overlap",
",",
"play",
"=",
"0",
",",
"min_length",
"=",
"0",
",",
"sl",
"=",
"0",
",",
"excl_play",
"=",
"0",
",",
"pad_data",
"=",
"0",
")",
":",
"for",
"seg",
"in",
"self",
... | 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 data.
- 2 : as 1 plus compute trig start and end times to coincide
with the start/end of the playground
@param min_length: the unused data must be greater than min_length to make a
chunk.
@param sl: slide by sl seconds before determining playground data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground.
@param pad_data: exclude the first and last pad_data seconds of the segment
when generating chunks | [
"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",... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3143-L3190 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.make_short_chunks_from_unused | 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 by sl seconds before determining playground data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground.
"""
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, end, start)
seg.set_unused(0) | python | 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 by sl seconds before determining playground data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground.
"""
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, end, start)
seg.set_unused(0) | [
"def",
"make_short_chunks_from_unused",
"(",
"self",
",",
"min_length",
",",
"overlap",
"=",
"0",
",",
"play",
"=",
"0",
",",
"sl",
"=",
"0",
",",
"excl_play",
"=",
"0",
")",
":",
"for",
"seg",
"in",
"self",
".",
"__sci_segs",
":",
"if",
"seg",
".",
... | 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 by sl seconds before determining playground data.
@param excl_play: exclude the first excl_play second from the start and end
of the chunk when computing if the chunk overlaps with playground. | [
"Create",
"a",
"chunk",
"that",
"uses",
"up",
"the",
"unused",
"data",
"in",
"the",
"science",
"segment"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3192-L3212 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.make_optimised_chunks | 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 the
segment when generating chunks
"""
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
for i in range(N-1):
start = seg_start + (i * max_length)
stop = start + max_length
seg.add_chunk(start, stop)
# optimise data usage for last 2 chunks
start = seg_start + ((N-1) * max_length)
middle = (start + seg_end)/2
seg.add_chunk(start, middle)
seg.add_chunk(middle, seg_end)
seg.set_unused(0)
elif seg.unused() > min_length:
# utilise as single chunk
seg.add_chunk(seg_start, seg_end)
else:
# no chunk of usable length
seg.set_unused(0) | python | 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 the
segment when generating chunks
"""
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
for i in range(N-1):
start = seg_start + (i * max_length)
stop = start + max_length
seg.add_chunk(start, stop)
# optimise data usage for last 2 chunks
start = seg_start + ((N-1) * max_length)
middle = (start + seg_end)/2
seg.add_chunk(start, middle)
seg.add_chunk(middle, seg_end)
seg.set_unused(0)
elif seg.unused() > min_length:
# utilise as single chunk
seg.add_chunk(seg_start, seg_end)
else:
# no chunk of usable length
seg.set_unused(0) | [
"def",
"make_optimised_chunks",
"(",
"self",
",",
"min_length",
",",
"max_length",
",",
"pad_data",
"=",
"0",
")",
":",
"for",
"seg",
"in",
"self",
".",
"__sci_segs",
":",
"# pad data if requested",
"seg_start",
"=",
"seg",
".",
"start",
"(",
")",
"+",
"pa... | 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 the
segment when generating chunks | [
"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",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3214-L3250 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.intersection | 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
"""
# 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.id()
# loop over segments from the second list which overlap this segment
while start2 < stop1:
if stop2 > start1:
# these overlap
# find the overlapping range
if start1 < start2:
ostart = start2
else:
ostart = start1
if stop1 > stop2:
ostop = stop2
else:
ostop = stop1
x = ScienceSegment(tuple([id, ostart, ostop, ostop-ostart]))
outlist.append(x)
if stop2 > stop1:
break
# step forward
iseg2 += 1
if iseg2 < len(other):
seg2 = other[iseg2]
start2 = seg2.start()
stop2 = seg2.end()
else:
# pseudo-segment in the far future
start2 = 2000000000
stop2 = 2000000000
# save the intersection and return the length
self.__sci_segs = outlist
return len(self) | python | 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
"""
# 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.id()
# loop over segments from the second list which overlap this segment
while start2 < stop1:
if stop2 > start1:
# these overlap
# find the overlapping range
if start1 < start2:
ostart = start2
else:
ostart = start1
if stop1 > stop2:
ostop = stop2
else:
ostop = stop1
x = ScienceSegment(tuple([id, ostart, ostop, ostop-ostart]))
outlist.append(x)
if stop2 > stop1:
break
# step forward
iseg2 += 1
if iseg2 < len(other):
seg2 = other[iseg2]
start2 = seg2.start()
stop2 = seg2.end()
else:
# pseudo-segment in the far future
start2 = 2000000000
stop2 = 2000000000
# save the intersection and return the length
self.__sci_segs = outlist
return len(self) | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"# we only deal with the case of two lists here",
"length1",
"=",
"len",
"(",
"self",
")",
"length2",
"=",
"len",
"(",
"other",
")",
"# initialize list of output segments",
"ostart",
"=",
"-",
"1",
"outli... | 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 | [
"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",
"."
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3252-L3310 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.union | 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
"""
# 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 start1 == -1:
i1 += 1
if i1 < length1:
start1 = self[i1].start()
stop1 = self[i1].end()
id = self[i1].id()
elif i2 == length2:
break
# if necessary, get a segment from list 2
if start2 == -1:
i2 += 1
if i2 < length2:
start2 = other[i2].start()
stop2 = other[i2].end()
elif i1 == length1:
break
# pick the earlier segment from the two lists
if start1 > -1 and ( start2 == -1 or start1 <= start2):
ustart = start1
ustop = stop1
# mark this segment has having been consumed
start1 = -1
elif start2 > -1:
ustart = start2
ustop = stop2
# mark this segment has having been consumed
start2 = -1
else:
break
# if the output segment is blank, initialize it; otherwise, see
# whether the new segment extends it or is disjoint
if ostart == -1:
ostart = ustart
ostop = ustop
elif ustart <= ostop:
if ustop > ostop:
# this extends the output segment
ostop = ustop
else:
# This lies entirely within the current output segment
pass
else:
# flush the current output segment, and replace it with the
# new segment
x = ScienceSegment(tuple([id,ostart,ostop,ostop-ostart]))
seglist.append(x)
ostart = ustart
ostop = ustop
# flush out the final output segment (if any)
if ostart != -1:
x = ScienceSegment(tuple([id,ostart,ostop,ostop-ostart]))
seglist.append(x)
self.__sci_segs = seglist
return len(self) | python | 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
"""
# 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 start1 == -1:
i1 += 1
if i1 < length1:
start1 = self[i1].start()
stop1 = self[i1].end()
id = self[i1].id()
elif i2 == length2:
break
# if necessary, get a segment from list 2
if start2 == -1:
i2 += 1
if i2 < length2:
start2 = other[i2].start()
stop2 = other[i2].end()
elif i1 == length1:
break
# pick the earlier segment from the two lists
if start1 > -1 and ( start2 == -1 or start1 <= start2):
ustart = start1
ustop = stop1
# mark this segment has having been consumed
start1 = -1
elif start2 > -1:
ustart = start2
ustop = stop2
# mark this segment has having been consumed
start2 = -1
else:
break
# if the output segment is blank, initialize it; otherwise, see
# whether the new segment extends it or is disjoint
if ostart == -1:
ostart = ustart
ostop = ustop
elif ustart <= ostop:
if ustop > ostop:
# this extends the output segment
ostop = ustop
else:
# This lies entirely within the current output segment
pass
else:
# flush the current output segment, and replace it with the
# new segment
x = ScienceSegment(tuple([id,ostart,ostop,ostop-ostart]))
seglist.append(x)
ostart = ustart
ostop = ustop
# flush out the final output segment (if any)
if ostart != -1:
x = ScienceSegment(tuple([id,ostart,ostop,ostop-ostart]))
seglist.append(x)
self.__sci_segs = seglist
return len(self) | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"# we only deal with the case of two lists here",
"length1",
"=",
"len",
"(",
"self",
")",
"length2",
"=",
"len",
"(",
"other",
")",
"# initialize list of output segments",
"ostart",
"=",
"-",
"1",
"seglist",
... | 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 | [
"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",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3314-L3396 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.coalesce | def coalesce(self):
"""
Coalesces any adjacent ScienceSegments. Returns the number of
ScienceSegments in the coalesced list.
"""
# 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()
id = seg.id()
if start > ostop:
# disconnected, so flush out the existing segment (if any)
if ostop >= 0:
x = ScienceSegment(tuple([id,ostart,ostop,ostop-ostart]))
outlist.append(x)
ostart = start
ostop = stop
elif stop > ostop:
# extend the current segment
ostop = stop
# flush out the final segment (if any)
if ostop >= 0:
x = ScienceSegment(tuple([id,ostart,ostop,ostop-ostart]))
outlist.append(x)
self.__sci_segs = outlist
return len(self) | python | def coalesce(self):
"""
Coalesces any adjacent ScienceSegments. Returns the number of
ScienceSegments in the coalesced list.
"""
# 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()
id = seg.id()
if start > ostop:
# disconnected, so flush out the existing segment (if any)
if ostop >= 0:
x = ScienceSegment(tuple([id,ostart,ostop,ostop-ostart]))
outlist.append(x)
ostart = start
ostop = stop
elif stop > ostop:
# extend the current segment
ostop = stop
# flush out the final segment (if any)
if ostop >= 0:
x = ScienceSegment(tuple([id,ostart,ostop,ostop-ostart]))
outlist.append(x)
self.__sci_segs = outlist
return len(self) | [
"def",
"coalesce",
"(",
"self",
")",
":",
"# 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 ... | Coalesces any adjacent ScienceSegments. Returns the number of
ScienceSegments in the coalesced list. | [
"Coalesces",
"any",
"adjacent",
"ScienceSegments",
".",
"Returns",
"the",
"number",
"of",
"ScienceSegments",
"in",
"the",
"coalesced",
"list",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3399-L3437 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.invert | def invert(self):
"""
Inverts the ScienceSegments in the class (i.e. set NOT). Returns the
number of ScienceSegments after inversion.
"""
# 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()
stop = seg.end()
if start < 0 or stop < start or start < ostart:
raise SegmentError, "Invalid list"
if start > 0:
x = ScienceSegment(tuple([0,ostart,start,start-ostart]))
outlist.append(x)
ostart = stop
if ostart < 1999999999:
x = ScienceSegment(tuple([0,ostart,1999999999,1999999999-ostart]))
outlist.append(x)
self.__sci_segs = outlist
return len(self) | python | def invert(self):
"""
Inverts the ScienceSegments in the class (i.e. set NOT). Returns the
number of ScienceSegments after inversion.
"""
# 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()
stop = seg.end()
if start < 0 or stop < start or start < ostart:
raise SegmentError, "Invalid list"
if start > 0:
x = ScienceSegment(tuple([0,ostart,start,start-ostart]))
outlist.append(x)
ostart = stop
if ostart < 1999999999:
x = ScienceSegment(tuple([0,ostart,1999999999,1999999999-ostart]))
outlist.append(x)
self.__sci_segs = outlist
return len(self) | [
"def",
"invert",
"(",
"self",
")",
":",
"# check for an empty list",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"# return a segment representing all time",
"self",
".",
"__sci_segs",
"=",
"ScienceSegment",
"(",
"tuple",
"(",
"[",
"0",
",",
"0",
",",
"199... | Inverts the ScienceSegments in the class (i.e. set NOT). Returns the
number of ScienceSegments after inversion. | [
"Inverts",
"the",
"ScienceSegments",
"in",
"the",
"class",
"(",
"i",
".",
"e",
".",
"set",
"NOT",
")",
".",
"Returns",
"the",
"number",
"of",
"ScienceSegments",
"after",
"inversion",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3440-L3469 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.play | def play(self):
"""
Keep only times in ScienceSegments which are in the playground
"""
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 start of seg
play_start = begin_s2+play_space*( 1 +
int((start - begin_s2 - play_len)/play_space) )
while play_start < stop:
if play_start > start:
ostart = play_start
else:
ostart = start
play_stop = play_start + play_len
if play_stop < stop:
ostop = play_stop
else:
ostop = stop
x = ScienceSegment(tuple([id, ostart, ostop, ostop-ostart]))
outlist.append(x)
# step forward
play_start = play_start + play_space
# save the playground segs and return the length
self.__sci_segs = outlist
return len(self) | python | def play(self):
"""
Keep only times in ScienceSegments which are in the playground
"""
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 start of seg
play_start = begin_s2+play_space*( 1 +
int((start - begin_s2 - play_len)/play_space) )
while play_start < stop:
if play_start > start:
ostart = play_start
else:
ostart = start
play_stop = play_start + play_len
if play_stop < stop:
ostop = play_stop
else:
ostop = stop
x = ScienceSegment(tuple([id, ostart, ostop, ostop-ostart]))
outlist.append(x)
# step forward
play_start = play_start + play_space
# save the playground segs and return the length
self.__sci_segs = outlist
return len(self) | [
"def",
"play",
"(",
"self",
")",
":",
"length",
"=",
"len",
"(",
"self",
")",
"# initialize list of output segments",
"ostart",
"=",
"-",
"1",
"outlist",
"=",
"[",
"]",
"begin_s2",
"=",
"729273613",
"play_space",
"=",
"6370",
"play_len",
"=",
"600",
"for",... | Keep only times in ScienceSegments which are in the playground | [
"Keep",
"only",
"times",
"in",
"ScienceSegments",
"which",
"are",
"in",
"the",
"playground"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3472-L3517 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.intersect_3 | def intersect_3(self, second, third):
"""
Intersection routine for three inputs. Built out of the intersect,
coalesce and play routines
"""
self.intersection(second)
self.intersection(third)
self.coalesce()
return len(self) | python | def intersect_3(self, second, third):
"""
Intersection routine for three inputs. Built out of the intersect,
coalesce and play routines
"""
self.intersection(second)
self.intersection(third)
self.coalesce()
return len(self) | [
"def",
"intersect_3",
"(",
"self",
",",
"second",
",",
"third",
")",
":",
"self",
".",
"intersection",
"(",
"second",
")",
"self",
".",
"intersection",
"(",
"third",
")",
"self",
".",
"coalesce",
"(",
")",
"return",
"len",
"(",
"self",
")"
] | Intersection routine for three inputs. Built out of the intersect,
coalesce and play routines | [
"Intersection",
"routine",
"for",
"three",
"inputs",
".",
"Built",
"out",
"of",
"the",
"intersect",
"coalesce",
"and",
"play",
"routines"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3520-L3528 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.intersect_4 | def intersect_4(self, second, third, fourth):
"""
Intersection routine for four inputs.
"""
self.intersection(second)
self.intersection(third)
self.intersection(fourth)
self.coalesce()
return len(self) | python | def intersect_4(self, second, third, fourth):
"""
Intersection routine for four inputs.
"""
self.intersection(second)
self.intersection(third)
self.intersection(fourth)
self.coalesce()
return len(self) | [
"def",
"intersect_4",
"(",
"self",
",",
"second",
",",
"third",
",",
"fourth",
")",
":",
"self",
".",
"intersection",
"(",
"second",
")",
"self",
".",
"intersection",
"(",
"third",
")",
"self",
".",
"intersection",
"(",
"fourth",
")",
"self",
".",
"coa... | Intersection routine for four inputs. | [
"Intersection",
"routine",
"for",
"four",
"inputs",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3530-L3538 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | ScienceData.split | def split(self, dt):
"""
Split the segments in the list is subsegments at least as long as dt
"""
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 = ScienceSegment(tuple([id,start,tmpstop,tmpstop-start]))
outlist.append(x)
start = tmpstop
# save the split list and return length
self.__sci_segs = outlist
return len(self) | python | def split(self, dt):
"""
Split the segments in the list is subsegments at least as long as dt
"""
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 = ScienceSegment(tuple([id,start,tmpstop,tmpstop-start]))
outlist.append(x)
start = tmpstop
# save the split list and return length
self.__sci_segs = outlist
return len(self) | [
"def",
"split",
"(",
"self",
",",
"dt",
")",
":",
"outlist",
"=",
"[",
"]",
"for",
"seg",
"in",
"self",
":",
"start",
"=",
"seg",
".",
"start",
"(",
")",
"stop",
"=",
"seg",
".",
"end",
"(",
")",
"id",
"=",
"seg",
".",
"id",
"(",
")",
"whil... | Split the segments in the list is subsegments at least as long as dt | [
"Split",
"the",
"segments",
"in",
"the",
"list",
"is",
"subsegments",
"at",
"least",
"as",
"long",
"as",
"dt"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3540-L3562 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | LsyncCache.group | def group(self, lst, n):
"""
Group an iterable into an n-tuples iterable. Incomplete
tuples are discarded
"""
return itertools.izip(*[itertools.islice(lst, i, None, n) for i in range(n)]) | python | def group(self, lst, n):
"""
Group an iterable into an n-tuples iterable. Incomplete
tuples are discarded
"""
return itertools.izip(*[itertools.islice(lst, i, None, n) for i in range(n)]) | [
"def",
"group",
"(",
"self",
",",
"lst",
",",
"n",
")",
":",
"return",
"itertools",
".",
"izip",
"(",
"*",
"[",
"itertools",
".",
"islice",
"(",
"lst",
",",
"i",
",",
"None",
",",
"n",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
")"
] | Group an iterable into an n-tuples iterable. Incomplete
tuples are discarded | [
"Group",
"an",
"iterable",
"into",
"an",
"n",
"-",
"tuples",
"iterable",
".",
"Incomplete",
"tuples",
"are",
"discarded"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3580-L3585 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | LsyncCache.parse | 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) Number of frames in the files (assumed to be 1)
1.5) Duration of the frame files.
2) UNIX timestamp for directory modification time.
3) Number of files that that match the above pattern in the directory.
4) List of time range or segments [start, stop)
We store the cache for each site and frameType combination
as a dictionary where the keys are (directory, duration)
tuples and the values are segment lists.
Since the cache file is already coalesced we do not
have to call the coalesce method on the segment lists.
"""
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't match the regex
if type_filter and type_filter.search(line) is None:
continue
# split on spaces and then comma to get the parts
header, modTime, fileCount, times = line.strip().split(' ', 3)
dir, site, frameType, frameCount, duration = header.split(',')
duration = int(duration)
# times string has form { t1 t2 t3 t4 t5 t6 ... tN t(N+1) }
# where the (ti, t(i+1)) represent segments
#
# first turn the times string into a list of integers
times = [ int(s) for s in times[1:-1].split(' ') ]
# group the integers by two and turn those tuples into segments
segments = [ pycbc_glue.segments.segment(a) for a in self.group(times, 2) ]
# initialize if necessary for this site
if not gwfDict.has_key(site):
gwfDict[site] = {}
# initialize if necessary for this frame type
if not gwfDict[site].has_key(frameType):
gwfDict[site][frameType] = {}
# record segment list as value indexed by the (directory, duration) tuple
key = (dir, duration)
if gwfDict[site][frameType].has_key(key):
msg = "The combination %s is not unique in the frame cache file" \
% str(key)
raise RuntimeError, msg
gwfDict[site][frameType][key] = pycbc_glue.segments.segmentlist(segments)
f.close()
cache['gwf'] = gwfDict | python | 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) Number of frames in the files (assumed to be 1)
1.5) Duration of the frame files.
2) UNIX timestamp for directory modification time.
3) Number of files that that match the above pattern in the directory.
4) List of time range or segments [start, stop)
We store the cache for each site and frameType combination
as a dictionary where the keys are (directory, duration)
tuples and the values are segment lists.
Since the cache file is already coalesced we do not
have to call the coalesce method on the segment lists.
"""
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't match the regex
if type_filter and type_filter.search(line) is None:
continue
# split on spaces and then comma to get the parts
header, modTime, fileCount, times = line.strip().split(' ', 3)
dir, site, frameType, frameCount, duration = header.split(',')
duration = int(duration)
# times string has form { t1 t2 t3 t4 t5 t6 ... tN t(N+1) }
# where the (ti, t(i+1)) represent segments
#
# first turn the times string into a list of integers
times = [ int(s) for s in times[1:-1].split(' ') ]
# group the integers by two and turn those tuples into segments
segments = [ pycbc_glue.segments.segment(a) for a in self.group(times, 2) ]
# initialize if necessary for this site
if not gwfDict.has_key(site):
gwfDict[site] = {}
# initialize if necessary for this frame type
if not gwfDict[site].has_key(frameType):
gwfDict[site][frameType] = {}
# record segment list as value indexed by the (directory, duration) tuple
key = (dir, duration)
if gwfDict[site][frameType].has_key(key):
msg = "The combination %s is not unique in the frame cache file" \
% str(key)
raise RuntimeError, msg
gwfDict[site][frameType][key] = pycbc_glue.segments.segmentlist(segments)
f.close()
cache['gwf'] = gwfDict | [
"def",
"parse",
"(",
"self",
",",
"type_regex",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"__path",
"cache",
"=",
"self",
".",
"cache",
"if",
"type_regex",
":",
"type_filter",
"=",
"re",
".",
"compile",
"(",
"type_regex",
")",
"else",
":",
"ty... | 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) Number of frames in the files (assumed to be 1)
1.5) Duration of the frame files.
2) UNIX timestamp for directory modification time.
3) Number of files that that match the above pattern in the directory.
4) List of time range or segments [start, stop)
We store the cache for each site and frameType combination
as a dictionary where the keys are (directory, duration)
tuples and the values are segment lists.
Since the cache file is already coalesced we do not
have to call the coalesce method on the segment lists. | [
"Each",
"line",
"of",
"the",
"frame",
"cache",
"file",
"is",
"like",
"the",
"following",
":"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3587-L3664 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | LSCDataFindNode.__set_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.
"""
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) | python | 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.
"""
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",
")",
":",
"if",
"self",
".",
"__start",
"and",
"self",
".",
"__end",
"and",
"self",
".",
"__observatory",
"and",
"self",
".",
"__type",
":",
"self",
".",
"__output",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self"... | Private method to set the file to write the cache to. Automaticaly set
once the ifo, start and end times have been set. | [
"Private",
"method",
"to",
"set",
"the",
"file",
"to",
"write",
"the",
"cache",
"to",
".",
"Automaticaly",
"set",
"once",
"the",
"ifo",
"start",
"and",
"end",
"times",
"have",
"been",
"set",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3814-L3821 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | LSCDataFindNode.set_start | def set_start(self,time,pad = None):
"""
Set the start time of the datafind query.
@param time: GPS start time of query.
"""
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() | python | def set_start(self,time,pad = None):
"""
Set the start time of the datafind query.
@param time: GPS start time of query.
"""
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",
")",
":",
"if",
"pad",
":",
"self",
".",
"add_var_opt",
"(",
"'gps-start-time'",
",",
"int",
"(",
"time",
")",
"-",
"int",
"(",
"pad",
")",
")",
"else",
":",
"self",
".",
"add... | Set the start time of the datafind query.
@param time: GPS start time of query. | [
"Set",
"the",
"start",
"time",
"of",
"the",
"datafind",
"query",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3823-L3833 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | LSCDataFindNode.set_end | def set_end(self,time):
"""
Set the end time of the datafind query.
@param time: GPS end time of query.
"""
self.add_var_opt('gps-end-time', time)
self.__end = time
self.__set_output() | python | def set_end(self,time):
"""
Set the end time of the datafind query.
@param time: GPS end time of query.
"""
self.add_var_opt('gps-end-time', time)
self.__end = time
self.__set_output() | [
"def",
"set_end",
"(",
"self",
",",
"time",
")",
":",
"self",
".",
"add_var_opt",
"(",
"'gps-end-time'",
",",
"time",
")",
"self",
".",
"__end",
"=",
"time",
"self",
".",
"__set_output",
"(",
")"
] | Set the end time of the datafind query.
@param time: GPS end time of query. | [
"Set",
"the",
"end",
"time",
"of",
"the",
"datafind",
"query",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3841-L3848 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | LSCDataFindNode.set_observatory | 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.
"""
self.add_var_opt('observatory',obs)
self.__observatory = str(obs)
self.__set_output() | python | 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.
"""
self.add_var_opt('observatory',obs)
self.__observatory = str(obs)
self.__set_output() | [
"def",
"set_observatory",
"(",
"self",
",",
"obs",
")",
":",
"self",
".",
"add_var_opt",
"(",
"'observatory'",
",",
"obs",
")",
"self",
".",
"__observatory",
"=",
"str",
"(",
"obs",
")",
"self",
".",
"__set_output",
"(",
")"
] | 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. | [
"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"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3856-L3866 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | LSCDataFindNode.set_type | def set_type(self,type):
"""
sets the frame type that we are querying
"""
self.add_var_opt('type',str(type))
self.__type = str(type)
self.__set_output() | python | def set_type(self,type):
"""
sets the frame type that we are querying
"""
self.add_var_opt('type',str(type))
self.__type = str(type)
self.__set_output() | [
"def",
"set_type",
"(",
"self",
",",
"type",
")",
":",
"self",
".",
"add_var_opt",
"(",
"'type'",
",",
"str",
"(",
"type",
")",
")",
"self",
".",
"__type",
"=",
"str",
"(",
"type",
")",
"self",
".",
"__set_output",
"(",
")"
] | sets the frame type that we are querying | [
"sets",
"the",
"frame",
"type",
"that",
"we",
"are",
"querying"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3874-L3880 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | LSCDataFindNode.get_output | 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)
"""
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:
self.__lfn_list = self.job().lsync_cache().get_lfns(
self.get_observatory(), self.get_type(),
self.get_start(), self.get_end())
else:
# try querying the ligo_data_find server
try:
server = os.environ['LIGO_DATAFIND_SERVER']
except KeyError:
raise RuntimeError, \
"Environment variable LIGO_DATAFIND_SERVER is not set"
try:
h = httplib.HTTPConnection(server)
except:
# try and get a proxy or certificate
# FIXME this doesn't check that it is valid, though
cert = None
key = None
try:
proxy = os.environ['X509_USER_PROXY']
cert = proxy
key = proxy
except:
try:
cert = os.environ['X509_USER_CERT']
key = os.environ['X509_USER_KEY']
except:
uid = os.getuid()
proxy_path = "/tmp/x509up_u%d" % uid
if os.access(path, os.R_OK):
cert = proxy_path
key = proxy_path
h = httplib.HTTPSConnection(server, key_file = key, cert_file = cert)
# construct the URL for a simple data find query
url = "/LDR/services/data/v1/gwf/%s/%s/%s,%s.json" % (
self.get_observatory(), self.get_type(),
str(self.get_start()), str(self.get_end()))
# query the server
h.request("GET", url)
response = h.getresponse()
if response.status != 200:
msg = "Server returned code %d: %s" % (response.status, response.reason)
body = response.read()
msg += body
raise RuntimeError, msg
# since status is 200 OK read the URLs
body = response.read()
# decode the JSON
urlList = cjson.decode(body)
lfnDict = {}
for url in urlList:
path = urlparse.urlparse(url)[2]
lfn = os.path.split(path)[1]
lfnDict[lfn] = 1
self.__lfn_list = lfnDict.keys()
self.__lfn_list.sort()
return self.__lfn_list
else:
return self.__output | python | 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)
"""
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:
self.__lfn_list = self.job().lsync_cache().get_lfns(
self.get_observatory(), self.get_type(),
self.get_start(), self.get_end())
else:
# try querying the ligo_data_find server
try:
server = os.environ['LIGO_DATAFIND_SERVER']
except KeyError:
raise RuntimeError, \
"Environment variable LIGO_DATAFIND_SERVER is not set"
try:
h = httplib.HTTPConnection(server)
except:
# try and get a proxy or certificate
# FIXME this doesn't check that it is valid, though
cert = None
key = None
try:
proxy = os.environ['X509_USER_PROXY']
cert = proxy
key = proxy
except:
try:
cert = os.environ['X509_USER_CERT']
key = os.environ['X509_USER_KEY']
except:
uid = os.getuid()
proxy_path = "/tmp/x509up_u%d" % uid
if os.access(path, os.R_OK):
cert = proxy_path
key = proxy_path
h = httplib.HTTPSConnection(server, key_file = key, cert_file = cert)
# construct the URL for a simple data find query
url = "/LDR/services/data/v1/gwf/%s/%s/%s,%s.json" % (
self.get_observatory(), self.get_type(),
str(self.get_start()), str(self.get_end()))
# query the server
h.request("GET", url)
response = h.getresponse()
if response.status != 200:
msg = "Server returned code %d: %s" % (response.status, response.reason)
body = response.read()
msg += body
raise RuntimeError, msg
# since status is 200 OK read the URLs
body = response.read()
# decode the JSON
urlList = cjson.decode(body)
lfnDict = {}
for url in urlList:
path = urlparse.urlparse(url)[2]
lfn = os.path.split(path)[1]
lfnDict[lfn] = 1
self.__lfn_list = lfnDict.keys()
self.__lfn_list.sort()
return self.__lfn_list
else:
return self.__output | [
"def",
"get_output",
"(",
"self",
")",
":",
"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",
... | Return the output file, i.e. the file containing the frame cache data.
or the files itself as tuple (for DAX) | [
"Return",
"the",
"output",
"file",
"i",
".",
"e",
".",
"the",
"file",
"containing",
"the",
"frame",
"cache",
"data",
".",
"or",
"the",
"files",
"itself",
"as",
"tuple",
"(",
"for",
"DAX",
")"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3891-L3971 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | LigolwSqliteNode.set_xml_output | def set_xml_output(self, xml_file):
"""
Tell ligolw_sqlite to dump the contents of the database to a file.
"""
if self.get_database() is None:
raise ValueError, "no database specified"
self.add_file_opt('extract', xml_file)
self.__xml_output = xml_file | python | def set_xml_output(self, xml_file):
"""
Tell ligolw_sqlite to dump the contents of the database to a file.
"""
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",
")",
":",
"if",
"self",
".",
"get_database",
"(",
")",
"is",
"None",
":",
"raise",
"ValueError",
",",
"\"no database specified\"",
"self",
".",
"add_file_opt",
"(",
"'extract'",
",",
"xml_file",
")",
"se... | Tell ligolw_sqlite to dump the contents of the database to a file. | [
"Tell",
"ligolw_sqlite",
"to",
"dump",
"the",
"contents",
"of",
"the",
"database",
"to",
"a",
"file",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L4317-L4324 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | LigolwSqliteNode.get_output | def get_output(self):
"""
Override standard get_output to return xml-file if xml-file is specified.
Otherwise, will return database.
"""
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" | python | def get_output(self):
"""
Override standard get_output to return xml-file if xml-file is specified.
Otherwise, will return database.
"""
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",
")",
":",
"if",
"self",
".",
"__xml_output",
":",
"return",
"self",
".",
"__xml_output",
"elif",
"self",
".",
"get_database",
"(",
")",
":",
"return",
"self",
".",
"get_database",
"(",
")",
"else",
":",
"raise",
"ValueEr... | Override standard get_output to return xml-file if xml-file is specified.
Otherwise, will return database. | [
"Override",
"standard",
"get_output",
"to",
"return",
"xml",
"-",
"file",
"if",
"xml",
"-",
"file",
"is",
"specified",
".",
"Otherwise",
"will",
"return",
"database",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L4326-L4336 |
idlesign/srptools | setup.py | get_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.
"""
contents = read(os.path.join(PATH_BASE, 'srptools', '__init__.py'))
version = re.search('VERSION = \(([^)]+)\)', contents)
version = version.group(1).replace(', ', '.').strip()
return version | python | 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.
"""
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",
"(",
")",
":",
"contents",
"=",
"read",
"(",
"os",
".",
"path",
".",
"join",
"(",
"PATH_BASE",
",",
"'srptools'",
",",
"'__init__.py'",
")",
")",
"version",
"=",
"re",
".",
"search",
"(",
"'VERSION = \\(([^)]+)\\)'",
",",
"contents",
... | 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. | [
"Reads",
"version",
"number",
"."
] | train | https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/setup.py#L16-L28 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/coincs.py | get_coinc_def_id | 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.
"""
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)
# make sure the next_id attribute is correct
coincdeftable.sync_next_id()
# get the id
return coincdeftable.get_coinc_def_id(search, coinc_type, create_new = create_new, description = description) | python | 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.
"""
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)
# make sure the next_id attribute is correct
coincdeftable.sync_next_id()
# get the id
return coincdeftable.get_coinc_def_id(search, coinc_type, create_new = create_new, description = description) | [
"def",
"get_coinc_def_id",
"(",
"xmldoc",
",",
"search",
",",
"coinc_type",
",",
"create_new",
"=",
"True",
",",
"description",
"=",
"u\"\"",
")",
":",
"try",
":",
"coincdeftable",
"=",
"lsctables",
".",
"CoincDefTable",
".",
"get_table",
"(",
"xmldoc",
")",... | 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. | [
"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",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/coincs.py#L50-L70 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | fromfilenames | 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 Technical Note LIGO-T010150-00-E, which allows the
start time and duration appearing in the file name to be
non-integers.
NOTE: the output is a segmentlist as described by the file names;
if the file names are not in time order, or describe overlaping
segments, then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use.
"""
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 | python | 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 Technical Note LIGO-T010150-00-E, which allows the
start time and duration appearing in the file name to be
non-integers.
NOTE: the output is a segmentlist as described by the file names;
if the file names are not in time order, or describe overlaping
segments, then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use.
"""
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",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"-([\\d.]+)-([\\d.]+)\\.[\\w_+#]+\\Z\"",
")",
"l",
"=",
"segments",
".",
"segmentlist",
"(",
")",
"for",
"name",
"in",
"filenames",
... | 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 Technical Note LIGO-T010150-00-E, which allows the
start time and duration appearing in the file name to be
non-integers.
NOTE: the output is a segmentlist as described by the file names;
if the file names are not in time order, or describe overlaping
segments, then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use. | [
"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",... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L62-L86 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | fromlalcache | 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_glue.lal import LIGOTimeGPS
>>> cache_seglists = fromlalcache(open(filename), coltype = LIGOTimeGPS).coalesce()
See also:
pycbc_glue.lal.CacheEntry
"""
return segments.segmentlist(lal.CacheEntry(l, coltype = coltype).segment for l in cachefile) | python | 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_glue.lal import LIGOTimeGPS
>>> cache_seglists = fromlalcache(open(filename), coltype = LIGOTimeGPS).coalesce()
See also:
pycbc_glue.lal.CacheEntry
"""
return segments.segmentlist(lal.CacheEntry(l, coltype = coltype).segment for l in cachefile) | [
"def",
"fromlalcache",
"(",
"cachefile",
",",
"coltype",
"=",
"int",
")",
":",
"return",
"segments",
".",
"segmentlist",
"(",
"lal",
".",
"CacheEntry",
"(",
"l",
",",
"coltype",
"=",
"coltype",
")",
".",
"segment",
"for",
"l",
"in",
"cachefile",
")"
] | 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_glue.lal import LIGOTimeGPS
>>> cache_seglists = fromlalcache(open(filename), coltype = LIGOTimeGPS).coalesce()
See also:
pycbc_glue.lal.CacheEntry | [
"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",
"segmen... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L94-L111 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | fromsegwizard | 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 argument.
Two-column, three-column, and four-column segwizard files are
recognized, but the entire file must be in the same format, which
is decided by the first parsed line. If strict is True and the
file is in three- or four-column format, then each segment's
duration is checked against that column in the input file.
NOTE: the output is a segmentlist as described by the file; if
the segments in the input file are not coalesced or out of order,
then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use.
"""
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 = None
l = segments.segmentlist()
for line in file:
line = commentpat.split(line)[0]
if not line:
continue
try:
[tokens] = fourcolsegpat.findall(line)
num = int(tokens[0])
seg = segments.segment(map(coltype, tokens[1:3]))
duration = coltype(tokens[3])
this_line_format = 4
except ValueError:
try:
[tokens] = threecolsegpat.findall(line)
seg = segments.segment(map(coltype, tokens[0:2]))
duration = coltype(tokens[2])
this_line_format = 3
except ValueError:
try:
[tokens] = twocolsegpat.findall(line)
seg = segments.segment(map(coltype, tokens[0:2]))
duration = abs(seg)
this_line_format = 2
except ValueError:
break
if strict:
if abs(seg) != duration:
raise ValueError("segment '%s' has incorrect duration" % line)
if format is None:
format = this_line_format
elif format != this_line_format:
raise ValueError("segment '%s' format mismatch" % line)
l.append(seg)
return l | python | 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 argument.
Two-column, three-column, and four-column segwizard files are
recognized, but the entire file must be in the same format, which
is decided by the first parsed line. If strict is True and the
file is in three- or four-column format, then each segment's
duration is checked against that column in the input file.
NOTE: the output is a segmentlist as described by the file; if
the segments in the input file are not coalesced or out of order,
then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use.
"""
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 = None
l = segments.segmentlist()
for line in file:
line = commentpat.split(line)[0]
if not line:
continue
try:
[tokens] = fourcolsegpat.findall(line)
num = int(tokens[0])
seg = segments.segment(map(coltype, tokens[1:3]))
duration = coltype(tokens[3])
this_line_format = 4
except ValueError:
try:
[tokens] = threecolsegpat.findall(line)
seg = segments.segment(map(coltype, tokens[0:2]))
duration = coltype(tokens[2])
this_line_format = 3
except ValueError:
try:
[tokens] = twocolsegpat.findall(line)
seg = segments.segment(map(coltype, tokens[0:2]))
duration = abs(seg)
this_line_format = 2
except ValueError:
break
if strict:
if abs(seg) != duration:
raise ValueError("segment '%s' has incorrect duration" % line)
if format is None:
format = this_line_format
elif format != this_line_format:
raise ValueError("segment '%s' format mismatch" % line)
l.append(seg)
return l | [
"def",
"fromsegwizard",
"(",
"file",
",",
"coltype",
"=",
"int",
",",
"strict",
"=",
"True",
")",
":",
"commentpat",
"=",
"re",
".",
"compile",
"(",
"r\"\\s*([#;].*)?\\Z\"",
",",
"re",
".",
"DOTALL",
")",
"twocolsegpat",
"=",
"re",
".",
"compile",
"(",
... | 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 argument.
Two-column, three-column, and four-column segwizard files are
recognized, but the entire file must be in the same format, which
is decided by the first parsed line. If strict is True and the
file is in three- or four-column format, then each segment's
duration is checked against that column in the input file.
NOTE: the output is a segmentlist as described by the file; if
the segments in the input file are not coalesced or out of order,
then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use. | [
"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",
")"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L119-L175 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | tosegwizard | 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.
"""
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)))) | python | 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.
"""
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",
")",
":",
"if",
"header",
":",
"print",
">>",
"file",
",",
"\"# seg\\tstart \\tstop \\tduration\"",
"for",
"n",
",",
"seg",
"in",
"enumerate",
... | 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. | [
"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",
"colum... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L178-L189 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | fromtama | 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.
NOTE: TAMA locked-segments files contain non-integer start and end
times, so the default column type is set to LIGOTimeGPS.
NOTE: the output is a segmentlist as described by the file; if
the segments in the input file are not coalesced or out of order,
then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use.
"""
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 | python | 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.
NOTE: TAMA locked-segments files contain non-integer start and end
times, so the default column type is set to LIGOTimeGPS.
NOTE: the output is a segmentlist as described by the file; if
the segments in the input file are not coalesced or out of order,
then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use.
"""
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",
")",
":",
"segmentpat",
"=",
"re",
".",
"compile",
"(",
"r\"\\A\\s*\\S+\\s+\\S+\\s+\\S+\\s+([\\d.+-eE]+)\\s+([\\d.+-eE]+)\"",
")",
"l",
"=",
"segments",
".",
"segmentlist",
"(",
")",
... | 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.
NOTE: TAMA locked-segments files contain non-integer start and end
times, so the default column type is set to LIGOTimeGPS.
NOTE: the output is a segmentlist as described by the file; if
the segments in the input file are not coalesced or out of order,
then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use. | [
"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",
")",
".",... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L197-L221 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | from_range_strings | 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 configuration files.
NOTE: the output is a segmentlist as described by the strings; if
the segments in the input file are not coalesced or out of order,
then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use.
Example:
>>> text = "0:10,35,100:"
>>> from_range_strings(text.split(","))
[segment(0, 10), segment(35, 35), segment(100, infinity)]
"""
# 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(range)
if parts[0] == "":
parts[0] = segments.NegInfinity
else:
parts[0] = boundtype(parts[0])
if parts[1] == "":
parts[1] = segments.PosInfinity
else:
parts[1] = boundtype(parts[1])
segs[i] = segments.segment(parts[0], parts[1])
# success
return segs | python | 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 configuration files.
NOTE: the output is a segmentlist as described by the strings; if
the segments in the input file are not coalesced or out of order,
then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use.
Example:
>>> text = "0:10,35,100:"
>>> from_range_strings(text.split(","))
[segment(0, 10), segment(35, 35), segment(100, infinity)]
"""
# 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(range)
if parts[0] == "":
parts[0] = segments.NegInfinity
else:
parts[0] = boundtype(parts[0])
if parts[1] == "":
parts[1] = segments.PosInfinity
else:
parts[1] = boundtype(parts[1])
segs[i] = segments.segment(parts[0], parts[1])
# success
return segs | [
"def",
"from_range_strings",
"(",
"ranges",
",",
"boundtype",
"=",
"int",
")",
":",
"# preallocate segmentlist",
"segs",
"=",
"segments",
".",
"segmentlist",
"(",
"[",
"None",
"]",
"*",
"len",
"(",
"ranges",
")",
")",
"# iterate over strings",
"for",
"i",
",... | 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 configuration files.
NOTE: the output is a segmentlist as described by the strings; if
the segments in the input file are not coalesced or out of order,
then thusly shall be the output of this function. It is
recommended that this function's output be coalesced before use.
Example:
>>> text = "0:10,35,100:"
>>> from_range_strings(text.split(","))
[segment(0, 10), segment(35, 35), segment(100, infinity)] | [
"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",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L229-L271 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | to_range_strings | 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), segment(100, infinity())])
>>> ",".join(to_range_strings(segs))
'0:10,35,100:'
"""
# 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 not segments.PosInfinity):
ranges[i] = ":%s" % str(seg[1])
elif (seg[0] is not segments.NegInfinity) and (seg[1] is segments.PosInfinity):
ranges[i] = "%s:" % str(seg[0])
elif (seg[0] is not segments.NegInfinity) and (seg[1] is not segments.PosInfinity):
ranges[i] = "%s:%s" % (str(seg[0]), str(seg[1]))
else:
raise ValueError(seg)
# success
return ranges | python | 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), segment(100, infinity())])
>>> ",".join(to_range_strings(segs))
'0:10,35,100:'
"""
# 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 not segments.PosInfinity):
ranges[i] = ":%s" % str(seg[1])
elif (seg[0] is not segments.NegInfinity) and (seg[1] is segments.PosInfinity):
ranges[i] = "%s:" % str(seg[0])
elif (seg[0] is not segments.NegInfinity) and (seg[1] is not segments.PosInfinity):
ranges[i] = "%s:%s" % (str(seg[0]), str(seg[1]))
else:
raise ValueError(seg)
# success
return ranges | [
"def",
"to_range_strings",
"(",
"seglist",
")",
":",
"# preallocate the string list",
"ranges",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"seglist",
")",
"# iterate over segments",
"for",
"i",
",",
"seg",
"in",
"enumerate",
"(",
"seglist",
")",
":",
"if",
"not... | 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), segment(100, infinity())])
>>> ",".join(to_range_strings(segs))
'0:10,35,100:' | [
"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",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L274-L307 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | segmentlistdict_to_short_string | 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
strings are combined using "/" to delimit them.
Example:
>>> from pycbc_glue.segments import *
>>> segs = segmentlistdict({"H1": segmentlist([segment(0, 10), segment(35, 35), segment(100, infinity())]), "L1": segmentlist([segment(5, 15), segment(45, 60)])})
>>> segmentlistdict_to_short_string(segs)
'H1=0:10,35,100:/L1=5:15,45:60'
This function, and its inverse segmentlistdict_from_short_string(),
are intended to be used to allow small segmentlistdict objects to
be encoded in command line options and config files. For large
segmentlistdict objects or when multiple sets of segmentlists are
required, the LIGO Light Weight XML encoding available through the
pycbc_glue.ligolw library should be used.
"""
return "/".join(["%s=%s" % (str(key), ",".join(to_range_strings(value))) for key, value in seglists.items()]) | python | 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
strings are combined using "/" to delimit them.
Example:
>>> from pycbc_glue.segments import *
>>> segs = segmentlistdict({"H1": segmentlist([segment(0, 10), segment(35, 35), segment(100, infinity())]), "L1": segmentlist([segment(5, 15), segment(45, 60)])})
>>> segmentlistdict_to_short_string(segs)
'H1=0:10,35,100:/L1=5:15,45:60'
This function, and its inverse segmentlistdict_from_short_string(),
are intended to be used to allow small segmentlistdict objects to
be encoded in command line options and config files. For large
segmentlistdict objects or when multiple sets of segmentlists are
required, the LIGO Light Weight XML encoding available through the
pycbc_glue.ligolw library should be used.
"""
return "/".join(["%s=%s" % (str(key), ",".join(to_range_strings(value))) for key, value in seglists.items()]) | [
"def",
"segmentlistdict_to_short_string",
"(",
"seglists",
")",
":",
"return",
"\"/\"",
".",
"join",
"(",
"[",
"\"%s=%s\"",
"%",
"(",
"str",
"(",
"key",
")",
",",
"\",\"",
".",
"join",
"(",
"to_range_strings",
"(",
"value",
")",
")",
")",
"for",
"key",
... | 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
strings are combined using "/" to delimit them.
Example:
>>> from pycbc_glue.segments import *
>>> segs = segmentlistdict({"H1": segmentlist([segment(0, 10), segment(35, 35), segment(100, infinity())]), "L1": segmentlist([segment(5, 15), segment(45, 60)])})
>>> segmentlistdict_to_short_string(segs)
'H1=0:10,35,100:/L1=5:15,45:60'
This function, and its inverse segmentlistdict_from_short_string(),
are intended to be used to allow small segmentlistdict objects to
be encoded in command line options and config files. For large
segmentlistdict objects or when multiple sets of segmentlists are
required, the LIGO Light Weight XML encoding available through the
pycbc_glue.ligolw library should be used. | [
"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",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L310-L333 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | segmentlistdict_from_short_string | 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:
>>> segmentlistdict_from_short_string("H1=0:10,35,100:/L1=5:15,45:60")
{'H1': [segment(0, 10), segment(35, 35), segment(100, infinity)], 'L1': [segment(5, 15), segment(45, 60)]}
This function, and its inverse segmentlistdict_to_short_string(),
are intended to be used to allow small segmentlistdict objects to
be encoded in command line options and config files. For large
segmentlistdict objects or when multiple sets of segmentlists are
required, the LIGO Light Weight XML encoding available through the
pycbc_glue.ligolw library should be used.
"""
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 | python | 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:
>>> segmentlistdict_from_short_string("H1=0:10,35,100:/L1=5:15,45:60")
{'H1': [segment(0, 10), segment(35, 35), segment(100, infinity)], 'L1': [segment(5, 15), segment(45, 60)]}
This function, and its inverse segmentlistdict_to_short_string(),
are intended to be used to allow small segmentlistdict objects to
be encoded in command line options and config files. For large
segmentlistdict objects or when multiple sets of segmentlists are
required, the LIGO Light Weight XML encoding available through the
pycbc_glue.ligolw library should be used.
"""
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",
")",
":",
"d",
"=",
"segments",
".",
"segmentlistdict",
"(",
")",
"for",
"token",
"in",
"s",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"/\"",
")",
":",
"key",
",",
... | 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:
>>> segmentlistdict_from_short_string("H1=0:10,35,100:/L1=5:15,45:60")
{'H1': [segment(0, 10), segment(35, 35), segment(100, infinity)], 'L1': [segment(5, 15), segment(45, 60)]}
This function, and its inverse segmentlistdict_to_short_string(),
are intended to be used to allow small segmentlistdict objects to
be encoded in command line options and config files. For large
segmentlistdict objects or when multiple sets of segmentlists are
required, the LIGO Light Weight XML encoding available through the
pycbc_glue.ligolw library should be used. | [
"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",... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L336-L360 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | from_bitstream | 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([[], [[]], [[]], [], []], 1013968613, 0.125))
[segment(1013968613.125, 1013968613.375)]
"""
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 * dt)
i = j # advance to end of block
i += 1 | python | 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([[], [[]], [[]], [], []], 1013968613, 0.125))
[segment(1013968613.125, 1013968613.375)]
"""
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 * dt)
i = j # advance to end of block
i += 1 | [
"def",
"from_bitstream",
"(",
"bitstream",
",",
"start",
",",
"dt",
",",
"minlen",
"=",
"1",
")",
":",
"bitstream",
"=",
"iter",
"(",
"bitstream",
")",
"i",
"=",
"0",
"while",
"1",
":",
"if",
"bitstream",
".",
"next",
"(",
")",
":",
"# found start of... | 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([[], [[]], [[]], [], []], 1013968613, 0.125))
[segment(1013968613.125, 1013968613.375)] | [
"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",
"."... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L363-L389 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | S2playground | 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)]
"""
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]) | python | 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)]
"""
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",
")",
":",
"lo",
"=",
"int",
"(",
"extent",
"[",
"0",
"]",
")",
"lo",
"-=",
"(",
"lo",
"-",
"729273613",
")",
"%",
"6370",
"hi",
"=",
"int",
"(",
"extent",
"[",
"1",
"]",
")",
"+",
"1",
"return",
"segments",... | 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)] | [
"Return",
"a",
"segmentlist",
"identifying",
"the",
"S2",
"playground",
"times",
"within",
"the",
"interval",
"defined",
"by",
"the",
"segment",
"extent",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L401-L415 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | segmentlist_range | 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 can be any
objects which support basic arithmetic operations.
Example:
>>> from pycbc_glue.segments import *
>>> segmentlist(segmentlist_range(0, 15, 5))
[segment(0, 5), segment(5, 10), segment(10, 15)]
>>> segmentlist(segmentlist_range('', 'xxx', 'x'))
[segment('', 'x'), segment('x', 'xx'), segment('xx', 'xxx')]
"""
n = 1
b = start
while True:
a, b = b, start + n * period
if b > stop:
break
yield segments.segment(a, b)
n += 1 | python | 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 can be any
objects which support basic arithmetic operations.
Example:
>>> from pycbc_glue.segments import *
>>> segmentlist(segmentlist_range(0, 15, 5))
[segment(0, 5), segment(5, 10), segment(10, 15)]
>>> segmentlist(segmentlist_range('', 'xxx', 'x'))
[segment('', 'x'), segment('x', 'xx'), segment('xx', 'xxx')]
"""
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",
")",
":",
"n",
"=",
"1",
"b",
"=",
"start",
"while",
"True",
":",
"a",
",",
"b",
"=",
"b",
",",
"start",
"+",
"n",
"*",
"period",
"if",
"b",
">",
"stop",
":",
"break",
"yield... | 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 can be any
objects which support basic arithmetic operations.
Example:
>>> from pycbc_glue.segments import *
>>> segmentlist(segmentlist_range(0, 15, 5))
[segment(0, 5), segment(5, 10), segment(10, 15)]
>>> segmentlist(segmentlist_range('', 'xxx', 'x'))
[segment('', 'x'), segment('x', 'xx'), segment('xx', 'xxx')] | [
"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",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L418-L442 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | Fold | 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 applications that wish to convert ranges of values
to ranges relative to epoch boundaries. Below, a list of time
intervals in hours is converted to a sequence of daily interval
lists with times relative to midnight.
Example:
>>> from pycbc_glue.segments import *
>>> x = segmentlist([segment(0, 13), segment(14, 20), segment(22, 36)])
>>> for y in Fold(x, segmentlist_range(0, 48, 24)): print y
...
[segment(0, 13), segment(14, 20), segment(22, 24)]
[segment(0, 12)]
"""
for seg in seglist2:
yield (seglist1 & segments.segmentlist([seg])).shift(-seg[0]) | python | 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 applications that wish to convert ranges of values
to ranges relative to epoch boundaries. Below, a list of time
intervals in hours is converted to a sequence of daily interval
lists with times relative to midnight.
Example:
>>> from pycbc_glue.segments import *
>>> x = segmentlist([segment(0, 13), segment(14, 20), segment(22, 36)])
>>> for y in Fold(x, segmentlist_range(0, 48, 24)): print y
...
[segment(0, 13), segment(14, 20), segment(22, 24)]
[segment(0, 12)]
"""
for seg in seglist2:
yield (seglist1 & segments.segmentlist([seg])).shift(-seg[0]) | [
"def",
"Fold",
"(",
"seglist1",
",",
"seglist2",
")",
":",
"for",
"seg",
"in",
"seglist2",
":",
"yield",
"(",
"seglist1",
"&",
"segments",
".",
"segmentlist",
"(",
"[",
"seg",
"]",
")",
")",
".",
"shift",
"(",
"-",
"seg",
"[",
"0",
"]",
")"
] | 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 applications that wish to convert ranges of values
to ranges relative to epoch boundaries. Below, a list of time
intervals in hours is converted to a sequence of daily interval
lists with times relative to midnight.
Example:
>>> from pycbc_glue.segments import *
>>> x = segmentlist([segment(0, 13), segment(14, 20), segment(22, 36)])
>>> for y in Fold(x, segmentlist_range(0, 48, 24)): print y
...
[segment(0, 13), segment(14, 20), segment(22, 24)]
[segment(0, 12)] | [
"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... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L454-L477 |
gwastro/pycbc-glue | pycbc_glue/segmentsUtils.py | vote | 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([segment(10, 25)])
>>> z = segmentlist([segment(15, 30)])
>>> vote((w, x, y, z), 3)
[segment(10, 20)]
The sequence of segmentlists is only iterated over once, and the
segmentlists within it are only iterated over once; they can all
be generators. If there are a total of N segments in M segment
lists and the final result has L segments the algorithm is O(N M) +
O(L).
"""
# 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):
# remove and return the smallest value from a list
val = min(l)
for i in xrange(len(l) - 1, -1, -1):
if l[i] is val:
return l.pop(i)
assert False # cannot get here
def vote_generator(seglists):
queue = []
for seglist in seglists:
segiter = iter(seglist)
try:
seg = segiter.next()
except StopIteration:
continue
# put them in so that the smallest boundary is
# closest to the end of the list
queue.append((seg[1], -1, segiter))
queue.append((seg[0], +1, None))
if not queue:
return
queue.sort(reverse = True)
bound = queue[-1][0]
votes = 0
while queue:
this_bound, delta, segiter = pop_min(queue)
if this_bound == bound:
votes += delta
else:
yield bound, votes
bound = this_bound
votes = delta
if segiter is not None:
try:
seg = segiter.next()
except StopIteration:
continue
queue.append((seg[1], -1, segiter))
queue.append((seg[0], +1, None))
yield bound, votes
# compute the cumulative sum of votes, and assemble a segmentlist
# from the intervals when the vote count is equal to or greater
# than n
result = segments.segmentlist()
votes = 0
for bound, delta in vote_generator(seglists):
if delta > 0 and n - delta <= votes < n:
start = bound
elif delta < 0 and n <= votes < n - delta:
result.append(segments.segment(start, bound))
del start # detect stops that aren't preceded by starts
votes += delta
assert votes == 0 # detect failed cumulative sum
return result | python | 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([segment(10, 25)])
>>> z = segmentlist([segment(15, 30)])
>>> vote((w, x, y, z), 3)
[segment(10, 20)]
The sequence of segmentlists is only iterated over once, and the
segmentlists within it are only iterated over once; they can all
be generators. If there are a total of N segments in M segment
lists and the final result has L segments the algorithm is O(N M) +
O(L).
"""
# 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):
# remove and return the smallest value from a list
val = min(l)
for i in xrange(len(l) - 1, -1, -1):
if l[i] is val:
return l.pop(i)
assert False # cannot get here
def vote_generator(seglists):
queue = []
for seglist in seglists:
segiter = iter(seglist)
try:
seg = segiter.next()
except StopIteration:
continue
# put them in so that the smallest boundary is
# closest to the end of the list
queue.append((seg[1], -1, segiter))
queue.append((seg[0], +1, None))
if not queue:
return
queue.sort(reverse = True)
bound = queue[-1][0]
votes = 0
while queue:
this_bound, delta, segiter = pop_min(queue)
if this_bound == bound:
votes += delta
else:
yield bound, votes
bound = this_bound
votes = delta
if segiter is not None:
try:
seg = segiter.next()
except StopIteration:
continue
queue.append((seg[1], -1, segiter))
queue.append((seg[0], +1, None))
yield bound, votes
# compute the cumulative sum of votes, and assemble a segmentlist
# from the intervals when the vote count is equal to or greater
# than n
result = segments.segmentlist()
votes = 0
for bound, delta in vote_generator(seglists):
if delta > 0 and n - delta <= votes < n:
start = bound
elif delta < 0 and n <= votes < n - delta:
result.append(segments.segment(start, bound))
del start # detect stops that aren't preceded by starts
votes += delta
assert votes == 0 # detect failed cumulative sum
return result | [
"def",
"vote",
"(",
"seglists",
",",
"n",
")",
":",
"# 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 tran... | 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([segment(10, 25)])
>>> z = segmentlist([segment(15, 30)])
>>> vote((w, x, y, z), 3)
[segment(10, 20)]
The sequence of segmentlists is only iterated over once, and the
segmentlists within it are only iterated over once; they can all
be generators. If there are a total of N segments in M segment
lists and the final result has L segments the algorithm is O(N M) +
O(L). | [
"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",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segmentsUtils.py#L480-L569 |
gwastro/pycbc-glue | pycbc_glue/datafind.py | validate_proxy | 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
"""
# 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")
except LookupError:
subject = proxy.get_subject().as_text()
if re.search(r'.+CN=proxy$', subject):
raise RuntimeError("Could not find a RFC 3820 compliant proxy "
"credential. Please run 'grid-proxy-init -rfc' "
"and try again.")
# attempt to make sure the proxy is still good for more than 15 minutes
try:
expireASN1 = proxy.get_not_after().__str__()
expireGMT = time.strptime(expireASN1, "%b %d %H:%M:%S %Y %Z")
expireUTC = calendar.timegm(expireGMT)
now = int(time.time())
secondsLeft = expireUTC - now
except Exception, e:
# problem getting or parsing time so just let the client
# continue and pass the issue along to the server
secondsLeft = 3600
if secondsLeft <= 0:
raise RuntimeError("Your proxy certificate is expired.\n"
"Please generate a new proxy certificate and "
"try again. ")
if secondsLeft < (60 * 15):
raise RuntimeError("Your proxy certificate expires in less than 15 "
"minutes.\nPlease generate a new proxy "
"certificate and try again.")
# return True to indicate validated proxy
return True | python | 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
"""
# 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")
except LookupError:
subject = proxy.get_subject().as_text()
if re.search(r'.+CN=proxy$', subject):
raise RuntimeError("Could not find a RFC 3820 compliant proxy "
"credential. Please run 'grid-proxy-init -rfc' "
"and try again.")
# attempt to make sure the proxy is still good for more than 15 minutes
try:
expireASN1 = proxy.get_not_after().__str__()
expireGMT = time.strptime(expireASN1, "%b %d %H:%M:%S %Y %Z")
expireUTC = calendar.timegm(expireGMT)
now = int(time.time())
secondsLeft = expireUTC - now
except Exception, e:
# problem getting or parsing time so just let the client
# continue and pass the issue along to the server
secondsLeft = 3600
if secondsLeft <= 0:
raise RuntimeError("Your proxy certificate is expired.\n"
"Please generate a new proxy certificate and "
"try again. ")
if secondsLeft < (60 * 15):
raise RuntimeError("Your proxy certificate expires in less than 15 "
"minutes.\nPlease generate a new proxy "
"certificate and try again.")
# return True to indicate validated proxy
return True | [
"def",
"validate_proxy",
"(",
"path",
")",
":",
"# load the proxy from path",
"try",
":",
"proxy",
"=",
"M2Crypto",
".",
"X509",
".",
"load_cert",
"(",
"path",
")",
"except",
"Exception",
",",
"e",
":",
"msg",
"=",
"\"Unable to load proxy from path %s : %s\"",
"... | 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 | [
"Validate",
"the",
"users",
"X509",
"proxy",
"certificate"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/datafind.py#L409-L457 |
gwastro/pycbc-glue | pycbc_glue/datafind.py | find_credential | 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
be validated
@raises RuntimeError: if the cert and key files cannot be located
"""
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 validate_proxy(filePath):
return filePath, filePath
else:
raise RuntimeError(rfc_proxy_msg)
# use X509_USER_CERT and X509_USER_KEY if set
if (os.environ.has_key('X509_USER_CERT') and
os.environ.has_key('X509_USER_KEY')):
certFile = os.environ['X509_USER_CERT']
keyFile = os.environ['X509_USER_KEY']
return certFile, keyFile
# search for proxy file on disk
uid = os.getuid()
path = "/tmp/x509up_u%d" % uid
if os.access(path, os.R_OK):
if validate_proxy(path):
return path, path
else:
raise RuntimeError(rfc_proxy_msg)
# if we get here could not find a credential
raise RuntimeError(rfc_proxy_msg) | python | 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
be validated
@raises RuntimeError: if the cert and key files cannot be located
"""
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 validate_proxy(filePath):
return filePath, filePath
else:
raise RuntimeError(rfc_proxy_msg)
# use X509_USER_CERT and X509_USER_KEY if set
if (os.environ.has_key('X509_USER_CERT') and
os.environ.has_key('X509_USER_KEY')):
certFile = os.environ['X509_USER_CERT']
keyFile = os.environ['X509_USER_KEY']
return certFile, keyFile
# search for proxy file on disk
uid = os.getuid()
path = "/tmp/x509up_u%d" % uid
if os.access(path, os.R_OK):
if validate_proxy(path):
return path, path
else:
raise RuntimeError(rfc_proxy_msg)
# if we get here could not find a credential
raise RuntimeError(rfc_proxy_msg) | [
"def",
"find_credential",
"(",
")",
":",
"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",... | 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
be validated
@raises RuntimeError: if the cert and key files cannot be located | [
"Locate",
"the",
"users",
"X509",
"certificate",
"and",
"key",
"files"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/datafind.py#L459-L500 |
gwastro/pycbc-glue | pycbc_glue/datafind.py | find_server | 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
is not set
"""
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 %s is not set" % _server_env) | python | 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
is not set
"""
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 %s is not set" % _server_env) | [
"def",
"find_server",
"(",
")",
":",
"if",
"os",
".",
"environ",
".",
"has_key",
"(",
"_server_env",
")",
":",
"host",
"=",
"os",
".",
"environ",
"[",
"_server_env",
"]",
"port",
"=",
"None",
"if",
"re",
".",
"search",
"(",
"':'",
",",
"host",
")",... | 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
is not set | [
"Find",
"the",
"default",
"server",
"host",
"from",
"the",
"environment"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/datafind.py#L502-L523 |
gwastro/pycbc-glue | pycbc_glue/datafind.py | GWDataFindHTTPConnection._requestresponse | 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 unsuccessful
"""
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, e))
if response.status != 200:
raise RuntimeError("Server returned code %d: %s%s"
% (response.status, response.reason,
response.read()))
return response | python | 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 unsuccessful
"""
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, e))
if response.status != 200:
raise RuntimeError("Server returned code %d: %s%s"
% (response.status, response.reason,
response.read()))
return response | [
"def",
"_requestresponse",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"{",
"}",
")",
":",
"try",
":",
"self",
".",
"request",
"(",
"method",
",",
"url",
")",
"response",
"=",
"self",
".",
"getresponse",
"... | 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 unsuccessful | [
"Internal",
"method",
"to",
"perform",
"request",
"and",
"verify",
"reponse",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/datafind.py#L101-L125 |
gwastro/pycbc-glue | pycbc_glue/datafind.py | GWDataFindHTTPConnection.find_observatories | 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.find_observatories("H")
['H', 'HL', 'HLT']
@type match: L{str}
@param match:
name to match return observatories against
@returns: L{list} of observatory prefixes
"""
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 | python | 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.find_observatories("H")
['H', 'HL', 'HLT']
@type match: L{str}
@param match:
name to match return observatories against
@returns: L{list} of observatory prefixes
"""
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",
")",
":",
"url",
"=",
"\"%s/gwf.json\"",
"%",
"_url_prefix",
"response",
"=",
"self",
".",
"_requestresponse",
"(",
"\"GET\"",
",",
"url",
")",
"sitelist",
"=",
"sorted",
"(",
"set",
"(",... | 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.find_observatories("H")
['H', 'HL', 'HLT']
@type match: L{str}
@param match:
name to match return observatories against
@returns: L{list} of observatory prefixes | [
"Query",
"the",
"LDR",
"host",
"for",
"observatories",
".",
"Use",
"match",
"to",
"restrict",
"returned",
"observatories",
"to",
"those",
"matching",
"the",
"regular",
"expression",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/datafind.py#L137-L162 |
gwastro/pycbc-glue | pycbc_glue/datafind.py | GWDataFindHTTPConnection.find_types | 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_RDS_C03_L2',
'L1_RDS_R_L1',
'L1_RDS_R_L3',
'L1_RDS_R_L4',
'PEM_RDS_A6',
'RDS_R_L1',
'RDS_R_L2',
'RDS_R_L3',
'TESTPEM_RDS_A6']
@param site: single-character name of site to match
@param match: type-name to match against
@type site: L{str}
@type match: L{str}
@returns: L{list} of frame types
"""
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)
typelist = [type for type in typelist if regmatch.search(type)]
return typelist | python | 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_RDS_C03_L2',
'L1_RDS_R_L1',
'L1_RDS_R_L3',
'L1_RDS_R_L4',
'PEM_RDS_A6',
'RDS_R_L1',
'RDS_R_L2',
'RDS_R_L3',
'TESTPEM_RDS_A6']
@param site: single-character name of site to match
@param match: type-name to match against
@type site: L{str}
@type match: L{str}
@returns: L{list} of frame types
"""
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)
typelist = [type for type in typelist if regmatch.search(type)]
return typelist | [
"def",
"find_types",
"(",
"self",
",",
"site",
"=",
"None",
",",
"match",
"=",
"None",
")",
":",
"if",
"site",
":",
"url",
"=",
"\"%s/gwf/%s.json\"",
"%",
"(",
"_url_prefix",
",",
"site",
"[",
"0",
"]",
")",
"else",
":",
"url",
"=",
"\"%s/gwf/all.jso... | 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_RDS_C03_L2',
'L1_RDS_R_L1',
'L1_RDS_R_L3',
'L1_RDS_R_L4',
'PEM_RDS_A6',
'RDS_R_L1',
'RDS_R_L2',
'RDS_R_L3',
'TESTPEM_RDS_A6']
@param site: single-character name of site to match
@param match: type-name to match against
@type site: L{str}
@type match: L{str}
@returns: L{list} of frame types | [
"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",
"express... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/datafind.py#L164-L201 |
gwastro/pycbc-glue | pycbc_glue/datafind.py | GWDataFindHTTPConnection.find_times | 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:
name of frametype to match
@param gpsstart:
integer GPS start time of query
@param gpsend:
integer GPS end time of query
@type site: L{str}
@type frametype: L{str}
@type gpsstart: L{int}
@type gpsend: L{int}
"""
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._requestresponse("GET", url)
segmentlist = decode(response.read())
return segments.segmentlist(map(segments.segment, segmentlist)) | python | 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:
name of frametype to match
@param gpsstart:
integer GPS start time of query
@param gpsend:
integer GPS end time of query
@type site: L{str}
@type frametype: L{str}
@type gpsstart: L{int}
@type gpsend: L{int}
"""
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._requestresponse("GET", url)
segmentlist = decode(response.read())
return segments.segmentlist(map(segments.segment, segmentlist)) | [
"def",
"find_times",
"(",
"self",
",",
"site",
",",
"frametype",
",",
"gpsstart",
"=",
"None",
",",
"gpsend",
"=",
"None",
")",
":",
"if",
"gpsstart",
"and",
"gpsend",
":",
"url",
"=",
"(",
"\"%s/gwf/%s/%s/segments/%s,%s.json\"",
"%",
"(",
"_url_prefix",
"... | 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:
name of frametype to match
@param gpsstart:
integer GPS start time of query
@param gpsend:
integer GPS end time of query
@type site: L{str}
@type frametype: L{str}
@type gpsstart: L{int}
@type gpsend: L{int} | [
"Query",
"the",
"LDR",
"for",
"times",
"for",
"which",
"frames",
"are",
"avaliable"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/datafind.py#L203-L234 |
gwastro/pycbc-glue | pycbc_glue/datafind.py | GWDataFindHTTPConnection.find_frame | 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, one of:
- C{'warn'} (default): print a warning,
- C{'error'}: raise an L{RuntimeError}, or
- C{'ignore'}: do nothing
@type frametype: L{str}
@type urltype: L{str}
@type on_missing: L{str}
@raises RuntimeError: if given framefile is malformed
"""
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("-")
except Exception, e:
raise RuntimeError("Error parsing filename %s: %s" % (framefile, e))
url = ("%s/gwf/%s/%s/%s.json"
% (_url_prefix, site, frametype, framefile))
response = self._requestresponse("GET", url)
urllist = decode(response.read())
if len(urllist) == 0:
if on_missing == "warn":
sys.stderr.write("No files found!\n")
elif on_missing == "error":
raise RuntimeError("No files found!")
# verify urltype is what we want
cache = lal.Cache(e for e in
[lal.CacheEntry.from_T050017(x, coltype=self.LIGOTimeGPSType)
for x in urllist] if not urltype or e.scheme == urltype)
return cache | python | 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, one of:
- C{'warn'} (default): print a warning,
- C{'error'}: raise an L{RuntimeError}, or
- C{'ignore'}: do nothing
@type frametype: L{str}
@type urltype: L{str}
@type on_missing: L{str}
@raises RuntimeError: if given framefile is malformed
"""
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("-")
except Exception, e:
raise RuntimeError("Error parsing filename %s: %s" % (framefile, e))
url = ("%s/gwf/%s/%s/%s.json"
% (_url_prefix, site, frametype, framefile))
response = self._requestresponse("GET", url)
urllist = decode(response.read())
if len(urllist) == 0:
if on_missing == "warn":
sys.stderr.write("No files found!\n")
elif on_missing == "error":
raise RuntimeError("No files found!")
# verify urltype is what we want
cache = lal.Cache(e for e in
[lal.CacheEntry.from_T050017(x, coltype=self.LIGOTimeGPSType)
for x in urllist] if not urltype or e.scheme == urltype)
return cache | [
"def",
"find_frame",
"(",
"self",
",",
"framefile",
",",
"urltype",
"=",
"None",
",",
"on_missing",
"=",
"\"warn\"",
")",
":",
"if",
"on_missing",
"not",
"in",
"(",
"\"warn\"",
",",
"\"error\"",
",",
"\"ignore\"",
")",
":",
"raise",
"ValueError",
"(",
"\... | 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, one of:
- C{'warn'} (default): print a warning,
- C{'error'}: raise an L{RuntimeError}, or
- C{'ignore'}: do nothing
@type frametype: L{str}
@type urltype: L{str}
@type on_missing: L{str}
@raises RuntimeError: if given framefile is malformed | [
"Query",
"the",
"LDR",
"host",
"for",
"a",
"single",
"framefile"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/datafind.py#L236-L278 |
gwastro/pycbc-glue | pycbc_glue/datafind.py | GWDataFindHTTPConnection.find_frame_urls | 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:
integer GPS end time of query
@param match:
regular expression to match against
@param urltype:
file scheme to search for (e.g. 'file')
@param on_gaps:
what to do when the requested frame isn't found, one of:
- C{'warn'} (default): print a warning,
- C{'error'}: raise an L{RuntimeError}, or
- C{'ignore'}: do nothing
@type site: L{str}
@type frametype: L{str}
@type gpsstart: L{int}
@type gpsend: L{int}
@type match: L{str}
@type urltype: L{str}
@type on_gaps: L{str}
@returns: L{Cache<pycbc_glue.lal.Cache>}
@raises RuntimeError: if gaps are found and C{on_gaps='error'}
"""
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 urltype:
url += "/%s" % urltype
# request JSON output
url += ".json"
# append a regex if input
if match:
url += "?match=%s" % match
# make query
response = self._requestresponse("GET", url)
urllist = decode(response.read())
out = lal.Cache([lal.CacheEntry.from_T050017(x,
coltype=self.LIGOTimeGPSType) for x in urllist])
if on_gaps == "ignore":
return out
else:
span = segments.segment(gpsstart, gpsend)
seglist = segments.segmentlist(e.segment for e in out).coalesce()
missing = (segments.segmentlist([span]) - seglist).coalesce()
if span in seglist:
return out
else:
msg = "Missing segments: \n%s" % "\n".join(map(str, missing))
if on_gaps=="warn":
sys.stderr.write("%s\n" % msg)
return out
else:
raise RuntimeError(msg) | python | 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:
integer GPS end time of query
@param match:
regular expression to match against
@param urltype:
file scheme to search for (e.g. 'file')
@param on_gaps:
what to do when the requested frame isn't found, one of:
- C{'warn'} (default): print a warning,
- C{'error'}: raise an L{RuntimeError}, or
- C{'ignore'}: do nothing
@type site: L{str}
@type frametype: L{str}
@type gpsstart: L{int}
@type gpsend: L{int}
@type match: L{str}
@type urltype: L{str}
@type on_gaps: L{str}
@returns: L{Cache<pycbc_glue.lal.Cache>}
@raises RuntimeError: if gaps are found and C{on_gaps='error'}
"""
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 urltype:
url += "/%s" % urltype
# request JSON output
url += ".json"
# append a regex if input
if match:
url += "?match=%s" % match
# make query
response = self._requestresponse("GET", url)
urllist = decode(response.read())
out = lal.Cache([lal.CacheEntry.from_T050017(x,
coltype=self.LIGOTimeGPSType) for x in urllist])
if on_gaps == "ignore":
return out
else:
span = segments.segment(gpsstart, gpsend)
seglist = segments.segmentlist(e.segment for e in out).coalesce()
missing = (segments.segmentlist([span]) - seglist).coalesce()
if span in seglist:
return out
else:
msg = "Missing segments: \n%s" % "\n".join(map(str, missing))
if on_gaps=="warn":
sys.stderr.write("%s\n" % msg)
return out
else:
raise RuntimeError(msg) | [
"def",
"find_frame_urls",
"(",
"self",
",",
"site",
",",
"frametype",
",",
"gpsstart",
",",
"gpsend",
",",
"match",
"=",
"None",
",",
"urltype",
"=",
"None",
",",
"on_gaps",
"=",
"\"warn\"",
")",
":",
"if",
"on_gaps",
"not",
"in",
"(",
"\"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:
integer GPS end time of query
@param match:
regular expression to match against
@param urltype:
file scheme to search for (e.g. 'file')
@param on_gaps:
what to do when the requested frame isn't found, one of:
- C{'warn'} (default): print a warning,
- C{'error'}: raise an L{RuntimeError}, or
- C{'ignore'}: do nothing
@type site: L{str}
@type frametype: L{str}
@type gpsstart: L{int}
@type gpsend: L{int}
@type match: L{str}
@type urltype: L{str}
@type on_gaps: L{str}
@returns: L{Cache<pycbc_glue.lal.Cache>}
@raises RuntimeError: if gaps are found and C{on_gaps='error'} | [
"Find",
"the",
"framefiles",
"for",
"the",
"given",
"type",
"in",
"the",
"[",
"start",
"end",
")",
"interval",
"frame"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/datafind.py#L324-L392 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | WalkChildren | def WalkChildren(elem):
"""
Walk the XML tree of children below elem, returning each in order.
"""
for child in elem.childNodes:
yield child
for elem in WalkChildren(child):
yield elem | python | def WalkChildren(elem):
"""
Walk the XML tree of children below elem, returning each in order.
"""
for child in elem.childNodes:
yield child
for elem in WalkChildren(child):
yield elem | [
"def",
"WalkChildren",
"(",
"elem",
")",
":",
"for",
"child",
"in",
"elem",
".",
"childNodes",
":",
"yield",
"child",
"for",
"elem",
"in",
"WalkChildren",
"(",
"child",
")",
":",
"yield",
"elem"
] | Walk the XML tree of children below elem, returning each in order. | [
"Walk",
"the",
"XML",
"tree",
"of",
"children",
"below",
"elem",
"returning",
"each",
"in",
"order",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L332-L339 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | make_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 connection to the
internet and the server to be up.
"""
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 | python | 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 connection to the
internet and the server to be up.
"""
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",
")",
":",
"parser",
"=",
"sax",
".",
"make_parser",
"(",
")",
"parser",
".",
"setContentHandler",
"(",
"handler",
")",
"parser",
".",
"setFeature",
"(",
"sax",
".",
"handler",
".",
"feature_namespaces",
",",
"True",
")... | 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 connection to the
internet and the server to be up. | [
"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"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L926-L940 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Element.appendChild | def appendChild(self, child):
"""
Add a child to this element. The child's parentNode
attribute is updated, too.
"""
self.childNodes.append(child)
child.parentNode = self
self._verifyChildren(len(self.childNodes) - 1)
return child | python | def appendChild(self, child):
"""
Add a child to this element. The child's parentNode
attribute is updated, too.
"""
self.childNodes.append(child)
child.parentNode = self
self._verifyChildren(len(self.childNodes) - 1)
return child | [
"def",
"appendChild",
"(",
"self",
",",
"child",
")",
":",
"self",
".",
"childNodes",
".",
"append",
"(",
"child",
")",
"child",
".",
"parentNode",
"=",
"self",
"self",
".",
"_verifyChildren",
"(",
"len",
"(",
"self",
".",
"childNodes",
")",
"-",
"1",
... | Add a child to this element. The child's parentNode
attribute is updated, too. | [
"Add",
"a",
"child",
"to",
"this",
"element",
".",
"The",
"child",
"s",
"parentNode",
"attribute",
"is",
"updated",
"too",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L178-L186 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Element.insertBefore | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"for",
"i",
",",
"childNode",
"in",
"enumerate",
"(",
"self",
".",
"childNodes",
")",
":",
"if",
"childNode",
"is",
"refchild",
":",
"self",
".",
"childNodes",
".",
"insert",... | 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. | [
"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",
"re... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L188-L200 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Element.removeChild | 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.
"""
for i, childNode in enumerate(self.childNodes):
if childNode is child:
del self.childNodes[i]
child.parentNode = None
return child
raise ValueError(child) | python | 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.
"""
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",
")",
":",
"for",
"i",
",",
"childNode",
"in",
"enumerate",
"(",
"self",
".",
"childNodes",
")",
":",
"if",
"childNode",
"is",
"child",
":",
"del",
"self",
".",
"childNodes",
"[",
"i",
"]",
"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. | [
"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",... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L202-L214 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Element.unlink | def unlink(self):
"""
Break internal references within the document tree rooted
on this element to promote garbage collection.
"""
self.parentNode = None
for child in self.childNodes:
child.unlink()
del self.childNodes[:] | python | def unlink(self):
"""
Break internal references within the document tree rooted
on this element to promote garbage collection.
"""
self.parentNode = None
for child in self.childNodes:
child.unlink()
del self.childNodes[:] | [
"def",
"unlink",
"(",
"self",
")",
":",
"self",
".",
"parentNode",
"=",
"None",
"for",
"child",
"in",
"self",
".",
"childNodes",
":",
"child",
".",
"unlink",
"(",
")",
"del",
"self",
".",
"childNodes",
"[",
":",
"]"
] | Break internal references within the document tree rooted
on this element to promote garbage collection. | [
"Break",
"internal",
"references",
"within",
"the",
"document",
"tree",
"rooted",
"on",
"this",
"element",
"to",
"promote",
"garbage",
"collection",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L216-L224 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Element.replaceChild | 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.
"""
# .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.parentNode = self
self._verifyChildren(i)
return newchild
raise ValueError(oldchild) | python | 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.
"""
# .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.parentNode = self
self._verifyChildren(i)
return newchild
raise ValueError(oldchild) | [
"def",
"replaceChild",
"(",
"self",
",",
"newchild",
",",
"oldchild",
")",
":",
"# .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",
"... | 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. | [
"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",
".... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L226-L242 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Element.getElements | def getElements(self, filter):
"""
Return a list of elements below and including this element
for which filter(element) returns True.
"""
l = reduce(lambda l, e: l + e.getElements(filter), self.childNodes, [])
if filter(self):
l.append(self)
return l | python | def getElements(self, filter):
"""
Return a list of elements below and including this element
for which filter(element) returns True.
"""
l = reduce(lambda l, e: l + e.getElements(filter), self.childNodes, [])
if filter(self):
l.append(self)
return l | [
"def",
"getElements",
"(",
"self",
",",
"filter",
")",
":",
"l",
"=",
"reduce",
"(",
"lambda",
"l",
",",
"e",
":",
"l",
"+",
"e",
".",
"getElements",
"(",
"filter",
")",
",",
"self",
".",
"childNodes",
",",
"[",
"]",
")",
"if",
"filter",
"(",
"... | Return a list of elements below and including this element
for which filter(element) returns True. | [
"Return",
"a",
"list",
"of",
"elements",
"below",
"and",
"including",
"this",
"element",
"for",
"which",
"filter",
"(",
"element",
")",
"returns",
"True",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L244-L252 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Element.appendData | def appendData(self, content):
"""
Add characters to the element's pcdata.
"""
if self.pcdata is not None:
self.pcdata += content
else:
self.pcdata = content | python | def appendData(self, content):
"""
Add characters to the element's pcdata.
"""
if self.pcdata is not None:
self.pcdata += content
else:
self.pcdata = content | [
"def",
"appendData",
"(",
"self",
",",
"content",
")",
":",
"if",
"self",
".",
"pcdata",
"is",
"not",
"None",
":",
"self",
".",
"pcdata",
"+=",
"content",
"else",
":",
"self",
".",
"pcdata",
"=",
"content"
] | Add characters to the element's pcdata. | [
"Add",
"characters",
"to",
"the",
"element",
"s",
"pcdata",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L290-L297 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Element.write | def write(self, fileobj = sys.stdout, indent = u""):
"""
Recursively write an element and it's children to a file.
"""
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))
fileobj.write(u"\n")
fileobj.write(self.end_tag(indent))
fileobj.write(u"\n") | python | def write(self, fileobj = sys.stdout, indent = u""):
"""
Recursively write an element and it's children to a file.
"""
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))
fileobj.write(u"\n")
fileobj.write(self.end_tag(indent))
fileobj.write(u"\n") | [
"def",
"write",
"(",
"self",
",",
"fileobj",
"=",
"sys",
".",
"stdout",
",",
"indent",
"=",
"u\"\"",
")",
":",
"fileobj",
".",
"write",
"(",
"self",
".",
"start_tag",
"(",
"indent",
")",
")",
"fileobj",
".",
"write",
"(",
"u\"\\n\"",
")",
"for",
"c... | Recursively write an element and it's children to a file. | [
"Recursively",
"write",
"an",
"element",
"and",
"it",
"s",
"children",
"to",
"a",
"file",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L315-L329 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Column.start_tag | def start_tag(self, indent):
"""
Generate the string for the element's start tag.
"""
return u"%s<%s%s/>" % (indent, self.tagName, u"".join(u" %s=\"%s\"" % keyvalue for keyvalue in self.attributes.items())) | python | def start_tag(self, indent):
"""
Generate the string for the element's start tag.
"""
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",
")",
":",
"return",
"u\"%s<%s%s/>\"",
"%",
"(",
"indent",
",",
"self",
".",
"tagName",
",",
"u\"\"",
".",
"join",
"(",
"u\" %s=\\\"%s\\\"\"",
"%",
"keyvalue",
"for",
"keyvalue",
"in",
"self",
".",
"attributes... | Generate the string for the element's start tag. | [
"Generate",
"the",
"string",
"for",
"the",
"element",
"s",
"start",
"tag",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L440-L444 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Column.write | def write(self, fileobj = sys.stdout, indent = u""):
"""
Recursively write an element and it's children to a file.
"""
fileobj.write(self.start_tag(indent))
fileobj.write(u"\n") | python | def write(self, fileobj = sys.stdout, indent = u""):
"""
Recursively write an element and it's children to a file.
"""
fileobj.write(self.start_tag(indent))
fileobj.write(u"\n") | [
"def",
"write",
"(",
"self",
",",
"fileobj",
"=",
"sys",
".",
"stdout",
",",
"indent",
"=",
"u\"\"",
")",
":",
"fileobj",
".",
"write",
"(",
"self",
".",
"start_tag",
"(",
"indent",
")",
")",
"fileobj",
".",
"write",
"(",
"u\"\\n\"",
")"
] | Recursively write an element and it's children to a file. | [
"Recursively",
"write",
"an",
"element",
"and",
"it",
"s",
"children",
"to",
"a",
"file",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L456-L461 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Time.now | 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.
"""
self = cls()
if Name is not None:
self.Name = Name
self.pcdata = datetime.datetime.utcnow()
return self | python | 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.
"""
self = cls()
if Name is not None:
self.Name = Name
self.pcdata = datetime.datetime.utcnow()
return self | [
"def",
"now",
"(",
"cls",
",",
"Name",
"=",
"None",
")",
":",
"self",
"=",
"cls",
"(",
")",
"if",
"Name",
"is",
"not",
"None",
":",
"self",
".",
"Name",
"=",
"Name",
"self",
".",
"pcdata",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
"... | 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. | [
"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",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L651-L661 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Time.from_gps | 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 gets written to disk.
"""
self = cls(AttributesImpl({u"Type": u"GPS"}))
if Name is not None:
self.Name = Name
self.pcdata = gps
return self | python | 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 gets written to disk.
"""
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",
")",
":",
"self",
"=",
"cls",
"(",
"AttributesImpl",
"(",
"{",
"u\"Type\"",
":",
"u\"GPS\"",
"}",
")",
")",
"if",
"Name",
"is",
"not",
"None",
":",
"self",
".",
"Name",
"=",
"Na... | 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 gets written to disk. | [
"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",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L664-L678 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | Document.write | def write(self, fileobj = sys.stdout, xsl_file = None):
"""
Write the document.
"""
fileobj.write(Header)
fileobj.write(u"\n")
if xsl_file is not None:
fileobj.write(u'<?xml-stylesheet type="text/xsl" href="%s" ?>\n' % xsl_file)
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) | python | def write(self, fileobj = sys.stdout, xsl_file = None):
"""
Write the document.
"""
fileobj.write(Header)
fileobj.write(u"\n")
if xsl_file is not None:
fileobj.write(u'<?xml-stylesheet type="text/xsl" href="%s" ?>\n' % xsl_file)
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) | [
"def",
"write",
"(",
"self",
",",
"fileobj",
"=",
"sys",
".",
"stdout",
",",
"xsl_file",
"=",
"None",
")",
":",
"fileobj",
".",
"write",
"(",
"Header",
")",
"fileobj",
".",
"write",
"(",
"u\"\\n\"",
")",
"if",
"xsl_file",
"is",
"not",
"None",
":",
... | Write the document. | [
"Write",
"the",
"document",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L695-L706 |
gwastro/pycbc-glue | pycbc_glue/LDBDClient.py | SimpleLWXMLParser.start_element | def start_element(self, name, attrs):
"""
Callback for start of an XML element. Checks to see if we are
about to start a table that matches the ignore pattern.
@param name: the name of the tag being opened
@type name: string
@param attrs: a dictionary of the attributes for the tag being opened
@type attrs: dictionary
"""
if name.lower() == "table":
for attr in attrs.keys():
if attr.lower() == "name":
if self.__ignore_pat.search(attrs[attr]):
self.__in_table = 1 | python | def start_element(self, name, attrs):
"""
Callback for start of an XML element. Checks to see if we are
about to start a table that matches the ignore pattern.
@param name: the name of the tag being opened
@type name: string
@param attrs: a dictionary of the attributes for the tag being opened
@type attrs: dictionary
"""
if name.lower() == "table":
for attr in attrs.keys():
if attr.lower() == "name":
if self.__ignore_pat.search(attrs[attr]):
self.__in_table = 1 | [
"def",
"start_element",
"(",
"self",
",",
"name",
",",
"attrs",
")",
":",
"if",
"name",
".",
"lower",
"(",
")",
"==",
"\"table\"",
":",
"for",
"attr",
"in",
"attrs",
".",
"keys",
"(",
")",
":",
"if",
"attr",
".",
"lower",
"(",
")",
"==",
"\"name\... | Callback for start of an XML element. Checks to see if we are
about to start a table that matches the ignore pattern.
@param name: the name of the tag being opened
@type name: string
@param attrs: a dictionary of the attributes for the tag being opened
@type attrs: dictionary | [
"Callback",
"for",
"start",
"of",
"an",
"XML",
"element",
".",
"Checks",
"to",
"see",
"if",
"we",
"are",
"about",
"to",
"start",
"a",
"table",
"that",
"matches",
"the",
"ignore",
"pattern",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/LDBDClient.py#L71-L86 |
gwastro/pycbc-glue | pycbc_glue/LDBDClient.py | SimpleLWXMLParser.parse_line | def parse_line(self, line):
"""
For each line we are passed, call the XML parser. Returns the
line if we are outside one of the ignored tables, otherwise
returns the empty string.
@param line: the line of the LIGO_LW XML file to be parsed
@type line: string
@return: the line of XML passed in or the null string
@rtype: string
"""
self.__p.Parse(line)
if self.__in_table:
self.__silent = 1
if not self.__silent:
ret = line
else:
ret = ""
if not self.__in_table:
self.__silent = 0
return ret | python | def parse_line(self, line):
"""
For each line we are passed, call the XML parser. Returns the
line if we are outside one of the ignored tables, otherwise
returns the empty string.
@param line: the line of the LIGO_LW XML file to be parsed
@type line: string
@return: the line of XML passed in or the null string
@rtype: string
"""
self.__p.Parse(line)
if self.__in_table:
self.__silent = 1
if not self.__silent:
ret = line
else:
ret = ""
if not self.__in_table:
self.__silent = 0
return ret | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"__p",
".",
"Parse",
"(",
"line",
")",
"if",
"self",
".",
"__in_table",
":",
"self",
".",
"__silent",
"=",
"1",
"if",
"not",
"self",
".",
"__silent",
":",
"ret",
"=",
"line",
"... | For each line we are passed, call the XML parser. Returns the
line if we are outside one of the ignored tables, otherwise
returns the empty string.
@param line: the line of the LIGO_LW XML file to be parsed
@type line: string
@return: the line of XML passed in or the null string
@rtype: string | [
"For",
"each",
"line",
"we",
"are",
"passed",
"call",
"the",
"XML",
"parser",
".",
"Returns",
"the",
"line",
"if",
"we",
"are",
"outside",
"one",
"of",
"the",
"ignored",
"tables",
"otherwise",
"returns",
"the",
"empty",
"string",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/LDBDClient.py#L100-L121 |
gwastro/pycbc-glue | pycbc_glue/LDBDClient.py | LDBDClient.ping | def ping(self):
"""
Ping the LDBD Server and return any message received back as a string.
@return: message received (may be empty) from LDBD Server as a string
"""
msg = "PING\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error pinging server %d:%s" % (ret, reply)
raise LDBDClientException, msg
return reply | python | def ping(self):
"""
Ping the LDBD Server and return any message received back as a string.
@return: message received (may be empty) from LDBD Server as a string
"""
msg = "PING\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error pinging server %d:%s" % (ret, reply)
raise LDBDClientException, msg
return reply | [
"def",
"ping",
"(",
"self",
")",
":",
"msg",
"=",
"\"PING\\0\"",
"self",
".",
"sfile",
".",
"write",
"(",
"msg",
")",
"ret",
",",
"output",
"=",
"self",
".",
"__response__",
"(",
")",
"reply",
"=",
"str",
"(",
"output",
"[",
"0",
"]",
")",
"if",
... | Ping the LDBD Server and return any message received back as a string.
@return: message received (may be empty) from LDBD Server as a string | [
"Ping",
"the",
"LDBD",
"Server",
"and",
"return",
"any",
"message",
"received",
"back",
"as",
"a",
"string",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/LDBDClient.py#L310-L327 |
gwastro/pycbc-glue | pycbc_glue/LDBDClient.py | LDBDClient.query | def query(self,sql):
"""
Execute an SQL query on the server and fetch the resulting XML file
back.
@return: message received (may be empty) from LDBD Server as a string
"""
msg = "QUERY\0" + sql + "\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error executing query on server %d:%s" % (ret, reply)
raise LDBDClientException, msg
return reply | python | def query(self,sql):
"""
Execute an SQL query on the server and fetch the resulting XML file
back.
@return: message received (may be empty) from LDBD Server as a string
"""
msg = "QUERY\0" + sql + "\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error executing query on server %d:%s" % (ret, reply)
raise LDBDClientException, msg
return reply | [
"def",
"query",
"(",
"self",
",",
"sql",
")",
":",
"msg",
"=",
"\"QUERY\\0\"",
"+",
"sql",
"+",
"\"\\0\"",
"self",
".",
"sfile",
".",
"write",
"(",
"msg",
")",
"ret",
",",
"output",
"=",
"self",
".",
"__response__",
"(",
")",
"reply",
"=",
"str",
... | Execute an SQL query on the server and fetch the resulting XML file
back.
@return: message received (may be empty) from LDBD Server as a string | [
"Execute",
"an",
"SQL",
"query",
"on",
"the",
"server",
"and",
"fetch",
"the",
"resulting",
"XML",
"file",
"back",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/LDBDClient.py#L329-L347 |
gwastro/pycbc-glue | pycbc_glue/LDBDClient.py | LDBDClient.insert | def insert(self,xmltext):
"""
Insert the LIGO_LW metadata in the xmltext string into the database.
@return: message received (may be empty) from LDBD Server as a string
"""
msg = "INSERT\0" + xmltext + "\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error executing insert on server %d:%s" % (ret, reply)
raise LDBDClientException, msg
return reply | python | def insert(self,xmltext):
"""
Insert the LIGO_LW metadata in the xmltext string into the database.
@return: message received (may be empty) from LDBD Server as a string
"""
msg = "INSERT\0" + xmltext + "\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error executing insert on server %d:%s" % (ret, reply)
raise LDBDClientException, msg
return reply | [
"def",
"insert",
"(",
"self",
",",
"xmltext",
")",
":",
"msg",
"=",
"\"INSERT\\0\"",
"+",
"xmltext",
"+",
"\"\\0\"",
"self",
".",
"sfile",
".",
"write",
"(",
"msg",
")",
"ret",
",",
"output",
"=",
"self",
".",
"__response__",
"(",
")",
"reply",
"=",
... | Insert the LIGO_LW metadata in the xmltext string into the database.
@return: message received (may be empty) from LDBD Server as a string | [
"Insert",
"the",
"LIGO_LW",
"metadata",
"in",
"the",
"xmltext",
"string",
"into",
"the",
"database",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/LDBDClient.py#L349-L366 |
gwastro/pycbc-glue | pycbc_glue/LDBDClient.py | LDBDClient.insertmap | def insertmap(self,xmltext,lfnpfn_dict):
"""
Insert the LIGO_LW metadata in the xmltext string into the database.
@return: message received (may be empty) from LDBD Server as a string
"""
pmsg = cPickle.dumps(lfnpfn_dict)
msg = "INSERTMAP\0" + xmltext + "\0" + pmsg + "\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error executing insert on server %d:%s" % (ret, reply)
raise LDBDClientException, msg
return reply | python | def insertmap(self,xmltext,lfnpfn_dict):
"""
Insert the LIGO_LW metadata in the xmltext string into the database.
@return: message received (may be empty) from LDBD Server as a string
"""
pmsg = cPickle.dumps(lfnpfn_dict)
msg = "INSERTMAP\0" + xmltext + "\0" + pmsg + "\0"
self.sfile.write(msg)
ret, output = self.__response__()
reply = str(output[0])
if ret:
msg = "Error executing insert on server %d:%s" % (ret, reply)
raise LDBDClientException, msg
return reply | [
"def",
"insertmap",
"(",
"self",
",",
"xmltext",
",",
"lfnpfn_dict",
")",
":",
"pmsg",
"=",
"cPickle",
".",
"dumps",
"(",
"lfnpfn_dict",
")",
"msg",
"=",
"\"INSERTMAP\\0\"",
"+",
"xmltext",
"+",
"\"\\0\"",
"+",
"pmsg",
"+",
"\"\\0\"",
"self",
".",
"sfile... | Insert the LIGO_LW metadata in the xmltext string into the database.
@return: message received (may be empty) from LDBD Server as a string | [
"Insert",
"the",
"LIGO_LW",
"metadata",
"in",
"the",
"xmltext",
"string",
"into",
"the",
"database",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/LDBDClient.py#L368-L387 |
gwastro/pycbc-glue | pycbc_glue/gpstime.py | dayOfWeek | def dayOfWeek(year, month, day):
"returns day of week: 0=Sun, 1=Mon, .., 6=Sat"
hr = 12 #make sure you fall into right day, middle is save
t = time.mktime((year, month, day, hr, 0, 0.0, 0, 0, -1))
pyDow = time.localtime(t)[6]
gpsDow = (pyDow + 1) % 7
return gpsDow | python | def dayOfWeek(year, month, day):
"returns day of week: 0=Sun, 1=Mon, .., 6=Sat"
hr = 12 #make sure you fall into right day, middle is save
t = time.mktime((year, month, day, hr, 0, 0.0, 0, 0, -1))
pyDow = time.localtime(t)[6]
gpsDow = (pyDow + 1) % 7
return gpsDow | [
"def",
"dayOfWeek",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"hr",
"=",
"12",
"#make sure you fall into right day, middle is save",
"t",
"=",
"time",
".",
"mktime",
"(",
"(",
"year",
",",
"month",
",",
"day",
",",
"hr",
",",
"0",
",",
"0.0",
",... | returns day of week: 0=Sun, 1=Mon, .., 6=Sat | [
"returns",
"day",
"of",
"week",
":",
"0",
"=",
"Sun",
"1",
"=",
"Mon",
"..",
"6",
"=",
"Sat"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/gpstime.py#L53-L59 |
gwastro/pycbc-glue | pycbc_glue/gpstime.py | gpsWeek | def gpsWeek(year, month, day):
"returns (full) gpsWeek for given date (in UTC)"
hr = 12 #make sure you fall into right day, middle is save
return gpsFromUTC(year, month, day, hr, 0, 0.0)[0] | python | def gpsWeek(year, month, day):
"returns (full) gpsWeek for given date (in UTC)"
hr = 12 #make sure you fall into right day, middle is save
return gpsFromUTC(year, month, day, hr, 0, 0.0)[0] | [
"def",
"gpsWeek",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"hr",
"=",
"12",
"#make sure you fall into right day, middle is save",
"return",
"gpsFromUTC",
"(",
"year",
",",
"month",
",",
"day",
",",
"hr",
",",
"0",
",",
"0.0",
")",
"[",
"0",
"]"
] | returns (full) gpsWeek for given date (in UTC) | [
"returns",
"(",
"full",
")",
"gpsWeek",
"for",
"given",
"date",
"(",
"in",
"UTC",
")"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/gpstime.py#L61-L64 |
gwastro/pycbc-glue | pycbc_glue/gpstime.py | julianDay | def julianDay(year, month, day):
"returns julian day=day since Jan 1 of year"
hr = 12 #make sure you fall into right day, middle is save
t = time.mktime((year, month, day, hr, 0, 0.0, 0, 0, -1))
julDay = time.localtime(t)[7]
return julDay | python | def julianDay(year, month, day):
"returns julian day=day since Jan 1 of year"
hr = 12 #make sure you fall into right day, middle is save
t = time.mktime((year, month, day, hr, 0, 0.0, 0, 0, -1))
julDay = time.localtime(t)[7]
return julDay | [
"def",
"julianDay",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"hr",
"=",
"12",
"#make sure you fall into right day, middle is save",
"t",
"=",
"time",
".",
"mktime",
"(",
"(",
"year",
",",
"month",
",",
"day",
",",
"hr",
",",
"0",
",",
"0.0",
",... | returns julian day=day since Jan 1 of year | [
"returns",
"julian",
"day",
"=",
"day",
"since",
"Jan",
"1",
"of",
"year"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/gpstime.py#L67-L72 |
gwastro/pycbc-glue | pycbc_glue/gpstime.py | mkUTC | def mkUTC(year, month, day, hour, min, sec):
"similar to python's mktime but for utc"
spec = [year, month, day, hour, min, sec] + [0, 0, 0]
utc = time.mktime(spec) - time.timezone
return utc | python | def mkUTC(year, month, day, hour, min, sec):
"similar to python's mktime but for utc"
spec = [year, month, day, hour, min, sec] + [0, 0, 0]
utc = time.mktime(spec) - time.timezone
return utc | [
"def",
"mkUTC",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"min",
",",
"sec",
")",
":",
"spec",
"=",
"[",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"min",
",",
"sec",
"]",
"+",
"[",
"0",
",",
"0",
",",
"0",
"]",
"u... | similar to python's mktime but for utc | [
"similar",
"to",
"python",
"s",
"mktime",
"but",
"for",
"utc"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/gpstime.py#L74-L78 |
gwastro/pycbc-glue | pycbc_glue/gpstime.py | wtFromUTCpy | def wtFromUTCpy(pyUTC, leapSecs=14):
"""convenience function:
allows to use python UTC times and
returns only week and tow"""
ymdhms = ymdhmsFromPyUTC(pyUTC)
wSowDSoD = apply(gpsFromUTC, ymdhms + (leapSecs,))
return wSowDSoD[0:2] | python | def wtFromUTCpy(pyUTC, leapSecs=14):
"""convenience function:
allows to use python UTC times and
returns only week and tow"""
ymdhms = ymdhmsFromPyUTC(pyUTC)
wSowDSoD = apply(gpsFromUTC, ymdhms + (leapSecs,))
return wSowDSoD[0:2] | [
"def",
"wtFromUTCpy",
"(",
"pyUTC",
",",
"leapSecs",
"=",
"14",
")",
":",
"ymdhms",
"=",
"ymdhmsFromPyUTC",
"(",
"pyUTC",
")",
"wSowDSoD",
"=",
"apply",
"(",
"gpsFromUTC",
",",
"ymdhms",
"+",
"(",
"leapSecs",
",",
")",
")",
"return",
"wSowDSoD",
"[",
"... | convenience function:
allows to use python UTC times and
returns only week and tow | [
"convenience",
"function",
":",
"allows",
"to",
"use",
"python",
"UTC",
"times",
"and",
"returns",
"only",
"week",
"and",
"tow"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/gpstime.py#L85-L91 |
gwastro/pycbc-glue | pycbc_glue/gpstime.py | gpsFromUTC | def gpsFromUTC(year, month, day, hour, min, sec, leapSecs=14):
"""converts UTC to: gpsWeek, secsOfWeek, gpsDay, secsOfDay
a good reference is: http://www.oc.nps.navy.mil/~jclynch/timsys.html
This is based on the following facts (see reference above):
GPS time is basically measured in (atomic) seconds since
January 6, 1980, 00:00:00.0 (the GPS Epoch)
The GPS week starts on Saturday midnight (Sunday morning), and runs
for 604800 seconds.
Currently, GPS time is 13 seconds ahead of UTC (see above reference).
While GPS SVs transmit this difference and the date when another leap
second takes effect, the use of leap seconds cannot be predicted. This
routine is precise until the next leap second is introduced and has to be
updated after that.
SOW = Seconds of Week
SOD = Seconds of Day
Note: Python represents time in integer seconds, fractions are lost!!!
"""
secFract = sec % 1
epochTuple = gpsEpoch + (-1, -1, 0)
t0 = time.mktime(epochTuple)
t = time.mktime((year, month, day, hour, min, sec, -1, -1, 0))
# Note: time.mktime strictly works in localtime and to yield UTC, it should be
# corrected with time.timezone
# However, since we use the difference, this correction is unnecessary.
# Warning: trouble if daylight savings flag is set to -1 or 1 !!!
t = t + leapSecs
tdiff = t - t0
gpsSOW = (tdiff % secsInWeek) + secFract
gpsWeek = int(math.floor(tdiff/secsInWeek))
gpsDay = int(math.floor(gpsSOW/secsInDay))
gpsSOD = (gpsSOW % secsInDay)
return (gpsWeek, gpsSOW, gpsDay, gpsSOD) | python | def gpsFromUTC(year, month, day, hour, min, sec, leapSecs=14):
"""converts UTC to: gpsWeek, secsOfWeek, gpsDay, secsOfDay
a good reference is: http://www.oc.nps.navy.mil/~jclynch/timsys.html
This is based on the following facts (see reference above):
GPS time is basically measured in (atomic) seconds since
January 6, 1980, 00:00:00.0 (the GPS Epoch)
The GPS week starts on Saturday midnight (Sunday morning), and runs
for 604800 seconds.
Currently, GPS time is 13 seconds ahead of UTC (see above reference).
While GPS SVs transmit this difference and the date when another leap
second takes effect, the use of leap seconds cannot be predicted. This
routine is precise until the next leap second is introduced and has to be
updated after that.
SOW = Seconds of Week
SOD = Seconds of Day
Note: Python represents time in integer seconds, fractions are lost!!!
"""
secFract = sec % 1
epochTuple = gpsEpoch + (-1, -1, 0)
t0 = time.mktime(epochTuple)
t = time.mktime((year, month, day, hour, min, sec, -1, -1, 0))
# Note: time.mktime strictly works in localtime and to yield UTC, it should be
# corrected with time.timezone
# However, since we use the difference, this correction is unnecessary.
# Warning: trouble if daylight savings flag is set to -1 or 1 !!!
t = t + leapSecs
tdiff = t - t0
gpsSOW = (tdiff % secsInWeek) + secFract
gpsWeek = int(math.floor(tdiff/secsInWeek))
gpsDay = int(math.floor(gpsSOW/secsInDay))
gpsSOD = (gpsSOW % secsInDay)
return (gpsWeek, gpsSOW, gpsDay, gpsSOD) | [
"def",
"gpsFromUTC",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"min",
",",
"sec",
",",
"leapSecs",
"=",
"14",
")",
":",
"secFract",
"=",
"sec",
"%",
"1",
"epochTuple",
"=",
"gpsEpoch",
"+",
"(",
"-",
"1",
",",
"-",
"1",
",",
"0",... | converts UTC to: gpsWeek, secsOfWeek, gpsDay, secsOfDay
a good reference is: http://www.oc.nps.navy.mil/~jclynch/timsys.html
This is based on the following facts (see reference above):
GPS time is basically measured in (atomic) seconds since
January 6, 1980, 00:00:00.0 (the GPS Epoch)
The GPS week starts on Saturday midnight (Sunday morning), and runs
for 604800 seconds.
Currently, GPS time is 13 seconds ahead of UTC (see above reference).
While GPS SVs transmit this difference and the date when another leap
second takes effect, the use of leap seconds cannot be predicted. This
routine is precise until the next leap second is introduced and has to be
updated after that.
SOW = Seconds of Week
SOD = Seconds of Day
Note: Python represents time in integer seconds, fractions are lost!!! | [
"converts",
"UTC",
"to",
":",
"gpsWeek",
"secsOfWeek",
"gpsDay",
"secsOfDay"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/gpstime.py#L93-L131 |
gwastro/pycbc-glue | pycbc_glue/gpstime.py | UTCFromGps | def UTCFromGps(gpsWeek, SOW, leapSecs=14):
"""converts gps week and seconds to UTC
see comments of inverse function!
SOW = seconds of week
gpsWeek is the full number (not modulo 1024)
"""
secFract = SOW % 1
epochTuple = gpsEpoch + (-1, -1, 0)
t0 = time.mktime(epochTuple) - time.timezone #mktime is localtime, correct for UTC
tdiff = (gpsWeek * secsInWeek) + SOW - leapSecs
t = t0 + tdiff
(year, month, day, hh, mm, ss, dayOfWeek, julianDay, daylightsaving) = time.gmtime(t)
#use gmtime since localtime does not allow to switch off daylighsavings correction!!!
return (year, month, day, hh, mm, ss + secFract) | python | def UTCFromGps(gpsWeek, SOW, leapSecs=14):
"""converts gps week and seconds to UTC
see comments of inverse function!
SOW = seconds of week
gpsWeek is the full number (not modulo 1024)
"""
secFract = SOW % 1
epochTuple = gpsEpoch + (-1, -1, 0)
t0 = time.mktime(epochTuple) - time.timezone #mktime is localtime, correct for UTC
tdiff = (gpsWeek * secsInWeek) + SOW - leapSecs
t = t0 + tdiff
(year, month, day, hh, mm, ss, dayOfWeek, julianDay, daylightsaving) = time.gmtime(t)
#use gmtime since localtime does not allow to switch off daylighsavings correction!!!
return (year, month, day, hh, mm, ss + secFract) | [
"def",
"UTCFromGps",
"(",
"gpsWeek",
",",
"SOW",
",",
"leapSecs",
"=",
"14",
")",
":",
"secFract",
"=",
"SOW",
"%",
"1",
"epochTuple",
"=",
"gpsEpoch",
"+",
"(",
"-",
"1",
",",
"-",
"1",
",",
"0",
")",
"t0",
"=",
"time",
".",
"mktime",
"(",
"ep... | converts gps week and seconds to UTC
see comments of inverse function!
SOW = seconds of week
gpsWeek is the full number (not modulo 1024) | [
"converts",
"gps",
"week",
"and",
"seconds",
"to",
"UTC"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/gpstime.py#L134-L149 |
gwastro/pycbc-glue | pycbc_glue/gpstime.py | GpsSecondsFromPyUTC | def GpsSecondsFromPyUTC( pyUTC, leapSecs=14 ):
"""converts the python epoch to gps seconds
pyEpoch = the python epoch from time.time()
"""
t = t=gpsFromUTC(*ymdhmsFromPyUTC( pyUTC ))
return int(t[0] * 60 * 60 * 24 * 7 + t[1]) | python | def GpsSecondsFromPyUTC( pyUTC, leapSecs=14 ):
"""converts the python epoch to gps seconds
pyEpoch = the python epoch from time.time()
"""
t = t=gpsFromUTC(*ymdhmsFromPyUTC( pyUTC ))
return int(t[0] * 60 * 60 * 24 * 7 + t[1]) | [
"def",
"GpsSecondsFromPyUTC",
"(",
"pyUTC",
",",
"leapSecs",
"=",
"14",
")",
":",
"t",
"=",
"t",
"=",
"gpsFromUTC",
"(",
"*",
"ymdhmsFromPyUTC",
"(",
"pyUTC",
")",
")",
"return",
"int",
"(",
"t",
"[",
"0",
"]",
"*",
"60",
"*",
"60",
"*",
"24",
"*... | converts the python epoch to gps seconds
pyEpoch = the python epoch from time.time() | [
"converts",
"the",
"python",
"epoch",
"to",
"gps",
"seconds"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/gpstime.py#L151-L157 |
RadhikaG/markdown-magic | magic/memeAPI.py | genMeme | def genMeme(template_id, text0, text1):
'''
This function returns the url of the meme with the given
template, upper text, and lower text using the ImgFlip
meme generation API. Thanks!
Returns None if it is unable to generate the meme.
'''
username = 'blag'
password = 'blag'
api_url = 'https://api.imgflip.com/caption_image'
payload = {
'template_id': template_id,
'username': username,
'password': password,
'text0': text0,
}
# Add bottom text if provided
if text1 != '':
payload['text1'] = text1
try:
r = requests.get(api_url, params=payload)
except ConnectionError:
time.sleep(1)
r = requests.get(api_url, params=payload)
# print(parsed_json)
parsed_json = json.loads(r.text)
request_status = parsed_json['success']
if request_status != True:
error_msg = parsed_json['error_message']
print(error_msg)
return None
else:
imgURL = parsed_json['data']['url']
# print(imgURL)
return imgURL | python | def genMeme(template_id, text0, text1):
'''
This function returns the url of the meme with the given
template, upper text, and lower text using the ImgFlip
meme generation API. Thanks!
Returns None if it is unable to generate the meme.
'''
username = 'blag'
password = 'blag'
api_url = 'https://api.imgflip.com/caption_image'
payload = {
'template_id': template_id,
'username': username,
'password': password,
'text0': text0,
}
# Add bottom text if provided
if text1 != '':
payload['text1'] = text1
try:
r = requests.get(api_url, params=payload)
except ConnectionError:
time.sleep(1)
r = requests.get(api_url, params=payload)
# print(parsed_json)
parsed_json = json.loads(r.text)
request_status = parsed_json['success']
if request_status != True:
error_msg = parsed_json['error_message']
print(error_msg)
return None
else:
imgURL = parsed_json['data']['url']
# print(imgURL)
return imgURL | [
"def",
"genMeme",
"(",
"template_id",
",",
"text0",
",",
"text1",
")",
":",
"username",
"=",
"'blag'",
"password",
"=",
"'blag'",
"api_url",
"=",
"'https://api.imgflip.com/caption_image'",
"payload",
"=",
"{",
"'template_id'",
":",
"template_id",
",",
"'username'"... | This function returns the url of the meme with the given
template, upper text, and lower text using the ImgFlip
meme generation API. Thanks!
Returns None if it is unable to generate the meme. | [
"This",
"function",
"returns",
"the",
"url",
"of",
"the",
"meme",
"with",
"the",
"given",
"template",
"upper",
"text",
"and",
"lower",
"text",
"using",
"the",
"ImgFlip",
"meme",
"generation",
"API",
".",
"Thanks!"
] | train | https://github.com/RadhikaG/markdown-magic/blob/af99549b033269d861ea13f0541cb4f894057c47/magic/memeAPI.py#L25-L68 |
RadhikaG/markdown-magic | magic/memeAPI.py | findMeme | def findMeme(inptStr):
'''
inptStr may be a string of the following forms:
* 'text0 | text1'
* 'text0'
Returns None if it can't find find a meme from the list given above
'''
global meme_id_dict
testStr = inptStr
testStr.lower()
template_id = 0
'''
meme_id_dict[i] is of form:
[meme_tagline, meme_name, template_id]
'''
for i in range(len(meme_id_dict)):
test_words = testStr.strip('|.,?!').split(' ')
meme_words = meme_id_dict[i][0].split(' ')
common_words = len(list(set(meme_words).intersection(test_words)))
if (len(meme_words) >= 4 and common_words >= 3) or (len(meme_words) < 4 and common_words >= 1):
template_id = meme_id_dict[i][2]
return template_id
if template_id == 0:
return None | python | def findMeme(inptStr):
'''
inptStr may be a string of the following forms:
* 'text0 | text1'
* 'text0'
Returns None if it can't find find a meme from the list given above
'''
global meme_id_dict
testStr = inptStr
testStr.lower()
template_id = 0
'''
meme_id_dict[i] is of form:
[meme_tagline, meme_name, template_id]
'''
for i in range(len(meme_id_dict)):
test_words = testStr.strip('|.,?!').split(' ')
meme_words = meme_id_dict[i][0].split(' ')
common_words = len(list(set(meme_words).intersection(test_words)))
if (len(meme_words) >= 4 and common_words >= 3) or (len(meme_words) < 4 and common_words >= 1):
template_id = meme_id_dict[i][2]
return template_id
if template_id == 0:
return None | [
"def",
"findMeme",
"(",
"inptStr",
")",
":",
"global",
"meme_id_dict",
"testStr",
"=",
"inptStr",
"testStr",
".",
"lower",
"(",
")",
"template_id",
"=",
"0",
"'''\n meme_id_dict[i] is of form:\n [meme_tagline, meme_name, template_id]\n '''",
"for",
"i",
"in",
"... | inptStr may be a string of the following forms:
* 'text0 | text1'
* 'text0'
Returns None if it can't find find a meme from the list given above | [
"inptStr",
"may",
"be",
"a",
"string",
"of",
"the",
"following",
"forms",
":",
"*",
"text0",
"|",
"text1",
"*",
"text0"
] | train | https://github.com/RadhikaG/markdown-magic/blob/af99549b033269d861ea13f0541cb4f894057c47/magic/memeAPI.py#L71-L102 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.