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 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
224,600 | lucasb-eyer/pydensecrf | pydensecrf/utils.py | create_pairwise_gaussian | def create_pairwise_gaussian(sdims, shape):
"""
Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseGaussian`.
shape: list or tuple
The shape the CRF has.
"""
# create mesh
hcord_range = [range(s) for s in shape]
mesh = np.array(np.meshgrid(*hcord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
return mesh.reshape([len(sdims), -1]) | python | def create_pairwise_gaussian(sdims, shape):
"""
Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseGaussian`.
shape: list or tuple
The shape the CRF has.
"""
# create mesh
hcord_range = [range(s) for s in shape]
mesh = np.array(np.meshgrid(*hcord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
return mesh.reshape([len(sdims), -1]) | [
"def",
"create_pairwise_gaussian",
"(",
"sdims",
",",
"shape",
")",
":",
"# create mesh",
"hcord_range",
"=",
"[",
"range",
"(",
"s",
")",
"for",
"s",
"in",
"shape",
"]",
"mesh",
"=",
"np",
".",
"array",
"(",
"np",
".",
"meshgrid",
"(",
"*",
"hcord_ran... | Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseGaussian`.
shape: list or tuple
The shape the CRF has. | [
"Util",
"function",
"that",
"create",
"pairwise",
"gaussian",
"potentials",
".",
"This",
"works",
"for",
"all",
"image",
"dimensions",
".",
"For",
"the",
"2D",
"case",
"does",
"the",
"same",
"as",
"DenseCRF2D",
".",
"addPairwiseGaussian",
"."
] | 4d5343c398d75d7ebae34f51a47769084ba3a613 | https://github.com/lucasb-eyer/pydensecrf/blob/4d5343c398d75d7ebae34f51a47769084ba3a613/pydensecrf/utils.py#L89-L111 |
224,601 | lucasb-eyer/pydensecrf | pydensecrf/utils.py | create_pairwise_bilateral | def create_pairwise_bilateral(sdims, schan, img, chdim=-1):
"""
Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseBilateral`.
schan: list or tuple
The scaling factors per channel in the image. This is referred to
`srgb` in `DenseCRF2D.addPairwiseBilateral`.
img: numpy.array
The input image.
chdim: int, optional
This specifies where the channel dimension is in the image. For
example `chdim=2` for a RGB image of size (240, 300, 3). If the
image has no channel dimension (e.g. it has only one channel) use
`chdim=-1`.
"""
# Put channel dim in right position
if chdim == -1:
# We don't have a channel, add a new axis
im_feat = img[np.newaxis].astype(np.float32)
else:
# Put the channel dim as axis 0, all others stay relatively the same
im_feat = np.rollaxis(img, chdim).astype(np.float32)
# scale image features per channel
# Allow for a single number in `schan` to broadcast across all channels:
if isinstance(schan, Number):
im_feat /= schan
else:
for i, s in enumerate(schan):
im_feat[i] /= s
# create a mesh
cord_range = [range(s) for s in im_feat.shape[1:]]
mesh = np.array(np.meshgrid(*cord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
feats = np.concatenate([mesh, im_feat])
return feats.reshape([feats.shape[0], -1]) | python | def create_pairwise_bilateral(sdims, schan, img, chdim=-1):
"""
Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseBilateral`.
schan: list or tuple
The scaling factors per channel in the image. This is referred to
`srgb` in `DenseCRF2D.addPairwiseBilateral`.
img: numpy.array
The input image.
chdim: int, optional
This specifies where the channel dimension is in the image. For
example `chdim=2` for a RGB image of size (240, 300, 3). If the
image has no channel dimension (e.g. it has only one channel) use
`chdim=-1`.
"""
# Put channel dim in right position
if chdim == -1:
# We don't have a channel, add a new axis
im_feat = img[np.newaxis].astype(np.float32)
else:
# Put the channel dim as axis 0, all others stay relatively the same
im_feat = np.rollaxis(img, chdim).astype(np.float32)
# scale image features per channel
# Allow for a single number in `schan` to broadcast across all channels:
if isinstance(schan, Number):
im_feat /= schan
else:
for i, s in enumerate(schan):
im_feat[i] /= s
# create a mesh
cord_range = [range(s) for s in im_feat.shape[1:]]
mesh = np.array(np.meshgrid(*cord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
feats = np.concatenate([mesh, im_feat])
return feats.reshape([feats.shape[0], -1]) | [
"def",
"create_pairwise_bilateral",
"(",
"sdims",
",",
"schan",
",",
"img",
",",
"chdim",
"=",
"-",
"1",
")",
":",
"# Put channel dim in right position",
"if",
"chdim",
"==",
"-",
"1",
":",
"# We don't have a channel, add a new axis",
"im_feat",
"=",
"img",
"[",
... | Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseBilateral`.
schan: list or tuple
The scaling factors per channel in the image. This is referred to
`srgb` in `DenseCRF2D.addPairwiseBilateral`.
img: numpy.array
The input image.
chdim: int, optional
This specifies where the channel dimension is in the image. For
example `chdim=2` for a RGB image of size (240, 300, 3). If the
image has no channel dimension (e.g. it has only one channel) use
`chdim=-1`. | [
"Util",
"function",
"that",
"create",
"pairwise",
"bilateral",
"potentials",
".",
"This",
"works",
"for",
"all",
"image",
"dimensions",
".",
"For",
"the",
"2D",
"case",
"does",
"the",
"same",
"as",
"DenseCRF2D",
".",
"addPairwiseBilateral",
"."
] | 4d5343c398d75d7ebae34f51a47769084ba3a613 | https://github.com/lucasb-eyer/pydensecrf/blob/4d5343c398d75d7ebae34f51a47769084ba3a613/pydensecrf/utils.py#L114-L162 |
224,602 | deanmalmgren/textract | textract/parsers/odt_parser.py | Parser.to_string | def to_string(self):
""" Converts the document to a string. """
buff = u""
for child in self.content.iter():
if child.tag in [self.qn('text:p'), self.qn('text:h')]:
buff += self.text_to_string(child) + "\n"
# remove last newline char
if buff:
buff = buff[:-1]
return buff | python | def to_string(self):
""" Converts the document to a string. """
buff = u""
for child in self.content.iter():
if child.tag in [self.qn('text:p'), self.qn('text:h')]:
buff += self.text_to_string(child) + "\n"
# remove last newline char
if buff:
buff = buff[:-1]
return buff | [
"def",
"to_string",
"(",
"self",
")",
":",
"buff",
"=",
"u\"\"",
"for",
"child",
"in",
"self",
".",
"content",
".",
"iter",
"(",
")",
":",
"if",
"child",
".",
"tag",
"in",
"[",
"self",
".",
"qn",
"(",
"'text:p'",
")",
",",
"self",
".",
"qn",
"(... | Converts the document to a string. | [
"Converts",
"the",
"document",
"to",
"a",
"string",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/odt_parser.py#L19-L28 |
224,603 | deanmalmgren/textract | textract/parsers/odt_parser.py | Parser.qn | def qn(self, namespace):
"""Connect tag prefix to longer namespace"""
nsmap = {
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
}
spl = namespace.split(':')
return '{{{}}}{}'.format(nsmap[spl[0]], spl[1]) | python | def qn(self, namespace):
"""Connect tag prefix to longer namespace"""
nsmap = {
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
}
spl = namespace.split(':')
return '{{{}}}{}'.format(nsmap[spl[0]], spl[1]) | [
"def",
"qn",
"(",
"self",
",",
"namespace",
")",
":",
"nsmap",
"=",
"{",
"'text'",
":",
"'urn:oasis:names:tc:opendocument:xmlns:text:1.0'",
",",
"}",
"spl",
"=",
"namespace",
".",
"split",
"(",
"':'",
")",
"return",
"'{{{}}}{}'",
".",
"format",
"(",
"nsmap",... | Connect tag prefix to longer namespace | [
"Connect",
"tag",
"prefix",
"to",
"longer",
"namespace"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/odt_parser.py#L51-L57 |
224,604 | deanmalmgren/textract | textract/cli.py | get_parser | def get_parser():
"""Initialize the parser for the command line interface and bind the
autocompletion functionality"""
# initialize the parser
parser = argparse.ArgumentParser(
description=(
'Command line tool for extracting text from any document. '
) % locals(),
)
# define the command line options here
parser.add_argument(
'filename', help='Filename to extract text.',
).completer = argcomplete.completers.FilesCompleter
parser.add_argument(
'-e', '--encoding', type=str, default=DEFAULT_ENCODING,
choices=_get_available_encodings(),
help='Specify the encoding of the output.',
)
parser.add_argument(
'--extension', type=str, default=None,
choices=_get_available_extensions(),
help='Specify the extension of the file.',
)
parser.add_argument(
'-m', '--method', default='',
help='Specify a method of extraction for formats that support it',
)
parser.add_argument(
'-o', '--output', type=FileType('wb'), default='-',
help='Output raw text in this file',
)
parser.add_argument(
'-O', '--option', type=str, action=AddToNamespaceAction,
help=(
'Add arbitrary options to various parsers of the form '
'KEYWORD=VALUE. A full list of available KEYWORD options is '
'available at http://bit.ly/textract-options'
),
)
parser.add_argument(
'-v', '--version', action='version', version='%(prog)s '+VERSION,
)
# enable autocompletion with argcomplete
argcomplete.autocomplete(parser)
return parser | python | def get_parser():
"""Initialize the parser for the command line interface and bind the
autocompletion functionality"""
# initialize the parser
parser = argparse.ArgumentParser(
description=(
'Command line tool for extracting text from any document. '
) % locals(),
)
# define the command line options here
parser.add_argument(
'filename', help='Filename to extract text.',
).completer = argcomplete.completers.FilesCompleter
parser.add_argument(
'-e', '--encoding', type=str, default=DEFAULT_ENCODING,
choices=_get_available_encodings(),
help='Specify the encoding of the output.',
)
parser.add_argument(
'--extension', type=str, default=None,
choices=_get_available_extensions(),
help='Specify the extension of the file.',
)
parser.add_argument(
'-m', '--method', default='',
help='Specify a method of extraction for formats that support it',
)
parser.add_argument(
'-o', '--output', type=FileType('wb'), default='-',
help='Output raw text in this file',
)
parser.add_argument(
'-O', '--option', type=str, action=AddToNamespaceAction,
help=(
'Add arbitrary options to various parsers of the form '
'KEYWORD=VALUE. A full list of available KEYWORD options is '
'available at http://bit.ly/textract-options'
),
)
parser.add_argument(
'-v', '--version', action='version', version='%(prog)s '+VERSION,
)
# enable autocompletion with argcomplete
argcomplete.autocomplete(parser)
return parser | [
"def",
"get_parser",
"(",
")",
":",
"# initialize the parser",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"(",
"'Command line tool for extracting text from any document. '",
")",
"%",
"locals",
"(",
")",
",",
")",
"# define the command li... | Initialize the parser for the command line interface and bind the
autocompletion functionality | [
"Initialize",
"the",
"parser",
"for",
"the",
"command",
"line",
"interface",
"and",
"bind",
"the",
"autocompletion",
"functionality"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/cli.py#L45-L93 |
224,605 | deanmalmgren/textract | textract/cli.py | _get_available_encodings | def _get_available_encodings():
"""Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709
"""
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__file__)]
for importer, modname, ispkg in pkgutil.walk_packages(path=paths):
available_encodings.add(modname)
available_encodings = list(available_encodings)
available_encodings.sort()
return available_encodings | python | def _get_available_encodings():
"""Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709
"""
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__file__)]
for importer, modname, ispkg in pkgutil.walk_packages(path=paths):
available_encodings.add(modname)
available_encodings = list(available_encodings)
available_encodings.sort()
return available_encodings | [
"def",
"_get_available_encodings",
"(",
")",
":",
"available_encodings",
"=",
"set",
"(",
"encodings",
".",
"aliases",
".",
"aliases",
".",
"values",
"(",
")",
")",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"encodings",
".",
"__file__",
... | Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709 | [
"Get",
"a",
"list",
"of",
"the",
"available",
"encodings",
"to",
"make",
"it",
"easy",
"to",
"tab",
"-",
"complete",
"the",
"command",
"line",
"interface",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/cli.py#L96-L108 |
224,606 | deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_pdftotext | def extract_pdftotext(self, filename, **kwargs):
"""Extract text from pdfs using the pdftotext command line utility."""
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
return stdout | python | def extract_pdftotext(self, filename, **kwargs):
"""Extract text from pdfs using the pdftotext command line utility."""
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
return stdout | [
"def",
"extract_pdftotext",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'layout'",
"in",
"kwargs",
":",
"args",
"=",
"[",
"'pdftotext'",
",",
"'-layout'",
",",
"filename",
",",
"'-'",
"]",
"else",
":",
"args",
"=",
"[",
"'... | Extract text from pdfs using the pdftotext command line utility. | [
"Extract",
"text",
"from",
"pdfs",
"using",
"the",
"pdftotext",
"command",
"line",
"utility",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L37-L44 |
224,607 | deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_pdfminer | def extract_pdfminer(self, filename, **kwargs):
"""Extract text from pdfs using pdfminer."""
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout | python | def extract_pdfminer(self, filename, **kwargs):
"""Extract text from pdfs using pdfminer."""
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout | [
"def",
"extract_pdfminer",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"stdout",
",",
"_",
"=",
"self",
".",
"run",
"(",
"[",
"'pdf2txt.py'",
",",
"filename",
"]",
")",
"return",
"stdout"
] | Extract text from pdfs using pdfminer. | [
"Extract",
"text",
"from",
"pdfs",
"using",
"pdfminer",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L46-L49 |
224,608 | deanmalmgren/textract | textract/parsers/audio.py | Parser.convert_to_wav | def convert_to_wav(self, filename):
"""
Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results
"""
temp_filename = '{0}.wav'.format(self.temp_filename())
self.run(['sox', '-G', '-c', '1', filename, temp_filename])
return temp_filename | python | def convert_to_wav(self, filename):
"""
Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results
"""
temp_filename = '{0}.wav'.format(self.temp_filename())
self.run(['sox', '-G', '-c', '1', filename, temp_filename])
return temp_filename | [
"def",
"convert_to_wav",
"(",
"self",
",",
"filename",
")",
":",
"temp_filename",
"=",
"'{0}.wav'",
".",
"format",
"(",
"self",
".",
"temp_filename",
"(",
")",
")",
"self",
".",
"run",
"(",
"[",
"'sox'",
",",
"'-G'",
",",
"'-c'",
",",
"'1'",
",",
"fi... | Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results | [
"Uses",
"sox",
"cmdline",
"tool",
"to",
"convert",
"audio",
"file",
"to",
".",
"wav"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/audio.py#L56-L66 |
224,609 | deanmalmgren/textract | textract/parsers/html_parser.py | Parser._visible | def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | python | def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | [
"def",
"_visible",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
".",
"name",
"in",
"self",
".",
"_disallowed_names",
":",
"return",
"False",
"elif",
"re",
".",
"match",
"(",
"u'<!--.*-->'",
",",
"six",
".",
"text_type",
"(",
"element",
".",
... | Used to filter text elements that have invisible text on the page. | [
"Used",
"to",
"filter",
"text",
"elements",
"that",
"have",
"invisible",
"text",
"on",
"the",
"page",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L27-L34 |
224,610 | deanmalmgren/textract | textract/parsers/html_parser.py | Parser._find_any_text | def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text | python | def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text | [
"def",
"_find_any_text",
"(",
"self",
",",
"tag",
")",
":",
"text",
"=",
"''",
"if",
"tag",
"is",
"not",
"None",
":",
"text",
"=",
"six",
".",
"text_type",
"(",
"tag",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'(<[^>]+>)'",
",",
"''",
",",
"text... | Looks for any possible text within given tag. | [
"Looks",
"for",
"any",
"possible",
"text",
"within",
"given",
"tag",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L44-L53 |
224,611 | deanmalmgren/textract | textract/parsers/html_parser.py | Parser._join_inlines | def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup | python | def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup | [
"def",
"_join_inlines",
"(",
"self",
",",
"soup",
")",
":",
"elements",
"=",
"soup",
".",
"find_all",
"(",
"True",
")",
"for",
"elem",
"in",
"elements",
":",
"if",
"self",
".",
"_inline",
"(",
"elem",
")",
":",
"elem",
".",
"unwrap",
"(",
")",
"ret... | Unwraps inline elements defined in self._inline_tags. | [
"Unwraps",
"inline",
"elements",
"defined",
"in",
"self",
".",
"_inline_tags",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L118-L125 |
224,612 | deanmalmgren/textract | textract/parsers/utils.py | ShellParser.temp_filename | def temp_filename(self):
"""Return a unique tempfile name.
"""
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handle, filename = tempfile.mkstemp()
os.close(handle)
return filename | python | def temp_filename(self):
"""Return a unique tempfile name.
"""
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handle, filename = tempfile.mkstemp()
os.close(handle)
return filename | [
"def",
"temp_filename",
"(",
"self",
")",
":",
"# TODO: it would be nice to get this to behave more like a",
"# context so we can make sure these temporary files are",
"# removed, regardless of whether an error occurs or the",
"# program is terminated.",
"handle",
",",
"filename",
"=",
"... | Return a unique tempfile name. | [
"Return",
"a",
"unique",
"tempfile",
"name",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/utils.py#L106-L115 |
224,613 | deanmalmgren/textract | textract/parsers/__init__.py | process | def process(filename, encoding=DEFAULT_ENCODING, extension=None, **kwargs):
"""This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``.
"""
# make sure the filename exists
if not os.path.exists(filename):
raise exceptions.MissingFileError(filename)
# get the filename extension, which is something like .docx for
# example, and import the module dynamically using importlib. This
# is a relative import so the name of the package is necessary
# normally, file extension will be extracted from the file name
# if the file name has no extension, then the user can pass the
# extension as an argument
if extension:
ext = extension
# check if the extension has the leading .
if not ext.startswith('.'):
ext = '.' + ext
ext = ext.lower()
else:
_, ext = os.path.splitext(filename)
ext = ext.lower()
# check the EXTENSION_SYNONYMS dictionary
ext = EXTENSION_SYNONYMS.get(ext, ext)
# to avoid conflicts with packages that are installed globally
# (e.g. python's json module), all extension parser modules have
# the _parser extension
rel_module = ext + _FILENAME_SUFFIX
# If we can't import the module, the file extension isn't currently
# supported
try:
filetype_module = importlib.import_module(
rel_module, 'textract.parsers'
)
except ImportError:
raise exceptions.ExtensionNotSupported(ext)
# do the extraction
parser = filetype_module.Parser()
return parser.process(filename, encoding, **kwargs) | python | def process(filename, encoding=DEFAULT_ENCODING, extension=None, **kwargs):
"""This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``.
"""
# make sure the filename exists
if not os.path.exists(filename):
raise exceptions.MissingFileError(filename)
# get the filename extension, which is something like .docx for
# example, and import the module dynamically using importlib. This
# is a relative import so the name of the package is necessary
# normally, file extension will be extracted from the file name
# if the file name has no extension, then the user can pass the
# extension as an argument
if extension:
ext = extension
# check if the extension has the leading .
if not ext.startswith('.'):
ext = '.' + ext
ext = ext.lower()
else:
_, ext = os.path.splitext(filename)
ext = ext.lower()
# check the EXTENSION_SYNONYMS dictionary
ext = EXTENSION_SYNONYMS.get(ext, ext)
# to avoid conflicts with packages that are installed globally
# (e.g. python's json module), all extension parser modules have
# the _parser extension
rel_module = ext + _FILENAME_SUFFIX
# If we can't import the module, the file extension isn't currently
# supported
try:
filetype_module = importlib.import_module(
rel_module, 'textract.parsers'
)
except ImportError:
raise exceptions.ExtensionNotSupported(ext)
# do the extraction
parser = filetype_module.Parser()
return parser.process(filename, encoding, **kwargs) | [
"def",
"process",
"(",
"filename",
",",
"encoding",
"=",
"DEFAULT_ENCODING",
",",
"extension",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# make sure the filename exists",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"rai... | This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``. | [
"This",
"is",
"the",
"core",
"function",
"used",
"for",
"extracting",
"text",
".",
"It",
"routes",
"the",
"filename",
"to",
"the",
"appropriate",
"parser",
"and",
"returns",
"the",
"extracted",
"text",
"as",
"a",
"byte",
"-",
"string",
"encoded",
"with",
"... | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/__init__.py#L31-L77 |
224,614 | deanmalmgren/textract | textract/parsers/__init__.py | _get_available_extensions | def _get_available_extensions():
"""Get a list of available file extensions to make it easy for
tab-completion and exception handling.
"""
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX + ".py")
ext_re = re.compile(glob_filename.replace('*', "(?P<ext>\w+)"))
for filename in glob.glob(glob_filename):
ext_match = ext_re.match(filename)
ext = ext_match.groups()[0]
extensions.append(ext)
extensions.append('.' + ext)
# from relevant synonyms (don't use the '' synonym)
for ext in EXTENSION_SYNONYMS.keys():
if ext:
extensions.append(ext)
extensions.append(ext.replace('.', '', 1))
extensions.sort()
return extensions | python | def _get_available_extensions():
"""Get a list of available file extensions to make it easy for
tab-completion and exception handling.
"""
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX + ".py")
ext_re = re.compile(glob_filename.replace('*', "(?P<ext>\w+)"))
for filename in glob.glob(glob_filename):
ext_match = ext_re.match(filename)
ext = ext_match.groups()[0]
extensions.append(ext)
extensions.append('.' + ext)
# from relevant synonyms (don't use the '' synonym)
for ext in EXTENSION_SYNONYMS.keys():
if ext:
extensions.append(ext)
extensions.append(ext.replace('.', '', 1))
extensions.sort()
return extensions | [
"def",
"_get_available_extensions",
"(",
")",
":",
"extensions",
"=",
"[",
"]",
"# from filenames",
"parsers_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"glob_filename",
"=",
"os",
".",
"p... | Get a list of available file extensions to make it easy for
tab-completion and exception handling. | [
"Get",
"a",
"list",
"of",
"available",
"file",
"extensions",
"to",
"make",
"it",
"easy",
"for",
"tab",
"-",
"completion",
"and",
"exception",
"handling",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/__init__.py#L80-L102 |
224,615 | deanmalmgren/textract | setup.py | parse_requirements | def parse_requirements(requirements_filename):
"""read in the dependencies from the requirements files
"""
dependencies, dependency_links = [], []
requirements_dir = os.path.dirname(requirements_filename)
with open(requirements_filename, 'r') as stream:
for line in stream:
line = line.strip()
if line.startswith("-r"):
filename = os.path.join(requirements_dir, line[2:].strip())
_dependencies, _dependency_links = parse_requirements(filename)
dependencies.extend(_dependencies)
dependency_links.extend(_dependency_links)
elif line.startswith("http"):
dependency_links.append(line)
else:
package = line.split('#')[0]
if package:
dependencies.append(package)
return dependencies, dependency_links | python | def parse_requirements(requirements_filename):
"""read in the dependencies from the requirements files
"""
dependencies, dependency_links = [], []
requirements_dir = os.path.dirname(requirements_filename)
with open(requirements_filename, 'r') as stream:
for line in stream:
line = line.strip()
if line.startswith("-r"):
filename = os.path.join(requirements_dir, line[2:].strip())
_dependencies, _dependency_links = parse_requirements(filename)
dependencies.extend(_dependencies)
dependency_links.extend(_dependency_links)
elif line.startswith("http"):
dependency_links.append(line)
else:
package = line.split('#')[0]
if package:
dependencies.append(package)
return dependencies, dependency_links | [
"def",
"parse_requirements",
"(",
"requirements_filename",
")",
":",
"dependencies",
",",
"dependency_links",
"=",
"[",
"]",
",",
"[",
"]",
"requirements_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"requirements_filename",
")",
"with",
"open",
"(",
"req... | read in the dependencies from the requirements files | [
"read",
"in",
"the",
"dependencies",
"from",
"the",
"requirements",
"files"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/setup.py#L18-L37 |
224,616 | lyst/lightfm | lightfm/data.py | Dataset.build_interactions | def build_interactions(self, data):
"""
Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
data: iterable of (user_id, item_id) or (user_id, item_id, weight)
An iterable of interactions. The user and item ids will be
translated to internal model indices using the mappings
constructed during the fit call. If weights are not provided
they will be assumed to be 1.0.
Returns
-------
(interactions, weights): COO matrix, COO matrix
Two COO matrices: the interactions matrix
and the corresponding weights matrix.
"""
interactions = _IncrementalCOOMatrix(self.interactions_shape(), np.int32)
weights = _IncrementalCOOMatrix(self.interactions_shape(), np.float32)
for datum in data:
user_idx, item_idx, weight = self._unpack_datum(datum)
interactions.append(user_idx, item_idx, 1)
weights.append(user_idx, item_idx, weight)
return (interactions.tocoo(), weights.tocoo()) | python | def build_interactions(self, data):
"""
Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
data: iterable of (user_id, item_id) or (user_id, item_id, weight)
An iterable of interactions. The user and item ids will be
translated to internal model indices using the mappings
constructed during the fit call. If weights are not provided
they will be assumed to be 1.0.
Returns
-------
(interactions, weights): COO matrix, COO matrix
Two COO matrices: the interactions matrix
and the corresponding weights matrix.
"""
interactions = _IncrementalCOOMatrix(self.interactions_shape(), np.int32)
weights = _IncrementalCOOMatrix(self.interactions_shape(), np.float32)
for datum in data:
user_idx, item_idx, weight = self._unpack_datum(datum)
interactions.append(user_idx, item_idx, 1)
weights.append(user_idx, item_idx, weight)
return (interactions.tocoo(), weights.tocoo()) | [
"def",
"build_interactions",
"(",
"self",
",",
"data",
")",
":",
"interactions",
"=",
"_IncrementalCOOMatrix",
"(",
"self",
".",
"interactions_shape",
"(",
")",
",",
"np",
".",
"int32",
")",
"weights",
"=",
"_IncrementalCOOMatrix",
"(",
"self",
".",
"interacti... | Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
data: iterable of (user_id, item_id) or (user_id, item_id, weight)
An iterable of interactions. The user and item ids will be
translated to internal model indices using the mappings
constructed during the fit call. If weights are not provided
they will be assumed to be 1.0.
Returns
-------
(interactions, weights): COO matrix, COO matrix
Two COO matrices: the interactions matrix
and the corresponding weights matrix. | [
"Build",
"an",
"interaction",
"matrix",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/data.py#L292-L326 |
224,617 | lyst/lightfm | lightfm/data.py | Dataset.mapping | def mapping(self):
"""
Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries
"""
return (
self._user_id_mapping,
self._user_feature_mapping,
self._item_id_mapping,
self._item_feature_mapping,
) | python | def mapping(self):
"""
Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries
"""
return (
self._user_id_mapping,
self._user_feature_mapping,
self._item_id_mapping,
self._item_feature_mapping,
) | [
"def",
"mapping",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_user_id_mapping",
",",
"self",
".",
"_user_feature_mapping",
",",
"self",
".",
"_item_id_mapping",
",",
"self",
".",
"_item_feature_mapping",
",",
")"
] | Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries | [
"Return",
"the",
"constructed",
"mappings",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/data.py#L428-L445 |
224,618 | lyst/lightfm | examples/movielens/data.py | _get_movielens_path | def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip') | python | def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip') | [
"def",
"_get_movielens_path",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"'movielens.zip'",
")"
] | Get path to the movielens dataset file. | [
"Get",
"path",
"to",
"the",
"movielens",
"dataset",
"file",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L12-L18 |
224,619 | lyst/lightfm | examples/movielens/data.py | _download_movielens | def _download_movielens(dest_path):
"""
Download the dataset.
"""
url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'
req = requests.get(url, stream=True)
with open(dest_path, 'wb') as fd:
for chunk in req.iter_content():
fd.write(chunk) | python | def _download_movielens(dest_path):
"""
Download the dataset.
"""
url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'
req = requests.get(url, stream=True)
with open(dest_path, 'wb') as fd:
for chunk in req.iter_content():
fd.write(chunk) | [
"def",
"_download_movielens",
"(",
"dest_path",
")",
":",
"url",
"=",
"'http://files.grouplens.org/datasets/movielens/ml-100k.zip'",
"req",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"with",
"open",
"(",
"dest_path",
",",
"'wb'",
"... | Download the dataset. | [
"Download",
"the",
"dataset",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L21-L31 |
224,620 | lyst/lightfm | examples/movielens/data.py | _get_movie_raw_metadata | def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') | python | def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') | [
"def",
"_get_movie_raw_metadata",
"(",
")",
":",
"path",
"=",
"_get_movielens_path",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"_download_movielens",
"(",
"path",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
... | Get raw lines of the genre file. | [
"Get",
"raw",
"lines",
"of",
"the",
"genre",
"file",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L82-L93 |
224,621 | lyst/lightfm | lightfm/lightfm.py | LightFM._initialize | def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = (
(self.random_state.rand(no_item_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.item_embedding_gradients = np.zeros_like(self.item_embeddings)
self.item_embedding_momentum = np.zeros_like(self.item_embeddings)
self.item_biases = np.zeros(no_item_features, dtype=np.float32)
self.item_bias_gradients = np.zeros_like(self.item_biases)
self.item_bias_momentum = np.zeros_like(self.item_biases)
# Initialise user features.
self.user_embeddings = (
(self.random_state.rand(no_user_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.user_embedding_gradients = np.zeros_like(self.user_embeddings)
self.user_embedding_momentum = np.zeros_like(self.user_embeddings)
self.user_biases = np.zeros(no_user_features, dtype=np.float32)
self.user_bias_gradients = np.zeros_like(self.user_biases)
self.user_bias_momentum = np.zeros_like(self.user_biases)
if self.learning_schedule == "adagrad":
self.item_embedding_gradients += 1
self.item_bias_gradients += 1
self.user_embedding_gradients += 1
self.user_bias_gradients += 1 | python | def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = (
(self.random_state.rand(no_item_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.item_embedding_gradients = np.zeros_like(self.item_embeddings)
self.item_embedding_momentum = np.zeros_like(self.item_embeddings)
self.item_biases = np.zeros(no_item_features, dtype=np.float32)
self.item_bias_gradients = np.zeros_like(self.item_biases)
self.item_bias_momentum = np.zeros_like(self.item_biases)
# Initialise user features.
self.user_embeddings = (
(self.random_state.rand(no_user_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.user_embedding_gradients = np.zeros_like(self.user_embeddings)
self.user_embedding_momentum = np.zeros_like(self.user_embeddings)
self.user_biases = np.zeros(no_user_features, dtype=np.float32)
self.user_bias_gradients = np.zeros_like(self.user_biases)
self.user_bias_momentum = np.zeros_like(self.user_biases)
if self.learning_schedule == "adagrad":
self.item_embedding_gradients += 1
self.item_bias_gradients += 1
self.user_embedding_gradients += 1
self.user_bias_gradients += 1 | [
"def",
"_initialize",
"(",
"self",
",",
"no_components",
",",
"no_item_features",
",",
"no_user_features",
")",
":",
"# Initialise item features.",
"self",
".",
"item_embeddings",
"=",
"(",
"(",
"self",
".",
"random_state",
".",
"rand",
"(",
"no_item_features",
",... | Initialise internal latent representations. | [
"Initialise",
"internal",
"latent",
"representations",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L264-L295 |
224,622 | lyst/lightfm | lightfm/lightfm.py | LightFM._run_epoch | def _run_epoch(
self,
item_features,
user_features,
interactions,
sample_weight,
num_threads,
loss,
):
"""
Run an individual epoch.
"""
if loss in ("warp", "bpr", "warp-kos"):
# The CSR conversion needs to happen before shuffle indices are created.
# Calling .tocsr may result in a change in the data arrays of the COO matrix,
positives_lookup = CSRMatrix(
self._get_positives_lookup_matrix(interactions)
)
# Create shuffle indexes.
shuffle_indices = np.arange(len(interactions.data), dtype=np.int32)
self.random_state.shuffle(shuffle_indices)
lightfm_data = self._get_lightfm_data()
# Call the estimation routines.
if loss == "warp":
fit_warp(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "bpr":
fit_bpr(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "warp-kos":
fit_warp_kos(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
self.k,
self.n,
num_threads,
self.random_state,
)
else:
fit_logistic(
CSRMatrix(item_features),
CSRMatrix(user_features),
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
) | python | def _run_epoch(
self,
item_features,
user_features,
interactions,
sample_weight,
num_threads,
loss,
):
"""
Run an individual epoch.
"""
if loss in ("warp", "bpr", "warp-kos"):
# The CSR conversion needs to happen before shuffle indices are created.
# Calling .tocsr may result in a change in the data arrays of the COO matrix,
positives_lookup = CSRMatrix(
self._get_positives_lookup_matrix(interactions)
)
# Create shuffle indexes.
shuffle_indices = np.arange(len(interactions.data), dtype=np.int32)
self.random_state.shuffle(shuffle_indices)
lightfm_data = self._get_lightfm_data()
# Call the estimation routines.
if loss == "warp":
fit_warp(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "bpr":
fit_bpr(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "warp-kos":
fit_warp_kos(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
self.k,
self.n,
num_threads,
self.random_state,
)
else:
fit_logistic(
CSRMatrix(item_features),
CSRMatrix(user_features),
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
) | [
"def",
"_run_epoch",
"(",
"self",
",",
"item_features",
",",
"user_features",
",",
"interactions",
",",
"sample_weight",
",",
"num_threads",
",",
"loss",
",",
")",
":",
"if",
"loss",
"in",
"(",
"\"warp\"",
",",
"\"bpr\"",
",",
"\"warp-kos\"",
")",
":",
"# ... | Run an individual epoch. | [
"Run",
"an",
"individual",
"epoch",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L651-L742 |
224,623 | lyst/lightfm | lightfm/lightfm.py | LightFM.predict | def predict(
self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1
):
"""
Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32 array of shape [n_pairs,]
single user id or an array containing the user ids for the
user-item pairs for which a prediction is to be computed. Note
that these are LightFM's internal id's, i.e. the index of the
user in the interaction matrix used for fitting the model.
item_ids: np.int32 array of shape [n_pairs,]
an array containing the item ids for the user-item pairs for which
a prediction is to be computed. Note that these are LightFM's
internal id's, i.e. the index of the item in the interaction
matrix used for fitting the model.
user_features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
item_features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
num_threads: int, optional
Number of parallel computation threads to use. Should
not be higher than the number of physical cores.
Returns
-------
np.float32 array of shape [n_pairs,]
Numpy array containing the recommendation scores for pairs defined
by the inputs.
"""
self._check_initialized()
if not isinstance(user_ids, np.ndarray):
user_ids = np.repeat(np.int32(user_ids), len(item_ids))
if isinstance(item_ids, (list, tuple)):
item_ids = np.array(item_ids, dtype=np.int32)
assert len(user_ids) == len(item_ids)
if user_ids.dtype != np.int32:
user_ids = user_ids.astype(np.int32)
if item_ids.dtype != np.int32:
item_ids = item_ids.astype(np.int32)
if num_threads < 1:
raise ValueError("Number of threads must be 1 or larger.")
if user_ids.min() < 0 or item_ids.min() < 0:
raise ValueError(
"User or item ids cannot be negative. "
"Check your inputs for negative numbers "
"or very large numbers that can overflow."
)
n_users = user_ids.max() + 1
n_items = item_ids.max() + 1
(user_features, item_features) = self._construct_feature_matrices(
n_users, n_items, user_features, item_features
)
lightfm_data = self._get_lightfm_data()
predictions = np.empty(len(user_ids), dtype=np.float64)
predict_lightfm(
CSRMatrix(item_features),
CSRMatrix(user_features),
user_ids,
item_ids,
predictions,
lightfm_data,
num_threads,
)
return predictions | python | def predict(
self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1
):
"""
Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32 array of shape [n_pairs,]
single user id or an array containing the user ids for the
user-item pairs for which a prediction is to be computed. Note
that these are LightFM's internal id's, i.e. the index of the
user in the interaction matrix used for fitting the model.
item_ids: np.int32 array of shape [n_pairs,]
an array containing the item ids for the user-item pairs for which
a prediction is to be computed. Note that these are LightFM's
internal id's, i.e. the index of the item in the interaction
matrix used for fitting the model.
user_features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
item_features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
num_threads: int, optional
Number of parallel computation threads to use. Should
not be higher than the number of physical cores.
Returns
-------
np.float32 array of shape [n_pairs,]
Numpy array containing the recommendation scores for pairs defined
by the inputs.
"""
self._check_initialized()
if not isinstance(user_ids, np.ndarray):
user_ids = np.repeat(np.int32(user_ids), len(item_ids))
if isinstance(item_ids, (list, tuple)):
item_ids = np.array(item_ids, dtype=np.int32)
assert len(user_ids) == len(item_ids)
if user_ids.dtype != np.int32:
user_ids = user_ids.astype(np.int32)
if item_ids.dtype != np.int32:
item_ids = item_ids.astype(np.int32)
if num_threads < 1:
raise ValueError("Number of threads must be 1 or larger.")
if user_ids.min() < 0 or item_ids.min() < 0:
raise ValueError(
"User or item ids cannot be negative. "
"Check your inputs for negative numbers "
"or very large numbers that can overflow."
)
n_users = user_ids.max() + 1
n_items = item_ids.max() + 1
(user_features, item_features) = self._construct_feature_matrices(
n_users, n_items, user_features, item_features
)
lightfm_data = self._get_lightfm_data()
predictions = np.empty(len(user_ids), dtype=np.float64)
predict_lightfm(
CSRMatrix(item_features),
CSRMatrix(user_features),
user_ids,
item_ids,
predictions,
lightfm_data,
num_threads,
)
return predictions | [
"def",
"predict",
"(",
"self",
",",
"user_ids",
",",
"item_ids",
",",
"item_features",
"=",
"None",
",",
"user_features",
"=",
"None",
",",
"num_threads",
"=",
"1",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"not",
"isinstance",
"(",
"u... | Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32 array of shape [n_pairs,]
single user id or an array containing the user ids for the
user-item pairs for which a prediction is to be computed. Note
that these are LightFM's internal id's, i.e. the index of the
user in the interaction matrix used for fitting the model.
item_ids: np.int32 array of shape [n_pairs,]
an array containing the item ids for the user-item pairs for which
a prediction is to be computed. Note that these are LightFM's
internal id's, i.e. the index of the item in the interaction
matrix used for fitting the model.
user_features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
item_features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
num_threads: int, optional
Number of parallel computation threads to use. Should
not be higher than the number of physical cores.
Returns
-------
np.float32 array of shape [n_pairs,]
Numpy array containing the recommendation scores for pairs defined
by the inputs. | [
"Compute",
"the",
"recommendation",
"score",
"for",
"user",
"-",
"item",
"pairs",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L744-L828 |
224,624 | lyst/lightfm | lightfm/lightfm.py | LightFM.get_item_representations | def get_item_representations(self, features=None):
"""
Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(item_biases, item_embeddings):
(np.float32 array of shape n_items,
np.float32 array of shape [n_items, num_components]
Biases and latent representations for items.
"""
self._check_initialized()
if features is None:
return self.item_biases, self.item_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.item_biases, features * self.item_embeddings | python | def get_item_representations(self, features=None):
"""
Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(item_biases, item_embeddings):
(np.float32 array of shape n_items,
np.float32 array of shape [n_items, num_components]
Biases and latent representations for items.
"""
self._check_initialized()
if features is None:
return self.item_biases, self.item_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.item_biases, features * self.item_embeddings | [
"def",
"get_item_representations",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"features",
"is",
"None",
":",
"return",
"self",
".",
"item_biases",
",",
"self",
".",
"item_embeddings",
"features",
"... | Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(item_biases, item_embeddings):
(np.float32 array of shape n_items,
np.float32 array of shape [n_items, num_components]
Biases and latent representations for items. | [
"Get",
"the",
"latent",
"representations",
"for",
"items",
"given",
"model",
"and",
"features",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L947-L974 |
224,625 | lyst/lightfm | lightfm/lightfm.py | LightFM.get_user_representations | def get_user_representations(self, features=None):
"""
Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(user_biases, user_embeddings):
(np.float32 array of shape n_users
np.float32 array of shape [n_users, num_components]
Biases and latent representations for users.
"""
self._check_initialized()
if features is None:
return self.user_biases, self.user_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.user_biases, features * self.user_embeddings | python | def get_user_representations(self, features=None):
"""
Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(user_biases, user_embeddings):
(np.float32 array of shape n_users
np.float32 array of shape [n_users, num_components]
Biases and latent representations for users.
"""
self._check_initialized()
if features is None:
return self.user_biases, self.user_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.user_biases, features * self.user_embeddings | [
"def",
"get_user_representations",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"features",
"is",
"None",
":",
"return",
"self",
".",
"user_biases",
",",
"self",
".",
"user_embeddings",
"features",
"... | Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(user_biases, user_embeddings):
(np.float32 array of shape n_users
np.float32 array of shape [n_users, num_components]
Biases and latent representations for users. | [
"Get",
"the",
"latent",
"representations",
"for",
"users",
"given",
"model",
"and",
"features",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L976-L1003 |
224,626 | quantopian/empyrical | empyrical/stats.py | _adjust_returns | def _adjust_returns(returns, adjustment_factor):
"""
Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series or np.ndarray or float or int
Returns
-------
adjusted_returns : array-like
"""
if isinstance(adjustment_factor, (float, int)) and adjustment_factor == 0:
return returns
return returns - adjustment_factor | python | def _adjust_returns(returns, adjustment_factor):
"""
Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series or np.ndarray or float or int
Returns
-------
adjusted_returns : array-like
"""
if isinstance(adjustment_factor, (float, int)) and adjustment_factor == 0:
return returns
return returns - adjustment_factor | [
"def",
"_adjust_returns",
"(",
"returns",
",",
"adjustment_factor",
")",
":",
"if",
"isinstance",
"(",
"adjustment_factor",
",",
"(",
"float",
",",
"int",
")",
")",
"and",
"adjustment_factor",
"==",
"0",
":",
"return",
"returns",
"return",
"returns",
"-",
"a... | Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series or np.ndarray or float or int
Returns
-------
adjusted_returns : array-like | [
"Returns",
"the",
"returns",
"series",
"adjusted",
"by",
"adjustment_factor",
".",
"Optimizes",
"for",
"the",
"case",
"of",
"adjustment_factor",
"being",
"0",
"by",
"returning",
"returns",
"itself",
"not",
"a",
"copy!"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L127-L143 |
224,627 | quantopian/empyrical | empyrical/stats.py | annualization_factor | def annualization_factor(period, annualization):
"""
Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annualization_factor : float
"""
if annualization is None:
try:
factor = ANNUALIZATION_FACTORS[period]
except KeyError:
raise ValueError(
"Period cannot be '{}'. "
"Can be '{}'.".format(
period, "', '".join(ANNUALIZATION_FACTORS.keys())
)
)
else:
factor = annualization
return factor | python | def annualization_factor(period, annualization):
"""
Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annualization_factor : float
"""
if annualization is None:
try:
factor = ANNUALIZATION_FACTORS[period]
except KeyError:
raise ValueError(
"Period cannot be '{}'. "
"Can be '{}'.".format(
period, "', '".join(ANNUALIZATION_FACTORS.keys())
)
)
else:
factor = annualization
return factor | [
"def",
"annualization_factor",
"(",
"period",
",",
"annualization",
")",
":",
"if",
"annualization",
"is",
"None",
":",
"try",
":",
"factor",
"=",
"ANNUALIZATION_FACTORS",
"[",
"period",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Period canno... | Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annualization_factor : float | [
"Return",
"annualization",
"factor",
"from",
"period",
"entered",
"or",
"if",
"a",
"custom",
"value",
"is",
"passed",
"in",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L146-L183 |
224,628 | quantopian/empyrical | empyrical/stats.py | simple_returns | def simple_returns(prices):
"""
Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-like
Returns of assets in wide-format, with assets as columns,
and index coerced to be tz-aware.
"""
if isinstance(prices, (pd.DataFrame, pd.Series)):
out = prices.pct_change().iloc[1:]
else:
# Assume np.ndarray
out = np.diff(prices, axis=0)
np.divide(out, prices[:-1], out=out)
return out | python | def simple_returns(prices):
"""
Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-like
Returns of assets in wide-format, with assets as columns,
and index coerced to be tz-aware.
"""
if isinstance(prices, (pd.DataFrame, pd.Series)):
out = prices.pct_change().iloc[1:]
else:
# Assume np.ndarray
out = np.diff(prices, axis=0)
np.divide(out, prices[:-1], out=out)
return out | [
"def",
"simple_returns",
"(",
"prices",
")",
":",
"if",
"isinstance",
"(",
"prices",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
":",
"out",
"=",
"prices",
".",
"pct_change",
"(",
")",
".",
"iloc",
"[",
"1",
":",
"]",
"e... | Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-like
Returns of assets in wide-format, with assets as columns,
and index coerced to be tz-aware. | [
"Compute",
"simple",
"returns",
"from",
"a",
"timeseries",
"of",
"prices",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L186-L209 |
224,629 | quantopian/empyrical | empyrical/stats.py | cum_returns | def cum_returns(returns, starting_value=0, out=None):
"""
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Example::
2015-07-16 -0.012143
2015-07-17 0.045350
2015-07-20 0.030957
2015-07-21 0.004902
- Also accepts two dimensional data. In this case, each column is
cumulated.
starting_value : float, optional
The starting returns.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
cumulative_returns : array-like
Series of cumulative returns.
"""
if len(returns) < 1:
return returns.copy()
nanmask = np.isnan(returns)
if np.any(nanmask):
returns = returns.copy()
returns[nanmask] = 0
allocated_output = out is None
if allocated_output:
out = np.empty_like(returns)
np.add(returns, 1, out=out)
out.cumprod(axis=0, out=out)
if starting_value == 0:
np.subtract(out, 1, out=out)
else:
np.multiply(out, starting_value, out=out)
if allocated_output:
if returns.ndim == 1 and isinstance(returns, pd.Series):
out = pd.Series(out, index=returns.index)
elif isinstance(returns, pd.DataFrame):
out = pd.DataFrame(
out, index=returns.index, columns=returns.columns,
)
return out | python | def cum_returns(returns, starting_value=0, out=None):
"""
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Example::
2015-07-16 -0.012143
2015-07-17 0.045350
2015-07-20 0.030957
2015-07-21 0.004902
- Also accepts two dimensional data. In this case, each column is
cumulated.
starting_value : float, optional
The starting returns.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
cumulative_returns : array-like
Series of cumulative returns.
"""
if len(returns) < 1:
return returns.copy()
nanmask = np.isnan(returns)
if np.any(nanmask):
returns = returns.copy()
returns[nanmask] = 0
allocated_output = out is None
if allocated_output:
out = np.empty_like(returns)
np.add(returns, 1, out=out)
out.cumprod(axis=0, out=out)
if starting_value == 0:
np.subtract(out, 1, out=out)
else:
np.multiply(out, starting_value, out=out)
if allocated_output:
if returns.ndim == 1 and isinstance(returns, pd.Series):
out = pd.Series(out, index=returns.index)
elif isinstance(returns, pd.DataFrame):
out = pd.DataFrame(
out, index=returns.index, columns=returns.columns,
)
return out | [
"def",
"cum_returns",
"(",
"returns",
",",
"starting_value",
"=",
"0",
",",
"out",
"=",
"None",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"1",
":",
"return",
"returns",
".",
"copy",
"(",
")",
"nanmask",
"=",
"np",
".",
"isnan",
"(",
"returns... | Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Example::
2015-07-16 -0.012143
2015-07-17 0.045350
2015-07-20 0.030957
2015-07-21 0.004902
- Also accepts two dimensional data. In this case, each column is
cumulated.
starting_value : float, optional
The starting returns.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
cumulative_returns : array-like
Series of cumulative returns. | [
"Compute",
"cumulative",
"returns",
"from",
"simple",
"returns",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L212-L270 |
224,630 | quantopian/empyrical | empyrical/stats.py | cum_returns_final | def cum_returns_final(returns, starting_value=0):
"""
Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
Returns
-------
total_returns : pd.Series, np.ndarray, or float
If input is 1-dimensional (a Series or 1D numpy array), the result is a
scalar.
If input is 2-dimensional (a DataFrame or 2D numpy array), the result
is a 1D array containing cumulative returns for each column of input.
"""
if len(returns) == 0:
return np.nan
if isinstance(returns, pd.DataFrame):
result = (returns + 1).prod()
else:
result = np.nanprod(returns + 1, axis=0)
if starting_value == 0:
result -= 1
else:
result *= starting_value
return result | python | def cum_returns_final(returns, starting_value=0):
"""
Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
Returns
-------
total_returns : pd.Series, np.ndarray, or float
If input is 1-dimensional (a Series or 1D numpy array), the result is a
scalar.
If input is 2-dimensional (a DataFrame or 2D numpy array), the result
is a 1D array containing cumulative returns for each column of input.
"""
if len(returns) == 0:
return np.nan
if isinstance(returns, pd.DataFrame):
result = (returns + 1).prod()
else:
result = np.nanprod(returns + 1, axis=0)
if starting_value == 0:
result -= 1
else:
result *= starting_value
return result | [
"def",
"cum_returns_final",
"(",
"returns",
",",
"starting_value",
"=",
"0",
")",
":",
"if",
"len",
"(",
"returns",
")",
"==",
"0",
":",
"return",
"np",
".",
"nan",
"if",
"isinstance",
"(",
"returns",
",",
"pd",
".",
"DataFrame",
")",
":",
"result",
... | Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
Returns
-------
total_returns : pd.Series, np.ndarray, or float
If input is 1-dimensional (a Series or 1D numpy array), the result is a
scalar.
If input is 2-dimensional (a DataFrame or 2D numpy array), the result
is a 1D array containing cumulative returns for each column of input. | [
"Compute",
"total",
"returns",
"from",
"simple",
"returns",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L273-L306 |
224,631 | quantopian/empyrical | empyrical/stats.py | aggregate_returns | def aggregate_returns(returns, convert_to):
"""
Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'weekly', 'monthly', or 'yearly'.
Returns
-------
aggregated_returns : pd.Series
"""
def cumulate_returns(x):
return cum_returns(x).iloc[-1]
if convert_to == WEEKLY:
grouping = [lambda x: x.year, lambda x: x.isocalendar()[1]]
elif convert_to == MONTHLY:
grouping = [lambda x: x.year, lambda x: x.month]
elif convert_to == YEARLY:
grouping = [lambda x: x.year]
else:
raise ValueError(
'convert_to must be {}, {} or {}'.format(WEEKLY, MONTHLY, YEARLY)
)
return returns.groupby(grouping).apply(cumulate_returns) | python | def aggregate_returns(returns, convert_to):
"""
Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'weekly', 'monthly', or 'yearly'.
Returns
-------
aggregated_returns : pd.Series
"""
def cumulate_returns(x):
return cum_returns(x).iloc[-1]
if convert_to == WEEKLY:
grouping = [lambda x: x.year, lambda x: x.isocalendar()[1]]
elif convert_to == MONTHLY:
grouping = [lambda x: x.year, lambda x: x.month]
elif convert_to == YEARLY:
grouping = [lambda x: x.year]
else:
raise ValueError(
'convert_to must be {}, {} or {}'.format(WEEKLY, MONTHLY, YEARLY)
)
return returns.groupby(grouping).apply(cumulate_returns) | [
"def",
"aggregate_returns",
"(",
"returns",
",",
"convert_to",
")",
":",
"def",
"cumulate_returns",
"(",
"x",
")",
":",
"return",
"cum_returns",
"(",
"x",
")",
".",
"iloc",
"[",
"-",
"1",
"]",
"if",
"convert_to",
"==",
"WEEKLY",
":",
"grouping",
"=",
"... | Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'weekly', 'monthly', or 'yearly'.
Returns
-------
aggregated_returns : pd.Series | [
"Aggregates",
"returns",
"by",
"week",
"month",
"or",
"year",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L309-L340 |
224,632 | quantopian/empyrical | empyrical/stats.py | max_drawdown | def max_drawdown(returns, out=None):
"""
Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
max_drawdown : float
Note
-----
See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
returns_array = np.asanyarray(returns)
cumulative = np.empty(
(returns.shape[0] + 1,) + returns.shape[1:],
dtype='float64',
)
cumulative[0] = start = 100
cum_returns(returns_array, starting_value=start, out=cumulative[1:])
max_return = np.fmax.accumulate(cumulative, axis=0)
nanmin((cumulative - max_return) / max_return, axis=0, out=out)
if returns_1d:
out = out.item()
elif allocated_output and isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | python | def max_drawdown(returns, out=None):
"""
Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
max_drawdown : float
Note
-----
See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
returns_array = np.asanyarray(returns)
cumulative = np.empty(
(returns.shape[0] + 1,) + returns.shape[1:],
dtype='float64',
)
cumulative[0] = start = 100
cum_returns(returns_array, starting_value=start, out=cumulative[1:])
max_return = np.fmax.accumulate(cumulative, axis=0)
nanmin((cumulative - max_return) / max_return, axis=0, out=out)
if returns_1d:
out = out.item()
elif allocated_output and isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | [
"def",
"max_drawdown",
"(",
"returns",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"returns",
".",
"shape",
"[",
"1",
":",
"]",
")",
"returns_1d",
... | Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
max_drawdown : float
Note
-----
See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details. | [
"Determines",
"the",
"maximum",
"drawdown",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L343-L393 |
224,633 | quantopian/empyrical | empyrical/stats.py | annual_return | def annual_return(returns, period=DAILY, annualization=None):
"""
Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annual_return : float
Annual Return as CAGR (Compounded Annual Growth Rate).
"""
if len(returns) < 1:
return np.nan
ann_factor = annualization_factor(period, annualization)
num_years = len(returns) / ann_factor
# Pass array to ensure index -1 looks up successfully.
ending_value = cum_returns_final(returns, starting_value=1)
return ending_value ** (1 / num_years) - 1 | python | def annual_return(returns, period=DAILY, annualization=None):
"""
Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annual_return : float
Annual Return as CAGR (Compounded Annual Growth Rate).
"""
if len(returns) < 1:
return np.nan
ann_factor = annualization_factor(period, annualization)
num_years = len(returns) / ann_factor
# Pass array to ensure index -1 looks up successfully.
ending_value = cum_returns_final(returns, starting_value=1)
return ending_value ** (1 / num_years) - 1 | [
"def",
"annual_return",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"1",
":",
"return",
"np",
".",
"nan",
"ann_factor",
"=",
"annualization_factor",
"(",
"period",
",",
... | Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annual_return : float
Annual Return as CAGR (Compounded Annual Growth Rate). | [
"Determines",
"the",
"mean",
"annual",
"growth",
"rate",
"of",
"returns",
".",
"This",
"is",
"equivilent",
"to",
"the",
"compound",
"annual",
"growth",
"rate",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L399-L438 |
224,634 | quantopian/empyrical | empyrical/stats.py | annual_volatility | def annual_volatility(returns,
period=DAILY,
alpha=2.0,
annualization=None,
out=None):
"""
Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
alpha : float, optional
Scaling relation (Levy stability exponent).
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
annual_volatility : float
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
nanstd(returns, ddof=1, axis=0, out=out)
out = np.multiply(out, ann_factor ** (1.0 / alpha), out=out)
if returns_1d:
out = out.item()
return out | python | def annual_volatility(returns,
period=DAILY,
alpha=2.0,
annualization=None,
out=None):
"""
Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
alpha : float, optional
Scaling relation (Levy stability exponent).
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
annual_volatility : float
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
nanstd(returns, ddof=1, axis=0, out=out)
out = np.multiply(out, ann_factor ** (1.0 / alpha), out=out)
if returns_1d:
out = out.item()
return out | [
"def",
"annual_volatility",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"alpha",
"=",
"2.0",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"... | Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
alpha : float, optional
Scaling relation (Levy stability exponent).
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
annual_volatility : float | [
"Determines",
"the",
"annual",
"volatility",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L478-L531 |
224,635 | quantopian/empyrical | empyrical/stats.py | calmar_ratio | def calmar_ratio(returns, period=DAILY, annualization=None):
"""
Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
calmar_ratio : float
Calmar ratio (drawdown ratio) as float. Returns np.nan if there is no
calmar ratio.
Note
-----
See https://en.wikipedia.org/wiki/Calmar_ratio for more details.
"""
max_dd = max_drawdown(returns=returns)
if max_dd < 0:
temp = annual_return(
returns=returns,
period=period,
annualization=annualization
) / abs(max_dd)
else:
return np.nan
if np.isinf(temp):
return np.nan
return temp | python | def calmar_ratio(returns, period=DAILY, annualization=None):
"""
Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
calmar_ratio : float
Calmar ratio (drawdown ratio) as float. Returns np.nan if there is no
calmar ratio.
Note
-----
See https://en.wikipedia.org/wiki/Calmar_ratio for more details.
"""
max_dd = max_drawdown(returns=returns)
if max_dd < 0:
temp = annual_return(
returns=returns,
period=period,
annualization=annualization
) / abs(max_dd)
else:
return np.nan
if np.isinf(temp):
return np.nan
return temp | [
"def",
"calmar_ratio",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
")",
":",
"max_dd",
"=",
"max_drawdown",
"(",
"returns",
"=",
"returns",
")",
"if",
"max_dd",
"<",
"0",
":",
"temp",
"=",
"annual_return",
"(",
"return... | Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
calmar_ratio : float
Calmar ratio (drawdown ratio) as float. Returns np.nan if there is no
calmar ratio.
Note
-----
See https://en.wikipedia.org/wiki/Calmar_ratio for more details. | [
"Determines",
"the",
"Calmar",
"ratio",
"or",
"drawdown",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L539-L587 |
224,636 | quantopian/empyrical | empyrical/stats.py | omega_ratio | def omega_ratio(returns, risk_free=0.0, required_return=0.0,
annualization=APPROX_BDAYS_PER_YEAR):
"""Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period
required_return : float, optional
Minimum acceptance return of the investor. Threshold over which to
consider positive vs negative returns. It will be converted to a
value appropriate for the period of the returns. E.g. An annual minimum
acceptable return of 100 will translate to a minimum acceptable
return of 0.018.
annualization : int, optional
Factor used to convert the required_return into a daily
value. Enter 1 if no time period conversion is necessary.
Returns
-------
omega_ratio : float
Note
-----
See https://en.wikipedia.org/wiki/Omega_ratio for more details.
"""
if len(returns) < 2:
return np.nan
if annualization == 1:
return_threshold = required_return
elif required_return <= -1:
return np.nan
else:
return_threshold = (1 + required_return) ** \
(1. / annualization) - 1
returns_less_thresh = returns - risk_free - return_threshold
numer = sum(returns_less_thresh[returns_less_thresh > 0.0])
denom = -1.0 * sum(returns_less_thresh[returns_less_thresh < 0.0])
if denom > 0.0:
return numer / denom
else:
return np.nan | python | def omega_ratio(returns, risk_free=0.0, required_return=0.0,
annualization=APPROX_BDAYS_PER_YEAR):
"""Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period
required_return : float, optional
Minimum acceptance return of the investor. Threshold over which to
consider positive vs negative returns. It will be converted to a
value appropriate for the period of the returns. E.g. An annual minimum
acceptable return of 100 will translate to a minimum acceptable
return of 0.018.
annualization : int, optional
Factor used to convert the required_return into a daily
value. Enter 1 if no time period conversion is necessary.
Returns
-------
omega_ratio : float
Note
-----
See https://en.wikipedia.org/wiki/Omega_ratio for more details.
"""
if len(returns) < 2:
return np.nan
if annualization == 1:
return_threshold = required_return
elif required_return <= -1:
return np.nan
else:
return_threshold = (1 + required_return) ** \
(1. / annualization) - 1
returns_less_thresh = returns - risk_free - return_threshold
numer = sum(returns_less_thresh[returns_less_thresh > 0.0])
denom = -1.0 * sum(returns_less_thresh[returns_less_thresh < 0.0])
if denom > 0.0:
return numer / denom
else:
return np.nan | [
"def",
"omega_ratio",
"(",
"returns",
",",
"risk_free",
"=",
"0.0",
",",
"required_return",
"=",
"0.0",
",",
"annualization",
"=",
"APPROX_BDAYS_PER_YEAR",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"2",
":",
"return",
"np",
".",
"nan",
"if",
"annu... | Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period
required_return : float, optional
Minimum acceptance return of the investor. Threshold over which to
consider positive vs negative returns. It will be converted to a
value appropriate for the period of the returns. E.g. An annual minimum
acceptable return of 100 will translate to a minimum acceptable
return of 0.018.
annualization : int, optional
Factor used to convert the required_return into a daily
value. Enter 1 if no time period conversion is necessary.
Returns
-------
omega_ratio : float
Note
-----
See https://en.wikipedia.org/wiki/Omega_ratio for more details. | [
"Determines",
"the",
"Omega",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L590-L640 |
224,637 | quantopian/empyrical | empyrical/stats.py | sharpe_ratio | def sharpe_ratio(returns,
risk_free=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sharpe_ratio : float
nan if insufficient length of returns or if if adjusted returns are 0.
Note
-----
See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
returns_risk_adj = np.asanyarray(_adjust_returns(returns, risk_free))
ann_factor = annualization_factor(period, annualization)
np.multiply(
np.divide(
nanmean(returns_risk_adj, axis=0),
nanstd(returns_risk_adj, ddof=1, axis=0),
out=out,
),
np.sqrt(ann_factor),
out=out,
)
if return_1d:
out = out.item()
return out | python | def sharpe_ratio(returns,
risk_free=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sharpe_ratio : float
nan if insufficient length of returns or if if adjusted returns are 0.
Note
-----
See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
returns_risk_adj = np.asanyarray(_adjust_returns(returns, risk_free))
ann_factor = annualization_factor(period, annualization)
np.multiply(
np.divide(
nanmean(returns_risk_adj, axis=0),
nanstd(returns_risk_adj, ddof=1, axis=0),
out=out,
),
np.sqrt(ann_factor),
out=out,
)
if return_1d:
out = out.item()
return out | [
"def",
"sharpe_ratio",
"(",
"returns",
",",
"risk_free",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",... | Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sharpe_ratio : float
nan if insufficient length of returns or if if adjusted returns are 0.
Note
-----
See https://en.wikipedia.org/wiki/Sharpe_ratio for more details. | [
"Determines",
"the",
"Sharpe",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L643-L712 |
224,638 | quantopian/empyrical | empyrical/stats.py | sortino_ratio | def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
_downside_risk : float, optional
The downside risk of the given inputs, if known. Will be calculated if
not provided.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sortino_ratio : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
adj_returns = np.asanyarray(_adjust_returns(returns, required_return))
ann_factor = annualization_factor(period, annualization)
average_annual_return = nanmean(adj_returns, axis=0) * ann_factor
annualized_downside_risk = (
_downside_risk
if _downside_risk is not None else
downside_risk(returns, required_return, period, annualization)
)
np.divide(average_annual_return, annualized_downside_risk, out=out)
if return_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | python | def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
_downside_risk : float, optional
The downside risk of the given inputs, if known. Will be calculated if
not provided.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sortino_ratio : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
adj_returns = np.asanyarray(_adjust_returns(returns, required_return))
ann_factor = annualization_factor(period, annualization)
average_annual_return = nanmean(adj_returns, axis=0) * ann_factor
annualized_downside_risk = (
_downside_risk
if _downside_risk is not None else
downside_risk(returns, required_return, period, annualization)
)
np.divide(average_annual_return, annualized_downside_risk, out=out)
if return_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | [
"def",
"sortino_ratio",
"(",
"returns",
",",
"required_return",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
",",
"_downside_risk",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
... | Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
_downside_risk : float, optional
The downside risk of the given inputs, if known. Will be calculated if
not provided.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sortino_ratio : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details. | [
"Determines",
"the",
"Sortino",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L718-L796 |
224,639 | quantopian/empyrical | empyrical/stats.py | downside_risk | def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
downside_deviation : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details, specifically why using the
standard deviation of the negative returns is not correct.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
downside_diff = np.clip(
_adjust_returns(
np.asanyarray(returns),
np.asanyarray(required_return),
),
np.NINF,
0,
)
np.square(downside_diff, out=downside_diff)
nanmean(downside_diff, axis=0, out=out)
np.sqrt(out, out=out)
np.multiply(out, np.sqrt(ann_factor), out=out)
if returns_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out, index=returns.columns)
return out | python | def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
downside_deviation : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details, specifically why using the
standard deviation of the negative returns is not correct.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
downside_diff = np.clip(
_adjust_returns(
np.asanyarray(returns),
np.asanyarray(required_return),
),
np.NINF,
0,
)
np.square(downside_diff, out=downside_diff)
nanmean(downside_diff, axis=0, out=out)
np.sqrt(out, out=out)
np.multiply(out, np.sqrt(ann_factor), out=out)
if returns_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out, index=returns.columns)
return out | [
"def",
"downside_risk",
"(",
"returns",
",",
"required_return",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",... | Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
downside_deviation : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details, specifically why using the
standard deviation of the negative returns is not correct. | [
"Determines",
"the",
"downside",
"deviation",
"below",
"a",
"threshold"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L802-L879 |
224,640 | quantopian/empyrical | empyrical/stats.py | excess_sharpe | def excess_sharpe(returns, factor_returns, out=None):
"""
Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns: float / series
Benchmark return to compare returns against.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
excess_sharpe : float
Note
-----
The excess Sharpe is a simplified Information Ratio that uses
tracking error rather than "active risk" as the denominator.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
active_return = _adjust_returns(returns, factor_returns)
tracking_error = np.nan_to_num(nanstd(active_return, ddof=1, axis=0))
out = np.divide(
nanmean(active_return, axis=0, out=out),
tracking_error,
out=out,
)
if returns_1d:
out = out.item()
return out | python | def excess_sharpe(returns, factor_returns, out=None):
"""
Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns: float / series
Benchmark return to compare returns against.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
excess_sharpe : float
Note
-----
The excess Sharpe is a simplified Information Ratio that uses
tracking error rather than "active risk" as the denominator.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
active_return = _adjust_returns(returns, factor_returns)
tracking_error = np.nan_to_num(nanstd(active_return, ddof=1, axis=0))
out = np.divide(
nanmean(active_return, axis=0, out=out),
tracking_error,
out=out,
)
if returns_1d:
out = out.item()
return out | [
"def",
"excess_sharpe",
"(",
"returns",
",",
"factor_returns",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"returns",
".",
"shape",
"[",
"1",
":",
... | Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns: float / series
Benchmark return to compare returns against.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
excess_sharpe : float
Note
-----
The excess Sharpe is a simplified Information Ratio that uses
tracking error rather than "active risk" as the denominator. | [
"Determines",
"the",
"Excess",
"Sharpe",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L885-L931 |
224,641 | quantopian/empyrical | empyrical/stats.py | _to_pandas | def _to_pandas(ob):
"""Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data.
"""
if isinstance(ob, (pd.Series, pd.DataFrame)):
return ob
if ob.ndim == 1:
return pd.Series(ob)
elif ob.ndim == 2:
return pd.DataFrame(ob)
else:
raise ValueError(
'cannot convert array of dim > 2 to a pandas structure',
) | python | def _to_pandas(ob):
"""Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data.
"""
if isinstance(ob, (pd.Series, pd.DataFrame)):
return ob
if ob.ndim == 1:
return pd.Series(ob)
elif ob.ndim == 2:
return pd.DataFrame(ob)
else:
raise ValueError(
'cannot convert array of dim > 2 to a pandas structure',
) | [
"def",
"_to_pandas",
"(",
"ob",
")",
":",
"if",
"isinstance",
"(",
"ob",
",",
"(",
"pd",
".",
"Series",
",",
"pd",
".",
"DataFrame",
")",
")",
":",
"return",
"ob",
"if",
"ob",
".",
"ndim",
"==",
"1",
":",
"return",
"pd",
".",
"Series",
"(",
"ob... | Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data. | [
"Convert",
"an",
"array",
"-",
"like",
"to",
"a",
"pandas",
"object",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L937-L960 |
224,642 | quantopian/empyrical | empyrical/stats.py | _aligned_series | def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
"""
head = many_series[0]
tail = many_series[1:]
n = len(head)
if (isinstance(head, np.ndarray) and
all(len(s) == n and isinstance(s, np.ndarray) for s in tail)):
# optimization: ndarrays of the same length are already aligned
return many_series
# dataframe has no ``itervalues``
return (
v
for _, v in iteritems(pd.concat(map(_to_pandas, many_series), axis=1))
) | python | def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
"""
head = many_series[0]
tail = many_series[1:]
n = len(head)
if (isinstance(head, np.ndarray) and
all(len(s) == n and isinstance(s, np.ndarray) for s in tail)):
# optimization: ndarrays of the same length are already aligned
return many_series
# dataframe has no ``itervalues``
return (
v
for _, v in iteritems(pd.concat(map(_to_pandas, many_series), axis=1))
) | [
"def",
"_aligned_series",
"(",
"*",
"many_series",
")",
":",
"head",
"=",
"many_series",
"[",
"0",
"]",
"tail",
"=",
"many_series",
"[",
"1",
":",
"]",
"n",
"=",
"len",
"(",
"head",
")",
"if",
"(",
"isinstance",
"(",
"head",
",",
"np",
".",
"ndarra... | Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values. | [
"Return",
"a",
"new",
"list",
"of",
"series",
"containing",
"the",
"data",
"in",
"the",
"input",
"series",
"but",
"with",
"their",
"indices",
"aligned",
".",
"NaNs",
"will",
"be",
"filled",
"in",
"for",
"missing",
"values",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L963-L992 |
224,643 | quantopian/empyrical | empyrical/stats.py | roll_alpha_beta | def roll_alpha_beta(returns, factor_returns, window=10, **kwargs):
"""
Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
window : int
Size of the rolling window in terms of the periodicity of the data.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
**kwargs
Forwarded to :func:`~empyrical.alpha_beta`.
"""
returns, factor_returns = _aligned_series(returns, factor_returns)
return roll_alpha_beta_aligned(
returns,
factor_returns,
window=window,
**kwargs
) | python | def roll_alpha_beta(returns, factor_returns, window=10, **kwargs):
"""
Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
window : int
Size of the rolling window in terms of the periodicity of the data.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
**kwargs
Forwarded to :func:`~empyrical.alpha_beta`.
"""
returns, factor_returns = _aligned_series(returns, factor_returns)
return roll_alpha_beta_aligned(
returns,
factor_returns,
window=window,
**kwargs
) | [
"def",
"roll_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"window",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"returns",
",",
"factor_returns",
"=",
"_aligned_series",
"(",
"returns",
",",
"factor_returns",
")",
"return",
"roll_alpha_beta_aligned... | Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
window : int
Size of the rolling window in terms of the periodicity of the data.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
**kwargs
Forwarded to :func:`~empyrical.alpha_beta`. | [
"Computes",
"alpha",
"and",
"beta",
"over",
"a",
"rolling",
"window",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1049-L1074 |
224,644 | quantopian/empyrical | empyrical/stats.py | stability_of_timeseries | def stability_of_timeseries(returns):
"""Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
Returns
-------
float
R-squared.
"""
if len(returns) < 2:
return np.nan
returns = np.asanyarray(returns)
returns = returns[~np.isnan(returns)]
cum_log_returns = np.log1p(returns).cumsum()
rhat = stats.linregress(np.arange(len(cum_log_returns)),
cum_log_returns)[2]
return rhat ** 2 | python | def stability_of_timeseries(returns):
"""Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
Returns
-------
float
R-squared.
"""
if len(returns) < 2:
return np.nan
returns = np.asanyarray(returns)
returns = returns[~np.isnan(returns)]
cum_log_returns = np.log1p(returns).cumsum()
rhat = stats.linregress(np.arange(len(cum_log_returns)),
cum_log_returns)[2]
return rhat ** 2 | [
"def",
"stability_of_timeseries",
"(",
"returns",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"2",
":",
"return",
"np",
".",
"nan",
"returns",
"=",
"np",
".",
"asanyarray",
"(",
"returns",
")",
"returns",
"=",
"returns",
"[",
"~",
"np",
".",
"is... | Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
Returns
-------
float
R-squared. | [
"Determines",
"R",
"-",
"squared",
"of",
"a",
"linear",
"fit",
"to",
"the",
"cumulative",
"log",
"returns",
".",
"Computes",
"an",
"ordinary",
"least",
"squares",
"linear",
"fit",
"and",
"returns",
"R",
"-",
"squared",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1454-L1481 |
224,645 | quantopian/empyrical | empyrical/stats.py | capture | def capture(returns, factor_returns, period=DAILY):
"""
Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
capture_ratio : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
details.
"""
return (annual_return(returns, period=period) /
annual_return(factor_returns, period=period)) | python | def capture(returns, factor_returns, period=DAILY):
"""
Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
capture_ratio : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
details.
"""
return (annual_return(returns, period=period) /
annual_return(factor_returns, period=period)) | [
"def",
"capture",
"(",
"returns",
",",
"factor_returns",
",",
"period",
"=",
"DAILY",
")",
":",
"return",
"(",
"annual_return",
"(",
"returns",
",",
"period",
"=",
"period",
")",
"/",
"annual_return",
"(",
"factor_returns",
",",
"period",
"=",
"period",
")... | Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
capture_ratio : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
details. | [
"Compute",
"capture",
"ratio",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1514-L1546 |
224,646 | quantopian/empyrical | empyrical/stats.py | up_capture | def up_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
up_capture : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
more information.
"""
return up(returns, factor_returns, function=capture, **kwargs) | python | def up_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
up_capture : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
more information.
"""
return up(returns, factor_returns, function=capture, **kwargs) | [
"def",
"up_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"capture",
",",
"*",
"*",
"kwargs",
")"
] | Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
up_capture : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
more information. | [
"Compute",
"the",
"capture",
"ratio",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"positive"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1549-L1580 |
224,647 | quantopian/empyrical | empyrical/stats.py | down_capture | def down_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
down_capture : float
Note
----
See http://www.investopedia.com/terms/d/down-market-capture-ratio.asp for
more information.
"""
return down(returns, factor_returns, function=capture, **kwargs) | python | def down_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
down_capture : float
Note
----
See http://www.investopedia.com/terms/d/down-market-capture-ratio.asp for
more information.
"""
return down(returns, factor_returns, function=capture, **kwargs) | [
"def",
"down_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"capture",
",",
"*",
"*",
"kwargs",
")"
] | Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
down_capture : float
Note
----
See http://www.investopedia.com/terms/d/down-market-capture-ratio.asp for
more information. | [
"Compute",
"the",
"capture",
"ratio",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"negative"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1583-L1614 |
224,648 | quantopian/empyrical | empyrical/stats.py | up_down_capture | def up_down_capture(returns, factor_returns, **kwargs):
"""
Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
up_down_capture : float
the updown capture ratio
"""
return (up_capture(returns, factor_returns, **kwargs) /
down_capture(returns, factor_returns, **kwargs)) | python | def up_down_capture(returns, factor_returns, **kwargs):
"""
Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
up_down_capture : float
the updown capture ratio
"""
return (up_capture(returns, factor_returns, **kwargs) /
down_capture(returns, factor_returns, **kwargs)) | [
"def",
"up_down_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"(",
"up_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
"/",
"down_capture",
"(",
"returns",
",",
"factor_returns",
... | Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
up_down_capture : float
the updown capture ratio | [
"Computes",
"the",
"ratio",
"of",
"up_capture",
"to",
"down_capture",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1617-L1645 |
224,649 | quantopian/empyrical | empyrical/stats.py | up_alpha_beta | def up_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta.
"""
return up(returns, factor_returns, function=alpha_beta_aligned, **kwargs) | python | def up_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta.
"""
return up(returns, factor_returns, function=alpha_beta_aligned, **kwargs) | [
"def",
"up_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"alpha_beta_aligned",
",",
"*",
"*",
"kwargs",
")"
] | Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta. | [
"Computes",
"alpha",
"and",
"beta",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"positive",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1648-L1663 |
224,650 | quantopian/empyrical | empyrical/stats.py | down_alpha_beta | def down_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float
"""
return down(returns, factor_returns, function=alpha_beta_aligned, **kwargs) | python | def down_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float
"""
return down(returns, factor_returns, function=alpha_beta_aligned, **kwargs) | [
"def",
"down_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"alpha_beta_aligned",
",",
"*",
"*",
"kwargs",
")"
] | Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float | [
"Computes",
"alpha",
"and",
"beta",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"negative",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1666-L1679 |
224,651 | quantopian/empyrical | empyrical/utils.py | roll | def roll(*args, **kwargs):
"""
Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
window (keyword): int
the number of periods included in each calculation.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
np.ndarray, pd.Series
depends on input type
ndarray(s) ==> ndarray
Series(s) ==> pd.Series
A Series or ndarray of the results of the stat across the rolling
window.
"""
func = kwargs.pop('function')
window = kwargs.pop('window')
if len(args) > 2:
raise ValueError("Cannot pass more than 2 return sets")
if len(args) == 2:
if not isinstance(args[0], type(args[1])):
raise ValueError("The two returns arguments are not the same.")
if isinstance(args[0], np.ndarray):
return _roll_ndarray(func, window, *args, **kwargs)
return _roll_pandas(func, window, *args, **kwargs) | python | def roll(*args, **kwargs):
"""
Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
window (keyword): int
the number of periods included in each calculation.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
np.ndarray, pd.Series
depends on input type
ndarray(s) ==> ndarray
Series(s) ==> pd.Series
A Series or ndarray of the results of the stat across the rolling
window.
"""
func = kwargs.pop('function')
window = kwargs.pop('window')
if len(args) > 2:
raise ValueError("Cannot pass more than 2 return sets")
if len(args) == 2:
if not isinstance(args[0], type(args[1])):
raise ValueError("The two returns arguments are not the same.")
if isinstance(args[0], np.ndarray):
return _roll_ndarray(func, window, *args, **kwargs)
return _roll_pandas(func, window, *args, **kwargs) | [
"def",
"roll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"window",
"=",
"kwargs",
".",
"pop",
"(",
"'window'",
")",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"raise",
"Va... | Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
window (keyword): int
the number of periods included in each calculation.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
np.ndarray, pd.Series
depends on input type
ndarray(s) ==> ndarray
Series(s) ==> pd.Series
A Series or ndarray of the results of the stat across the rolling
window. | [
"Calculates",
"a",
"given",
"statistic",
"across",
"a",
"rolling",
"time",
"period",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L78-L118 |
224,652 | quantopian/empyrical | empyrical/utils.py | up | def up(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
Same as the return of the function
"""
func = kwargs.pop('function')
returns = returns[factor_returns > 0]
factor_returns = factor_returns[factor_returns > 0]
return func(returns, factor_returns, **kwargs) | python | def up(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
Same as the return of the function
"""
func = kwargs.pop('function')
returns = returns[factor_returns > 0]
factor_returns = factor_returns[factor_returns > 0]
return func(returns, factor_returns, **kwargs) | [
"def",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"returns",
"=",
"returns",
"[",
"factor_returns",
">",
"0",
"]",
"factor_returns",
"=",
"factor_returns",
"[... | Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
Same as the return of the function | [
"Calculates",
"a",
"given",
"statistic",
"filtering",
"only",
"positive",
"factor",
"return",
"periods",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L121-L144 |
224,653 | quantopian/empyrical | empyrical/utils.py | down | def down(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
Same as the return of the 'function'
"""
func = kwargs.pop('function')
returns = returns[factor_returns < 0]
factor_returns = factor_returns[factor_returns < 0]
return func(returns, factor_returns, **kwargs) | python | def down(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
Same as the return of the 'function'
"""
func = kwargs.pop('function')
returns = returns[factor_returns < 0]
factor_returns = factor_returns[factor_returns < 0]
return func(returns, factor_returns, **kwargs) | [
"def",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"returns",
"=",
"returns",
"[",
"factor_returns",
"<",
"0",
"]",
"factor_returns",
"=",
"factor_returns",
... | Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
Same as the return of the 'function' | [
"Calculates",
"a",
"given",
"statistic",
"filtering",
"only",
"negative",
"factor",
"return",
"periods",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L147-L170 |
224,654 | quantopian/empyrical | empyrical/utils.py | get_treasury_yield | def get_treasury_yield(start=None, end=None, period='3MO'):
"""
Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
period : {'1MO', '3MO', '6MO', 1', '5', '10'}, optional
Which maturity to use.
Returns
-------
pd.Series
Annual treasury yield for every day.
"""
if start is None:
start = '1/1/1970'
if end is None:
end = _1_bday_ago()
treasury = web.DataReader("DGS3{}".format(period), "fred",
start, end)
treasury = treasury.ffill()
return treasury | python | def get_treasury_yield(start=None, end=None, period='3MO'):
"""
Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
period : {'1MO', '3MO', '6MO', 1', '5', '10'}, optional
Which maturity to use.
Returns
-------
pd.Series
Annual treasury yield for every day.
"""
if start is None:
start = '1/1/1970'
if end is None:
end = _1_bday_ago()
treasury = web.DataReader("DGS3{}".format(period), "fred",
start, end)
treasury = treasury.ffill()
return treasury | [
"def",
"get_treasury_yield",
"(",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"period",
"=",
"'3MO'",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"'1/1/1970'",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"_1_bday_ago",
"(",
")",... | Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
period : {'1MO', '3MO', '6MO', 1', '5', '10'}, optional
Which maturity to use.
Returns
-------
pd.Series
Annual treasury yield for every day. | [
"Load",
"treasury",
"yields",
"from",
"FRED",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L379-L409 |
224,655 | quantopian/empyrical | empyrical/utils.py | default_returns_func | def default_returns_func(symbol, start=None, end=None):
"""
Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
Returns
-------
pd.Series
Daily returns for the symbol.
- See full explanation in tears.create_full_tear_sheet (returns).
"""
if start is None:
start = '1/1/1970'
if end is None:
end = _1_bday_ago()
start = get_utc_timestamp(start)
end = get_utc_timestamp(end)
if symbol == 'SPY':
filepath = data_path('spy.csv')
rets = get_returns_cached(filepath,
get_symbol_returns_from_yahoo,
end,
symbol='SPY',
start='1/1/1970',
end=datetime.now())
rets = rets[start:end]
else:
rets = get_symbol_returns_from_yahoo(symbol, start=start, end=end)
return rets[symbol] | python | def default_returns_func(symbol, start=None, end=None):
"""
Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
Returns
-------
pd.Series
Daily returns for the symbol.
- See full explanation in tears.create_full_tear_sheet (returns).
"""
if start is None:
start = '1/1/1970'
if end is None:
end = _1_bday_ago()
start = get_utc_timestamp(start)
end = get_utc_timestamp(end)
if symbol == 'SPY':
filepath = data_path('spy.csv')
rets = get_returns_cached(filepath,
get_symbol_returns_from_yahoo,
end,
symbol='SPY',
start='1/1/1970',
end=datetime.now())
rets = rets[start:end]
else:
rets = get_symbol_returns_from_yahoo(symbol, start=start, end=end)
return rets[symbol] | [
"def",
"default_returns_func",
"(",
"symbol",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"'1/1/1970'",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"_1_bday_ago",
"(",
")",
"start",
"=... | Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
Returns
-------
pd.Series
Daily returns for the symbol.
- See full explanation in tears.create_full_tear_sheet (returns). | [
"Gets",
"returns",
"for",
"a",
"symbol",
".",
"Queries",
"Yahoo",
"Finance",
".",
"Attempts",
"to",
"cache",
"SPY",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L452-L495 |
224,656 | quantopian/empyrical | empyrical/perf_attrib.py | perf_attrib | def perf_attrib(returns,
positions,
factor_returns,
factor_loadings):
"""
Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., contributed to total returns, as
well as the daily exposure to each of the risk factors. The returns that
can be attributed to one of the given risk factors are the
`common_returns`, and the returns that _cannot_ be attributed to a risk
factor are the `specific_returns`. The `common_returns` and
`specific_returns` summed together will always equal the total returns.
Parameters
----------
returns : pd.Series
Returns for each day in the date range.
- Example:
2017-01-01 -0.017098
2017-01-02 0.002683
2017-01-03 -0.008669
positions: pd.Series
Daily holdings in percentages, indexed by date.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
XOM 0.571429
2017-01-02 AAPL 0.202381
TLT 0.535714
XOM 0.261905
factor_returns : pd.DataFrame
Returns by factor, with date as index and factors as columns
- Example:
momentum reversal
2017-01-01 0.002779 -0.005453
2017-01-02 0.001096 0.010290
factor_loadings : pd.DataFrame
Factor loadings for all days in the date range, with date and ticker as
index, and factors as columns.
- Example:
momentum reversal
dt ticker
2017-01-01 AAPL -1.592914 0.852830
TLT 0.184864 0.895534
XOM 0.993160 1.149353
2017-01-02 AAPL -0.140009 -0.524952
TLT -1.066978 0.185435
XOM -1.798401 0.761549
Returns
-------
tuple of (risk_exposures_portfolio, perf_attribution)
risk_exposures_portfolio : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
2017-01-01 -0.238655 0.077123
2017-01-02 0.821872 1.520515
perf_attribution : pd.DataFrame
df with factors, common returns, and specific returns as columns,
and datetimes as index
- Example:
momentum reversal common_returns specific_returns
dt
2017-01-01 0.249087 0.935925 1.185012 1.185012
2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980
Note
----
See https://en.wikipedia.org/wiki/Performance_attribution for more details.
"""
risk_exposures_portfolio = compute_exposures(positions,
factor_loadings)
perf_attrib_by_factor = risk_exposures_portfolio.multiply(factor_returns)
common_returns = perf_attrib_by_factor.sum(axis='columns')
specific_returns = returns - common_returns
returns_df = pd.DataFrame({'total_returns': returns,
'common_returns': common_returns,
'specific_returns': specific_returns})
return (risk_exposures_portfolio,
pd.concat([perf_attrib_by_factor, returns_df], axis='columns')) | python | def perf_attrib(returns,
positions,
factor_returns,
factor_loadings):
"""
Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., contributed to total returns, as
well as the daily exposure to each of the risk factors. The returns that
can be attributed to one of the given risk factors are the
`common_returns`, and the returns that _cannot_ be attributed to a risk
factor are the `specific_returns`. The `common_returns` and
`specific_returns` summed together will always equal the total returns.
Parameters
----------
returns : pd.Series
Returns for each day in the date range.
- Example:
2017-01-01 -0.017098
2017-01-02 0.002683
2017-01-03 -0.008669
positions: pd.Series
Daily holdings in percentages, indexed by date.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
XOM 0.571429
2017-01-02 AAPL 0.202381
TLT 0.535714
XOM 0.261905
factor_returns : pd.DataFrame
Returns by factor, with date as index and factors as columns
- Example:
momentum reversal
2017-01-01 0.002779 -0.005453
2017-01-02 0.001096 0.010290
factor_loadings : pd.DataFrame
Factor loadings for all days in the date range, with date and ticker as
index, and factors as columns.
- Example:
momentum reversal
dt ticker
2017-01-01 AAPL -1.592914 0.852830
TLT 0.184864 0.895534
XOM 0.993160 1.149353
2017-01-02 AAPL -0.140009 -0.524952
TLT -1.066978 0.185435
XOM -1.798401 0.761549
Returns
-------
tuple of (risk_exposures_portfolio, perf_attribution)
risk_exposures_portfolio : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
2017-01-01 -0.238655 0.077123
2017-01-02 0.821872 1.520515
perf_attribution : pd.DataFrame
df with factors, common returns, and specific returns as columns,
and datetimes as index
- Example:
momentum reversal common_returns specific_returns
dt
2017-01-01 0.249087 0.935925 1.185012 1.185012
2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980
Note
----
See https://en.wikipedia.org/wiki/Performance_attribution for more details.
"""
risk_exposures_portfolio = compute_exposures(positions,
factor_loadings)
perf_attrib_by_factor = risk_exposures_portfolio.multiply(factor_returns)
common_returns = perf_attrib_by_factor.sum(axis='columns')
specific_returns = returns - common_returns
returns_df = pd.DataFrame({'total_returns': returns,
'common_returns': common_returns,
'specific_returns': specific_returns})
return (risk_exposures_portfolio,
pd.concat([perf_attrib_by_factor, returns_df], axis='columns')) | [
"def",
"perf_attrib",
"(",
"returns",
",",
"positions",
",",
"factor_returns",
",",
"factor_loadings",
")",
":",
"risk_exposures_portfolio",
"=",
"compute_exposures",
"(",
"positions",
",",
"factor_loadings",
")",
"perf_attrib_by_factor",
"=",
"risk_exposures_portfolio",
... | Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., contributed to total returns, as
well as the daily exposure to each of the risk factors. The returns that
can be attributed to one of the given risk factors are the
`common_returns`, and the returns that _cannot_ be attributed to a risk
factor are the `specific_returns`. The `common_returns` and
`specific_returns` summed together will always equal the total returns.
Parameters
----------
returns : pd.Series
Returns for each day in the date range.
- Example:
2017-01-01 -0.017098
2017-01-02 0.002683
2017-01-03 -0.008669
positions: pd.Series
Daily holdings in percentages, indexed by date.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
XOM 0.571429
2017-01-02 AAPL 0.202381
TLT 0.535714
XOM 0.261905
factor_returns : pd.DataFrame
Returns by factor, with date as index and factors as columns
- Example:
momentum reversal
2017-01-01 0.002779 -0.005453
2017-01-02 0.001096 0.010290
factor_loadings : pd.DataFrame
Factor loadings for all days in the date range, with date and ticker as
index, and factors as columns.
- Example:
momentum reversal
dt ticker
2017-01-01 AAPL -1.592914 0.852830
TLT 0.184864 0.895534
XOM 0.993160 1.149353
2017-01-02 AAPL -0.140009 -0.524952
TLT -1.066978 0.185435
XOM -1.798401 0.761549
Returns
-------
tuple of (risk_exposures_portfolio, perf_attribution)
risk_exposures_portfolio : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
2017-01-01 -0.238655 0.077123
2017-01-02 0.821872 1.520515
perf_attribution : pd.DataFrame
df with factors, common returns, and specific returns as columns,
and datetimes as index
- Example:
momentum reversal common_returns specific_returns
dt
2017-01-01 0.249087 0.935925 1.185012 1.185012
2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980
Note
----
See https://en.wikipedia.org/wiki/Performance_attribution for more details. | [
"Attributes",
"the",
"performance",
"of",
"a",
"returns",
"stream",
"to",
"a",
"set",
"of",
"risk",
"factors",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/perf_attrib.py#L4-L97 |
224,657 | quantopian/empyrical | empyrical/perf_attrib.py | compute_exposures | def compute_exposures(positions, factor_loadings):
"""
Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
XOM 0.571429
2017-01-02 AAPL 0.202381
TLT 0.535714
XOM 0.261905
factor_loadings : pd.DataFrame
Factor loadings for all days in the date range, with date and ticker as
index, and factors as columns.
- Example:
momentum reversal
dt ticker
2017-01-01 AAPL -1.592914 0.852830
TLT 0.184864 0.895534
XOM 0.993160 1.149353
2017-01-02 AAPL -0.140009 -0.524952
TLT -1.066978 0.185435
XOM -1.798401 0.761549
Returns
-------
risk_exposures_portfolio : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
2017-01-01 -0.238655 0.077123
2017-01-02 0.821872 1.520515
"""
risk_exposures = factor_loadings.multiply(positions, axis='rows')
return risk_exposures.groupby(level='dt').sum() | python | def compute_exposures(positions, factor_loadings):
"""
Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
XOM 0.571429
2017-01-02 AAPL 0.202381
TLT 0.535714
XOM 0.261905
factor_loadings : pd.DataFrame
Factor loadings for all days in the date range, with date and ticker as
index, and factors as columns.
- Example:
momentum reversal
dt ticker
2017-01-01 AAPL -1.592914 0.852830
TLT 0.184864 0.895534
XOM 0.993160 1.149353
2017-01-02 AAPL -0.140009 -0.524952
TLT -1.066978 0.185435
XOM -1.798401 0.761549
Returns
-------
risk_exposures_portfolio : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
2017-01-01 -0.238655 0.077123
2017-01-02 0.821872 1.520515
"""
risk_exposures = factor_loadings.multiply(positions, axis='rows')
return risk_exposures.groupby(level='dt').sum() | [
"def",
"compute_exposures",
"(",
"positions",
",",
"factor_loadings",
")",
":",
"risk_exposures",
"=",
"factor_loadings",
".",
"multiply",
"(",
"positions",
",",
"axis",
"=",
"'rows'",
")",
"return",
"risk_exposures",
".",
"groupby",
"(",
"level",
"=",
"'dt'",
... | Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
XOM 0.571429
2017-01-02 AAPL 0.202381
TLT 0.535714
XOM 0.261905
factor_loadings : pd.DataFrame
Factor loadings for all days in the date range, with date and ticker as
index, and factors as columns.
- Example:
momentum reversal
dt ticker
2017-01-01 AAPL -1.592914 0.852830
TLT 0.184864 0.895534
XOM 0.993160 1.149353
2017-01-02 AAPL -0.140009 -0.524952
TLT -1.066978 0.185435
XOM -1.798401 0.761549
Returns
-------
risk_exposures_portfolio : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
2017-01-01 -0.238655 0.077123
2017-01-02 0.821872 1.520515 | [
"Compute",
"daily",
"risk",
"factor",
"exposures",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/perf_attrib.py#L100-L141 |
224,658 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.has_pending | def has_pending(self):
"""Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.workqueue:
return True
for assigned_unit in self.assigned_work.values():
if self._pending_of(assigned_unit) > 0:
return True
return False | python | def has_pending(self):
"""Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.workqueue:
return True
for assigned_unit in self.assigned_work.values():
if self._pending_of(assigned_unit) > 0:
return True
return False | [
"def",
"has_pending",
"(",
"self",
")",
":",
"if",
"self",
".",
"workqueue",
":",
"return",
"True",
"for",
"assigned_unit",
"in",
"self",
".",
"assigned_work",
".",
"values",
"(",
")",
":",
"if",
"self",
".",
"_pending_of",
"(",
"assigned_unit",
")",
">"... | Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active". | [
"Return",
"True",
"if",
"there",
"are",
"pending",
"test",
"items",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L133-L147 |
224,659 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.add_node | def add_node(self, node):
"""Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node.
"""
assert node not in self.assigned_work
self.assigned_work[node] = OrderedDict() | python | def add_node(self, node):
"""Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node.
"""
assert node not in self.assigned_work
self.assigned_work[node] = OrderedDict() | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"assert",
"node",
"not",
"in",
"self",
".",
"assigned_work",
"self",
".",
"assigned_work",
"[",
"node",
"]",
"=",
"OrderedDict",
"(",
")"
] | Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node. | [
"Add",
"a",
"new",
"node",
"to",
"the",
"scheduler",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L149-L158 |
224,660 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.remove_node | def remove_node(self, node):
"""Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfinished``.
- ``DSession.worker_errordown``.
Return the item being executed while the node crashed or None if the
node has no more pending items.
"""
workload = self.assigned_work.pop(node)
if not self._pending_of(workload):
return None
# The node crashed, identify test that crashed
for work_unit in workload.values():
for nodeid, completed in work_unit.items():
if not completed:
crashitem = nodeid
break
else:
continue
break
else:
raise RuntimeError(
"Unable to identify crashitem on a workload with pending items"
)
# Made uncompleted work unit available again
self.workqueue.update(workload)
for node in self.assigned_work:
self._reschedule(node)
return crashitem | python | def remove_node(self, node):
"""Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfinished``.
- ``DSession.worker_errordown``.
Return the item being executed while the node crashed or None if the
node has no more pending items.
"""
workload = self.assigned_work.pop(node)
if not self._pending_of(workload):
return None
# The node crashed, identify test that crashed
for work_unit in workload.values():
for nodeid, completed in work_unit.items():
if not completed:
crashitem = nodeid
break
else:
continue
break
else:
raise RuntimeError(
"Unable to identify crashitem on a workload with pending items"
)
# Made uncompleted work unit available again
self.workqueue.update(workload)
for node in self.assigned_work:
self._reschedule(node)
return crashitem | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"workload",
"=",
"self",
".",
"assigned_work",
".",
"pop",
"(",
"node",
")",
"if",
"not",
"self",
".",
"_pending_of",
"(",
"workload",
")",
":",
"return",
"None",
"# The node crashed, identify test th... | Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfinished``.
- ``DSession.worker_errordown``.
Return the item being executed while the node crashed or None if the
node has no more pending items. | [
"Remove",
"a",
"node",
"from",
"the",
"scheduler",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L160-L199 |
224,661 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.add_node_collection | def add_node_collection(self, node, collection):
"""Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``.
"""
# Check that add_node() was called on the node before
assert node in self.assigned_work
# A new node has been added later, perhaps an original one died.
if self.collection_is_completed:
# Assert that .schedule() should have been called by now
assert self.collection
# Check that the new collection matches the official collection
if collection != self.collection:
other_node = next(iter(self.registered_collections.keys()))
msg = report_collection_diff(
self.collection, collection, other_node.gateway.id, node.gateway.id
)
self.log(msg)
return
self.registered_collections[node] = list(collection) | python | def add_node_collection(self, node, collection):
"""Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``.
"""
# Check that add_node() was called on the node before
assert node in self.assigned_work
# A new node has been added later, perhaps an original one died.
if self.collection_is_completed:
# Assert that .schedule() should have been called by now
assert self.collection
# Check that the new collection matches the official collection
if collection != self.collection:
other_node = next(iter(self.registered_collections.keys()))
msg = report_collection_diff(
self.collection, collection, other_node.gateway.id, node.gateway.id
)
self.log(msg)
return
self.registered_collections[node] = list(collection) | [
"def",
"add_node_collection",
"(",
"self",
",",
"node",
",",
"collection",
")",
":",
"# Check that add_node() was called on the node before",
"assert",
"node",
"in",
"self",
".",
"assigned_work",
"# A new node has been added later, perhaps an original one died.",
"if",
"self",
... | Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``. | [
"Add",
"the",
"collected",
"test",
"items",
"from",
"a",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L201-L231 |
224,662 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._assign_work_unit | def _assign_work_unit(self, node):
"""Assign a work unit to a node."""
assert self.workqueue
# Grab a unit of work
scope, work_unit = self.workqueue.popitem(last=False)
# Keep track of the assigned work
assigned_to_node = self.assigned_work.setdefault(node, default=OrderedDict())
assigned_to_node[scope] = work_unit
# Ask the node to execute the workload
worker_collection = self.registered_collections[node]
nodeids_indexes = [
worker_collection.index(nodeid)
for nodeid, completed in work_unit.items()
if not completed
]
node.send_runtest_some(nodeids_indexes) | python | def _assign_work_unit(self, node):
"""Assign a work unit to a node."""
assert self.workqueue
# Grab a unit of work
scope, work_unit = self.workqueue.popitem(last=False)
# Keep track of the assigned work
assigned_to_node = self.assigned_work.setdefault(node, default=OrderedDict())
assigned_to_node[scope] = work_unit
# Ask the node to execute the workload
worker_collection = self.registered_collections[node]
nodeids_indexes = [
worker_collection.index(nodeid)
for nodeid, completed in work_unit.items()
if not completed
]
node.send_runtest_some(nodeids_indexes) | [
"def",
"_assign_work_unit",
"(",
"self",
",",
"node",
")",
":",
"assert",
"self",
".",
"workqueue",
"# Grab a unit of work",
"scope",
",",
"work_unit",
"=",
"self",
".",
"workqueue",
".",
"popitem",
"(",
"last",
"=",
"False",
")",
"# Keep track of the assigned w... | Assign a work unit to a node. | [
"Assign",
"a",
"work",
"unit",
"to",
"a",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L246-L265 |
224,663 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._pending_of | def _pending_of(self, workload):
"""Return the number of pending tests in a workload."""
pending = sum(list(scope.values()).count(False) for scope in workload.values())
return pending | python | def _pending_of(self, workload):
"""Return the number of pending tests in a workload."""
pending = sum(list(scope.values()).count(False) for scope in workload.values())
return pending | [
"def",
"_pending_of",
"(",
"self",
",",
"workload",
")",
":",
"pending",
"=",
"sum",
"(",
"list",
"(",
"scope",
".",
"values",
"(",
")",
")",
".",
"count",
"(",
"False",
")",
"for",
"scope",
"in",
"workload",
".",
"values",
"(",
")",
")",
"return",... | Return the number of pending tests in a workload. | [
"Return",
"the",
"number",
"of",
"pending",
"tests",
"in",
"a",
"workload",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L291-L294 |
224,664 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._reschedule | def _reschedule(self, node):
"""Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests.
"""
# Do not add more work to a node shutting down
if node.shutting_down:
return
# Check that more work is available
if not self.workqueue:
node.shutdown()
return
self.log("Number of units waiting for node:", len(self.workqueue))
# Check that the node is almost depleted of work
# 2: Heuristic of minimum tests to enqueue more work
if self._pending_of(self.assigned_work[node]) > 2:
return
# Pop one unit of work and assign it
self._assign_work_unit(node) | python | def _reschedule(self, node):
"""Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests.
"""
# Do not add more work to a node shutting down
if node.shutting_down:
return
# Check that more work is available
if not self.workqueue:
node.shutdown()
return
self.log("Number of units waiting for node:", len(self.workqueue))
# Check that the node is almost depleted of work
# 2: Heuristic of minimum tests to enqueue more work
if self._pending_of(self.assigned_work[node]) > 2:
return
# Pop one unit of work and assign it
self._assign_work_unit(node) | [
"def",
"_reschedule",
"(",
"self",
",",
"node",
")",
":",
"# Do not add more work to a node shutting down",
"if",
"node",
".",
"shutting_down",
":",
"return",
"# Check that more work is available",
"if",
"not",
"self",
".",
"workqueue",
":",
"node",
".",
"shutdown",
... | Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests. | [
"Maybe",
"schedule",
"new",
"items",
"on",
"the",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L296-L320 |
224,665 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.schedule | def schedule(self):
"""Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collection_is_completed`` is True, this is called by the hook:
- ``DSession.worker_collectionfinish``.
"""
assert self.collection_is_completed
# Initial distribution already happened, reschedule on all nodes
if self.collection is not None:
for node in self.nodes:
self._reschedule(node)
return
# Check that all nodes collected the same tests
if not self._check_nodes_have_same_collection():
self.log("**Different tests collected, aborting run**")
return
# Collections are identical, create the final list of items
self.collection = list(next(iter(self.registered_collections.values())))
if not self.collection:
return
# Determine chunks of work (scopes)
for nodeid in self.collection:
scope = self._split_scope(nodeid)
work_unit = self.workqueue.setdefault(scope, default=OrderedDict())
work_unit[nodeid] = False
# Avoid having more workers than work
extra_nodes = len(self.nodes) - len(self.workqueue)
if extra_nodes > 0:
self.log("Shuting down {0} nodes".format(extra_nodes))
for _ in range(extra_nodes):
unused_node, assigned = self.assigned_work.popitem(last=True)
self.log("Shuting down unused node {0}".format(unused_node))
unused_node.shutdown()
# Assign initial workload
for node in self.nodes:
self._assign_work_unit(node)
# Ensure nodes start with at least two work units if possible (#277)
for node in self.nodes:
self._reschedule(node)
# Initial distribution sent all tests, start node shutdown
if not self.workqueue:
for node in self.nodes:
node.shutdown() | python | def schedule(self):
"""Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collection_is_completed`` is True, this is called by the hook:
- ``DSession.worker_collectionfinish``.
"""
assert self.collection_is_completed
# Initial distribution already happened, reschedule on all nodes
if self.collection is not None:
for node in self.nodes:
self._reschedule(node)
return
# Check that all nodes collected the same tests
if not self._check_nodes_have_same_collection():
self.log("**Different tests collected, aborting run**")
return
# Collections are identical, create the final list of items
self.collection = list(next(iter(self.registered_collections.values())))
if not self.collection:
return
# Determine chunks of work (scopes)
for nodeid in self.collection:
scope = self._split_scope(nodeid)
work_unit = self.workqueue.setdefault(scope, default=OrderedDict())
work_unit[nodeid] = False
# Avoid having more workers than work
extra_nodes = len(self.nodes) - len(self.workqueue)
if extra_nodes > 0:
self.log("Shuting down {0} nodes".format(extra_nodes))
for _ in range(extra_nodes):
unused_node, assigned = self.assigned_work.popitem(last=True)
self.log("Shuting down unused node {0}".format(unused_node))
unused_node.shutdown()
# Assign initial workload
for node in self.nodes:
self._assign_work_unit(node)
# Ensure nodes start with at least two work units if possible (#277)
for node in self.nodes:
self._reschedule(node)
# Initial distribution sent all tests, start node shutdown
if not self.workqueue:
for node in self.nodes:
node.shutdown() | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"# Initial distribution already happened, reschedule on all nodes",
"if",
"self",
".",
"collection",
"is",
"not",
"None",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",... | Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collection_is_completed`` is True, this is called by the hook:
- ``DSession.worker_collectionfinish``. | [
"Initiate",
"distribution",
"of",
"the",
"test",
"collection",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L322-L380 |
224,666 | pytest-dev/pytest-xdist | xdist/scheduler/each.py | EachScheduling.schedule | def schedule(self):
"""Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those tests.
"""
assert self.collection_is_completed
for node, pending in self.node2pending.items():
if node in self._started:
continue
if not pending:
pending[:] = range(len(self.node2collection[node]))
node.send_runtest_all()
node.shutdown()
else:
node.send_runtest_some(pending)
self._started.append(node) | python | def schedule(self):
"""Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those tests.
"""
assert self.collection_is_completed
for node, pending in self.node2pending.items():
if node in self._started:
continue
if not pending:
pending[:] = range(len(self.node2collection[node]))
node.send_runtest_all()
node.shutdown()
else:
node.send_runtest_some(pending)
self._started.append(node) | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"for",
"node",
",",
"pending",
"in",
"self",
".",
"node2pending",
".",
"items",
"(",
")",
":",
"if",
"node",
"in",
"self",
".",
"_started",
":",
"continue",
"if",... | Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those tests. | [
"Schedule",
"the",
"test",
"items",
"on",
"the",
"nodes"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/each.py#L114-L132 |
224,667 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.has_pending | def has_pending(self):
"""Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.pending:
return True
for pending in self.node2pending.values():
if pending:
return True
return False | python | def has_pending(self):
"""Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.pending:
return True
for pending in self.node2pending.values():
if pending:
return True
return False | [
"def",
"has_pending",
"(",
"self",
")",
":",
"if",
"self",
".",
"pending",
":",
"return",
"True",
"for",
"pending",
"in",
"self",
".",
"node2pending",
".",
"values",
"(",
")",
":",
"if",
"pending",
":",
"return",
"True",
"return",
"False"
] | Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active". | [
"Return",
"True",
"if",
"there",
"are",
"pending",
"test",
"items"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L96-L108 |
224,668 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.check_schedule | def check_schedule(self, node, duration=0):
"""Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influence how many tests the node is assigned.
"""
if node.shutting_down:
return
if self.pending:
# how many nodes do we have?
num_nodes = len(self.node2pending)
# if our node goes below a heuristic minimum, fill it out to
# heuristic maximum
items_per_node_min = max(2, len(self.pending) // num_nodes // 4)
items_per_node_max = max(2, len(self.pending) // num_nodes // 2)
node_pending = self.node2pending[node]
if len(node_pending) < items_per_node_min:
if duration >= 0.1 and len(node_pending) >= 2:
# seems the node is doing long-running tests
# and has enough items to continue
# so let's rather wait with sending new items
return
num_send = items_per_node_max - len(node_pending)
self._send_tests(node, num_send)
else:
node.shutdown()
self.log("num items waiting for node:", len(self.pending)) | python | def check_schedule(self, node, duration=0):
"""Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influence how many tests the node is assigned.
"""
if node.shutting_down:
return
if self.pending:
# how many nodes do we have?
num_nodes = len(self.node2pending)
# if our node goes below a heuristic minimum, fill it out to
# heuristic maximum
items_per_node_min = max(2, len(self.pending) // num_nodes // 4)
items_per_node_max = max(2, len(self.pending) // num_nodes // 2)
node_pending = self.node2pending[node]
if len(node_pending) < items_per_node_min:
if duration >= 0.1 and len(node_pending) >= 2:
# seems the node is doing long-running tests
# and has enough items to continue
# so let's rather wait with sending new items
return
num_send = items_per_node_max - len(node_pending)
self._send_tests(node, num_send)
else:
node.shutdown()
self.log("num items waiting for node:", len(self.pending)) | [
"def",
"check_schedule",
"(",
"self",
",",
"node",
",",
"duration",
"=",
"0",
")",
":",
"if",
"node",
".",
"shutting_down",
":",
"return",
"if",
"self",
".",
"pending",
":",
"# how many nodes do we have?",
"num_nodes",
"=",
"len",
"(",
"self",
".",
"node2p... | Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influence how many tests the node is assigned. | [
"Maybe",
"schedule",
"new",
"items",
"on",
"the",
"node"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L154-L184 |
224,669 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.remove_node | def remove_node(self, node):
"""Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
``DSession.worker_errordown`` hooks.
Return the item which was being executing while the node
crashed or None if the node has no more pending items.
"""
pending = self.node2pending.pop(node)
if not pending:
return
# The node crashed, reassing pending items
crashitem = self.collection[pending.pop(0)]
self.pending.extend(pending)
for node in self.node2pending:
self.check_schedule(node)
return crashitem | python | def remove_node(self, node):
"""Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
``DSession.worker_errordown`` hooks.
Return the item which was being executing while the node
crashed or None if the node has no more pending items.
"""
pending = self.node2pending.pop(node)
if not pending:
return
# The node crashed, reassing pending items
crashitem = self.collection[pending.pop(0)]
self.pending.extend(pending)
for node in self.node2pending:
self.check_schedule(node)
return crashitem | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"pending",
"=",
"self",
".",
"node2pending",
".",
"pop",
"(",
"node",
")",
"if",
"not",
"pending",
":",
"return",
"# The node crashed, reassing pending items",
"crashitem",
"=",
"self",
".",
"collection... | Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
``DSession.worker_errordown`` hooks.
Return the item which was being executing while the node
crashed or None if the node has no more pending items. | [
"Remove",
"a",
"node",
"from",
"the",
"scheduler"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L186-L208 |
224,670 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.schedule | def schedule(self):
"""Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
This is called by the ``DSession.worker_collectionfinish`` hook
if ``.collection_is_completed`` is True.
"""
assert self.collection_is_completed
# Initial distribution already happened, reschedule on all nodes
if self.collection is not None:
for node in self.nodes:
self.check_schedule(node)
return
# XXX allow nodes to have different collections
if not self._check_nodes_have_same_collection():
self.log("**Different tests collected, aborting run**")
return
# Collections are identical, create the index of pending items.
self.collection = list(self.node2collection.values())[0]
self.pending[:] = range(len(self.collection))
if not self.collection:
return
# Send a batch of tests to run. If we don't have at least two
# tests per node, we have to send them all so that we can send
# shutdown signals and get all nodes working.
initial_batch = max(len(self.pending) // 4, 2 * len(self.nodes))
# distribute tests round-robin up to the batch size
# (or until we run out)
nodes = cycle(self.nodes)
for i in range(initial_batch):
self._send_tests(next(nodes), 1)
if not self.pending:
# initial distribution sent all tests, start node shutdown
for node in self.nodes:
node.shutdown() | python | def schedule(self):
"""Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
This is called by the ``DSession.worker_collectionfinish`` hook
if ``.collection_is_completed`` is True.
"""
assert self.collection_is_completed
# Initial distribution already happened, reschedule on all nodes
if self.collection is not None:
for node in self.nodes:
self.check_schedule(node)
return
# XXX allow nodes to have different collections
if not self._check_nodes_have_same_collection():
self.log("**Different tests collected, aborting run**")
return
# Collections are identical, create the index of pending items.
self.collection = list(self.node2collection.values())[0]
self.pending[:] = range(len(self.collection))
if not self.collection:
return
# Send a batch of tests to run. If we don't have at least two
# tests per node, we have to send them all so that we can send
# shutdown signals and get all nodes working.
initial_batch = max(len(self.pending) // 4, 2 * len(self.nodes))
# distribute tests round-robin up to the batch size
# (or until we run out)
nodes = cycle(self.nodes)
for i in range(initial_batch):
self._send_tests(next(nodes), 1)
if not self.pending:
# initial distribution sent all tests, start node shutdown
for node in self.nodes:
node.shutdown() | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"# Initial distribution already happened, reschedule on all nodes",
"if",
"self",
".",
"collection",
"is",
"not",
"None",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",... | Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
This is called by the ``DSession.worker_collectionfinish`` hook
if ``.collection_is_completed`` is True. | [
"Initiate",
"distribution",
"of",
"the",
"test",
"collection"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L210-L254 |
224,671 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling._check_nodes_have_same_collection | def _check_nodes_have_same_collection(self):
"""Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook.
"""
node_collection_items = list(self.node2collection.items())
first_node, col = node_collection_items[0]
same_collection = True
for node, collection in node_collection_items[1:]:
msg = report_collection_diff(
col, collection, first_node.gateway.id, node.gateway.id
)
if msg:
same_collection = False
self.log(msg)
if self.config is not None:
rep = CollectReport(
node.gateway.id, "failed", longrepr=msg, result=[]
)
self.config.hook.pytest_collectreport(report=rep)
return same_collection | python | def _check_nodes_have_same_collection(self):
"""Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook.
"""
node_collection_items = list(self.node2collection.items())
first_node, col = node_collection_items[0]
same_collection = True
for node, collection in node_collection_items[1:]:
msg = report_collection_diff(
col, collection, first_node.gateway.id, node.gateway.id
)
if msg:
same_collection = False
self.log(msg)
if self.config is not None:
rep = CollectReport(
node.gateway.id, "failed", longrepr=msg, result=[]
)
self.config.hook.pytest_collectreport(report=rep)
return same_collection | [
"def",
"_check_nodes_have_same_collection",
"(",
"self",
")",
":",
"node_collection_items",
"=",
"list",
"(",
"self",
".",
"node2collection",
".",
"items",
"(",
")",
")",
"first_node",
",",
"col",
"=",
"node_collection_items",
"[",
"0",
"]",
"same_collection",
"... | Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook. | [
"Return",
"True",
"if",
"all",
"nodes",
"have",
"collected",
"the",
"same",
"items",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L263-L286 |
224,672 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.loop_once | def loop_once(self):
"""Process one callback from one of the workers."""
while 1:
if not self._active_nodes:
# If everything has died stop looping
self.triggershutdown()
raise RuntimeError("Unexpectedly no active workers available")
try:
eventcall = self.queue.get(timeout=2.0)
break
except Empty:
continue
callname, kwargs = eventcall
assert callname, kwargs
method = "worker_" + callname
call = getattr(self, method)
self.log("calling method", method, kwargs)
call(**kwargs)
if self.sched.tests_finished:
self.triggershutdown() | python | def loop_once(self):
"""Process one callback from one of the workers."""
while 1:
if not self._active_nodes:
# If everything has died stop looping
self.triggershutdown()
raise RuntimeError("Unexpectedly no active workers available")
try:
eventcall = self.queue.get(timeout=2.0)
break
except Empty:
continue
callname, kwargs = eventcall
assert callname, kwargs
method = "worker_" + callname
call = getattr(self, method)
self.log("calling method", method, kwargs)
call(**kwargs)
if self.sched.tests_finished:
self.triggershutdown() | [
"def",
"loop_once",
"(",
"self",
")",
":",
"while",
"1",
":",
"if",
"not",
"self",
".",
"_active_nodes",
":",
"# If everything has died stop looping",
"self",
".",
"triggershutdown",
"(",
")",
"raise",
"RuntimeError",
"(",
"\"Unexpectedly no active workers available\"... | Process one callback from one of the workers. | [
"Process",
"one",
"callback",
"from",
"one",
"of",
"the",
"workers",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L121-L140 |
224,673 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_workerready | def worker_workerready(self, node, workerinfo):
"""Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input.
"""
node.workerinfo = workerinfo
node.workerinfo["id"] = node.gateway.id
node.workerinfo["spec"] = node.gateway.spec
# TODO: (#234 task) needs this for pytest. Remove when refactor in pytest repo
node.slaveinfo = node.workerinfo
self.config.hook.pytest_testnodeready(node=node)
if self.shuttingdown:
node.shutdown()
else:
self.sched.add_node(node) | python | def worker_workerready(self, node, workerinfo):
"""Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input.
"""
node.workerinfo = workerinfo
node.workerinfo["id"] = node.gateway.id
node.workerinfo["spec"] = node.gateway.spec
# TODO: (#234 task) needs this for pytest. Remove when refactor in pytest repo
node.slaveinfo = node.workerinfo
self.config.hook.pytest_testnodeready(node=node)
if self.shuttingdown:
node.shutdown()
else:
self.sched.add_node(node) | [
"def",
"worker_workerready",
"(",
"self",
",",
"node",
",",
"workerinfo",
")",
":",
"node",
".",
"workerinfo",
"=",
"workerinfo",
"node",
".",
"workerinfo",
"[",
"\"id\"",
"]",
"=",
"node",
".",
"gateway",
".",
"id",
"node",
".",
"workerinfo",
"[",
"\"sp... | Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input. | [
"Emitted",
"when",
"a",
"node",
"first",
"starts",
"up",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L146-L163 |
224,674 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_workerfinished | def worker_workerfinished(self, node):
"""Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered.
"""
self.config.hook.pytest_testnodedown(node=node, error=None)
if node.workeroutput["exitstatus"] == 2: # keyboard-interrupt
self.shouldstop = "%s received keyboard-interrupt" % (node,)
self.worker_errordown(node, "keyboard-interrupt")
return
if node in self.sched.nodes:
crashitem = self.sched.remove_node(node)
assert not crashitem, (crashitem, node)
self._active_nodes.remove(node) | python | def worker_workerfinished(self, node):
"""Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered.
"""
self.config.hook.pytest_testnodedown(node=node, error=None)
if node.workeroutput["exitstatus"] == 2: # keyboard-interrupt
self.shouldstop = "%s received keyboard-interrupt" % (node,)
self.worker_errordown(node, "keyboard-interrupt")
return
if node in self.sched.nodes:
crashitem = self.sched.remove_node(node)
assert not crashitem, (crashitem, node)
self._active_nodes.remove(node) | [
"def",
"worker_workerfinished",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_testnodedown",
"(",
"node",
"=",
"node",
",",
"error",
"=",
"None",
")",
"if",
"node",
".",
"workeroutput",
"[",
"\"exitstatus\"",
"]",
"... | Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered. | [
"Emitted",
"when",
"node",
"executes",
"its",
"pytest_sessionfinish",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L165-L181 |
224,675 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_errordown | def worker_errordown(self, node, error):
"""Emitted by the WorkerController when a node dies."""
self.config.hook.pytest_testnodedown(node=node, error=error)
try:
crashitem = self.sched.remove_node(node)
except KeyError:
pass
else:
if crashitem:
self.handle_crashitem(crashitem, node)
self._failed_nodes_count += 1
maximum_reached = (
self._max_worker_restart is not None
and self._failed_nodes_count > self._max_worker_restart
)
if maximum_reached:
if self._max_worker_restart == 0:
msg = "Worker restarting disabled"
else:
msg = "Maximum crashed workers reached: %d" % self._max_worker_restart
self.report_line(msg)
else:
self.report_line("Replacing crashed worker %s" % node.gateway.id)
self._clone_node(node)
self._active_nodes.remove(node) | python | def worker_errordown(self, node, error):
"""Emitted by the WorkerController when a node dies."""
self.config.hook.pytest_testnodedown(node=node, error=error)
try:
crashitem = self.sched.remove_node(node)
except KeyError:
pass
else:
if crashitem:
self.handle_crashitem(crashitem, node)
self._failed_nodes_count += 1
maximum_reached = (
self._max_worker_restart is not None
and self._failed_nodes_count > self._max_worker_restart
)
if maximum_reached:
if self._max_worker_restart == 0:
msg = "Worker restarting disabled"
else:
msg = "Maximum crashed workers reached: %d" % self._max_worker_restart
self.report_line(msg)
else:
self.report_line("Replacing crashed worker %s" % node.gateway.id)
self._clone_node(node)
self._active_nodes.remove(node) | [
"def",
"worker_errordown",
"(",
"self",
",",
"node",
",",
"error",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_testnodedown",
"(",
"node",
"=",
"node",
",",
"error",
"=",
"error",
")",
"try",
":",
"crashitem",
"=",
"self",
".",
"sched",
... | Emitted by the WorkerController when a node dies. | [
"Emitted",
"by",
"the",
"WorkerController",
"when",
"a",
"node",
"dies",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L183-L208 |
224,676 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_collectionfinish | def worker_collectionfinish(self, node, ids):
"""worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler to schedule the collected items. When initiating
scheduling the first time it logs which scheduler is in use.
"""
if self.shuttingdown:
return
self.config.hook.pytest_xdist_node_collection_finished(node=node, ids=ids)
# tell session which items were effectively collected otherwise
# the master node will finish the session with EXIT_NOTESTSCOLLECTED
self._session.testscollected = len(ids)
self.sched.add_node_collection(node, ids)
if self.terminal:
self.trdist.setstatus(node.gateway.spec, "[%d]" % (len(ids)))
if self.sched.collection_is_completed:
if self.terminal and not self.sched.has_pending:
self.trdist.ensure_show_status()
self.terminal.write_line("")
if self.config.option.verbose > 0:
self.terminal.write_line(
"scheduling tests via %s" % (self.sched.__class__.__name__)
)
self.sched.schedule() | python | def worker_collectionfinish(self, node, ids):
"""worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler to schedule the collected items. When initiating
scheduling the first time it logs which scheduler is in use.
"""
if self.shuttingdown:
return
self.config.hook.pytest_xdist_node_collection_finished(node=node, ids=ids)
# tell session which items were effectively collected otherwise
# the master node will finish the session with EXIT_NOTESTSCOLLECTED
self._session.testscollected = len(ids)
self.sched.add_node_collection(node, ids)
if self.terminal:
self.trdist.setstatus(node.gateway.spec, "[%d]" % (len(ids)))
if self.sched.collection_is_completed:
if self.terminal and not self.sched.has_pending:
self.trdist.ensure_show_status()
self.terminal.write_line("")
if self.config.option.verbose > 0:
self.terminal.write_line(
"scheduling tests via %s" % (self.sched.__class__.__name__)
)
self.sched.schedule() | [
"def",
"worker_collectionfinish",
"(",
"self",
",",
"node",
",",
"ids",
")",
":",
"if",
"self",
".",
"shuttingdown",
":",
"return",
"self",
".",
"config",
".",
"hook",
".",
"pytest_xdist_node_collection_finished",
"(",
"node",
"=",
"node",
",",
"ids",
"=",
... | worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler to schedule the collected items. When initiating
scheduling the first time it logs which scheduler is in use. | [
"worker",
"has",
"finished",
"test",
"collection",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L210-L236 |
224,677 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_logstart | def worker_logstart(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logstart hook."""
self.config.hook.pytest_runtest_logstart(nodeid=nodeid, location=location) | python | def worker_logstart(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logstart hook."""
self.config.hook.pytest_runtest_logstart(nodeid=nodeid, location=location) | [
"def",
"worker_logstart",
"(",
"self",
",",
"node",
",",
"nodeid",
",",
"location",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_runtest_logstart",
"(",
"nodeid",
"=",
"nodeid",
",",
"location",
"=",
"location",
")"
] | Emitted when a node calls the pytest_runtest_logstart hook. | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_runtest_logstart",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L238-L240 |
224,678 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_logfinish | def worker_logfinish(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logfinish hook."""
self.config.hook.pytest_runtest_logfinish(nodeid=nodeid, location=location) | python | def worker_logfinish(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logfinish hook."""
self.config.hook.pytest_runtest_logfinish(nodeid=nodeid, location=location) | [
"def",
"worker_logfinish",
"(",
"self",
",",
"node",
",",
"nodeid",
",",
"location",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_runtest_logfinish",
"(",
"nodeid",
"=",
"nodeid",
",",
"location",
"=",
"location",
")"
] | Emitted when a node calls the pytest_runtest_logfinish hook. | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_runtest_logfinish",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L242-L244 |
224,679 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_collectreport | def worker_collectreport(self, node, rep):
"""Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330).
"""
assert not rep.passed
self._failed_worker_collectreport(node, rep) | python | def worker_collectreport(self, node, rep):
"""Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330).
"""
assert not rep.passed
self._failed_worker_collectreport(node, rep) | [
"def",
"worker_collectreport",
"(",
"self",
",",
"node",
",",
"rep",
")",
":",
"assert",
"not",
"rep",
".",
"passed",
"self",
".",
"_failed_worker_collectreport",
"(",
"node",
",",
"rep",
")"
] | Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330). | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_collectreport",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L260-L267 |
224,680 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession._clone_node | def _clone_node(self, node):
"""Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and do work soon.
"""
spec = node.gateway.spec
spec.id = None
self.nodemanager.group.allocate_id(spec)
node = self.nodemanager.setup_node(spec, self.queue.put)
self._active_nodes.add(node)
return node | python | def _clone_node(self, node):
"""Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and do work soon.
"""
spec = node.gateway.spec
spec.id = None
self.nodemanager.group.allocate_id(spec)
node = self.nodemanager.setup_node(spec, self.queue.put)
self._active_nodes.add(node)
return node | [
"def",
"_clone_node",
"(",
"self",
",",
"node",
")",
":",
"spec",
"=",
"node",
".",
"gateway",
".",
"spec",
"spec",
".",
"id",
"=",
"None",
"self",
".",
"nodemanager",
".",
"group",
".",
"allocate_id",
"(",
"spec",
")",
"node",
"=",
"self",
".",
"n... | Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and do work soon. | [
"Return",
"new",
"node",
"based",
"on",
"an",
"existing",
"one",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L279-L292 |
224,681 | pytest-dev/pytest-xdist | xdist/workermanage.py | NodeManager.rsync_roots | def rsync_roots(self, gateway):
"""Rsync the set of roots to the node's gateway cwd."""
if self.roots:
for root in self.roots:
self.rsync(gateway, root, **self.rsyncoptions) | python | def rsync_roots(self, gateway):
"""Rsync the set of roots to the node's gateway cwd."""
if self.roots:
for root in self.roots:
self.rsync(gateway, root, **self.rsyncoptions) | [
"def",
"rsync_roots",
"(",
"self",
",",
"gateway",
")",
":",
"if",
"self",
".",
"roots",
":",
"for",
"root",
"in",
"self",
".",
"roots",
":",
"self",
".",
"rsync",
"(",
"gateway",
",",
"root",
",",
"*",
"*",
"self",
".",
"rsyncoptions",
")"
] | Rsync the set of roots to the node's gateway cwd. | [
"Rsync",
"the",
"set",
"of",
"roots",
"to",
"the",
"node",
"s",
"gateway",
"cwd",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L53-L57 |
224,682 | pytest-dev/pytest-xdist | xdist/workermanage.py | NodeManager._getrsyncoptions | def _getrsyncoptions(self):
"""Get options to be passed for rsync."""
ignores = list(self.DEFAULT_IGNORES)
ignores += self.config.option.rsyncignore
ignores += self.config.getini("rsyncignore")
return {"ignores": ignores, "verbose": self.config.option.verbose} | python | def _getrsyncoptions(self):
"""Get options to be passed for rsync."""
ignores = list(self.DEFAULT_IGNORES)
ignores += self.config.option.rsyncignore
ignores += self.config.getini("rsyncignore")
return {"ignores": ignores, "verbose": self.config.option.verbose} | [
"def",
"_getrsyncoptions",
"(",
"self",
")",
":",
"ignores",
"=",
"list",
"(",
"self",
".",
"DEFAULT_IGNORES",
")",
"ignores",
"+=",
"self",
".",
"config",
".",
"option",
".",
"rsyncignore",
"ignores",
"+=",
"self",
".",
"config",
".",
"getini",
"(",
"\"... | Get options to be passed for rsync. | [
"Get",
"options",
"to",
"be",
"passed",
"for",
"rsync",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L109-L115 |
224,683 | pytest-dev/pytest-xdist | xdist/workermanage.py | WorkerController.sendcommand | def sendcommand(self, name, **kwargs):
""" send a named parametrized command to the other side. """
self.log("sending command %s(**%s)" % (name, kwargs))
self.channel.send((name, kwargs)) | python | def sendcommand(self, name, **kwargs):
""" send a named parametrized command to the other side. """
self.log("sending command %s(**%s)" % (name, kwargs))
self.channel.send((name, kwargs)) | [
"def",
"sendcommand",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"log",
"(",
"\"sending command %s(**%s)\"",
"%",
"(",
"name",
",",
"kwargs",
")",
")",
"self",
".",
"channel",
".",
"send",
"(",
"(",
"name",
",",
"kwargs... | send a named parametrized command to the other side. | [
"send",
"a",
"named",
"parametrized",
"command",
"to",
"the",
"other",
"side",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L284-L287 |
224,684 | pytest-dev/pytest-xdist | xdist/workermanage.py | WorkerController.process_from_remote | def process_from_remote(self, eventcall): # noqa too complex
""" this gets called for each object we receive from
the other side and if the channel closes.
Note that channel callbacks run in the receiver
thread of execnet gateways - we need to
avoid raising exceptions or doing heavy work.
"""
try:
if eventcall == self.ENDMARK:
err = self.channel._getremoteerror()
if not self._down:
if not err or isinstance(err, EOFError):
err = "Not properly terminated" # lost connection?
self.notify_inproc("errordown", node=self, error=err)
self._down = True
return
eventname, kwargs = eventcall
if eventname in ("collectionstart",):
self.log("ignoring %s(%s)" % (eventname, kwargs))
elif eventname == "workerready":
self.notify_inproc(eventname, node=self, **kwargs)
elif eventname == "workerfinished":
self._down = True
self.workeroutput = self.slaveoutput = kwargs["workeroutput"]
self.notify_inproc("workerfinished", node=self)
elif eventname in ("logstart", "logfinish"):
self.notify_inproc(eventname, node=self, **kwargs)
elif eventname in ("testreport", "collectreport", "teardownreport"):
item_index = kwargs.pop("item_index", None)
rep = self.config.hook.pytest_report_from_serializable(
config=self.config, data=kwargs["data"]
)
if item_index is not None:
rep.item_index = item_index
self.notify_inproc(eventname, node=self, rep=rep)
elif eventname == "collectionfinish":
self.notify_inproc(eventname, node=self, ids=kwargs["ids"])
elif eventname == "runtest_protocol_complete":
self.notify_inproc(eventname, node=self, **kwargs)
elif eventname == "logwarning":
self.notify_inproc(
eventname,
message=kwargs["message"],
code=kwargs["code"],
nodeid=kwargs["nodeid"],
fslocation=kwargs["nodeid"],
)
elif eventname == "warning_captured":
warning_message = unserialize_warning_message(
kwargs["warning_message_data"]
)
self.notify_inproc(
eventname,
warning_message=warning_message,
when=kwargs["when"],
item=kwargs["item"],
)
else:
raise ValueError("unknown event: %s" % (eventname,))
except KeyboardInterrupt:
# should not land in receiver-thread
raise
except: # noqa
from _pytest._code import ExceptionInfo
# ExceptionInfo API changed in pytest 4.1
if hasattr(ExceptionInfo, "from_current"):
excinfo = ExceptionInfo.from_current()
else:
excinfo = ExceptionInfo()
print("!" * 20, excinfo)
self.config.notify_exception(excinfo)
self.shutdown()
self.notify_inproc("errordown", node=self, error=excinfo) | python | def process_from_remote(self, eventcall): # noqa too complex
""" this gets called for each object we receive from
the other side and if the channel closes.
Note that channel callbacks run in the receiver
thread of execnet gateways - we need to
avoid raising exceptions or doing heavy work.
"""
try:
if eventcall == self.ENDMARK:
err = self.channel._getremoteerror()
if not self._down:
if not err or isinstance(err, EOFError):
err = "Not properly terminated" # lost connection?
self.notify_inproc("errordown", node=self, error=err)
self._down = True
return
eventname, kwargs = eventcall
if eventname in ("collectionstart",):
self.log("ignoring %s(%s)" % (eventname, kwargs))
elif eventname == "workerready":
self.notify_inproc(eventname, node=self, **kwargs)
elif eventname == "workerfinished":
self._down = True
self.workeroutput = self.slaveoutput = kwargs["workeroutput"]
self.notify_inproc("workerfinished", node=self)
elif eventname in ("logstart", "logfinish"):
self.notify_inproc(eventname, node=self, **kwargs)
elif eventname in ("testreport", "collectreport", "teardownreport"):
item_index = kwargs.pop("item_index", None)
rep = self.config.hook.pytest_report_from_serializable(
config=self.config, data=kwargs["data"]
)
if item_index is not None:
rep.item_index = item_index
self.notify_inproc(eventname, node=self, rep=rep)
elif eventname == "collectionfinish":
self.notify_inproc(eventname, node=self, ids=kwargs["ids"])
elif eventname == "runtest_protocol_complete":
self.notify_inproc(eventname, node=self, **kwargs)
elif eventname == "logwarning":
self.notify_inproc(
eventname,
message=kwargs["message"],
code=kwargs["code"],
nodeid=kwargs["nodeid"],
fslocation=kwargs["nodeid"],
)
elif eventname == "warning_captured":
warning_message = unserialize_warning_message(
kwargs["warning_message_data"]
)
self.notify_inproc(
eventname,
warning_message=warning_message,
when=kwargs["when"],
item=kwargs["item"],
)
else:
raise ValueError("unknown event: %s" % (eventname,))
except KeyboardInterrupt:
# should not land in receiver-thread
raise
except: # noqa
from _pytest._code import ExceptionInfo
# ExceptionInfo API changed in pytest 4.1
if hasattr(ExceptionInfo, "from_current"):
excinfo = ExceptionInfo.from_current()
else:
excinfo = ExceptionInfo()
print("!" * 20, excinfo)
self.config.notify_exception(excinfo)
self.shutdown()
self.notify_inproc("errordown", node=self, error=excinfo) | [
"def",
"process_from_remote",
"(",
"self",
",",
"eventcall",
")",
":",
"# noqa too complex",
"try",
":",
"if",
"eventcall",
"==",
"self",
".",
"ENDMARK",
":",
"err",
"=",
"self",
".",
"channel",
".",
"_getremoteerror",
"(",
")",
"if",
"not",
"self",
".",
... | this gets called for each object we receive from
the other side and if the channel closes.
Note that channel callbacks run in the receiver
thread of execnet gateways - we need to
avoid raising exceptions or doing heavy work. | [
"this",
"gets",
"called",
"for",
"each",
"object",
"we",
"receive",
"from",
"the",
"other",
"side",
"and",
"if",
"the",
"channel",
"closes",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L293-L367 |
224,685 | pytest-dev/pytest-xdist | xdist/report.py | report_collection_diff | def report_collection_diff(from_collection, to_collection, from_id, to_id):
"""Report the collected test difference between two nodes.
:returns: detailed message describing the difference between the given
collections, or None if they are equal.
"""
if from_collection == to_collection:
return None
diff = unified_diff(from_collection, to_collection, fromfile=from_id, tofile=to_id)
error_message = (
u"Different tests were collected between {from_id} and {to_id}. "
u"The difference is:\n"
u"{diff}"
).format(from_id=from_id, to_id=to_id, diff="\n".join(diff))
msg = "\n".join([x.rstrip() for x in error_message.split("\n")])
return msg | python | def report_collection_diff(from_collection, to_collection, from_id, to_id):
"""Report the collected test difference between two nodes.
:returns: detailed message describing the difference between the given
collections, or None if they are equal.
"""
if from_collection == to_collection:
return None
diff = unified_diff(from_collection, to_collection, fromfile=from_id, tofile=to_id)
error_message = (
u"Different tests were collected between {from_id} and {to_id}. "
u"The difference is:\n"
u"{diff}"
).format(from_id=from_id, to_id=to_id, diff="\n".join(diff))
msg = "\n".join([x.rstrip() for x in error_message.split("\n")])
return msg | [
"def",
"report_collection_diff",
"(",
"from_collection",
",",
"to_collection",
",",
"from_id",
",",
"to_id",
")",
":",
"if",
"from_collection",
"==",
"to_collection",
":",
"return",
"None",
"diff",
"=",
"unified_diff",
"(",
"from_collection",
",",
"to_collection",
... | Report the collected test difference between two nodes.
:returns: detailed message describing the difference between the given
collections, or None if they are equal. | [
"Report",
"the",
"collected",
"test",
"difference",
"between",
"two",
"nodes",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/report.py#L5-L21 |
224,686 | ivelum/djangoql | djangoql/queryset.py | apply_search | def apply_search(queryset, search, schema=None):
"""
Applies search written in DjangoQL mini-language to given queryset
"""
ast = DjangoQLParser().parse(search)
schema = schema or DjangoQLSchema
schema_instance = schema(queryset.model)
schema_instance.validate(ast)
return queryset.filter(build_filter(ast, schema_instance)) | python | def apply_search(queryset, search, schema=None):
"""
Applies search written in DjangoQL mini-language to given queryset
"""
ast = DjangoQLParser().parse(search)
schema = schema or DjangoQLSchema
schema_instance = schema(queryset.model)
schema_instance.validate(ast)
return queryset.filter(build_filter(ast, schema_instance)) | [
"def",
"apply_search",
"(",
"queryset",
",",
"search",
",",
"schema",
"=",
"None",
")",
":",
"ast",
"=",
"DjangoQLParser",
"(",
")",
".",
"parse",
"(",
"search",
")",
"schema",
"=",
"schema",
"or",
"DjangoQLSchema",
"schema_instance",
"=",
"schema",
"(",
... | Applies search written in DjangoQL mini-language to given queryset | [
"Applies",
"search",
"written",
"in",
"DjangoQL",
"mini",
"-",
"language",
"to",
"given",
"queryset"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/queryset.py#L32-L40 |
224,687 | ivelum/djangoql | djangoql/schema.py | DjangoQLField.get_options | def get_options(self):
"""
Override this method to provide custom suggestion options
"""
choices = self._field_choices()
if choices:
return [c[1] for c in choices]
else:
return self.model.objects.\
order_by(self.name).\
values_list(self.name, flat=True) | python | def get_options(self):
"""
Override this method to provide custom suggestion options
"""
choices = self._field_choices()
if choices:
return [c[1] for c in choices]
else:
return self.model.objects.\
order_by(self.name).\
values_list(self.name, flat=True) | [
"def",
"get_options",
"(",
"self",
")",
":",
"choices",
"=",
"self",
".",
"_field_choices",
"(",
")",
"if",
"choices",
":",
"return",
"[",
"c",
"[",
"1",
"]",
"for",
"c",
"in",
"choices",
"]",
"else",
":",
"return",
"self",
".",
"model",
".",
"obje... | Override this method to provide custom suggestion options | [
"Override",
"this",
"method",
"to",
"provide",
"custom",
"suggestion",
"options"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L55-L65 |
224,688 | ivelum/djangoql | djangoql/schema.py | DjangoQLField.get_lookup_value | def get_lookup_value(self, value):
"""
Override this method to convert displayed values to lookup values
"""
choices = self._field_choices()
if choices:
if isinstance(value, list):
return [c[0] for c in choices if c[1] in value]
else:
for c in choices:
if c[1] == value:
return c[0]
return value | python | def get_lookup_value(self, value):
"""
Override this method to convert displayed values to lookup values
"""
choices = self._field_choices()
if choices:
if isinstance(value, list):
return [c[0] for c in choices if c[1] in value]
else:
for c in choices:
if c[1] == value:
return c[0]
return value | [
"def",
"get_lookup_value",
"(",
"self",
",",
"value",
")",
":",
"choices",
"=",
"self",
".",
"_field_choices",
"(",
")",
"if",
"choices",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"[",
"c",
"[",
"0",
"]",
"for",
"c",
"... | Override this method to convert displayed values to lookup values | [
"Override",
"this",
"method",
"to",
"convert",
"displayed",
"values",
"to",
"lookup",
"values"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L73-L85 |
224,689 | ivelum/djangoql | djangoql/schema.py | DjangoQLField.get_operator | def get_operator(self, operator):
"""
Get a comparison suffix to be used in Django ORM & inversion flag for it
:param operator: string, DjangoQL comparison operator
:return: (suffix, invert) - a tuple with 2 values:
suffix - suffix to be used in ORM query, for example '__gt' for '>'
invert - boolean, True if this comparison needs to be inverted
"""
op = {
'=': '',
'>': '__gt',
'>=': '__gte',
'<': '__lt',
'<=': '__lte',
'~': '__icontains',
'in': '__in',
}.get(operator)
if op is not None:
return op, False
op = {
'!=': '',
'!~': '__icontains',
'not in': '__in',
}[operator]
return op, True | python | def get_operator(self, operator):
"""
Get a comparison suffix to be used in Django ORM & inversion flag for it
:param operator: string, DjangoQL comparison operator
:return: (suffix, invert) - a tuple with 2 values:
suffix - suffix to be used in ORM query, for example '__gt' for '>'
invert - boolean, True if this comparison needs to be inverted
"""
op = {
'=': '',
'>': '__gt',
'>=': '__gte',
'<': '__lt',
'<=': '__lte',
'~': '__icontains',
'in': '__in',
}.get(operator)
if op is not None:
return op, False
op = {
'!=': '',
'!~': '__icontains',
'not in': '__in',
}[operator]
return op, True | [
"def",
"get_operator",
"(",
"self",
",",
"operator",
")",
":",
"op",
"=",
"{",
"'='",
":",
"''",
",",
"'>'",
":",
"'__gt'",
",",
"'>='",
":",
"'__gte'",
",",
"'<'",
":",
"'__lt'",
",",
"'<='",
":",
"'__lte'",
",",
"'~'",
":",
"'__icontains'",
",",
... | Get a comparison suffix to be used in Django ORM & inversion flag for it
:param operator: string, DjangoQL comparison operator
:return: (suffix, invert) - a tuple with 2 values:
suffix - suffix to be used in ORM query, for example '__gt' for '>'
invert - boolean, True if this comparison needs to be inverted | [
"Get",
"a",
"comparison",
"suffix",
"to",
"be",
"used",
"in",
"Django",
"ORM",
"&",
"inversion",
"flag",
"for",
"it"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L87-L112 |
224,690 | ivelum/djangoql | djangoql/schema.py | DjangoQLSchema.introspect | def introspect(self, model, exclude=()):
"""
Start with given model and recursively walk through its relationships.
Returns a dict with all model labels and their fields found.
"""
result = {}
open_set = deque([model])
closed_set = list(exclude)
while open_set:
model = open_set.popleft()
model_label = self.model_label(model)
if model_label in closed_set:
continue
model_fields = OrderedDict()
for field in self.get_fields(model):
if not isinstance(field, DjangoQLField):
field = self.get_field_instance(model, field)
if not field:
continue
if isinstance(field, RelationField):
if field.relation not in closed_set:
model_fields[field.name] = field
open_set.append(field.related_model)
else:
model_fields[field.name] = field
result[model_label] = model_fields
closed_set.append(model_label)
return result | python | def introspect(self, model, exclude=()):
"""
Start with given model and recursively walk through its relationships.
Returns a dict with all model labels and their fields found.
"""
result = {}
open_set = deque([model])
closed_set = list(exclude)
while open_set:
model = open_set.popleft()
model_label = self.model_label(model)
if model_label in closed_set:
continue
model_fields = OrderedDict()
for field in self.get_fields(model):
if not isinstance(field, DjangoQLField):
field = self.get_field_instance(model, field)
if not field:
continue
if isinstance(field, RelationField):
if field.relation not in closed_set:
model_fields[field.name] = field
open_set.append(field.related_model)
else:
model_fields[field.name] = field
result[model_label] = model_fields
closed_set.append(model_label)
return result | [
"def",
"introspect",
"(",
"self",
",",
"model",
",",
"exclude",
"=",
"(",
")",
")",
":",
"result",
"=",
"{",
"}",
"open_set",
"=",
"deque",
"(",
"[",
"model",
"]",
")",
"closed_set",
"=",
"list",
"(",
"exclude",
")",
"while",
"open_set",
":",
"mode... | Start with given model and recursively walk through its relationships.
Returns a dict with all model labels and their fields found. | [
"Start",
"with",
"given",
"model",
"and",
"recursively",
"walk",
"through",
"its",
"relationships",
"."
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L332-L365 |
224,691 | ivelum/djangoql | djangoql/schema.py | DjangoQLSchema.get_fields | def get_fields(self, model):
"""
By default, returns all field names of a given model.
Override this method to limit field options. You can either return a
plain list of field names from it, like ['id', 'name'], or call
.super() and exclude unwanted fields from its result.
"""
return sorted(
[f.name for f in model._meta.get_fields() if f.name != 'password']
) | python | def get_fields(self, model):
"""
By default, returns all field names of a given model.
Override this method to limit field options. You can either return a
plain list of field names from it, like ['id', 'name'], or call
.super() and exclude unwanted fields from its result.
"""
return sorted(
[f.name for f in model._meta.get_fields() if f.name != 'password']
) | [
"def",
"get_fields",
"(",
"self",
",",
"model",
")",
":",
"return",
"sorted",
"(",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"model",
".",
"_meta",
".",
"get_fields",
"(",
")",
"if",
"f",
".",
"name",
"!=",
"'password'",
"]",
")"
] | By default, returns all field names of a given model.
Override this method to limit field options. You can either return a
plain list of field names from it, like ['id', 'name'], or call
.super() and exclude unwanted fields from its result. | [
"By",
"default",
"returns",
"all",
"field",
"names",
"of",
"a",
"given",
"model",
"."
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L367-L377 |
224,692 | ivelum/djangoql | djangoql/schema.py | DjangoQLSchema.validate | def validate(self, node):
"""
Validate DjangoQL AST tree vs. current schema
"""
assert isinstance(node, Node)
if isinstance(node.operator, Logical):
self.validate(node.left)
self.validate(node.right)
return
assert isinstance(node.left, Name)
assert isinstance(node.operator, Comparison)
assert isinstance(node.right, (Const, List))
# Check that field and value types are compatible
field = self.resolve_name(node.left)
value = node.right.value
if field is None:
if value is not None:
raise DjangoQLSchemaError(
'Related model %s can be compared to None only, but not to '
'%s' % (node.left.value, type(value).__name__)
)
else:
values = value if isinstance(node.right, List) else [value]
for v in values:
field.validate(v) | python | def validate(self, node):
"""
Validate DjangoQL AST tree vs. current schema
"""
assert isinstance(node, Node)
if isinstance(node.operator, Logical):
self.validate(node.left)
self.validate(node.right)
return
assert isinstance(node.left, Name)
assert isinstance(node.operator, Comparison)
assert isinstance(node.right, (Const, List))
# Check that field and value types are compatible
field = self.resolve_name(node.left)
value = node.right.value
if field is None:
if value is not None:
raise DjangoQLSchemaError(
'Related model %s can be compared to None only, but not to '
'%s' % (node.left.value, type(value).__name__)
)
else:
values = value if isinstance(node.right, List) else [value]
for v in values:
field.validate(v) | [
"def",
"validate",
"(",
"self",
",",
"node",
")",
":",
"assert",
"isinstance",
"(",
"node",
",",
"Node",
")",
"if",
"isinstance",
"(",
"node",
".",
"operator",
",",
"Logical",
")",
":",
"self",
".",
"validate",
"(",
"node",
".",
"left",
")",
"self",
... | Validate DjangoQL AST tree vs. current schema | [
"Validate",
"DjangoQL",
"AST",
"tree",
"vs",
".",
"current",
"schema"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/schema.py#L454-L479 |
224,693 | ivelum/djangoql | djangoql/lexer.py | DjangoQLLexer.find_column | def find_column(self, t):
"""
Returns token position in current text, starting from 1
"""
cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators)
if cr == -1:
return t.lexpos + 1
return t.lexpos - cr | python | def find_column(self, t):
"""
Returns token position in current text, starting from 1
"""
cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators)
if cr == -1:
return t.lexpos + 1
return t.lexpos - cr | [
"def",
"find_column",
"(",
"self",
",",
"t",
")",
":",
"cr",
"=",
"max",
"(",
"self",
".",
"text",
".",
"rfind",
"(",
"l",
",",
"0",
",",
"t",
".",
"lexpos",
")",
"for",
"l",
"in",
"self",
".",
"line_terminators",
")",
"if",
"cr",
"==",
"-",
... | Returns token position in current text, starting from 1 | [
"Returns",
"token",
"position",
"in",
"current",
"text",
"starting",
"from",
"1"
] | 8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897 | https://github.com/ivelum/djangoql/blob/8d0c6b0b11824a2406c9a73a6ccd6d7ba22a3897/djangoql/lexer.py#L40-L47 |
224,694 | aiogram/aiogram | aiogram/dispatcher/filters/filters.py | execute_filter | async def execute_filter(filter_: FilterObj, args):
"""
Helper for executing filter
:param filter_:
:param args:
:return:
"""
if filter_.is_async:
return await filter_.filter(*args, **filter_.kwargs)
else:
return filter_.filter(*args, **filter_.kwargs) | python | async def execute_filter(filter_: FilterObj, args):
"""
Helper for executing filter
:param filter_:
:param args:
:return:
"""
if filter_.is_async:
return await filter_.filter(*args, **filter_.kwargs)
else:
return filter_.filter(*args, **filter_.kwargs) | [
"async",
"def",
"execute_filter",
"(",
"filter_",
":",
"FilterObj",
",",
"args",
")",
":",
"if",
"filter_",
".",
"is_async",
":",
"return",
"await",
"filter_",
".",
"filter",
"(",
"*",
"args",
",",
"*",
"*",
"filter_",
".",
"kwargs",
")",
"else",
":",
... | Helper for executing filter
:param filter_:
:param args:
:return: | [
"Helper",
"for",
"executing",
"filter"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L47-L58 |
224,695 | aiogram/aiogram | aiogram/dispatcher/filters/filters.py | check_filters | async def check_filters(filters: typing.Iterable[FilterObj], args):
"""
Check list of filters
:param filters:
:param args:
:return:
"""
data = {}
if filters is not None:
for filter_ in filters:
f = await execute_filter(filter_, args)
if not f:
raise FilterNotPassed()
elif isinstance(f, dict):
data.update(f)
return data | python | async def check_filters(filters: typing.Iterable[FilterObj], args):
"""
Check list of filters
:param filters:
:param args:
:return:
"""
data = {}
if filters is not None:
for filter_ in filters:
f = await execute_filter(filter_, args)
if not f:
raise FilterNotPassed()
elif isinstance(f, dict):
data.update(f)
return data | [
"async",
"def",
"check_filters",
"(",
"filters",
":",
"typing",
".",
"Iterable",
"[",
"FilterObj",
"]",
",",
"args",
")",
":",
"data",
"=",
"{",
"}",
"if",
"filters",
"is",
"not",
"None",
":",
"for",
"filter_",
"in",
"filters",
":",
"f",
"=",
"await"... | Check list of filters
:param filters:
:param args:
:return: | [
"Check",
"list",
"of",
"filters"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L61-L77 |
224,696 | aiogram/aiogram | aiogram/dispatcher/filters/filters.py | AbstractFilter.validate | def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Optional[typing.Dict[str, typing.Any]]:
"""
Validate and parse config.
This method will be called by the filters factory when you bind this filter.
Must be overridden.
:param full_config: dict with arguments passed to handler registrar
:return: Current filter config
"""
pass | python | def validate(cls, full_config: typing.Dict[str, typing.Any]) -> typing.Optional[typing.Dict[str, typing.Any]]:
"""
Validate and parse config.
This method will be called by the filters factory when you bind this filter.
Must be overridden.
:param full_config: dict with arguments passed to handler registrar
:return: Current filter config
"""
pass | [
"def",
"validate",
"(",
"cls",
",",
"full_config",
":",
"typing",
".",
"Dict",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
")",
"->",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Dict",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
"]",
":",
"pa... | Validate and parse config.
This method will be called by the filters factory when you bind this filter.
Must be overridden.
:param full_config: dict with arguments passed to handler registrar
:return: Current filter config | [
"Validate",
"and",
"parse",
"config",
"."
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L136-L146 |
224,697 | aiogram/aiogram | aiogram/dispatcher/filters/filters.py | AndFilter.check | async def check(self, *args):
"""
All filters must return a positive result
:param args:
:return:
"""
data = {}
for target in self.targets:
result = await target(*args)
if not result:
return False
if isinstance(result, dict):
data.update(result)
if not data:
return True
return data | python | async def check(self, *args):
"""
All filters must return a positive result
:param args:
:return:
"""
data = {}
for target in self.targets:
result = await target(*args)
if not result:
return False
if isinstance(result, dict):
data.update(result)
if not data:
return True
return data | [
"async",
"def",
"check",
"(",
"self",
",",
"*",
"args",
")",
":",
"data",
"=",
"{",
"}",
"for",
"target",
"in",
"self",
".",
"targets",
":",
"result",
"=",
"await",
"target",
"(",
"*",
"args",
")",
"if",
"not",
"result",
":",
"return",
"False",
"... | All filters must return a positive result
:param args:
:return: | [
"All",
"filters",
"must",
"return",
"a",
"positive",
"result"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/filters/filters.py#L247-L263 |
224,698 | aiogram/aiogram | examples/broadcast_example.py | send_message | async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool:
"""
Safe messages sender
:param user_id:
:param text:
:param disable_notification:
:return:
"""
try:
await bot.send_message(user_id, text, disable_notification=disable_notification)
except exceptions.BotBlocked:
log.error(f"Target [ID:{user_id}]: blocked by user")
except exceptions.ChatNotFound:
log.error(f"Target [ID:{user_id}]: invalid user ID")
except exceptions.RetryAfter as e:
log.error(f"Target [ID:{user_id}]: Flood limit is exceeded. Sleep {e.timeout} seconds.")
await asyncio.sleep(e.timeout)
return await send_message(user_id, text) # Recursive call
except exceptions.UserDeactivated:
log.error(f"Target [ID:{user_id}]: user is deactivated")
except exceptions.TelegramAPIError:
log.exception(f"Target [ID:{user_id}]: failed")
else:
log.info(f"Target [ID:{user_id}]: success")
return True
return False | python | async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool:
"""
Safe messages sender
:param user_id:
:param text:
:param disable_notification:
:return:
"""
try:
await bot.send_message(user_id, text, disable_notification=disable_notification)
except exceptions.BotBlocked:
log.error(f"Target [ID:{user_id}]: blocked by user")
except exceptions.ChatNotFound:
log.error(f"Target [ID:{user_id}]: invalid user ID")
except exceptions.RetryAfter as e:
log.error(f"Target [ID:{user_id}]: Flood limit is exceeded. Sleep {e.timeout} seconds.")
await asyncio.sleep(e.timeout)
return await send_message(user_id, text) # Recursive call
except exceptions.UserDeactivated:
log.error(f"Target [ID:{user_id}]: user is deactivated")
except exceptions.TelegramAPIError:
log.exception(f"Target [ID:{user_id}]: failed")
else:
log.info(f"Target [ID:{user_id}]: success")
return True
return False | [
"async",
"def",
"send_message",
"(",
"user_id",
":",
"int",
",",
"text",
":",
"str",
",",
"disable_notification",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"try",
":",
"await",
"bot",
".",
"send_message",
"(",
"user_id",
",",
"text",
",",
"dis... | Safe messages sender
:param user_id:
:param text:
:param disable_notification:
:return: | [
"Safe",
"messages",
"sender"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/broadcast_example.py#L26-L52 |
224,699 | aiogram/aiogram | aiogram/types/message.py | Message.get_full_command | def get_full_command(self):
"""
Split command and args
:return: tuple of (command, args)
"""
if self.is_command():
command, _, args = self.text.partition(' ')
return command, args | python | def get_full_command(self):
"""
Split command and args
:return: tuple of (command, args)
"""
if self.is_command():
command, _, args = self.text.partition(' ')
return command, args | [
"def",
"get_full_command",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_command",
"(",
")",
":",
"command",
",",
"_",
",",
"args",
"=",
"self",
".",
"text",
".",
"partition",
"(",
"' '",
")",
"return",
"command",
",",
"args"
] | Split command and args
:return: tuple of (command, args) | [
"Split",
"command",
"and",
"args"
] | 2af930149ce2482547721e2c8755c10307295e48 | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/message.py#L156-L164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.