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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
29,400 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xpathContext.setContextNode | def setContextNode(self, node):
"""Set the current node of an xpathContext """
if node is None: node__o = None
else: node__o = node._o
libxml2mod.xmlXPathSetContextNode(self._o, node__o) | python | def setContextNode(self, node):
"""Set the current node of an xpathContext """
if node is None: node__o = None
else: node__o = node._o
libxml2mod.xmlXPathSetContextNode(self._o, node__o) | [
"def",
"setContextNode",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"is",
"None",
":",
"node__o",
"=",
"None",
"else",
":",
"node__o",
"=",
"node",
".",
"_o",
"libxml2mod",
".",
"xmlXPathSetContextNode",
"(",
"self",
".",
"_o",
",",
"node__o",
")"
] | Set the current node of an xpathContext | [
"Set",
"the",
"current",
"node",
"of",
"an",
"xpathContext"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7297-L7301 |
29,401 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xpathContext.registerXPathFunction | def registerXPathFunction(self, name, ns_uri, f):
"""Register a Python written function to the XPath interpreter """
ret = libxml2mod.xmlRegisterXPathFunction(self._o, name, ns_uri, f)
return ret | python | def registerXPathFunction(self, name, ns_uri, f):
"""Register a Python written function to the XPath interpreter """
ret = libxml2mod.xmlRegisterXPathFunction(self._o, name, ns_uri, f)
return ret | [
"def",
"registerXPathFunction",
"(",
"self",
",",
"name",
",",
"ns_uri",
",",
"f",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRegisterXPathFunction",
"(",
"self",
".",
"_o",
",",
"name",
",",
"ns_uri",
",",
"f",
")",
"return",
"ret"
] | Register a Python written function to the XPath interpreter | [
"Register",
"a",
"Python",
"written",
"function",
"to",
"the",
"XPath",
"interpreter"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7307-L7310 |
29,402 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xpathContext.xpathRegisterVariable | def xpathRegisterVariable(self, name, ns_uri, value):
"""Register a variable with the XPath context """
ret = libxml2mod.xmlXPathRegisterVariable(self._o, name, ns_uri, value)
return ret | python | def xpathRegisterVariable(self, name, ns_uri, value):
"""Register a variable with the XPath context """
ret = libxml2mod.xmlXPathRegisterVariable(self._o, name, ns_uri, value)
return ret | [
"def",
"xpathRegisterVariable",
"(",
"self",
",",
"name",
",",
"ns_uri",
",",
"value",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathRegisterVariable",
"(",
"self",
".",
"_o",
",",
"name",
",",
"ns_uri",
",",
"value",
")",
"return",
"ret"
] | Register a variable with the XPath context | [
"Register",
"a",
"variable",
"with",
"the",
"XPath",
"context"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7312-L7315 |
29,403 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xpathContext.xpathEvalExpression | def xpathEvalExpression(self, str):
"""Evaluate the XPath expression in the given context. """
ret = libxml2mod.xmlXPathEvalExpression(str, self._o)
if ret is None:raise xpathError('xmlXPathEvalExpression() failed')
return xpathObjectRet(ret) | python | def xpathEvalExpression(self, str):
"""Evaluate the XPath expression in the given context. """
ret = libxml2mod.xmlXPathEvalExpression(str, self._o)
if ret is None:raise xpathError('xmlXPathEvalExpression() failed')
return xpathObjectRet(ret) | [
"def",
"xpathEvalExpression",
"(",
"self",
",",
"str",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathEvalExpression",
"(",
"str",
",",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"xpathError",
"(",
"'xmlXPathEvalExpression() failed'",
")",
"return",
"xpathObjectRet",
"(",
"ret",
")"
] | Evaluate the XPath expression in the given context. | [
"Evaluate",
"the",
"XPath",
"expression",
"in",
"the",
"given",
"context",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7339-L7343 |
29,404 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xpathContext.xpathNewParserContext | def xpathNewParserContext(self, str):
"""Create a new xmlXPathParserContext """
ret = libxml2mod.xmlXPathNewParserContext(str, self._o)
if ret is None:raise xpathError('xmlXPathNewParserContext() failed')
__tmp = xpathParserContext(_obj=ret)
return __tmp | python | def xpathNewParserContext(self, str):
"""Create a new xmlXPathParserContext """
ret = libxml2mod.xmlXPathNewParserContext(str, self._o)
if ret is None:raise xpathError('xmlXPathNewParserContext() failed')
__tmp = xpathParserContext(_obj=ret)
return __tmp | [
"def",
"xpathNewParserContext",
"(",
"self",
",",
"str",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathNewParserContext",
"(",
"str",
",",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"xpathError",
"(",
"'xmlXPathNewParserContext() failed'",
")",
"__tmp",
"=",
"xpathParserContext",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | Create a new xmlXPathParserContext | [
"Create",
"a",
"new",
"xmlXPathParserContext"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7353-L7358 |
29,405 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xpathContext.xpathNsLookup | def xpathNsLookup(self, prefix):
"""Search in the namespace declaration array of the context
for the given namespace name associated to the given prefix """
ret = libxml2mod.xmlXPathNsLookup(self._o, prefix)
return ret | python | def xpathNsLookup(self, prefix):
"""Search in the namespace declaration array of the context
for the given namespace name associated to the given prefix """
ret = libxml2mod.xmlXPathNsLookup(self._o, prefix)
return ret | [
"def",
"xpathNsLookup",
"(",
"self",
",",
"prefix",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathNsLookup",
"(",
"self",
".",
"_o",
",",
"prefix",
")",
"return",
"ret"
] | Search in the namespace declaration array of the context
for the given namespace name associated to the given prefix | [
"Search",
"in",
"the",
"namespace",
"declaration",
"array",
"of",
"the",
"context",
"for",
"the",
"given",
"namespace",
"name",
"associated",
"to",
"the",
"given",
"prefix"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7360-L7364 |
29,406 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xpathContext.xpathRegisterNs | def xpathRegisterNs(self, prefix, ns_uri):
"""Register a new namespace. If @ns_uri is None it unregisters
the namespace """
ret = libxml2mod.xmlXPathRegisterNs(self._o, prefix, ns_uri)
return ret | python | def xpathRegisterNs(self, prefix, ns_uri):
"""Register a new namespace. If @ns_uri is None it unregisters
the namespace """
ret = libxml2mod.xmlXPathRegisterNs(self._o, prefix, ns_uri)
return ret | [
"def",
"xpathRegisterNs",
"(",
"self",
",",
"prefix",
",",
"ns_uri",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathRegisterNs",
"(",
"self",
".",
"_o",
",",
"prefix",
",",
"ns_uri",
")",
"return",
"ret"
] | Register a new namespace. If @ns_uri is None it unregisters
the namespace | [
"Register",
"a",
"new",
"namespace",
".",
"If"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7370-L7374 |
29,407 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xpathParserContext.context | def context(self):
"""Get the xpathContext from an xpathParserContext """
ret = libxml2mod.xmlXPathParserGetContext(self._o)
if ret is None:raise xpathError('xmlXPathParserGetContext() failed')
__tmp = xpathContext(_obj=ret)
return __tmp | python | def context(self):
"""Get the xpathContext from an xpathParserContext """
ret = libxml2mod.xmlXPathParserGetContext(self._o)
if ret is None:raise xpathError('xmlXPathParserGetContext() failed')
__tmp = xpathContext(_obj=ret)
return __tmp | [
"def",
"context",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathParserGetContext",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"xpathError",
"(",
"'xmlXPathParserGetContext() failed'",
")",
"__tmp",
"=",
"xpathContext",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | Get the xpathContext from an xpathParserContext | [
"Get",
"the",
"xpathContext",
"from",
"an",
"xpathParserContext"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7421-L7426 |
29,408 | apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | xpathParserContext.xpatherror | def xpatherror(self, file, line, no):
"""Formats an error message. """
libxml2mod.xmlXPatherror(self._o, file, line, no) | python | def xpatherror(self, file, line, no):
"""Formats an error message. """
libxml2mod.xmlXPatherror(self._o, file, line, no) | [
"def",
"xpatherror",
"(",
"self",
",",
"file",
",",
"line",
",",
"no",
")",
":",
"libxml2mod",
".",
"xmlXPatherror",
"(",
"self",
".",
"_o",
",",
"file",
",",
"line",
",",
"no",
")"
] | Formats an error message. | [
"Formats",
"an",
"error",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7969-L7971 |
29,409 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | traverse | def traverse (target, include_roots = False, include_sources = False):
""" Traverses the dependency graph of 'target' and return all targets that will
be created before this one is created. If root of some dependency graph is
found during traversal, it's either included or not, dependencing of the
value of 'include_roots'. In either case, sources of root are not traversed.
"""
assert isinstance(target, VirtualTarget)
assert isinstance(include_roots, (int, bool))
assert isinstance(include_sources, (int, bool))
result = []
if target.action ():
action = target.action ()
# This includes 'target' as well
result += action.targets ()
for t in action.sources ():
# FIXME:
# TODO: see comment in Manager.register_object ()
#if not isinstance (t, VirtualTarget):
# t = target.project_.manager_.get_object (t)
if not t.root ():
result += traverse (t, include_roots, include_sources)
elif include_roots:
result.append (t)
elif include_sources:
result.append (target)
return result | python | def traverse (target, include_roots = False, include_sources = False):
""" Traverses the dependency graph of 'target' and return all targets that will
be created before this one is created. If root of some dependency graph is
found during traversal, it's either included or not, dependencing of the
value of 'include_roots'. In either case, sources of root are not traversed.
"""
assert isinstance(target, VirtualTarget)
assert isinstance(include_roots, (int, bool))
assert isinstance(include_sources, (int, bool))
result = []
if target.action ():
action = target.action ()
# This includes 'target' as well
result += action.targets ()
for t in action.sources ():
# FIXME:
# TODO: see comment in Manager.register_object ()
#if not isinstance (t, VirtualTarget):
# t = target.project_.manager_.get_object (t)
if not t.root ():
result += traverse (t, include_roots, include_sources)
elif include_roots:
result.append (t)
elif include_sources:
result.append (target)
return result | [
"def",
"traverse",
"(",
"target",
",",
"include_roots",
"=",
"False",
",",
"include_sources",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"target",
",",
"VirtualTarget",
")",
"assert",
"isinstance",
"(",
"include_roots",
",",
"(",
"int",
",",
"bool",
")",
")",
"assert",
"isinstance",
"(",
"include_sources",
",",
"(",
"int",
",",
"bool",
")",
")",
"result",
"=",
"[",
"]",
"if",
"target",
".",
"action",
"(",
")",
":",
"action",
"=",
"target",
".",
"action",
"(",
")",
"# This includes 'target' as well",
"result",
"+=",
"action",
".",
"targets",
"(",
")",
"for",
"t",
"in",
"action",
".",
"sources",
"(",
")",
":",
"# FIXME:",
"# TODO: see comment in Manager.register_object ()",
"#if not isinstance (t, VirtualTarget):",
"# t = target.project_.manager_.get_object (t)",
"if",
"not",
"t",
".",
"root",
"(",
")",
":",
"result",
"+=",
"traverse",
"(",
"t",
",",
"include_roots",
",",
"include_sources",
")",
"elif",
"include_roots",
":",
"result",
".",
"append",
"(",
"t",
")",
"elif",
"include_sources",
":",
"result",
".",
"append",
"(",
"target",
")",
"return",
"result"
] | Traverses the dependency graph of 'target' and return all targets that will
be created before this one is created. If root of some dependency graph is
found during traversal, it's either included or not, dependencing of the
value of 'include_roots'. In either case, sources of root are not traversed. | [
"Traverses",
"the",
"dependency",
"graph",
"of",
"target",
"and",
"return",
"all",
"targets",
"that",
"will",
"be",
"created",
"before",
"this",
"one",
"is",
"created",
".",
"If",
"root",
"of",
"some",
"dependency",
"graph",
"is",
"found",
"during",
"traversal",
"it",
"s",
"either",
"included",
"or",
"not",
"dependencing",
"of",
"the",
"value",
"of",
"include_roots",
".",
"In",
"either",
"case",
"sources",
"of",
"root",
"are",
"not",
"traversed",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L963-L996 |
29,410 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | clone_action | def clone_action (action, new_project, new_action_name, new_properties):
"""Takes an 'action' instances and creates new instance of it
and all produced target. The rule-name and properties are set
to 'new-rule-name' and 'new-properties', if those are specified.
Returns the cloned action."""
if __debug__:
from .targets import ProjectTarget
assert isinstance(action, Action)
assert isinstance(new_project, ProjectTarget)
assert isinstance(new_action_name, basestring)
assert isinstance(new_properties, property_set.PropertySet)
if not new_action_name:
new_action_name = action.action_name()
if not new_properties:
new_properties = action.properties()
cloned_action = action.__class__(action.manager_, action.sources(), new_action_name,
new_properties)
cloned_targets = []
for target in action.targets():
n = target.name()
# Don't modify the name of the produced targets. Strip the directory f
cloned_target = FileTarget(n, target.type(), new_project,
cloned_action, exact=True)
d = target.dependencies()
if d:
cloned_target.depends(d)
cloned_target.root(target.root())
cloned_target.creating_subvariant(target.creating_subvariant())
cloned_targets.append(cloned_target)
return cloned_action | python | def clone_action (action, new_project, new_action_name, new_properties):
"""Takes an 'action' instances and creates new instance of it
and all produced target. The rule-name and properties are set
to 'new-rule-name' and 'new-properties', if those are specified.
Returns the cloned action."""
if __debug__:
from .targets import ProjectTarget
assert isinstance(action, Action)
assert isinstance(new_project, ProjectTarget)
assert isinstance(new_action_name, basestring)
assert isinstance(new_properties, property_set.PropertySet)
if not new_action_name:
new_action_name = action.action_name()
if not new_properties:
new_properties = action.properties()
cloned_action = action.__class__(action.manager_, action.sources(), new_action_name,
new_properties)
cloned_targets = []
for target in action.targets():
n = target.name()
# Don't modify the name of the produced targets. Strip the directory f
cloned_target = FileTarget(n, target.type(), new_project,
cloned_action, exact=True)
d = target.dependencies()
if d:
cloned_target.depends(d)
cloned_target.root(target.root())
cloned_target.creating_subvariant(target.creating_subvariant())
cloned_targets.append(cloned_target)
return cloned_action | [
"def",
"clone_action",
"(",
"action",
",",
"new_project",
",",
"new_action_name",
",",
"new_properties",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"targets",
"import",
"ProjectTarget",
"assert",
"isinstance",
"(",
"action",
",",
"Action",
")",
"assert",
"isinstance",
"(",
"new_project",
",",
"ProjectTarget",
")",
"assert",
"isinstance",
"(",
"new_action_name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"new_properties",
",",
"property_set",
".",
"PropertySet",
")",
"if",
"not",
"new_action_name",
":",
"new_action_name",
"=",
"action",
".",
"action_name",
"(",
")",
"if",
"not",
"new_properties",
":",
"new_properties",
"=",
"action",
".",
"properties",
"(",
")",
"cloned_action",
"=",
"action",
".",
"__class__",
"(",
"action",
".",
"manager_",
",",
"action",
".",
"sources",
"(",
")",
",",
"new_action_name",
",",
"new_properties",
")",
"cloned_targets",
"=",
"[",
"]",
"for",
"target",
"in",
"action",
".",
"targets",
"(",
")",
":",
"n",
"=",
"target",
".",
"name",
"(",
")",
"# Don't modify the name of the produced targets. Strip the directory f",
"cloned_target",
"=",
"FileTarget",
"(",
"n",
",",
"target",
".",
"type",
"(",
")",
",",
"new_project",
",",
"cloned_action",
",",
"exact",
"=",
"True",
")",
"d",
"=",
"target",
".",
"dependencies",
"(",
")",
"if",
"d",
":",
"cloned_target",
".",
"depends",
"(",
"d",
")",
"cloned_target",
".",
"root",
"(",
"target",
".",
"root",
"(",
")",
")",
"cloned_target",
".",
"creating_subvariant",
"(",
"target",
".",
"creating_subvariant",
"(",
")",
")",
"cloned_targets",
".",
"append",
"(",
"cloned_target",
")",
"return",
"cloned_action"
] | Takes an 'action' instances and creates new instance of it
and all produced target. The rule-name and properties are set
to 'new-rule-name' and 'new-properties', if those are specified.
Returns the cloned action. | [
"Takes",
"an",
"action",
"instances",
"and",
"creates",
"new",
"instance",
"of",
"it",
"and",
"all",
"produced",
"target",
".",
"The",
"rule",
"-",
"name",
"and",
"properties",
"are",
"set",
"to",
"new",
"-",
"rule",
"-",
"name",
"and",
"new",
"-",
"properties",
"if",
"those",
"are",
"specified",
".",
"Returns",
"the",
"cloned",
"action",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L998-L1034 |
29,411 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | VirtualTargetRegistry.register | def register (self, target):
""" Registers a new virtual target. Checks if there's already registered target, with the same
name, type, project and subvariant properties, and also with the same sources
and equal action. If such target is found it is retured and 'target' is not registered.
Otherwise, 'target' is registered and returned.
"""
assert isinstance(target, VirtualTarget)
if target.path():
signature = target.path() + "-" + target.name()
else:
signature = "-" + target.name()
result = None
if signature not in self.cache_:
self.cache_ [signature] = []
for t in self.cache_ [signature]:
a1 = t.action ()
a2 = target.action ()
# TODO: why are we checking for not result?
if not result:
if not a1 and not a2:
result = t
else:
if a1 and a2 and a1.action_name () == a2.action_name () and a1.sources () == a2.sources ():
ps1 = a1.properties ()
ps2 = a2.properties ()
p1 = ps1.base () + ps1.free () +\
b2.util.set.difference(ps1.dependency(), ps1.incidental())
p2 = ps2.base () + ps2.free () +\
b2.util.set.difference(ps2.dependency(), ps2.incidental())
if p1 == p2:
result = t
if not result:
self.cache_ [signature].append (target)
result = target
# TODO: Don't append if we found pre-existing target?
self.recent_targets_.append(result)
self.all_targets_.append(result)
return result | python | def register (self, target):
""" Registers a new virtual target. Checks if there's already registered target, with the same
name, type, project and subvariant properties, and also with the same sources
and equal action. If such target is found it is retured and 'target' is not registered.
Otherwise, 'target' is registered and returned.
"""
assert isinstance(target, VirtualTarget)
if target.path():
signature = target.path() + "-" + target.name()
else:
signature = "-" + target.name()
result = None
if signature not in self.cache_:
self.cache_ [signature] = []
for t in self.cache_ [signature]:
a1 = t.action ()
a2 = target.action ()
# TODO: why are we checking for not result?
if not result:
if not a1 and not a2:
result = t
else:
if a1 and a2 and a1.action_name () == a2.action_name () and a1.sources () == a2.sources ():
ps1 = a1.properties ()
ps2 = a2.properties ()
p1 = ps1.base () + ps1.free () +\
b2.util.set.difference(ps1.dependency(), ps1.incidental())
p2 = ps2.base () + ps2.free () +\
b2.util.set.difference(ps2.dependency(), ps2.incidental())
if p1 == p2:
result = t
if not result:
self.cache_ [signature].append (target)
result = target
# TODO: Don't append if we found pre-existing target?
self.recent_targets_.append(result)
self.all_targets_.append(result)
return result | [
"def",
"register",
"(",
"self",
",",
"target",
")",
":",
"assert",
"isinstance",
"(",
"target",
",",
"VirtualTarget",
")",
"if",
"target",
".",
"path",
"(",
")",
":",
"signature",
"=",
"target",
".",
"path",
"(",
")",
"+",
"\"-\"",
"+",
"target",
".",
"name",
"(",
")",
"else",
":",
"signature",
"=",
"\"-\"",
"+",
"target",
".",
"name",
"(",
")",
"result",
"=",
"None",
"if",
"signature",
"not",
"in",
"self",
".",
"cache_",
":",
"self",
".",
"cache_",
"[",
"signature",
"]",
"=",
"[",
"]",
"for",
"t",
"in",
"self",
".",
"cache_",
"[",
"signature",
"]",
":",
"a1",
"=",
"t",
".",
"action",
"(",
")",
"a2",
"=",
"target",
".",
"action",
"(",
")",
"# TODO: why are we checking for not result?",
"if",
"not",
"result",
":",
"if",
"not",
"a1",
"and",
"not",
"a2",
":",
"result",
"=",
"t",
"else",
":",
"if",
"a1",
"and",
"a2",
"and",
"a1",
".",
"action_name",
"(",
")",
"==",
"a2",
".",
"action_name",
"(",
")",
"and",
"a1",
".",
"sources",
"(",
")",
"==",
"a2",
".",
"sources",
"(",
")",
":",
"ps1",
"=",
"a1",
".",
"properties",
"(",
")",
"ps2",
"=",
"a2",
".",
"properties",
"(",
")",
"p1",
"=",
"ps1",
".",
"base",
"(",
")",
"+",
"ps1",
".",
"free",
"(",
")",
"+",
"b2",
".",
"util",
".",
"set",
".",
"difference",
"(",
"ps1",
".",
"dependency",
"(",
")",
",",
"ps1",
".",
"incidental",
"(",
")",
")",
"p2",
"=",
"ps2",
".",
"base",
"(",
")",
"+",
"ps2",
".",
"free",
"(",
")",
"+",
"b2",
".",
"util",
".",
"set",
".",
"difference",
"(",
"ps2",
".",
"dependency",
"(",
")",
",",
"ps2",
".",
"incidental",
"(",
")",
")",
"if",
"p1",
"==",
"p2",
":",
"result",
"=",
"t",
"if",
"not",
"result",
":",
"self",
".",
"cache_",
"[",
"signature",
"]",
".",
"append",
"(",
"target",
")",
"result",
"=",
"target",
"# TODO: Don't append if we found pre-existing target?",
"self",
".",
"recent_targets_",
".",
"append",
"(",
"result",
")",
"self",
".",
"all_targets_",
".",
"append",
"(",
"result",
")",
"return",
"result"
] | Registers a new virtual target. Checks if there's already registered target, with the same
name, type, project and subvariant properties, and also with the same sources
and equal action. If such target is found it is retured and 'target' is not registered.
Otherwise, 'target' is registered and returned. | [
"Registers",
"a",
"new",
"virtual",
"target",
".",
"Checks",
"if",
"there",
"s",
"already",
"registered",
"target",
"with",
"the",
"same",
"name",
"type",
"project",
"and",
"subvariant",
"properties",
"and",
"also",
"with",
"the",
"same",
"sources",
"and",
"equal",
"action",
".",
"If",
"such",
"target",
"is",
"found",
"it",
"is",
"retured",
"and",
"target",
"is",
"not",
"registered",
".",
"Otherwise",
"target",
"is",
"registered",
"and",
"returned",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L107-L150 |
29,412 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | VirtualTarget.depends | def depends (self, d):
""" Adds additional instances of 'VirtualTarget' that this
one depends on.
"""
self.dependencies_ = unique (self.dependencies_ + d).sort () | python | def depends (self, d):
""" Adds additional instances of 'VirtualTarget' that this
one depends on.
"""
self.dependencies_ = unique (self.dependencies_ + d).sort () | [
"def",
"depends",
"(",
"self",
",",
"d",
")",
":",
"self",
".",
"dependencies_",
"=",
"unique",
"(",
"self",
".",
"dependencies_",
"+",
"d",
")",
".",
"sort",
"(",
")"
] | Adds additional instances of 'VirtualTarget' that this
one depends on. | [
"Adds",
"additional",
"instances",
"of",
"VirtualTarget",
"that",
"this",
"one",
"depends",
"on",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L299-L303 |
29,413 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | VirtualTarget.actualize | def actualize (self, scanner = None):
""" Generates all the actual targets and sets up build actions for
this target.
If 'scanner' is specified, creates an additional target
with the same location as actual target, which will depend on the
actual target and be associated with 'scanner'. That additional
target is returned. See the docs (#dependency_scanning) for rationale.
Target must correspond to a file if 'scanner' is specified.
If scanner is not specified, then actual target is returned.
"""
if __debug__:
from .scanner import Scanner
assert scanner is None or isinstance(scanner, Scanner)
actual_name = self.actualize_no_scanner ()
if self.always_:
bjam.call("ALWAYS", actual_name)
if not scanner:
return actual_name
else:
# Add the scanner instance to the grist for name.
g = '-'.join ([ungrist(get_grist(actual_name)), str(id(scanner))])
name = replace_grist (actual_name, '<' + g + '>')
if name not in self.made_:
self.made_ [name] = True
self.project_.manager ().engine ().add_dependency (name, actual_name)
self.actualize_location (name)
self.project_.manager ().scanners ().install (scanner, name, str (self))
return name | python | def actualize (self, scanner = None):
""" Generates all the actual targets and sets up build actions for
this target.
If 'scanner' is specified, creates an additional target
with the same location as actual target, which will depend on the
actual target and be associated with 'scanner'. That additional
target is returned. See the docs (#dependency_scanning) for rationale.
Target must correspond to a file if 'scanner' is specified.
If scanner is not specified, then actual target is returned.
"""
if __debug__:
from .scanner import Scanner
assert scanner is None or isinstance(scanner, Scanner)
actual_name = self.actualize_no_scanner ()
if self.always_:
bjam.call("ALWAYS", actual_name)
if not scanner:
return actual_name
else:
# Add the scanner instance to the grist for name.
g = '-'.join ([ungrist(get_grist(actual_name)), str(id(scanner))])
name = replace_grist (actual_name, '<' + g + '>')
if name not in self.made_:
self.made_ [name] = True
self.project_.manager ().engine ().add_dependency (name, actual_name)
self.actualize_location (name)
self.project_.manager ().scanners ().install (scanner, name, str (self))
return name | [
"def",
"actualize",
"(",
"self",
",",
"scanner",
"=",
"None",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"scanner",
"import",
"Scanner",
"assert",
"scanner",
"is",
"None",
"or",
"isinstance",
"(",
"scanner",
",",
"Scanner",
")",
"actual_name",
"=",
"self",
".",
"actualize_no_scanner",
"(",
")",
"if",
"self",
".",
"always_",
":",
"bjam",
".",
"call",
"(",
"\"ALWAYS\"",
",",
"actual_name",
")",
"if",
"not",
"scanner",
":",
"return",
"actual_name",
"else",
":",
"# Add the scanner instance to the grist for name.",
"g",
"=",
"'-'",
".",
"join",
"(",
"[",
"ungrist",
"(",
"get_grist",
"(",
"actual_name",
")",
")",
",",
"str",
"(",
"id",
"(",
"scanner",
")",
")",
"]",
")",
"name",
"=",
"replace_grist",
"(",
"actual_name",
",",
"'<'",
"+",
"g",
"+",
"'>'",
")",
"if",
"name",
"not",
"in",
"self",
".",
"made_",
":",
"self",
".",
"made_",
"[",
"name",
"]",
"=",
"True",
"self",
".",
"project_",
".",
"manager",
"(",
")",
".",
"engine",
"(",
")",
".",
"add_dependency",
"(",
"name",
",",
"actual_name",
")",
"self",
".",
"actualize_location",
"(",
"name",
")",
"self",
".",
"project_",
".",
"manager",
"(",
")",
".",
"scanners",
"(",
")",
".",
"install",
"(",
"scanner",
",",
"name",
",",
"str",
"(",
"self",
")",
")",
"return",
"name"
] | Generates all the actual targets and sets up build actions for
this target.
If 'scanner' is specified, creates an additional target
with the same location as actual target, which will depend on the
actual target and be associated with 'scanner'. That additional
target is returned. See the docs (#dependency_scanning) for rationale.
Target must correspond to a file if 'scanner' is specified.
If scanner is not specified, then actual target is returned. | [
"Generates",
"all",
"the",
"actual",
"targets",
"and",
"sets",
"up",
"build",
"actions",
"for",
"this",
"target",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L311-L349 |
29,414 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | AbstractFileTarget.set_path | def set_path (self, path):
""" Sets the path. When generating target name, it will override any path
computation from properties.
"""
assert isinstance(path, basestring)
self.path_ = os.path.normpath(path) | python | def set_path (self, path):
""" Sets the path. When generating target name, it will override any path
computation from properties.
"""
assert isinstance(path, basestring)
self.path_ = os.path.normpath(path) | [
"def",
"set_path",
"(",
"self",
",",
"path",
")",
":",
"assert",
"isinstance",
"(",
"path",
",",
"basestring",
")",
"self",
".",
"path_",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")"
] | Sets the path. When generating target name, it will override any path
computation from properties. | [
"Sets",
"the",
"path",
".",
"When",
"generating",
"target",
"name",
"it",
"will",
"override",
"any",
"path",
"computation",
"from",
"properties",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L425-L430 |
29,415 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | AbstractFileTarget.grist | def grist (self):
"""Helper to 'actual_name', above. Compute unique prefix used to distinguish
this target from other targets with the same name which create different
file.
"""
# Depending on target, there may be different approaches to generating
# unique prefixes. We'll generate prefixes in the form
# <one letter approach code> <the actual prefix>
path = self.path ()
if path:
# The target will be generated to a known path. Just use the path
# for identification, since path is as unique as it can get.
return 'p' + path
else:
# File is either source, which will be searched for, or is not a file at
# all. Use the location of project for distinguishing.
project_location = self.project_.get ('location')
path_components = b2.util.path.split(project_location)
location_grist = '!'.join (path_components)
if self.action_:
ps = self.action_.properties ()
property_grist = ps.as_path ()
# 'property_grist' can be empty when 'ps' is an empty
# property set.
if property_grist:
location_grist = location_grist + '/' + property_grist
return 'l' + location_grist | python | def grist (self):
"""Helper to 'actual_name', above. Compute unique prefix used to distinguish
this target from other targets with the same name which create different
file.
"""
# Depending on target, there may be different approaches to generating
# unique prefixes. We'll generate prefixes in the form
# <one letter approach code> <the actual prefix>
path = self.path ()
if path:
# The target will be generated to a known path. Just use the path
# for identification, since path is as unique as it can get.
return 'p' + path
else:
# File is either source, which will be searched for, or is not a file at
# all. Use the location of project for distinguishing.
project_location = self.project_.get ('location')
path_components = b2.util.path.split(project_location)
location_grist = '!'.join (path_components)
if self.action_:
ps = self.action_.properties ()
property_grist = ps.as_path ()
# 'property_grist' can be empty when 'ps' is an empty
# property set.
if property_grist:
location_grist = location_grist + '/' + property_grist
return 'l' + location_grist | [
"def",
"grist",
"(",
"self",
")",
":",
"# Depending on target, there may be different approaches to generating",
"# unique prefixes. We'll generate prefixes in the form",
"# <one letter approach code> <the actual prefix>",
"path",
"=",
"self",
".",
"path",
"(",
")",
"if",
"path",
":",
"# The target will be generated to a known path. Just use the path",
"# for identification, since path is as unique as it can get.",
"return",
"'p'",
"+",
"path",
"else",
":",
"# File is either source, which will be searched for, or is not a file at",
"# all. Use the location of project for distinguishing.",
"project_location",
"=",
"self",
".",
"project_",
".",
"get",
"(",
"'location'",
")",
"path_components",
"=",
"b2",
".",
"util",
".",
"path",
".",
"split",
"(",
"project_location",
")",
"location_grist",
"=",
"'!'",
".",
"join",
"(",
"path_components",
")",
"if",
"self",
".",
"action_",
":",
"ps",
"=",
"self",
".",
"action_",
".",
"properties",
"(",
")",
"property_grist",
"=",
"ps",
".",
"as_path",
"(",
")",
"# 'property_grist' can be empty when 'ps' is an empty",
"# property set.",
"if",
"property_grist",
":",
"location_grist",
"=",
"location_grist",
"+",
"'/'",
"+",
"property_grist",
"return",
"'l'",
"+",
"location_grist"
] | Helper to 'actual_name', above. Compute unique prefix used to distinguish
this target from other targets with the same name which create different
file. | [
"Helper",
"to",
"actual_name",
"above",
".",
"Compute",
"unique",
"prefix",
"used",
"to",
"distinguish",
"this",
"target",
"from",
"other",
"targets",
"with",
"the",
"same",
"name",
"which",
"create",
"different",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L500-L530 |
29,416 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | FileTarget.path | def path (self):
""" Returns the directory for this target.
"""
if not self.path_:
if self.action_:
p = self.action_.properties ()
(target_path, relative_to_build_dir) = p.target_path ()
if relative_to_build_dir:
# Indicates that the path is relative to
# build dir.
target_path = os.path.join (self.project_.build_dir (), target_path)
# Store the computed path, so that it's not recomputed
# any more
self.path_ = target_path
return os.path.normpath(self.path_) | python | def path (self):
""" Returns the directory for this target.
"""
if not self.path_:
if self.action_:
p = self.action_.properties ()
(target_path, relative_to_build_dir) = p.target_path ()
if relative_to_build_dir:
# Indicates that the path is relative to
# build dir.
target_path = os.path.join (self.project_.build_dir (), target_path)
# Store the computed path, so that it's not recomputed
# any more
self.path_ = target_path
return os.path.normpath(self.path_) | [
"def",
"path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"path_",
":",
"if",
"self",
".",
"action_",
":",
"p",
"=",
"self",
".",
"action_",
".",
"properties",
"(",
")",
"(",
"target_path",
",",
"relative_to_build_dir",
")",
"=",
"p",
".",
"target_path",
"(",
")",
"if",
"relative_to_build_dir",
":",
"# Indicates that the path is relative to",
"# build dir.",
"target_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project_",
".",
"build_dir",
"(",
")",
",",
"target_path",
")",
"# Store the computed path, so that it's not recomputed",
"# any more",
"self",
".",
"path_",
"=",
"target_path",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"self",
".",
"path_",
")"
] | Returns the directory for this target. | [
"Returns",
"the",
"directory",
"for",
"this",
"target",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L727-L744 |
29,417 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | Action.actualize | def actualize (self):
""" Generates actual build instructions.
"""
if self.actualized_:
return
self.actualized_ = True
ps = self.properties ()
properties = self.adjust_properties (ps)
actual_targets = []
for i in self.targets ():
actual_targets.append (i.actualize ())
self.actualize_sources (self.sources (), properties)
self.engine_.add_dependency (actual_targets, self.actual_sources_ + self.dependency_only_sources_)
# FIXME: check the comment below. Was self.action_name_ [1]
# Action name can include additional rule arguments, which should not
# be passed to 'set-target-variables'.
# FIXME: breaking circular dependency
import toolset
toolset.set_target_variables (self.manager_, self.action_name_, actual_targets, properties)
engine = self.manager_.engine ()
# FIXME: this is supposed to help --out-xml option, but we don't
# implement that now, and anyway, we should handle it in Python,
# not but putting variables on bjam-level targets.
bjam.call("set-target-variable", actual_targets, ".action", repr(self))
self.manager_.engine ().set_update_action (self.action_name_, actual_targets, self.actual_sources_,
properties)
# Since we set up creating action here, we also set up
# action for cleaning up
self.manager_.engine ().set_update_action ('common.Clean', 'clean-all',
actual_targets)
return actual_targets | python | def actualize (self):
""" Generates actual build instructions.
"""
if self.actualized_:
return
self.actualized_ = True
ps = self.properties ()
properties = self.adjust_properties (ps)
actual_targets = []
for i in self.targets ():
actual_targets.append (i.actualize ())
self.actualize_sources (self.sources (), properties)
self.engine_.add_dependency (actual_targets, self.actual_sources_ + self.dependency_only_sources_)
# FIXME: check the comment below. Was self.action_name_ [1]
# Action name can include additional rule arguments, which should not
# be passed to 'set-target-variables'.
# FIXME: breaking circular dependency
import toolset
toolset.set_target_variables (self.manager_, self.action_name_, actual_targets, properties)
engine = self.manager_.engine ()
# FIXME: this is supposed to help --out-xml option, but we don't
# implement that now, and anyway, we should handle it in Python,
# not but putting variables on bjam-level targets.
bjam.call("set-target-variable", actual_targets, ".action", repr(self))
self.manager_.engine ().set_update_action (self.action_name_, actual_targets, self.actual_sources_,
properties)
# Since we set up creating action here, we also set up
# action for cleaning up
self.manager_.engine ().set_update_action ('common.Clean', 'clean-all',
actual_targets)
return actual_targets | [
"def",
"actualize",
"(",
"self",
")",
":",
"if",
"self",
".",
"actualized_",
":",
"return",
"self",
".",
"actualized_",
"=",
"True",
"ps",
"=",
"self",
".",
"properties",
"(",
")",
"properties",
"=",
"self",
".",
"adjust_properties",
"(",
"ps",
")",
"actual_targets",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"targets",
"(",
")",
":",
"actual_targets",
".",
"append",
"(",
"i",
".",
"actualize",
"(",
")",
")",
"self",
".",
"actualize_sources",
"(",
"self",
".",
"sources",
"(",
")",
",",
"properties",
")",
"self",
".",
"engine_",
".",
"add_dependency",
"(",
"actual_targets",
",",
"self",
".",
"actual_sources_",
"+",
"self",
".",
"dependency_only_sources_",
")",
"# FIXME: check the comment below. Was self.action_name_ [1]",
"# Action name can include additional rule arguments, which should not",
"# be passed to 'set-target-variables'.",
"# FIXME: breaking circular dependency",
"import",
"toolset",
"toolset",
".",
"set_target_variables",
"(",
"self",
".",
"manager_",
",",
"self",
".",
"action_name_",
",",
"actual_targets",
",",
"properties",
")",
"engine",
"=",
"self",
".",
"manager_",
".",
"engine",
"(",
")",
"# FIXME: this is supposed to help --out-xml option, but we don't",
"# implement that now, and anyway, we should handle it in Python,",
"# not but putting variables on bjam-level targets.",
"bjam",
".",
"call",
"(",
"\"set-target-variable\"",
",",
"actual_targets",
",",
"\".action\"",
",",
"repr",
"(",
"self",
")",
")",
"self",
".",
"manager_",
".",
"engine",
"(",
")",
".",
"set_update_action",
"(",
"self",
".",
"action_name_",
",",
"actual_targets",
",",
"self",
".",
"actual_sources_",
",",
"properties",
")",
"# Since we set up creating action here, we also set up",
"# action for cleaning up",
"self",
".",
"manager_",
".",
"engine",
"(",
")",
".",
"set_update_action",
"(",
"'common.Clean'",
",",
"'clean-all'",
",",
"actual_targets",
")",
"return",
"actual_targets"
] | Generates actual build instructions. | [
"Generates",
"actual",
"build",
"instructions",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L818-L861 |
29,418 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | Action.actualize_source_type | def actualize_source_type (self, sources, prop_set):
""" Helper for 'actualize_sources'.
For each passed source, actualizes it with the appropriate scanner.
Returns the actualized virtual targets.
"""
assert is_iterable_typed(sources, VirtualTarget)
assert isinstance(prop_set, property_set.PropertySet)
result = []
for i in sources:
scanner = None
# FIXME: what's this?
# if isinstance (i, str):
# i = self.manager_.get_object (i)
if i.type ():
scanner = b2.build.type.get_scanner (i.type (), prop_set)
r = i.actualize (scanner)
result.append (r)
return result | python | def actualize_source_type (self, sources, prop_set):
""" Helper for 'actualize_sources'.
For each passed source, actualizes it with the appropriate scanner.
Returns the actualized virtual targets.
"""
assert is_iterable_typed(sources, VirtualTarget)
assert isinstance(prop_set, property_set.PropertySet)
result = []
for i in sources:
scanner = None
# FIXME: what's this?
# if isinstance (i, str):
# i = self.manager_.get_object (i)
if i.type ():
scanner = b2.build.type.get_scanner (i.type (), prop_set)
r = i.actualize (scanner)
result.append (r)
return result | [
"def",
"actualize_source_type",
"(",
"self",
",",
"sources",
",",
"prop_set",
")",
":",
"assert",
"is_iterable_typed",
"(",
"sources",
",",
"VirtualTarget",
")",
"assert",
"isinstance",
"(",
"prop_set",
",",
"property_set",
".",
"PropertySet",
")",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"sources",
":",
"scanner",
"=",
"None",
"# FIXME: what's this?",
"# if isinstance (i, str):",
"# i = self.manager_.get_object (i)",
"if",
"i",
".",
"type",
"(",
")",
":",
"scanner",
"=",
"b2",
".",
"build",
".",
"type",
".",
"get_scanner",
"(",
"i",
".",
"type",
"(",
")",
",",
"prop_set",
")",
"r",
"=",
"i",
".",
"actualize",
"(",
"scanner",
")",
"result",
".",
"append",
"(",
"r",
")",
"return",
"result"
] | Helper for 'actualize_sources'.
For each passed source, actualizes it with the appropriate scanner.
Returns the actualized virtual targets. | [
"Helper",
"for",
"actualize_sources",
".",
"For",
"each",
"passed",
"source",
"actualizes",
"it",
"with",
"the",
"appropriate",
"scanner",
".",
"Returns",
"the",
"actualized",
"virtual",
"targets",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L863-L884 |
29,419 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py | Subvariant.all_referenced_targets | def all_referenced_targets(self, result):
"""Returns all targets referenced by this subvariant,
either directly or indirectly, and either as sources,
or as dependency properties. Targets referred with
dependency property are returned a properties, not targets."""
if __debug__:
from .property import Property
assert is_iterable_typed(result, (VirtualTarget, Property))
# Find directly referenced targets.
deps = self.build_properties().dependency()
all_targets = self.sources_ + deps
# Find other subvariants.
r = []
for e in all_targets:
if not e in result:
result.add(e)
if isinstance(e, property.Property):
t = e.value
else:
t = e
# FIXME: how can this be?
cs = t.creating_subvariant()
if cs:
r.append(cs)
r = unique(r)
for s in r:
if s != self:
s.all_referenced_targets(result) | python | def all_referenced_targets(self, result):
"""Returns all targets referenced by this subvariant,
either directly or indirectly, and either as sources,
or as dependency properties. Targets referred with
dependency property are returned a properties, not targets."""
if __debug__:
from .property import Property
assert is_iterable_typed(result, (VirtualTarget, Property))
# Find directly referenced targets.
deps = self.build_properties().dependency()
all_targets = self.sources_ + deps
# Find other subvariants.
r = []
for e in all_targets:
if not e in result:
result.add(e)
if isinstance(e, property.Property):
t = e.value
else:
t = e
# FIXME: how can this be?
cs = t.creating_subvariant()
if cs:
r.append(cs)
r = unique(r)
for s in r:
if s != self:
s.all_referenced_targets(result) | [
"def",
"all_referenced_targets",
"(",
"self",
",",
"result",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"property",
"import",
"Property",
"assert",
"is_iterable_typed",
"(",
"result",
",",
"(",
"VirtualTarget",
",",
"Property",
")",
")",
"# Find directly referenced targets.",
"deps",
"=",
"self",
".",
"build_properties",
"(",
")",
".",
"dependency",
"(",
")",
"all_targets",
"=",
"self",
".",
"sources_",
"+",
"deps",
"# Find other subvariants.",
"r",
"=",
"[",
"]",
"for",
"e",
"in",
"all_targets",
":",
"if",
"not",
"e",
"in",
"result",
":",
"result",
".",
"add",
"(",
"e",
")",
"if",
"isinstance",
"(",
"e",
",",
"property",
".",
"Property",
")",
":",
"t",
"=",
"e",
".",
"value",
"else",
":",
"t",
"=",
"e",
"# FIXME: how can this be?",
"cs",
"=",
"t",
".",
"creating_subvariant",
"(",
")",
"if",
"cs",
":",
"r",
".",
"append",
"(",
"cs",
")",
"r",
"=",
"unique",
"(",
"r",
")",
"for",
"s",
"in",
"r",
":",
"if",
"s",
"!=",
"self",
":",
"s",
".",
"all_referenced_targets",
"(",
"result",
")"
] | Returns all targets referenced by this subvariant,
either directly or indirectly, and either as sources,
or as dependency properties. Targets referred with
dependency property are returned a properties, not targets. | [
"Returns",
"all",
"targets",
"referenced",
"by",
"this",
"subvariant",
"either",
"directly",
"or",
"indirectly",
"and",
"either",
"as",
"sources",
"or",
"as",
"dependency",
"properties",
".",
"Targets",
"referred",
"with",
"dependency",
"property",
"are",
"returned",
"a",
"properties",
"not",
"targets",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L1099-L1128 |
29,420 | apple/turicreate | src/unity/python/turicreate/meta/asttools/__init__.py | cmp_ast | def cmp_ast(node1, node2):
'''
Compare if two nodes are equal.
'''
if type(node1) != type(node2):
return False
if isinstance(node1, (list, tuple)):
if len(node1) != len(node2):
return False
for left, right in zip(node1, node2):
if not cmp_ast(left, right):
return False
elif isinstance(node1, ast.AST):
for field in node1._fields:
left = getattr(node1, field, Undedined)
right = getattr(node2, field, Undedined)
if not cmp_ast(left, right):
return False
else:
return node1 == node2
return True | python | def cmp_ast(node1, node2):
'''
Compare if two nodes are equal.
'''
if type(node1) != type(node2):
return False
if isinstance(node1, (list, tuple)):
if len(node1) != len(node2):
return False
for left, right in zip(node1, node2):
if not cmp_ast(left, right):
return False
elif isinstance(node1, ast.AST):
for field in node1._fields:
left = getattr(node1, field, Undedined)
right = getattr(node2, field, Undedined)
if not cmp_ast(left, right):
return False
else:
return node1 == node2
return True | [
"def",
"cmp_ast",
"(",
"node1",
",",
"node2",
")",
":",
"if",
"type",
"(",
"node1",
")",
"!=",
"type",
"(",
"node2",
")",
":",
"return",
"False",
"if",
"isinstance",
"(",
"node1",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"len",
"(",
"node1",
")",
"!=",
"len",
"(",
"node2",
")",
":",
"return",
"False",
"for",
"left",
",",
"right",
"in",
"zip",
"(",
"node1",
",",
"node2",
")",
":",
"if",
"not",
"cmp_ast",
"(",
"left",
",",
"right",
")",
":",
"return",
"False",
"elif",
"isinstance",
"(",
"node1",
",",
"ast",
".",
"AST",
")",
":",
"for",
"field",
"in",
"node1",
".",
"_fields",
":",
"left",
"=",
"getattr",
"(",
"node1",
",",
"field",
",",
"Undedined",
")",
"right",
"=",
"getattr",
"(",
"node2",
",",
"field",
",",
"Undedined",
")",
"if",
"not",
"cmp_ast",
"(",
"left",
",",
"right",
")",
":",
"return",
"False",
"else",
":",
"return",
"node1",
"==",
"node2",
"return",
"True"
] | Compare if two nodes are equal. | [
"Compare",
"if",
"two",
"nodes",
"are",
"equal",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/__init__.py#L23-L49 |
29,421 | apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/boost_mpl_preprocess.py | create_more_container_files | def create_more_container_files(sourceDir, suffix, maxElements, containers, containers2):
"""Creates additional files for the individual MPL-containers."""
# Create files for each MPL-container with 20 to 'maxElements' elements
# which will be used during generation.
for container in containers:
for i in range(20, maxElements, 10):
# Create copy of "template"-file.
newFile = os.path.join( sourceDir, container, container + str(i+10) + suffix )
shutil.copyfile( os.path.join( sourceDir, container, container + "20" + suffix ), newFile )
# Adjust copy of "template"-file accordingly.
for line in fileinput.input( newFile, inplace=1, mode="rU" ):
line = re.sub(r'20', '%TWENTY%', line.rstrip())
line = re.sub(r'11', '%ELEVEN%', line.rstrip())
line = re.sub(r'10(?![0-9])', '%TEN%', line.rstrip())
line = re.sub(r'%TWENTY%', re.escape(str(i+10)), line.rstrip())
line = re.sub(r'%ELEVEN%', re.escape(str(i + 1)), line.rstrip())
line = re.sub(r'%TEN%', re.escape(str(i)), line.rstrip())
print(line)
for container in containers2:
for i in range(20, maxElements, 10):
# Create copy of "template"-file.
newFile = os.path.join( sourceDir, container, container + str(i+10) + "_c" + suffix )
shutil.copyfile( os.path.join( sourceDir, container, container + "20_c" + suffix ), newFile )
# Adjust copy of "template"-file accordingly.
for line in fileinput.input( newFile, inplace=1, mode="rU" ):
line = re.sub(r'20', '%TWENTY%', line.rstrip())
line = re.sub(r'11', '%ELEVEN%', line.rstrip())
line = re.sub(r'10(?![0-9])', '%TEN%', line.rstrip())
line = re.sub(r'%TWENTY%', re.escape(str(i+10)), line.rstrip())
line = re.sub(r'%ELEVEN%', re.escape(str(i + 1)), line.rstrip())
line = re.sub(r'%TEN%', re.escape(str(i)), line.rstrip())
print(line) | python | def create_more_container_files(sourceDir, suffix, maxElements, containers, containers2):
"""Creates additional files for the individual MPL-containers."""
# Create files for each MPL-container with 20 to 'maxElements' elements
# which will be used during generation.
for container in containers:
for i in range(20, maxElements, 10):
# Create copy of "template"-file.
newFile = os.path.join( sourceDir, container, container + str(i+10) + suffix )
shutil.copyfile( os.path.join( sourceDir, container, container + "20" + suffix ), newFile )
# Adjust copy of "template"-file accordingly.
for line in fileinput.input( newFile, inplace=1, mode="rU" ):
line = re.sub(r'20', '%TWENTY%', line.rstrip())
line = re.sub(r'11', '%ELEVEN%', line.rstrip())
line = re.sub(r'10(?![0-9])', '%TEN%', line.rstrip())
line = re.sub(r'%TWENTY%', re.escape(str(i+10)), line.rstrip())
line = re.sub(r'%ELEVEN%', re.escape(str(i + 1)), line.rstrip())
line = re.sub(r'%TEN%', re.escape(str(i)), line.rstrip())
print(line)
for container in containers2:
for i in range(20, maxElements, 10):
# Create copy of "template"-file.
newFile = os.path.join( sourceDir, container, container + str(i+10) + "_c" + suffix )
shutil.copyfile( os.path.join( sourceDir, container, container + "20_c" + suffix ), newFile )
# Adjust copy of "template"-file accordingly.
for line in fileinput.input( newFile, inplace=1, mode="rU" ):
line = re.sub(r'20', '%TWENTY%', line.rstrip())
line = re.sub(r'11', '%ELEVEN%', line.rstrip())
line = re.sub(r'10(?![0-9])', '%TEN%', line.rstrip())
line = re.sub(r'%TWENTY%', re.escape(str(i+10)), line.rstrip())
line = re.sub(r'%ELEVEN%', re.escape(str(i + 1)), line.rstrip())
line = re.sub(r'%TEN%', re.escape(str(i)), line.rstrip())
print(line) | [
"def",
"create_more_container_files",
"(",
"sourceDir",
",",
"suffix",
",",
"maxElements",
",",
"containers",
",",
"containers2",
")",
":",
"# Create files for each MPL-container with 20 to 'maxElements' elements",
"# which will be used during generation.",
"for",
"container",
"in",
"containers",
":",
"for",
"i",
"in",
"range",
"(",
"20",
",",
"maxElements",
",",
"10",
")",
":",
"# Create copy of \"template\"-file.",
"newFile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sourceDir",
",",
"container",
",",
"container",
"+",
"str",
"(",
"i",
"+",
"10",
")",
"+",
"suffix",
")",
"shutil",
".",
"copyfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sourceDir",
",",
"container",
",",
"container",
"+",
"\"20\"",
"+",
"suffix",
")",
",",
"newFile",
")",
"# Adjust copy of \"template\"-file accordingly.",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"newFile",
",",
"inplace",
"=",
"1",
",",
"mode",
"=",
"\"rU\"",
")",
":",
"line",
"=",
"re",
".",
"sub",
"(",
"r'20'",
",",
"'%TWENTY%'",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"r'11'",
",",
"'%ELEVEN%'",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"r'10(?![0-9])'",
",",
"'%TEN%'",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"r'%TWENTY%'",
",",
"re",
".",
"escape",
"(",
"str",
"(",
"i",
"+",
"10",
")",
")",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"r'%ELEVEN%'",
",",
"re",
".",
"escape",
"(",
"str",
"(",
"i",
"+",
"1",
")",
")",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"r'%TEN%'",
",",
"re",
".",
"escape",
"(",
"str",
"(",
"i",
")",
")",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"print",
"(",
"line",
")",
"for",
"container",
"in",
"containers2",
":",
"for",
"i",
"in",
"range",
"(",
"20",
",",
"maxElements",
",",
"10",
")",
":",
"# Create copy of \"template\"-file.",
"newFile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sourceDir",
",",
"container",
",",
"container",
"+",
"str",
"(",
"i",
"+",
"10",
")",
"+",
"\"_c\"",
"+",
"suffix",
")",
"shutil",
".",
"copyfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sourceDir",
",",
"container",
",",
"container",
"+",
"\"20_c\"",
"+",
"suffix",
")",
",",
"newFile",
")",
"# Adjust copy of \"template\"-file accordingly.",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"newFile",
",",
"inplace",
"=",
"1",
",",
"mode",
"=",
"\"rU\"",
")",
":",
"line",
"=",
"re",
".",
"sub",
"(",
"r'20'",
",",
"'%TWENTY%'",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"r'11'",
",",
"'%ELEVEN%'",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"r'10(?![0-9])'",
",",
"'%TEN%'",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"r'%TWENTY%'",
",",
"re",
".",
"escape",
"(",
"str",
"(",
"i",
"+",
"10",
")",
")",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"r'%ELEVEN%'",
",",
"re",
".",
"escape",
"(",
"str",
"(",
"i",
"+",
"1",
")",
")",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"r'%TEN%'",
",",
"re",
".",
"escape",
"(",
"str",
"(",
"i",
")",
")",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"print",
"(",
"line",
")"
] | Creates additional files for the individual MPL-containers. | [
"Creates",
"additional",
"files",
"for",
"the",
"individual",
"MPL",
"-",
"containers",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/boost_mpl_preprocess.py#L21-L53 |
29,422 | apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/boost_mpl_preprocess.py | create_input_for_numbered_sequences | def create_input_for_numbered_sequences(headerDir, sourceDir, containers, maxElements):
"""Creates additional source- and header-files for the numbered sequence MPL-containers."""
# Create additional container-list without "map".
containersWithoutMap = containers[:]
try:
containersWithoutMap.remove('map')
except ValueError:
# We can safely ignore if "map" is not contained in 'containers'!
pass
# Create header/source-files.
create_more_container_files(headerDir, ".hpp", maxElements, containers, containersWithoutMap)
create_more_container_files(sourceDir, ".cpp", maxElements, containers, containersWithoutMap) | python | def create_input_for_numbered_sequences(headerDir, sourceDir, containers, maxElements):
"""Creates additional source- and header-files for the numbered sequence MPL-containers."""
# Create additional container-list without "map".
containersWithoutMap = containers[:]
try:
containersWithoutMap.remove('map')
except ValueError:
# We can safely ignore if "map" is not contained in 'containers'!
pass
# Create header/source-files.
create_more_container_files(headerDir, ".hpp", maxElements, containers, containersWithoutMap)
create_more_container_files(sourceDir, ".cpp", maxElements, containers, containersWithoutMap) | [
"def",
"create_input_for_numbered_sequences",
"(",
"headerDir",
",",
"sourceDir",
",",
"containers",
",",
"maxElements",
")",
":",
"# Create additional container-list without \"map\".",
"containersWithoutMap",
"=",
"containers",
"[",
":",
"]",
"try",
":",
"containersWithoutMap",
".",
"remove",
"(",
"'map'",
")",
"except",
"ValueError",
":",
"# We can safely ignore if \"map\" is not contained in 'containers'!",
"pass",
"# Create header/source-files.",
"create_more_container_files",
"(",
"headerDir",
",",
"\".hpp\"",
",",
"maxElements",
",",
"containers",
",",
"containersWithoutMap",
")",
"create_more_container_files",
"(",
"sourceDir",
",",
"\".cpp\"",
",",
"maxElements",
",",
"containers",
",",
"containersWithoutMap",
")"
] | Creates additional source- and header-files for the numbered sequence MPL-containers. | [
"Creates",
"additional",
"source",
"-",
"and",
"header",
"-",
"files",
"for",
"the",
"numbered",
"sequence",
"MPL",
"-",
"containers",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/boost_mpl_preprocess.py#L56-L67 |
29,423 | apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/boost_mpl_preprocess.py | adjust_container_limits_for_variadic_sequences | def adjust_container_limits_for_variadic_sequences(headerDir, containers, maxElements):
"""Adjusts the limits of variadic sequence MPL-containers."""
for container in containers:
headerFile = os.path.join( headerDir, "limits", container + ".hpp" )
regexMatch = r'(define\s+BOOST_MPL_LIMIT_' + container.upper() + r'_SIZE\s+)[0-9]+'
regexReplace = r'\g<1>' + re.escape( str(maxElements) )
for line in fileinput.input( headerFile, inplace=1, mode="rU" ):
line = re.sub(regexMatch, regexReplace, line.rstrip())
print(line) | python | def adjust_container_limits_for_variadic_sequences(headerDir, containers, maxElements):
"""Adjusts the limits of variadic sequence MPL-containers."""
for container in containers:
headerFile = os.path.join( headerDir, "limits", container + ".hpp" )
regexMatch = r'(define\s+BOOST_MPL_LIMIT_' + container.upper() + r'_SIZE\s+)[0-9]+'
regexReplace = r'\g<1>' + re.escape( str(maxElements) )
for line in fileinput.input( headerFile, inplace=1, mode="rU" ):
line = re.sub(regexMatch, regexReplace, line.rstrip())
print(line) | [
"def",
"adjust_container_limits_for_variadic_sequences",
"(",
"headerDir",
",",
"containers",
",",
"maxElements",
")",
":",
"for",
"container",
"in",
"containers",
":",
"headerFile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"headerDir",
",",
"\"limits\"",
",",
"container",
"+",
"\".hpp\"",
")",
"regexMatch",
"=",
"r'(define\\s+BOOST_MPL_LIMIT_'",
"+",
"container",
".",
"upper",
"(",
")",
"+",
"r'_SIZE\\s+)[0-9]+'",
"regexReplace",
"=",
"r'\\g<1>'",
"+",
"re",
".",
"escape",
"(",
"str",
"(",
"maxElements",
")",
")",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"headerFile",
",",
"inplace",
"=",
"1",
",",
"mode",
"=",
"\"rU\"",
")",
":",
"line",
"=",
"re",
".",
"sub",
"(",
"regexMatch",
",",
"regexReplace",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"print",
"(",
"line",
")"
] | Adjusts the limits of variadic sequence MPL-containers. | [
"Adjusts",
"the",
"limits",
"of",
"variadic",
"sequence",
"MPL",
"-",
"containers",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/boost_mpl_preprocess.py#L70-L78 |
29,424 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py | NeuralNetworkBuilder.add_inner_product | def add_inner_product(self, name, W, b, input_channels, output_channels, has_bias,
input_name, output_name, **kwargs):
"""
Add an inner product layer to the model.
Parameters
----------
name: str
The name of this layer
W: numpy.array or bytes()
Weight matrix of shape (output_channels, input_channels)
If W is of type bytes(), i.e. quantized, other quantization related arguments must be provided as well (see below).
b: numpy.array
Bias vector of shape (output_channels, ).
input_channels: int
Number of input channels.
output_channels: int
Number of output channels.
has_bias: boolean
Whether the bias vector of this layer is ignored in the spec.
- If True, the bias vector of this layer is not ignored.
- If False, the bias vector is ignored.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of this layer.
Quantization arguments expected in kwargs, when W is of type bytes():
quantization_type : str
When weights are quantized (i.e. W is of type bytes()), this should be either "linear" or "lut".
nbits: int
Should be between 1 and 8 (inclusive). Number of bits per weight value. Only applicable when
weights are quantized.
quant_scale: numpy.array(dtype=numpy.float32)
scale vector to be used with linear quantization. Must be of length either 1 or output_channels.
quant_bias: numpy.array(dtype=numpy.float32)
bias vector to be used with linear quantization. Must be of length either 1 or output_channels.
quant_lut: numpy.array(dtype=numpy.float32)
the LUT (look up table) to be used with LUT quantization. Must be of length 2^nbits.
See Also
--------
add_embedding, add_convolution
"""
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.innerProduct
# Fill in the parameters
spec_layer_params.inputChannels = input_channels
spec_layer_params.outputChannels = output_channels
spec_layer_params.hasBias = has_bias
weights = spec_layer_params.weights
if len(kwargs) == 0:
weights.floatValue.extend(map(float, W.flatten()))
else:
_verify_quantization_arguments(weight=W, output_channels=output_channels, **kwargs)
_fill_quantized_weights(weights_message=weights, W=W, **kwargs)
if has_bias:
bias = spec_layer_params.bias
bias.floatValue.extend(map(float, b.flatten())) | python | def add_inner_product(self, name, W, b, input_channels, output_channels, has_bias,
input_name, output_name, **kwargs):
"""
Add an inner product layer to the model.
Parameters
----------
name: str
The name of this layer
W: numpy.array or bytes()
Weight matrix of shape (output_channels, input_channels)
If W is of type bytes(), i.e. quantized, other quantization related arguments must be provided as well (see below).
b: numpy.array
Bias vector of shape (output_channels, ).
input_channels: int
Number of input channels.
output_channels: int
Number of output channels.
has_bias: boolean
Whether the bias vector of this layer is ignored in the spec.
- If True, the bias vector of this layer is not ignored.
- If False, the bias vector is ignored.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of this layer.
Quantization arguments expected in kwargs, when W is of type bytes():
quantization_type : str
When weights are quantized (i.e. W is of type bytes()), this should be either "linear" or "lut".
nbits: int
Should be between 1 and 8 (inclusive). Number of bits per weight value. Only applicable when
weights are quantized.
quant_scale: numpy.array(dtype=numpy.float32)
scale vector to be used with linear quantization. Must be of length either 1 or output_channels.
quant_bias: numpy.array(dtype=numpy.float32)
bias vector to be used with linear quantization. Must be of length either 1 or output_channels.
quant_lut: numpy.array(dtype=numpy.float32)
the LUT (look up table) to be used with LUT quantization. Must be of length 2^nbits.
See Also
--------
add_embedding, add_convolution
"""
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.innerProduct
# Fill in the parameters
spec_layer_params.inputChannels = input_channels
spec_layer_params.outputChannels = output_channels
spec_layer_params.hasBias = has_bias
weights = spec_layer_params.weights
if len(kwargs) == 0:
weights.floatValue.extend(map(float, W.flatten()))
else:
_verify_quantization_arguments(weight=W, output_channels=output_channels, **kwargs)
_fill_quantized_weights(weights_message=weights, W=W, **kwargs)
if has_bias:
bias = spec_layer_params.bias
bias.floatValue.extend(map(float, b.flatten())) | [
"def",
"add_inner_product",
"(",
"self",
",",
"name",
",",
"W",
",",
"b",
",",
"input_channels",
",",
"output_channels",
",",
"has_bias",
",",
"input_name",
",",
"output_name",
",",
"*",
"*",
"kwargs",
")",
":",
"spec",
"=",
"self",
".",
"spec",
"nn_spec",
"=",
"self",
".",
"nn_spec",
"# Add a new layer",
"spec_layer",
"=",
"nn_spec",
".",
"layers",
".",
"add",
"(",
")",
"spec_layer",
".",
"name",
"=",
"name",
"spec_layer",
".",
"input",
".",
"append",
"(",
"input_name",
")",
"spec_layer",
".",
"output",
".",
"append",
"(",
"output_name",
")",
"spec_layer_params",
"=",
"spec_layer",
".",
"innerProduct",
"# Fill in the parameters",
"spec_layer_params",
".",
"inputChannels",
"=",
"input_channels",
"spec_layer_params",
".",
"outputChannels",
"=",
"output_channels",
"spec_layer_params",
".",
"hasBias",
"=",
"has_bias",
"weights",
"=",
"spec_layer_params",
".",
"weights",
"if",
"len",
"(",
"kwargs",
")",
"==",
"0",
":",
"weights",
".",
"floatValue",
".",
"extend",
"(",
"map",
"(",
"float",
",",
"W",
".",
"flatten",
"(",
")",
")",
")",
"else",
":",
"_verify_quantization_arguments",
"(",
"weight",
"=",
"W",
",",
"output_channels",
"=",
"output_channels",
",",
"*",
"*",
"kwargs",
")",
"_fill_quantized_weights",
"(",
"weights_message",
"=",
"weights",
",",
"W",
"=",
"W",
",",
"*",
"*",
"kwargs",
")",
"if",
"has_bias",
":",
"bias",
"=",
"spec_layer_params",
".",
"bias",
"bias",
".",
"floatValue",
".",
"extend",
"(",
"map",
"(",
"float",
",",
"b",
".",
"flatten",
"(",
")",
")",
")"
] | Add an inner product layer to the model.
Parameters
----------
name: str
The name of this layer
W: numpy.array or bytes()
Weight matrix of shape (output_channels, input_channels)
If W is of type bytes(), i.e. quantized, other quantization related arguments must be provided as well (see below).
b: numpy.array
Bias vector of shape (output_channels, ).
input_channels: int
Number of input channels.
output_channels: int
Number of output channels.
has_bias: boolean
Whether the bias vector of this layer is ignored in the spec.
- If True, the bias vector of this layer is not ignored.
- If False, the bias vector is ignored.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of this layer.
Quantization arguments expected in kwargs, when W is of type bytes():
quantization_type : str
When weights are quantized (i.e. W is of type bytes()), this should be either "linear" or "lut".
nbits: int
Should be between 1 and 8 (inclusive). Number of bits per weight value. Only applicable when
weights are quantized.
quant_scale: numpy.array(dtype=numpy.float32)
scale vector to be used with linear quantization. Must be of length either 1 or output_channels.
quant_bias: numpy.array(dtype=numpy.float32)
bias vector to be used with linear quantization. Must be of length either 1 or output_channels.
quant_lut: numpy.array(dtype=numpy.float32)
the LUT (look up table) to be used with LUT quantization. Must be of length 2^nbits.
See Also
--------
add_embedding, add_convolution | [
"Add",
"an",
"inner",
"product",
"layer",
"to",
"the",
"model",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py#L394-L471 |
29,425 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py | NeuralNetworkBuilder.add_resize_bilinear | def add_resize_bilinear(self, name, input_name, output_name, target_height=1, target_width=1,
mode='ALIGN_ENDPOINTS_MODE'):
"""
Add resize bilinear layer to the model. A layer that resizes the input to a given spatial size using bilinear interpolation.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of this layer.
target_height: int
Output height dimension.
target_width: int
Output width dimension.
mode: str
Following values are supported: 'STRICT_ALIGN_ENDPOINTS_MODE', 'ALIGN_ENDPOINTS_MODE', 'UPSAMPLE_MODE', 'ROI_ALIGN_MODE'.
This parameter determines the sampling grid used for bilinear interpolation. Kindly refer to NeuralNetwork.proto for details.
See Also
--------
add_upsample
"""
spec = self.spec
nn_spec = self.nn_spec
# Add a new inner-product layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.resizeBilinear
spec_layer_params.targetSize.append(target_height)
spec_layer_params.targetSize.append(target_width)
if mode == 'ALIGN_ENDPOINTS_MODE':
spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value('ALIGN_ENDPOINTS_MODE')
elif mode == 'STRICT_ALIGN_ENDPOINTS_MODE':
spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value('STRICT_ALIGN_ENDPOINTS_MODE')
elif mode == 'UPSAMPLE_MODE':
spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value('UPSAMPLE_MODE')
elif mode == 'ROI_ALIGN_MODE':
spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value('ROI_ALIGN_MODE')
else:
raise ValueError("Unspported resize bilinear mode %s" % mode) | python | def add_resize_bilinear(self, name, input_name, output_name, target_height=1, target_width=1,
mode='ALIGN_ENDPOINTS_MODE'):
"""
Add resize bilinear layer to the model. A layer that resizes the input to a given spatial size using bilinear interpolation.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of this layer.
target_height: int
Output height dimension.
target_width: int
Output width dimension.
mode: str
Following values are supported: 'STRICT_ALIGN_ENDPOINTS_MODE', 'ALIGN_ENDPOINTS_MODE', 'UPSAMPLE_MODE', 'ROI_ALIGN_MODE'.
This parameter determines the sampling grid used for bilinear interpolation. Kindly refer to NeuralNetwork.proto for details.
See Also
--------
add_upsample
"""
spec = self.spec
nn_spec = self.nn_spec
# Add a new inner-product layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.resizeBilinear
spec_layer_params.targetSize.append(target_height)
spec_layer_params.targetSize.append(target_width)
if mode == 'ALIGN_ENDPOINTS_MODE':
spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value('ALIGN_ENDPOINTS_MODE')
elif mode == 'STRICT_ALIGN_ENDPOINTS_MODE':
spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value('STRICT_ALIGN_ENDPOINTS_MODE')
elif mode == 'UPSAMPLE_MODE':
spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value('UPSAMPLE_MODE')
elif mode == 'ROI_ALIGN_MODE':
spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value('ROI_ALIGN_MODE')
else:
raise ValueError("Unspported resize bilinear mode %s" % mode) | [
"def",
"add_resize_bilinear",
"(",
"self",
",",
"name",
",",
"input_name",
",",
"output_name",
",",
"target_height",
"=",
"1",
",",
"target_width",
"=",
"1",
",",
"mode",
"=",
"'ALIGN_ENDPOINTS_MODE'",
")",
":",
"spec",
"=",
"self",
".",
"spec",
"nn_spec",
"=",
"self",
".",
"nn_spec",
"# Add a new inner-product layer",
"spec_layer",
"=",
"nn_spec",
".",
"layers",
".",
"add",
"(",
")",
"spec_layer",
".",
"name",
"=",
"name",
"spec_layer",
".",
"input",
".",
"append",
"(",
"input_name",
")",
"spec_layer",
".",
"output",
".",
"append",
"(",
"output_name",
")",
"spec_layer_params",
"=",
"spec_layer",
".",
"resizeBilinear",
"spec_layer_params",
".",
"targetSize",
".",
"append",
"(",
"target_height",
")",
"spec_layer_params",
".",
"targetSize",
".",
"append",
"(",
"target_width",
")",
"if",
"mode",
"==",
"'ALIGN_ENDPOINTS_MODE'",
":",
"spec_layer_params",
".",
"mode",
".",
"samplingMethod",
"=",
"_NeuralNetwork_pb2",
".",
"SamplingMode",
".",
"Method",
".",
"Value",
"(",
"'ALIGN_ENDPOINTS_MODE'",
")",
"elif",
"mode",
"==",
"'STRICT_ALIGN_ENDPOINTS_MODE'",
":",
"spec_layer_params",
".",
"mode",
".",
"samplingMethod",
"=",
"_NeuralNetwork_pb2",
".",
"SamplingMode",
".",
"Method",
".",
"Value",
"(",
"'STRICT_ALIGN_ENDPOINTS_MODE'",
")",
"elif",
"mode",
"==",
"'UPSAMPLE_MODE'",
":",
"spec_layer_params",
".",
"mode",
".",
"samplingMethod",
"=",
"_NeuralNetwork_pb2",
".",
"SamplingMode",
".",
"Method",
".",
"Value",
"(",
"'UPSAMPLE_MODE'",
")",
"elif",
"mode",
"==",
"'ROI_ALIGN_MODE'",
":",
"spec_layer_params",
".",
"mode",
".",
"samplingMethod",
"=",
"_NeuralNetwork_pb2",
".",
"SamplingMode",
".",
"Method",
".",
"Value",
"(",
"'ROI_ALIGN_MODE'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unspported resize bilinear mode %s\"",
"%",
"mode",
")"
] | Add resize bilinear layer to the model. A layer that resizes the input to a given spatial size using bilinear interpolation.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of this layer.
target_height: int
Output height dimension.
target_width: int
Output width dimension.
mode: str
Following values are supported: 'STRICT_ALIGN_ENDPOINTS_MODE', 'ALIGN_ENDPOINTS_MODE', 'UPSAMPLE_MODE', 'ROI_ALIGN_MODE'.
This parameter determines the sampling grid used for bilinear interpolation. Kindly refer to NeuralNetwork.proto for details.
See Also
--------
add_upsample | [
"Add",
"resize",
"bilinear",
"layer",
"to",
"the",
"model",
".",
"A",
"layer",
"that",
"resizes",
"the",
"input",
"to",
"a",
"given",
"spatial",
"size",
"using",
"bilinear",
"interpolation",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py#L2612-L2657 |
29,426 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _toolkit_serialize_summary_struct | def _toolkit_serialize_summary_struct(model, sections, section_titles):
"""
Serialize model summary into a dict with ordered lists of sections and section titles
Parameters
----------
model : Model object
sections : Ordered list of lists (sections) of tuples (field,value)
[
[(field1, value1), (field2, value2)],
[(field3, value3), (field4, value4)],
]
section_titles : Ordered list of section titles
Returns
-------
output_dict : A dict with two entries:
'sections' : ordered list with tuples of the form ('label',value)
'section_titles' : ordered list of section labels
"""
output_dict = dict()
output_dict['sections'] = [ [ ( field[0], __extract_model_summary_value(model, field[1]) ) \
for field in section ]
for section in sections ]
output_dict['section_titles'] = section_titles
return output_dict | python | def _toolkit_serialize_summary_struct(model, sections, section_titles):
"""
Serialize model summary into a dict with ordered lists of sections and section titles
Parameters
----------
model : Model object
sections : Ordered list of lists (sections) of tuples (field,value)
[
[(field1, value1), (field2, value2)],
[(field3, value3), (field4, value4)],
]
section_titles : Ordered list of section titles
Returns
-------
output_dict : A dict with two entries:
'sections' : ordered list with tuples of the form ('label',value)
'section_titles' : ordered list of section labels
"""
output_dict = dict()
output_dict['sections'] = [ [ ( field[0], __extract_model_summary_value(model, field[1]) ) \
for field in section ]
for section in sections ]
output_dict['section_titles'] = section_titles
return output_dict | [
"def",
"_toolkit_serialize_summary_struct",
"(",
"model",
",",
"sections",
",",
"section_titles",
")",
":",
"output_dict",
"=",
"dict",
"(",
")",
"output_dict",
"[",
"'sections'",
"]",
"=",
"[",
"[",
"(",
"field",
"[",
"0",
"]",
",",
"__extract_model_summary_value",
"(",
"model",
",",
"field",
"[",
"1",
"]",
")",
")",
"for",
"field",
"in",
"section",
"]",
"for",
"section",
"in",
"sections",
"]",
"output_dict",
"[",
"'section_titles'",
"]",
"=",
"section_titles",
"return",
"output_dict"
] | Serialize model summary into a dict with ordered lists of sections and section titles
Parameters
----------
model : Model object
sections : Ordered list of lists (sections) of tuples (field,value)
[
[(field1, value1), (field2, value2)],
[(field3, value3), (field4, value4)],
]
section_titles : Ordered list of section titles
Returns
-------
output_dict : A dict with two entries:
'sections' : ordered list with tuples of the form ('label',value)
'section_titles' : ordered list of section labels | [
"Serialize",
"model",
"summary",
"into",
"a",
"dict",
"with",
"ordered",
"lists",
"of",
"sections",
"and",
"section",
"titles"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L34-L61 |
29,427 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _find_only_column_of_type | def _find_only_column_of_type(sframe, target_type, type_name, col_name):
"""
Finds the only column in `SFrame` with a type specified by `target_type`.
If there are zero or more than one such columns, an exception will be
raised. The name and type of the target column should be provided as
strings for the purpose of error feedback.
"""
image_column_name = None
if type(target_type) != list:
target_type = [target_type]
for name, ctype in zip(sframe.column_names(), sframe.column_types()):
if ctype in target_type:
if image_column_name is not None:
raise ToolkitError('No "{col_name}" column specified and more than one {type_name} column in "dataset". Can not infer correct {col_name} column.'.format(col_name=col_name, type_name=type_name))
image_column_name = name
if image_column_name is None:
raise ToolkitError('No %s column in "dataset".' % type_name)
return image_column_name | python | def _find_only_column_of_type(sframe, target_type, type_name, col_name):
"""
Finds the only column in `SFrame` with a type specified by `target_type`.
If there are zero or more than one such columns, an exception will be
raised. The name and type of the target column should be provided as
strings for the purpose of error feedback.
"""
image_column_name = None
if type(target_type) != list:
target_type = [target_type]
for name, ctype in zip(sframe.column_names(), sframe.column_types()):
if ctype in target_type:
if image_column_name is not None:
raise ToolkitError('No "{col_name}" column specified and more than one {type_name} column in "dataset". Can not infer correct {col_name} column.'.format(col_name=col_name, type_name=type_name))
image_column_name = name
if image_column_name is None:
raise ToolkitError('No %s column in "dataset".' % type_name)
return image_column_name | [
"def",
"_find_only_column_of_type",
"(",
"sframe",
",",
"target_type",
",",
"type_name",
",",
"col_name",
")",
":",
"image_column_name",
"=",
"None",
"if",
"type",
"(",
"target_type",
")",
"!=",
"list",
":",
"target_type",
"=",
"[",
"target_type",
"]",
"for",
"name",
",",
"ctype",
"in",
"zip",
"(",
"sframe",
".",
"column_names",
"(",
")",
",",
"sframe",
".",
"column_types",
"(",
")",
")",
":",
"if",
"ctype",
"in",
"target_type",
":",
"if",
"image_column_name",
"is",
"not",
"None",
":",
"raise",
"ToolkitError",
"(",
"'No \"{col_name}\" column specified and more than one {type_name} column in \"dataset\". Can not infer correct {col_name} column.'",
".",
"format",
"(",
"col_name",
"=",
"col_name",
",",
"type_name",
"=",
"type_name",
")",
")",
"image_column_name",
"=",
"name",
"if",
"image_column_name",
"is",
"None",
":",
"raise",
"ToolkitError",
"(",
"'No %s column in \"dataset\".'",
"%",
"type_name",
")",
"return",
"image_column_name"
] | Finds the only column in `SFrame` with a type specified by `target_type`.
If there are zero or more than one such columns, an exception will be
raised. The name and type of the target column should be provided as
strings for the purpose of error feedback. | [
"Finds",
"the",
"only",
"column",
"in",
"SFrame",
"with",
"a",
"type",
"specified",
"by",
"target_type",
".",
"If",
"there",
"are",
"zero",
"or",
"more",
"than",
"one",
"such",
"columns",
"an",
"exception",
"will",
"be",
"raised",
".",
"The",
"name",
"and",
"type",
"of",
"the",
"target",
"column",
"should",
"be",
"provided",
"as",
"strings",
"for",
"the",
"purpose",
"of",
"error",
"feedback",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L86-L103 |
29,428 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _find_only_image_column | def _find_only_image_column(sframe):
"""
Finds the only column in `sframe` with a type of turicreate.Image.
If there are zero or more than one image columns, an exception will
be raised.
"""
from turicreate import Image
return _find_only_column_of_type(sframe, target_type=Image,
type_name='image', col_name='feature') | python | def _find_only_image_column(sframe):
"""
Finds the only column in `sframe` with a type of turicreate.Image.
If there are zero or more than one image columns, an exception will
be raised.
"""
from turicreate import Image
return _find_only_column_of_type(sframe, target_type=Image,
type_name='image', col_name='feature') | [
"def",
"_find_only_image_column",
"(",
"sframe",
")",
":",
"from",
"turicreate",
"import",
"Image",
"return",
"_find_only_column_of_type",
"(",
"sframe",
",",
"target_type",
"=",
"Image",
",",
"type_name",
"=",
"'image'",
",",
"col_name",
"=",
"'feature'",
")"
] | Finds the only column in `sframe` with a type of turicreate.Image.
If there are zero or more than one image columns, an exception will
be raised. | [
"Finds",
"the",
"only",
"column",
"in",
"sframe",
"with",
"a",
"type",
"of",
"turicreate",
".",
"Image",
".",
"If",
"there",
"are",
"zero",
"or",
"more",
"than",
"one",
"image",
"columns",
"an",
"exception",
"will",
"be",
"raised",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L105-L113 |
29,429 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _SGraphFromJsonTree | def _SGraphFromJsonTree(json_str):
"""
Convert the Json Tree to SGraph
"""
g = json.loads(json_str)
vertices = [_Vertex(x['id'],
dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id']))
for x in g['vertices']]
edges = [_Edge(x['src'], x['dst'],
dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'src' and k != 'dst']))
for x in g['edges']]
sg = _SGraph().add_vertices(vertices)
if len(edges) > 0:
sg = sg.add_edges(edges)
return sg | python | def _SGraphFromJsonTree(json_str):
"""
Convert the Json Tree to SGraph
"""
g = json.loads(json_str)
vertices = [_Vertex(x['id'],
dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id']))
for x in g['vertices']]
edges = [_Edge(x['src'], x['dst'],
dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'src' and k != 'dst']))
for x in g['edges']]
sg = _SGraph().add_vertices(vertices)
if len(edges) > 0:
sg = sg.add_edges(edges)
return sg | [
"def",
"_SGraphFromJsonTree",
"(",
"json_str",
")",
":",
"g",
"=",
"json",
".",
"loads",
"(",
"json_str",
")",
"vertices",
"=",
"[",
"_Vertex",
"(",
"x",
"[",
"'id'",
"]",
",",
"dict",
"(",
"[",
"(",
"str",
"(",
"k",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"_six",
".",
"iteritems",
"(",
"x",
")",
"if",
"k",
"!=",
"'id'",
"]",
")",
")",
"for",
"x",
"in",
"g",
"[",
"'vertices'",
"]",
"]",
"edges",
"=",
"[",
"_Edge",
"(",
"x",
"[",
"'src'",
"]",
",",
"x",
"[",
"'dst'",
"]",
",",
"dict",
"(",
"[",
"(",
"str",
"(",
"k",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"_six",
".",
"iteritems",
"(",
"x",
")",
"if",
"k",
"!=",
"'src'",
"and",
"k",
"!=",
"'dst'",
"]",
")",
")",
"for",
"x",
"in",
"g",
"[",
"'edges'",
"]",
"]",
"sg",
"=",
"_SGraph",
"(",
")",
".",
"add_vertices",
"(",
"vertices",
")",
"if",
"len",
"(",
"edges",
")",
">",
"0",
":",
"sg",
"=",
"sg",
".",
"add_edges",
"(",
"edges",
")",
"return",
"sg"
] | Convert the Json Tree to SGraph | [
"Convert",
"the",
"Json",
"Tree",
"to",
"SGraph"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L203-L217 |
29,430 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _summarize_coefficients | def _summarize_coefficients(top_coefs, bottom_coefs):
"""
Return a tuple of sections and section titles.
Sections are pretty print of model coefficients
Parameters
----------
top_coefs : SFrame of top k coefficients
bottom_coefs : SFrame of bottom k coefficients
Returns
-------
(sections, section_titles) : tuple
sections : list
summary sections for top/bottom k coefficients
section_titles : list
summary section titles
"""
def get_row_name(row):
if row['index'] is None:
return row['name']
else:
return "%s[%s]" % (row['name'], row['index'])
if len(top_coefs) == 0:
top_coefs_list = [('No Positive Coefficients', _precomputed_field('') )]
else:
top_coefs_list = [ (get_row_name(row),
_precomputed_field(row['value'])) \
for row in top_coefs ]
if len(bottom_coefs) == 0:
bottom_coefs_list = [('No Negative Coefficients', _precomputed_field(''))]
else:
bottom_coefs_list = [ (get_row_name(row),
_precomputed_field(row['value'])) \
for row in bottom_coefs ]
return ([top_coefs_list, bottom_coefs_list], \
[ 'Highest Positive Coefficients', 'Lowest Negative Coefficients'] ) | python | def _summarize_coefficients(top_coefs, bottom_coefs):
"""
Return a tuple of sections and section titles.
Sections are pretty print of model coefficients
Parameters
----------
top_coefs : SFrame of top k coefficients
bottom_coefs : SFrame of bottom k coefficients
Returns
-------
(sections, section_titles) : tuple
sections : list
summary sections for top/bottom k coefficients
section_titles : list
summary section titles
"""
def get_row_name(row):
if row['index'] is None:
return row['name']
else:
return "%s[%s]" % (row['name'], row['index'])
if len(top_coefs) == 0:
top_coefs_list = [('No Positive Coefficients', _precomputed_field('') )]
else:
top_coefs_list = [ (get_row_name(row),
_precomputed_field(row['value'])) \
for row in top_coefs ]
if len(bottom_coefs) == 0:
bottom_coefs_list = [('No Negative Coefficients', _precomputed_field(''))]
else:
bottom_coefs_list = [ (get_row_name(row),
_precomputed_field(row['value'])) \
for row in bottom_coefs ]
return ([top_coefs_list, bottom_coefs_list], \
[ 'Highest Positive Coefficients', 'Lowest Negative Coefficients'] ) | [
"def",
"_summarize_coefficients",
"(",
"top_coefs",
",",
"bottom_coefs",
")",
":",
"def",
"get_row_name",
"(",
"row",
")",
":",
"if",
"row",
"[",
"'index'",
"]",
"is",
"None",
":",
"return",
"row",
"[",
"'name'",
"]",
"else",
":",
"return",
"\"%s[%s]\"",
"%",
"(",
"row",
"[",
"'name'",
"]",
",",
"row",
"[",
"'index'",
"]",
")",
"if",
"len",
"(",
"top_coefs",
")",
"==",
"0",
":",
"top_coefs_list",
"=",
"[",
"(",
"'No Positive Coefficients'",
",",
"_precomputed_field",
"(",
"''",
")",
")",
"]",
"else",
":",
"top_coefs_list",
"=",
"[",
"(",
"get_row_name",
"(",
"row",
")",
",",
"_precomputed_field",
"(",
"row",
"[",
"'value'",
"]",
")",
")",
"for",
"row",
"in",
"top_coefs",
"]",
"if",
"len",
"(",
"bottom_coefs",
")",
"==",
"0",
":",
"bottom_coefs_list",
"=",
"[",
"(",
"'No Negative Coefficients'",
",",
"_precomputed_field",
"(",
"''",
")",
")",
"]",
"else",
":",
"bottom_coefs_list",
"=",
"[",
"(",
"get_row_name",
"(",
"row",
")",
",",
"_precomputed_field",
"(",
"row",
"[",
"'value'",
"]",
")",
")",
"for",
"row",
"in",
"bottom_coefs",
"]",
"return",
"(",
"[",
"top_coefs_list",
",",
"bottom_coefs_list",
"]",
",",
"[",
"'Highest Positive Coefficients'",
",",
"'Lowest Negative Coefficients'",
"]",
")"
] | Return a tuple of sections and section titles.
Sections are pretty print of model coefficients
Parameters
----------
top_coefs : SFrame of top k coefficients
bottom_coefs : SFrame of bottom k coefficients
Returns
-------
(sections, section_titles) : tuple
sections : list
summary sections for top/bottom k coefficients
section_titles : list
summary section titles | [
"Return",
"a",
"tuple",
"of",
"sections",
"and",
"section",
"titles",
".",
"Sections",
"are",
"pretty",
"print",
"of",
"model",
"coefficients"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L223-L264 |
29,431 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _toolkit_get_topk_bottomk | def _toolkit_get_topk_bottomk(values, k=5):
"""
Returns a tuple of the top k values from the positive and
negative values in a SArray
Parameters
----------
values : SFrame of model coefficients
k: Maximum number of largest positive and k lowest negative numbers to return
Returns
-------
(topk_positive, bottomk_positive) : tuple
topk_positive : list
floats that represent the top 'k' ( or less ) positive
values
bottomk_positive : list
floats that represent the top 'k' ( or less ) negative
values
"""
top_values = values.topk('value', k=k)
top_values = top_values[top_values['value'] > 0]
bottom_values = values.topk('value', k=k, reverse=True)
bottom_values = bottom_values[bottom_values['value'] < 0]
return (top_values, bottom_values) | python | def _toolkit_get_topk_bottomk(values, k=5):
"""
Returns a tuple of the top k values from the positive and
negative values in a SArray
Parameters
----------
values : SFrame of model coefficients
k: Maximum number of largest positive and k lowest negative numbers to return
Returns
-------
(topk_positive, bottomk_positive) : tuple
topk_positive : list
floats that represent the top 'k' ( or less ) positive
values
bottomk_positive : list
floats that represent the top 'k' ( or less ) negative
values
"""
top_values = values.topk('value', k=k)
top_values = top_values[top_values['value'] > 0]
bottom_values = values.topk('value', k=k, reverse=True)
bottom_values = bottom_values[bottom_values['value'] < 0]
return (top_values, bottom_values) | [
"def",
"_toolkit_get_topk_bottomk",
"(",
"values",
",",
"k",
"=",
"5",
")",
":",
"top_values",
"=",
"values",
".",
"topk",
"(",
"'value'",
",",
"k",
"=",
"k",
")",
"top_values",
"=",
"top_values",
"[",
"top_values",
"[",
"'value'",
"]",
">",
"0",
"]",
"bottom_values",
"=",
"values",
".",
"topk",
"(",
"'value'",
",",
"k",
"=",
"k",
",",
"reverse",
"=",
"True",
")",
"bottom_values",
"=",
"bottom_values",
"[",
"bottom_values",
"[",
"'value'",
"]",
"<",
"0",
"]",
"return",
"(",
"top_values",
",",
"bottom_values",
")"
] | Returns a tuple of the top k values from the positive and
negative values in a SArray
Parameters
----------
values : SFrame of model coefficients
k: Maximum number of largest positive and k lowest negative numbers to return
Returns
-------
(topk_positive, bottomk_positive) : tuple
topk_positive : list
floats that represent the top 'k' ( or less ) positive
values
bottomk_positive : list
floats that represent the top 'k' ( or less ) negative
values | [
"Returns",
"a",
"tuple",
"of",
"the",
"top",
"k",
"values",
"from",
"the",
"positive",
"and",
"negative",
"values",
"in",
"a",
"SArray"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L266-L294 |
29,432 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | __extract_model_summary_value | def __extract_model_summary_value(model, value):
"""
Extract a model summary field value
"""
field_value = None
if isinstance(value, _precomputed_field):
field_value = value.field
else:
field_value = model._get(value)
if isinstance(field_value, float):
try:
field_value = round(field_value, 4)
except:
pass
return field_value | python | def __extract_model_summary_value(model, value):
"""
Extract a model summary field value
"""
field_value = None
if isinstance(value, _precomputed_field):
field_value = value.field
else:
field_value = model._get(value)
if isinstance(field_value, float):
try:
field_value = round(field_value, 4)
except:
pass
return field_value | [
"def",
"__extract_model_summary_value",
"(",
"model",
",",
"value",
")",
":",
"field_value",
"=",
"None",
"if",
"isinstance",
"(",
"value",
",",
"_precomputed_field",
")",
":",
"field_value",
"=",
"value",
".",
"field",
"else",
":",
"field_value",
"=",
"model",
".",
"_get",
"(",
"value",
")",
"if",
"isinstance",
"(",
"field_value",
",",
"float",
")",
":",
"try",
":",
"field_value",
"=",
"round",
"(",
"field_value",
",",
"4",
")",
"except",
":",
"pass",
"return",
"field_value"
] | Extract a model summary field value | [
"Extract",
"a",
"model",
"summary",
"field",
"value"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L320-L334 |
29,433 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _make_repr_table_from_sframe | def _make_repr_table_from_sframe(X):
"""
Serializes an SFrame to a list of strings, that, when printed, creates a well-formatted table.
"""
assert isinstance(X, _SFrame)
column_names = X.column_names()
out_data = [ [None]*len(column_names) for i in range(X.num_rows())]
column_sizes = [len(s) for s in column_names]
for i, c in enumerate(column_names):
for j, e in enumerate(X[c]):
out_data[j][i] = str(e)
column_sizes[i] = max(column_sizes[i], len(e))
# now, go through and pad everything.
out_data = ([ [cn.ljust(k, ' ') for cn, k in zip(column_names, column_sizes)],
["-"*k for k in column_sizes] ]
+ [ [e.ljust(k, ' ') for e, k in zip(row, column_sizes)] for row in out_data] )
return [' '.join(row) for row in out_data] | python | def _make_repr_table_from_sframe(X):
"""
Serializes an SFrame to a list of strings, that, when printed, creates a well-formatted table.
"""
assert isinstance(X, _SFrame)
column_names = X.column_names()
out_data = [ [None]*len(column_names) for i in range(X.num_rows())]
column_sizes = [len(s) for s in column_names]
for i, c in enumerate(column_names):
for j, e in enumerate(X[c]):
out_data[j][i] = str(e)
column_sizes[i] = max(column_sizes[i], len(e))
# now, go through and pad everything.
out_data = ([ [cn.ljust(k, ' ') for cn, k in zip(column_names, column_sizes)],
["-"*k for k in column_sizes] ]
+ [ [e.ljust(k, ' ') for e, k in zip(row, column_sizes)] for row in out_data] )
return [' '.join(row) for row in out_data] | [
"def",
"_make_repr_table_from_sframe",
"(",
"X",
")",
":",
"assert",
"isinstance",
"(",
"X",
",",
"_SFrame",
")",
"column_names",
"=",
"X",
".",
"column_names",
"(",
")",
"out_data",
"=",
"[",
"[",
"None",
"]",
"*",
"len",
"(",
"column_names",
")",
"for",
"i",
"in",
"range",
"(",
"X",
".",
"num_rows",
"(",
")",
")",
"]",
"column_sizes",
"=",
"[",
"len",
"(",
"s",
")",
"for",
"s",
"in",
"column_names",
"]",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"column_names",
")",
":",
"for",
"j",
",",
"e",
"in",
"enumerate",
"(",
"X",
"[",
"c",
"]",
")",
":",
"out_data",
"[",
"j",
"]",
"[",
"i",
"]",
"=",
"str",
"(",
"e",
")",
"column_sizes",
"[",
"i",
"]",
"=",
"max",
"(",
"column_sizes",
"[",
"i",
"]",
",",
"len",
"(",
"e",
")",
")",
"# now, go through and pad everything.",
"out_data",
"=",
"(",
"[",
"[",
"cn",
".",
"ljust",
"(",
"k",
",",
"' '",
")",
"for",
"cn",
",",
"k",
"in",
"zip",
"(",
"column_names",
",",
"column_sizes",
")",
"]",
",",
"[",
"\"-\"",
"*",
"k",
"for",
"k",
"in",
"column_sizes",
"]",
"]",
"+",
"[",
"[",
"e",
".",
"ljust",
"(",
"k",
",",
"' '",
")",
"for",
"e",
",",
"k",
"in",
"zip",
"(",
"row",
",",
"column_sizes",
")",
"]",
"for",
"row",
"in",
"out_data",
"]",
")",
"return",
"[",
"' '",
".",
"join",
"(",
"row",
")",
"for",
"row",
"in",
"out_data",
"]"
] | Serializes an SFrame to a list of strings, that, when printed, creates a well-formatted table. | [
"Serializes",
"an",
"SFrame",
"to",
"a",
"list",
"of",
"strings",
"that",
"when",
"printed",
"creates",
"a",
"well",
"-",
"formatted",
"table",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L336-L359 |
29,434 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _toolkit_repr_print | def _toolkit_repr_print(model, fields, section_titles, width = None):
"""
Display a toolkit repr according to some simple rules.
Parameters
----------
model : Turi Create model
fields: List of lists of tuples
Each tuple should be (display_name, field_name), where field_name can
be a string or a _precomputed_field object.
section_titles: List of section titles, one per list in the fields arg.
Example
-------
model_fields = [
("L1 penalty", 'l1_penalty'),
("L2 penalty", 'l2_penalty'),
("Examples", 'num_examples'),
("Features", 'num_features'),
("Coefficients", 'num_coefficients')]
solver_fields = [
("Solver", 'solver'),
("Solver iterations", 'training_iterations'),
("Solver status", 'training_solver_status'),
("Training time (sec)", 'training_time')]
training_fields = [
("Log-likelihood", 'training_loss')]
fields = [model_fields, solver_fields, training_fields]:
section_titles = ['Model description',
'Solver description',
'Training information']
_toolkit_repr_print(model, fields, section_titles)
"""
assert len(section_titles) == len(fields), \
"The number of section titles ({0}) ".format(len(section_titles)) +\
"doesn't match the number of groups of fields, {0}.".format(len(fields))
out_fields = [ ("Class", model.__class__.__name__), ""]
# Record the max_width so that if width is not provided, we calculate it.
max_width = len("Class")
for index, (section_title, field_list) in enumerate(zip(section_titles, fields)):
# Add in the section header.
out_fields += [section_title, "-"*len(section_title)]
# Add in all the key-value pairs
for f in field_list:
if isinstance(f, tuple):
f = (str(f[0]), f[1])
out_fields.append( (f[0], __extract_model_summary_value(model, f[1])) )
max_width = max(max_width, len(f[0]))
elif isinstance(f, _SFrame):
out_fields.append("")
out_fields += _make_repr_table_from_sframe(f)
out_fields.append("")
else:
raise TypeError("Type of field %s not recognized." % str(f))
# Add in the empty footer.
out_fields.append("")
if width is None:
width = max_width
# Now, go through and format the key_value pairs nicely.
def format_key_pair(key, value):
if type(key) is list:
key = ','.join(str(k) for k in key)
return key.ljust(width, ' ') + ' : ' + str(value)
out_fields = [s if type(s) is str else format_key_pair(*s) for s in out_fields]
return '\n'.join(out_fields) | python | def _toolkit_repr_print(model, fields, section_titles, width = None):
"""
Display a toolkit repr according to some simple rules.
Parameters
----------
model : Turi Create model
fields: List of lists of tuples
Each tuple should be (display_name, field_name), where field_name can
be a string or a _precomputed_field object.
section_titles: List of section titles, one per list in the fields arg.
Example
-------
model_fields = [
("L1 penalty", 'l1_penalty'),
("L2 penalty", 'l2_penalty'),
("Examples", 'num_examples'),
("Features", 'num_features'),
("Coefficients", 'num_coefficients')]
solver_fields = [
("Solver", 'solver'),
("Solver iterations", 'training_iterations'),
("Solver status", 'training_solver_status'),
("Training time (sec)", 'training_time')]
training_fields = [
("Log-likelihood", 'training_loss')]
fields = [model_fields, solver_fields, training_fields]:
section_titles = ['Model description',
'Solver description',
'Training information']
_toolkit_repr_print(model, fields, section_titles)
"""
assert len(section_titles) == len(fields), \
"The number of section titles ({0}) ".format(len(section_titles)) +\
"doesn't match the number of groups of fields, {0}.".format(len(fields))
out_fields = [ ("Class", model.__class__.__name__), ""]
# Record the max_width so that if width is not provided, we calculate it.
max_width = len("Class")
for index, (section_title, field_list) in enumerate(zip(section_titles, fields)):
# Add in the section header.
out_fields += [section_title, "-"*len(section_title)]
# Add in all the key-value pairs
for f in field_list:
if isinstance(f, tuple):
f = (str(f[0]), f[1])
out_fields.append( (f[0], __extract_model_summary_value(model, f[1])) )
max_width = max(max_width, len(f[0]))
elif isinstance(f, _SFrame):
out_fields.append("")
out_fields += _make_repr_table_from_sframe(f)
out_fields.append("")
else:
raise TypeError("Type of field %s not recognized." % str(f))
# Add in the empty footer.
out_fields.append("")
if width is None:
width = max_width
# Now, go through and format the key_value pairs nicely.
def format_key_pair(key, value):
if type(key) is list:
key = ','.join(str(k) for k in key)
return key.ljust(width, ' ') + ' : ' + str(value)
out_fields = [s if type(s) is str else format_key_pair(*s) for s in out_fields]
return '\n'.join(out_fields) | [
"def",
"_toolkit_repr_print",
"(",
"model",
",",
"fields",
",",
"section_titles",
",",
"width",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"section_titles",
")",
"==",
"len",
"(",
"fields",
")",
",",
"\"The number of section titles ({0}) \"",
".",
"format",
"(",
"len",
"(",
"section_titles",
")",
")",
"+",
"\"doesn't match the number of groups of fields, {0}.\"",
".",
"format",
"(",
"len",
"(",
"fields",
")",
")",
"out_fields",
"=",
"[",
"(",
"\"Class\"",
",",
"model",
".",
"__class__",
".",
"__name__",
")",
",",
"\"\"",
"]",
"# Record the max_width so that if width is not provided, we calculate it.",
"max_width",
"=",
"len",
"(",
"\"Class\"",
")",
"for",
"index",
",",
"(",
"section_title",
",",
"field_list",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"section_titles",
",",
"fields",
")",
")",
":",
"# Add in the section header.",
"out_fields",
"+=",
"[",
"section_title",
",",
"\"-\"",
"*",
"len",
"(",
"section_title",
")",
"]",
"# Add in all the key-value pairs",
"for",
"f",
"in",
"field_list",
":",
"if",
"isinstance",
"(",
"f",
",",
"tuple",
")",
":",
"f",
"=",
"(",
"str",
"(",
"f",
"[",
"0",
"]",
")",
",",
"f",
"[",
"1",
"]",
")",
"out_fields",
".",
"append",
"(",
"(",
"f",
"[",
"0",
"]",
",",
"__extract_model_summary_value",
"(",
"model",
",",
"f",
"[",
"1",
"]",
")",
")",
")",
"max_width",
"=",
"max",
"(",
"max_width",
",",
"len",
"(",
"f",
"[",
"0",
"]",
")",
")",
"elif",
"isinstance",
"(",
"f",
",",
"_SFrame",
")",
":",
"out_fields",
".",
"append",
"(",
"\"\"",
")",
"out_fields",
"+=",
"_make_repr_table_from_sframe",
"(",
"f",
")",
"out_fields",
".",
"append",
"(",
"\"\"",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Type of field %s not recognized.\"",
"%",
"str",
"(",
"f",
")",
")",
"# Add in the empty footer.",
"out_fields",
".",
"append",
"(",
"\"\"",
")",
"if",
"width",
"is",
"None",
":",
"width",
"=",
"max_width",
"# Now, go through and format the key_value pairs nicely.",
"def",
"format_key_pair",
"(",
"key",
",",
"value",
")",
":",
"if",
"type",
"(",
"key",
")",
"is",
"list",
":",
"key",
"=",
"','",
".",
"join",
"(",
"str",
"(",
"k",
")",
"for",
"k",
"in",
"key",
")",
"return",
"key",
".",
"ljust",
"(",
"width",
",",
"' '",
")",
"+",
"' : '",
"+",
"str",
"(",
"value",
")",
"out_fields",
"=",
"[",
"s",
"if",
"type",
"(",
"s",
")",
"is",
"str",
"else",
"format_key_pair",
"(",
"*",
"s",
")",
"for",
"s",
"in",
"out_fields",
"]",
"return",
"'\\n'",
".",
"join",
"(",
"out_fields",
")"
] | Display a toolkit repr according to some simple rules.
Parameters
----------
model : Turi Create model
fields: List of lists of tuples
Each tuple should be (display_name, field_name), where field_name can
be a string or a _precomputed_field object.
section_titles: List of section titles, one per list in the fields arg.
Example
-------
model_fields = [
("L1 penalty", 'l1_penalty'),
("L2 penalty", 'l2_penalty'),
("Examples", 'num_examples'),
("Features", 'num_features'),
("Coefficients", 'num_coefficients')]
solver_fields = [
("Solver", 'solver'),
("Solver iterations", 'training_iterations'),
("Solver status", 'training_solver_status'),
("Training time (sec)", 'training_time')]
training_fields = [
("Log-likelihood", 'training_loss')]
fields = [model_fields, solver_fields, training_fields]:
section_titles = ['Model description',
'Solver description',
'Training information']
_toolkit_repr_print(model, fields, section_titles) | [
"Display",
"a",
"toolkit",
"repr",
"according",
"to",
"some",
"simple",
"rules",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L362-L446 |
29,435 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _map_unity_proxy_to_object | def _map_unity_proxy_to_object(value):
"""
Map returning value, if it is unity SFrame, SArray, map it
"""
vtype = type(value)
if vtype in _proxy_map:
return _proxy_map[vtype](value)
elif vtype == list:
return [_map_unity_proxy_to_object(v) for v in value]
elif vtype == dict:
return {k:_map_unity_proxy_to_object(v) for k,v in value.items()}
else:
return value | python | def _map_unity_proxy_to_object(value):
"""
Map returning value, if it is unity SFrame, SArray, map it
"""
vtype = type(value)
if vtype in _proxy_map:
return _proxy_map[vtype](value)
elif vtype == list:
return [_map_unity_proxy_to_object(v) for v in value]
elif vtype == dict:
return {k:_map_unity_proxy_to_object(v) for k,v in value.items()}
else:
return value | [
"def",
"_map_unity_proxy_to_object",
"(",
"value",
")",
":",
"vtype",
"=",
"type",
"(",
"value",
")",
"if",
"vtype",
"in",
"_proxy_map",
":",
"return",
"_proxy_map",
"[",
"vtype",
"]",
"(",
"value",
")",
"elif",
"vtype",
"==",
"list",
":",
"return",
"[",
"_map_unity_proxy_to_object",
"(",
"v",
")",
"for",
"v",
"in",
"value",
"]",
"elif",
"vtype",
"==",
"dict",
":",
"return",
"{",
"k",
":",
"_map_unity_proxy_to_object",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"value",
".",
"items",
"(",
")",
"}",
"else",
":",
"return",
"value"
] | Map returning value, if it is unity SFrame, SArray, map it | [
"Map",
"returning",
"value",
"if",
"it",
"is",
"unity",
"SFrame",
"SArray",
"map",
"it"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L448-L460 |
29,436 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _toolkits_select_columns | def _toolkits_select_columns(dataset, columns):
"""
Same as select columns but redirect runtime error to ToolkitError.
"""
try:
return dataset.select_columns(columns)
except RuntimeError:
missing_features = list(set(columns).difference(set(dataset.column_names())))
raise ToolkitError("Input data does not contain the following columns: " +
"{}".format(missing_features)) | python | def _toolkits_select_columns(dataset, columns):
"""
Same as select columns but redirect runtime error to ToolkitError.
"""
try:
return dataset.select_columns(columns)
except RuntimeError:
missing_features = list(set(columns).difference(set(dataset.column_names())))
raise ToolkitError("Input data does not contain the following columns: " +
"{}".format(missing_features)) | [
"def",
"_toolkits_select_columns",
"(",
"dataset",
",",
"columns",
")",
":",
"try",
":",
"return",
"dataset",
".",
"select_columns",
"(",
"columns",
")",
"except",
"RuntimeError",
":",
"missing_features",
"=",
"list",
"(",
"set",
"(",
"columns",
")",
".",
"difference",
"(",
"set",
"(",
"dataset",
".",
"column_names",
"(",
")",
")",
")",
")",
"raise",
"ToolkitError",
"(",
"\"Input data does not contain the following columns: \"",
"+",
"\"{}\"",
".",
"format",
"(",
"missing_features",
")",
")"
] | Same as select columns but redirect runtime error to ToolkitError. | [
"Same",
"as",
"select",
"columns",
"but",
"redirect",
"runtime",
"error",
"to",
"ToolkitError",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L462-L471 |
29,437 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _raise_error_if_column_exists | def _raise_error_if_column_exists(dataset, column_name = 'dataset',
dataset_variable_name = 'dataset',
column_name_error_message_name = 'column_name'):
"""
Check if a column exists in an SFrame with error message.
"""
err_msg = 'The SFrame {0} must contain the column {1}.'.format(
dataset_variable_name,
column_name_error_message_name)
if column_name not in dataset.column_names():
raise ToolkitError(str(err_msg)) | python | def _raise_error_if_column_exists(dataset, column_name = 'dataset',
dataset_variable_name = 'dataset',
column_name_error_message_name = 'column_name'):
"""
Check if a column exists in an SFrame with error message.
"""
err_msg = 'The SFrame {0} must contain the column {1}.'.format(
dataset_variable_name,
column_name_error_message_name)
if column_name not in dataset.column_names():
raise ToolkitError(str(err_msg)) | [
"def",
"_raise_error_if_column_exists",
"(",
"dataset",
",",
"column_name",
"=",
"'dataset'",
",",
"dataset_variable_name",
"=",
"'dataset'",
",",
"column_name_error_message_name",
"=",
"'column_name'",
")",
":",
"err_msg",
"=",
"'The SFrame {0} must contain the column {1}.'",
".",
"format",
"(",
"dataset_variable_name",
",",
"column_name_error_message_name",
")",
"if",
"column_name",
"not",
"in",
"dataset",
".",
"column_names",
"(",
")",
":",
"raise",
"ToolkitError",
"(",
"str",
"(",
"err_msg",
")",
")"
] | Check if a column exists in an SFrame with error message. | [
"Check",
"if",
"a",
"column",
"exists",
"in",
"an",
"SFrame",
"with",
"error",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L473-L483 |
29,438 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _check_categorical_option_type | def _check_categorical_option_type(option_name, option_value, possible_values):
"""
Check whether or not the requested option is one of the allowed values.
"""
err_msg = '{0} is not a valid option for {1}. '.format(option_value, option_name)
err_msg += ' Expected one of: '.format(possible_values)
err_msg += ', '.join(map(str, possible_values))
if option_value not in possible_values:
raise ToolkitError(err_msg) | python | def _check_categorical_option_type(option_name, option_value, possible_values):
"""
Check whether or not the requested option is one of the allowed values.
"""
err_msg = '{0} is not a valid option for {1}. '.format(option_value, option_name)
err_msg += ' Expected one of: '.format(possible_values)
err_msg += ', '.join(map(str, possible_values))
if option_value not in possible_values:
raise ToolkitError(err_msg) | [
"def",
"_check_categorical_option_type",
"(",
"option_name",
",",
"option_value",
",",
"possible_values",
")",
":",
"err_msg",
"=",
"'{0} is not a valid option for {1}. '",
".",
"format",
"(",
"option_value",
",",
"option_name",
")",
"err_msg",
"+=",
"' Expected one of: '",
".",
"format",
"(",
"possible_values",
")",
"err_msg",
"+=",
"', '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"possible_values",
")",
")",
"if",
"option_value",
"not",
"in",
"possible_values",
":",
"raise",
"ToolkitError",
"(",
"err_msg",
")"
] | Check whether or not the requested option is one of the allowed values. | [
"Check",
"whether",
"or",
"not",
"the",
"requested",
"option",
"is",
"one",
"of",
"the",
"allowed",
"values",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L485-L494 |
29,439 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _raise_error_if_not_sarray | def _raise_error_if_not_sarray(dataset, variable_name="SArray"):
"""
Check if the input is an SArray. Provide a proper error
message otherwise.
"""
err_msg = "Input %s is not an SArray."
if not isinstance(dataset, _SArray):
raise ToolkitError(err_msg % variable_name) | python | def _raise_error_if_not_sarray(dataset, variable_name="SArray"):
"""
Check if the input is an SArray. Provide a proper error
message otherwise.
"""
err_msg = "Input %s is not an SArray."
if not isinstance(dataset, _SArray):
raise ToolkitError(err_msg % variable_name) | [
"def",
"_raise_error_if_not_sarray",
"(",
"dataset",
",",
"variable_name",
"=",
"\"SArray\"",
")",
":",
"err_msg",
"=",
"\"Input %s is not an SArray.\"",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"_SArray",
")",
":",
"raise",
"ToolkitError",
"(",
"err_msg",
"%",
"variable_name",
")"
] | Check if the input is an SArray. Provide a proper error
message otherwise. | [
"Check",
"if",
"the",
"input",
"is",
"an",
"SArray",
".",
"Provide",
"a",
"proper",
"error",
"message",
"otherwise",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L496-L503 |
29,440 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _raise_error_if_sframe_empty | def _raise_error_if_sframe_empty(dataset, variable_name="SFrame"):
"""
Check if the input is empty.
"""
err_msg = "Input %s either has no rows or no columns. A non-empty SFrame "
err_msg += "is required."
if dataset.num_rows() == 0 or dataset.num_columns() == 0:
raise ToolkitError(err_msg % variable_name) | python | def _raise_error_if_sframe_empty(dataset, variable_name="SFrame"):
"""
Check if the input is empty.
"""
err_msg = "Input %s either has no rows or no columns. A non-empty SFrame "
err_msg += "is required."
if dataset.num_rows() == 0 or dataset.num_columns() == 0:
raise ToolkitError(err_msg % variable_name) | [
"def",
"_raise_error_if_sframe_empty",
"(",
"dataset",
",",
"variable_name",
"=",
"\"SFrame\"",
")",
":",
"err_msg",
"=",
"\"Input %s either has no rows or no columns. A non-empty SFrame \"",
"err_msg",
"+=",
"\"is required.\"",
"if",
"dataset",
".",
"num_rows",
"(",
")",
"==",
"0",
"or",
"dataset",
".",
"num_columns",
"(",
")",
"==",
"0",
":",
"raise",
"ToolkitError",
"(",
"err_msg",
"%",
"variable_name",
")"
] | Check if the input is empty. | [
"Check",
"if",
"the",
"input",
"is",
"empty",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L522-L530 |
29,441 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _numeric_param_check_range | def _numeric_param_check_range(variable_name, variable_value, range_bottom, range_top):
"""
Checks if numeric parameter is within given range
"""
err_msg = "%s must be between %i and %i"
if variable_value < range_bottom or variable_value > range_top:
raise ToolkitError(err_msg % (variable_name, range_bottom, range_top)) | python | def _numeric_param_check_range(variable_name, variable_value, range_bottom, range_top):
"""
Checks if numeric parameter is within given range
"""
err_msg = "%s must be between %i and %i"
if variable_value < range_bottom or variable_value > range_top:
raise ToolkitError(err_msg % (variable_name, range_bottom, range_top)) | [
"def",
"_numeric_param_check_range",
"(",
"variable_name",
",",
"variable_value",
",",
"range_bottom",
",",
"range_top",
")",
":",
"err_msg",
"=",
"\"%s must be between %i and %i\"",
"if",
"variable_value",
"<",
"range_bottom",
"or",
"variable_value",
">",
"range_top",
":",
"raise",
"ToolkitError",
"(",
"err_msg",
"%",
"(",
"variable_name",
",",
"range_bottom",
",",
"range_top",
")",
")"
] | Checks if numeric parameter is within given range | [
"Checks",
"if",
"numeric",
"parameter",
"is",
"within",
"given",
"range"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L554-L561 |
29,442 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _validate_data | def _validate_data(dataset, target, features=None, validation_set='auto'):
"""
Validate and canonicalize training and validation data.
Parameters
----------
dataset : SFrame
Dataset for training the model.
target : string
Name of the column containing the target variable.
features : list[string], optional
List of feature names used.
validation_set : SFrame, optional
A dataset for monitoring the model's generalization performance, with
the same schema as the training dataset. Can also be None or 'auto'.
Returns
-------
dataset : SFrame
The input dataset, minus any columns not referenced by target or
features
validation_set : SFrame or str
A canonicalized version of the input validation_set. For SFrame
arguments, the returned SFrame only includes those columns referenced by
target or features. SFrame arguments that do not match the schema of
dataset, or string arguments that are not 'auto', trigger an exception.
"""
_raise_error_if_not_sframe(dataset, "training dataset")
# Determine columns to keep
if features is None:
features = [feat for feat in dataset.column_names() if feat != target]
if not hasattr(features, '__iter__'):
raise TypeError("Input 'features' must be a list.")
if not all([isinstance(x, str) for x in features]):
raise TypeError(
"Invalid feature %s: Feature names must be of type str" % x)
# Check validation_set argument
if isinstance(validation_set, str):
# Only string value allowed is 'auto'
if validation_set != 'auto':
raise TypeError('Unrecognized value for validation_set.')
elif isinstance(validation_set, _SFrame):
# Attempt to append the two datasets together to check schema
validation_set.head().append(dataset.head())
# Reduce validation set to requested columns
validation_set = _toolkits_select_columns(
validation_set, features + [target])
elif not validation_set is None:
raise TypeError("validation_set must be either 'auto', None, or an "
"SFrame matching the training data.")
# Reduce training set to requested columns
dataset = _toolkits_select_columns(dataset, features + [target])
return dataset, validation_set | python | def _validate_data(dataset, target, features=None, validation_set='auto'):
"""
Validate and canonicalize training and validation data.
Parameters
----------
dataset : SFrame
Dataset for training the model.
target : string
Name of the column containing the target variable.
features : list[string], optional
List of feature names used.
validation_set : SFrame, optional
A dataset for monitoring the model's generalization performance, with
the same schema as the training dataset. Can also be None or 'auto'.
Returns
-------
dataset : SFrame
The input dataset, minus any columns not referenced by target or
features
validation_set : SFrame or str
A canonicalized version of the input validation_set. For SFrame
arguments, the returned SFrame only includes those columns referenced by
target or features. SFrame arguments that do not match the schema of
dataset, or string arguments that are not 'auto', trigger an exception.
"""
_raise_error_if_not_sframe(dataset, "training dataset")
# Determine columns to keep
if features is None:
features = [feat for feat in dataset.column_names() if feat != target]
if not hasattr(features, '__iter__'):
raise TypeError("Input 'features' must be a list.")
if not all([isinstance(x, str) for x in features]):
raise TypeError(
"Invalid feature %s: Feature names must be of type str" % x)
# Check validation_set argument
if isinstance(validation_set, str):
# Only string value allowed is 'auto'
if validation_set != 'auto':
raise TypeError('Unrecognized value for validation_set.')
elif isinstance(validation_set, _SFrame):
# Attempt to append the two datasets together to check schema
validation_set.head().append(dataset.head())
# Reduce validation set to requested columns
validation_set = _toolkits_select_columns(
validation_set, features + [target])
elif not validation_set is None:
raise TypeError("validation_set must be either 'auto', None, or an "
"SFrame matching the training data.")
# Reduce training set to requested columns
dataset = _toolkits_select_columns(dataset, features + [target])
return dataset, validation_set | [
"def",
"_validate_data",
"(",
"dataset",
",",
"target",
",",
"features",
"=",
"None",
",",
"validation_set",
"=",
"'auto'",
")",
":",
"_raise_error_if_not_sframe",
"(",
"dataset",
",",
"\"training dataset\"",
")",
"# Determine columns to keep",
"if",
"features",
"is",
"None",
":",
"features",
"=",
"[",
"feat",
"for",
"feat",
"in",
"dataset",
".",
"column_names",
"(",
")",
"if",
"feat",
"!=",
"target",
"]",
"if",
"not",
"hasattr",
"(",
"features",
",",
"'__iter__'",
")",
":",
"raise",
"TypeError",
"(",
"\"Input 'features' must be a list.\"",
")",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"str",
")",
"for",
"x",
"in",
"features",
"]",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid feature %s: Feature names must be of type str\"",
"%",
"x",
")",
"# Check validation_set argument",
"if",
"isinstance",
"(",
"validation_set",
",",
"str",
")",
":",
"# Only string value allowed is 'auto'",
"if",
"validation_set",
"!=",
"'auto'",
":",
"raise",
"TypeError",
"(",
"'Unrecognized value for validation_set.'",
")",
"elif",
"isinstance",
"(",
"validation_set",
",",
"_SFrame",
")",
":",
"# Attempt to append the two datasets together to check schema",
"validation_set",
".",
"head",
"(",
")",
".",
"append",
"(",
"dataset",
".",
"head",
"(",
")",
")",
"# Reduce validation set to requested columns",
"validation_set",
"=",
"_toolkits_select_columns",
"(",
"validation_set",
",",
"features",
"+",
"[",
"target",
"]",
")",
"elif",
"not",
"validation_set",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"validation_set must be either 'auto', None, or an \"",
"\"SFrame matching the training data.\"",
")",
"# Reduce training set to requested columns",
"dataset",
"=",
"_toolkits_select_columns",
"(",
"dataset",
",",
"features",
"+",
"[",
"target",
"]",
")",
"return",
"dataset",
",",
"validation_set"
] | Validate and canonicalize training and validation data.
Parameters
----------
dataset : SFrame
Dataset for training the model.
target : string
Name of the column containing the target variable.
features : list[string], optional
List of feature names used.
validation_set : SFrame, optional
A dataset for monitoring the model's generalization performance, with
the same schema as the training dataset. Can also be None or 'auto'.
Returns
-------
dataset : SFrame
The input dataset, minus any columns not referenced by target or
features
validation_set : SFrame or str
A canonicalized version of the input validation_set. For SFrame
arguments, the returned SFrame only includes those columns referenced by
target or features. SFrame arguments that do not match the schema of
dataset, or string arguments that are not 'auto', trigger an exception. | [
"Validate",
"and",
"canonicalize",
"training",
"and",
"validation",
"data",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L563-L625 |
29,443 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _validate_row_label | def _validate_row_label(dataset, label=None, default_label='__id'):
"""
Validate a row label column. If the row label is not specified, a column is
created with row numbers, named with the string in the `default_label`
parameter.
Parameters
----------
dataset : SFrame
Input dataset.
label : str, optional
Name of the column containing row labels.
default_label : str, optional
The default column name if `label` is not specified. A column with row
numbers is added to the output SFrame in this case.
Returns
-------
dataset : SFrame
The input dataset, but with an additional row label column, *if* there
was no input label.
label : str
The final label column name.
"""
## If no label is provided, set it to be a default and add a row number to
# dataset. Check that this new name does not conflict with an existing
# name.
if not label:
## Try a bunch of variations of the default label to find one that's not
# already a column name.
label_name_base = default_label
label = default_label
i = 1
while label in dataset.column_names():
label = label_name_base + '.{}'.format(i)
i += 1
dataset = dataset.add_row_number(column_name=label)
## Validate the label name and types.
if not isinstance(label, str):
raise TypeError("The row label column name '{}' must be a string.".format(label))
if not label in dataset.column_names():
raise ToolkitError("Row label column '{}' not found in the dataset.".format(label))
if not dataset[label].dtype in (str, int):
raise TypeError("Row labels must be integers or strings.")
## Return the modified dataset and label
return dataset, label | python | def _validate_row_label(dataset, label=None, default_label='__id'):
"""
Validate a row label column. If the row label is not specified, a column is
created with row numbers, named with the string in the `default_label`
parameter.
Parameters
----------
dataset : SFrame
Input dataset.
label : str, optional
Name of the column containing row labels.
default_label : str, optional
The default column name if `label` is not specified. A column with row
numbers is added to the output SFrame in this case.
Returns
-------
dataset : SFrame
The input dataset, but with an additional row label column, *if* there
was no input label.
label : str
The final label column name.
"""
## If no label is provided, set it to be a default and add a row number to
# dataset. Check that this new name does not conflict with an existing
# name.
if not label:
## Try a bunch of variations of the default label to find one that's not
# already a column name.
label_name_base = default_label
label = default_label
i = 1
while label in dataset.column_names():
label = label_name_base + '.{}'.format(i)
i += 1
dataset = dataset.add_row_number(column_name=label)
## Validate the label name and types.
if not isinstance(label, str):
raise TypeError("The row label column name '{}' must be a string.".format(label))
if not label in dataset.column_names():
raise ToolkitError("Row label column '{}' not found in the dataset.".format(label))
if not dataset[label].dtype in (str, int):
raise TypeError("Row labels must be integers or strings.")
## Return the modified dataset and label
return dataset, label | [
"def",
"_validate_row_label",
"(",
"dataset",
",",
"label",
"=",
"None",
",",
"default_label",
"=",
"'__id'",
")",
":",
"## If no label is provided, set it to be a default and add a row number to",
"# dataset. Check that this new name does not conflict with an existing",
"# name.",
"if",
"not",
"label",
":",
"## Try a bunch of variations of the default label to find one that's not",
"# already a column name.",
"label_name_base",
"=",
"default_label",
"label",
"=",
"default_label",
"i",
"=",
"1",
"while",
"label",
"in",
"dataset",
".",
"column_names",
"(",
")",
":",
"label",
"=",
"label_name_base",
"+",
"'.{}'",
".",
"format",
"(",
"i",
")",
"i",
"+=",
"1",
"dataset",
"=",
"dataset",
".",
"add_row_number",
"(",
"column_name",
"=",
"label",
")",
"## Validate the label name and types.",
"if",
"not",
"isinstance",
"(",
"label",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"The row label column name '{}' must be a string.\"",
".",
"format",
"(",
"label",
")",
")",
"if",
"not",
"label",
"in",
"dataset",
".",
"column_names",
"(",
")",
":",
"raise",
"ToolkitError",
"(",
"\"Row label column '{}' not found in the dataset.\"",
".",
"format",
"(",
"label",
")",
")",
"if",
"not",
"dataset",
"[",
"label",
"]",
".",
"dtype",
"in",
"(",
"str",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Row labels must be integers or strings.\"",
")",
"## Return the modified dataset and label",
"return",
"dataset",
",",
"label"
] | Validate a row label column. If the row label is not specified, a column is
created with row numbers, named with the string in the `default_label`
parameter.
Parameters
----------
dataset : SFrame
Input dataset.
label : str, optional
Name of the column containing row labels.
default_label : str, optional
The default column name if `label` is not specified. A column with row
numbers is added to the output SFrame in this case.
Returns
-------
dataset : SFrame
The input dataset, but with an additional row label column, *if* there
was no input label.
label : str
The final label column name. | [
"Validate",
"a",
"row",
"label",
"column",
".",
"If",
"the",
"row",
"label",
"is",
"not",
"specified",
"a",
"column",
"is",
"created",
"with",
"row",
"numbers",
"named",
"with",
"the",
"string",
"in",
"the",
"default_label",
"parameter",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L627-L682 |
29,444 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _mac_ver | def _mac_ver():
"""
Returns Mac version as a tuple of integers, making it easy to do proper
version comparisons. On non-Macs, it returns an empty tuple.
"""
import platform
import sys
if sys.platform == 'darwin':
ver_str = platform.mac_ver()[0]
return tuple([int(v) for v in ver_str.split('.')])
else:
return () | python | def _mac_ver():
"""
Returns Mac version as a tuple of integers, making it easy to do proper
version comparisons. On non-Macs, it returns an empty tuple.
"""
import platform
import sys
if sys.platform == 'darwin':
ver_str = platform.mac_ver()[0]
return tuple([int(v) for v in ver_str.split('.')])
else:
return () | [
"def",
"_mac_ver",
"(",
")",
":",
"import",
"platform",
"import",
"sys",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"ver_str",
"=",
"platform",
".",
"mac_ver",
"(",
")",
"[",
"0",
"]",
"return",
"tuple",
"(",
"[",
"int",
"(",
"v",
")",
"for",
"v",
"in",
"ver_str",
".",
"split",
"(",
"'.'",
")",
"]",
")",
"else",
":",
"return",
"(",
")"
] | Returns Mac version as a tuple of integers, making it easy to do proper
version comparisons. On non-Macs, it returns an empty tuple. | [
"Returns",
"Mac",
"version",
"as",
"a",
"tuple",
"of",
"integers",
"making",
"it",
"easy",
"to",
"do",
"proper",
"version",
"comparisons",
".",
"On",
"non",
"-",
"Macs",
"it",
"returns",
"an",
"empty",
"tuple",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L698-L709 |
29,445 | apple/turicreate | src/unity/python/turicreate/toolkits/_internal_utils.py | _print_neural_compute_device | def _print_neural_compute_device(cuda_gpus, use_mps, cuda_mem_req=None, has_mps_impl=True):
"""
Print a message making it clear to the user what compute resource is used in
neural network training.
"""
num_cuda_gpus = len(cuda_gpus)
if num_cuda_gpus >= 1:
gpu_names = ', '.join(gpu['name'] for gpu in cuda_gpus)
if use_mps:
from ._mps_utils import mps_device_name
print('Using GPU to create model ({})'.format(mps_device_name()))
elif num_cuda_gpus >= 1:
from . import _mxnet_utils
plural = 's' if num_cuda_gpus >= 2 else ''
print('Using GPU{} to create model ({})'.format(plural, gpu_names))
if cuda_mem_req is not None:
_mxnet_utils._warn_if_less_than_cuda_free_memory(cuda_mem_req, max_devices=num_cuda_gpus)
else:
import sys
print('Using CPU to create model')
if sys.platform == 'darwin' and _mac_ver() < (10, 14) and has_mps_impl:
print('NOTE: If available, an AMD GPU can be leveraged on macOS 10.14+ for faster model creation') | python | def _print_neural_compute_device(cuda_gpus, use_mps, cuda_mem_req=None, has_mps_impl=True):
"""
Print a message making it clear to the user what compute resource is used in
neural network training.
"""
num_cuda_gpus = len(cuda_gpus)
if num_cuda_gpus >= 1:
gpu_names = ', '.join(gpu['name'] for gpu in cuda_gpus)
if use_mps:
from ._mps_utils import mps_device_name
print('Using GPU to create model ({})'.format(mps_device_name()))
elif num_cuda_gpus >= 1:
from . import _mxnet_utils
plural = 's' if num_cuda_gpus >= 2 else ''
print('Using GPU{} to create model ({})'.format(plural, gpu_names))
if cuda_mem_req is not None:
_mxnet_utils._warn_if_less_than_cuda_free_memory(cuda_mem_req, max_devices=num_cuda_gpus)
else:
import sys
print('Using CPU to create model')
if sys.platform == 'darwin' and _mac_ver() < (10, 14) and has_mps_impl:
print('NOTE: If available, an AMD GPU can be leveraged on macOS 10.14+ for faster model creation') | [
"def",
"_print_neural_compute_device",
"(",
"cuda_gpus",
",",
"use_mps",
",",
"cuda_mem_req",
"=",
"None",
",",
"has_mps_impl",
"=",
"True",
")",
":",
"num_cuda_gpus",
"=",
"len",
"(",
"cuda_gpus",
")",
"if",
"num_cuda_gpus",
">=",
"1",
":",
"gpu_names",
"=",
"', '",
".",
"join",
"(",
"gpu",
"[",
"'name'",
"]",
"for",
"gpu",
"in",
"cuda_gpus",
")",
"if",
"use_mps",
":",
"from",
".",
"_mps_utils",
"import",
"mps_device_name",
"print",
"(",
"'Using GPU to create model ({})'",
".",
"format",
"(",
"mps_device_name",
"(",
")",
")",
")",
"elif",
"num_cuda_gpus",
">=",
"1",
":",
"from",
".",
"import",
"_mxnet_utils",
"plural",
"=",
"'s'",
"if",
"num_cuda_gpus",
">=",
"2",
"else",
"''",
"print",
"(",
"'Using GPU{} to create model ({})'",
".",
"format",
"(",
"plural",
",",
"gpu_names",
")",
")",
"if",
"cuda_mem_req",
"is",
"not",
"None",
":",
"_mxnet_utils",
".",
"_warn_if_less_than_cuda_free_memory",
"(",
"cuda_mem_req",
",",
"max_devices",
"=",
"num_cuda_gpus",
")",
"else",
":",
"import",
"sys",
"print",
"(",
"'Using CPU to create model'",
")",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
"and",
"_mac_ver",
"(",
")",
"<",
"(",
"10",
",",
"14",
")",
"and",
"has_mps_impl",
":",
"print",
"(",
"'NOTE: If available, an AMD GPU can be leveraged on macOS 10.14+ for faster model creation'",
")"
] | Print a message making it clear to the user what compute resource is used in
neural network training. | [
"Print",
"a",
"message",
"making",
"it",
"clear",
"to",
"the",
"user",
"what",
"compute",
"resource",
"is",
"used",
"in",
"neural",
"network",
"training",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_internal_utils.py#L711-L733 |
29,446 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/proto_builder.py | _GetMessageFromFactory | def _GetMessageFromFactory(factory, full_name):
"""Get a proto class from the MessageFactory by name.
Args:
factory: a MessageFactory instance.
full_name: str, the fully qualified name of the proto type.
Returns:
A class, for the type identified by full_name.
Raises:
KeyError, if the proto is not found in the factory's descriptor pool.
"""
proto_descriptor = factory.pool.FindMessageTypeByName(full_name)
proto_cls = factory.GetPrototype(proto_descriptor)
return proto_cls | python | def _GetMessageFromFactory(factory, full_name):
"""Get a proto class from the MessageFactory by name.
Args:
factory: a MessageFactory instance.
full_name: str, the fully qualified name of the proto type.
Returns:
A class, for the type identified by full_name.
Raises:
KeyError, if the proto is not found in the factory's descriptor pool.
"""
proto_descriptor = factory.pool.FindMessageTypeByName(full_name)
proto_cls = factory.GetPrototype(proto_descriptor)
return proto_cls | [
"def",
"_GetMessageFromFactory",
"(",
"factory",
",",
"full_name",
")",
":",
"proto_descriptor",
"=",
"factory",
".",
"pool",
".",
"FindMessageTypeByName",
"(",
"full_name",
")",
"proto_cls",
"=",
"factory",
".",
"GetPrototype",
"(",
"proto_descriptor",
")",
"return",
"proto_cls"
] | Get a proto class from the MessageFactory by name.
Args:
factory: a MessageFactory instance.
full_name: str, the fully qualified name of the proto type.
Returns:
A class, for the type identified by full_name.
Raises:
KeyError, if the proto is not found in the factory's descriptor pool. | [
"Get",
"a",
"proto",
"class",
"from",
"the",
"MessageFactory",
"by",
"name",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/proto_builder.py#L44-L57 |
29,447 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/proto_builder.py | MakeSimpleProtoClass | def MakeSimpleProtoClass(fields, full_name=None, pool=None):
"""Create a Protobuf class whose fields are basic types.
Note: this doesn't validate field names!
Args:
fields: dict of {name: field_type} mappings for each field in the proto. If
this is an OrderedDict the order will be maintained, otherwise the
fields will be sorted by name.
full_name: optional str, the fully-qualified name of the proto type.
pool: optional DescriptorPool instance.
Returns:
a class, the new protobuf class with a FileDescriptor.
"""
factory = message_factory.MessageFactory(pool=pool)
if full_name is not None:
try:
proto_cls = _GetMessageFromFactory(factory, full_name)
return proto_cls
except KeyError:
# The factory's DescriptorPool doesn't know about this class yet.
pass
# Get a list of (name, field_type) tuples from the fields dict. If fields was
# an OrderedDict we keep the order, but otherwise we sort the field to ensure
# consistent ordering.
field_items = fields.items()
if not isinstance(fields, OrderedDict):
field_items = sorted(field_items)
# Use a consistent file name that is unlikely to conflict with any imported
# proto files.
fields_hash = hashlib.sha1()
for f_name, f_type in field_items:
fields_hash.update(f_name.encode('utf-8'))
fields_hash.update(str(f_type).encode('utf-8'))
proto_file_name = fields_hash.hexdigest() + '.proto'
# If the proto is anonymous, use the same hash to name it.
if full_name is None:
full_name = ('net.proto2.python.public.proto_builder.AnonymousProto_' +
fields_hash.hexdigest())
try:
proto_cls = _GetMessageFromFactory(factory, full_name)
return proto_cls
except KeyError:
# The factory's DescriptorPool doesn't know about this class yet.
pass
# This is the first time we see this proto: add a new descriptor to the pool.
factory.pool.Add(
_MakeFileDescriptorProto(proto_file_name, full_name, field_items))
return _GetMessageFromFactory(factory, full_name) | python | def MakeSimpleProtoClass(fields, full_name=None, pool=None):
"""Create a Protobuf class whose fields are basic types.
Note: this doesn't validate field names!
Args:
fields: dict of {name: field_type} mappings for each field in the proto. If
this is an OrderedDict the order will be maintained, otherwise the
fields will be sorted by name.
full_name: optional str, the fully-qualified name of the proto type.
pool: optional DescriptorPool instance.
Returns:
a class, the new protobuf class with a FileDescriptor.
"""
factory = message_factory.MessageFactory(pool=pool)
if full_name is not None:
try:
proto_cls = _GetMessageFromFactory(factory, full_name)
return proto_cls
except KeyError:
# The factory's DescriptorPool doesn't know about this class yet.
pass
# Get a list of (name, field_type) tuples from the fields dict. If fields was
# an OrderedDict we keep the order, but otherwise we sort the field to ensure
# consistent ordering.
field_items = fields.items()
if not isinstance(fields, OrderedDict):
field_items = sorted(field_items)
# Use a consistent file name that is unlikely to conflict with any imported
# proto files.
fields_hash = hashlib.sha1()
for f_name, f_type in field_items:
fields_hash.update(f_name.encode('utf-8'))
fields_hash.update(str(f_type).encode('utf-8'))
proto_file_name = fields_hash.hexdigest() + '.proto'
# If the proto is anonymous, use the same hash to name it.
if full_name is None:
full_name = ('net.proto2.python.public.proto_builder.AnonymousProto_' +
fields_hash.hexdigest())
try:
proto_cls = _GetMessageFromFactory(factory, full_name)
return proto_cls
except KeyError:
# The factory's DescriptorPool doesn't know about this class yet.
pass
# This is the first time we see this proto: add a new descriptor to the pool.
factory.pool.Add(
_MakeFileDescriptorProto(proto_file_name, full_name, field_items))
return _GetMessageFromFactory(factory, full_name) | [
"def",
"MakeSimpleProtoClass",
"(",
"fields",
",",
"full_name",
"=",
"None",
",",
"pool",
"=",
"None",
")",
":",
"factory",
"=",
"message_factory",
".",
"MessageFactory",
"(",
"pool",
"=",
"pool",
")",
"if",
"full_name",
"is",
"not",
"None",
":",
"try",
":",
"proto_cls",
"=",
"_GetMessageFromFactory",
"(",
"factory",
",",
"full_name",
")",
"return",
"proto_cls",
"except",
"KeyError",
":",
"# The factory's DescriptorPool doesn't know about this class yet.",
"pass",
"# Get a list of (name, field_type) tuples from the fields dict. If fields was",
"# an OrderedDict we keep the order, but otherwise we sort the field to ensure",
"# consistent ordering.",
"field_items",
"=",
"fields",
".",
"items",
"(",
")",
"if",
"not",
"isinstance",
"(",
"fields",
",",
"OrderedDict",
")",
":",
"field_items",
"=",
"sorted",
"(",
"field_items",
")",
"# Use a consistent file name that is unlikely to conflict with any imported",
"# proto files.",
"fields_hash",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"for",
"f_name",
",",
"f_type",
"in",
"field_items",
":",
"fields_hash",
".",
"update",
"(",
"f_name",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"fields_hash",
".",
"update",
"(",
"str",
"(",
"f_type",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"proto_file_name",
"=",
"fields_hash",
".",
"hexdigest",
"(",
")",
"+",
"'.proto'",
"# If the proto is anonymous, use the same hash to name it.",
"if",
"full_name",
"is",
"None",
":",
"full_name",
"=",
"(",
"'net.proto2.python.public.proto_builder.AnonymousProto_'",
"+",
"fields_hash",
".",
"hexdigest",
"(",
")",
")",
"try",
":",
"proto_cls",
"=",
"_GetMessageFromFactory",
"(",
"factory",
",",
"full_name",
")",
"return",
"proto_cls",
"except",
"KeyError",
":",
"# The factory's DescriptorPool doesn't know about this class yet.",
"pass",
"# This is the first time we see this proto: add a new descriptor to the pool.",
"factory",
".",
"pool",
".",
"Add",
"(",
"_MakeFileDescriptorProto",
"(",
"proto_file_name",
",",
"full_name",
",",
"field_items",
")",
")",
"return",
"_GetMessageFromFactory",
"(",
"factory",
",",
"full_name",
")"
] | Create a Protobuf class whose fields are basic types.
Note: this doesn't validate field names!
Args:
fields: dict of {name: field_type} mappings for each field in the proto. If
this is an OrderedDict the order will be maintained, otherwise the
fields will be sorted by name.
full_name: optional str, the fully-qualified name of the proto type.
pool: optional DescriptorPool instance.
Returns:
a class, the new protobuf class with a FileDescriptor. | [
"Create",
"a",
"Protobuf",
"class",
"whose",
"fields",
"are",
"basic",
"types",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/proto_builder.py#L60-L113 |
29,448 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/proto_builder.py | _MakeFileDescriptorProto | def _MakeFileDescriptorProto(proto_file_name, full_name, field_items):
"""Populate FileDescriptorProto for MessageFactory's DescriptorPool."""
package, name = full_name.rsplit('.', 1)
file_proto = descriptor_pb2.FileDescriptorProto()
file_proto.name = os.path.join(package.replace('.', '/'), proto_file_name)
file_proto.package = package
desc_proto = file_proto.message_type.add()
desc_proto.name = name
for f_number, (f_name, f_type) in enumerate(field_items, 1):
field_proto = desc_proto.field.add()
field_proto.name = f_name
field_proto.number = f_number
field_proto.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
field_proto.type = f_type
return file_proto | python | def _MakeFileDescriptorProto(proto_file_name, full_name, field_items):
"""Populate FileDescriptorProto for MessageFactory's DescriptorPool."""
package, name = full_name.rsplit('.', 1)
file_proto = descriptor_pb2.FileDescriptorProto()
file_proto.name = os.path.join(package.replace('.', '/'), proto_file_name)
file_proto.package = package
desc_proto = file_proto.message_type.add()
desc_proto.name = name
for f_number, (f_name, f_type) in enumerate(field_items, 1):
field_proto = desc_proto.field.add()
field_proto.name = f_name
field_proto.number = f_number
field_proto.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
field_proto.type = f_type
return file_proto | [
"def",
"_MakeFileDescriptorProto",
"(",
"proto_file_name",
",",
"full_name",
",",
"field_items",
")",
":",
"package",
",",
"name",
"=",
"full_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"file_proto",
"=",
"descriptor_pb2",
".",
"FileDescriptorProto",
"(",
")",
"file_proto",
".",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"package",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
",",
"proto_file_name",
")",
"file_proto",
".",
"package",
"=",
"package",
"desc_proto",
"=",
"file_proto",
".",
"message_type",
".",
"add",
"(",
")",
"desc_proto",
".",
"name",
"=",
"name",
"for",
"f_number",
",",
"(",
"f_name",
",",
"f_type",
")",
"in",
"enumerate",
"(",
"field_items",
",",
"1",
")",
":",
"field_proto",
"=",
"desc_proto",
".",
"field",
".",
"add",
"(",
")",
"field_proto",
".",
"name",
"=",
"f_name",
"field_proto",
".",
"number",
"=",
"f_number",
"field_proto",
".",
"label",
"=",
"descriptor_pb2",
".",
"FieldDescriptorProto",
".",
"LABEL_OPTIONAL",
"field_proto",
".",
"type",
"=",
"f_type",
"return",
"file_proto"
] | Populate FileDescriptorProto for MessageFactory's DescriptorPool. | [
"Populate",
"FileDescriptorProto",
"for",
"MessageFactory",
"s",
"DescriptorPool",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/proto_builder.py#L116-L130 |
29,449 | apple/turicreate | src/unity/python/turicreate/toolkits/_coreml_utils.py | _get_model_metadata | def _get_model_metadata(model_class, metadata, version=None):
"""
Returns user-defined metadata, making sure information all models should
have is also available, as a dictionary
"""
from turicreate import __version__
info = {
'turicreate_version': __version__,
'type': model_class,
}
if version is not None:
info['version'] = str(version)
info.update(metadata)
return info | python | def _get_model_metadata(model_class, metadata, version=None):
"""
Returns user-defined metadata, making sure information all models should
have is also available, as a dictionary
"""
from turicreate import __version__
info = {
'turicreate_version': __version__,
'type': model_class,
}
if version is not None:
info['version'] = str(version)
info.update(metadata)
return info | [
"def",
"_get_model_metadata",
"(",
"model_class",
",",
"metadata",
",",
"version",
"=",
"None",
")",
":",
"from",
"turicreate",
"import",
"__version__",
"info",
"=",
"{",
"'turicreate_version'",
":",
"__version__",
",",
"'type'",
":",
"model_class",
",",
"}",
"if",
"version",
"is",
"not",
"None",
":",
"info",
"[",
"'version'",
"]",
"=",
"str",
"(",
"version",
")",
"info",
".",
"update",
"(",
"metadata",
")",
"return",
"info"
] | Returns user-defined metadata, making sure information all models should
have is also available, as a dictionary | [
"Returns",
"user",
"-",
"defined",
"metadata",
"making",
"sure",
"information",
"all",
"models",
"should",
"have",
"is",
"also",
"available",
"as",
"a",
"dictionary"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_coreml_utils.py#L16-L29 |
29,450 | apple/turicreate | src/unity/python/turicreate/toolkits/_coreml_utils.py | _set_model_metadata | def _set_model_metadata(mlmodel, model_class, metadata, version=None):
"""
Sets user-defined metadata, making sure information all models should have
is also available
"""
info = _get_model_metadata(model_class, metadata, version)
mlmodel.user_defined_metadata.update(info) | python | def _set_model_metadata(mlmodel, model_class, metadata, version=None):
"""
Sets user-defined metadata, making sure information all models should have
is also available
"""
info = _get_model_metadata(model_class, metadata, version)
mlmodel.user_defined_metadata.update(info) | [
"def",
"_set_model_metadata",
"(",
"mlmodel",
",",
"model_class",
",",
"metadata",
",",
"version",
"=",
"None",
")",
":",
"info",
"=",
"_get_model_metadata",
"(",
"model_class",
",",
"metadata",
",",
"version",
")",
"mlmodel",
".",
"user_defined_metadata",
".",
"update",
"(",
"info",
")"
] | Sets user-defined metadata, making sure information all models should have
is also available | [
"Sets",
"user",
"-",
"defined",
"metadata",
"making",
"sure",
"information",
"all",
"models",
"should",
"have",
"is",
"also",
"available"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_coreml_utils.py#L32-L38 |
29,451 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py | _ToCamelCase | def _ToCamelCase(name):
"""Converts name to camel-case and returns it."""
capitalize_next = False
result = []
for c in name:
if c == '_':
if result:
capitalize_next = True
elif capitalize_next:
result.append(c.upper())
capitalize_next = False
else:
result += c
# Lower-case the first letter.
if result and result[0].isupper():
result[0] = result[0].lower()
return ''.join(result) | python | def _ToCamelCase(name):
"""Converts name to camel-case and returns it."""
capitalize_next = False
result = []
for c in name:
if c == '_':
if result:
capitalize_next = True
elif capitalize_next:
result.append(c.upper())
capitalize_next = False
else:
result += c
# Lower-case the first letter.
if result and result[0].isupper():
result[0] = result[0].lower()
return ''.join(result) | [
"def",
"_ToCamelCase",
"(",
"name",
")",
":",
"capitalize_next",
"=",
"False",
"result",
"=",
"[",
"]",
"for",
"c",
"in",
"name",
":",
"if",
"c",
"==",
"'_'",
":",
"if",
"result",
":",
"capitalize_next",
"=",
"True",
"elif",
"capitalize_next",
":",
"result",
".",
"append",
"(",
"c",
".",
"upper",
"(",
")",
")",
"capitalize_next",
"=",
"False",
"else",
":",
"result",
"+=",
"c",
"# Lower-case the first letter.",
"if",
"result",
"and",
"result",
"[",
"0",
"]",
".",
"isupper",
"(",
")",
":",
"result",
"[",
"0",
"]",
"=",
"result",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | Converts name to camel-case and returns it. | [
"Converts",
"name",
"to",
"camel",
"-",
"case",
"and",
"returns",
"it",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py#L873-L891 |
29,452 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py | _ToJsonName | def _ToJsonName(name):
"""Converts name to Json name and returns it."""
capitalize_next = False
result = []
for c in name:
if c == '_':
capitalize_next = True
elif capitalize_next:
result.append(c.upper())
capitalize_next = False
else:
result += c
return ''.join(result) | python | def _ToJsonName(name):
"""Converts name to Json name and returns it."""
capitalize_next = False
result = []
for c in name:
if c == '_':
capitalize_next = True
elif capitalize_next:
result.append(c.upper())
capitalize_next = False
else:
result += c
return ''.join(result) | [
"def",
"_ToJsonName",
"(",
"name",
")",
":",
"capitalize_next",
"=",
"False",
"result",
"=",
"[",
"]",
"for",
"c",
"in",
"name",
":",
"if",
"c",
"==",
"'_'",
":",
"capitalize_next",
"=",
"True",
"elif",
"capitalize_next",
":",
"result",
".",
"append",
"(",
"c",
".",
"upper",
"(",
")",
")",
"capitalize_next",
"=",
"False",
"else",
":",
"result",
"+=",
"c",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | Converts name to Json name and returns it. | [
"Converts",
"name",
"to",
"Json",
"name",
"and",
"returns",
"it",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py#L902-L916 |
29,453 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py | DescriptorBase._SetOptions | def _SetOptions(self, options, options_class_name):
"""Sets the descriptor's options
This function is used in generated proto2 files to update descriptor
options. It must not be used outside proto2.
"""
self._options = options
self._options_class_name = options_class_name
# Does this descriptor have non-default options?
self.has_options = options is not None | python | def _SetOptions(self, options, options_class_name):
"""Sets the descriptor's options
This function is used in generated proto2 files to update descriptor
options. It must not be used outside proto2.
"""
self._options = options
self._options_class_name = options_class_name
# Does this descriptor have non-default options?
self.has_options = options is not None | [
"def",
"_SetOptions",
"(",
"self",
",",
"options",
",",
"options_class_name",
")",
":",
"self",
".",
"_options",
"=",
"options",
"self",
".",
"_options_class_name",
"=",
"options_class_name",
"# Does this descriptor have non-default options?",
"self",
".",
"has_options",
"=",
"options",
"is",
"not",
"None"
] | Sets the descriptor's options
This function is used in generated proto2 files to update descriptor
options. It must not be used outside proto2. | [
"Sets",
"the",
"descriptor",
"s",
"options"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py#L106-L116 |
29,454 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py | DescriptorBase.GetOptions | def GetOptions(self):
"""Retrieves descriptor options.
This method returns the options set or creates the default options for the
descriptor.
"""
if self._options:
return self._options
from google.protobuf import descriptor_pb2
try:
options_class = getattr(descriptor_pb2, self._options_class_name)
except AttributeError:
raise RuntimeError('Unknown options class name %s!' %
(self._options_class_name))
self._options = options_class()
return self._options | python | def GetOptions(self):
"""Retrieves descriptor options.
This method returns the options set or creates the default options for the
descriptor.
"""
if self._options:
return self._options
from google.protobuf import descriptor_pb2
try:
options_class = getattr(descriptor_pb2, self._options_class_name)
except AttributeError:
raise RuntimeError('Unknown options class name %s!' %
(self._options_class_name))
self._options = options_class()
return self._options | [
"def",
"GetOptions",
"(",
"self",
")",
":",
"if",
"self",
".",
"_options",
":",
"return",
"self",
".",
"_options",
"from",
"google",
".",
"protobuf",
"import",
"descriptor_pb2",
"try",
":",
"options_class",
"=",
"getattr",
"(",
"descriptor_pb2",
",",
"self",
".",
"_options_class_name",
")",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
"(",
"'Unknown options class name %s!'",
"%",
"(",
"self",
".",
"_options_class_name",
")",
")",
"self",
".",
"_options",
"=",
"options_class",
"(",
")",
"return",
"self",
".",
"_options"
] | Retrieves descriptor options.
This method returns the options set or creates the default options for the
descriptor. | [
"Retrieves",
"descriptor",
"options",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py#L118-L133 |
29,455 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py | _NestedDescriptorBase.CopyToProto | def CopyToProto(self, proto):
"""Copies this to the matching proto in descriptor_pb2.
Args:
proto: An empty proto instance from descriptor_pb2.
Raises:
Error: If self couldnt be serialized, due to to few constructor arguments.
"""
if (self.file is not None and
self._serialized_start is not None and
self._serialized_end is not None):
proto.ParseFromString(self.file.serialized_pb[
self._serialized_start:self._serialized_end])
else:
raise Error('Descriptor does not contain serialization.') | python | def CopyToProto(self, proto):
"""Copies this to the matching proto in descriptor_pb2.
Args:
proto: An empty proto instance from descriptor_pb2.
Raises:
Error: If self couldnt be serialized, due to to few constructor arguments.
"""
if (self.file is not None and
self._serialized_start is not None and
self._serialized_end is not None):
proto.ParseFromString(self.file.serialized_pb[
self._serialized_start:self._serialized_end])
else:
raise Error('Descriptor does not contain serialization.') | [
"def",
"CopyToProto",
"(",
"self",
",",
"proto",
")",
":",
"if",
"(",
"self",
".",
"file",
"is",
"not",
"None",
"and",
"self",
".",
"_serialized_start",
"is",
"not",
"None",
"and",
"self",
".",
"_serialized_end",
"is",
"not",
"None",
")",
":",
"proto",
".",
"ParseFromString",
"(",
"self",
".",
"file",
".",
"serialized_pb",
"[",
"self",
".",
"_serialized_start",
":",
"self",
".",
"_serialized_end",
"]",
")",
"else",
":",
"raise",
"Error",
"(",
"'Descriptor does not contain serialization.'",
")"
] | Copies this to the matching proto in descriptor_pb2.
Args:
proto: An empty proto instance from descriptor_pb2.
Raises:
Error: If self couldnt be serialized, due to to few constructor arguments. | [
"Copies",
"this",
"to",
"the",
"matching",
"proto",
"in",
"descriptor_pb2",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py#L174-L189 |
29,456 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py | Descriptor.EnumValueName | def EnumValueName(self, enum, value):
"""Returns the string name of an enum value.
This is just a small helper method to simplify a common operation.
Args:
enum: string name of the Enum.
value: int, value of the enum.
Returns:
string name of the enum value.
Raises:
KeyError if either the Enum doesn't exist or the value is not a valid
value for the enum.
"""
return self.enum_types_by_name[enum].values_by_number[value].name | python | def EnumValueName(self, enum, value):
"""Returns the string name of an enum value.
This is just a small helper method to simplify a common operation.
Args:
enum: string name of the Enum.
value: int, value of the enum.
Returns:
string name of the enum value.
Raises:
KeyError if either the Enum doesn't exist or the value is not a valid
value for the enum.
"""
return self.enum_types_by_name[enum].values_by_number[value].name | [
"def",
"EnumValueName",
"(",
"self",
",",
"enum",
",",
"value",
")",
":",
"return",
"self",
".",
"enum_types_by_name",
"[",
"enum",
"]",
".",
"values_by_number",
"[",
"value",
"]",
".",
"name"
] | Returns the string name of an enum value.
This is just a small helper method to simplify a common operation.
Args:
enum: string name of the Enum.
value: int, value of the enum.
Returns:
string name of the enum value.
Raises:
KeyError if either the Enum doesn't exist or the value is not a valid
value for the enum. | [
"Returns",
"the",
"string",
"name",
"of",
"an",
"enum",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor.py#L321-L337 |
29,457 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | resolve_reference | def resolve_reference(target_reference, project):
""" Given a target_reference, made in context of 'project',
returns the AbstractTarget instance that is referred to, as well
as properties explicitly specified for this reference.
"""
# Separate target name from properties override
assert isinstance(target_reference, basestring)
assert isinstance(project, ProjectTarget)
split = _re_separate_target_from_properties.match (target_reference)
if not split:
raise BaseException ("Invalid reference: '%s'" % target_reference)
id = split.group (1)
sproperties = []
if split.group (3):
sproperties = property.create_from_strings(feature.split(split.group(3)))
sproperties = feature.expand_composites(sproperties)
# Find the target
target = project.find (id)
return (target, property_set.create(sproperties)) | python | def resolve_reference(target_reference, project):
""" Given a target_reference, made in context of 'project',
returns the AbstractTarget instance that is referred to, as well
as properties explicitly specified for this reference.
"""
# Separate target name from properties override
assert isinstance(target_reference, basestring)
assert isinstance(project, ProjectTarget)
split = _re_separate_target_from_properties.match (target_reference)
if not split:
raise BaseException ("Invalid reference: '%s'" % target_reference)
id = split.group (1)
sproperties = []
if split.group (3):
sproperties = property.create_from_strings(feature.split(split.group(3)))
sproperties = feature.expand_composites(sproperties)
# Find the target
target = project.find (id)
return (target, property_set.create(sproperties)) | [
"def",
"resolve_reference",
"(",
"target_reference",
",",
"project",
")",
":",
"# Separate target name from properties override",
"assert",
"isinstance",
"(",
"target_reference",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"split",
"=",
"_re_separate_target_from_properties",
".",
"match",
"(",
"target_reference",
")",
"if",
"not",
"split",
":",
"raise",
"BaseException",
"(",
"\"Invalid reference: '%s'\"",
"%",
"target_reference",
")",
"id",
"=",
"split",
".",
"group",
"(",
"1",
")",
"sproperties",
"=",
"[",
"]",
"if",
"split",
".",
"group",
"(",
"3",
")",
":",
"sproperties",
"=",
"property",
".",
"create_from_strings",
"(",
"feature",
".",
"split",
"(",
"split",
".",
"group",
"(",
"3",
")",
")",
")",
"sproperties",
"=",
"feature",
".",
"expand_composites",
"(",
"sproperties",
")",
"# Find the target",
"target",
"=",
"project",
".",
"find",
"(",
"id",
")",
"return",
"(",
"target",
",",
"property_set",
".",
"create",
"(",
"sproperties",
")",
")"
] | Given a target_reference, made in context of 'project',
returns the AbstractTarget instance that is referred to, as well
as properties explicitly specified for this reference. | [
"Given",
"a",
"target_reference",
"made",
"in",
"context",
"of",
"project",
"returns",
"the",
"AbstractTarget",
"instance",
"that",
"is",
"referred",
"to",
"as",
"well",
"as",
"properties",
"explicitly",
"specified",
"for",
"this",
"reference",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L841-L864 |
29,458 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | TargetRegistry.main_target_alternative | def main_target_alternative (self, target):
""" Registers the specified target as a main target alternatives.
Returns 'target'.
"""
assert isinstance(target, AbstractTarget)
target.project ().add_alternative (target)
return target | python | def main_target_alternative (self, target):
""" Registers the specified target as a main target alternatives.
Returns 'target'.
"""
assert isinstance(target, AbstractTarget)
target.project ().add_alternative (target)
return target | [
"def",
"main_target_alternative",
"(",
"self",
",",
"target",
")",
":",
"assert",
"isinstance",
"(",
"target",
",",
"AbstractTarget",
")",
"target",
".",
"project",
"(",
")",
".",
"add_alternative",
"(",
"target",
")",
"return",
"target"
] | Registers the specified target as a main target alternatives.
Returns 'target'. | [
"Registers",
"the",
"specified",
"target",
"as",
"a",
"main",
"target",
"alternatives",
".",
"Returns",
"target",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L107-L113 |
29,459 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | TargetRegistry.main_target_requirements | def main_target_requirements(self, specification, project):
"""Returns the requirement to use when declaring a main target,
which are obtained by
- translating all specified property paths, and
- refining project requirements with the one specified for the target
'specification' are the properties xplicitly specified for a
main target
'project' is the project where the main taret is to be declared."""
assert is_iterable_typed(specification, basestring)
assert isinstance(project, ProjectTarget)
# create a copy since the list is being modified
specification = list(specification)
specification.extend(toolset.requirements())
requirements = property_set.refine_from_user_input(
project.get("requirements"), specification,
project.project_module(), project.get("location"))
return requirements | python | def main_target_requirements(self, specification, project):
"""Returns the requirement to use when declaring a main target,
which are obtained by
- translating all specified property paths, and
- refining project requirements with the one specified for the target
'specification' are the properties xplicitly specified for a
main target
'project' is the project where the main taret is to be declared."""
assert is_iterable_typed(specification, basestring)
assert isinstance(project, ProjectTarget)
# create a copy since the list is being modified
specification = list(specification)
specification.extend(toolset.requirements())
requirements = property_set.refine_from_user_input(
project.get("requirements"), specification,
project.project_module(), project.get("location"))
return requirements | [
"def",
"main_target_requirements",
"(",
"self",
",",
"specification",
",",
"project",
")",
":",
"assert",
"is_iterable_typed",
"(",
"specification",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"# create a copy since the list is being modified",
"specification",
"=",
"list",
"(",
"specification",
")",
"specification",
".",
"extend",
"(",
"toolset",
".",
"requirements",
"(",
")",
")",
"requirements",
"=",
"property_set",
".",
"refine_from_user_input",
"(",
"project",
".",
"get",
"(",
"\"requirements\"",
")",
",",
"specification",
",",
"project",
".",
"project_module",
"(",
")",
",",
"project",
".",
"get",
"(",
"\"location\"",
")",
")",
"return",
"requirements"
] | Returns the requirement to use when declaring a main target,
which are obtained by
- translating all specified property paths, and
- refining project requirements with the one specified for the target
'specification' are the properties xplicitly specified for a
main target
'project' is the project where the main taret is to be declared. | [
"Returns",
"the",
"requirement",
"to",
"use",
"when",
"declaring",
"a",
"main",
"target",
"which",
"are",
"obtained",
"by",
"-",
"translating",
"all",
"specified",
"property",
"paths",
"and",
"-",
"refining",
"project",
"requirements",
"with",
"the",
"one",
"specified",
"for",
"the",
"target"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L148-L167 |
29,460 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | TargetRegistry.start_building | def start_building (self, main_target_instance):
""" Helper rules to detect cycles in main target references.
"""
assert isinstance(main_target_instance, MainTarget)
if id(main_target_instance) in self.targets_being_built_:
names = []
for t in self.targets_being_built_.values() + [main_target_instance]:
names.append (t.full_name())
get_manager().errors()("Recursion in main target references\n")
self.targets_being_built_[id(main_target_instance)] = main_target_instance | python | def start_building (self, main_target_instance):
""" Helper rules to detect cycles in main target references.
"""
assert isinstance(main_target_instance, MainTarget)
if id(main_target_instance) in self.targets_being_built_:
names = []
for t in self.targets_being_built_.values() + [main_target_instance]:
names.append (t.full_name())
get_manager().errors()("Recursion in main target references\n")
self.targets_being_built_[id(main_target_instance)] = main_target_instance | [
"def",
"start_building",
"(",
"self",
",",
"main_target_instance",
")",
":",
"assert",
"isinstance",
"(",
"main_target_instance",
",",
"MainTarget",
")",
"if",
"id",
"(",
"main_target_instance",
")",
"in",
"self",
".",
"targets_being_built_",
":",
"names",
"=",
"[",
"]",
"for",
"t",
"in",
"self",
".",
"targets_being_built_",
".",
"values",
"(",
")",
"+",
"[",
"main_target_instance",
"]",
":",
"names",
".",
"append",
"(",
"t",
".",
"full_name",
"(",
")",
")",
"get_manager",
"(",
")",
".",
"errors",
"(",
")",
"(",
"\"Recursion in main target references\\n\"",
")",
"self",
".",
"targets_being_built_",
"[",
"id",
"(",
"main_target_instance",
")",
"]",
"=",
"main_target_instance"
] | Helper rules to detect cycles in main target references. | [
"Helper",
"rules",
"to",
"detect",
"cycles",
"in",
"main",
"target",
"references",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L204-L215 |
29,461 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | TargetRegistry.create_typed_target | def create_typed_target (self, type, project, name, sources, requirements, default_build, usage_requirements):
""" Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
by the user in Jamfile corresponding to 'project'.
"""
assert isinstance(type, basestring)
assert isinstance(project, ProjectTarget)
assert is_iterable_typed(sources, basestring)
assert is_iterable_typed(requirements, basestring)
assert is_iterable_typed(default_build, basestring)
return self.main_target_alternative (TypedTarget (name, project, type,
self.main_target_sources (sources, name),
self.main_target_requirements (requirements, project),
self.main_target_default_build (default_build, project),
self.main_target_usage_requirements (usage_requirements, project))) | python | def create_typed_target (self, type, project, name, sources, requirements, default_build, usage_requirements):
""" Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
by the user in Jamfile corresponding to 'project'.
"""
assert isinstance(type, basestring)
assert isinstance(project, ProjectTarget)
assert is_iterable_typed(sources, basestring)
assert is_iterable_typed(requirements, basestring)
assert is_iterable_typed(default_build, basestring)
return self.main_target_alternative (TypedTarget (name, project, type,
self.main_target_sources (sources, name),
self.main_target_requirements (requirements, project),
self.main_target_default_build (default_build, project),
self.main_target_usage_requirements (usage_requirements, project))) | [
"def",
"create_typed_target",
"(",
"self",
",",
"type",
",",
"project",
",",
"name",
",",
"sources",
",",
"requirements",
",",
"default_build",
",",
"usage_requirements",
")",
":",
"assert",
"isinstance",
"(",
"type",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"assert",
"is_iterable_typed",
"(",
"sources",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"requirements",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"default_build",
",",
"basestring",
")",
"return",
"self",
".",
"main_target_alternative",
"(",
"TypedTarget",
"(",
"name",
",",
"project",
",",
"type",
",",
"self",
".",
"main_target_sources",
"(",
"sources",
",",
"name",
")",
",",
"self",
".",
"main_target_requirements",
"(",
"requirements",
",",
"project",
")",
",",
"self",
".",
"main_target_default_build",
"(",
"default_build",
",",
"project",
")",
",",
"self",
".",
"main_target_usage_requirements",
"(",
"usage_requirements",
",",
"project",
")",
")",
")"
] | Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
by the user in Jamfile corresponding to 'project'. | [
"Creates",
"a",
"TypedTarget",
"with",
"the",
"specified",
"properties",
".",
"The",
"name",
"sources",
"requirements",
"default_build",
"and",
"usage_requirements",
"are",
"assumed",
"to",
"be",
"in",
"the",
"form",
"specified",
"by",
"the",
"user",
"in",
"Jamfile",
"corresponding",
"to",
"project",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L222-L237 |
29,462 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | ProjectTarget.generate | def generate (self, ps):
""" Generates all possible targets contained in this project.
"""
assert isinstance(ps, property_set.PropertySet)
self.manager_.targets().log(
"Building project '%s' with '%s'" % (self.name (), str(ps)))
self.manager_.targets().increase_indent ()
result = GenerateResult ()
for t in self.targets_to_build ():
g = t.generate (ps)
result.extend (g)
self.manager_.targets().decrease_indent ()
return result | python | def generate (self, ps):
""" Generates all possible targets contained in this project.
"""
assert isinstance(ps, property_set.PropertySet)
self.manager_.targets().log(
"Building project '%s' with '%s'" % (self.name (), str(ps)))
self.manager_.targets().increase_indent ()
result = GenerateResult ()
for t in self.targets_to_build ():
g = t.generate (ps)
result.extend (g)
self.manager_.targets().decrease_indent ()
return result | [
"def",
"generate",
"(",
"self",
",",
"ps",
")",
":",
"assert",
"isinstance",
"(",
"ps",
",",
"property_set",
".",
"PropertySet",
")",
"self",
".",
"manager_",
".",
"targets",
"(",
")",
".",
"log",
"(",
"\"Building project '%s' with '%s'\"",
"%",
"(",
"self",
".",
"name",
"(",
")",
",",
"str",
"(",
"ps",
")",
")",
")",
"self",
".",
"manager_",
".",
"targets",
"(",
")",
".",
"increase_indent",
"(",
")",
"result",
"=",
"GenerateResult",
"(",
")",
"for",
"t",
"in",
"self",
".",
"targets_to_build",
"(",
")",
":",
"g",
"=",
"t",
".",
"generate",
"(",
"ps",
")",
"result",
".",
"extend",
"(",
"g",
")",
"self",
".",
"manager_",
".",
"targets",
"(",
")",
".",
"decrease_indent",
"(",
")",
"return",
"result"
] | Generates all possible targets contained in this project. | [
"Generates",
"all",
"possible",
"targets",
"contained",
"in",
"this",
"project",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L433-L448 |
29,463 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | ProjectTarget.targets_to_build | def targets_to_build (self):
""" Computes and returns a list of AbstractTarget instances which
must be built when this project is built.
"""
result = []
if not self.built_main_targets_:
self.build_main_targets ()
# Collect all main targets here, except for "explicit" ones.
for n, t in self.main_target_.iteritems ():
if not t.name () in self.explicit_targets_:
result.append (t)
# Collect all projects referenced via "projects-to-build" attribute.
self_location = self.get ('location')
for pn in self.get ('projects-to-build'):
result.append (self.find(pn + "/"))
return result | python | def targets_to_build (self):
""" Computes and returns a list of AbstractTarget instances which
must be built when this project is built.
"""
result = []
if not self.built_main_targets_:
self.build_main_targets ()
# Collect all main targets here, except for "explicit" ones.
for n, t in self.main_target_.iteritems ():
if not t.name () in self.explicit_targets_:
result.append (t)
# Collect all projects referenced via "projects-to-build" attribute.
self_location = self.get ('location')
for pn in self.get ('projects-to-build'):
result.append (self.find(pn + "/"))
return result | [
"def",
"targets_to_build",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"built_main_targets_",
":",
"self",
".",
"build_main_targets",
"(",
")",
"# Collect all main targets here, except for \"explicit\" ones.",
"for",
"n",
",",
"t",
"in",
"self",
".",
"main_target_",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"t",
".",
"name",
"(",
")",
"in",
"self",
".",
"explicit_targets_",
":",
"result",
".",
"append",
"(",
"t",
")",
"# Collect all projects referenced via \"projects-to-build\" attribute.",
"self_location",
"=",
"self",
".",
"get",
"(",
"'location'",
")",
"for",
"pn",
"in",
"self",
".",
"get",
"(",
"'projects-to-build'",
")",
":",
"result",
".",
"append",
"(",
"self",
".",
"find",
"(",
"pn",
"+",
"\"/\"",
")",
")",
"return",
"result"
] | Computes and returns a list of AbstractTarget instances which
must be built when this project is built. | [
"Computes",
"and",
"returns",
"a",
"list",
"of",
"AbstractTarget",
"instances",
"which",
"must",
"be",
"built",
"when",
"this",
"project",
"is",
"built",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L450-L469 |
29,464 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | ProjectTarget.mark_targets_as_explicit | def mark_targets_as_explicit (self, target_names):
"""Add 'target' to the list of targets in this project
that should be build only by explicit request."""
# Record the name of the target, not instance, since this
# rule is called before main target instaces are created.
assert is_iterable_typed(target_names, basestring)
self.explicit_targets_.update(target_names) | python | def mark_targets_as_explicit (self, target_names):
"""Add 'target' to the list of targets in this project
that should be build only by explicit request."""
# Record the name of the target, not instance, since this
# rule is called before main target instaces are created.
assert is_iterable_typed(target_names, basestring)
self.explicit_targets_.update(target_names) | [
"def",
"mark_targets_as_explicit",
"(",
"self",
",",
"target_names",
")",
":",
"# Record the name of the target, not instance, since this",
"# rule is called before main target instaces are created.",
"assert",
"is_iterable_typed",
"(",
"target_names",
",",
"basestring",
")",
"self",
".",
"explicit_targets_",
".",
"update",
"(",
"target_names",
")"
] | Add 'target' to the list of targets in this project
that should be build only by explicit request. | [
"Add",
"target",
"to",
"the",
"list",
"of",
"targets",
"in",
"this",
"project",
"that",
"should",
"be",
"build",
"only",
"by",
"explicit",
"request",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L471-L478 |
29,465 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | ProjectTarget.add_alternative | def add_alternative (self, target_instance):
""" Add new target alternative.
"""
assert isinstance(target_instance, AbstractTarget)
if self.built_main_targets_:
raise IllegalOperation ("add-alternative called when main targets are already created for project '%s'" % self.full_name ())
self.alternatives_.append (target_instance) | python | def add_alternative (self, target_instance):
""" Add new target alternative.
"""
assert isinstance(target_instance, AbstractTarget)
if self.built_main_targets_:
raise IllegalOperation ("add-alternative called when main targets are already created for project '%s'" % self.full_name ())
self.alternatives_.append (target_instance) | [
"def",
"add_alternative",
"(",
"self",
",",
"target_instance",
")",
":",
"assert",
"isinstance",
"(",
"target_instance",
",",
"AbstractTarget",
")",
"if",
"self",
".",
"built_main_targets_",
":",
"raise",
"IllegalOperation",
"(",
"\"add-alternative called when main targets are already created for project '%s'\"",
"%",
"self",
".",
"full_name",
"(",
")",
")",
"self",
".",
"alternatives_",
".",
"append",
"(",
"target_instance",
")"
] | Add new target alternative. | [
"Add",
"new",
"target",
"alternative",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L484-L491 |
29,466 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | ProjectTarget.has_main_target | def has_main_target (self, name):
"""Tells if a main target with the specified name exists."""
assert isinstance(name, basestring)
if not self.built_main_targets_:
self.build_main_targets()
return name in self.main_target_ | python | def has_main_target (self, name):
"""Tells if a main target with the specified name exists."""
assert isinstance(name, basestring)
if not self.built_main_targets_:
self.build_main_targets()
return name in self.main_target_ | [
"def",
"has_main_target",
"(",
"self",
",",
"name",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"if",
"not",
"self",
".",
"built_main_targets_",
":",
"self",
".",
"build_main_targets",
"(",
")",
"return",
"name",
"in",
"self",
".",
"main_target_"
] | Tells if a main target with the specified name exists. | [
"Tells",
"if",
"a",
"main",
"target",
"with",
"the",
"specified",
"name",
"exists",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L500-L506 |
29,467 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | ProjectTarget.create_main_target | def create_main_target (self, name):
""" Returns a 'MainTarget' class instance corresponding to the 'name'.
"""
assert isinstance(name, basestring)
if not self.built_main_targets_:
self.build_main_targets ()
return self.main_targets_.get (name, None) | python | def create_main_target (self, name):
""" Returns a 'MainTarget' class instance corresponding to the 'name'.
"""
assert isinstance(name, basestring)
if not self.built_main_targets_:
self.build_main_targets ()
return self.main_targets_.get (name, None) | [
"def",
"create_main_target",
"(",
"self",
",",
"name",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"if",
"not",
"self",
".",
"built_main_targets_",
":",
"self",
".",
"build_main_targets",
"(",
")",
"return",
"self",
".",
"main_targets_",
".",
"get",
"(",
"name",
",",
"None",
")"
] | Returns a 'MainTarget' class instance corresponding to the 'name'. | [
"Returns",
"a",
"MainTarget",
"class",
"instance",
"corresponding",
"to",
"the",
"name",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L508-L515 |
29,468 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | ProjectTarget.find_really | def find_really(self, id):
""" Find and return the target with the specified id, treated
relative to self.
"""
assert isinstance(id, basestring)
result = None
current_location = self.get ('location')
__re_split_project_target = re.compile (r'(.*)//(.*)')
split = __re_split_project_target.match (id)
project_part = None
target_part = None
if split:
project_part = split.group(1)
target_part = split.group(2)
if not target_part:
get_manager().errors()(
'Project ID, "{}", is not a valid target reference. There should '
'be either a target name after the "//" or the "//" should be removed '
'from the target reference.'
.format(id)
)
project_registry = self.project_.manager ().projects ()
extra_error_message = ''
if project_part:
# There's explicit project part in id. Looks up the
# project and pass the request to it.
pm = project_registry.find (project_part, current_location)
if pm:
project_target = project_registry.target (pm)
result = project_target.find (target_part, no_error=1)
else:
extra_error_message = "error: could not find project '$(project_part)'"
else:
# Interpret target-name as name of main target
# Need to do this before checking for file. Consider this:
#
# exe test : test.cpp ;
# install s : test : <location>. ;
#
# After first build we'll have target 'test' in Jamfile and file
# 'test' on the disk. We need target to override the file.
result = None
if self.has_main_target(id):
result = self.main_target(id)
if not result:
result = FileReference (self.manager_, id, self.project_)
if not result.exists ():
# File actually does not exist.
# Reset 'target' so that an error is issued.
result = None
if not result:
# Interpret id as project-id
project_module = project_registry.find (id, current_location)
if project_module:
result = project_registry.target (project_module)
return result | python | def find_really(self, id):
""" Find and return the target with the specified id, treated
relative to self.
"""
assert isinstance(id, basestring)
result = None
current_location = self.get ('location')
__re_split_project_target = re.compile (r'(.*)//(.*)')
split = __re_split_project_target.match (id)
project_part = None
target_part = None
if split:
project_part = split.group(1)
target_part = split.group(2)
if not target_part:
get_manager().errors()(
'Project ID, "{}", is not a valid target reference. There should '
'be either a target name after the "//" or the "//" should be removed '
'from the target reference.'
.format(id)
)
project_registry = self.project_.manager ().projects ()
extra_error_message = ''
if project_part:
# There's explicit project part in id. Looks up the
# project and pass the request to it.
pm = project_registry.find (project_part, current_location)
if pm:
project_target = project_registry.target (pm)
result = project_target.find (target_part, no_error=1)
else:
extra_error_message = "error: could not find project '$(project_part)'"
else:
# Interpret target-name as name of main target
# Need to do this before checking for file. Consider this:
#
# exe test : test.cpp ;
# install s : test : <location>. ;
#
# After first build we'll have target 'test' in Jamfile and file
# 'test' on the disk. We need target to override the file.
result = None
if self.has_main_target(id):
result = self.main_target(id)
if not result:
result = FileReference (self.manager_, id, self.project_)
if not result.exists ():
# File actually does not exist.
# Reset 'target' so that an error is issued.
result = None
if not result:
# Interpret id as project-id
project_module = project_registry.find (id, current_location)
if project_module:
result = project_registry.target (project_module)
return result | [
"def",
"find_really",
"(",
"self",
",",
"id",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"result",
"=",
"None",
"current_location",
"=",
"self",
".",
"get",
"(",
"'location'",
")",
"__re_split_project_target",
"=",
"re",
".",
"compile",
"(",
"r'(.*)//(.*)'",
")",
"split",
"=",
"__re_split_project_target",
".",
"match",
"(",
"id",
")",
"project_part",
"=",
"None",
"target_part",
"=",
"None",
"if",
"split",
":",
"project_part",
"=",
"split",
".",
"group",
"(",
"1",
")",
"target_part",
"=",
"split",
".",
"group",
"(",
"2",
")",
"if",
"not",
"target_part",
":",
"get_manager",
"(",
")",
".",
"errors",
"(",
")",
"(",
"'Project ID, \"{}\", is not a valid target reference. There should '",
"'be either a target name after the \"//\" or the \"//\" should be removed '",
"'from the target reference.'",
".",
"format",
"(",
"id",
")",
")",
"project_registry",
"=",
"self",
".",
"project_",
".",
"manager",
"(",
")",
".",
"projects",
"(",
")",
"extra_error_message",
"=",
"''",
"if",
"project_part",
":",
"# There's explicit project part in id. Looks up the",
"# project and pass the request to it.",
"pm",
"=",
"project_registry",
".",
"find",
"(",
"project_part",
",",
"current_location",
")",
"if",
"pm",
":",
"project_target",
"=",
"project_registry",
".",
"target",
"(",
"pm",
")",
"result",
"=",
"project_target",
".",
"find",
"(",
"target_part",
",",
"no_error",
"=",
"1",
")",
"else",
":",
"extra_error_message",
"=",
"\"error: could not find project '$(project_part)'\"",
"else",
":",
"# Interpret target-name as name of main target",
"# Need to do this before checking for file. Consider this:",
"#",
"# exe test : test.cpp ;",
"# install s : test : <location>. ;",
"#",
"# After first build we'll have target 'test' in Jamfile and file",
"# 'test' on the disk. We need target to override the file.",
"result",
"=",
"None",
"if",
"self",
".",
"has_main_target",
"(",
"id",
")",
":",
"result",
"=",
"self",
".",
"main_target",
"(",
"id",
")",
"if",
"not",
"result",
":",
"result",
"=",
"FileReference",
"(",
"self",
".",
"manager_",
",",
"id",
",",
"self",
".",
"project_",
")",
"if",
"not",
"result",
".",
"exists",
"(",
")",
":",
"# File actually does not exist.",
"# Reset 'target' so that an error is issued.",
"result",
"=",
"None",
"if",
"not",
"result",
":",
"# Interpret id as project-id",
"project_module",
"=",
"project_registry",
".",
"find",
"(",
"id",
",",
"current_location",
")",
"if",
"project_module",
":",
"result",
"=",
"project_registry",
".",
"target",
"(",
"project_module",
")",
"return",
"result"
] | Find and return the target with the specified id, treated
relative to self. | [
"Find",
"and",
"return",
"the",
"target",
"with",
"the",
"specified",
"id",
"treated",
"relative",
"to",
"self",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L518-L588 |
29,469 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | ProjectTarget.add_constant | def add_constant(self, name, value, path=0):
"""Adds a new constant for this project.
The constant will be available for use in Jamfile
module for this project. If 'path' is true,
the constant will be interpreted relatively
to the location of project.
"""
assert isinstance(name, basestring)
assert is_iterable_typed(value, basestring)
assert isinstance(path, int) # will also match bools
if path:
l = self.location_
if not l:
# Project corresponding to config files do not have
# 'location' attribute, but do have source location.
# It might be more reasonable to make every project have
# a location and use some other approach to prevent buildable
# targets in config files, but that's for later.
l = self.get('source-location')
value = os.path.join(l, value[0])
# Now make the value absolute path. Constants should be in
# platform-native form.
value = [os.path.normpath(os.path.join(os.getcwd(), value))]
self.constants_[name] = value
bjam.call("set-variable", self.project_module(), name, value) | python | def add_constant(self, name, value, path=0):
"""Adds a new constant for this project.
The constant will be available for use in Jamfile
module for this project. If 'path' is true,
the constant will be interpreted relatively
to the location of project.
"""
assert isinstance(name, basestring)
assert is_iterable_typed(value, basestring)
assert isinstance(path, int) # will also match bools
if path:
l = self.location_
if not l:
# Project corresponding to config files do not have
# 'location' attribute, but do have source location.
# It might be more reasonable to make every project have
# a location and use some other approach to prevent buildable
# targets in config files, but that's for later.
l = self.get('source-location')
value = os.path.join(l, value[0])
# Now make the value absolute path. Constants should be in
# platform-native form.
value = [os.path.normpath(os.path.join(os.getcwd(), value))]
self.constants_[name] = value
bjam.call("set-variable", self.project_module(), name, value) | [
"def",
"add_constant",
"(",
"self",
",",
"name",
",",
"value",
",",
"path",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"path",
",",
"int",
")",
"# will also match bools",
"if",
"path",
":",
"l",
"=",
"self",
".",
"location_",
"if",
"not",
"l",
":",
"# Project corresponding to config files do not have",
"# 'location' attribute, but do have source location.",
"# It might be more reasonable to make every project have",
"# a location and use some other approach to prevent buildable",
"# targets in config files, but that's for later.",
"l",
"=",
"self",
".",
"get",
"(",
"'source-location'",
")",
"value",
"=",
"os",
".",
"path",
".",
"join",
"(",
"l",
",",
"value",
"[",
"0",
"]",
")",
"# Now make the value absolute path. Constants should be in",
"# platform-native form.",
"value",
"=",
"[",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"value",
")",
")",
"]",
"self",
".",
"constants_",
"[",
"name",
"]",
"=",
"value",
"bjam",
".",
"call",
"(",
"\"set-variable\"",
",",
"self",
".",
"project_module",
"(",
")",
",",
"name",
",",
"value",
")"
] | Adds a new constant for this project.
The constant will be available for use in Jamfile
module for this project. If 'path' is true,
the constant will be interpreted relatively
to the location of project. | [
"Adds",
"a",
"new",
"constant",
"for",
"this",
"project",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L619-L646 |
29,470 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | MainTarget.add_alternative | def add_alternative (self, target):
""" Add a new alternative for this target.
"""
assert isinstance(target, BasicTarget)
d = target.default_build ()
if self.alternatives_ and self.default_build_ != d:
get_manager().errors()("default build must be identical in all alternatives\n"
"main target is '%s'\n"
"with '%s'\n"
"differing from previous default build: '%s'" % (self.full_name (), d.raw (), self.default_build_.raw ()))
else:
self.default_build_ = d
self.alternatives_.append (target) | python | def add_alternative (self, target):
""" Add a new alternative for this target.
"""
assert isinstance(target, BasicTarget)
d = target.default_build ()
if self.alternatives_ and self.default_build_ != d:
get_manager().errors()("default build must be identical in all alternatives\n"
"main target is '%s'\n"
"with '%s'\n"
"differing from previous default build: '%s'" % (self.full_name (), d.raw (), self.default_build_.raw ()))
else:
self.default_build_ = d
self.alternatives_.append (target) | [
"def",
"add_alternative",
"(",
"self",
",",
"target",
")",
":",
"assert",
"isinstance",
"(",
"target",
",",
"BasicTarget",
")",
"d",
"=",
"target",
".",
"default_build",
"(",
")",
"if",
"self",
".",
"alternatives_",
"and",
"self",
".",
"default_build_",
"!=",
"d",
":",
"get_manager",
"(",
")",
".",
"errors",
"(",
")",
"(",
"\"default build must be identical in all alternatives\\n\"",
"\"main target is '%s'\\n\"",
"\"with '%s'\\n\"",
"\"differing from previous default build: '%s'\"",
"%",
"(",
"self",
".",
"full_name",
"(",
")",
",",
"d",
".",
"raw",
"(",
")",
",",
"self",
".",
"default_build_",
".",
"raw",
"(",
")",
")",
")",
"else",
":",
"self",
".",
"default_build_",
"=",
"d",
"self",
".",
"alternatives_",
".",
"append",
"(",
"target",
")"
] | Add a new alternative for this target. | [
"Add",
"a",
"new",
"alternative",
"for",
"this",
"target",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L676-L691 |
29,471 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | MainTarget.generate | def generate (self, ps):
""" Select an alternative for this main target, by finding all alternatives
which requirements are satisfied by 'properties' and picking the one with
longest requirements set.
Returns the result of calling 'generate' on that alternative.
"""
assert isinstance(ps, property_set.PropertySet)
self.manager_.targets ().start_building (self)
# We want composite properties in build request act as if
# all the properties it expands too are explicitly specified.
ps = ps.expand ()
all_property_sets = self.apply_default_build (ps)
result = GenerateResult ()
for p in all_property_sets:
result.extend (self.__generate_really (p))
self.manager_.targets ().end_building (self)
return result | python | def generate (self, ps):
""" Select an alternative for this main target, by finding all alternatives
which requirements are satisfied by 'properties' and picking the one with
longest requirements set.
Returns the result of calling 'generate' on that alternative.
"""
assert isinstance(ps, property_set.PropertySet)
self.manager_.targets ().start_building (self)
# We want composite properties in build request act as if
# all the properties it expands too are explicitly specified.
ps = ps.expand ()
all_property_sets = self.apply_default_build (ps)
result = GenerateResult ()
for p in all_property_sets:
result.extend (self.__generate_really (p))
self.manager_.targets ().end_building (self)
return result | [
"def",
"generate",
"(",
"self",
",",
"ps",
")",
":",
"assert",
"isinstance",
"(",
"ps",
",",
"property_set",
".",
"PropertySet",
")",
"self",
".",
"manager_",
".",
"targets",
"(",
")",
".",
"start_building",
"(",
"self",
")",
"# We want composite properties in build request act as if",
"# all the properties it expands too are explicitly specified.",
"ps",
"=",
"ps",
".",
"expand",
"(",
")",
"all_property_sets",
"=",
"self",
".",
"apply_default_build",
"(",
"ps",
")",
"result",
"=",
"GenerateResult",
"(",
")",
"for",
"p",
"in",
"all_property_sets",
":",
"result",
".",
"extend",
"(",
"self",
".",
"__generate_really",
"(",
"p",
")",
")",
"self",
".",
"manager_",
".",
"targets",
"(",
")",
".",
"end_building",
"(",
"self",
")",
"return",
"result"
] | Select an alternative for this main target, by finding all alternatives
which requirements are satisfied by 'properties' and picking the one with
longest requirements set.
Returns the result of calling 'generate' on that alternative. | [
"Select",
"an",
"alternative",
"for",
"this",
"main",
"target",
"by",
"finding",
"all",
"alternatives",
"which",
"requirements",
"are",
"satisfied",
"by",
"properties",
"and",
"picking",
"the",
"one",
"with",
"longest",
"requirements",
"set",
".",
"Returns",
"the",
"result",
"of",
"calling",
"generate",
"on",
"that",
"alternative",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L752-L774 |
29,472 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | MainTarget.__generate_really | def __generate_really (self, prop_set):
""" Generates the main target with the given property set
and returns a list which first element is property_set object
containing usage_requirements of generated target and with
generated virtual target in other elements. It's possible
that no targets are generated.
"""
assert isinstance(prop_set, property_set.PropertySet)
best_alternative = self.__select_alternatives (prop_set, debug=0)
self.best_alternative = best_alternative
if not best_alternative:
# FIXME: revive.
# self.__select_alternatives(prop_set, debug=1)
self.manager_.errors()(
"No best alternative for '%s'.\n"
% (self.full_name(),))
result = best_alternative.generate (prop_set)
# Now return virtual targets for the only alternative
return result | python | def __generate_really (self, prop_set):
""" Generates the main target with the given property set
and returns a list which first element is property_set object
containing usage_requirements of generated target and with
generated virtual target in other elements. It's possible
that no targets are generated.
"""
assert isinstance(prop_set, property_set.PropertySet)
best_alternative = self.__select_alternatives (prop_set, debug=0)
self.best_alternative = best_alternative
if not best_alternative:
# FIXME: revive.
# self.__select_alternatives(prop_set, debug=1)
self.manager_.errors()(
"No best alternative for '%s'.\n"
% (self.full_name(),))
result = best_alternative.generate (prop_set)
# Now return virtual targets for the only alternative
return result | [
"def",
"__generate_really",
"(",
"self",
",",
"prop_set",
")",
":",
"assert",
"isinstance",
"(",
"prop_set",
",",
"property_set",
".",
"PropertySet",
")",
"best_alternative",
"=",
"self",
".",
"__select_alternatives",
"(",
"prop_set",
",",
"debug",
"=",
"0",
")",
"self",
".",
"best_alternative",
"=",
"best_alternative",
"if",
"not",
"best_alternative",
":",
"# FIXME: revive.",
"# self.__select_alternatives(prop_set, debug=1)",
"self",
".",
"manager_",
".",
"errors",
"(",
")",
"(",
"\"No best alternative for '%s'.\\n\"",
"%",
"(",
"self",
".",
"full_name",
"(",
")",
",",
")",
")",
"result",
"=",
"best_alternative",
".",
"generate",
"(",
"prop_set",
")",
"# Now return virtual targets for the only alternative",
"return",
"result"
] | Generates the main target with the given property set
and returns a list which first element is property_set object
containing usage_requirements of generated target and with
generated virtual target in other elements. It's possible
that no targets are generated. | [
"Generates",
"the",
"main",
"target",
"with",
"the",
"given",
"property",
"set",
"and",
"returns",
"a",
"list",
"which",
"first",
"element",
"is",
"property_set",
"object",
"containing",
"usage_requirements",
"of",
"generated",
"target",
"and",
"with",
"generated",
"virtual",
"target",
"in",
"other",
"elements",
".",
"It",
"s",
"possible",
"that",
"no",
"targets",
"are",
"generated",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L776-L797 |
29,473 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | BasicTarget.common_properties | def common_properties (self, build_request, requirements):
""" Given build request and requirements, return properties
common to dependency build request and target build
properties.
"""
# For optimization, we add free unconditional requirements directly,
# without using complex algorithsm.
# This gives the complex algorithm better chance of caching results.
# The exact effect of this "optimization" is no longer clear
assert isinstance(build_request, property_set.PropertySet)
assert isinstance(requirements, property_set.PropertySet)
free_unconditional = []
other = []
for p in requirements.all():
if p.feature.free and not p.condition and p.feature.name != 'conditional':
free_unconditional.append(p)
else:
other.append(p)
other = property_set.create(other)
key = (build_request, other)
if key not in self.request_cache:
self.request_cache[key] = self.__common_properties2 (build_request, other)
return self.request_cache[key].add_raw(free_unconditional) | python | def common_properties (self, build_request, requirements):
""" Given build request and requirements, return properties
common to dependency build request and target build
properties.
"""
# For optimization, we add free unconditional requirements directly,
# without using complex algorithsm.
# This gives the complex algorithm better chance of caching results.
# The exact effect of this "optimization" is no longer clear
assert isinstance(build_request, property_set.PropertySet)
assert isinstance(requirements, property_set.PropertySet)
free_unconditional = []
other = []
for p in requirements.all():
if p.feature.free and not p.condition and p.feature.name != 'conditional':
free_unconditional.append(p)
else:
other.append(p)
other = property_set.create(other)
key = (build_request, other)
if key not in self.request_cache:
self.request_cache[key] = self.__common_properties2 (build_request, other)
return self.request_cache[key].add_raw(free_unconditional) | [
"def",
"common_properties",
"(",
"self",
",",
"build_request",
",",
"requirements",
")",
":",
"# For optimization, we add free unconditional requirements directly,",
"# without using complex algorithsm.",
"# This gives the complex algorithm better chance of caching results.",
"# The exact effect of this \"optimization\" is no longer clear",
"assert",
"isinstance",
"(",
"build_request",
",",
"property_set",
".",
"PropertySet",
")",
"assert",
"isinstance",
"(",
"requirements",
",",
"property_set",
".",
"PropertySet",
")",
"free_unconditional",
"=",
"[",
"]",
"other",
"=",
"[",
"]",
"for",
"p",
"in",
"requirements",
".",
"all",
"(",
")",
":",
"if",
"p",
".",
"feature",
".",
"free",
"and",
"not",
"p",
".",
"condition",
"and",
"p",
".",
"feature",
".",
"name",
"!=",
"'conditional'",
":",
"free_unconditional",
".",
"append",
"(",
"p",
")",
"else",
":",
"other",
".",
"append",
"(",
"p",
")",
"other",
"=",
"property_set",
".",
"create",
"(",
"other",
")",
"key",
"=",
"(",
"build_request",
",",
"other",
")",
"if",
"key",
"not",
"in",
"self",
".",
"request_cache",
":",
"self",
".",
"request_cache",
"[",
"key",
"]",
"=",
"self",
".",
"__common_properties2",
"(",
"build_request",
",",
"other",
")",
"return",
"self",
".",
"request_cache",
"[",
"key",
"]",
".",
"add_raw",
"(",
"free_unconditional",
")"
] | Given build request and requirements, return properties
common to dependency build request and target build
properties. | [
"Given",
"build",
"request",
"and",
"requirements",
"return",
"properties",
"common",
"to",
"dependency",
"build",
"request",
"and",
"target",
"build",
"properties",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L958-L982 |
29,474 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | BasicTarget.match | def match (self, property_set_, debug):
""" Returns the alternative condition for this alternative, if
the condition is satisfied by 'property_set'.
"""
# The condition is composed of all base non-conditional properties.
# It's not clear if we should expand 'self.requirements_' or not.
# For one thing, it would be nice to be able to put
# <toolset>msvc-6.0
# in requirements.
# On the other hand, if we have <variant>release in condition it
# does not make sense to require <optimization>full to be in
# build request just to select this variant.
assert isinstance(property_set_, property_set.PropertySet)
bcondition = self.requirements_.base ()
ccondition = self.requirements_.conditional ()
condition = b2.util.set.difference (bcondition, ccondition)
if debug:
print " next alternative: required properties:", [str(p) for p in condition]
if b2.util.set.contains (condition, property_set_.all()):
if debug:
print " matched"
return condition
else:
return None | python | def match (self, property_set_, debug):
""" Returns the alternative condition for this alternative, if
the condition is satisfied by 'property_set'.
"""
# The condition is composed of all base non-conditional properties.
# It's not clear if we should expand 'self.requirements_' or not.
# For one thing, it would be nice to be able to put
# <toolset>msvc-6.0
# in requirements.
# On the other hand, if we have <variant>release in condition it
# does not make sense to require <optimization>full to be in
# build request just to select this variant.
assert isinstance(property_set_, property_set.PropertySet)
bcondition = self.requirements_.base ()
ccondition = self.requirements_.conditional ()
condition = b2.util.set.difference (bcondition, ccondition)
if debug:
print " next alternative: required properties:", [str(p) for p in condition]
if b2.util.set.contains (condition, property_set_.all()):
if debug:
print " matched"
return condition
else:
return None | [
"def",
"match",
"(",
"self",
",",
"property_set_",
",",
"debug",
")",
":",
"# The condition is composed of all base non-conditional properties.",
"# It's not clear if we should expand 'self.requirements_' or not.",
"# For one thing, it would be nice to be able to put",
"# <toolset>msvc-6.0",
"# in requirements.",
"# On the other hand, if we have <variant>release in condition it",
"# does not make sense to require <optimization>full to be in",
"# build request just to select this variant.",
"assert",
"isinstance",
"(",
"property_set_",
",",
"property_set",
".",
"PropertySet",
")",
"bcondition",
"=",
"self",
".",
"requirements_",
".",
"base",
"(",
")",
"ccondition",
"=",
"self",
".",
"requirements_",
".",
"conditional",
"(",
")",
"condition",
"=",
"b2",
".",
"util",
".",
"set",
".",
"difference",
"(",
"bcondition",
",",
"ccondition",
")",
"if",
"debug",
":",
"print",
"\" next alternative: required properties:\"",
",",
"[",
"str",
"(",
"p",
")",
"for",
"p",
"in",
"condition",
"]",
"if",
"b2",
".",
"util",
".",
"set",
".",
"contains",
"(",
"condition",
",",
"property_set_",
".",
"all",
"(",
")",
")",
":",
"if",
"debug",
":",
"print",
"\" matched\"",
"return",
"condition",
"else",
":",
"return",
"None"
] | Returns the alternative condition for this alternative, if
the condition is satisfied by 'property_set'. | [
"Returns",
"the",
"alternative",
"condition",
"for",
"this",
"alternative",
"if",
"the",
"condition",
"is",
"satisfied",
"by",
"property_set",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L1103-L1131 |
29,475 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | BasicTarget.generate_dependency_properties | def generate_dependency_properties(self, properties, ps):
""" Takes a target reference, which might be either target id
or a dependency property, and generates that target using
'property_set' as build request.
Returns a tuple (result, usage_requirements).
"""
assert is_iterable_typed(properties, property.Property)
assert isinstance(ps, property_set.PropertySet)
result_properties = []
usage_requirements = []
for p in properties:
result = generate_from_reference(p.value, self.project_, ps)
for t in result.targets():
result_properties.append(property.Property(p.feature, t))
usage_requirements += result.usage_requirements().all()
return (result_properties, usage_requirements) | python | def generate_dependency_properties(self, properties, ps):
""" Takes a target reference, which might be either target id
or a dependency property, and generates that target using
'property_set' as build request.
Returns a tuple (result, usage_requirements).
"""
assert is_iterable_typed(properties, property.Property)
assert isinstance(ps, property_set.PropertySet)
result_properties = []
usage_requirements = []
for p in properties:
result = generate_from_reference(p.value, self.project_, ps)
for t in result.targets():
result_properties.append(property.Property(p.feature, t))
usage_requirements += result.usage_requirements().all()
return (result_properties, usage_requirements) | [
"def",
"generate_dependency_properties",
"(",
"self",
",",
"properties",
",",
"ps",
")",
":",
"assert",
"is_iterable_typed",
"(",
"properties",
",",
"property",
".",
"Property",
")",
"assert",
"isinstance",
"(",
"ps",
",",
"property_set",
".",
"PropertySet",
")",
"result_properties",
"=",
"[",
"]",
"usage_requirements",
"=",
"[",
"]",
"for",
"p",
"in",
"properties",
":",
"result",
"=",
"generate_from_reference",
"(",
"p",
".",
"value",
",",
"self",
".",
"project_",
",",
"ps",
")",
"for",
"t",
"in",
"result",
".",
"targets",
"(",
")",
":",
"result_properties",
".",
"append",
"(",
"property",
".",
"Property",
"(",
"p",
".",
"feature",
",",
"t",
")",
")",
"usage_requirements",
"+=",
"result",
".",
"usage_requirements",
"(",
")",
".",
"all",
"(",
")",
"return",
"(",
"result_properties",
",",
"usage_requirements",
")"
] | Takes a target reference, which might be either target id
or a dependency property, and generates that target using
'property_set' as build request.
Returns a tuple (result, usage_requirements). | [
"Takes",
"a",
"target",
"reference",
"which",
"might",
"be",
"either",
"target",
"id",
"or",
"a",
"dependency",
"property",
"and",
"generates",
"that",
"target",
"using",
"property_set",
"as",
"build",
"request",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L1147-L1167 |
29,476 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | BasicTarget.compute_usage_requirements | def compute_usage_requirements (self, subvariant):
""" Given the set of generated targets, and refined build
properties, determines and sets appripriate usage requirements
on those targets.
"""
assert isinstance(subvariant, virtual_target.Subvariant)
rproperties = subvariant.build_properties ()
xusage_requirements =self.evaluate_requirements(
self.usage_requirements_, rproperties, "added")
# We generate all dependency properties and add them,
# as well as their usage requirements, to result.
(r1, r2) = self.generate_dependency_properties(xusage_requirements.dependency (), rproperties)
extra = r1 + r2
result = property_set.create (xusage_requirements.non_dependency () + extra)
# Propagate usage requirements we've got from sources, except
# for the <pch-header> and <pch-file> features.
#
# That feature specifies which pch file to use, and should apply
# only to direct dependents. Consider:
#
# pch pch1 : ...
# lib lib1 : ..... pch1 ;
# pch pch2 :
# lib lib2 : pch2 lib1 ;
#
# Here, lib2 should not get <pch-header> property from pch1.
#
# Essentially, when those two features are in usage requirements,
# they are propagated only to direct dependents. We might need
# a more general mechanism, but for now, only those two
# features are special.
properties = []
for p in subvariant.sources_usage_requirements().all():
if p.feature.name not in ('pch-header', 'pch-file'):
properties.append(p)
if 'shared' in rproperties.get('link'):
new_properties = []
for p in properties:
if p.feature.name != 'library':
new_properties.append(p)
properties = new_properties
result = result.add_raw(properties)
return result | python | def compute_usage_requirements (self, subvariant):
""" Given the set of generated targets, and refined build
properties, determines and sets appripriate usage requirements
on those targets.
"""
assert isinstance(subvariant, virtual_target.Subvariant)
rproperties = subvariant.build_properties ()
xusage_requirements =self.evaluate_requirements(
self.usage_requirements_, rproperties, "added")
# We generate all dependency properties and add them,
# as well as their usage requirements, to result.
(r1, r2) = self.generate_dependency_properties(xusage_requirements.dependency (), rproperties)
extra = r1 + r2
result = property_set.create (xusage_requirements.non_dependency () + extra)
# Propagate usage requirements we've got from sources, except
# for the <pch-header> and <pch-file> features.
#
# That feature specifies which pch file to use, and should apply
# only to direct dependents. Consider:
#
# pch pch1 : ...
# lib lib1 : ..... pch1 ;
# pch pch2 :
# lib lib2 : pch2 lib1 ;
#
# Here, lib2 should not get <pch-header> property from pch1.
#
# Essentially, when those two features are in usage requirements,
# they are propagated only to direct dependents. We might need
# a more general mechanism, but for now, only those two
# features are special.
properties = []
for p in subvariant.sources_usage_requirements().all():
if p.feature.name not in ('pch-header', 'pch-file'):
properties.append(p)
if 'shared' in rproperties.get('link'):
new_properties = []
for p in properties:
if p.feature.name != 'library':
new_properties.append(p)
properties = new_properties
result = result.add_raw(properties)
return result | [
"def",
"compute_usage_requirements",
"(",
"self",
",",
"subvariant",
")",
":",
"assert",
"isinstance",
"(",
"subvariant",
",",
"virtual_target",
".",
"Subvariant",
")",
"rproperties",
"=",
"subvariant",
".",
"build_properties",
"(",
")",
"xusage_requirements",
"=",
"self",
".",
"evaluate_requirements",
"(",
"self",
".",
"usage_requirements_",
",",
"rproperties",
",",
"\"added\"",
")",
"# We generate all dependency properties and add them,",
"# as well as their usage requirements, to result.",
"(",
"r1",
",",
"r2",
")",
"=",
"self",
".",
"generate_dependency_properties",
"(",
"xusage_requirements",
".",
"dependency",
"(",
")",
",",
"rproperties",
")",
"extra",
"=",
"r1",
"+",
"r2",
"result",
"=",
"property_set",
".",
"create",
"(",
"xusage_requirements",
".",
"non_dependency",
"(",
")",
"+",
"extra",
")",
"# Propagate usage requirements we've got from sources, except",
"# for the <pch-header> and <pch-file> features.",
"#",
"# That feature specifies which pch file to use, and should apply",
"# only to direct dependents. Consider:",
"#",
"# pch pch1 : ...",
"# lib lib1 : ..... pch1 ;",
"# pch pch2 :",
"# lib lib2 : pch2 lib1 ;",
"#",
"# Here, lib2 should not get <pch-header> property from pch1.",
"#",
"# Essentially, when those two features are in usage requirements,",
"# they are propagated only to direct dependents. We might need",
"# a more general mechanism, but for now, only those two",
"# features are special.",
"properties",
"=",
"[",
"]",
"for",
"p",
"in",
"subvariant",
".",
"sources_usage_requirements",
"(",
")",
".",
"all",
"(",
")",
":",
"if",
"p",
".",
"feature",
".",
"name",
"not",
"in",
"(",
"'pch-header'",
",",
"'pch-file'",
")",
":",
"properties",
".",
"append",
"(",
"p",
")",
"if",
"'shared'",
"in",
"rproperties",
".",
"get",
"(",
"'link'",
")",
":",
"new_properties",
"=",
"[",
"]",
"for",
"p",
"in",
"properties",
":",
"if",
"p",
".",
"feature",
".",
"name",
"!=",
"'library'",
":",
"new_properties",
".",
"append",
"(",
"p",
")",
"properties",
"=",
"new_properties",
"result",
"=",
"result",
".",
"add_raw",
"(",
"properties",
")",
"return",
"result"
] | Given the set of generated targets, and refined build
properties, determines and sets appripriate usage requirements
on those targets. | [
"Given",
"the",
"set",
"of",
"generated",
"targets",
"and",
"refined",
"build",
"properties",
"determines",
"and",
"sets",
"appripriate",
"usage",
"requirements",
"on",
"those",
"targets",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L1296-L1342 |
29,477 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | BasicTarget.create_subvariant | def create_subvariant (self, root_targets, all_targets,
build_request, sources,
rproperties, usage_requirements):
"""Creates a new subvariant-dg instances for 'targets'
- 'root-targets' the virtual targets will be returned to dependents
- 'all-targets' all virtual
targets created while building this main target
- 'build-request' is property-set instance with
requested build properties"""
assert is_iterable_typed(root_targets, virtual_target.VirtualTarget)
assert is_iterable_typed(all_targets, virtual_target.VirtualTarget)
assert isinstance(build_request, property_set.PropertySet)
assert is_iterable_typed(sources, virtual_target.VirtualTarget)
assert isinstance(rproperties, property_set.PropertySet)
assert isinstance(usage_requirements, property_set.PropertySet)
for e in root_targets:
e.root (True)
s = Subvariant (self, build_request, sources,
rproperties, usage_requirements, all_targets)
for v in all_targets:
if not v.creating_subvariant():
v.creating_subvariant(s)
return s | python | def create_subvariant (self, root_targets, all_targets,
build_request, sources,
rproperties, usage_requirements):
"""Creates a new subvariant-dg instances for 'targets'
- 'root-targets' the virtual targets will be returned to dependents
- 'all-targets' all virtual
targets created while building this main target
- 'build-request' is property-set instance with
requested build properties"""
assert is_iterable_typed(root_targets, virtual_target.VirtualTarget)
assert is_iterable_typed(all_targets, virtual_target.VirtualTarget)
assert isinstance(build_request, property_set.PropertySet)
assert is_iterable_typed(sources, virtual_target.VirtualTarget)
assert isinstance(rproperties, property_set.PropertySet)
assert isinstance(usage_requirements, property_set.PropertySet)
for e in root_targets:
e.root (True)
s = Subvariant (self, build_request, sources,
rproperties, usage_requirements, all_targets)
for v in all_targets:
if not v.creating_subvariant():
v.creating_subvariant(s)
return s | [
"def",
"create_subvariant",
"(",
"self",
",",
"root_targets",
",",
"all_targets",
",",
"build_request",
",",
"sources",
",",
"rproperties",
",",
"usage_requirements",
")",
":",
"assert",
"is_iterable_typed",
"(",
"root_targets",
",",
"virtual_target",
".",
"VirtualTarget",
")",
"assert",
"is_iterable_typed",
"(",
"all_targets",
",",
"virtual_target",
".",
"VirtualTarget",
")",
"assert",
"isinstance",
"(",
"build_request",
",",
"property_set",
".",
"PropertySet",
")",
"assert",
"is_iterable_typed",
"(",
"sources",
",",
"virtual_target",
".",
"VirtualTarget",
")",
"assert",
"isinstance",
"(",
"rproperties",
",",
"property_set",
".",
"PropertySet",
")",
"assert",
"isinstance",
"(",
"usage_requirements",
",",
"property_set",
".",
"PropertySet",
")",
"for",
"e",
"in",
"root_targets",
":",
"e",
".",
"root",
"(",
"True",
")",
"s",
"=",
"Subvariant",
"(",
"self",
",",
"build_request",
",",
"sources",
",",
"rproperties",
",",
"usage_requirements",
",",
"all_targets",
")",
"for",
"v",
"in",
"all_targets",
":",
"if",
"not",
"v",
".",
"creating_subvariant",
"(",
")",
":",
"v",
".",
"creating_subvariant",
"(",
"s",
")",
"return",
"s"
] | Creates a new subvariant-dg instances for 'targets'
- 'root-targets' the virtual targets will be returned to dependents
- 'all-targets' all virtual
targets created while building this main target
- 'build-request' is property-set instance with
requested build properties | [
"Creates",
"a",
"new",
"subvariant",
"-",
"dg",
"instances",
"for",
"targets",
"-",
"root",
"-",
"targets",
"the",
"virtual",
"targets",
"will",
"be",
"returned",
"to",
"dependents",
"-",
"all",
"-",
"targets",
"all",
"virtual",
"targets",
"created",
"while",
"building",
"this",
"main",
"target",
"-",
"build",
"-",
"request",
"is",
"property",
"-",
"set",
"instance",
"with",
"requested",
"build",
"properties"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L1344-L1370 |
29,478 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/builtin.py | variant | def variant (name, parents_or_properties, explicit_properties = []):
""" Declares a new variant.
First determines explicit properties for this variant, by
refining parents' explicit properties with the passed explicit
properties. The result is remembered and will be used if
this variant is used as parent.
Second, determines the full property set for this variant by
adding to the explicit properties default values for all properties
which neither present nor are symmetric.
Lastly, makes appropriate value of 'variant' property expand
to the full property set.
name: Name of the variant
parents_or_properties: Specifies parent variants, if
'explicit_properties' are given,
and explicit_properties otherwise.
explicit_properties: Explicit properties.
"""
parents = []
if not explicit_properties:
explicit_properties = parents_or_properties
else:
parents = parents_or_properties
inherited = property_set.empty()
if parents:
# If we allow multiple parents, we'd have to to check for conflicts
# between base variants, and there was no demand for so to bother.
if len (parents) > 1:
raise BaseException ("Multiple base variants are not yet supported")
p = parents[0]
# TODO: the check may be stricter
if not feature.is_implicit_value (p):
raise BaseException ("Invalid base variant '%s'" % p)
inherited = __variant_explicit_properties[p]
explicit_properties = property_set.create_with_validation(explicit_properties)
explicit_properties = inherited.refine(explicit_properties)
# Record explicitly specified properties for this variant
# We do this after inheriting parents' properties, so that
# they affect other variants, derived from this one.
__variant_explicit_properties[name] = explicit_properties
feature.extend('variant', [name])
feature.compose ("<variant>" + name, explicit_properties.all()) | python | def variant (name, parents_or_properties, explicit_properties = []):
""" Declares a new variant.
First determines explicit properties for this variant, by
refining parents' explicit properties with the passed explicit
properties. The result is remembered and will be used if
this variant is used as parent.
Second, determines the full property set for this variant by
adding to the explicit properties default values for all properties
which neither present nor are symmetric.
Lastly, makes appropriate value of 'variant' property expand
to the full property set.
name: Name of the variant
parents_or_properties: Specifies parent variants, if
'explicit_properties' are given,
and explicit_properties otherwise.
explicit_properties: Explicit properties.
"""
parents = []
if not explicit_properties:
explicit_properties = parents_or_properties
else:
parents = parents_or_properties
inherited = property_set.empty()
if parents:
# If we allow multiple parents, we'd have to to check for conflicts
# between base variants, and there was no demand for so to bother.
if len (parents) > 1:
raise BaseException ("Multiple base variants are not yet supported")
p = parents[0]
# TODO: the check may be stricter
if not feature.is_implicit_value (p):
raise BaseException ("Invalid base variant '%s'" % p)
inherited = __variant_explicit_properties[p]
explicit_properties = property_set.create_with_validation(explicit_properties)
explicit_properties = inherited.refine(explicit_properties)
# Record explicitly specified properties for this variant
# We do this after inheriting parents' properties, so that
# they affect other variants, derived from this one.
__variant_explicit_properties[name] = explicit_properties
feature.extend('variant', [name])
feature.compose ("<variant>" + name, explicit_properties.all()) | [
"def",
"variant",
"(",
"name",
",",
"parents_or_properties",
",",
"explicit_properties",
"=",
"[",
"]",
")",
":",
"parents",
"=",
"[",
"]",
"if",
"not",
"explicit_properties",
":",
"explicit_properties",
"=",
"parents_or_properties",
"else",
":",
"parents",
"=",
"parents_or_properties",
"inherited",
"=",
"property_set",
".",
"empty",
"(",
")",
"if",
"parents",
":",
"# If we allow multiple parents, we'd have to to check for conflicts",
"# between base variants, and there was no demand for so to bother.",
"if",
"len",
"(",
"parents",
")",
">",
"1",
":",
"raise",
"BaseException",
"(",
"\"Multiple base variants are not yet supported\"",
")",
"p",
"=",
"parents",
"[",
"0",
"]",
"# TODO: the check may be stricter",
"if",
"not",
"feature",
".",
"is_implicit_value",
"(",
"p",
")",
":",
"raise",
"BaseException",
"(",
"\"Invalid base variant '%s'\"",
"%",
"p",
")",
"inherited",
"=",
"__variant_explicit_properties",
"[",
"p",
"]",
"explicit_properties",
"=",
"property_set",
".",
"create_with_validation",
"(",
"explicit_properties",
")",
"explicit_properties",
"=",
"inherited",
".",
"refine",
"(",
"explicit_properties",
")",
"# Record explicitly specified properties for this variant",
"# We do this after inheriting parents' properties, so that",
"# they affect other variants, derived from this one.",
"__variant_explicit_properties",
"[",
"name",
"]",
"=",
"explicit_properties",
"feature",
".",
"extend",
"(",
"'variant'",
",",
"[",
"name",
"]",
")",
"feature",
".",
"compose",
"(",
"\"<variant>\"",
"+",
"name",
",",
"explicit_properties",
".",
"all",
"(",
")",
")"
] | Declares a new variant.
First determines explicit properties for this variant, by
refining parents' explicit properties with the passed explicit
properties. The result is remembered and will be used if
this variant is used as parent.
Second, determines the full property set for this variant by
adding to the explicit properties default values for all properties
which neither present nor are symmetric.
Lastly, makes appropriate value of 'variant' property expand
to the full property set.
name: Name of the variant
parents_or_properties: Specifies parent variants, if
'explicit_properties' are given,
and explicit_properties otherwise.
explicit_properties: Explicit properties. | [
"Declares",
"a",
"new",
"variant",
".",
"First",
"determines",
"explicit",
"properties",
"for",
"this",
"variant",
"by",
"refining",
"parents",
"explicit",
"properties",
"with",
"the",
"passed",
"explicit",
"properties",
".",
"The",
"result",
"is",
"remembered",
"and",
"will",
"be",
"used",
"if",
"this",
"variant",
"is",
"used",
"as",
"parent",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/builtin.py#L33-L82 |
29,479 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/builtin.py | CompileAction.adjust_properties | def adjust_properties (self, prop_set):
""" For all virtual targets for the same dependency graph as self,
i.e. which belong to the same main target, add their directories
to include path.
"""
assert isinstance(prop_set, property_set.PropertySet)
s = self.targets () [0].creating_subvariant ()
return prop_set.add_raw (s.implicit_includes ('include', 'H')) | python | def adjust_properties (self, prop_set):
""" For all virtual targets for the same dependency graph as self,
i.e. which belong to the same main target, add their directories
to include path.
"""
assert isinstance(prop_set, property_set.PropertySet)
s = self.targets () [0].creating_subvariant ()
return prop_set.add_raw (s.implicit_includes ('include', 'H')) | [
"def",
"adjust_properties",
"(",
"self",
",",
"prop_set",
")",
":",
"assert",
"isinstance",
"(",
"prop_set",
",",
"property_set",
".",
"PropertySet",
")",
"s",
"=",
"self",
".",
"targets",
"(",
")",
"[",
"0",
"]",
".",
"creating_subvariant",
"(",
")",
"return",
"prop_set",
".",
"add_raw",
"(",
"s",
".",
"implicit_includes",
"(",
"'include'",
",",
"'H'",
")",
")"
] | For all virtual targets for the same dependency graph as self,
i.e. which belong to the same main target, add their directories
to include path. | [
"For",
"all",
"virtual",
"targets",
"for",
"the",
"same",
"dependency",
"graph",
"as",
"self",
"i",
".",
"e",
".",
"which",
"belong",
"to",
"the",
"same",
"main",
"target",
"add",
"their",
"directories",
"to",
"include",
"path",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/builtin.py#L581-L589 |
29,480 | apple/turicreate | src/unity/python/turicreate/toolkits/recommender/popularity_recommender.py | create | def create(observation_data,
user_id='user_id', item_id='item_id', target=None,
user_data=None, item_data=None,
random_seed=0,
verbose=True):
"""
Create a model that makes recommendations using item popularity. When no
target column is provided, the popularity is determined by the number of
observations involving each item. When a target is provided, popularity
is computed using the item's mean target value. When the target column
contains ratings, for example, the model computes the mean rating for
each item and uses this to rank items for recommendations.
Parameters
----------
observation_data : SFrame
The dataset to use for training the model. It must contain a column of
user ids and a column of item ids. Each row represents an observed
interaction between the user and the item. The (user, item) pairs
are stored with the model so that they can later be excluded from
recommendations if desired. It can optionally contain a target ratings
column. All other columns are interpreted by the underlying model as
side features for the observations.
The user id and item id columns must be of type 'int' or 'str'. The
target column must be of type 'int' or 'float'.
user_id : string, optional
The name of the column in `observation_data` that corresponds to the
user id.
item_id : string, optional
The name of the column in `observation_data` that corresponds to the
item id.
target : string, optional
The `observation_data` can optionally contain a column of scores
representing ratings given by the users. If present, the name of this
column may be specified variables `target`.
user_data : SFrame, optional
Side information for the users. This SFrame must have a column with
the same name as what is specified by the `user_id` input parameter.
`user_data` can provide any amount of additional user-specific
information.
item_data : SFrame, optional
Side information for the items. This SFrame must have a column with
the same name as what is specified by the `item_id` input parameter.
`item_data` can provide any amount of additional item-specific
information.
verbose : bool, optional
Enables verbose output.
Examples
--------
>>> sf = turicreate.SFrame({'user_id': ["0", "0", "0", "1", "1", "2", "2", "2"],
... 'item_id': ["a", "b", "c", "a", "b", "b", "c", "d"],
... 'rating': [1, 3, 2, 5, 4, 1, 4, 3]})
>>> m = turicreate.popularity_recommender.create(sf, target='rating')
See Also
--------
PopularityRecommender
"""
from turicreate._cython.cy_server import QuietProgress
opts = {}
model_proxy = _turicreate.extensions.popularity()
model_proxy.init_options(opts)
if user_data is None:
user_data = _turicreate.SFrame()
if item_data is None:
item_data = _turicreate.SFrame()
nearest_items = _turicreate.SFrame()
opts = {'user_id': user_id,
'item_id': item_id,
'target': target,
'random_seed': 1}
extra_data = {"nearest_items" : _turicreate.SFrame()}
with QuietProgress(verbose):
model_proxy.train(observation_data, user_data, item_data, opts, extra_data)
return PopularityRecommender(model_proxy) | python | def create(observation_data,
user_id='user_id', item_id='item_id', target=None,
user_data=None, item_data=None,
random_seed=0,
verbose=True):
"""
Create a model that makes recommendations using item popularity. When no
target column is provided, the popularity is determined by the number of
observations involving each item. When a target is provided, popularity
is computed using the item's mean target value. When the target column
contains ratings, for example, the model computes the mean rating for
each item and uses this to rank items for recommendations.
Parameters
----------
observation_data : SFrame
The dataset to use for training the model. It must contain a column of
user ids and a column of item ids. Each row represents an observed
interaction between the user and the item. The (user, item) pairs
are stored with the model so that they can later be excluded from
recommendations if desired. It can optionally contain a target ratings
column. All other columns are interpreted by the underlying model as
side features for the observations.
The user id and item id columns must be of type 'int' or 'str'. The
target column must be of type 'int' or 'float'.
user_id : string, optional
The name of the column in `observation_data` that corresponds to the
user id.
item_id : string, optional
The name of the column in `observation_data` that corresponds to the
item id.
target : string, optional
The `observation_data` can optionally contain a column of scores
representing ratings given by the users. If present, the name of this
column may be specified variables `target`.
user_data : SFrame, optional
Side information for the users. This SFrame must have a column with
the same name as what is specified by the `user_id` input parameter.
`user_data` can provide any amount of additional user-specific
information.
item_data : SFrame, optional
Side information for the items. This SFrame must have a column with
the same name as what is specified by the `item_id` input parameter.
`item_data` can provide any amount of additional item-specific
information.
verbose : bool, optional
Enables verbose output.
Examples
--------
>>> sf = turicreate.SFrame({'user_id': ["0", "0", "0", "1", "1", "2", "2", "2"],
... 'item_id': ["a", "b", "c", "a", "b", "b", "c", "d"],
... 'rating': [1, 3, 2, 5, 4, 1, 4, 3]})
>>> m = turicreate.popularity_recommender.create(sf, target='rating')
See Also
--------
PopularityRecommender
"""
from turicreate._cython.cy_server import QuietProgress
opts = {}
model_proxy = _turicreate.extensions.popularity()
model_proxy.init_options(opts)
if user_data is None:
user_data = _turicreate.SFrame()
if item_data is None:
item_data = _turicreate.SFrame()
nearest_items = _turicreate.SFrame()
opts = {'user_id': user_id,
'item_id': item_id,
'target': target,
'random_seed': 1}
extra_data = {"nearest_items" : _turicreate.SFrame()}
with QuietProgress(verbose):
model_proxy.train(observation_data, user_data, item_data, opts, extra_data)
return PopularityRecommender(model_proxy) | [
"def",
"create",
"(",
"observation_data",
",",
"user_id",
"=",
"'user_id'",
",",
"item_id",
"=",
"'item_id'",
",",
"target",
"=",
"None",
",",
"user_data",
"=",
"None",
",",
"item_data",
"=",
"None",
",",
"random_seed",
"=",
"0",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"turicreate",
".",
"_cython",
".",
"cy_server",
"import",
"QuietProgress",
"opts",
"=",
"{",
"}",
"model_proxy",
"=",
"_turicreate",
".",
"extensions",
".",
"popularity",
"(",
")",
"model_proxy",
".",
"init_options",
"(",
"opts",
")",
"if",
"user_data",
"is",
"None",
":",
"user_data",
"=",
"_turicreate",
".",
"SFrame",
"(",
")",
"if",
"item_data",
"is",
"None",
":",
"item_data",
"=",
"_turicreate",
".",
"SFrame",
"(",
")",
"nearest_items",
"=",
"_turicreate",
".",
"SFrame",
"(",
")",
"opts",
"=",
"{",
"'user_id'",
":",
"user_id",
",",
"'item_id'",
":",
"item_id",
",",
"'target'",
":",
"target",
",",
"'random_seed'",
":",
"1",
"}",
"extra_data",
"=",
"{",
"\"nearest_items\"",
":",
"_turicreate",
".",
"SFrame",
"(",
")",
"}",
"with",
"QuietProgress",
"(",
"verbose",
")",
":",
"model_proxy",
".",
"train",
"(",
"observation_data",
",",
"user_data",
",",
"item_data",
",",
"opts",
",",
"extra_data",
")",
"return",
"PopularityRecommender",
"(",
"model_proxy",
")"
] | Create a model that makes recommendations using item popularity. When no
target column is provided, the popularity is determined by the number of
observations involving each item. When a target is provided, popularity
is computed using the item's mean target value. When the target column
contains ratings, for example, the model computes the mean rating for
each item and uses this to rank items for recommendations.
Parameters
----------
observation_data : SFrame
The dataset to use for training the model. It must contain a column of
user ids and a column of item ids. Each row represents an observed
interaction between the user and the item. The (user, item) pairs
are stored with the model so that they can later be excluded from
recommendations if desired. It can optionally contain a target ratings
column. All other columns are interpreted by the underlying model as
side features for the observations.
The user id and item id columns must be of type 'int' or 'str'. The
target column must be of type 'int' or 'float'.
user_id : string, optional
The name of the column in `observation_data` that corresponds to the
user id.
item_id : string, optional
The name of the column in `observation_data` that corresponds to the
item id.
target : string, optional
The `observation_data` can optionally contain a column of scores
representing ratings given by the users. If present, the name of this
column may be specified variables `target`.
user_data : SFrame, optional
Side information for the users. This SFrame must have a column with
the same name as what is specified by the `user_id` input parameter.
`user_data` can provide any amount of additional user-specific
information.
item_data : SFrame, optional
Side information for the items. This SFrame must have a column with
the same name as what is specified by the `item_id` input parameter.
`item_data` can provide any amount of additional item-specific
information.
verbose : bool, optional
Enables verbose output.
Examples
--------
>>> sf = turicreate.SFrame({'user_id': ["0", "0", "0", "1", "1", "2", "2", "2"],
... 'item_id': ["a", "b", "c", "a", "b", "b", "c", "d"],
... 'rating': [1, 3, 2, 5, 4, 1, 4, 3]})
>>> m = turicreate.popularity_recommender.create(sf, target='rating')
See Also
--------
PopularityRecommender | [
"Create",
"a",
"model",
"that",
"makes",
"recommendations",
"using",
"item",
"popularity",
".",
"When",
"no",
"target",
"column",
"is",
"provided",
"the",
"popularity",
"is",
"determined",
"by",
"the",
"number",
"of",
"observations",
"involving",
"each",
"item",
".",
"When",
"a",
"target",
"is",
"provided",
"popularity",
"is",
"computed",
"using",
"the",
"item",
"s",
"mean",
"target",
"value",
".",
"When",
"the",
"target",
"column",
"contains",
"ratings",
"for",
"example",
"the",
"model",
"computes",
"the",
"mean",
"rating",
"for",
"each",
"item",
"and",
"uses",
"this",
"to",
"rank",
"items",
"for",
"recommendations",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/recommender/popularity_recommender.py#L15-L102 |
29,481 | apple/turicreate | src/external/xgboost/python-package/xgboost/sklearn.py | XGBModel.get_params | def get_params(self, deep=False):
"""Get parameter.s"""
params = super(XGBModel, self).get_params(deep=deep)
if params['missing'] is np.nan:
params['missing'] = None # sklearn doesn't handle nan. see #4725
if not params.get('eval_metric', True):
del params['eval_metric'] # don't give as None param to Booster
return params | python | def get_params(self, deep=False):
"""Get parameter.s"""
params = super(XGBModel, self).get_params(deep=deep)
if params['missing'] is np.nan:
params['missing'] = None # sklearn doesn't handle nan. see #4725
if not params.get('eval_metric', True):
del params['eval_metric'] # don't give as None param to Booster
return params | [
"def",
"get_params",
"(",
"self",
",",
"deep",
"=",
"False",
")",
":",
"params",
"=",
"super",
"(",
"XGBModel",
",",
"self",
")",
".",
"get_params",
"(",
"deep",
"=",
"deep",
")",
"if",
"params",
"[",
"'missing'",
"]",
"is",
"np",
".",
"nan",
":",
"params",
"[",
"'missing'",
"]",
"=",
"None",
"# sklearn doesn't handle nan. see #4725",
"if",
"not",
"params",
".",
"get",
"(",
"'eval_metric'",
",",
"True",
")",
":",
"del",
"params",
"[",
"'eval_metric'",
"]",
"# don't give as None param to Booster",
"return",
"params"
] | Get parameter.s | [
"Get",
"parameter",
".",
"s"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/sklearn.py#L126-L133 |
29,482 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/utility.py | replace_grist | def replace_grist (features, new_grist):
""" Replaces the grist of a string by a new one.
Returns the string with the new grist.
"""
assert is_iterable_typed(features, basestring) or isinstance(features, basestring)
assert isinstance(new_grist, basestring)
# this function is used a lot in the build phase and the original implementation
# was extremely slow; thus some of the weird-looking optimizations for this function.
single_item = False
if isinstance(features, str):
features = [features]
single_item = True
result = []
for feature in features:
# '<feature>value' -> ('<feature', '>', 'value')
# 'something' -> ('something', '', '')
# '<toolset>msvc/<feature>value' -> ('<toolset', '>', 'msvc/<feature>value')
grist, split, value = feature.partition('>')
# if a partition didn't occur, then grist is just 'something'
# set the value to be the grist
if not value and not split:
value = grist
result.append(new_grist + value)
if single_item:
return result[0]
return result | python | def replace_grist (features, new_grist):
""" Replaces the grist of a string by a new one.
Returns the string with the new grist.
"""
assert is_iterable_typed(features, basestring) or isinstance(features, basestring)
assert isinstance(new_grist, basestring)
# this function is used a lot in the build phase and the original implementation
# was extremely slow; thus some of the weird-looking optimizations for this function.
single_item = False
if isinstance(features, str):
features = [features]
single_item = True
result = []
for feature in features:
# '<feature>value' -> ('<feature', '>', 'value')
# 'something' -> ('something', '', '')
# '<toolset>msvc/<feature>value' -> ('<toolset', '>', 'msvc/<feature>value')
grist, split, value = feature.partition('>')
# if a partition didn't occur, then grist is just 'something'
# set the value to be the grist
if not value and not split:
value = grist
result.append(new_grist + value)
if single_item:
return result[0]
return result | [
"def",
"replace_grist",
"(",
"features",
",",
"new_grist",
")",
":",
"assert",
"is_iterable_typed",
"(",
"features",
",",
"basestring",
")",
"or",
"isinstance",
"(",
"features",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"new_grist",
",",
"basestring",
")",
"# this function is used a lot in the build phase and the original implementation",
"# was extremely slow; thus some of the weird-looking optimizations for this function.",
"single_item",
"=",
"False",
"if",
"isinstance",
"(",
"features",
",",
"str",
")",
":",
"features",
"=",
"[",
"features",
"]",
"single_item",
"=",
"True",
"result",
"=",
"[",
"]",
"for",
"feature",
"in",
"features",
":",
"# '<feature>value' -> ('<feature', '>', 'value')",
"# 'something' -> ('something', '', '')",
"# '<toolset>msvc/<feature>value' -> ('<toolset', '>', 'msvc/<feature>value')",
"grist",
",",
"split",
",",
"value",
"=",
"feature",
".",
"partition",
"(",
"'>'",
")",
"# if a partition didn't occur, then grist is just 'something'",
"# set the value to be the grist",
"if",
"not",
"value",
"and",
"not",
"split",
":",
"value",
"=",
"grist",
"result",
".",
"append",
"(",
"new_grist",
"+",
"value",
")",
"if",
"single_item",
":",
"return",
"result",
"[",
"0",
"]",
"return",
"result"
] | Replaces the grist of a string by a new one.
Returns the string with the new grist. | [
"Replaces",
"the",
"grist",
"of",
"a",
"string",
"by",
"a",
"new",
"one",
".",
"Returns",
"the",
"string",
"with",
"the",
"new",
"grist",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/utility.py#L56-L83 |
29,483 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/utility.py | get_value | def get_value (property):
""" Gets the value of a property, that is, the part following the grist, if any.
"""
assert is_iterable_typed(property, basestring) or isinstance(property, basestring)
return replace_grist (property, '') | python | def get_value (property):
""" Gets the value of a property, that is, the part following the grist, if any.
"""
assert is_iterable_typed(property, basestring) or isinstance(property, basestring)
return replace_grist (property, '') | [
"def",
"get_value",
"(",
"property",
")",
":",
"assert",
"is_iterable_typed",
"(",
"property",
",",
"basestring",
")",
"or",
"isinstance",
"(",
"property",
",",
"basestring",
")",
"return",
"replace_grist",
"(",
"property",
",",
"''",
")"
] | Gets the value of a property, that is, the part following the grist, if any. | [
"Gets",
"the",
"value",
"of",
"a",
"property",
"that",
"is",
"the",
"part",
"following",
"the",
"grist",
"if",
"any",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/utility.py#L85-L89 |
29,484 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/utility.py | get_grist | def get_grist (value):
""" Returns the grist of a string.
If value is a sequence, does it for every value and returns the result as a sequence.
"""
assert is_iterable_typed(value, basestring) or isinstance(value, basestring)
def get_grist_one (name):
split = __re_grist_and_value.match (name)
if not split:
return ''
else:
return split.group (1)
if isinstance (value, str):
return get_grist_one (value)
else:
return [ get_grist_one (v) for v in value ] | python | def get_grist (value):
""" Returns the grist of a string.
If value is a sequence, does it for every value and returns the result as a sequence.
"""
assert is_iterable_typed(value, basestring) or isinstance(value, basestring)
def get_grist_one (name):
split = __re_grist_and_value.match (name)
if not split:
return ''
else:
return split.group (1)
if isinstance (value, str):
return get_grist_one (value)
else:
return [ get_grist_one (v) for v in value ] | [
"def",
"get_grist",
"(",
"value",
")",
":",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basestring",
")",
"or",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"def",
"get_grist_one",
"(",
"name",
")",
":",
"split",
"=",
"__re_grist_and_value",
".",
"match",
"(",
"name",
")",
"if",
"not",
"split",
":",
"return",
"''",
"else",
":",
"return",
"split",
".",
"group",
"(",
"1",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"get_grist_one",
"(",
"value",
")",
"else",
":",
"return",
"[",
"get_grist_one",
"(",
"v",
")",
"for",
"v",
"in",
"value",
"]"
] | Returns the grist of a string.
If value is a sequence, does it for every value and returns the result as a sequence. | [
"Returns",
"the",
"grist",
"of",
"a",
"string",
".",
"If",
"value",
"is",
"a",
"sequence",
"does",
"it",
"for",
"every",
"value",
"and",
"returns",
"the",
"result",
"as",
"a",
"sequence",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/utility.py#L91-L106 |
29,485 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/utility.py | ungrist | def ungrist (value):
""" Returns the value without grist.
If value is a sequence, does it for every value and returns the result as a sequence.
"""
assert is_iterable_typed(value, basestring) or isinstance(value, basestring)
def ungrist_one (value):
stripped = __re_grist_content.match (value)
if not stripped:
raise BaseException ("in ungrist: '%s' is not of the form <.*>" % value)
return stripped.group (1)
if isinstance (value, str):
return ungrist_one (value)
else:
return [ ungrist_one (v) for v in value ] | python | def ungrist (value):
""" Returns the value without grist.
If value is a sequence, does it for every value and returns the result as a sequence.
"""
assert is_iterable_typed(value, basestring) or isinstance(value, basestring)
def ungrist_one (value):
stripped = __re_grist_content.match (value)
if not stripped:
raise BaseException ("in ungrist: '%s' is not of the form <.*>" % value)
return stripped.group (1)
if isinstance (value, str):
return ungrist_one (value)
else:
return [ ungrist_one (v) for v in value ] | [
"def",
"ungrist",
"(",
"value",
")",
":",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basestring",
")",
"or",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"def",
"ungrist_one",
"(",
"value",
")",
":",
"stripped",
"=",
"__re_grist_content",
".",
"match",
"(",
"value",
")",
"if",
"not",
"stripped",
":",
"raise",
"BaseException",
"(",
"\"in ungrist: '%s' is not of the form <.*>\"",
"%",
"value",
")",
"return",
"stripped",
".",
"group",
"(",
"1",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"ungrist_one",
"(",
"value",
")",
"else",
":",
"return",
"[",
"ungrist_one",
"(",
"v",
")",
"for",
"v",
"in",
"value",
"]"
] | Returns the value without grist.
If value is a sequence, does it for every value and returns the result as a sequence. | [
"Returns",
"the",
"value",
"without",
"grist",
".",
"If",
"value",
"is",
"a",
"sequence",
"does",
"it",
"for",
"every",
"value",
"and",
"returns",
"the",
"result",
"as",
"a",
"sequence",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/utility.py#L108-L123 |
29,486 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/utility.py | replace_suffix | def replace_suffix (name, new_suffix):
""" Replaces the suffix of name by new_suffix.
If no suffix exists, the new one is added.
"""
assert isinstance(name, basestring)
assert isinstance(new_suffix, basestring)
split = os.path.splitext (name)
return split [0] + new_suffix | python | def replace_suffix (name, new_suffix):
""" Replaces the suffix of name by new_suffix.
If no suffix exists, the new one is added.
"""
assert isinstance(name, basestring)
assert isinstance(new_suffix, basestring)
split = os.path.splitext (name)
return split [0] + new_suffix | [
"def",
"replace_suffix",
"(",
"name",
",",
"new_suffix",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"new_suffix",
",",
"basestring",
")",
"split",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"return",
"split",
"[",
"0",
"]",
"+",
"new_suffix"
] | Replaces the suffix of name by new_suffix.
If no suffix exists, the new one is added. | [
"Replaces",
"the",
"suffix",
"of",
"name",
"by",
"new_suffix",
".",
"If",
"no",
"suffix",
"exists",
"the",
"new",
"one",
"is",
"added",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/utility.py#L125-L132 |
29,487 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/utility.py | on_windows | def on_windows ():
""" Returns true if running on windows, whether in cygwin or not.
"""
if bjam.variable("NT"):
return True
elif bjam.variable("UNIX"):
uname = bjam.variable("JAMUNAME")
if uname and uname[0].startswith("CYGWIN"):
return True
return False | python | def on_windows ():
""" Returns true if running on windows, whether in cygwin or not.
"""
if bjam.variable("NT"):
return True
elif bjam.variable("UNIX"):
uname = bjam.variable("JAMUNAME")
if uname and uname[0].startswith("CYGWIN"):
return True
return False | [
"def",
"on_windows",
"(",
")",
":",
"if",
"bjam",
".",
"variable",
"(",
"\"NT\"",
")",
":",
"return",
"True",
"elif",
"bjam",
".",
"variable",
"(",
"\"UNIX\"",
")",
":",
"uname",
"=",
"bjam",
".",
"variable",
"(",
"\"JAMUNAME\"",
")",
"if",
"uname",
"and",
"uname",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"CYGWIN\"",
")",
":",
"return",
"True",
"return",
"False"
] | Returns true if running on windows, whether in cygwin or not. | [
"Returns",
"true",
"if",
"running",
"on",
"windows",
"whether",
"in",
"cygwin",
"or",
"not",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/utility.py#L164-L176 |
29,488 | apple/turicreate | src/unity/python/turicreate/toolkits/clustering/kmeans.py | _validate_dataset | def _validate_dataset(dataset):
"""
Validate the main Kmeans dataset.
Parameters
----------
dataset: SFrame
Input dataset.
"""
if not (isinstance(dataset, _SFrame)):
raise TypeError("Input 'dataset' must be an SFrame.")
if dataset.num_rows() == 0 or dataset.num_columns() == 0:
raise ValueError("Input 'dataset' has no data.") | python | def _validate_dataset(dataset):
"""
Validate the main Kmeans dataset.
Parameters
----------
dataset: SFrame
Input dataset.
"""
if not (isinstance(dataset, _SFrame)):
raise TypeError("Input 'dataset' must be an SFrame.")
if dataset.num_rows() == 0 or dataset.num_columns() == 0:
raise ValueError("Input 'dataset' has no data.") | [
"def",
"_validate_dataset",
"(",
"dataset",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"dataset",
",",
"_SFrame",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Input 'dataset' must be an SFrame.\"",
")",
"if",
"dataset",
".",
"num_rows",
"(",
")",
"==",
"0",
"or",
"dataset",
".",
"num_columns",
"(",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Input 'dataset' has no data.\"",
")"
] | Validate the main Kmeans dataset.
Parameters
----------
dataset: SFrame
Input dataset. | [
"Validate",
"the",
"main",
"Kmeans",
"dataset",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/clustering/kmeans.py#L25-L38 |
29,489 | apple/turicreate | src/unity/python/turicreate/toolkits/clustering/kmeans.py | _validate_initial_centers | def _validate_initial_centers(initial_centers):
"""
Validate the initial centers.
Parameters
----------
initial_centers : SFrame
Initial cluster center locations, in SFrame form.
"""
if not (isinstance(initial_centers, _SFrame)):
raise TypeError("Input 'initial_centers' must be an SFrame.")
if initial_centers.num_rows() == 0 or initial_centers.num_columns() == 0:
raise ValueError("An 'initial_centers' argument is provided " +
"but has no data.") | python | def _validate_initial_centers(initial_centers):
"""
Validate the initial centers.
Parameters
----------
initial_centers : SFrame
Initial cluster center locations, in SFrame form.
"""
if not (isinstance(initial_centers, _SFrame)):
raise TypeError("Input 'initial_centers' must be an SFrame.")
if initial_centers.num_rows() == 0 or initial_centers.num_columns() == 0:
raise ValueError("An 'initial_centers' argument is provided " +
"but has no data.") | [
"def",
"_validate_initial_centers",
"(",
"initial_centers",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"initial_centers",
",",
"_SFrame",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Input 'initial_centers' must be an SFrame.\"",
")",
"if",
"initial_centers",
".",
"num_rows",
"(",
")",
"==",
"0",
"or",
"initial_centers",
".",
"num_columns",
"(",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"An 'initial_centers' argument is provided \"",
"+",
"\"but has no data.\"",
")"
] | Validate the initial centers.
Parameters
----------
initial_centers : SFrame
Initial cluster center locations, in SFrame form. | [
"Validate",
"the",
"initial",
"centers",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/clustering/kmeans.py#L41-L55 |
29,490 | apple/turicreate | src/unity/python/turicreate/toolkits/clustering/kmeans.py | _validate_num_clusters | def _validate_num_clusters(num_clusters, initial_centers, num_rows):
"""
Validate the combination of the `num_clusters` and `initial_centers`
parameters in the Kmeans model create function. If the combination is
valid, determine and return the correct number of clusters.
Parameters
----------
num_clusters : int
Specified number of clusters.
initial_centers : SFrame
Specified initial cluster center locations, in SFrame form. If the
number of rows in this SFrame does not match `num_clusters`, there is a
problem.
num_rows : int
Number of rows in the input dataset.
Returns
-------
_num_clusters : int
The correct number of clusters to use going forward
"""
## Basic validation
if num_clusters is not None and not isinstance(num_clusters, int):
raise _ToolkitError("Parameter 'num_clusters' must be an integer.")
## Determine the correct number of clusters.
if initial_centers is None:
if num_clusters is None:
raise ValueError("Number of clusters cannot be determined from " +
"'num_clusters' or 'initial_centers'. You must " +
"specify one of these arguments.")
else:
_num_clusters = num_clusters
else:
num_centers = initial_centers.num_rows()
if num_clusters is None:
_num_clusters = num_centers
else:
if num_clusters != num_centers:
raise ValueError("The value of 'num_clusters' does not match " +
"the number of provided initial centers. " +
"Please provide only one of these arguments " +
"or ensure the values match.")
else:
_num_clusters = num_clusters
if _num_clusters > num_rows:
raise ValueError("The desired number of clusters exceeds the number " +
"of data points. Please set 'num_clusters' to be " +
"smaller than the number of data points.")
return _num_clusters | python | def _validate_num_clusters(num_clusters, initial_centers, num_rows):
"""
Validate the combination of the `num_clusters` and `initial_centers`
parameters in the Kmeans model create function. If the combination is
valid, determine and return the correct number of clusters.
Parameters
----------
num_clusters : int
Specified number of clusters.
initial_centers : SFrame
Specified initial cluster center locations, in SFrame form. If the
number of rows in this SFrame does not match `num_clusters`, there is a
problem.
num_rows : int
Number of rows in the input dataset.
Returns
-------
_num_clusters : int
The correct number of clusters to use going forward
"""
## Basic validation
if num_clusters is not None and not isinstance(num_clusters, int):
raise _ToolkitError("Parameter 'num_clusters' must be an integer.")
## Determine the correct number of clusters.
if initial_centers is None:
if num_clusters is None:
raise ValueError("Number of clusters cannot be determined from " +
"'num_clusters' or 'initial_centers'. You must " +
"specify one of these arguments.")
else:
_num_clusters = num_clusters
else:
num_centers = initial_centers.num_rows()
if num_clusters is None:
_num_clusters = num_centers
else:
if num_clusters != num_centers:
raise ValueError("The value of 'num_clusters' does not match " +
"the number of provided initial centers. " +
"Please provide only one of these arguments " +
"or ensure the values match.")
else:
_num_clusters = num_clusters
if _num_clusters > num_rows:
raise ValueError("The desired number of clusters exceeds the number " +
"of data points. Please set 'num_clusters' to be " +
"smaller than the number of data points.")
return _num_clusters | [
"def",
"_validate_num_clusters",
"(",
"num_clusters",
",",
"initial_centers",
",",
"num_rows",
")",
":",
"## Basic validation",
"if",
"num_clusters",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"num_clusters",
",",
"int",
")",
":",
"raise",
"_ToolkitError",
"(",
"\"Parameter 'num_clusters' must be an integer.\"",
")",
"## Determine the correct number of clusters.",
"if",
"initial_centers",
"is",
"None",
":",
"if",
"num_clusters",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Number of clusters cannot be determined from \"",
"+",
"\"'num_clusters' or 'initial_centers'. You must \"",
"+",
"\"specify one of these arguments.\"",
")",
"else",
":",
"_num_clusters",
"=",
"num_clusters",
"else",
":",
"num_centers",
"=",
"initial_centers",
".",
"num_rows",
"(",
")",
"if",
"num_clusters",
"is",
"None",
":",
"_num_clusters",
"=",
"num_centers",
"else",
":",
"if",
"num_clusters",
"!=",
"num_centers",
":",
"raise",
"ValueError",
"(",
"\"The value of 'num_clusters' does not match \"",
"+",
"\"the number of provided initial centers. \"",
"+",
"\"Please provide only one of these arguments \"",
"+",
"\"or ensure the values match.\"",
")",
"else",
":",
"_num_clusters",
"=",
"num_clusters",
"if",
"_num_clusters",
">",
"num_rows",
":",
"raise",
"ValueError",
"(",
"\"The desired number of clusters exceeds the number \"",
"+",
"\"of data points. Please set 'num_clusters' to be \"",
"+",
"\"smaller than the number of data points.\"",
")",
"return",
"_num_clusters"
] | Validate the combination of the `num_clusters` and `initial_centers`
parameters in the Kmeans model create function. If the combination is
valid, determine and return the correct number of clusters.
Parameters
----------
num_clusters : int
Specified number of clusters.
initial_centers : SFrame
Specified initial cluster center locations, in SFrame form. If the
number of rows in this SFrame does not match `num_clusters`, there is a
problem.
num_rows : int
Number of rows in the input dataset.
Returns
-------
_num_clusters : int
The correct number of clusters to use going forward | [
"Validate",
"the",
"combination",
"of",
"the",
"num_clusters",
"and",
"initial_centers",
"parameters",
"in",
"the",
"Kmeans",
"model",
"create",
"function",
".",
"If",
"the",
"combination",
"is",
"valid",
"determine",
"and",
"return",
"the",
"correct",
"number",
"of",
"clusters",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/clustering/kmeans.py#L58-L115 |
29,491 | apple/turicreate | src/unity/python/turicreate/toolkits/clustering/kmeans.py | _validate_features | def _validate_features(features, column_type_map, valid_types, label):
"""
Identify the subset of desired `features` that are valid for the Kmeans
model. A warning is emitted for each feature that is excluded.
Parameters
----------
features : list[str]
Desired feature names.
column_type_map : dict[str, type]
Dictionary mapping each column name to the type of values in the
column.
valid_types : list[type]
Exclude features whose type is not in this list.
label : str
Name of the row label column.
Returns
-------
valid_features : list[str]
Names of features to include in the model.
"""
if not isinstance(features, list):
raise TypeError("Input 'features' must be a list, if specified.")
if len(features) == 0:
raise ValueError("If specified, input 'features' must contain " +
"at least one column name.")
## Remove duplicates
num_original_features = len(features)
features = set(features)
if len(features) < num_original_features:
_logging.warning("Duplicates have been removed from the list of features")
## Remove the row label
if label in features:
features.remove(label)
_logging.warning("The row label has been removed from the list of features.")
## Check the type of each feature against the list of valid types
valid_features = []
for ftr in features:
if not isinstance(ftr, str):
_logging.warning("Feature '{}' excluded. ".format(ftr) +
"Features must be specified as strings " +
"corresponding to column names in the input dataset.")
elif ftr not in column_type_map.keys():
_logging.warning("Feature '{}' excluded because ".format(ftr) +
"it is not in the input dataset.")
elif column_type_map[ftr] not in valid_types:
_logging.warning("Feature '{}' excluded because of its type. ".format(ftr) +
"Kmeans features must be int, float, dict, or array.array type.")
else:
valid_features.append(ftr)
if len(valid_features) == 0:
raise _ToolkitError("All specified features have been excluded. " +
"Please specify valid features.")
return valid_features | python | def _validate_features(features, column_type_map, valid_types, label):
"""
Identify the subset of desired `features` that are valid for the Kmeans
model. A warning is emitted for each feature that is excluded.
Parameters
----------
features : list[str]
Desired feature names.
column_type_map : dict[str, type]
Dictionary mapping each column name to the type of values in the
column.
valid_types : list[type]
Exclude features whose type is not in this list.
label : str
Name of the row label column.
Returns
-------
valid_features : list[str]
Names of features to include in the model.
"""
if not isinstance(features, list):
raise TypeError("Input 'features' must be a list, if specified.")
if len(features) == 0:
raise ValueError("If specified, input 'features' must contain " +
"at least one column name.")
## Remove duplicates
num_original_features = len(features)
features = set(features)
if len(features) < num_original_features:
_logging.warning("Duplicates have been removed from the list of features")
## Remove the row label
if label in features:
features.remove(label)
_logging.warning("The row label has been removed from the list of features.")
## Check the type of each feature against the list of valid types
valid_features = []
for ftr in features:
if not isinstance(ftr, str):
_logging.warning("Feature '{}' excluded. ".format(ftr) +
"Features must be specified as strings " +
"corresponding to column names in the input dataset.")
elif ftr not in column_type_map.keys():
_logging.warning("Feature '{}' excluded because ".format(ftr) +
"it is not in the input dataset.")
elif column_type_map[ftr] not in valid_types:
_logging.warning("Feature '{}' excluded because of its type. ".format(ftr) +
"Kmeans features must be int, float, dict, or array.array type.")
else:
valid_features.append(ftr)
if len(valid_features) == 0:
raise _ToolkitError("All specified features have been excluded. " +
"Please specify valid features.")
return valid_features | [
"def",
"_validate_features",
"(",
"features",
",",
"column_type_map",
",",
"valid_types",
",",
"label",
")",
":",
"if",
"not",
"isinstance",
"(",
"features",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"Input 'features' must be a list, if specified.\"",
")",
"if",
"len",
"(",
"features",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"If specified, input 'features' must contain \"",
"+",
"\"at least one column name.\"",
")",
"## Remove duplicates",
"num_original_features",
"=",
"len",
"(",
"features",
")",
"features",
"=",
"set",
"(",
"features",
")",
"if",
"len",
"(",
"features",
")",
"<",
"num_original_features",
":",
"_logging",
".",
"warning",
"(",
"\"Duplicates have been removed from the list of features\"",
")",
"## Remove the row label",
"if",
"label",
"in",
"features",
":",
"features",
".",
"remove",
"(",
"label",
")",
"_logging",
".",
"warning",
"(",
"\"The row label has been removed from the list of features.\"",
")",
"## Check the type of each feature against the list of valid types",
"valid_features",
"=",
"[",
"]",
"for",
"ftr",
"in",
"features",
":",
"if",
"not",
"isinstance",
"(",
"ftr",
",",
"str",
")",
":",
"_logging",
".",
"warning",
"(",
"\"Feature '{}' excluded. \"",
".",
"format",
"(",
"ftr",
")",
"+",
"\"Features must be specified as strings \"",
"+",
"\"corresponding to column names in the input dataset.\"",
")",
"elif",
"ftr",
"not",
"in",
"column_type_map",
".",
"keys",
"(",
")",
":",
"_logging",
".",
"warning",
"(",
"\"Feature '{}' excluded because \"",
".",
"format",
"(",
"ftr",
")",
"+",
"\"it is not in the input dataset.\"",
")",
"elif",
"column_type_map",
"[",
"ftr",
"]",
"not",
"in",
"valid_types",
":",
"_logging",
".",
"warning",
"(",
"\"Feature '{}' excluded because of its type. \"",
".",
"format",
"(",
"ftr",
")",
"+",
"\"Kmeans features must be int, float, dict, or array.array type.\"",
")",
"else",
":",
"valid_features",
".",
"append",
"(",
"ftr",
")",
"if",
"len",
"(",
"valid_features",
")",
"==",
"0",
":",
"raise",
"_ToolkitError",
"(",
"\"All specified features have been excluded. \"",
"+",
"\"Please specify valid features.\"",
")",
"return",
"valid_features"
] | Identify the subset of desired `features` that are valid for the Kmeans
model. A warning is emitted for each feature that is excluded.
Parameters
----------
features : list[str]
Desired feature names.
column_type_map : dict[str, type]
Dictionary mapping each column name to the type of values in the
column.
valid_types : list[type]
Exclude features whose type is not in this list.
label : str
Name of the row label column.
Returns
-------
valid_features : list[str]
Names of features to include in the model. | [
"Identify",
"the",
"subset",
"of",
"desired",
"features",
"that",
"are",
"valid",
"for",
"the",
"Kmeans",
"model",
".",
"A",
"warning",
"is",
"emitted",
"for",
"each",
"feature",
"that",
"is",
"excluded",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/clustering/kmeans.py#L118-L186 |
29,492 | apple/turicreate | src/unity/python/turicreate/toolkits/clustering/kmeans.py | create | def create(dataset, num_clusters=None, features=None, label=None,
initial_centers=None, max_iterations=10, batch_size=None,
verbose=True):
"""
Create a k-means clustering model. The KmeansModel object contains the
computed cluster centers and the cluster assignment for each instance in
the input 'dataset'.
Given a number of clusters, k-means iteratively chooses the best cluster
centers and assigns nearby points to the best cluster. If no points change
cluster membership between iterations, the algorithm terminates.
Parameters
----------
dataset : SFrame
Each row in the SFrame is an observation.
num_clusters : int
Number of clusters. This is the 'k' in k-means.
features : list[str], optional
Names of feature columns to use in computing distances between
observations and cluster centers. 'None' (the default) indicates that
all columns should be used as features. Columns may be of the following
types:
- *Numeric*: values of numeric type integer or float.
- *Array*: list of numeric (int or float) values. Each list element
is treated as a distinct feature in the model.
- *Dict*: dictionary of keys mapped to numeric values. Each unique key
is treated as a distinct feature in the model.
Note that columns of type *list* are not supported. Convert them to
array columns if all entries in the list are of numeric types.
label : str, optional
Name of the column to use as row labels in the Kmeans output. The
values in this column must be integers or strings. If not specified,
row numbers are used by default.
initial_centers : SFrame, optional
Initial centers to use when starting the K-means algorithm. If
specified, this parameter overrides the *num_clusters* parameter. The
'initial_centers' SFrame must contain the same features used in the
input 'dataset'.
If not specified (the default), initial centers are chosen
intelligently with the K-means++ algorithm.
max_iterations : int, optional
The maximum number of iterations to run. Prints a warning if the
algorithm does not converge after max_iterations iterations. If set to
0, the model returns clusters defined by the initial centers and
assignments to those centers.
batch_size : int, optional
Number of randomly-chosen data points to use in each iteration. If
'None' (the default) or greater than the number of rows in 'dataset',
then this parameter is ignored: all rows of `dataset` are used in each
iteration and model training terminates once point assignments stop
changing or `max_iterations` is reached.
verbose : bool, optional
If True, print model training progress to the screen.
Returns
-------
out : KmeansModel
A Model object containing a cluster id for each vertex, and the centers
of the clusters.
See Also
--------
KmeansModel
Notes
-----
- Integer features in the 'dataset' or 'initial_centers' inputs are
converted internally to float type, and the corresponding features in the
output centers are float-typed.
- It can be important for the K-means model to standardize the features so
they have the same scale. This function does *not* standardize
automatically.
References
----------
- `Wikipedia - k-means clustering
<http://en.wikipedia.org/wiki/K-means_clustering>`_
- Artuhur, D. and Vassilvitskii, S. (2007) `k-means++: The Advantages of
Careful Seeding <http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf>`_. In
Proceedings of the Eighteenth Annual ACM-SIAM Symposium on Discrete
Algorithms. pp. 1027-1035.
- Elkan, C. (2003) `Using the triangle inequality to accelerate k-means
<http://www.aaai.org/Papers/ICML/2003/ICML03-022.pdf>`_. In Proceedings
of the Twentieth International Conference on Machine Learning, Volume 3,
pp. 147-153.
- Sculley, D. (2010) `Web Scale K-Means Clustering
<http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf>`_. In
Proceedings of the 19th International Conference on World Wide Web. pp.
1177-1178
Examples
--------
>>> sf = turicreate.SFrame({
... 'x1': [0.6777, -9.391, 7.0385, 2.2657, 7.7864, -10.16, -8.162,
... 8.8817, -9.525, -9.153, 2.0860, 7.6619, 6.5511, 2.7020],
... 'x2': [5.6110, 8.5139, 5.3913, 5.4743, 8.3606, 7.8843, 2.7305,
... 5.1679, 6.7231, 3.7051, 1.7682, 7.4608, 3.1270, 6.5624]})
...
>>> model = turicreate.kmeans.create(sf, num_clusters=3)
"""
opts = {'model_name': 'kmeans',
'max_iterations': max_iterations,
}
## Validate the input dataset and initial centers.
_validate_dataset(dataset)
if initial_centers is not None:
_validate_initial_centers(initial_centers)
## Validate and determine the correct number of clusters.
opts['num_clusters'] = _validate_num_clusters(num_clusters,
initial_centers,
dataset.num_rows())
## Validate the row label
col_type_map = {c: dataset[c].dtype for c in dataset.column_names()}
if label is not None:
_validate_row_label(label, col_type_map)
if label in ['cluster_id', 'distance']:
raise ValueError("Row label column name cannot be 'cluster_id' " +
"or 'distance'; these are reserved for other " +
"columns in the Kmeans model's output.")
opts['row_labels'] = dataset[label]
opts['row_label_name'] = label
else:
opts['row_labels'] = _tc.SArray.from_sequence(dataset.num_rows())
opts['row_label_name'] = 'row_id'
## Validate the features relative to the input dataset.
if features is None:
features = dataset.column_names()
valid_features = _validate_features(features, col_type_map,
valid_types=[_array, dict, int, float],
label=label)
sf_features = dataset.select_columns(valid_features)
opts['features'] = sf_features
## Validate the features in the initial centers (if provided)
if initial_centers is not None:
try:
initial_centers = initial_centers.select_columns(valid_features)
except:
raise ValueError("Specified features cannot be extracted from " +
"the provided initial centers.")
if initial_centers.column_types() != sf_features.column_types():
raise TypeError("Feature types are different in the dataset and " +
"initial centers.")
else:
initial_centers = _tc.SFrame()
opts['initial_centers'] = initial_centers
## Validate the batch size and determine the training method.
if batch_size is None:
opts['method'] = 'elkan'
opts['batch_size'] = dataset.num_rows()
else:
opts['method'] = 'minibatch'
opts['batch_size'] = batch_size
## Create and return the model
with _QuietProgress(verbose):
params = _tc.extensions._kmeans.train(opts)
return KmeansModel(params['model']) | python | def create(dataset, num_clusters=None, features=None, label=None,
initial_centers=None, max_iterations=10, batch_size=None,
verbose=True):
"""
Create a k-means clustering model. The KmeansModel object contains the
computed cluster centers and the cluster assignment for each instance in
the input 'dataset'.
Given a number of clusters, k-means iteratively chooses the best cluster
centers and assigns nearby points to the best cluster. If no points change
cluster membership between iterations, the algorithm terminates.
Parameters
----------
dataset : SFrame
Each row in the SFrame is an observation.
num_clusters : int
Number of clusters. This is the 'k' in k-means.
features : list[str], optional
Names of feature columns to use in computing distances between
observations and cluster centers. 'None' (the default) indicates that
all columns should be used as features. Columns may be of the following
types:
- *Numeric*: values of numeric type integer or float.
- *Array*: list of numeric (int or float) values. Each list element
is treated as a distinct feature in the model.
- *Dict*: dictionary of keys mapped to numeric values. Each unique key
is treated as a distinct feature in the model.
Note that columns of type *list* are not supported. Convert them to
array columns if all entries in the list are of numeric types.
label : str, optional
Name of the column to use as row labels in the Kmeans output. The
values in this column must be integers or strings. If not specified,
row numbers are used by default.
initial_centers : SFrame, optional
Initial centers to use when starting the K-means algorithm. If
specified, this parameter overrides the *num_clusters* parameter. The
'initial_centers' SFrame must contain the same features used in the
input 'dataset'.
If not specified (the default), initial centers are chosen
intelligently with the K-means++ algorithm.
max_iterations : int, optional
The maximum number of iterations to run. Prints a warning if the
algorithm does not converge after max_iterations iterations. If set to
0, the model returns clusters defined by the initial centers and
assignments to those centers.
batch_size : int, optional
Number of randomly-chosen data points to use in each iteration. If
'None' (the default) or greater than the number of rows in 'dataset',
then this parameter is ignored: all rows of `dataset` are used in each
iteration and model training terminates once point assignments stop
changing or `max_iterations` is reached.
verbose : bool, optional
If True, print model training progress to the screen.
Returns
-------
out : KmeansModel
A Model object containing a cluster id for each vertex, and the centers
of the clusters.
See Also
--------
KmeansModel
Notes
-----
- Integer features in the 'dataset' or 'initial_centers' inputs are
converted internally to float type, and the corresponding features in the
output centers are float-typed.
- It can be important for the K-means model to standardize the features so
they have the same scale. This function does *not* standardize
automatically.
References
----------
- `Wikipedia - k-means clustering
<http://en.wikipedia.org/wiki/K-means_clustering>`_
- Artuhur, D. and Vassilvitskii, S. (2007) `k-means++: The Advantages of
Careful Seeding <http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf>`_. In
Proceedings of the Eighteenth Annual ACM-SIAM Symposium on Discrete
Algorithms. pp. 1027-1035.
- Elkan, C. (2003) `Using the triangle inequality to accelerate k-means
<http://www.aaai.org/Papers/ICML/2003/ICML03-022.pdf>`_. In Proceedings
of the Twentieth International Conference on Machine Learning, Volume 3,
pp. 147-153.
- Sculley, D. (2010) `Web Scale K-Means Clustering
<http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf>`_. In
Proceedings of the 19th International Conference on World Wide Web. pp.
1177-1178
Examples
--------
>>> sf = turicreate.SFrame({
... 'x1': [0.6777, -9.391, 7.0385, 2.2657, 7.7864, -10.16, -8.162,
... 8.8817, -9.525, -9.153, 2.0860, 7.6619, 6.5511, 2.7020],
... 'x2': [5.6110, 8.5139, 5.3913, 5.4743, 8.3606, 7.8843, 2.7305,
... 5.1679, 6.7231, 3.7051, 1.7682, 7.4608, 3.1270, 6.5624]})
...
>>> model = turicreate.kmeans.create(sf, num_clusters=3)
"""
opts = {'model_name': 'kmeans',
'max_iterations': max_iterations,
}
## Validate the input dataset and initial centers.
_validate_dataset(dataset)
if initial_centers is not None:
_validate_initial_centers(initial_centers)
## Validate and determine the correct number of clusters.
opts['num_clusters'] = _validate_num_clusters(num_clusters,
initial_centers,
dataset.num_rows())
## Validate the row label
col_type_map = {c: dataset[c].dtype for c in dataset.column_names()}
if label is not None:
_validate_row_label(label, col_type_map)
if label in ['cluster_id', 'distance']:
raise ValueError("Row label column name cannot be 'cluster_id' " +
"or 'distance'; these are reserved for other " +
"columns in the Kmeans model's output.")
opts['row_labels'] = dataset[label]
opts['row_label_name'] = label
else:
opts['row_labels'] = _tc.SArray.from_sequence(dataset.num_rows())
opts['row_label_name'] = 'row_id'
## Validate the features relative to the input dataset.
if features is None:
features = dataset.column_names()
valid_features = _validate_features(features, col_type_map,
valid_types=[_array, dict, int, float],
label=label)
sf_features = dataset.select_columns(valid_features)
opts['features'] = sf_features
## Validate the features in the initial centers (if provided)
if initial_centers is not None:
try:
initial_centers = initial_centers.select_columns(valid_features)
except:
raise ValueError("Specified features cannot be extracted from " +
"the provided initial centers.")
if initial_centers.column_types() != sf_features.column_types():
raise TypeError("Feature types are different in the dataset and " +
"initial centers.")
else:
initial_centers = _tc.SFrame()
opts['initial_centers'] = initial_centers
## Validate the batch size and determine the training method.
if batch_size is None:
opts['method'] = 'elkan'
opts['batch_size'] = dataset.num_rows()
else:
opts['method'] = 'minibatch'
opts['batch_size'] = batch_size
## Create and return the model
with _QuietProgress(verbose):
params = _tc.extensions._kmeans.train(opts)
return KmeansModel(params['model']) | [
"def",
"create",
"(",
"dataset",
",",
"num_clusters",
"=",
"None",
",",
"features",
"=",
"None",
",",
"label",
"=",
"None",
",",
"initial_centers",
"=",
"None",
",",
"max_iterations",
"=",
"10",
",",
"batch_size",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"opts",
"=",
"{",
"'model_name'",
":",
"'kmeans'",
",",
"'max_iterations'",
":",
"max_iterations",
",",
"}",
"## Validate the input dataset and initial centers.",
"_validate_dataset",
"(",
"dataset",
")",
"if",
"initial_centers",
"is",
"not",
"None",
":",
"_validate_initial_centers",
"(",
"initial_centers",
")",
"## Validate and determine the correct number of clusters.",
"opts",
"[",
"'num_clusters'",
"]",
"=",
"_validate_num_clusters",
"(",
"num_clusters",
",",
"initial_centers",
",",
"dataset",
".",
"num_rows",
"(",
")",
")",
"## Validate the row label",
"col_type_map",
"=",
"{",
"c",
":",
"dataset",
"[",
"c",
"]",
".",
"dtype",
"for",
"c",
"in",
"dataset",
".",
"column_names",
"(",
")",
"}",
"if",
"label",
"is",
"not",
"None",
":",
"_validate_row_label",
"(",
"label",
",",
"col_type_map",
")",
"if",
"label",
"in",
"[",
"'cluster_id'",
",",
"'distance'",
"]",
":",
"raise",
"ValueError",
"(",
"\"Row label column name cannot be 'cluster_id' \"",
"+",
"\"or 'distance'; these are reserved for other \"",
"+",
"\"columns in the Kmeans model's output.\"",
")",
"opts",
"[",
"'row_labels'",
"]",
"=",
"dataset",
"[",
"label",
"]",
"opts",
"[",
"'row_label_name'",
"]",
"=",
"label",
"else",
":",
"opts",
"[",
"'row_labels'",
"]",
"=",
"_tc",
".",
"SArray",
".",
"from_sequence",
"(",
"dataset",
".",
"num_rows",
"(",
")",
")",
"opts",
"[",
"'row_label_name'",
"]",
"=",
"'row_id'",
"## Validate the features relative to the input dataset.",
"if",
"features",
"is",
"None",
":",
"features",
"=",
"dataset",
".",
"column_names",
"(",
")",
"valid_features",
"=",
"_validate_features",
"(",
"features",
",",
"col_type_map",
",",
"valid_types",
"=",
"[",
"_array",
",",
"dict",
",",
"int",
",",
"float",
"]",
",",
"label",
"=",
"label",
")",
"sf_features",
"=",
"dataset",
".",
"select_columns",
"(",
"valid_features",
")",
"opts",
"[",
"'features'",
"]",
"=",
"sf_features",
"## Validate the features in the initial centers (if provided)",
"if",
"initial_centers",
"is",
"not",
"None",
":",
"try",
":",
"initial_centers",
"=",
"initial_centers",
".",
"select_columns",
"(",
"valid_features",
")",
"except",
":",
"raise",
"ValueError",
"(",
"\"Specified features cannot be extracted from \"",
"+",
"\"the provided initial centers.\"",
")",
"if",
"initial_centers",
".",
"column_types",
"(",
")",
"!=",
"sf_features",
".",
"column_types",
"(",
")",
":",
"raise",
"TypeError",
"(",
"\"Feature types are different in the dataset and \"",
"+",
"\"initial centers.\"",
")",
"else",
":",
"initial_centers",
"=",
"_tc",
".",
"SFrame",
"(",
")",
"opts",
"[",
"'initial_centers'",
"]",
"=",
"initial_centers",
"## Validate the batch size and determine the training method.",
"if",
"batch_size",
"is",
"None",
":",
"opts",
"[",
"'method'",
"]",
"=",
"'elkan'",
"opts",
"[",
"'batch_size'",
"]",
"=",
"dataset",
".",
"num_rows",
"(",
")",
"else",
":",
"opts",
"[",
"'method'",
"]",
"=",
"'minibatch'",
"opts",
"[",
"'batch_size'",
"]",
"=",
"batch_size",
"## Create and return the model",
"with",
"_QuietProgress",
"(",
"verbose",
")",
":",
"params",
"=",
"_tc",
".",
"extensions",
".",
"_kmeans",
".",
"train",
"(",
"opts",
")",
"return",
"KmeansModel",
"(",
"params",
"[",
"'model'",
"]",
")"
] | Create a k-means clustering model. The KmeansModel object contains the
computed cluster centers and the cluster assignment for each instance in
the input 'dataset'.
Given a number of clusters, k-means iteratively chooses the best cluster
centers and assigns nearby points to the best cluster. If no points change
cluster membership between iterations, the algorithm terminates.
Parameters
----------
dataset : SFrame
Each row in the SFrame is an observation.
num_clusters : int
Number of clusters. This is the 'k' in k-means.
features : list[str], optional
Names of feature columns to use in computing distances between
observations and cluster centers. 'None' (the default) indicates that
all columns should be used as features. Columns may be of the following
types:
- *Numeric*: values of numeric type integer or float.
- *Array*: list of numeric (int or float) values. Each list element
is treated as a distinct feature in the model.
- *Dict*: dictionary of keys mapped to numeric values. Each unique key
is treated as a distinct feature in the model.
Note that columns of type *list* are not supported. Convert them to
array columns if all entries in the list are of numeric types.
label : str, optional
Name of the column to use as row labels in the Kmeans output. The
values in this column must be integers or strings. If not specified,
row numbers are used by default.
initial_centers : SFrame, optional
Initial centers to use when starting the K-means algorithm. If
specified, this parameter overrides the *num_clusters* parameter. The
'initial_centers' SFrame must contain the same features used in the
input 'dataset'.
If not specified (the default), initial centers are chosen
intelligently with the K-means++ algorithm.
max_iterations : int, optional
The maximum number of iterations to run. Prints a warning if the
algorithm does not converge after max_iterations iterations. If set to
0, the model returns clusters defined by the initial centers and
assignments to those centers.
batch_size : int, optional
Number of randomly-chosen data points to use in each iteration. If
'None' (the default) or greater than the number of rows in 'dataset',
then this parameter is ignored: all rows of `dataset` are used in each
iteration and model training terminates once point assignments stop
changing or `max_iterations` is reached.
verbose : bool, optional
If True, print model training progress to the screen.
Returns
-------
out : KmeansModel
A Model object containing a cluster id for each vertex, and the centers
of the clusters.
See Also
--------
KmeansModel
Notes
-----
- Integer features in the 'dataset' or 'initial_centers' inputs are
converted internally to float type, and the corresponding features in the
output centers are float-typed.
- It can be important for the K-means model to standardize the features so
they have the same scale. This function does *not* standardize
automatically.
References
----------
- `Wikipedia - k-means clustering
<http://en.wikipedia.org/wiki/K-means_clustering>`_
- Artuhur, D. and Vassilvitskii, S. (2007) `k-means++: The Advantages of
Careful Seeding <http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf>`_. In
Proceedings of the Eighteenth Annual ACM-SIAM Symposium on Discrete
Algorithms. pp. 1027-1035.
- Elkan, C. (2003) `Using the triangle inequality to accelerate k-means
<http://www.aaai.org/Papers/ICML/2003/ICML03-022.pdf>`_. In Proceedings
of the Twentieth International Conference on Machine Learning, Volume 3,
pp. 147-153.
- Sculley, D. (2010) `Web Scale K-Means Clustering
<http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf>`_. In
Proceedings of the 19th International Conference on World Wide Web. pp.
1177-1178
Examples
--------
>>> sf = turicreate.SFrame({
... 'x1': [0.6777, -9.391, 7.0385, 2.2657, 7.7864, -10.16, -8.162,
... 8.8817, -9.525, -9.153, 2.0860, 7.6619, 6.5511, 2.7020],
... 'x2': [5.6110, 8.5139, 5.3913, 5.4743, 8.3606, 7.8843, 2.7305,
... 5.1679, 6.7231, 3.7051, 1.7682, 7.4608, 3.1270, 6.5624]})
...
>>> model = turicreate.kmeans.create(sf, num_clusters=3) | [
"Create",
"a",
"k",
"-",
"means",
"clustering",
"model",
".",
"The",
"KmeansModel",
"object",
"contains",
"the",
"computed",
"cluster",
"centers",
"and",
"the",
"cluster",
"assignment",
"for",
"each",
"instance",
"in",
"the",
"input",
"dataset",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/clustering/kmeans.py#L410-L602 |
29,493 | apple/turicreate | src/unity/python/turicreate/toolkits/clustering/kmeans.py | KmeansModel.predict | def predict(self, dataset, output_type='cluster_id', verbose=True):
"""
Return predicted cluster label for instances in the new 'dataset'.
K-means predictions are made by assigning each new instance to the
closest cluster center.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include the features used for
model training; additional columns are ignored.
output_type : {'cluster_id', 'distance'}, optional
Form of the prediction. 'cluster_id' (the default) returns the
cluster label assigned to each input instance, while 'distance'
returns the Euclidean distance between the instance and its
assigned cluster's center.
verbose : bool, optional
If True, print progress updates to the screen.
Returns
-------
out : SArray
Model predictions. Depending on the specified `output_type`, either
the assigned cluster label or the distance of each point to its
closest cluster center. The order of the predictions is the same as
order of the input data rows.
See Also
--------
create
Examples
--------
>>> sf = turicreate.SFrame({
... 'x1': [0.6777, -9.391, 7.0385, 2.2657, 7.7864, -10.16, -8.162,
... 8.8817, -9.525, -9.153, 2.0860, 7.6619, 6.5511, 2.7020],
... 'x2': [5.6110, 8.5139, 5.3913, 5.4743, 8.3606, 7.8843, 2.7305,
... 5.1679, 6.7231, 3.7051, 1.7682, 7.4608, 3.1270, 6.5624]})
...
>>> model = turicreate.kmeans.create(sf, num_clusters=3)
...
>>> sf_new = turicreate.SFrame({'x1': [-5.6584, -1.0167, -9.6181],
... 'x2': [-6.3803, -3.7937, -1.1022]})
>>> clusters = model.predict(sf_new, output_type='cluster_id')
>>> print clusters
[1, 0, 1]
"""
## Validate the input dataset.
_tkutl._raise_error_if_not_sframe(dataset, "dataset")
_tkutl._raise_error_if_sframe_empty(dataset, "dataset")
## Validate the output type.
if not isinstance(output_type, str):
raise TypeError("The 'output_type' parameter must be a string.")
if not output_type in ('cluster_id', 'distance'):
raise ValueError("The 'output_type' parameter must be either " +
"'cluster_label' or 'distance'.")
## Get model features.
ref_features = self.features
sf_features = _tkutl._toolkits_select_columns(dataset, ref_features)
## Compute predictions.
opts = {'model': self.__proxy__,
'model_name': self.__name__,
'dataset': sf_features}
with _QuietProgress(verbose):
result = _tc.extensions._kmeans.predict(opts)
sf_result = result['predictions']
if output_type == 'distance':
return sf_result['distance']
else:
return sf_result['cluster_id'] | python | def predict(self, dataset, output_type='cluster_id', verbose=True):
"""
Return predicted cluster label for instances in the new 'dataset'.
K-means predictions are made by assigning each new instance to the
closest cluster center.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include the features used for
model training; additional columns are ignored.
output_type : {'cluster_id', 'distance'}, optional
Form of the prediction. 'cluster_id' (the default) returns the
cluster label assigned to each input instance, while 'distance'
returns the Euclidean distance between the instance and its
assigned cluster's center.
verbose : bool, optional
If True, print progress updates to the screen.
Returns
-------
out : SArray
Model predictions. Depending on the specified `output_type`, either
the assigned cluster label or the distance of each point to its
closest cluster center. The order of the predictions is the same as
order of the input data rows.
See Also
--------
create
Examples
--------
>>> sf = turicreate.SFrame({
... 'x1': [0.6777, -9.391, 7.0385, 2.2657, 7.7864, -10.16, -8.162,
... 8.8817, -9.525, -9.153, 2.0860, 7.6619, 6.5511, 2.7020],
... 'x2': [5.6110, 8.5139, 5.3913, 5.4743, 8.3606, 7.8843, 2.7305,
... 5.1679, 6.7231, 3.7051, 1.7682, 7.4608, 3.1270, 6.5624]})
...
>>> model = turicreate.kmeans.create(sf, num_clusters=3)
...
>>> sf_new = turicreate.SFrame({'x1': [-5.6584, -1.0167, -9.6181],
... 'x2': [-6.3803, -3.7937, -1.1022]})
>>> clusters = model.predict(sf_new, output_type='cluster_id')
>>> print clusters
[1, 0, 1]
"""
## Validate the input dataset.
_tkutl._raise_error_if_not_sframe(dataset, "dataset")
_tkutl._raise_error_if_sframe_empty(dataset, "dataset")
## Validate the output type.
if not isinstance(output_type, str):
raise TypeError("The 'output_type' parameter must be a string.")
if not output_type in ('cluster_id', 'distance'):
raise ValueError("The 'output_type' parameter must be either " +
"'cluster_label' or 'distance'.")
## Get model features.
ref_features = self.features
sf_features = _tkutl._toolkits_select_columns(dataset, ref_features)
## Compute predictions.
opts = {'model': self.__proxy__,
'model_name': self.__name__,
'dataset': sf_features}
with _QuietProgress(verbose):
result = _tc.extensions._kmeans.predict(opts)
sf_result = result['predictions']
if output_type == 'distance':
return sf_result['distance']
else:
return sf_result['cluster_id'] | [
"def",
"predict",
"(",
"self",
",",
"dataset",
",",
"output_type",
"=",
"'cluster_id'",
",",
"verbose",
"=",
"True",
")",
":",
"## Validate the input dataset.",
"_tkutl",
".",
"_raise_error_if_not_sframe",
"(",
"dataset",
",",
"\"dataset\"",
")",
"_tkutl",
".",
"_raise_error_if_sframe_empty",
"(",
"dataset",
",",
"\"dataset\"",
")",
"## Validate the output type.",
"if",
"not",
"isinstance",
"(",
"output_type",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"The 'output_type' parameter must be a string.\"",
")",
"if",
"not",
"output_type",
"in",
"(",
"'cluster_id'",
",",
"'distance'",
")",
":",
"raise",
"ValueError",
"(",
"\"The 'output_type' parameter must be either \"",
"+",
"\"'cluster_label' or 'distance'.\"",
")",
"## Get model features.",
"ref_features",
"=",
"self",
".",
"features",
"sf_features",
"=",
"_tkutl",
".",
"_toolkits_select_columns",
"(",
"dataset",
",",
"ref_features",
")",
"## Compute predictions.",
"opts",
"=",
"{",
"'model'",
":",
"self",
".",
"__proxy__",
",",
"'model_name'",
":",
"self",
".",
"__name__",
",",
"'dataset'",
":",
"sf_features",
"}",
"with",
"_QuietProgress",
"(",
"verbose",
")",
":",
"result",
"=",
"_tc",
".",
"extensions",
".",
"_kmeans",
".",
"predict",
"(",
"opts",
")",
"sf_result",
"=",
"result",
"[",
"'predictions'",
"]",
"if",
"output_type",
"==",
"'distance'",
":",
"return",
"sf_result",
"[",
"'distance'",
"]",
"else",
":",
"return",
"sf_result",
"[",
"'cluster_id'",
"]"
] | Return predicted cluster label for instances in the new 'dataset'.
K-means predictions are made by assigning each new instance to the
closest cluster center.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include the features used for
model training; additional columns are ignored.
output_type : {'cluster_id', 'distance'}, optional
Form of the prediction. 'cluster_id' (the default) returns the
cluster label assigned to each input instance, while 'distance'
returns the Euclidean distance between the instance and its
assigned cluster's center.
verbose : bool, optional
If True, print progress updates to the screen.
Returns
-------
out : SArray
Model predictions. Depending on the specified `output_type`, either
the assigned cluster label or the distance of each point to its
closest cluster center. The order of the predictions is the same as
order of the input data rows.
See Also
--------
create
Examples
--------
>>> sf = turicreate.SFrame({
... 'x1': [0.6777, -9.391, 7.0385, 2.2657, 7.7864, -10.16, -8.162,
... 8.8817, -9.525, -9.153, 2.0860, 7.6619, 6.5511, 2.7020],
... 'x2': [5.6110, 8.5139, 5.3913, 5.4743, 8.3606, 7.8843, 2.7305,
... 5.1679, 6.7231, 3.7051, 1.7682, 7.4608, 3.1270, 6.5624]})
...
>>> model = turicreate.kmeans.create(sf, num_clusters=3)
...
>>> sf_new = turicreate.SFrame({'x1': [-5.6584, -1.0167, -9.6181],
... 'x2': [-6.3803, -3.7937, -1.1022]})
>>> clusters = model.predict(sf_new, output_type='cluster_id')
>>> print clusters
[1, 0, 1] | [
"Return",
"predicted",
"cluster",
"label",
"for",
"instances",
"in",
"the",
"new",
"dataset",
".",
"K",
"-",
"means",
"predictions",
"are",
"made",
"by",
"assigning",
"each",
"new",
"instance",
"to",
"the",
"closest",
"cluster",
"center",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/clustering/kmeans.py#L208-L287 |
29,494 | apple/turicreate | src/unity/python/turicreate/toolkits/clustering/kmeans.py | KmeansModel._get | def _get(self, field):
"""
Return the value of a given field.
+-----------------------+----------------------------------------------+
| Field | Description |
+=======================+==============================================+
| batch_size | Number of randomly chosen examples to use in |
| | each training iteration. |
+-----------------------+----------------------------------------------+
| cluster_id | Cluster assignment for each data point and |
| | Euclidean distance to the cluster center |
+-----------------------+----------------------------------------------+
| cluster_info | Cluster centers, sum of squared Euclidean |
| | distances from each cluster member to the |
| | assigned center, and the number of data |
| | points belonging to the cluster |
+-----------------------+----------------------------------------------+
| features | Names of feature columns |
+-----------------------+----------------------------------------------+
| max_iterations | Maximum number of iterations to perform |
+-----------------------+----------------------------------------------+
| method | Algorithm used to train the model. |
+-----------------------+----------------------------------------------+
| num_clusters | Number of clusters |
+-----------------------+----------------------------------------------+
| num_examples | Number of examples in the dataset |
+-----------------------+----------------------------------------------+
| num_features | Number of feature columns used |
+-----------------------+----------------------------------------------+
| num_unpacked_features | Number of features unpacked from the |
| | feature columns |
+-----------------------+----------------------------------------------+
| training_iterations | Total number of iterations performed |
+-----------------------+----------------------------------------------+
| training_time | Total time taken to cluster the data |
+-----------------------+----------------------------------------------+
| unpacked_features | Names of features unpacked from the |
| | feature columns |
+-----------------------+----------------------------------------------+
Parameters
----------
field : str
The name of the field to query.
Returns
-------
out
Value of the requested field
"""
opts = {'model': self.__proxy__,
'model_name': self.__name__,
'field': field}
response = _tc.extensions._kmeans.get_value(opts)
return response['value'] | python | def _get(self, field):
"""
Return the value of a given field.
+-----------------------+----------------------------------------------+
| Field | Description |
+=======================+==============================================+
| batch_size | Number of randomly chosen examples to use in |
| | each training iteration. |
+-----------------------+----------------------------------------------+
| cluster_id | Cluster assignment for each data point and |
| | Euclidean distance to the cluster center |
+-----------------------+----------------------------------------------+
| cluster_info | Cluster centers, sum of squared Euclidean |
| | distances from each cluster member to the |
| | assigned center, and the number of data |
| | points belonging to the cluster |
+-----------------------+----------------------------------------------+
| features | Names of feature columns |
+-----------------------+----------------------------------------------+
| max_iterations | Maximum number of iterations to perform |
+-----------------------+----------------------------------------------+
| method | Algorithm used to train the model. |
+-----------------------+----------------------------------------------+
| num_clusters | Number of clusters |
+-----------------------+----------------------------------------------+
| num_examples | Number of examples in the dataset |
+-----------------------+----------------------------------------------+
| num_features | Number of feature columns used |
+-----------------------+----------------------------------------------+
| num_unpacked_features | Number of features unpacked from the |
| | feature columns |
+-----------------------+----------------------------------------------+
| training_iterations | Total number of iterations performed |
+-----------------------+----------------------------------------------+
| training_time | Total time taken to cluster the data |
+-----------------------+----------------------------------------------+
| unpacked_features | Names of features unpacked from the |
| | feature columns |
+-----------------------+----------------------------------------------+
Parameters
----------
field : str
The name of the field to query.
Returns
-------
out
Value of the requested field
"""
opts = {'model': self.__proxy__,
'model_name': self.__name__,
'field': field}
response = _tc.extensions._kmeans.get_value(opts)
return response['value'] | [
"def",
"_get",
"(",
"self",
",",
"field",
")",
":",
"opts",
"=",
"{",
"'model'",
":",
"self",
".",
"__proxy__",
",",
"'model_name'",
":",
"self",
".",
"__name__",
",",
"'field'",
":",
"field",
"}",
"response",
"=",
"_tc",
".",
"extensions",
".",
"_kmeans",
".",
"get_value",
"(",
"opts",
")",
"return",
"response",
"[",
"'value'",
"]"
] | Return the value of a given field.
+-----------------------+----------------------------------------------+
| Field | Description |
+=======================+==============================================+
| batch_size | Number of randomly chosen examples to use in |
| | each training iteration. |
+-----------------------+----------------------------------------------+
| cluster_id | Cluster assignment for each data point and |
| | Euclidean distance to the cluster center |
+-----------------------+----------------------------------------------+
| cluster_info | Cluster centers, sum of squared Euclidean |
| | distances from each cluster member to the |
| | assigned center, and the number of data |
| | points belonging to the cluster |
+-----------------------+----------------------------------------------+
| features | Names of feature columns |
+-----------------------+----------------------------------------------+
| max_iterations | Maximum number of iterations to perform |
+-----------------------+----------------------------------------------+
| method | Algorithm used to train the model. |
+-----------------------+----------------------------------------------+
| num_clusters | Number of clusters |
+-----------------------+----------------------------------------------+
| num_examples | Number of examples in the dataset |
+-----------------------+----------------------------------------------+
| num_features | Number of feature columns used |
+-----------------------+----------------------------------------------+
| num_unpacked_features | Number of features unpacked from the |
| | feature columns |
+-----------------------+----------------------------------------------+
| training_iterations | Total number of iterations performed |
+-----------------------+----------------------------------------------+
| training_time | Total time taken to cluster the data |
+-----------------------+----------------------------------------------+
| unpacked_features | Names of features unpacked from the |
| | feature columns |
+-----------------------+----------------------------------------------+
Parameters
----------
field : str
The name of the field to query.
Returns
-------
out
Value of the requested field | [
"Return",
"the",
"value",
"of",
"a",
"given",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/clustering/kmeans.py#L289-L345 |
29,495 | apple/turicreate | src/unity/python/turicreate/toolkits/text_analytics/_util.py | count_words | def count_words(text, to_lower=True, delimiters=DEFAULT_DELIMITERS):
"""
If `text` is an SArray of strings or an SArray of lists of strings, the
occurances of word are counted for each row in the SArray.
If `text` is an SArray of dictionaries, the keys are tokenized and the
values are the counts. Counts for the same word, in the same row, are
added together.
This output is commonly known as the "bag-of-words" representation of text
data.
Parameters
----------
text : SArray[str | dict | list]
SArray of type: string, dict or list.
to_lower : bool, optional
If True, all strings are converted to lower case before counting.
delimiters : list[str], None, optional
Input strings are tokenized using `delimiters` characters in this list.
Each entry in this list must contain a single character. If set to
`None`, then a Penn treebank-style tokenization is used, which contains
smart handling of punctuations.
Returns
-------
out : SArray[dict]
An SArray with the same length as the`text` input. For each row, the keys
of the dictionary are the words and the values are the corresponding counts.
See Also
--------
count_ngrams, tf_idf, tokenize,
References
----------
- `Bag of words model <http://en.wikipedia.org/wiki/Bag-of-words_model>`_
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
# Create input data
>>> sa = turicreate.SArray(["The quick brown fox jumps.",
"Word word WORD, word!!!word"])
# Run count_words
>>> turicreate.text_analytics.count_words(sa)
dtype: dict
Rows: 2
[{'quick': 1, 'brown': 1, 'the': 1, 'fox': 1, 'jumps.': 1},
{'word,': 5}]
# Run count_words with Penn treebank style tokenization to handle
# punctuations
>>> turicreate.text_analytics.count_words(sa, delimiters=None)
dtype: dict
Rows: 2
[{'brown': 1, 'jumps': 1, 'fox': 1, '.': 1, 'quick': 1, 'the': 1},
{'word': 3, 'word!!!word': 1, ',': 1}]
# Run count_words with dictionary input
>>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5},
{'a dog': 0, 'a dog cat': 5}])
>>> turicreate.text_analytics.count_words(sa)
dtype: dict
Rows: 2
[{'bob': 1.5, 'alice': 1.5}, {'a': 5, 'dog': 5, 'cat': 5}]
# Run count_words with list input
>>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']])
>>> turicreate.text_analytics.count_words(sa)
dtype: dict
Rows: 2
[{'bar': 1, 'bah': 1, 'one': 1}, {'a': 2, 'dog': 2, 'cat': 1}]
"""
_raise_error_if_not_sarray(text, "text")
## Compute word counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.WordCounter(features='docs',
to_lower=to_lower,
delimiters=delimiters,
output_column_prefix=None)
output_sf = fe.fit_transform(sf)
return output_sf['docs'] | python | def count_words(text, to_lower=True, delimiters=DEFAULT_DELIMITERS):
"""
If `text` is an SArray of strings or an SArray of lists of strings, the
occurances of word are counted for each row in the SArray.
If `text` is an SArray of dictionaries, the keys are tokenized and the
values are the counts. Counts for the same word, in the same row, are
added together.
This output is commonly known as the "bag-of-words" representation of text
data.
Parameters
----------
text : SArray[str | dict | list]
SArray of type: string, dict or list.
to_lower : bool, optional
If True, all strings are converted to lower case before counting.
delimiters : list[str], None, optional
Input strings are tokenized using `delimiters` characters in this list.
Each entry in this list must contain a single character. If set to
`None`, then a Penn treebank-style tokenization is used, which contains
smart handling of punctuations.
Returns
-------
out : SArray[dict]
An SArray with the same length as the`text` input. For each row, the keys
of the dictionary are the words and the values are the corresponding counts.
See Also
--------
count_ngrams, tf_idf, tokenize,
References
----------
- `Bag of words model <http://en.wikipedia.org/wiki/Bag-of-words_model>`_
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
# Create input data
>>> sa = turicreate.SArray(["The quick brown fox jumps.",
"Word word WORD, word!!!word"])
# Run count_words
>>> turicreate.text_analytics.count_words(sa)
dtype: dict
Rows: 2
[{'quick': 1, 'brown': 1, 'the': 1, 'fox': 1, 'jumps.': 1},
{'word,': 5}]
# Run count_words with Penn treebank style tokenization to handle
# punctuations
>>> turicreate.text_analytics.count_words(sa, delimiters=None)
dtype: dict
Rows: 2
[{'brown': 1, 'jumps': 1, 'fox': 1, '.': 1, 'quick': 1, 'the': 1},
{'word': 3, 'word!!!word': 1, ',': 1}]
# Run count_words with dictionary input
>>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5},
{'a dog': 0, 'a dog cat': 5}])
>>> turicreate.text_analytics.count_words(sa)
dtype: dict
Rows: 2
[{'bob': 1.5, 'alice': 1.5}, {'a': 5, 'dog': 5, 'cat': 5}]
# Run count_words with list input
>>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']])
>>> turicreate.text_analytics.count_words(sa)
dtype: dict
Rows: 2
[{'bar': 1, 'bah': 1, 'one': 1}, {'a': 2, 'dog': 2, 'cat': 1}]
"""
_raise_error_if_not_sarray(text, "text")
## Compute word counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.WordCounter(features='docs',
to_lower=to_lower,
delimiters=delimiters,
output_column_prefix=None)
output_sf = fe.fit_transform(sf)
return output_sf['docs'] | [
"def",
"count_words",
"(",
"text",
",",
"to_lower",
"=",
"True",
",",
"delimiters",
"=",
"DEFAULT_DELIMITERS",
")",
":",
"_raise_error_if_not_sarray",
"(",
"text",
",",
"\"text\"",
")",
"## Compute word counts",
"sf",
"=",
"_turicreate",
".",
"SFrame",
"(",
"{",
"'docs'",
":",
"text",
"}",
")",
"fe",
"=",
"_feature_engineering",
".",
"WordCounter",
"(",
"features",
"=",
"'docs'",
",",
"to_lower",
"=",
"to_lower",
",",
"delimiters",
"=",
"delimiters",
",",
"output_column_prefix",
"=",
"None",
")",
"output_sf",
"=",
"fe",
".",
"fit_transform",
"(",
"sf",
")",
"return",
"output_sf",
"[",
"'docs'",
"]"
] | If `text` is an SArray of strings or an SArray of lists of strings, the
occurances of word are counted for each row in the SArray.
If `text` is an SArray of dictionaries, the keys are tokenized and the
values are the counts. Counts for the same word, in the same row, are
added together.
This output is commonly known as the "bag-of-words" representation of text
data.
Parameters
----------
text : SArray[str | dict | list]
SArray of type: string, dict or list.
to_lower : bool, optional
If True, all strings are converted to lower case before counting.
delimiters : list[str], None, optional
Input strings are tokenized using `delimiters` characters in this list.
Each entry in this list must contain a single character. If set to
`None`, then a Penn treebank-style tokenization is used, which contains
smart handling of punctuations.
Returns
-------
out : SArray[dict]
An SArray with the same length as the`text` input. For each row, the keys
of the dictionary are the words and the values are the corresponding counts.
See Also
--------
count_ngrams, tf_idf, tokenize,
References
----------
- `Bag of words model <http://en.wikipedia.org/wiki/Bag-of-words_model>`_
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
# Create input data
>>> sa = turicreate.SArray(["The quick brown fox jumps.",
"Word word WORD, word!!!word"])
# Run count_words
>>> turicreate.text_analytics.count_words(sa)
dtype: dict
Rows: 2
[{'quick': 1, 'brown': 1, 'the': 1, 'fox': 1, 'jumps.': 1},
{'word,': 5}]
# Run count_words with Penn treebank style tokenization to handle
# punctuations
>>> turicreate.text_analytics.count_words(sa, delimiters=None)
dtype: dict
Rows: 2
[{'brown': 1, 'jumps': 1, 'fox': 1, '.': 1, 'quick': 1, 'the': 1},
{'word': 3, 'word!!!word': 1, ',': 1}]
# Run count_words with dictionary input
>>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5},
{'a dog': 0, 'a dog cat': 5}])
>>> turicreate.text_analytics.count_words(sa)
dtype: dict
Rows: 2
[{'bob': 1.5, 'alice': 1.5}, {'a': 5, 'dog': 5, 'cat': 5}]
# Run count_words with list input
>>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']])
>>> turicreate.text_analytics.count_words(sa)
dtype: dict
Rows: 2
[{'bar': 1, 'bah': 1, 'one': 1}, {'a': 2, 'dog': 2, 'cat': 1}] | [
"If",
"text",
"is",
"an",
"SArray",
"of",
"strings",
"or",
"an",
"SArray",
"of",
"lists",
"of",
"strings",
"the",
"occurances",
"of",
"word",
"are",
"counted",
"for",
"each",
"row",
"in",
"the",
"SArray",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L24-L117 |
29,496 | apple/turicreate | src/unity/python/turicreate/toolkits/text_analytics/_util.py | count_ngrams | def count_ngrams(text, n=2, method="word", to_lower=True,
delimiters=DEFAULT_DELIMITERS,
ignore_punct=True, ignore_space=True):
"""
Return an SArray of ``dict`` type where each element contains the count
for each of the n-grams that appear in the corresponding input element.
The n-grams can be specified to be either character n-grams or word
n-grams. The input SArray could contain strings, dicts with string keys
and numeric values, or lists of strings.
Parameters
----------
Text : SArray[str | dict | list]
Input text data.
n : int, optional
The number of words in each n-gram. An ``n`` value of 1 returns word
counts.
method : {'word', 'character'}, optional
If "word", the function performs a count of word n-grams. If
"character", does a character n-gram count.
to_lower : bool, optional
If True, all words are converted to lower case before counting.
delimiters : list[str], None, optional
If method is "word", input strings are tokenized using `delimiters`
characters in this list. Each entry in this list must contain a single
character. If set to `None`, then a Penn treebank-style tokenization is
used, which contains smart handling of punctuations. If method is
"character," this option is ignored.
ignore_punct : bool, optional
If method is "character", indicates if *punctuations* between words are
counted as part of the n-gram. For instance, with the input SArray
element of "fun.games", if this parameter is set to False one
tri-gram would be 'n.g'. If ``ignore_punct`` is set to True, there
would be no such tri-gram (there would still be 'nga'). This
parameter has no effect if the method is set to "word".
ignore_space : bool, optional
If method is "character", indicates if *spaces* between words are
counted as part of the n-gram. For instance, with the input SArray
element of "fun games", if this parameter is set to False one
tri-gram would be 'n g'. If ``ignore_space`` is set to True, there
would be no such tri-gram (there would still be 'nga'). This
parameter has no effect if the method is set to "word".
Returns
-------
out : SArray[dict]
An SArray of dictionary type, where each key is the n-gram string
and each value is its count.
See Also
--------
count_words, tokenize,
Notes
-----
- Ignoring case (with ``to_lower``) involves a full string copy of the
SArray data. To increase speed for large documents, set ``to_lower`` to
False.
- Punctuation and spaces are both delimiters by default when counting
word n-grams. When counting character n-grams, one may choose to ignore
punctuations, spaces, neither, or both.
References
----------
- `N-gram wikipedia article <http://en.wikipedia.org/wiki/N-gram>`_
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
# Counting word n-grams:
>>> sa = turicreate.SArray(['I like big dogs. I LIKE BIG DOGS.'])
>>> turicreate.text_analytics.count_ngrams(sa, 3)
dtype: dict
Rows: 1
[{'big dogs i': 1, 'like big dogs': 2, 'dogs i like': 1, 'i like big': 2}]
# Counting character n-grams:
>>> sa = turicreate.SArray(['Fun. Is. Fun'])
>>> turicreate.text_analytics.count_ngrams(sa, 3, "character")
dtype: dict
Rows: 1
{'fun': 2, 'nis': 1, 'sfu': 1, 'isf': 1, 'uni': 1}]
# Run count_ngrams with dictionary input
>>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5},
{'a dog': 0, 'a dog cat': 5}])
>>> turicreate.text_analytics.count_ngrams(sa)
dtype: dict
Rows: 2
[{'bob alice': 0.5, 'alice bob': 1}, {'dog cat': 5, 'a dog': 5}]
# Run count_ngrams with list input
>>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']])
>>> turicreate.text_analytics.count_ngrams(sa)
dtype: dict
Rows: 2
[{'bar bah': 1}, {'dog cat': 1, 'a dog': 2}]
"""
_raise_error_if_not_sarray(text, "text")
# Compute ngrams counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.NGramCounter(features='docs',
n=n,
method=method,
to_lower=to_lower,
delimiters=delimiters,
ignore_punct=ignore_punct,
ignore_space=ignore_space,
output_column_prefix=None)
output_sf = fe.fit_transform(sf)
return output_sf['docs'] | python | def count_ngrams(text, n=2, method="word", to_lower=True,
delimiters=DEFAULT_DELIMITERS,
ignore_punct=True, ignore_space=True):
"""
Return an SArray of ``dict`` type where each element contains the count
for each of the n-grams that appear in the corresponding input element.
The n-grams can be specified to be either character n-grams or word
n-grams. The input SArray could contain strings, dicts with string keys
and numeric values, or lists of strings.
Parameters
----------
Text : SArray[str | dict | list]
Input text data.
n : int, optional
The number of words in each n-gram. An ``n`` value of 1 returns word
counts.
method : {'word', 'character'}, optional
If "word", the function performs a count of word n-grams. If
"character", does a character n-gram count.
to_lower : bool, optional
If True, all words are converted to lower case before counting.
delimiters : list[str], None, optional
If method is "word", input strings are tokenized using `delimiters`
characters in this list. Each entry in this list must contain a single
character. If set to `None`, then a Penn treebank-style tokenization is
used, which contains smart handling of punctuations. If method is
"character," this option is ignored.
ignore_punct : bool, optional
If method is "character", indicates if *punctuations* between words are
counted as part of the n-gram. For instance, with the input SArray
element of "fun.games", if this parameter is set to False one
tri-gram would be 'n.g'. If ``ignore_punct`` is set to True, there
would be no such tri-gram (there would still be 'nga'). This
parameter has no effect if the method is set to "word".
ignore_space : bool, optional
If method is "character", indicates if *spaces* between words are
counted as part of the n-gram. For instance, with the input SArray
element of "fun games", if this parameter is set to False one
tri-gram would be 'n g'. If ``ignore_space`` is set to True, there
would be no such tri-gram (there would still be 'nga'). This
parameter has no effect if the method is set to "word".
Returns
-------
out : SArray[dict]
An SArray of dictionary type, where each key is the n-gram string
and each value is its count.
See Also
--------
count_words, tokenize,
Notes
-----
- Ignoring case (with ``to_lower``) involves a full string copy of the
SArray data. To increase speed for large documents, set ``to_lower`` to
False.
- Punctuation and spaces are both delimiters by default when counting
word n-grams. When counting character n-grams, one may choose to ignore
punctuations, spaces, neither, or both.
References
----------
- `N-gram wikipedia article <http://en.wikipedia.org/wiki/N-gram>`_
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
# Counting word n-grams:
>>> sa = turicreate.SArray(['I like big dogs. I LIKE BIG DOGS.'])
>>> turicreate.text_analytics.count_ngrams(sa, 3)
dtype: dict
Rows: 1
[{'big dogs i': 1, 'like big dogs': 2, 'dogs i like': 1, 'i like big': 2}]
# Counting character n-grams:
>>> sa = turicreate.SArray(['Fun. Is. Fun'])
>>> turicreate.text_analytics.count_ngrams(sa, 3, "character")
dtype: dict
Rows: 1
{'fun': 2, 'nis': 1, 'sfu': 1, 'isf': 1, 'uni': 1}]
# Run count_ngrams with dictionary input
>>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5},
{'a dog': 0, 'a dog cat': 5}])
>>> turicreate.text_analytics.count_ngrams(sa)
dtype: dict
Rows: 2
[{'bob alice': 0.5, 'alice bob': 1}, {'dog cat': 5, 'a dog': 5}]
# Run count_ngrams with list input
>>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']])
>>> turicreate.text_analytics.count_ngrams(sa)
dtype: dict
Rows: 2
[{'bar bah': 1}, {'dog cat': 1, 'a dog': 2}]
"""
_raise_error_if_not_sarray(text, "text")
# Compute ngrams counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.NGramCounter(features='docs',
n=n,
method=method,
to_lower=to_lower,
delimiters=delimiters,
ignore_punct=ignore_punct,
ignore_space=ignore_space,
output_column_prefix=None)
output_sf = fe.fit_transform(sf)
return output_sf['docs'] | [
"def",
"count_ngrams",
"(",
"text",
",",
"n",
"=",
"2",
",",
"method",
"=",
"\"word\"",
",",
"to_lower",
"=",
"True",
",",
"delimiters",
"=",
"DEFAULT_DELIMITERS",
",",
"ignore_punct",
"=",
"True",
",",
"ignore_space",
"=",
"True",
")",
":",
"_raise_error_if_not_sarray",
"(",
"text",
",",
"\"text\"",
")",
"# Compute ngrams counts",
"sf",
"=",
"_turicreate",
".",
"SFrame",
"(",
"{",
"'docs'",
":",
"text",
"}",
")",
"fe",
"=",
"_feature_engineering",
".",
"NGramCounter",
"(",
"features",
"=",
"'docs'",
",",
"n",
"=",
"n",
",",
"method",
"=",
"method",
",",
"to_lower",
"=",
"to_lower",
",",
"delimiters",
"=",
"delimiters",
",",
"ignore_punct",
"=",
"ignore_punct",
",",
"ignore_space",
"=",
"ignore_space",
",",
"output_column_prefix",
"=",
"None",
")",
"output_sf",
"=",
"fe",
".",
"fit_transform",
"(",
"sf",
")",
"return",
"output_sf",
"[",
"'docs'",
"]"
] | Return an SArray of ``dict`` type where each element contains the count
for each of the n-grams that appear in the corresponding input element.
The n-grams can be specified to be either character n-grams or word
n-grams. The input SArray could contain strings, dicts with string keys
and numeric values, or lists of strings.
Parameters
----------
Text : SArray[str | dict | list]
Input text data.
n : int, optional
The number of words in each n-gram. An ``n`` value of 1 returns word
counts.
method : {'word', 'character'}, optional
If "word", the function performs a count of word n-grams. If
"character", does a character n-gram count.
to_lower : bool, optional
If True, all words are converted to lower case before counting.
delimiters : list[str], None, optional
If method is "word", input strings are tokenized using `delimiters`
characters in this list. Each entry in this list must contain a single
character. If set to `None`, then a Penn treebank-style tokenization is
used, which contains smart handling of punctuations. If method is
"character," this option is ignored.
ignore_punct : bool, optional
If method is "character", indicates if *punctuations* between words are
counted as part of the n-gram. For instance, with the input SArray
element of "fun.games", if this parameter is set to False one
tri-gram would be 'n.g'. If ``ignore_punct`` is set to True, there
would be no such tri-gram (there would still be 'nga'). This
parameter has no effect if the method is set to "word".
ignore_space : bool, optional
If method is "character", indicates if *spaces* between words are
counted as part of the n-gram. For instance, with the input SArray
element of "fun games", if this parameter is set to False one
tri-gram would be 'n g'. If ``ignore_space`` is set to True, there
would be no such tri-gram (there would still be 'nga'). This
parameter has no effect if the method is set to "word".
Returns
-------
out : SArray[dict]
An SArray of dictionary type, where each key is the n-gram string
and each value is its count.
See Also
--------
count_words, tokenize,
Notes
-----
- Ignoring case (with ``to_lower``) involves a full string copy of the
SArray data. To increase speed for large documents, set ``to_lower`` to
False.
- Punctuation and spaces are both delimiters by default when counting
word n-grams. When counting character n-grams, one may choose to ignore
punctuations, spaces, neither, or both.
References
----------
- `N-gram wikipedia article <http://en.wikipedia.org/wiki/N-gram>`_
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
# Counting word n-grams:
>>> sa = turicreate.SArray(['I like big dogs. I LIKE BIG DOGS.'])
>>> turicreate.text_analytics.count_ngrams(sa, 3)
dtype: dict
Rows: 1
[{'big dogs i': 1, 'like big dogs': 2, 'dogs i like': 1, 'i like big': 2}]
# Counting character n-grams:
>>> sa = turicreate.SArray(['Fun. Is. Fun'])
>>> turicreate.text_analytics.count_ngrams(sa, 3, "character")
dtype: dict
Rows: 1
{'fun': 2, 'nis': 1, 'sfu': 1, 'isf': 1, 'uni': 1}]
# Run count_ngrams with dictionary input
>>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5},
{'a dog': 0, 'a dog cat': 5}])
>>> turicreate.text_analytics.count_ngrams(sa)
dtype: dict
Rows: 2
[{'bob alice': 0.5, 'alice bob': 1}, {'dog cat': 5, 'a dog': 5}]
# Run count_ngrams with list input
>>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']])
>>> turicreate.text_analytics.count_ngrams(sa)
dtype: dict
Rows: 2
[{'bar bah': 1}, {'dog cat': 1, 'a dog': 2}] | [
"Return",
"an",
"SArray",
"of",
"dict",
"type",
"where",
"each",
"element",
"contains",
"the",
"count",
"for",
"each",
"of",
"the",
"n",
"-",
"grams",
"that",
"appear",
"in",
"the",
"corresponding",
"input",
"element",
".",
"The",
"n",
"-",
"grams",
"can",
"be",
"specified",
"to",
"be",
"either",
"character",
"n",
"-",
"grams",
"or",
"word",
"n",
"-",
"grams",
".",
"The",
"input",
"SArray",
"could",
"contain",
"strings",
"dicts",
"with",
"string",
"keys",
"and",
"numeric",
"values",
"or",
"lists",
"of",
"strings",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L119-L243 |
29,497 | apple/turicreate | src/unity/python/turicreate/toolkits/text_analytics/_util.py | tf_idf | def tf_idf(text):
"""
Compute the TF-IDF scores for each word in each document. The collection
of documents must be in bag-of-words format.
.. math::
\mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w))
where :math:`tf(w, d)` is the number of times word :math:`w` appeared in
document :math:`d`, :math:`f(w)` is the number of documents word :math:`w`
appeared in, :math:`N` is the number of documents, and we use the
natural logarithm.
Parameters
----------
text : SArray[str | dict | list]
Input text data.
Returns
-------
out : SArray[dict]
The same document corpus where each score has been replaced by the
TF-IDF transformation.
See Also
--------
count_words, count_ngrams, tokenize,
References
----------
- `Wikipedia - TF-IDF <https://en.wikipedia.org/wiki/TFIDF>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
>>> docs = turicreate.SArray('https://static.turi.com/datasets/nips-text')
>>> docs_tfidf = turicreate.text_analytics.tf_idf(docs)
"""
_raise_error_if_not_sarray(text, "text")
if len(text) == 0:
return _turicreate.SArray()
dataset = _turicreate.SFrame({'docs': text})
scores = _feature_engineering.TFIDF('docs').fit_transform(dataset)
return scores['docs'] | python | def tf_idf(text):
"""
Compute the TF-IDF scores for each word in each document. The collection
of documents must be in bag-of-words format.
.. math::
\mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w))
where :math:`tf(w, d)` is the number of times word :math:`w` appeared in
document :math:`d`, :math:`f(w)` is the number of documents word :math:`w`
appeared in, :math:`N` is the number of documents, and we use the
natural logarithm.
Parameters
----------
text : SArray[str | dict | list]
Input text data.
Returns
-------
out : SArray[dict]
The same document corpus where each score has been replaced by the
TF-IDF transformation.
See Also
--------
count_words, count_ngrams, tokenize,
References
----------
- `Wikipedia - TF-IDF <https://en.wikipedia.org/wiki/TFIDF>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
>>> docs = turicreate.SArray('https://static.turi.com/datasets/nips-text')
>>> docs_tfidf = turicreate.text_analytics.tf_idf(docs)
"""
_raise_error_if_not_sarray(text, "text")
if len(text) == 0:
return _turicreate.SArray()
dataset = _turicreate.SFrame({'docs': text})
scores = _feature_engineering.TFIDF('docs').fit_transform(dataset)
return scores['docs'] | [
"def",
"tf_idf",
"(",
"text",
")",
":",
"_raise_error_if_not_sarray",
"(",
"text",
",",
"\"text\"",
")",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":",
"return",
"_turicreate",
".",
"SArray",
"(",
")",
"dataset",
"=",
"_turicreate",
".",
"SFrame",
"(",
"{",
"'docs'",
":",
"text",
"}",
")",
"scores",
"=",
"_feature_engineering",
".",
"TFIDF",
"(",
"'docs'",
")",
".",
"fit_transform",
"(",
"dataset",
")",
"return",
"scores",
"[",
"'docs'",
"]"
] | Compute the TF-IDF scores for each word in each document. The collection
of documents must be in bag-of-words format.
.. math::
\mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w))
where :math:`tf(w, d)` is the number of times word :math:`w` appeared in
document :math:`d`, :math:`f(w)` is the number of documents word :math:`w`
appeared in, :math:`N` is the number of documents, and we use the
natural logarithm.
Parameters
----------
text : SArray[str | dict | list]
Input text data.
Returns
-------
out : SArray[dict]
The same document corpus where each score has been replaced by the
TF-IDF transformation.
See Also
--------
count_words, count_ngrams, tokenize,
References
----------
- `Wikipedia - TF-IDF <https://en.wikipedia.org/wiki/TFIDF>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
>>> docs = turicreate.SArray('https://static.turi.com/datasets/nips-text')
>>> docs_tfidf = turicreate.text_analytics.tf_idf(docs) | [
"Compute",
"the",
"TF",
"-",
"IDF",
"scores",
"for",
"each",
"word",
"in",
"each",
"document",
".",
"The",
"collection",
"of",
"documents",
"must",
"be",
"in",
"bag",
"-",
"of",
"-",
"words",
"format",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L246-L295 |
29,498 | apple/turicreate | src/unity/python/turicreate/toolkits/text_analytics/_util.py | drop_words | def drop_words(text, threshold=2, to_lower=True, delimiters=DEFAULT_DELIMITERS,
stop_words=None):
'''
Remove words that occur below a certain number of times in an SArray.
This is a common method of cleaning text before it is used, and can increase the
quality and explainability of the models learned on the transformed data.
RareWordTrimmer can be applied to all the string-, dictionary-, and list-typed
columns in an SArray.
* **string** : The string is first tokenized. By default, all letters are
first converted to lower case, then tokenized by space characters. Each
token is taken to be a word, and the words occurring below a threshold
number of times across the entire column are removed, then the remaining
tokens are concatenated back into a string.
* **list** : Each element of the list must be a string, where each element
is assumed to be a token. The remaining tokens are then filtered
by count occurrences and a threshold value.
* **dict** : The method first obtains the list of keys in the dictionary.
This list is then processed as a standard list, except the value of each
key must be of integer type and is considered to be the count of that key.
Parameters
----------
text : SArray[str | dict | list]
The input text data.
threshold : int, optional
The count below which words are removed from the input.
stop_words: list[str], optional
A manually specified list of stop words, which are removed regardless
of count.
to_lower : bool, optional
Indicates whether to map the input strings to lower case before counting.
delimiters: list[string], optional
A list of delimiter characters for tokenization. By default, the list
is defined to be the list of space characters. The user can define
any custom list of single-character delimiters. Alternatively, setting
`delimiters=None` will use a Penn treebank type tokenization, which
is better at handling punctuations. (See reference below for details.)
Returns
-------
out : SArray.
An SArray with words below a threshold removed.
See Also
--------
count_ngrams, tf_idf, tokenize,
References
----------
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
# Create input data
>>> sa = turicreate.SArray(["The quick brown fox jumps in a fox like way.",
"Word word WORD, word!!!word"])
# Run drop_words
>>> turicreate.text_analytics.drop_words(sa)
dtype: str
Rows: 2
['fox fox', 'word word']
# Run drop_words with Penn treebank style tokenization to handle
# punctuations
>>> turicreate.text_analytics.drop_words(sa, delimiters=None)
dtype: str
Rows: 2
['fox fox', 'word word word']
# Run drop_words with dictionary input
>>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 2},
{'a dog': 0, 'a dog cat': 5}])
>>> turicreate.text_analytics.drop_words(sa)
dtype: dict
Rows: 2
[{'bob alice': 2}, {'a dog cat': 5}]
# Run drop_words with list input
>>> sa = turicreate.SArray([['one', 'bar bah', 'One'],
['a dog', 'a dog cat', 'A DOG']])
>>> turicreate.text_analytics.drop_words(sa)
dtype: list
Rows: 2
[['one', 'one'], ['a dog', 'a dog']]
'''
_raise_error_if_not_sarray(text, "text")
## Compute word counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.RareWordTrimmer(features='docs',
threshold=threshold,
to_lower=to_lower,
delimiters=delimiters,
stopwords=stop_words,
output_column_prefix=None)
tokens = fe.fit_transform(sf)
return tokens['docs'] | python | def drop_words(text, threshold=2, to_lower=True, delimiters=DEFAULT_DELIMITERS,
stop_words=None):
'''
Remove words that occur below a certain number of times in an SArray.
This is a common method of cleaning text before it is used, and can increase the
quality and explainability of the models learned on the transformed data.
RareWordTrimmer can be applied to all the string-, dictionary-, and list-typed
columns in an SArray.
* **string** : The string is first tokenized. By default, all letters are
first converted to lower case, then tokenized by space characters. Each
token is taken to be a word, and the words occurring below a threshold
number of times across the entire column are removed, then the remaining
tokens are concatenated back into a string.
* **list** : Each element of the list must be a string, where each element
is assumed to be a token. The remaining tokens are then filtered
by count occurrences and a threshold value.
* **dict** : The method first obtains the list of keys in the dictionary.
This list is then processed as a standard list, except the value of each
key must be of integer type and is considered to be the count of that key.
Parameters
----------
text : SArray[str | dict | list]
The input text data.
threshold : int, optional
The count below which words are removed from the input.
stop_words: list[str], optional
A manually specified list of stop words, which are removed regardless
of count.
to_lower : bool, optional
Indicates whether to map the input strings to lower case before counting.
delimiters: list[string], optional
A list of delimiter characters for tokenization. By default, the list
is defined to be the list of space characters. The user can define
any custom list of single-character delimiters. Alternatively, setting
`delimiters=None` will use a Penn treebank type tokenization, which
is better at handling punctuations. (See reference below for details.)
Returns
-------
out : SArray.
An SArray with words below a threshold removed.
See Also
--------
count_ngrams, tf_idf, tokenize,
References
----------
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
# Create input data
>>> sa = turicreate.SArray(["The quick brown fox jumps in a fox like way.",
"Word word WORD, word!!!word"])
# Run drop_words
>>> turicreate.text_analytics.drop_words(sa)
dtype: str
Rows: 2
['fox fox', 'word word']
# Run drop_words with Penn treebank style tokenization to handle
# punctuations
>>> turicreate.text_analytics.drop_words(sa, delimiters=None)
dtype: str
Rows: 2
['fox fox', 'word word word']
# Run drop_words with dictionary input
>>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 2},
{'a dog': 0, 'a dog cat': 5}])
>>> turicreate.text_analytics.drop_words(sa)
dtype: dict
Rows: 2
[{'bob alice': 2}, {'a dog cat': 5}]
# Run drop_words with list input
>>> sa = turicreate.SArray([['one', 'bar bah', 'One'],
['a dog', 'a dog cat', 'A DOG']])
>>> turicreate.text_analytics.drop_words(sa)
dtype: list
Rows: 2
[['one', 'one'], ['a dog', 'a dog']]
'''
_raise_error_if_not_sarray(text, "text")
## Compute word counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.RareWordTrimmer(features='docs',
threshold=threshold,
to_lower=to_lower,
delimiters=delimiters,
stopwords=stop_words,
output_column_prefix=None)
tokens = fe.fit_transform(sf)
return tokens['docs'] | [
"def",
"drop_words",
"(",
"text",
",",
"threshold",
"=",
"2",
",",
"to_lower",
"=",
"True",
",",
"delimiters",
"=",
"DEFAULT_DELIMITERS",
",",
"stop_words",
"=",
"None",
")",
":",
"_raise_error_if_not_sarray",
"(",
"text",
",",
"\"text\"",
")",
"## Compute word counts",
"sf",
"=",
"_turicreate",
".",
"SFrame",
"(",
"{",
"'docs'",
":",
"text",
"}",
")",
"fe",
"=",
"_feature_engineering",
".",
"RareWordTrimmer",
"(",
"features",
"=",
"'docs'",
",",
"threshold",
"=",
"threshold",
",",
"to_lower",
"=",
"to_lower",
",",
"delimiters",
"=",
"delimiters",
",",
"stopwords",
"=",
"stop_words",
",",
"output_column_prefix",
"=",
"None",
")",
"tokens",
"=",
"fe",
".",
"fit_transform",
"(",
"sf",
")",
"return",
"tokens",
"[",
"'docs'",
"]"
] | Remove words that occur below a certain number of times in an SArray.
This is a common method of cleaning text before it is used, and can increase the
quality and explainability of the models learned on the transformed data.
RareWordTrimmer can be applied to all the string-, dictionary-, and list-typed
columns in an SArray.
* **string** : The string is first tokenized. By default, all letters are
first converted to lower case, then tokenized by space characters. Each
token is taken to be a word, and the words occurring below a threshold
number of times across the entire column are removed, then the remaining
tokens are concatenated back into a string.
* **list** : Each element of the list must be a string, where each element
is assumed to be a token. The remaining tokens are then filtered
by count occurrences and a threshold value.
* **dict** : The method first obtains the list of keys in the dictionary.
This list is then processed as a standard list, except the value of each
key must be of integer type and is considered to be the count of that key.
Parameters
----------
text : SArray[str | dict | list]
The input text data.
threshold : int, optional
The count below which words are removed from the input.
stop_words: list[str], optional
A manually specified list of stop words, which are removed regardless
of count.
to_lower : bool, optional
Indicates whether to map the input strings to lower case before counting.
delimiters: list[string], optional
A list of delimiter characters for tokenization. By default, the list
is defined to be the list of space characters. The user can define
any custom list of single-character delimiters. Alternatively, setting
`delimiters=None` will use a Penn treebank type tokenization, which
is better at handling punctuations. (See reference below for details.)
Returns
-------
out : SArray.
An SArray with words below a threshold removed.
See Also
--------
count_ngrams, tf_idf, tokenize,
References
----------
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
# Create input data
>>> sa = turicreate.SArray(["The quick brown fox jumps in a fox like way.",
"Word word WORD, word!!!word"])
# Run drop_words
>>> turicreate.text_analytics.drop_words(sa)
dtype: str
Rows: 2
['fox fox', 'word word']
# Run drop_words with Penn treebank style tokenization to handle
# punctuations
>>> turicreate.text_analytics.drop_words(sa, delimiters=None)
dtype: str
Rows: 2
['fox fox', 'word word word']
# Run drop_words with dictionary input
>>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 2},
{'a dog': 0, 'a dog cat': 5}])
>>> turicreate.text_analytics.drop_words(sa)
dtype: dict
Rows: 2
[{'bob alice': 2}, {'a dog cat': 5}]
# Run drop_words with list input
>>> sa = turicreate.SArray([['one', 'bar bah', 'One'],
['a dog', 'a dog cat', 'A DOG']])
>>> turicreate.text_analytics.drop_words(sa)
dtype: list
Rows: 2
[['one', 'one'], ['a dog', 'a dog']] | [
"Remove",
"words",
"that",
"occur",
"below",
"a",
"certain",
"number",
"of",
"times",
"in",
"an",
"SArray",
".",
"This",
"is",
"a",
"common",
"method",
"of",
"cleaning",
"text",
"before",
"it",
"is",
"used",
"and",
"can",
"increase",
"the",
"quality",
"and",
"explainability",
"of",
"the",
"models",
"learned",
"on",
"the",
"transformed",
"data",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L298-L410 |
29,499 | apple/turicreate | src/unity/python/turicreate/toolkits/text_analytics/_util.py | tokenize | def tokenize(text, to_lower=False, delimiters=DEFAULT_DELIMITERS):
"""
Tokenize the input SArray of text strings and return the list of tokens.
Parameters
----------
text : SArray[str]
Input data of strings representing English text. This tokenizer is not
intended to process XML, HTML, or other structured text formats.
to_lower : bool, optional
If True, all strings are converted to lower case before tokenization.
delimiters : list[str], None, optional
Input strings are tokenized using delimiter characters in this list.
Each entry in this list must contain a single character. If set to
`None`, then a Penn treebank-style tokenization is used, which contains
smart handling of punctuations.
Returns
-------
out : SArray[list]
Each text string in the input is mapped to a list of tokens.
See Also
--------
count_words, count_ngrams, tf_idf
References
----------
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
>>> docs = turicreate.SArray(['This is the first sentence.',
"This one, it's the second sentence."])
# Default tokenization by space characters
>>> turicreate.text_analytics.tokenize(docs)
dtype: list
Rows: 2
[['This', 'is', 'the', 'first', 'sentence.'],
['This', 'one,', "it's", 'the', 'second', 'sentence.']]
# Penn treebank-style tokenization
>>> turicreate.text_analytics.tokenize(docs, delimiters=None)
dtype: list
Rows: 2
[['This', 'is', 'the', 'first', 'sentence', '.'],
['This', 'one', ',', 'it', "'s", 'the', 'second', 'sentence', '.']]
"""
_raise_error_if_not_sarray(text, "text")
## Compute word counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.Tokenizer(features='docs',
to_lower=to_lower,
delimiters=delimiters,
output_column_prefix=None)
tokens = fe.fit_transform(sf)
return tokens['docs'] | python | def tokenize(text, to_lower=False, delimiters=DEFAULT_DELIMITERS):
"""
Tokenize the input SArray of text strings and return the list of tokens.
Parameters
----------
text : SArray[str]
Input data of strings representing English text. This tokenizer is not
intended to process XML, HTML, or other structured text formats.
to_lower : bool, optional
If True, all strings are converted to lower case before tokenization.
delimiters : list[str], None, optional
Input strings are tokenized using delimiter characters in this list.
Each entry in this list must contain a single character. If set to
`None`, then a Penn treebank-style tokenization is used, which contains
smart handling of punctuations.
Returns
-------
out : SArray[list]
Each text string in the input is mapped to a list of tokens.
See Also
--------
count_words, count_ngrams, tf_idf
References
----------
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
>>> docs = turicreate.SArray(['This is the first sentence.',
"This one, it's the second sentence."])
# Default tokenization by space characters
>>> turicreate.text_analytics.tokenize(docs)
dtype: list
Rows: 2
[['This', 'is', 'the', 'first', 'sentence.'],
['This', 'one,', "it's", 'the', 'second', 'sentence.']]
# Penn treebank-style tokenization
>>> turicreate.text_analytics.tokenize(docs, delimiters=None)
dtype: list
Rows: 2
[['This', 'is', 'the', 'first', 'sentence', '.'],
['This', 'one', ',', 'it', "'s", 'the', 'second', 'sentence', '.']]
"""
_raise_error_if_not_sarray(text, "text")
## Compute word counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.Tokenizer(features='docs',
to_lower=to_lower,
delimiters=delimiters,
output_column_prefix=None)
tokens = fe.fit_transform(sf)
return tokens['docs'] | [
"def",
"tokenize",
"(",
"text",
",",
"to_lower",
"=",
"False",
",",
"delimiters",
"=",
"DEFAULT_DELIMITERS",
")",
":",
"_raise_error_if_not_sarray",
"(",
"text",
",",
"\"text\"",
")",
"## Compute word counts",
"sf",
"=",
"_turicreate",
".",
"SFrame",
"(",
"{",
"'docs'",
":",
"text",
"}",
")",
"fe",
"=",
"_feature_engineering",
".",
"Tokenizer",
"(",
"features",
"=",
"'docs'",
",",
"to_lower",
"=",
"to_lower",
",",
"delimiters",
"=",
"delimiters",
",",
"output_column_prefix",
"=",
"None",
")",
"tokens",
"=",
"fe",
".",
"fit_transform",
"(",
"sf",
")",
"return",
"tokens",
"[",
"'docs'",
"]"
] | Tokenize the input SArray of text strings and return the list of tokens.
Parameters
----------
text : SArray[str]
Input data of strings representing English text. This tokenizer is not
intended to process XML, HTML, or other structured text formats.
to_lower : bool, optional
If True, all strings are converted to lower case before tokenization.
delimiters : list[str], None, optional
Input strings are tokenized using delimiter characters in this list.
Each entry in this list must contain a single character. If set to
`None`, then a Penn treebank-style tokenization is used, which contains
smart handling of punctuations.
Returns
-------
out : SArray[list]
Each text string in the input is mapped to a list of tokens.
See Also
--------
count_words, count_ngrams, tf_idf
References
----------
- `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_
Examples
--------
.. sourcecode:: python
>>> import turicreate
>>> docs = turicreate.SArray(['This is the first sentence.',
"This one, it's the second sentence."])
# Default tokenization by space characters
>>> turicreate.text_analytics.tokenize(docs)
dtype: list
Rows: 2
[['This', 'is', 'the', 'first', 'sentence.'],
['This', 'one,', "it's", 'the', 'second', 'sentence.']]
# Penn treebank-style tokenization
>>> turicreate.text_analytics.tokenize(docs, delimiters=None)
dtype: list
Rows: 2
[['This', 'is', 'the', 'first', 'sentence', '.'],
['This', 'one', ',', 'it', "'s", 'the', 'second', 'sentence', '.']] | [
"Tokenize",
"the",
"input",
"SArray",
"of",
"text",
"strings",
"and",
"return",
"the",
"list",
"of",
"tokens",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L412-L478 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.