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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
232,700 | nerdvegas/rez | src/rezplugins/build_system/custom.py | CustomBuildSystem.build | def build(self, context, variant, build_path, install_path, install=False,
build_type=BuildType.local):
"""Perform the build.
Note that most of the func args aren't used here - that's because this
info is already passed to the custom build command via environment
variables.
"""
ret = {}
if self.write_build_scripts:
# write out the script that places the user in a build env, where
# they can run bez directly themselves.
build_env_script = os.path.join(build_path, "build-env")
create_forwarding_script(build_env_script,
module=("build_system", "custom"),
func_name="_FWD__spawn_build_shell",
working_dir=self.working_dir,
build_path=build_path,
variant_index=variant.index,
install=install,
install_path=install_path)
ret["success"] = True
ret["build_env_script"] = build_env_script
return ret
# get build command
command = self.package.build_command
# False just means no build command
if command is False:
ret["success"] = True
return ret
def expand(txt):
root = self.package.root
install_ = "install" if install else ''
return txt.format(root=root, install=install_).strip()
if isinstance(command, basestring):
if self.build_args:
command = command + ' ' + ' '.join(map(quote, self.build_args))
command = expand(command)
cmd_str = command
else: # list
command = command + self.build_args
command = map(expand, command)
cmd_str = ' '.join(map(quote, command))
if self.verbose:
pr = Printer(sys.stdout)
pr("Running build command: %s" % cmd_str, heading)
# run the build command
def _callback(executor):
self._add_build_actions(executor,
context=context,
package=self.package,
variant=variant,
build_type=build_type,
install=install,
build_path=build_path,
install_path=install_path)
if self.opts:
# write args defined in ./parse_build_args.py out as env vars
extra_args = getattr(self.opts.parser, "_rezbuild_extra_args", [])
for key, value in vars(self.opts).iteritems():
if key in extra_args:
varname = "__PARSE_ARG_%s" % key.upper()
# do some value conversions
if isinstance(value, bool):
value = 1 if value else 0
elif isinstance(value, (list, tuple)):
value = map(str, value)
value = map(quote, value)
value = ' '.join(value)
executor.env[varname] = value
retcode, _, _ = context.execute_shell(command=command,
block=True,
cwd=build_path,
actions_callback=_callback)
ret["success"] = (not retcode)
return ret | python | def build(self, context, variant, build_path, install_path, install=False,
build_type=BuildType.local):
"""Perform the build.
Note that most of the func args aren't used here - that's because this
info is already passed to the custom build command via environment
variables.
"""
ret = {}
if self.write_build_scripts:
# write out the script that places the user in a build env, where
# they can run bez directly themselves.
build_env_script = os.path.join(build_path, "build-env")
create_forwarding_script(build_env_script,
module=("build_system", "custom"),
func_name="_FWD__spawn_build_shell",
working_dir=self.working_dir,
build_path=build_path,
variant_index=variant.index,
install=install,
install_path=install_path)
ret["success"] = True
ret["build_env_script"] = build_env_script
return ret
# get build command
command = self.package.build_command
# False just means no build command
if command is False:
ret["success"] = True
return ret
def expand(txt):
root = self.package.root
install_ = "install" if install else ''
return txt.format(root=root, install=install_).strip()
if isinstance(command, basestring):
if self.build_args:
command = command + ' ' + ' '.join(map(quote, self.build_args))
command = expand(command)
cmd_str = command
else: # list
command = command + self.build_args
command = map(expand, command)
cmd_str = ' '.join(map(quote, command))
if self.verbose:
pr = Printer(sys.stdout)
pr("Running build command: %s" % cmd_str, heading)
# run the build command
def _callback(executor):
self._add_build_actions(executor,
context=context,
package=self.package,
variant=variant,
build_type=build_type,
install=install,
build_path=build_path,
install_path=install_path)
if self.opts:
# write args defined in ./parse_build_args.py out as env vars
extra_args = getattr(self.opts.parser, "_rezbuild_extra_args", [])
for key, value in vars(self.opts).iteritems():
if key in extra_args:
varname = "__PARSE_ARG_%s" % key.upper()
# do some value conversions
if isinstance(value, bool):
value = 1 if value else 0
elif isinstance(value, (list, tuple)):
value = map(str, value)
value = map(quote, value)
value = ' '.join(value)
executor.env[varname] = value
retcode, _, _ = context.execute_shell(command=command,
block=True,
cwd=build_path,
actions_callback=_callback)
ret["success"] = (not retcode)
return ret | [
"def",
"build",
"(",
"self",
",",
"context",
",",
"variant",
",",
"build_path",
",",
"install_path",
",",
"install",
"=",
"False",
",",
"build_type",
"=",
"BuildType",
".",
"local",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"self",
".",
"write_build_scripts",
":",
"# write out the script that places the user in a build env, where",
"# they can run bez directly themselves.",
"build_env_script",
"=",
"os",
".",
"path",
".",
"join",
"(",
"build_path",
",",
"\"build-env\"",
")",
"create_forwarding_script",
"(",
"build_env_script",
",",
"module",
"=",
"(",
"\"build_system\"",
",",
"\"custom\"",
")",
",",
"func_name",
"=",
"\"_FWD__spawn_build_shell\"",
",",
"working_dir",
"=",
"self",
".",
"working_dir",
",",
"build_path",
"=",
"build_path",
",",
"variant_index",
"=",
"variant",
".",
"index",
",",
"install",
"=",
"install",
",",
"install_path",
"=",
"install_path",
")",
"ret",
"[",
"\"success\"",
"]",
"=",
"True",
"ret",
"[",
"\"build_env_script\"",
"]",
"=",
"build_env_script",
"return",
"ret",
"# get build command",
"command",
"=",
"self",
".",
"package",
".",
"build_command",
"# False just means no build command",
"if",
"command",
"is",
"False",
":",
"ret",
"[",
"\"success\"",
"]",
"=",
"True",
"return",
"ret",
"def",
"expand",
"(",
"txt",
")",
":",
"root",
"=",
"self",
".",
"package",
".",
"root",
"install_",
"=",
"\"install\"",
"if",
"install",
"else",
"''",
"return",
"txt",
".",
"format",
"(",
"root",
"=",
"root",
",",
"install",
"=",
"install_",
")",
".",
"strip",
"(",
")",
"if",
"isinstance",
"(",
"command",
",",
"basestring",
")",
":",
"if",
"self",
".",
"build_args",
":",
"command",
"=",
"command",
"+",
"' '",
"+",
"' '",
".",
"join",
"(",
"map",
"(",
"quote",
",",
"self",
".",
"build_args",
")",
")",
"command",
"=",
"expand",
"(",
"command",
")",
"cmd_str",
"=",
"command",
"else",
":",
"# list",
"command",
"=",
"command",
"+",
"self",
".",
"build_args",
"command",
"=",
"map",
"(",
"expand",
",",
"command",
")",
"cmd_str",
"=",
"' '",
".",
"join",
"(",
"map",
"(",
"quote",
",",
"command",
")",
")",
"if",
"self",
".",
"verbose",
":",
"pr",
"=",
"Printer",
"(",
"sys",
".",
"stdout",
")",
"pr",
"(",
"\"Running build command: %s\"",
"%",
"cmd_str",
",",
"heading",
")",
"# run the build command",
"def",
"_callback",
"(",
"executor",
")",
":",
"self",
".",
"_add_build_actions",
"(",
"executor",
",",
"context",
"=",
"context",
",",
"package",
"=",
"self",
".",
"package",
",",
"variant",
"=",
"variant",
",",
"build_type",
"=",
"build_type",
",",
"install",
"=",
"install",
",",
"build_path",
"=",
"build_path",
",",
"install_path",
"=",
"install_path",
")",
"if",
"self",
".",
"opts",
":",
"# write args defined in ./parse_build_args.py out as env vars",
"extra_args",
"=",
"getattr",
"(",
"self",
".",
"opts",
".",
"parser",
",",
"\"_rezbuild_extra_args\"",
",",
"[",
"]",
")",
"for",
"key",
",",
"value",
"in",
"vars",
"(",
"self",
".",
"opts",
")",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
"in",
"extra_args",
":",
"varname",
"=",
"\"__PARSE_ARG_%s\"",
"%",
"key",
".",
"upper",
"(",
")",
"# do some value conversions",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"value",
"=",
"1",
"if",
"value",
"else",
"0",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"value",
"=",
"map",
"(",
"str",
",",
"value",
")",
"value",
"=",
"map",
"(",
"quote",
",",
"value",
")",
"value",
"=",
"' '",
".",
"join",
"(",
"value",
")",
"executor",
".",
"env",
"[",
"varname",
"]",
"=",
"value",
"retcode",
",",
"_",
",",
"_",
"=",
"context",
".",
"execute_shell",
"(",
"command",
"=",
"command",
",",
"block",
"=",
"True",
",",
"cwd",
"=",
"build_path",
",",
"actions_callback",
"=",
"_callback",
")",
"ret",
"[",
"\"success\"",
"]",
"=",
"(",
"not",
"retcode",
")",
"return",
"ret"
] | Perform the build.
Note that most of the func args aren't used here - that's because this
info is already passed to the custom build command via environment
variables. | [
"Perform",
"the",
"build",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/build_system/custom.py#L87-L176 |
232,701 | nerdvegas/rez | src/rezplugins/release_vcs/hg.py | HgReleaseVCS._create_tag_highlevel | def _create_tag_highlevel(self, tag_name, message=None):
"""Create a tag on the toplevel repo if there is no patch repo,
or a tag on the patch repo and bookmark on the top repo if there is a
patch repo
Returns a list where each entry is a dict for each bookmark or tag
created, which looks like {'type': ('bookmark' or 'tag'), 'patch': bool}
"""
results = []
if self.patch_path:
# make a tag on the patch queue
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=True)
if tagged:
results.append({'type': 'tag', 'patch': True})
# use a bookmark on the main repo since we can't change it
self.hg('bookmark', '-f', tag_name)
results.append({'type': 'bookmark', 'patch': False})
else:
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=False)
if tagged:
results.append({'type': 'tag', 'patch': False})
return results | python | def _create_tag_highlevel(self, tag_name, message=None):
"""Create a tag on the toplevel repo if there is no patch repo,
or a tag on the patch repo and bookmark on the top repo if there is a
patch repo
Returns a list where each entry is a dict for each bookmark or tag
created, which looks like {'type': ('bookmark' or 'tag'), 'patch': bool}
"""
results = []
if self.patch_path:
# make a tag on the patch queue
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=True)
if tagged:
results.append({'type': 'tag', 'patch': True})
# use a bookmark on the main repo since we can't change it
self.hg('bookmark', '-f', tag_name)
results.append({'type': 'bookmark', 'patch': False})
else:
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=False)
if tagged:
results.append({'type': 'tag', 'patch': False})
return results | [
"def",
"_create_tag_highlevel",
"(",
"self",
",",
"tag_name",
",",
"message",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"if",
"self",
".",
"patch_path",
":",
"# make a tag on the patch queue",
"tagged",
"=",
"self",
".",
"_create_tag_lowlevel",
"(",
"tag_name",
",",
"message",
"=",
"message",
",",
"patch",
"=",
"True",
")",
"if",
"tagged",
":",
"results",
".",
"append",
"(",
"{",
"'type'",
":",
"'tag'",
",",
"'patch'",
":",
"True",
"}",
")",
"# use a bookmark on the main repo since we can't change it",
"self",
".",
"hg",
"(",
"'bookmark'",
",",
"'-f'",
",",
"tag_name",
")",
"results",
".",
"append",
"(",
"{",
"'type'",
":",
"'bookmark'",
",",
"'patch'",
":",
"False",
"}",
")",
"else",
":",
"tagged",
"=",
"self",
".",
"_create_tag_lowlevel",
"(",
"tag_name",
",",
"message",
"=",
"message",
",",
"patch",
"=",
"False",
")",
"if",
"tagged",
":",
"results",
".",
"append",
"(",
"{",
"'type'",
":",
"'tag'",
",",
"'patch'",
":",
"False",
"}",
")",
"return",
"results"
] | Create a tag on the toplevel repo if there is no patch repo,
or a tag on the patch repo and bookmark on the top repo if there is a
patch repo
Returns a list where each entry is a dict for each bookmark or tag
created, which looks like {'type': ('bookmark' or 'tag'), 'patch': bool} | [
"Create",
"a",
"tag",
"on",
"the",
"toplevel",
"repo",
"if",
"there",
"is",
"no",
"patch",
"repo",
"or",
"a",
"tag",
"on",
"the",
"patch",
"repo",
"and",
"bookmark",
"on",
"the",
"top",
"repo",
"if",
"there",
"is",
"a",
"patch",
"repo"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/hg.py#L58-L82 |
232,702 | nerdvegas/rez | src/rezplugins/release_vcs/hg.py | HgReleaseVCS._create_tag_lowlevel | def _create_tag_lowlevel(self, tag_name, message=None, force=True,
patch=False):
"""Create a tag on the toplevel or patch repo
If the tag exists, and force is False, no tag is made. If force is True,
and a tag exists, but it is a direct ancestor of the current commit,
and there is no difference in filestate between the current commit
and the tagged commit, no tag is made. Otherwise, the old tag is
overwritten to point at the current commit.
Returns True or False indicating whether the tag was actually committed
"""
# check if tag already exists, and if it does, if it is a direct
# ancestor, and there is NO difference in the files between the tagged
# state and current state
#
# This check is mainly to avoid re-creating the same tag over and over
# on what is essentially the same commit, since tagging will
# technically create a new commit, and update the working copy to it.
#
# Without this check, say you were releasing to three different
# locations, one right after another; the first would create the tag,
# and a new tag commit. The second would then recreate the exact same
# tag, but now pointing at the commit that made the first tag.
# The third would create the tag a THIRD time, but now pointing at the
# commit that created the 2nd tag.
tags = self.get_tags(patch=patch)
old_commit = tags.get(tag_name)
if old_commit is not None:
if not force:
return False
old_rev = old_commit['rev']
# ok, now check to see if direct ancestor...
if self.is_ancestor(old_rev, '.', patch=patch):
# ...and if filestates are same
altered = self.hg('status', '--rev', old_rev, '--rev', '.',
'--no-status')
if not altered or altered == ['.hgtags']:
force = False
if not force:
return False
tag_args = ['tag', tag_name]
if message:
tag_args += ['--message', message]
# we should be ok with ALWAYS having force flag on now, since we should
# have already checked if the commit exists.. but be paranoid, in case
# we've missed some edge case...
if force:
tag_args += ['--force']
self.hg(patch=patch, *tag_args)
return True | python | def _create_tag_lowlevel(self, tag_name, message=None, force=True,
patch=False):
"""Create a tag on the toplevel or patch repo
If the tag exists, and force is False, no tag is made. If force is True,
and a tag exists, but it is a direct ancestor of the current commit,
and there is no difference in filestate between the current commit
and the tagged commit, no tag is made. Otherwise, the old tag is
overwritten to point at the current commit.
Returns True or False indicating whether the tag was actually committed
"""
# check if tag already exists, and if it does, if it is a direct
# ancestor, and there is NO difference in the files between the tagged
# state and current state
#
# This check is mainly to avoid re-creating the same tag over and over
# on what is essentially the same commit, since tagging will
# technically create a new commit, and update the working copy to it.
#
# Without this check, say you were releasing to three different
# locations, one right after another; the first would create the tag,
# and a new tag commit. The second would then recreate the exact same
# tag, but now pointing at the commit that made the first tag.
# The third would create the tag a THIRD time, but now pointing at the
# commit that created the 2nd tag.
tags = self.get_tags(patch=patch)
old_commit = tags.get(tag_name)
if old_commit is not None:
if not force:
return False
old_rev = old_commit['rev']
# ok, now check to see if direct ancestor...
if self.is_ancestor(old_rev, '.', patch=patch):
# ...and if filestates are same
altered = self.hg('status', '--rev', old_rev, '--rev', '.',
'--no-status')
if not altered or altered == ['.hgtags']:
force = False
if not force:
return False
tag_args = ['tag', tag_name]
if message:
tag_args += ['--message', message]
# we should be ok with ALWAYS having force flag on now, since we should
# have already checked if the commit exists.. but be paranoid, in case
# we've missed some edge case...
if force:
tag_args += ['--force']
self.hg(patch=patch, *tag_args)
return True | [
"def",
"_create_tag_lowlevel",
"(",
"self",
",",
"tag_name",
",",
"message",
"=",
"None",
",",
"force",
"=",
"True",
",",
"patch",
"=",
"False",
")",
":",
"# check if tag already exists, and if it does, if it is a direct",
"# ancestor, and there is NO difference in the files between the tagged",
"# state and current state",
"#",
"# This check is mainly to avoid re-creating the same tag over and over",
"# on what is essentially the same commit, since tagging will",
"# technically create a new commit, and update the working copy to it.",
"#",
"# Without this check, say you were releasing to three different",
"# locations, one right after another; the first would create the tag,",
"# and a new tag commit. The second would then recreate the exact same",
"# tag, but now pointing at the commit that made the first tag.",
"# The third would create the tag a THIRD time, but now pointing at the",
"# commit that created the 2nd tag.",
"tags",
"=",
"self",
".",
"get_tags",
"(",
"patch",
"=",
"patch",
")",
"old_commit",
"=",
"tags",
".",
"get",
"(",
"tag_name",
")",
"if",
"old_commit",
"is",
"not",
"None",
":",
"if",
"not",
"force",
":",
"return",
"False",
"old_rev",
"=",
"old_commit",
"[",
"'rev'",
"]",
"# ok, now check to see if direct ancestor...",
"if",
"self",
".",
"is_ancestor",
"(",
"old_rev",
",",
"'.'",
",",
"patch",
"=",
"patch",
")",
":",
"# ...and if filestates are same",
"altered",
"=",
"self",
".",
"hg",
"(",
"'status'",
",",
"'--rev'",
",",
"old_rev",
",",
"'--rev'",
",",
"'.'",
",",
"'--no-status'",
")",
"if",
"not",
"altered",
"or",
"altered",
"==",
"[",
"'.hgtags'",
"]",
":",
"force",
"=",
"False",
"if",
"not",
"force",
":",
"return",
"False",
"tag_args",
"=",
"[",
"'tag'",
",",
"tag_name",
"]",
"if",
"message",
":",
"tag_args",
"+=",
"[",
"'--message'",
",",
"message",
"]",
"# we should be ok with ALWAYS having force flag on now, since we should",
"# have already checked if the commit exists.. but be paranoid, in case",
"# we've missed some edge case...",
"if",
"force",
":",
"tag_args",
"+=",
"[",
"'--force'",
"]",
"self",
".",
"hg",
"(",
"patch",
"=",
"patch",
",",
"*",
"tag_args",
")",
"return",
"True"
] | Create a tag on the toplevel or patch repo
If the tag exists, and force is False, no tag is made. If force is True,
and a tag exists, but it is a direct ancestor of the current commit,
and there is no difference in filestate between the current commit
and the tagged commit, no tag is made. Otherwise, the old tag is
overwritten to point at the current commit.
Returns True or False indicating whether the tag was actually committed | [
"Create",
"a",
"tag",
"on",
"the",
"toplevel",
"or",
"patch",
"repo"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/hg.py#L84-L137 |
232,703 | nerdvegas/rez | src/rezplugins/release_vcs/hg.py | HgReleaseVCS.is_ancestor | def is_ancestor(self, commit1, commit2, patch=False):
"""Returns True if commit1 is a direct ancestor of commit2, or False
otherwise.
This method considers a commit to be a direct ancestor of itself"""
result = self.hg("log", "-r", "first(%s::%s)" % (commit1, commit2),
"--template", "exists", patch=patch)
return "exists" in result | python | def is_ancestor(self, commit1, commit2, patch=False):
"""Returns True if commit1 is a direct ancestor of commit2, or False
otherwise.
This method considers a commit to be a direct ancestor of itself"""
result = self.hg("log", "-r", "first(%s::%s)" % (commit1, commit2),
"--template", "exists", patch=patch)
return "exists" in result | [
"def",
"is_ancestor",
"(",
"self",
",",
"commit1",
",",
"commit2",
",",
"patch",
"=",
"False",
")",
":",
"result",
"=",
"self",
".",
"hg",
"(",
"\"log\"",
",",
"\"-r\"",
",",
"\"first(%s::%s)\"",
"%",
"(",
"commit1",
",",
"commit2",
")",
",",
"\"--template\"",
",",
"\"exists\"",
",",
"patch",
"=",
"patch",
")",
"return",
"\"exists\"",
"in",
"result"
] | Returns True if commit1 is a direct ancestor of commit2, or False
otherwise.
This method considers a commit to be a direct ancestor of itself | [
"Returns",
"True",
"if",
"commit1",
"is",
"a",
"direct",
"ancestor",
"of",
"commit2",
"or",
"False",
"otherwise",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/hg.py#L159-L166 |
232,704 | nerdvegas/rez | src/rez/utils/patching.py | get_patched_request | def get_patched_request(requires, patchlist):
"""Apply patch args to a request.
For example, consider:
>>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"])
["foo-6", "bah-8.1"]
>>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"])
["foo-5"]
The following rules apply wrt how normal/conflict/weak patches override
(note though that the new request is always added, even if it doesn't
override an existing request):
PATCH OVERRIDES: foo !foo ~foo
----- ---------- --- ---- -----
foo Y Y Y
!foo N N N
~foo N N Y
^foo Y Y Y
Args:
requires (list of str or `version.Requirement`): Request.
patchlist (list of str): List of patch requests.
Returns:
List of `version.Requirement`: Patched request.
"""
# rules from table in docstring above
rules = {
'': (True, True, True ),
'!': (False, False, False),
'~': (False, False, True ),
'^': (True, True, True )
}
requires = [Requirement(x) if not isinstance(x, Requirement) else x
for x in requires]
appended = []
for patch in patchlist:
if patch and patch[0] in ('!', '~', '^'):
ch = patch[0]
name = Requirement(patch[1:]).name
else:
ch = ''
name = Requirement(patch).name
rule = rules[ch]
replaced = (ch == '^')
for i, req in enumerate(requires):
if req is None or req.name != name:
continue
if not req.conflict:
replace = rule[0] # foo
elif not req.weak:
replace = rule[1] # !foo
else:
replace = rule[2] # ~foo
if replace:
if replaced:
requires[i] = None
else:
requires[i] = Requirement(patch)
replaced = True
if not replaced:
appended.append(Requirement(patch))
result = [x for x in requires if x is not None] + appended
return result | python | def get_patched_request(requires, patchlist):
"""Apply patch args to a request.
For example, consider:
>>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"])
["foo-6", "bah-8.1"]
>>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"])
["foo-5"]
The following rules apply wrt how normal/conflict/weak patches override
(note though that the new request is always added, even if it doesn't
override an existing request):
PATCH OVERRIDES: foo !foo ~foo
----- ---------- --- ---- -----
foo Y Y Y
!foo N N N
~foo N N Y
^foo Y Y Y
Args:
requires (list of str or `version.Requirement`): Request.
patchlist (list of str): List of patch requests.
Returns:
List of `version.Requirement`: Patched request.
"""
# rules from table in docstring above
rules = {
'': (True, True, True ),
'!': (False, False, False),
'~': (False, False, True ),
'^': (True, True, True )
}
requires = [Requirement(x) if not isinstance(x, Requirement) else x
for x in requires]
appended = []
for patch in patchlist:
if patch and patch[0] in ('!', '~', '^'):
ch = patch[0]
name = Requirement(patch[1:]).name
else:
ch = ''
name = Requirement(patch).name
rule = rules[ch]
replaced = (ch == '^')
for i, req in enumerate(requires):
if req is None or req.name != name:
continue
if not req.conflict:
replace = rule[0] # foo
elif not req.weak:
replace = rule[1] # !foo
else:
replace = rule[2] # ~foo
if replace:
if replaced:
requires[i] = None
else:
requires[i] = Requirement(patch)
replaced = True
if not replaced:
appended.append(Requirement(patch))
result = [x for x in requires if x is not None] + appended
return result | [
"def",
"get_patched_request",
"(",
"requires",
",",
"patchlist",
")",
":",
"# rules from table in docstring above",
"rules",
"=",
"{",
"''",
":",
"(",
"True",
",",
"True",
",",
"True",
")",
",",
"'!'",
":",
"(",
"False",
",",
"False",
",",
"False",
")",
",",
"'~'",
":",
"(",
"False",
",",
"False",
",",
"True",
")",
",",
"'^'",
":",
"(",
"True",
",",
"True",
",",
"True",
")",
"}",
"requires",
"=",
"[",
"Requirement",
"(",
"x",
")",
"if",
"not",
"isinstance",
"(",
"x",
",",
"Requirement",
")",
"else",
"x",
"for",
"x",
"in",
"requires",
"]",
"appended",
"=",
"[",
"]",
"for",
"patch",
"in",
"patchlist",
":",
"if",
"patch",
"and",
"patch",
"[",
"0",
"]",
"in",
"(",
"'!'",
",",
"'~'",
",",
"'^'",
")",
":",
"ch",
"=",
"patch",
"[",
"0",
"]",
"name",
"=",
"Requirement",
"(",
"patch",
"[",
"1",
":",
"]",
")",
".",
"name",
"else",
":",
"ch",
"=",
"''",
"name",
"=",
"Requirement",
"(",
"patch",
")",
".",
"name",
"rule",
"=",
"rules",
"[",
"ch",
"]",
"replaced",
"=",
"(",
"ch",
"==",
"'^'",
")",
"for",
"i",
",",
"req",
"in",
"enumerate",
"(",
"requires",
")",
":",
"if",
"req",
"is",
"None",
"or",
"req",
".",
"name",
"!=",
"name",
":",
"continue",
"if",
"not",
"req",
".",
"conflict",
":",
"replace",
"=",
"rule",
"[",
"0",
"]",
"# foo",
"elif",
"not",
"req",
".",
"weak",
":",
"replace",
"=",
"rule",
"[",
"1",
"]",
"# !foo",
"else",
":",
"replace",
"=",
"rule",
"[",
"2",
"]",
"# ~foo",
"if",
"replace",
":",
"if",
"replaced",
":",
"requires",
"[",
"i",
"]",
"=",
"None",
"else",
":",
"requires",
"[",
"i",
"]",
"=",
"Requirement",
"(",
"patch",
")",
"replaced",
"=",
"True",
"if",
"not",
"replaced",
":",
"appended",
".",
"append",
"(",
"Requirement",
"(",
"patch",
")",
")",
"result",
"=",
"[",
"x",
"for",
"x",
"in",
"requires",
"if",
"x",
"is",
"not",
"None",
"]",
"+",
"appended",
"return",
"result"
] | Apply patch args to a request.
For example, consider:
>>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"])
["foo-6", "bah-8.1"]
>>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"])
["foo-5"]
The following rules apply wrt how normal/conflict/weak patches override
(note though that the new request is always added, even if it doesn't
override an existing request):
PATCH OVERRIDES: foo !foo ~foo
----- ---------- --- ---- -----
foo Y Y Y
!foo N N N
~foo N N Y
^foo Y Y Y
Args:
requires (list of str or `version.Requirement`): Request.
patchlist (list of str): List of patch requests.
Returns:
List of `version.Requirement`: Patched request. | [
"Apply",
"patch",
"args",
"to",
"a",
"request",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/patching.py#L4-L78 |
232,705 | nerdvegas/rez | src/support/shotgun_toolkit/rez_app_launch.py | AppLaunch.execute | def execute(self, app_path, app_args, version, **kwargs):
"""
The execute functon of the hook will be called to start the required application
:param app_path: (str) The path of the application executable
:param app_args: (str) Any arguments the application may require
:param version: (str) version of the application being run if set in the "versions" settings
of the Launcher instance, otherwise None
:returns: (dict) The two valid keys are 'command' (str) and 'return_code' (int).
"""
multi_launchapp = self.parent
extra = multi_launchapp.get_setting("extra")
use_rez = False
if self.check_rez():
from rez.resolved_context import ResolvedContext
from rez.config import config
# Define variables used to bootstrap tank from overwrite on first reference
# PYTHONPATH is used by tk-maya
# NUKE_PATH is used by tk-nuke
# HIERO_PLUGIN_PATH is used by tk-nuke (nukestudio)
# KATANA_RESOURCES is used by tk-katana
config.parent_variables = ["PYTHONPATH", "HOUDINI_PATH", "NUKE_PATH", "HIERO_PLUGIN_PATH", "KATANA_RESOURCES"]
rez_packages = extra["rez_packages"]
context = ResolvedContext(rez_packages)
use_rez = True
system = sys.platform
shell_type = 'bash'
if system == "linux2":
# on linux, we just run the executable directly
cmd = "%s %s &" % (app_path, app_args)
elif self.parent.get_setting("engine") in ["tk-flame", "tk-flare"]:
# flame and flare works in a different way from other DCCs
# on both linux and mac, they run unix-style command line
# and on the mac the more standardized "open" command cannot
# be utilized.
cmd = "%s %s &" % (app_path, app_args)
elif system == "darwin":
# on the mac, the executable paths are normally pointing
# to the application bundle and not to the binary file
# embedded in the bundle, meaning that we should use the
# built-in mac open command to execute it
cmd = "open -n \"%s\"" % (app_path)
if app_args:
cmd += " --args \"%s\"" % app_args.replace("\"", "\\\"")
elif system == "win32":
# on windows, we run the start command in order to avoid
# any command shells popping up as part of the application launch.
cmd = "start /B \"App\" \"%s\" %s" % (app_path, app_args)
shell_type = 'cmd'
# Execute App in a Rez context
if use_rez:
n_env = os.environ.copy()
proc = context.execute_shell(
command=cmd,
parent_environ=n_env,
shell=shell_type,
stdin=False,
block=False
)
exit_code = proc.wait()
context.print_info(verbosity=True)
else:
# run the command to launch the app
exit_code = os.system(cmd)
return {
"command": cmd,
"return_code": exit_code
} | python | def execute(self, app_path, app_args, version, **kwargs):
"""
The execute functon of the hook will be called to start the required application
:param app_path: (str) The path of the application executable
:param app_args: (str) Any arguments the application may require
:param version: (str) version of the application being run if set in the "versions" settings
of the Launcher instance, otherwise None
:returns: (dict) The two valid keys are 'command' (str) and 'return_code' (int).
"""
multi_launchapp = self.parent
extra = multi_launchapp.get_setting("extra")
use_rez = False
if self.check_rez():
from rez.resolved_context import ResolvedContext
from rez.config import config
# Define variables used to bootstrap tank from overwrite on first reference
# PYTHONPATH is used by tk-maya
# NUKE_PATH is used by tk-nuke
# HIERO_PLUGIN_PATH is used by tk-nuke (nukestudio)
# KATANA_RESOURCES is used by tk-katana
config.parent_variables = ["PYTHONPATH", "HOUDINI_PATH", "NUKE_PATH", "HIERO_PLUGIN_PATH", "KATANA_RESOURCES"]
rez_packages = extra["rez_packages"]
context = ResolvedContext(rez_packages)
use_rez = True
system = sys.platform
shell_type = 'bash'
if system == "linux2":
# on linux, we just run the executable directly
cmd = "%s %s &" % (app_path, app_args)
elif self.parent.get_setting("engine") in ["tk-flame", "tk-flare"]:
# flame and flare works in a different way from other DCCs
# on both linux and mac, they run unix-style command line
# and on the mac the more standardized "open" command cannot
# be utilized.
cmd = "%s %s &" % (app_path, app_args)
elif system == "darwin":
# on the mac, the executable paths are normally pointing
# to the application bundle and not to the binary file
# embedded in the bundle, meaning that we should use the
# built-in mac open command to execute it
cmd = "open -n \"%s\"" % (app_path)
if app_args:
cmd += " --args \"%s\"" % app_args.replace("\"", "\\\"")
elif system == "win32":
# on windows, we run the start command in order to avoid
# any command shells popping up as part of the application launch.
cmd = "start /B \"App\" \"%s\" %s" % (app_path, app_args)
shell_type = 'cmd'
# Execute App in a Rez context
if use_rez:
n_env = os.environ.copy()
proc = context.execute_shell(
command=cmd,
parent_environ=n_env,
shell=shell_type,
stdin=False,
block=False
)
exit_code = proc.wait()
context.print_info(verbosity=True)
else:
# run the command to launch the app
exit_code = os.system(cmd)
return {
"command": cmd,
"return_code": exit_code
} | [
"def",
"execute",
"(",
"self",
",",
"app_path",
",",
"app_args",
",",
"version",
",",
"*",
"*",
"kwargs",
")",
":",
"multi_launchapp",
"=",
"self",
".",
"parent",
"extra",
"=",
"multi_launchapp",
".",
"get_setting",
"(",
"\"extra\"",
")",
"use_rez",
"=",
"False",
"if",
"self",
".",
"check_rez",
"(",
")",
":",
"from",
"rez",
".",
"resolved_context",
"import",
"ResolvedContext",
"from",
"rez",
".",
"config",
"import",
"config",
"# Define variables used to bootstrap tank from overwrite on first reference",
"# PYTHONPATH is used by tk-maya",
"# NUKE_PATH is used by tk-nuke",
"# HIERO_PLUGIN_PATH is used by tk-nuke (nukestudio)",
"# KATANA_RESOURCES is used by tk-katana",
"config",
".",
"parent_variables",
"=",
"[",
"\"PYTHONPATH\"",
",",
"\"HOUDINI_PATH\"",
",",
"\"NUKE_PATH\"",
",",
"\"HIERO_PLUGIN_PATH\"",
",",
"\"KATANA_RESOURCES\"",
"]",
"rez_packages",
"=",
"extra",
"[",
"\"rez_packages\"",
"]",
"context",
"=",
"ResolvedContext",
"(",
"rez_packages",
")",
"use_rez",
"=",
"True",
"system",
"=",
"sys",
".",
"platform",
"shell_type",
"=",
"'bash'",
"if",
"system",
"==",
"\"linux2\"",
":",
"# on linux, we just run the executable directly",
"cmd",
"=",
"\"%s %s &\"",
"%",
"(",
"app_path",
",",
"app_args",
")",
"elif",
"self",
".",
"parent",
".",
"get_setting",
"(",
"\"engine\"",
")",
"in",
"[",
"\"tk-flame\"",
",",
"\"tk-flare\"",
"]",
":",
"# flame and flare works in a different way from other DCCs",
"# on both linux and mac, they run unix-style command line",
"# and on the mac the more standardized \"open\" command cannot",
"# be utilized.",
"cmd",
"=",
"\"%s %s &\"",
"%",
"(",
"app_path",
",",
"app_args",
")",
"elif",
"system",
"==",
"\"darwin\"",
":",
"# on the mac, the executable paths are normally pointing",
"# to the application bundle and not to the binary file",
"# embedded in the bundle, meaning that we should use the",
"# built-in mac open command to execute it",
"cmd",
"=",
"\"open -n \\\"%s\\\"\"",
"%",
"(",
"app_path",
")",
"if",
"app_args",
":",
"cmd",
"+=",
"\" --args \\\"%s\\\"\"",
"%",
"app_args",
".",
"replace",
"(",
"\"\\\"\"",
",",
"\"\\\\\\\"\"",
")",
"elif",
"system",
"==",
"\"win32\"",
":",
"# on windows, we run the start command in order to avoid",
"# any command shells popping up as part of the application launch.",
"cmd",
"=",
"\"start /B \\\"App\\\" \\\"%s\\\" %s\"",
"%",
"(",
"app_path",
",",
"app_args",
")",
"shell_type",
"=",
"'cmd'",
"# Execute App in a Rez context",
"if",
"use_rez",
":",
"n_env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"proc",
"=",
"context",
".",
"execute_shell",
"(",
"command",
"=",
"cmd",
",",
"parent_environ",
"=",
"n_env",
",",
"shell",
"=",
"shell_type",
",",
"stdin",
"=",
"False",
",",
"block",
"=",
"False",
")",
"exit_code",
"=",
"proc",
".",
"wait",
"(",
")",
"context",
".",
"print_info",
"(",
"verbosity",
"=",
"True",
")",
"else",
":",
"# run the command to launch the app",
"exit_code",
"=",
"os",
".",
"system",
"(",
"cmd",
")",
"return",
"{",
"\"command\"",
":",
"cmd",
",",
"\"return_code\"",
":",
"exit_code",
"}"
] | The execute functon of the hook will be called to start the required application
:param app_path: (str) The path of the application executable
:param app_args: (str) Any arguments the application may require
:param version: (str) version of the application being run if set in the "versions" settings
of the Launcher instance, otherwise None
:returns: (dict) The two valid keys are 'command' (str) and 'return_code' (int). | [
"The",
"execute",
"functon",
"of",
"the",
"hook",
"will",
"be",
"called",
"to",
"start",
"the",
"required",
"application"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/support/shotgun_toolkit/rez_app_launch.py#L37-L117 |
232,706 | nerdvegas/rez | src/support/shotgun_toolkit/rez_app_launch.py | AppLaunch.check_rez | def check_rez(self, strict=True):
"""
Checks to see if a Rez package is available in the current environment.
If it is available, add it to the system path, exposing the Rez Python API
:param strict: (bool) If True, raise an error if Rez is not available as a package.
This will prevent the app from being launched.
:returns: A path to the Rez package.
"""
system = sys.platform
if system == "win32":
rez_cmd = 'rez-env rez -- echo %REZ_REZ_ROOT%'
else:
rez_cmd = 'rez-env rez -- printenv REZ_REZ_ROOT'
process = subprocess.Popen(rez_cmd, stdout=subprocess.PIPE, shell=True)
rez_path, err = process.communicate()
if err or not rez_path:
if strict:
raise ImportError("Failed to find Rez as a package in the current "
"environment! Try 'rez-bind rez'!")
else:
print >> sys.stderr, ("WARNING: Failed to find a Rez package in the current "
"environment. Unable to request Rez packages.")
rez_path = ""
else:
rez_path = rez_path.strip()
print "Found Rez:", rez_path
print "Adding Rez to system path..."
sys.path.append(rez_path)
return rez_path | python | def check_rez(self, strict=True):
"""
Checks to see if a Rez package is available in the current environment.
If it is available, add it to the system path, exposing the Rez Python API
:param strict: (bool) If True, raise an error if Rez is not available as a package.
This will prevent the app from being launched.
:returns: A path to the Rez package.
"""
system = sys.platform
if system == "win32":
rez_cmd = 'rez-env rez -- echo %REZ_REZ_ROOT%'
else:
rez_cmd = 'rez-env rez -- printenv REZ_REZ_ROOT'
process = subprocess.Popen(rez_cmd, stdout=subprocess.PIPE, shell=True)
rez_path, err = process.communicate()
if err or not rez_path:
if strict:
raise ImportError("Failed to find Rez as a package in the current "
"environment! Try 'rez-bind rez'!")
else:
print >> sys.stderr, ("WARNING: Failed to find a Rez package in the current "
"environment. Unable to request Rez packages.")
rez_path = ""
else:
rez_path = rez_path.strip()
print "Found Rez:", rez_path
print "Adding Rez to system path..."
sys.path.append(rez_path)
return rez_path | [
"def",
"check_rez",
"(",
"self",
",",
"strict",
"=",
"True",
")",
":",
"system",
"=",
"sys",
".",
"platform",
"if",
"system",
"==",
"\"win32\"",
":",
"rez_cmd",
"=",
"'rez-env rez -- echo %REZ_REZ_ROOT%'",
"else",
":",
"rez_cmd",
"=",
"'rez-env rez -- printenv REZ_REZ_ROOT'",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"rez_cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"shell",
"=",
"True",
")",
"rez_path",
",",
"err",
"=",
"process",
".",
"communicate",
"(",
")",
"if",
"err",
"or",
"not",
"rez_path",
":",
"if",
"strict",
":",
"raise",
"ImportError",
"(",
"\"Failed to find Rez as a package in the current \"",
"\"environment! Try 'rez-bind rez'!\"",
")",
"else",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"(",
"\"WARNING: Failed to find a Rez package in the current \"",
"\"environment. Unable to request Rez packages.\"",
")",
"rez_path",
"=",
"\"\"",
"else",
":",
"rez_path",
"=",
"rez_path",
".",
"strip",
"(",
")",
"print",
"\"Found Rez:\"",
",",
"rez_path",
"print",
"\"Adding Rez to system path...\"",
"sys",
".",
"path",
".",
"append",
"(",
"rez_path",
")",
"return",
"rez_path"
] | Checks to see if a Rez package is available in the current environment.
If it is available, add it to the system path, exposing the Rez Python API
:param strict: (bool) If True, raise an error if Rez is not available as a package.
This will prevent the app from being launched.
:returns: A path to the Rez package. | [
"Checks",
"to",
"see",
"if",
"a",
"Rez",
"package",
"is",
"available",
"in",
"the",
"current",
"environment",
".",
"If",
"it",
"is",
"available",
"add",
"it",
"to",
"the",
"system",
"path",
"exposing",
"the",
"Rez",
"Python",
"API"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/support/shotgun_toolkit/rez_app_launch.py#L119-L155 |
232,707 | nerdvegas/rez | src/rezplugins/release_vcs/svn.py | get_last_changed_revision | def get_last_changed_revision(client, url):
"""
util func, get last revision of url
"""
try:
svn_entries = client.info2(url,
pysvn.Revision(pysvn.opt_revision_kind.head),
recurse=False)
if not svn_entries:
raise ReleaseVCSError("svn.info2() returned no results on url %s" % url)
return svn_entries[0][1].last_changed_rev
except pysvn.ClientError, ce:
raise ReleaseVCSError("svn.info2() raised ClientError: %s" % ce) | python | def get_last_changed_revision(client, url):
"""
util func, get last revision of url
"""
try:
svn_entries = client.info2(url,
pysvn.Revision(pysvn.opt_revision_kind.head),
recurse=False)
if not svn_entries:
raise ReleaseVCSError("svn.info2() returned no results on url %s" % url)
return svn_entries[0][1].last_changed_rev
except pysvn.ClientError, ce:
raise ReleaseVCSError("svn.info2() raised ClientError: %s" % ce) | [
"def",
"get_last_changed_revision",
"(",
"client",
",",
"url",
")",
":",
"try",
":",
"svn_entries",
"=",
"client",
".",
"info2",
"(",
"url",
",",
"pysvn",
".",
"Revision",
"(",
"pysvn",
".",
"opt_revision_kind",
".",
"head",
")",
",",
"recurse",
"=",
"False",
")",
"if",
"not",
"svn_entries",
":",
"raise",
"ReleaseVCSError",
"(",
"\"svn.info2() returned no results on url %s\"",
"%",
"url",
")",
"return",
"svn_entries",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"last_changed_rev",
"except",
"pysvn",
".",
"ClientError",
",",
"ce",
":",
"raise",
"ReleaseVCSError",
"(",
"\"svn.info2() raised ClientError: %s\"",
"%",
"ce",
")"
] | util func, get last revision of url | [
"util",
"func",
"get",
"last",
"revision",
"of",
"url"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/svn.py#L26-L38 |
232,708 | nerdvegas/rez | src/rezplugins/release_vcs/svn.py | get_svn_login | def get_svn_login(realm, username, may_save):
"""
provide svn with permissions. @TODO this will have to be updated to take
into account automated releases etc.
"""
import getpass
print "svn requires a password for the user %s:" % username
pwd = ''
while not pwd.strip():
pwd = getpass.getpass("--> ")
return True, username, pwd, False | python | def get_svn_login(realm, username, may_save):
"""
provide svn with permissions. @TODO this will have to be updated to take
into account automated releases etc.
"""
import getpass
print "svn requires a password for the user %s:" % username
pwd = ''
while not pwd.strip():
pwd = getpass.getpass("--> ")
return True, username, pwd, False | [
"def",
"get_svn_login",
"(",
"realm",
",",
"username",
",",
"may_save",
")",
":",
"import",
"getpass",
"print",
"\"svn requires a password for the user %s:\"",
"%",
"username",
"pwd",
"=",
"''",
"while",
"not",
"pwd",
".",
"strip",
"(",
")",
":",
"pwd",
"=",
"getpass",
".",
"getpass",
"(",
"\"--> \"",
")",
"return",
"True",
",",
"username",
",",
"pwd",
",",
"False"
] | provide svn with permissions. @TODO this will have to be updated to take
into account automated releases etc. | [
"provide",
"svn",
"with",
"permissions",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/svn.py#L41-L53 |
232,709 | nerdvegas/rez | src/rez/vendor/pygraph/readwrite/markup.py | read | def read(string):
"""
Read a graph from a XML document and return it. Nodes and edges specified in the input will
be added to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: graph
@return: Graph
"""
dom = parseString(string)
if dom.getElementsByTagName("graph"):
G = graph()
elif dom.getElementsByTagName("digraph"):
G = digraph()
elif dom.getElementsByTagName("hypergraph"):
return read_hypergraph(string)
else:
raise InvalidGraphType
# Read nodes...
for each_node in dom.getElementsByTagName("node"):
G.add_node(each_node.getAttribute('id'))
for each_attr in each_node.getElementsByTagName("attribute"):
G.add_node_attribute(each_node.getAttribute('id'),
(each_attr.getAttribute('attr'),
each_attr.getAttribute('value')))
# Read edges...
for each_edge in dom.getElementsByTagName("edge"):
if (not G.has_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')))):
G.add_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')), \
wt = float(each_edge.getAttribute('wt')), label = each_edge.getAttribute('label'))
for each_attr in each_edge.getElementsByTagName("attribute"):
attr_tuple = (each_attr.getAttribute('attr'), each_attr.getAttribute('value'))
if (attr_tuple not in G.edge_attributes((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')))):
G.add_edge_attribute((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')), attr_tuple)
return G | python | def read(string):
"""
Read a graph from a XML document and return it. Nodes and edges specified in the input will
be added to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: graph
@return: Graph
"""
dom = parseString(string)
if dom.getElementsByTagName("graph"):
G = graph()
elif dom.getElementsByTagName("digraph"):
G = digraph()
elif dom.getElementsByTagName("hypergraph"):
return read_hypergraph(string)
else:
raise InvalidGraphType
# Read nodes...
for each_node in dom.getElementsByTagName("node"):
G.add_node(each_node.getAttribute('id'))
for each_attr in each_node.getElementsByTagName("attribute"):
G.add_node_attribute(each_node.getAttribute('id'),
(each_attr.getAttribute('attr'),
each_attr.getAttribute('value')))
# Read edges...
for each_edge in dom.getElementsByTagName("edge"):
if (not G.has_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')))):
G.add_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')), \
wt = float(each_edge.getAttribute('wt')), label = each_edge.getAttribute('label'))
for each_attr in each_edge.getElementsByTagName("attribute"):
attr_tuple = (each_attr.getAttribute('attr'), each_attr.getAttribute('value'))
if (attr_tuple not in G.edge_attributes((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')))):
G.add_edge_attribute((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')), attr_tuple)
return G | [
"def",
"read",
"(",
"string",
")",
":",
"dom",
"=",
"parseString",
"(",
"string",
")",
"if",
"dom",
".",
"getElementsByTagName",
"(",
"\"graph\"",
")",
":",
"G",
"=",
"graph",
"(",
")",
"elif",
"dom",
".",
"getElementsByTagName",
"(",
"\"digraph\"",
")",
":",
"G",
"=",
"digraph",
"(",
")",
"elif",
"dom",
".",
"getElementsByTagName",
"(",
"\"hypergraph\"",
")",
":",
"return",
"read_hypergraph",
"(",
"string",
")",
"else",
":",
"raise",
"InvalidGraphType",
"# Read nodes...",
"for",
"each_node",
"in",
"dom",
".",
"getElementsByTagName",
"(",
"\"node\"",
")",
":",
"G",
".",
"add_node",
"(",
"each_node",
".",
"getAttribute",
"(",
"'id'",
")",
")",
"for",
"each_attr",
"in",
"each_node",
".",
"getElementsByTagName",
"(",
"\"attribute\"",
")",
":",
"G",
".",
"add_node_attribute",
"(",
"each_node",
".",
"getAttribute",
"(",
"'id'",
")",
",",
"(",
"each_attr",
".",
"getAttribute",
"(",
"'attr'",
")",
",",
"each_attr",
".",
"getAttribute",
"(",
"'value'",
")",
")",
")",
"# Read edges...",
"for",
"each_edge",
"in",
"dom",
".",
"getElementsByTagName",
"(",
"\"edge\"",
")",
":",
"if",
"(",
"not",
"G",
".",
"has_edge",
"(",
"(",
"each_edge",
".",
"getAttribute",
"(",
"'from'",
")",
",",
"each_edge",
".",
"getAttribute",
"(",
"'to'",
")",
")",
")",
")",
":",
"G",
".",
"add_edge",
"(",
"(",
"each_edge",
".",
"getAttribute",
"(",
"'from'",
")",
",",
"each_edge",
".",
"getAttribute",
"(",
"'to'",
")",
")",
",",
"wt",
"=",
"float",
"(",
"each_edge",
".",
"getAttribute",
"(",
"'wt'",
")",
")",
",",
"label",
"=",
"each_edge",
".",
"getAttribute",
"(",
"'label'",
")",
")",
"for",
"each_attr",
"in",
"each_edge",
".",
"getElementsByTagName",
"(",
"\"attribute\"",
")",
":",
"attr_tuple",
"=",
"(",
"each_attr",
".",
"getAttribute",
"(",
"'attr'",
")",
",",
"each_attr",
".",
"getAttribute",
"(",
"'value'",
")",
")",
"if",
"(",
"attr_tuple",
"not",
"in",
"G",
".",
"edge_attributes",
"(",
"(",
"each_edge",
".",
"getAttribute",
"(",
"'from'",
")",
",",
"each_edge",
".",
"getAttribute",
"(",
"'to'",
")",
")",
")",
")",
":",
"G",
".",
"add_edge_attribute",
"(",
"(",
"each_edge",
".",
"getAttribute",
"(",
"'from'",
")",
",",
"each_edge",
".",
"getAttribute",
"(",
"'to'",
")",
")",
",",
"attr_tuple",
")",
"return",
"G"
] | Read a graph from a XML document and return it. Nodes and edges specified in the input will
be added to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: graph
@return: Graph | [
"Read",
"a",
"graph",
"from",
"a",
"XML",
"document",
"and",
"return",
"it",
".",
"Nodes",
"and",
"edges",
"specified",
"in",
"the",
"input",
"will",
"be",
"added",
"to",
"the",
"current",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/readwrite/markup.py#L91-L132 |
232,710 | nerdvegas/rez | src/rez/vendor/pygraph/readwrite/markup.py | read_hypergraph | def read_hypergraph(string):
"""
Read a graph from a XML document. Nodes and hyperedges specified in the input will be added
to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: hypergraph
@return: Hypergraph
"""
hgr = hypergraph()
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
hgr.add_node(each_node.getAttribute('id'))
for each_node in dom.getElementsByTagName("hyperedge"):
hgr.add_hyperedge(each_node.getAttribute('id'))
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
for each_edge in each_node.getElementsByTagName("link"):
hgr.link(str(each_node.getAttribute('id')), str(each_edge.getAttribute('to')))
return hgr | python | def read_hypergraph(string):
"""
Read a graph from a XML document. Nodes and hyperedges specified in the input will be added
to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: hypergraph
@return: Hypergraph
"""
hgr = hypergraph()
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
hgr.add_node(each_node.getAttribute('id'))
for each_node in dom.getElementsByTagName("hyperedge"):
hgr.add_hyperedge(each_node.getAttribute('id'))
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
for each_edge in each_node.getElementsByTagName("link"):
hgr.link(str(each_node.getAttribute('id')), str(each_edge.getAttribute('to')))
return hgr | [
"def",
"read_hypergraph",
"(",
"string",
")",
":",
"hgr",
"=",
"hypergraph",
"(",
")",
"dom",
"=",
"parseString",
"(",
"string",
")",
"for",
"each_node",
"in",
"dom",
".",
"getElementsByTagName",
"(",
"\"node\"",
")",
":",
"hgr",
".",
"add_node",
"(",
"each_node",
".",
"getAttribute",
"(",
"'id'",
")",
")",
"for",
"each_node",
"in",
"dom",
".",
"getElementsByTagName",
"(",
"\"hyperedge\"",
")",
":",
"hgr",
".",
"add_hyperedge",
"(",
"each_node",
".",
"getAttribute",
"(",
"'id'",
")",
")",
"dom",
"=",
"parseString",
"(",
"string",
")",
"for",
"each_node",
"in",
"dom",
".",
"getElementsByTagName",
"(",
"\"node\"",
")",
":",
"for",
"each_edge",
"in",
"each_node",
".",
"getElementsByTagName",
"(",
"\"link\"",
")",
":",
"hgr",
".",
"link",
"(",
"str",
"(",
"each_node",
".",
"getAttribute",
"(",
"'id'",
")",
")",
",",
"str",
"(",
"each_edge",
".",
"getAttribute",
"(",
"'to'",
")",
")",
")",
"return",
"hgr"
] | Read a graph from a XML document. Nodes and hyperedges specified in the input will be added
to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: hypergraph
@return: Hypergraph | [
"Read",
"a",
"graph",
"from",
"a",
"XML",
"document",
".",
"Nodes",
"and",
"hyperedges",
"specified",
"in",
"the",
"input",
"will",
"be",
"added",
"to",
"the",
"current",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/readwrite/markup.py#L172-L195 |
232,711 | nerdvegas/rez | src/rez/utils/diff_packages.py | diff_packages | def diff_packages(pkg1, pkg2=None):
"""Invoke a diff editor to show the difference between the source of two
packages.
Args:
pkg1 (`Package`): Package to diff.
pkg2 (`Package`): Package to diff against. If None, the next most recent
package version is used.
"""
if pkg2 is None:
it = iter_packages(pkg1.name)
pkgs = [x for x in it if x.version < pkg1.version]
if not pkgs:
raise RezError("No package to diff with - %s is the earliest "
"package version" % pkg1.qualified_name)
pkgs = sorted(pkgs, key=lambda x: x.version)
pkg2 = pkgs[-1]
def _check_pkg(pkg):
if not (pkg.vcs and pkg.revision):
raise RezError("Cannot diff package %s: it is a legacy format "
"package that does not contain enough information"
% pkg.qualified_name)
_check_pkg(pkg1)
_check_pkg(pkg2)
path = mkdtemp(prefix="rez-pkg-diff")
paths = []
for pkg in (pkg1, pkg2):
print "Exporting %s..." % pkg.qualified_name
path_ = os.path.join(path, pkg.qualified_name)
vcs_cls_1 = plugin_manager.get_plugin_class("release_vcs", pkg1.vcs)
vcs_cls_1.export(revision=pkg.revision, path=path_)
paths.append(path_)
difftool = config.difftool
print "Opening diff viewer %s..." % difftool
proc = Popen([difftool] + paths)
proc.wait() | python | def diff_packages(pkg1, pkg2=None):
"""Invoke a diff editor to show the difference between the source of two
packages.
Args:
pkg1 (`Package`): Package to diff.
pkg2 (`Package`): Package to diff against. If None, the next most recent
package version is used.
"""
if pkg2 is None:
it = iter_packages(pkg1.name)
pkgs = [x for x in it if x.version < pkg1.version]
if not pkgs:
raise RezError("No package to diff with - %s is the earliest "
"package version" % pkg1.qualified_name)
pkgs = sorted(pkgs, key=lambda x: x.version)
pkg2 = pkgs[-1]
def _check_pkg(pkg):
if not (pkg.vcs and pkg.revision):
raise RezError("Cannot diff package %s: it is a legacy format "
"package that does not contain enough information"
% pkg.qualified_name)
_check_pkg(pkg1)
_check_pkg(pkg2)
path = mkdtemp(prefix="rez-pkg-diff")
paths = []
for pkg in (pkg1, pkg2):
print "Exporting %s..." % pkg.qualified_name
path_ = os.path.join(path, pkg.qualified_name)
vcs_cls_1 = plugin_manager.get_plugin_class("release_vcs", pkg1.vcs)
vcs_cls_1.export(revision=pkg.revision, path=path_)
paths.append(path_)
difftool = config.difftool
print "Opening diff viewer %s..." % difftool
proc = Popen([difftool] + paths)
proc.wait() | [
"def",
"diff_packages",
"(",
"pkg1",
",",
"pkg2",
"=",
"None",
")",
":",
"if",
"pkg2",
"is",
"None",
":",
"it",
"=",
"iter_packages",
"(",
"pkg1",
".",
"name",
")",
"pkgs",
"=",
"[",
"x",
"for",
"x",
"in",
"it",
"if",
"x",
".",
"version",
"<",
"pkg1",
".",
"version",
"]",
"if",
"not",
"pkgs",
":",
"raise",
"RezError",
"(",
"\"No package to diff with - %s is the earliest \"",
"\"package version\"",
"%",
"pkg1",
".",
"qualified_name",
")",
"pkgs",
"=",
"sorted",
"(",
"pkgs",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"version",
")",
"pkg2",
"=",
"pkgs",
"[",
"-",
"1",
"]",
"def",
"_check_pkg",
"(",
"pkg",
")",
":",
"if",
"not",
"(",
"pkg",
".",
"vcs",
"and",
"pkg",
".",
"revision",
")",
":",
"raise",
"RezError",
"(",
"\"Cannot diff package %s: it is a legacy format \"",
"\"package that does not contain enough information\"",
"%",
"pkg",
".",
"qualified_name",
")",
"_check_pkg",
"(",
"pkg1",
")",
"_check_pkg",
"(",
"pkg2",
")",
"path",
"=",
"mkdtemp",
"(",
"prefix",
"=",
"\"rez-pkg-diff\"",
")",
"paths",
"=",
"[",
"]",
"for",
"pkg",
"in",
"(",
"pkg1",
",",
"pkg2",
")",
":",
"print",
"\"Exporting %s...\"",
"%",
"pkg",
".",
"qualified_name",
"path_",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"pkg",
".",
"qualified_name",
")",
"vcs_cls_1",
"=",
"plugin_manager",
".",
"get_plugin_class",
"(",
"\"release_vcs\"",
",",
"pkg1",
".",
"vcs",
")",
"vcs_cls_1",
".",
"export",
"(",
"revision",
"=",
"pkg",
".",
"revision",
",",
"path",
"=",
"path_",
")",
"paths",
".",
"append",
"(",
"path_",
")",
"difftool",
"=",
"config",
".",
"difftool",
"print",
"\"Opening diff viewer %s...\"",
"%",
"difftool",
"proc",
"=",
"Popen",
"(",
"[",
"difftool",
"]",
"+",
"paths",
")",
"proc",
".",
"wait",
"(",
")"
] | Invoke a diff editor to show the difference between the source of two
packages.
Args:
pkg1 (`Package`): Package to diff.
pkg2 (`Package`): Package to diff against. If None, the next most recent
package version is used. | [
"Invoke",
"a",
"diff",
"editor",
"to",
"show",
"the",
"difference",
"between",
"the",
"source",
"of",
"two",
"packages",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/diff_packages.py#L10-L49 |
232,712 | nerdvegas/rez | src/rez/cli/_util.py | sigint_handler | def sigint_handler(signum, frame):
"""Exit gracefully on ctrl-C."""
global _handled_int
if not _handled_int:
_handled_int = True
if not _env_var_true("_REZ_QUIET_ON_SIG"):
print >> sys.stderr, "Interrupted by user"
sigbase_handler(signum, frame) | python | def sigint_handler(signum, frame):
"""Exit gracefully on ctrl-C."""
global _handled_int
if not _handled_int:
_handled_int = True
if not _env_var_true("_REZ_QUIET_ON_SIG"):
print >> sys.stderr, "Interrupted by user"
sigbase_handler(signum, frame) | [
"def",
"sigint_handler",
"(",
"signum",
",",
"frame",
")",
":",
"global",
"_handled_int",
"if",
"not",
"_handled_int",
":",
"_handled_int",
"=",
"True",
"if",
"not",
"_env_var_true",
"(",
"\"_REZ_QUIET_ON_SIG\"",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Interrupted by user\"",
"sigbase_handler",
"(",
"signum",
",",
"frame",
")"
] | Exit gracefully on ctrl-C. | [
"Exit",
"gracefully",
"on",
"ctrl",
"-",
"C",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/_util.py#L141-L148 |
232,713 | nerdvegas/rez | src/rez/cli/_util.py | sigterm_handler | def sigterm_handler(signum, frame):
"""Exit gracefully on terminate."""
global _handled_term
if not _handled_term:
_handled_term = True
if not _env_var_true("_REZ_QUIET_ON_SIG"):
print >> sys.stderr, "Terminated by user"
sigbase_handler(signum, frame) | python | def sigterm_handler(signum, frame):
"""Exit gracefully on terminate."""
global _handled_term
if not _handled_term:
_handled_term = True
if not _env_var_true("_REZ_QUIET_ON_SIG"):
print >> sys.stderr, "Terminated by user"
sigbase_handler(signum, frame) | [
"def",
"sigterm_handler",
"(",
"signum",
",",
"frame",
")",
":",
"global",
"_handled_term",
"if",
"not",
"_handled_term",
":",
"_handled_term",
"=",
"True",
"if",
"not",
"_env_var_true",
"(",
"\"_REZ_QUIET_ON_SIG\"",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Terminated by user\"",
"sigbase_handler",
"(",
"signum",
",",
"frame",
")"
] | Exit gracefully on terminate. | [
"Exit",
"gracefully",
"on",
"terminate",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/_util.py#L151-L158 |
232,714 | nerdvegas/rez | src/rez/cli/_util.py | LazyArgumentParser.format_help | def format_help(self):
"""Sets up all sub-parsers when help is requested."""
if self._subparsers:
for action in self._subparsers._actions:
if isinstance(action, LazySubParsersAction):
for parser_name, parser in action._name_parser_map.iteritems():
action._setup_subparser(parser_name, parser)
return super(LazyArgumentParser, self).format_help() | python | def format_help(self):
"""Sets up all sub-parsers when help is requested."""
if self._subparsers:
for action in self._subparsers._actions:
if isinstance(action, LazySubParsersAction):
for parser_name, parser in action._name_parser_map.iteritems():
action._setup_subparser(parser_name, parser)
return super(LazyArgumentParser, self).format_help() | [
"def",
"format_help",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subparsers",
":",
"for",
"action",
"in",
"self",
".",
"_subparsers",
".",
"_actions",
":",
"if",
"isinstance",
"(",
"action",
",",
"LazySubParsersAction",
")",
":",
"for",
"parser_name",
",",
"parser",
"in",
"action",
".",
"_name_parser_map",
".",
"iteritems",
"(",
")",
":",
"action",
".",
"_setup_subparser",
"(",
"parser_name",
",",
"parser",
")",
"return",
"super",
"(",
"LazyArgumentParser",
",",
"self",
")",
".",
"format_help",
"(",
")"
] | Sets up all sub-parsers when help is requested. | [
"Sets",
"up",
"all",
"sub",
"-",
"parsers",
"when",
"help",
"is",
"requested",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/_util.py#L110-L117 |
232,715 | nerdvegas/rez | src/rez/utils/formatting.py | is_valid_package_name | def is_valid_package_name(name, raise_error=False):
"""Test the validity of a package name string.
Args:
name (str): Name to test.
raise_error (bool): If True, raise an exception on failure
Returns:
bool.
"""
is_valid = PACKAGE_NAME_REGEX.match(name)
if raise_error and not is_valid:
raise PackageRequestError("Not a valid package name: %r" % name)
return is_valid | python | def is_valid_package_name(name, raise_error=False):
"""Test the validity of a package name string.
Args:
name (str): Name to test.
raise_error (bool): If True, raise an exception on failure
Returns:
bool.
"""
is_valid = PACKAGE_NAME_REGEX.match(name)
if raise_error and not is_valid:
raise PackageRequestError("Not a valid package name: %r" % name)
return is_valid | [
"def",
"is_valid_package_name",
"(",
"name",
",",
"raise_error",
"=",
"False",
")",
":",
"is_valid",
"=",
"PACKAGE_NAME_REGEX",
".",
"match",
"(",
"name",
")",
"if",
"raise_error",
"and",
"not",
"is_valid",
":",
"raise",
"PackageRequestError",
"(",
"\"Not a valid package name: %r\"",
"%",
"name",
")",
"return",
"is_valid"
] | Test the validity of a package name string.
Args:
name (str): Name to test.
raise_error (bool): If True, raise an exception on failure
Returns:
bool. | [
"Test",
"the",
"validity",
"of",
"a",
"package",
"name",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L27-L40 |
232,716 | nerdvegas/rez | src/rez/utils/formatting.py | expand_abbreviations | def expand_abbreviations(txt, fields):
"""Expand abbreviations in a format string.
If an abbreviation does not match a field, or matches multiple fields, it
is left unchanged.
Example:
>>> fields = ("hey", "there", "dude")
>>> expand_abbreviations("hello {d}", fields)
'hello dude'
Args:
txt (str): Format string.
fields (list of str): Fields to expand to.
Returns:
Expanded string.
"""
def _expand(matchobj):
s = matchobj.group("var")
if s not in fields:
matches = [x for x in fields if x.startswith(s)]
if len(matches) == 1:
s = matches[0]
return "{%s}" % s
return re.sub(FORMAT_VAR_REGEX, _expand, txt) | python | def expand_abbreviations(txt, fields):
"""Expand abbreviations in a format string.
If an abbreviation does not match a field, or matches multiple fields, it
is left unchanged.
Example:
>>> fields = ("hey", "there", "dude")
>>> expand_abbreviations("hello {d}", fields)
'hello dude'
Args:
txt (str): Format string.
fields (list of str): Fields to expand to.
Returns:
Expanded string.
"""
def _expand(matchobj):
s = matchobj.group("var")
if s not in fields:
matches = [x for x in fields if x.startswith(s)]
if len(matches) == 1:
s = matches[0]
return "{%s}" % s
return re.sub(FORMAT_VAR_REGEX, _expand, txt) | [
"def",
"expand_abbreviations",
"(",
"txt",
",",
"fields",
")",
":",
"def",
"_expand",
"(",
"matchobj",
")",
":",
"s",
"=",
"matchobj",
".",
"group",
"(",
"\"var\"",
")",
"if",
"s",
"not",
"in",
"fields",
":",
"matches",
"=",
"[",
"x",
"for",
"x",
"in",
"fields",
"if",
"x",
".",
"startswith",
"(",
"s",
")",
"]",
"if",
"len",
"(",
"matches",
")",
"==",
"1",
":",
"s",
"=",
"matches",
"[",
"0",
"]",
"return",
"\"{%s}\"",
"%",
"s",
"return",
"re",
".",
"sub",
"(",
"FORMAT_VAR_REGEX",
",",
"_expand",
",",
"txt",
")"
] | Expand abbreviations in a format string.
If an abbreviation does not match a field, or matches multiple fields, it
is left unchanged.
Example:
>>> fields = ("hey", "there", "dude")
>>> expand_abbreviations("hello {d}", fields)
'hello dude'
Args:
txt (str): Format string.
fields (list of str): Fields to expand to.
Returns:
Expanded string. | [
"Expand",
"abbreviations",
"in",
"a",
"format",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L174-L200 |
232,717 | nerdvegas/rez | src/rez/utils/formatting.py | dict_to_attributes_code | def dict_to_attributes_code(dict_):
"""Given a nested dict, generate a python code equivalent.
Example:
>>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}}
>>> print dict_to_attributes_code(d)
foo = 'bah'
colors.red = 1
colors.blue = 2
Returns:
str.
"""
lines = []
for key, value in dict_.iteritems():
if isinstance(value, dict):
txt = dict_to_attributes_code(value)
lines_ = txt.split('\n')
for line in lines_:
if not line.startswith(' '):
line = "%s.%s" % (key, line)
lines.append(line)
else:
value_txt = pformat(value)
if '\n' in value_txt:
lines.append("%s = \\" % key)
value_txt = indent(value_txt)
lines.extend(value_txt.split('\n'))
else:
line = "%s = %s" % (key, value_txt)
lines.append(line)
return '\n'.join(lines) | python | def dict_to_attributes_code(dict_):
"""Given a nested dict, generate a python code equivalent.
Example:
>>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}}
>>> print dict_to_attributes_code(d)
foo = 'bah'
colors.red = 1
colors.blue = 2
Returns:
str.
"""
lines = []
for key, value in dict_.iteritems():
if isinstance(value, dict):
txt = dict_to_attributes_code(value)
lines_ = txt.split('\n')
for line in lines_:
if not line.startswith(' '):
line = "%s.%s" % (key, line)
lines.append(line)
else:
value_txt = pformat(value)
if '\n' in value_txt:
lines.append("%s = \\" % key)
value_txt = indent(value_txt)
lines.extend(value_txt.split('\n'))
else:
line = "%s = %s" % (key, value_txt)
lines.append(line)
return '\n'.join(lines) | [
"def",
"dict_to_attributes_code",
"(",
"dict_",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"dict_",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"txt",
"=",
"dict_to_attributes_code",
"(",
"value",
")",
"lines_",
"=",
"txt",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines_",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"' '",
")",
":",
"line",
"=",
"\"%s.%s\"",
"%",
"(",
"key",
",",
"line",
")",
"lines",
".",
"append",
"(",
"line",
")",
"else",
":",
"value_txt",
"=",
"pformat",
"(",
"value",
")",
"if",
"'\\n'",
"in",
"value_txt",
":",
"lines",
".",
"append",
"(",
"\"%s = \\\\\"",
"%",
"key",
")",
"value_txt",
"=",
"indent",
"(",
"value_txt",
")",
"lines",
".",
"extend",
"(",
"value_txt",
".",
"split",
"(",
"'\\n'",
")",
")",
"else",
":",
"line",
"=",
"\"%s = %s\"",
"%",
"(",
"key",
",",
"value_txt",
")",
"lines",
".",
"append",
"(",
"line",
")",
"return",
"'\\n'",
".",
"join",
"(",
"lines",
")"
] | Given a nested dict, generate a python code equivalent.
Example:
>>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}}
>>> print dict_to_attributes_code(d)
foo = 'bah'
colors.red = 1
colors.blue = 2
Returns:
str. | [
"Given",
"a",
"nested",
"dict",
"generate",
"a",
"python",
"code",
"equivalent",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L247-L279 |
232,718 | nerdvegas/rez | src/rez/utils/formatting.py | columnise | def columnise(rows, padding=2):
"""Print rows of entries in aligned columns."""
strs = []
maxwidths = {}
for row in rows:
for i, e in enumerate(row):
se = str(e)
nse = len(se)
w = maxwidths.get(i, -1)
if nse > w:
maxwidths[i] = nse
for row in rows:
s = ''
for i, e in enumerate(row):
se = str(e)
if i < len(row) - 1:
n = maxwidths[i] + padding - len(se)
se += ' ' * n
s += se
strs.append(s)
return strs | python | def columnise(rows, padding=2):
"""Print rows of entries in aligned columns."""
strs = []
maxwidths = {}
for row in rows:
for i, e in enumerate(row):
se = str(e)
nse = len(se)
w = maxwidths.get(i, -1)
if nse > w:
maxwidths[i] = nse
for row in rows:
s = ''
for i, e in enumerate(row):
se = str(e)
if i < len(row) - 1:
n = maxwidths[i] + padding - len(se)
se += ' ' * n
s += se
strs.append(s)
return strs | [
"def",
"columnise",
"(",
"rows",
",",
"padding",
"=",
"2",
")",
":",
"strs",
"=",
"[",
"]",
"maxwidths",
"=",
"{",
"}",
"for",
"row",
"in",
"rows",
":",
"for",
"i",
",",
"e",
"in",
"enumerate",
"(",
"row",
")",
":",
"se",
"=",
"str",
"(",
"e",
")",
"nse",
"=",
"len",
"(",
"se",
")",
"w",
"=",
"maxwidths",
".",
"get",
"(",
"i",
",",
"-",
"1",
")",
"if",
"nse",
">",
"w",
":",
"maxwidths",
"[",
"i",
"]",
"=",
"nse",
"for",
"row",
"in",
"rows",
":",
"s",
"=",
"''",
"for",
"i",
",",
"e",
"in",
"enumerate",
"(",
"row",
")",
":",
"se",
"=",
"str",
"(",
"e",
")",
"if",
"i",
"<",
"len",
"(",
"row",
")",
"-",
"1",
":",
"n",
"=",
"maxwidths",
"[",
"i",
"]",
"+",
"padding",
"-",
"len",
"(",
"se",
")",
"se",
"+=",
"' '",
"*",
"n",
"s",
"+=",
"se",
"strs",
".",
"append",
"(",
"s",
")",
"return",
"strs"
] | Print rows of entries in aligned columns. | [
"Print",
"rows",
"of",
"entries",
"in",
"aligned",
"columns",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L282-L304 |
232,719 | nerdvegas/rez | src/rez/utils/formatting.py | print_colored_columns | def print_colored_columns(printer, rows, padding=2):
"""Like `columnise`, but with colored rows.
Args:
printer (`colorize.Printer`): Printer object.
Note:
The last entry in each row is the row color, or None for no coloring.
"""
rows_ = [x[:-1] for x in rows]
colors = [x[-1] for x in rows]
for col, line in zip(colors, columnise(rows_, padding=padding)):
printer(line, col) | python | def print_colored_columns(printer, rows, padding=2):
"""Like `columnise`, but with colored rows.
Args:
printer (`colorize.Printer`): Printer object.
Note:
The last entry in each row is the row color, or None for no coloring.
"""
rows_ = [x[:-1] for x in rows]
colors = [x[-1] for x in rows]
for col, line in zip(colors, columnise(rows_, padding=padding)):
printer(line, col) | [
"def",
"print_colored_columns",
"(",
"printer",
",",
"rows",
",",
"padding",
"=",
"2",
")",
":",
"rows_",
"=",
"[",
"x",
"[",
":",
"-",
"1",
"]",
"for",
"x",
"in",
"rows",
"]",
"colors",
"=",
"[",
"x",
"[",
"-",
"1",
"]",
"for",
"x",
"in",
"rows",
"]",
"for",
"col",
",",
"line",
"in",
"zip",
"(",
"colors",
",",
"columnise",
"(",
"rows_",
",",
"padding",
"=",
"padding",
")",
")",
":",
"printer",
"(",
"line",
",",
"col",
")"
] | Like `columnise`, but with colored rows.
Args:
printer (`colorize.Printer`): Printer object.
Note:
The last entry in each row is the row color, or None for no coloring. | [
"Like",
"columnise",
"but",
"with",
"colored",
"rows",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L307-L319 |
232,720 | nerdvegas/rez | src/rez/utils/formatting.py | expanduser | def expanduser(path):
"""Expand '~' to home directory in the given string.
Note that this function deliberately differs from the builtin
os.path.expanduser() on Linux systems, which expands strings such as
'~sclaus' to that user's homedir. This is problematic in rez because the
string '~packagename' may inadvertently convert to a homedir, if a package
happens to match a username.
"""
if '~' not in path:
return path
if os.name == "nt":
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif 'HOMEPATH' in os.environ:
drive = os.environ.get('HOMEDRIVE', '')
userhome = os.path.join(drive, os.environ['HOMEPATH'])
else:
return path
else:
userhome = os.path.expanduser('~')
def _expanduser(path):
return EXPANDUSER_RE.sub(
lambda m: m.groups()[0] + userhome + m.groups()[1],
path)
# only replace '~' if it's at start of string or is preceeded by pathsep or
# ';' or whitespace; AND, is followed either by sep, pathsep, ';', ' ' or
# end-of-string.
#
return os.path.normpath(_expanduser(path)) | python | def expanduser(path):
"""Expand '~' to home directory in the given string.
Note that this function deliberately differs from the builtin
os.path.expanduser() on Linux systems, which expands strings such as
'~sclaus' to that user's homedir. This is problematic in rez because the
string '~packagename' may inadvertently convert to a homedir, if a package
happens to match a username.
"""
if '~' not in path:
return path
if os.name == "nt":
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif 'HOMEPATH' in os.environ:
drive = os.environ.get('HOMEDRIVE', '')
userhome = os.path.join(drive, os.environ['HOMEPATH'])
else:
return path
else:
userhome = os.path.expanduser('~')
def _expanduser(path):
return EXPANDUSER_RE.sub(
lambda m: m.groups()[0] + userhome + m.groups()[1],
path)
# only replace '~' if it's at start of string or is preceeded by pathsep or
# ';' or whitespace; AND, is followed either by sep, pathsep, ';', ' ' or
# end-of-string.
#
return os.path.normpath(_expanduser(path)) | [
"def",
"expanduser",
"(",
"path",
")",
":",
"if",
"'~'",
"not",
"in",
"path",
":",
"return",
"path",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"if",
"'HOME'",
"in",
"os",
".",
"environ",
":",
"userhome",
"=",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
"elif",
"'USERPROFILE'",
"in",
"os",
".",
"environ",
":",
"userhome",
"=",
"os",
".",
"environ",
"[",
"'USERPROFILE'",
"]",
"elif",
"'HOMEPATH'",
"in",
"os",
".",
"environ",
":",
"drive",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'HOMEDRIVE'",
",",
"''",
")",
"userhome",
"=",
"os",
".",
"path",
".",
"join",
"(",
"drive",
",",
"os",
".",
"environ",
"[",
"'HOMEPATH'",
"]",
")",
"else",
":",
"return",
"path",
"else",
":",
"userhome",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"def",
"_expanduser",
"(",
"path",
")",
":",
"return",
"EXPANDUSER_RE",
".",
"sub",
"(",
"lambda",
"m",
":",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"+",
"userhome",
"+",
"m",
".",
"groups",
"(",
")",
"[",
"1",
"]",
",",
"path",
")",
"# only replace '~' if it's at start of string or is preceeded by pathsep or",
"# ';' or whitespace; AND, is followed either by sep, pathsep, ';', ' ' or",
"# end-of-string.",
"#",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"_expanduser",
"(",
"path",
")",
")"
] | Expand '~' to home directory in the given string.
Note that this function deliberately differs from the builtin
os.path.expanduser() on Linux systems, which expands strings such as
'~sclaus' to that user's homedir. This is problematic in rez because the
string '~packagename' may inadvertently convert to a homedir, if a package
happens to match a username. | [
"Expand",
"~",
"to",
"home",
"directory",
"in",
"the",
"given",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L439-L473 |
232,721 | nerdvegas/rez | src/rez/utils/formatting.py | as_block_string | def as_block_string(txt):
"""Return a string formatted as a python block comment string, like the one
you're currently reading. Special characters are escaped if necessary.
"""
import json
lines = []
for line in txt.split('\n'):
line_ = json.dumps(line)
line_ = line_[1:-1].rstrip() # drop double quotes
lines.append(line_)
return '"""\n%s\n"""' % '\n'.join(lines) | python | def as_block_string(txt):
"""Return a string formatted as a python block comment string, like the one
you're currently reading. Special characters are escaped if necessary.
"""
import json
lines = []
for line in txt.split('\n'):
line_ = json.dumps(line)
line_ = line_[1:-1].rstrip() # drop double quotes
lines.append(line_)
return '"""\n%s\n"""' % '\n'.join(lines) | [
"def",
"as_block_string",
"(",
"txt",
")",
":",
"import",
"json",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"txt",
".",
"split",
"(",
"'\\n'",
")",
":",
"line_",
"=",
"json",
".",
"dumps",
"(",
"line",
")",
"line_",
"=",
"line_",
"[",
"1",
":",
"-",
"1",
"]",
".",
"rstrip",
"(",
")",
"# drop double quotes",
"lines",
".",
"append",
"(",
"line_",
")",
"return",
"'\"\"\"\\n%s\\n\"\"\"'",
"%",
"'\\n'",
".",
"join",
"(",
"lines",
")"
] | Return a string formatted as a python block comment string, like the one
you're currently reading. Special characters are escaped if necessary. | [
"Return",
"a",
"string",
"formatted",
"as",
"a",
"python",
"block",
"comment",
"string",
"like",
"the",
"one",
"you",
"re",
"currently",
"reading",
".",
"Special",
"characters",
"are",
"escaped",
"if",
"necessary",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L476-L488 |
232,722 | nerdvegas/rez | src/rez/utils/formatting.py | StringFormatMixin.format | def format(self, s, pretty=None, expand=None):
"""Format a string.
Args:
s (str): String to format, eg "hello {name}"
pretty (bool): If True, references to non-string attributes such as
lists are converted to basic form, with characters such as
brackets and parenthesis removed. If None, defaults to the
object's 'format_pretty' attribute.
expand (`StringFormatType`): Expansion mode. If None, will default
to the object's 'format_expand' attribute.
Returns:
The formatting string.
"""
if pretty is None:
pretty = self.format_pretty
if expand is None:
expand = self.format_expand
formatter = ObjectStringFormatter(self, pretty=pretty, expand=expand)
return formatter.format(s) | python | def format(self, s, pretty=None, expand=None):
"""Format a string.
Args:
s (str): String to format, eg "hello {name}"
pretty (bool): If True, references to non-string attributes such as
lists are converted to basic form, with characters such as
brackets and parenthesis removed. If None, defaults to the
object's 'format_pretty' attribute.
expand (`StringFormatType`): Expansion mode. If None, will default
to the object's 'format_expand' attribute.
Returns:
The formatting string.
"""
if pretty is None:
pretty = self.format_pretty
if expand is None:
expand = self.format_expand
formatter = ObjectStringFormatter(self, pretty=pretty, expand=expand)
return formatter.format(s) | [
"def",
"format",
"(",
"self",
",",
"s",
",",
"pretty",
"=",
"None",
",",
"expand",
"=",
"None",
")",
":",
"if",
"pretty",
"is",
"None",
":",
"pretty",
"=",
"self",
".",
"format_pretty",
"if",
"expand",
"is",
"None",
":",
"expand",
"=",
"self",
".",
"format_expand",
"formatter",
"=",
"ObjectStringFormatter",
"(",
"self",
",",
"pretty",
"=",
"pretty",
",",
"expand",
"=",
"expand",
")",
"return",
"formatter",
".",
"format",
"(",
"s",
")"
] | Format a string.
Args:
s (str): String to format, eg "hello {name}"
pretty (bool): If True, references to non-string attributes such as
lists are converted to basic form, with characters such as
brackets and parenthesis removed. If None, defaults to the
object's 'format_pretty' attribute.
expand (`StringFormatType`): Expansion mode. If None, will default
to the object's 'format_expand' attribute.
Returns:
The formatting string. | [
"Format",
"a",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L150-L171 |
232,723 | nerdvegas/rez | src/rez/vendor/version/version.py | Version.copy | def copy(self):
"""Returns a copy of the version."""
other = Version(None)
other.tokens = self.tokens[:]
other.seps = self.seps[:]
return other | python | def copy(self):
"""Returns a copy of the version."""
other = Version(None)
other.tokens = self.tokens[:]
other.seps = self.seps[:]
return other | [
"def",
"copy",
"(",
"self",
")",
":",
"other",
"=",
"Version",
"(",
"None",
")",
"other",
".",
"tokens",
"=",
"self",
".",
"tokens",
"[",
":",
"]",
"other",
".",
"seps",
"=",
"self",
".",
"seps",
"[",
":",
"]",
"return",
"other"
] | Returns a copy of the version. | [
"Returns",
"a",
"copy",
"of",
"the",
"version",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L297-L302 |
232,724 | nerdvegas/rez | src/rez/vendor/version/version.py | Version.trim | def trim(self, len_):
"""Return a copy of the version, possibly with less tokens.
Args:
len_ (int): New version length. If >= current length, an
unchanged copy of the version is returned.
"""
other = Version(None)
other.tokens = self.tokens[:len_]
other.seps = self.seps[:len_ - 1]
return other | python | def trim(self, len_):
"""Return a copy of the version, possibly with less tokens.
Args:
len_ (int): New version length. If >= current length, an
unchanged copy of the version is returned.
"""
other = Version(None)
other.tokens = self.tokens[:len_]
other.seps = self.seps[:len_ - 1]
return other | [
"def",
"trim",
"(",
"self",
",",
"len_",
")",
":",
"other",
"=",
"Version",
"(",
"None",
")",
"other",
".",
"tokens",
"=",
"self",
".",
"tokens",
"[",
":",
"len_",
"]",
"other",
".",
"seps",
"=",
"self",
".",
"seps",
"[",
":",
"len_",
"-",
"1",
"]",
"return",
"other"
] | Return a copy of the version, possibly with less tokens.
Args:
len_ (int): New version length. If >= current length, an
unchanged copy of the version is returned. | [
"Return",
"a",
"copy",
"of",
"the",
"version",
"possibly",
"with",
"less",
"tokens",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L304-L314 |
232,725 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.union | def union(self, other):
"""OR together version ranges.
Calculates the union of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to OR with.
Returns:
New VersionRange object representing the union.
"""
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds[:]
for range in other:
bounds += range.bounds
bounds = self._union(bounds)
range = VersionRange(None)
range.bounds = bounds
return range | python | def union(self, other):
"""OR together version ranges.
Calculates the union of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to OR with.
Returns:
New VersionRange object representing the union.
"""
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds[:]
for range in other:
bounds += range.bounds
bounds = self._union(bounds)
range = VersionRange(None)
range.bounds = bounds
return range | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"hasattr",
"(",
"other",
",",
"\"__iter__\"",
")",
":",
"other",
"=",
"[",
"other",
"]",
"bounds",
"=",
"self",
".",
"bounds",
"[",
":",
"]",
"for",
"range",
"in",
"other",
":",
"bounds",
"+=",
"range",
".",
"bounds",
"bounds",
"=",
"self",
".",
"_union",
"(",
"bounds",
")",
"range",
"=",
"VersionRange",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"bounds",
"return",
"range"
] | OR together version ranges.
Calculates the union of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to OR with.
Returns:
New VersionRange object representing the union. | [
"OR",
"together",
"version",
"ranges",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L814-L834 |
232,726 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.intersection | def intersection(self, other):
"""AND together version ranges.
Calculates the intersection of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to AND with.
Returns:
New VersionRange object representing the intersection, or None if
no ranges intersect.
"""
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds
for range in other:
bounds = self._intersection(bounds, range.bounds)
if not bounds:
return None
range = VersionRange(None)
range.bounds = bounds
return range | python | def intersection(self, other):
"""AND together version ranges.
Calculates the intersection of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to AND with.
Returns:
New VersionRange object representing the intersection, or None if
no ranges intersect.
"""
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds
for range in other:
bounds = self._intersection(bounds, range.bounds)
if not bounds:
return None
range = VersionRange(None)
range.bounds = bounds
return range | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"hasattr",
"(",
"other",
",",
"\"__iter__\"",
")",
":",
"other",
"=",
"[",
"other",
"]",
"bounds",
"=",
"self",
".",
"bounds",
"for",
"range",
"in",
"other",
":",
"bounds",
"=",
"self",
".",
"_intersection",
"(",
"bounds",
",",
"range",
".",
"bounds",
")",
"if",
"not",
"bounds",
":",
"return",
"None",
"range",
"=",
"VersionRange",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"bounds",
"return",
"range"
] | AND together version ranges.
Calculates the intersection of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to AND with.
Returns:
New VersionRange object representing the intersection, or None if
no ranges intersect. | [
"AND",
"together",
"version",
"ranges",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L836-L859 |
232,727 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.inverse | def inverse(self):
"""Calculate the inverse of the range.
Returns:
New VersionRange object representing the inverse of this range, or
None if there is no inverse (ie, this range is the any range).
"""
if self.is_any():
return None
else:
bounds = self._inverse(self.bounds)
range = VersionRange(None)
range.bounds = bounds
return range | python | def inverse(self):
"""Calculate the inverse of the range.
Returns:
New VersionRange object representing the inverse of this range, or
None if there is no inverse (ie, this range is the any range).
"""
if self.is_any():
return None
else:
bounds = self._inverse(self.bounds)
range = VersionRange(None)
range.bounds = bounds
return range | [
"def",
"inverse",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_any",
"(",
")",
":",
"return",
"None",
"else",
":",
"bounds",
"=",
"self",
".",
"_inverse",
"(",
"self",
".",
"bounds",
")",
"range",
"=",
"VersionRange",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"bounds",
"return",
"range"
] | Calculate the inverse of the range.
Returns:
New VersionRange object representing the inverse of this range, or
None if there is no inverse (ie, this range is the any range). | [
"Calculate",
"the",
"inverse",
"of",
"the",
"range",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L861-L874 |
232,728 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.split | def split(self):
"""Split into separate contiguous ranges.
Returns:
A list of VersionRange objects. For example, the range "3|5+" will
be split into ["3", "5+"].
"""
ranges = []
for bound in self.bounds:
range = VersionRange(None)
range.bounds = [bound]
ranges.append(range)
return ranges | python | def split(self):
"""Split into separate contiguous ranges.
Returns:
A list of VersionRange objects. For example, the range "3|5+" will
be split into ["3", "5+"].
"""
ranges = []
for bound in self.bounds:
range = VersionRange(None)
range.bounds = [bound]
ranges.append(range)
return ranges | [
"def",
"split",
"(",
"self",
")",
":",
"ranges",
"=",
"[",
"]",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"range",
"=",
"VersionRange",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"[",
"bound",
"]",
"ranges",
".",
"append",
"(",
"range",
")",
"return",
"ranges"
] | Split into separate contiguous ranges.
Returns:
A list of VersionRange objects. For example, the range "3|5+" will
be split into ["3", "5+"]. | [
"Split",
"into",
"separate",
"contiguous",
"ranges",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L887-L899 |
232,729 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.as_span | def as_span(cls, lower_version=None, upper_version=None,
lower_inclusive=True, upper_inclusive=True):
"""Create a range from lower_version..upper_version.
Args:
lower_version: Version object representing lower bound of the range.
upper_version: Version object representing upper bound of the range.
Returns:
`VersionRange` object.
"""
lower = (None if lower_version is None
else _LowerBound(lower_version, lower_inclusive))
upper = (None if upper_version is None
else _UpperBound(upper_version, upper_inclusive))
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | python | def as_span(cls, lower_version=None, upper_version=None,
lower_inclusive=True, upper_inclusive=True):
"""Create a range from lower_version..upper_version.
Args:
lower_version: Version object representing lower bound of the range.
upper_version: Version object representing upper bound of the range.
Returns:
`VersionRange` object.
"""
lower = (None if lower_version is None
else _LowerBound(lower_version, lower_inclusive))
upper = (None if upper_version is None
else _UpperBound(upper_version, upper_inclusive))
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | [
"def",
"as_span",
"(",
"cls",
",",
"lower_version",
"=",
"None",
",",
"upper_version",
"=",
"None",
",",
"lower_inclusive",
"=",
"True",
",",
"upper_inclusive",
"=",
"True",
")",
":",
"lower",
"=",
"(",
"None",
"if",
"lower_version",
"is",
"None",
"else",
"_LowerBound",
"(",
"lower_version",
",",
"lower_inclusive",
")",
")",
"upper",
"=",
"(",
"None",
"if",
"upper_version",
"is",
"None",
"else",
"_UpperBound",
"(",
"upper_version",
",",
"upper_inclusive",
")",
")",
"bound",
"=",
"_Bound",
"(",
"lower",
",",
"upper",
")",
"range",
"=",
"cls",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"[",
"bound",
"]",
"return",
"range"
] | Create a range from lower_version..upper_version.
Args:
lower_version: Version object representing lower bound of the range.
upper_version: Version object representing upper bound of the range.
Returns:
`VersionRange` object. | [
"Create",
"a",
"range",
"from",
"lower_version",
"..",
"upper_version",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L902-L921 |
232,730 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.from_version | def from_version(cls, version, op=None):
"""Create a range from a version.
Args:
version: Version object. This is used as the upper/lower bound of
the range.
op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<',
'lte'/'<=', 'eq'/'=='. If None, a bounded range will be created
that contains the version superset.
Returns:
`VersionRange` object.
"""
lower = None
upper = None
if op is None:
lower = _LowerBound(version, True)
upper = _UpperBound(version.next(), False)
elif op in ("eq", "=="):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
elif op in ("gt", ">"):
lower = _LowerBound(version, False)
elif op in ("gte", ">="):
lower = _LowerBound(version, True)
elif op in ("lt", "<"):
upper = _UpperBound(version, False)
elif op in ("lte", "<="):
upper = _UpperBound(version, True)
else:
raise VersionError("Unknown bound operation '%s'" % op)
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | python | def from_version(cls, version, op=None):
"""Create a range from a version.
Args:
version: Version object. This is used as the upper/lower bound of
the range.
op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<',
'lte'/'<=', 'eq'/'=='. If None, a bounded range will be created
that contains the version superset.
Returns:
`VersionRange` object.
"""
lower = None
upper = None
if op is None:
lower = _LowerBound(version, True)
upper = _UpperBound(version.next(), False)
elif op in ("eq", "=="):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
elif op in ("gt", ">"):
lower = _LowerBound(version, False)
elif op in ("gte", ">="):
lower = _LowerBound(version, True)
elif op in ("lt", "<"):
upper = _UpperBound(version, False)
elif op in ("lte", "<="):
upper = _UpperBound(version, True)
else:
raise VersionError("Unknown bound operation '%s'" % op)
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | [
"def",
"from_version",
"(",
"cls",
",",
"version",
",",
"op",
"=",
"None",
")",
":",
"lower",
"=",
"None",
"upper",
"=",
"None",
"if",
"op",
"is",
"None",
":",
"lower",
"=",
"_LowerBound",
"(",
"version",
",",
"True",
")",
"upper",
"=",
"_UpperBound",
"(",
"version",
".",
"next",
"(",
")",
",",
"False",
")",
"elif",
"op",
"in",
"(",
"\"eq\"",
",",
"\"==\"",
")",
":",
"lower",
"=",
"_LowerBound",
"(",
"version",
",",
"True",
")",
"upper",
"=",
"_UpperBound",
"(",
"version",
",",
"True",
")",
"elif",
"op",
"in",
"(",
"\"gt\"",
",",
"\">\"",
")",
":",
"lower",
"=",
"_LowerBound",
"(",
"version",
",",
"False",
")",
"elif",
"op",
"in",
"(",
"\"gte\"",
",",
"\">=\"",
")",
":",
"lower",
"=",
"_LowerBound",
"(",
"version",
",",
"True",
")",
"elif",
"op",
"in",
"(",
"\"lt\"",
",",
"\"<\"",
")",
":",
"upper",
"=",
"_UpperBound",
"(",
"version",
",",
"False",
")",
"elif",
"op",
"in",
"(",
"\"lte\"",
",",
"\"<=\"",
")",
":",
"upper",
"=",
"_UpperBound",
"(",
"version",
",",
"True",
")",
"else",
":",
"raise",
"VersionError",
"(",
"\"Unknown bound operation '%s'\"",
"%",
"op",
")",
"bound",
"=",
"_Bound",
"(",
"lower",
",",
"upper",
")",
"range",
"=",
"cls",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"[",
"bound",
"]",
"return",
"range"
] | Create a range from a version.
Args:
version: Version object. This is used as the upper/lower bound of
the range.
op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<',
'lte'/'<=', 'eq'/'=='. If None, a bounded range will be created
that contains the version superset.
Returns:
`VersionRange` object. | [
"Create",
"a",
"range",
"from",
"a",
"version",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L924-L960 |
232,731 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.from_versions | def from_versions(cls, versions):
"""Create a range from a list of versions.
This method creates a range that contains only the given versions and
no other. Typically the range looks like (for eg) "==3|==4|==5.1".
Args:
versions: List of Version objects.
Returns:
`VersionRange` object.
"""
range = cls(None)
range.bounds = []
for version in dedup(sorted(versions)):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
bound = _Bound(lower, upper)
range.bounds.append(bound)
return range | python | def from_versions(cls, versions):
"""Create a range from a list of versions.
This method creates a range that contains only the given versions and
no other. Typically the range looks like (for eg) "==3|==4|==5.1".
Args:
versions: List of Version objects.
Returns:
`VersionRange` object.
"""
range = cls(None)
range.bounds = []
for version in dedup(sorted(versions)):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
bound = _Bound(lower, upper)
range.bounds.append(bound)
return range | [
"def",
"from_versions",
"(",
"cls",
",",
"versions",
")",
":",
"range",
"=",
"cls",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"[",
"]",
"for",
"version",
"in",
"dedup",
"(",
"sorted",
"(",
"versions",
")",
")",
":",
"lower",
"=",
"_LowerBound",
"(",
"version",
",",
"True",
")",
"upper",
"=",
"_UpperBound",
"(",
"version",
",",
"True",
")",
"bound",
"=",
"_Bound",
"(",
"lower",
",",
"upper",
")",
"range",
".",
"bounds",
".",
"append",
"(",
"bound",
")",
"return",
"range"
] | Create a range from a list of versions.
This method creates a range that contains only the given versions and
no other. Typically the range looks like (for eg) "==3|==4|==5.1".
Args:
versions: List of Version objects.
Returns:
`VersionRange` object. | [
"Create",
"a",
"range",
"from",
"a",
"list",
"of",
"versions",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L963-L982 |
232,732 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.to_versions | def to_versions(self):
"""Returns exact version ranges as Version objects, or None if there
are no exact version ranges present.
"""
versions = []
for bound in self.bounds:
if bound.lower.inclusive and bound.upper.inclusive \
and (bound.lower.version == bound.upper.version):
versions.append(bound.lower.version)
return versions or None | python | def to_versions(self):
"""Returns exact version ranges as Version objects, or None if there
are no exact version ranges present.
"""
versions = []
for bound in self.bounds:
if bound.lower.inclusive and bound.upper.inclusive \
and (bound.lower.version == bound.upper.version):
versions.append(bound.lower.version)
return versions or None | [
"def",
"to_versions",
"(",
"self",
")",
":",
"versions",
"=",
"[",
"]",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"if",
"bound",
".",
"lower",
".",
"inclusive",
"and",
"bound",
".",
"upper",
".",
"inclusive",
"and",
"(",
"bound",
".",
"lower",
".",
"version",
"==",
"bound",
".",
"upper",
".",
"version",
")",
":",
"versions",
".",
"append",
"(",
"bound",
".",
"lower",
".",
"version",
")",
"return",
"versions",
"or",
"None"
] | Returns exact version ranges as Version objects, or None if there
are no exact version ranges present. | [
"Returns",
"exact",
"version",
"ranges",
"as",
"Version",
"objects",
"or",
"None",
"if",
"there",
"are",
"no",
"exact",
"version",
"ranges",
"present",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L984-L994 |
232,733 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.contains_version | def contains_version(self, version):
"""Returns True if version is contained in this range."""
if len(self.bounds) < 5:
# not worth overhead of binary search
for bound in self.bounds:
i = bound.version_containment(version)
if i == 0:
return True
if i == -1:
return False
else:
_, contains = self._contains_version(version)
return contains
return False | python | def contains_version(self, version):
"""Returns True if version is contained in this range."""
if len(self.bounds) < 5:
# not worth overhead of binary search
for bound in self.bounds:
i = bound.version_containment(version)
if i == 0:
return True
if i == -1:
return False
else:
_, contains = self._contains_version(version)
return contains
return False | [
"def",
"contains_version",
"(",
"self",
",",
"version",
")",
":",
"if",
"len",
"(",
"self",
".",
"bounds",
")",
"<",
"5",
":",
"# not worth overhead of binary search",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"i",
"=",
"bound",
".",
"version_containment",
"(",
"version",
")",
"if",
"i",
"==",
"0",
":",
"return",
"True",
"if",
"i",
"==",
"-",
"1",
":",
"return",
"False",
"else",
":",
"_",
",",
"contains",
"=",
"self",
".",
"_contains_version",
"(",
"version",
")",
"return",
"contains",
"return",
"False"
] | Returns True if version is contained in this range. | [
"Returns",
"True",
"if",
"version",
"is",
"contained",
"in",
"this",
"range",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L996-L1010 |
232,734 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.iter_intersecting | def iter_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
mode=_ContainsVersionIterator.MODE_INTERSECTING) | python | def iter_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
mode=_ContainsVersionIterator.MODE_INTERSECTING) | [
"def",
"iter_intersecting",
"(",
"self",
",",
"iterable",
",",
"key",
"=",
"None",
",",
"descending",
"=",
"False",
")",
":",
"return",
"_ContainsVersionIterator",
"(",
"self",
",",
"iterable",
",",
"key",
",",
"descending",
",",
"mode",
"=",
"_ContainsVersionIterator",
".",
"MODE_INTERSECTING",
")"
] | Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect. | [
"Like",
"iter_intersect_test",
"but",
"returns",
"intersections",
"only",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1033-L1040 |
232,735 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.iter_non_intersecting | def iter_non_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns non-intersections only.
Returns:
An iterator that returns items from `iterable` that don't intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
mode=_ContainsVersionIterator.MODE_NON_INTERSECTING) | python | def iter_non_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns non-intersections only.
Returns:
An iterator that returns items from `iterable` that don't intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
mode=_ContainsVersionIterator.MODE_NON_INTERSECTING) | [
"def",
"iter_non_intersecting",
"(",
"self",
",",
"iterable",
",",
"key",
"=",
"None",
",",
"descending",
"=",
"False",
")",
":",
"return",
"_ContainsVersionIterator",
"(",
"self",
",",
"iterable",
",",
"key",
",",
"descending",
",",
"mode",
"=",
"_ContainsVersionIterator",
".",
"MODE_NON_INTERSECTING",
")"
] | Like `iter_intersect_test`, but returns non-intersections only.
Returns:
An iterator that returns items from `iterable` that don't intersect. | [
"Like",
"iter_intersect_test",
"but",
"returns",
"non",
"-",
"intersections",
"only",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1042-L1049 |
232,736 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.span | def span(self):
"""Return a contiguous range that is a superset of this range.
Returns:
A VersionRange object representing the span of this range. For
example, the span of "2+<4|6+<8" would be "2+<8".
"""
other = VersionRange(None)
bound = _Bound(self.bounds[0].lower, self.bounds[-1].upper)
other.bounds = [bound]
return other | python | def span(self):
"""Return a contiguous range that is a superset of this range.
Returns:
A VersionRange object representing the span of this range. For
example, the span of "2+<4|6+<8" would be "2+<8".
"""
other = VersionRange(None)
bound = _Bound(self.bounds[0].lower, self.bounds[-1].upper)
other.bounds = [bound]
return other | [
"def",
"span",
"(",
"self",
")",
":",
"other",
"=",
"VersionRange",
"(",
"None",
")",
"bound",
"=",
"_Bound",
"(",
"self",
".",
"bounds",
"[",
"0",
"]",
".",
"lower",
",",
"self",
".",
"bounds",
"[",
"-",
"1",
"]",
".",
"upper",
")",
"other",
".",
"bounds",
"=",
"[",
"bound",
"]",
"return",
"other"
] | Return a contiguous range that is a superset of this range.
Returns:
A VersionRange object representing the span of this range. For
example, the span of "2+<4|6+<8" would be "2+<8". | [
"Return",
"a",
"contiguous",
"range",
"that",
"is",
"a",
"superset",
"of",
"this",
"range",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1051-L1061 |
232,737 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.visit_versions | def visit_versions(self, func):
"""Visit each version in the range, and apply a function to each.
This is for advanced usage only.
If `func` returns a `Version`, this call will change the versions in
place.
It is possible to change versions in a way that is nonsensical - for
example setting an upper bound to a smaller version than the lower bound.
Use at your own risk.
Args:
func (callable): Takes a `Version` instance arg, and is applied to
every version in the range. If `func` returns a `Version`, it
will replace the existing version, updating this `VersionRange`
instance in place.
"""
for bound in self.bounds:
if bound.lower is not _LowerBound.min:
result = func(bound.lower.version)
if isinstance(result, Version):
bound.lower.version = result
if bound.upper is not _UpperBound.inf:
result = func(bound.upper.version)
if isinstance(result, Version):
bound.upper.version = result | python | def visit_versions(self, func):
"""Visit each version in the range, and apply a function to each.
This is for advanced usage only.
If `func` returns a `Version`, this call will change the versions in
place.
It is possible to change versions in a way that is nonsensical - for
example setting an upper bound to a smaller version than the lower bound.
Use at your own risk.
Args:
func (callable): Takes a `Version` instance arg, and is applied to
every version in the range. If `func` returns a `Version`, it
will replace the existing version, updating this `VersionRange`
instance in place.
"""
for bound in self.bounds:
if bound.lower is not _LowerBound.min:
result = func(bound.lower.version)
if isinstance(result, Version):
bound.lower.version = result
if bound.upper is not _UpperBound.inf:
result = func(bound.upper.version)
if isinstance(result, Version):
bound.upper.version = result | [
"def",
"visit_versions",
"(",
"self",
",",
"func",
")",
":",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"if",
"bound",
".",
"lower",
"is",
"not",
"_LowerBound",
".",
"min",
":",
"result",
"=",
"func",
"(",
"bound",
".",
"lower",
".",
"version",
")",
"if",
"isinstance",
"(",
"result",
",",
"Version",
")",
":",
"bound",
".",
"lower",
".",
"version",
"=",
"result",
"if",
"bound",
".",
"upper",
"is",
"not",
"_UpperBound",
".",
"inf",
":",
"result",
"=",
"func",
"(",
"bound",
".",
"upper",
".",
"version",
")",
"if",
"isinstance",
"(",
"result",
",",
"Version",
")",
":",
"bound",
".",
"upper",
".",
"version",
"=",
"result"
] | Visit each version in the range, and apply a function to each.
This is for advanced usage only.
If `func` returns a `Version`, this call will change the versions in
place.
It is possible to change versions in a way that is nonsensical - for
example setting an upper bound to a smaller version than the lower bound.
Use at your own risk.
Args:
func (callable): Takes a `Version` instance arg, and is applied to
every version in the range. If `func` returns a `Version`, it
will replace the existing version, updating this `VersionRange`
instance in place. | [
"Visit",
"each",
"version",
"in",
"the",
"range",
"and",
"apply",
"a",
"function",
"to",
"each",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1065-L1092 |
232,738 | getsentry/raven-python | raven/transport/http.py | HTTPTransport.send | def send(self, url, data, headers):
"""
Sends a request to a remote webserver using HTTP POST.
"""
req = urllib2.Request(url, headers=headers)
try:
response = urlopen(
url=req,
data=data,
timeout=self.timeout,
verify_ssl=self.verify_ssl,
ca_certs=self.ca_certs,
)
except urllib2.HTTPError as exc:
msg = exc.headers.get('x-sentry-error')
code = exc.getcode()
if code == 429:
try:
retry_after = int(exc.headers.get('retry-after'))
except (ValueError, TypeError):
retry_after = 0
raise RateLimited(msg, retry_after)
elif msg:
raise APIError(msg, code)
else:
raise
return response | python | def send(self, url, data, headers):
"""
Sends a request to a remote webserver using HTTP POST.
"""
req = urllib2.Request(url, headers=headers)
try:
response = urlopen(
url=req,
data=data,
timeout=self.timeout,
verify_ssl=self.verify_ssl,
ca_certs=self.ca_certs,
)
except urllib2.HTTPError as exc:
msg = exc.headers.get('x-sentry-error')
code = exc.getcode()
if code == 429:
try:
retry_after = int(exc.headers.get('retry-after'))
except (ValueError, TypeError):
retry_after = 0
raise RateLimited(msg, retry_after)
elif msg:
raise APIError(msg, code)
else:
raise
return response | [
"def",
"send",
"(",
"self",
",",
"url",
",",
"data",
",",
"headers",
")",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"try",
":",
"response",
"=",
"urlopen",
"(",
"url",
"=",
"req",
",",
"data",
"=",
"data",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"verify_ssl",
"=",
"self",
".",
"verify_ssl",
",",
"ca_certs",
"=",
"self",
".",
"ca_certs",
",",
")",
"except",
"urllib2",
".",
"HTTPError",
"as",
"exc",
":",
"msg",
"=",
"exc",
".",
"headers",
".",
"get",
"(",
"'x-sentry-error'",
")",
"code",
"=",
"exc",
".",
"getcode",
"(",
")",
"if",
"code",
"==",
"429",
":",
"try",
":",
"retry_after",
"=",
"int",
"(",
"exc",
".",
"headers",
".",
"get",
"(",
"'retry-after'",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"retry_after",
"=",
"0",
"raise",
"RateLimited",
"(",
"msg",
",",
"retry_after",
")",
"elif",
"msg",
":",
"raise",
"APIError",
"(",
"msg",
",",
"code",
")",
"else",
":",
"raise",
"return",
"response"
] | Sends a request to a remote webserver using HTTP POST. | [
"Sends",
"a",
"request",
"to",
"a",
"remote",
"webserver",
"using",
"HTTP",
"POST",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/transport/http.py#L31-L58 |
232,739 | getsentry/raven-python | raven/contrib/django/views.py | extract_auth_vars | def extract_auth_vars(request):
"""
raven-js will pass both Authorization and X-Sentry-Auth depending on the browser
and server configurations.
"""
if request.META.get('HTTP_X_SENTRY_AUTH', '').startswith('Sentry'):
return request.META['HTTP_X_SENTRY_AUTH']
elif request.META.get('HTTP_AUTHORIZATION', '').startswith('Sentry'):
return request.META['HTTP_AUTHORIZATION']
else:
# Try to construct from GET request
args = [
'%s=%s' % i
for i in request.GET.items()
if i[0].startswith('sentry_') and i[0] != 'sentry_data'
]
if args:
return 'Sentry %s' % ', '.join(args)
return None | python | def extract_auth_vars(request):
"""
raven-js will pass both Authorization and X-Sentry-Auth depending on the browser
and server configurations.
"""
if request.META.get('HTTP_X_SENTRY_AUTH', '').startswith('Sentry'):
return request.META['HTTP_X_SENTRY_AUTH']
elif request.META.get('HTTP_AUTHORIZATION', '').startswith('Sentry'):
return request.META['HTTP_AUTHORIZATION']
else:
# Try to construct from GET request
args = [
'%s=%s' % i
for i in request.GET.items()
if i[0].startswith('sentry_') and i[0] != 'sentry_data'
]
if args:
return 'Sentry %s' % ', '.join(args)
return None | [
"def",
"extract_auth_vars",
"(",
"request",
")",
":",
"if",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_X_SENTRY_AUTH'",
",",
"''",
")",
".",
"startswith",
"(",
"'Sentry'",
")",
":",
"return",
"request",
".",
"META",
"[",
"'HTTP_X_SENTRY_AUTH'",
"]",
"elif",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_AUTHORIZATION'",
",",
"''",
")",
".",
"startswith",
"(",
"'Sentry'",
")",
":",
"return",
"request",
".",
"META",
"[",
"'HTTP_AUTHORIZATION'",
"]",
"else",
":",
"# Try to construct from GET request",
"args",
"=",
"[",
"'%s=%s'",
"%",
"i",
"for",
"i",
"in",
"request",
".",
"GET",
".",
"items",
"(",
")",
"if",
"i",
"[",
"0",
"]",
".",
"startswith",
"(",
"'sentry_'",
")",
"and",
"i",
"[",
"0",
"]",
"!=",
"'sentry_data'",
"]",
"if",
"args",
":",
"return",
"'Sentry %s'",
"%",
"', '",
".",
"join",
"(",
"args",
")",
"return",
"None"
] | raven-js will pass both Authorization and X-Sentry-Auth depending on the browser
and server configurations. | [
"raven",
"-",
"js",
"will",
"pass",
"both",
"Authorization",
"and",
"X",
"-",
"Sentry",
"-",
"Auth",
"depending",
"on",
"the",
"browser",
"and",
"server",
"configurations",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/views.py#L61-L79 |
232,740 | getsentry/raven-python | raven/events.py | Exception._get_value | def _get_value(self, exc_type, exc_value, exc_traceback):
"""
Convert exception info to a value for the values list.
"""
stack_info = get_stack_info(
iter_traceback_frames(exc_traceback),
transformer=self.transform,
capture_locals=self.client.capture_locals,
)
exc_module = getattr(exc_type, '__module__', None)
if exc_module:
exc_module = str(exc_module)
exc_type = getattr(exc_type, '__name__', '<unknown>')
return {
'value': to_unicode(exc_value),
'type': str(exc_type),
'module': to_unicode(exc_module),
'stacktrace': stack_info,
} | python | def _get_value(self, exc_type, exc_value, exc_traceback):
"""
Convert exception info to a value for the values list.
"""
stack_info = get_stack_info(
iter_traceback_frames(exc_traceback),
transformer=self.transform,
capture_locals=self.client.capture_locals,
)
exc_module = getattr(exc_type, '__module__', None)
if exc_module:
exc_module = str(exc_module)
exc_type = getattr(exc_type, '__name__', '<unknown>')
return {
'value': to_unicode(exc_value),
'type': str(exc_type),
'module': to_unicode(exc_module),
'stacktrace': stack_info,
} | [
"def",
"_get_value",
"(",
"self",
",",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
")",
":",
"stack_info",
"=",
"get_stack_info",
"(",
"iter_traceback_frames",
"(",
"exc_traceback",
")",
",",
"transformer",
"=",
"self",
".",
"transform",
",",
"capture_locals",
"=",
"self",
".",
"client",
".",
"capture_locals",
",",
")",
"exc_module",
"=",
"getattr",
"(",
"exc_type",
",",
"'__module__'",
",",
"None",
")",
"if",
"exc_module",
":",
"exc_module",
"=",
"str",
"(",
"exc_module",
")",
"exc_type",
"=",
"getattr",
"(",
"exc_type",
",",
"'__name__'",
",",
"'<unknown>'",
")",
"return",
"{",
"'value'",
":",
"to_unicode",
"(",
"exc_value",
")",
",",
"'type'",
":",
"str",
"(",
"exc_type",
")",
",",
"'module'",
":",
"to_unicode",
"(",
"exc_module",
")",
",",
"'stacktrace'",
":",
"stack_info",
",",
"}"
] | Convert exception info to a value for the values list. | [
"Convert",
"exception",
"info",
"to",
"a",
"value",
"for",
"the",
"values",
"list",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/events.py#L90-L110 |
232,741 | getsentry/raven-python | raven/breadcrumbs.py | record | def record(message=None, timestamp=None, level=None, category=None,
data=None, type=None, processor=None):
"""Records a breadcrumb for all active clients. This is what integration
code should use rather than invoking the `captureBreadcrumb` method
on a specific client.
"""
if timestamp is None:
timestamp = time()
for ctx in raven.context.get_active_contexts():
ctx.breadcrumbs.record(timestamp, level, message, category,
data, type, processor) | python | def record(message=None, timestamp=None, level=None, category=None,
data=None, type=None, processor=None):
"""Records a breadcrumb for all active clients. This is what integration
code should use rather than invoking the `captureBreadcrumb` method
on a specific client.
"""
if timestamp is None:
timestamp = time()
for ctx in raven.context.get_active_contexts():
ctx.breadcrumbs.record(timestamp, level, message, category,
data, type, processor) | [
"def",
"record",
"(",
"message",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"level",
"=",
"None",
",",
"category",
"=",
"None",
",",
"data",
"=",
"None",
",",
"type",
"=",
"None",
",",
"processor",
"=",
"None",
")",
":",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"time",
"(",
")",
"for",
"ctx",
"in",
"raven",
".",
"context",
".",
"get_active_contexts",
"(",
")",
":",
"ctx",
".",
"breadcrumbs",
".",
"record",
"(",
"timestamp",
",",
"level",
",",
"message",
",",
"category",
",",
"data",
",",
"type",
",",
"processor",
")"
] | Records a breadcrumb for all active clients. This is what integration
code should use rather than invoking the `captureBreadcrumb` method
on a specific client. | [
"Records",
"a",
"breadcrumb",
"for",
"all",
"active",
"clients",
".",
"This",
"is",
"what",
"integration",
"code",
"should",
"use",
"rather",
"than",
"invoking",
"the",
"captureBreadcrumb",
"method",
"on",
"a",
"specific",
"client",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/breadcrumbs.py#L116-L126 |
232,742 | getsentry/raven-python | raven/breadcrumbs.py | ignore_logger | def ignore_logger(name_or_logger, allow_level=None):
"""Ignores a logger during breadcrumb recording.
"""
def handler(logger, level, msg, args, kwargs):
if allow_level is not None and \
level >= allow_level:
return False
return True
register_special_log_handler(name_or_logger, handler) | python | def ignore_logger(name_or_logger, allow_level=None):
"""Ignores a logger during breadcrumb recording.
"""
def handler(logger, level, msg, args, kwargs):
if allow_level is not None and \
level >= allow_level:
return False
return True
register_special_log_handler(name_or_logger, handler) | [
"def",
"ignore_logger",
"(",
"name_or_logger",
",",
"allow_level",
"=",
"None",
")",
":",
"def",
"handler",
"(",
"logger",
",",
"level",
",",
"msg",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"allow_level",
"is",
"not",
"None",
"and",
"level",
">=",
"allow_level",
":",
"return",
"False",
"return",
"True",
"register_special_log_handler",
"(",
"name_or_logger",
",",
"handler",
")"
] | Ignores a logger during breadcrumb recording. | [
"Ignores",
"a",
"logger",
"during",
"breadcrumb",
"recording",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/breadcrumbs.py#L275-L283 |
232,743 | getsentry/raven-python | raven/utils/serializer/manager.py | Serializer.transform | def transform(self, value, **kwargs):
"""
Primary function which handles recursively transforming
values via their serializers
"""
if value is None:
return None
objid = id(value)
if objid in self.context:
return '<...>'
self.context.add(objid)
try:
for serializer in self.serializers:
try:
if serializer.can(value):
return serializer.serialize(value, **kwargs)
except Exception as e:
logger.exception(e)
return text_type(type(value))
# if all else fails, lets use the repr of the object
try:
return repr(value)
except Exception as e:
logger.exception(e)
# It's common case that a model's __unicode__ definition
# may try to query the database which if it was not
# cleaned up correctly, would hit a transaction aborted
# exception
return text_type(type(value))
finally:
self.context.remove(objid) | python | def transform(self, value, **kwargs):
"""
Primary function which handles recursively transforming
values via their serializers
"""
if value is None:
return None
objid = id(value)
if objid in self.context:
return '<...>'
self.context.add(objid)
try:
for serializer in self.serializers:
try:
if serializer.can(value):
return serializer.serialize(value, **kwargs)
except Exception as e:
logger.exception(e)
return text_type(type(value))
# if all else fails, lets use the repr of the object
try:
return repr(value)
except Exception as e:
logger.exception(e)
# It's common case that a model's __unicode__ definition
# may try to query the database which if it was not
# cleaned up correctly, would hit a transaction aborted
# exception
return text_type(type(value))
finally:
self.context.remove(objid) | [
"def",
"transform",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"objid",
"=",
"id",
"(",
"value",
")",
"if",
"objid",
"in",
"self",
".",
"context",
":",
"return",
"'<...>'",
"self",
".",
"context",
".",
"add",
"(",
"objid",
")",
"try",
":",
"for",
"serializer",
"in",
"self",
".",
"serializers",
":",
"try",
":",
"if",
"serializer",
".",
"can",
"(",
"value",
")",
":",
"return",
"serializer",
".",
"serialize",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"e",
")",
"return",
"text_type",
"(",
"type",
"(",
"value",
")",
")",
"# if all else fails, lets use the repr of the object",
"try",
":",
"return",
"repr",
"(",
"value",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"e",
")",
"# It's common case that a model's __unicode__ definition",
"# may try to query the database which if it was not",
"# cleaned up correctly, would hit a transaction aborted",
"# exception",
"return",
"text_type",
"(",
"type",
"(",
"value",
")",
")",
"finally",
":",
"self",
".",
"context",
".",
"remove",
"(",
"objid",
")"
] | Primary function which handles recursively transforming
values via their serializers | [
"Primary",
"function",
"which",
"handles",
"recursively",
"transforming",
"values",
"via",
"their",
"serializers"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/serializer/manager.py#L52-L85 |
232,744 | getsentry/raven-python | raven/contrib/tornado/__init__.py | AsyncSentryClient.send | def send(self, auth_header=None, callback=None, **data):
"""
Serializes the message and passes the payload onto ``send_encoded``.
"""
message = self.encode(data)
return self.send_encoded(message, auth_header=auth_header, callback=callback) | python | def send(self, auth_header=None, callback=None, **data):
"""
Serializes the message and passes the payload onto ``send_encoded``.
"""
message = self.encode(data)
return self.send_encoded(message, auth_header=auth_header, callback=callback) | [
"def",
"send",
"(",
"self",
",",
"auth_header",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"data",
")",
":",
"message",
"=",
"self",
".",
"encode",
"(",
"data",
")",
"return",
"self",
".",
"send_encoded",
"(",
"message",
",",
"auth_header",
"=",
"auth_header",
",",
"callback",
"=",
"callback",
")"
] | Serializes the message and passes the payload onto ``send_encoded``. | [
"Serializes",
"the",
"message",
"and",
"passes",
"the",
"payload",
"onto",
"send_encoded",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/tornado/__init__.py#L47-L53 |
232,745 | getsentry/raven-python | raven/contrib/tornado/__init__.py | AsyncSentryClient._send_remote | def _send_remote(self, url, data, headers=None, callback=None):
"""
Initialise a Tornado AsyncClient and send the request to the sentry
server. If the callback is a callable, it will be called with the
response.
"""
if headers is None:
headers = {}
return AsyncHTTPClient().fetch(
url, callback, method="POST", body=data, headers=headers,
validate_cert=self.validate_cert
) | python | def _send_remote(self, url, data, headers=None, callback=None):
"""
Initialise a Tornado AsyncClient and send the request to the sentry
server. If the callback is a callable, it will be called with the
response.
"""
if headers is None:
headers = {}
return AsyncHTTPClient().fetch(
url, callback, method="POST", body=data, headers=headers,
validate_cert=self.validate_cert
) | [
"def",
"_send_remote",
"(",
"self",
",",
"url",
",",
"data",
",",
"headers",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"}",
"return",
"AsyncHTTPClient",
"(",
")",
".",
"fetch",
"(",
"url",
",",
"callback",
",",
"method",
"=",
"\"POST\"",
",",
"body",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"validate_cert",
"=",
"self",
".",
"validate_cert",
")"
] | Initialise a Tornado AsyncClient and send the request to the sentry
server. If the callback is a callable, it will be called with the
response. | [
"Initialise",
"a",
"Tornado",
"AsyncClient",
"and",
"send",
"the",
"request",
"to",
"the",
"sentry",
"server",
".",
"If",
"the",
"callback",
"is",
"a",
"callable",
"it",
"will",
"be",
"called",
"with",
"the",
"response",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/tornado/__init__.py#L82-L94 |
232,746 | getsentry/raven-python | raven/contrib/tornado/__init__.py | SentryMixin.get_sentry_data_from_request | def get_sentry_data_from_request(self):
"""
Extracts the data required for 'sentry.interfaces.Http' from the
current request being handled by the request handler
:param return: A dictionary.
"""
return {
'request': {
'url': self.request.full_url(),
'method': self.request.method,
'data': self.request.body,
'query_string': self.request.query,
'cookies': self.request.headers.get('Cookie', None),
'headers': dict(self.request.headers),
}
} | python | def get_sentry_data_from_request(self):
"""
Extracts the data required for 'sentry.interfaces.Http' from the
current request being handled by the request handler
:param return: A dictionary.
"""
return {
'request': {
'url': self.request.full_url(),
'method': self.request.method,
'data': self.request.body,
'query_string': self.request.query,
'cookies': self.request.headers.get('Cookie', None),
'headers': dict(self.request.headers),
}
} | [
"def",
"get_sentry_data_from_request",
"(",
"self",
")",
":",
"return",
"{",
"'request'",
":",
"{",
"'url'",
":",
"self",
".",
"request",
".",
"full_url",
"(",
")",
",",
"'method'",
":",
"self",
".",
"request",
".",
"method",
",",
"'data'",
":",
"self",
".",
"request",
".",
"body",
",",
"'query_string'",
":",
"self",
".",
"request",
".",
"query",
",",
"'cookies'",
":",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Cookie'",
",",
"None",
")",
",",
"'headers'",
":",
"dict",
"(",
"self",
".",
"request",
".",
"headers",
")",
",",
"}",
"}"
] | Extracts the data required for 'sentry.interfaces.Http' from the
current request being handled by the request handler
:param return: A dictionary. | [
"Extracts",
"the",
"data",
"required",
"for",
"sentry",
".",
"interfaces",
".",
"Http",
"from",
"the",
"current",
"request",
"being",
"handled",
"by",
"the",
"request",
"handler"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/tornado/__init__.py#L147-L163 |
232,747 | getsentry/raven-python | raven/base.py | Client.get_public_dsn | def get_public_dsn(self, scheme=None):
"""
Returns a public DSN which is consumable by raven-js
>>> # Return scheme-less DSN
>>> print client.get_public_dsn()
>>> # Specify a scheme to use (http or https)
>>> print client.get_public_dsn('https')
"""
if self.is_enabled():
url = self.remote.get_public_dsn()
if scheme:
return '%s:%s' % (scheme, url)
return url | python | def get_public_dsn(self, scheme=None):
"""
Returns a public DSN which is consumable by raven-js
>>> # Return scheme-less DSN
>>> print client.get_public_dsn()
>>> # Specify a scheme to use (http or https)
>>> print client.get_public_dsn('https')
"""
if self.is_enabled():
url = self.remote.get_public_dsn()
if scheme:
return '%s:%s' % (scheme, url)
return url | [
"def",
"get_public_dsn",
"(",
"self",
",",
"scheme",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_enabled",
"(",
")",
":",
"url",
"=",
"self",
".",
"remote",
".",
"get_public_dsn",
"(",
")",
"if",
"scheme",
":",
"return",
"'%s:%s'",
"%",
"(",
"scheme",
",",
"url",
")",
"return",
"url"
] | Returns a public DSN which is consumable by raven-js
>>> # Return scheme-less DSN
>>> print client.get_public_dsn()
>>> # Specify a scheme to use (http or https)
>>> print client.get_public_dsn('https') | [
"Returns",
"a",
"public",
"DSN",
"which",
"is",
"consumable",
"by",
"raven",
"-",
"js"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L330-L345 |
232,748 | getsentry/raven-python | raven/base.py | Client.capture | def capture(self, event_type, data=None, date=None, time_spent=None,
extra=None, stack=None, tags=None, sample_rate=None,
**kwargs):
"""
Captures and processes an event and pipes it off to SentryClient.send.
To use structured data (interfaces) with capture:
>>> capture('raven.events.Message', message='foo', data={
>>> 'request': {
>>> 'url': '...',
>>> 'data': {},
>>> 'query_string': '...',
>>> 'method': 'POST',
>>> },
>>> 'logger': 'logger.name',
>>> }, extra={
>>> 'key': 'value',
>>> })
The finalized ``data`` structure contains the following (some optional)
builtin values:
>>> {
>>> # the culprit and version information
>>> 'culprit': 'full.module.name', # or /arbitrary/path
>>>
>>> # all detectable installed modules
>>> 'modules': {
>>> 'full.module.name': 'version string',
>>> },
>>>
>>> # arbitrary data provided by user
>>> 'extra': {
>>> 'key': 'value',
>>> }
>>> }
:param event_type: the module path to the Event class. Builtins can use
shorthand class notation and exclude the full module
path.
:param data: the data base, useful for specifying structured data
interfaces. Any key which contains a '.' will be
assumed to be a data interface.
:param date: the datetime of this event
:param time_spent: a integer value representing the duration of the
event (in milliseconds)
:param extra: a dictionary of additional standard metadata
:param stack: a stacktrace for the event
:param tags: dict of extra tags
:param sample_rate: a float in the range [0, 1] to sample this message
:return: a 32-length string identifying this event
"""
if not self.is_enabled():
return
exc_info = kwargs.get('exc_info')
if exc_info is not None:
if self.skip_error_for_logging(exc_info):
return
elif not self.should_capture(exc_info):
self.logger.info(
'Not capturing exception due to filters: %s', exc_info[0],
exc_info=sys.exc_info())
return
self.record_exception_seen(exc_info)
data = self.build_msg(
event_type, data, date, time_spent, extra, stack, tags=tags,
**kwargs)
# should this event be sampled?
if sample_rate is None:
sample_rate = self.sample_rate
if self._random.random() < sample_rate:
self.send(**data)
self._local_state.last_event_id = data['event_id']
return data['event_id'] | python | def capture(self, event_type, data=None, date=None, time_spent=None,
extra=None, stack=None, tags=None, sample_rate=None,
**kwargs):
"""
Captures and processes an event and pipes it off to SentryClient.send.
To use structured data (interfaces) with capture:
>>> capture('raven.events.Message', message='foo', data={
>>> 'request': {
>>> 'url': '...',
>>> 'data': {},
>>> 'query_string': '...',
>>> 'method': 'POST',
>>> },
>>> 'logger': 'logger.name',
>>> }, extra={
>>> 'key': 'value',
>>> })
The finalized ``data`` structure contains the following (some optional)
builtin values:
>>> {
>>> # the culprit and version information
>>> 'culprit': 'full.module.name', # or /arbitrary/path
>>>
>>> # all detectable installed modules
>>> 'modules': {
>>> 'full.module.name': 'version string',
>>> },
>>>
>>> # arbitrary data provided by user
>>> 'extra': {
>>> 'key': 'value',
>>> }
>>> }
:param event_type: the module path to the Event class. Builtins can use
shorthand class notation and exclude the full module
path.
:param data: the data base, useful for specifying structured data
interfaces. Any key which contains a '.' will be
assumed to be a data interface.
:param date: the datetime of this event
:param time_spent: a integer value representing the duration of the
event (in milliseconds)
:param extra: a dictionary of additional standard metadata
:param stack: a stacktrace for the event
:param tags: dict of extra tags
:param sample_rate: a float in the range [0, 1] to sample this message
:return: a 32-length string identifying this event
"""
if not self.is_enabled():
return
exc_info = kwargs.get('exc_info')
if exc_info is not None:
if self.skip_error_for_logging(exc_info):
return
elif not self.should_capture(exc_info):
self.logger.info(
'Not capturing exception due to filters: %s', exc_info[0],
exc_info=sys.exc_info())
return
self.record_exception_seen(exc_info)
data = self.build_msg(
event_type, data, date, time_spent, extra, stack, tags=tags,
**kwargs)
# should this event be sampled?
if sample_rate is None:
sample_rate = self.sample_rate
if self._random.random() < sample_rate:
self.send(**data)
self._local_state.last_event_id = data['event_id']
return data['event_id'] | [
"def",
"capture",
"(",
"self",
",",
"event_type",
",",
"data",
"=",
"None",
",",
"date",
"=",
"None",
",",
"time_spent",
"=",
"None",
",",
"extra",
"=",
"None",
",",
"stack",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"sample_rate",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"is_enabled",
"(",
")",
":",
"return",
"exc_info",
"=",
"kwargs",
".",
"get",
"(",
"'exc_info'",
")",
"if",
"exc_info",
"is",
"not",
"None",
":",
"if",
"self",
".",
"skip_error_for_logging",
"(",
"exc_info",
")",
":",
"return",
"elif",
"not",
"self",
".",
"should_capture",
"(",
"exc_info",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Not capturing exception due to filters: %s'",
",",
"exc_info",
"[",
"0",
"]",
",",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
")",
"return",
"self",
".",
"record_exception_seen",
"(",
"exc_info",
")",
"data",
"=",
"self",
".",
"build_msg",
"(",
"event_type",
",",
"data",
",",
"date",
",",
"time_spent",
",",
"extra",
",",
"stack",
",",
"tags",
"=",
"tags",
",",
"*",
"*",
"kwargs",
")",
"# should this event be sampled?",
"if",
"sample_rate",
"is",
"None",
":",
"sample_rate",
"=",
"self",
".",
"sample_rate",
"if",
"self",
".",
"_random",
".",
"random",
"(",
")",
"<",
"sample_rate",
":",
"self",
".",
"send",
"(",
"*",
"*",
"data",
")",
"self",
".",
"_local_state",
".",
"last_event_id",
"=",
"data",
"[",
"'event_id'",
"]",
"return",
"data",
"[",
"'event_id'",
"]"
] | Captures and processes an event and pipes it off to SentryClient.send.
To use structured data (interfaces) with capture:
>>> capture('raven.events.Message', message='foo', data={
>>> 'request': {
>>> 'url': '...',
>>> 'data': {},
>>> 'query_string': '...',
>>> 'method': 'POST',
>>> },
>>> 'logger': 'logger.name',
>>> }, extra={
>>> 'key': 'value',
>>> })
The finalized ``data`` structure contains the following (some optional)
builtin values:
>>> {
>>> # the culprit and version information
>>> 'culprit': 'full.module.name', # or /arbitrary/path
>>>
>>> # all detectable installed modules
>>> 'modules': {
>>> 'full.module.name': 'version string',
>>> },
>>>
>>> # arbitrary data provided by user
>>> 'extra': {
>>> 'key': 'value',
>>> }
>>> }
:param event_type: the module path to the Event class. Builtins can use
shorthand class notation and exclude the full module
path.
:param data: the data base, useful for specifying structured data
interfaces. Any key which contains a '.' will be
assumed to be a data interface.
:param date: the datetime of this event
:param time_spent: a integer value representing the duration of the
event (in milliseconds)
:param extra: a dictionary of additional standard metadata
:param stack: a stacktrace for the event
:param tags: dict of extra tags
:param sample_rate: a float in the range [0, 1] to sample this message
:return: a 32-length string identifying this event | [
"Captures",
"and",
"processes",
"an",
"event",
"and",
"pipes",
"it",
"off",
"to",
"SentryClient",
".",
"send",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L577-L657 |
232,749 | getsentry/raven-python | raven/base.py | Client._log_failed_submission | def _log_failed_submission(self, data):
"""
Log a reasonable representation of an event that should have been sent
to Sentry
"""
message = data.pop('message', '<no message value>')
output = [message]
if 'exception' in data and 'stacktrace' in data['exception']['values'][-1]:
# try to reconstruct a reasonable version of the exception
for frame in data['exception']['values'][-1]['stacktrace'].get('frames', []):
output.append(' File "%(fn)s", line %(lineno)s, in %(func)s' % {
'fn': frame.get('filename', 'unknown_filename'),
'lineno': frame.get('lineno', -1),
'func': frame.get('function', 'unknown_function'),
})
self.uncaught_logger.error(output) | python | def _log_failed_submission(self, data):
"""
Log a reasonable representation of an event that should have been sent
to Sentry
"""
message = data.pop('message', '<no message value>')
output = [message]
if 'exception' in data and 'stacktrace' in data['exception']['values'][-1]:
# try to reconstruct a reasonable version of the exception
for frame in data['exception']['values'][-1]['stacktrace'].get('frames', []):
output.append(' File "%(fn)s", line %(lineno)s, in %(func)s' % {
'fn': frame.get('filename', 'unknown_filename'),
'lineno': frame.get('lineno', -1),
'func': frame.get('function', 'unknown_function'),
})
self.uncaught_logger.error(output) | [
"def",
"_log_failed_submission",
"(",
"self",
",",
"data",
")",
":",
"message",
"=",
"data",
".",
"pop",
"(",
"'message'",
",",
"'<no message value>'",
")",
"output",
"=",
"[",
"message",
"]",
"if",
"'exception'",
"in",
"data",
"and",
"'stacktrace'",
"in",
"data",
"[",
"'exception'",
"]",
"[",
"'values'",
"]",
"[",
"-",
"1",
"]",
":",
"# try to reconstruct a reasonable version of the exception",
"for",
"frame",
"in",
"data",
"[",
"'exception'",
"]",
"[",
"'values'",
"]",
"[",
"-",
"1",
"]",
"[",
"'stacktrace'",
"]",
".",
"get",
"(",
"'frames'",
",",
"[",
"]",
")",
":",
"output",
".",
"append",
"(",
"' File \"%(fn)s\", line %(lineno)s, in %(func)s'",
"%",
"{",
"'fn'",
":",
"frame",
".",
"get",
"(",
"'filename'",
",",
"'unknown_filename'",
")",
",",
"'lineno'",
":",
"frame",
".",
"get",
"(",
"'lineno'",
",",
"-",
"1",
")",
",",
"'func'",
":",
"frame",
".",
"get",
"(",
"'function'",
",",
"'unknown_function'",
")",
",",
"}",
")",
"self",
".",
"uncaught_logger",
".",
"error",
"(",
"output",
")"
] | Log a reasonable representation of an event that should have been sent
to Sentry | [
"Log",
"a",
"reasonable",
"representation",
"of",
"an",
"event",
"that",
"should",
"have",
"been",
"sent",
"to",
"Sentry"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L696-L712 |
232,750 | getsentry/raven-python | raven/base.py | Client.send_encoded | def send_encoded(self, message, auth_header=None, **kwargs):
"""
Given an already serialized message, signs the message and passes the
payload off to ``send_remote``.
"""
client_string = 'raven-python/%s' % (raven.VERSION,)
if not auth_header:
timestamp = time.time()
auth_header = get_auth_header(
protocol=self.protocol_version,
timestamp=timestamp,
client=client_string,
api_key=self.remote.public_key,
api_secret=self.remote.secret_key,
)
headers = {
'User-Agent': client_string,
'X-Sentry-Auth': auth_header,
'Content-Encoding': self.get_content_encoding(),
'Content-Type': 'application/octet-stream',
}
return self.send_remote(
url=self.remote.store_endpoint,
data=message,
headers=headers,
**kwargs
) | python | def send_encoded(self, message, auth_header=None, **kwargs):
"""
Given an already serialized message, signs the message and passes the
payload off to ``send_remote``.
"""
client_string = 'raven-python/%s' % (raven.VERSION,)
if not auth_header:
timestamp = time.time()
auth_header = get_auth_header(
protocol=self.protocol_version,
timestamp=timestamp,
client=client_string,
api_key=self.remote.public_key,
api_secret=self.remote.secret_key,
)
headers = {
'User-Agent': client_string,
'X-Sentry-Auth': auth_header,
'Content-Encoding': self.get_content_encoding(),
'Content-Type': 'application/octet-stream',
}
return self.send_remote(
url=self.remote.store_endpoint,
data=message,
headers=headers,
**kwargs
) | [
"def",
"send_encoded",
"(",
"self",
",",
"message",
",",
"auth_header",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client_string",
"=",
"'raven-python/%s'",
"%",
"(",
"raven",
".",
"VERSION",
",",
")",
"if",
"not",
"auth_header",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"auth_header",
"=",
"get_auth_header",
"(",
"protocol",
"=",
"self",
".",
"protocol_version",
",",
"timestamp",
"=",
"timestamp",
",",
"client",
"=",
"client_string",
",",
"api_key",
"=",
"self",
".",
"remote",
".",
"public_key",
",",
"api_secret",
"=",
"self",
".",
"remote",
".",
"secret_key",
",",
")",
"headers",
"=",
"{",
"'User-Agent'",
":",
"client_string",
",",
"'X-Sentry-Auth'",
":",
"auth_header",
",",
"'Content-Encoding'",
":",
"self",
".",
"get_content_encoding",
"(",
")",
",",
"'Content-Type'",
":",
"'application/octet-stream'",
",",
"}",
"return",
"self",
".",
"send_remote",
"(",
"url",
"=",
"self",
".",
"remote",
".",
"store_endpoint",
",",
"data",
"=",
"message",
",",
"headers",
"=",
"headers",
",",
"*",
"*",
"kwargs",
")"
] | Given an already serialized message, signs the message and passes the
payload off to ``send_remote``. | [
"Given",
"an",
"already",
"serialized",
"message",
"signs",
"the",
"message",
"and",
"passes",
"the",
"payload",
"off",
"to",
"send_remote",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L752-L781 |
232,751 | getsentry/raven-python | raven/base.py | Client.captureQuery | def captureQuery(self, query, params=(), engine=None, **kwargs):
"""
Creates an event for a SQL query.
>>> client.captureQuery('SELECT * FROM foo')
"""
return self.capture(
'raven.events.Query', query=query, params=params, engine=engine,
**kwargs) | python | def captureQuery(self, query, params=(), engine=None, **kwargs):
"""
Creates an event for a SQL query.
>>> client.captureQuery('SELECT * FROM foo')
"""
return self.capture(
'raven.events.Query', query=query, params=params, engine=engine,
**kwargs) | [
"def",
"captureQuery",
"(",
"self",
",",
"query",
",",
"params",
"=",
"(",
")",
",",
"engine",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"capture",
"(",
"'raven.events.Query'",
",",
"query",
"=",
"query",
",",
"params",
"=",
"params",
",",
"engine",
"=",
"engine",
",",
"*",
"*",
"kwargs",
")"
] | Creates an event for a SQL query.
>>> client.captureQuery('SELECT * FROM foo') | [
"Creates",
"an",
"event",
"for",
"a",
"SQL",
"query",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L892-L900 |
232,752 | getsentry/raven-python | raven/base.py | Client.captureBreadcrumb | def captureBreadcrumb(self, *args, **kwargs):
"""
Records a breadcrumb with the current context. They will be
sent with the next event.
"""
# Note: framework integration should not call this method but
# instead use the raven.breadcrumbs.record_breadcrumb function
# which will record to the correct client automatically.
self.context.breadcrumbs.record(*args, **kwargs) | python | def captureBreadcrumb(self, *args, **kwargs):
"""
Records a breadcrumb with the current context. They will be
sent with the next event.
"""
# Note: framework integration should not call this method but
# instead use the raven.breadcrumbs.record_breadcrumb function
# which will record to the correct client automatically.
self.context.breadcrumbs.record(*args, **kwargs) | [
"def",
"captureBreadcrumb",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Note: framework integration should not call this method but",
"# instead use the raven.breadcrumbs.record_breadcrumb function",
"# which will record to the correct client automatically.",
"self",
".",
"context",
".",
"breadcrumbs",
".",
"record",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Records a breadcrumb with the current context. They will be
sent with the next event. | [
"Records",
"a",
"breadcrumb",
"with",
"the",
"current",
"context",
".",
"They",
"will",
"be",
"sent",
"with",
"the",
"next",
"event",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L908-L916 |
232,753 | getsentry/raven-python | raven/transport/registry.py | TransportRegistry.register_scheme | def register_scheme(self, scheme, cls):
"""
It is possible to inject new schemes at runtime
"""
if scheme in self._schemes:
raise DuplicateScheme()
urlparse.register_scheme(scheme)
# TODO (vng): verify the interface of the new class
self._schemes[scheme] = cls | python | def register_scheme(self, scheme, cls):
"""
It is possible to inject new schemes at runtime
"""
if scheme in self._schemes:
raise DuplicateScheme()
urlparse.register_scheme(scheme)
# TODO (vng): verify the interface of the new class
self._schemes[scheme] = cls | [
"def",
"register_scheme",
"(",
"self",
",",
"scheme",
",",
"cls",
")",
":",
"if",
"scheme",
"in",
"self",
".",
"_schemes",
":",
"raise",
"DuplicateScheme",
"(",
")",
"urlparse",
".",
"register_scheme",
"(",
"scheme",
")",
"# TODO (vng): verify the interface of the new class",
"self",
".",
"_schemes",
"[",
"scheme",
"]",
"=",
"cls"
] | It is possible to inject new schemes at runtime | [
"It",
"is",
"possible",
"to",
"inject",
"new",
"schemes",
"at",
"runtime"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/transport/registry.py#L40-L49 |
232,754 | getsentry/raven-python | raven/contrib/flask.py | Sentry.get_http_info | def get_http_info(self, request):
"""
Determine how to retrieve actual data by using request.mimetype.
"""
if self.is_json_type(request.mimetype):
retriever = self.get_json_data
else:
retriever = self.get_form_data
return self.get_http_info_with_retriever(request, retriever) | python | def get_http_info(self, request):
"""
Determine how to retrieve actual data by using request.mimetype.
"""
if self.is_json_type(request.mimetype):
retriever = self.get_json_data
else:
retriever = self.get_form_data
return self.get_http_info_with_retriever(request, retriever) | [
"def",
"get_http_info",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"is_json_type",
"(",
"request",
".",
"mimetype",
")",
":",
"retriever",
"=",
"self",
".",
"get_json_data",
"else",
":",
"retriever",
"=",
"self",
".",
"get_form_data",
"return",
"self",
".",
"get_http_info_with_retriever",
"(",
"request",
",",
"retriever",
")"
] | Determine how to retrieve actual data by using request.mimetype. | [
"Determine",
"how",
"to",
"retrieve",
"actual",
"data",
"by",
"using",
"request",
".",
"mimetype",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/flask.py#L194-L202 |
232,755 | getsentry/raven-python | raven/conf/__init__.py | setup_logging | def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS):
"""
Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logging(SentryHandler(client))
Within Django:
>>> from raven.contrib.django.handlers import SentryHandler
>>> setup_logging(SentryHandler())
Returns a boolean based on if logging was configured or not.
"""
logger = logging.getLogger()
if handler.__class__ in map(type, logger.handlers):
return False
logger.addHandler(handler)
# Add StreamHandler to sentry's default so you can catch missed exceptions
for logger_name in exclude:
logger = logging.getLogger(logger_name)
logger.propagate = False
logger.addHandler(logging.StreamHandler())
return True | python | def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS):
"""
Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logging(SentryHandler(client))
Within Django:
>>> from raven.contrib.django.handlers import SentryHandler
>>> setup_logging(SentryHandler())
Returns a boolean based on if logging was configured or not.
"""
logger = logging.getLogger()
if handler.__class__ in map(type, logger.handlers):
return False
logger.addHandler(handler)
# Add StreamHandler to sentry's default so you can catch missed exceptions
for logger_name in exclude:
logger = logging.getLogger(logger_name)
logger.propagate = False
logger.addHandler(logging.StreamHandler())
return True | [
"def",
"setup_logging",
"(",
"handler",
",",
"exclude",
"=",
"EXCLUDE_LOGGER_DEFAULTS",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"if",
"handler",
".",
"__class__",
"in",
"map",
"(",
"type",
",",
"logger",
".",
"handlers",
")",
":",
"return",
"False",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"# Add StreamHandler to sentry's default so you can catch missed exceptions",
"for",
"logger_name",
"in",
"exclude",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger_name",
")",
"logger",
".",
"propagate",
"=",
"False",
"logger",
".",
"addHandler",
"(",
"logging",
".",
"StreamHandler",
"(",
")",
")",
"return",
"True"
] | Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logging(SentryHandler(client))
Within Django:
>>> from raven.contrib.django.handlers import SentryHandler
>>> setup_logging(SentryHandler())
Returns a boolean based on if logging was configured or not. | [
"Configures",
"logging",
"to",
"pipe",
"to",
"Sentry",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/conf/__init__.py#L26-L57 |
232,756 | getsentry/raven-python | raven/utils/stacks.py | to_dict | def to_dict(dictish):
"""
Given something that closely resembles a dictionary, we attempt
to coerce it into a propery dictionary.
"""
if hasattr(dictish, 'iterkeys'):
m = dictish.iterkeys
elif hasattr(dictish, 'keys'):
m = dictish.keys
else:
raise ValueError(dictish)
return dict((k, dictish[k]) for k in m()) | python | def to_dict(dictish):
"""
Given something that closely resembles a dictionary, we attempt
to coerce it into a propery dictionary.
"""
if hasattr(dictish, 'iterkeys'):
m = dictish.iterkeys
elif hasattr(dictish, 'keys'):
m = dictish.keys
else:
raise ValueError(dictish)
return dict((k, dictish[k]) for k in m()) | [
"def",
"to_dict",
"(",
"dictish",
")",
":",
"if",
"hasattr",
"(",
"dictish",
",",
"'iterkeys'",
")",
":",
"m",
"=",
"dictish",
".",
"iterkeys",
"elif",
"hasattr",
"(",
"dictish",
",",
"'keys'",
")",
":",
"m",
"=",
"dictish",
".",
"keys",
"else",
":",
"raise",
"ValueError",
"(",
"dictish",
")",
"return",
"dict",
"(",
"(",
"k",
",",
"dictish",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"m",
"(",
")",
")"
] | Given something that closely resembles a dictionary, we attempt
to coerce it into a propery dictionary. | [
"Given",
"something",
"that",
"closely",
"resembles",
"a",
"dictionary",
"we",
"attempt",
"to",
"coerce",
"it",
"into",
"a",
"propery",
"dictionary",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/stacks.py#L96-L108 |
232,757 | getsentry/raven-python | raven/utils/stacks.py | slim_frame_data | def slim_frame_data(frames, frame_allowance=25):
"""
Removes various excess metadata from middle frames which go beyond
``frame_allowance``.
Returns ``frames``.
"""
frames_len = 0
app_frames = []
system_frames = []
for frame in frames:
frames_len += 1
if frame.get('in_app'):
app_frames.append(frame)
else:
system_frames.append(frame)
if frames_len <= frame_allowance:
return frames
remaining = frames_len - frame_allowance
app_count = len(app_frames)
system_allowance = max(frame_allowance - app_count, 0)
if system_allowance:
half_max = int(system_allowance / 2)
# prioritize trimming system frames
for frame in system_frames[half_max:-half_max]:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
remaining -= 1
else:
for frame in system_frames:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
remaining -= 1
if remaining:
app_allowance = app_count - remaining
half_max = int(app_allowance / 2)
for frame in app_frames[half_max:-half_max]:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
return frames | python | def slim_frame_data(frames, frame_allowance=25):
"""
Removes various excess metadata from middle frames which go beyond
``frame_allowance``.
Returns ``frames``.
"""
frames_len = 0
app_frames = []
system_frames = []
for frame in frames:
frames_len += 1
if frame.get('in_app'):
app_frames.append(frame)
else:
system_frames.append(frame)
if frames_len <= frame_allowance:
return frames
remaining = frames_len - frame_allowance
app_count = len(app_frames)
system_allowance = max(frame_allowance - app_count, 0)
if system_allowance:
half_max = int(system_allowance / 2)
# prioritize trimming system frames
for frame in system_frames[half_max:-half_max]:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
remaining -= 1
else:
for frame in system_frames:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
remaining -= 1
if remaining:
app_allowance = app_count - remaining
half_max = int(app_allowance / 2)
for frame in app_frames[half_max:-half_max]:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
return frames | [
"def",
"slim_frame_data",
"(",
"frames",
",",
"frame_allowance",
"=",
"25",
")",
":",
"frames_len",
"=",
"0",
"app_frames",
"=",
"[",
"]",
"system_frames",
"=",
"[",
"]",
"for",
"frame",
"in",
"frames",
":",
"frames_len",
"+=",
"1",
"if",
"frame",
".",
"get",
"(",
"'in_app'",
")",
":",
"app_frames",
".",
"append",
"(",
"frame",
")",
"else",
":",
"system_frames",
".",
"append",
"(",
"frame",
")",
"if",
"frames_len",
"<=",
"frame_allowance",
":",
"return",
"frames",
"remaining",
"=",
"frames_len",
"-",
"frame_allowance",
"app_count",
"=",
"len",
"(",
"app_frames",
")",
"system_allowance",
"=",
"max",
"(",
"frame_allowance",
"-",
"app_count",
",",
"0",
")",
"if",
"system_allowance",
":",
"half_max",
"=",
"int",
"(",
"system_allowance",
"/",
"2",
")",
"# prioritize trimming system frames",
"for",
"frame",
"in",
"system_frames",
"[",
"half_max",
":",
"-",
"half_max",
"]",
":",
"frame",
".",
"pop",
"(",
"'vars'",
",",
"None",
")",
"frame",
".",
"pop",
"(",
"'pre_context'",
",",
"None",
")",
"frame",
".",
"pop",
"(",
"'post_context'",
",",
"None",
")",
"remaining",
"-=",
"1",
"else",
":",
"for",
"frame",
"in",
"system_frames",
":",
"frame",
".",
"pop",
"(",
"'vars'",
",",
"None",
")",
"frame",
".",
"pop",
"(",
"'pre_context'",
",",
"None",
")",
"frame",
".",
"pop",
"(",
"'post_context'",
",",
"None",
")",
"remaining",
"-=",
"1",
"if",
"remaining",
":",
"app_allowance",
"=",
"app_count",
"-",
"remaining",
"half_max",
"=",
"int",
"(",
"app_allowance",
"/",
"2",
")",
"for",
"frame",
"in",
"app_frames",
"[",
"half_max",
":",
"-",
"half_max",
"]",
":",
"frame",
".",
"pop",
"(",
"'vars'",
",",
"None",
")",
"frame",
".",
"pop",
"(",
"'pre_context'",
",",
"None",
")",
"frame",
".",
"pop",
"(",
"'post_context'",
",",
"None",
")",
"return",
"frames"
] | Removes various excess metadata from middle frames which go beyond
``frame_allowance``.
Returns ``frames``. | [
"Removes",
"various",
"excess",
"metadata",
"from",
"middle",
"frames",
"which",
"go",
"beyond",
"frame_allowance",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/stacks.py#L167-L215 |
232,758 | getsentry/raven-python | raven/contrib/webpy/utils.py | get_data_from_request | def get_data_from_request():
"""Returns request data extracted from web.ctx."""
return {
'request': {
'url': '%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path']),
'query_string': web.ctx.query,
'method': web.ctx.method,
'data': web.data(),
'headers': dict(get_headers(web.ctx.environ)),
'env': dict(get_environ(web.ctx.environ)),
}
} | python | def get_data_from_request():
"""Returns request data extracted from web.ctx."""
return {
'request': {
'url': '%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path']),
'query_string': web.ctx.query,
'method': web.ctx.method,
'data': web.data(),
'headers': dict(get_headers(web.ctx.environ)),
'env': dict(get_environ(web.ctx.environ)),
}
} | [
"def",
"get_data_from_request",
"(",
")",
":",
"return",
"{",
"'request'",
":",
"{",
"'url'",
":",
"'%s://%s%s'",
"%",
"(",
"web",
".",
"ctx",
"[",
"'protocol'",
"]",
",",
"web",
".",
"ctx",
"[",
"'host'",
"]",
",",
"web",
".",
"ctx",
"[",
"'path'",
"]",
")",
",",
"'query_string'",
":",
"web",
".",
"ctx",
".",
"query",
",",
"'method'",
":",
"web",
".",
"ctx",
".",
"method",
",",
"'data'",
":",
"web",
".",
"data",
"(",
")",
",",
"'headers'",
":",
"dict",
"(",
"get_headers",
"(",
"web",
".",
"ctx",
".",
"environ",
")",
")",
",",
"'env'",
":",
"dict",
"(",
"get_environ",
"(",
"web",
".",
"ctx",
".",
"environ",
")",
")",
",",
"}",
"}"
] | Returns request data extracted from web.ctx. | [
"Returns",
"request",
"data",
"extracted",
"from",
"web",
".",
"ctx",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/webpy/utils.py#L15-L26 |
232,759 | getsentry/raven-python | raven/contrib/django/resolver.py | get_regex | def get_regex(resolver_or_pattern):
"""Utility method for django's deprecated resolver.regex"""
try:
regex = resolver_or_pattern.regex
except AttributeError:
regex = resolver_or_pattern.pattern.regex
return regex | python | def get_regex(resolver_or_pattern):
"""Utility method for django's deprecated resolver.regex"""
try:
regex = resolver_or_pattern.regex
except AttributeError:
regex = resolver_or_pattern.pattern.regex
return regex | [
"def",
"get_regex",
"(",
"resolver_or_pattern",
")",
":",
"try",
":",
"regex",
"=",
"resolver_or_pattern",
".",
"regex",
"except",
"AttributeError",
":",
"regex",
"=",
"resolver_or_pattern",
".",
"pattern",
".",
"regex",
"return",
"regex"
] | Utility method for django's deprecated resolver.regex | [
"Utility",
"method",
"for",
"django",
"s",
"deprecated",
"resolver",
".",
"regex"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/resolver.py#L11-L17 |
232,760 | getsentry/raven-python | raven/utils/basic.py | once | def once(func):
"""Runs a thing once and once only."""
lock = threading.Lock()
def new_func(*args, **kwargs):
if new_func.called:
return
with lock:
if new_func.called:
return
rv = func(*args, **kwargs)
new_func.called = True
return rv
new_func = update_wrapper(new_func, func)
new_func.called = False
return new_func | python | def once(func):
"""Runs a thing once and once only."""
lock = threading.Lock()
def new_func(*args, **kwargs):
if new_func.called:
return
with lock:
if new_func.called:
return
rv = func(*args, **kwargs)
new_func.called = True
return rv
new_func = update_wrapper(new_func, func)
new_func.called = False
return new_func | [
"def",
"once",
"(",
"func",
")",
":",
"lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"new_func",
".",
"called",
":",
"return",
"with",
"lock",
":",
"if",
"new_func",
".",
"called",
":",
"return",
"rv",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"new_func",
".",
"called",
"=",
"True",
"return",
"rv",
"new_func",
"=",
"update_wrapper",
"(",
"new_func",
",",
"func",
")",
"new_func",
".",
"called",
"=",
"False",
"return",
"new_func"
] | Runs a thing once and once only. | [
"Runs",
"a",
"thing",
"once",
"and",
"once",
"only",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/basic.py#L75-L91 |
232,761 | getsentry/raven-python | raven/contrib/django/utils.py | get_host | def get_host(request):
"""
A reimplementation of Django's get_host, without the
SuspiciousOperation check.
"""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in request.META):
host = request.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in request.META:
host = request.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = request.META['SERVER_NAME']
server_port = str(request.META['SERVER_PORT'])
if server_port != (request.is_secure() and '443' or '80'):
host = '%s:%s' % (host, server_port)
return host | python | def get_host(request):
"""
A reimplementation of Django's get_host, without the
SuspiciousOperation check.
"""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in request.META):
host = request.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in request.META:
host = request.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = request.META['SERVER_NAME']
server_port = str(request.META['SERVER_PORT'])
if server_port != (request.is_secure() and '443' or '80'):
host = '%s:%s' % (host, server_port)
return host | [
"def",
"get_host",
"(",
"request",
")",
":",
"# We try three options, in order of decreasing preference.",
"if",
"settings",
".",
"USE_X_FORWARDED_HOST",
"and",
"(",
"'HTTP_X_FORWARDED_HOST'",
"in",
"request",
".",
"META",
")",
":",
"host",
"=",
"request",
".",
"META",
"[",
"'HTTP_X_FORWARDED_HOST'",
"]",
"elif",
"'HTTP_HOST'",
"in",
"request",
".",
"META",
":",
"host",
"=",
"request",
".",
"META",
"[",
"'HTTP_HOST'",
"]",
"else",
":",
"# Reconstruct the host using the algorithm from PEP 333.",
"host",
"=",
"request",
".",
"META",
"[",
"'SERVER_NAME'",
"]",
"server_port",
"=",
"str",
"(",
"request",
".",
"META",
"[",
"'SERVER_PORT'",
"]",
")",
"if",
"server_port",
"!=",
"(",
"request",
".",
"is_secure",
"(",
")",
"and",
"'443'",
"or",
"'80'",
")",
":",
"host",
"=",
"'%s:%s'",
"%",
"(",
"host",
",",
"server_port",
")",
"return",
"host"
] | A reimplementation of Django's get_host, without the
SuspiciousOperation check. | [
"A",
"reimplementation",
"of",
"Django",
"s",
"get_host",
"without",
"the",
"SuspiciousOperation",
"check",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/utils.py#L84-L101 |
232,762 | getsentry/raven-python | raven/contrib/django/models.py | install_middleware | def install_middleware(middleware_name, lookup_names=None):
"""
Install specified middleware
"""
if lookup_names is None:
lookup_names = (middleware_name,)
# default settings.MIDDLEWARE is None
middleware_attr = 'MIDDLEWARE' if getattr(settings,
'MIDDLEWARE',
None) is not None \
else 'MIDDLEWARE_CLASSES'
# make sure to get an empty tuple when attr is None
middleware = getattr(settings, middleware_attr, ()) or ()
if set(lookup_names).isdisjoint(set(middleware)):
setattr(settings,
middleware_attr,
type(middleware)((middleware_name,)) + middleware) | python | def install_middleware(middleware_name, lookup_names=None):
"""
Install specified middleware
"""
if lookup_names is None:
lookup_names = (middleware_name,)
# default settings.MIDDLEWARE is None
middleware_attr = 'MIDDLEWARE' if getattr(settings,
'MIDDLEWARE',
None) is not None \
else 'MIDDLEWARE_CLASSES'
# make sure to get an empty tuple when attr is None
middleware = getattr(settings, middleware_attr, ()) or ()
if set(lookup_names).isdisjoint(set(middleware)):
setattr(settings,
middleware_attr,
type(middleware)((middleware_name,)) + middleware) | [
"def",
"install_middleware",
"(",
"middleware_name",
",",
"lookup_names",
"=",
"None",
")",
":",
"if",
"lookup_names",
"is",
"None",
":",
"lookup_names",
"=",
"(",
"middleware_name",
",",
")",
"# default settings.MIDDLEWARE is None",
"middleware_attr",
"=",
"'MIDDLEWARE'",
"if",
"getattr",
"(",
"settings",
",",
"'MIDDLEWARE'",
",",
"None",
")",
"is",
"not",
"None",
"else",
"'MIDDLEWARE_CLASSES'",
"# make sure to get an empty tuple when attr is None",
"middleware",
"=",
"getattr",
"(",
"settings",
",",
"middleware_attr",
",",
"(",
")",
")",
"or",
"(",
")",
"if",
"set",
"(",
"lookup_names",
")",
".",
"isdisjoint",
"(",
"set",
"(",
"middleware",
")",
")",
":",
"setattr",
"(",
"settings",
",",
"middleware_attr",
",",
"type",
"(",
"middleware",
")",
"(",
"(",
"middleware_name",
",",
")",
")",
"+",
"middleware",
")"
] | Install specified middleware | [
"Install",
"specified",
"middleware"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/models.py#L222-L238 |
232,763 | sebp/scikit-survival | sksurv/meta/base.py | _fit_and_score | def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params):
"""Train survival model on given data and return its score on test data"""
X_train, y_train = _safe_split(est, x, y, train_index)
train_params = fit_params.copy()
# Training
est.set_params(**parameters)
est.fit(X_train, y_train, **train_params)
# Testing
test_predict_params = predict_params.copy()
X_test, y_test = _safe_split(est, x, y, test_index, train_index)
score = scorer(est, X_test, y_test, **test_predict_params)
if not isinstance(score, numbers.Number):
raise ValueError("scoring must return a number, got %s (%s) instead."
% (str(score), type(score)))
return score | python | def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params):
"""Train survival model on given data and return its score on test data"""
X_train, y_train = _safe_split(est, x, y, train_index)
train_params = fit_params.copy()
# Training
est.set_params(**parameters)
est.fit(X_train, y_train, **train_params)
# Testing
test_predict_params = predict_params.copy()
X_test, y_test = _safe_split(est, x, y, test_index, train_index)
score = scorer(est, X_test, y_test, **test_predict_params)
if not isinstance(score, numbers.Number):
raise ValueError("scoring must return a number, got %s (%s) instead."
% (str(score), type(score)))
return score | [
"def",
"_fit_and_score",
"(",
"est",
",",
"x",
",",
"y",
",",
"scorer",
",",
"train_index",
",",
"test_index",
",",
"parameters",
",",
"fit_params",
",",
"predict_params",
")",
":",
"X_train",
",",
"y_train",
"=",
"_safe_split",
"(",
"est",
",",
"x",
",",
"y",
",",
"train_index",
")",
"train_params",
"=",
"fit_params",
".",
"copy",
"(",
")",
"# Training",
"est",
".",
"set_params",
"(",
"*",
"*",
"parameters",
")",
"est",
".",
"fit",
"(",
"X_train",
",",
"y_train",
",",
"*",
"*",
"train_params",
")",
"# Testing",
"test_predict_params",
"=",
"predict_params",
".",
"copy",
"(",
")",
"X_test",
",",
"y_test",
"=",
"_safe_split",
"(",
"est",
",",
"x",
",",
"y",
",",
"test_index",
",",
"train_index",
")",
"score",
"=",
"scorer",
"(",
"est",
",",
"X_test",
",",
"y_test",
",",
"*",
"*",
"test_predict_params",
")",
"if",
"not",
"isinstance",
"(",
"score",
",",
"numbers",
".",
"Number",
")",
":",
"raise",
"ValueError",
"(",
"\"scoring must return a number, got %s (%s) instead.\"",
"%",
"(",
"str",
"(",
"score",
")",
",",
"type",
"(",
"score",
")",
")",
")",
"return",
"score"
] | Train survival model on given data and return its score on test data | [
"Train",
"survival",
"model",
"on",
"given",
"data",
"and",
"return",
"its",
"score",
"on",
"test",
"data"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/base.py#L17-L35 |
232,764 | sebp/scikit-survival | sksurv/linear_model/coxnet.py | CoxnetSurvivalAnalysis._interpolate_coefficients | def _interpolate_coefficients(self, alpha):
"""Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to
neighbors of alpha in the list of alphas constructed during training."""
exact = False
coef_idx = None
for i, val in enumerate(self.alphas_):
if val > alpha:
coef_idx = i
elif alpha - val < numpy.finfo(numpy.float).eps:
coef_idx = i
exact = True
break
if coef_idx is None:
coef = self.coef_[:, 0]
elif exact or coef_idx == len(self.alphas_) - 1:
coef = self.coef_[:, coef_idx]
else:
# interpolate between coefficients
a1 = self.alphas_[coef_idx + 1]
a2 = self.alphas_[coef_idx]
frac = (alpha - a1) / (a2 - a1)
coef = frac * self.coef_[:, coef_idx] + (1.0 - frac) * self.coef_[:, coef_idx + 1]
return coef | python | def _interpolate_coefficients(self, alpha):
"""Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to
neighbors of alpha in the list of alphas constructed during training."""
exact = False
coef_idx = None
for i, val in enumerate(self.alphas_):
if val > alpha:
coef_idx = i
elif alpha - val < numpy.finfo(numpy.float).eps:
coef_idx = i
exact = True
break
if coef_idx is None:
coef = self.coef_[:, 0]
elif exact or coef_idx == len(self.alphas_) - 1:
coef = self.coef_[:, coef_idx]
else:
# interpolate between coefficients
a1 = self.alphas_[coef_idx + 1]
a2 = self.alphas_[coef_idx]
frac = (alpha - a1) / (a2 - a1)
coef = frac * self.coef_[:, coef_idx] + (1.0 - frac) * self.coef_[:, coef_idx + 1]
return coef | [
"def",
"_interpolate_coefficients",
"(",
"self",
",",
"alpha",
")",
":",
"exact",
"=",
"False",
"coef_idx",
"=",
"None",
"for",
"i",
",",
"val",
"in",
"enumerate",
"(",
"self",
".",
"alphas_",
")",
":",
"if",
"val",
">",
"alpha",
":",
"coef_idx",
"=",
"i",
"elif",
"alpha",
"-",
"val",
"<",
"numpy",
".",
"finfo",
"(",
"numpy",
".",
"float",
")",
".",
"eps",
":",
"coef_idx",
"=",
"i",
"exact",
"=",
"True",
"break",
"if",
"coef_idx",
"is",
"None",
":",
"coef",
"=",
"self",
".",
"coef_",
"[",
":",
",",
"0",
"]",
"elif",
"exact",
"or",
"coef_idx",
"==",
"len",
"(",
"self",
".",
"alphas_",
")",
"-",
"1",
":",
"coef",
"=",
"self",
".",
"coef_",
"[",
":",
",",
"coef_idx",
"]",
"else",
":",
"# interpolate between coefficients",
"a1",
"=",
"self",
".",
"alphas_",
"[",
"coef_idx",
"+",
"1",
"]",
"a2",
"=",
"self",
".",
"alphas_",
"[",
"coef_idx",
"]",
"frac",
"=",
"(",
"alpha",
"-",
"a1",
")",
"/",
"(",
"a2",
"-",
"a1",
")",
"coef",
"=",
"frac",
"*",
"self",
".",
"coef_",
"[",
":",
",",
"coef_idx",
"]",
"+",
"(",
"1.0",
"-",
"frac",
")",
"*",
"self",
".",
"coef_",
"[",
":",
",",
"coef_idx",
"+",
"1",
"]",
"return",
"coef"
] | Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to
neighbors of alpha in the list of alphas constructed during training. | [
"Interpolate",
"coefficients",
"by",
"calculating",
"the",
"weighted",
"average",
"of",
"coefficient",
"vectors",
"corresponding",
"to",
"neighbors",
"of",
"alpha",
"in",
"the",
"list",
"of",
"alphas",
"constructed",
"during",
"training",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxnet.py#L239-L263 |
232,765 | sebp/scikit-survival | sksurv/linear_model/coxnet.py | CoxnetSurvivalAnalysis.predict | def predict(self, X, alpha=None):
"""The linear predictor of the model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test data of which to calculate log-likelihood from
alpha : float, optional
Constant that multiplies the penalty terms. If the same alpha was used during training, exact
coefficients are used, otherwise coefficients are interpolated from the closest alpha values that
were used during training. If set to ``None``, the last alpha in the solution path is used.
Returns
-------
T : array, shape = (n_samples,)
The predicted decision function
"""
X = check_array(X)
coef = self._get_coef(alpha)
return numpy.dot(X, coef) | python | def predict(self, X, alpha=None):
"""The linear predictor of the model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test data of which to calculate log-likelihood from
alpha : float, optional
Constant that multiplies the penalty terms. If the same alpha was used during training, exact
coefficients are used, otherwise coefficients are interpolated from the closest alpha values that
were used during training. If set to ``None``, the last alpha in the solution path is used.
Returns
-------
T : array, shape = (n_samples,)
The predicted decision function
"""
X = check_array(X)
coef = self._get_coef(alpha)
return numpy.dot(X, coef) | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"alpha",
"=",
"None",
")",
":",
"X",
"=",
"check_array",
"(",
"X",
")",
"coef",
"=",
"self",
".",
"_get_coef",
"(",
"alpha",
")",
"return",
"numpy",
".",
"dot",
"(",
"X",
",",
"coef",
")"
] | The linear predictor of the model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test data of which to calculate log-likelihood from
alpha : float, optional
Constant that multiplies the penalty terms. If the same alpha was used during training, exact
coefficients are used, otherwise coefficients are interpolated from the closest alpha values that
were used during training. If set to ``None``, the last alpha in the solution path is used.
Returns
-------
T : array, shape = (n_samples,)
The predicted decision function | [
"The",
"linear",
"predictor",
"of",
"the",
"model",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxnet.py#L265-L285 |
232,766 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._create_base_ensemble | def _create_base_ensemble(self, out, n_estimators, n_folds):
"""For each base estimator collect models trained on each fold"""
ensemble_scores = numpy.empty((n_estimators, n_folds))
base_ensemble = numpy.empty_like(ensemble_scores, dtype=numpy.object)
for model, fold, score, est in out:
ensemble_scores[model, fold] = score
base_ensemble[model, fold] = est
return ensemble_scores, base_ensemble | python | def _create_base_ensemble(self, out, n_estimators, n_folds):
"""For each base estimator collect models trained on each fold"""
ensemble_scores = numpy.empty((n_estimators, n_folds))
base_ensemble = numpy.empty_like(ensemble_scores, dtype=numpy.object)
for model, fold, score, est in out:
ensemble_scores[model, fold] = score
base_ensemble[model, fold] = est
return ensemble_scores, base_ensemble | [
"def",
"_create_base_ensemble",
"(",
"self",
",",
"out",
",",
"n_estimators",
",",
"n_folds",
")",
":",
"ensemble_scores",
"=",
"numpy",
".",
"empty",
"(",
"(",
"n_estimators",
",",
"n_folds",
")",
")",
"base_ensemble",
"=",
"numpy",
".",
"empty_like",
"(",
"ensemble_scores",
",",
"dtype",
"=",
"numpy",
".",
"object",
")",
"for",
"model",
",",
"fold",
",",
"score",
",",
"est",
"in",
"out",
":",
"ensemble_scores",
"[",
"model",
",",
"fold",
"]",
"=",
"score",
"base_ensemble",
"[",
"model",
",",
"fold",
"]",
"=",
"est",
"return",
"ensemble_scores",
",",
"base_ensemble"
] | For each base estimator collect models trained on each fold | [
"For",
"each",
"base",
"estimator",
"collect",
"models",
"trained",
"on",
"each",
"fold"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L152-L160 |
232,767 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._create_cv_ensemble | def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None):
"""For each selected base estimator, average models trained on each fold"""
fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object)
for i, idx in enumerate(idx_models_included):
model_name = self.base_estimators[idx][0] if model_names is None else model_names[idx]
avg_model = EnsembleAverage(base_ensemble[idx, :], name=model_name)
fitted_models[i] = avg_model
return fitted_models | python | def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None):
"""For each selected base estimator, average models trained on each fold"""
fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object)
for i, idx in enumerate(idx_models_included):
model_name = self.base_estimators[idx][0] if model_names is None else model_names[idx]
avg_model = EnsembleAverage(base_ensemble[idx, :], name=model_name)
fitted_models[i] = avg_model
return fitted_models | [
"def",
"_create_cv_ensemble",
"(",
"self",
",",
"base_ensemble",
",",
"idx_models_included",
",",
"model_names",
"=",
"None",
")",
":",
"fitted_models",
"=",
"numpy",
".",
"empty",
"(",
"len",
"(",
"idx_models_included",
")",
",",
"dtype",
"=",
"numpy",
".",
"object",
")",
"for",
"i",
",",
"idx",
"in",
"enumerate",
"(",
"idx_models_included",
")",
":",
"model_name",
"=",
"self",
".",
"base_estimators",
"[",
"idx",
"]",
"[",
"0",
"]",
"if",
"model_names",
"is",
"None",
"else",
"model_names",
"[",
"idx",
"]",
"avg_model",
"=",
"EnsembleAverage",
"(",
"base_ensemble",
"[",
"idx",
",",
":",
"]",
",",
"name",
"=",
"model_name",
")",
"fitted_models",
"[",
"i",
"]",
"=",
"avg_model",
"return",
"fitted_models"
] | For each selected base estimator, average models trained on each fold | [
"For",
"each",
"selected",
"base",
"estimator",
"average",
"models",
"trained",
"on",
"each",
"fold"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L162-L170 |
232,768 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._get_base_estimators | def _get_base_estimators(self, X):
"""Takes special care of estimators using custom kernel function
Parameters
----------
X : array, shape = (n_samples, n_features)
Samples to pre-compute kernel matrix from.
Returns
-------
base_estimators : list
Same as `self.base_estimators`, expect that estimators with custom kernel function
use ``kernel='precomputed'``.
kernel_cache : dict
Maps estimator name to kernel matrix. Use this for cross-validation instead of `X`.
"""
base_estimators = []
kernel_cache = {}
kernel_fns = {}
for i, (name, estimator) in enumerate(self.base_estimators):
if hasattr(estimator, 'kernel') and callable(estimator.kernel):
if not hasattr(estimator, '_get_kernel'):
raise ValueError(
'estimator %s uses a custom kernel function, but does not have a _get_kernel method' % name)
kernel_mat = kernel_fns.get(estimator.kernel, None)
if kernel_mat is None:
kernel_mat = estimator._get_kernel(X)
kernel_cache[i] = kernel_mat
kernel_fns[estimator.kernel] = kernel_mat
kernel_cache[i] = kernel_mat
# We precompute kernel, but only for training, for testing use original custom kernel function
kernel_estimator = clone(estimator)
kernel_estimator.set_params(kernel='precomputed')
base_estimators.append((name, kernel_estimator))
else:
base_estimators.append((name, estimator))
return base_estimators, kernel_cache | python | def _get_base_estimators(self, X):
"""Takes special care of estimators using custom kernel function
Parameters
----------
X : array, shape = (n_samples, n_features)
Samples to pre-compute kernel matrix from.
Returns
-------
base_estimators : list
Same as `self.base_estimators`, expect that estimators with custom kernel function
use ``kernel='precomputed'``.
kernel_cache : dict
Maps estimator name to kernel matrix. Use this for cross-validation instead of `X`.
"""
base_estimators = []
kernel_cache = {}
kernel_fns = {}
for i, (name, estimator) in enumerate(self.base_estimators):
if hasattr(estimator, 'kernel') and callable(estimator.kernel):
if not hasattr(estimator, '_get_kernel'):
raise ValueError(
'estimator %s uses a custom kernel function, but does not have a _get_kernel method' % name)
kernel_mat = kernel_fns.get(estimator.kernel, None)
if kernel_mat is None:
kernel_mat = estimator._get_kernel(X)
kernel_cache[i] = kernel_mat
kernel_fns[estimator.kernel] = kernel_mat
kernel_cache[i] = kernel_mat
# We precompute kernel, but only for training, for testing use original custom kernel function
kernel_estimator = clone(estimator)
kernel_estimator.set_params(kernel='precomputed')
base_estimators.append((name, kernel_estimator))
else:
base_estimators.append((name, estimator))
return base_estimators, kernel_cache | [
"def",
"_get_base_estimators",
"(",
"self",
",",
"X",
")",
":",
"base_estimators",
"=",
"[",
"]",
"kernel_cache",
"=",
"{",
"}",
"kernel_fns",
"=",
"{",
"}",
"for",
"i",
",",
"(",
"name",
",",
"estimator",
")",
"in",
"enumerate",
"(",
"self",
".",
"base_estimators",
")",
":",
"if",
"hasattr",
"(",
"estimator",
",",
"'kernel'",
")",
"and",
"callable",
"(",
"estimator",
".",
"kernel",
")",
":",
"if",
"not",
"hasattr",
"(",
"estimator",
",",
"'_get_kernel'",
")",
":",
"raise",
"ValueError",
"(",
"'estimator %s uses a custom kernel function, but does not have a _get_kernel method'",
"%",
"name",
")",
"kernel_mat",
"=",
"kernel_fns",
".",
"get",
"(",
"estimator",
".",
"kernel",
",",
"None",
")",
"if",
"kernel_mat",
"is",
"None",
":",
"kernel_mat",
"=",
"estimator",
".",
"_get_kernel",
"(",
"X",
")",
"kernel_cache",
"[",
"i",
"]",
"=",
"kernel_mat",
"kernel_fns",
"[",
"estimator",
".",
"kernel",
"]",
"=",
"kernel_mat",
"kernel_cache",
"[",
"i",
"]",
"=",
"kernel_mat",
"# We precompute kernel, but only for training, for testing use original custom kernel function",
"kernel_estimator",
"=",
"clone",
"(",
"estimator",
")",
"kernel_estimator",
".",
"set_params",
"(",
"kernel",
"=",
"'precomputed'",
")",
"base_estimators",
".",
"append",
"(",
"(",
"name",
",",
"kernel_estimator",
")",
")",
"else",
":",
"base_estimators",
".",
"append",
"(",
"(",
"name",
",",
"estimator",
")",
")",
"return",
"base_estimators",
",",
"kernel_cache"
] | Takes special care of estimators using custom kernel function
Parameters
----------
X : array, shape = (n_samples, n_features)
Samples to pre-compute kernel matrix from.
Returns
-------
base_estimators : list
Same as `self.base_estimators`, expect that estimators with custom kernel function
use ``kernel='precomputed'``.
kernel_cache : dict
Maps estimator name to kernel matrix. Use this for cross-validation instead of `X`. | [
"Takes",
"special",
"care",
"of",
"estimators",
"using",
"custom",
"kernel",
"function"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L172-L214 |
232,769 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._restore_base_estimators | def _restore_base_estimators(self, kernel_cache, out, X, cv):
"""Restore custom kernel functions of estimators for predictions"""
train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)}
for idx, fold, _, est in out:
if idx in kernel_cache:
if not hasattr(est, 'fit_X_'):
raise ValueError(
'estimator %s uses a custom kernel function, '
'but does not have the attribute `fit_X_` after training' % self.base_estimators[idx][0])
est.set_params(kernel=self.base_estimators[idx][1].kernel)
est.fit_X_ = X[train_folds[fold]]
return out | python | def _restore_base_estimators(self, kernel_cache, out, X, cv):
"""Restore custom kernel functions of estimators for predictions"""
train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)}
for idx, fold, _, est in out:
if idx in kernel_cache:
if not hasattr(est, 'fit_X_'):
raise ValueError(
'estimator %s uses a custom kernel function, '
'but does not have the attribute `fit_X_` after training' % self.base_estimators[idx][0])
est.set_params(kernel=self.base_estimators[idx][1].kernel)
est.fit_X_ = X[train_folds[fold]]
return out | [
"def",
"_restore_base_estimators",
"(",
"self",
",",
"kernel_cache",
",",
"out",
",",
"X",
",",
"cv",
")",
":",
"train_folds",
"=",
"{",
"fold",
":",
"train_index",
"for",
"fold",
",",
"(",
"train_index",
",",
"_",
")",
"in",
"enumerate",
"(",
"cv",
")",
"}",
"for",
"idx",
",",
"fold",
",",
"_",
",",
"est",
"in",
"out",
":",
"if",
"idx",
"in",
"kernel_cache",
":",
"if",
"not",
"hasattr",
"(",
"est",
",",
"'fit_X_'",
")",
":",
"raise",
"ValueError",
"(",
"'estimator %s uses a custom kernel function, '",
"'but does not have the attribute `fit_X_` after training'",
"%",
"self",
".",
"base_estimators",
"[",
"idx",
"]",
"[",
"0",
"]",
")",
"est",
".",
"set_params",
"(",
"kernel",
"=",
"self",
".",
"base_estimators",
"[",
"idx",
"]",
"[",
"1",
"]",
".",
"kernel",
")",
"est",
".",
"fit_X_",
"=",
"X",
"[",
"train_folds",
"[",
"fold",
"]",
"]",
"return",
"out"
] | Restore custom kernel functions of estimators for predictions | [
"Restore",
"custom",
"kernel",
"functions",
"of",
"estimators",
"for",
"predictions"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L216-L230 |
232,770 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._fit_and_score_ensemble | def _fit_and_score_ensemble(self, X, y, cv, **fit_params):
"""Create a cross-validated model by training a model for each fold with the same model parameters"""
fit_params_steps = self._split_fit_params(fit_params)
folds = list(cv.split(X, y))
# Take care of custom kernel functions
base_estimators, kernel_cache = self._get_base_estimators(X)
out = Parallel(
n_jobs=self.n_jobs, verbose=self.verbose
)(
delayed(_fit_and_score_fold)(clone(estimator),
X if i not in kernel_cache else kernel_cache[i],
y,
self.scorer,
train_index, test_index,
fit_params_steps[name],
i, fold)
for i, (name, estimator) in enumerate(base_estimators)
for fold, (train_index, test_index) in enumerate(folds))
if len(kernel_cache) > 0:
out = self._restore_base_estimators(kernel_cache, out, X, folds)
return self._create_base_ensemble(out, len(base_estimators), len(folds)) | python | def _fit_and_score_ensemble(self, X, y, cv, **fit_params):
"""Create a cross-validated model by training a model for each fold with the same model parameters"""
fit_params_steps = self._split_fit_params(fit_params)
folds = list(cv.split(X, y))
# Take care of custom kernel functions
base_estimators, kernel_cache = self._get_base_estimators(X)
out = Parallel(
n_jobs=self.n_jobs, verbose=self.verbose
)(
delayed(_fit_and_score_fold)(clone(estimator),
X if i not in kernel_cache else kernel_cache[i],
y,
self.scorer,
train_index, test_index,
fit_params_steps[name],
i, fold)
for i, (name, estimator) in enumerate(base_estimators)
for fold, (train_index, test_index) in enumerate(folds))
if len(kernel_cache) > 0:
out = self._restore_base_estimators(kernel_cache, out, X, folds)
return self._create_base_ensemble(out, len(base_estimators), len(folds)) | [
"def",
"_fit_and_score_ensemble",
"(",
"self",
",",
"X",
",",
"y",
",",
"cv",
",",
"*",
"*",
"fit_params",
")",
":",
"fit_params_steps",
"=",
"self",
".",
"_split_fit_params",
"(",
"fit_params",
")",
"folds",
"=",
"list",
"(",
"cv",
".",
"split",
"(",
"X",
",",
"y",
")",
")",
"# Take care of custom kernel functions",
"base_estimators",
",",
"kernel_cache",
"=",
"self",
".",
"_get_base_estimators",
"(",
"X",
")",
"out",
"=",
"Parallel",
"(",
"n_jobs",
"=",
"self",
".",
"n_jobs",
",",
"verbose",
"=",
"self",
".",
"verbose",
")",
"(",
"delayed",
"(",
"_fit_and_score_fold",
")",
"(",
"clone",
"(",
"estimator",
")",
",",
"X",
"if",
"i",
"not",
"in",
"kernel_cache",
"else",
"kernel_cache",
"[",
"i",
"]",
",",
"y",
",",
"self",
".",
"scorer",
",",
"train_index",
",",
"test_index",
",",
"fit_params_steps",
"[",
"name",
"]",
",",
"i",
",",
"fold",
")",
"for",
"i",
",",
"(",
"name",
",",
"estimator",
")",
"in",
"enumerate",
"(",
"base_estimators",
")",
"for",
"fold",
",",
"(",
"train_index",
",",
"test_index",
")",
"in",
"enumerate",
"(",
"folds",
")",
")",
"if",
"len",
"(",
"kernel_cache",
")",
">",
"0",
":",
"out",
"=",
"self",
".",
"_restore_base_estimators",
"(",
"kernel_cache",
",",
"out",
",",
"X",
",",
"folds",
")",
"return",
"self",
".",
"_create_base_ensemble",
"(",
"out",
",",
"len",
"(",
"base_estimators",
")",
",",
"len",
"(",
"folds",
")",
")"
] | Create a cross-validated model by training a model for each fold with the same model parameters | [
"Create",
"a",
"cross",
"-",
"validated",
"model",
"by",
"training",
"a",
"model",
"for",
"each",
"fold",
"with",
"the",
"same",
"model",
"parameters"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L232-L257 |
232,771 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection.fit | def fit(self, X, y=None, **fit_params):
"""Fit ensemble of models
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self
"""
self._check_params()
cv = check_cv(self.cv, X)
self._fit(X, y, cv, **fit_params)
return self | python | def fit(self, X, y=None, **fit_params):
"""Fit ensemble of models
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self
"""
self._check_params()
cv = check_cv(self.cv, X)
self._fit(X, y, cv, **fit_params)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"fit_params",
")",
":",
"self",
".",
"_check_params",
"(",
")",
"cv",
"=",
"check_cv",
"(",
"self",
".",
"cv",
",",
"X",
")",
"self",
".",
"_fit",
"(",
"X",
",",
"y",
",",
"cv",
",",
"*",
"*",
"fit_params",
")",
"return",
"self"
] | Fit ensemble of models
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self | [
"Fit",
"ensemble",
"of",
"models"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L277-L297 |
232,772 | sebp/scikit-survival | sksurv/io/arffwrite.py | writearff | def writearff(data, filename, relation_name=None, index=True):
"""Write ARFF file
Parameters
----------
data : :class:`pandas.DataFrame`
DataFrame containing data
filename : string or file-like object
Path to ARFF file or file-like object. In the latter case,
the handle is closed by calling this function.
relation_name : string, optional, default: "pandas"
Name of relation in ARFF file.
index : boolean, optional, default: True
Write row names (index)
"""
if isinstance(filename, str):
fp = open(filename, 'w')
if relation_name is None:
relation_name = os.path.basename(filename)
else:
fp = filename
if relation_name is None:
relation_name = "pandas"
try:
data = _write_header(data, fp, relation_name, index)
fp.write("\n")
_write_data(data, fp)
finally:
fp.close() | python | def writearff(data, filename, relation_name=None, index=True):
"""Write ARFF file
Parameters
----------
data : :class:`pandas.DataFrame`
DataFrame containing data
filename : string or file-like object
Path to ARFF file or file-like object. In the latter case,
the handle is closed by calling this function.
relation_name : string, optional, default: "pandas"
Name of relation in ARFF file.
index : boolean, optional, default: True
Write row names (index)
"""
if isinstance(filename, str):
fp = open(filename, 'w')
if relation_name is None:
relation_name = os.path.basename(filename)
else:
fp = filename
if relation_name is None:
relation_name = "pandas"
try:
data = _write_header(data, fp, relation_name, index)
fp.write("\n")
_write_data(data, fp)
finally:
fp.close() | [
"def",
"writearff",
"(",
"data",
",",
"filename",
",",
"relation_name",
"=",
"None",
",",
"index",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"fp",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"if",
"relation_name",
"is",
"None",
":",
"relation_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"else",
":",
"fp",
"=",
"filename",
"if",
"relation_name",
"is",
"None",
":",
"relation_name",
"=",
"\"pandas\"",
"try",
":",
"data",
"=",
"_write_header",
"(",
"data",
",",
"fp",
",",
"relation_name",
",",
"index",
")",
"fp",
".",
"write",
"(",
"\"\\n\"",
")",
"_write_data",
"(",
"data",
",",
"fp",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")"
] | Write ARFF file
Parameters
----------
data : :class:`pandas.DataFrame`
DataFrame containing data
filename : string or file-like object
Path to ARFF file or file-like object. In the latter case,
the handle is closed by calling this function.
relation_name : string, optional, default: "pandas"
Name of relation in ARFF file.
index : boolean, optional, default: True
Write row names (index) | [
"Write",
"ARFF",
"file"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L23-L57 |
232,773 | sebp/scikit-survival | sksurv/io/arffwrite.py | _write_header | def _write_header(data, fp, relation_name, index):
"""Write header containing attribute names and types"""
fp.write("@relation {0}\n\n".format(relation_name))
if index:
data = data.reset_index()
attribute_names = _sanitize_column_names(data)
for column, series in data.iteritems():
name = attribute_names[column]
fp.write("@attribute {0}\t".format(name))
if is_categorical_dtype(series) or is_object_dtype(series):
_write_attribute_categorical(series, fp)
elif numpy.issubdtype(series.dtype, numpy.floating):
fp.write("real")
elif numpy.issubdtype(series.dtype, numpy.integer):
fp.write("integer")
elif numpy.issubdtype(series.dtype, numpy.datetime64):
fp.write("date 'yyyy-MM-dd HH:mm:ss'")
else:
raise TypeError('unsupported type %s' % series.dtype)
fp.write("\n")
return data | python | def _write_header(data, fp, relation_name, index):
"""Write header containing attribute names and types"""
fp.write("@relation {0}\n\n".format(relation_name))
if index:
data = data.reset_index()
attribute_names = _sanitize_column_names(data)
for column, series in data.iteritems():
name = attribute_names[column]
fp.write("@attribute {0}\t".format(name))
if is_categorical_dtype(series) or is_object_dtype(series):
_write_attribute_categorical(series, fp)
elif numpy.issubdtype(series.dtype, numpy.floating):
fp.write("real")
elif numpy.issubdtype(series.dtype, numpy.integer):
fp.write("integer")
elif numpy.issubdtype(series.dtype, numpy.datetime64):
fp.write("date 'yyyy-MM-dd HH:mm:ss'")
else:
raise TypeError('unsupported type %s' % series.dtype)
fp.write("\n")
return data | [
"def",
"_write_header",
"(",
"data",
",",
"fp",
",",
"relation_name",
",",
"index",
")",
":",
"fp",
".",
"write",
"(",
"\"@relation {0}\\n\\n\"",
".",
"format",
"(",
"relation_name",
")",
")",
"if",
"index",
":",
"data",
"=",
"data",
".",
"reset_index",
"(",
")",
"attribute_names",
"=",
"_sanitize_column_names",
"(",
"data",
")",
"for",
"column",
",",
"series",
"in",
"data",
".",
"iteritems",
"(",
")",
":",
"name",
"=",
"attribute_names",
"[",
"column",
"]",
"fp",
".",
"write",
"(",
"\"@attribute {0}\\t\"",
".",
"format",
"(",
"name",
")",
")",
"if",
"is_categorical_dtype",
"(",
"series",
")",
"or",
"is_object_dtype",
"(",
"series",
")",
":",
"_write_attribute_categorical",
"(",
"series",
",",
"fp",
")",
"elif",
"numpy",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"numpy",
".",
"floating",
")",
":",
"fp",
".",
"write",
"(",
"\"real\"",
")",
"elif",
"numpy",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"numpy",
".",
"integer",
")",
":",
"fp",
".",
"write",
"(",
"\"integer\"",
")",
"elif",
"numpy",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"numpy",
".",
"datetime64",
")",
":",
"fp",
".",
"write",
"(",
"\"date 'yyyy-MM-dd HH:mm:ss'\"",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'unsupported type %s'",
"%",
"series",
".",
"dtype",
")",
"fp",
".",
"write",
"(",
"\"\\n\"",
")",
"return",
"data"
] | Write header containing attribute names and types | [
"Write",
"header",
"containing",
"attribute",
"names",
"and",
"types"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L60-L85 |
232,774 | sebp/scikit-survival | sksurv/io/arffwrite.py | _sanitize_column_names | def _sanitize_column_names(data):
"""Replace illegal characters with underscore"""
new_names = {}
for name in data.columns:
new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name)
return new_names | python | def _sanitize_column_names(data):
"""Replace illegal characters with underscore"""
new_names = {}
for name in data.columns:
new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name)
return new_names | [
"def",
"_sanitize_column_names",
"(",
"data",
")",
":",
"new_names",
"=",
"{",
"}",
"for",
"name",
"in",
"data",
".",
"columns",
":",
"new_names",
"[",
"name",
"]",
"=",
"_ILLEGAL_CHARACTER_PAT",
".",
"sub",
"(",
"\"_\"",
",",
"name",
")",
"return",
"new_names"
] | Replace illegal characters with underscore | [
"Replace",
"illegal",
"characters",
"with",
"underscore"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L88-L93 |
232,775 | sebp/scikit-survival | sksurv/io/arffwrite.py | _write_data | def _write_data(data, fp):
"""Write the data section"""
fp.write("@data\n")
def to_str(x):
if pandas.isnull(x):
return '?'
else:
return str(x)
data = data.applymap(to_str)
n_rows = data.shape[0]
for i in range(n_rows):
str_values = list(data.iloc[i, :].apply(_check_str_array))
line = ",".join(str_values)
fp.write(line)
fp.write("\n") | python | def _write_data(data, fp):
"""Write the data section"""
fp.write("@data\n")
def to_str(x):
if pandas.isnull(x):
return '?'
else:
return str(x)
data = data.applymap(to_str)
n_rows = data.shape[0]
for i in range(n_rows):
str_values = list(data.iloc[i, :].apply(_check_str_array))
line = ",".join(str_values)
fp.write(line)
fp.write("\n") | [
"def",
"_write_data",
"(",
"data",
",",
"fp",
")",
":",
"fp",
".",
"write",
"(",
"\"@data\\n\"",
")",
"def",
"to_str",
"(",
"x",
")",
":",
"if",
"pandas",
".",
"isnull",
"(",
"x",
")",
":",
"return",
"'?'",
"else",
":",
"return",
"str",
"(",
"x",
")",
"data",
"=",
"data",
".",
"applymap",
"(",
"to_str",
")",
"n_rows",
"=",
"data",
".",
"shape",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"n_rows",
")",
":",
"str_values",
"=",
"list",
"(",
"data",
".",
"iloc",
"[",
"i",
",",
":",
"]",
".",
"apply",
"(",
"_check_str_array",
")",
")",
"line",
"=",
"\",\"",
".",
"join",
"(",
"str_values",
")",
"fp",
".",
"write",
"(",
"line",
")",
"fp",
".",
"write",
"(",
"\"\\n\"",
")"
] | Write the data section | [
"Write",
"the",
"data",
"section"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L130-L146 |
232,776 | sebp/scikit-survival | sksurv/meta/stacking.py | Stacking.fit | def fit(self, X, y=None, **fit_params):
"""Fit base estimators.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self
"""
X = numpy.asarray(X)
self._fit_estimators(X, y, **fit_params)
Xt = self._predict_estimators(X)
self.meta_estimator.fit(Xt, y)
return self | python | def fit(self, X, y=None, **fit_params):
"""Fit base estimators.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self
"""
X = numpy.asarray(X)
self._fit_estimators(X, y, **fit_params)
Xt = self._predict_estimators(X)
self.meta_estimator.fit(Xt, y)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"fit_params",
")",
":",
"X",
"=",
"numpy",
".",
"asarray",
"(",
"X",
")",
"self",
".",
"_fit_estimators",
"(",
"X",
",",
"y",
",",
"*",
"*",
"fit_params",
")",
"Xt",
"=",
"self",
".",
"_predict_estimators",
"(",
"X",
")",
"self",
".",
"meta_estimator",
".",
"fit",
"(",
"Xt",
",",
"y",
")",
"return",
"self"
] | Fit base estimators.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self | [
"Fit",
"base",
"estimators",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/stacking.py#L115-L135 |
232,777 | sebp/scikit-survival | sksurv/column.py | standardize | def standardize(table, with_std=True):
"""
Perform Z-Normalization on each numeric column of the given table.
Parameters
----------
table : pandas.DataFrame or numpy.ndarray
Data to standardize.
with_std : bool, optional, default: True
If ``False`` data is only centered and not converted to unit variance.
Returns
-------
normalized : pandas.DataFrame
Table with numeric columns normalized.
Categorical columns in the input table remain unchanged.
"""
if isinstance(table, pandas.DataFrame):
cat_columns = table.select_dtypes(include=['category']).columns
else:
cat_columns = []
new_frame = _apply_along_column(table, standardize_column, with_std=with_std)
# work around for apply converting category dtype to object
# https://github.com/pydata/pandas/issues/9573
for col in cat_columns:
new_frame[col] = table[col].copy()
return new_frame | python | def standardize(table, with_std=True):
"""
Perform Z-Normalization on each numeric column of the given table.
Parameters
----------
table : pandas.DataFrame or numpy.ndarray
Data to standardize.
with_std : bool, optional, default: True
If ``False`` data is only centered and not converted to unit variance.
Returns
-------
normalized : pandas.DataFrame
Table with numeric columns normalized.
Categorical columns in the input table remain unchanged.
"""
if isinstance(table, pandas.DataFrame):
cat_columns = table.select_dtypes(include=['category']).columns
else:
cat_columns = []
new_frame = _apply_along_column(table, standardize_column, with_std=with_std)
# work around for apply converting category dtype to object
# https://github.com/pydata/pandas/issues/9573
for col in cat_columns:
new_frame[col] = table[col].copy()
return new_frame | [
"def",
"standardize",
"(",
"table",
",",
"with_std",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"table",
",",
"pandas",
".",
"DataFrame",
")",
":",
"cat_columns",
"=",
"table",
".",
"select_dtypes",
"(",
"include",
"=",
"[",
"'category'",
"]",
")",
".",
"columns",
"else",
":",
"cat_columns",
"=",
"[",
"]",
"new_frame",
"=",
"_apply_along_column",
"(",
"table",
",",
"standardize_column",
",",
"with_std",
"=",
"with_std",
")",
"# work around for apply converting category dtype to object",
"# https://github.com/pydata/pandas/issues/9573",
"for",
"col",
"in",
"cat_columns",
":",
"new_frame",
"[",
"col",
"]",
"=",
"table",
"[",
"col",
"]",
".",
"copy",
"(",
")",
"return",
"new_frame"
] | Perform Z-Normalization on each numeric column of the given table.
Parameters
----------
table : pandas.DataFrame or numpy.ndarray
Data to standardize.
with_std : bool, optional, default: True
If ``False`` data is only centered and not converted to unit variance.
Returns
-------
normalized : pandas.DataFrame
Table with numeric columns normalized.
Categorical columns in the input table remain unchanged. | [
"Perform",
"Z",
"-",
"Normalization",
"on",
"each",
"numeric",
"column",
"of",
"the",
"given",
"table",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L47-L77 |
232,778 | sebp/scikit-survival | sksurv/column.py | encode_categorical | def encode_categorical(table, columns=None, **kwargs):
"""
Encode categorical columns with `M` categories into `M-1` columns according
to the one-hot scheme.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
columns : list-like, optional, default: None
Column names in the DataFrame to be encoded.
If `columns` is None then all the columns with
`object` or `category` dtype will be converted.
allow_drop : boolean, optional, default: True
Whether to allow dropping categorical columns that only consist
of a single category.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
Numeric columns in the input table remain unchanged.
"""
if isinstance(table, pandas.Series):
if not is_categorical_dtype(table.dtype) and not table.dtype.char == "O":
raise TypeError("series must be of categorical dtype, but was {}".format(table.dtype))
return _encode_categorical_series(table, **kwargs)
def _is_categorical_or_object(series):
return is_categorical_dtype(series.dtype) or series.dtype.char == "O"
if columns is None:
# for columns containing categories
columns_to_encode = {nam for nam, s in table.iteritems() if _is_categorical_or_object(s)}
else:
columns_to_encode = set(columns)
items = []
for name, series in table.iteritems():
if name in columns_to_encode:
series = _encode_categorical_series(series, **kwargs)
if series is None:
continue
items.append(series)
# concat columns of tables
new_table = pandas.concat(items, axis=1, copy=False)
return new_table | python | def encode_categorical(table, columns=None, **kwargs):
"""
Encode categorical columns with `M` categories into `M-1` columns according
to the one-hot scheme.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
columns : list-like, optional, default: None
Column names in the DataFrame to be encoded.
If `columns` is None then all the columns with
`object` or `category` dtype will be converted.
allow_drop : boolean, optional, default: True
Whether to allow dropping categorical columns that only consist
of a single category.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
Numeric columns in the input table remain unchanged.
"""
if isinstance(table, pandas.Series):
if not is_categorical_dtype(table.dtype) and not table.dtype.char == "O":
raise TypeError("series must be of categorical dtype, but was {}".format(table.dtype))
return _encode_categorical_series(table, **kwargs)
def _is_categorical_or_object(series):
return is_categorical_dtype(series.dtype) or series.dtype.char == "O"
if columns is None:
# for columns containing categories
columns_to_encode = {nam for nam, s in table.iteritems() if _is_categorical_or_object(s)}
else:
columns_to_encode = set(columns)
items = []
for name, series in table.iteritems():
if name in columns_to_encode:
series = _encode_categorical_series(series, **kwargs)
if series is None:
continue
items.append(series)
# concat columns of tables
new_table = pandas.concat(items, axis=1, copy=False)
return new_table | [
"def",
"encode_categorical",
"(",
"table",
",",
"columns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"table",
",",
"pandas",
".",
"Series",
")",
":",
"if",
"not",
"is_categorical_dtype",
"(",
"table",
".",
"dtype",
")",
"and",
"not",
"table",
".",
"dtype",
".",
"char",
"==",
"\"O\"",
":",
"raise",
"TypeError",
"(",
"\"series must be of categorical dtype, but was {}\"",
".",
"format",
"(",
"table",
".",
"dtype",
")",
")",
"return",
"_encode_categorical_series",
"(",
"table",
",",
"*",
"*",
"kwargs",
")",
"def",
"_is_categorical_or_object",
"(",
"series",
")",
":",
"return",
"is_categorical_dtype",
"(",
"series",
".",
"dtype",
")",
"or",
"series",
".",
"dtype",
".",
"char",
"==",
"\"O\"",
"if",
"columns",
"is",
"None",
":",
"# for columns containing categories",
"columns_to_encode",
"=",
"{",
"nam",
"for",
"nam",
",",
"s",
"in",
"table",
".",
"iteritems",
"(",
")",
"if",
"_is_categorical_or_object",
"(",
"s",
")",
"}",
"else",
":",
"columns_to_encode",
"=",
"set",
"(",
"columns",
")",
"items",
"=",
"[",
"]",
"for",
"name",
",",
"series",
"in",
"table",
".",
"iteritems",
"(",
")",
":",
"if",
"name",
"in",
"columns_to_encode",
":",
"series",
"=",
"_encode_categorical_series",
"(",
"series",
",",
"*",
"*",
"kwargs",
")",
"if",
"series",
"is",
"None",
":",
"continue",
"items",
".",
"append",
"(",
"series",
")",
"# concat columns of tables",
"new_table",
"=",
"pandas",
".",
"concat",
"(",
"items",
",",
"axis",
"=",
"1",
",",
"copy",
"=",
"False",
")",
"return",
"new_table"
] | Encode categorical columns with `M` categories into `M-1` columns according
to the one-hot scheme.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
columns : list-like, optional, default: None
Column names in the DataFrame to be encoded.
If `columns` is None then all the columns with
`object` or `category` dtype will be converted.
allow_drop : boolean, optional, default: True
Whether to allow dropping categorical columns that only consist
of a single category.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
Numeric columns in the input table remain unchanged. | [
"Encode",
"categorical",
"columns",
"with",
"M",
"categories",
"into",
"M",
"-",
"1",
"columns",
"according",
"to",
"the",
"one",
"-",
"hot",
"scheme",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L97-L146 |
232,779 | sebp/scikit-survival | sksurv/column.py | categorical_to_numeric | def categorical_to_numeric(table):
"""Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
Numeric columns in the input table remain unchanged.
"""
def transform(column):
if is_categorical_dtype(column.dtype):
return column.cat.codes
if column.dtype.char == "O":
try:
nc = column.astype(numpy.int64)
except ValueError:
classes = column.dropna().unique()
classes.sort(kind="mergesort")
nc = column.replace(classes, numpy.arange(classes.shape[0]))
return nc
elif column.dtype == bool:
return column.astype(numpy.int64)
return column
if isinstance(table, pandas.Series):
return pandas.Series(transform(table), name=table.name, index=table.index)
else:
if _pandas_version_under0p23:
return table.apply(transform, axis=0, reduce=False)
else:
return table.apply(transform, axis=0, result_type='reduce') | python | def categorical_to_numeric(table):
"""Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
Numeric columns in the input table remain unchanged.
"""
def transform(column):
if is_categorical_dtype(column.dtype):
return column.cat.codes
if column.dtype.char == "O":
try:
nc = column.astype(numpy.int64)
except ValueError:
classes = column.dropna().unique()
classes.sort(kind="mergesort")
nc = column.replace(classes, numpy.arange(classes.shape[0]))
return nc
elif column.dtype == bool:
return column.astype(numpy.int64)
return column
if isinstance(table, pandas.Series):
return pandas.Series(transform(table), name=table.name, index=table.index)
else:
if _pandas_version_under0p23:
return table.apply(transform, axis=0, reduce=False)
else:
return table.apply(transform, axis=0, result_type='reduce') | [
"def",
"categorical_to_numeric",
"(",
"table",
")",
":",
"def",
"transform",
"(",
"column",
")",
":",
"if",
"is_categorical_dtype",
"(",
"column",
".",
"dtype",
")",
":",
"return",
"column",
".",
"cat",
".",
"codes",
"if",
"column",
".",
"dtype",
".",
"char",
"==",
"\"O\"",
":",
"try",
":",
"nc",
"=",
"column",
".",
"astype",
"(",
"numpy",
".",
"int64",
")",
"except",
"ValueError",
":",
"classes",
"=",
"column",
".",
"dropna",
"(",
")",
".",
"unique",
"(",
")",
"classes",
".",
"sort",
"(",
"kind",
"=",
"\"mergesort\"",
")",
"nc",
"=",
"column",
".",
"replace",
"(",
"classes",
",",
"numpy",
".",
"arange",
"(",
"classes",
".",
"shape",
"[",
"0",
"]",
")",
")",
"return",
"nc",
"elif",
"column",
".",
"dtype",
"==",
"bool",
":",
"return",
"column",
".",
"astype",
"(",
"numpy",
".",
"int64",
")",
"return",
"column",
"if",
"isinstance",
"(",
"table",
",",
"pandas",
".",
"Series",
")",
":",
"return",
"pandas",
".",
"Series",
"(",
"transform",
"(",
"table",
")",
",",
"name",
"=",
"table",
".",
"name",
",",
"index",
"=",
"table",
".",
"index",
")",
"else",
":",
"if",
"_pandas_version_under0p23",
":",
"return",
"table",
".",
"apply",
"(",
"transform",
",",
"axis",
"=",
"0",
",",
"reduce",
"=",
"False",
")",
"else",
":",
"return",
"table",
".",
"apply",
"(",
"transform",
",",
"axis",
"=",
"0",
",",
"result_type",
"=",
"'reduce'",
")"
] | Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
Numeric columns in the input table remain unchanged. | [
"Encode",
"categorical",
"columns",
"to",
"numeric",
"by",
"converting",
"each",
"category",
"to",
"an",
"integer",
"value",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L171-L208 |
232,780 | sebp/scikit-survival | sksurv/util.py | check_y_survival | def check_y_survival(y_or_event, *args, allow_all_censored=False):
"""Check that array correctly represents an outcome for survival analysis.
Parameters
----------
y_or_event : structured array with two fields, or boolean array
If a structured array, it must contain the binary event indicator
as first field, and time of event or time of censoring as
second field. Otherwise, it is assumed that a boolean array
representing the event indicator is passed.
*args : list of array-likes
Any number of array-like objects representing time information.
Elements that are `None` are passed along in the return value.
allow_all_censored : bool, optional, default: False
Whether to allow all events to be censored.
Returns
-------
event : array, shape=[n_samples,], dtype=bool
Binary event indicator.
time : array, shape=[n_samples,], dtype=float
Time of event or censoring.
"""
if len(args) == 0:
y = y_or_event
if not isinstance(y, numpy.ndarray) or y.dtype.fields is None or len(y.dtype.fields) != 2:
raise ValueError('y must be a structured array with the first field'
' being a binary class event indicator and the second field'
' the time of the event/censoring')
event_field, time_field = y.dtype.names
y_event = y[event_field]
time_args = (y[time_field],)
else:
y_event = numpy.asanyarray(y_or_event)
time_args = args
event = check_array(y_event, ensure_2d=False)
if not numpy.issubdtype(event.dtype, numpy.bool_):
raise ValueError('elements of event indicator must be boolean, but found {0}'.format(event.dtype))
if not (allow_all_censored or numpy.any(event)):
raise ValueError('all samples are censored')
return_val = [event]
for i, yt in enumerate(time_args):
if yt is None:
return_val.append(yt)
continue
yt = check_array(yt, ensure_2d=False)
if not numpy.issubdtype(yt.dtype, numpy.number):
raise ValueError('time must be numeric, but found {} for argument {}'.format(yt.dtype, i + 2))
return_val.append(yt)
return tuple(return_val) | python | def check_y_survival(y_or_event, *args, allow_all_censored=False):
"""Check that array correctly represents an outcome for survival analysis.
Parameters
----------
y_or_event : structured array with two fields, or boolean array
If a structured array, it must contain the binary event indicator
as first field, and time of event or time of censoring as
second field. Otherwise, it is assumed that a boolean array
representing the event indicator is passed.
*args : list of array-likes
Any number of array-like objects representing time information.
Elements that are `None` are passed along in the return value.
allow_all_censored : bool, optional, default: False
Whether to allow all events to be censored.
Returns
-------
event : array, shape=[n_samples,], dtype=bool
Binary event indicator.
time : array, shape=[n_samples,], dtype=float
Time of event or censoring.
"""
if len(args) == 0:
y = y_or_event
if not isinstance(y, numpy.ndarray) or y.dtype.fields is None or len(y.dtype.fields) != 2:
raise ValueError('y must be a structured array with the first field'
' being a binary class event indicator and the second field'
' the time of the event/censoring')
event_field, time_field = y.dtype.names
y_event = y[event_field]
time_args = (y[time_field],)
else:
y_event = numpy.asanyarray(y_or_event)
time_args = args
event = check_array(y_event, ensure_2d=False)
if not numpy.issubdtype(event.dtype, numpy.bool_):
raise ValueError('elements of event indicator must be boolean, but found {0}'.format(event.dtype))
if not (allow_all_censored or numpy.any(event)):
raise ValueError('all samples are censored')
return_val = [event]
for i, yt in enumerate(time_args):
if yt is None:
return_val.append(yt)
continue
yt = check_array(yt, ensure_2d=False)
if not numpy.issubdtype(yt.dtype, numpy.number):
raise ValueError('time must be numeric, but found {} for argument {}'.format(yt.dtype, i + 2))
return_val.append(yt)
return tuple(return_val) | [
"def",
"check_y_survival",
"(",
"y_or_event",
",",
"*",
"args",
",",
"allow_all_censored",
"=",
"False",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"y",
"=",
"y_or_event",
"if",
"not",
"isinstance",
"(",
"y",
",",
"numpy",
".",
"ndarray",
")",
"or",
"y",
".",
"dtype",
".",
"fields",
"is",
"None",
"or",
"len",
"(",
"y",
".",
"dtype",
".",
"fields",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'y must be a structured array with the first field'",
"' being a binary class event indicator and the second field'",
"' the time of the event/censoring'",
")",
"event_field",
",",
"time_field",
"=",
"y",
".",
"dtype",
".",
"names",
"y_event",
"=",
"y",
"[",
"event_field",
"]",
"time_args",
"=",
"(",
"y",
"[",
"time_field",
"]",
",",
")",
"else",
":",
"y_event",
"=",
"numpy",
".",
"asanyarray",
"(",
"y_or_event",
")",
"time_args",
"=",
"args",
"event",
"=",
"check_array",
"(",
"y_event",
",",
"ensure_2d",
"=",
"False",
")",
"if",
"not",
"numpy",
".",
"issubdtype",
"(",
"event",
".",
"dtype",
",",
"numpy",
".",
"bool_",
")",
":",
"raise",
"ValueError",
"(",
"'elements of event indicator must be boolean, but found {0}'",
".",
"format",
"(",
"event",
".",
"dtype",
")",
")",
"if",
"not",
"(",
"allow_all_censored",
"or",
"numpy",
".",
"any",
"(",
"event",
")",
")",
":",
"raise",
"ValueError",
"(",
"'all samples are censored'",
")",
"return_val",
"=",
"[",
"event",
"]",
"for",
"i",
",",
"yt",
"in",
"enumerate",
"(",
"time_args",
")",
":",
"if",
"yt",
"is",
"None",
":",
"return_val",
".",
"append",
"(",
"yt",
")",
"continue",
"yt",
"=",
"check_array",
"(",
"yt",
",",
"ensure_2d",
"=",
"False",
")",
"if",
"not",
"numpy",
".",
"issubdtype",
"(",
"yt",
".",
"dtype",
",",
"numpy",
".",
"number",
")",
":",
"raise",
"ValueError",
"(",
"'time must be numeric, but found {} for argument {}'",
".",
"format",
"(",
"yt",
".",
"dtype",
",",
"i",
"+",
"2",
")",
")",
"return_val",
".",
"append",
"(",
"yt",
")",
"return",
"tuple",
"(",
"return_val",
")"
] | Check that array correctly represents an outcome for survival analysis.
Parameters
----------
y_or_event : structured array with two fields, or boolean array
If a structured array, it must contain the binary event indicator
as first field, and time of event or time of censoring as
second field. Otherwise, it is assumed that a boolean array
representing the event indicator is passed.
*args : list of array-likes
Any number of array-like objects representing time information.
Elements that are `None` are passed along in the return value.
allow_all_censored : bool, optional, default: False
Whether to allow all events to be censored.
Returns
-------
event : array, shape=[n_samples,], dtype=bool
Binary event indicator.
time : array, shape=[n_samples,], dtype=float
Time of event or censoring. | [
"Check",
"that",
"array",
"correctly",
"represents",
"an",
"outcome",
"for",
"survival",
"analysis",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L104-L164 |
232,781 | sebp/scikit-survival | sksurv/util.py | check_arrays_survival | def check_arrays_survival(X, y, **kwargs):
"""Check that all arrays have consistent first dimensions.
Parameters
----------
X : array-like
Data matrix containing feature vectors.
y : structured array with two fields
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
kwargs : dict
Additional arguments passed to :func:`sklearn.utils.check_array`.
Returns
-------
X : array, shape=[n_samples, n_features]
Feature vectors.
event : array, shape=[n_samples,], dtype=bool
Binary event indicator.
time : array, shape=[n_samples,], dtype=float
Time of event or censoring.
"""
event, time = check_y_survival(y)
kwargs.setdefault("dtype", numpy.float64)
X = check_array(X, ensure_min_samples=2, **kwargs)
check_consistent_length(X, event, time)
return X, event, time | python | def check_arrays_survival(X, y, **kwargs):
"""Check that all arrays have consistent first dimensions.
Parameters
----------
X : array-like
Data matrix containing feature vectors.
y : structured array with two fields
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
kwargs : dict
Additional arguments passed to :func:`sklearn.utils.check_array`.
Returns
-------
X : array, shape=[n_samples, n_features]
Feature vectors.
event : array, shape=[n_samples,], dtype=bool
Binary event indicator.
time : array, shape=[n_samples,], dtype=float
Time of event or censoring.
"""
event, time = check_y_survival(y)
kwargs.setdefault("dtype", numpy.float64)
X = check_array(X, ensure_min_samples=2, **kwargs)
check_consistent_length(X, event, time)
return X, event, time | [
"def",
"check_arrays_survival",
"(",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"event",
",",
"time",
"=",
"check_y_survival",
"(",
"y",
")",
"kwargs",
".",
"setdefault",
"(",
"\"dtype\"",
",",
"numpy",
".",
"float64",
")",
"X",
"=",
"check_array",
"(",
"X",
",",
"ensure_min_samples",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
"check_consistent_length",
"(",
"X",
",",
"event",
",",
"time",
")",
"return",
"X",
",",
"event",
",",
"time"
] | Check that all arrays have consistent first dimensions.
Parameters
----------
X : array-like
Data matrix containing feature vectors.
y : structured array with two fields
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
kwargs : dict
Additional arguments passed to :func:`sklearn.utils.check_array`.
Returns
-------
X : array, shape=[n_samples, n_features]
Feature vectors.
event : array, shape=[n_samples,], dtype=bool
Binary event indicator.
time : array, shape=[n_samples,], dtype=float
Time of event or censoring. | [
"Check",
"that",
"all",
"arrays",
"have",
"consistent",
"first",
"dimensions",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L167-L198 |
232,782 | sebp/scikit-survival | sksurv/util.py | Surv.from_arrays | def from_arrays(event, time, name_event=None, name_time=None):
"""Create structured array.
Parameters
----------
event : array-like
Event indicator. A boolean array or array with values 0/1.
time : array-like
Observed time.
name_event : str|None
Name of event, optional, default: 'event'
name_time : str|None
Name of observed time, optional, default: 'time'
Returns
-------
y : np.array
Structured array with two fields.
"""
name_event = name_event or 'event'
name_time = name_time or 'time'
if name_time == name_event:
raise ValueError('name_time must be different from name_event')
time = numpy.asanyarray(time, dtype=numpy.float_)
y = numpy.empty(time.shape[0],
dtype=[(name_event, numpy.bool_), (name_time, numpy.float_)])
y[name_time] = time
event = numpy.asanyarray(event)
check_consistent_length(time, event)
if numpy.issubdtype(event.dtype, numpy.bool_):
y[name_event] = event
else:
events = numpy.unique(event)
events.sort()
if len(events) != 2:
raise ValueError('event indicator must be binary')
if numpy.all(events == numpy.array([0, 1], dtype=events.dtype)):
y[name_event] = event.astype(numpy.bool_)
else:
raise ValueError('non-boolean event indicator must contain 0 and 1 only')
return y | python | def from_arrays(event, time, name_event=None, name_time=None):
"""Create structured array.
Parameters
----------
event : array-like
Event indicator. A boolean array or array with values 0/1.
time : array-like
Observed time.
name_event : str|None
Name of event, optional, default: 'event'
name_time : str|None
Name of observed time, optional, default: 'time'
Returns
-------
y : np.array
Structured array with two fields.
"""
name_event = name_event or 'event'
name_time = name_time or 'time'
if name_time == name_event:
raise ValueError('name_time must be different from name_event')
time = numpy.asanyarray(time, dtype=numpy.float_)
y = numpy.empty(time.shape[0],
dtype=[(name_event, numpy.bool_), (name_time, numpy.float_)])
y[name_time] = time
event = numpy.asanyarray(event)
check_consistent_length(time, event)
if numpy.issubdtype(event.dtype, numpy.bool_):
y[name_event] = event
else:
events = numpy.unique(event)
events.sort()
if len(events) != 2:
raise ValueError('event indicator must be binary')
if numpy.all(events == numpy.array([0, 1], dtype=events.dtype)):
y[name_event] = event.astype(numpy.bool_)
else:
raise ValueError('non-boolean event indicator must contain 0 and 1 only')
return y | [
"def",
"from_arrays",
"(",
"event",
",",
"time",
",",
"name_event",
"=",
"None",
",",
"name_time",
"=",
"None",
")",
":",
"name_event",
"=",
"name_event",
"or",
"'event'",
"name_time",
"=",
"name_time",
"or",
"'time'",
"if",
"name_time",
"==",
"name_event",
":",
"raise",
"ValueError",
"(",
"'name_time must be different from name_event'",
")",
"time",
"=",
"numpy",
".",
"asanyarray",
"(",
"time",
",",
"dtype",
"=",
"numpy",
".",
"float_",
")",
"y",
"=",
"numpy",
".",
"empty",
"(",
"time",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"[",
"(",
"name_event",
",",
"numpy",
".",
"bool_",
")",
",",
"(",
"name_time",
",",
"numpy",
".",
"float_",
")",
"]",
")",
"y",
"[",
"name_time",
"]",
"=",
"time",
"event",
"=",
"numpy",
".",
"asanyarray",
"(",
"event",
")",
"check_consistent_length",
"(",
"time",
",",
"event",
")",
"if",
"numpy",
".",
"issubdtype",
"(",
"event",
".",
"dtype",
",",
"numpy",
".",
"bool_",
")",
":",
"y",
"[",
"name_event",
"]",
"=",
"event",
"else",
":",
"events",
"=",
"numpy",
".",
"unique",
"(",
"event",
")",
"events",
".",
"sort",
"(",
")",
"if",
"len",
"(",
"events",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'event indicator must be binary'",
")",
"if",
"numpy",
".",
"all",
"(",
"events",
"==",
"numpy",
".",
"array",
"(",
"[",
"0",
",",
"1",
"]",
",",
"dtype",
"=",
"events",
".",
"dtype",
")",
")",
":",
"y",
"[",
"name_event",
"]",
"=",
"event",
".",
"astype",
"(",
"numpy",
".",
"bool_",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'non-boolean event indicator must contain 0 and 1 only'",
")",
"return",
"y"
] | Create structured array.
Parameters
----------
event : array-like
Event indicator. A boolean array or array with values 0/1.
time : array-like
Observed time.
name_event : str|None
Name of event, optional, default: 'event'
name_time : str|None
Name of observed time, optional, default: 'time'
Returns
-------
y : np.array
Structured array with two fields. | [
"Create",
"structured",
"array",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L28-L73 |
232,783 | sebp/scikit-survival | sksurv/util.py | Surv.from_dataframe | def from_dataframe(event, time, data):
"""Create structured array from data frame.
Parameters
----------
event : object
Identifier of column containing event indicator.
time : object
Identifier of column containing time.
data : pandas.DataFrame
Dataset.
Returns
-------
y : np.array
Structured array with two fields.
"""
if not isinstance(data, pandas.DataFrame):
raise TypeError(
"exepected pandas.DataFrame, but got {!r}".format(type(data)))
return Surv.from_arrays(
data.loc[:, event].values,
data.loc[:, time].values,
name_event=str(event),
name_time=str(time)) | python | def from_dataframe(event, time, data):
"""Create structured array from data frame.
Parameters
----------
event : object
Identifier of column containing event indicator.
time : object
Identifier of column containing time.
data : pandas.DataFrame
Dataset.
Returns
-------
y : np.array
Structured array with two fields.
"""
if not isinstance(data, pandas.DataFrame):
raise TypeError(
"exepected pandas.DataFrame, but got {!r}".format(type(data)))
return Surv.from_arrays(
data.loc[:, event].values,
data.loc[:, time].values,
name_event=str(event),
name_time=str(time)) | [
"def",
"from_dataframe",
"(",
"event",
",",
"time",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"pandas",
".",
"DataFrame",
")",
":",
"raise",
"TypeError",
"(",
"\"exepected pandas.DataFrame, but got {!r}\"",
".",
"format",
"(",
"type",
"(",
"data",
")",
")",
")",
"return",
"Surv",
".",
"from_arrays",
"(",
"data",
".",
"loc",
"[",
":",
",",
"event",
"]",
".",
"values",
",",
"data",
".",
"loc",
"[",
":",
",",
"time",
"]",
".",
"values",
",",
"name_event",
"=",
"str",
"(",
"event",
")",
",",
"name_time",
"=",
"str",
"(",
"time",
")",
")"
] | Create structured array from data frame.
Parameters
----------
event : object
Identifier of column containing event indicator.
time : object
Identifier of column containing time.
data : pandas.DataFrame
Dataset.
Returns
-------
y : np.array
Structured array with two fields. | [
"Create",
"structured",
"array",
"from",
"data",
"frame",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L76-L101 |
232,784 | sebp/scikit-survival | sksurv/ensemble/survival_loss.py | CoxPH.update_terminal_regions | def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
learning_rate=1.0, k=0):
"""Least squares does not need to update terminal regions.
But it has to update the predictions.
"""
# update predictions
y_pred[:, k] += learning_rate * tree.predict(X).ravel() | python | def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
learning_rate=1.0, k=0):
"""Least squares does not need to update terminal regions.
But it has to update the predictions.
"""
# update predictions
y_pred[:, k] += learning_rate * tree.predict(X).ravel() | [
"def",
"update_terminal_regions",
"(",
"self",
",",
"tree",
",",
"X",
",",
"y",
",",
"residual",
",",
"y_pred",
",",
"sample_weight",
",",
"sample_mask",
",",
"learning_rate",
"=",
"1.0",
",",
"k",
"=",
"0",
")",
":",
"# update predictions",
"y_pred",
"[",
":",
",",
"k",
"]",
"+=",
"learning_rate",
"*",
"tree",
".",
"predict",
"(",
"X",
")",
".",
"ravel",
"(",
")"
] | Least squares does not need to update terminal regions.
But it has to update the predictions. | [
"Least",
"squares",
"does",
"not",
"need",
"to",
"update",
"terminal",
"regions",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/survival_loss.py#L55-L63 |
232,785 | sebp/scikit-survival | sksurv/setup.py | build_from_c_and_cpp_files | def build_from_c_and_cpp_files(extensions):
"""Modify the extensions to build from the .c and .cpp files.
This is useful for releases, this way cython is not required to
run python setup.py install.
"""
for extension in extensions:
sources = []
for sfile in extension.sources:
path, ext = os.path.splitext(sfile)
if ext in ('.pyx', '.py'):
if extension.language == 'c++':
ext = '.cpp'
else:
ext = '.c'
sfile = path + ext
sources.append(sfile)
extension.sources = sources | python | def build_from_c_and_cpp_files(extensions):
"""Modify the extensions to build from the .c and .cpp files.
This is useful for releases, this way cython is not required to
run python setup.py install.
"""
for extension in extensions:
sources = []
for sfile in extension.sources:
path, ext = os.path.splitext(sfile)
if ext in ('.pyx', '.py'):
if extension.language == 'c++':
ext = '.cpp'
else:
ext = '.c'
sfile = path + ext
sources.append(sfile)
extension.sources = sources | [
"def",
"build_from_c_and_cpp_files",
"(",
"extensions",
")",
":",
"for",
"extension",
"in",
"extensions",
":",
"sources",
"=",
"[",
"]",
"for",
"sfile",
"in",
"extension",
".",
"sources",
":",
"path",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"sfile",
")",
"if",
"ext",
"in",
"(",
"'.pyx'",
",",
"'.py'",
")",
":",
"if",
"extension",
".",
"language",
"==",
"'c++'",
":",
"ext",
"=",
"'.cpp'",
"else",
":",
"ext",
"=",
"'.c'",
"sfile",
"=",
"path",
"+",
"ext",
"sources",
".",
"append",
"(",
"sfile",
")",
"extension",
".",
"sources",
"=",
"sources"
] | Modify the extensions to build from the .c and .cpp files.
This is useful for releases, this way cython is not required to
run python setup.py install. | [
"Modify",
"the",
"extensions",
"to",
"build",
"from",
"the",
".",
"c",
"and",
".",
"cpp",
"files",
".",
"This",
"is",
"useful",
"for",
"releases",
"this",
"way",
"cython",
"is",
"not",
"required",
"to",
"run",
"python",
"setup",
".",
"py",
"install",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/setup.py#L20-L36 |
232,786 | sebp/scikit-survival | sksurv/svm/survival_svm.py | SurvivalCounter._count_values | def _count_values(self):
"""Return dict mapping relevance level to sample index"""
indices = {yi: [i] for i, yi in enumerate(self.y) if self.status[i]}
return indices | python | def _count_values(self):
"""Return dict mapping relevance level to sample index"""
indices = {yi: [i] for i, yi in enumerate(self.y) if self.status[i]}
return indices | [
"def",
"_count_values",
"(",
"self",
")",
":",
"indices",
"=",
"{",
"yi",
":",
"[",
"i",
"]",
"for",
"i",
",",
"yi",
"in",
"enumerate",
"(",
"self",
".",
"y",
")",
"if",
"self",
".",
"status",
"[",
"i",
"]",
"}",
"return",
"indices"
] | Return dict mapping relevance level to sample index | [
"Return",
"dict",
"mapping",
"relevance",
"level",
"to",
"sample",
"index"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/survival_svm.py#L134-L138 |
232,787 | sebp/scikit-survival | sksurv/svm/survival_svm.py | BaseSurvivalSVM._create_optimizer | def _create_optimizer(self, X, y, status):
"""Samples are ordered by relevance"""
if self.optimizer is None:
self.optimizer = 'avltree'
times, ranks = y
if self.optimizer == 'simple':
optimizer = SimpleOptimizer(X, status, self.alpha, self.rank_ratio, timeit=self.timeit)
elif self.optimizer == 'PRSVM':
optimizer = PRSVMOptimizer(X, status, self.alpha, self.rank_ratio, timeit=self.timeit)
elif self.optimizer == 'direct-count':
optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept,
SurvivalCounter(X, ranks, status, len(ranks), times), timeit=self.timeit)
elif self.optimizer == 'rbtree':
optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept,
OrderStatisticTreeSurvivalCounter(X, ranks, status, RBTree, times),
timeit=self.timeit)
elif self.optimizer == 'avltree':
optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept,
OrderStatisticTreeSurvivalCounter(X, ranks, status, AVLTree, times),
timeit=self.timeit)
else:
raise ValueError('unknown optimizer: {0}'.format(self.optimizer))
return optimizer | python | def _create_optimizer(self, X, y, status):
"""Samples are ordered by relevance"""
if self.optimizer is None:
self.optimizer = 'avltree'
times, ranks = y
if self.optimizer == 'simple':
optimizer = SimpleOptimizer(X, status, self.alpha, self.rank_ratio, timeit=self.timeit)
elif self.optimizer == 'PRSVM':
optimizer = PRSVMOptimizer(X, status, self.alpha, self.rank_ratio, timeit=self.timeit)
elif self.optimizer == 'direct-count':
optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept,
SurvivalCounter(X, ranks, status, len(ranks), times), timeit=self.timeit)
elif self.optimizer == 'rbtree':
optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept,
OrderStatisticTreeSurvivalCounter(X, ranks, status, RBTree, times),
timeit=self.timeit)
elif self.optimizer == 'avltree':
optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept,
OrderStatisticTreeSurvivalCounter(X, ranks, status, AVLTree, times),
timeit=self.timeit)
else:
raise ValueError('unknown optimizer: {0}'.format(self.optimizer))
return optimizer | [
"def",
"_create_optimizer",
"(",
"self",
",",
"X",
",",
"y",
",",
"status",
")",
":",
"if",
"self",
".",
"optimizer",
"is",
"None",
":",
"self",
".",
"optimizer",
"=",
"'avltree'",
"times",
",",
"ranks",
"=",
"y",
"if",
"self",
".",
"optimizer",
"==",
"'simple'",
":",
"optimizer",
"=",
"SimpleOptimizer",
"(",
"X",
",",
"status",
",",
"self",
".",
"alpha",
",",
"self",
".",
"rank_ratio",
",",
"timeit",
"=",
"self",
".",
"timeit",
")",
"elif",
"self",
".",
"optimizer",
"==",
"'PRSVM'",
":",
"optimizer",
"=",
"PRSVMOptimizer",
"(",
"X",
",",
"status",
",",
"self",
".",
"alpha",
",",
"self",
".",
"rank_ratio",
",",
"timeit",
"=",
"self",
".",
"timeit",
")",
"elif",
"self",
".",
"optimizer",
"==",
"'direct-count'",
":",
"optimizer",
"=",
"LargeScaleOptimizer",
"(",
"self",
".",
"alpha",
",",
"self",
".",
"rank_ratio",
",",
"self",
".",
"fit_intercept",
",",
"SurvivalCounter",
"(",
"X",
",",
"ranks",
",",
"status",
",",
"len",
"(",
"ranks",
")",
",",
"times",
")",
",",
"timeit",
"=",
"self",
".",
"timeit",
")",
"elif",
"self",
".",
"optimizer",
"==",
"'rbtree'",
":",
"optimizer",
"=",
"LargeScaleOptimizer",
"(",
"self",
".",
"alpha",
",",
"self",
".",
"rank_ratio",
",",
"self",
".",
"fit_intercept",
",",
"OrderStatisticTreeSurvivalCounter",
"(",
"X",
",",
"ranks",
",",
"status",
",",
"RBTree",
",",
"times",
")",
",",
"timeit",
"=",
"self",
".",
"timeit",
")",
"elif",
"self",
".",
"optimizer",
"==",
"'avltree'",
":",
"optimizer",
"=",
"LargeScaleOptimizer",
"(",
"self",
".",
"alpha",
",",
"self",
".",
"rank_ratio",
",",
"self",
".",
"fit_intercept",
",",
"OrderStatisticTreeSurvivalCounter",
"(",
"X",
",",
"ranks",
",",
"status",
",",
"AVLTree",
",",
"times",
")",
",",
"timeit",
"=",
"self",
".",
"timeit",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'unknown optimizer: {0}'",
".",
"format",
"(",
"self",
".",
"optimizer",
")",
")",
"return",
"optimizer"
] | Samples are ordered by relevance | [
"Samples",
"are",
"ordered",
"by",
"relevance"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/survival_svm.py#L608-L633 |
232,788 | sebp/scikit-survival | sksurv/svm/survival_svm.py | BaseSurvivalSVM._argsort_and_resolve_ties | def _argsort_and_resolve_ties(time, random_state):
"""Like numpy.argsort, but resolves ties uniformly at random"""
n_samples = len(time)
order = numpy.argsort(time, kind="mergesort")
i = 0
while i < n_samples - 1:
inext = i + 1
while inext < n_samples and time[order[i]] == time[order[inext]]:
inext += 1
if i + 1 != inext:
# resolve ties randomly
random_state.shuffle(order[i:inext])
i = inext
return order | python | def _argsort_and_resolve_ties(time, random_state):
"""Like numpy.argsort, but resolves ties uniformly at random"""
n_samples = len(time)
order = numpy.argsort(time, kind="mergesort")
i = 0
while i < n_samples - 1:
inext = i + 1
while inext < n_samples and time[order[i]] == time[order[inext]]:
inext += 1
if i + 1 != inext:
# resolve ties randomly
random_state.shuffle(order[i:inext])
i = inext
return order | [
"def",
"_argsort_and_resolve_ties",
"(",
"time",
",",
"random_state",
")",
":",
"n_samples",
"=",
"len",
"(",
"time",
")",
"order",
"=",
"numpy",
".",
"argsort",
"(",
"time",
",",
"kind",
"=",
"\"mergesort\"",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"n_samples",
"-",
"1",
":",
"inext",
"=",
"i",
"+",
"1",
"while",
"inext",
"<",
"n_samples",
"and",
"time",
"[",
"order",
"[",
"i",
"]",
"]",
"==",
"time",
"[",
"order",
"[",
"inext",
"]",
"]",
":",
"inext",
"+=",
"1",
"if",
"i",
"+",
"1",
"!=",
"inext",
":",
"# resolve ties randomly",
"random_state",
".",
"shuffle",
"(",
"order",
"[",
"i",
":",
"inext",
"]",
")",
"i",
"=",
"inext",
"return",
"order"
] | Like numpy.argsort, but resolves ties uniformly at random | [
"Like",
"numpy",
".",
"argsort",
"but",
"resolves",
"ties",
"uniformly",
"at",
"random"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/survival_svm.py#L702-L717 |
232,789 | sebp/scikit-survival | sksurv/linear_model/aft.py | IPCRidge.fit | def fit(self, X, y):
"""Build an accelerated failure time model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Returns
-------
self
"""
X, event, time = check_arrays_survival(X, y)
weights = ipc_weights(event, time)
super().fit(X, numpy.log(time), sample_weight=weights)
return self | python | def fit(self, X, y):
"""Build an accelerated failure time model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Returns
-------
self
"""
X, event, time = check_arrays_survival(X, y)
weights = ipc_weights(event, time)
super().fit(X, numpy.log(time), sample_weight=weights)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"X",
",",
"event",
",",
"time",
"=",
"check_arrays_survival",
"(",
"X",
",",
"y",
")",
"weights",
"=",
"ipc_weights",
"(",
"event",
",",
"time",
")",
"super",
"(",
")",
".",
"fit",
"(",
"X",
",",
"numpy",
".",
"log",
"(",
"time",
")",
",",
"sample_weight",
"=",
"weights",
")",
"return",
"self"
] | Build an accelerated failure time model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Returns
-------
self | [
"Build",
"an",
"accelerated",
"failure",
"time",
"model",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/aft.py#L52-L74 |
232,790 | sebp/scikit-survival | sksurv/linear_model/coxph.py | BreslowEstimator.fit | def fit(self, linear_predictor, event, time):
"""Compute baseline cumulative hazard function.
Parameters
----------
linear_predictor : array-like, shape = (n_samples,)
Linear predictor of risk: `X @ coef`.
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time : array-like, shape = (n_samples,)
Contains event/censoring times.
Returns
-------
self
"""
risk_score = numpy.exp(linear_predictor)
order = numpy.argsort(time, kind="mergesort")
risk_score = risk_score[order]
uniq_times, n_events, n_at_risk = _compute_counts(event, time, order)
divisor = numpy.empty(n_at_risk.shape, dtype=numpy.float_)
value = numpy.sum(risk_score)
divisor[0] = value
k = 0
for i in range(1, len(n_at_risk)):
d = n_at_risk[i - 1] - n_at_risk[i]
value -= risk_score[k:(k + d)].sum()
k += d
divisor[i] = value
assert k == n_at_risk[0] - n_at_risk[-1]
y = numpy.cumsum(n_events / divisor)
self.cum_baseline_hazard_ = StepFunction(uniq_times, y)
self.baseline_survival_ = StepFunction(self.cum_baseline_hazard_.x,
numpy.exp(- self.cum_baseline_hazard_.y))
return self | python | def fit(self, linear_predictor, event, time):
"""Compute baseline cumulative hazard function.
Parameters
----------
linear_predictor : array-like, shape = (n_samples,)
Linear predictor of risk: `X @ coef`.
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time : array-like, shape = (n_samples,)
Contains event/censoring times.
Returns
-------
self
"""
risk_score = numpy.exp(linear_predictor)
order = numpy.argsort(time, kind="mergesort")
risk_score = risk_score[order]
uniq_times, n_events, n_at_risk = _compute_counts(event, time, order)
divisor = numpy.empty(n_at_risk.shape, dtype=numpy.float_)
value = numpy.sum(risk_score)
divisor[0] = value
k = 0
for i in range(1, len(n_at_risk)):
d = n_at_risk[i - 1] - n_at_risk[i]
value -= risk_score[k:(k + d)].sum()
k += d
divisor[i] = value
assert k == n_at_risk[0] - n_at_risk[-1]
y = numpy.cumsum(n_events / divisor)
self.cum_baseline_hazard_ = StepFunction(uniq_times, y)
self.baseline_survival_ = StepFunction(self.cum_baseline_hazard_.x,
numpy.exp(- self.cum_baseline_hazard_.y))
return self | [
"def",
"fit",
"(",
"self",
",",
"linear_predictor",
",",
"event",
",",
"time",
")",
":",
"risk_score",
"=",
"numpy",
".",
"exp",
"(",
"linear_predictor",
")",
"order",
"=",
"numpy",
".",
"argsort",
"(",
"time",
",",
"kind",
"=",
"\"mergesort\"",
")",
"risk_score",
"=",
"risk_score",
"[",
"order",
"]",
"uniq_times",
",",
"n_events",
",",
"n_at_risk",
"=",
"_compute_counts",
"(",
"event",
",",
"time",
",",
"order",
")",
"divisor",
"=",
"numpy",
".",
"empty",
"(",
"n_at_risk",
".",
"shape",
",",
"dtype",
"=",
"numpy",
".",
"float_",
")",
"value",
"=",
"numpy",
".",
"sum",
"(",
"risk_score",
")",
"divisor",
"[",
"0",
"]",
"=",
"value",
"k",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"n_at_risk",
")",
")",
":",
"d",
"=",
"n_at_risk",
"[",
"i",
"-",
"1",
"]",
"-",
"n_at_risk",
"[",
"i",
"]",
"value",
"-=",
"risk_score",
"[",
"k",
":",
"(",
"k",
"+",
"d",
")",
"]",
".",
"sum",
"(",
")",
"k",
"+=",
"d",
"divisor",
"[",
"i",
"]",
"=",
"value",
"assert",
"k",
"==",
"n_at_risk",
"[",
"0",
"]",
"-",
"n_at_risk",
"[",
"-",
"1",
"]",
"y",
"=",
"numpy",
".",
"cumsum",
"(",
"n_events",
"/",
"divisor",
")",
"self",
".",
"cum_baseline_hazard_",
"=",
"StepFunction",
"(",
"uniq_times",
",",
"y",
")",
"self",
".",
"baseline_survival_",
"=",
"StepFunction",
"(",
"self",
".",
"cum_baseline_hazard_",
".",
"x",
",",
"numpy",
".",
"exp",
"(",
"-",
"self",
".",
"cum_baseline_hazard_",
".",
"y",
")",
")",
"return",
"self"
] | Compute baseline cumulative hazard function.
Parameters
----------
linear_predictor : array-like, shape = (n_samples,)
Linear predictor of risk: `X @ coef`.
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time : array-like, shape = (n_samples,)
Contains event/censoring times.
Returns
-------
self | [
"Compute",
"baseline",
"cumulative",
"hazard",
"function",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L42-L81 |
232,791 | sebp/scikit-survival | sksurv/linear_model/coxph.py | CoxPHOptimizer.nlog_likelihood | def nlog_likelihood(self, w):
"""Compute negative partial log-likelihood
Parameters
----------
w : array, shape = (n_features,)
Estimate of coefficients
Returns
-------
loss : float
Average negative partial log-likelihood
"""
time = self.time
n_samples = self.x.shape[0]
xw = numpy.dot(self.x, w)
loss = 0
risk_set = 0
k = 0
for i in range(n_samples):
ti = time[i]
while k < n_samples and ti == time[k]:
risk_set += numpy.exp(xw[k])
k += 1
if self.event[i]:
loss -= (xw[i] - numpy.log(risk_set)) / n_samples
# add regularization term to log-likelihood
return loss + self.alpha * squared_norm(w) / (2. * n_samples) | python | def nlog_likelihood(self, w):
"""Compute negative partial log-likelihood
Parameters
----------
w : array, shape = (n_features,)
Estimate of coefficients
Returns
-------
loss : float
Average negative partial log-likelihood
"""
time = self.time
n_samples = self.x.shape[0]
xw = numpy.dot(self.x, w)
loss = 0
risk_set = 0
k = 0
for i in range(n_samples):
ti = time[i]
while k < n_samples and ti == time[k]:
risk_set += numpy.exp(xw[k])
k += 1
if self.event[i]:
loss -= (xw[i] - numpy.log(risk_set)) / n_samples
# add regularization term to log-likelihood
return loss + self.alpha * squared_norm(w) / (2. * n_samples) | [
"def",
"nlog_likelihood",
"(",
"self",
",",
"w",
")",
":",
"time",
"=",
"self",
".",
"time",
"n_samples",
"=",
"self",
".",
"x",
".",
"shape",
"[",
"0",
"]",
"xw",
"=",
"numpy",
".",
"dot",
"(",
"self",
".",
"x",
",",
"w",
")",
"loss",
"=",
"0",
"risk_set",
"=",
"0",
"k",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"n_samples",
")",
":",
"ti",
"=",
"time",
"[",
"i",
"]",
"while",
"k",
"<",
"n_samples",
"and",
"ti",
"==",
"time",
"[",
"k",
"]",
":",
"risk_set",
"+=",
"numpy",
".",
"exp",
"(",
"xw",
"[",
"k",
"]",
")",
"k",
"+=",
"1",
"if",
"self",
".",
"event",
"[",
"i",
"]",
":",
"loss",
"-=",
"(",
"xw",
"[",
"i",
"]",
"-",
"numpy",
".",
"log",
"(",
"risk_set",
")",
")",
"/",
"n_samples",
"# add regularization term to log-likelihood",
"return",
"loss",
"+",
"self",
".",
"alpha",
"*",
"squared_norm",
"(",
"w",
")",
"/",
"(",
"2.",
"*",
"n_samples",
")"
] | Compute negative partial log-likelihood
Parameters
----------
w : array, shape = (n_features,)
Estimate of coefficients
Returns
-------
loss : float
Average negative partial log-likelihood | [
"Compute",
"negative",
"partial",
"log",
"-",
"likelihood"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L138-L168 |
232,792 | sebp/scikit-survival | sksurv/linear_model/coxph.py | CoxPHOptimizer.update | def update(self, w, offset=0):
"""Compute gradient and Hessian matrix with respect to `w`."""
time = self.time
x = self.x
exp_xw = numpy.exp(offset + numpy.dot(x, w))
n_samples, n_features = x.shape
gradient = numpy.zeros((1, n_features), dtype=float)
hessian = numpy.zeros((n_features, n_features), dtype=float)
inv_n_samples = 1. / n_samples
risk_set = 0
risk_set_x = 0
risk_set_xx = 0
k = 0
# iterate time in descending order
for i in range(n_samples):
ti = time[i]
while k < n_samples and ti == time[k]:
risk_set += exp_xw[k]
# preserve 2D shape of row vector
xk = x[k:k + 1]
risk_set_x += exp_xw[k] * xk
# outer product
xx = numpy.dot(xk.T, xk)
risk_set_xx += exp_xw[k] * xx
k += 1
if self.event[i]:
gradient -= (x[i:i + 1] - risk_set_x / risk_set) * inv_n_samples
a = risk_set_xx / risk_set
z = risk_set_x / risk_set
# outer product
b = numpy.dot(z.T, z)
hessian += (a - b) * inv_n_samples
if self.alpha > 0:
gradient += self.alpha * inv_n_samples * w
diag_idx = numpy.diag_indices(n_features)
hessian[diag_idx] += self.alpha * inv_n_samples
self.gradient = gradient.ravel()
self.hessian = hessian | python | def update(self, w, offset=0):
"""Compute gradient and Hessian matrix with respect to `w`."""
time = self.time
x = self.x
exp_xw = numpy.exp(offset + numpy.dot(x, w))
n_samples, n_features = x.shape
gradient = numpy.zeros((1, n_features), dtype=float)
hessian = numpy.zeros((n_features, n_features), dtype=float)
inv_n_samples = 1. / n_samples
risk_set = 0
risk_set_x = 0
risk_set_xx = 0
k = 0
# iterate time in descending order
for i in range(n_samples):
ti = time[i]
while k < n_samples and ti == time[k]:
risk_set += exp_xw[k]
# preserve 2D shape of row vector
xk = x[k:k + 1]
risk_set_x += exp_xw[k] * xk
# outer product
xx = numpy.dot(xk.T, xk)
risk_set_xx += exp_xw[k] * xx
k += 1
if self.event[i]:
gradient -= (x[i:i + 1] - risk_set_x / risk_set) * inv_n_samples
a = risk_set_xx / risk_set
z = risk_set_x / risk_set
# outer product
b = numpy.dot(z.T, z)
hessian += (a - b) * inv_n_samples
if self.alpha > 0:
gradient += self.alpha * inv_n_samples * w
diag_idx = numpy.diag_indices(n_features)
hessian[diag_idx] += self.alpha * inv_n_samples
self.gradient = gradient.ravel()
self.hessian = hessian | [
"def",
"update",
"(",
"self",
",",
"w",
",",
"offset",
"=",
"0",
")",
":",
"time",
"=",
"self",
".",
"time",
"x",
"=",
"self",
".",
"x",
"exp_xw",
"=",
"numpy",
".",
"exp",
"(",
"offset",
"+",
"numpy",
".",
"dot",
"(",
"x",
",",
"w",
")",
")",
"n_samples",
",",
"n_features",
"=",
"x",
".",
"shape",
"gradient",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"1",
",",
"n_features",
")",
",",
"dtype",
"=",
"float",
")",
"hessian",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"n_features",
",",
"n_features",
")",
",",
"dtype",
"=",
"float",
")",
"inv_n_samples",
"=",
"1.",
"/",
"n_samples",
"risk_set",
"=",
"0",
"risk_set_x",
"=",
"0",
"risk_set_xx",
"=",
"0",
"k",
"=",
"0",
"# iterate time in descending order",
"for",
"i",
"in",
"range",
"(",
"n_samples",
")",
":",
"ti",
"=",
"time",
"[",
"i",
"]",
"while",
"k",
"<",
"n_samples",
"and",
"ti",
"==",
"time",
"[",
"k",
"]",
":",
"risk_set",
"+=",
"exp_xw",
"[",
"k",
"]",
"# preserve 2D shape of row vector",
"xk",
"=",
"x",
"[",
"k",
":",
"k",
"+",
"1",
"]",
"risk_set_x",
"+=",
"exp_xw",
"[",
"k",
"]",
"*",
"xk",
"# outer product",
"xx",
"=",
"numpy",
".",
"dot",
"(",
"xk",
".",
"T",
",",
"xk",
")",
"risk_set_xx",
"+=",
"exp_xw",
"[",
"k",
"]",
"*",
"xx",
"k",
"+=",
"1",
"if",
"self",
".",
"event",
"[",
"i",
"]",
":",
"gradient",
"-=",
"(",
"x",
"[",
"i",
":",
"i",
"+",
"1",
"]",
"-",
"risk_set_x",
"/",
"risk_set",
")",
"*",
"inv_n_samples",
"a",
"=",
"risk_set_xx",
"/",
"risk_set",
"z",
"=",
"risk_set_x",
"/",
"risk_set",
"# outer product",
"b",
"=",
"numpy",
".",
"dot",
"(",
"z",
".",
"T",
",",
"z",
")",
"hessian",
"+=",
"(",
"a",
"-",
"b",
")",
"*",
"inv_n_samples",
"if",
"self",
".",
"alpha",
">",
"0",
":",
"gradient",
"+=",
"self",
".",
"alpha",
"*",
"inv_n_samples",
"*",
"w",
"diag_idx",
"=",
"numpy",
".",
"diag_indices",
"(",
"n_features",
")",
"hessian",
"[",
"diag_idx",
"]",
"+=",
"self",
".",
"alpha",
"*",
"inv_n_samples",
"self",
".",
"gradient",
"=",
"gradient",
".",
"ravel",
"(",
")",
"self",
".",
"hessian",
"=",
"hessian"
] | Compute gradient and Hessian matrix with respect to `w`. | [
"Compute",
"gradient",
"and",
"Hessian",
"matrix",
"with",
"respect",
"to",
"w",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L170-L218 |
232,793 | sebp/scikit-survival | sksurv/linear_model/coxph.py | CoxPHSurvivalAnalysis.fit | def fit(self, X, y):
"""Minimize negative partial log-likelihood for provided data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Returns
-------
self
"""
X, event, time = check_arrays_survival(X, y)
if self.alpha < 0:
raise ValueError("alpha must be positive, but was %r" % self.alpha)
optimizer = CoxPHOptimizer(X, event, time, self.alpha)
verbose_reporter = VerboseReporter(self.verbose)
w = numpy.zeros(X.shape[1])
w_prev = w
i = 0
loss = float('inf')
while True:
if i >= self.n_iter:
verbose_reporter.end_max_iter(i)
warnings.warn(('Optimization did not converge: Maximum number of iterations has been exceeded.'),
stacklevel=2, category=ConvergenceWarning)
break
optimizer.update(w)
delta = solve(optimizer.hessian, optimizer.gradient,
overwrite_a=False, overwrite_b=False, check_finite=False)
if not numpy.all(numpy.isfinite(delta)):
raise ValueError("search direction contains NaN or infinite values")
w_new = w - delta
loss_new = optimizer.nlog_likelihood(w_new)
verbose_reporter.update(i, delta, loss_new)
if loss_new > loss:
# perform step-halving if negative log-likelihood does not decrease
w = (w_prev + w) / 2
loss = optimizer.nlog_likelihood(w)
verbose_reporter.step_halving(i, loss)
i += 1
continue
w_prev = w
w = w_new
res = numpy.abs(1 - (loss_new / loss))
if res < self.tol:
verbose_reporter.end_converged(i)
break
loss = loss_new
i += 1
self.coef_ = w
self._baseline_model.fit(numpy.dot(X, self.coef_), event, time)
return self | python | def fit(self, X, y):
"""Minimize negative partial log-likelihood for provided data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Returns
-------
self
"""
X, event, time = check_arrays_survival(X, y)
if self.alpha < 0:
raise ValueError("alpha must be positive, but was %r" % self.alpha)
optimizer = CoxPHOptimizer(X, event, time, self.alpha)
verbose_reporter = VerboseReporter(self.verbose)
w = numpy.zeros(X.shape[1])
w_prev = w
i = 0
loss = float('inf')
while True:
if i >= self.n_iter:
verbose_reporter.end_max_iter(i)
warnings.warn(('Optimization did not converge: Maximum number of iterations has been exceeded.'),
stacklevel=2, category=ConvergenceWarning)
break
optimizer.update(w)
delta = solve(optimizer.hessian, optimizer.gradient,
overwrite_a=False, overwrite_b=False, check_finite=False)
if not numpy.all(numpy.isfinite(delta)):
raise ValueError("search direction contains NaN or infinite values")
w_new = w - delta
loss_new = optimizer.nlog_likelihood(w_new)
verbose_reporter.update(i, delta, loss_new)
if loss_new > loss:
# perform step-halving if negative log-likelihood does not decrease
w = (w_prev + w) / 2
loss = optimizer.nlog_likelihood(w)
verbose_reporter.step_halving(i, loss)
i += 1
continue
w_prev = w
w = w_new
res = numpy.abs(1 - (loss_new / loss))
if res < self.tol:
verbose_reporter.end_converged(i)
break
loss = loss_new
i += 1
self.coef_ = w
self._baseline_model.fit(numpy.dot(X, self.coef_), event, time)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"X",
",",
"event",
",",
"time",
"=",
"check_arrays_survival",
"(",
"X",
",",
"y",
")",
"if",
"self",
".",
"alpha",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"alpha must be positive, but was %r\"",
"%",
"self",
".",
"alpha",
")",
"optimizer",
"=",
"CoxPHOptimizer",
"(",
"X",
",",
"event",
",",
"time",
",",
"self",
".",
"alpha",
")",
"verbose_reporter",
"=",
"VerboseReporter",
"(",
"self",
".",
"verbose",
")",
"w",
"=",
"numpy",
".",
"zeros",
"(",
"X",
".",
"shape",
"[",
"1",
"]",
")",
"w_prev",
"=",
"w",
"i",
"=",
"0",
"loss",
"=",
"float",
"(",
"'inf'",
")",
"while",
"True",
":",
"if",
"i",
">=",
"self",
".",
"n_iter",
":",
"verbose_reporter",
".",
"end_max_iter",
"(",
"i",
")",
"warnings",
".",
"warn",
"(",
"(",
"'Optimization did not converge: Maximum number of iterations has been exceeded.'",
")",
",",
"stacklevel",
"=",
"2",
",",
"category",
"=",
"ConvergenceWarning",
")",
"break",
"optimizer",
".",
"update",
"(",
"w",
")",
"delta",
"=",
"solve",
"(",
"optimizer",
".",
"hessian",
",",
"optimizer",
".",
"gradient",
",",
"overwrite_a",
"=",
"False",
",",
"overwrite_b",
"=",
"False",
",",
"check_finite",
"=",
"False",
")",
"if",
"not",
"numpy",
".",
"all",
"(",
"numpy",
".",
"isfinite",
"(",
"delta",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"search direction contains NaN or infinite values\"",
")",
"w_new",
"=",
"w",
"-",
"delta",
"loss_new",
"=",
"optimizer",
".",
"nlog_likelihood",
"(",
"w_new",
")",
"verbose_reporter",
".",
"update",
"(",
"i",
",",
"delta",
",",
"loss_new",
")",
"if",
"loss_new",
">",
"loss",
":",
"# perform step-halving if negative log-likelihood does not decrease",
"w",
"=",
"(",
"w_prev",
"+",
"w",
")",
"/",
"2",
"loss",
"=",
"optimizer",
".",
"nlog_likelihood",
"(",
"w",
")",
"verbose_reporter",
".",
"step_halving",
"(",
"i",
",",
"loss",
")",
"i",
"+=",
"1",
"continue",
"w_prev",
"=",
"w",
"w",
"=",
"w_new",
"res",
"=",
"numpy",
".",
"abs",
"(",
"1",
"-",
"(",
"loss_new",
"/",
"loss",
")",
")",
"if",
"res",
"<",
"self",
".",
"tol",
":",
"verbose_reporter",
".",
"end_converged",
"(",
"i",
")",
"break",
"loss",
"=",
"loss_new",
"i",
"+=",
"1",
"self",
".",
"coef_",
"=",
"w",
"self",
".",
"_baseline_model",
".",
"fit",
"(",
"numpy",
".",
"dot",
"(",
"X",
",",
"self",
".",
"coef_",
")",
",",
"event",
",",
"time",
")",
"return",
"self"
] | Minimize negative partial log-likelihood for provided data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Returns
-------
self | [
"Minimize",
"negative",
"partial",
"log",
"-",
"likelihood",
"for",
"provided",
"data",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L292-L359 |
232,794 | sebp/scikit-survival | sksurv/nonparametric.py | _compute_counts | def _compute_counts(event, time, order=None):
"""Count right censored and uncensored samples at each unique time point.
Parameters
----------
event : array
Boolean event indicator.
time : array
Survival time or time of censoring.
order : array or None
Indices to order time in ascending order.
If None, order will be computed.
Returns
-------
times : array
Unique time points.
n_events : array
Number of events at each time point.
n_at_risk : array
Number of samples that are censored or have an event at each time point.
"""
n_samples = event.shape[0]
if order is None:
order = numpy.argsort(time, kind="mergesort")
uniq_times = numpy.empty(n_samples, dtype=time.dtype)
uniq_events = numpy.empty(n_samples, dtype=numpy.int_)
uniq_counts = numpy.empty(n_samples, dtype=numpy.int_)
i = 0
prev_val = time[order[0]]
j = 0
while True:
count_event = 0
count = 0
while i < n_samples and prev_val == time[order[i]]:
if event[order[i]]:
count_event += 1
count += 1
i += 1
uniq_times[j] = prev_val
uniq_events[j] = count_event
uniq_counts[j] = count
j += 1
if i == n_samples:
break
prev_val = time[order[i]]
times = numpy.resize(uniq_times, j)
n_events = numpy.resize(uniq_events, j)
total_count = numpy.resize(uniq_counts, j)
# offset cumulative sum by one
total_count = numpy.concatenate(([0], total_count))
n_at_risk = n_samples - numpy.cumsum(total_count)
return times, n_events, n_at_risk[:-1] | python | def _compute_counts(event, time, order=None):
"""Count right censored and uncensored samples at each unique time point.
Parameters
----------
event : array
Boolean event indicator.
time : array
Survival time or time of censoring.
order : array or None
Indices to order time in ascending order.
If None, order will be computed.
Returns
-------
times : array
Unique time points.
n_events : array
Number of events at each time point.
n_at_risk : array
Number of samples that are censored or have an event at each time point.
"""
n_samples = event.shape[0]
if order is None:
order = numpy.argsort(time, kind="mergesort")
uniq_times = numpy.empty(n_samples, dtype=time.dtype)
uniq_events = numpy.empty(n_samples, dtype=numpy.int_)
uniq_counts = numpy.empty(n_samples, dtype=numpy.int_)
i = 0
prev_val = time[order[0]]
j = 0
while True:
count_event = 0
count = 0
while i < n_samples and prev_val == time[order[i]]:
if event[order[i]]:
count_event += 1
count += 1
i += 1
uniq_times[j] = prev_val
uniq_events[j] = count_event
uniq_counts[j] = count
j += 1
if i == n_samples:
break
prev_val = time[order[i]]
times = numpy.resize(uniq_times, j)
n_events = numpy.resize(uniq_events, j)
total_count = numpy.resize(uniq_counts, j)
# offset cumulative sum by one
total_count = numpy.concatenate(([0], total_count))
n_at_risk = n_samples - numpy.cumsum(total_count)
return times, n_events, n_at_risk[:-1] | [
"def",
"_compute_counts",
"(",
"event",
",",
"time",
",",
"order",
"=",
"None",
")",
":",
"n_samples",
"=",
"event",
".",
"shape",
"[",
"0",
"]",
"if",
"order",
"is",
"None",
":",
"order",
"=",
"numpy",
".",
"argsort",
"(",
"time",
",",
"kind",
"=",
"\"mergesort\"",
")",
"uniq_times",
"=",
"numpy",
".",
"empty",
"(",
"n_samples",
",",
"dtype",
"=",
"time",
".",
"dtype",
")",
"uniq_events",
"=",
"numpy",
".",
"empty",
"(",
"n_samples",
",",
"dtype",
"=",
"numpy",
".",
"int_",
")",
"uniq_counts",
"=",
"numpy",
".",
"empty",
"(",
"n_samples",
",",
"dtype",
"=",
"numpy",
".",
"int_",
")",
"i",
"=",
"0",
"prev_val",
"=",
"time",
"[",
"order",
"[",
"0",
"]",
"]",
"j",
"=",
"0",
"while",
"True",
":",
"count_event",
"=",
"0",
"count",
"=",
"0",
"while",
"i",
"<",
"n_samples",
"and",
"prev_val",
"==",
"time",
"[",
"order",
"[",
"i",
"]",
"]",
":",
"if",
"event",
"[",
"order",
"[",
"i",
"]",
"]",
":",
"count_event",
"+=",
"1",
"count",
"+=",
"1",
"i",
"+=",
"1",
"uniq_times",
"[",
"j",
"]",
"=",
"prev_val",
"uniq_events",
"[",
"j",
"]",
"=",
"count_event",
"uniq_counts",
"[",
"j",
"]",
"=",
"count",
"j",
"+=",
"1",
"if",
"i",
"==",
"n_samples",
":",
"break",
"prev_val",
"=",
"time",
"[",
"order",
"[",
"i",
"]",
"]",
"times",
"=",
"numpy",
".",
"resize",
"(",
"uniq_times",
",",
"j",
")",
"n_events",
"=",
"numpy",
".",
"resize",
"(",
"uniq_events",
",",
"j",
")",
"total_count",
"=",
"numpy",
".",
"resize",
"(",
"uniq_counts",
",",
"j",
")",
"# offset cumulative sum by one",
"total_count",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"[",
"0",
"]",
",",
"total_count",
")",
")",
"n_at_risk",
"=",
"n_samples",
"-",
"numpy",
".",
"cumsum",
"(",
"total_count",
")",
"return",
"times",
",",
"n_events",
",",
"n_at_risk",
"[",
":",
"-",
"1",
"]"
] | Count right censored and uncensored samples at each unique time point.
Parameters
----------
event : array
Boolean event indicator.
time : array
Survival time or time of censoring.
order : array or None
Indices to order time in ascending order.
If None, order will be computed.
Returns
-------
times : array
Unique time points.
n_events : array
Number of events at each time point.
n_at_risk : array
Number of samples that are censored or have an event at each time point. | [
"Count",
"right",
"censored",
"and",
"uncensored",
"samples",
"at",
"each",
"unique",
"time",
"point",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L28-L94 |
232,795 | sebp/scikit-survival | sksurv/nonparametric.py | _compute_counts_truncated | def _compute_counts_truncated(event, time_enter, time_exit):
"""Compute counts for left truncated and right censored survival data.
Parameters
----------
event : array
Boolean event indicator.
time_start : array
Time when a subject entered the study.
time_exit : array
Time when a subject left the study due to an
event or censoring.
Returns
-------
times : array
Unique time points.
n_events : array
Number of events at each time point.
n_at_risk : array
Number of samples that are censored or have an event at each time point.
"""
if (time_enter > time_exit).any():
raise ValueError("exit time must be larger start time for all samples")
n_samples = event.shape[0]
uniq_times = numpy.sort(numpy.unique(numpy.concatenate((time_enter, time_exit))), kind="mergesort")
total_counts = numpy.empty(len(uniq_times), dtype=numpy.int_)
event_counts = numpy.empty(len(uniq_times), dtype=numpy.int_)
order_enter = numpy.argsort(time_enter, kind="mergesort")
order_exit = numpy.argsort(time_exit, kind="mergesort")
s_time_enter = time_enter[order_enter]
s_time_exit = time_exit[order_exit]
t0 = uniq_times[0]
# everything larger is included
idx_enter = numpy.searchsorted(s_time_enter, t0, side="right")
# everything smaller is excluded
idx_exit = numpy.searchsorted(s_time_exit, t0, side="left")
total_counts[0] = idx_enter
# except people die on the day they enter
event_counts[0] = 0
for i in range(1, len(uniq_times)):
ti = uniq_times[i]
while idx_enter < n_samples and s_time_enter[idx_enter] <= ti:
idx_enter += 1
while idx_exit < n_samples and s_time_exit[idx_exit] < ti:
idx_exit += 1
risk_set = numpy.setdiff1d(order_enter[:idx_enter], order_exit[:idx_exit], assume_unique=True)
total_counts[i] = len(risk_set)
count_event = 0
k = idx_exit
while k < n_samples and s_time_exit[k] == ti:
if event[order_exit[k]]:
count_event += 1
k += 1
event_counts[i] = count_event
return uniq_times, event_counts, total_counts | python | def _compute_counts_truncated(event, time_enter, time_exit):
"""Compute counts for left truncated and right censored survival data.
Parameters
----------
event : array
Boolean event indicator.
time_start : array
Time when a subject entered the study.
time_exit : array
Time when a subject left the study due to an
event or censoring.
Returns
-------
times : array
Unique time points.
n_events : array
Number of events at each time point.
n_at_risk : array
Number of samples that are censored or have an event at each time point.
"""
if (time_enter > time_exit).any():
raise ValueError("exit time must be larger start time for all samples")
n_samples = event.shape[0]
uniq_times = numpy.sort(numpy.unique(numpy.concatenate((time_enter, time_exit))), kind="mergesort")
total_counts = numpy.empty(len(uniq_times), dtype=numpy.int_)
event_counts = numpy.empty(len(uniq_times), dtype=numpy.int_)
order_enter = numpy.argsort(time_enter, kind="mergesort")
order_exit = numpy.argsort(time_exit, kind="mergesort")
s_time_enter = time_enter[order_enter]
s_time_exit = time_exit[order_exit]
t0 = uniq_times[0]
# everything larger is included
idx_enter = numpy.searchsorted(s_time_enter, t0, side="right")
# everything smaller is excluded
idx_exit = numpy.searchsorted(s_time_exit, t0, side="left")
total_counts[0] = idx_enter
# except people die on the day they enter
event_counts[0] = 0
for i in range(1, len(uniq_times)):
ti = uniq_times[i]
while idx_enter < n_samples and s_time_enter[idx_enter] <= ti:
idx_enter += 1
while idx_exit < n_samples and s_time_exit[idx_exit] < ti:
idx_exit += 1
risk_set = numpy.setdiff1d(order_enter[:idx_enter], order_exit[:idx_exit], assume_unique=True)
total_counts[i] = len(risk_set)
count_event = 0
k = idx_exit
while k < n_samples and s_time_exit[k] == ti:
if event[order_exit[k]]:
count_event += 1
k += 1
event_counts[i] = count_event
return uniq_times, event_counts, total_counts | [
"def",
"_compute_counts_truncated",
"(",
"event",
",",
"time_enter",
",",
"time_exit",
")",
":",
"if",
"(",
"time_enter",
">",
"time_exit",
")",
".",
"any",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"exit time must be larger start time for all samples\"",
")",
"n_samples",
"=",
"event",
".",
"shape",
"[",
"0",
"]",
"uniq_times",
"=",
"numpy",
".",
"sort",
"(",
"numpy",
".",
"unique",
"(",
"numpy",
".",
"concatenate",
"(",
"(",
"time_enter",
",",
"time_exit",
")",
")",
")",
",",
"kind",
"=",
"\"mergesort\"",
")",
"total_counts",
"=",
"numpy",
".",
"empty",
"(",
"len",
"(",
"uniq_times",
")",
",",
"dtype",
"=",
"numpy",
".",
"int_",
")",
"event_counts",
"=",
"numpy",
".",
"empty",
"(",
"len",
"(",
"uniq_times",
")",
",",
"dtype",
"=",
"numpy",
".",
"int_",
")",
"order_enter",
"=",
"numpy",
".",
"argsort",
"(",
"time_enter",
",",
"kind",
"=",
"\"mergesort\"",
")",
"order_exit",
"=",
"numpy",
".",
"argsort",
"(",
"time_exit",
",",
"kind",
"=",
"\"mergesort\"",
")",
"s_time_enter",
"=",
"time_enter",
"[",
"order_enter",
"]",
"s_time_exit",
"=",
"time_exit",
"[",
"order_exit",
"]",
"t0",
"=",
"uniq_times",
"[",
"0",
"]",
"# everything larger is included",
"idx_enter",
"=",
"numpy",
".",
"searchsorted",
"(",
"s_time_enter",
",",
"t0",
",",
"side",
"=",
"\"right\"",
")",
"# everything smaller is excluded",
"idx_exit",
"=",
"numpy",
".",
"searchsorted",
"(",
"s_time_exit",
",",
"t0",
",",
"side",
"=",
"\"left\"",
")",
"total_counts",
"[",
"0",
"]",
"=",
"idx_enter",
"# except people die on the day they enter",
"event_counts",
"[",
"0",
"]",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"uniq_times",
")",
")",
":",
"ti",
"=",
"uniq_times",
"[",
"i",
"]",
"while",
"idx_enter",
"<",
"n_samples",
"and",
"s_time_enter",
"[",
"idx_enter",
"]",
"<=",
"ti",
":",
"idx_enter",
"+=",
"1",
"while",
"idx_exit",
"<",
"n_samples",
"and",
"s_time_exit",
"[",
"idx_exit",
"]",
"<",
"ti",
":",
"idx_exit",
"+=",
"1",
"risk_set",
"=",
"numpy",
".",
"setdiff1d",
"(",
"order_enter",
"[",
":",
"idx_enter",
"]",
",",
"order_exit",
"[",
":",
"idx_exit",
"]",
",",
"assume_unique",
"=",
"True",
")",
"total_counts",
"[",
"i",
"]",
"=",
"len",
"(",
"risk_set",
")",
"count_event",
"=",
"0",
"k",
"=",
"idx_exit",
"while",
"k",
"<",
"n_samples",
"and",
"s_time_exit",
"[",
"k",
"]",
"==",
"ti",
":",
"if",
"event",
"[",
"order_exit",
"[",
"k",
"]",
"]",
":",
"count_event",
"+=",
"1",
"k",
"+=",
"1",
"event_counts",
"[",
"i",
"]",
"=",
"count_event",
"return",
"uniq_times",
",",
"event_counts",
",",
"total_counts"
] | Compute counts for left truncated and right censored survival data.
Parameters
----------
event : array
Boolean event indicator.
time_start : array
Time when a subject entered the study.
time_exit : array
Time when a subject left the study due to an
event or censoring.
Returns
-------
times : array
Unique time points.
n_events : array
Number of events at each time point.
n_at_risk : array
Number of samples that are censored or have an event at each time point. | [
"Compute",
"counts",
"for",
"left",
"truncated",
"and",
"right",
"censored",
"survival",
"data",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L97-L167 |
232,796 | sebp/scikit-survival | sksurv/nonparametric.py | kaplan_meier_estimator | def kaplan_meier_estimator(event, time_exit, time_enter=None, time_min=None):
"""Kaplan-Meier estimator of survival function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time_exit : array-like, shape = (n_samples,)
Contains event/censoring times.
time_enter : array-like, shape = (n_samples,), optional
Contains time when each individual entered the study for
left truncated survival data.
time_min : float, optional
Compute estimator conditional on survival at least up to
the specified time.
Returns
-------
time : array, shape = (n_times,)
Unique times.
prob_survival : array, shape = (n_times,)
Survival probability at each unique time point.
If `time_enter` is provided, estimates are conditional probabilities.
Examples
--------
Creating a Kaplan-Meier curve:
>>> x, y = kaplan_meier_estimator(event, time)
>>> plt.step(x, y, where="post")
>>> plt.ylim(0, 1)
>>> plt.show()
References
----------
.. [1] Kaplan, E. L. and Meier, P., "Nonparametric estimation from incomplete observations",
Journal of The American Statistical Association, vol. 53, pp. 457-481, 1958.
"""
event, time_enter, time_exit = check_y_survival(event, time_enter, time_exit, allow_all_censored=True)
check_consistent_length(event, time_enter, time_exit)
if time_enter is None:
uniq_times, n_events, n_at_risk = _compute_counts(event, time_exit)
else:
uniq_times, n_events, n_at_risk = _compute_counts_truncated(event, time_enter, time_exit)
values = 1 - n_events / n_at_risk
if time_min is not None:
mask = uniq_times >= time_min
uniq_times = numpy.compress(mask, uniq_times)
values = numpy.compress(mask, values)
y = numpy.cumprod(values)
return uniq_times, y | python | def kaplan_meier_estimator(event, time_exit, time_enter=None, time_min=None):
"""Kaplan-Meier estimator of survival function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time_exit : array-like, shape = (n_samples,)
Contains event/censoring times.
time_enter : array-like, shape = (n_samples,), optional
Contains time when each individual entered the study for
left truncated survival data.
time_min : float, optional
Compute estimator conditional on survival at least up to
the specified time.
Returns
-------
time : array, shape = (n_times,)
Unique times.
prob_survival : array, shape = (n_times,)
Survival probability at each unique time point.
If `time_enter` is provided, estimates are conditional probabilities.
Examples
--------
Creating a Kaplan-Meier curve:
>>> x, y = kaplan_meier_estimator(event, time)
>>> plt.step(x, y, where="post")
>>> plt.ylim(0, 1)
>>> plt.show()
References
----------
.. [1] Kaplan, E. L. and Meier, P., "Nonparametric estimation from incomplete observations",
Journal of The American Statistical Association, vol. 53, pp. 457-481, 1958.
"""
event, time_enter, time_exit = check_y_survival(event, time_enter, time_exit, allow_all_censored=True)
check_consistent_length(event, time_enter, time_exit)
if time_enter is None:
uniq_times, n_events, n_at_risk = _compute_counts(event, time_exit)
else:
uniq_times, n_events, n_at_risk = _compute_counts_truncated(event, time_enter, time_exit)
values = 1 - n_events / n_at_risk
if time_min is not None:
mask = uniq_times >= time_min
uniq_times = numpy.compress(mask, uniq_times)
values = numpy.compress(mask, values)
y = numpy.cumprod(values)
return uniq_times, y | [
"def",
"kaplan_meier_estimator",
"(",
"event",
",",
"time_exit",
",",
"time_enter",
"=",
"None",
",",
"time_min",
"=",
"None",
")",
":",
"event",
",",
"time_enter",
",",
"time_exit",
"=",
"check_y_survival",
"(",
"event",
",",
"time_enter",
",",
"time_exit",
",",
"allow_all_censored",
"=",
"True",
")",
"check_consistent_length",
"(",
"event",
",",
"time_enter",
",",
"time_exit",
")",
"if",
"time_enter",
"is",
"None",
":",
"uniq_times",
",",
"n_events",
",",
"n_at_risk",
"=",
"_compute_counts",
"(",
"event",
",",
"time_exit",
")",
"else",
":",
"uniq_times",
",",
"n_events",
",",
"n_at_risk",
"=",
"_compute_counts_truncated",
"(",
"event",
",",
"time_enter",
",",
"time_exit",
")",
"values",
"=",
"1",
"-",
"n_events",
"/",
"n_at_risk",
"if",
"time_min",
"is",
"not",
"None",
":",
"mask",
"=",
"uniq_times",
">=",
"time_min",
"uniq_times",
"=",
"numpy",
".",
"compress",
"(",
"mask",
",",
"uniq_times",
")",
"values",
"=",
"numpy",
".",
"compress",
"(",
"mask",
",",
"values",
")",
"y",
"=",
"numpy",
".",
"cumprod",
"(",
"values",
")",
"return",
"uniq_times",
",",
"y"
] | Kaplan-Meier estimator of survival function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time_exit : array-like, shape = (n_samples,)
Contains event/censoring times.
time_enter : array-like, shape = (n_samples,), optional
Contains time when each individual entered the study for
left truncated survival data.
time_min : float, optional
Compute estimator conditional on survival at least up to
the specified time.
Returns
-------
time : array, shape = (n_times,)
Unique times.
prob_survival : array, shape = (n_times,)
Survival probability at each unique time point.
If `time_enter` is provided, estimates are conditional probabilities.
Examples
--------
Creating a Kaplan-Meier curve:
>>> x, y = kaplan_meier_estimator(event, time)
>>> plt.step(x, y, where="post")
>>> plt.ylim(0, 1)
>>> plt.show()
References
----------
.. [1] Kaplan, E. L. and Meier, P., "Nonparametric estimation from incomplete observations",
Journal of The American Statistical Association, vol. 53, pp. 457-481, 1958. | [
"Kaplan",
"-",
"Meier",
"estimator",
"of",
"survival",
"function",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L170-L228 |
232,797 | sebp/scikit-survival | sksurv/nonparametric.py | nelson_aalen_estimator | def nelson_aalen_estimator(event, time):
"""Nelson-Aalen estimator of cumulative hazard function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time : array-like, shape = (n_samples,)
Contains event/censoring times.
Returns
-------
time : array, shape = (n_times,)
Unique times.
cum_hazard : array, shape = (n_times,)
Cumulative hazard at each unique time point.
References
----------
.. [1] Nelson, W., "Theory and applications of hazard plotting for censored failure data",
Technometrics, vol. 14, pp. 945-965, 1972.
.. [2] Aalen, O. O., "Nonparametric inference for a family of counting processes",
Annals of Statistics, vol. 6, pp. 701–726, 1978.
"""
event, time = check_y_survival(event, time)
check_consistent_length(event, time)
uniq_times, n_events, n_at_risk = _compute_counts(event, time)
y = numpy.cumsum(n_events / n_at_risk)
return uniq_times, y | python | def nelson_aalen_estimator(event, time):
"""Nelson-Aalen estimator of cumulative hazard function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time : array-like, shape = (n_samples,)
Contains event/censoring times.
Returns
-------
time : array, shape = (n_times,)
Unique times.
cum_hazard : array, shape = (n_times,)
Cumulative hazard at each unique time point.
References
----------
.. [1] Nelson, W., "Theory and applications of hazard plotting for censored failure data",
Technometrics, vol. 14, pp. 945-965, 1972.
.. [2] Aalen, O. O., "Nonparametric inference for a family of counting processes",
Annals of Statistics, vol. 6, pp. 701–726, 1978.
"""
event, time = check_y_survival(event, time)
check_consistent_length(event, time)
uniq_times, n_events, n_at_risk = _compute_counts(event, time)
y = numpy.cumsum(n_events / n_at_risk)
return uniq_times, y | [
"def",
"nelson_aalen_estimator",
"(",
"event",
",",
"time",
")",
":",
"event",
",",
"time",
"=",
"check_y_survival",
"(",
"event",
",",
"time",
")",
"check_consistent_length",
"(",
"event",
",",
"time",
")",
"uniq_times",
",",
"n_events",
",",
"n_at_risk",
"=",
"_compute_counts",
"(",
"event",
",",
"time",
")",
"y",
"=",
"numpy",
".",
"cumsum",
"(",
"n_events",
"/",
"n_at_risk",
")",
"return",
"uniq_times",
",",
"y"
] | Nelson-Aalen estimator of cumulative hazard function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time : array-like, shape = (n_samples,)
Contains event/censoring times.
Returns
-------
time : array, shape = (n_times,)
Unique times.
cum_hazard : array, shape = (n_times,)
Cumulative hazard at each unique time point.
References
----------
.. [1] Nelson, W., "Theory and applications of hazard plotting for censored failure data",
Technometrics, vol. 14, pp. 945-965, 1972.
.. [2] Aalen, O. O., "Nonparametric inference for a family of counting processes",
Annals of Statistics, vol. 6, pp. 701–726, 1978. | [
"Nelson",
"-",
"Aalen",
"estimator",
"of",
"cumulative",
"hazard",
"function",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L231-L264 |
232,798 | sebp/scikit-survival | sksurv/nonparametric.py | ipc_weights | def ipc_weights(event, time):
"""Compute inverse probability of censoring weights
Parameters
----------
event : array, shape = (n_samples,)
Boolean event indicator.
time : array, shape = (n_samples,)
Time when a subject experienced an event or was censored.
Returns
-------
weights : array, shape = (n_samples,)
inverse probability of censoring weights
"""
if event.all():
return numpy.ones(time.shape[0])
unique_time, p = kaplan_meier_estimator(~event, time)
idx = numpy.searchsorted(unique_time, time[event])
Ghat = p[idx]
assert (Ghat > 0).all()
weights = numpy.zeros(time.shape[0])
weights[event] = 1.0 / Ghat
return weights | python | def ipc_weights(event, time):
"""Compute inverse probability of censoring weights
Parameters
----------
event : array, shape = (n_samples,)
Boolean event indicator.
time : array, shape = (n_samples,)
Time when a subject experienced an event or was censored.
Returns
-------
weights : array, shape = (n_samples,)
inverse probability of censoring weights
"""
if event.all():
return numpy.ones(time.shape[0])
unique_time, p = kaplan_meier_estimator(~event, time)
idx = numpy.searchsorted(unique_time, time[event])
Ghat = p[idx]
assert (Ghat > 0).all()
weights = numpy.zeros(time.shape[0])
weights[event] = 1.0 / Ghat
return weights | [
"def",
"ipc_weights",
"(",
"event",
",",
"time",
")",
":",
"if",
"event",
".",
"all",
"(",
")",
":",
"return",
"numpy",
".",
"ones",
"(",
"time",
".",
"shape",
"[",
"0",
"]",
")",
"unique_time",
",",
"p",
"=",
"kaplan_meier_estimator",
"(",
"~",
"event",
",",
"time",
")",
"idx",
"=",
"numpy",
".",
"searchsorted",
"(",
"unique_time",
",",
"time",
"[",
"event",
"]",
")",
"Ghat",
"=",
"p",
"[",
"idx",
"]",
"assert",
"(",
"Ghat",
">",
"0",
")",
".",
"all",
"(",
")",
"weights",
"=",
"numpy",
".",
"zeros",
"(",
"time",
".",
"shape",
"[",
"0",
"]",
")",
"weights",
"[",
"event",
"]",
"=",
"1.0",
"/",
"Ghat",
"return",
"weights"
] | Compute inverse probability of censoring weights
Parameters
----------
event : array, shape = (n_samples,)
Boolean event indicator.
time : array, shape = (n_samples,)
Time when a subject experienced an event or was censored.
Returns
-------
weights : array, shape = (n_samples,)
inverse probability of censoring weights | [
"Compute",
"inverse",
"probability",
"of",
"censoring",
"weights"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L267-L296 |
232,799 | sebp/scikit-survival | sksurv/nonparametric.py | SurvivalFunctionEstimator.fit | def fit(self, y):
"""Estimate survival distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Returns
-------
self
"""
event, time = check_y_survival(y, allow_all_censored=True)
unique_time, prob = kaplan_meier_estimator(event, time)
self.unique_time_ = numpy.concatenate(([-numpy.infty], unique_time))
self.prob_ = numpy.concatenate(([1.], prob))
return self | python | def fit(self, y):
"""Estimate survival distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Returns
-------
self
"""
event, time = check_y_survival(y, allow_all_censored=True)
unique_time, prob = kaplan_meier_estimator(event, time)
self.unique_time_ = numpy.concatenate(([-numpy.infty], unique_time))
self.prob_ = numpy.concatenate(([1.], prob))
return self | [
"def",
"fit",
"(",
"self",
",",
"y",
")",
":",
"event",
",",
"time",
"=",
"check_y_survival",
"(",
"y",
",",
"allow_all_censored",
"=",
"True",
")",
"unique_time",
",",
"prob",
"=",
"kaplan_meier_estimator",
"(",
"event",
",",
"time",
")",
"self",
".",
"unique_time_",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"[",
"-",
"numpy",
".",
"infty",
"]",
",",
"unique_time",
")",
")",
"self",
".",
"prob_",
"=",
"numpy",
".",
"concatenate",
"(",
"(",
"[",
"1.",
"]",
",",
"prob",
")",
")",
"return",
"self"
] | Estimate survival distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Returns
-------
self | [
"Estimate",
"survival",
"distribution",
"from",
"training",
"data",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L305-L325 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.