id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
228,400 | gwastro/pycbc | pycbc/workflow/datafind.py | get_missing_segs_from_frame_file_cache | def get_missing_segs_from_frame_file_cache(datafindcaches):
"""
This function will use os.path.isfile to determine if all the frame files
returned by the local datafind server actually exist on the disk. This can
then be used to update the science times if needed.
Parameters
-----------
datafindcaches : OutGroupList
List of all the datafind output files.
Returns
--------
missingFrameSegs : Dict. of ifo keyed glue.segment.segmentlist instances
The times corresponding to missing frames found in datafindOuts.
missingFrames: Dict. of ifo keyed lal.Cache instances
The list of missing frames
"""
missingFrameSegs = {}
missingFrames = {}
for cache in datafindcaches:
if len(cache) > 0:
# Don't bother if these are not file:// urls, assume all urls in
# one cache file must be the same type
if not cache[0].scheme == 'file':
warn_msg = "We have %s entries in the " %(cache[0].scheme,)
warn_msg += "cache file. I do not check if these exist."
logging.info(warn_msg)
continue
_, currMissingFrames = cache.checkfilesexist(on_missing="warn")
missingSegs = segments.segmentlist(e.segment \
for e in currMissingFrames).coalesce()
ifo = cache.ifo
if ifo not in missingFrameSegs:
missingFrameSegs[ifo] = missingSegs
missingFrames[ifo] = lal.Cache(currMissingFrames)
else:
missingFrameSegs[ifo].extend(missingSegs)
# NOTE: This .coalesce probably isn't needed as the segments
# should be disjoint. If speed becomes an issue maybe remove it?
missingFrameSegs[ifo].coalesce()
missingFrames[ifo].extend(currMissingFrames)
return missingFrameSegs, missingFrames | python | def get_missing_segs_from_frame_file_cache(datafindcaches):
missingFrameSegs = {}
missingFrames = {}
for cache in datafindcaches:
if len(cache) > 0:
# Don't bother if these are not file:// urls, assume all urls in
# one cache file must be the same type
if not cache[0].scheme == 'file':
warn_msg = "We have %s entries in the " %(cache[0].scheme,)
warn_msg += "cache file. I do not check if these exist."
logging.info(warn_msg)
continue
_, currMissingFrames = cache.checkfilesexist(on_missing="warn")
missingSegs = segments.segmentlist(e.segment \
for e in currMissingFrames).coalesce()
ifo = cache.ifo
if ifo not in missingFrameSegs:
missingFrameSegs[ifo] = missingSegs
missingFrames[ifo] = lal.Cache(currMissingFrames)
else:
missingFrameSegs[ifo].extend(missingSegs)
# NOTE: This .coalesce probably isn't needed as the segments
# should be disjoint. If speed becomes an issue maybe remove it?
missingFrameSegs[ifo].coalesce()
missingFrames[ifo].extend(currMissingFrames)
return missingFrameSegs, missingFrames | [
"def",
"get_missing_segs_from_frame_file_cache",
"(",
"datafindcaches",
")",
":",
"missingFrameSegs",
"=",
"{",
"}",
"missingFrames",
"=",
"{",
"}",
"for",
"cache",
"in",
"datafindcaches",
":",
"if",
"len",
"(",
"cache",
")",
">",
"0",
":",
"# Don't bother if th... | This function will use os.path.isfile to determine if all the frame files
returned by the local datafind server actually exist on the disk. This can
then be used to update the science times if needed.
Parameters
-----------
datafindcaches : OutGroupList
List of all the datafind output files.
Returns
--------
missingFrameSegs : Dict. of ifo keyed glue.segment.segmentlist instances
The times corresponding to missing frames found in datafindOuts.
missingFrames: Dict. of ifo keyed lal.Cache instances
The list of missing frames | [
"This",
"function",
"will",
"use",
"os",
".",
"path",
".",
"isfile",
"to",
"determine",
"if",
"all",
"the",
"frame",
"files",
"returned",
"by",
"the",
"local",
"datafind",
"server",
"actually",
"exist",
"on",
"the",
"disk",
".",
"This",
"can",
"then",
"b... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L765-L807 |
228,401 | gwastro/pycbc | pycbc/workflow/datafind.py | setup_datafind_server_connection | def setup_datafind_server_connection(cp, tags=None):
"""
This function is resposible for setting up the connection with the datafind
server.
Parameters
-----------
cp : pycbc.workflow.configuration.WorkflowConfigParser
The memory representation of the ConfigParser
Returns
--------
connection
The open connection to the datafind server.
"""
if tags is None:
tags = []
if cp.has_option_tags("workflow-datafind",
"datafind-ligo-datafind-server", tags):
datafind_server = cp.get_opt_tags("workflow-datafind",
"datafind-ligo-datafind-server", tags)
else:
datafind_server = None
return datafind_connection(datafind_server) | python | def setup_datafind_server_connection(cp, tags=None):
if tags is None:
tags = []
if cp.has_option_tags("workflow-datafind",
"datafind-ligo-datafind-server", tags):
datafind_server = cp.get_opt_tags("workflow-datafind",
"datafind-ligo-datafind-server", tags)
else:
datafind_server = None
return datafind_connection(datafind_server) | [
"def",
"setup_datafind_server_connection",
"(",
"cp",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"if",
"cp",
".",
"has_option_tags",
"(",
"\"workflow-datafind\"",
",",
"\"datafind-ligo-datafind-server\"",
",",
"... | This function is resposible for setting up the connection with the datafind
server.
Parameters
-----------
cp : pycbc.workflow.configuration.WorkflowConfigParser
The memory representation of the ConfigParser
Returns
--------
connection
The open connection to the datafind server. | [
"This",
"function",
"is",
"resposible",
"for",
"setting",
"up",
"the",
"connection",
"with",
"the",
"datafind",
"server",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L809-L833 |
228,402 | gwastro/pycbc | pycbc/workflow/datafind.py | get_segment_summary_times | def get_segment_summary_times(scienceFile, segmentName):
"""
This function will find the times for which the segment_summary is set
for the flag given by segmentName.
Parameters
-----------
scienceFile : SegFile
The segment file that we want to use to determine this.
segmentName : string
The DQ flag to search for times in the segment_summary table.
Returns
---------
summSegList : ligo.segments.segmentlist
The times that are covered in the segment summary table.
"""
# Parse the segmentName
segmentName = segmentName.split(':')
if not len(segmentName) in [2,3]:
raise ValueError("Invalid channel name %s." %(segmentName))
ifo = segmentName[0]
channel = segmentName[1]
version = ''
if len(segmentName) == 3:
version = int(segmentName[2])
# Load the filename
xmldoc = utils.load_filename(scienceFile.cache_entry.path,
gz=scienceFile.cache_entry.path.endswith("gz"),
contenthandler=ContentHandler)
# Get the segment_def_id for the segmentName
segmentDefTable = table.get_table(xmldoc, "segment_definer")
for entry in segmentDefTable:
if (entry.ifos == ifo) and (entry.name == channel):
if len(segmentName) == 2 or (entry.version==version):
segDefID = entry.segment_def_id
break
else:
raise ValueError("Cannot find channel %s in segment_definer table."\
%(segmentName))
# Get the segmentlist corresponding to this segmentName in segment_summary
segmentSummTable = table.get_table(xmldoc, "segment_summary")
summSegList = segments.segmentlist([])
for entry in segmentSummTable:
if entry.segment_def_id == segDefID:
segment = segments.segment(entry.start_time, entry.end_time)
summSegList.append(segment)
summSegList.coalesce()
return summSegList | python | def get_segment_summary_times(scienceFile, segmentName):
# Parse the segmentName
segmentName = segmentName.split(':')
if not len(segmentName) in [2,3]:
raise ValueError("Invalid channel name %s." %(segmentName))
ifo = segmentName[0]
channel = segmentName[1]
version = ''
if len(segmentName) == 3:
version = int(segmentName[2])
# Load the filename
xmldoc = utils.load_filename(scienceFile.cache_entry.path,
gz=scienceFile.cache_entry.path.endswith("gz"),
contenthandler=ContentHandler)
# Get the segment_def_id for the segmentName
segmentDefTable = table.get_table(xmldoc, "segment_definer")
for entry in segmentDefTable:
if (entry.ifos == ifo) and (entry.name == channel):
if len(segmentName) == 2 or (entry.version==version):
segDefID = entry.segment_def_id
break
else:
raise ValueError("Cannot find channel %s in segment_definer table."\
%(segmentName))
# Get the segmentlist corresponding to this segmentName in segment_summary
segmentSummTable = table.get_table(xmldoc, "segment_summary")
summSegList = segments.segmentlist([])
for entry in segmentSummTable:
if entry.segment_def_id == segDefID:
segment = segments.segment(entry.start_time, entry.end_time)
summSegList.append(segment)
summSegList.coalesce()
return summSegList | [
"def",
"get_segment_summary_times",
"(",
"scienceFile",
",",
"segmentName",
")",
":",
"# Parse the segmentName",
"segmentName",
"=",
"segmentName",
".",
"split",
"(",
"':'",
")",
"if",
"not",
"len",
"(",
"segmentName",
")",
"in",
"[",
"2",
",",
"3",
"]",
":"... | This function will find the times for which the segment_summary is set
for the flag given by segmentName.
Parameters
-----------
scienceFile : SegFile
The segment file that we want to use to determine this.
segmentName : string
The DQ flag to search for times in the segment_summary table.
Returns
---------
summSegList : ligo.segments.segmentlist
The times that are covered in the segment summary table. | [
"This",
"function",
"will",
"find",
"the",
"times",
"for",
"which",
"the",
"segment_summary",
"is",
"set",
"for",
"the",
"flag",
"given",
"by",
"segmentName",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L835-L887 |
228,403 | gwastro/pycbc | pycbc/workflow/datafind.py | run_datafind_instance | def run_datafind_instance(cp, outputDir, connection, observatory, frameType,
startTime, endTime, ifo, tags=None):
"""
This function will query the datafind server once to find frames between
the specified times for the specified frame type and observatory.
Parameters
----------
cp : ConfigParser instance
Source for any kwargs that should be sent to the datafind module
outputDir : Output cache files will be written here. We also write the
commands for reproducing what is done in this function to this
directory.
connection : datafind connection object
Initialized through the glue.datafind module, this is the open
connection to the datafind server.
observatory : string
The observatory to query frames for. Ex. 'H', 'L' or 'V'. NB: not
'H1', 'L1', 'V1' which denote interferometers.
frameType : string
The frame type to query for.
startTime : int
Integer start time to query the datafind server for frames.
endTime : int
Integer end time to query the datafind server for frames.
ifo : string
The interferometer to use for naming output. Ex. 'H1', 'L1', 'V1'.
Maybe this could be merged with the observatory string, but this
could cause issues if running on old 'H2' and 'H1' data.
tags : list of string, optional (default=None)
Use this to specify tags. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniquify the actual filename.
FIXME: Filenames may not be unique with current codes!
Returns
--------
dfCache : glue.lal.Cache instance
The glue.lal.Cache representation of the call to the datafind
server and the returned frame files.
cacheFile : pycbc.workflow.core.File
Cache file listing all of the datafind output files for use later in the pipeline.
"""
if tags is None:
tags = []
seg = segments.segment([startTime, endTime])
# Take the datafind kwargs from config (usually urltype=file is
# given).
dfKwargs = {}
# By default ignore missing frames, this case is dealt with outside of here
dfKwargs['on_gaps'] = 'ignore'
if cp.has_section("datafind"):
for item, value in cp.items("datafind"):
dfKwargs[item] = value
for tag in tags:
if cp.has_section('datafind-%s' %(tag)):
for item, value in cp.items("datafind-%s" %(tag)):
dfKwargs[item] = value
# It is useful to print the corresponding command to the logs
# directory to check if this was expected.
log_datafind_command(observatory, frameType, startTime, endTime,
os.path.join(outputDir,'logs'), **dfKwargs)
logging.debug("Asking datafind server for frames.")
dfCache = connection.find_frame_urls(observatory, frameType,
startTime, endTime, **dfKwargs)
logging.debug("Frames returned")
# workflow format output file
cache_file = File(ifo, 'DATAFIND', seg, extension='lcf',
directory=outputDir, tags=tags)
cache_file.PFN(cache_file.cache_entry.path, site='local')
dfCache.ifo = ifo
# Dump output to file
fP = open(cache_file.storage_path, "w")
# FIXME: CANNOT use dfCache.tofile because it will print 815901601.00000
# as a gps time which is incompatible with the lal cache format
# (and the C codes) which demand an integer.
#dfCache.tofile(fP)
for entry in dfCache:
start = str(int(entry.segment[0]))
duration = str(int(abs(entry.segment)))
print("%s %s %s %s %s" \
% (entry.observatory, entry.description, start, duration, entry.url), file=fP)
entry.segment = segments.segment(int(entry.segment[0]), int(entry.segment[1]))
fP.close()
return dfCache, cache_file | python | def run_datafind_instance(cp, outputDir, connection, observatory, frameType,
startTime, endTime, ifo, tags=None):
if tags is None:
tags = []
seg = segments.segment([startTime, endTime])
# Take the datafind kwargs from config (usually urltype=file is
# given).
dfKwargs = {}
# By default ignore missing frames, this case is dealt with outside of here
dfKwargs['on_gaps'] = 'ignore'
if cp.has_section("datafind"):
for item, value in cp.items("datafind"):
dfKwargs[item] = value
for tag in tags:
if cp.has_section('datafind-%s' %(tag)):
for item, value in cp.items("datafind-%s" %(tag)):
dfKwargs[item] = value
# It is useful to print the corresponding command to the logs
# directory to check if this was expected.
log_datafind_command(observatory, frameType, startTime, endTime,
os.path.join(outputDir,'logs'), **dfKwargs)
logging.debug("Asking datafind server for frames.")
dfCache = connection.find_frame_urls(observatory, frameType,
startTime, endTime, **dfKwargs)
logging.debug("Frames returned")
# workflow format output file
cache_file = File(ifo, 'DATAFIND', seg, extension='lcf',
directory=outputDir, tags=tags)
cache_file.PFN(cache_file.cache_entry.path, site='local')
dfCache.ifo = ifo
# Dump output to file
fP = open(cache_file.storage_path, "w")
# FIXME: CANNOT use dfCache.tofile because it will print 815901601.00000
# as a gps time which is incompatible with the lal cache format
# (and the C codes) which demand an integer.
#dfCache.tofile(fP)
for entry in dfCache:
start = str(int(entry.segment[0]))
duration = str(int(abs(entry.segment)))
print("%s %s %s %s %s" \
% (entry.observatory, entry.description, start, duration, entry.url), file=fP)
entry.segment = segments.segment(int(entry.segment[0]), int(entry.segment[1]))
fP.close()
return dfCache, cache_file | [
"def",
"run_datafind_instance",
"(",
"cp",
",",
"outputDir",
",",
"connection",
",",
"observatory",
",",
"frameType",
",",
"startTime",
",",
"endTime",
",",
"ifo",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"... | This function will query the datafind server once to find frames between
the specified times for the specified frame type and observatory.
Parameters
----------
cp : ConfigParser instance
Source for any kwargs that should be sent to the datafind module
outputDir : Output cache files will be written here. We also write the
commands for reproducing what is done in this function to this
directory.
connection : datafind connection object
Initialized through the glue.datafind module, this is the open
connection to the datafind server.
observatory : string
The observatory to query frames for. Ex. 'H', 'L' or 'V'. NB: not
'H1', 'L1', 'V1' which denote interferometers.
frameType : string
The frame type to query for.
startTime : int
Integer start time to query the datafind server for frames.
endTime : int
Integer end time to query the datafind server for frames.
ifo : string
The interferometer to use for naming output. Ex. 'H1', 'L1', 'V1'.
Maybe this could be merged with the observatory string, but this
could cause issues if running on old 'H2' and 'H1' data.
tags : list of string, optional (default=None)
Use this to specify tags. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniquify the actual filename.
FIXME: Filenames may not be unique with current codes!
Returns
--------
dfCache : glue.lal.Cache instance
The glue.lal.Cache representation of the call to the datafind
server and the returned frame files.
cacheFile : pycbc.workflow.core.File
Cache file listing all of the datafind output files for use later in the pipeline. | [
"This",
"function",
"will",
"query",
"the",
"datafind",
"server",
"once",
"to",
"find",
"frames",
"between",
"the",
"specified",
"times",
"for",
"the",
"specified",
"frame",
"type",
"and",
"observatory",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L889-L980 |
228,404 | gwastro/pycbc | pycbc/workflow/datafind.py | log_datafind_command | def log_datafind_command(observatory, frameType, startTime, endTime,
outputDir, **dfKwargs):
"""
This command will print an equivalent gw_data_find command to disk that
can be used to debug why the internal datafind module is not working.
"""
# FIXME: This does not accurately reproduce the call as assuming the
# kwargs will be the same is wrong, so some things need to be converted
# "properly" to the command line equivalent.
gw_command = ['gw_data_find', '--observatory', observatory,
'--type', frameType,
'--gps-start-time', str(startTime),
'--gps-end-time', str(endTime)]
for name, value in dfKwargs.items():
if name == 'match':
gw_command.append("--match")
gw_command.append(str(value))
elif name == 'urltype':
gw_command.append("--url-type")
gw_command.append(str(value))
elif name == 'on_gaps':
pass
else:
errMsg = "Unknown datafind kwarg given: %s. " %(name)
errMsg+= "This argument is stripped in the logged .sh command."
logging.warn(errMsg)
fileName = "%s-%s-%d-%d.sh" \
%(observatory, frameType, startTime, endTime-startTime)
filePath = os.path.join(outputDir, fileName)
fP = open(filePath, 'w')
fP.write(' '.join(gw_command))
fP.close() | python | def log_datafind_command(observatory, frameType, startTime, endTime,
outputDir, **dfKwargs):
# FIXME: This does not accurately reproduce the call as assuming the
# kwargs will be the same is wrong, so some things need to be converted
# "properly" to the command line equivalent.
gw_command = ['gw_data_find', '--observatory', observatory,
'--type', frameType,
'--gps-start-time', str(startTime),
'--gps-end-time', str(endTime)]
for name, value in dfKwargs.items():
if name == 'match':
gw_command.append("--match")
gw_command.append(str(value))
elif name == 'urltype':
gw_command.append("--url-type")
gw_command.append(str(value))
elif name == 'on_gaps':
pass
else:
errMsg = "Unknown datafind kwarg given: %s. " %(name)
errMsg+= "This argument is stripped in the logged .sh command."
logging.warn(errMsg)
fileName = "%s-%s-%d-%d.sh" \
%(observatory, frameType, startTime, endTime-startTime)
filePath = os.path.join(outputDir, fileName)
fP = open(filePath, 'w')
fP.write(' '.join(gw_command))
fP.close() | [
"def",
"log_datafind_command",
"(",
"observatory",
",",
"frameType",
",",
"startTime",
",",
"endTime",
",",
"outputDir",
",",
"*",
"*",
"dfKwargs",
")",
":",
"# FIXME: This does not accurately reproduce the call as assuming the",
"# kwargs will be the same is wrong, so some thi... | This command will print an equivalent gw_data_find command to disk that
can be used to debug why the internal datafind module is not working. | [
"This",
"command",
"will",
"print",
"an",
"equivalent",
"gw_data_find",
"command",
"to",
"disk",
"that",
"can",
"be",
"used",
"to",
"debug",
"why",
"the",
"internal",
"datafind",
"module",
"is",
"not",
"working",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L983-L1016 |
228,405 | gwastro/pycbc | pycbc/vetoes/bank_chisq.py | segment_snrs | def segment_snrs(filters, stilde, psd, low_frequency_cutoff):
""" This functions calculates the snr of each bank veto template against
the segment
Parameters
----------
filters: list of FrequencySeries
The list of bank veto templates filters.
stilde: FrequencySeries
The current segment of data.
psd: FrequencySeries
low_frequency_cutoff: float
Returns
-------
snr (list): List of snr time series.
norm (list): List of normalizations factors for the snr time series.
"""
snrs = []
norms = []
for bank_template in filters:
# For every template compute the snr against the stilde segment
snr, _, norm = matched_filter_core(
bank_template, stilde, h_norm=bank_template.sigmasq(psd),
psd=None, low_frequency_cutoff=low_frequency_cutoff)
# SNR time series stored here
snrs.append(snr)
# Template normalization factor stored here
norms.append(norm)
return snrs, norms | python | def segment_snrs(filters, stilde, psd, low_frequency_cutoff):
snrs = []
norms = []
for bank_template in filters:
# For every template compute the snr against the stilde segment
snr, _, norm = matched_filter_core(
bank_template, stilde, h_norm=bank_template.sigmasq(psd),
psd=None, low_frequency_cutoff=low_frequency_cutoff)
# SNR time series stored here
snrs.append(snr)
# Template normalization factor stored here
norms.append(norm)
return snrs, norms | [
"def",
"segment_snrs",
"(",
"filters",
",",
"stilde",
",",
"psd",
",",
"low_frequency_cutoff",
")",
":",
"snrs",
"=",
"[",
"]",
"norms",
"=",
"[",
"]",
"for",
"bank_template",
"in",
"filters",
":",
"# For every template compute the snr against the stilde segment",
... | This functions calculates the snr of each bank veto template against
the segment
Parameters
----------
filters: list of FrequencySeries
The list of bank veto templates filters.
stilde: FrequencySeries
The current segment of data.
psd: FrequencySeries
low_frequency_cutoff: float
Returns
-------
snr (list): List of snr time series.
norm (list): List of normalizations factors for the snr time series. | [
"This",
"functions",
"calculates",
"the",
"snr",
"of",
"each",
"bank",
"veto",
"template",
"against",
"the",
"segment"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/vetoes/bank_chisq.py#L30-L61 |
228,406 | gwastro/pycbc | pycbc/vetoes/bank_chisq.py | template_overlaps | def template_overlaps(bank_filters, template, psd, low_frequency_cutoff):
""" This functions calculates the overlaps between the template and the
bank veto templates.
Parameters
----------
bank_filters: List of FrequencySeries
template: FrequencySeries
psd: FrequencySeries
low_frequency_cutoff: float
Returns
-------
overlaps: List of complex overlap values.
"""
overlaps = []
template_ow = template / psd
for bank_template in bank_filters:
overlap = overlap_cplx(template_ow, bank_template,
low_frequency_cutoff=low_frequency_cutoff, normalized=False)
norm = sqrt(1 / template.sigmasq(psd) / bank_template.sigmasq(psd))
overlaps.append(overlap * norm)
if (abs(overlaps[-1]) > 0.99):
errMsg = "Overlap > 0.99 between bank template and filter. "
errMsg += "This bank template will not be used to calculate "
errMsg += "bank chisq for this filter template. The expected "
errMsg += "value will be added to the chisq to account for "
errMsg += "the removal of this template.\n"
errMsg += "Masses of filter template: %e %e\n" \
%(template.params.mass1, template.params.mass2)
errMsg += "Masses of bank filter template: %e %e\n" \
%(bank_template.params.mass1, bank_template.params.mass2)
errMsg += "Overlap: %e" %(abs(overlaps[-1]))
logging.debug(errMsg)
return overlaps | python | def template_overlaps(bank_filters, template, psd, low_frequency_cutoff):
overlaps = []
template_ow = template / psd
for bank_template in bank_filters:
overlap = overlap_cplx(template_ow, bank_template,
low_frequency_cutoff=low_frequency_cutoff, normalized=False)
norm = sqrt(1 / template.sigmasq(psd) / bank_template.sigmasq(psd))
overlaps.append(overlap * norm)
if (abs(overlaps[-1]) > 0.99):
errMsg = "Overlap > 0.99 between bank template and filter. "
errMsg += "This bank template will not be used to calculate "
errMsg += "bank chisq for this filter template. The expected "
errMsg += "value will be added to the chisq to account for "
errMsg += "the removal of this template.\n"
errMsg += "Masses of filter template: %e %e\n" \
%(template.params.mass1, template.params.mass2)
errMsg += "Masses of bank filter template: %e %e\n" \
%(bank_template.params.mass1, bank_template.params.mass2)
errMsg += "Overlap: %e" %(abs(overlaps[-1]))
logging.debug(errMsg)
return overlaps | [
"def",
"template_overlaps",
"(",
"bank_filters",
",",
"template",
",",
"psd",
",",
"low_frequency_cutoff",
")",
":",
"overlaps",
"=",
"[",
"]",
"template_ow",
"=",
"template",
"/",
"psd",
"for",
"bank_template",
"in",
"bank_filters",
":",
"overlap",
"=",
"over... | This functions calculates the overlaps between the template and the
bank veto templates.
Parameters
----------
bank_filters: List of FrequencySeries
template: FrequencySeries
psd: FrequencySeries
low_frequency_cutoff: float
Returns
-------
overlaps: List of complex overlap values. | [
"This",
"functions",
"calculates",
"the",
"overlaps",
"between",
"the",
"template",
"and",
"the",
"bank",
"veto",
"templates",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/vetoes/bank_chisq.py#L63-L97 |
228,407 | gwastro/pycbc | pycbc/vetoes/bank_chisq.py | bank_chisq_from_filters | def bank_chisq_from_filters(tmplt_snr, tmplt_norm, bank_snrs, bank_norms,
tmplt_bank_matches, indices=None):
""" This function calculates and returns a TimeSeries object containing the
bank veto calculated over a segment.
Parameters
----------
tmplt_snr: TimeSeries
The SNR time series from filtering the segment against the current
search template
tmplt_norm: float
The normalization factor for the search template
bank_snrs: list of TimeSeries
The precomputed list of SNR time series between each of the bank veto
templates and the segment
bank_norms: list of floats
The normalization factors for the list of bank veto templates
(usually this will be the same for all bank veto templates)
tmplt_bank_matches: list of floats
The complex overlap between the search template and each
of the bank templates
indices: {None, Array}, optional
Array of indices into the snr time series. If given, the bank chisq
will only be calculated at these values.
Returns
-------
bank_chisq: TimeSeries of the bank vetos
"""
if indices is not None:
tmplt_snr = Array(tmplt_snr, copy=False)
bank_snrs_tmp = []
for bank_snr in bank_snrs:
bank_snrs_tmp.append(bank_snr.take(indices))
bank_snrs=bank_snrs_tmp
# Initialise bank_chisq as 0s everywhere
bank_chisq = zeros(len(tmplt_snr), dtype=real_same_precision_as(tmplt_snr))
# Loop over all the bank templates
for i in range(len(bank_snrs)):
bank_match = tmplt_bank_matches[i]
if (abs(bank_match) > 0.99):
# Not much point calculating bank_chisquared if the bank template
# is very close to the filter template. Can also hit numerical
# error due to approximations made in this calculation.
# The value of 2 is the expected addition to the chisq for this
# template
bank_chisq += 2.
continue
bank_norm = sqrt((1 - bank_match*bank_match.conj()).real)
bank_SNR = bank_snrs[i] * (bank_norms[i] / bank_norm)
tmplt_SNR = tmplt_snr * (bank_match.conj() * tmplt_norm / bank_norm)
bank_SNR = Array(bank_SNR, copy=False)
tmplt_SNR = Array(tmplt_SNR, copy=False)
bank_chisq += (bank_SNR - tmplt_SNR).squared_norm()
if indices is not None:
return bank_chisq
else:
return TimeSeries(bank_chisq, delta_t=tmplt_snr.delta_t,
epoch=tmplt_snr.start_time, copy=False) | python | def bank_chisq_from_filters(tmplt_snr, tmplt_norm, bank_snrs, bank_norms,
tmplt_bank_matches, indices=None):
if indices is not None:
tmplt_snr = Array(tmplt_snr, copy=False)
bank_snrs_tmp = []
for bank_snr in bank_snrs:
bank_snrs_tmp.append(bank_snr.take(indices))
bank_snrs=bank_snrs_tmp
# Initialise bank_chisq as 0s everywhere
bank_chisq = zeros(len(tmplt_snr), dtype=real_same_precision_as(tmplt_snr))
# Loop over all the bank templates
for i in range(len(bank_snrs)):
bank_match = tmplt_bank_matches[i]
if (abs(bank_match) > 0.99):
# Not much point calculating bank_chisquared if the bank template
# is very close to the filter template. Can also hit numerical
# error due to approximations made in this calculation.
# The value of 2 is the expected addition to the chisq for this
# template
bank_chisq += 2.
continue
bank_norm = sqrt((1 - bank_match*bank_match.conj()).real)
bank_SNR = bank_snrs[i] * (bank_norms[i] / bank_norm)
tmplt_SNR = tmplt_snr * (bank_match.conj() * tmplt_norm / bank_norm)
bank_SNR = Array(bank_SNR, copy=False)
tmplt_SNR = Array(tmplt_SNR, copy=False)
bank_chisq += (bank_SNR - tmplt_SNR).squared_norm()
if indices is not None:
return bank_chisq
else:
return TimeSeries(bank_chisq, delta_t=tmplt_snr.delta_t,
epoch=tmplt_snr.start_time, copy=False) | [
"def",
"bank_chisq_from_filters",
"(",
"tmplt_snr",
",",
"tmplt_norm",
",",
"bank_snrs",
",",
"bank_norms",
",",
"tmplt_bank_matches",
",",
"indices",
"=",
"None",
")",
":",
"if",
"indices",
"is",
"not",
"None",
":",
"tmplt_snr",
"=",
"Array",
"(",
"tmplt_snr"... | This function calculates and returns a TimeSeries object containing the
bank veto calculated over a segment.
Parameters
----------
tmplt_snr: TimeSeries
The SNR time series from filtering the segment against the current
search template
tmplt_norm: float
The normalization factor for the search template
bank_snrs: list of TimeSeries
The precomputed list of SNR time series between each of the bank veto
templates and the segment
bank_norms: list of floats
The normalization factors for the list of bank veto templates
(usually this will be the same for all bank veto templates)
tmplt_bank_matches: list of floats
The complex overlap between the search template and each
of the bank templates
indices: {None, Array}, optional
Array of indices into the snr time series. If given, the bank chisq
will only be calculated at these values.
Returns
-------
bank_chisq: TimeSeries of the bank vetos | [
"This",
"function",
"calculates",
"and",
"returns",
"a",
"TimeSeries",
"object",
"containing",
"the",
"bank",
"veto",
"calculated",
"over",
"a",
"segment",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/vetoes/bank_chisq.py#L99-L163 |
228,408 | gwastro/pycbc | pycbc/events/veto.py | start_end_from_segments | def start_end_from_segments(segment_file):
"""
Return the start and end time arrays from a segment file.
Parameters
----------
segment_file: xml segment file
Returns
-------
start: numpy.ndarray
end: numpy.ndarray
"""
from glue.ligolw.ligolw import LIGOLWContentHandler as h; lsctables.use_in(h)
indoc = ligolw_utils.load_filename(segment_file, False, contenthandler=h)
segment_table = table.get_table(indoc, lsctables.SegmentTable.tableName)
start = numpy.array(segment_table.getColumnByName('start_time'))
start_ns = numpy.array(segment_table.getColumnByName('start_time_ns'))
end = numpy.array(segment_table.getColumnByName('end_time'))
end_ns = numpy.array(segment_table.getColumnByName('end_time_ns'))
return start + start_ns * 1e-9, end + end_ns * 1e-9 | python | def start_end_from_segments(segment_file):
from glue.ligolw.ligolw import LIGOLWContentHandler as h; lsctables.use_in(h)
indoc = ligolw_utils.load_filename(segment_file, False, contenthandler=h)
segment_table = table.get_table(indoc, lsctables.SegmentTable.tableName)
start = numpy.array(segment_table.getColumnByName('start_time'))
start_ns = numpy.array(segment_table.getColumnByName('start_time_ns'))
end = numpy.array(segment_table.getColumnByName('end_time'))
end_ns = numpy.array(segment_table.getColumnByName('end_time_ns'))
return start + start_ns * 1e-9, end + end_ns * 1e-9 | [
"def",
"start_end_from_segments",
"(",
"segment_file",
")",
":",
"from",
"glue",
".",
"ligolw",
".",
"ligolw",
"import",
"LIGOLWContentHandler",
"as",
"h",
"lsctables",
".",
"use_in",
"(",
"h",
")",
"indoc",
"=",
"ligolw_utils",
".",
"load_filename",
"(",
"seg... | Return the start and end time arrays from a segment file.
Parameters
----------
segment_file: xml segment file
Returns
-------
start: numpy.ndarray
end: numpy.ndarray | [
"Return",
"the",
"start",
"and",
"end",
"time",
"arrays",
"from",
"a",
"segment",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/veto.py#L16-L36 |
228,409 | gwastro/pycbc | pycbc/events/veto.py | indices_within_times | def indices_within_times(times, start, end):
"""
Return an index array into times that lie within the durations defined by start end arrays
Parameters
----------
times: numpy.ndarray
Array of times
start: numpy.ndarray
Array of duration start times
end: numpy.ndarray
Array of duration end times
Returns
-------
indices: numpy.ndarray
Array of indices into times
"""
# coalesce the start/end segments
start, end = segments_to_start_end(start_end_to_segments(start, end).coalesce())
tsort = times.argsort()
times_sorted = times[tsort]
left = numpy.searchsorted(times_sorted, start)
right = numpy.searchsorted(times_sorted, end)
if len(left) == 0:
return numpy.array([], dtype=numpy.uint32)
return tsort[numpy.hstack(numpy.r_[s:e] for s, e in zip(left, right))] | python | def indices_within_times(times, start, end):
# coalesce the start/end segments
start, end = segments_to_start_end(start_end_to_segments(start, end).coalesce())
tsort = times.argsort()
times_sorted = times[tsort]
left = numpy.searchsorted(times_sorted, start)
right = numpy.searchsorted(times_sorted, end)
if len(left) == 0:
return numpy.array([], dtype=numpy.uint32)
return tsort[numpy.hstack(numpy.r_[s:e] for s, e in zip(left, right))] | [
"def",
"indices_within_times",
"(",
"times",
",",
"start",
",",
"end",
")",
":",
"# coalesce the start/end segments",
"start",
",",
"end",
"=",
"segments_to_start_end",
"(",
"start_end_to_segments",
"(",
"start",
",",
"end",
")",
".",
"coalesce",
"(",
")",
")",
... | Return an index array into times that lie within the durations defined by start end arrays
Parameters
----------
times: numpy.ndarray
Array of times
start: numpy.ndarray
Array of duration start times
end: numpy.ndarray
Array of duration end times
Returns
-------
indices: numpy.ndarray
Array of indices into times | [
"Return",
"an",
"index",
"array",
"into",
"times",
"that",
"lie",
"within",
"the",
"durations",
"defined",
"by",
"start",
"end",
"arrays"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/veto.py#L39-L68 |
228,410 | gwastro/pycbc | pycbc/events/veto.py | indices_outside_times | def indices_outside_times(times, start, end):
"""
Return an index array into times that like outside the durations defined by start end arrays
Parameters
----------
times: numpy.ndarray
Array of times
start: numpy.ndarray
Array of duration start times
end: numpy.ndarray
Array of duration end times
Returns
-------
indices: numpy.ndarray
Array of indices into times
"""
exclude = indices_within_times(times, start, end)
indices = numpy.arange(0, len(times))
return numpy.delete(indices, exclude) | python | def indices_outside_times(times, start, end):
exclude = indices_within_times(times, start, end)
indices = numpy.arange(0, len(times))
return numpy.delete(indices, exclude) | [
"def",
"indices_outside_times",
"(",
"times",
",",
"start",
",",
"end",
")",
":",
"exclude",
"=",
"indices_within_times",
"(",
"times",
",",
"start",
",",
"end",
")",
"indices",
"=",
"numpy",
".",
"arange",
"(",
"0",
",",
"len",
"(",
"times",
")",
")",... | Return an index array into times that like outside the durations defined by start end arrays
Parameters
----------
times: numpy.ndarray
Array of times
start: numpy.ndarray
Array of duration start times
end: numpy.ndarray
Array of duration end times
Returns
-------
indices: numpy.ndarray
Array of indices into times | [
"Return",
"an",
"index",
"array",
"into",
"times",
"that",
"like",
"outside",
"the",
"durations",
"defined",
"by",
"start",
"end",
"arrays"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/veto.py#L70-L90 |
228,411 | gwastro/pycbc | pycbc/events/veto.py | select_segments_by_definer | def select_segments_by_definer(segment_file, segment_name=None, ifo=None):
""" Return the list of segments that match the segment name
Parameters
----------
segment_file: str
path to segment xml file
segment_name: str
Name of segment
ifo: str, optional
Returns
-------
seg: list of segments
"""
from glue.ligolw.ligolw import LIGOLWContentHandler as h; lsctables.use_in(h)
indoc = ligolw_utils.load_filename(segment_file, False, contenthandler=h)
segment_table = table.get_table(indoc, 'segment')
seg_def_table = table.get_table(indoc, 'segment_definer')
def_ifos = seg_def_table.getColumnByName('ifos')
def_names = seg_def_table.getColumnByName('name')
def_ids = seg_def_table.getColumnByName('segment_def_id')
valid_id = []
for def_ifo, def_name, def_id in zip(def_ifos, def_names, def_ids):
if ifo and ifo != def_ifo:
continue
if segment_name and segment_name != def_name:
continue
valid_id += [def_id]
start = numpy.array(segment_table.getColumnByName('start_time'))
start_ns = numpy.array(segment_table.getColumnByName('start_time_ns'))
end = numpy.array(segment_table.getColumnByName('end_time'))
end_ns = numpy.array(segment_table.getColumnByName('end_time_ns'))
start, end = start + 1e-9 * start_ns, end + 1e-9 * end_ns
did = segment_table.getColumnByName('segment_def_id')
keep = numpy.array([d in valid_id for d in did])
if sum(keep) > 0:
return start_end_to_segments(start[keep], end[keep])
else:
return segmentlist([]) | python | def select_segments_by_definer(segment_file, segment_name=None, ifo=None):
from glue.ligolw.ligolw import LIGOLWContentHandler as h; lsctables.use_in(h)
indoc = ligolw_utils.load_filename(segment_file, False, contenthandler=h)
segment_table = table.get_table(indoc, 'segment')
seg_def_table = table.get_table(indoc, 'segment_definer')
def_ifos = seg_def_table.getColumnByName('ifos')
def_names = seg_def_table.getColumnByName('name')
def_ids = seg_def_table.getColumnByName('segment_def_id')
valid_id = []
for def_ifo, def_name, def_id in zip(def_ifos, def_names, def_ids):
if ifo and ifo != def_ifo:
continue
if segment_name and segment_name != def_name:
continue
valid_id += [def_id]
start = numpy.array(segment_table.getColumnByName('start_time'))
start_ns = numpy.array(segment_table.getColumnByName('start_time_ns'))
end = numpy.array(segment_table.getColumnByName('end_time'))
end_ns = numpy.array(segment_table.getColumnByName('end_time_ns'))
start, end = start + 1e-9 * start_ns, end + 1e-9 * end_ns
did = segment_table.getColumnByName('segment_def_id')
keep = numpy.array([d in valid_id for d in did])
if sum(keep) > 0:
return start_end_to_segments(start[keep], end[keep])
else:
return segmentlist([]) | [
"def",
"select_segments_by_definer",
"(",
"segment_file",
",",
"segment_name",
"=",
"None",
",",
"ifo",
"=",
"None",
")",
":",
"from",
"glue",
".",
"ligolw",
".",
"ligolw",
"import",
"LIGOLWContentHandler",
"as",
"h",
"lsctables",
".",
"use_in",
"(",
"h",
")... | Return the list of segments that match the segment name
Parameters
----------
segment_file: str
path to segment xml file
segment_name: str
Name of segment
ifo: str, optional
Returns
-------
seg: list of segments | [
"Return",
"the",
"list",
"of",
"segments",
"that",
"match",
"the",
"segment",
"name"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/veto.py#L92-L136 |
228,412 | gwastro/pycbc | pycbc/events/veto.py | indices_within_segments | def indices_within_segments(times, segment_files, ifo=None, segment_name=None):
""" Return the list of indices that should be vetoed by the segments in the
list of veto_files.
Parameters
----------
times: numpy.ndarray of integer type
Array of gps start times
segment_files: string or list of strings
A string or list of strings that contain the path to xml files that
contain a segment table
ifo: string, optional
The ifo to retrieve segments for from the segment files
segment_name: str, optional
name of segment
Returns
-------
indices: numpy.ndarray
The array of index values within the segments
segmentlist:
The segment list corresponding to the selected time.
"""
veto_segs = segmentlist([])
indices = numpy.array([], dtype=numpy.uint32)
for veto_file in segment_files:
veto_segs += select_segments_by_definer(veto_file, segment_name, ifo)
veto_segs.coalesce()
start, end = segments_to_start_end(veto_segs)
if len(start) > 0:
idx = indices_within_times(times, start, end)
indices = numpy.union1d(indices, idx)
return indices, veto_segs.coalesce() | python | def indices_within_segments(times, segment_files, ifo=None, segment_name=None):
veto_segs = segmentlist([])
indices = numpy.array([], dtype=numpy.uint32)
for veto_file in segment_files:
veto_segs += select_segments_by_definer(veto_file, segment_name, ifo)
veto_segs.coalesce()
start, end = segments_to_start_end(veto_segs)
if len(start) > 0:
idx = indices_within_times(times, start, end)
indices = numpy.union1d(indices, idx)
return indices, veto_segs.coalesce() | [
"def",
"indices_within_segments",
"(",
"times",
",",
"segment_files",
",",
"ifo",
"=",
"None",
",",
"segment_name",
"=",
"None",
")",
":",
"veto_segs",
"=",
"segmentlist",
"(",
"[",
"]",
")",
"indices",
"=",
"numpy",
".",
"array",
"(",
"[",
"]",
",",
"... | Return the list of indices that should be vetoed by the segments in the
list of veto_files.
Parameters
----------
times: numpy.ndarray of integer type
Array of gps start times
segment_files: string or list of strings
A string or list of strings that contain the path to xml files that
contain a segment table
ifo: string, optional
The ifo to retrieve segments for from the segment files
segment_name: str, optional
name of segment
Returns
-------
indices: numpy.ndarray
The array of index values within the segments
segmentlist:
The segment list corresponding to the selected time. | [
"Return",
"the",
"list",
"of",
"indices",
"that",
"should",
"be",
"vetoed",
"by",
"the",
"segments",
"in",
"the",
"list",
"of",
"veto_files",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/veto.py#L138-L171 |
228,413 | gwastro/pycbc | pycbc/events/veto.py | indices_outside_segments | def indices_outside_segments(times, segment_files, ifo=None, segment_name=None):
""" Return the list of indices that are outside the segments in the
list of segment files.
Parameters
----------
times: numpy.ndarray of integer type
Array of gps start times
segment_files: string or list of strings
A string or list of strings that contain the path to xml files that
contain a segment table
ifo: string, optional
The ifo to retrieve segments for from the segment files
segment_name: str, optional
name of segment
Returns
--------
indices: numpy.ndarray
The array of index values outside the segments
segmentlist:
The segment list corresponding to the selected time.
"""
exclude, segs = indices_within_segments(times, segment_files,
ifo=ifo, segment_name=segment_name)
indices = numpy.arange(0, len(times))
return numpy.delete(indices, exclude), segs | python | def indices_outside_segments(times, segment_files, ifo=None, segment_name=None):
exclude, segs = indices_within_segments(times, segment_files,
ifo=ifo, segment_name=segment_name)
indices = numpy.arange(0, len(times))
return numpy.delete(indices, exclude), segs | [
"def",
"indices_outside_segments",
"(",
"times",
",",
"segment_files",
",",
"ifo",
"=",
"None",
",",
"segment_name",
"=",
"None",
")",
":",
"exclude",
",",
"segs",
"=",
"indices_within_segments",
"(",
"times",
",",
"segment_files",
",",
"ifo",
"=",
"ifo",
",... | Return the list of indices that are outside the segments in the
list of segment files.
Parameters
----------
times: numpy.ndarray of integer type
Array of gps start times
segment_files: string or list of strings
A string or list of strings that contain the path to xml files that
contain a segment table
ifo: string, optional
The ifo to retrieve segments for from the segment files
segment_name: str, optional
name of segment
Returns
--------
indices: numpy.ndarray
The array of index values outside the segments
segmentlist:
The segment list corresponding to the selected time. | [
"Return",
"the",
"list",
"of",
"indices",
"that",
"are",
"outside",
"the",
"segments",
"in",
"the",
"list",
"of",
"segment",
"files",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/veto.py#L173-L198 |
228,414 | gwastro/pycbc | pycbc/events/veto.py | get_segment_definer_comments | def get_segment_definer_comments(xml_file, include_version=True):
"""Returns a dict with the comment column as the value for each segment"""
from glue.ligolw.ligolw import LIGOLWContentHandler as h
lsctables.use_in(h)
# read segment definer table
xmldoc, _ = ligolw_utils.load_fileobj(xml_file,
gz=xml_file.name.endswith(".gz"),
contenthandler=h)
seg_def_table = table.get_table(xmldoc,
lsctables.SegmentDefTable.tableName)
# put comment column into a dict
comment_dict = {}
for seg_def in seg_def_table:
if include_version:
full_channel_name = ':'.join([str(seg_def.ifos),
str(seg_def.name),
str(seg_def.version)])
else:
full_channel_name = ':'.join([str(seg_def.ifos),
str(seg_def.name)])
comment_dict[full_channel_name] = seg_def.comment
return comment_dict | python | def get_segment_definer_comments(xml_file, include_version=True):
from glue.ligolw.ligolw import LIGOLWContentHandler as h
lsctables.use_in(h)
# read segment definer table
xmldoc, _ = ligolw_utils.load_fileobj(xml_file,
gz=xml_file.name.endswith(".gz"),
contenthandler=h)
seg_def_table = table.get_table(xmldoc,
lsctables.SegmentDefTable.tableName)
# put comment column into a dict
comment_dict = {}
for seg_def in seg_def_table:
if include_version:
full_channel_name = ':'.join([str(seg_def.ifos),
str(seg_def.name),
str(seg_def.version)])
else:
full_channel_name = ':'.join([str(seg_def.ifos),
str(seg_def.name)])
comment_dict[full_channel_name] = seg_def.comment
return comment_dict | [
"def",
"get_segment_definer_comments",
"(",
"xml_file",
",",
"include_version",
"=",
"True",
")",
":",
"from",
"glue",
".",
"ligolw",
".",
"ligolw",
"import",
"LIGOLWContentHandler",
"as",
"h",
"lsctables",
".",
"use_in",
"(",
"h",
")",
"# read segment definer tab... | Returns a dict with the comment column as the value for each segment | [
"Returns",
"a",
"dict",
"with",
"the",
"comment",
"column",
"as",
"the",
"value",
"for",
"each",
"segment"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/veto.py#L200-L226 |
228,415 | gwastro/pycbc | pycbc/catalog/__init__.py | Merger.strain | def strain(self, ifo, duration=32, sample_rate=4096):
""" Return strain around the event
Currently this will return the strain around the event in the smallest
format available. Selection of other data is not yet available.
Parameters
----------
ifo: str
The name of the observatory you want strain for. Ex. H1, L1, V1
Returns
-------
strain: pycbc.types.TimeSeries
Strain around the event.
"""
from astropy.utils.data import download_file
from pycbc.frame import read_frame
# Information is currently wrong on GWOSC!
# channels = self.data['files']['FrameChannels']
# for channel in channels:
# if ifo in channel:
# break
length = "{}sec".format(duration)
if sample_rate == 4096:
sampling = "4KHz"
elif sample_rate == 16384:
sampling = "16KHz"
channel = "{}:GWOSC-{}_R1_STRAIN".format(ifo, sampling.upper())
url = self.data['files'][ifo][length][sampling]['GWF']
filename = download_file(url, cache=True)
return read_frame(str(filename), str(channel)) | python | def strain(self, ifo, duration=32, sample_rate=4096):
from astropy.utils.data import download_file
from pycbc.frame import read_frame
# Information is currently wrong on GWOSC!
# channels = self.data['files']['FrameChannels']
# for channel in channels:
# if ifo in channel:
# break
length = "{}sec".format(duration)
if sample_rate == 4096:
sampling = "4KHz"
elif sample_rate == 16384:
sampling = "16KHz"
channel = "{}:GWOSC-{}_R1_STRAIN".format(ifo, sampling.upper())
url = self.data['files'][ifo][length][sampling]['GWF']
filename = download_file(url, cache=True)
return read_frame(str(filename), str(channel)) | [
"def",
"strain",
"(",
"self",
",",
"ifo",
",",
"duration",
"=",
"32",
",",
"sample_rate",
"=",
"4096",
")",
":",
"from",
"astropy",
".",
"utils",
".",
"data",
"import",
"download_file",
"from",
"pycbc",
".",
"frame",
"import",
"read_frame",
"# Information ... | Return strain around the event
Currently this will return the strain around the event in the smallest
format available. Selection of other data is not yet available.
Parameters
----------
ifo: str
The name of the observatory you want strain for. Ex. H1, L1, V1
Returns
-------
strain: pycbc.types.TimeSeries
Strain around the event. | [
"Return",
"strain",
"around",
"the",
"event"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/catalog/__init__.py#L73-L107 |
228,416 | gwastro/pycbc | pycbc/workflow/inference_followups.py | make_inference_prior_plot | def make_inference_prior_plot(workflow, config_file, output_dir,
sections=None, name="inference_prior",
analysis_seg=None, tags=None):
""" Sets up the corner plot of the priors in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
config_file: pycbc.workflow.File
The WorkflowConfigParser parasable inference configuration file..
output_dir: str
The directory to store result plots and files.
sections : list
A list of subsections to use.
name: str
The name in the [executables] section of the configuration file
to use.
analysis_segs: {None, ligo.segments.Segment}
The segment this job encompasses. If None then use the total analysis
time from the workflow.
tags: {None, optional}
Tags to add to the inference executables.
Returns
-------
pycbc.workflow.FileList
A list of result and output files.
"""
# default values
tags = [] if tags is None else tags
analysis_seg = workflow.analysis_time \
if analysis_seg is None else analysis_seg
# make the directory that will contain the output files
makedir(output_dir)
# make a node for plotting the posterior as a corner plot
node = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,
out_dir=output_dir, universe="local",
tags=tags).create_node()
# add command line options
node.add_input_opt("--config-file", config_file)
node.new_output_file_opt(analysis_seg, ".png", "--output-file")
if sections is not None:
node.add_opt("--sections", " ".join(sections))
# add node to workflow
workflow += node
return node.output_files | python | def make_inference_prior_plot(workflow, config_file, output_dir,
sections=None, name="inference_prior",
analysis_seg=None, tags=None):
# default values
tags = [] if tags is None else tags
analysis_seg = workflow.analysis_time \
if analysis_seg is None else analysis_seg
# make the directory that will contain the output files
makedir(output_dir)
# make a node for plotting the posterior as a corner plot
node = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,
out_dir=output_dir, universe="local",
tags=tags).create_node()
# add command line options
node.add_input_opt("--config-file", config_file)
node.new_output_file_opt(analysis_seg, ".png", "--output-file")
if sections is not None:
node.add_opt("--sections", " ".join(sections))
# add node to workflow
workflow += node
return node.output_files | [
"def",
"make_inference_prior_plot",
"(",
"workflow",
",",
"config_file",
",",
"output_dir",
",",
"sections",
"=",
"None",
",",
"name",
"=",
"\"inference_prior\"",
",",
"analysis_seg",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"# default values",
"tags",
... | Sets up the corner plot of the priors in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
config_file: pycbc.workflow.File
The WorkflowConfigParser parasable inference configuration file..
output_dir: str
The directory to store result plots and files.
sections : list
A list of subsections to use.
name: str
The name in the [executables] section of the configuration file
to use.
analysis_segs: {None, ligo.segments.Segment}
The segment this job encompasses. If None then use the total analysis
time from the workflow.
tags: {None, optional}
Tags to add to the inference executables.
Returns
-------
pycbc.workflow.FileList
A list of result and output files. | [
"Sets",
"up",
"the",
"corner",
"plot",
"of",
"the",
"priors",
"in",
"the",
"workflow",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/inference_followups.py#L126-L178 |
228,417 | gwastro/pycbc | pycbc/workflow/inference_followups.py | make_inference_summary_table | def make_inference_summary_table(workflow, inference_file, output_dir,
variable_args=None, name="inference_table",
analysis_seg=None, tags=None):
""" Sets up the corner plot of the posteriors in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
inference_file: pycbc.workflow.File
The file with posterior samples.
output_dir: str
The directory to store result plots and files.
variable_args : list
A list of parameters to use instead of [variable_args].
name: str
The name in the [executables] section of the configuration file
to use.
analysis_segs: {None, ligo.segments.Segment}
The segment this job encompasses. If None then use the total analysis
time from the workflow.
tags: {None, optional}
Tags to add to the inference executables.
Returns
-------
pycbc.workflow.FileList
A list of result and output files.
"""
# default values
tags = [] if tags is None else tags
analysis_seg = workflow.analysis_time \
if analysis_seg is None else analysis_seg
# make the directory that will contain the output files
makedir(output_dir)
# make a node for plotting the posterior as a corner plot
node = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,
out_dir=output_dir, tags=tags).create_node()
# add command line options
node.add_input_opt("--input-file", inference_file)
node.new_output_file_opt(analysis_seg, ".html", "--output-file")
node.add_opt("--parameters", " ".join(variable_args))
# add node to workflow
workflow += node
return node.output_files | python | def make_inference_summary_table(workflow, inference_file, output_dir,
variable_args=None, name="inference_table",
analysis_seg=None, tags=None):
# default values
tags = [] if tags is None else tags
analysis_seg = workflow.analysis_time \
if analysis_seg is None else analysis_seg
# make the directory that will contain the output files
makedir(output_dir)
# make a node for plotting the posterior as a corner plot
node = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,
out_dir=output_dir, tags=tags).create_node()
# add command line options
node.add_input_opt("--input-file", inference_file)
node.new_output_file_opt(analysis_seg, ".html", "--output-file")
node.add_opt("--parameters", " ".join(variable_args))
# add node to workflow
workflow += node
return node.output_files | [
"def",
"make_inference_summary_table",
"(",
"workflow",
",",
"inference_file",
",",
"output_dir",
",",
"variable_args",
"=",
"None",
",",
"name",
"=",
"\"inference_table\"",
",",
"analysis_seg",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"# default values",
... | Sets up the corner plot of the posteriors in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
inference_file: pycbc.workflow.File
The file with posterior samples.
output_dir: str
The directory to store result plots and files.
variable_args : list
A list of parameters to use instead of [variable_args].
name: str
The name in the [executables] section of the configuration file
to use.
analysis_segs: {None, ligo.segments.Segment}
The segment this job encompasses. If None then use the total analysis
time from the workflow.
tags: {None, optional}
Tags to add to the inference executables.
Returns
-------
pycbc.workflow.FileList
A list of result and output files. | [
"Sets",
"up",
"the",
"corner",
"plot",
"of",
"the",
"posteriors",
"in",
"the",
"workflow",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/inference_followups.py#L180-L230 |
228,418 | gwastro/pycbc | pycbc/workflow/inference_followups.py | make_inference_acceptance_rate_plot | def make_inference_acceptance_rate_plot(workflow, inference_file, output_dir,
name="inference_rate", analysis_seg=None, tags=None):
""" Sets up the acceptance rate plot in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
inference_file: pycbc.workflow.File
The file with posterior samples.
output_dir: str
The directory to store result plots and files.
name: str
The name in the [executables] section of the configuration file
to use.
analysis_segs: {None, ligo.segments.Segment}
The segment this job encompasses. If None then use the total analysis
time from the workflow.
tags: {None, optional}
Tags to add to the inference executables.
Returns
-------
pycbc.workflow.FileList
A list of result and output files.
"""
# default values
tags = [] if tags is None else tags
analysis_seg = workflow.analysis_time \
if analysis_seg is None else analysis_seg
# make the directory that will contain the output files
makedir(output_dir)
# make a node for plotting the acceptance rate
node = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,
out_dir=output_dir, tags=tags).create_node()
# add command line options
node.add_input_opt("--input-file", inference_file)
node.new_output_file_opt(analysis_seg, ".png", "--output-file")
# add node to workflow
workflow += node
return node.output_files | python | def make_inference_acceptance_rate_plot(workflow, inference_file, output_dir,
name="inference_rate", analysis_seg=None, tags=None):
# default values
tags = [] if tags is None else tags
analysis_seg = workflow.analysis_time \
if analysis_seg is None else analysis_seg
# make the directory that will contain the output files
makedir(output_dir)
# make a node for plotting the acceptance rate
node = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,
out_dir=output_dir, tags=tags).create_node()
# add command line options
node.add_input_opt("--input-file", inference_file)
node.new_output_file_opt(analysis_seg, ".png", "--output-file")
# add node to workflow
workflow += node
return node.output_files | [
"def",
"make_inference_acceptance_rate_plot",
"(",
"workflow",
",",
"inference_file",
",",
"output_dir",
",",
"name",
"=",
"\"inference_rate\"",
",",
"analysis_seg",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"# default values",
"tags",
"=",
"[",
"]",
"if"... | Sets up the acceptance rate plot in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
inference_file: pycbc.workflow.File
The file with posterior samples.
output_dir: str
The directory to store result plots and files.
name: str
The name in the [executables] section of the configuration file
to use.
analysis_segs: {None, ligo.segments.Segment}
The segment this job encompasses. If None then use the total analysis
time from the workflow.
tags: {None, optional}
Tags to add to the inference executables.
Returns
-------
pycbc.workflow.FileList
A list of result and output files. | [
"Sets",
"up",
"the",
"acceptance",
"rate",
"plot",
"in",
"the",
"workflow",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/inference_followups.py#L325-L371 |
228,419 | gwastro/pycbc | pycbc/workflow/inference_followups.py | make_inference_inj_plots | def make_inference_inj_plots(workflow, inference_files, output_dir,
parameters, name="inference_recovery",
analysis_seg=None, tags=None):
""" Sets up the recovered versus injected parameter plot in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
inference_files: pycbc.workflow.FileList
The files with posterior samples.
output_dir: str
The directory to store result plots and files.
parameters : list
A ``list`` of parameters. Each parameter gets its own plot.
name: str
The name in the [executables] section of the configuration file
to use.
analysis_segs: {None, ligo.segments.Segment}
The segment this job encompasses. If None then use the total analysis
time from the workflow.
tags: {None, optional}
Tags to add to the inference executables.
Returns
-------
pycbc.workflow.FileList
A list of result and output files.
"""
# default values
tags = [] if tags is None else tags
analysis_seg = workflow.analysis_time \
if analysis_seg is None else analysis_seg
output_files = FileList([])
# make the directory that will contain the output files
makedir(output_dir)
# add command line options
for (ii, param) in enumerate(parameters):
plot_exe = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,
out_dir=output_dir,
tags=tags+['param{}'.format(ii)])
node = plot_exe.create_node()
node.add_input_list_opt("--input-file", inference_files)
node.new_output_file_opt(analysis_seg, ".png", "--output-file")
node.add_opt("--parameters", param)
workflow += node
output_files += node.output_files
return output_files | python | def make_inference_inj_plots(workflow, inference_files, output_dir,
parameters, name="inference_recovery",
analysis_seg=None, tags=None):
# default values
tags = [] if tags is None else tags
analysis_seg = workflow.analysis_time \
if analysis_seg is None else analysis_seg
output_files = FileList([])
# make the directory that will contain the output files
makedir(output_dir)
# add command line options
for (ii, param) in enumerate(parameters):
plot_exe = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,
out_dir=output_dir,
tags=tags+['param{}'.format(ii)])
node = plot_exe.create_node()
node.add_input_list_opt("--input-file", inference_files)
node.new_output_file_opt(analysis_seg, ".png", "--output-file")
node.add_opt("--parameters", param)
workflow += node
output_files += node.output_files
return output_files | [
"def",
"make_inference_inj_plots",
"(",
"workflow",
",",
"inference_files",
",",
"output_dir",
",",
"parameters",
",",
"name",
"=",
"\"inference_recovery\"",
",",
"analysis_seg",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"# default values",
"tags",
"=",
"... | Sets up the recovered versus injected parameter plot in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
inference_files: pycbc.workflow.FileList
The files with posterior samples.
output_dir: str
The directory to store result plots and files.
parameters : list
A ``list`` of parameters. Each parameter gets its own plot.
name: str
The name in the [executables] section of the configuration file
to use.
analysis_segs: {None, ligo.segments.Segment}
The segment this job encompasses. If None then use the total analysis
time from the workflow.
tags: {None, optional}
Tags to add to the inference executables.
Returns
-------
pycbc.workflow.FileList
A list of result and output files. | [
"Sets",
"up",
"the",
"recovered",
"versus",
"injected",
"parameter",
"plot",
"in",
"the",
"workflow",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/inference_followups.py#L373-L424 |
228,420 | gwastro/pycbc | pycbc/workflow/segment.py | get_science_segments | def get_science_segments(workflow, out_dir, tags=None):
"""
Get the analyzable segments after applying ini specified vetoes.
Parameters
-----------
workflow : Workflow object
Instance of the workflow object
out_dir : path
Location to store output files
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options.
Returns
--------
sci_seg_file : workflow.core.SegFile instance
The segment file combined from all ifos containing the science segments.
sci_segs : Ifo keyed dict of ligo.segments.segmentlist instances
The science segs for each ifo, keyed by ifo
sci_seg_name : str
The name with which science segs are stored in the output XML file.
"""
if tags is None:
tags = []
logging.info('Starting generation of science segments')
make_analysis_dir(out_dir)
start_time = workflow.analysis_time[0]
end_time = workflow.analysis_time[1]
# NOTE: Should this be overrideable in the config file?
sci_seg_name = "SCIENCE"
sci_segs = {}
sci_seg_dict = segments.segmentlistdict()
sci_seg_summ_dict = segments.segmentlistdict()
for ifo in workflow.ifos:
curr_sci_segs, curr_sci_xml, curr_seg_name = get_sci_segs_for_ifo(ifo,
workflow.cp, start_time, end_time, out_dir, tags)
sci_seg_dict[ifo + ':' + sci_seg_name] = curr_sci_segs
sci_segs[ifo] = curr_sci_segs
sci_seg_summ_dict[ifo + ':' + sci_seg_name] = \
curr_sci_xml.seg_summ_dict[ifo + ':' + curr_seg_name]
sci_seg_file = SegFile.from_segment_list_dict(sci_seg_name,
sci_seg_dict, extension='xml',
valid_segment=workflow.analysis_time,
seg_summ_dict=sci_seg_summ_dict,
directory=out_dir, tags=tags)
logging.info('Done generating science segments')
return sci_seg_file, sci_segs, sci_seg_name | python | def get_science_segments(workflow, out_dir, tags=None):
if tags is None:
tags = []
logging.info('Starting generation of science segments')
make_analysis_dir(out_dir)
start_time = workflow.analysis_time[0]
end_time = workflow.analysis_time[1]
# NOTE: Should this be overrideable in the config file?
sci_seg_name = "SCIENCE"
sci_segs = {}
sci_seg_dict = segments.segmentlistdict()
sci_seg_summ_dict = segments.segmentlistdict()
for ifo in workflow.ifos:
curr_sci_segs, curr_sci_xml, curr_seg_name = get_sci_segs_for_ifo(ifo,
workflow.cp, start_time, end_time, out_dir, tags)
sci_seg_dict[ifo + ':' + sci_seg_name] = curr_sci_segs
sci_segs[ifo] = curr_sci_segs
sci_seg_summ_dict[ifo + ':' + sci_seg_name] = \
curr_sci_xml.seg_summ_dict[ifo + ':' + curr_seg_name]
sci_seg_file = SegFile.from_segment_list_dict(sci_seg_name,
sci_seg_dict, extension='xml',
valid_segment=workflow.analysis_time,
seg_summ_dict=sci_seg_summ_dict,
directory=out_dir, tags=tags)
logging.info('Done generating science segments')
return sci_seg_file, sci_segs, sci_seg_name | [
"def",
"get_science_segments",
"(",
"workflow",
",",
"out_dir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"logging",
".",
"info",
"(",
"'Starting generation of science segments'",
")",
"make_analysis_dir",
"(",... | Get the analyzable segments after applying ini specified vetoes.
Parameters
-----------
workflow : Workflow object
Instance of the workflow object
out_dir : path
Location to store output files
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options.
Returns
--------
sci_seg_file : workflow.core.SegFile instance
The segment file combined from all ifos containing the science segments.
sci_segs : Ifo keyed dict of ligo.segments.segmentlist instances
The science segs for each ifo, keyed by ifo
sci_seg_name : str
The name with which science segs are stored in the output XML file. | [
"Get",
"the",
"analyzable",
"segments",
"after",
"applying",
"ini",
"specified",
"vetoes",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L41-L91 |
228,421 | gwastro/pycbc | pycbc/workflow/segment.py | get_files_for_vetoes | def get_files_for_vetoes(workflow, out_dir,
runtime_names=None, in_workflow_names=None, tags=None):
"""
Get the various sets of veto segments that will be used in this analysis.
Parameters
-----------
workflow : Workflow object
Instance of the workflow object
out_dir : path
Location to store output files
runtime_names : list
Veto category groups with these names in the [workflow-segment] section
of the ini file will be generated now.
in_workflow_names : list
Veto category groups with these names in the [workflow-segment] section
of the ini file will be generated in the workflow. If a veto category
appears here and in runtime_names, it will be generated now.
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options.
Returns
--------
veto_seg_files : FileList
List of veto segment files generated
"""
if tags is None:
tags = []
if runtime_names is None:
runtime_names = []
if in_workflow_names is None:
in_workflow_names = []
logging.info('Starting generating veto files for analysis')
make_analysis_dir(out_dir)
start_time = workflow.analysis_time[0]
end_time = workflow.analysis_time[1]
save_veto_definer(workflow.cp, out_dir, tags)
now_cat_sets = []
for name in runtime_names:
cat_sets = parse_cat_ini_opt(workflow.cp.get_opt_tags(
'workflow-segments', name, tags))
now_cat_sets.extend(cat_sets)
now_cats = set()
for cset in now_cat_sets:
now_cats = now_cats.union(cset)
later_cat_sets = []
for name in in_workflow_names:
cat_sets = parse_cat_ini_opt(workflow.cp.get_opt_tags(
'workflow-segments', name, tags))
later_cat_sets.extend(cat_sets)
later_cats = set()
for cset in later_cat_sets:
later_cats = later_cats.union(cset)
# Avoid duplication
later_cats = later_cats - now_cats
veto_gen_job = create_segs_from_cats_job(workflow.cp, out_dir,
workflow.ifo_string, tags=tags)
cat_files = FileList()
for ifo in workflow.ifos:
for category in now_cats:
cat_files.append(get_veto_segs(workflow, ifo,
cat_to_veto_def_cat(category),
start_time, end_time, out_dir,
veto_gen_job, execute_now=True,
tags=tags))
for category in later_cats:
cat_files.append(get_veto_segs(workflow, ifo,
cat_to_veto_def_cat(category),
start_time, end_time, out_dir,
veto_gen_job, tags=tags,
execute_now=False))
logging.info('Done generating veto segments')
return cat_files | python | def get_files_for_vetoes(workflow, out_dir,
runtime_names=None, in_workflow_names=None, tags=None):
if tags is None:
tags = []
if runtime_names is None:
runtime_names = []
if in_workflow_names is None:
in_workflow_names = []
logging.info('Starting generating veto files for analysis')
make_analysis_dir(out_dir)
start_time = workflow.analysis_time[0]
end_time = workflow.analysis_time[1]
save_veto_definer(workflow.cp, out_dir, tags)
now_cat_sets = []
for name in runtime_names:
cat_sets = parse_cat_ini_opt(workflow.cp.get_opt_tags(
'workflow-segments', name, tags))
now_cat_sets.extend(cat_sets)
now_cats = set()
for cset in now_cat_sets:
now_cats = now_cats.union(cset)
later_cat_sets = []
for name in in_workflow_names:
cat_sets = parse_cat_ini_opt(workflow.cp.get_opt_tags(
'workflow-segments', name, tags))
later_cat_sets.extend(cat_sets)
later_cats = set()
for cset in later_cat_sets:
later_cats = later_cats.union(cset)
# Avoid duplication
later_cats = later_cats - now_cats
veto_gen_job = create_segs_from_cats_job(workflow.cp, out_dir,
workflow.ifo_string, tags=tags)
cat_files = FileList()
for ifo in workflow.ifos:
for category in now_cats:
cat_files.append(get_veto_segs(workflow, ifo,
cat_to_veto_def_cat(category),
start_time, end_time, out_dir,
veto_gen_job, execute_now=True,
tags=tags))
for category in later_cats:
cat_files.append(get_veto_segs(workflow, ifo,
cat_to_veto_def_cat(category),
start_time, end_time, out_dir,
veto_gen_job, tags=tags,
execute_now=False))
logging.info('Done generating veto segments')
return cat_files | [
"def",
"get_files_for_vetoes",
"(",
"workflow",
",",
"out_dir",
",",
"runtime_names",
"=",
"None",
",",
"in_workflow_names",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"if",
"runtime_names",
"... | Get the various sets of veto segments that will be used in this analysis.
Parameters
-----------
workflow : Workflow object
Instance of the workflow object
out_dir : path
Location to store output files
runtime_names : list
Veto category groups with these names in the [workflow-segment] section
of the ini file will be generated now.
in_workflow_names : list
Veto category groups with these names in the [workflow-segment] section
of the ini file will be generated in the workflow. If a veto category
appears here and in runtime_names, it will be generated now.
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options.
Returns
--------
veto_seg_files : FileList
List of veto segment files generated | [
"Get",
"the",
"various",
"sets",
"of",
"veto",
"segments",
"that",
"will",
"be",
"used",
"in",
"this",
"analysis",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L93-L174 |
228,422 | gwastro/pycbc | pycbc/workflow/segment.py | get_cumulative_veto_group_files | def get_cumulative_veto_group_files(workflow, option, cat_files,
out_dir, execute_now=True, tags=None):
"""
Get the cumulative veto files that define the different backgrounds
we want to analyze, defined by groups of vetos.
Parameters
-----------
workflow : Workflow object
Instance of the workflow object
option : str
ini file option to use to get the veto groups
cat_files : FileList of SegFiles
The category veto files generated by get_veto_segs
out_dir : path
Location to store output files
execute_now : Boolean
If true outputs are generated at runtime. Else jobs go into the workflow
and are generated then.
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options.
Returns
--------
seg_files : workflow.core.FileList instance
The cumulative segment files for each veto group.
names : list of strings
The segment names for the corresponding seg_file
cat_files : workflow.core.FileList instance
The list of individual category veto files
"""
if tags is None:
tags = []
logging.info("Starting generating vetoes for groups in %s" %(option))
make_analysis_dir(out_dir)
cat_sets = parse_cat_ini_opt(workflow.cp.get_opt_tags('workflow-segments',
option, tags))
cum_seg_files = FileList()
names = []
for cat_set in cat_sets:
segment_name = "CUMULATIVE_CAT_%s" % (''.join(sorted(cat_set)))
logging.info('getting information for %s' % segment_name)
categories = [cat_to_veto_def_cat(c) for c in cat_set]
cum_seg_files += [get_cumulative_segs(workflow, categories, cat_files,
out_dir, execute_now=execute_now,
segment_name=segment_name, tags=tags)]
names.append(segment_name)
logging.info("Done generating vetoes for groups in %s" %(option))
return cum_seg_files, names, cat_files | python | def get_cumulative_veto_group_files(workflow, option, cat_files,
out_dir, execute_now=True, tags=None):
if tags is None:
tags = []
logging.info("Starting generating vetoes for groups in %s" %(option))
make_analysis_dir(out_dir)
cat_sets = parse_cat_ini_opt(workflow.cp.get_opt_tags('workflow-segments',
option, tags))
cum_seg_files = FileList()
names = []
for cat_set in cat_sets:
segment_name = "CUMULATIVE_CAT_%s" % (''.join(sorted(cat_set)))
logging.info('getting information for %s' % segment_name)
categories = [cat_to_veto_def_cat(c) for c in cat_set]
cum_seg_files += [get_cumulative_segs(workflow, categories, cat_files,
out_dir, execute_now=execute_now,
segment_name=segment_name, tags=tags)]
names.append(segment_name)
logging.info("Done generating vetoes for groups in %s" %(option))
return cum_seg_files, names, cat_files | [
"def",
"get_cumulative_veto_group_files",
"(",
"workflow",
",",
"option",
",",
"cat_files",
",",
"out_dir",
",",
"execute_now",
"=",
"True",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"logging",
".",
"info... | Get the cumulative veto files that define the different backgrounds
we want to analyze, defined by groups of vetos.
Parameters
-----------
workflow : Workflow object
Instance of the workflow object
option : str
ini file option to use to get the veto groups
cat_files : FileList of SegFiles
The category veto files generated by get_veto_segs
out_dir : path
Location to store output files
execute_now : Boolean
If true outputs are generated at runtime. Else jobs go into the workflow
and are generated then.
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options.
Returns
--------
seg_files : workflow.core.FileList instance
The cumulative segment files for each veto group.
names : list of strings
The segment names for the corresponding seg_file
cat_files : workflow.core.FileList instance
The list of individual category veto files | [
"Get",
"the",
"cumulative",
"veto",
"files",
"that",
"define",
"the",
"different",
"backgrounds",
"we",
"want",
"to",
"analyze",
"defined",
"by",
"groups",
"of",
"vetos",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L286-L340 |
228,423 | gwastro/pycbc | pycbc/workflow/segment.py | get_sci_segs_for_ifo | def get_sci_segs_for_ifo(ifo, cp, start_time, end_time, out_dir, tags=None):
"""
Obtain science segments for the selected ifo
Parameters
-----------
ifo : string
The string describing the ifo to obtain science times for.
start_time : gps time (either int/LIGOTimeGPS)
The time at which to begin searching for segments.
end_time : gps time (either int/LIGOTimeGPS)
The time at which to stop searching for segments.
out_dir : path
The directory in which output will be stored.
tag : string, optional (default=None)
Use this to specify a tag. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
Returns
--------
sci_segs : ligo.segments.segmentlist
The segmentlist generated by this call
sci_xml_file : pycbc.workflow.core.SegFile
The workflow File object corresponding to this science segments file.
out_sci_seg_name : string
The name of the output segment list in the output XML file.
"""
if tags is None:
tags = []
seg_valid_seg = segments.segment([start_time,end_time])
sci_seg_name = cp.get_opt_tags(
"workflow-segments", "segments-%s-science-name" %(ifo.lower()), tags)
sci_seg_url = cp.get_opt_tags(
"workflow-segments", "segments-database-url", tags)
# NOTE: ligolw_segment_query returns slightly strange output. The output
# segment list is put in with name "RESULT". So this is hardcoded here
out_sci_seg_name = "RESULT"
if tags:
sci_xml_file_path = os.path.join(
out_dir, "%s-SCIENCE_SEGMENTS_%s.xml" \
%(ifo.upper(), '_'.join(tags)))
tag_list=tags + ['SCIENCE']
else:
sci_xml_file_path = os.path.join(
out_dir, "%s-SCIENCE_SEGMENTS.xml" %(ifo.upper()) )
tag_list = ['SCIENCE']
if file_needs_generating(sci_xml_file_path, cp, tags=tags):
seg_find_call = [ resolve_url(cp.get("executables","segment_query"),
permissions=stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR),
"--query-segments",
"--segment-url", sci_seg_url,
"--gps-start-time", str(start_time),
"--gps-end-time", str(end_time),
"--include-segments", sci_seg_name,
"--output-file", sci_xml_file_path ]
make_external_call(seg_find_call, out_dir=os.path.join(out_dir,'logs'),
out_basename='%s-science-call' %(ifo.lower()) )
# Yes its yucky to generate a file and then read it back in.
sci_xml_file_path = os.path.abspath(sci_xml_file_path)
sci_xml_file = SegFile.from_segment_xml(sci_xml_file_path, tags=tag_list,
valid_segment=seg_valid_seg)
# NOTE: ligolw_segment_query returns slightly strange output. The output
# segment_summary output does not use RESULT. Therefore move the
# segment_summary across.
sci_xml_file.seg_summ_dict[ifo.upper() + ":" + out_sci_seg_name] = \
sci_xml_file.seg_summ_dict[':'.join(sci_seg_name.split(':')[0:2])]
sci_segs = sci_xml_file.return_union_seglist()
return sci_segs, sci_xml_file, out_sci_seg_name | python | def get_sci_segs_for_ifo(ifo, cp, start_time, end_time, out_dir, tags=None):
if tags is None:
tags = []
seg_valid_seg = segments.segment([start_time,end_time])
sci_seg_name = cp.get_opt_tags(
"workflow-segments", "segments-%s-science-name" %(ifo.lower()), tags)
sci_seg_url = cp.get_opt_tags(
"workflow-segments", "segments-database-url", tags)
# NOTE: ligolw_segment_query returns slightly strange output. The output
# segment list is put in with name "RESULT". So this is hardcoded here
out_sci_seg_name = "RESULT"
if tags:
sci_xml_file_path = os.path.join(
out_dir, "%s-SCIENCE_SEGMENTS_%s.xml" \
%(ifo.upper(), '_'.join(tags)))
tag_list=tags + ['SCIENCE']
else:
sci_xml_file_path = os.path.join(
out_dir, "%s-SCIENCE_SEGMENTS.xml" %(ifo.upper()) )
tag_list = ['SCIENCE']
if file_needs_generating(sci_xml_file_path, cp, tags=tags):
seg_find_call = [ resolve_url(cp.get("executables","segment_query"),
permissions=stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR),
"--query-segments",
"--segment-url", sci_seg_url,
"--gps-start-time", str(start_time),
"--gps-end-time", str(end_time),
"--include-segments", sci_seg_name,
"--output-file", sci_xml_file_path ]
make_external_call(seg_find_call, out_dir=os.path.join(out_dir,'logs'),
out_basename='%s-science-call' %(ifo.lower()) )
# Yes its yucky to generate a file and then read it back in.
sci_xml_file_path = os.path.abspath(sci_xml_file_path)
sci_xml_file = SegFile.from_segment_xml(sci_xml_file_path, tags=tag_list,
valid_segment=seg_valid_seg)
# NOTE: ligolw_segment_query returns slightly strange output. The output
# segment_summary output does not use RESULT. Therefore move the
# segment_summary across.
sci_xml_file.seg_summ_dict[ifo.upper() + ":" + out_sci_seg_name] = \
sci_xml_file.seg_summ_dict[':'.join(sci_seg_name.split(':')[0:2])]
sci_segs = sci_xml_file.return_union_seglist()
return sci_segs, sci_xml_file, out_sci_seg_name | [
"def",
"get_sci_segs_for_ifo",
"(",
"ifo",
",",
"cp",
",",
"start_time",
",",
"end_time",
",",
"out_dir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"seg_valid_seg",
"=",
"segments",
".",
"segment",
"(",... | Obtain science segments for the selected ifo
Parameters
-----------
ifo : string
The string describing the ifo to obtain science times for.
start_time : gps time (either int/LIGOTimeGPS)
The time at which to begin searching for segments.
end_time : gps time (either int/LIGOTimeGPS)
The time at which to stop searching for segments.
out_dir : path
The directory in which output will be stored.
tag : string, optional (default=None)
Use this to specify a tag. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
Returns
--------
sci_segs : ligo.segments.segmentlist
The segmentlist generated by this call
sci_xml_file : pycbc.workflow.core.SegFile
The workflow File object corresponding to this science segments file.
out_sci_seg_name : string
The name of the output segment list in the output XML file. | [
"Obtain",
"science",
"segments",
"for",
"the",
"selected",
"ifo"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L627-L702 |
228,424 | gwastro/pycbc | pycbc/workflow/segment.py | get_veto_segs | def get_veto_segs(workflow, ifo, category, start_time, end_time, out_dir,
veto_gen_job, tags=None, execute_now=False):
"""
Obtain veto segments for the selected ifo and veto category and add the job
to generate this to the workflow.
Parameters
-----------
workflow: pycbc.workflow.core.Workflow
An instance of the Workflow class that manages the workflow.
ifo : string
The string describing the ifo to generate vetoes for.
category : int
The veto category to generate vetoes for.
start_time : gps time (either int/LIGOTimeGPS)
The time at which to begin searching for segments.
end_time : gps time (either int/LIGOTimeGPS)
The time at which to stop searching for segments.
out_dir : path
The directory in which output will be stored.
vetoGenJob : Job
The veto generation Job class that will be used to create the Node.
tag : string, optional (default=None)
Use this to specify a tag. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
FIXME: Filenames may not be unique with current codes!
execute_now : boolean, optional
If true, jobs are executed immediately. If false, they are added to the
workflow to be run later.
Returns
--------
veto_def_file : pycbc.workflow.core.SegFile
The workflow File object corresponding to this DQ veto file.
"""
if tags is None:
tags = []
seg_valid_seg = segments.segment([start_time,end_time])
# FIXME: This job needs an internet connection and X509_USER_PROXY
# For internet connection, it may need a headnode (ie universe local)
# For X509_USER_PROXY, I don't know what pegasus is doing
node = Node(veto_gen_job)
node.add_opt('--veto-categories', str(category))
node.add_opt('--ifo-list', ifo)
node.add_opt('--gps-start-time', str(start_time))
node.add_opt('--gps-end-time', str(end_time))
if tags:
veto_xml_file_name = "%s-VETOTIME_CAT%d_%s-%d-%d.xml" \
%(ifo, category, '_'.join(tags), start_time,
end_time-start_time)
else:
veto_xml_file_name = "%s-VETOTIME_CAT%d-%d-%d.xml" \
%(ifo, category, start_time, end_time-start_time)
veto_xml_file_path = os.path.abspath(os.path.join(out_dir,
veto_xml_file_name))
curr_url = urlparse.urlunparse(['file', 'localhost',
veto_xml_file_path, None, None, None])
if tags:
curr_tags = tags + ['VETO_CAT%d' %(category)]
else:
curr_tags = ['VETO_CAT%d' %(category)]
if file_needs_generating(veto_xml_file_path, workflow.cp, tags=tags):
if execute_now:
workflow.execute_node(node, verbatim_exe = True)
veto_xml_file = SegFile.from_segment_xml(veto_xml_file_path,
tags=curr_tags,
valid_segment=seg_valid_seg)
else:
veto_xml_file = SegFile(ifo, 'SEGMENTS', seg_valid_seg,
file_url=curr_url, tags=curr_tags)
node._add_output(veto_xml_file)
workflow.add_node(node)
else:
node.executed = True
for fil in node._outputs:
fil.node = None
veto_xml_file = SegFile.from_segment_xml(veto_xml_file_path,
tags=curr_tags,
valid_segment=seg_valid_seg)
return veto_xml_file | python | def get_veto_segs(workflow, ifo, category, start_time, end_time, out_dir,
veto_gen_job, tags=None, execute_now=False):
if tags is None:
tags = []
seg_valid_seg = segments.segment([start_time,end_time])
# FIXME: This job needs an internet connection and X509_USER_PROXY
# For internet connection, it may need a headnode (ie universe local)
# For X509_USER_PROXY, I don't know what pegasus is doing
node = Node(veto_gen_job)
node.add_opt('--veto-categories', str(category))
node.add_opt('--ifo-list', ifo)
node.add_opt('--gps-start-time', str(start_time))
node.add_opt('--gps-end-time', str(end_time))
if tags:
veto_xml_file_name = "%s-VETOTIME_CAT%d_%s-%d-%d.xml" \
%(ifo, category, '_'.join(tags), start_time,
end_time-start_time)
else:
veto_xml_file_name = "%s-VETOTIME_CAT%d-%d-%d.xml" \
%(ifo, category, start_time, end_time-start_time)
veto_xml_file_path = os.path.abspath(os.path.join(out_dir,
veto_xml_file_name))
curr_url = urlparse.urlunparse(['file', 'localhost',
veto_xml_file_path, None, None, None])
if tags:
curr_tags = tags + ['VETO_CAT%d' %(category)]
else:
curr_tags = ['VETO_CAT%d' %(category)]
if file_needs_generating(veto_xml_file_path, workflow.cp, tags=tags):
if execute_now:
workflow.execute_node(node, verbatim_exe = True)
veto_xml_file = SegFile.from_segment_xml(veto_xml_file_path,
tags=curr_tags,
valid_segment=seg_valid_seg)
else:
veto_xml_file = SegFile(ifo, 'SEGMENTS', seg_valid_seg,
file_url=curr_url, tags=curr_tags)
node._add_output(veto_xml_file)
workflow.add_node(node)
else:
node.executed = True
for fil in node._outputs:
fil.node = None
veto_xml_file = SegFile.from_segment_xml(veto_xml_file_path,
tags=curr_tags,
valid_segment=seg_valid_seg)
return veto_xml_file | [
"def",
"get_veto_segs",
"(",
"workflow",
",",
"ifo",
",",
"category",
",",
"start_time",
",",
"end_time",
",",
"out_dir",
",",
"veto_gen_job",
",",
"tags",
"=",
"None",
",",
"execute_now",
"=",
"False",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
... | Obtain veto segments for the selected ifo and veto category and add the job
to generate this to the workflow.
Parameters
-----------
workflow: pycbc.workflow.core.Workflow
An instance of the Workflow class that manages the workflow.
ifo : string
The string describing the ifo to generate vetoes for.
category : int
The veto category to generate vetoes for.
start_time : gps time (either int/LIGOTimeGPS)
The time at which to begin searching for segments.
end_time : gps time (either int/LIGOTimeGPS)
The time at which to stop searching for segments.
out_dir : path
The directory in which output will be stored.
vetoGenJob : Job
The veto generation Job class that will be used to create the Node.
tag : string, optional (default=None)
Use this to specify a tag. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
FIXME: Filenames may not be unique with current codes!
execute_now : boolean, optional
If true, jobs are executed immediately. If false, they are added to the
workflow to be run later.
Returns
--------
veto_def_file : pycbc.workflow.core.SegFile
The workflow File object corresponding to this DQ veto file. | [
"Obtain",
"veto",
"segments",
"for",
"the",
"selected",
"ifo",
"and",
"veto",
"category",
"and",
"add",
"the",
"job",
"to",
"generate",
"this",
"to",
"the",
"workflow",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L704-L787 |
228,425 | gwastro/pycbc | pycbc/workflow/segment.py | create_segs_from_cats_job | def create_segs_from_cats_job(cp, out_dir, ifo_string, tags=None):
"""
This function creates the CondorDAGJob that will be used to run
ligolw_segments_from_cats as part of the workflow
Parameters
-----------
cp : pycbc.workflow.configuration.WorkflowConfigParser
The in-memory representation of the configuration (.ini) files
out_dir : path
Directory in which to put output files
ifo_string : string
String containing all active ifos, ie. "H1L1V1"
tag : list of strings, optional (default=None)
Use this to specify a tag(s). This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
FIXME: Filenames may not be unique with current codes!
Returns
--------
job : Job instance
The Job instance that will run segments_from_cats jobs
"""
if tags is None:
tags = []
seg_server_url = cp.get_opt_tags("workflow-segments",
"segments-database-url", tags)
veto_def_file = cp.get_opt_tags("workflow-segments",
"segments-veto-definer-file", tags)
job = Executable(cp, 'segments_from_cats', universe='local',
ifos=ifo_string, out_dir=out_dir, tags=tags)
job.add_opt('--separate-categories')
job.add_opt('--segment-url', seg_server_url)
job.add_opt('--veto-file', veto_def_file)
# FIXME: Would like the proxy in the Workflow instance
# FIXME: Explore using the x509 condor commands
# If the user has a proxy set in the environment, add it to the job
return job | python | def create_segs_from_cats_job(cp, out_dir, ifo_string, tags=None):
if tags is None:
tags = []
seg_server_url = cp.get_opt_tags("workflow-segments",
"segments-database-url", tags)
veto_def_file = cp.get_opt_tags("workflow-segments",
"segments-veto-definer-file", tags)
job = Executable(cp, 'segments_from_cats', universe='local',
ifos=ifo_string, out_dir=out_dir, tags=tags)
job.add_opt('--separate-categories')
job.add_opt('--segment-url', seg_server_url)
job.add_opt('--veto-file', veto_def_file)
# FIXME: Would like the proxy in the Workflow instance
# FIXME: Explore using the x509 condor commands
# If the user has a proxy set in the environment, add it to the job
return job | [
"def",
"create_segs_from_cats_job",
"(",
"cp",
",",
"out_dir",
",",
"ifo_string",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"seg_server_url",
"=",
"cp",
".",
"get_opt_tags",
"(",
"\"workflow-segments\"",
",... | This function creates the CondorDAGJob that will be used to run
ligolw_segments_from_cats as part of the workflow
Parameters
-----------
cp : pycbc.workflow.configuration.WorkflowConfigParser
The in-memory representation of the configuration (.ini) files
out_dir : path
Directory in which to put output files
ifo_string : string
String containing all active ifos, ie. "H1L1V1"
tag : list of strings, optional (default=None)
Use this to specify a tag(s). This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
FIXME: Filenames may not be unique with current codes!
Returns
--------
job : Job instance
The Job instance that will run segments_from_cats jobs | [
"This",
"function",
"creates",
"the",
"CondorDAGJob",
"that",
"will",
"be",
"used",
"to",
"run",
"ligolw_segments_from_cats",
"as",
"part",
"of",
"the",
"workflow"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L789-L832 |
228,426 | gwastro/pycbc | pycbc/workflow/segment.py | get_cumulative_segs | def get_cumulative_segs(workflow, categories, seg_files_list, out_dir,
tags=None, execute_now=False, segment_name=None):
"""
Function to generate one of the cumulative, multi-detector segment files
as part of the workflow.
Parameters
-----------
workflow: pycbc.workflow.core.Workflow
An instance of the Workflow class that manages the workflow.
categories : int
The veto categories to include in this cumulative veto.
seg_files_list : Listionary of SegFiles
The list of segment files to be used as input for combining.
out_dir : path
The directory to write output to.
tags : list of strings, optional
A list of strings that is used to identify this job
execute_now : boolean, optional
If true, jobs are executed immediately. If false, they are added to the
workflow to be run later.
segment_name : str
The name of the combined, cumulative segments in the output file.
"""
if tags is None:
tags = []
add_inputs = FileList([])
valid_segment = workflow.analysis_time
if segment_name is None:
segment_name = 'VETO_CAT%d_CUMULATIVE' % (categories[-1])
cp = workflow.cp
# calculate the cumulative veto files for a given ifo
for ifo in workflow.ifos:
cum_job = LigoLWCombineSegsExecutable(cp, 'ligolw_combine_segments',
out_dir=out_dir, tags=[segment_name]+tags, ifos=ifo)
inputs = []
files = seg_files_list.find_output_with_ifo(ifo)
for category in categories:
file_list = files.find_output_with_tag('VETO_CAT%d' %(category))
inputs+=file_list
cum_node = cum_job.create_node(valid_segment, inputs, segment_name)
if file_needs_generating(cum_node.output_files[0].cache_entry.path,
workflow.cp, tags=tags):
if execute_now:
workflow.execute_node(cum_node)
else:
workflow.add_node(cum_node)
else:
cum_node.executed = True
for fil in cum_node._outputs:
fil.node = None
fil.PFN(urlparse.urljoin('file:',
urllib.pathname2url(fil.storage_path)),
site='local')
add_inputs += cum_node.output_files
# add cumulative files for each ifo together
name = '%s_VETO_SEGMENTS' %(segment_name)
outfile = File(workflow.ifos, name, workflow.analysis_time,
directory=out_dir, extension='xml',
tags=[segment_name] + tags)
add_job = LigolwAddExecutable(cp, 'llwadd', ifos=ifo, out_dir=out_dir,
tags=tags)
add_node = add_job.create_node(valid_segment, add_inputs, output=outfile)
if file_needs_generating(add_node.output_files[0].cache_entry.path,
workflow.cp, tags=tags):
if execute_now:
workflow.execute_node(add_node)
else:
workflow.add_node(add_node)
else:
add_node.executed = True
for fil in add_node._outputs:
fil.node = None
fil.PFN(urlparse.urljoin('file:',
urllib.pathname2url(fil.storage_path)),
site='local')
return outfile | python | def get_cumulative_segs(workflow, categories, seg_files_list, out_dir,
tags=None, execute_now=False, segment_name=None):
if tags is None:
tags = []
add_inputs = FileList([])
valid_segment = workflow.analysis_time
if segment_name is None:
segment_name = 'VETO_CAT%d_CUMULATIVE' % (categories[-1])
cp = workflow.cp
# calculate the cumulative veto files for a given ifo
for ifo in workflow.ifos:
cum_job = LigoLWCombineSegsExecutable(cp, 'ligolw_combine_segments',
out_dir=out_dir, tags=[segment_name]+tags, ifos=ifo)
inputs = []
files = seg_files_list.find_output_with_ifo(ifo)
for category in categories:
file_list = files.find_output_with_tag('VETO_CAT%d' %(category))
inputs+=file_list
cum_node = cum_job.create_node(valid_segment, inputs, segment_name)
if file_needs_generating(cum_node.output_files[0].cache_entry.path,
workflow.cp, tags=tags):
if execute_now:
workflow.execute_node(cum_node)
else:
workflow.add_node(cum_node)
else:
cum_node.executed = True
for fil in cum_node._outputs:
fil.node = None
fil.PFN(urlparse.urljoin('file:',
urllib.pathname2url(fil.storage_path)),
site='local')
add_inputs += cum_node.output_files
# add cumulative files for each ifo together
name = '%s_VETO_SEGMENTS' %(segment_name)
outfile = File(workflow.ifos, name, workflow.analysis_time,
directory=out_dir, extension='xml',
tags=[segment_name] + tags)
add_job = LigolwAddExecutable(cp, 'llwadd', ifos=ifo, out_dir=out_dir,
tags=tags)
add_node = add_job.create_node(valid_segment, add_inputs, output=outfile)
if file_needs_generating(add_node.output_files[0].cache_entry.path,
workflow.cp, tags=tags):
if execute_now:
workflow.execute_node(add_node)
else:
workflow.add_node(add_node)
else:
add_node.executed = True
for fil in add_node._outputs:
fil.node = None
fil.PFN(urlparse.urljoin('file:',
urllib.pathname2url(fil.storage_path)),
site='local')
return outfile | [
"def",
"get_cumulative_segs",
"(",
"workflow",
",",
"categories",
",",
"seg_files_list",
",",
"out_dir",
",",
"tags",
"=",
"None",
",",
"execute_now",
"=",
"False",
",",
"segment_name",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
... | Function to generate one of the cumulative, multi-detector segment files
as part of the workflow.
Parameters
-----------
workflow: pycbc.workflow.core.Workflow
An instance of the Workflow class that manages the workflow.
categories : int
The veto categories to include in this cumulative veto.
seg_files_list : Listionary of SegFiles
The list of segment files to be used as input for combining.
out_dir : path
The directory to write output to.
tags : list of strings, optional
A list of strings that is used to identify this job
execute_now : boolean, optional
If true, jobs are executed immediately. If false, they are added to the
workflow to be run later.
segment_name : str
The name of the combined, cumulative segments in the output file. | [
"Function",
"to",
"generate",
"one",
"of",
"the",
"cumulative",
"multi",
"-",
"detector",
"segment",
"files",
"as",
"part",
"of",
"the",
"workflow",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L834-L912 |
228,427 | gwastro/pycbc | pycbc/workflow/segment.py | add_cumulative_files | def add_cumulative_files(workflow, output_file, input_files, out_dir,
execute_now=False, tags=None):
"""
Function to combine a set of segment files into a single one. This function
will not merge the segment lists but keep each separate.
Parameters
-----------
workflow: pycbc.workflow.core.Workflow
An instance of the Workflow class that manages the workflow.
output_file: pycbc.workflow.core.File
The output file object
input_files: pycbc.workflow.core.FileList
This list of input segment files
out_dir : path
The directory to write output to.
execute_now : boolean, optional
If true, jobs are executed immediately. If false, they are added to the
workflow to be run later.
tags : list of strings, optional
A list of strings that is used to identify this job
"""
if tags is None:
tags = []
llwadd_job = LigolwAddExecutable(workflow.cp, 'llwadd',
ifo=output_file.ifo_list, out_dir=out_dir, tags=tags)
add_node = llwadd_job.create_node(output_file.segment, input_files,
output=output_file)
if file_needs_generating(add_node.output_files[0].cache_entry.path,
workflow.cp, tags=tags):
if execute_now:
workflow.execute_node(add_node)
else:
workflow.add_node(add_node)
else:
add_node.executed = True
for fil in add_node._outputs:
fil.node = None
fil.PFN(urlparse.urljoin('file:',
urllib.pathname2url(fil.storage_path)),
site='local')
return add_node.output_files[0] | python | def add_cumulative_files(workflow, output_file, input_files, out_dir,
execute_now=False, tags=None):
if tags is None:
tags = []
llwadd_job = LigolwAddExecutable(workflow.cp, 'llwadd',
ifo=output_file.ifo_list, out_dir=out_dir, tags=tags)
add_node = llwadd_job.create_node(output_file.segment, input_files,
output=output_file)
if file_needs_generating(add_node.output_files[0].cache_entry.path,
workflow.cp, tags=tags):
if execute_now:
workflow.execute_node(add_node)
else:
workflow.add_node(add_node)
else:
add_node.executed = True
for fil in add_node._outputs:
fil.node = None
fil.PFN(urlparse.urljoin('file:',
urllib.pathname2url(fil.storage_path)),
site='local')
return add_node.output_files[0] | [
"def",
"add_cumulative_files",
"(",
"workflow",
",",
"output_file",
",",
"input_files",
",",
"out_dir",
",",
"execute_now",
"=",
"False",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"llwadd_job",
"=",
"Ligo... | Function to combine a set of segment files into a single one. This function
will not merge the segment lists but keep each separate.
Parameters
-----------
workflow: pycbc.workflow.core.Workflow
An instance of the Workflow class that manages the workflow.
output_file: pycbc.workflow.core.File
The output file object
input_files: pycbc.workflow.core.FileList
This list of input segment files
out_dir : path
The directory to write output to.
execute_now : boolean, optional
If true, jobs are executed immediately. If false, they are added to the
workflow to be run later.
tags : list of strings, optional
A list of strings that is used to identify this job | [
"Function",
"to",
"combine",
"a",
"set",
"of",
"segment",
"files",
"into",
"a",
"single",
"one",
".",
"This",
"function",
"will",
"not",
"merge",
"the",
"segment",
"lists",
"but",
"keep",
"each",
"separate",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L914-L955 |
228,428 | gwastro/pycbc | pycbc/workflow/segment.py | find_playground_segments | def find_playground_segments(segs):
'''Finds playground time in a list of segments.
Playground segments include the first 600s of every 6370s stride starting
at GPS time 729273613.
Parameters
----------
segs : segmentfilelist
A segmentfilelist to find playground segments.
Returns
-------
outlist : segmentfilelist
A segmentfilelist with all playground segments during the input
segmentfilelist (ie. segs).
'''
# initializations
start_s2 = 729273613
playground_stride = 6370
playground_length = 600
outlist = segments.segmentlist()
# loop over segments
for seg in segs:
start = seg[0]
end = seg[1]
# the first playground segment whose end is after the start of seg
playground_start = start_s2 + playground_stride * ( 1 + \
int(start-start_s2-playground_length) / playground_stride)
while playground_start < end:
# find start of playground segment
if playground_start > start:
ostart = playground_start
else:
ostart = start
playground_end = playground_start + playground_length
# find end of playground segment
if playground_end < end:
oend = playground_end
else:
oend = end
# append segment
x = segments.segment(ostart, oend)
outlist.append(x)
# increment
playground_start = playground_start + playground_stride
return outlist | python | def find_playground_segments(segs):
'''Finds playground time in a list of segments.
Playground segments include the first 600s of every 6370s stride starting
at GPS time 729273613.
Parameters
----------
segs : segmentfilelist
A segmentfilelist to find playground segments.
Returns
-------
outlist : segmentfilelist
A segmentfilelist with all playground segments during the input
segmentfilelist (ie. segs).
'''
# initializations
start_s2 = 729273613
playground_stride = 6370
playground_length = 600
outlist = segments.segmentlist()
# loop over segments
for seg in segs:
start = seg[0]
end = seg[1]
# the first playground segment whose end is after the start of seg
playground_start = start_s2 + playground_stride * ( 1 + \
int(start-start_s2-playground_length) / playground_stride)
while playground_start < end:
# find start of playground segment
if playground_start > start:
ostart = playground_start
else:
ostart = start
playground_end = playground_start + playground_length
# find end of playground segment
if playground_end < end:
oend = playground_end
else:
oend = end
# append segment
x = segments.segment(ostart, oend)
outlist.append(x)
# increment
playground_start = playground_start + playground_stride
return outlist | [
"def",
"find_playground_segments",
"(",
"segs",
")",
":",
"# initializations",
"start_s2",
"=",
"729273613",
"playground_stride",
"=",
"6370",
"playground_length",
"=",
"600",
"outlist",
"=",
"segments",
".",
"segmentlist",
"(",
")",
"# loop over segments",
"for",
"... | Finds playground time in a list of segments.
Playground segments include the first 600s of every 6370s stride starting
at GPS time 729273613.
Parameters
----------
segs : segmentfilelist
A segmentfilelist to find playground segments.
Returns
-------
outlist : segmentfilelist
A segmentfilelist with all playground segments during the input
segmentfilelist (ie. segs). | [
"Finds",
"playground",
"time",
"in",
"a",
"list",
"of",
"segments",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L957-L1012 |
228,429 | gwastro/pycbc | pycbc/workflow/segment.py | save_veto_definer | def save_veto_definer(cp, out_dir, tags=None):
""" Retrieve the veto definer file and save it locally
Parameters
-----------
cp : ConfigParser instance
out_dir : path
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options.
"""
if tags is None:
tags = []
make_analysis_dir(out_dir)
veto_def_url = cp.get_opt_tags("workflow-segments",
"segments-veto-definer-url", tags)
veto_def_base_name = os.path.basename(veto_def_url)
veto_def_new_path = os.path.abspath(os.path.join(out_dir,
veto_def_base_name))
# Don't need to do this if already done
resolve_url(veto_def_url,out_dir)
# and update location
cp.set("workflow-segments", "segments-veto-definer-file", veto_def_new_path)
return veto_def_new_path | python | def save_veto_definer(cp, out_dir, tags=None):
if tags is None:
tags = []
make_analysis_dir(out_dir)
veto_def_url = cp.get_opt_tags("workflow-segments",
"segments-veto-definer-url", tags)
veto_def_base_name = os.path.basename(veto_def_url)
veto_def_new_path = os.path.abspath(os.path.join(out_dir,
veto_def_base_name))
# Don't need to do this if already done
resolve_url(veto_def_url,out_dir)
# and update location
cp.set("workflow-segments", "segments-veto-definer-file", veto_def_new_path)
return veto_def_new_path | [
"def",
"save_veto_definer",
"(",
"cp",
",",
"out_dir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"make_analysis_dir",
"(",
"out_dir",
")",
"veto_def_url",
"=",
"cp",
".",
"get_opt_tags",
"(",
"\"workflow-... | Retrieve the veto definer file and save it locally
Parameters
-----------
cp : ConfigParser instance
out_dir : path
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options. | [
"Retrieve",
"the",
"veto",
"definer",
"file",
"and",
"save",
"it",
"locally"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L1261-L1285 |
228,430 | gwastro/pycbc | pycbc/workflow/segment.py | parse_cat_ini_opt | def parse_cat_ini_opt(cat_str):
""" Parse a cat str from the ini file into a list of sets """
if cat_str == "":
return []
cat_groups = cat_str.split(',')
cat_sets = []
for group in cat_groups:
group = group.strip()
cat_sets += [set(c for c in group)]
return cat_sets | python | def parse_cat_ini_opt(cat_str):
if cat_str == "":
return []
cat_groups = cat_str.split(',')
cat_sets = []
for group in cat_groups:
group = group.strip()
cat_sets += [set(c for c in group)]
return cat_sets | [
"def",
"parse_cat_ini_opt",
"(",
"cat_str",
")",
":",
"if",
"cat_str",
"==",
"\"\"",
":",
"return",
"[",
"]",
"cat_groups",
"=",
"cat_str",
".",
"split",
"(",
"','",
")",
"cat_sets",
"=",
"[",
"]",
"for",
"group",
"in",
"cat_groups",
":",
"group",
"=",... | Parse a cat str from the ini file into a list of sets | [
"Parse",
"a",
"cat",
"str",
"from",
"the",
"ini",
"file",
"into",
"a",
"list",
"of",
"sets"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L1287-L1297 |
228,431 | gwastro/pycbc | pycbc/workflow/segment.py | file_needs_generating | def file_needs_generating(file_path, cp, tags=None):
"""
This job tests the file location and determines if the file should be
generated now or if an error should be raised. This uses the
generate_segment_files variable, global to this module, which is described
above and in the documentation.
Parameters
-----------
file_path : path
Location of file to check
cp : ConfigParser
The associated ConfigParser from which the
segments-generate-segment-files variable is returned.
It is recommended for most applications to use the default option by
leaving segments-generate-segment-files blank, which will regenerate
all segment files at runtime. Only use this facility if you need it.
Choices are
* 'always' : DEFAULT: All files will be generated even if they already exist.
* 'if_not_present': Files will be generated if they do not already exist. Pre-existing files will be read in and used.
* 'error_on_duplicate': Files will be generated if they do not already exist. Pre-existing files will raise a failure.
* 'never': Pre-existing files will be read in and used. If no file exists the code will fail.
Returns
--------
int
1 = Generate the file. 0 = File already exists, use it. Other cases
will raise an error.
"""
if tags is None:
tags = []
if cp.has_option_tags("workflow-segments",
"segments-generate-segment-files", tags):
value = cp.get_opt_tags("workflow-segments",
"segments-generate-segment-files", tags)
generate_segment_files = value
else:
generate_segment_files = 'always'
# Does the file exist
if os.path.isfile(file_path):
if generate_segment_files in ['if_not_present', 'never']:
return 0
elif generate_segment_files == 'always':
err_msg = "File %s already exists. " %(file_path,)
err_msg += "Regenerating and overwriting."
logging.warn(err_msg)
return 1
elif generate_segment_files == 'error_on_duplicate':
err_msg = "File %s already exists. " %(file_path,)
err_msg += "Refusing to overwrite file and exiting."
raise ValueError(err_msg)
else:
err_msg = 'Global variable generate_segment_files must be one of '
err_msg += '"always", "if_not_present", "error_on_duplicate", '
err_msg += '"never". Got %s.' %(generate_segment_files,)
raise ValueError(err_msg)
else:
if generate_segment_files in ['always', 'if_not_present',
'error_on_duplicate']:
return 1
elif generate_segment_files == 'never':
err_msg = 'File %s does not exist. ' %(file_path,)
raise ValueError(err_msg)
else:
err_msg = 'Global variable generate_segment_files must be one of '
err_msg += '"always", "if_not_present", "error_on_duplicate", '
err_msg += '"never". Got %s.' %(generate_segment_files,)
raise ValueError(err_msg) | python | def file_needs_generating(file_path, cp, tags=None):
if tags is None:
tags = []
if cp.has_option_tags("workflow-segments",
"segments-generate-segment-files", tags):
value = cp.get_opt_tags("workflow-segments",
"segments-generate-segment-files", tags)
generate_segment_files = value
else:
generate_segment_files = 'always'
# Does the file exist
if os.path.isfile(file_path):
if generate_segment_files in ['if_not_present', 'never']:
return 0
elif generate_segment_files == 'always':
err_msg = "File %s already exists. " %(file_path,)
err_msg += "Regenerating and overwriting."
logging.warn(err_msg)
return 1
elif generate_segment_files == 'error_on_duplicate':
err_msg = "File %s already exists. " %(file_path,)
err_msg += "Refusing to overwrite file and exiting."
raise ValueError(err_msg)
else:
err_msg = 'Global variable generate_segment_files must be one of '
err_msg += '"always", "if_not_present", "error_on_duplicate", '
err_msg += '"never". Got %s.' %(generate_segment_files,)
raise ValueError(err_msg)
else:
if generate_segment_files in ['always', 'if_not_present',
'error_on_duplicate']:
return 1
elif generate_segment_files == 'never':
err_msg = 'File %s does not exist. ' %(file_path,)
raise ValueError(err_msg)
else:
err_msg = 'Global variable generate_segment_files must be one of '
err_msg += '"always", "if_not_present", "error_on_duplicate", '
err_msg += '"never". Got %s.' %(generate_segment_files,)
raise ValueError(err_msg) | [
"def",
"file_needs_generating",
"(",
"file_path",
",",
"cp",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"if",
"cp",
".",
"has_option_tags",
"(",
"\"workflow-segments\"",
",",
"\"segments-generate-segment-files\"... | This job tests the file location and determines if the file should be
generated now or if an error should be raised. This uses the
generate_segment_files variable, global to this module, which is described
above and in the documentation.
Parameters
-----------
file_path : path
Location of file to check
cp : ConfigParser
The associated ConfigParser from which the
segments-generate-segment-files variable is returned.
It is recommended for most applications to use the default option by
leaving segments-generate-segment-files blank, which will regenerate
all segment files at runtime. Only use this facility if you need it.
Choices are
* 'always' : DEFAULT: All files will be generated even if they already exist.
* 'if_not_present': Files will be generated if they do not already exist. Pre-existing files will be read in and used.
* 'error_on_duplicate': Files will be generated if they do not already exist. Pre-existing files will raise a failure.
* 'never': Pre-existing files will be read in and used. If no file exists the code will fail.
Returns
--------
int
1 = Generate the file. 0 = File already exists, use it. Other cases
will raise an error. | [
"This",
"job",
"tests",
"the",
"file",
"location",
"and",
"determines",
"if",
"the",
"file",
"should",
"be",
"generated",
"now",
"or",
"if",
"an",
"error",
"should",
"be",
"raised",
".",
"This",
"uses",
"the",
"generate_segment_files",
"variable",
"global",
... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L1325-L1393 |
228,432 | gwastro/pycbc | pycbc/workflow/segment.py | get_segments_file | def get_segments_file(workflow, name, option_name, out_dir):
"""Get cumulative segments from option name syntax for each ifo.
Use syntax of configparser string to define the resulting segment_file
e.x. option_name = +up_flag1,+up_flag2,+up_flag3,-down_flag1,-down_flag2
Each ifo may have a different string and is stored separately in the file.
Flags which add time must precede flags which subtract time.
Parameters
----------
workflow: pycbc.workflow.Workflow
name: string
Name of the segment list being created
option_name: str
Name of option in the associated config parser to get the flag list
returns
--------
seg_file: pycbc.workflow.SegFile
SegFile intance that points to the segment xml file on disk.
"""
from pycbc.dq import query_str
make_analysis_dir(out_dir)
cp = workflow.cp
start = workflow.analysis_time[0]
end = workflow.analysis_time[1]
# Check for veto definer file
veto_definer = None
if cp.has_option("workflow-segments", "segments-veto-definer-url"):
veto_definer = save_veto_definer(workflow.cp, out_dir, [])
# Check for provided server
server = "segments.ligo.org"
if cp.has_option("workflow-segments", "segments-database-url"):
server = cp.get("workflow-segments",
"segments-database-url")
segs = {}
for ifo in workflow.ifos:
flag_str = cp.get_opt_tags("workflow-segments", option_name, [ifo])
key = ifo + ':' + name
segs[key] = query_str(ifo, flag_str, start, end,
server=server,
veto_definer=veto_definer)
logging.info("%s: got %s flags", ifo, option_name)
return SegFile.from_segment_list_dict(name, segs,
extension='.xml',
valid_segment=workflow.analysis_time,
directory=out_dir) | python | def get_segments_file(workflow, name, option_name, out_dir):
from pycbc.dq import query_str
make_analysis_dir(out_dir)
cp = workflow.cp
start = workflow.analysis_time[0]
end = workflow.analysis_time[1]
# Check for veto definer file
veto_definer = None
if cp.has_option("workflow-segments", "segments-veto-definer-url"):
veto_definer = save_veto_definer(workflow.cp, out_dir, [])
# Check for provided server
server = "segments.ligo.org"
if cp.has_option("workflow-segments", "segments-database-url"):
server = cp.get("workflow-segments",
"segments-database-url")
segs = {}
for ifo in workflow.ifos:
flag_str = cp.get_opt_tags("workflow-segments", option_name, [ifo])
key = ifo + ':' + name
segs[key] = query_str(ifo, flag_str, start, end,
server=server,
veto_definer=veto_definer)
logging.info("%s: got %s flags", ifo, option_name)
return SegFile.from_segment_list_dict(name, segs,
extension='.xml',
valid_segment=workflow.analysis_time,
directory=out_dir) | [
"def",
"get_segments_file",
"(",
"workflow",
",",
"name",
",",
"option_name",
",",
"out_dir",
")",
":",
"from",
"pycbc",
".",
"dq",
"import",
"query_str",
"make_analysis_dir",
"(",
"out_dir",
")",
"cp",
"=",
"workflow",
".",
"cp",
"start",
"=",
"workflow",
... | Get cumulative segments from option name syntax for each ifo.
Use syntax of configparser string to define the resulting segment_file
e.x. option_name = +up_flag1,+up_flag2,+up_flag3,-down_flag1,-down_flag2
Each ifo may have a different string and is stored separately in the file.
Flags which add time must precede flags which subtract time.
Parameters
----------
workflow: pycbc.workflow.Workflow
name: string
Name of the segment list being created
option_name: str
Name of option in the associated config parser to get the flag list
returns
--------
seg_file: pycbc.workflow.SegFile
SegFile intance that points to the segment xml file on disk. | [
"Get",
"cumulative",
"segments",
"from",
"option",
"name",
"syntax",
"for",
"each",
"ifo",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L1395-L1445 |
228,433 | gwastro/pycbc | pycbc/filter/fotonfilter.py | get_swstat_bits | def get_swstat_bits(frame_filenames, swstat_channel_name, start_time, end_time):
''' This function just checks the first time in the SWSTAT channel
to see if the filter was on, it doesn't check times beyond that.
This is just for a first test on a small chunck of data.
To read the SWSTAT bits, reference: https://dcc.ligo.org/DocDB/0107/T1300711/001/LIGO-T1300711-v1.pdf
Bit 0-9 = Filter on/off switches for the 10 filters in an SFM.
Bit 10 = Filter module input switch on/off
Bit 11 = Filter module offset switch on/off
Bit 12 = Filter module output switch on/off
Bit 13 = Filter module limit switch on/off
Bit 14 = Filter module history reset momentary switch
'''
# read frames
swstat = frame.read_frame(frame_filenames, swstat_channel_name,
start_time=start_time, end_time=end_time)
# convert number in channel to binary
bits = bin(int(swstat[0]))
# check if filterbank input or output was off
filterbank_off = False
if len(bits) < 14 or int(bits[-13]) == 0 or int(bits[-11]) == 0:
filterbank_off = True
return bits[-10:], filterbank_off | python | def get_swstat_bits(frame_filenames, swstat_channel_name, start_time, end_time):
''' This function just checks the first time in the SWSTAT channel
to see if the filter was on, it doesn't check times beyond that.
This is just for a first test on a small chunck of data.
To read the SWSTAT bits, reference: https://dcc.ligo.org/DocDB/0107/T1300711/001/LIGO-T1300711-v1.pdf
Bit 0-9 = Filter on/off switches for the 10 filters in an SFM.
Bit 10 = Filter module input switch on/off
Bit 11 = Filter module offset switch on/off
Bit 12 = Filter module output switch on/off
Bit 13 = Filter module limit switch on/off
Bit 14 = Filter module history reset momentary switch
'''
# read frames
swstat = frame.read_frame(frame_filenames, swstat_channel_name,
start_time=start_time, end_time=end_time)
# convert number in channel to binary
bits = bin(int(swstat[0]))
# check if filterbank input or output was off
filterbank_off = False
if len(bits) < 14 or int(bits[-13]) == 0 or int(bits[-11]) == 0:
filterbank_off = True
return bits[-10:], filterbank_off | [
"def",
"get_swstat_bits",
"(",
"frame_filenames",
",",
"swstat_channel_name",
",",
"start_time",
",",
"end_time",
")",
":",
"# read frames",
"swstat",
"=",
"frame",
".",
"read_frame",
"(",
"frame_filenames",
",",
"swstat_channel_name",
",",
"start_time",
"=",
"start... | This function just checks the first time in the SWSTAT channel
to see if the filter was on, it doesn't check times beyond that.
This is just for a first test on a small chunck of data.
To read the SWSTAT bits, reference: https://dcc.ligo.org/DocDB/0107/T1300711/001/LIGO-T1300711-v1.pdf
Bit 0-9 = Filter on/off switches for the 10 filters in an SFM.
Bit 10 = Filter module input switch on/off
Bit 11 = Filter module offset switch on/off
Bit 12 = Filter module output switch on/off
Bit 13 = Filter module limit switch on/off
Bit 14 = Filter module history reset momentary switch | [
"This",
"function",
"just",
"checks",
"the",
"first",
"time",
"in",
"the",
"SWSTAT",
"channel",
"to",
"see",
"if",
"the",
"filter",
"was",
"on",
"it",
"doesn",
"t",
"check",
"times",
"beyond",
"that",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/fotonfilter.py#L26-L54 |
228,434 | gwastro/pycbc | pycbc/filter/fotonfilter.py | filter_data | def filter_data(data, filter_name, filter_file, bits, filterbank_off=False,
swstat_channel_name=None):
'''
A naive function to determine if the filter was on at the time
and then filter the data.
'''
# if filterbank is off then return a time series of zeroes
if filterbank_off:
return numpy.zeros(len(data))
# loop over the 10 filters in the filterbank
for i in range(10):
# read the filter
filter = Filter(filter_file[filter_name][i])
# if bit is on then filter the data
bit = int(bits[-(i+1)])
if bit:
logging.info('filtering with filter module %d', i)
# if there are second-order sections then filter with them
if len(filter.sections):
data = filter.apply(data)
# else it is a filter with only gain so apply the gain
else:
coeffs = iir2z(filter_file[filter_name][i])
if len(coeffs) > 1:
logging.info('Gain-only filter module return more than one number')
sys.exit()
gain = coeffs[0]
data = gain * data
return data | python | def filter_data(data, filter_name, filter_file, bits, filterbank_off=False,
swstat_channel_name=None):
'''
A naive function to determine if the filter was on at the time
and then filter the data.
'''
# if filterbank is off then return a time series of zeroes
if filterbank_off:
return numpy.zeros(len(data))
# loop over the 10 filters in the filterbank
for i in range(10):
# read the filter
filter = Filter(filter_file[filter_name][i])
# if bit is on then filter the data
bit = int(bits[-(i+1)])
if bit:
logging.info('filtering with filter module %d', i)
# if there are second-order sections then filter with them
if len(filter.sections):
data = filter.apply(data)
# else it is a filter with only gain so apply the gain
else:
coeffs = iir2z(filter_file[filter_name][i])
if len(coeffs) > 1:
logging.info('Gain-only filter module return more than one number')
sys.exit()
gain = coeffs[0]
data = gain * data
return data | [
"def",
"filter_data",
"(",
"data",
",",
"filter_name",
",",
"filter_file",
",",
"bits",
",",
"filterbank_off",
"=",
"False",
",",
"swstat_channel_name",
"=",
"None",
")",
":",
"# if filterbank is off then return a time series of zeroes",
"if",
"filterbank_off",
":",
"... | A naive function to determine if the filter was on at the time
and then filter the data. | [
"A",
"naive",
"function",
"to",
"determine",
"if",
"the",
"filter",
"was",
"on",
"at",
"the",
"time",
"and",
"then",
"filter",
"the",
"data",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/fotonfilter.py#L57-L92 |
228,435 | gwastro/pycbc | pycbc/filter/fotonfilter.py | read_gain_from_frames | def read_gain_from_frames(frame_filenames, gain_channel_name, start_time, end_time):
'''
Returns the gain from the file.
'''
# get timeseries from frame
gain = frame.read_frame(frame_filenames, gain_channel_name,
start_time=start_time, end_time=end_time)
return gain[0] | python | def read_gain_from_frames(frame_filenames, gain_channel_name, start_time, end_time):
'''
Returns the gain from the file.
'''
# get timeseries from frame
gain = frame.read_frame(frame_filenames, gain_channel_name,
start_time=start_time, end_time=end_time)
return gain[0] | [
"def",
"read_gain_from_frames",
"(",
"frame_filenames",
",",
"gain_channel_name",
",",
"start_time",
",",
"end_time",
")",
":",
"# get timeseries from frame",
"gain",
"=",
"frame",
".",
"read_frame",
"(",
"frame_filenames",
",",
"gain_channel_name",
",",
"start_time",
... | Returns the gain from the file. | [
"Returns",
"the",
"gain",
"from",
"the",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/fotonfilter.py#L94-L103 |
228,436 | gwastro/pycbc | pycbc/inference/sampler/__init__.py | load_from_config | def load_from_config(cp, model, **kwargs):
"""Loads a sampler from the given config file.
This looks for a name in the section ``[sampler]`` to determine which
sampler class to load. That sampler's ``from_config`` is then called.
Parameters
----------
cp : WorkflowConfigParser
Config parser to read from.
model : pycbc.inference.model
Which model to pass to the sampler.
\**kwargs :
All other keyword arguments are passed directly to the sampler's
``from_config`` file.
Returns
-------
sampler :
The initialized sampler.
"""
name = cp.get('sampler', 'name')
return samplers[name].from_config(cp, model, **kwargs) | python | def load_from_config(cp, model, **kwargs):
name = cp.get('sampler', 'name')
return samplers[name].from_config(cp, model, **kwargs) | [
"def",
"load_from_config",
"(",
"cp",
",",
"model",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"cp",
".",
"get",
"(",
"'sampler'",
",",
"'name'",
")",
"return",
"samplers",
"[",
"name",
"]",
".",
"from_config",
"(",
"cp",
",",
"model",
",",
"*... | Loads a sampler from the given config file.
This looks for a name in the section ``[sampler]`` to determine which
sampler class to load. That sampler's ``from_config`` is then called.
Parameters
----------
cp : WorkflowConfigParser
Config parser to read from.
model : pycbc.inference.model
Which model to pass to the sampler.
\**kwargs :
All other keyword arguments are passed directly to the sampler's
``from_config`` file.
Returns
-------
sampler :
The initialized sampler. | [
"Loads",
"a",
"sampler",
"from",
"the",
"given",
"config",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/__init__.py#L33-L55 |
228,437 | gwastro/pycbc | pycbc/filter/qtransform.py | qplane | def qplane(qplane_tile_dict, fseries, return_complex=False):
"""Performs q-transform on each tile for each q-plane and selects
tile with the maximum energy. Q-transform can then
be interpolated to a desired frequency and time resolution.
Parameters
----------
qplane_tile_dict:
Dictionary containing a list of q-tile tupples for each q-plane
fseries: 'pycbc FrequencySeries'
frequency-series data set
return_complex: {False, bool}
Return the raw complex series instead of the normalized power.
Returns
-------
q : float
The q of the maximum q plane
times : numpy.ndarray
The time that the qtransform is sampled.
freqs : numpy.ndarray
The frequencies that the qtransform is samled.
qplane : numpy.ndarray (2d)
The two dimensional interpolated qtransform of this time series.
"""
# store q-transforms for each q in a dict
qplanes = {}
max_energy, max_key = None, None
for i, q in enumerate(qplane_tile_dict):
energies = []
for f0 in qplane_tile_dict[q]:
energy = qseries(fseries, q, f0, return_complex=return_complex)
menergy = abs(energy).max()
energies.append(energy)
if i == 0 or menergy > max_energy:
max_energy = menergy
max_key = q
qplanes[q] = energies
# record q-transform output for peak q
plane = qplanes[max_key]
frequencies = qplane_tile_dict[max_key]
times = plane[0].sample_times.numpy()
plane = numpy.array([v.numpy() for v in plane])
return max_key, times, frequencies, numpy.array(plane) | python | def qplane(qplane_tile_dict, fseries, return_complex=False):
# store q-transforms for each q in a dict
qplanes = {}
max_energy, max_key = None, None
for i, q in enumerate(qplane_tile_dict):
energies = []
for f0 in qplane_tile_dict[q]:
energy = qseries(fseries, q, f0, return_complex=return_complex)
menergy = abs(energy).max()
energies.append(energy)
if i == 0 or menergy > max_energy:
max_energy = menergy
max_key = q
qplanes[q] = energies
# record q-transform output for peak q
plane = qplanes[max_key]
frequencies = qplane_tile_dict[max_key]
times = plane[0].sample_times.numpy()
plane = numpy.array([v.numpy() for v in plane])
return max_key, times, frequencies, numpy.array(plane) | [
"def",
"qplane",
"(",
"qplane_tile_dict",
",",
"fseries",
",",
"return_complex",
"=",
"False",
")",
":",
"# store q-transforms for each q in a dict",
"qplanes",
"=",
"{",
"}",
"max_energy",
",",
"max_key",
"=",
"None",
",",
"None",
"for",
"i",
",",
"q",
"in",
... | Performs q-transform on each tile for each q-plane and selects
tile with the maximum energy. Q-transform can then
be interpolated to a desired frequency and time resolution.
Parameters
----------
qplane_tile_dict:
Dictionary containing a list of q-tile tupples for each q-plane
fseries: 'pycbc FrequencySeries'
frequency-series data set
return_complex: {False, bool}
Return the raw complex series instead of the normalized power.
Returns
-------
q : float
The q of the maximum q plane
times : numpy.ndarray
The time that the qtransform is sampled.
freqs : numpy.ndarray
The frequencies that the qtransform is samled.
qplane : numpy.ndarray (2d)
The two dimensional interpolated qtransform of this time series. | [
"Performs",
"q",
"-",
"transform",
"on",
"each",
"tile",
"for",
"each",
"q",
"-",
"plane",
"and",
"selects",
"tile",
"with",
"the",
"maximum",
"energy",
".",
"Q",
"-",
"transform",
"can",
"then",
"be",
"interpolated",
"to",
"a",
"desired",
"frequency",
"... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/qtransform.py#L38-L84 |
228,438 | gwastro/pycbc | pycbc/filter/qtransform.py | qtiling | def qtiling(fseries, qrange, frange, mismatch=0.2):
"""Iterable constructor of QTile tuples
Parameters
----------
fseries: 'pycbc FrequencySeries'
frequency-series data set
qrange:
upper and lower bounds of q range
frange:
upper and lower bounds of frequency range
mismatch:
percentage of desired fractional mismatch
Returns
-------
qplane_tile_dict: 'dict'
dictionary containing Q-tile tuples for a set of Q-planes
"""
qplane_tile_dict = {}
qs = list(_iter_qs(qrange, deltam_f(mismatch)))
for q in qs:
qtilefreq = _iter_frequencies(q, frange, mismatch, fseries.duration)
qplane_tile_dict[q] = numpy.array(list(qtilefreq))
return qplane_tile_dict | python | def qtiling(fseries, qrange, frange, mismatch=0.2):
qplane_tile_dict = {}
qs = list(_iter_qs(qrange, deltam_f(mismatch)))
for q in qs:
qtilefreq = _iter_frequencies(q, frange, mismatch, fseries.duration)
qplane_tile_dict[q] = numpy.array(list(qtilefreq))
return qplane_tile_dict | [
"def",
"qtiling",
"(",
"fseries",
",",
"qrange",
",",
"frange",
",",
"mismatch",
"=",
"0.2",
")",
":",
"qplane_tile_dict",
"=",
"{",
"}",
"qs",
"=",
"list",
"(",
"_iter_qs",
"(",
"qrange",
",",
"deltam_f",
"(",
"mismatch",
")",
")",
")",
"for",
"q",
... | Iterable constructor of QTile tuples
Parameters
----------
fseries: 'pycbc FrequencySeries'
frequency-series data set
qrange:
upper and lower bounds of q range
frange:
upper and lower bounds of frequency range
mismatch:
percentage of desired fractional mismatch
Returns
-------
qplane_tile_dict: 'dict'
dictionary containing Q-tile tuples for a set of Q-planes | [
"Iterable",
"constructor",
"of",
"QTile",
"tuples"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/qtransform.py#L86-L111 |
228,439 | gwastro/pycbc | pycbc/_version_helper.py | get_build_name | def get_build_name(git_path='git'):
"""Find the username of the current builder
"""
name,retcode = call(('git', 'config', 'user.name'), returncode=True)
if retcode:
name = "Unknown User"
email,retcode = call(('git', 'config', 'user.email'), returncode=True)
if retcode:
email = ""
return "%s <%s>" % (name, email) | python | def get_build_name(git_path='git'):
name,retcode = call(('git', 'config', 'user.name'), returncode=True)
if retcode:
name = "Unknown User"
email,retcode = call(('git', 'config', 'user.email'), returncode=True)
if retcode:
email = ""
return "%s <%s>" % (name, email) | [
"def",
"get_build_name",
"(",
"git_path",
"=",
"'git'",
")",
":",
"name",
",",
"retcode",
"=",
"call",
"(",
"(",
"'git'",
",",
"'config'",
",",
"'user.name'",
")",
",",
"returncode",
"=",
"True",
")",
"if",
"retcode",
":",
"name",
"=",
"\"Unknown User\""... | Find the username of the current builder | [
"Find",
"the",
"username",
"of",
"the",
"current",
"builder"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/_version_helper.py#L73-L82 |
228,440 | gwastro/pycbc | pycbc/_version_helper.py | get_last_commit | def get_last_commit(git_path='git'):
"""Returns the details of the last git commit
Returns a tuple (hash, date, author name, author e-mail,
committer name, committer e-mail).
"""
hash_, udate, aname, amail, cname, cmail = (
call((git_path, 'log', '-1',
'--pretty=format:%H,%ct,%an,%ae,%cn,%ce')).split(","))
date = time.strftime('%Y-%m-%d %H:%M:%S +0000', time.gmtime(float(udate)))
author = '%s <%s>' % (aname, amail)
committer = '%s <%s>' % (cname, cmail)
return hash_, date, author, committer | python | def get_last_commit(git_path='git'):
hash_, udate, aname, amail, cname, cmail = (
call((git_path, 'log', '-1',
'--pretty=format:%H,%ct,%an,%ae,%cn,%ce')).split(","))
date = time.strftime('%Y-%m-%d %H:%M:%S +0000', time.gmtime(float(udate)))
author = '%s <%s>' % (aname, amail)
committer = '%s <%s>' % (cname, cmail)
return hash_, date, author, committer | [
"def",
"get_last_commit",
"(",
"git_path",
"=",
"'git'",
")",
":",
"hash_",
",",
"udate",
",",
"aname",
",",
"amail",
",",
"cname",
",",
"cmail",
"=",
"(",
"call",
"(",
"(",
"git_path",
",",
"'log'",
",",
"'-1'",
",",
"'--pretty=format:%H,%ct,%an,%ae,%cn,%... | Returns the details of the last git commit
Returns a tuple (hash, date, author name, author e-mail,
committer name, committer e-mail). | [
"Returns",
"the",
"details",
"of",
"the",
"last",
"git",
"commit"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/_version_helper.py#L91-L103 |
228,441 | gwastro/pycbc | pycbc/_version_helper.py | get_git_branch | def get_git_branch(git_path='git'):
"""Returns the name of the current git branch
"""
branch_match = call((git_path, 'rev-parse', '--symbolic-full-name', 'HEAD'))
if branch_match == "HEAD":
return None
else:
return os.path.basename(branch_match) | python | def get_git_branch(git_path='git'):
branch_match = call((git_path, 'rev-parse', '--symbolic-full-name', 'HEAD'))
if branch_match == "HEAD":
return None
else:
return os.path.basename(branch_match) | [
"def",
"get_git_branch",
"(",
"git_path",
"=",
"'git'",
")",
":",
"branch_match",
"=",
"call",
"(",
"(",
"git_path",
",",
"'rev-parse'",
",",
"'--symbolic-full-name'",
",",
"'HEAD'",
")",
")",
"if",
"branch_match",
"==",
"\"HEAD\"",
":",
"return",
"None",
"e... | Returns the name of the current git branch | [
"Returns",
"the",
"name",
"of",
"the",
"current",
"git",
"branch"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/_version_helper.py#L106-L113 |
228,442 | gwastro/pycbc | pycbc/_version_helper.py | get_git_tag | def get_git_tag(hash_, git_path='git'):
"""Returns the name of the current git tag
"""
tag, status = call((git_path, 'describe', '--exact-match',
'--tags', hash_), returncode=True)
if status == 0:
return tag
else:
return None | python | def get_git_tag(hash_, git_path='git'):
tag, status = call((git_path, 'describe', '--exact-match',
'--tags', hash_), returncode=True)
if status == 0:
return tag
else:
return None | [
"def",
"get_git_tag",
"(",
"hash_",
",",
"git_path",
"=",
"'git'",
")",
":",
"tag",
",",
"status",
"=",
"call",
"(",
"(",
"git_path",
",",
"'describe'",
",",
"'--exact-match'",
",",
"'--tags'",
",",
"hash_",
")",
",",
"returncode",
"=",
"True",
")",
"i... | Returns the name of the current git tag | [
"Returns",
"the",
"name",
"of",
"the",
"current",
"git",
"tag"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/_version_helper.py#L116-L124 |
228,443 | gwastro/pycbc | pycbc/_version_helper.py | get_git_status | def get_git_status(git_path='git'):
"""Returns the state of the git working copy
"""
status_output = subprocess.call((git_path, 'diff-files', '--quiet'))
if status_output != 0:
return 'UNCLEAN: Modified working tree'
else:
# check index for changes
status_output = subprocess.call((git_path, 'diff-index', '--cached',
'--quiet', 'HEAD'))
if status_output != 0:
return 'UNCLEAN: Modified index'
else:
return 'CLEAN: All modifications committed' | python | def get_git_status(git_path='git'):
status_output = subprocess.call((git_path, 'diff-files', '--quiet'))
if status_output != 0:
return 'UNCLEAN: Modified working tree'
else:
# check index for changes
status_output = subprocess.call((git_path, 'diff-index', '--cached',
'--quiet', 'HEAD'))
if status_output != 0:
return 'UNCLEAN: Modified index'
else:
return 'CLEAN: All modifications committed' | [
"def",
"get_git_status",
"(",
"git_path",
"=",
"'git'",
")",
":",
"status_output",
"=",
"subprocess",
".",
"call",
"(",
"(",
"git_path",
",",
"'diff-files'",
",",
"'--quiet'",
")",
")",
"if",
"status_output",
"!=",
"0",
":",
"return",
"'UNCLEAN: Modified worki... | Returns the state of the git working copy | [
"Returns",
"the",
"state",
"of",
"the",
"git",
"working",
"copy"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/_version_helper.py#L126-L139 |
228,444 | gwastro/pycbc | pycbc/_version_helper.py | generate_git_version_info | def generate_git_version_info():
"""Query the git repository information to generate a version module.
"""
info = GitInfo()
git_path = call(('which', 'git'))
# get build info
info.builder = get_build_name()
info.build_date = get_build_date()
# parse git ID
info.hash, info.date, info.author, info.committer = (
get_last_commit(git_path))
# determine branch
info.branch = get_git_branch(git_path)
# determine tag
info.tag = get_git_tag(info.hash, git_path)
# determine version
if info.tag:
info.version = info.tag.strip('v')
info.release = not re.search('[a-z]', info.version.lower())
else:
info.version = info.hash[:6]
info.release = False
# Determine *last* stable release
info.last_release = determine_latest_release_version()
# refresh index
call((git_path, 'update-index', '-q', '--refresh'))
# check working copy for changes
info.status = get_git_status(git_path)
return info | python | def generate_git_version_info():
info = GitInfo()
git_path = call(('which', 'git'))
# get build info
info.builder = get_build_name()
info.build_date = get_build_date()
# parse git ID
info.hash, info.date, info.author, info.committer = (
get_last_commit(git_path))
# determine branch
info.branch = get_git_branch(git_path)
# determine tag
info.tag = get_git_tag(info.hash, git_path)
# determine version
if info.tag:
info.version = info.tag.strip('v')
info.release = not re.search('[a-z]', info.version.lower())
else:
info.version = info.hash[:6]
info.release = False
# Determine *last* stable release
info.last_release = determine_latest_release_version()
# refresh index
call((git_path, 'update-index', '-q', '--refresh'))
# check working copy for changes
info.status = get_git_status(git_path)
return info | [
"def",
"generate_git_version_info",
"(",
")",
":",
"info",
"=",
"GitInfo",
"(",
")",
"git_path",
"=",
"call",
"(",
"(",
"'which'",
",",
"'git'",
")",
")",
"# get build info",
"info",
".",
"builder",
"=",
"get_build_name",
"(",
")",
"info",
".",
"build_date... | Query the git repository information to generate a version module. | [
"Query",
"the",
"git",
"repository",
"information",
"to",
"generate",
"a",
"version",
"module",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/_version_helper.py#L166-L203 |
228,445 | gwastro/pycbc | pycbc/vetoes/sgchisq.py | SingleDetSGChisq.values | def values(self, stilde, template, psd, snrv, snr_norm,
bchisq, bchisq_dof, indices):
""" Calculate sine-Gaussian chisq
Parameters
----------
stilde: pycbc.types.Frequencyseries
The overwhitened strain
template: pycbc.types.Frequencyseries
The waveform template being analyzed
psd: pycbc.types.Frequencyseries
The power spectral density of the data
snrv: numpy.ndarray
The peak unnormalized complex SNR values
snr_norm: float
The normalization factor for the snr
bchisq: numpy.ndarray
The Bruce Allen power chisq values for these triggers
bchisq_dof: numpy.ndarray
The degrees of freedom of the Bruce chisq
indics: numpy.ndarray
The indices of the snr peaks.
Returns
-------
chisq: Array
Chisq values, one for each sample index
"""
if not self.do:
return None
if template.params.template_hash not in self.params:
return numpy.ones(len(snrv))
values = self.params[template.params.template_hash].split(',')
# Get the chisq bins to use as the frequency reference point
bins = self.cached_chisq_bins(template, psd)
# This is implemented slowly, so let's not call it often, OK?
chisq = numpy.ones(len(snrv))
for i, snrvi in enumerate(snrv):
#Skip if newsnr too low
snr = abs(snrvi * snr_norm)
nsnr = ranking.newsnr(snr, bchisq[i] / bchisq_dof[i])
if nsnr < self.snr_threshold:
continue
N = (len(template) - 1) * 2
dt = 1.0 / (N * template.delta_f)
kmin = int(template.f_lower / psd.delta_f)
time = float(template.epoch) + dt * indices[i]
# Shift the time of interest to be centered on 0
stilde_shift = apply_fseries_time_shift(stilde, -time)
# Only apply the sine-Gaussian in a +-50 Hz range around the
# central frequency
qwindow = 50
chisq[i] = 0
# Estimate the maximum frequency up to which the waveform has
# power by approximating power per frequency
# as constant over the last 2 chisq bins. We cannot use the final
# chisq bin edge as it does not have to be where the waveform
# terminates.
fstep = (bins[-2] - bins[-3])
fpeak = (bins[-2] + fstep) * template.delta_f
# This is 90% of the Nyquist frequency of the data
# This allows us to avoid issues near Nyquist due to resample
# Filtering
fstop = len(stilde) * stilde.delta_f * 0.9
dof = 0
# Calculate the sum of SNR^2 for the sine-Gaussians specified
for descr in values:
# Get the q and frequency offset from the descriptor
q, offset = descr.split('-')
q, offset = float(q), float(offset)
fcen = fpeak + offset
flow = max(kmin * template.delta_f, fcen - qwindow)
fhigh = fcen + qwindow
# If any sine-gaussian tile has an upper frequency near
# nyquist return 1 instead.
if fhigh > fstop:
return numpy.ones(len(snrv))
kmin = int(flow / template.delta_f)
kmax = int(fhigh / template.delta_f)
#Calculate sine-gaussian tile
gtem = sinegauss.fd_sine_gaussian(1.0, q, fcen, flow,
len(template) * template.delta_f,
template.delta_f).astype(numpy.complex64)
gsigma = sigma(gtem, psd=psd,
low_frequency_cutoff=flow,
high_frequency_cutoff=fhigh)
#Calculate the SNR of the tile
gsnr = (gtem[kmin:kmax] * stilde_shift[kmin:kmax]).sum()
gsnr *= 4.0 * gtem.delta_f / gsigma
chisq[i] += abs(gsnr)**2.0
dof += 2
if dof == 0:
chisq[i] = 1
else:
chisq[i] /= dof
return chisq | python | def values(self, stilde, template, psd, snrv, snr_norm,
bchisq, bchisq_dof, indices):
if not self.do:
return None
if template.params.template_hash not in self.params:
return numpy.ones(len(snrv))
values = self.params[template.params.template_hash].split(',')
# Get the chisq bins to use as the frequency reference point
bins = self.cached_chisq_bins(template, psd)
# This is implemented slowly, so let's not call it often, OK?
chisq = numpy.ones(len(snrv))
for i, snrvi in enumerate(snrv):
#Skip if newsnr too low
snr = abs(snrvi * snr_norm)
nsnr = ranking.newsnr(snr, bchisq[i] / bchisq_dof[i])
if nsnr < self.snr_threshold:
continue
N = (len(template) - 1) * 2
dt = 1.0 / (N * template.delta_f)
kmin = int(template.f_lower / psd.delta_f)
time = float(template.epoch) + dt * indices[i]
# Shift the time of interest to be centered on 0
stilde_shift = apply_fseries_time_shift(stilde, -time)
# Only apply the sine-Gaussian in a +-50 Hz range around the
# central frequency
qwindow = 50
chisq[i] = 0
# Estimate the maximum frequency up to which the waveform has
# power by approximating power per frequency
# as constant over the last 2 chisq bins. We cannot use the final
# chisq bin edge as it does not have to be where the waveform
# terminates.
fstep = (bins[-2] - bins[-3])
fpeak = (bins[-2] + fstep) * template.delta_f
# This is 90% of the Nyquist frequency of the data
# This allows us to avoid issues near Nyquist due to resample
# Filtering
fstop = len(stilde) * stilde.delta_f * 0.9
dof = 0
# Calculate the sum of SNR^2 for the sine-Gaussians specified
for descr in values:
# Get the q and frequency offset from the descriptor
q, offset = descr.split('-')
q, offset = float(q), float(offset)
fcen = fpeak + offset
flow = max(kmin * template.delta_f, fcen - qwindow)
fhigh = fcen + qwindow
# If any sine-gaussian tile has an upper frequency near
# nyquist return 1 instead.
if fhigh > fstop:
return numpy.ones(len(snrv))
kmin = int(flow / template.delta_f)
kmax = int(fhigh / template.delta_f)
#Calculate sine-gaussian tile
gtem = sinegauss.fd_sine_gaussian(1.0, q, fcen, flow,
len(template) * template.delta_f,
template.delta_f).astype(numpy.complex64)
gsigma = sigma(gtem, psd=psd,
low_frequency_cutoff=flow,
high_frequency_cutoff=fhigh)
#Calculate the SNR of the tile
gsnr = (gtem[kmin:kmax] * stilde_shift[kmin:kmax]).sum()
gsnr *= 4.0 * gtem.delta_f / gsigma
chisq[i] += abs(gsnr)**2.0
dof += 2
if dof == 0:
chisq[i] = 1
else:
chisq[i] /= dof
return chisq | [
"def",
"values",
"(",
"self",
",",
"stilde",
",",
"template",
",",
"psd",
",",
"snrv",
",",
"snr_norm",
",",
"bchisq",
",",
"bchisq_dof",
",",
"indices",
")",
":",
"if",
"not",
"self",
".",
"do",
":",
"return",
"None",
"if",
"template",
".",
"params"... | Calculate sine-Gaussian chisq
Parameters
----------
stilde: pycbc.types.Frequencyseries
The overwhitened strain
template: pycbc.types.Frequencyseries
The waveform template being analyzed
psd: pycbc.types.Frequencyseries
The power spectral density of the data
snrv: numpy.ndarray
The peak unnormalized complex SNR values
snr_norm: float
The normalization factor for the snr
bchisq: numpy.ndarray
The Bruce Allen power chisq values for these triggers
bchisq_dof: numpy.ndarray
The degrees of freedom of the Bruce chisq
indics: numpy.ndarray
The indices of the snr peaks.
Returns
-------
chisq: Array
Chisq values, one for each sample index | [
"Calculate",
"sine",
"-",
"Gaussian",
"chisq"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/vetoes/sgchisq.py#L71-L177 |
228,446 | gwastro/pycbc | pycbc/events/stat.py | PhaseTDStatistic.logsignalrate | def logsignalrate(self, s0, s1, slide, step):
"""Calculate the normalized log rate density of signals via lookup"""
td = numpy.array(s0['end_time'] - s1['end_time'] - slide*step, ndmin=1)
pd = numpy.array((s0['coa_phase'] - s1['coa_phase']) % \
(2. * numpy.pi), ndmin=1)
rd = numpy.array((s0['sigmasq'] / s1['sigmasq']) ** 0.5, ndmin=1)
sn0 = numpy.array(s0['snr'], ndmin=1)
sn1 = numpy.array(s1['snr'], ndmin=1)
snr0 = sn0 * 1
snr1 = sn1 * 1
snr0[rd > 1] = sn1[rd > 1]
snr1[rd > 1] = sn0[rd > 1]
rd[rd > 1] = 1. / rd[rd > 1]
# Find which bin each coinc falls into
tv = numpy.searchsorted(self.tbins, td) - 1
pv = numpy.searchsorted(self.pbins, pd) - 1
s0v = numpy.searchsorted(self.sbins, snr0) - 1
s1v = numpy.searchsorted(self.sbins, snr1) - 1
rv = numpy.searchsorted(self.rbins, rd) - 1
# Enforce that points fits into the bin boundaries: if a point lies
# outside the boundaries it is pushed back to the nearest bin.
tv[tv < 0] = 0
tv[tv >= len(self.tbins) - 1] = len(self.tbins) - 2
pv[pv < 0] = 0
pv[pv >= len(self.pbins) - 1] = len(self.pbins) - 2
s0v[s0v < 0] = 0
s0v[s0v >= len(self.sbins) - 1] = len(self.sbins) - 2
s1v[s1v < 0] = 0
s1v[s1v >= len(self.sbins) - 1] = len(self.sbins) - 2
rv[rv < 0] = 0
rv[rv >= len(self.rbins) - 1] = len(self.rbins) - 2
return self.hist[tv, pv, s0v, s1v, rv] | python | def logsignalrate(self, s0, s1, slide, step):
td = numpy.array(s0['end_time'] - s1['end_time'] - slide*step, ndmin=1)
pd = numpy.array((s0['coa_phase'] - s1['coa_phase']) % \
(2. * numpy.pi), ndmin=1)
rd = numpy.array((s0['sigmasq'] / s1['sigmasq']) ** 0.5, ndmin=1)
sn0 = numpy.array(s0['snr'], ndmin=1)
sn1 = numpy.array(s1['snr'], ndmin=1)
snr0 = sn0 * 1
snr1 = sn1 * 1
snr0[rd > 1] = sn1[rd > 1]
snr1[rd > 1] = sn0[rd > 1]
rd[rd > 1] = 1. / rd[rd > 1]
# Find which bin each coinc falls into
tv = numpy.searchsorted(self.tbins, td) - 1
pv = numpy.searchsorted(self.pbins, pd) - 1
s0v = numpy.searchsorted(self.sbins, snr0) - 1
s1v = numpy.searchsorted(self.sbins, snr1) - 1
rv = numpy.searchsorted(self.rbins, rd) - 1
# Enforce that points fits into the bin boundaries: if a point lies
# outside the boundaries it is pushed back to the nearest bin.
tv[tv < 0] = 0
tv[tv >= len(self.tbins) - 1] = len(self.tbins) - 2
pv[pv < 0] = 0
pv[pv >= len(self.pbins) - 1] = len(self.pbins) - 2
s0v[s0v < 0] = 0
s0v[s0v >= len(self.sbins) - 1] = len(self.sbins) - 2
s1v[s1v < 0] = 0
s1v[s1v >= len(self.sbins) - 1] = len(self.sbins) - 2
rv[rv < 0] = 0
rv[rv >= len(self.rbins) - 1] = len(self.rbins) - 2
return self.hist[tv, pv, s0v, s1v, rv] | [
"def",
"logsignalrate",
"(",
"self",
",",
"s0",
",",
"s1",
",",
"slide",
",",
"step",
")",
":",
"td",
"=",
"numpy",
".",
"array",
"(",
"s0",
"[",
"'end_time'",
"]",
"-",
"s1",
"[",
"'end_time'",
"]",
"-",
"slide",
"*",
"step",
",",
"ndmin",
"=",
... | Calculate the normalized log rate density of signals via lookup | [
"Calculate",
"the",
"normalized",
"log",
"rate",
"density",
"of",
"signals",
"via",
"lookup"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/stat.py#L261-L297 |
228,447 | gwastro/pycbc | pycbc/events/stat.py | ExpFitStatistic.lognoiserate | def lognoiserate(self, trigs):
"""
Calculate the log noise rate density over single-ifo newsnr
Read in single trigger information, make the newsnr statistic
and rescale by the fitted coefficients alpha and rate
"""
alphai, ratei, thresh = self.find_fits(trigs)
newsnr = self.get_newsnr(trigs)
# alphai is constant of proportionality between single-ifo newsnr and
# negative log noise likelihood in given template
# ratei is rate of trigs in given template compared to average
# thresh is stat threshold used in given ifo
lognoisel = - alphai * (newsnr - thresh) + numpy.log(alphai) + \
numpy.log(ratei)
return numpy.array(lognoisel, ndmin=1, dtype=numpy.float32) | python | def lognoiserate(self, trigs):
alphai, ratei, thresh = self.find_fits(trigs)
newsnr = self.get_newsnr(trigs)
# alphai is constant of proportionality between single-ifo newsnr and
# negative log noise likelihood in given template
# ratei is rate of trigs in given template compared to average
# thresh is stat threshold used in given ifo
lognoisel = - alphai * (newsnr - thresh) + numpy.log(alphai) + \
numpy.log(ratei)
return numpy.array(lognoisel, ndmin=1, dtype=numpy.float32) | [
"def",
"lognoiserate",
"(",
"self",
",",
"trigs",
")",
":",
"alphai",
",",
"ratei",
",",
"thresh",
"=",
"self",
".",
"find_fits",
"(",
"trigs",
")",
"newsnr",
"=",
"self",
".",
"get_newsnr",
"(",
"trigs",
")",
"# alphai is constant of proportionality between s... | Calculate the log noise rate density over single-ifo newsnr
Read in single trigger information, make the newsnr statistic
and rescale by the fitted coefficients alpha and rate | [
"Calculate",
"the",
"log",
"noise",
"rate",
"density",
"over",
"single",
"-",
"ifo",
"newsnr"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/stat.py#L395-L410 |
228,448 | gwastro/pycbc | pycbc/events/stat.py | ExpFitStatistic.coinc | def coinc(self, s0, s1, slide, step): # pylint:disable=unused-argument
"""Calculate the final coinc ranking statistic"""
# Approximate log likelihood ratio by summing single-ifo negative
# log noise likelihoods
loglr = - s0 - s1
# add squares of threshold stat values via idealized Gaussian formula
threshes = [self.fits_by_tid[i]['thresh'] for i in self.ifos]
loglr += sum([t**2. / 2. for t in threshes])
# convert back to a coinc-SNR-like statistic
# via log likelihood ratio \propto rho_c^2 / 2
return (2. * loglr) ** 0.5 | python | def coinc(self, s0, s1, slide, step): # pylint:disable=unused-argument
# Approximate log likelihood ratio by summing single-ifo negative
# log noise likelihoods
loglr = - s0 - s1
# add squares of threshold stat values via idealized Gaussian formula
threshes = [self.fits_by_tid[i]['thresh'] for i in self.ifos]
loglr += sum([t**2. / 2. for t in threshes])
# convert back to a coinc-SNR-like statistic
# via log likelihood ratio \propto rho_c^2 / 2
return (2. * loglr) ** 0.5 | [
"def",
"coinc",
"(",
"self",
",",
"s0",
",",
"s1",
",",
"slide",
",",
"step",
")",
":",
"# pylint:disable=unused-argument",
"# Approximate log likelihood ratio by summing single-ifo negative",
"# log noise likelihoods",
"loglr",
"=",
"-",
"s0",
"-",
"s1",
"# add squares... | Calculate the final coinc ranking statistic | [
"Calculate",
"the",
"final",
"coinc",
"ranking",
"statistic"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/stat.py#L416-L426 |
228,449 | tomturner/django-tenants | django_tenants/models.py | TenantMixin._drop_schema | def _drop_schema(self, force_drop=False):
""" Drops the schema"""
connection = connections[get_tenant_database_alias()]
has_schema = hasattr(connection, 'schema_name')
if has_schema and connection.schema_name not in (self.schema_name, get_public_schema_name()):
raise Exception("Can't delete tenant outside it's own schema or "
"the public schema. Current schema is %s."
% connection.schema_name)
if has_schema and schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop):
self.pre_drop()
cursor = connection.cursor()
cursor.execute('DROP SCHEMA %s CASCADE' % self.schema_name) | python | def _drop_schema(self, force_drop=False):
connection = connections[get_tenant_database_alias()]
has_schema = hasattr(connection, 'schema_name')
if has_schema and connection.schema_name not in (self.schema_name, get_public_schema_name()):
raise Exception("Can't delete tenant outside it's own schema or "
"the public schema. Current schema is %s."
% connection.schema_name)
if has_schema and schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop):
self.pre_drop()
cursor = connection.cursor()
cursor.execute('DROP SCHEMA %s CASCADE' % self.schema_name) | [
"def",
"_drop_schema",
"(",
"self",
",",
"force_drop",
"=",
"False",
")",
":",
"connection",
"=",
"connections",
"[",
"get_tenant_database_alias",
"(",
")",
"]",
"has_schema",
"=",
"hasattr",
"(",
"connection",
",",
"'schema_name'",
")",
"if",
"has_schema",
"a... | Drops the schema | [
"Drops",
"the",
"schema"
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/django_tenants/models.py#L128-L140 |
228,450 | tomturner/django-tenants | django_tenants/models.py | TenantMixin.get_primary_domain | def get_primary_domain(self):
"""
Returns the primary domain of the tenant
"""
try:
domain = self.domains.get(is_primary=True)
return domain
except get_tenant_domain_model().DoesNotExist:
return None | python | def get_primary_domain(self):
try:
domain = self.domains.get(is_primary=True)
return domain
except get_tenant_domain_model().DoesNotExist:
return None | [
"def",
"get_primary_domain",
"(",
"self",
")",
":",
"try",
":",
"domain",
"=",
"self",
".",
"domains",
".",
"get",
"(",
"is_primary",
"=",
"True",
")",
"return",
"domain",
"except",
"get_tenant_domain_model",
"(",
")",
".",
"DoesNotExist",
":",
"return",
"... | Returns the primary domain of the tenant | [
"Returns",
"the",
"primary",
"domain",
"of",
"the",
"tenant"
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/django_tenants/models.py#L198-L206 |
228,451 | tomturner/django-tenants | django_tenants/models.py | TenantMixin.reverse | def reverse(self, request, view_name):
"""
Returns the URL of this tenant.
"""
http_type = 'https://' if request.is_secure() else 'http://'
domain = get_current_site(request).domain
url = ''.join((http_type, self.schema_name, '.', domain, reverse(view_name)))
return url | python | def reverse(self, request, view_name):
http_type = 'https://' if request.is_secure() else 'http://'
domain = get_current_site(request).domain
url = ''.join((http_type, self.schema_name, '.', domain, reverse(view_name)))
return url | [
"def",
"reverse",
"(",
"self",
",",
"request",
",",
"view_name",
")",
":",
"http_type",
"=",
"'https://'",
"if",
"request",
".",
"is_secure",
"(",
")",
"else",
"'http://'",
"domain",
"=",
"get_current_site",
"(",
"request",
")",
".",
"domain",
"url",
"=",
... | Returns the URL of this tenant. | [
"Returns",
"the",
"URL",
"of",
"this",
"tenant",
"."
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/django_tenants/models.py#L208-L218 |
228,452 | tomturner/django-tenants | django_tenants/routers.py | TenantSyncRouter.app_in_list | def app_in_list(self, app_label, apps_list):
"""
Is 'app_label' present in 'apps_list'?
apps_list is either settings.SHARED_APPS or settings.TENANT_APPS, a
list of app names.
We check the presence of the app's name or the full path to the apps's
AppConfig class.
https://docs.djangoproject.com/en/1.8/ref/applications/#configuring-applications
"""
appconfig = django_apps.get_app_config(app_label)
appconfig_full_name = '{}.{}'.format(
appconfig.__module__, appconfig.__class__.__name__)
return (appconfig.name in apps_list) or (appconfig_full_name in apps_list) | python | def app_in_list(self, app_label, apps_list):
appconfig = django_apps.get_app_config(app_label)
appconfig_full_name = '{}.{}'.format(
appconfig.__module__, appconfig.__class__.__name__)
return (appconfig.name in apps_list) or (appconfig_full_name in apps_list) | [
"def",
"app_in_list",
"(",
"self",
",",
"app_label",
",",
"apps_list",
")",
":",
"appconfig",
"=",
"django_apps",
".",
"get_app_config",
"(",
"app_label",
")",
"appconfig_full_name",
"=",
"'{}.{}'",
".",
"format",
"(",
"appconfig",
".",
"__module__",
",",
"app... | Is 'app_label' present in 'apps_list'?
apps_list is either settings.SHARED_APPS or settings.TENANT_APPS, a
list of app names.
We check the presence of the app's name or the full path to the apps's
AppConfig class.
https://docs.djangoproject.com/en/1.8/ref/applications/#configuring-applications | [
"Is",
"app_label",
"present",
"in",
"apps_list",
"?"
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/django_tenants/routers.py#L11-L25 |
228,453 | tomturner/django-tenants | django_tenants/staticfiles/finders.py | TenantFileSystemFinder.check | def check(self, **kwargs):
"""
In addition to parent class' checks, also ensure that MULTITENANT_STATICFILES_DIRS
is a tuple or a list.
"""
errors = super().check(**kwargs)
multitenant_staticfiles_dirs = settings.MULTITENANT_STATICFILES_DIRS
if not isinstance(multitenant_staticfiles_dirs, (list, tuple)):
errors.append(
Error(
"Your MULTITENANT_STATICFILES_DIRS setting is not a tuple or list.",
hint="Perhaps you forgot a trailing comma?",
)
)
return errors | python | def check(self, **kwargs):
errors = super().check(**kwargs)
multitenant_staticfiles_dirs = settings.MULTITENANT_STATICFILES_DIRS
if not isinstance(multitenant_staticfiles_dirs, (list, tuple)):
errors.append(
Error(
"Your MULTITENANT_STATICFILES_DIRS setting is not a tuple or list.",
hint="Perhaps you forgot a trailing comma?",
)
)
return errors | [
"def",
"check",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"super",
"(",
")",
".",
"check",
"(",
"*",
"*",
"kwargs",
")",
"multitenant_staticfiles_dirs",
"=",
"settings",
".",
"MULTITENANT_STATICFILES_DIRS",
"if",
"not",
"isinstance",
"... | In addition to parent class' checks, also ensure that MULTITENANT_STATICFILES_DIRS
is a tuple or a list. | [
"In",
"addition",
"to",
"parent",
"class",
"checks",
"also",
"ensure",
"that",
"MULTITENANT_STATICFILES_DIRS",
"is",
"a",
"tuple",
"or",
"a",
"list",
"."
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/django_tenants/staticfiles/finders.py#L79-L95 |
228,454 | tomturner/django-tenants | django_tenants/postgresql_backend/base.py | DatabaseWrapper.set_schema_to_public | def set_schema_to_public(self):
"""
Instructs to stay in the common 'public' schema.
"""
self.tenant = FakeTenant(schema_name=get_public_schema_name())
self.schema_name = get_public_schema_name()
self.set_settings_schema(self.schema_name)
self.search_path_set = False | python | def set_schema_to_public(self):
self.tenant = FakeTenant(schema_name=get_public_schema_name())
self.schema_name = get_public_schema_name()
self.set_settings_schema(self.schema_name)
self.search_path_set = False | [
"def",
"set_schema_to_public",
"(",
"self",
")",
":",
"self",
".",
"tenant",
"=",
"FakeTenant",
"(",
"schema_name",
"=",
"get_public_schema_name",
"(",
")",
")",
"self",
".",
"schema_name",
"=",
"get_public_schema_name",
"(",
")",
"self",
".",
"set_settings_sche... | Instructs to stay in the common 'public' schema. | [
"Instructs",
"to",
"stay",
"in",
"the",
"common",
"public",
"schema",
"."
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/django_tenants/postgresql_backend/base.py#L97-L104 |
228,455 | tomturner/django-tenants | django_tenants/template/loaders/cached.py | Loader.cache_key | def cache_key(self, template_name, skip=None):
"""
Generate a cache key for the template name, dirs, and skip.
If skip is provided, only origins that match template_name are included
in the cache key. This ensures each template is only parsed and cached
once if contained in different extend chains like:
x -> a -> a
y -> a -> a
z -> a -> a
"""
dirs_prefix = ''
skip_prefix = ''
tenant_prefix = ''
if skip:
matching = [origin.name for origin in skip if origin.template_name == template_name]
if matching:
skip_prefix = self.generate_hash(matching)
if connection.tenant:
tenant_prefix = str(connection.tenant.pk)
return '-'.join(s for s in (str(template_name), tenant_prefix, skip_prefix, dirs_prefix) if s) | python | def cache_key(self, template_name, skip=None):
dirs_prefix = ''
skip_prefix = ''
tenant_prefix = ''
if skip:
matching = [origin.name for origin in skip if origin.template_name == template_name]
if matching:
skip_prefix = self.generate_hash(matching)
if connection.tenant:
tenant_prefix = str(connection.tenant.pk)
return '-'.join(s for s in (str(template_name), tenant_prefix, skip_prefix, dirs_prefix) if s) | [
"def",
"cache_key",
"(",
"self",
",",
"template_name",
",",
"skip",
"=",
"None",
")",
":",
"dirs_prefix",
"=",
"''",
"skip_prefix",
"=",
"''",
"tenant_prefix",
"=",
"''",
"if",
"skip",
":",
"matching",
"=",
"[",
"origin",
".",
"name",
"for",
"origin",
... | Generate a cache key for the template name, dirs, and skip.
If skip is provided, only origins that match template_name are included
in the cache key. This ensures each template is only parsed and cached
once if contained in different extend chains like:
x -> a -> a
y -> a -> a
z -> a -> a | [
"Generate",
"a",
"cache",
"key",
"for",
"the",
"template",
"name",
"dirs",
"and",
"skip",
"."
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/django_tenants/template/loaders/cached.py#L13-L38 |
228,456 | tomturner/django-tenants | django_tenants/utils.py | parse_tenant_config_path | def parse_tenant_config_path(config_path):
"""
Convenience function for parsing django-tenants' path configuration strings.
If the string contains '%s', then the current tenant's schema name will be inserted at that location. Otherwise
the schema name will be appended to the end of the string.
:param config_path: A configuration path string that optionally contains '%s' to indicate where the tenant
schema name should be inserted.
:return: The formatted string containing the schema name
"""
try:
# Insert schema name
return config_path % connection.schema_name
except (TypeError, ValueError):
# No %s in string; append schema name at the end
return os.path.join(config_path, connection.schema_name) | python | def parse_tenant_config_path(config_path):
try:
# Insert schema name
return config_path % connection.schema_name
except (TypeError, ValueError):
# No %s in string; append schema name at the end
return os.path.join(config_path, connection.schema_name) | [
"def",
"parse_tenant_config_path",
"(",
"config_path",
")",
":",
"try",
":",
"# Insert schema name",
"return",
"config_path",
"%",
"connection",
".",
"schema_name",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"# No %s in string; append schema name at the end"... | Convenience function for parsing django-tenants' path configuration strings.
If the string contains '%s', then the current tenant's schema name will be inserted at that location. Otherwise
the schema name will be appended to the end of the string.
:param config_path: A configuration path string that optionally contains '%s' to indicate where the tenant
schema name should be inserted.
:return: The formatted string containing the schema name | [
"Convenience",
"function",
"for",
"parsing",
"django",
"-",
"tenants",
"path",
"configuration",
"strings",
"."
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/django_tenants/utils.py#L165-L182 |
228,457 | tomturner/django-tenants | django_tenants/clone.py | CloneSchema._create_clone_schema_function | def _create_clone_schema_function(self):
"""
Creates a postgres function `clone_schema` that copies a schema and its
contents. Will replace any existing `clone_schema` functions owned by the
`postgres` superuser.
"""
cursor = connection.cursor()
cursor.execute(CLONE_SCHEMA_FUNCTION)
cursor.close() | python | def _create_clone_schema_function(self):
cursor = connection.cursor()
cursor.execute(CLONE_SCHEMA_FUNCTION)
cursor.close() | [
"def",
"_create_clone_schema_function",
"(",
"self",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"CLONE_SCHEMA_FUNCTION",
")",
"cursor",
".",
"close",
"(",
")"
] | Creates a postgres function `clone_schema` that copies a schema and its
contents. Will replace any existing `clone_schema` functions owned by the
`postgres` superuser. | [
"Creates",
"a",
"postgres",
"function",
"clone_schema",
"that",
"copies",
"a",
"schema",
"and",
"its",
"contents",
".",
"Will",
"replace",
"any",
"existing",
"clone_schema",
"functions",
"owned",
"by",
"the",
"postgres",
"superuser",
"."
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/django_tenants/clone.py#L203-L211 |
228,458 | tomturner/django-tenants | django_tenants/clone.py | CloneSchema.clone_schema | def clone_schema(self, base_schema_name, new_schema_name):
"""
Creates a new schema `new_schema_name` as a clone of an existing schema
`old_schema_name`.
"""
connection.set_schema_to_public()
cursor = connection.cursor()
# check if the clone_schema function already exists in the db
try:
cursor.execute("SELECT 'clone_schema'::regproc")
except ProgrammingError:
self._create_clone_schema_function()
transaction.commit()
sql = 'SELECT clone_schema(%(base_schema)s, %(new_schema)s, TRUE)'
cursor.execute(
sql,
{'base_schema': base_schema_name, 'new_schema': new_schema_name}
)
cursor.close() | python | def clone_schema(self, base_schema_name, new_schema_name):
connection.set_schema_to_public()
cursor = connection.cursor()
# check if the clone_schema function already exists in the db
try:
cursor.execute("SELECT 'clone_schema'::regproc")
except ProgrammingError:
self._create_clone_schema_function()
transaction.commit()
sql = 'SELECT clone_schema(%(base_schema)s, %(new_schema)s, TRUE)'
cursor.execute(
sql,
{'base_schema': base_schema_name, 'new_schema': new_schema_name}
)
cursor.close() | [
"def",
"clone_schema",
"(",
"self",
",",
"base_schema_name",
",",
"new_schema_name",
")",
":",
"connection",
".",
"set_schema_to_public",
"(",
")",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"# check if the clone_schema function already exists in the db",
"tr... | Creates a new schema `new_schema_name` as a clone of an existing schema
`old_schema_name`. | [
"Creates",
"a",
"new",
"schema",
"new_schema_name",
"as",
"a",
"clone",
"of",
"an",
"existing",
"schema",
"old_schema_name",
"."
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/django_tenants/clone.py#L213-L233 |
228,459 | tomturner/django-tenants | fabfile.py | install_database | def install_database(name, owner, template='template0', encoding='UTF8', locale='en_US.UTF-8'):
"""
Require a PostgreSQL database.
::
from fabtools import require
require.postgres.database('myapp', owner='dbuser')
"""
create_database(name, owner, template=template, encoding=encoding,
locale=locale) | python | def install_database(name, owner, template='template0', encoding='UTF8', locale='en_US.UTF-8'):
create_database(name, owner, template=template, encoding=encoding,
locale=locale) | [
"def",
"install_database",
"(",
"name",
",",
"owner",
",",
"template",
"=",
"'template0'",
",",
"encoding",
"=",
"'UTF8'",
",",
"locale",
"=",
"'en_US.UTF-8'",
")",
":",
"create_database",
"(",
"name",
",",
"owner",
",",
"template",
"=",
"template",
",",
"... | Require a PostgreSQL database.
::
from fabtools import require
require.postgres.database('myapp', owner='dbuser') | [
"Require",
"a",
"PostgreSQL",
"database",
"."
] | f3e06e2b0facee7ed797e5694bcac433df3e5315 | https://github.com/tomturner/django-tenants/blob/f3e06e2b0facee7ed797e5694bcac433df3e5315/fabfile.py#L67-L81 |
228,460 | micahhausler/container-transform | container_transform/ecs.py | ECSTransformer.add_volume | def add_volume(self, volume):
"""
Add a volume to self.volumes if it isn't already present
"""
for old_vol in self.volumes:
if volume == old_vol:
return
self.volumes.append(volume) | python | def add_volume(self, volume):
for old_vol in self.volumes:
if volume == old_vol:
return
self.volumes.append(volume) | [
"def",
"add_volume",
"(",
"self",
",",
"volume",
")",
":",
"for",
"old_vol",
"in",
"self",
".",
"volumes",
":",
"if",
"volume",
"==",
"old_vol",
":",
"return",
"self",
".",
"volumes",
".",
"append",
"(",
"volume",
")"
] | Add a volume to self.volumes if it isn't already present | [
"Add",
"a",
"volume",
"to",
"self",
".",
"volumes",
"if",
"it",
"isn",
"t",
"already",
"present"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/ecs.py#L70-L77 |
228,461 | micahhausler/container-transform | container_transform/ecs.py | ECSTransformer.emit_containers | def emit_containers(self, containers, verbose=True):
"""
Emits the task definition and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
task_definition = {
'family': self.family,
'containerDefinitions': containers,
'volumes': self.volumes or []
}
if verbose:
return json.dumps(task_definition, indent=4, sort_keys=True)
else:
return json.dumps(task_definition) | python | def emit_containers(self, containers, verbose=True):
containers = sorted(containers, key=lambda c: c.get('name'))
task_definition = {
'family': self.family,
'containerDefinitions': containers,
'volumes': self.volumes or []
}
if verbose:
return json.dumps(task_definition, indent=4, sort_keys=True)
else:
return json.dumps(task_definition) | [
"def",
"emit_containers",
"(",
"self",
",",
"containers",
",",
"verbose",
"=",
"True",
")",
":",
"containers",
"=",
"sorted",
"(",
"containers",
",",
"key",
"=",
"lambda",
"c",
":",
"c",
".",
"get",
"(",
"'name'",
")",
")",
"task_definition",
"=",
"{",... | Emits the task definition and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str | [
"Emits",
"the",
"task",
"definition",
"and",
"sorts",
"containers",
"by",
"name"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/ecs.py#L79-L101 |
228,462 | micahhausler/container-transform | container_transform/ecs.py | ECSTransformer.ingest_volumes_param | def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a task description
"""
data = {}
for volume in volumes:
if volume.get('host', {}).get('sourcePath'):
data[volume.get('name')] = {
'path': volume.get('host', {}).get('sourcePath'),
'readonly': volume.get('readOnly', False)
}
else:
data[volume.get('name')] = {
'path': '/tmp/{}'.format(uuid.uuid4().hex[:8]),
'readonly': volume.get('readOnly', False)
}
return data | python | def ingest_volumes_param(self, volumes):
data = {}
for volume in volumes:
if volume.get('host', {}).get('sourcePath'):
data[volume.get('name')] = {
'path': volume.get('host', {}).get('sourcePath'),
'readonly': volume.get('readOnly', False)
}
else:
data[volume.get('name')] = {
'path': '/tmp/{}'.format(uuid.uuid4().hex[:8]),
'readonly': volume.get('readOnly', False)
}
return data | [
"def",
"ingest_volumes_param",
"(",
"self",
",",
"volumes",
")",
":",
"data",
"=",
"{",
"}",
"for",
"volume",
"in",
"volumes",
":",
"if",
"volume",
".",
"get",
"(",
"'host'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'sourcePath'",
")",
":",
"data",
"[... | This is for ingesting the "volumes" of a task description | [
"This",
"is",
"for",
"ingesting",
"the",
"volumes",
"of",
"a",
"task",
"description"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/ecs.py#L216-L233 |
228,463 | micahhausler/container-transform | container_transform/ecs.py | ECSTransformer._build_mountpoint | def _build_mountpoint(self, volume):
"""
Given a generic volume definition, create the mountPoints element
"""
self.add_volume(self._build_volume(volume))
return {
'sourceVolume': self.path_to_name(volume.get('host')),
'containerPath': volume.get('container')
} | python | def _build_mountpoint(self, volume):
self.add_volume(self._build_volume(volume))
return {
'sourceVolume': self.path_to_name(volume.get('host')),
'containerPath': volume.get('container')
} | [
"def",
"_build_mountpoint",
"(",
"self",
",",
"volume",
")",
":",
"self",
".",
"add_volume",
"(",
"self",
".",
"_build_volume",
"(",
"volume",
")",
")",
"return",
"{",
"'sourceVolume'",
":",
"self",
".",
"path_to_name",
"(",
"volume",
".",
"get",
"(",
"'... | Given a generic volume definition, create the mountPoints element | [
"Given",
"a",
"generic",
"volume",
"definition",
"create",
"the",
"mountPoints",
"element"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/ecs.py#L259-L267 |
228,464 | micahhausler/container-transform | container_transform/marathon.py | MarathonTransformer.flatten_container | def flatten_container(self, container):
"""
Accepts a marathon container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.MARATHON.value]['name'] and \
'.' in names[TransformationTypes.MARATHON.value]['name']:
marathon_dotted_name = names[TransformationTypes.MARATHON.value]['name']
parts = marathon_dotted_name.split('.')
if parts[-2] == 'parameters':
# Special lookup for docker parameters
common_type = names[TransformationTypes.MARATHON.value].get('type')
result = self._lookup_parameter(container, parts[-1], common_type)
if result:
container[marathon_dotted_name] = result
else:
result = lookup_nested_dict(container, *parts)
if result:
container[marathon_dotted_name] = result
return container | python | def flatten_container(self, container):
for names in ARG_MAP.values():
if names[TransformationTypes.MARATHON.value]['name'] and \
'.' in names[TransformationTypes.MARATHON.value]['name']:
marathon_dotted_name = names[TransformationTypes.MARATHON.value]['name']
parts = marathon_dotted_name.split('.')
if parts[-2] == 'parameters':
# Special lookup for docker parameters
common_type = names[TransformationTypes.MARATHON.value].get('type')
result = self._lookup_parameter(container, parts[-1], common_type)
if result:
container[marathon_dotted_name] = result
else:
result = lookup_nested_dict(container, *parts)
if result:
container[marathon_dotted_name] = result
return container | [
"def",
"flatten_container",
"(",
"self",
",",
"container",
")",
":",
"for",
"names",
"in",
"ARG_MAP",
".",
"values",
"(",
")",
":",
"if",
"names",
"[",
"TransformationTypes",
".",
"MARATHON",
".",
"value",
"]",
"[",
"'name'",
"]",
"and",
"'.'",
"in",
"... | Accepts a marathon container and pulls out the nested values into the top level | [
"Accepts",
"a",
"marathon",
"container",
"and",
"pulls",
"out",
"the",
"nested",
"values",
"into",
"the",
"top",
"level"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/marathon.py#L108-L129 |
228,465 | micahhausler/container-transform | container_transform/marathon.py | MarathonTransformer._convert_volume | def _convert_volume(self, volume):
"""
This is for ingesting the "volumes" of a app description
"""
data = {
'host': volume.get('hostPath'),
'container': volume.get('containerPath'),
'readonly': volume.get('mode') == 'RO',
}
return data | python | def _convert_volume(self, volume):
data = {
'host': volume.get('hostPath'),
'container': volume.get('containerPath'),
'readonly': volume.get('mode') == 'RO',
}
return data | [
"def",
"_convert_volume",
"(",
"self",
",",
"volume",
")",
":",
"data",
"=",
"{",
"'host'",
":",
"volume",
".",
"get",
"(",
"'hostPath'",
")",
",",
"'container'",
":",
"volume",
".",
"get",
"(",
"'containerPath'",
")",
",",
"'readonly'",
":",
"volume",
... | This is for ingesting the "volumes" of a app description | [
"This",
"is",
"for",
"ingesting",
"the",
"volumes",
"of",
"a",
"app",
"description"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/marathon.py#L323-L332 |
228,466 | micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer._find_convertable_object | def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
if len(convertable_object_idxs) < 1:
raise Exception("Kubernetes config didn't contain any of {}".format(
', '.join(self.pod_types.keys())
))
return list(data)[convertable_object_idxs[0]] | python | def _find_convertable_object(self, data):
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
if len(convertable_object_idxs) < 1:
raise Exception("Kubernetes config didn't contain any of {}".format(
', '.join(self.pod_types.keys())
))
return list(data)[convertable_object_idxs[0]] | [
"def",
"_find_convertable_object",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"list",
"(",
"data",
")",
"convertable_object_idxs",
"=",
"[",
"idx",
"for",
"idx",
",",
"obj",
"in",
"enumerate",
"(",
"data",
")",
"if",
"obj",
".",
"get",
"(",
"'kin... | Get the first instance of a `self.pod_types` | [
"Get",
"the",
"first",
"instance",
"of",
"a",
"self",
".",
"pod_types"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L70-L85 |
228,467 | micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer._read_stream | def _read_stream(self, stream):
"""
Read in the pod stream
"""
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes', [])) | python | def _read_stream(self, stream):
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes', [])) | [
"def",
"_read_stream",
"(",
"self",
",",
"stream",
")",
":",
"data",
"=",
"yaml",
".",
"safe_load_all",
"(",
"stream",
"=",
"stream",
")",
"obj",
"=",
"self",
".",
"_find_convertable_object",
"(",
"data",
")",
"pod",
"=",
"self",
".",
"pod_types",
"[",
... | Read in the pod stream | [
"Read",
"in",
"the",
"pod",
"stream"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L87-L94 |
228,468 | micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer.ingest_volumes_param | def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a pod spec
"""
data = {}
for volume in volumes:
if volume.get('hostPath', {}).get('path'):
data[volume.get('name')] = {
'path': volume.get('hostPath', {}).get('path'),
}
elif volume.get('emptyDir'):
data[volume.get('name')] = {}
else:
data[volume.get('name')] = {}
# TODO Support other k8s volume types?
return data | python | def ingest_volumes_param(self, volumes):
data = {}
for volume in volumes:
if volume.get('hostPath', {}).get('path'):
data[volume.get('name')] = {
'path': volume.get('hostPath', {}).get('path'),
}
elif volume.get('emptyDir'):
data[volume.get('name')] = {}
else:
data[volume.get('name')] = {}
# TODO Support other k8s volume types?
return data | [
"def",
"ingest_volumes_param",
"(",
"self",
",",
"volumes",
")",
":",
"data",
"=",
"{",
"}",
"for",
"volume",
"in",
"volumes",
":",
"if",
"volume",
".",
"get",
"(",
"'hostPath'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'path'",
")",
":",
"data",
"[",... | This is for ingesting the "volumes" of a pod spec | [
"This",
"is",
"for",
"ingesting",
"the",
"volumes",
"of",
"a",
"pod",
"spec"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L96-L111 |
228,469 | micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer.flatten_container | def flatten_container(self, container):
"""
Accepts a kubernetes container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.KUBERNETES.value]['name'] and \
'.' in names[TransformationTypes.KUBERNETES.value]['name']:
kubernetes_dotted_name = names[TransformationTypes.KUBERNETES.value]['name']
parts = kubernetes_dotted_name.split('.')
result = lookup_nested_dict(container, *parts)
if result:
container[kubernetes_dotted_name] = result
return container | python | def flatten_container(self, container):
for names in ARG_MAP.values():
if names[TransformationTypes.KUBERNETES.value]['name'] and \
'.' in names[TransformationTypes.KUBERNETES.value]['name']:
kubernetes_dotted_name = names[TransformationTypes.KUBERNETES.value]['name']
parts = kubernetes_dotted_name.split('.')
result = lookup_nested_dict(container, *parts)
if result:
container[kubernetes_dotted_name] = result
return container | [
"def",
"flatten_container",
"(",
"self",
",",
"container",
")",
":",
"for",
"names",
"in",
"ARG_MAP",
".",
"values",
"(",
")",
":",
"if",
"names",
"[",
"TransformationTypes",
".",
"KUBERNETES",
".",
"value",
"]",
"[",
"'name'",
"]",
"and",
"'.'",
"in",
... | Accepts a kubernetes container and pulls out the nested values into the top level | [
"Accepts",
"a",
"kubernetes",
"container",
"and",
"pulls",
"out",
"the",
"nested",
"values",
"into",
"the",
"top",
"level"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L124-L136 |
228,470 | micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer._build_volume | def _build_volume(self, volume):
"""
Given a generic volume definition, create the volumes element
"""
self.volumes[self._build_volume_name(volume.get('host'))] = {
'name': self._build_volume_name(volume.get('host')),
'hostPath': {
'path': volume.get('host')
}
}
response = {
'name': self._build_volume_name(volume.get('host')),
'mountPath': volume.get('container'),
}
if volume.get('readonly', False):
response['readOnly'] = bool(volume.get('readonly', False))
return response | python | def _build_volume(self, volume):
self.volumes[self._build_volume_name(volume.get('host'))] = {
'name': self._build_volume_name(volume.get('host')),
'hostPath': {
'path': volume.get('host')
}
}
response = {
'name': self._build_volume_name(volume.get('host')),
'mountPath': volume.get('container'),
}
if volume.get('readonly', False):
response['readOnly'] = bool(volume.get('readonly', False))
return response | [
"def",
"_build_volume",
"(",
"self",
",",
"volume",
")",
":",
"self",
".",
"volumes",
"[",
"self",
".",
"_build_volume_name",
"(",
"volume",
".",
"get",
"(",
"'host'",
")",
")",
"]",
"=",
"{",
"'name'",
":",
"self",
".",
"_build_volume_name",
"(",
"vol... | Given a generic volume definition, create the volumes element | [
"Given",
"a",
"generic",
"volume",
"definition",
"create",
"the",
"volumes",
"element"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L352-L369 |
228,471 | micahhausler/container-transform | container_transform/converter.py | Converter._convert_container | def _convert_container(self, container, input_transformer, output_transformer):
"""
Converts a given dictionary to an output container definition
:type container: dict
:param container: The container definitions as a dictionary
:rtype: dict
:return: A output_type container definition
"""
output = {}
for parameter, options in ARG_MAP.items():
output_name = options.get(self.output_type, {}).get('name')
output_required = options.get(self.output_type, {}).get('required')
input_name = options.get(self.input_type, {}).get('name')
if container.get(input_name) and \
hasattr(input_transformer, 'ingest_{}'.format(parameter)) and \
output_name and hasattr(output_transformer, 'emit_{}'.format(parameter)):
# call transform_{}
ingest_func = getattr(input_transformer, 'ingest_{}'.format(parameter))
emit_func = getattr(output_transformer, 'emit_{}'.format(parameter))
output[output_name] = emit_func(ingest_func(container.get(input_name)))
if not container.get(input_name) and output_required:
msg_template = 'Container {name} is missing required parameter "{output_name}".'
self.messages.add(
msg_template.format(
output_name=output_name,
output_type=self.output_type,
name=container.get('name', container)
)
)
return output | python | def _convert_container(self, container, input_transformer, output_transformer):
output = {}
for parameter, options in ARG_MAP.items():
output_name = options.get(self.output_type, {}).get('name')
output_required = options.get(self.output_type, {}).get('required')
input_name = options.get(self.input_type, {}).get('name')
if container.get(input_name) and \
hasattr(input_transformer, 'ingest_{}'.format(parameter)) and \
output_name and hasattr(output_transformer, 'emit_{}'.format(parameter)):
# call transform_{}
ingest_func = getattr(input_transformer, 'ingest_{}'.format(parameter))
emit_func = getattr(output_transformer, 'emit_{}'.format(parameter))
output[output_name] = emit_func(ingest_func(container.get(input_name)))
if not container.get(input_name) and output_required:
msg_template = 'Container {name} is missing required parameter "{output_name}".'
self.messages.add(
msg_template.format(
output_name=output_name,
output_type=self.output_type,
name=container.get('name', container)
)
)
return output | [
"def",
"_convert_container",
"(",
"self",
",",
"container",
",",
"input_transformer",
",",
"output_transformer",
")",
":",
"output",
"=",
"{",
"}",
"for",
"parameter",
",",
"options",
"in",
"ARG_MAP",
".",
"items",
"(",
")",
":",
"output_name",
"=",
"options... | Converts a given dictionary to an output container definition
:type container: dict
:param container: The container definitions as a dictionary
:rtype: dict
:return: A output_type container definition | [
"Converts",
"a",
"given",
"dictionary",
"to",
"an",
"output",
"container",
"definition"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/converter.py#L66-L102 |
228,472 | micahhausler/container-transform | container_transform/client.py | transform | def transform(input_file, input_type, output_type, verbose, quiet):
"""
container-transform is a small utility to transform various docker
container formats to one another.
Default input type is compose, default output type is ECS
Default is to read from STDIN if no INPUT_FILE is provided
All options may be set by environment variables with the prefix "CT_"
followed by the full argument name.
"""
converter = Converter(input_file, input_type, output_type)
output = converter.convert(verbose)
click.echo(click.style(output, fg='green'))
if not quiet:
for message in converter.messages:
click.echo(click.style(message, fg='red', bold=True), err=True) | python | def transform(input_file, input_type, output_type, verbose, quiet):
converter = Converter(input_file, input_type, output_type)
output = converter.convert(verbose)
click.echo(click.style(output, fg='green'))
if not quiet:
for message in converter.messages:
click.echo(click.style(message, fg='red', bold=True), err=True) | [
"def",
"transform",
"(",
"input_file",
",",
"input_type",
",",
"output_type",
",",
"verbose",
",",
"quiet",
")",
":",
"converter",
"=",
"Converter",
"(",
"input_file",
",",
"input_type",
",",
"output_type",
")",
"output",
"=",
"converter",
".",
"convert",
"(... | container-transform is a small utility to transform various docker
container formats to one another.
Default input type is compose, default output type is ECS
Default is to read from STDIN if no INPUT_FILE is provided
All options may be set by environment variables with the prefix "CT_"
followed by the full argument name. | [
"container",
"-",
"transform",
"is",
"a",
"small",
"utility",
"to",
"transform",
"various",
"docker",
"container",
"formats",
"to",
"one",
"another",
"."
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/client.py#L51-L70 |
228,473 | micahhausler/container-transform | container_transform/chronos.py | ChronosTransformer.flatten_container | def flatten_container(self, container):
"""
Accepts a chronos container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.CHRONOS.value]['name'] and \
'.' in names[TransformationTypes.CHRONOS.value]['name']:
chronos_dotted_name = names[TransformationTypes.CHRONOS.value]['name']
parts = chronos_dotted_name.split('.')
if parts[-2] == 'parameters':
# Special lookup for docker parameters
common_type = names[TransformationTypes.CHRONOS.value].get('type')
result = self._lookup_parameter(container, parts[-1], common_type)
if result:
container[chronos_dotted_name] = result
else:
result = lookup_nested_dict(container, *parts)
if result:
container[chronos_dotted_name] = result
return container | python | def flatten_container(self, container):
for names in ARG_MAP.values():
if names[TransformationTypes.CHRONOS.value]['name'] and \
'.' in names[TransformationTypes.CHRONOS.value]['name']:
chronos_dotted_name = names[TransformationTypes.CHRONOS.value]['name']
parts = chronos_dotted_name.split('.')
if parts[-2] == 'parameters':
# Special lookup for docker parameters
common_type = names[TransformationTypes.CHRONOS.value].get('type')
result = self._lookup_parameter(container, parts[-1], common_type)
if result:
container[chronos_dotted_name] = result
else:
result = lookup_nested_dict(container, *parts)
if result:
container[chronos_dotted_name] = result
return container | [
"def",
"flatten_container",
"(",
"self",
",",
"container",
")",
":",
"for",
"names",
"in",
"ARG_MAP",
".",
"values",
"(",
")",
":",
"if",
"names",
"[",
"TransformationTypes",
".",
"CHRONOS",
".",
"value",
"]",
"[",
"'name'",
"]",
"and",
"'.'",
"in",
"n... | Accepts a chronos container and pulls out the nested values into the top level | [
"Accepts",
"a",
"chronos",
"container",
"and",
"pulls",
"out",
"the",
"nested",
"values",
"into",
"the",
"top",
"level"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/chronos.py#L106-L126 |
228,474 | micahhausler/container-transform | container_transform/compose.py | ComposeTransformer.ingest_containers | def ingest_containers(self, containers=None):
"""
Transform the YAML into a dict with normalized keys
"""
containers = containers or self.stream or {}
output_containers = []
for container_name, definition in containers.items():
container = definition.copy()
container['name'] = container_name
output_containers.append(container)
return output_containers | python | def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
output_containers = []
for container_name, definition in containers.items():
container = definition.copy()
container['name'] = container_name
output_containers.append(container)
return output_containers | [
"def",
"ingest_containers",
"(",
"self",
",",
"containers",
"=",
"None",
")",
":",
"containers",
"=",
"containers",
"or",
"self",
".",
"stream",
"or",
"{",
"}",
"output_containers",
"=",
"[",
"]",
"for",
"container_name",
",",
"definition",
"in",
"containers... | Transform the YAML into a dict with normalized keys | [
"Transform",
"the",
"YAML",
"into",
"a",
"dict",
"with",
"normalized",
"keys"
] | 68223fae98f30b8bb2ce0f02ba9e58afbc80f196 | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/compose.py#L46-L59 |
228,475 | pyca/pynacl | src/nacl/hash.py | sha256 | def sha256(message, encoder=nacl.encoding.HexEncoder):
"""
Hashes ``message`` with SHA256.
:param message: The message to hash.
:type message: bytes
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes
"""
return encoder.encode(nacl.bindings.crypto_hash_sha256(message)) | python | def sha256(message, encoder=nacl.encoding.HexEncoder):
return encoder.encode(nacl.bindings.crypto_hash_sha256(message)) | [
"def",
"sha256",
"(",
"message",
",",
"encoder",
"=",
"nacl",
".",
"encoding",
".",
"HexEncoder",
")",
":",
"return",
"encoder",
".",
"encode",
"(",
"nacl",
".",
"bindings",
".",
"crypto_hash_sha256",
"(",
"message",
")",
")"
] | Hashes ``message`` with SHA256.
:param message: The message to hash.
:type message: bytes
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes | [
"Hashes",
"message",
"with",
"SHA256",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/hash.py#L60-L70 |
228,476 | pyca/pynacl | src/nacl/hash.py | sha512 | def sha512(message, encoder=nacl.encoding.HexEncoder):
"""
Hashes ``message`` with SHA512.
:param message: The message to hash.
:type message: bytes
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes
"""
return encoder.encode(nacl.bindings.crypto_hash_sha512(message)) | python | def sha512(message, encoder=nacl.encoding.HexEncoder):
return encoder.encode(nacl.bindings.crypto_hash_sha512(message)) | [
"def",
"sha512",
"(",
"message",
",",
"encoder",
"=",
"nacl",
".",
"encoding",
".",
"HexEncoder",
")",
":",
"return",
"encoder",
".",
"encode",
"(",
"nacl",
".",
"bindings",
".",
"crypto_hash_sha512",
"(",
"message",
")",
")"
] | Hashes ``message`` with SHA512.
:param message: The message to hash.
:type message: bytes
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes | [
"Hashes",
"message",
"with",
"SHA512",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/hash.py#L73-L83 |
228,477 | pyca/pynacl | src/nacl/hash.py | blake2b | def blake2b(data, digest_size=BLAKE2B_BYTES, key=b'',
salt=b'', person=b'',
encoder=nacl.encoding.HexEncoder):
"""
Hashes ``data`` with blake2b.
:param data: the digest input byte sequence
:type data: bytes
:param digest_size: the requested digest size; must be at most
:const:`BLAKE2B_BYTES_MAX`;
the default digest size is
:const:`BLAKE2B_BYTES`
:type digest_size: int
:param key: the key to be set for keyed MAC/PRF usage; if set, the key
must be at most :data:`~nacl.hash.BLAKE2B_KEYBYTES_MAX` long
:type key: bytes
:param salt: an initialization salt at most
:const:`BLAKE2B_SALTBYTES` long;
it will be zero-padded if needed
:type salt: bytes
:param person: a personalization string at most
:const:`BLAKE2B_PERSONALBYTES` long;
it will be zero-padded if needed
:type person: bytes
:param encoder: the encoder to use on returned digest
:type encoder: class
:returns: The hashed message.
:rtype: bytes
"""
digest = _b2b_hash(data, digest_size=digest_size, key=key,
salt=salt, person=person)
return encoder.encode(digest) | python | def blake2b(data, digest_size=BLAKE2B_BYTES, key=b'',
salt=b'', person=b'',
encoder=nacl.encoding.HexEncoder):
digest = _b2b_hash(data, digest_size=digest_size, key=key,
salt=salt, person=person)
return encoder.encode(digest) | [
"def",
"blake2b",
"(",
"data",
",",
"digest_size",
"=",
"BLAKE2B_BYTES",
",",
"key",
"=",
"b''",
",",
"salt",
"=",
"b''",
",",
"person",
"=",
"b''",
",",
"encoder",
"=",
"nacl",
".",
"encoding",
".",
"HexEncoder",
")",
":",
"digest",
"=",
"_b2b_hash",
... | Hashes ``data`` with blake2b.
:param data: the digest input byte sequence
:type data: bytes
:param digest_size: the requested digest size; must be at most
:const:`BLAKE2B_BYTES_MAX`;
the default digest size is
:const:`BLAKE2B_BYTES`
:type digest_size: int
:param key: the key to be set for keyed MAC/PRF usage; if set, the key
must be at most :data:`~nacl.hash.BLAKE2B_KEYBYTES_MAX` long
:type key: bytes
:param salt: an initialization salt at most
:const:`BLAKE2B_SALTBYTES` long;
it will be zero-padded if needed
:type salt: bytes
:param person: a personalization string at most
:const:`BLAKE2B_PERSONALBYTES` long;
it will be zero-padded if needed
:type person: bytes
:param encoder: the encoder to use on returned digest
:type encoder: class
:returns: The hashed message.
:rtype: bytes | [
"Hashes",
"data",
"with",
"blake2b",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/hash.py#L86-L118 |
228,478 | pyca/pynacl | src/nacl/hash.py | siphash24 | def siphash24(message, key=b'', encoder=nacl.encoding.HexEncoder):
"""
Computes a keyed MAC of ``message`` using the short-input-optimized
siphash-2-4 construction.
:param message: The message to hash.
:type message: bytes
:param key: the message authentication key for the siphash MAC construct
:type key: bytes(:const:`SIPHASH_KEYBYTES`)
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes(:const:`SIPHASH_BYTES`)
"""
digest = _sip_hash(message, key)
return encoder.encode(digest) | python | def siphash24(message, key=b'', encoder=nacl.encoding.HexEncoder):
digest = _sip_hash(message, key)
return encoder.encode(digest) | [
"def",
"siphash24",
"(",
"message",
",",
"key",
"=",
"b''",
",",
"encoder",
"=",
"nacl",
".",
"encoding",
".",
"HexEncoder",
")",
":",
"digest",
"=",
"_sip_hash",
"(",
"message",
",",
"key",
")",
"return",
"encoder",
".",
"encode",
"(",
"digest",
")"
] | Computes a keyed MAC of ``message`` using the short-input-optimized
siphash-2-4 construction.
:param message: The message to hash.
:type message: bytes
:param key: the message authentication key for the siphash MAC construct
:type key: bytes(:const:`SIPHASH_KEYBYTES`)
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes(:const:`SIPHASH_BYTES`) | [
"Computes",
"a",
"keyed",
"MAC",
"of",
"message",
"using",
"the",
"short",
"-",
"input",
"-",
"optimized",
"siphash",
"-",
"2",
"-",
"4",
"construction",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/hash.py#L124-L138 |
228,479 | pyca/pynacl | src/nacl/hash.py | siphashx24 | def siphashx24(message, key=b'', encoder=nacl.encoding.HexEncoder):
"""
Computes a keyed MAC of ``message`` using the 128 bit variant of the
siphash-2-4 construction.
:param message: The message to hash.
:type message: bytes
:param key: the message authentication key for the siphash MAC construct
:type key: bytes(:const:`SIPHASHX_KEYBYTES`)
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes(:const:`SIPHASHX_BYTES`)
.. versionadded:: 1.2
"""
digest = _sip_hashx(message, key)
return encoder.encode(digest) | python | def siphashx24(message, key=b'', encoder=nacl.encoding.HexEncoder):
digest = _sip_hashx(message, key)
return encoder.encode(digest) | [
"def",
"siphashx24",
"(",
"message",
",",
"key",
"=",
"b''",
",",
"encoder",
"=",
"nacl",
".",
"encoding",
".",
"HexEncoder",
")",
":",
"digest",
"=",
"_sip_hashx",
"(",
"message",
",",
"key",
")",
"return",
"encoder",
".",
"encode",
"(",
"digest",
")"... | Computes a keyed MAC of ``message`` using the 128 bit variant of the
siphash-2-4 construction.
:param message: The message to hash.
:type message: bytes
:param key: the message authentication key for the siphash MAC construct
:type key: bytes(:const:`SIPHASHX_KEYBYTES`)
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes(:const:`SIPHASHX_BYTES`)
.. versionadded:: 1.2 | [
"Computes",
"a",
"keyed",
"MAC",
"of",
"message",
"using",
"the",
"128",
"bit",
"variant",
"of",
"the",
"siphash",
"-",
"2",
"-",
"4",
"construction",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/hash.py#L144-L160 |
228,480 | pyca/pynacl | src/nacl/bindings/crypto_sign.py | crypto_sign_keypair | def crypto_sign_keypair():
"""
Returns a randomly generated public key and secret key.
:rtype: (bytes(public_key), bytes(secret_key))
"""
pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
rc = lib.crypto_sign_keypair(pk, sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return (
ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
) | python | def crypto_sign_keypair():
pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
rc = lib.crypto_sign_keypair(pk, sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return (
ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
) | [
"def",
"crypto_sign_keypair",
"(",
")",
":",
"pk",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_sign_PUBLICKEYBYTES",
")",
"sk",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_sign_SECRETKEYBYTES",
")",
"rc",
"=",
"lib",
"... | Returns a randomly generated public key and secret key.
:rtype: (bytes(public_key), bytes(secret_key)) | [
"Returns",
"a",
"randomly",
"generated",
"public",
"key",
"and",
"secret",
"key",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_sign.py#L33-L50 |
228,481 | pyca/pynacl | src/nacl/bindings/crypto_sign.py | crypto_sign_seed_keypair | def crypto_sign_seed_keypair(seed):
"""
Computes and returns the public key and secret key using the seed ``seed``.
:param seed: bytes
:rtype: (bytes(public_key), bytes(secret_key))
"""
if len(seed) != crypto_sign_SEEDBYTES:
raise exc.ValueError("Invalid seed")
pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
rc = lib.crypto_sign_seed_keypair(pk, sk, seed)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return (
ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
) | python | def crypto_sign_seed_keypair(seed):
if len(seed) != crypto_sign_SEEDBYTES:
raise exc.ValueError("Invalid seed")
pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
rc = lib.crypto_sign_seed_keypair(pk, sk, seed)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return (
ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
) | [
"def",
"crypto_sign_seed_keypair",
"(",
"seed",
")",
":",
"if",
"len",
"(",
"seed",
")",
"!=",
"crypto_sign_SEEDBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Invalid seed\"",
")",
"pk",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"cryp... | Computes and returns the public key and secret key using the seed ``seed``.
:param seed: bytes
:rtype: (bytes(public_key), bytes(secret_key)) | [
"Computes",
"and",
"returns",
"the",
"public",
"key",
"and",
"secret",
"key",
"using",
"the",
"seed",
"seed",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_sign.py#L53-L74 |
228,482 | pyca/pynacl | src/nacl/bindings/crypto_sign.py | crypto_sign | def crypto_sign(message, sk):
"""
Signs the message ``message`` using the secret key ``sk`` and returns the
signed message.
:param message: bytes
:param sk: bytes
:rtype: bytes
"""
signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES)
signed_len = ffi.new("unsigned long long *")
rc = lib.crypto_sign(signed, signed_len, message, len(message), sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(signed, signed_len[0])[:] | python | def crypto_sign(message, sk):
signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES)
signed_len = ffi.new("unsigned long long *")
rc = lib.crypto_sign(signed, signed_len, message, len(message), sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(signed, signed_len[0])[:] | [
"def",
"crypto_sign",
"(",
"message",
",",
"sk",
")",
":",
"signed",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"len",
"(",
"message",
")",
"+",
"crypto_sign_BYTES",
")",
"signed_len",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned long long *\"",
... | Signs the message ``message`` using the secret key ``sk`` and returns the
signed message.
:param message: bytes
:param sk: bytes
:rtype: bytes | [
"Signs",
"the",
"message",
"message",
"using",
"the",
"secret",
"key",
"sk",
"and",
"returns",
"the",
"signed",
"message",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_sign.py#L77-L94 |
228,483 | pyca/pynacl | src/nacl/bindings/crypto_sign.py | crypto_sign_open | def crypto_sign_open(signed, pk):
"""
Verifies the signature of the signed message ``signed`` using the public
key ``pk`` and returns the unsigned message.
:param signed: bytes
:param pk: bytes
:rtype: bytes
"""
message = ffi.new("unsigned char[]", len(signed))
message_len = ffi.new("unsigned long long *")
if lib.crypto_sign_open(
message, message_len, signed, len(signed), pk) != 0:
raise exc.BadSignatureError("Signature was forged or corrupt")
return ffi.buffer(message, message_len[0])[:] | python | def crypto_sign_open(signed, pk):
message = ffi.new("unsigned char[]", len(signed))
message_len = ffi.new("unsigned long long *")
if lib.crypto_sign_open(
message, message_len, signed, len(signed), pk) != 0:
raise exc.BadSignatureError("Signature was forged or corrupt")
return ffi.buffer(message, message_len[0])[:] | [
"def",
"crypto_sign_open",
"(",
"signed",
",",
"pk",
")",
":",
"message",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"len",
"(",
"signed",
")",
")",
"message_len",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned long long *\"",
")",
"if",
"lib",
"... | Verifies the signature of the signed message ``signed`` using the public
key ``pk`` and returns the unsigned message.
:param signed: bytes
:param pk: bytes
:rtype: bytes | [
"Verifies",
"the",
"signature",
"of",
"the",
"signed",
"message",
"signed",
"using",
"the",
"public",
"key",
"pk",
"and",
"returns",
"the",
"unsigned",
"message",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_sign.py#L97-L113 |
228,484 | pyca/pynacl | src/nacl/bindings/crypto_sign.py | crypto_sign_ed25519ph_update | def crypto_sign_ed25519ph_update(edph, pmsg):
"""
Update the hash state wrapped in edph
:param edph: the ed25519ph state being updated
:type edph: crypto_sign_ed25519ph_state
:param pmsg: the partial message
:type pmsg: bytes
:rtype: None
"""
ensure(isinstance(edph, crypto_sign_ed25519ph_state),
'edph parameter must be a ed25519ph_state object',
raising=exc.TypeError)
ensure(isinstance(pmsg, bytes),
'pmsg parameter must be a bytes object',
raising=exc.TypeError)
rc = lib.crypto_sign_ed25519ph_update(edph.state,
pmsg,
len(pmsg))
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError) | python | def crypto_sign_ed25519ph_update(edph, pmsg):
ensure(isinstance(edph, crypto_sign_ed25519ph_state),
'edph parameter must be a ed25519ph_state object',
raising=exc.TypeError)
ensure(isinstance(pmsg, bytes),
'pmsg parameter must be a bytes object',
raising=exc.TypeError)
rc = lib.crypto_sign_ed25519ph_update(edph.state,
pmsg,
len(pmsg))
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError) | [
"def",
"crypto_sign_ed25519ph_update",
"(",
"edph",
",",
"pmsg",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"edph",
",",
"crypto_sign_ed25519ph_state",
")",
",",
"'edph parameter must be a ed25519ph_state object'",
",",
"raising",
"=",
"exc",
".",
"TypeError",
")",
... | Update the hash state wrapped in edph
:param edph: the ed25519ph state being updated
:type edph: crypto_sign_ed25519ph_state
:param pmsg: the partial message
:type pmsg: bytes
:rtype: None | [
"Update",
"the",
"hash",
"state",
"wrapped",
"in",
"edph"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_sign.py#L219-L240 |
228,485 | pyca/pynacl | src/nacl/bindings/crypto_sign.py | crypto_sign_ed25519ph_final_create | def crypto_sign_ed25519ph_final_create(edph,
sk):
"""
Create a signature for the data hashed in edph
using the secret key sk
:param edph: the ed25519ph state for the data
being signed
:type edph: crypto_sign_ed25519ph_state
:param sk: the ed25519 secret part of the signing key
:type sk: bytes
:return: ed25519ph signature
:rtype: bytes
"""
ensure(isinstance(edph, crypto_sign_ed25519ph_state),
'edph parameter must be a ed25519ph_state object',
raising=exc.TypeError)
ensure(isinstance(sk, bytes),
'secret key parameter must be a bytes object',
raising=exc.TypeError)
ensure(len(sk) == crypto_sign_SECRETKEYBYTES,
('secret key must be {0} '
'bytes long').format(crypto_sign_SECRETKEYBYTES),
raising=exc.TypeError)
signature = ffi.new("unsigned char[]", crypto_sign_BYTES)
rc = lib.crypto_sign_ed25519ph_final_create(edph.state,
signature,
ffi.NULL,
sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(signature, crypto_sign_BYTES)[:] | python | def crypto_sign_ed25519ph_final_create(edph,
sk):
ensure(isinstance(edph, crypto_sign_ed25519ph_state),
'edph parameter must be a ed25519ph_state object',
raising=exc.TypeError)
ensure(isinstance(sk, bytes),
'secret key parameter must be a bytes object',
raising=exc.TypeError)
ensure(len(sk) == crypto_sign_SECRETKEYBYTES,
('secret key must be {0} '
'bytes long').format(crypto_sign_SECRETKEYBYTES),
raising=exc.TypeError)
signature = ffi.new("unsigned char[]", crypto_sign_BYTES)
rc = lib.crypto_sign_ed25519ph_final_create(edph.state,
signature,
ffi.NULL,
sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(signature, crypto_sign_BYTES)[:] | [
"def",
"crypto_sign_ed25519ph_final_create",
"(",
"edph",
",",
"sk",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"edph",
",",
"crypto_sign_ed25519ph_state",
")",
",",
"'edph parameter must be a ed25519ph_state object'",
",",
"raising",
"=",
"exc",
".",
"TypeError",
")... | Create a signature for the data hashed in edph
using the secret key sk
:param edph: the ed25519ph state for the data
being signed
:type edph: crypto_sign_ed25519ph_state
:param sk: the ed25519 secret part of the signing key
:type sk: bytes
:return: ed25519ph signature
:rtype: bytes | [
"Create",
"a",
"signature",
"for",
"the",
"data",
"hashed",
"in",
"edph",
"using",
"the",
"secret",
"key",
"sk"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_sign.py#L243-L276 |
228,486 | pyca/pynacl | src/nacl/bindings/crypto_sign.py | crypto_sign_ed25519ph_final_verify | def crypto_sign_ed25519ph_final_verify(edph,
signature,
pk):
"""
Verify a prehashed signature using the public key pk
:param edph: the ed25519ph state for the data
being verified
:type edph: crypto_sign_ed25519ph_state
:param signature: the signature being verified
:type signature: bytes
:param pk: the ed25519 public part of the signing key
:type pk: bytes
:return: True if the signature is valid
:rtype: boolean
:raises exc.BadSignatureError: if the signature is not valid
"""
ensure(isinstance(edph, crypto_sign_ed25519ph_state),
'edph parameter must be a ed25519ph_state object',
raising=exc.TypeError)
ensure(isinstance(signature, bytes),
'signature parameter must be a bytes object',
raising=exc.TypeError)
ensure(len(signature) == crypto_sign_BYTES,
('signature must be {0} '
'bytes long').format(crypto_sign_BYTES),
raising=exc.TypeError)
ensure(isinstance(pk, bytes),
'public key parameter must be a bytes object',
raising=exc.TypeError)
ensure(len(pk) == crypto_sign_PUBLICKEYBYTES,
('public key must be {0} '
'bytes long').format(crypto_sign_PUBLICKEYBYTES),
raising=exc.TypeError)
rc = lib.crypto_sign_ed25519ph_final_verify(edph.state,
signature,
pk)
if rc != 0:
raise exc.BadSignatureError("Signature was forged or corrupt")
return True | python | def crypto_sign_ed25519ph_final_verify(edph,
signature,
pk):
ensure(isinstance(edph, crypto_sign_ed25519ph_state),
'edph parameter must be a ed25519ph_state object',
raising=exc.TypeError)
ensure(isinstance(signature, bytes),
'signature parameter must be a bytes object',
raising=exc.TypeError)
ensure(len(signature) == crypto_sign_BYTES,
('signature must be {0} '
'bytes long').format(crypto_sign_BYTES),
raising=exc.TypeError)
ensure(isinstance(pk, bytes),
'public key parameter must be a bytes object',
raising=exc.TypeError)
ensure(len(pk) == crypto_sign_PUBLICKEYBYTES,
('public key must be {0} '
'bytes long').format(crypto_sign_PUBLICKEYBYTES),
raising=exc.TypeError)
rc = lib.crypto_sign_ed25519ph_final_verify(edph.state,
signature,
pk)
if rc != 0:
raise exc.BadSignatureError("Signature was forged or corrupt")
return True | [
"def",
"crypto_sign_ed25519ph_final_verify",
"(",
"edph",
",",
"signature",
",",
"pk",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"edph",
",",
"crypto_sign_ed25519ph_state",
")",
",",
"'edph parameter must be a ed25519ph_state object'",
",",
"raising",
"=",
"exc",
".... | Verify a prehashed signature using the public key pk
:param edph: the ed25519ph state for the data
being verified
:type edph: crypto_sign_ed25519ph_state
:param signature: the signature being verified
:type signature: bytes
:param pk: the ed25519 public part of the signing key
:type pk: bytes
:return: True if the signature is valid
:rtype: boolean
:raises exc.BadSignatureError: if the signature is not valid | [
"Verify",
"a",
"prehashed",
"signature",
"using",
"the",
"public",
"key",
"pk"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_sign.py#L279-L319 |
228,487 | pyca/pynacl | src/nacl/pwhash/argon2i.py | kdf | def kdf(size, password, salt,
opslimit=OPSLIMIT_SENSITIVE,
memlimit=MEMLIMIT_SENSITIVE,
encoder=nacl.encoding.RawEncoder):
"""
Derive a ``size`` bytes long key from a caller-supplied
``password`` and ``salt`` pair using the argon2i
memory-hard construct.
the enclosing module provides the constants
- :py:const:`.OPSLIMIT_INTERACTIVE`
- :py:const:`.MEMLIMIT_INTERACTIVE`
- :py:const:`.OPSLIMIT_MODERATE`
- :py:const:`.MEMLIMIT_MODERATE`
- :py:const:`.OPSLIMIT_SENSITIVE`
- :py:const:`.MEMLIMIT_SENSITIVE`
as a guidance for correct settings.
:param size: derived key size, must be between
:py:const:`.BYTES_MIN` and
:py:const:`.BYTES_MAX`
:type size: int
:param password: password used to seed the key derivation procedure;
it length must be between
:py:const:`.PASSWD_MIN` and
:py:const:`.PASSWD_MAX`
:type password: bytes
:param salt: **RANDOM** salt used in the key derivation procedure;
its length must be exactly :py:const:`.SALTBYTES`
:type salt: bytes
:param opslimit: the time component (operation count)
of the key derivation procedure's computational cost;
it must be between
:py:const:`.OPSLIMIT_MIN` and
:py:const:`.OPSLIMIT_MAX`
:type opslimit: int
:param memlimit: the memory occupation component
of the key derivation procedure's computational cost;
it must be between
:py:const:`.MEMLIMIT_MIN` and
:py:const:`.MEMLIMIT_MAX`
:type memlimit: int
:rtype: bytes
.. versionadded:: 1.2
"""
return encoder.encode(
nacl.bindings.crypto_pwhash_alg(size, password, salt,
opslimit, memlimit,
ALG)
) | python | def kdf(size, password, salt,
opslimit=OPSLIMIT_SENSITIVE,
memlimit=MEMLIMIT_SENSITIVE,
encoder=nacl.encoding.RawEncoder):
return encoder.encode(
nacl.bindings.crypto_pwhash_alg(size, password, salt,
opslimit, memlimit,
ALG)
) | [
"def",
"kdf",
"(",
"size",
",",
"password",
",",
"salt",
",",
"opslimit",
"=",
"OPSLIMIT_SENSITIVE",
",",
"memlimit",
"=",
"MEMLIMIT_SENSITIVE",
",",
"encoder",
"=",
"nacl",
".",
"encoding",
".",
"RawEncoder",
")",
":",
"return",
"encoder",
".",
"encode",
... | Derive a ``size`` bytes long key from a caller-supplied
``password`` and ``salt`` pair using the argon2i
memory-hard construct.
the enclosing module provides the constants
- :py:const:`.OPSLIMIT_INTERACTIVE`
- :py:const:`.MEMLIMIT_INTERACTIVE`
- :py:const:`.OPSLIMIT_MODERATE`
- :py:const:`.MEMLIMIT_MODERATE`
- :py:const:`.OPSLIMIT_SENSITIVE`
- :py:const:`.MEMLIMIT_SENSITIVE`
as a guidance for correct settings.
:param size: derived key size, must be between
:py:const:`.BYTES_MIN` and
:py:const:`.BYTES_MAX`
:type size: int
:param password: password used to seed the key derivation procedure;
it length must be between
:py:const:`.PASSWD_MIN` and
:py:const:`.PASSWD_MAX`
:type password: bytes
:param salt: **RANDOM** salt used in the key derivation procedure;
its length must be exactly :py:const:`.SALTBYTES`
:type salt: bytes
:param opslimit: the time component (operation count)
of the key derivation procedure's computational cost;
it must be between
:py:const:`.OPSLIMIT_MIN` and
:py:const:`.OPSLIMIT_MAX`
:type opslimit: int
:param memlimit: the memory occupation component
of the key derivation procedure's computational cost;
it must be between
:py:const:`.MEMLIMIT_MIN` and
:py:const:`.MEMLIMIT_MAX`
:type memlimit: int
:rtype: bytes
.. versionadded:: 1.2 | [
"Derive",
"a",
"size",
"bytes",
"long",
"key",
"from",
"a",
"caller",
"-",
"supplied",
"password",
"and",
"salt",
"pair",
"using",
"the",
"argon2i",
"memory",
"-",
"hard",
"construct",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/pwhash/argon2i.py#L57-L110 |
228,488 | pyca/pynacl | src/nacl/pwhash/argon2i.py | str | def str(password,
opslimit=OPSLIMIT_INTERACTIVE,
memlimit=MEMLIMIT_INTERACTIVE):
"""
Hashes a password with a random salt, using the memory-hard
argon2i construct and returning an ascii string that has all
the needed info to check against a future password
The default settings for opslimit and memlimit are those deemed
correct for the interactive user login case.
:param bytes password:
:param int opslimit:
:param int memlimit:
:rtype: bytes
.. versionadded:: 1.2
"""
return nacl.bindings.crypto_pwhash_str_alg(password,
opslimit,
memlimit,
ALG) | python | def str(password,
opslimit=OPSLIMIT_INTERACTIVE,
memlimit=MEMLIMIT_INTERACTIVE):
return nacl.bindings.crypto_pwhash_str_alg(password,
opslimit,
memlimit,
ALG) | [
"def",
"str",
"(",
"password",
",",
"opslimit",
"=",
"OPSLIMIT_INTERACTIVE",
",",
"memlimit",
"=",
"MEMLIMIT_INTERACTIVE",
")",
":",
"return",
"nacl",
".",
"bindings",
".",
"crypto_pwhash_str_alg",
"(",
"password",
",",
"opslimit",
",",
"memlimit",
",",
"ALG",
... | Hashes a password with a random salt, using the memory-hard
argon2i construct and returning an ascii string that has all
the needed info to check against a future password
The default settings for opslimit and memlimit are those deemed
correct for the interactive user login case.
:param bytes password:
:param int opslimit:
:param int memlimit:
:rtype: bytes
.. versionadded:: 1.2 | [
"Hashes",
"a",
"password",
"with",
"a",
"random",
"salt",
"using",
"the",
"memory",
"-",
"hard",
"argon2i",
"construct",
"and",
"returning",
"an",
"ascii",
"string",
"that",
"has",
"all",
"the",
"needed",
"info",
"to",
"check",
"against",
"a",
"future",
"p... | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/pwhash/argon2i.py#L113-L135 |
228,489 | pyca/pynacl | src/nacl/hashlib.py | scrypt | def scrypt(password, salt='', n=2**20, r=8, p=1,
maxmem=2**25, dklen=64):
"""
Derive a cryptographic key using the scrypt KDF.
Implements the same signature as the ``hashlib.scrypt`` implemented
in cpython version 3.6
"""
return nacl.bindings.crypto_pwhash_scryptsalsa208sha256_ll(
password, salt, n, r, p, maxmem=maxmem, dklen=dklen) | python | def scrypt(password, salt='', n=2**20, r=8, p=1,
maxmem=2**25, dklen=64):
return nacl.bindings.crypto_pwhash_scryptsalsa208sha256_ll(
password, salt, n, r, p, maxmem=maxmem, dklen=dklen) | [
"def",
"scrypt",
"(",
"password",
",",
"salt",
"=",
"''",
",",
"n",
"=",
"2",
"**",
"20",
",",
"r",
"=",
"8",
",",
"p",
"=",
"1",
",",
"maxmem",
"=",
"2",
"**",
"25",
",",
"dklen",
"=",
"64",
")",
":",
"return",
"nacl",
".",
"bindings",
"."... | Derive a cryptographic key using the scrypt KDF.
Implements the same signature as the ``hashlib.scrypt`` implemented
in cpython version 3.6 | [
"Derive",
"a",
"cryptographic",
"key",
"using",
"the",
"scrypt",
"KDF",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/hashlib.py#L112-L121 |
228,490 | pyca/pynacl | src/nacl/bindings/crypto_secretbox.py | crypto_secretbox | def crypto_secretbox(message, nonce, key):
"""
Encrypts and returns the message ``message`` with the secret ``key`` and
the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param key: bytes
:rtype: bytes
"""
if len(key) != crypto_secretbox_KEYBYTES:
raise exc.ValueError("Invalid key")
if len(nonce) != crypto_secretbox_NONCEBYTES:
raise exc.ValueError("Invalid nonce")
padded = b"\x00" * crypto_secretbox_ZEROBYTES + message
ciphertext = ffi.new("unsigned char[]", len(padded))
res = lib.crypto_secretbox(ciphertext, padded, len(padded), nonce, key)
ensure(res == 0, "Encryption failed", raising=exc.CryptoError)
ciphertext = ffi.buffer(ciphertext, len(padded))
return ciphertext[crypto_secretbox_BOXZEROBYTES:] | python | def crypto_secretbox(message, nonce, key):
if len(key) != crypto_secretbox_KEYBYTES:
raise exc.ValueError("Invalid key")
if len(nonce) != crypto_secretbox_NONCEBYTES:
raise exc.ValueError("Invalid nonce")
padded = b"\x00" * crypto_secretbox_ZEROBYTES + message
ciphertext = ffi.new("unsigned char[]", len(padded))
res = lib.crypto_secretbox(ciphertext, padded, len(padded), nonce, key)
ensure(res == 0, "Encryption failed", raising=exc.CryptoError)
ciphertext = ffi.buffer(ciphertext, len(padded))
return ciphertext[crypto_secretbox_BOXZEROBYTES:] | [
"def",
"crypto_secretbox",
"(",
"message",
",",
"nonce",
",",
"key",
")",
":",
"if",
"len",
"(",
"key",
")",
"!=",
"crypto_secretbox_KEYBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Invalid key\"",
")",
"if",
"len",
"(",
"nonce",
")",
"!=",
"cr... | Encrypts and returns the message ``message`` with the secret ``key`` and
the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param key: bytes
:rtype: bytes | [
"Encrypts",
"and",
"returns",
"the",
"message",
"message",
"with",
"the",
"secret",
"key",
"and",
"the",
"nonce",
"nonce",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_secretbox.py#L30-L53 |
228,491 | pyca/pynacl | src/nacl/bindings/crypto_generichash.py | _checkparams | def _checkparams(digest_size, key, salt, person):
"""Check hash paramters"""
ensure(isinstance(key, bytes),
'Key must be a bytes sequence',
raising=exc.TypeError)
ensure(isinstance(salt, bytes),
'Salt must be a bytes sequence',
raising=exc.TypeError)
ensure(isinstance(person, bytes),
'Person must be a bytes sequence',
raising=exc.TypeError)
ensure(isinstance(digest_size, integer_types),
'Digest size must be an integer number',
raising=exc.TypeError)
ensure(digest_size <= crypto_generichash_BYTES_MAX,
_TOOBIG.format("Digest_size", crypto_generichash_BYTES_MAX),
raising=exc.ValueError)
ensure(len(key) <= crypto_generichash_KEYBYTES_MAX,
_OVERLONG.format("Key", crypto_generichash_KEYBYTES_MAX),
raising=exc.ValueError)
ensure(len(salt) <= crypto_generichash_SALTBYTES,
_OVERLONG.format("Salt", crypto_generichash_SALTBYTES),
raising=exc.ValueError)
ensure(len(person) <= crypto_generichash_PERSONALBYTES,
_OVERLONG.format("Person", crypto_generichash_PERSONALBYTES),
raising=exc.ValueError) | python | def _checkparams(digest_size, key, salt, person):
ensure(isinstance(key, bytes),
'Key must be a bytes sequence',
raising=exc.TypeError)
ensure(isinstance(salt, bytes),
'Salt must be a bytes sequence',
raising=exc.TypeError)
ensure(isinstance(person, bytes),
'Person must be a bytes sequence',
raising=exc.TypeError)
ensure(isinstance(digest_size, integer_types),
'Digest size must be an integer number',
raising=exc.TypeError)
ensure(digest_size <= crypto_generichash_BYTES_MAX,
_TOOBIG.format("Digest_size", crypto_generichash_BYTES_MAX),
raising=exc.ValueError)
ensure(len(key) <= crypto_generichash_KEYBYTES_MAX,
_OVERLONG.format("Key", crypto_generichash_KEYBYTES_MAX),
raising=exc.ValueError)
ensure(len(salt) <= crypto_generichash_SALTBYTES,
_OVERLONG.format("Salt", crypto_generichash_SALTBYTES),
raising=exc.ValueError)
ensure(len(person) <= crypto_generichash_PERSONALBYTES,
_OVERLONG.format("Person", crypto_generichash_PERSONALBYTES),
raising=exc.ValueError) | [
"def",
"_checkparams",
"(",
"digest_size",
",",
"key",
",",
"salt",
",",
"person",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"key",
",",
"bytes",
")",
",",
"'Key must be a bytes sequence'",
",",
"raising",
"=",
"exc",
".",
"TypeError",
")",
"ensure",
"("... | Check hash paramters | [
"Check",
"hash",
"paramters"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_generichash.py#L39-L71 |
228,492 | pyca/pynacl | src/nacl/bindings/crypto_generichash.py | generichash_blake2b_salt_personal | def generichash_blake2b_salt_personal(data,
digest_size=crypto_generichash_BYTES,
key=b'', salt=b'', person=b''):
"""One shot hash interface
:param data: the input data to the hash function
:param digest_size: must be at most
:py:data:`.crypto_generichash_BYTES_MAX`;
the default digest size is
:py:data:`.crypto_generichash_BYTES`
:type digest_size: int
:param key: must be at most
:py:data:`.crypto_generichash_KEYBYTES_MAX` long
:type key: bytes
:param salt: must be at most
:py:data:`.crypto_generichash_SALTBYTES` long;
will be zero-padded if needed
:type salt: bytes
:param person: must be at most
:py:data:`.crypto_generichash_PERSONALBYTES` long:
will be zero-padded if needed
:type person: bytes
:return: digest_size long digest
:rtype: bytes
"""
_checkparams(digest_size, key, salt, person)
ensure(isinstance(data, bytes),
'Input data must be a bytes sequence',
raising=exc.TypeError)
digest = ffi.new("unsigned char[]", digest_size)
# both _salt and _personal must be zero-padded to the correct length
_salt = ffi.new("unsigned char []", crypto_generichash_SALTBYTES)
_person = ffi.new("unsigned char []", crypto_generichash_PERSONALBYTES)
ffi.memmove(_salt, salt, len(salt))
ffi.memmove(_person, person, len(person))
rc = lib.crypto_generichash_blake2b_salt_personal(digest, digest_size,
data, len(data),
key, len(key),
_salt, _person)
ensure(rc == 0, 'Unexpected failure',
raising=exc.RuntimeError)
return ffi.buffer(digest, digest_size)[:] | python | def generichash_blake2b_salt_personal(data,
digest_size=crypto_generichash_BYTES,
key=b'', salt=b'', person=b''):
_checkparams(digest_size, key, salt, person)
ensure(isinstance(data, bytes),
'Input data must be a bytes sequence',
raising=exc.TypeError)
digest = ffi.new("unsigned char[]", digest_size)
# both _salt and _personal must be zero-padded to the correct length
_salt = ffi.new("unsigned char []", crypto_generichash_SALTBYTES)
_person = ffi.new("unsigned char []", crypto_generichash_PERSONALBYTES)
ffi.memmove(_salt, salt, len(salt))
ffi.memmove(_person, person, len(person))
rc = lib.crypto_generichash_blake2b_salt_personal(digest, digest_size,
data, len(data),
key, len(key),
_salt, _person)
ensure(rc == 0, 'Unexpected failure',
raising=exc.RuntimeError)
return ffi.buffer(digest, digest_size)[:] | [
"def",
"generichash_blake2b_salt_personal",
"(",
"data",
",",
"digest_size",
"=",
"crypto_generichash_BYTES",
",",
"key",
"=",
"b''",
",",
"salt",
"=",
"b''",
",",
"person",
"=",
"b''",
")",
":",
"_checkparams",
"(",
"digest_size",
",",
"key",
",",
"salt",
"... | One shot hash interface
:param data: the input data to the hash function
:param digest_size: must be at most
:py:data:`.crypto_generichash_BYTES_MAX`;
the default digest size is
:py:data:`.crypto_generichash_BYTES`
:type digest_size: int
:param key: must be at most
:py:data:`.crypto_generichash_KEYBYTES_MAX` long
:type key: bytes
:param salt: must be at most
:py:data:`.crypto_generichash_SALTBYTES` long;
will be zero-padded if needed
:type salt: bytes
:param person: must be at most
:py:data:`.crypto_generichash_PERSONALBYTES` long:
will be zero-padded if needed
:type person: bytes
:return: digest_size long digest
:rtype: bytes | [
"One",
"shot",
"hash",
"interface"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_generichash.py#L74-L122 |
228,493 | pyca/pynacl | src/nacl/bindings/crypto_generichash.py | generichash_blake2b_init | def generichash_blake2b_init(key=b'', salt=b'',
person=b'',
digest_size=crypto_generichash_BYTES):
"""
Create a new initialized blake2b hash state
:param key: must be at most
:py:data:`.crypto_generichash_KEYBYTES_MAX` long
:type key: bytes
:param salt: must be at most
:py:data:`.crypto_generichash_SALTBYTES` long;
will be zero-padded if needed
:type salt: bytes
:param person: must be at most
:py:data:`.crypto_generichash_PERSONALBYTES` long:
will be zero-padded if needed
:type person: bytes
:param digest_size: must be at most
:py:data:`.crypto_generichash_BYTES_MAX`;
the default digest size is
:py:data:`.crypto_generichash_BYTES`
:type digest_size: int
:return: a initialized :py:class:`.Blake2State`
:rtype: object
"""
_checkparams(digest_size, key, salt, person)
state = Blake2State(digest_size)
# both _salt and _personal must be zero-padded to the correct length
_salt = ffi.new("unsigned char []", crypto_generichash_SALTBYTES)
_person = ffi.new("unsigned char []", crypto_generichash_PERSONALBYTES)
ffi.memmove(_salt, salt, len(salt))
ffi.memmove(_person, person, len(person))
rc = lib.crypto_generichash_blake2b_init_salt_personal(state._statebuf,
key, len(key),
digest_size,
_salt, _person)
ensure(rc == 0, 'Unexpected failure',
raising=exc.RuntimeError)
return state | python | def generichash_blake2b_init(key=b'', salt=b'',
person=b'',
digest_size=crypto_generichash_BYTES):
_checkparams(digest_size, key, salt, person)
state = Blake2State(digest_size)
# both _salt and _personal must be zero-padded to the correct length
_salt = ffi.new("unsigned char []", crypto_generichash_SALTBYTES)
_person = ffi.new("unsigned char []", crypto_generichash_PERSONALBYTES)
ffi.memmove(_salt, salt, len(salt))
ffi.memmove(_person, person, len(person))
rc = lib.crypto_generichash_blake2b_init_salt_personal(state._statebuf,
key, len(key),
digest_size,
_salt, _person)
ensure(rc == 0, 'Unexpected failure',
raising=exc.RuntimeError)
return state | [
"def",
"generichash_blake2b_init",
"(",
"key",
"=",
"b''",
",",
"salt",
"=",
"b''",
",",
"person",
"=",
"b''",
",",
"digest_size",
"=",
"crypto_generichash_BYTES",
")",
":",
"_checkparams",
"(",
"digest_size",
",",
"key",
",",
"salt",
",",
"person",
")",
"... | Create a new initialized blake2b hash state
:param key: must be at most
:py:data:`.crypto_generichash_KEYBYTES_MAX` long
:type key: bytes
:param salt: must be at most
:py:data:`.crypto_generichash_SALTBYTES` long;
will be zero-padded if needed
:type salt: bytes
:param person: must be at most
:py:data:`.crypto_generichash_PERSONALBYTES` long:
will be zero-padded if needed
:type person: bytes
:param digest_size: must be at most
:py:data:`.crypto_generichash_BYTES_MAX`;
the default digest size is
:py:data:`.crypto_generichash_BYTES`
:type digest_size: int
:return: a initialized :py:class:`.Blake2State`
:rtype: object | [
"Create",
"a",
"new",
"initialized",
"blake2b",
"hash",
"state"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_generichash.py#L151-L195 |
228,494 | pyca/pynacl | src/nacl/bindings/crypto_generichash.py | generichash_blake2b_update | def generichash_blake2b_update(state, data):
"""Update the blake2b hash state
:param state: a initialized Blake2bState object as returned from
:py:func:`.crypto_generichash_blake2b_init`
:type state: :py:class:`.Blake2State`
:param data:
:type data: bytes
"""
ensure(isinstance(state, Blake2State),
'State must be a Blake2State object',
raising=exc.TypeError)
ensure(isinstance(data, bytes),
'Input data must be a bytes sequence',
raising=exc.TypeError)
rc = lib.crypto_generichash_blake2b_update(state._statebuf,
data, len(data))
ensure(rc == 0, 'Unexpected failure',
raising=exc.RuntimeError) | python | def generichash_blake2b_update(state, data):
ensure(isinstance(state, Blake2State),
'State must be a Blake2State object',
raising=exc.TypeError)
ensure(isinstance(data, bytes),
'Input data must be a bytes sequence',
raising=exc.TypeError)
rc = lib.crypto_generichash_blake2b_update(state._statebuf,
data, len(data))
ensure(rc == 0, 'Unexpected failure',
raising=exc.RuntimeError) | [
"def",
"generichash_blake2b_update",
"(",
"state",
",",
"data",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"state",
",",
"Blake2State",
")",
",",
"'State must be a Blake2State object'",
",",
"raising",
"=",
"exc",
".",
"TypeError",
")",
"ensure",
"(",
"isinstan... | Update the blake2b hash state
:param state: a initialized Blake2bState object as returned from
:py:func:`.crypto_generichash_blake2b_init`
:type state: :py:class:`.Blake2State`
:param data:
:type data: bytes | [
"Update",
"the",
"blake2b",
"hash",
"state"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_generichash.py#L198-L219 |
228,495 | pyca/pynacl | src/nacl/bindings/crypto_generichash.py | generichash_blake2b_final | def generichash_blake2b_final(state):
"""Finalize the blake2b hash state and return the digest.
:param state: a initialized Blake2bState object as returned from
:py:func:`.crypto_generichash_blake2b_init`
:type state: :py:class:`.Blake2State`
:return: the blake2 digest of the passed-in data stream
:rtype: bytes
"""
ensure(isinstance(state, Blake2State),
'State must be a Blake2State object',
raising=exc.TypeError)
_digest = ffi.new("unsigned char[]", crypto_generichash_BYTES_MAX)
rc = lib.crypto_generichash_blake2b_final(state._statebuf,
_digest, state.digest_size)
ensure(rc == 0, 'Unexpected failure',
raising=exc.RuntimeError)
return ffi.buffer(_digest, state.digest_size)[:] | python | def generichash_blake2b_final(state):
ensure(isinstance(state, Blake2State),
'State must be a Blake2State object',
raising=exc.TypeError)
_digest = ffi.new("unsigned char[]", crypto_generichash_BYTES_MAX)
rc = lib.crypto_generichash_blake2b_final(state._statebuf,
_digest, state.digest_size)
ensure(rc == 0, 'Unexpected failure',
raising=exc.RuntimeError)
return ffi.buffer(_digest, state.digest_size)[:] | [
"def",
"generichash_blake2b_final",
"(",
"state",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"state",
",",
"Blake2State",
")",
",",
"'State must be a Blake2State object'",
",",
"raising",
"=",
"exc",
".",
"TypeError",
")",
"_digest",
"=",
"ffi",
".",
"new",
"... | Finalize the blake2b hash state and return the digest.
:param state: a initialized Blake2bState object as returned from
:py:func:`.crypto_generichash_blake2b_init`
:type state: :py:class:`.Blake2State`
:return: the blake2 digest of the passed-in data stream
:rtype: bytes | [
"Finalize",
"the",
"blake2b",
"hash",
"state",
"and",
"return",
"the",
"digest",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_generichash.py#L222-L242 |
228,496 | pyca/pynacl | src/nacl/bindings/crypto_secretstream.py | crypto_secretstream_xchacha20poly1305_init_push | def crypto_secretstream_xchacha20poly1305_init_push(state, key):
"""
Initialize a crypto_secretstream_xchacha20poly1305 encryption buffer.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
:param key: must be
:data:`.crypto_secretstream_xchacha20poly1305_KEYBYTES` long
:type key: bytes
:return: header
:rtype: bytes
"""
ensure(
isinstance(state, crypto_secretstream_xchacha20poly1305_state),
'State must be a crypto_secretstream_xchacha20poly1305_state object',
raising=exc.TypeError,
)
ensure(
isinstance(key, bytes),
'Key must be a bytes sequence',
raising=exc.TypeError,
)
ensure(
len(key) == crypto_secretstream_xchacha20poly1305_KEYBYTES,
'Invalid key length',
raising=exc.ValueError,
)
headerbuf = ffi.new(
"unsigned char []",
crypto_secretstream_xchacha20poly1305_HEADERBYTES,
)
rc = lib.crypto_secretstream_xchacha20poly1305_init_push(
state.statebuf, headerbuf, key)
ensure(rc == 0, 'Unexpected failure', raising=exc.RuntimeError)
return ffi.buffer(headerbuf)[:] | python | def crypto_secretstream_xchacha20poly1305_init_push(state, key):
ensure(
isinstance(state, crypto_secretstream_xchacha20poly1305_state),
'State must be a crypto_secretstream_xchacha20poly1305_state object',
raising=exc.TypeError,
)
ensure(
isinstance(key, bytes),
'Key must be a bytes sequence',
raising=exc.TypeError,
)
ensure(
len(key) == crypto_secretstream_xchacha20poly1305_KEYBYTES,
'Invalid key length',
raising=exc.ValueError,
)
headerbuf = ffi.new(
"unsigned char []",
crypto_secretstream_xchacha20poly1305_HEADERBYTES,
)
rc = lib.crypto_secretstream_xchacha20poly1305_init_push(
state.statebuf, headerbuf, key)
ensure(rc == 0, 'Unexpected failure', raising=exc.RuntimeError)
return ffi.buffer(headerbuf)[:] | [
"def",
"crypto_secretstream_xchacha20poly1305_init_push",
"(",
"state",
",",
"key",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"state",
",",
"crypto_secretstream_xchacha20poly1305_state",
")",
",",
"'State must be a crypto_secretstream_xchacha20poly1305_state object'",
",",
"r... | Initialize a crypto_secretstream_xchacha20poly1305 encryption buffer.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
:param key: must be
:data:`.crypto_secretstream_xchacha20poly1305_KEYBYTES` long
:type key: bytes
:return: header
:rtype: bytes | [
"Initialize",
"a",
"crypto_secretstream_xchacha20poly1305",
"encryption",
"buffer",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_secretstream.py#L76-L114 |
228,497 | pyca/pynacl | src/nacl/bindings/crypto_secretstream.py | crypto_secretstream_xchacha20poly1305_push | def crypto_secretstream_xchacha20poly1305_push(
state,
m,
ad=None,
tag=crypto_secretstream_xchacha20poly1305_TAG_MESSAGE,
):
"""
Add an encrypted message to the secret stream.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
:param m: the message to encrypt, the maximum length of an individual
message is
:data:`.crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX`.
:type m: bytes
:param ad: additional data to include in the authentication tag
:type ad: bytes or None
:param tag: the message tag, usually
:data:`.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE` or
:data:`.crypto_secretstream_xchacha20poly1305_TAG_FINAL`.
:type tag: int
:return: ciphertext
:rtype: bytes
"""
ensure(
isinstance(state, crypto_secretstream_xchacha20poly1305_state),
'State must be a crypto_secretstream_xchacha20poly1305_state object',
raising=exc.TypeError,
)
ensure(isinstance(m, bytes), 'Message is not bytes', raising=exc.TypeError)
ensure(
len(m) <= crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX,
'Message is too long',
raising=exc.ValueError,
)
ensure(
ad is None or isinstance(ad, bytes),
'Additional data must be bytes or None',
raising=exc.TypeError,
)
clen = len(m) + crypto_secretstream_xchacha20poly1305_ABYTES
if state.rawbuf is None or len(state.rawbuf) < clen:
state.rawbuf = ffi.new('unsigned char[]', clen)
if ad is None:
ad = ffi.NULL
adlen = 0
else:
adlen = len(ad)
rc = lib.crypto_secretstream_xchacha20poly1305_push(
state.statebuf,
state.rawbuf, ffi.NULL,
m, len(m),
ad, adlen,
tag,
)
ensure(rc == 0, 'Unexpected failure', raising=exc.RuntimeError)
return ffi.buffer(state.rawbuf, clen)[:] | python | def crypto_secretstream_xchacha20poly1305_push(
state,
m,
ad=None,
tag=crypto_secretstream_xchacha20poly1305_TAG_MESSAGE,
):
ensure(
isinstance(state, crypto_secretstream_xchacha20poly1305_state),
'State must be a crypto_secretstream_xchacha20poly1305_state object',
raising=exc.TypeError,
)
ensure(isinstance(m, bytes), 'Message is not bytes', raising=exc.TypeError)
ensure(
len(m) <= crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX,
'Message is too long',
raising=exc.ValueError,
)
ensure(
ad is None or isinstance(ad, bytes),
'Additional data must be bytes or None',
raising=exc.TypeError,
)
clen = len(m) + crypto_secretstream_xchacha20poly1305_ABYTES
if state.rawbuf is None or len(state.rawbuf) < clen:
state.rawbuf = ffi.new('unsigned char[]', clen)
if ad is None:
ad = ffi.NULL
adlen = 0
else:
adlen = len(ad)
rc = lib.crypto_secretstream_xchacha20poly1305_push(
state.statebuf,
state.rawbuf, ffi.NULL,
m, len(m),
ad, adlen,
tag,
)
ensure(rc == 0, 'Unexpected failure', raising=exc.RuntimeError)
return ffi.buffer(state.rawbuf, clen)[:] | [
"def",
"crypto_secretstream_xchacha20poly1305_push",
"(",
"state",
",",
"m",
",",
"ad",
"=",
"None",
",",
"tag",
"=",
"crypto_secretstream_xchacha20poly1305_TAG_MESSAGE",
",",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"state",
",",
"crypto_secretstream_xchacha20poly13... | Add an encrypted message to the secret stream.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
:param m: the message to encrypt, the maximum length of an individual
message is
:data:`.crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX`.
:type m: bytes
:param ad: additional data to include in the authentication tag
:type ad: bytes or None
:param tag: the message tag, usually
:data:`.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE` or
:data:`.crypto_secretstream_xchacha20poly1305_TAG_FINAL`.
:type tag: int
:return: ciphertext
:rtype: bytes | [
"Add",
"an",
"encrypted",
"message",
"to",
"the",
"secret",
"stream",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_secretstream.py#L117-L178 |
228,498 | pyca/pynacl | src/nacl/bindings/crypto_secretstream.py | crypto_secretstream_xchacha20poly1305_init_pull | def crypto_secretstream_xchacha20poly1305_init_pull(state, header, key):
"""
Initialize a crypto_secretstream_xchacha20poly1305 decryption buffer.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
:param header: must be
:data:`.crypto_secretstream_xchacha20poly1305_HEADERBYTES` long
:type header: bytes
:param key: must be
:data:`.crypto_secretstream_xchacha20poly1305_KEYBYTES` long
:type key: bytes
"""
ensure(
isinstance(state, crypto_secretstream_xchacha20poly1305_state),
'State must be a crypto_secretstream_xchacha20poly1305_state object',
raising=exc.TypeError,
)
ensure(
isinstance(header, bytes),
'Header must be a bytes sequence',
raising=exc.TypeError,
)
ensure(
len(header) == crypto_secretstream_xchacha20poly1305_HEADERBYTES,
'Invalid header length',
raising=exc.ValueError,
)
ensure(
isinstance(key, bytes),
'Key must be a bytes sequence',
raising=exc.TypeError,
)
ensure(
len(key) == crypto_secretstream_xchacha20poly1305_KEYBYTES,
'Invalid key length',
raising=exc.ValueError,
)
if state.tagbuf is None:
state.tagbuf = ffi.new('unsigned char *')
rc = lib.crypto_secretstream_xchacha20poly1305_init_pull(
state.statebuf, header, key)
ensure(rc == 0, 'Unexpected failure', raising=exc.RuntimeError) | python | def crypto_secretstream_xchacha20poly1305_init_pull(state, header, key):
ensure(
isinstance(state, crypto_secretstream_xchacha20poly1305_state),
'State must be a crypto_secretstream_xchacha20poly1305_state object',
raising=exc.TypeError,
)
ensure(
isinstance(header, bytes),
'Header must be a bytes sequence',
raising=exc.TypeError,
)
ensure(
len(header) == crypto_secretstream_xchacha20poly1305_HEADERBYTES,
'Invalid header length',
raising=exc.ValueError,
)
ensure(
isinstance(key, bytes),
'Key must be a bytes sequence',
raising=exc.TypeError,
)
ensure(
len(key) == crypto_secretstream_xchacha20poly1305_KEYBYTES,
'Invalid key length',
raising=exc.ValueError,
)
if state.tagbuf is None:
state.tagbuf = ffi.new('unsigned char *')
rc = lib.crypto_secretstream_xchacha20poly1305_init_pull(
state.statebuf, header, key)
ensure(rc == 0, 'Unexpected failure', raising=exc.RuntimeError) | [
"def",
"crypto_secretstream_xchacha20poly1305_init_pull",
"(",
"state",
",",
"header",
",",
"key",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"state",
",",
"crypto_secretstream_xchacha20poly1305_state",
")",
",",
"'State must be a crypto_secretstream_xchacha20poly1305_state ob... | Initialize a crypto_secretstream_xchacha20poly1305 decryption buffer.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
:param header: must be
:data:`.crypto_secretstream_xchacha20poly1305_HEADERBYTES` long
:type header: bytes
:param key: must be
:data:`.crypto_secretstream_xchacha20poly1305_KEYBYTES` long
:type key: bytes | [
"Initialize",
"a",
"crypto_secretstream_xchacha20poly1305",
"decryption",
"buffer",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_secretstream.py#L181-L226 |
228,499 | pyca/pynacl | src/nacl/bindings/crypto_secretstream.py | crypto_secretstream_xchacha20poly1305_pull | def crypto_secretstream_xchacha20poly1305_pull(state, c, ad=None):
"""
Read a decrypted message from the secret stream.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
:param c: the ciphertext to decrypt, the maximum length of an individual
ciphertext is
:data:`.crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX` +
:data:`.crypto_secretstream_xchacha20poly1305_ABYTES`.
:type c: bytes
:param ad: additional data to include in the authentication tag
:type ad: bytes or None
:return: (message, tag)
:rtype: (bytes, int)
"""
ensure(
isinstance(state, crypto_secretstream_xchacha20poly1305_state),
'State must be a crypto_secretstream_xchacha20poly1305_state object',
raising=exc.TypeError,
)
ensure(
state.tagbuf is not None,
(
'State must be initialized using '
'crypto_secretstream_xchacha20poly1305_init_pull'
),
raising=exc.ValueError,
)
ensure(
isinstance(c, bytes),
'Ciphertext is not bytes',
raising=exc.TypeError,
)
ensure(
len(c) > crypto_secretstream_xchacha20poly1305_ABYTES,
'Ciphertext is too short',
raising=exc.ValueError,
)
ensure(
len(c) <= (
crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX +
crypto_secretstream_xchacha20poly1305_ABYTES
),
'Ciphertext is too long',
raising=exc.ValueError,
)
ensure(
ad is None or isinstance(ad, bytes),
'Additional data must be bytes or None',
raising=exc.TypeError,
)
mlen = len(c) - crypto_secretstream_xchacha20poly1305_ABYTES
if state.rawbuf is None or len(state.rawbuf) < mlen:
state.rawbuf = ffi.new('unsigned char[]', mlen)
if ad is None:
ad = ffi.NULL
adlen = 0
else:
adlen = len(ad)
rc = lib.crypto_secretstream_xchacha20poly1305_pull(
state.statebuf,
state.rawbuf, ffi.NULL,
state.tagbuf,
c, len(c),
ad, adlen,
)
ensure(rc == 0, 'Unexpected failure', raising=exc.RuntimeError)
return (ffi.buffer(state.rawbuf, mlen)[:], int(state.tagbuf[0])) | python | def crypto_secretstream_xchacha20poly1305_pull(state, c, ad=None):
ensure(
isinstance(state, crypto_secretstream_xchacha20poly1305_state),
'State must be a crypto_secretstream_xchacha20poly1305_state object',
raising=exc.TypeError,
)
ensure(
state.tagbuf is not None,
(
'State must be initialized using '
'crypto_secretstream_xchacha20poly1305_init_pull'
),
raising=exc.ValueError,
)
ensure(
isinstance(c, bytes),
'Ciphertext is not bytes',
raising=exc.TypeError,
)
ensure(
len(c) > crypto_secretstream_xchacha20poly1305_ABYTES,
'Ciphertext is too short',
raising=exc.ValueError,
)
ensure(
len(c) <= (
crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX +
crypto_secretstream_xchacha20poly1305_ABYTES
),
'Ciphertext is too long',
raising=exc.ValueError,
)
ensure(
ad is None or isinstance(ad, bytes),
'Additional data must be bytes or None',
raising=exc.TypeError,
)
mlen = len(c) - crypto_secretstream_xchacha20poly1305_ABYTES
if state.rawbuf is None or len(state.rawbuf) < mlen:
state.rawbuf = ffi.new('unsigned char[]', mlen)
if ad is None:
ad = ffi.NULL
adlen = 0
else:
adlen = len(ad)
rc = lib.crypto_secretstream_xchacha20poly1305_pull(
state.statebuf,
state.rawbuf, ffi.NULL,
state.tagbuf,
c, len(c),
ad, adlen,
)
ensure(rc == 0, 'Unexpected failure', raising=exc.RuntimeError)
return (ffi.buffer(state.rawbuf, mlen)[:], int(state.tagbuf[0])) | [
"def",
"crypto_secretstream_xchacha20poly1305_pull",
"(",
"state",
",",
"c",
",",
"ad",
"=",
"None",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"state",
",",
"crypto_secretstream_xchacha20poly1305_state",
")",
",",
"'State must be a crypto_secretstream_xchacha20poly1305_st... | Read a decrypted message from the secret stream.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
:param c: the ciphertext to decrypt, the maximum length of an individual
ciphertext is
:data:`.crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX` +
:data:`.crypto_secretstream_xchacha20poly1305_ABYTES`.
:type c: bytes
:param ad: additional data to include in the authentication tag
:type ad: bytes or None
:return: (message, tag)
:rtype: (bytes, int) | [
"Read",
"a",
"decrypted",
"message",
"from",
"the",
"secret",
"stream",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_secretstream.py#L229-L302 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.