repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool.AddExtensionDescriptor | def AddExtensionDescriptor(self, extension):
"""Adds a FieldDescriptor describing an extension to the pool.
Args:
extension: A FieldDescriptor.
Raises:
AssertionError: when another extension with the same number extends the
same message.
TypeError: when the specified extension is not a
descriptor.FieldDescriptor.
"""
if not (isinstance(extension, descriptor.FieldDescriptor) and
extension.is_extension):
raise TypeError('Expected an extension descriptor.')
if extension.extension_scope is None:
self._toplevel_extensions[extension.full_name] = extension
try:
existing_desc = self._extensions_by_number[
extension.containing_type][extension.number]
except KeyError:
pass
else:
if extension is not existing_desc:
raise AssertionError(
'Extensions "%s" and "%s" both try to extend message type "%s" '
'with field number %d.' %
(extension.full_name, existing_desc.full_name,
extension.containing_type.full_name, extension.number))
self._extensions_by_number[extension.containing_type][
extension.number] = extension
self._extensions_by_name[extension.containing_type][
extension.full_name] = extension
# Also register MessageSet extensions with the type name.
if _IsMessageSetExtension(extension):
self._extensions_by_name[extension.containing_type][
extension.message_type.full_name] = extension | python | def AddExtensionDescriptor(self, extension):
"""Adds a FieldDescriptor describing an extension to the pool.
Args:
extension: A FieldDescriptor.
Raises:
AssertionError: when another extension with the same number extends the
same message.
TypeError: when the specified extension is not a
descriptor.FieldDescriptor.
"""
if not (isinstance(extension, descriptor.FieldDescriptor) and
extension.is_extension):
raise TypeError('Expected an extension descriptor.')
if extension.extension_scope is None:
self._toplevel_extensions[extension.full_name] = extension
try:
existing_desc = self._extensions_by_number[
extension.containing_type][extension.number]
except KeyError:
pass
else:
if extension is not existing_desc:
raise AssertionError(
'Extensions "%s" and "%s" both try to extend message type "%s" '
'with field number %d.' %
(extension.full_name, existing_desc.full_name,
extension.containing_type.full_name, extension.number))
self._extensions_by_number[extension.containing_type][
extension.number] = extension
self._extensions_by_name[extension.containing_type][
extension.full_name] = extension
# Also register MessageSet extensions with the type name.
if _IsMessageSetExtension(extension):
self._extensions_by_name[extension.containing_type][
extension.message_type.full_name] = extension | [
"def",
"AddExtensionDescriptor",
"(",
"self",
",",
"extension",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"extension",
",",
"descriptor",
".",
"FieldDescriptor",
")",
"and",
"extension",
".",
"is_extension",
")",
":",
"raise",
"TypeError",
"(",
"'Expected an extension descriptor.'",
")",
"if",
"extension",
".",
"extension_scope",
"is",
"None",
":",
"self",
".",
"_toplevel_extensions",
"[",
"extension",
".",
"full_name",
"]",
"=",
"extension",
"try",
":",
"existing_desc",
"=",
"self",
".",
"_extensions_by_number",
"[",
"extension",
".",
"containing_type",
"]",
"[",
"extension",
".",
"number",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"extension",
"is",
"not",
"existing_desc",
":",
"raise",
"AssertionError",
"(",
"'Extensions \"%s\" and \"%s\" both try to extend message type \"%s\" '",
"'with field number %d.'",
"%",
"(",
"extension",
".",
"full_name",
",",
"existing_desc",
".",
"full_name",
",",
"extension",
".",
"containing_type",
".",
"full_name",
",",
"extension",
".",
"number",
")",
")",
"self",
".",
"_extensions_by_number",
"[",
"extension",
".",
"containing_type",
"]",
"[",
"extension",
".",
"number",
"]",
"=",
"extension",
"self",
".",
"_extensions_by_name",
"[",
"extension",
".",
"containing_type",
"]",
"[",
"extension",
".",
"full_name",
"]",
"=",
"extension",
"# Also register MessageSet extensions with the type name.",
"if",
"_IsMessageSetExtension",
"(",
"extension",
")",
":",
"self",
".",
"_extensions_by_name",
"[",
"extension",
".",
"containing_type",
"]",
"[",
"extension",
".",
"message_type",
".",
"full_name",
"]",
"=",
"extension"
] | Adds a FieldDescriptor describing an extension to the pool.
Args:
extension: A FieldDescriptor.
Raises:
AssertionError: when another extension with the same number extends the
same message.
TypeError: when the specified extension is not a
descriptor.FieldDescriptor. | [
"Adds",
"a",
"FieldDescriptor",
"describing",
"an",
"extension",
"to",
"the",
"pool",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L205-L245 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool.AddFileDescriptor | def AddFileDescriptor(self, file_desc):
"""Adds a FileDescriptor to the pool, non-recursively.
If the FileDescriptor contains messages or enums, the caller must explicitly
register them.
Args:
file_desc: A FileDescriptor.
"""
self._AddFileDescriptor(file_desc)
# TODO(jieluo): This is a temporary solution for FieldDescriptor.file.
# Remove it when FieldDescriptor.file is added in code gen.
for extension in file_desc.extensions_by_name.values():
self._file_desc_by_toplevel_extension[
extension.full_name] = file_desc | python | def AddFileDescriptor(self, file_desc):
"""Adds a FileDescriptor to the pool, non-recursively.
If the FileDescriptor contains messages or enums, the caller must explicitly
register them.
Args:
file_desc: A FileDescriptor.
"""
self._AddFileDescriptor(file_desc)
# TODO(jieluo): This is a temporary solution for FieldDescriptor.file.
# Remove it when FieldDescriptor.file is added in code gen.
for extension in file_desc.extensions_by_name.values():
self._file_desc_by_toplevel_extension[
extension.full_name] = file_desc | [
"def",
"AddFileDescriptor",
"(",
"self",
",",
"file_desc",
")",
":",
"self",
".",
"_AddFileDescriptor",
"(",
"file_desc",
")",
"# TODO(jieluo): This is a temporary solution for FieldDescriptor.file.",
"# Remove it when FieldDescriptor.file is added in code gen.",
"for",
"extension",
"in",
"file_desc",
".",
"extensions_by_name",
".",
"values",
"(",
")",
":",
"self",
".",
"_file_desc_by_toplevel_extension",
"[",
"extension",
".",
"full_name",
"]",
"=",
"file_desc"
] | Adds a FileDescriptor to the pool, non-recursively.
If the FileDescriptor contains messages or enums, the caller must explicitly
register them.
Args:
file_desc: A FileDescriptor. | [
"Adds",
"a",
"FileDescriptor",
"to",
"the",
"pool",
"non",
"-",
"recursively",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L247-L262 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._AddFileDescriptor | def _AddFileDescriptor(self, file_desc):
"""Adds a FileDescriptor to the pool, non-recursively.
If the FileDescriptor contains messages or enums, the caller must explicitly
register them.
Args:
file_desc: A FileDescriptor.
"""
if not isinstance(file_desc, descriptor.FileDescriptor):
raise TypeError('Expected instance of descriptor.FileDescriptor.')
self._file_descriptors[file_desc.name] = file_desc | python | def _AddFileDescriptor(self, file_desc):
"""Adds a FileDescriptor to the pool, non-recursively.
If the FileDescriptor contains messages or enums, the caller must explicitly
register them.
Args:
file_desc: A FileDescriptor.
"""
if not isinstance(file_desc, descriptor.FileDescriptor):
raise TypeError('Expected instance of descriptor.FileDescriptor.')
self._file_descriptors[file_desc.name] = file_desc | [
"def",
"_AddFileDescriptor",
"(",
"self",
",",
"file_desc",
")",
":",
"if",
"not",
"isinstance",
"(",
"file_desc",
",",
"descriptor",
".",
"FileDescriptor",
")",
":",
"raise",
"TypeError",
"(",
"'Expected instance of descriptor.FileDescriptor.'",
")",
"self",
".",
"_file_descriptors",
"[",
"file_desc",
".",
"name",
"]",
"=",
"file_desc"
] | Adds a FileDescriptor to the pool, non-recursively.
If the FileDescriptor contains messages or enums, the caller must explicitly
register them.
Args:
file_desc: A FileDescriptor. | [
"Adds",
"a",
"FileDescriptor",
"to",
"the",
"pool",
"non",
"-",
"recursively",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L264-L276 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool.FindFileByName | def FindFileByName(self, file_name):
"""Gets a FileDescriptor by file name.
Args:
file_name: The path to the file to get a descriptor for.
Returns:
A FileDescriptor for the named file.
Raises:
KeyError: if the file cannot be found in the pool.
"""
try:
return self._file_descriptors[file_name]
except KeyError:
pass
try:
file_proto = self._internal_db.FindFileByName(file_name)
except KeyError as error:
if self._descriptor_db:
file_proto = self._descriptor_db.FindFileByName(file_name)
else:
raise error
if not file_proto:
raise KeyError('Cannot find a file named %s' % file_name)
return self._ConvertFileProtoToFileDescriptor(file_proto) | python | def FindFileByName(self, file_name):
"""Gets a FileDescriptor by file name.
Args:
file_name: The path to the file to get a descriptor for.
Returns:
A FileDescriptor for the named file.
Raises:
KeyError: if the file cannot be found in the pool.
"""
try:
return self._file_descriptors[file_name]
except KeyError:
pass
try:
file_proto = self._internal_db.FindFileByName(file_name)
except KeyError as error:
if self._descriptor_db:
file_proto = self._descriptor_db.FindFileByName(file_name)
else:
raise error
if not file_proto:
raise KeyError('Cannot find a file named %s' % file_name)
return self._ConvertFileProtoToFileDescriptor(file_proto) | [
"def",
"FindFileByName",
"(",
"self",
",",
"file_name",
")",
":",
"try",
":",
"return",
"self",
".",
"_file_descriptors",
"[",
"file_name",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"file_proto",
"=",
"self",
".",
"_internal_db",
".",
"FindFileByName",
"(",
"file_name",
")",
"except",
"KeyError",
"as",
"error",
":",
"if",
"self",
".",
"_descriptor_db",
":",
"file_proto",
"=",
"self",
".",
"_descriptor_db",
".",
"FindFileByName",
"(",
"file_name",
")",
"else",
":",
"raise",
"error",
"if",
"not",
"file_proto",
":",
"raise",
"KeyError",
"(",
"'Cannot find a file named %s'",
"%",
"file_name",
")",
"return",
"self",
".",
"_ConvertFileProtoToFileDescriptor",
"(",
"file_proto",
")"
] | Gets a FileDescriptor by file name.
Args:
file_name: The path to the file to get a descriptor for.
Returns:
A FileDescriptor for the named file.
Raises:
KeyError: if the file cannot be found in the pool. | [
"Gets",
"a",
"FileDescriptor",
"by",
"file",
"name",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L278-L305 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool.FindFileContainingSymbol | def FindFileContainingSymbol(self, symbol):
"""Gets the FileDescriptor for the file containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file cannot be found in the pool.
"""
symbol = _NormalizeFullyQualifiedName(symbol)
try:
return self._descriptors[symbol].file
except KeyError:
pass
try:
return self._enum_descriptors[symbol].file
except KeyError:
pass
try:
return self._FindFileContainingSymbolInDb(symbol)
except KeyError:
pass
try:
return self._file_desc_by_toplevel_extension[symbol]
except KeyError:
pass
# Try nested extensions inside a message.
message_name, _, extension_name = symbol.rpartition('.')
try:
message = self.FindMessageTypeByName(message_name)
assert message.extensions_by_name[extension_name]
return message.file
except KeyError:
raise KeyError('Cannot find a file containing %s' % symbol) | python | def FindFileContainingSymbol(self, symbol):
"""Gets the FileDescriptor for the file containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file cannot be found in the pool.
"""
symbol = _NormalizeFullyQualifiedName(symbol)
try:
return self._descriptors[symbol].file
except KeyError:
pass
try:
return self._enum_descriptors[symbol].file
except KeyError:
pass
try:
return self._FindFileContainingSymbolInDb(symbol)
except KeyError:
pass
try:
return self._file_desc_by_toplevel_extension[symbol]
except KeyError:
pass
# Try nested extensions inside a message.
message_name, _, extension_name = symbol.rpartition('.')
try:
message = self.FindMessageTypeByName(message_name)
assert message.extensions_by_name[extension_name]
return message.file
except KeyError:
raise KeyError('Cannot find a file containing %s' % symbol) | [
"def",
"FindFileContainingSymbol",
"(",
"self",
",",
"symbol",
")",
":",
"symbol",
"=",
"_NormalizeFullyQualifiedName",
"(",
"symbol",
")",
"try",
":",
"return",
"self",
".",
"_descriptors",
"[",
"symbol",
"]",
".",
"file",
"except",
"KeyError",
":",
"pass",
"try",
":",
"return",
"self",
".",
"_enum_descriptors",
"[",
"symbol",
"]",
".",
"file",
"except",
"KeyError",
":",
"pass",
"try",
":",
"return",
"self",
".",
"_FindFileContainingSymbolInDb",
"(",
"symbol",
")",
"except",
"KeyError",
":",
"pass",
"try",
":",
"return",
"self",
".",
"_file_desc_by_toplevel_extension",
"[",
"symbol",
"]",
"except",
"KeyError",
":",
"pass",
"# Try nested extensions inside a message.",
"message_name",
",",
"_",
",",
"extension_name",
"=",
"symbol",
".",
"rpartition",
"(",
"'.'",
")",
"try",
":",
"message",
"=",
"self",
".",
"FindMessageTypeByName",
"(",
"message_name",
")",
"assert",
"message",
".",
"extensions_by_name",
"[",
"extension_name",
"]",
"return",
"message",
".",
"file",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"'Cannot find a file containing %s'",
"%",
"symbol",
")"
] | Gets the FileDescriptor for the file containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file cannot be found in the pool. | [
"Gets",
"the",
"FileDescriptor",
"for",
"the",
"file",
"containing",
"the",
"specified",
"symbol",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L307-L349 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool.FindMessageTypeByName | def FindMessageTypeByName(self, full_name):
"""Loads the named descriptor from the pool.
Args:
full_name: The full name of the descriptor to load.
Returns:
The descriptor for the named type.
Raises:
KeyError: if the message cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in self._descriptors:
self._FindFileContainingSymbolInDb(full_name)
return self._descriptors[full_name] | python | def FindMessageTypeByName(self, full_name):
"""Loads the named descriptor from the pool.
Args:
full_name: The full name of the descriptor to load.
Returns:
The descriptor for the named type.
Raises:
KeyError: if the message cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in self._descriptors:
self._FindFileContainingSymbolInDb(full_name)
return self._descriptors[full_name] | [
"def",
"FindMessageTypeByName",
"(",
"self",
",",
"full_name",
")",
":",
"full_name",
"=",
"_NormalizeFullyQualifiedName",
"(",
"full_name",
")",
"if",
"full_name",
"not",
"in",
"self",
".",
"_descriptors",
":",
"self",
".",
"_FindFileContainingSymbolInDb",
"(",
"full_name",
")",
"return",
"self",
".",
"_descriptors",
"[",
"full_name",
"]"
] | Loads the named descriptor from the pool.
Args:
full_name: The full name of the descriptor to load.
Returns:
The descriptor for the named type.
Raises:
KeyError: if the message cannot be found in the pool. | [
"Loads",
"the",
"named",
"descriptor",
"from",
"the",
"pool",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L351-L367 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool.FindEnumTypeByName | def FindEnumTypeByName(self, full_name):
"""Loads the named enum descriptor from the pool.
Args:
full_name: The full name of the enum descriptor to load.
Returns:
The enum descriptor for the named type.
Raises:
KeyError: if the enum cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in self._enum_descriptors:
self._FindFileContainingSymbolInDb(full_name)
return self._enum_descriptors[full_name] | python | def FindEnumTypeByName(self, full_name):
"""Loads the named enum descriptor from the pool.
Args:
full_name: The full name of the enum descriptor to load.
Returns:
The enum descriptor for the named type.
Raises:
KeyError: if the enum cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in self._enum_descriptors:
self._FindFileContainingSymbolInDb(full_name)
return self._enum_descriptors[full_name] | [
"def",
"FindEnumTypeByName",
"(",
"self",
",",
"full_name",
")",
":",
"full_name",
"=",
"_NormalizeFullyQualifiedName",
"(",
"full_name",
")",
"if",
"full_name",
"not",
"in",
"self",
".",
"_enum_descriptors",
":",
"self",
".",
"_FindFileContainingSymbolInDb",
"(",
"full_name",
")",
"return",
"self",
".",
"_enum_descriptors",
"[",
"full_name",
"]"
] | Loads the named enum descriptor from the pool.
Args:
full_name: The full name of the enum descriptor to load.
Returns:
The enum descriptor for the named type.
Raises:
KeyError: if the enum cannot be found in the pool. | [
"Loads",
"the",
"named",
"enum",
"descriptor",
"from",
"the",
"pool",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L369-L385 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool.FindFieldByName | def FindFieldByName(self, full_name):
"""Loads the named field descriptor from the pool.
Args:
full_name: The full name of the field descriptor to load.
Returns:
The field descriptor for the named field.
Raises:
KeyError: if the field cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
message_name, _, field_name = full_name.rpartition('.')
message_descriptor = self.FindMessageTypeByName(message_name)
return message_descriptor.fields_by_name[field_name] | python | def FindFieldByName(self, full_name):
"""Loads the named field descriptor from the pool.
Args:
full_name: The full name of the field descriptor to load.
Returns:
The field descriptor for the named field.
Raises:
KeyError: if the field cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
message_name, _, field_name = full_name.rpartition('.')
message_descriptor = self.FindMessageTypeByName(message_name)
return message_descriptor.fields_by_name[field_name] | [
"def",
"FindFieldByName",
"(",
"self",
",",
"full_name",
")",
":",
"full_name",
"=",
"_NormalizeFullyQualifiedName",
"(",
"full_name",
")",
"message_name",
",",
"_",
",",
"field_name",
"=",
"full_name",
".",
"rpartition",
"(",
"'.'",
")",
"message_descriptor",
"=",
"self",
".",
"FindMessageTypeByName",
"(",
"message_name",
")",
"return",
"message_descriptor",
".",
"fields_by_name",
"[",
"field_name",
"]"
] | Loads the named field descriptor from the pool.
Args:
full_name: The full name of the field descriptor to load.
Returns:
The field descriptor for the named field.
Raises:
KeyError: if the field cannot be found in the pool. | [
"Loads",
"the",
"named",
"field",
"descriptor",
"from",
"the",
"pool",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L387-L402 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool.FindServiceByName | def FindServiceByName(self, full_name):
"""Loads the named service descriptor from the pool.
Args:
full_name: The full name of the service descriptor to load.
Returns:
The service descriptor for the named service.
Raises:
KeyError: if the service cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in self._service_descriptors:
self._FindFileContainingSymbolInDb(full_name)
return self._service_descriptors[full_name] | python | def FindServiceByName(self, full_name):
"""Loads the named service descriptor from the pool.
Args:
full_name: The full name of the service descriptor to load.
Returns:
The service descriptor for the named service.
Raises:
KeyError: if the service cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in self._service_descriptors:
self._FindFileContainingSymbolInDb(full_name)
return self._service_descriptors[full_name] | [
"def",
"FindServiceByName",
"(",
"self",
",",
"full_name",
")",
":",
"full_name",
"=",
"_NormalizeFullyQualifiedName",
"(",
"full_name",
")",
"if",
"full_name",
"not",
"in",
"self",
".",
"_service_descriptors",
":",
"self",
".",
"_FindFileContainingSymbolInDb",
"(",
"full_name",
")",
"return",
"self",
".",
"_service_descriptors",
"[",
"full_name",
"]"
] | Loads the named service descriptor from the pool.
Args:
full_name: The full name of the service descriptor to load.
Returns:
The service descriptor for the named service.
Raises:
KeyError: if the service cannot be found in the pool. | [
"Loads",
"the",
"named",
"service",
"descriptor",
"from",
"the",
"pool",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L467-L482 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._FindFileContainingSymbolInDb | def _FindFileContainingSymbolInDb(self, symbol):
"""Finds the file in descriptor DB containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file cannot be found in the descriptor database.
"""
try:
file_proto = self._internal_db.FindFileContainingSymbol(symbol)
except KeyError as error:
if self._descriptor_db:
file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
else:
raise error
if not file_proto:
raise KeyError('Cannot find a file containing %s' % symbol)
return self._ConvertFileProtoToFileDescriptor(file_proto) | python | def _FindFileContainingSymbolInDb(self, symbol):
"""Finds the file in descriptor DB containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file cannot be found in the descriptor database.
"""
try:
file_proto = self._internal_db.FindFileContainingSymbol(symbol)
except KeyError as error:
if self._descriptor_db:
file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
else:
raise error
if not file_proto:
raise KeyError('Cannot find a file containing %s' % symbol)
return self._ConvertFileProtoToFileDescriptor(file_proto) | [
"def",
"_FindFileContainingSymbolInDb",
"(",
"self",
",",
"symbol",
")",
":",
"try",
":",
"file_proto",
"=",
"self",
".",
"_internal_db",
".",
"FindFileContainingSymbol",
"(",
"symbol",
")",
"except",
"KeyError",
"as",
"error",
":",
"if",
"self",
".",
"_descriptor_db",
":",
"file_proto",
"=",
"self",
".",
"_descriptor_db",
".",
"FindFileContainingSymbol",
"(",
"symbol",
")",
"else",
":",
"raise",
"error",
"if",
"not",
"file_proto",
":",
"raise",
"KeyError",
"(",
"'Cannot find a file containing %s'",
"%",
"symbol",
")",
"return",
"self",
".",
"_ConvertFileProtoToFileDescriptor",
"(",
"file_proto",
")"
] | Finds the file in descriptor DB containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file cannot be found in the descriptor database. | [
"Finds",
"the",
"file",
"in",
"descriptor",
"DB",
"containing",
"the",
"specified",
"symbol",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L484-L505 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._ConvertFileProtoToFileDescriptor | def _ConvertFileProtoToFileDescriptor(self, file_proto):
"""Creates a FileDescriptor from a proto or returns a cached copy.
This method also has the side effect of loading all the symbols found in
the file into the appropriate dictionaries in the pool.
Args:
file_proto: The proto to convert.
Returns:
A FileDescriptor matching the passed in proto.
"""
if file_proto.name not in self._file_descriptors:
built_deps = list(self._GetDeps(file_proto.dependency))
direct_deps = [self.FindFileByName(n) for n in file_proto.dependency]
public_deps = [direct_deps[i] for i in file_proto.public_dependency]
file_descriptor = descriptor.FileDescriptor(
pool=self,
name=file_proto.name,
package=file_proto.package,
syntax=file_proto.syntax,
options=_OptionsOrNone(file_proto),
serialized_pb=file_proto.SerializeToString(),
dependencies=direct_deps,
public_dependencies=public_deps)
scope = {}
# This loop extracts all the message and enum types from all the
# dependencies of the file_proto. This is necessary to create the
# scope of available message types when defining the passed in
# file proto.
for dependency in built_deps:
scope.update(self._ExtractSymbols(
dependency.message_types_by_name.values()))
scope.update((_PrefixWithDot(enum.full_name), enum)
for enum in dependency.enum_types_by_name.values())
for message_type in file_proto.message_type:
message_desc = self._ConvertMessageDescriptor(
message_type, file_proto.package, file_descriptor, scope,
file_proto.syntax)
file_descriptor.message_types_by_name[message_desc.name] = (
message_desc)
for enum_type in file_proto.enum_type:
file_descriptor.enum_types_by_name[enum_type.name] = (
self._ConvertEnumDescriptor(enum_type, file_proto.package,
file_descriptor, None, scope))
for index, extension_proto in enumerate(file_proto.extension):
extension_desc = self._MakeFieldDescriptor(
extension_proto, file_proto.package, index, is_extension=True)
extension_desc.containing_type = self._GetTypeFromScope(
file_descriptor.package, extension_proto.extendee, scope)
self._SetFieldType(extension_proto, extension_desc,
file_descriptor.package, scope)
file_descriptor.extensions_by_name[extension_desc.name] = (
extension_desc)
for desc_proto in file_proto.message_type:
self._SetAllFieldTypes(file_proto.package, desc_proto, scope)
if file_proto.package:
desc_proto_prefix = _PrefixWithDot(file_proto.package)
else:
desc_proto_prefix = ''
for desc_proto in file_proto.message_type:
desc = self._GetTypeFromScope(
desc_proto_prefix, desc_proto.name, scope)
file_descriptor.message_types_by_name[desc_proto.name] = desc
for index, service_proto in enumerate(file_proto.service):
file_descriptor.services_by_name[service_proto.name] = (
self._MakeServiceDescriptor(service_proto, index, scope,
file_proto.package, file_descriptor))
self.Add(file_proto)
self._file_descriptors[file_proto.name] = file_descriptor
return self._file_descriptors[file_proto.name] | python | def _ConvertFileProtoToFileDescriptor(self, file_proto):
"""Creates a FileDescriptor from a proto or returns a cached copy.
This method also has the side effect of loading all the symbols found in
the file into the appropriate dictionaries in the pool.
Args:
file_proto: The proto to convert.
Returns:
A FileDescriptor matching the passed in proto.
"""
if file_proto.name not in self._file_descriptors:
built_deps = list(self._GetDeps(file_proto.dependency))
direct_deps = [self.FindFileByName(n) for n in file_proto.dependency]
public_deps = [direct_deps[i] for i in file_proto.public_dependency]
file_descriptor = descriptor.FileDescriptor(
pool=self,
name=file_proto.name,
package=file_proto.package,
syntax=file_proto.syntax,
options=_OptionsOrNone(file_proto),
serialized_pb=file_proto.SerializeToString(),
dependencies=direct_deps,
public_dependencies=public_deps)
scope = {}
# This loop extracts all the message and enum types from all the
# dependencies of the file_proto. This is necessary to create the
# scope of available message types when defining the passed in
# file proto.
for dependency in built_deps:
scope.update(self._ExtractSymbols(
dependency.message_types_by_name.values()))
scope.update((_PrefixWithDot(enum.full_name), enum)
for enum in dependency.enum_types_by_name.values())
for message_type in file_proto.message_type:
message_desc = self._ConvertMessageDescriptor(
message_type, file_proto.package, file_descriptor, scope,
file_proto.syntax)
file_descriptor.message_types_by_name[message_desc.name] = (
message_desc)
for enum_type in file_proto.enum_type:
file_descriptor.enum_types_by_name[enum_type.name] = (
self._ConvertEnumDescriptor(enum_type, file_proto.package,
file_descriptor, None, scope))
for index, extension_proto in enumerate(file_proto.extension):
extension_desc = self._MakeFieldDescriptor(
extension_proto, file_proto.package, index, is_extension=True)
extension_desc.containing_type = self._GetTypeFromScope(
file_descriptor.package, extension_proto.extendee, scope)
self._SetFieldType(extension_proto, extension_desc,
file_descriptor.package, scope)
file_descriptor.extensions_by_name[extension_desc.name] = (
extension_desc)
for desc_proto in file_proto.message_type:
self._SetAllFieldTypes(file_proto.package, desc_proto, scope)
if file_proto.package:
desc_proto_prefix = _PrefixWithDot(file_proto.package)
else:
desc_proto_prefix = ''
for desc_proto in file_proto.message_type:
desc = self._GetTypeFromScope(
desc_proto_prefix, desc_proto.name, scope)
file_descriptor.message_types_by_name[desc_proto.name] = desc
for index, service_proto in enumerate(file_proto.service):
file_descriptor.services_by_name[service_proto.name] = (
self._MakeServiceDescriptor(service_proto, index, scope,
file_proto.package, file_descriptor))
self.Add(file_proto)
self._file_descriptors[file_proto.name] = file_descriptor
return self._file_descriptors[file_proto.name] | [
"def",
"_ConvertFileProtoToFileDescriptor",
"(",
"self",
",",
"file_proto",
")",
":",
"if",
"file_proto",
".",
"name",
"not",
"in",
"self",
".",
"_file_descriptors",
":",
"built_deps",
"=",
"list",
"(",
"self",
".",
"_GetDeps",
"(",
"file_proto",
".",
"dependency",
")",
")",
"direct_deps",
"=",
"[",
"self",
".",
"FindFileByName",
"(",
"n",
")",
"for",
"n",
"in",
"file_proto",
".",
"dependency",
"]",
"public_deps",
"=",
"[",
"direct_deps",
"[",
"i",
"]",
"for",
"i",
"in",
"file_proto",
".",
"public_dependency",
"]",
"file_descriptor",
"=",
"descriptor",
".",
"FileDescriptor",
"(",
"pool",
"=",
"self",
",",
"name",
"=",
"file_proto",
".",
"name",
",",
"package",
"=",
"file_proto",
".",
"package",
",",
"syntax",
"=",
"file_proto",
".",
"syntax",
",",
"options",
"=",
"_OptionsOrNone",
"(",
"file_proto",
")",
",",
"serialized_pb",
"=",
"file_proto",
".",
"SerializeToString",
"(",
")",
",",
"dependencies",
"=",
"direct_deps",
",",
"public_dependencies",
"=",
"public_deps",
")",
"scope",
"=",
"{",
"}",
"# This loop extracts all the message and enum types from all the",
"# dependencies of the file_proto. This is necessary to create the",
"# scope of available message types when defining the passed in",
"# file proto.",
"for",
"dependency",
"in",
"built_deps",
":",
"scope",
".",
"update",
"(",
"self",
".",
"_ExtractSymbols",
"(",
"dependency",
".",
"message_types_by_name",
".",
"values",
"(",
")",
")",
")",
"scope",
".",
"update",
"(",
"(",
"_PrefixWithDot",
"(",
"enum",
".",
"full_name",
")",
",",
"enum",
")",
"for",
"enum",
"in",
"dependency",
".",
"enum_types_by_name",
".",
"values",
"(",
")",
")",
"for",
"message_type",
"in",
"file_proto",
".",
"message_type",
":",
"message_desc",
"=",
"self",
".",
"_ConvertMessageDescriptor",
"(",
"message_type",
",",
"file_proto",
".",
"package",
",",
"file_descriptor",
",",
"scope",
",",
"file_proto",
".",
"syntax",
")",
"file_descriptor",
".",
"message_types_by_name",
"[",
"message_desc",
".",
"name",
"]",
"=",
"(",
"message_desc",
")",
"for",
"enum_type",
"in",
"file_proto",
".",
"enum_type",
":",
"file_descriptor",
".",
"enum_types_by_name",
"[",
"enum_type",
".",
"name",
"]",
"=",
"(",
"self",
".",
"_ConvertEnumDescriptor",
"(",
"enum_type",
",",
"file_proto",
".",
"package",
",",
"file_descriptor",
",",
"None",
",",
"scope",
")",
")",
"for",
"index",
",",
"extension_proto",
"in",
"enumerate",
"(",
"file_proto",
".",
"extension",
")",
":",
"extension_desc",
"=",
"self",
".",
"_MakeFieldDescriptor",
"(",
"extension_proto",
",",
"file_proto",
".",
"package",
",",
"index",
",",
"is_extension",
"=",
"True",
")",
"extension_desc",
".",
"containing_type",
"=",
"self",
".",
"_GetTypeFromScope",
"(",
"file_descriptor",
".",
"package",
",",
"extension_proto",
".",
"extendee",
",",
"scope",
")",
"self",
".",
"_SetFieldType",
"(",
"extension_proto",
",",
"extension_desc",
",",
"file_descriptor",
".",
"package",
",",
"scope",
")",
"file_descriptor",
".",
"extensions_by_name",
"[",
"extension_desc",
".",
"name",
"]",
"=",
"(",
"extension_desc",
")",
"for",
"desc_proto",
"in",
"file_proto",
".",
"message_type",
":",
"self",
".",
"_SetAllFieldTypes",
"(",
"file_proto",
".",
"package",
",",
"desc_proto",
",",
"scope",
")",
"if",
"file_proto",
".",
"package",
":",
"desc_proto_prefix",
"=",
"_PrefixWithDot",
"(",
"file_proto",
".",
"package",
")",
"else",
":",
"desc_proto_prefix",
"=",
"''",
"for",
"desc_proto",
"in",
"file_proto",
".",
"message_type",
":",
"desc",
"=",
"self",
".",
"_GetTypeFromScope",
"(",
"desc_proto_prefix",
",",
"desc_proto",
".",
"name",
",",
"scope",
")",
"file_descriptor",
".",
"message_types_by_name",
"[",
"desc_proto",
".",
"name",
"]",
"=",
"desc",
"for",
"index",
",",
"service_proto",
"in",
"enumerate",
"(",
"file_proto",
".",
"service",
")",
":",
"file_descriptor",
".",
"services_by_name",
"[",
"service_proto",
".",
"name",
"]",
"=",
"(",
"self",
".",
"_MakeServiceDescriptor",
"(",
"service_proto",
",",
"index",
",",
"scope",
",",
"file_proto",
".",
"package",
",",
"file_descriptor",
")",
")",
"self",
".",
"Add",
"(",
"file_proto",
")",
"self",
".",
"_file_descriptors",
"[",
"file_proto",
".",
"name",
"]",
"=",
"file_descriptor",
"return",
"self",
".",
"_file_descriptors",
"[",
"file_proto",
".",
"name",
"]"
] | Creates a FileDescriptor from a proto or returns a cached copy.
This method also has the side effect of loading all the symbols found in
the file into the appropriate dictionaries in the pool.
Args:
file_proto: The proto to convert.
Returns:
A FileDescriptor matching the passed in proto. | [
"Creates",
"a",
"FileDescriptor",
"from",
"a",
"proto",
"or",
"returns",
"a",
"cached",
"copy",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L507-L589 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._ConvertMessageDescriptor | def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,
scope=None, syntax=None):
"""Adds the proto to the pool in the specified package.
Args:
desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
package: The package the proto should be located in.
file_desc: The file containing this message.
scope: Dict mapping short and full symbols to message and enum types.
syntax: string indicating syntax of the file ("proto2" or "proto3")
Returns:
The added descriptor.
"""
if package:
desc_name = '.'.join((package, desc_proto.name))
else:
desc_name = desc_proto.name
if file_desc is None:
file_name = None
else:
file_name = file_desc.name
if scope is None:
scope = {}
nested = [
self._ConvertMessageDescriptor(
nested, desc_name, file_desc, scope, syntax)
for nested in desc_proto.nested_type]
enums = [
self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope)
for enum in desc_proto.enum_type]
fields = [self._MakeFieldDescriptor(field, desc_name, index)
for index, field in enumerate(desc_proto.field)]
extensions = [
self._MakeFieldDescriptor(extension, desc_name, index,
is_extension=True)
for index, extension in enumerate(desc_proto.extension)]
oneofs = [
descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)),
index, None, [], desc.options)
for index, desc in enumerate(desc_proto.oneof_decl)]
extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range]
if extension_ranges:
is_extendable = True
else:
is_extendable = False
desc = descriptor.Descriptor(
name=desc_proto.name,
full_name=desc_name,
filename=file_name,
containing_type=None,
fields=fields,
oneofs=oneofs,
nested_types=nested,
enum_types=enums,
extensions=extensions,
options=_OptionsOrNone(desc_proto),
is_extendable=is_extendable,
extension_ranges=extension_ranges,
file=file_desc,
serialized_start=None,
serialized_end=None,
syntax=syntax)
for nested in desc.nested_types:
nested.containing_type = desc
for enum in desc.enum_types:
enum.containing_type = desc
for field_index, field_desc in enumerate(desc_proto.field):
if field_desc.HasField('oneof_index'):
oneof_index = field_desc.oneof_index
oneofs[oneof_index].fields.append(fields[field_index])
fields[field_index].containing_oneof = oneofs[oneof_index]
scope[_PrefixWithDot(desc_name)] = desc
self._descriptors[desc_name] = desc
return desc | python | def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,
scope=None, syntax=None):
"""Adds the proto to the pool in the specified package.
Args:
desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
package: The package the proto should be located in.
file_desc: The file containing this message.
scope: Dict mapping short and full symbols to message and enum types.
syntax: string indicating syntax of the file ("proto2" or "proto3")
Returns:
The added descriptor.
"""
if package:
desc_name = '.'.join((package, desc_proto.name))
else:
desc_name = desc_proto.name
if file_desc is None:
file_name = None
else:
file_name = file_desc.name
if scope is None:
scope = {}
nested = [
self._ConvertMessageDescriptor(
nested, desc_name, file_desc, scope, syntax)
for nested in desc_proto.nested_type]
enums = [
self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope)
for enum in desc_proto.enum_type]
fields = [self._MakeFieldDescriptor(field, desc_name, index)
for index, field in enumerate(desc_proto.field)]
extensions = [
self._MakeFieldDescriptor(extension, desc_name, index,
is_extension=True)
for index, extension in enumerate(desc_proto.extension)]
oneofs = [
descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)),
index, None, [], desc.options)
for index, desc in enumerate(desc_proto.oneof_decl)]
extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range]
if extension_ranges:
is_extendable = True
else:
is_extendable = False
desc = descriptor.Descriptor(
name=desc_proto.name,
full_name=desc_name,
filename=file_name,
containing_type=None,
fields=fields,
oneofs=oneofs,
nested_types=nested,
enum_types=enums,
extensions=extensions,
options=_OptionsOrNone(desc_proto),
is_extendable=is_extendable,
extension_ranges=extension_ranges,
file=file_desc,
serialized_start=None,
serialized_end=None,
syntax=syntax)
for nested in desc.nested_types:
nested.containing_type = desc
for enum in desc.enum_types:
enum.containing_type = desc
for field_index, field_desc in enumerate(desc_proto.field):
if field_desc.HasField('oneof_index'):
oneof_index = field_desc.oneof_index
oneofs[oneof_index].fields.append(fields[field_index])
fields[field_index].containing_oneof = oneofs[oneof_index]
scope[_PrefixWithDot(desc_name)] = desc
self._descriptors[desc_name] = desc
return desc | [
"def",
"_ConvertMessageDescriptor",
"(",
"self",
",",
"desc_proto",
",",
"package",
"=",
"None",
",",
"file_desc",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"syntax",
"=",
"None",
")",
":",
"if",
"package",
":",
"desc_name",
"=",
"'.'",
".",
"join",
"(",
"(",
"package",
",",
"desc_proto",
".",
"name",
")",
")",
"else",
":",
"desc_name",
"=",
"desc_proto",
".",
"name",
"if",
"file_desc",
"is",
"None",
":",
"file_name",
"=",
"None",
"else",
":",
"file_name",
"=",
"file_desc",
".",
"name",
"if",
"scope",
"is",
"None",
":",
"scope",
"=",
"{",
"}",
"nested",
"=",
"[",
"self",
".",
"_ConvertMessageDescriptor",
"(",
"nested",
",",
"desc_name",
",",
"file_desc",
",",
"scope",
",",
"syntax",
")",
"for",
"nested",
"in",
"desc_proto",
".",
"nested_type",
"]",
"enums",
"=",
"[",
"self",
".",
"_ConvertEnumDescriptor",
"(",
"enum",
",",
"desc_name",
",",
"file_desc",
",",
"None",
",",
"scope",
")",
"for",
"enum",
"in",
"desc_proto",
".",
"enum_type",
"]",
"fields",
"=",
"[",
"self",
".",
"_MakeFieldDescriptor",
"(",
"field",
",",
"desc_name",
",",
"index",
")",
"for",
"index",
",",
"field",
"in",
"enumerate",
"(",
"desc_proto",
".",
"field",
")",
"]",
"extensions",
"=",
"[",
"self",
".",
"_MakeFieldDescriptor",
"(",
"extension",
",",
"desc_name",
",",
"index",
",",
"is_extension",
"=",
"True",
")",
"for",
"index",
",",
"extension",
"in",
"enumerate",
"(",
"desc_proto",
".",
"extension",
")",
"]",
"oneofs",
"=",
"[",
"descriptor",
".",
"OneofDescriptor",
"(",
"desc",
".",
"name",
",",
"'.'",
".",
"join",
"(",
"(",
"desc_name",
",",
"desc",
".",
"name",
")",
")",
",",
"index",
",",
"None",
",",
"[",
"]",
",",
"desc",
".",
"options",
")",
"for",
"index",
",",
"desc",
"in",
"enumerate",
"(",
"desc_proto",
".",
"oneof_decl",
")",
"]",
"extension_ranges",
"=",
"[",
"(",
"r",
".",
"start",
",",
"r",
".",
"end",
")",
"for",
"r",
"in",
"desc_proto",
".",
"extension_range",
"]",
"if",
"extension_ranges",
":",
"is_extendable",
"=",
"True",
"else",
":",
"is_extendable",
"=",
"False",
"desc",
"=",
"descriptor",
".",
"Descriptor",
"(",
"name",
"=",
"desc_proto",
".",
"name",
",",
"full_name",
"=",
"desc_name",
",",
"filename",
"=",
"file_name",
",",
"containing_type",
"=",
"None",
",",
"fields",
"=",
"fields",
",",
"oneofs",
"=",
"oneofs",
",",
"nested_types",
"=",
"nested",
",",
"enum_types",
"=",
"enums",
",",
"extensions",
"=",
"extensions",
",",
"options",
"=",
"_OptionsOrNone",
"(",
"desc_proto",
")",
",",
"is_extendable",
"=",
"is_extendable",
",",
"extension_ranges",
"=",
"extension_ranges",
",",
"file",
"=",
"file_desc",
",",
"serialized_start",
"=",
"None",
",",
"serialized_end",
"=",
"None",
",",
"syntax",
"=",
"syntax",
")",
"for",
"nested",
"in",
"desc",
".",
"nested_types",
":",
"nested",
".",
"containing_type",
"=",
"desc",
"for",
"enum",
"in",
"desc",
".",
"enum_types",
":",
"enum",
".",
"containing_type",
"=",
"desc",
"for",
"field_index",
",",
"field_desc",
"in",
"enumerate",
"(",
"desc_proto",
".",
"field",
")",
":",
"if",
"field_desc",
".",
"HasField",
"(",
"'oneof_index'",
")",
":",
"oneof_index",
"=",
"field_desc",
".",
"oneof_index",
"oneofs",
"[",
"oneof_index",
"]",
".",
"fields",
".",
"append",
"(",
"fields",
"[",
"field_index",
"]",
")",
"fields",
"[",
"field_index",
"]",
".",
"containing_oneof",
"=",
"oneofs",
"[",
"oneof_index",
"]",
"scope",
"[",
"_PrefixWithDot",
"(",
"desc_name",
")",
"]",
"=",
"desc",
"self",
".",
"_descriptors",
"[",
"desc_name",
"]",
"=",
"desc",
"return",
"desc"
] | Adds the proto to the pool in the specified package.
Args:
desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
package: The package the proto should be located in.
file_desc: The file containing this message.
scope: Dict mapping short and full symbols to message and enum types.
syntax: string indicating syntax of the file ("proto2" or "proto3")
Returns:
The added descriptor. | [
"Adds",
"the",
"proto",
"to",
"the",
"pool",
"in",
"the",
"specified",
"package",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L591-L670 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._SetAllFieldTypes | def _SetAllFieldTypes(self, package, desc_proto, scope):
"""Sets all the descriptor's fields's types.
This method also sets the containing types on any extensions.
Args:
package: The current package of desc_proto.
desc_proto: The message descriptor to update.
scope: Enclosing scope of available types.
"""
package = _PrefixWithDot(package)
main_desc = self._GetTypeFromScope(package, desc_proto.name, scope)
if package == '.':
nested_package = _PrefixWithDot(desc_proto.name)
else:
nested_package = '.'.join([package, desc_proto.name])
for field_proto, field_desc in zip(desc_proto.field, main_desc.fields):
self._SetFieldType(field_proto, field_desc, nested_package, scope)
for extension_proto, extension_desc in (
zip(desc_proto.extension, main_desc.extensions)):
extension_desc.containing_type = self._GetTypeFromScope(
nested_package, extension_proto.extendee, scope)
self._SetFieldType(extension_proto, extension_desc, nested_package, scope)
for nested_type in desc_proto.nested_type:
self._SetAllFieldTypes(nested_package, nested_type, scope) | python | def _SetAllFieldTypes(self, package, desc_proto, scope):
"""Sets all the descriptor's fields's types.
This method also sets the containing types on any extensions.
Args:
package: The current package of desc_proto.
desc_proto: The message descriptor to update.
scope: Enclosing scope of available types.
"""
package = _PrefixWithDot(package)
main_desc = self._GetTypeFromScope(package, desc_proto.name, scope)
if package == '.':
nested_package = _PrefixWithDot(desc_proto.name)
else:
nested_package = '.'.join([package, desc_proto.name])
for field_proto, field_desc in zip(desc_proto.field, main_desc.fields):
self._SetFieldType(field_proto, field_desc, nested_package, scope)
for extension_proto, extension_desc in (
zip(desc_proto.extension, main_desc.extensions)):
extension_desc.containing_type = self._GetTypeFromScope(
nested_package, extension_proto.extendee, scope)
self._SetFieldType(extension_proto, extension_desc, nested_package, scope)
for nested_type in desc_proto.nested_type:
self._SetAllFieldTypes(nested_package, nested_type, scope) | [
"def",
"_SetAllFieldTypes",
"(",
"self",
",",
"package",
",",
"desc_proto",
",",
"scope",
")",
":",
"package",
"=",
"_PrefixWithDot",
"(",
"package",
")",
"main_desc",
"=",
"self",
".",
"_GetTypeFromScope",
"(",
"package",
",",
"desc_proto",
".",
"name",
",",
"scope",
")",
"if",
"package",
"==",
"'.'",
":",
"nested_package",
"=",
"_PrefixWithDot",
"(",
"desc_proto",
".",
"name",
")",
"else",
":",
"nested_package",
"=",
"'.'",
".",
"join",
"(",
"[",
"package",
",",
"desc_proto",
".",
"name",
"]",
")",
"for",
"field_proto",
",",
"field_desc",
"in",
"zip",
"(",
"desc_proto",
".",
"field",
",",
"main_desc",
".",
"fields",
")",
":",
"self",
".",
"_SetFieldType",
"(",
"field_proto",
",",
"field_desc",
",",
"nested_package",
",",
"scope",
")",
"for",
"extension_proto",
",",
"extension_desc",
"in",
"(",
"zip",
"(",
"desc_proto",
".",
"extension",
",",
"main_desc",
".",
"extensions",
")",
")",
":",
"extension_desc",
".",
"containing_type",
"=",
"self",
".",
"_GetTypeFromScope",
"(",
"nested_package",
",",
"extension_proto",
".",
"extendee",
",",
"scope",
")",
"self",
".",
"_SetFieldType",
"(",
"extension_proto",
",",
"extension_desc",
",",
"nested_package",
",",
"scope",
")",
"for",
"nested_type",
"in",
"desc_proto",
".",
"nested_type",
":",
"self",
".",
"_SetAllFieldTypes",
"(",
"nested_package",
",",
"nested_type",
",",
"scope",
")"
] | Sets all the descriptor's fields's types.
This method also sets the containing types on any extensions.
Args:
package: The current package of desc_proto.
desc_proto: The message descriptor to update.
scope: Enclosing scope of available types. | [
"Sets",
"all",
"the",
"descriptor",
"s",
"fields",
"s",
"types",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L752-L782 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._SetFieldType | def _SetFieldType(self, field_proto, field_desc, package, scope):
"""Sets the field's type, cpp_type, message_type and enum_type.
Args:
field_proto: Data about the field in proto format.
field_desc: The descriptor to modiy.
package: The package the field's container is in.
scope: Enclosing scope of available types.
"""
if field_proto.type_name:
desc = self._GetTypeFromScope(package, field_proto.type_name, scope)
else:
desc = None
if not field_proto.HasField('type'):
if isinstance(desc, descriptor.Descriptor):
field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE
else:
field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM
field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType(
field_proto.type)
if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE
or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP):
field_desc.message_type = desc
if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
field_desc.enum_type = desc
if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED:
field_desc.has_default_value = False
field_desc.default_value = []
elif field_proto.HasField('default_value'):
field_desc.has_default_value = True
if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
field_desc.default_value = float(field_proto.default_value)
elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
field_desc.default_value = field_proto.default_value
elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
field_desc.default_value = field_proto.default_value.lower() == 'true'
elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
field_desc.default_value = field_desc.enum_type.values_by_name[
field_proto.default_value].number
elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
field_desc.default_value = text_encoding.CUnescape(
field_proto.default_value)
else:
# All other types are of the "int" type.
field_desc.default_value = int(field_proto.default_value)
else:
field_desc.has_default_value = False
if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
field_desc.default_value = 0.0
elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
field_desc.default_value = u''
elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
field_desc.default_value = False
elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
field_desc.default_value = field_desc.enum_type.values[0].number
elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
field_desc.default_value = b''
else:
# All other types are of the "int" type.
field_desc.default_value = 0
field_desc.type = field_proto.type | python | def _SetFieldType(self, field_proto, field_desc, package, scope):
"""Sets the field's type, cpp_type, message_type and enum_type.
Args:
field_proto: Data about the field in proto format.
field_desc: The descriptor to modiy.
package: The package the field's container is in.
scope: Enclosing scope of available types.
"""
if field_proto.type_name:
desc = self._GetTypeFromScope(package, field_proto.type_name, scope)
else:
desc = None
if not field_proto.HasField('type'):
if isinstance(desc, descriptor.Descriptor):
field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE
else:
field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM
field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType(
field_proto.type)
if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE
or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP):
field_desc.message_type = desc
if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
field_desc.enum_type = desc
if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED:
field_desc.has_default_value = False
field_desc.default_value = []
elif field_proto.HasField('default_value'):
field_desc.has_default_value = True
if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
field_desc.default_value = float(field_proto.default_value)
elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
field_desc.default_value = field_proto.default_value
elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
field_desc.default_value = field_proto.default_value.lower() == 'true'
elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
field_desc.default_value = field_desc.enum_type.values_by_name[
field_proto.default_value].number
elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
field_desc.default_value = text_encoding.CUnescape(
field_proto.default_value)
else:
# All other types are of the "int" type.
field_desc.default_value = int(field_proto.default_value)
else:
field_desc.has_default_value = False
if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
field_desc.default_value = 0.0
elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
field_desc.default_value = u''
elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
field_desc.default_value = False
elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
field_desc.default_value = field_desc.enum_type.values[0].number
elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
field_desc.default_value = b''
else:
# All other types are of the "int" type.
field_desc.default_value = 0
field_desc.type = field_proto.type | [
"def",
"_SetFieldType",
"(",
"self",
",",
"field_proto",
",",
"field_desc",
",",
"package",
",",
"scope",
")",
":",
"if",
"field_proto",
".",
"type_name",
":",
"desc",
"=",
"self",
".",
"_GetTypeFromScope",
"(",
"package",
",",
"field_proto",
".",
"type_name",
",",
"scope",
")",
"else",
":",
"desc",
"=",
"None",
"if",
"not",
"field_proto",
".",
"HasField",
"(",
"'type'",
")",
":",
"if",
"isinstance",
"(",
"desc",
",",
"descriptor",
".",
"Descriptor",
")",
":",
"field_proto",
".",
"type",
"=",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_MESSAGE",
"else",
":",
"field_proto",
".",
"type",
"=",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_ENUM",
"field_desc",
".",
"cpp_type",
"=",
"descriptor",
".",
"FieldDescriptor",
".",
"ProtoTypeToCppProtoType",
"(",
"field_proto",
".",
"type",
")",
"if",
"(",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_MESSAGE",
"or",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_GROUP",
")",
":",
"field_desc",
".",
"message_type",
"=",
"desc",
"if",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_ENUM",
":",
"field_desc",
".",
"enum_type",
"=",
"desc",
"if",
"field_proto",
".",
"label",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"LABEL_REPEATED",
":",
"field_desc",
".",
"has_default_value",
"=",
"False",
"field_desc",
".",
"default_value",
"=",
"[",
"]",
"elif",
"field_proto",
".",
"HasField",
"(",
"'default_value'",
")",
":",
"field_desc",
".",
"has_default_value",
"=",
"True",
"if",
"(",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_DOUBLE",
"or",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_FLOAT",
")",
":",
"field_desc",
".",
"default_value",
"=",
"float",
"(",
"field_proto",
".",
"default_value",
")",
"elif",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_STRING",
":",
"field_desc",
".",
"default_value",
"=",
"field_proto",
".",
"default_value",
"elif",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_BOOL",
":",
"field_desc",
".",
"default_value",
"=",
"field_proto",
".",
"default_value",
".",
"lower",
"(",
")",
"==",
"'true'",
"elif",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_ENUM",
":",
"field_desc",
".",
"default_value",
"=",
"field_desc",
".",
"enum_type",
".",
"values_by_name",
"[",
"field_proto",
".",
"default_value",
"]",
".",
"number",
"elif",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_BYTES",
":",
"field_desc",
".",
"default_value",
"=",
"text_encoding",
".",
"CUnescape",
"(",
"field_proto",
".",
"default_value",
")",
"else",
":",
"# All other types are of the \"int\" type.",
"field_desc",
".",
"default_value",
"=",
"int",
"(",
"field_proto",
".",
"default_value",
")",
"else",
":",
"field_desc",
".",
"has_default_value",
"=",
"False",
"if",
"(",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_DOUBLE",
"or",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_FLOAT",
")",
":",
"field_desc",
".",
"default_value",
"=",
"0.0",
"elif",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_STRING",
":",
"field_desc",
".",
"default_value",
"=",
"u''",
"elif",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_BOOL",
":",
"field_desc",
".",
"default_value",
"=",
"False",
"elif",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_ENUM",
":",
"field_desc",
".",
"default_value",
"=",
"field_desc",
".",
"enum_type",
".",
"values",
"[",
"0",
"]",
".",
"number",
"elif",
"field_proto",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_BYTES",
":",
"field_desc",
".",
"default_value",
"=",
"b''",
"else",
":",
"# All other types are of the \"int\" type.",
"field_desc",
".",
"default_value",
"=",
"0",
"field_desc",
".",
"type",
"=",
"field_proto",
".",
"type"
] | Sets the field's type, cpp_type, message_type and enum_type.
Args:
field_proto: Data about the field in proto format.
field_desc: The descriptor to modiy.
package: The package the field's container is in.
scope: Enclosing scope of available types. | [
"Sets",
"the",
"field",
"s",
"type",
"cpp_type",
"message_type",
"and",
"enum_type",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L784-L852 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._MakeEnumValueDescriptor | def _MakeEnumValueDescriptor(self, value_proto, index):
"""Creates a enum value descriptor object from a enum value proto.
Args:
value_proto: The proto describing the enum value.
index: The index of the enum value.
Returns:
An initialized EnumValueDescriptor object.
"""
return descriptor.EnumValueDescriptor(
name=value_proto.name,
index=index,
number=value_proto.number,
options=_OptionsOrNone(value_proto),
type=None) | python | def _MakeEnumValueDescriptor(self, value_proto, index):
"""Creates a enum value descriptor object from a enum value proto.
Args:
value_proto: The proto describing the enum value.
index: The index of the enum value.
Returns:
An initialized EnumValueDescriptor object.
"""
return descriptor.EnumValueDescriptor(
name=value_proto.name,
index=index,
number=value_proto.number,
options=_OptionsOrNone(value_proto),
type=None) | [
"def",
"_MakeEnumValueDescriptor",
"(",
"self",
",",
"value_proto",
",",
"index",
")",
":",
"return",
"descriptor",
".",
"EnumValueDescriptor",
"(",
"name",
"=",
"value_proto",
".",
"name",
",",
"index",
"=",
"index",
",",
"number",
"=",
"value_proto",
".",
"number",
",",
"options",
"=",
"_OptionsOrNone",
"(",
"value_proto",
")",
",",
"type",
"=",
"None",
")"
] | Creates a enum value descriptor object from a enum value proto.
Args:
value_proto: The proto describing the enum value.
index: The index of the enum value.
Returns:
An initialized EnumValueDescriptor object. | [
"Creates",
"a",
"enum",
"value",
"descriptor",
"object",
"from",
"a",
"enum",
"value",
"proto",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L854-L870 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._MakeServiceDescriptor | def _MakeServiceDescriptor(self, service_proto, service_index, scope,
package, file_desc):
"""Make a protobuf ServiceDescriptor given a ServiceDescriptorProto.
Args:
service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message.
service_index: The index of the service in the File.
scope: Dict mapping short and full symbols to message and enum types.
package: Optional package name for the new message EnumDescriptor.
file_desc: The file containing the service descriptor.
Returns:
The added descriptor.
"""
if package:
service_name = '.'.join((package, service_proto.name))
else:
service_name = service_proto.name
methods = [self._MakeMethodDescriptor(method_proto, service_name, package,
scope, index)
for index, method_proto in enumerate(service_proto.method)]
desc = descriptor.ServiceDescriptor(name=service_proto.name,
full_name=service_name,
index=service_index,
methods=methods,
options=_OptionsOrNone(service_proto),
file=file_desc)
self._service_descriptors[service_name] = desc
return desc | python | def _MakeServiceDescriptor(self, service_proto, service_index, scope,
package, file_desc):
"""Make a protobuf ServiceDescriptor given a ServiceDescriptorProto.
Args:
service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message.
service_index: The index of the service in the File.
scope: Dict mapping short and full symbols to message and enum types.
package: Optional package name for the new message EnumDescriptor.
file_desc: The file containing the service descriptor.
Returns:
The added descriptor.
"""
if package:
service_name = '.'.join((package, service_proto.name))
else:
service_name = service_proto.name
methods = [self._MakeMethodDescriptor(method_proto, service_name, package,
scope, index)
for index, method_proto in enumerate(service_proto.method)]
desc = descriptor.ServiceDescriptor(name=service_proto.name,
full_name=service_name,
index=service_index,
methods=methods,
options=_OptionsOrNone(service_proto),
file=file_desc)
self._service_descriptors[service_name] = desc
return desc | [
"def",
"_MakeServiceDescriptor",
"(",
"self",
",",
"service_proto",
",",
"service_index",
",",
"scope",
",",
"package",
",",
"file_desc",
")",
":",
"if",
"package",
":",
"service_name",
"=",
"'.'",
".",
"join",
"(",
"(",
"package",
",",
"service_proto",
".",
"name",
")",
")",
"else",
":",
"service_name",
"=",
"service_proto",
".",
"name",
"methods",
"=",
"[",
"self",
".",
"_MakeMethodDescriptor",
"(",
"method_proto",
",",
"service_name",
",",
"package",
",",
"scope",
",",
"index",
")",
"for",
"index",
",",
"method_proto",
"in",
"enumerate",
"(",
"service_proto",
".",
"method",
")",
"]",
"desc",
"=",
"descriptor",
".",
"ServiceDescriptor",
"(",
"name",
"=",
"service_proto",
".",
"name",
",",
"full_name",
"=",
"service_name",
",",
"index",
"=",
"service_index",
",",
"methods",
"=",
"methods",
",",
"options",
"=",
"_OptionsOrNone",
"(",
"service_proto",
")",
",",
"file",
"=",
"file_desc",
")",
"self",
".",
"_service_descriptors",
"[",
"service_name",
"]",
"=",
"desc",
"return",
"desc"
] | Make a protobuf ServiceDescriptor given a ServiceDescriptorProto.
Args:
service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message.
service_index: The index of the service in the File.
scope: Dict mapping short and full symbols to message and enum types.
package: Optional package name for the new message EnumDescriptor.
file_desc: The file containing the service descriptor.
Returns:
The added descriptor. | [
"Make",
"a",
"protobuf",
"ServiceDescriptor",
"given",
"a",
"ServiceDescriptorProto",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L872-L902 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._MakeMethodDescriptor | def _MakeMethodDescriptor(self, method_proto, service_name, package, scope,
index):
"""Creates a method descriptor from a MethodDescriptorProto.
Args:
method_proto: The proto describing the method.
service_name: The name of the containing service.
package: Optional package name to look up for types.
scope: Scope containing available types.
index: Index of the method in the service.
Returns:
An initialized MethodDescriptor object.
"""
full_name = '.'.join((service_name, method_proto.name))
input_type = self._GetTypeFromScope(
package, method_proto.input_type, scope)
output_type = self._GetTypeFromScope(
package, method_proto.output_type, scope)
return descriptor.MethodDescriptor(name=method_proto.name,
full_name=full_name,
index=index,
containing_service=None,
input_type=input_type,
output_type=output_type,
options=_OptionsOrNone(method_proto)) | python | def _MakeMethodDescriptor(self, method_proto, service_name, package, scope,
index):
"""Creates a method descriptor from a MethodDescriptorProto.
Args:
method_proto: The proto describing the method.
service_name: The name of the containing service.
package: Optional package name to look up for types.
scope: Scope containing available types.
index: Index of the method in the service.
Returns:
An initialized MethodDescriptor object.
"""
full_name = '.'.join((service_name, method_proto.name))
input_type = self._GetTypeFromScope(
package, method_proto.input_type, scope)
output_type = self._GetTypeFromScope(
package, method_proto.output_type, scope)
return descriptor.MethodDescriptor(name=method_proto.name,
full_name=full_name,
index=index,
containing_service=None,
input_type=input_type,
output_type=output_type,
options=_OptionsOrNone(method_proto)) | [
"def",
"_MakeMethodDescriptor",
"(",
"self",
",",
"method_proto",
",",
"service_name",
",",
"package",
",",
"scope",
",",
"index",
")",
":",
"full_name",
"=",
"'.'",
".",
"join",
"(",
"(",
"service_name",
",",
"method_proto",
".",
"name",
")",
")",
"input_type",
"=",
"self",
".",
"_GetTypeFromScope",
"(",
"package",
",",
"method_proto",
".",
"input_type",
",",
"scope",
")",
"output_type",
"=",
"self",
".",
"_GetTypeFromScope",
"(",
"package",
",",
"method_proto",
".",
"output_type",
",",
"scope",
")",
"return",
"descriptor",
".",
"MethodDescriptor",
"(",
"name",
"=",
"method_proto",
".",
"name",
",",
"full_name",
"=",
"full_name",
",",
"index",
"=",
"index",
",",
"containing_service",
"=",
"None",
",",
"input_type",
"=",
"input_type",
",",
"output_type",
"=",
"output_type",
",",
"options",
"=",
"_OptionsOrNone",
"(",
"method_proto",
")",
")"
] | Creates a method descriptor from a MethodDescriptorProto.
Args:
method_proto: The proto describing the method.
service_name: The name of the containing service.
package: Optional package name to look up for types.
scope: Scope containing available types.
index: Index of the method in the service.
Returns:
An initialized MethodDescriptor object. | [
"Creates",
"a",
"method",
"descriptor",
"from",
"a",
"MethodDescriptorProto",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L904-L929 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._ExtractSymbols | def _ExtractSymbols(self, descriptors):
"""Pulls out all the symbols from descriptor protos.
Args:
descriptors: The messages to extract descriptors from.
Yields:
A two element tuple of the type name and descriptor object.
"""
for desc in descriptors:
yield (_PrefixWithDot(desc.full_name), desc)
for symbol in self._ExtractSymbols(desc.nested_types):
yield symbol
for enum in desc.enum_types:
yield (_PrefixWithDot(enum.full_name), enum) | python | def _ExtractSymbols(self, descriptors):
"""Pulls out all the symbols from descriptor protos.
Args:
descriptors: The messages to extract descriptors from.
Yields:
A two element tuple of the type name and descriptor object.
"""
for desc in descriptors:
yield (_PrefixWithDot(desc.full_name), desc)
for symbol in self._ExtractSymbols(desc.nested_types):
yield symbol
for enum in desc.enum_types:
yield (_PrefixWithDot(enum.full_name), enum) | [
"def",
"_ExtractSymbols",
"(",
"self",
",",
"descriptors",
")",
":",
"for",
"desc",
"in",
"descriptors",
":",
"yield",
"(",
"_PrefixWithDot",
"(",
"desc",
".",
"full_name",
")",
",",
"desc",
")",
"for",
"symbol",
"in",
"self",
".",
"_ExtractSymbols",
"(",
"desc",
".",
"nested_types",
")",
":",
"yield",
"symbol",
"for",
"enum",
"in",
"desc",
".",
"enum_types",
":",
"yield",
"(",
"_PrefixWithDot",
"(",
"enum",
".",
"full_name",
")",
",",
"enum",
")"
] | Pulls out all the symbols from descriptor protos.
Args:
descriptors: The messages to extract descriptors from.
Yields:
A two element tuple of the type name and descriptor object. | [
"Pulls",
"out",
"all",
"the",
"symbols",
"from",
"descriptor",
"protos",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L931-L945 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._GetDeps | def _GetDeps(self, dependencies):
"""Recursively finds dependencies for file protos.
Args:
dependencies: The names of the files being depended on.
Yields:
Each direct and indirect dependency.
"""
for dependency in dependencies:
dep_desc = self.FindFileByName(dependency)
yield dep_desc
for parent_dep in dep_desc.dependencies:
yield parent_dep | python | def _GetDeps(self, dependencies):
"""Recursively finds dependencies for file protos.
Args:
dependencies: The names of the files being depended on.
Yields:
Each direct and indirect dependency.
"""
for dependency in dependencies:
dep_desc = self.FindFileByName(dependency)
yield dep_desc
for parent_dep in dep_desc.dependencies:
yield parent_dep | [
"def",
"_GetDeps",
"(",
"self",
",",
"dependencies",
")",
":",
"for",
"dependency",
"in",
"dependencies",
":",
"dep_desc",
"=",
"self",
".",
"FindFileByName",
"(",
"dependency",
")",
"yield",
"dep_desc",
"for",
"parent_dep",
"in",
"dep_desc",
".",
"dependencies",
":",
"yield",
"parent_dep"
] | Recursively finds dependencies for file protos.
Args:
dependencies: The names of the files being depended on.
Yields:
Each direct and indirect dependency. | [
"Recursively",
"finds",
"dependencies",
"for",
"file",
"protos",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L947-L961 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | DescriptorPool._GetTypeFromScope | def _GetTypeFromScope(self, package, type_name, scope):
"""Finds a given type name in the current scope.
Args:
package: The package the proto should be located in.
type_name: The name of the type to be found in the scope.
scope: Dict mapping short and full symbols to message and enum types.
Returns:
The descriptor for the requested type.
"""
if type_name not in scope:
components = _PrefixWithDot(package).split('.')
while components:
possible_match = '.'.join(components + [type_name])
if possible_match in scope:
type_name = possible_match
break
else:
components.pop(-1)
return scope[type_name] | python | def _GetTypeFromScope(self, package, type_name, scope):
"""Finds a given type name in the current scope.
Args:
package: The package the proto should be located in.
type_name: The name of the type to be found in the scope.
scope: Dict mapping short and full symbols to message and enum types.
Returns:
The descriptor for the requested type.
"""
if type_name not in scope:
components = _PrefixWithDot(package).split('.')
while components:
possible_match = '.'.join(components + [type_name])
if possible_match in scope:
type_name = possible_match
break
else:
components.pop(-1)
return scope[type_name] | [
"def",
"_GetTypeFromScope",
"(",
"self",
",",
"package",
",",
"type_name",
",",
"scope",
")",
":",
"if",
"type_name",
"not",
"in",
"scope",
":",
"components",
"=",
"_PrefixWithDot",
"(",
"package",
")",
".",
"split",
"(",
"'.'",
")",
"while",
"components",
":",
"possible_match",
"=",
"'.'",
".",
"join",
"(",
"components",
"+",
"[",
"type_name",
"]",
")",
"if",
"possible_match",
"in",
"scope",
":",
"type_name",
"=",
"possible_match",
"break",
"else",
":",
"components",
".",
"pop",
"(",
"-",
"1",
")",
"return",
"scope",
"[",
"type_name",
"]"
] | Finds a given type name in the current scope.
Args:
package: The package the proto should be located in.
type_name: The name of the type to be found in the scope.
scope: Dict mapping short and full symbols to message and enum types.
Returns:
The descriptor for the requested type. | [
"Finds",
"a",
"given",
"type",
"name",
"in",
"the",
"current",
"scope",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L963-L983 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/sequence.py | max_element | def max_element (elements, ordered = None):
""" Returns the maximum number in 'elements'. Uses 'ordered' for comparisons,
or '<' is none is provided.
"""
assert is_iterable(elements)
assert callable(ordered) or ordered is None
if not ordered: ordered = operator.lt
max = elements [0]
for e in elements [1:]:
if ordered (max, e):
max = e
return max | python | def max_element (elements, ordered = None):
""" Returns the maximum number in 'elements'. Uses 'ordered' for comparisons,
or '<' is none is provided.
"""
assert is_iterable(elements)
assert callable(ordered) or ordered is None
if not ordered: ordered = operator.lt
max = elements [0]
for e in elements [1:]:
if ordered (max, e):
max = e
return max | [
"def",
"max_element",
"(",
"elements",
",",
"ordered",
"=",
"None",
")",
":",
"assert",
"is_iterable",
"(",
"elements",
")",
"assert",
"callable",
"(",
"ordered",
")",
"or",
"ordered",
"is",
"None",
"if",
"not",
"ordered",
":",
"ordered",
"=",
"operator",
".",
"lt",
"max",
"=",
"elements",
"[",
"0",
"]",
"for",
"e",
"in",
"elements",
"[",
"1",
":",
"]",
":",
"if",
"ordered",
"(",
"max",
",",
"e",
")",
":",
"max",
"=",
"e",
"return",
"max"
] | Returns the maximum number in 'elements'. Uses 'ordered' for comparisons,
or '<' is none is provided. | [
"Returns",
"the",
"maximum",
"number",
"in",
"elements",
".",
"Uses",
"ordered",
"for",
"comparisons",
"or",
"<",
"is",
"none",
"is",
"provided",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/sequence.py#L24-L37 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/sequence.py | select_highest_ranked | def select_highest_ranked (elements, ranks):
""" Returns all of 'elements' for which corresponding element in parallel
list 'rank' is equal to the maximum value in 'rank'.
"""
assert is_iterable(elements)
assert is_iterable(ranks)
if not elements:
return []
max_rank = max_element (ranks)
result = []
while elements:
if ranks [0] == max_rank:
result.append (elements [0])
elements = elements [1:]
ranks = ranks [1:]
return result | python | def select_highest_ranked (elements, ranks):
""" Returns all of 'elements' for which corresponding element in parallel
list 'rank' is equal to the maximum value in 'rank'.
"""
assert is_iterable(elements)
assert is_iterable(ranks)
if not elements:
return []
max_rank = max_element (ranks)
result = []
while elements:
if ranks [0] == max_rank:
result.append (elements [0])
elements = elements [1:]
ranks = ranks [1:]
return result | [
"def",
"select_highest_ranked",
"(",
"elements",
",",
"ranks",
")",
":",
"assert",
"is_iterable",
"(",
"elements",
")",
"assert",
"is_iterable",
"(",
"ranks",
")",
"if",
"not",
"elements",
":",
"return",
"[",
"]",
"max_rank",
"=",
"max_element",
"(",
"ranks",
")",
"result",
"=",
"[",
"]",
"while",
"elements",
":",
"if",
"ranks",
"[",
"0",
"]",
"==",
"max_rank",
":",
"result",
".",
"append",
"(",
"elements",
"[",
"0",
"]",
")",
"elements",
"=",
"elements",
"[",
"1",
":",
"]",
"ranks",
"=",
"ranks",
"[",
"1",
":",
"]",
"return",
"result"
] | Returns all of 'elements' for which corresponding element in parallel
list 'rank' is equal to the maximum value in 'rank'. | [
"Returns",
"all",
"of",
"elements",
"for",
"which",
"corresponding",
"element",
"in",
"parallel",
"list",
"rank",
"is",
"equal",
"to",
"the",
"maximum",
"value",
"in",
"rank",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/sequence.py#L39-L58 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/message.py | Message.CopyFrom | def CopyFrom(self, other_msg):
"""Copies the content of the specified message into the current message.
The method clears the current message and then merges the specified
message using MergeFrom.
Args:
other_msg: Message to copy into the current one.
"""
if self is other_msg:
return
self.Clear()
self.MergeFrom(other_msg) | python | def CopyFrom(self, other_msg):
"""Copies the content of the specified message into the current message.
The method clears the current message and then merges the specified
message using MergeFrom.
Args:
other_msg: Message to copy into the current one.
"""
if self is other_msg:
return
self.Clear()
self.MergeFrom(other_msg) | [
"def",
"CopyFrom",
"(",
"self",
",",
"other_msg",
")",
":",
"if",
"self",
"is",
"other_msg",
":",
"return",
"self",
".",
"Clear",
"(",
")",
"self",
".",
"MergeFrom",
"(",
"other_msg",
")"
] | Copies the content of the specified message into the current message.
The method clears the current message and then merges the specified
message using MergeFrom.
Args:
other_msg: Message to copy into the current one. | [
"Copies",
"the",
"content",
"of",
"the",
"specified",
"message",
"into",
"the",
"current",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/message.py#L106-L118 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/xgboost/_tree_ensemble.py | recurse_json | def recurse_json(mlkit_tree, xgb_tree_json, tree_id, node_id, feature_map,
force_32bit_float):
"""Traverse through the tree and append to the tree spec.
"""
relative_hit_rate = None
try:
relative_hit_rate = xgb_tree_json['cover']
except KeyError:
pass
# Fill node attributes
if 'leaf' not in xgb_tree_json:
branch_mode = 'BranchOnValueLessThan'
split_name = xgb_tree_json['split']
feature_index = split_name if not feature_map else feature_map[split_name]
# xgboost internally uses float32, but the parsing from json pulls it out
# as a 64bit double. To trigger the internal float32 detection in the
# tree ensemble compiler, we need to explicitly cast it to a float 32
# value, then back to the 64 bit float that protobuf expects. This is
# controlled with the force_32bit_float flag.
feature_value = xgb_tree_json['split_condition']
if force_32bit_float:
feature_value = float(_np.float32(feature_value))
true_child_id = xgb_tree_json['yes']
false_child_id = xgb_tree_json['no']
# Get the missing value behavior correct
missing_value_tracks_true_child = False
try:
if xgb_tree_json['missing'] == true_child_id:
missing_value_tracks_true_child = True
except KeyError:
pass
mlkit_tree.add_branch_node(tree_id, node_id, feature_index,
feature_value, branch_mode, true_child_id, false_child_id,
relative_hit_rate = relative_hit_rate,
missing_value_tracks_true_child = missing_value_tracks_true_child)
else:
value = xgb_tree_json["leaf"]
if force_32bit_float:
value = float(_np.float32(value))
mlkit_tree.add_leaf_node(tree_id, node_id, value,
relative_hit_rate = relative_hit_rate)
# Now recurse
if "children" in xgb_tree_json:
for child in xgb_tree_json["children"]:
recurse_json(mlkit_tree, child, tree_id, child['nodeid'], feature_map, force_32bit_float) | python | def recurse_json(mlkit_tree, xgb_tree_json, tree_id, node_id, feature_map,
force_32bit_float):
"""Traverse through the tree and append to the tree spec.
"""
relative_hit_rate = None
try:
relative_hit_rate = xgb_tree_json['cover']
except KeyError:
pass
# Fill node attributes
if 'leaf' not in xgb_tree_json:
branch_mode = 'BranchOnValueLessThan'
split_name = xgb_tree_json['split']
feature_index = split_name if not feature_map else feature_map[split_name]
# xgboost internally uses float32, but the parsing from json pulls it out
# as a 64bit double. To trigger the internal float32 detection in the
# tree ensemble compiler, we need to explicitly cast it to a float 32
# value, then back to the 64 bit float that protobuf expects. This is
# controlled with the force_32bit_float flag.
feature_value = xgb_tree_json['split_condition']
if force_32bit_float:
feature_value = float(_np.float32(feature_value))
true_child_id = xgb_tree_json['yes']
false_child_id = xgb_tree_json['no']
# Get the missing value behavior correct
missing_value_tracks_true_child = False
try:
if xgb_tree_json['missing'] == true_child_id:
missing_value_tracks_true_child = True
except KeyError:
pass
mlkit_tree.add_branch_node(tree_id, node_id, feature_index,
feature_value, branch_mode, true_child_id, false_child_id,
relative_hit_rate = relative_hit_rate,
missing_value_tracks_true_child = missing_value_tracks_true_child)
else:
value = xgb_tree_json["leaf"]
if force_32bit_float:
value = float(_np.float32(value))
mlkit_tree.add_leaf_node(tree_id, node_id, value,
relative_hit_rate = relative_hit_rate)
# Now recurse
if "children" in xgb_tree_json:
for child in xgb_tree_json["children"]:
recurse_json(mlkit_tree, child, tree_id, child['nodeid'], feature_map, force_32bit_float) | [
"def",
"recurse_json",
"(",
"mlkit_tree",
",",
"xgb_tree_json",
",",
"tree_id",
",",
"node_id",
",",
"feature_map",
",",
"force_32bit_float",
")",
":",
"relative_hit_rate",
"=",
"None",
"try",
":",
"relative_hit_rate",
"=",
"xgb_tree_json",
"[",
"'cover'",
"]",
"except",
"KeyError",
":",
"pass",
"# Fill node attributes",
"if",
"'leaf'",
"not",
"in",
"xgb_tree_json",
":",
"branch_mode",
"=",
"'BranchOnValueLessThan'",
"split_name",
"=",
"xgb_tree_json",
"[",
"'split'",
"]",
"feature_index",
"=",
"split_name",
"if",
"not",
"feature_map",
"else",
"feature_map",
"[",
"split_name",
"]",
"# xgboost internally uses float32, but the parsing from json pulls it out",
"# as a 64bit double. To trigger the internal float32 detection in the",
"# tree ensemble compiler, we need to explicitly cast it to a float 32",
"# value, then back to the 64 bit float that protobuf expects. This is",
"# controlled with the force_32bit_float flag.",
"feature_value",
"=",
"xgb_tree_json",
"[",
"'split_condition'",
"]",
"if",
"force_32bit_float",
":",
"feature_value",
"=",
"float",
"(",
"_np",
".",
"float32",
"(",
"feature_value",
")",
")",
"true_child_id",
"=",
"xgb_tree_json",
"[",
"'yes'",
"]",
"false_child_id",
"=",
"xgb_tree_json",
"[",
"'no'",
"]",
"# Get the missing value behavior correct",
"missing_value_tracks_true_child",
"=",
"False",
"try",
":",
"if",
"xgb_tree_json",
"[",
"'missing'",
"]",
"==",
"true_child_id",
":",
"missing_value_tracks_true_child",
"=",
"True",
"except",
"KeyError",
":",
"pass",
"mlkit_tree",
".",
"add_branch_node",
"(",
"tree_id",
",",
"node_id",
",",
"feature_index",
",",
"feature_value",
",",
"branch_mode",
",",
"true_child_id",
",",
"false_child_id",
",",
"relative_hit_rate",
"=",
"relative_hit_rate",
",",
"missing_value_tracks_true_child",
"=",
"missing_value_tracks_true_child",
")",
"else",
":",
"value",
"=",
"xgb_tree_json",
"[",
"\"leaf\"",
"]",
"if",
"force_32bit_float",
":",
"value",
"=",
"float",
"(",
"_np",
".",
"float32",
"(",
"value",
")",
")",
"mlkit_tree",
".",
"add_leaf_node",
"(",
"tree_id",
",",
"node_id",
",",
"value",
",",
"relative_hit_rate",
"=",
"relative_hit_rate",
")",
"# Now recurse",
"if",
"\"children\"",
"in",
"xgb_tree_json",
":",
"for",
"child",
"in",
"xgb_tree_json",
"[",
"\"children\"",
"]",
":",
"recurse_json",
"(",
"mlkit_tree",
",",
"child",
",",
"tree_id",
",",
"child",
"[",
"'nodeid'",
"]",
",",
"feature_map",
",",
"force_32bit_float",
")"
] | Traverse through the tree and append to the tree spec. | [
"Traverse",
"through",
"the",
"tree",
"and",
"append",
"to",
"the",
"tree",
"spec",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/xgboost/_tree_ensemble.py#L15-L73 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/xgboost/_tree_ensemble.py | convert_tree_ensemble | def convert_tree_ensemble(model, feature_names, target, force_32bit_float):
"""Convert a generic tree model to the protobuf spec.
This currently supports:
* Decision tree regression
Parameters
----------
model: str | Booster
Path on disk where the XGboost JSON representation of the model is or
a handle to the XGboost model.
feature_names : list of strings or None
Names of each of the features. When set to None, the feature names are
extracted from the model.
target: str,
Name of the output column.
force_32bit_float: bool
If True, then the resulting CoreML model will use 32 bit floats internally.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_XGBOOST):
raise RuntimeError('xgboost not found. xgboost conversion API is disabled.')
import json
import os
feature_map = None
if isinstance(model, (_xgboost.core.Booster, _xgboost.XGBRegressor)):
# Testing a few corner cases that we don't support
if isinstance(model, _xgboost.XGBRegressor):
try:
objective = model.get_xgb_params()["objective"]
except:
objective = None
if objective in ["reg:gamma", "reg:tweedie"]:
raise ValueError("Regression objective '%s' not supported for export." % objective)
# Now use the booster API.
if isinstance(model, _xgboost.XGBRegressor):
# Name change in 0.7
if hasattr(model, 'get_booster'):
model = model.get_booster()
else:
model = model.booster()
# Xgboost sometimes has feature names in there. Sometimes does not.
if (feature_names is None) and (model.feature_names is None):
raise ValueError("Feature names not present in the model. Must be provided during conversion.")
feature_names = model.feature_names
if feature_names is None:
feature_names = model.feature_names
xgb_model_str = model.get_dump(with_stats=True, dump_format = 'json')
if model.feature_names:
feature_map = {f:i for i,f in enumerate(model.feature_names)}
# Path on the file system where the XGboost model exists.
elif isinstance(model, str):
if not os.path.exists(model):
raise TypeError("Invalid path %s." % model)
with open(model) as f:
xgb_model_str = json.load(f)
feature_map = {f:i for i,f in enumerate(feature_names)}
else:
raise TypeError("Unexpected type. Expecting XGBoost model.")
mlkit_tree = _TreeEnsembleRegressor(feature_names, target)
mlkit_tree.set_default_prediction_value(0.5)
for xgb_tree_id, xgb_tree_str in enumerate(xgb_model_str):
xgb_tree_json = json.loads(xgb_tree_str)
recurse_json(mlkit_tree, xgb_tree_json, xgb_tree_id, node_id = 0,
feature_map = feature_map, force_32bit_float = force_32bit_float)
return mlkit_tree.spec | python | def convert_tree_ensemble(model, feature_names, target, force_32bit_float):
"""Convert a generic tree model to the protobuf spec.
This currently supports:
* Decision tree regression
Parameters
----------
model: str | Booster
Path on disk where the XGboost JSON representation of the model is or
a handle to the XGboost model.
feature_names : list of strings or None
Names of each of the features. When set to None, the feature names are
extracted from the model.
target: str,
Name of the output column.
force_32bit_float: bool
If True, then the resulting CoreML model will use 32 bit floats internally.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_XGBOOST):
raise RuntimeError('xgboost not found. xgboost conversion API is disabled.')
import json
import os
feature_map = None
if isinstance(model, (_xgboost.core.Booster, _xgboost.XGBRegressor)):
# Testing a few corner cases that we don't support
if isinstance(model, _xgboost.XGBRegressor):
try:
objective = model.get_xgb_params()["objective"]
except:
objective = None
if objective in ["reg:gamma", "reg:tweedie"]:
raise ValueError("Regression objective '%s' not supported for export." % objective)
# Now use the booster API.
if isinstance(model, _xgboost.XGBRegressor):
# Name change in 0.7
if hasattr(model, 'get_booster'):
model = model.get_booster()
else:
model = model.booster()
# Xgboost sometimes has feature names in there. Sometimes does not.
if (feature_names is None) and (model.feature_names is None):
raise ValueError("Feature names not present in the model. Must be provided during conversion.")
feature_names = model.feature_names
if feature_names is None:
feature_names = model.feature_names
xgb_model_str = model.get_dump(with_stats=True, dump_format = 'json')
if model.feature_names:
feature_map = {f:i for i,f in enumerate(model.feature_names)}
# Path on the file system where the XGboost model exists.
elif isinstance(model, str):
if not os.path.exists(model):
raise TypeError("Invalid path %s." % model)
with open(model) as f:
xgb_model_str = json.load(f)
feature_map = {f:i for i,f in enumerate(feature_names)}
else:
raise TypeError("Unexpected type. Expecting XGBoost model.")
mlkit_tree = _TreeEnsembleRegressor(feature_names, target)
mlkit_tree.set_default_prediction_value(0.5)
for xgb_tree_id, xgb_tree_str in enumerate(xgb_model_str):
xgb_tree_json = json.loads(xgb_tree_str)
recurse_json(mlkit_tree, xgb_tree_json, xgb_tree_id, node_id = 0,
feature_map = feature_map, force_32bit_float = force_32bit_float)
return mlkit_tree.spec | [
"def",
"convert_tree_ensemble",
"(",
"model",
",",
"feature_names",
",",
"target",
",",
"force_32bit_float",
")",
":",
"if",
"not",
"(",
"_HAS_XGBOOST",
")",
":",
"raise",
"RuntimeError",
"(",
"'xgboost not found. xgboost conversion API is disabled.'",
")",
"import",
"json",
"import",
"os",
"feature_map",
"=",
"None",
"if",
"isinstance",
"(",
"model",
",",
"(",
"_xgboost",
".",
"core",
".",
"Booster",
",",
"_xgboost",
".",
"XGBRegressor",
")",
")",
":",
"# Testing a few corner cases that we don't support",
"if",
"isinstance",
"(",
"model",
",",
"_xgboost",
".",
"XGBRegressor",
")",
":",
"try",
":",
"objective",
"=",
"model",
".",
"get_xgb_params",
"(",
")",
"[",
"\"objective\"",
"]",
"except",
":",
"objective",
"=",
"None",
"if",
"objective",
"in",
"[",
"\"reg:gamma\"",
",",
"\"reg:tweedie\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"Regression objective '%s' not supported for export.\"",
"%",
"objective",
")",
"# Now use the booster API.",
"if",
"isinstance",
"(",
"model",
",",
"_xgboost",
".",
"XGBRegressor",
")",
":",
"# Name change in 0.7",
"if",
"hasattr",
"(",
"model",
",",
"'get_booster'",
")",
":",
"model",
"=",
"model",
".",
"get_booster",
"(",
")",
"else",
":",
"model",
"=",
"model",
".",
"booster",
"(",
")",
"# Xgboost sometimes has feature names in there. Sometimes does not.",
"if",
"(",
"feature_names",
"is",
"None",
")",
"and",
"(",
"model",
".",
"feature_names",
"is",
"None",
")",
":",
"raise",
"ValueError",
"(",
"\"Feature names not present in the model. Must be provided during conversion.\"",
")",
"feature_names",
"=",
"model",
".",
"feature_names",
"if",
"feature_names",
"is",
"None",
":",
"feature_names",
"=",
"model",
".",
"feature_names",
"xgb_model_str",
"=",
"model",
".",
"get_dump",
"(",
"with_stats",
"=",
"True",
",",
"dump_format",
"=",
"'json'",
")",
"if",
"model",
".",
"feature_names",
":",
"feature_map",
"=",
"{",
"f",
":",
"i",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"model",
".",
"feature_names",
")",
"}",
"# Path on the file system where the XGboost model exists.",
"elif",
"isinstance",
"(",
"model",
",",
"str",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"model",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid path %s.\"",
"%",
"model",
")",
"with",
"open",
"(",
"model",
")",
"as",
"f",
":",
"xgb_model_str",
"=",
"json",
".",
"load",
"(",
"f",
")",
"feature_map",
"=",
"{",
"f",
":",
"i",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"feature_names",
")",
"}",
"else",
":",
"raise",
"TypeError",
"(",
"\"Unexpected type. Expecting XGBoost model.\"",
")",
"mlkit_tree",
"=",
"_TreeEnsembleRegressor",
"(",
"feature_names",
",",
"target",
")",
"mlkit_tree",
".",
"set_default_prediction_value",
"(",
"0.5",
")",
"for",
"xgb_tree_id",
",",
"xgb_tree_str",
"in",
"enumerate",
"(",
"xgb_model_str",
")",
":",
"xgb_tree_json",
"=",
"json",
".",
"loads",
"(",
"xgb_tree_str",
")",
"recurse_json",
"(",
"mlkit_tree",
",",
"xgb_tree_json",
",",
"xgb_tree_id",
",",
"node_id",
"=",
"0",
",",
"feature_map",
"=",
"feature_map",
",",
"force_32bit_float",
"=",
"force_32bit_float",
")",
"return",
"mlkit_tree",
".",
"spec"
] | Convert a generic tree model to the protobuf spec.
This currently supports:
* Decision tree regression
Parameters
----------
model: str | Booster
Path on disk where the XGboost JSON representation of the model is or
a handle to the XGboost model.
feature_names : list of strings or None
Names of each of the features. When set to None, the feature names are
extracted from the model.
target: str,
Name of the output column.
force_32bit_float: bool
If True, then the resulting CoreML model will use 32 bit floats internally.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model | [
"Convert",
"a",
"generic",
"tree",
"model",
"to",
"the",
"protobuf",
"spec",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/xgboost/_tree_ensemble.py#L75-L156 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_one_hot_encoder.py | convert | def convert(model, input_features, output_features):
"""Convert a one-hot-encoder model to the protobuf spec.
Parameters
----------
model: OneHotEncoder
A trained one-hot encoder model.
input_features: str, optional
Name of the input column.
output_features: str, optional
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Make sure the model is fitted.
_sklearn_util.check_expected_type(model, OneHotEncoder)
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'active_features_'))
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'n_values_'))
input_dimension = get_input_dimension(model)
if input_dimension is not None:
# Make sure that our starting dimensions are correctly managed.
assert len(input_features) == 1
assert input_features[0][1] == datatypes.Array(input_dimension)
input_dimension = input_features[0][1].num_elements
expected_output_dimension = update_dimension(model, input_dimension)
assert output_features[0][1] == datatypes.Array(expected_output_dimension)
# Create a pipeline that can do all of the subsequent feature extraction.
feature_vectorizer_input_features = []
feature_vectorizer_size_map = {}
if model.categorical_features == 'all':
_categorical_features = set(range(input_dimension))
_cat_feature_idx_mapping = dict( (i, i) for i in range(input_dimension))
else:
_categorical_features = set(model.categorical_features)
_cat_feature_idx_mapping = dict( (_idx, i) for i, _idx in enumerate(sorted(model.categorical_features)))
pline = Pipeline(input_features, output_features)
# Track the overall packing index, which determines the output ordering.
pack_idx = 0
# First, go through all the columns that are encoded. The sklearn OHE puts
# all of these first, regardless of their original ordering.
for idx in range(input_dimension):
f_name = "__OHE_%d__" % pack_idx
if idx in _categorical_features:
# This input column is one hot encoded
feature_extractor_spec = create_array_feature_extractor(
input_features, f_name, idx, output_type = 'Int64')
pline.add_model(feature_extractor_spec)
_cat_feature_idx = _cat_feature_idx_mapping[idx]
ohe_input_features = [(f_name, datatypes.Int64())]
ohe_output_features = [(f_name, datatypes.Dictionary('Int64'))]
# Create a one hot encoder per column
o_spec = _Model_pb2.Model()
o_spec.specificationVersion = SPECIFICATION_VERSION
o_spec = set_transform_interface_params(o_spec, ohe_input_features, ohe_output_features)
ohe_spec = o_spec.oneHotEncoder
ohe_spec.outputSparse = True
if model.handle_unknown == 'error':
ohe_spec.handleUnknown = _OHE_pb2.OneHotEncoder.HandleUnknown.Value('ErrorOnUnknown')
else:
ohe_spec.handleUnknown = _OHE_pb2.OneHotEncoder.HandleUnknown.Value('IgnoreUnknown')
# Need to do a quick search to find the part of the active_features_ mask
# that represents the categorical variables in our part. Could do this
# with binary search, but we probably don't need speed so much here.
def bs_find(a, i):
lb, k = 0, len(a)
while k > 0:
_idx = lb + (k // 2)
if a[_idx] < i:
lb = _idx + 1
k -= 1
k = (k // 2)
return lb
# Here are the indices we are looking fo
f_idx_bottom = model.feature_indices_[_cat_feature_idx]
f_idx_top = model.feature_indices_[_cat_feature_idx + 1]
# Now find where in the active features list we should look.
cat_feat_idx_bottom = bs_find(model.active_features_, f_idx_bottom)
cat_feat_idx_top = bs_find(model.active_features_, f_idx_top)
n_cat_values = cat_feat_idx_top - cat_feat_idx_bottom
for i in range(cat_feat_idx_bottom, cat_feat_idx_top):
# The actual categorical value is stored as an offset in the active_features list.
cat_idx = model.active_features_[i] - f_idx_bottom
ohe_spec.int64Categories.vector.append(cat_idx)
# Add the ohe to the pipeline
pline.add_model(o_spec)
# Add the result to the feature_vectorizer at the end.
feature_vectorizer_input_features.append( (f_name, datatypes.Dictionary('Int64')) )
feature_vectorizer_size_map[f_name] = n_cat_values
pack_idx += 1
# Now go through all the columns that are not encoded as the sklearn OHE puts
# these after the encoded ones. For speed, we can put these all in a single
# ArrayFeatureExtractor
#
pass_through_features = [idx for idx in range(input_dimension)
if idx not in _categorical_features]
if pass_through_features:
f_name = "__OHE_pass_through__"
# This input column is not one hot encoded
feature_extractor_spec = create_array_feature_extractor(
input_features, f_name, pass_through_features)
pline.add_model(feature_extractor_spec)
feature_vectorizer_input_features.append(
(f_name, datatypes.Array(len(pass_through_features))) )
# Finally, add the feature vectorizer to the pipeline.
output_feature_name = output_features[0][0]
output_feature_dimension = output_features[0][1].num_elements
fvec, _num_out_dim = create_feature_vectorizer(feature_vectorizer_input_features,
output_features[0][0], feature_vectorizer_size_map)
# Make sure that the feature vectorizer input actually matches up with the
assert _num_out_dim == output_features[0][1].num_elements
pline.add_model(fvec)
return _MLModel(pline.spec) | python | def convert(model, input_features, output_features):
"""Convert a one-hot-encoder model to the protobuf spec.
Parameters
----------
model: OneHotEncoder
A trained one-hot encoder model.
input_features: str, optional
Name of the input column.
output_features: str, optional
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Make sure the model is fitted.
_sklearn_util.check_expected_type(model, OneHotEncoder)
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'active_features_'))
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'n_values_'))
input_dimension = get_input_dimension(model)
if input_dimension is not None:
# Make sure that our starting dimensions are correctly managed.
assert len(input_features) == 1
assert input_features[0][1] == datatypes.Array(input_dimension)
input_dimension = input_features[0][1].num_elements
expected_output_dimension = update_dimension(model, input_dimension)
assert output_features[0][1] == datatypes.Array(expected_output_dimension)
# Create a pipeline that can do all of the subsequent feature extraction.
feature_vectorizer_input_features = []
feature_vectorizer_size_map = {}
if model.categorical_features == 'all':
_categorical_features = set(range(input_dimension))
_cat_feature_idx_mapping = dict( (i, i) for i in range(input_dimension))
else:
_categorical_features = set(model.categorical_features)
_cat_feature_idx_mapping = dict( (_idx, i) for i, _idx in enumerate(sorted(model.categorical_features)))
pline = Pipeline(input_features, output_features)
# Track the overall packing index, which determines the output ordering.
pack_idx = 0
# First, go through all the columns that are encoded. The sklearn OHE puts
# all of these first, regardless of their original ordering.
for idx in range(input_dimension):
f_name = "__OHE_%d__" % pack_idx
if idx in _categorical_features:
# This input column is one hot encoded
feature_extractor_spec = create_array_feature_extractor(
input_features, f_name, idx, output_type = 'Int64')
pline.add_model(feature_extractor_spec)
_cat_feature_idx = _cat_feature_idx_mapping[idx]
ohe_input_features = [(f_name, datatypes.Int64())]
ohe_output_features = [(f_name, datatypes.Dictionary('Int64'))]
# Create a one hot encoder per column
o_spec = _Model_pb2.Model()
o_spec.specificationVersion = SPECIFICATION_VERSION
o_spec = set_transform_interface_params(o_spec, ohe_input_features, ohe_output_features)
ohe_spec = o_spec.oneHotEncoder
ohe_spec.outputSparse = True
if model.handle_unknown == 'error':
ohe_spec.handleUnknown = _OHE_pb2.OneHotEncoder.HandleUnknown.Value('ErrorOnUnknown')
else:
ohe_spec.handleUnknown = _OHE_pb2.OneHotEncoder.HandleUnknown.Value('IgnoreUnknown')
# Need to do a quick search to find the part of the active_features_ mask
# that represents the categorical variables in our part. Could do this
# with binary search, but we probably don't need speed so much here.
def bs_find(a, i):
lb, k = 0, len(a)
while k > 0:
_idx = lb + (k // 2)
if a[_idx] < i:
lb = _idx + 1
k -= 1
k = (k // 2)
return lb
# Here are the indices we are looking fo
f_idx_bottom = model.feature_indices_[_cat_feature_idx]
f_idx_top = model.feature_indices_[_cat_feature_idx + 1]
# Now find where in the active features list we should look.
cat_feat_idx_bottom = bs_find(model.active_features_, f_idx_bottom)
cat_feat_idx_top = bs_find(model.active_features_, f_idx_top)
n_cat_values = cat_feat_idx_top - cat_feat_idx_bottom
for i in range(cat_feat_idx_bottom, cat_feat_idx_top):
# The actual categorical value is stored as an offset in the active_features list.
cat_idx = model.active_features_[i] - f_idx_bottom
ohe_spec.int64Categories.vector.append(cat_idx)
# Add the ohe to the pipeline
pline.add_model(o_spec)
# Add the result to the feature_vectorizer at the end.
feature_vectorizer_input_features.append( (f_name, datatypes.Dictionary('Int64')) )
feature_vectorizer_size_map[f_name] = n_cat_values
pack_idx += 1
# Now go through all the columns that are not encoded as the sklearn OHE puts
# these after the encoded ones. For speed, we can put these all in a single
# ArrayFeatureExtractor
#
pass_through_features = [idx for idx in range(input_dimension)
if idx not in _categorical_features]
if pass_through_features:
f_name = "__OHE_pass_through__"
# This input column is not one hot encoded
feature_extractor_spec = create_array_feature_extractor(
input_features, f_name, pass_through_features)
pline.add_model(feature_extractor_spec)
feature_vectorizer_input_features.append(
(f_name, datatypes.Array(len(pass_through_features))) )
# Finally, add the feature vectorizer to the pipeline.
output_feature_name = output_features[0][0]
output_feature_dimension = output_features[0][1].num_elements
fvec, _num_out_dim = create_feature_vectorizer(feature_vectorizer_input_features,
output_features[0][0], feature_vectorizer_size_map)
# Make sure that the feature vectorizer input actually matches up with the
assert _num_out_dim == output_features[0][1].num_elements
pline.add_model(fvec)
return _MLModel(pline.spec) | [
"def",
"convert",
"(",
"model",
",",
"input_features",
",",
"output_features",
")",
":",
"if",
"not",
"(",
"_HAS_SKLEARN",
")",
":",
"raise",
"RuntimeError",
"(",
"'scikit-learn not found. scikit-learn conversion API is disabled.'",
")",
"# Make sure the model is fitted.",
"_sklearn_util",
".",
"check_expected_type",
"(",
"model",
",",
"OneHotEncoder",
")",
"_sklearn_util",
".",
"check_fitted",
"(",
"model",
",",
"lambda",
"m",
":",
"hasattr",
"(",
"m",
",",
"'active_features_'",
")",
")",
"_sklearn_util",
".",
"check_fitted",
"(",
"model",
",",
"lambda",
"m",
":",
"hasattr",
"(",
"m",
",",
"'n_values_'",
")",
")",
"input_dimension",
"=",
"get_input_dimension",
"(",
"model",
")",
"if",
"input_dimension",
"is",
"not",
"None",
":",
"# Make sure that our starting dimensions are correctly managed.",
"assert",
"len",
"(",
"input_features",
")",
"==",
"1",
"assert",
"input_features",
"[",
"0",
"]",
"[",
"1",
"]",
"==",
"datatypes",
".",
"Array",
"(",
"input_dimension",
")",
"input_dimension",
"=",
"input_features",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"num_elements",
"expected_output_dimension",
"=",
"update_dimension",
"(",
"model",
",",
"input_dimension",
")",
"assert",
"output_features",
"[",
"0",
"]",
"[",
"1",
"]",
"==",
"datatypes",
".",
"Array",
"(",
"expected_output_dimension",
")",
"# Create a pipeline that can do all of the subsequent feature extraction.",
"feature_vectorizer_input_features",
"=",
"[",
"]",
"feature_vectorizer_size_map",
"=",
"{",
"}",
"if",
"model",
".",
"categorical_features",
"==",
"'all'",
":",
"_categorical_features",
"=",
"set",
"(",
"range",
"(",
"input_dimension",
")",
")",
"_cat_feature_idx_mapping",
"=",
"dict",
"(",
"(",
"i",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"input_dimension",
")",
")",
"else",
":",
"_categorical_features",
"=",
"set",
"(",
"model",
".",
"categorical_features",
")",
"_cat_feature_idx_mapping",
"=",
"dict",
"(",
"(",
"_idx",
",",
"i",
")",
"for",
"i",
",",
"_idx",
"in",
"enumerate",
"(",
"sorted",
"(",
"model",
".",
"categorical_features",
")",
")",
")",
"pline",
"=",
"Pipeline",
"(",
"input_features",
",",
"output_features",
")",
"# Track the overall packing index, which determines the output ordering.",
"pack_idx",
"=",
"0",
"# First, go through all the columns that are encoded. The sklearn OHE puts",
"# all of these first, regardless of their original ordering.",
"for",
"idx",
"in",
"range",
"(",
"input_dimension",
")",
":",
"f_name",
"=",
"\"__OHE_%d__\"",
"%",
"pack_idx",
"if",
"idx",
"in",
"_categorical_features",
":",
"# This input column is one hot encoded",
"feature_extractor_spec",
"=",
"create_array_feature_extractor",
"(",
"input_features",
",",
"f_name",
",",
"idx",
",",
"output_type",
"=",
"'Int64'",
")",
"pline",
".",
"add_model",
"(",
"feature_extractor_spec",
")",
"_cat_feature_idx",
"=",
"_cat_feature_idx_mapping",
"[",
"idx",
"]",
"ohe_input_features",
"=",
"[",
"(",
"f_name",
",",
"datatypes",
".",
"Int64",
"(",
")",
")",
"]",
"ohe_output_features",
"=",
"[",
"(",
"f_name",
",",
"datatypes",
".",
"Dictionary",
"(",
"'Int64'",
")",
")",
"]",
"# Create a one hot encoder per column",
"o_spec",
"=",
"_Model_pb2",
".",
"Model",
"(",
")",
"o_spec",
".",
"specificationVersion",
"=",
"SPECIFICATION_VERSION",
"o_spec",
"=",
"set_transform_interface_params",
"(",
"o_spec",
",",
"ohe_input_features",
",",
"ohe_output_features",
")",
"ohe_spec",
"=",
"o_spec",
".",
"oneHotEncoder",
"ohe_spec",
".",
"outputSparse",
"=",
"True",
"if",
"model",
".",
"handle_unknown",
"==",
"'error'",
":",
"ohe_spec",
".",
"handleUnknown",
"=",
"_OHE_pb2",
".",
"OneHotEncoder",
".",
"HandleUnknown",
".",
"Value",
"(",
"'ErrorOnUnknown'",
")",
"else",
":",
"ohe_spec",
".",
"handleUnknown",
"=",
"_OHE_pb2",
".",
"OneHotEncoder",
".",
"HandleUnknown",
".",
"Value",
"(",
"'IgnoreUnknown'",
")",
"# Need to do a quick search to find the part of the active_features_ mask",
"# that represents the categorical variables in our part. Could do this",
"# with binary search, but we probably don't need speed so much here.",
"def",
"bs_find",
"(",
"a",
",",
"i",
")",
":",
"lb",
",",
"k",
"=",
"0",
",",
"len",
"(",
"a",
")",
"while",
"k",
">",
"0",
":",
"_idx",
"=",
"lb",
"+",
"(",
"k",
"//",
"2",
")",
"if",
"a",
"[",
"_idx",
"]",
"<",
"i",
":",
"lb",
"=",
"_idx",
"+",
"1",
"k",
"-=",
"1",
"k",
"=",
"(",
"k",
"//",
"2",
")",
"return",
"lb",
"# Here are the indices we are looking fo",
"f_idx_bottom",
"=",
"model",
".",
"feature_indices_",
"[",
"_cat_feature_idx",
"]",
"f_idx_top",
"=",
"model",
".",
"feature_indices_",
"[",
"_cat_feature_idx",
"+",
"1",
"]",
"# Now find where in the active features list we should look.",
"cat_feat_idx_bottom",
"=",
"bs_find",
"(",
"model",
".",
"active_features_",
",",
"f_idx_bottom",
")",
"cat_feat_idx_top",
"=",
"bs_find",
"(",
"model",
".",
"active_features_",
",",
"f_idx_top",
")",
"n_cat_values",
"=",
"cat_feat_idx_top",
"-",
"cat_feat_idx_bottom",
"for",
"i",
"in",
"range",
"(",
"cat_feat_idx_bottom",
",",
"cat_feat_idx_top",
")",
":",
"# The actual categorical value is stored as an offset in the active_features list.",
"cat_idx",
"=",
"model",
".",
"active_features_",
"[",
"i",
"]",
"-",
"f_idx_bottom",
"ohe_spec",
".",
"int64Categories",
".",
"vector",
".",
"append",
"(",
"cat_idx",
")",
"# Add the ohe to the pipeline",
"pline",
".",
"add_model",
"(",
"o_spec",
")",
"# Add the result to the feature_vectorizer at the end.",
"feature_vectorizer_input_features",
".",
"append",
"(",
"(",
"f_name",
",",
"datatypes",
".",
"Dictionary",
"(",
"'Int64'",
")",
")",
")",
"feature_vectorizer_size_map",
"[",
"f_name",
"]",
"=",
"n_cat_values",
"pack_idx",
"+=",
"1",
"# Now go through all the columns that are not encoded as the sklearn OHE puts",
"# these after the encoded ones. For speed, we can put these all in a single",
"# ArrayFeatureExtractor",
"#",
"pass_through_features",
"=",
"[",
"idx",
"for",
"idx",
"in",
"range",
"(",
"input_dimension",
")",
"if",
"idx",
"not",
"in",
"_categorical_features",
"]",
"if",
"pass_through_features",
":",
"f_name",
"=",
"\"__OHE_pass_through__\"",
"# This input column is not one hot encoded",
"feature_extractor_spec",
"=",
"create_array_feature_extractor",
"(",
"input_features",
",",
"f_name",
",",
"pass_through_features",
")",
"pline",
".",
"add_model",
"(",
"feature_extractor_spec",
")",
"feature_vectorizer_input_features",
".",
"append",
"(",
"(",
"f_name",
",",
"datatypes",
".",
"Array",
"(",
"len",
"(",
"pass_through_features",
")",
")",
")",
")",
"# Finally, add the feature vectorizer to the pipeline.",
"output_feature_name",
"=",
"output_features",
"[",
"0",
"]",
"[",
"0",
"]",
"output_feature_dimension",
"=",
"output_features",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"num_elements",
"fvec",
",",
"_num_out_dim",
"=",
"create_feature_vectorizer",
"(",
"feature_vectorizer_input_features",
",",
"output_features",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"feature_vectorizer_size_map",
")",
"# Make sure that the feature vectorizer input actually matches up with the",
"assert",
"_num_out_dim",
"==",
"output_features",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"num_elements",
"pline",
".",
"add_model",
"(",
"fvec",
")",
"return",
"_MLModel",
"(",
"pline",
".",
"spec",
")"
] | Convert a one-hot-encoder model to the protobuf spec.
Parameters
----------
model: OneHotEncoder
A trained one-hot encoder model.
input_features: str, optional
Name of the input column.
output_features: str, optional
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model | [
"Convert",
"a",
"one",
"-",
"hot",
"-",
"encoder",
"model",
"to",
"the",
"protobuf",
"spec",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_one_hot_encoder.py#L33-L189 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_one_hot_encoder.py | update_dimension | def update_dimension(model, input_dimension):
"""
Given a model that takes an array of dimension input_dimension, returns
the output dimension.
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'active_features_'))
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'n_values_'))
if model.categorical_features == 'all':
return len(model.active_features_)
else:
out_dimension = (len(model.active_features_)
+ (input_dimension - len(model.n_values_)))
return out_dimension | python | def update_dimension(model, input_dimension):
"""
Given a model that takes an array of dimension input_dimension, returns
the output dimension.
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'active_features_'))
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'n_values_'))
if model.categorical_features == 'all':
return len(model.active_features_)
else:
out_dimension = (len(model.active_features_)
+ (input_dimension - len(model.n_values_)))
return out_dimension | [
"def",
"update_dimension",
"(",
"model",
",",
"input_dimension",
")",
":",
"if",
"not",
"(",
"_HAS_SKLEARN",
")",
":",
"raise",
"RuntimeError",
"(",
"'scikit-learn not found. scikit-learn conversion API is disabled.'",
")",
"_sklearn_util",
".",
"check_fitted",
"(",
"model",
",",
"lambda",
"m",
":",
"hasattr",
"(",
"m",
",",
"'active_features_'",
")",
")",
"_sklearn_util",
".",
"check_fitted",
"(",
"model",
",",
"lambda",
"m",
":",
"hasattr",
"(",
"m",
",",
"'n_values_'",
")",
")",
"if",
"model",
".",
"categorical_features",
"==",
"'all'",
":",
"return",
"len",
"(",
"model",
".",
"active_features_",
")",
"else",
":",
"out_dimension",
"=",
"(",
"len",
"(",
"model",
".",
"active_features_",
")",
"+",
"(",
"input_dimension",
"-",
"len",
"(",
"model",
".",
"n_values_",
")",
")",
")",
"return",
"out_dimension"
] | Given a model that takes an array of dimension input_dimension, returns
the output dimension. | [
"Given",
"a",
"model",
"that",
"takes",
"an",
"array",
"of",
"dimension",
"input_dimension",
"returns",
"the",
"output",
"dimension",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_one_hot_encoder.py#L192-L209 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_reshape | def convert_reshape(net, node, module, builder):
"""Converts a reshape layer from mxnet to coreml.
This doesn't currently handle the deprecated parameters for the reshape layer.
Parameters
----------
net: network
An mxnet network object.
node: layer
Node to convert.
module: module
A module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
target_shape = literal_eval(param['shape'])
if target_shape == (0, -1):
convert_flatten(net, node, module, builder)
return
if any(item <= 0 for item in target_shape):
raise NotImplementedError('Special dimensional values less than or equal to 0 are not supported yet.'
'Feel free to file an issue here: https://github.com/dmlc/mxnet/issues.')
if 'reverse' in node and node['reverse'] == 'True':
raise NotImplementedError('"reverse" parameter is not supported by yet.'
'Feel free to file an issue here: https://github.com/dmlc/mxnet/issues.')
mode = 0 # CHANNEL_FIRST
builder.add_reshape(name, input_name, output_name, target_shape, mode) | python | def convert_reshape(net, node, module, builder):
"""Converts a reshape layer from mxnet to coreml.
This doesn't currently handle the deprecated parameters for the reshape layer.
Parameters
----------
net: network
An mxnet network object.
node: layer
Node to convert.
module: module
A module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
target_shape = literal_eval(param['shape'])
if target_shape == (0, -1):
convert_flatten(net, node, module, builder)
return
if any(item <= 0 for item in target_shape):
raise NotImplementedError('Special dimensional values less than or equal to 0 are not supported yet.'
'Feel free to file an issue here: https://github.com/dmlc/mxnet/issues.')
if 'reverse' in node and node['reverse'] == 'True':
raise NotImplementedError('"reverse" parameter is not supported by yet.'
'Feel free to file an issue here: https://github.com/dmlc/mxnet/issues.')
mode = 0 # CHANNEL_FIRST
builder.add_reshape(name, input_name, output_name, target_shape, mode) | [
"def",
"convert_reshape",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attr",
"(",
"node",
")",
"target_shape",
"=",
"literal_eval",
"(",
"param",
"[",
"'shape'",
"]",
")",
"if",
"target_shape",
"==",
"(",
"0",
",",
"-",
"1",
")",
":",
"convert_flatten",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
"return",
"if",
"any",
"(",
"item",
"<=",
"0",
"for",
"item",
"in",
"target_shape",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Special dimensional values less than or equal to 0 are not supported yet.'",
"'Feel free to file an issue here: https://github.com/dmlc/mxnet/issues.'",
")",
"if",
"'reverse'",
"in",
"node",
"and",
"node",
"[",
"'reverse'",
"]",
"==",
"'True'",
":",
"raise",
"NotImplementedError",
"(",
"'\"reverse\" parameter is not supported by yet.'",
"'Feel free to file an issue here: https://github.com/dmlc/mxnet/issues.'",
")",
"mode",
"=",
"0",
"# CHANNEL_FIRST",
"builder",
".",
"add_reshape",
"(",
"name",
",",
"input_name",
",",
"output_name",
",",
"target_shape",
",",
"mode",
")"
] | Converts a reshape layer from mxnet to coreml.
This doesn't currently handle the deprecated parameters for the reshape layer.
Parameters
----------
net: network
An mxnet network object.
node: layer
Node to convert.
module: module
A module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Converts",
"a",
"reshape",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L61-L97 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_elementwise_mul_scalar | def convert_elementwise_mul_scalar(net, node, module, builder):
"""Convert a scalar multiplication from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
import numpy
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
mult = literal_eval(param['scalar'])
builder.add_scale(name=name,
W=numpy.array([mult]),
b=0,
has_bias=False,
input_name=input_name,
output_name=output_name) | python | def convert_elementwise_mul_scalar(net, node, module, builder):
"""Convert a scalar multiplication from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
import numpy
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
mult = literal_eval(param['scalar'])
builder.add_scale(name=name,
W=numpy.array([mult]),
b=0,
has_bias=False,
input_name=input_name,
output_name=output_name) | [
"def",
"convert_elementwise_mul_scalar",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"import",
"numpy",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attr",
"(",
"node",
")",
"mult",
"=",
"literal_eval",
"(",
"param",
"[",
"'scalar'",
"]",
")",
"builder",
".",
"add_scale",
"(",
"name",
"=",
"name",
",",
"W",
"=",
"numpy",
".",
"array",
"(",
"[",
"mult",
"]",
")",
",",
"b",
"=",
"0",
",",
"has_bias",
"=",
"False",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")"
] | Convert a scalar multiplication from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"scalar",
"multiplication",
"from",
"mxnet",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L224-L252 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_dense | def convert_dense(net, node, module, builder):
"""Convert a dense layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
has_bias = True
name = node['name']
inputs = node['inputs']
args, _ = module.get_params()
W = args[_get_node_name(net, inputs[1][0])].asnumpy()
if has_bias:
Wb = args[_get_node_name(net, inputs[2][0])].asnumpy()
else:
Wb = None
nC, nB = W.shape
builder.add_inner_product(
name=name,
W=W,
b=Wb,
input_channels=nB,
output_channels=nC,
has_bias=has_bias,
input_name=input_name,
output_name=output_name
) | python | def convert_dense(net, node, module, builder):
"""Convert a dense layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
has_bias = True
name = node['name']
inputs = node['inputs']
args, _ = module.get_params()
W = args[_get_node_name(net, inputs[1][0])].asnumpy()
if has_bias:
Wb = args[_get_node_name(net, inputs[2][0])].asnumpy()
else:
Wb = None
nC, nB = W.shape
builder.add_inner_product(
name=name,
W=W,
b=Wb,
input_channels=nB,
output_channels=nC,
has_bias=has_bias,
input_name=input_name,
output_name=output_name
) | [
"def",
"convert_dense",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"has_bias",
"=",
"True",
"name",
"=",
"node",
"[",
"'name'",
"]",
"inputs",
"=",
"node",
"[",
"'inputs'",
"]",
"args",
",",
"_",
"=",
"module",
".",
"get_params",
"(",
")",
"W",
"=",
"args",
"[",
"_get_node_name",
"(",
"net",
",",
"inputs",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"]",
".",
"asnumpy",
"(",
")",
"if",
"has_bias",
":",
"Wb",
"=",
"args",
"[",
"_get_node_name",
"(",
"net",
",",
"inputs",
"[",
"2",
"]",
"[",
"0",
"]",
")",
"]",
".",
"asnumpy",
"(",
")",
"else",
":",
"Wb",
"=",
"None",
"nC",
",",
"nB",
"=",
"W",
".",
"shape",
"builder",
".",
"add_inner_product",
"(",
"name",
"=",
"name",
",",
"W",
"=",
"W",
",",
"b",
"=",
"Wb",
",",
"input_channels",
"=",
"nB",
",",
"output_channels",
"=",
"nC",
",",
"has_bias",
"=",
"has_bias",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")"
] | Convert a dense layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"dense",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L286-L325 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_padding | def convert_padding(net, node, module, builder):
"""Convert a padding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
pad = literal_eval(param['pad_width'])
pad_left = pad[4]
pad_top = pad[5]
pad_right = pad[6]
pad_bottom = pad[7]
if param['mode'] == 'reflect':
builder.add_padding(
name=name,
top=pad_top,
bottom=pad_bottom,
left=pad_left,
right=pad_right,
padding_type='reflection',
input_name=input_name,
output_name=output_name
)
else:
raise TypeError("Padding type %s not supported" % param['mode']) | python | def convert_padding(net, node, module, builder):
"""Convert a padding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
pad = literal_eval(param['pad_width'])
pad_left = pad[4]
pad_top = pad[5]
pad_right = pad[6]
pad_bottom = pad[7]
if param['mode'] == 'reflect':
builder.add_padding(
name=name,
top=pad_top,
bottom=pad_bottom,
left=pad_left,
right=pad_right,
padding_type='reflection',
input_name=input_name,
output_name=output_name
)
else:
raise TypeError("Padding type %s not supported" % param['mode']) | [
"def",
"convert_padding",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attr",
"(",
"node",
")",
"pad",
"=",
"literal_eval",
"(",
"param",
"[",
"'pad_width'",
"]",
")",
"pad_left",
"=",
"pad",
"[",
"4",
"]",
"pad_top",
"=",
"pad",
"[",
"5",
"]",
"pad_right",
"=",
"pad",
"[",
"6",
"]",
"pad_bottom",
"=",
"pad",
"[",
"7",
"]",
"if",
"param",
"[",
"'mode'",
"]",
"==",
"'reflect'",
":",
"builder",
".",
"add_padding",
"(",
"name",
"=",
"name",
",",
"top",
"=",
"pad_top",
",",
"bottom",
"=",
"pad_bottom",
",",
"left",
"=",
"pad_left",
",",
"right",
"=",
"pad_right",
",",
"padding_type",
"=",
"'reflection'",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Padding type %s not supported\"",
"%",
"param",
"[",
"'mode'",
"]",
")"
] | Convert a padding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"padding",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L421-L462 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_upsample | def convert_upsample(net, node, module, builder):
"""Convert a UpSampling layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
inputs = node['inputs']
args, _ = module.get_params()
scale = literal_eval(param['scale'])
#method
if 'sample_type' in param.keys():
method = param['sample_type']
if method == 'nearest':
mode = 'NN'
elif method == '':
mode = 'BILINEAR'
builder.add_upsample(name, scaling_factor_h=scale, scaling_factor_w=scale,
input_name=input_name, output_name=output_name, mode=mode) | python | def convert_upsample(net, node, module, builder):
"""Convert a UpSampling layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
inputs = node['inputs']
args, _ = module.get_params()
scale = literal_eval(param['scale'])
#method
if 'sample_type' in param.keys():
method = param['sample_type']
if method == 'nearest':
mode = 'NN'
elif method == '':
mode = 'BILINEAR'
builder.add_upsample(name, scaling_factor_h=scale, scaling_factor_w=scale,
input_name=input_name, output_name=output_name, mode=mode) | [
"def",
"convert_upsample",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attr",
"(",
"node",
")",
"inputs",
"=",
"node",
"[",
"'inputs'",
"]",
"args",
",",
"_",
"=",
"module",
".",
"get_params",
"(",
")",
"scale",
"=",
"literal_eval",
"(",
"param",
"[",
"'scale'",
"]",
")",
"#method",
"if",
"'sample_type'",
"in",
"param",
".",
"keys",
"(",
")",
":",
"method",
"=",
"param",
"[",
"'sample_type'",
"]",
"if",
"method",
"==",
"'nearest'",
":",
"mode",
"=",
"'NN'",
"elif",
"method",
"==",
"''",
":",
"mode",
"=",
"'BILINEAR'",
"builder",
".",
"add_upsample",
"(",
"name",
",",
"scaling_factor_h",
"=",
"scale",
",",
"scaling_factor_w",
"=",
"scale",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
",",
"mode",
"=",
"mode",
")"
] | Convert a UpSampling layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"UpSampling",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L704-L738 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_softmax | def convert_softmax(net, node, module, builder):
"""Convert a softmax layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
if param is not None and 'axis' in param:
axis = literal_eval(param['axis'])
assert axis == 1, "Only softmax with axis 1 is supported"
builder.add_softmax(name=name,
input_name=input_name,
output_name=output_name) | python | def convert_softmax(net, node, module, builder):
"""Convert a softmax layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
if param is not None and 'axis' in param:
axis = literal_eval(param['axis'])
assert axis == 1, "Only softmax with axis 1 is supported"
builder.add_softmax(name=name,
input_name=input_name,
output_name=output_name) | [
"def",
"convert_softmax",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attr",
"(",
"node",
")",
"if",
"param",
"is",
"not",
"None",
"and",
"'axis'",
"in",
"param",
":",
"axis",
"=",
"literal_eval",
"(",
"param",
"[",
"'axis'",
"]",
")",
"assert",
"axis",
"==",
"1",
",",
"\"Only softmax with axis 1 is supported\"",
"builder",
".",
"add_softmax",
"(",
"name",
"=",
"name",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")"
] | Convert a softmax layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"softmax",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L768-L795 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_custom | def convert_custom(net, node, module, builder):
"""Convert highly specific ops"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
if param['op_type'] == 'special-darknet-maxpool':
_add_pooling.add_pooling_with_padding_types(
builder=builder,
name=name,
height=2,
width=2,
stride_height=1,
stride_width=1,
layer_type='MAX',
padding_type='SAME',
is_global=False,
same_padding_asymmetry_mode='BOTTOM_RIGHT_HEAVY',
input_name=input_name,
output_name=output_name
)
else:
raise TypeError("MXNet layer of type Custom is not supported.") | python | def convert_custom(net, node, module, builder):
"""Convert highly specific ops"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
if param['op_type'] == 'special-darknet-maxpool':
_add_pooling.add_pooling_with_padding_types(
builder=builder,
name=name,
height=2,
width=2,
stride_height=1,
stride_width=1,
layer_type='MAX',
padding_type='SAME',
is_global=False,
same_padding_asymmetry_mode='BOTTOM_RIGHT_HEAVY',
input_name=input_name,
output_name=output_name
)
else:
raise TypeError("MXNet layer of type Custom is not supported.") | [
"def",
"convert_custom",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attr",
"(",
"node",
")",
"if",
"param",
"[",
"'op_type'",
"]",
"==",
"'special-darknet-maxpool'",
":",
"_add_pooling",
".",
"add_pooling_with_padding_types",
"(",
"builder",
"=",
"builder",
",",
"name",
"=",
"name",
",",
"height",
"=",
"2",
",",
"width",
"=",
"2",
",",
"stride_height",
"=",
"1",
",",
"stride_width",
"=",
"1",
",",
"layer_type",
"=",
"'MAX'",
",",
"padding_type",
"=",
"'SAME'",
",",
"is_global",
"=",
"False",
",",
"same_padding_asymmetry_mode",
"=",
"'BOTTOM_RIGHT_HEAVY'",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"MXNet layer of type Custom is not supported.\"",
")"
] | Convert highly specific ops | [
"Convert",
"highly",
"specific",
"ops"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L808-L829 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_embedding | def convert_embedding(net, node, model, builder):
"""Convert an embedding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
inputs = node['inputs']
outputs = node['outputs']
arg_params, aux_params = model.get_params()
W = arg_params[_get_node_name(net, inputs[1][0])].asnumpy()
if not ONE_HOT_ENCODE_HACK:
nC, nB = W.shape
W = W.T
builder.add_embedding(name = name,
W = W,
b = None,
input_dim = nC,
output_channels = nB,
has_bias = False,
input_name = input_name,
output_name = output_name)
else:
W = W.T
nC, nB = W.shape
builder.add_inner_product(name = name,
W = W,
b = None,
input_channels = nB,
output_channels = nC,
has_bias = False,
input_name = input_name,
output_name = output_name) | python | def convert_embedding(net, node, model, builder):
"""Convert an embedding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
inputs = node['inputs']
outputs = node['outputs']
arg_params, aux_params = model.get_params()
W = arg_params[_get_node_name(net, inputs[1][0])].asnumpy()
if not ONE_HOT_ENCODE_HACK:
nC, nB = W.shape
W = W.T
builder.add_embedding(name = name,
W = W,
b = None,
input_dim = nC,
output_channels = nB,
has_bias = False,
input_name = input_name,
output_name = output_name)
else:
W = W.T
nC, nB = W.shape
builder.add_inner_product(name = name,
W = W,
b = None,
input_channels = nB,
output_channels = nC,
has_bias = False,
input_name = input_name,
output_name = output_name) | [
"def",
"convert_embedding",
"(",
"net",
",",
"node",
",",
"model",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"inputs",
"=",
"node",
"[",
"'inputs'",
"]",
"outputs",
"=",
"node",
"[",
"'outputs'",
"]",
"arg_params",
",",
"aux_params",
"=",
"model",
".",
"get_params",
"(",
")",
"W",
"=",
"arg_params",
"[",
"_get_node_name",
"(",
"net",
",",
"inputs",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"]",
".",
"asnumpy",
"(",
")",
"if",
"not",
"ONE_HOT_ENCODE_HACK",
":",
"nC",
",",
"nB",
"=",
"W",
".",
"shape",
"W",
"=",
"W",
".",
"T",
"builder",
".",
"add_embedding",
"(",
"name",
"=",
"name",
",",
"W",
"=",
"W",
",",
"b",
"=",
"None",
",",
"input_dim",
"=",
"nC",
",",
"output_channels",
"=",
"nB",
",",
"has_bias",
"=",
"False",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")",
"else",
":",
"W",
"=",
"W",
".",
"T",
"nC",
",",
"nB",
"=",
"W",
".",
"shape",
"builder",
".",
"add_inner_product",
"(",
"name",
"=",
"name",
",",
"W",
"=",
"W",
",",
"b",
"=",
"None",
",",
"input_channels",
"=",
"nB",
",",
"output_channels",
"=",
"nC",
",",
"has_bias",
"=",
"False",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")"
] | Convert an embedding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"an",
"embedding",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L831-L875 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_scalar_add | def convert_scalar_add(net, node, model, builder):
"""Convert a scalar add layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
import numpy as _np
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
mode = 'ADD'
alpha = _np.array([float(param['scalar'])])
builder.add_scale(name = name, input_name = input_name,
output_name = output_name, W = _np.array([1.0]), b = alpha, has_bias=True) | python | def convert_scalar_add(net, node, model, builder):
"""Convert a scalar add layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
import numpy as _np
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
mode = 'ADD'
alpha = _np.array([float(param['scalar'])])
builder.add_scale(name = name, input_name = input_name,
output_name = output_name, W = _np.array([1.0]), b = alpha, has_bias=True) | [
"def",
"convert_scalar_add",
"(",
"net",
",",
"node",
",",
"model",
",",
"builder",
")",
":",
"import",
"numpy",
"as",
"_np",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attr",
"(",
"node",
")",
"mode",
"=",
"'ADD'",
"alpha",
"=",
"_np",
".",
"array",
"(",
"[",
"float",
"(",
"param",
"[",
"'scalar'",
"]",
")",
"]",
")",
"builder",
".",
"add_scale",
"(",
"name",
"=",
"name",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
",",
"W",
"=",
"_np",
".",
"array",
"(",
"[",
"1.0",
"]",
")",
",",
"b",
"=",
"alpha",
",",
"has_bias",
"=",
"True",
")"
] | Convert a scalar add layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"scalar",
"add",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L899-L923 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_scalar_multiply | def convert_scalar_multiply(net, node, model, builder):
"""Convert a scalar multiply layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
import numpy as _np
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
alpha = _np.array([float(param['scalar'])])
builder.add_scale(name = name, input_name = input_name,
output_name = output_name, W = alpha, has_bias=False, b=None) | python | def convert_scalar_multiply(net, node, model, builder):
"""Convert a scalar multiply layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
import numpy as _np
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attr(node)
alpha = _np.array([float(param['scalar'])])
builder.add_scale(name = name, input_name = input_name,
output_name = output_name, W = alpha, has_bias=False, b=None) | [
"def",
"convert_scalar_multiply",
"(",
"net",
",",
"node",
",",
"model",
",",
"builder",
")",
":",
"import",
"numpy",
"as",
"_np",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attr",
"(",
"node",
")",
"alpha",
"=",
"_np",
".",
"array",
"(",
"[",
"float",
"(",
"param",
"[",
"'scalar'",
"]",
")",
"]",
")",
"builder",
".",
"add_scale",
"(",
"name",
"=",
"name",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
",",
"W",
"=",
"alpha",
",",
"has_bias",
"=",
"False",
",",
"b",
"=",
"None",
")"
] | Convert a scalar multiply layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"scalar",
"multiply",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L926-L949 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py | convert_instancenorm | def convert_instancenorm(net, node, model, builder):
"""Convert an instance norm layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
import numpy as _np
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
inputs = node['inputs']
outputs = node['outputs']
data_blob_name = _get_node_name(net, inputs[0][0])
gamma_blob_name = _get_node_name(net, inputs[1][0])
beta_blob_name = _get_node_name(net, inputs[2][0])
channels = _get_node_channels(net, inputs[0][0])
bn_output_name = output_name + '_bn_'
builder.add_batchnorm(
name = name + '_normalize',
channels = channels,
gamma = _np.ones((channels, )),
beta = _np.zeros((channels, )),
mean = None,
variance = None,
input_name = input_name,
output_name = bn_output_name,
compute_mean_var = True,
instance_normalization = True)
gamma_input_names = [bn_output_name, gamma_blob_name]
gamma_output_name = output_name + '_mult_gamma'
builder.add_elementwise(name=name+'_mult_gamma', input_names=gamma_input_names,
output_name = gamma_output_name, mode='MULTIPLY', alpha = None)
beta_input_names = [gamma_output_name, beta_blob_name]
builder.add_elementwise(name=name+'_add_beta', input_names=beta_input_names,
output_name = output_name, mode='ADD', alpha=None) | python | def convert_instancenorm(net, node, model, builder):
"""Convert an instance norm layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
import numpy as _np
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
inputs = node['inputs']
outputs = node['outputs']
data_blob_name = _get_node_name(net, inputs[0][0])
gamma_blob_name = _get_node_name(net, inputs[1][0])
beta_blob_name = _get_node_name(net, inputs[2][0])
channels = _get_node_channels(net, inputs[0][0])
bn_output_name = output_name + '_bn_'
builder.add_batchnorm(
name = name + '_normalize',
channels = channels,
gamma = _np.ones((channels, )),
beta = _np.zeros((channels, )),
mean = None,
variance = None,
input_name = input_name,
output_name = bn_output_name,
compute_mean_var = True,
instance_normalization = True)
gamma_input_names = [bn_output_name, gamma_blob_name]
gamma_output_name = output_name + '_mult_gamma'
builder.add_elementwise(name=name+'_mult_gamma', input_names=gamma_input_names,
output_name = gamma_output_name, mode='MULTIPLY', alpha = None)
beta_input_names = [gamma_output_name, beta_blob_name]
builder.add_elementwise(name=name+'_add_beta', input_names=beta_input_names,
output_name = output_name, mode='ADD', alpha=None) | [
"def",
"convert_instancenorm",
"(",
"net",
",",
"node",
",",
"model",
",",
"builder",
")",
":",
"import",
"numpy",
"as",
"_np",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"inputs",
"=",
"node",
"[",
"'inputs'",
"]",
"outputs",
"=",
"node",
"[",
"'outputs'",
"]",
"data_blob_name",
"=",
"_get_node_name",
"(",
"net",
",",
"inputs",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"gamma_blob_name",
"=",
"_get_node_name",
"(",
"net",
",",
"inputs",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"beta_blob_name",
"=",
"_get_node_name",
"(",
"net",
",",
"inputs",
"[",
"2",
"]",
"[",
"0",
"]",
")",
"channels",
"=",
"_get_node_channels",
"(",
"net",
",",
"inputs",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"bn_output_name",
"=",
"output_name",
"+",
"'_bn_'",
"builder",
".",
"add_batchnorm",
"(",
"name",
"=",
"name",
"+",
"'_normalize'",
",",
"channels",
"=",
"channels",
",",
"gamma",
"=",
"_np",
".",
"ones",
"(",
"(",
"channels",
",",
")",
")",
",",
"beta",
"=",
"_np",
".",
"zeros",
"(",
"(",
"channels",
",",
")",
")",
",",
"mean",
"=",
"None",
",",
"variance",
"=",
"None",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"bn_output_name",
",",
"compute_mean_var",
"=",
"True",
",",
"instance_normalization",
"=",
"True",
")",
"gamma_input_names",
"=",
"[",
"bn_output_name",
",",
"gamma_blob_name",
"]",
"gamma_output_name",
"=",
"output_name",
"+",
"'_mult_gamma'",
"builder",
".",
"add_elementwise",
"(",
"name",
"=",
"name",
"+",
"'_mult_gamma'",
",",
"input_names",
"=",
"gamma_input_names",
",",
"output_name",
"=",
"gamma_output_name",
",",
"mode",
"=",
"'MULTIPLY'",
",",
"alpha",
"=",
"None",
")",
"beta_input_names",
"=",
"[",
"gamma_output_name",
",",
"beta_blob_name",
"]",
"builder",
".",
"add_elementwise",
"(",
"name",
"=",
"name",
"+",
"'_add_beta'",
",",
"input_names",
"=",
"beta_input_names",
",",
"output_name",
"=",
"output_name",
",",
"mode",
"=",
"'ADD'",
",",
"alpha",
"=",
"None",
")"
] | Convert an instance norm layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"an",
"instance",
"norm",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_to_coreml/_layers.py#L976-L1026 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | _get_aws_credentials | def _get_aws_credentials():
"""
Returns the values stored in the AWS credential environment variables.
Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and
the value stored in the AWS_SECRET_ACCESS_KEY environment variable.
Returns
-------
out : tuple [string]
The first string of the tuple is the value of the AWS_ACCESS_KEY_ID
environment variable. The second string of the tuple is the value of the
AWS_SECRET_ACCESS_KEY environment variable.
Examples
--------
>>> turicreate.aws.get_credentials()
('RBZH792CTQPP7T435BGQ', '7x2hMqplWsLpU/qQCN6xAPKcmWo46TlPJXYTvKcv')
"""
if (not 'AWS_ACCESS_KEY_ID' in _os.environ):
raise KeyError('No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.')
if (not 'AWS_SECRET_ACCESS_KEY' in _os.environ):
raise KeyError('No secret key found. Please set the environment variable AWS_SECRET_ACCESS_KEY.')
return (_os.environ['AWS_ACCESS_KEY_ID'], _os.environ['AWS_SECRET_ACCESS_KEY']) | python | def _get_aws_credentials():
"""
Returns the values stored in the AWS credential environment variables.
Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and
the value stored in the AWS_SECRET_ACCESS_KEY environment variable.
Returns
-------
out : tuple [string]
The first string of the tuple is the value of the AWS_ACCESS_KEY_ID
environment variable. The second string of the tuple is the value of the
AWS_SECRET_ACCESS_KEY environment variable.
Examples
--------
>>> turicreate.aws.get_credentials()
('RBZH792CTQPP7T435BGQ', '7x2hMqplWsLpU/qQCN6xAPKcmWo46TlPJXYTvKcv')
"""
if (not 'AWS_ACCESS_KEY_ID' in _os.environ):
raise KeyError('No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.')
if (not 'AWS_SECRET_ACCESS_KEY' in _os.environ):
raise KeyError('No secret key found. Please set the environment variable AWS_SECRET_ACCESS_KEY.')
return (_os.environ['AWS_ACCESS_KEY_ID'], _os.environ['AWS_SECRET_ACCESS_KEY']) | [
"def",
"_get_aws_credentials",
"(",
")",
":",
"if",
"(",
"not",
"'AWS_ACCESS_KEY_ID'",
"in",
"_os",
".",
"environ",
")",
":",
"raise",
"KeyError",
"(",
"'No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.'",
")",
"if",
"(",
"not",
"'AWS_SECRET_ACCESS_KEY'",
"in",
"_os",
".",
"environ",
")",
":",
"raise",
"KeyError",
"(",
"'No secret key found. Please set the environment variable AWS_SECRET_ACCESS_KEY.'",
")",
"return",
"(",
"_os",
".",
"environ",
"[",
"'AWS_ACCESS_KEY_ID'",
"]",
",",
"_os",
".",
"environ",
"[",
"'AWS_SECRET_ACCESS_KEY'",
"]",
")"
] | Returns the values stored in the AWS credential environment variables.
Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and
the value stored in the AWS_SECRET_ACCESS_KEY environment variable.
Returns
-------
out : tuple [string]
The first string of the tuple is the value of the AWS_ACCESS_KEY_ID
environment variable. The second string of the tuple is the value of the
AWS_SECRET_ACCESS_KEY environment variable.
Examples
--------
>>> turicreate.aws.get_credentials()
('RBZH792CTQPP7T435BGQ', '7x2hMqplWsLpU/qQCN6xAPKcmWo46TlPJXYTvKcv') | [
"Returns",
"the",
"values",
"stored",
"in",
"the",
"AWS",
"credential",
"environment",
"variables",
".",
"Returns",
"the",
"value",
"stored",
"in",
"the",
"AWS_ACCESS_KEY_ID",
"environment",
"variable",
"and",
"the",
"value",
"stored",
"in",
"the",
"AWS_SECRET_ACCESS_KEY",
"environment",
"variable",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L47-L70 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | _try_inject_s3_credentials | def _try_inject_s3_credentials(url):
"""
Inject aws credentials into s3 url as s3://[aws_id]:[aws_key]:[bucket/][objectkey]
If s3 url already contains secret key/id pairs, just return as is.
"""
assert url.startswith('s3://')
path = url[5:]
# Check if the path already contains credentials
tokens = path.split(':')
# If there are two ':', its possible that we have already injected credentials
if len(tokens) == 3:
# Edge case: there are exactly two ':'s in the object key which is a false alarm.
# We prevent this by checking that '/' is not in the assumed key and id.
if ('/' not in tokens[0]) and ('/' not in tokens[1]):
return url
# S3 url does not contain secret key/id pair, query the environment variables
(k, v) = _get_aws_credentials()
return 's3://' + k + ':' + v + ':' + path | python | def _try_inject_s3_credentials(url):
"""
Inject aws credentials into s3 url as s3://[aws_id]:[aws_key]:[bucket/][objectkey]
If s3 url already contains secret key/id pairs, just return as is.
"""
assert url.startswith('s3://')
path = url[5:]
# Check if the path already contains credentials
tokens = path.split(':')
# If there are two ':', its possible that we have already injected credentials
if len(tokens) == 3:
# Edge case: there are exactly two ':'s in the object key which is a false alarm.
# We prevent this by checking that '/' is not in the assumed key and id.
if ('/' not in tokens[0]) and ('/' not in tokens[1]):
return url
# S3 url does not contain secret key/id pair, query the environment variables
(k, v) = _get_aws_credentials()
return 's3://' + k + ':' + v + ':' + path | [
"def",
"_try_inject_s3_credentials",
"(",
"url",
")",
":",
"assert",
"url",
".",
"startswith",
"(",
"'s3://'",
")",
"path",
"=",
"url",
"[",
"5",
":",
"]",
"# Check if the path already contains credentials",
"tokens",
"=",
"path",
".",
"split",
"(",
"':'",
")",
"# If there are two ':', its possible that we have already injected credentials",
"if",
"len",
"(",
"tokens",
")",
"==",
"3",
":",
"# Edge case: there are exactly two ':'s in the object key which is a false alarm.",
"# We prevent this by checking that '/' is not in the assumed key and id.",
"if",
"(",
"'/'",
"not",
"in",
"tokens",
"[",
"0",
"]",
")",
"and",
"(",
"'/'",
"not",
"in",
"tokens",
"[",
"1",
"]",
")",
":",
"return",
"url",
"# S3 url does not contain secret key/id pair, query the environment variables",
"(",
"k",
",",
"v",
")",
"=",
"_get_aws_credentials",
"(",
")",
"return",
"'s3://'",
"+",
"k",
"+",
"':'",
"+",
"v",
"+",
"':'",
"+",
"path"
] | Inject aws credentials into s3 url as s3://[aws_id]:[aws_key]:[bucket/][objectkey]
If s3 url already contains secret key/id pairs, just return as is. | [
"Inject",
"aws",
"credentials",
"into",
"s3",
"url",
"as",
"s3",
":",
"//",
"[",
"aws_id",
"]",
":",
"[",
"aws_key",
"]",
":",
"[",
"bucket",
"/",
"]",
"[",
"objectkey",
"]"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L73-L92 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | _make_internal_url | def _make_internal_url(url):
"""
Process user input url string with proper normalization
For all urls:
Expands ~ to $HOME
For S3 urls:
Returns the s3 URL with credentials filled in using turicreate.aws.get_aws_credential().
For example: "s3://mybucket/foo" -> "s3://$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY:mybucket/foo".
For hdfs urls:
Error if hadoop classpath is not set
For local file urls:
convert slashes for windows sanity
Parameters
----------
string
A URL (as described above).
Raises
------
ValueError
If a bad url is provided.
"""
if not url:
raise ValueError('Invalid url: %s' % url)
from .. import _sys_util
from . import _file_util
# Convert Windows paths to Unix-style slashes
url = _convert_slashes(url)
# Try to split the url into (protocol, path).
protocol = _file_util.get_protocol(url)
is_local = False
if protocol in ['http', 'https']:
pass
elif protocol == 'hdfs':
if not _sys_util.get_hadoop_class_path():
raise ValueError("HDFS URL is not supported because Hadoop not found. Please make hadoop available from PATH or set the environment variable HADOOP_HOME and try again.")
elif protocol == 's3':
return _try_inject_s3_credentials(url)
elif protocol == '':
is_local = True
elif (protocol == 'local' or protocol == 'remote'):
# local and remote are legacy protocol for separate server process
is_local = True
# This code assumes local and remote are same machine
url = _re.sub(protocol+'://','',url,count=1)
else:
raise ValueError('Invalid url protocol %s. Supported url protocols are: local, s3://, https:// and hdfs://' % protocol)
if is_local:
url = _os.path.abspath(_os.path.expanduser(url))
return url | python | def _make_internal_url(url):
"""
Process user input url string with proper normalization
For all urls:
Expands ~ to $HOME
For S3 urls:
Returns the s3 URL with credentials filled in using turicreate.aws.get_aws_credential().
For example: "s3://mybucket/foo" -> "s3://$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY:mybucket/foo".
For hdfs urls:
Error if hadoop classpath is not set
For local file urls:
convert slashes for windows sanity
Parameters
----------
string
A URL (as described above).
Raises
------
ValueError
If a bad url is provided.
"""
if not url:
raise ValueError('Invalid url: %s' % url)
from .. import _sys_util
from . import _file_util
# Convert Windows paths to Unix-style slashes
url = _convert_slashes(url)
# Try to split the url into (protocol, path).
protocol = _file_util.get_protocol(url)
is_local = False
if protocol in ['http', 'https']:
pass
elif protocol == 'hdfs':
if not _sys_util.get_hadoop_class_path():
raise ValueError("HDFS URL is not supported because Hadoop not found. Please make hadoop available from PATH or set the environment variable HADOOP_HOME and try again.")
elif protocol == 's3':
return _try_inject_s3_credentials(url)
elif protocol == '':
is_local = True
elif (protocol == 'local' or protocol == 'remote'):
# local and remote are legacy protocol for separate server process
is_local = True
# This code assumes local and remote are same machine
url = _re.sub(protocol+'://','',url,count=1)
else:
raise ValueError('Invalid url protocol %s. Supported url protocols are: local, s3://, https:// and hdfs://' % protocol)
if is_local:
url = _os.path.abspath(_os.path.expanduser(url))
return url | [
"def",
"_make_internal_url",
"(",
"url",
")",
":",
"if",
"not",
"url",
":",
"raise",
"ValueError",
"(",
"'Invalid url: %s'",
"%",
"url",
")",
"from",
".",
".",
"import",
"_sys_util",
"from",
".",
"import",
"_file_util",
"# Convert Windows paths to Unix-style slashes",
"url",
"=",
"_convert_slashes",
"(",
"url",
")",
"# Try to split the url into (protocol, path).",
"protocol",
"=",
"_file_util",
".",
"get_protocol",
"(",
"url",
")",
"is_local",
"=",
"False",
"if",
"protocol",
"in",
"[",
"'http'",
",",
"'https'",
"]",
":",
"pass",
"elif",
"protocol",
"==",
"'hdfs'",
":",
"if",
"not",
"_sys_util",
".",
"get_hadoop_class_path",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"HDFS URL is not supported because Hadoop not found. Please make hadoop available from PATH or set the environment variable HADOOP_HOME and try again.\"",
")",
"elif",
"protocol",
"==",
"'s3'",
":",
"return",
"_try_inject_s3_credentials",
"(",
"url",
")",
"elif",
"protocol",
"==",
"''",
":",
"is_local",
"=",
"True",
"elif",
"(",
"protocol",
"==",
"'local'",
"or",
"protocol",
"==",
"'remote'",
")",
":",
"# local and remote are legacy protocol for separate server process",
"is_local",
"=",
"True",
"# This code assumes local and remote are same machine",
"url",
"=",
"_re",
".",
"sub",
"(",
"protocol",
"+",
"'://'",
",",
"''",
",",
"url",
",",
"count",
"=",
"1",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid url protocol %s. Supported url protocols are: local, s3://, https:// and hdfs://'",
"%",
"protocol",
")",
"if",
"is_local",
":",
"url",
"=",
"_os",
".",
"path",
".",
"abspath",
"(",
"_os",
".",
"path",
".",
"expanduser",
"(",
"url",
")",
")",
"return",
"url"
] | Process user input url string with proper normalization
For all urls:
Expands ~ to $HOME
For S3 urls:
Returns the s3 URL with credentials filled in using turicreate.aws.get_aws_credential().
For example: "s3://mybucket/foo" -> "s3://$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY:mybucket/foo".
For hdfs urls:
Error if hadoop classpath is not set
For local file urls:
convert slashes for windows sanity
Parameters
----------
string
A URL (as described above).
Raises
------
ValueError
If a bad url is provided. | [
"Process",
"user",
"input",
"url",
"string",
"with",
"proper",
"normalization",
"For",
"all",
"urls",
":",
"Expands",
"~",
"to",
"$HOME",
"For",
"S3",
"urls",
":",
"Returns",
"the",
"s3",
"URL",
"with",
"credentials",
"filled",
"in",
"using",
"turicreate",
".",
"aws",
".",
"get_aws_credential",
"()",
".",
"For",
"example",
":",
"s3",
":",
"//",
"mybucket",
"/",
"foo",
"-",
">",
"s3",
":",
"//",
"$AWS_ACCESS_KEY_ID",
":",
"$AWS_SECRET_ACCESS_KEY",
":",
"mybucket",
"/",
"foo",
".",
"For",
"hdfs",
"urls",
":",
"Error",
"if",
"hadoop",
"classpath",
"is",
"not",
"set",
"For",
"local",
"file",
"urls",
":",
"convert",
"slashes",
"for",
"windows",
"sanity"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L95-L149 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | is_directory_archive | def is_directory_archive(path):
"""
Utility function that returns True if the path provided is a directory that has an SFrame or SGraph in it.
SFrames are written to disk as a directory archive, this function identifies if a given directory is an archive
for an SFrame.
Parameters
----------
path : string
Directory to evaluate.
Returns
-------
True if path provided is an archive location, False otherwise
"""
if path is None:
return False
if not _os.path.isdir(path):
return False
ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini'])
if not _os.path.exists(ini_path):
return False
if _os.path.isfile(ini_path):
return True
return False | python | def is_directory_archive(path):
"""
Utility function that returns True if the path provided is a directory that has an SFrame or SGraph in it.
SFrames are written to disk as a directory archive, this function identifies if a given directory is an archive
for an SFrame.
Parameters
----------
path : string
Directory to evaluate.
Returns
-------
True if path provided is an archive location, False otherwise
"""
if path is None:
return False
if not _os.path.isdir(path):
return False
ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini'])
if not _os.path.exists(ini_path):
return False
if _os.path.isfile(ini_path):
return True
return False | [
"def",
"is_directory_archive",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"False",
"if",
"not",
"_os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"False",
"ini_path",
"=",
"'/'",
".",
"join",
"(",
"[",
"_convert_slashes",
"(",
"path",
")",
",",
"'dir_archive.ini'",
"]",
")",
"if",
"not",
"_os",
".",
"path",
".",
"exists",
"(",
"ini_path",
")",
":",
"return",
"False",
"if",
"_os",
".",
"path",
".",
"isfile",
"(",
"ini_path",
")",
":",
"return",
"True",
"return",
"False"
] | Utility function that returns True if the path provided is a directory that has an SFrame or SGraph in it.
SFrames are written to disk as a directory archive, this function identifies if a given directory is an archive
for an SFrame.
Parameters
----------
path : string
Directory to evaluate.
Returns
-------
True if path provided is an archive location, False otherwise | [
"Utility",
"function",
"that",
"returns",
"True",
"if",
"the",
"path",
"provided",
"is",
"a",
"directory",
"that",
"has",
"an",
"SFrame",
"or",
"SGraph",
"in",
"it",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L152-L181 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | get_archive_type | def get_archive_type(path):
"""
Returns the contents type for the provided archive path.
Parameters
----------
path : string
Directory to evaluate.
Returns
-------
Returns a string of: sframe, sgraph, raises TypeError for anything else
"""
if not is_directory_archive(path):
raise TypeError('Unable to determine the type of archive at path: %s' % path)
try:
ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini'])
parser = _ConfigParser.SafeConfigParser()
parser.read(ini_path)
contents = parser.get('metadata', 'contents')
return contents
except Exception as e:
raise TypeError('Unable to determine type of archive for path: %s' % path, e) | python | def get_archive_type(path):
"""
Returns the contents type for the provided archive path.
Parameters
----------
path : string
Directory to evaluate.
Returns
-------
Returns a string of: sframe, sgraph, raises TypeError for anything else
"""
if not is_directory_archive(path):
raise TypeError('Unable to determine the type of archive at path: %s' % path)
try:
ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini'])
parser = _ConfigParser.SafeConfigParser()
parser.read(ini_path)
contents = parser.get('metadata', 'contents')
return contents
except Exception as e:
raise TypeError('Unable to determine type of archive for path: %s' % path, e) | [
"def",
"get_archive_type",
"(",
"path",
")",
":",
"if",
"not",
"is_directory_archive",
"(",
"path",
")",
":",
"raise",
"TypeError",
"(",
"'Unable to determine the type of archive at path: %s'",
"%",
"path",
")",
"try",
":",
"ini_path",
"=",
"'/'",
".",
"join",
"(",
"[",
"_convert_slashes",
"(",
"path",
")",
",",
"'dir_archive.ini'",
"]",
")",
"parser",
"=",
"_ConfigParser",
".",
"SafeConfigParser",
"(",
")",
"parser",
".",
"read",
"(",
"ini_path",
")",
"contents",
"=",
"parser",
".",
"get",
"(",
"'metadata'",
",",
"'contents'",
")",
"return",
"contents",
"except",
"Exception",
"as",
"e",
":",
"raise",
"TypeError",
"(",
"'Unable to determine type of archive for path: %s'",
"%",
"path",
",",
"e",
")"
] | Returns the contents type for the provided archive path.
Parameters
----------
path : string
Directory to evaluate.
Returns
-------
Returns a string of: sframe, sgraph, raises TypeError for anything else | [
"Returns",
"the",
"contents",
"type",
"for",
"the",
"provided",
"archive",
"path",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L183-L207 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | crossproduct | def crossproduct(d):
"""
Create an SFrame containing the crossproduct of all provided options.
Parameters
----------
d : dict
Each key is the name of an option, and each value is a list
of the possible values for that option.
Returns
-------
out : SFrame
There will be a column for each key in the provided dictionary,
and a row for each unique combination of all values.
Example
-------
settings = {'argument_1':[0, 1],
'argument_2':['a', 'b', 'c']}
print crossproduct(settings)
+------------+------------+
| argument_2 | argument_1 |
+------------+------------+
| a | 0 |
| a | 1 |
| b | 0 |
| b | 1 |
| c | 0 |
| c | 1 |
+------------+------------+
[6 rows x 2 columns]
"""
from .. import SArray
d = [list(zip(list(d.keys()), x)) for x in _itertools.product(*list(d.values()))]
sa = [{k:v for (k,v) in x} for x in d]
return SArray(sa).unpack(column_name_prefix='') | python | def crossproduct(d):
"""
Create an SFrame containing the crossproduct of all provided options.
Parameters
----------
d : dict
Each key is the name of an option, and each value is a list
of the possible values for that option.
Returns
-------
out : SFrame
There will be a column for each key in the provided dictionary,
and a row for each unique combination of all values.
Example
-------
settings = {'argument_1':[0, 1],
'argument_2':['a', 'b', 'c']}
print crossproduct(settings)
+------------+------------+
| argument_2 | argument_1 |
+------------+------------+
| a | 0 |
| a | 1 |
| b | 0 |
| b | 1 |
| c | 0 |
| c | 1 |
+------------+------------+
[6 rows x 2 columns]
"""
from .. import SArray
d = [list(zip(list(d.keys()), x)) for x in _itertools.product(*list(d.values()))]
sa = [{k:v for (k,v) in x} for x in d]
return SArray(sa).unpack(column_name_prefix='') | [
"def",
"crossproduct",
"(",
"d",
")",
":",
"from",
".",
".",
"import",
"SArray",
"d",
"=",
"[",
"list",
"(",
"zip",
"(",
"list",
"(",
"d",
".",
"keys",
"(",
")",
")",
",",
"x",
")",
")",
"for",
"x",
"in",
"_itertools",
".",
"product",
"(",
"*",
"list",
"(",
"d",
".",
"values",
"(",
")",
")",
")",
"]",
"sa",
"=",
"[",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"x",
"}",
"for",
"x",
"in",
"d",
"]",
"return",
"SArray",
"(",
"sa",
")",
".",
"unpack",
"(",
"column_name_prefix",
"=",
"''",
")"
] | Create an SFrame containing the crossproduct of all provided options.
Parameters
----------
d : dict
Each key is the name of an option, and each value is a list
of the possible values for that option.
Returns
-------
out : SFrame
There will be a column for each key in the provided dictionary,
and a row for each unique combination of all values.
Example
-------
settings = {'argument_1':[0, 1],
'argument_2':['a', 'b', 'c']}
print crossproduct(settings)
+------------+------------+
| argument_2 | argument_1 |
+------------+------------+
| a | 0 |
| a | 1 |
| b | 0 |
| b | 1 |
| c | 0 |
| c | 1 |
+------------+------------+
[6 rows x 2 columns] | [
"Create",
"an",
"SFrame",
"containing",
"the",
"crossproduct",
"of",
"all",
"provided",
"options",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L209-L246 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | get_turicreate_object_type | def get_turicreate_object_type(url):
'''
Given url where a Turi Create object is persisted, return the Turi
Create object type: 'model', 'graph', 'sframe', or 'sarray'
'''
from .._connect import main as _glconnect
ret = _glconnect.get_unity().get_turicreate_object_type(_make_internal_url(url))
# to be consistent, we use sgraph instead of graph here
if ret == 'graph':
ret = 'sgraph'
return ret | python | def get_turicreate_object_type(url):
'''
Given url where a Turi Create object is persisted, return the Turi
Create object type: 'model', 'graph', 'sframe', or 'sarray'
'''
from .._connect import main as _glconnect
ret = _glconnect.get_unity().get_turicreate_object_type(_make_internal_url(url))
# to be consistent, we use sgraph instead of graph here
if ret == 'graph':
ret = 'sgraph'
return ret | [
"def",
"get_turicreate_object_type",
"(",
"url",
")",
":",
"from",
".",
".",
"_connect",
"import",
"main",
"as",
"_glconnect",
"ret",
"=",
"_glconnect",
".",
"get_unity",
"(",
")",
".",
"get_turicreate_object_type",
"(",
"_make_internal_url",
"(",
"url",
")",
")",
"# to be consistent, we use sgraph instead of graph here",
"if",
"ret",
"==",
"'graph'",
":",
"ret",
"=",
"'sgraph'",
"return",
"ret"
] | Given url where a Turi Create object is persisted, return the Turi
Create object type: 'model', 'graph', 'sframe', or 'sarray' | [
"Given",
"url",
"where",
"a",
"Turi",
"Create",
"object",
"is",
"persisted",
"return",
"the",
"Turi",
"Create",
"object",
"type",
":",
"model",
"graph",
"sframe",
"or",
"sarray"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L249-L260 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | _assert_sframe_equal | def _assert_sframe_equal(sf1,
sf2,
check_column_names=True,
check_column_order=True,
check_row_order=True,
float_column_delta=None):
"""
Assert the two SFrames are equal.
The default behavior of this function uses the strictest possible
definition of equality, where all columns must be in the same order, with
the same names and have the same data in the same order. Each of these
stipulations can be relaxed individually and in concert with another, with
the exception of `check_column_order` and `check_column_names`, we must use
one of these to determine which columns to compare with one another.
Parameters
----------
sf1 : SFrame
sf2 : SFrame
check_column_names : bool
If true, assert if the data values in two columns are the same, but
they have different names. If False, column order is used to determine
which columns to compare.
check_column_order : bool
If true, assert if the data values in two columns are the same, but are
not in the same column position (one is the i-th column and the other
is the j-th column, i != j). If False, column names are used to
determine which columns to compare.
check_row_order : bool
If true, assert if all rows in the first SFrame exist in the second
SFrame, but they are not in the same order.
float_column_delta : float
The acceptable delta that two float values can be and still be
considered "equal". When this is None, only exact equality is accepted.
This is the default behavior since columns of all Nones are often of
float type. Applies to all float columns.
"""
from .. import SFrame as _SFrame
if (type(sf1) is not _SFrame) or (type(sf2) is not _SFrame):
raise TypeError("Cannot function on types other than SFrames.")
if not check_column_order and not check_column_names:
raise ValueError("Cannot ignore both column order and column names.")
sf1.__materialize__()
sf2.__materialize__()
if sf1.num_columns() != sf2.num_columns():
raise AssertionError("Number of columns mismatched: " +
str(sf1.num_columns()) + " != " + str(sf2.num_columns()))
s1_names = sf1.column_names()
s2_names = sf2.column_names()
sorted_s1_names = sorted(s1_names)
sorted_s2_names = sorted(s2_names)
if check_column_names:
if (check_column_order and (s1_names != s2_names)) or (sorted_s1_names != sorted_s2_names):
raise AssertionError("SFrame does not have same column names: " +
str(sf1.column_names()) + " != " + str(sf2.column_names()))
if sf1.num_rows() != sf2.num_rows():
raise AssertionError("Number of rows mismatched: " +
str(sf1.num_rows()) + " != " + str(sf2.num_rows()))
if not check_row_order and (sf1.num_rows() > 1):
sf1 = sf1.sort(s1_names)
sf2 = sf2.sort(s2_names)
names_to_check = None
if check_column_names:
names_to_check = list(zip(sorted_s1_names, sorted_s2_names))
else:
names_to_check = list(zip(s1_names, s2_names))
for i in names_to_check:
col1 = sf1[i[0]]
col2 = sf2[i[1]]
if col1.dtype != col2.dtype:
raise AssertionError("Columns " + str(i) + " types mismatched.")
compare_ary = None
if col1.dtype == float and float_column_delta is not None:
dt = float_column_delta
compare_ary = ((col1 > col2-dt) & (col1 < col2+dt))
else:
compare_ary = (sf1[i[0]] == sf2[i[1]])
if not compare_ary.all():
count = 0
for j in compare_ary:
if not j:
first_row = count
break
count += 1
raise AssertionError("Columns " + str(i) +
" are not equal! First differing element is at row " +
str(first_row) + ": " + str((col1[first_row],col2[first_row]))) | python | def _assert_sframe_equal(sf1,
sf2,
check_column_names=True,
check_column_order=True,
check_row_order=True,
float_column_delta=None):
"""
Assert the two SFrames are equal.
The default behavior of this function uses the strictest possible
definition of equality, where all columns must be in the same order, with
the same names and have the same data in the same order. Each of these
stipulations can be relaxed individually and in concert with another, with
the exception of `check_column_order` and `check_column_names`, we must use
one of these to determine which columns to compare with one another.
Parameters
----------
sf1 : SFrame
sf2 : SFrame
check_column_names : bool
If true, assert if the data values in two columns are the same, but
they have different names. If False, column order is used to determine
which columns to compare.
check_column_order : bool
If true, assert if the data values in two columns are the same, but are
not in the same column position (one is the i-th column and the other
is the j-th column, i != j). If False, column names are used to
determine which columns to compare.
check_row_order : bool
If true, assert if all rows in the first SFrame exist in the second
SFrame, but they are not in the same order.
float_column_delta : float
The acceptable delta that two float values can be and still be
considered "equal". When this is None, only exact equality is accepted.
This is the default behavior since columns of all Nones are often of
float type. Applies to all float columns.
"""
from .. import SFrame as _SFrame
if (type(sf1) is not _SFrame) or (type(sf2) is not _SFrame):
raise TypeError("Cannot function on types other than SFrames.")
if not check_column_order and not check_column_names:
raise ValueError("Cannot ignore both column order and column names.")
sf1.__materialize__()
sf2.__materialize__()
if sf1.num_columns() != sf2.num_columns():
raise AssertionError("Number of columns mismatched: " +
str(sf1.num_columns()) + " != " + str(sf2.num_columns()))
s1_names = sf1.column_names()
s2_names = sf2.column_names()
sorted_s1_names = sorted(s1_names)
sorted_s2_names = sorted(s2_names)
if check_column_names:
if (check_column_order and (s1_names != s2_names)) or (sorted_s1_names != sorted_s2_names):
raise AssertionError("SFrame does not have same column names: " +
str(sf1.column_names()) + " != " + str(sf2.column_names()))
if sf1.num_rows() != sf2.num_rows():
raise AssertionError("Number of rows mismatched: " +
str(sf1.num_rows()) + " != " + str(sf2.num_rows()))
if not check_row_order and (sf1.num_rows() > 1):
sf1 = sf1.sort(s1_names)
sf2 = sf2.sort(s2_names)
names_to_check = None
if check_column_names:
names_to_check = list(zip(sorted_s1_names, sorted_s2_names))
else:
names_to_check = list(zip(s1_names, s2_names))
for i in names_to_check:
col1 = sf1[i[0]]
col2 = sf2[i[1]]
if col1.dtype != col2.dtype:
raise AssertionError("Columns " + str(i) + " types mismatched.")
compare_ary = None
if col1.dtype == float and float_column_delta is not None:
dt = float_column_delta
compare_ary = ((col1 > col2-dt) & (col1 < col2+dt))
else:
compare_ary = (sf1[i[0]] == sf2[i[1]])
if not compare_ary.all():
count = 0
for j in compare_ary:
if not j:
first_row = count
break
count += 1
raise AssertionError("Columns " + str(i) +
" are not equal! First differing element is at row " +
str(first_row) + ": " + str((col1[first_row],col2[first_row]))) | [
"def",
"_assert_sframe_equal",
"(",
"sf1",
",",
"sf2",
",",
"check_column_names",
"=",
"True",
",",
"check_column_order",
"=",
"True",
",",
"check_row_order",
"=",
"True",
",",
"float_column_delta",
"=",
"None",
")",
":",
"from",
".",
".",
"import",
"SFrame",
"as",
"_SFrame",
"if",
"(",
"type",
"(",
"sf1",
")",
"is",
"not",
"_SFrame",
")",
"or",
"(",
"type",
"(",
"sf2",
")",
"is",
"not",
"_SFrame",
")",
":",
"raise",
"TypeError",
"(",
"\"Cannot function on types other than SFrames.\"",
")",
"if",
"not",
"check_column_order",
"and",
"not",
"check_column_names",
":",
"raise",
"ValueError",
"(",
"\"Cannot ignore both column order and column names.\"",
")",
"sf1",
".",
"__materialize__",
"(",
")",
"sf2",
".",
"__materialize__",
"(",
")",
"if",
"sf1",
".",
"num_columns",
"(",
")",
"!=",
"sf2",
".",
"num_columns",
"(",
")",
":",
"raise",
"AssertionError",
"(",
"\"Number of columns mismatched: \"",
"+",
"str",
"(",
"sf1",
".",
"num_columns",
"(",
")",
")",
"+",
"\" != \"",
"+",
"str",
"(",
"sf2",
".",
"num_columns",
"(",
")",
")",
")",
"s1_names",
"=",
"sf1",
".",
"column_names",
"(",
")",
"s2_names",
"=",
"sf2",
".",
"column_names",
"(",
")",
"sorted_s1_names",
"=",
"sorted",
"(",
"s1_names",
")",
"sorted_s2_names",
"=",
"sorted",
"(",
"s2_names",
")",
"if",
"check_column_names",
":",
"if",
"(",
"check_column_order",
"and",
"(",
"s1_names",
"!=",
"s2_names",
")",
")",
"or",
"(",
"sorted_s1_names",
"!=",
"sorted_s2_names",
")",
":",
"raise",
"AssertionError",
"(",
"\"SFrame does not have same column names: \"",
"+",
"str",
"(",
"sf1",
".",
"column_names",
"(",
")",
")",
"+",
"\" != \"",
"+",
"str",
"(",
"sf2",
".",
"column_names",
"(",
")",
")",
")",
"if",
"sf1",
".",
"num_rows",
"(",
")",
"!=",
"sf2",
".",
"num_rows",
"(",
")",
":",
"raise",
"AssertionError",
"(",
"\"Number of rows mismatched: \"",
"+",
"str",
"(",
"sf1",
".",
"num_rows",
"(",
")",
")",
"+",
"\" != \"",
"+",
"str",
"(",
"sf2",
".",
"num_rows",
"(",
")",
")",
")",
"if",
"not",
"check_row_order",
"and",
"(",
"sf1",
".",
"num_rows",
"(",
")",
">",
"1",
")",
":",
"sf1",
"=",
"sf1",
".",
"sort",
"(",
"s1_names",
")",
"sf2",
"=",
"sf2",
".",
"sort",
"(",
"s2_names",
")",
"names_to_check",
"=",
"None",
"if",
"check_column_names",
":",
"names_to_check",
"=",
"list",
"(",
"zip",
"(",
"sorted_s1_names",
",",
"sorted_s2_names",
")",
")",
"else",
":",
"names_to_check",
"=",
"list",
"(",
"zip",
"(",
"s1_names",
",",
"s2_names",
")",
")",
"for",
"i",
"in",
"names_to_check",
":",
"col1",
"=",
"sf1",
"[",
"i",
"[",
"0",
"]",
"]",
"col2",
"=",
"sf2",
"[",
"i",
"[",
"1",
"]",
"]",
"if",
"col1",
".",
"dtype",
"!=",
"col2",
".",
"dtype",
":",
"raise",
"AssertionError",
"(",
"\"Columns \"",
"+",
"str",
"(",
"i",
")",
"+",
"\" types mismatched.\"",
")",
"compare_ary",
"=",
"None",
"if",
"col1",
".",
"dtype",
"==",
"float",
"and",
"float_column_delta",
"is",
"not",
"None",
":",
"dt",
"=",
"float_column_delta",
"compare_ary",
"=",
"(",
"(",
"col1",
">",
"col2",
"-",
"dt",
")",
"&",
"(",
"col1",
"<",
"col2",
"+",
"dt",
")",
")",
"else",
":",
"compare_ary",
"=",
"(",
"sf1",
"[",
"i",
"[",
"0",
"]",
"]",
"==",
"sf2",
"[",
"i",
"[",
"1",
"]",
"]",
")",
"if",
"not",
"compare_ary",
".",
"all",
"(",
")",
":",
"count",
"=",
"0",
"for",
"j",
"in",
"compare_ary",
":",
"if",
"not",
"j",
":",
"first_row",
"=",
"count",
"break",
"count",
"+=",
"1",
"raise",
"AssertionError",
"(",
"\"Columns \"",
"+",
"str",
"(",
"i",
")",
"+",
"\" are not equal! First differing element is at row \"",
"+",
"str",
"(",
"first_row",
")",
"+",
"\": \"",
"+",
"str",
"(",
"(",
"col1",
"[",
"first_row",
"]",
",",
"col2",
"[",
"first_row",
"]",
")",
")",
")"
] | Assert the two SFrames are equal.
The default behavior of this function uses the strictest possible
definition of equality, where all columns must be in the same order, with
the same names and have the same data in the same order. Each of these
stipulations can be relaxed individually and in concert with another, with
the exception of `check_column_order` and `check_column_names`, we must use
one of these to determine which columns to compare with one another.
Parameters
----------
sf1 : SFrame
sf2 : SFrame
check_column_names : bool
If true, assert if the data values in two columns are the same, but
they have different names. If False, column order is used to determine
which columns to compare.
check_column_order : bool
If true, assert if the data values in two columns are the same, but are
not in the same column position (one is the i-th column and the other
is the j-th column, i != j). If False, column names are used to
determine which columns to compare.
check_row_order : bool
If true, assert if all rows in the first SFrame exist in the second
SFrame, but they are not in the same order.
float_column_delta : float
The acceptable delta that two float values can be and still be
considered "equal". When this is None, only exact equality is accepted.
This is the default behavior since columns of all Nones are often of
float type. Applies to all float columns. | [
"Assert",
"the",
"two",
"SFrames",
"are",
"equal",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L263-L365 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | _get_temp_file_location | def _get_temp_file_location():
'''
Returns user specified temporary file location.
The temporary location is specified through:
>>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...)
'''
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
cache_dir = _convert_slashes(unity.get_current_cache_file_location())
if not _os.path.exists(cache_dir):
_os.makedirs(cache_dir)
return cache_dir | python | def _get_temp_file_location():
'''
Returns user specified temporary file location.
The temporary location is specified through:
>>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...)
'''
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
cache_dir = _convert_slashes(unity.get_current_cache_file_location())
if not _os.path.exists(cache_dir):
_os.makedirs(cache_dir)
return cache_dir | [
"def",
"_get_temp_file_location",
"(",
")",
":",
"from",
".",
".",
"_connect",
"import",
"main",
"as",
"_glconnect",
"unity",
"=",
"_glconnect",
".",
"get_unity",
"(",
")",
"cache_dir",
"=",
"_convert_slashes",
"(",
"unity",
".",
"get_current_cache_file_location",
"(",
")",
")",
"if",
"not",
"_os",
".",
"path",
".",
"exists",
"(",
"cache_dir",
")",
":",
"_os",
".",
"makedirs",
"(",
"cache_dir",
")",
"return",
"cache_dir"
] | Returns user specified temporary file location.
The temporary location is specified through:
>>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...) | [
"Returns",
"user",
"specified",
"temporary",
"file",
"location",
".",
"The",
"temporary",
"location",
"is",
"specified",
"through",
":"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L367-L380 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | _make_temp_directory | def _make_temp_directory(prefix):
'''
Generate a temporary directory that would not live beyond the lifetime of
unity_server.
Caller is expected to clean up the temp file as soon as the directory is no
longer needed. But the directory will be cleaned as unity_server restarts
'''
temp_dir = _make_temp_filename(prefix=str(prefix))
_os.makedirs(temp_dir)
return temp_dir | python | def _make_temp_directory(prefix):
'''
Generate a temporary directory that would not live beyond the lifetime of
unity_server.
Caller is expected to clean up the temp file as soon as the directory is no
longer needed. But the directory will be cleaned as unity_server restarts
'''
temp_dir = _make_temp_filename(prefix=str(prefix))
_os.makedirs(temp_dir)
return temp_dir | [
"def",
"_make_temp_directory",
"(",
"prefix",
")",
":",
"temp_dir",
"=",
"_make_temp_filename",
"(",
"prefix",
"=",
"str",
"(",
"prefix",
")",
")",
"_os",
".",
"makedirs",
"(",
"temp_dir",
")",
"return",
"temp_dir"
] | Generate a temporary directory that would not live beyond the lifetime of
unity_server.
Caller is expected to clean up the temp file as soon as the directory is no
longer needed. But the directory will be cleaned as unity_server restarts | [
"Generate",
"a",
"temporary",
"directory",
"that",
"would",
"not",
"live",
"beyond",
"the",
"lifetime",
"of",
"unity_server",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L382-L392 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | _make_temp_filename | def _make_temp_filename(prefix):
'''
Generate a temporary file that would not live beyond the lifetime of
unity_server.
Caller is expected to clean up the temp file as soon as the file is no
longer needed. But temp files created using this method will be cleaned up
when unity_server restarts
'''
temp_location = _get_temp_file_location()
temp_file_name = '/'.join([temp_location, str(prefix)+str(_uuid.uuid4())])
return temp_file_name | python | def _make_temp_filename(prefix):
'''
Generate a temporary file that would not live beyond the lifetime of
unity_server.
Caller is expected to clean up the temp file as soon as the file is no
longer needed. But temp files created using this method will be cleaned up
when unity_server restarts
'''
temp_location = _get_temp_file_location()
temp_file_name = '/'.join([temp_location, str(prefix)+str(_uuid.uuid4())])
return temp_file_name | [
"def",
"_make_temp_filename",
"(",
"prefix",
")",
":",
"temp_location",
"=",
"_get_temp_file_location",
"(",
")",
"temp_file_name",
"=",
"'/'",
".",
"join",
"(",
"[",
"temp_location",
",",
"str",
"(",
"prefix",
")",
"+",
"str",
"(",
"_uuid",
".",
"uuid4",
"(",
")",
")",
"]",
")",
"return",
"temp_file_name"
] | Generate a temporary file that would not live beyond the lifetime of
unity_server.
Caller is expected to clean up the temp file as soon as the file is no
longer needed. But temp files created using this method will be cleaned up
when unity_server restarts | [
"Generate",
"a",
"temporary",
"file",
"that",
"would",
"not",
"live",
"beyond",
"the",
"lifetime",
"of",
"unity_server",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L394-L405 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | _pickle_to_temp_location_or_memory | def _pickle_to_temp_location_or_memory(obj):
'''
If obj can be serialized directly into memory (via cloudpickle) this
will return the serialized bytes.
Otherwise, gl_pickle is attempted and it will then
generates a temporary directory serializes an object into it, returning
the directory name. This directory will not have lifespan greater than
that of unity_server.
'''
from . import _cloudpickle as cloudpickle
try:
# try cloudpickle first and see if that works
lambda_str = cloudpickle.dumps(obj)
return lambda_str
except:
pass
# nope. that does not work! lets try again with gl pickle
filename = _make_temp_filename('pickle')
from .. import _gl_pickle
pickler = _gl_pickle.GLPickler(filename)
pickler.dump(obj)
pickler.close()
return filename | python | def _pickle_to_temp_location_or_memory(obj):
'''
If obj can be serialized directly into memory (via cloudpickle) this
will return the serialized bytes.
Otherwise, gl_pickle is attempted and it will then
generates a temporary directory serializes an object into it, returning
the directory name. This directory will not have lifespan greater than
that of unity_server.
'''
from . import _cloudpickle as cloudpickle
try:
# try cloudpickle first and see if that works
lambda_str = cloudpickle.dumps(obj)
return lambda_str
except:
pass
# nope. that does not work! lets try again with gl pickle
filename = _make_temp_filename('pickle')
from .. import _gl_pickle
pickler = _gl_pickle.GLPickler(filename)
pickler.dump(obj)
pickler.close()
return filename | [
"def",
"_pickle_to_temp_location_or_memory",
"(",
"obj",
")",
":",
"from",
".",
"import",
"_cloudpickle",
"as",
"cloudpickle",
"try",
":",
"# try cloudpickle first and see if that works",
"lambda_str",
"=",
"cloudpickle",
".",
"dumps",
"(",
"obj",
")",
"return",
"lambda_str",
"except",
":",
"pass",
"# nope. that does not work! lets try again with gl pickle",
"filename",
"=",
"_make_temp_filename",
"(",
"'pickle'",
")",
"from",
".",
".",
"import",
"_gl_pickle",
"pickler",
"=",
"_gl_pickle",
".",
"GLPickler",
"(",
"filename",
")",
"pickler",
".",
"dump",
"(",
"obj",
")",
"pickler",
".",
"close",
"(",
")",
"return",
"filename"
] | If obj can be serialized directly into memory (via cloudpickle) this
will return the serialized bytes.
Otherwise, gl_pickle is attempted and it will then
generates a temporary directory serializes an object into it, returning
the directory name. This directory will not have lifespan greater than
that of unity_server. | [
"If",
"obj",
"can",
"be",
"serialized",
"directly",
"into",
"memory",
"(",
"via",
"cloudpickle",
")",
"this",
"will",
"return",
"the",
"serialized",
"bytes",
".",
"Otherwise",
"gl_pickle",
"is",
"attempted",
"and",
"it",
"will",
"then",
"generates",
"a",
"temporary",
"directory",
"serializes",
"an",
"object",
"into",
"it",
"returning",
"the",
"directory",
"name",
".",
"This",
"directory",
"will",
"not",
"have",
"lifespan",
"greater",
"than",
"that",
"of",
"unity_server",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L407-L430 | train |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | _get_cuda_gpus | def _get_cuda_gpus():
"""
Returns a list of dictionaries, with the following keys:
- index (integer, device index of the GPU)
- name (str, GPU name)
- memory_free (float, free memory in MiB)
- memory_total (float, total memory in MiB)
"""
import subprocess
try:
output = subprocess.check_output(['nvidia-smi',
'--query-gpu=index,gpu_name,memory.free,memory.total',
'--format=csv,noheader,nounits'],
universal_newlines=True)
except OSError:
return []
except subprocess.CalledProcessError:
return []
gpus = []
for gpu_line in output.split('\n'):
if gpu_line:
index, gpu_name, memory_free, memory_total = gpu_line.split(', ')
index = int(index)
memory_free = float(memory_free)
memory_total = float(memory_total)
gpus.append({
'index': index,
'name': gpu_name,
'memory_free': memory_free,
'memory_total': memory_total,
})
return gpus | python | def _get_cuda_gpus():
"""
Returns a list of dictionaries, with the following keys:
- index (integer, device index of the GPU)
- name (str, GPU name)
- memory_free (float, free memory in MiB)
- memory_total (float, total memory in MiB)
"""
import subprocess
try:
output = subprocess.check_output(['nvidia-smi',
'--query-gpu=index,gpu_name,memory.free,memory.total',
'--format=csv,noheader,nounits'],
universal_newlines=True)
except OSError:
return []
except subprocess.CalledProcessError:
return []
gpus = []
for gpu_line in output.split('\n'):
if gpu_line:
index, gpu_name, memory_free, memory_total = gpu_line.split(', ')
index = int(index)
memory_free = float(memory_free)
memory_total = float(memory_total)
gpus.append({
'index': index,
'name': gpu_name,
'memory_free': memory_free,
'memory_total': memory_total,
})
return gpus | [
"def",
"_get_cuda_gpus",
"(",
")",
":",
"import",
"subprocess",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'nvidia-smi'",
",",
"'--query-gpu=index,gpu_name,memory.free,memory.total'",
",",
"'--format=csv,noheader,nounits'",
"]",
",",
"universal_newlines",
"=",
"True",
")",
"except",
"OSError",
":",
"return",
"[",
"]",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"return",
"[",
"]",
"gpus",
"=",
"[",
"]",
"for",
"gpu_line",
"in",
"output",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"gpu_line",
":",
"index",
",",
"gpu_name",
",",
"memory_free",
",",
"memory_total",
"=",
"gpu_line",
".",
"split",
"(",
"', '",
")",
"index",
"=",
"int",
"(",
"index",
")",
"memory_free",
"=",
"float",
"(",
"memory_free",
")",
"memory_total",
"=",
"float",
"(",
"memory_total",
")",
"gpus",
".",
"append",
"(",
"{",
"'index'",
":",
"index",
",",
"'name'",
":",
"gpu_name",
",",
"'memory_free'",
":",
"memory_free",
",",
"'memory_total'",
":",
"memory_total",
",",
"}",
")",
"return",
"gpus"
] | Returns a list of dictionaries, with the following keys:
- index (integer, device index of the GPU)
- name (str, GPU name)
- memory_free (float, free memory in MiB)
- memory_total (float, total memory in MiB) | [
"Returns",
"a",
"list",
"of",
"dictionaries",
"with",
"the",
"following",
"keys",
":",
"-",
"index",
"(",
"integer",
"device",
"index",
"of",
"the",
"GPU",
")",
"-",
"name",
"(",
"str",
"GPU",
"name",
")",
"-",
"memory_free",
"(",
"float",
"free",
"memory",
"in",
"MiB",
")",
"-",
"memory_total",
"(",
"float",
"total",
"memory",
"in",
"MiB",
")"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L473-L505 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/_parameterized.py | _ParameterDecorator | def _ParameterDecorator(naming_type, testcases):
"""Implementation of the parameterization decorators.
Args:
naming_type: The naming type.
testcases: Testcase parameters.
Returns:
A function for modifying the decorated object.
"""
def _Apply(obj):
if isinstance(obj, type):
_ModifyClass(
obj,
list(testcases) if not isinstance(testcases, collections.Sequence)
else testcases,
naming_type)
return obj
else:
return _ParameterizedTestIter(obj, testcases, naming_type)
if _IsSingletonList(testcases):
assert _NonStringIterable(testcases[0]), (
'Single parameter argument must be a non-string iterable')
testcases = testcases[0]
return _Apply | python | def _ParameterDecorator(naming_type, testcases):
"""Implementation of the parameterization decorators.
Args:
naming_type: The naming type.
testcases: Testcase parameters.
Returns:
A function for modifying the decorated object.
"""
def _Apply(obj):
if isinstance(obj, type):
_ModifyClass(
obj,
list(testcases) if not isinstance(testcases, collections.Sequence)
else testcases,
naming_type)
return obj
else:
return _ParameterizedTestIter(obj, testcases, naming_type)
if _IsSingletonList(testcases):
assert _NonStringIterable(testcases[0]), (
'Single parameter argument must be a non-string iterable')
testcases = testcases[0]
return _Apply | [
"def",
"_ParameterDecorator",
"(",
"naming_type",
",",
"testcases",
")",
":",
"def",
"_Apply",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"type",
")",
":",
"_ModifyClass",
"(",
"obj",
",",
"list",
"(",
"testcases",
")",
"if",
"not",
"isinstance",
"(",
"testcases",
",",
"collections",
".",
"Sequence",
")",
"else",
"testcases",
",",
"naming_type",
")",
"return",
"obj",
"else",
":",
"return",
"_ParameterizedTestIter",
"(",
"obj",
",",
"testcases",
",",
"naming_type",
")",
"if",
"_IsSingletonList",
"(",
"testcases",
")",
":",
"assert",
"_NonStringIterable",
"(",
"testcases",
"[",
"0",
"]",
")",
",",
"(",
"'Single parameter argument must be a non-string iterable'",
")",
"testcases",
"=",
"testcases",
"[",
"0",
"]",
"return",
"_Apply"
] | Implementation of the parameterization decorators.
Args:
naming_type: The naming type.
testcases: Testcase parameters.
Returns:
A function for modifying the decorated object. | [
"Implementation",
"of",
"the",
"parameterization",
"decorators",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/_parameterized.py#L280-L306 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | check_header_comment | def check_header_comment(filename):
"""Checks if the header-comment of the given file needs fixing."""
# Check input file.
name = os.path.basename( filename )
# Read content of input file.
sourcefile = open( filename, "rU" )
content = sourcefile.read()
sourcefile.close()
# Search content for '$Id$'.
match = re.search(r'\$Id\$', content)
if match == None:
# Make sure that the correct value for '$Id$' was already set.
match = re.search(r'\$Id: ' + name + r'\s+[^$]+\$', content)
if match != None:
# The given file needs no fixing.
return False
# The given file needs fixing.
return True | python | def check_header_comment(filename):
"""Checks if the header-comment of the given file needs fixing."""
# Check input file.
name = os.path.basename( filename )
# Read content of input file.
sourcefile = open( filename, "rU" )
content = sourcefile.read()
sourcefile.close()
# Search content for '$Id$'.
match = re.search(r'\$Id\$', content)
if match == None:
# Make sure that the correct value for '$Id$' was already set.
match = re.search(r'\$Id: ' + name + r'\s+[^$]+\$', content)
if match != None:
# The given file needs no fixing.
return False
# The given file needs fixing.
return True | [
"def",
"check_header_comment",
"(",
"filename",
")",
":",
"# Check input file.",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"# Read content of input file.",
"sourcefile",
"=",
"open",
"(",
"filename",
",",
"\"rU\"",
")",
"content",
"=",
"sourcefile",
".",
"read",
"(",
")",
"sourcefile",
".",
"close",
"(",
")",
"# Search content for '$Id$'.",
"match",
"=",
"re",
".",
"search",
"(",
"r'\\$Id\\$'",
",",
"content",
")",
"if",
"match",
"==",
"None",
":",
"# Make sure that the correct value for '$Id$' was already set.",
"match",
"=",
"re",
".",
"search",
"(",
"r'\\$Id: '",
"+",
"name",
"+",
"r'\\s+[^$]+\\$'",
",",
"content",
")",
"if",
"match",
"!=",
"None",
":",
"# The given file needs no fixing.",
"return",
"False",
"# The given file needs fixing.",
"return",
"True"
] | Checks if the header-comment of the given file needs fixing. | [
"Checks",
"if",
"the",
"header",
"-",
"comment",
"of",
"the",
"given",
"file",
"needs",
"fixing",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L19-L36 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | check_input_files_for_variadic_seq | def check_input_files_for_variadic_seq(headerDir, sourceDir):
"""Checks if files, used as input when pre-processing MPL-containers in their variadic form, need fixing."""
# Check input files in include/source-directories.
files = glob.glob( os.path.join( headerDir, "*.hpp" ) )
files += glob.glob( os.path.join( headerDir, "aux_", "*.hpp" ) )
files += glob.glob( os.path.join( sourceDir, "src", "*" ) )
for currentFile in sorted( files ):
if check_header_comment( currentFile ):
return True
return False | python | def check_input_files_for_variadic_seq(headerDir, sourceDir):
"""Checks if files, used as input when pre-processing MPL-containers in their variadic form, need fixing."""
# Check input files in include/source-directories.
files = glob.glob( os.path.join( headerDir, "*.hpp" ) )
files += glob.glob( os.path.join( headerDir, "aux_", "*.hpp" ) )
files += glob.glob( os.path.join( sourceDir, "src", "*" ) )
for currentFile in sorted( files ):
if check_header_comment( currentFile ):
return True
return False | [
"def",
"check_input_files_for_variadic_seq",
"(",
"headerDir",
",",
"sourceDir",
")",
":",
"# Check input files in include/source-directories.",
"files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"headerDir",
",",
"\"*.hpp\"",
")",
")",
"files",
"+=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"headerDir",
",",
"\"aux_\"",
",",
"\"*.hpp\"",
")",
")",
"files",
"+=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sourceDir",
",",
"\"src\"",
",",
"\"*\"",
")",
")",
"for",
"currentFile",
"in",
"sorted",
"(",
"files",
")",
":",
"if",
"check_header_comment",
"(",
"currentFile",
")",
":",
"return",
"True",
"return",
"False"
] | Checks if files, used as input when pre-processing MPL-containers in their variadic form, need fixing. | [
"Checks",
"if",
"files",
"used",
"as",
"input",
"when",
"pre",
"-",
"processing",
"MPL",
"-",
"containers",
"in",
"their",
"variadic",
"form",
"need",
"fixing",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L39-L48 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | check_input_files_for_numbered_seq | def check_input_files_for_numbered_seq(sourceDir, suffix, containers):
"""Check if files, used as input when pre-processing MPL-containers in their numbered form, need fixing."""
# Check input files for each MPL-container type.
for container in containers:
files = glob.glob( os.path.join( sourceDir, container, container + '*' + suffix ) )
for currentFile in sorted( files ):
if check_header_comment( currentFile ):
return True
return False | python | def check_input_files_for_numbered_seq(sourceDir, suffix, containers):
"""Check if files, used as input when pre-processing MPL-containers in their numbered form, need fixing."""
# Check input files for each MPL-container type.
for container in containers:
files = glob.glob( os.path.join( sourceDir, container, container + '*' + suffix ) )
for currentFile in sorted( files ):
if check_header_comment( currentFile ):
return True
return False | [
"def",
"check_input_files_for_numbered_seq",
"(",
"sourceDir",
",",
"suffix",
",",
"containers",
")",
":",
"# Check input files for each MPL-container type.",
"for",
"container",
"in",
"containers",
":",
"files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sourceDir",
",",
"container",
",",
"container",
"+",
"'*'",
"+",
"suffix",
")",
")",
"for",
"currentFile",
"in",
"sorted",
"(",
"files",
")",
":",
"if",
"check_header_comment",
"(",
"currentFile",
")",
":",
"return",
"True",
"return",
"False"
] | Check if files, used as input when pre-processing MPL-containers in their numbered form, need fixing. | [
"Check",
"if",
"files",
"used",
"as",
"input",
"when",
"pre",
"-",
"processing",
"MPL",
"-",
"containers",
"in",
"their",
"numbered",
"form",
"need",
"fixing",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L51-L59 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | check_input_files | def check_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'],
seqType='both', verbose=False):
"""Checks if source- and header-files, used as input when pre-processing MPL-containers, need fixing."""
# Check the input files for containers in their variadic form.
result1 = False
if seqType == "both" or seqType == "variadic":
if verbose:
print "Check if input files for pre-processing Boost.MPL variadic containers need fixing."
result1 = check_input_files_for_variadic_seq(headerDir, sourceDir)
if verbose:
if result1:
print " At least one input file needs fixing!"
else:
print " No input file needs fixing!"
# Check the input files for containers in their numbered form.
result2 = False
result3 = False
if seqType == "both" or seqType == "numbered":
if verbose:
print "Check input files for pre-processing Boost.MPL numbered containers."
result2 = check_input_files_for_numbered_seq(headerDir, ".hpp", containers)
result3 = check_input_files_for_numbered_seq(sourceDir, ".cpp", containers)
if verbose:
if result2 or result3:
print " At least one input file needs fixing!"
else:
print " No input file needs fixing!"
# Return result.
return result1 or result2 or result3 | python | def check_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'],
seqType='both', verbose=False):
"""Checks if source- and header-files, used as input when pre-processing MPL-containers, need fixing."""
# Check the input files for containers in their variadic form.
result1 = False
if seqType == "both" or seqType == "variadic":
if verbose:
print "Check if input files for pre-processing Boost.MPL variadic containers need fixing."
result1 = check_input_files_for_variadic_seq(headerDir, sourceDir)
if verbose:
if result1:
print " At least one input file needs fixing!"
else:
print " No input file needs fixing!"
# Check the input files for containers in their numbered form.
result2 = False
result3 = False
if seqType == "both" or seqType == "numbered":
if verbose:
print "Check input files for pre-processing Boost.MPL numbered containers."
result2 = check_input_files_for_numbered_seq(headerDir, ".hpp", containers)
result3 = check_input_files_for_numbered_seq(sourceDir, ".cpp", containers)
if verbose:
if result2 or result3:
print " At least one input file needs fixing!"
else:
print " No input file needs fixing!"
# Return result.
return result1 or result2 or result3 | [
"def",
"check_input_files",
"(",
"headerDir",
",",
"sourceDir",
",",
"containers",
"=",
"[",
"'vector'",
",",
"'list'",
",",
"'set'",
",",
"'map'",
"]",
",",
"seqType",
"=",
"'both'",
",",
"verbose",
"=",
"False",
")",
":",
"# Check the input files for containers in their variadic form.",
"result1",
"=",
"False",
"if",
"seqType",
"==",
"\"both\"",
"or",
"seqType",
"==",
"\"variadic\"",
":",
"if",
"verbose",
":",
"print",
"\"Check if input files for pre-processing Boost.MPL variadic containers need fixing.\"",
"result1",
"=",
"check_input_files_for_variadic_seq",
"(",
"headerDir",
",",
"sourceDir",
")",
"if",
"verbose",
":",
"if",
"result1",
":",
"print",
"\" At least one input file needs fixing!\"",
"else",
":",
"print",
"\" No input file needs fixing!\"",
"# Check the input files for containers in their numbered form.",
"result2",
"=",
"False",
"result3",
"=",
"False",
"if",
"seqType",
"==",
"\"both\"",
"or",
"seqType",
"==",
"\"numbered\"",
":",
"if",
"verbose",
":",
"print",
"\"Check input files for pre-processing Boost.MPL numbered containers.\"",
"result2",
"=",
"check_input_files_for_numbered_seq",
"(",
"headerDir",
",",
"\".hpp\"",
",",
"containers",
")",
"result3",
"=",
"check_input_files_for_numbered_seq",
"(",
"sourceDir",
",",
"\".cpp\"",
",",
"containers",
")",
"if",
"verbose",
":",
"if",
"result2",
"or",
"result3",
":",
"print",
"\" At least one input file needs fixing!\"",
"else",
":",
"print",
"\" No input file needs fixing!\"",
"# Return result.",
"return",
"result1",
"or",
"result2",
"or",
"result3"
] | Checks if source- and header-files, used as input when pre-processing MPL-containers, need fixing. | [
"Checks",
"if",
"source",
"-",
"and",
"header",
"-",
"files",
"used",
"as",
"input",
"when",
"pre",
"-",
"processing",
"MPL",
"-",
"containers",
"need",
"fixing",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L62-L90 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | fix_header_comment | def fix_header_comment(filename, timestamp):
"""Fixes the header-comment of the given file."""
# Fix input file.
name = os.path.basename( filename )
for line in fileinput.input( filename, inplace=1, mode="rU" ):
# If header-comment already contains anything for '$Id$', remove it.
line = re.sub(r'\$Id:[^$]+\$', r'$Id$', line.rstrip())
# Replace '$Id$' by a string containing the file's name (and a timestamp)!
line = re.sub(re.escape(r'$Id$'), r'$Id: ' + name + r' ' + timestamp.isoformat() + r' $', line.rstrip())
print(line) | python | def fix_header_comment(filename, timestamp):
"""Fixes the header-comment of the given file."""
# Fix input file.
name = os.path.basename( filename )
for line in fileinput.input( filename, inplace=1, mode="rU" ):
# If header-comment already contains anything for '$Id$', remove it.
line = re.sub(r'\$Id:[^$]+\$', r'$Id$', line.rstrip())
# Replace '$Id$' by a string containing the file's name (and a timestamp)!
line = re.sub(re.escape(r'$Id$'), r'$Id: ' + name + r' ' + timestamp.isoformat() + r' $', line.rstrip())
print(line) | [
"def",
"fix_header_comment",
"(",
"filename",
",",
"timestamp",
")",
":",
"# Fix input file.",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"filename",
",",
"inplace",
"=",
"1",
",",
"mode",
"=",
"\"rU\"",
")",
":",
"# If header-comment already contains anything for '$Id$', remove it.",
"line",
"=",
"re",
".",
"sub",
"(",
"r'\\$Id:[^$]+\\$'",
",",
"r'$Id$'",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"# Replace '$Id$' by a string containing the file's name (and a timestamp)!",
"line",
"=",
"re",
".",
"sub",
"(",
"re",
".",
"escape",
"(",
"r'$Id$'",
")",
",",
"r'$Id: '",
"+",
"name",
"+",
"r' '",
"+",
"timestamp",
".",
"isoformat",
"(",
")",
"+",
"r' $'",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"print",
"(",
"line",
")"
] | Fixes the header-comment of the given file. | [
"Fixes",
"the",
"header",
"-",
"comment",
"of",
"the",
"given",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L92-L101 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | fix_input_files_for_variadic_seq | def fix_input_files_for_variadic_seq(headerDir, sourceDir, timestamp):
"""Fixes files used as input when pre-processing MPL-containers in their variadic form."""
# Fix files in include/source-directories.
files = glob.glob( os.path.join( headerDir, "*.hpp" ) )
files += glob.glob( os.path.join( headerDir, "aux_", "*.hpp" ) )
files += glob.glob( os.path.join( sourceDir, "src", "*" ) )
for currentFile in sorted( files ):
fix_header_comment( currentFile, timestamp ) | python | def fix_input_files_for_variadic_seq(headerDir, sourceDir, timestamp):
"""Fixes files used as input when pre-processing MPL-containers in their variadic form."""
# Fix files in include/source-directories.
files = glob.glob( os.path.join( headerDir, "*.hpp" ) )
files += glob.glob( os.path.join( headerDir, "aux_", "*.hpp" ) )
files += glob.glob( os.path.join( sourceDir, "src", "*" ) )
for currentFile in sorted( files ):
fix_header_comment( currentFile, timestamp ) | [
"def",
"fix_input_files_for_variadic_seq",
"(",
"headerDir",
",",
"sourceDir",
",",
"timestamp",
")",
":",
"# Fix files in include/source-directories.",
"files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"headerDir",
",",
"\"*.hpp\"",
")",
")",
"files",
"+=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"headerDir",
",",
"\"aux_\"",
",",
"\"*.hpp\"",
")",
")",
"files",
"+=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sourceDir",
",",
"\"src\"",
",",
"\"*\"",
")",
")",
"for",
"currentFile",
"in",
"sorted",
"(",
"files",
")",
":",
"fix_header_comment",
"(",
"currentFile",
",",
"timestamp",
")"
] | Fixes files used as input when pre-processing MPL-containers in their variadic form. | [
"Fixes",
"files",
"used",
"as",
"input",
"when",
"pre",
"-",
"processing",
"MPL",
"-",
"containers",
"in",
"their",
"variadic",
"form",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L104-L111 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | fix_input_files_for_numbered_seq | def fix_input_files_for_numbered_seq(sourceDir, suffix, timestamp, containers):
"""Fixes files used as input when pre-processing MPL-containers in their numbered form."""
# Fix input files for each MPL-container type.
for container in containers:
files = glob.glob( os.path.join( sourceDir, container, container + '*' + suffix ) )
for currentFile in sorted( files ):
fix_header_comment( currentFile, timestamp ) | python | def fix_input_files_for_numbered_seq(sourceDir, suffix, timestamp, containers):
"""Fixes files used as input when pre-processing MPL-containers in their numbered form."""
# Fix input files for each MPL-container type.
for container in containers:
files = glob.glob( os.path.join( sourceDir, container, container + '*' + suffix ) )
for currentFile in sorted( files ):
fix_header_comment( currentFile, timestamp ) | [
"def",
"fix_input_files_for_numbered_seq",
"(",
"sourceDir",
",",
"suffix",
",",
"timestamp",
",",
"containers",
")",
":",
"# Fix input files for each MPL-container type.",
"for",
"container",
"in",
"containers",
":",
"files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sourceDir",
",",
"container",
",",
"container",
"+",
"'*'",
"+",
"suffix",
")",
")",
"for",
"currentFile",
"in",
"sorted",
"(",
"files",
")",
":",
"fix_header_comment",
"(",
"currentFile",
",",
"timestamp",
")"
] | Fixes files used as input when pre-processing MPL-containers in their numbered form. | [
"Fixes",
"files",
"used",
"as",
"input",
"when",
"pre",
"-",
"processing",
"MPL",
"-",
"containers",
"in",
"their",
"numbered",
"form",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L114-L120 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | fix_input_files | def fix_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'],
seqType='both', verbose=False):
"""Fixes source- and header-files used as input when pre-processing MPL-containers."""
# The new modification time.
timestamp = datetime.datetime.now();
# Fix the input files for containers in their variadic form.
if seqType == "both" or seqType == "variadic":
if verbose:
print "Fix input files for pre-processing Boost.MPL variadic containers."
fix_input_files_for_variadic_seq(headerDir, sourceDir, timestamp)
# Fix the input files for containers in their numbered form.
if seqType == "both" or seqType == "numbered":
if verbose:
print "Fix input files for pre-processing Boost.MPL numbered containers."
fix_input_files_for_numbered_seq(headerDir, ".hpp", timestamp, containers)
fix_input_files_for_numbered_seq(sourceDir, ".cpp", timestamp, containers) | python | def fix_input_files(headerDir, sourceDir, containers=['vector', 'list', 'set', 'map'],
seqType='both', verbose=False):
"""Fixes source- and header-files used as input when pre-processing MPL-containers."""
# The new modification time.
timestamp = datetime.datetime.now();
# Fix the input files for containers in their variadic form.
if seqType == "both" or seqType == "variadic":
if verbose:
print "Fix input files for pre-processing Boost.MPL variadic containers."
fix_input_files_for_variadic_seq(headerDir, sourceDir, timestamp)
# Fix the input files for containers in their numbered form.
if seqType == "both" or seqType == "numbered":
if verbose:
print "Fix input files for pre-processing Boost.MPL numbered containers."
fix_input_files_for_numbered_seq(headerDir, ".hpp", timestamp, containers)
fix_input_files_for_numbered_seq(sourceDir, ".cpp", timestamp, containers) | [
"def",
"fix_input_files",
"(",
"headerDir",
",",
"sourceDir",
",",
"containers",
"=",
"[",
"'vector'",
",",
"'list'",
",",
"'set'",
",",
"'map'",
"]",
",",
"seqType",
"=",
"'both'",
",",
"verbose",
"=",
"False",
")",
":",
"# The new modification time.",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"# Fix the input files for containers in their variadic form.",
"if",
"seqType",
"==",
"\"both\"",
"or",
"seqType",
"==",
"\"variadic\"",
":",
"if",
"verbose",
":",
"print",
"\"Fix input files for pre-processing Boost.MPL variadic containers.\"",
"fix_input_files_for_variadic_seq",
"(",
"headerDir",
",",
"sourceDir",
",",
"timestamp",
")",
"# Fix the input files for containers in their numbered form.",
"if",
"seqType",
"==",
"\"both\"",
"or",
"seqType",
"==",
"\"numbered\"",
":",
"if",
"verbose",
":",
"print",
"\"Fix input files for pre-processing Boost.MPL numbered containers.\"",
"fix_input_files_for_numbered_seq",
"(",
"headerDir",
",",
"\".hpp\"",
",",
"timestamp",
",",
"containers",
")",
"fix_input_files_for_numbered_seq",
"(",
"sourceDir",
",",
"\".cpp\"",
",",
"timestamp",
",",
"containers",
")"
] | Fixes source- and header-files used as input when pre-processing MPL-containers. | [
"Fixes",
"source",
"-",
"and",
"header",
"-",
"files",
"used",
"as",
"input",
"when",
"pre",
"-",
"processing",
"MPL",
"-",
"containers",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L123-L138 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | to_existing_absolute_path | def to_existing_absolute_path(string):
"""Converts a path into its absolute path and verifies that it exists or throws an exception."""
value = os.path.abspath(string)
if not os.path.exists( value ) or not os.path.isdir( value ):
msg = '"%r" is not a valid path to a directory.' % string
raise argparse.ArgumentTypeError(msg)
return value | python | def to_existing_absolute_path(string):
"""Converts a path into its absolute path and verifies that it exists or throws an exception."""
value = os.path.abspath(string)
if not os.path.exists( value ) or not os.path.isdir( value ):
msg = '"%r" is not a valid path to a directory.' % string
raise argparse.ArgumentTypeError(msg)
return value | [
"def",
"to_existing_absolute_path",
"(",
"string",
")",
":",
"value",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"string",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"value",
")",
"or",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"value",
")",
":",
"msg",
"=",
"'\"%r\" is not a valid path to a directory.'",
"%",
"string",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"msg",
")",
"return",
"value"
] | Converts a path into its absolute path and verifies that it exists or throws an exception. | [
"Converts",
"a",
"path",
"into",
"its",
"absolute",
"path",
"and",
"verifies",
"that",
"it",
"exists",
"or",
"throws",
"an",
"exception",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L141-L147 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | main | def main():
"""The main function."""
# Prepare and run cmdline-parser.
cmdlineParser = argparse.ArgumentParser(
description="Fixes the input files used for pre-processing of Boost.MPL headers.")
cmdlineParser.add_argument("-v", "--verbose", dest='verbose', action='store_true',
help="Be a little bit more verbose.")
cmdlineParser.add_argument("--check-only", dest='checkonly', action='store_true',
help="Only checks if fixing is required.")
cmdlineParser.add_argument(dest='sourceDir', metavar="<source-dir>",
type=to_existing_absolute_path,
help="The source-directory of Boost.")
args = cmdlineParser.parse_args()
# Some verbose debug output.
if args.verbose:
print "Arguments extracted from command-line:"
print " verbose = ", args.verbose
print " check-only = ", args.checkonly
print " source directory = ", args.sourceDir
# The directories for header- and source files of Boost.MPL.
# NOTE: Assuming 'args.sourceDir' is the source-directory of the entire boost project.
headerDir = os.path.join( args.sourceDir, "boost", "mpl" )
sourceDir = os.path.join( args.sourceDir, "libs", "mpl", "preprocessed" )
# Check that the header/source-directories exist.
if not os.path.exists( headerDir ) or not os.path.exists( sourceDir ):
# Maybe 'args.sourceDir' is not the source-directory of the entire boost project
# but instead of the Boost.MPL git-directory, only?
headerDir = os.path.join( args.sourceDir, "include", "boost", "mpl" )
sourceDir = os.path.join( args.sourceDir, "preprocessed" )
if not os.path.exists( headerDir ) or not os.path.exists( sourceDir ):
cmdlineParser.print_usage()
print "error: Cannot find Boost.MPL header/source files in given Boost source-directory!"
sys.exit(0)
# Some verbose debug output.
if args.verbose:
print "Chosen header-directory: ", headerDir
print "Chosen source-directory: ", sourceDir
if args.checkonly:
# Check input files for generating pre-processed headers.
result = check_input_files(headerDir, sourceDir, verbose = args.verbose)
if result:
print "Fixing the input-files used for pre-processing of Boost.MPL headers IS required."
else:
print "Fixing the input-files used for pre-processing of Boost.MPL headers is NOT required."
else:
# Fix input files for generating pre-processed headers.
fix_input_files(headerDir, sourceDir, verbose = args.verbose) | python | def main():
"""The main function."""
# Prepare and run cmdline-parser.
cmdlineParser = argparse.ArgumentParser(
description="Fixes the input files used for pre-processing of Boost.MPL headers.")
cmdlineParser.add_argument("-v", "--verbose", dest='verbose', action='store_true',
help="Be a little bit more verbose.")
cmdlineParser.add_argument("--check-only", dest='checkonly', action='store_true',
help="Only checks if fixing is required.")
cmdlineParser.add_argument(dest='sourceDir', metavar="<source-dir>",
type=to_existing_absolute_path,
help="The source-directory of Boost.")
args = cmdlineParser.parse_args()
# Some verbose debug output.
if args.verbose:
print "Arguments extracted from command-line:"
print " verbose = ", args.verbose
print " check-only = ", args.checkonly
print " source directory = ", args.sourceDir
# The directories for header- and source files of Boost.MPL.
# NOTE: Assuming 'args.sourceDir' is the source-directory of the entire boost project.
headerDir = os.path.join( args.sourceDir, "boost", "mpl" )
sourceDir = os.path.join( args.sourceDir, "libs", "mpl", "preprocessed" )
# Check that the header/source-directories exist.
if not os.path.exists( headerDir ) or not os.path.exists( sourceDir ):
# Maybe 'args.sourceDir' is not the source-directory of the entire boost project
# but instead of the Boost.MPL git-directory, only?
headerDir = os.path.join( args.sourceDir, "include", "boost", "mpl" )
sourceDir = os.path.join( args.sourceDir, "preprocessed" )
if not os.path.exists( headerDir ) or not os.path.exists( sourceDir ):
cmdlineParser.print_usage()
print "error: Cannot find Boost.MPL header/source files in given Boost source-directory!"
sys.exit(0)
# Some verbose debug output.
if args.verbose:
print "Chosen header-directory: ", headerDir
print "Chosen source-directory: ", sourceDir
if args.checkonly:
# Check input files for generating pre-processed headers.
result = check_input_files(headerDir, sourceDir, verbose = args.verbose)
if result:
print "Fixing the input-files used for pre-processing of Boost.MPL headers IS required."
else:
print "Fixing the input-files used for pre-processing of Boost.MPL headers is NOT required."
else:
# Fix input files for generating pre-processed headers.
fix_input_files(headerDir, sourceDir, verbose = args.verbose) | [
"def",
"main",
"(",
")",
":",
"# Prepare and run cmdline-parser.",
"cmdlineParser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Fixes the input files used for pre-processing of Boost.MPL headers.\"",
")",
"cmdlineParser",
".",
"add_argument",
"(",
"\"-v\"",
",",
"\"--verbose\"",
",",
"dest",
"=",
"'verbose'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"Be a little bit more verbose.\"",
")",
"cmdlineParser",
".",
"add_argument",
"(",
"\"--check-only\"",
",",
"dest",
"=",
"'checkonly'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"Only checks if fixing is required.\"",
")",
"cmdlineParser",
".",
"add_argument",
"(",
"dest",
"=",
"'sourceDir'",
",",
"metavar",
"=",
"\"<source-dir>\"",
",",
"type",
"=",
"to_existing_absolute_path",
",",
"help",
"=",
"\"The source-directory of Boost.\"",
")",
"args",
"=",
"cmdlineParser",
".",
"parse_args",
"(",
")",
"# Some verbose debug output.",
"if",
"args",
".",
"verbose",
":",
"print",
"\"Arguments extracted from command-line:\"",
"print",
"\" verbose = \"",
",",
"args",
".",
"verbose",
"print",
"\" check-only = \"",
",",
"args",
".",
"checkonly",
"print",
"\" source directory = \"",
",",
"args",
".",
"sourceDir",
"# The directories for header- and source files of Boost.MPL. ",
"# NOTE: Assuming 'args.sourceDir' is the source-directory of the entire boost project.",
"headerDir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"sourceDir",
",",
"\"boost\"",
",",
"\"mpl\"",
")",
"sourceDir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"sourceDir",
",",
"\"libs\"",
",",
"\"mpl\"",
",",
"\"preprocessed\"",
")",
"# Check that the header/source-directories exist.",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"headerDir",
")",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"sourceDir",
")",
":",
"# Maybe 'args.sourceDir' is not the source-directory of the entire boost project",
"# but instead of the Boost.MPL git-directory, only?",
"headerDir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"sourceDir",
",",
"\"include\"",
",",
"\"boost\"",
",",
"\"mpl\"",
")",
"sourceDir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"sourceDir",
",",
"\"preprocessed\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"headerDir",
")",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"sourceDir",
")",
":",
"cmdlineParser",
".",
"print_usage",
"(",
")",
"print",
"\"error: Cannot find Boost.MPL header/source files in given Boost source-directory!\"",
"sys",
".",
"exit",
"(",
"0",
")",
"# Some verbose debug output.",
"if",
"args",
".",
"verbose",
":",
"print",
"\"Chosen header-directory: \"",
",",
"headerDir",
"print",
"\"Chosen source-directory: \"",
",",
"sourceDir",
"if",
"args",
".",
"checkonly",
":",
"# Check input files for generating pre-processed headers.",
"result",
"=",
"check_input_files",
"(",
"headerDir",
",",
"sourceDir",
",",
"verbose",
"=",
"args",
".",
"verbose",
")",
"if",
"result",
":",
"print",
"\"Fixing the input-files used for pre-processing of Boost.MPL headers IS required.\"",
"else",
":",
"print",
"\"Fixing the input-files used for pre-processing of Boost.MPL headers is NOT required.\"",
"else",
":",
"# Fix input files for generating pre-processed headers.",
"fix_input_files",
"(",
"headerDir",
",",
"sourceDir",
",",
"verbose",
"=",
"args",
".",
"verbose",
")"
] | The main function. | [
"The",
"main",
"function",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L150-L201 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/image_similarity/image_similarity.py | create | def create(dataset, label = None, feature = None, model = 'resnet-50', verbose = True,
batch_size = 64):
"""
Create a :class:`ImageSimilarityModel` model.
Parameters
----------
dataset : SFrame
Input data. The column named by the 'feature' parameter will be
extracted for modeling.
label : string
Name of the SFrame column with row labels to be used as uuid's to
identify the data. If 'label' is set to None, row numbers are used to
identify reference dataset rows when the model is queried.
feature : string
indicates that the SFrame has only column of Image type and that will
Name of the column containing the input images. 'None' (the default)
be used for similarity.
model: string, optional
Uses a pretrained model to bootstrap an image similarity model
- "resnet-50" : Uses a pretrained resnet model.
- "squeezenet_v1.1" : Uses a pretrained squeezenet model.
- "VisionFeaturePrint_Scene": Uses an OS internal feature extractor.
Only on available on iOS 12.0+,
macOS 10.14+ and tvOS 12.0+.
Models are downloaded from the internet if not available locally. Once
downloaded, the models are cached for future use.
verbose : bool, optional
If True, print progress updates and model details.
batch_size : int, optional
If you are getting memory errors, try decreasing this value. If you
have a powerful computer, increasing this value may improve performance.
Returns
-------
out : ImageSimilarityModel
A trained :class:`ImageSimilarityModel` model.
See Also
--------
ImageSimilarityModel
Examples
--------
.. sourcecode:: python
# Train an image similarity model
>>> model = turicreate.image_similarity.create(data)
# Query the model for similar images
>>> similar_images = model.query(data)
+-------------+-----------------+-------------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+-------------------+------+
| 0 | 0 | 0.0 | 1 |
| 0 | 519 | 12.5319706301 | 2 |
| 0 | 1619 | 12.5563764596 | 3 |
| 0 | 186 | 12.6132604915 | 4 |
| 0 | 1809 | 12.9180964745 | 5 |
| 1 | 1 | 2.02304872852e-06 | 1 |
| 1 | 1579 | 11.4288186151 | 2 |
| 1 | 1237 | 12.3764325949 | 3 |
| 1 | 80 | 12.7264363676 | 4 |
| 1 | 58 | 12.7675058558 | 5 |
+-------------+-----------------+-------------------+------+
[500 rows x 4 columns]
"""
start_time = _time.time()
# Check parameters
allowed_models = list(_pre_trained_models.MODELS.keys())
if _mac_ver() >= (10,14):
allowed_models.append('VisionFeaturePrint_Scene')
# Also, to make sure existing code doesn't break, replace incorrect name
# with the correct name version
if model == "VisionFeaturePrint_Screen":
print("WARNING: Correct spelling of model name is VisionFeaturePrint_Scene. VisionFeaturePrint_Screen will be removed in future releases.")
model = "VisionFeaturePrint_Scene"
_tkutl._check_categorical_option_type('model', model, allowed_models)
if len(dataset) == 0:
raise _ToolkitError('Unable to train on empty dataset')
if (label is not None) and (label not in dataset.column_names()):
raise _ToolkitError("Row label column '%s' does not exist" % label)
if (feature is not None) and (feature not in dataset.column_names()):
raise _ToolkitError("Image feature column '%s' does not exist" % feature)
if(batch_size < 1):
raise ValueError("'batch_size' must be greater than or equal to 1")
# Set defaults
if feature is None:
feature = _tkutl._find_only_image_column(dataset)
feature_extractor = _image_feature_extractor._create_feature_extractor(model)
# Extract features
extracted_features = _tc.SFrame({
'__image_features__': feature_extractor.extract_features(dataset, feature, verbose=verbose,
batch_size=batch_size),
})
# Train a similarity model using the extracted features
if label is not None:
extracted_features[label] = dataset[label]
nn_model = _tc.nearest_neighbors.create(extracted_features, label = label,
features = ['__image_features__'], verbose = verbose)
# set input image shape
if model in _pre_trained_models.MODELS:
input_image_shape = _pre_trained_models.MODELS[model].input_image_shape
else: # model == VisionFeaturePrint_Scene
input_image_shape = (3, 299, 299)
# Save the model
state = {
'similarity_model': nn_model,
'model': model,
'feature_extractor': feature_extractor,
'input_image_shape': input_image_shape,
'label': label,
'feature': feature,
'num_features': 1,
'num_examples': nn_model.num_examples,
'training_time': _time.time() - start_time,
}
return ImageSimilarityModel(state) | python | def create(dataset, label = None, feature = None, model = 'resnet-50', verbose = True,
batch_size = 64):
"""
Create a :class:`ImageSimilarityModel` model.
Parameters
----------
dataset : SFrame
Input data. The column named by the 'feature' parameter will be
extracted for modeling.
label : string
Name of the SFrame column with row labels to be used as uuid's to
identify the data. If 'label' is set to None, row numbers are used to
identify reference dataset rows when the model is queried.
feature : string
indicates that the SFrame has only column of Image type and that will
Name of the column containing the input images. 'None' (the default)
be used for similarity.
model: string, optional
Uses a pretrained model to bootstrap an image similarity model
- "resnet-50" : Uses a pretrained resnet model.
- "squeezenet_v1.1" : Uses a pretrained squeezenet model.
- "VisionFeaturePrint_Scene": Uses an OS internal feature extractor.
Only on available on iOS 12.0+,
macOS 10.14+ and tvOS 12.0+.
Models are downloaded from the internet if not available locally. Once
downloaded, the models are cached for future use.
verbose : bool, optional
If True, print progress updates and model details.
batch_size : int, optional
If you are getting memory errors, try decreasing this value. If you
have a powerful computer, increasing this value may improve performance.
Returns
-------
out : ImageSimilarityModel
A trained :class:`ImageSimilarityModel` model.
See Also
--------
ImageSimilarityModel
Examples
--------
.. sourcecode:: python
# Train an image similarity model
>>> model = turicreate.image_similarity.create(data)
# Query the model for similar images
>>> similar_images = model.query(data)
+-------------+-----------------+-------------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+-------------------+------+
| 0 | 0 | 0.0 | 1 |
| 0 | 519 | 12.5319706301 | 2 |
| 0 | 1619 | 12.5563764596 | 3 |
| 0 | 186 | 12.6132604915 | 4 |
| 0 | 1809 | 12.9180964745 | 5 |
| 1 | 1 | 2.02304872852e-06 | 1 |
| 1 | 1579 | 11.4288186151 | 2 |
| 1 | 1237 | 12.3764325949 | 3 |
| 1 | 80 | 12.7264363676 | 4 |
| 1 | 58 | 12.7675058558 | 5 |
+-------------+-----------------+-------------------+------+
[500 rows x 4 columns]
"""
start_time = _time.time()
# Check parameters
allowed_models = list(_pre_trained_models.MODELS.keys())
if _mac_ver() >= (10,14):
allowed_models.append('VisionFeaturePrint_Scene')
# Also, to make sure existing code doesn't break, replace incorrect name
# with the correct name version
if model == "VisionFeaturePrint_Screen":
print("WARNING: Correct spelling of model name is VisionFeaturePrint_Scene. VisionFeaturePrint_Screen will be removed in future releases.")
model = "VisionFeaturePrint_Scene"
_tkutl._check_categorical_option_type('model', model, allowed_models)
if len(dataset) == 0:
raise _ToolkitError('Unable to train on empty dataset')
if (label is not None) and (label not in dataset.column_names()):
raise _ToolkitError("Row label column '%s' does not exist" % label)
if (feature is not None) and (feature not in dataset.column_names()):
raise _ToolkitError("Image feature column '%s' does not exist" % feature)
if(batch_size < 1):
raise ValueError("'batch_size' must be greater than or equal to 1")
# Set defaults
if feature is None:
feature = _tkutl._find_only_image_column(dataset)
feature_extractor = _image_feature_extractor._create_feature_extractor(model)
# Extract features
extracted_features = _tc.SFrame({
'__image_features__': feature_extractor.extract_features(dataset, feature, verbose=verbose,
batch_size=batch_size),
})
# Train a similarity model using the extracted features
if label is not None:
extracted_features[label] = dataset[label]
nn_model = _tc.nearest_neighbors.create(extracted_features, label = label,
features = ['__image_features__'], verbose = verbose)
# set input image shape
if model in _pre_trained_models.MODELS:
input_image_shape = _pre_trained_models.MODELS[model].input_image_shape
else: # model == VisionFeaturePrint_Scene
input_image_shape = (3, 299, 299)
# Save the model
state = {
'similarity_model': nn_model,
'model': model,
'feature_extractor': feature_extractor,
'input_image_shape': input_image_shape,
'label': label,
'feature': feature,
'num_features': 1,
'num_examples': nn_model.num_examples,
'training_time': _time.time() - start_time,
}
return ImageSimilarityModel(state) | [
"def",
"create",
"(",
"dataset",
",",
"label",
"=",
"None",
",",
"feature",
"=",
"None",
",",
"model",
"=",
"'resnet-50'",
",",
"verbose",
"=",
"True",
",",
"batch_size",
"=",
"64",
")",
":",
"start_time",
"=",
"_time",
".",
"time",
"(",
")",
"# Check parameters",
"allowed_models",
"=",
"list",
"(",
"_pre_trained_models",
".",
"MODELS",
".",
"keys",
"(",
")",
")",
"if",
"_mac_ver",
"(",
")",
">=",
"(",
"10",
",",
"14",
")",
":",
"allowed_models",
".",
"append",
"(",
"'VisionFeaturePrint_Scene'",
")",
"# Also, to make sure existing code doesn't break, replace incorrect name",
"# with the correct name version",
"if",
"model",
"==",
"\"VisionFeaturePrint_Screen\"",
":",
"print",
"(",
"\"WARNING: Correct spelling of model name is VisionFeaturePrint_Scene. VisionFeaturePrint_Screen will be removed in future releases.\"",
")",
"model",
"=",
"\"VisionFeaturePrint_Scene\"",
"_tkutl",
".",
"_check_categorical_option_type",
"(",
"'model'",
",",
"model",
",",
"allowed_models",
")",
"if",
"len",
"(",
"dataset",
")",
"==",
"0",
":",
"raise",
"_ToolkitError",
"(",
"'Unable to train on empty dataset'",
")",
"if",
"(",
"label",
"is",
"not",
"None",
")",
"and",
"(",
"label",
"not",
"in",
"dataset",
".",
"column_names",
"(",
")",
")",
":",
"raise",
"_ToolkitError",
"(",
"\"Row label column '%s' does not exist\"",
"%",
"label",
")",
"if",
"(",
"feature",
"is",
"not",
"None",
")",
"and",
"(",
"feature",
"not",
"in",
"dataset",
".",
"column_names",
"(",
")",
")",
":",
"raise",
"_ToolkitError",
"(",
"\"Image feature column '%s' does not exist\"",
"%",
"feature",
")",
"if",
"(",
"batch_size",
"<",
"1",
")",
":",
"raise",
"ValueError",
"(",
"\"'batch_size' must be greater than or equal to 1\"",
")",
"# Set defaults",
"if",
"feature",
"is",
"None",
":",
"feature",
"=",
"_tkutl",
".",
"_find_only_image_column",
"(",
"dataset",
")",
"feature_extractor",
"=",
"_image_feature_extractor",
".",
"_create_feature_extractor",
"(",
"model",
")",
"# Extract features",
"extracted_features",
"=",
"_tc",
".",
"SFrame",
"(",
"{",
"'__image_features__'",
":",
"feature_extractor",
".",
"extract_features",
"(",
"dataset",
",",
"feature",
",",
"verbose",
"=",
"verbose",
",",
"batch_size",
"=",
"batch_size",
")",
",",
"}",
")",
"# Train a similarity model using the extracted features",
"if",
"label",
"is",
"not",
"None",
":",
"extracted_features",
"[",
"label",
"]",
"=",
"dataset",
"[",
"label",
"]",
"nn_model",
"=",
"_tc",
".",
"nearest_neighbors",
".",
"create",
"(",
"extracted_features",
",",
"label",
"=",
"label",
",",
"features",
"=",
"[",
"'__image_features__'",
"]",
",",
"verbose",
"=",
"verbose",
")",
"# set input image shape",
"if",
"model",
"in",
"_pre_trained_models",
".",
"MODELS",
":",
"input_image_shape",
"=",
"_pre_trained_models",
".",
"MODELS",
"[",
"model",
"]",
".",
"input_image_shape",
"else",
":",
"# model == VisionFeaturePrint_Scene",
"input_image_shape",
"=",
"(",
"3",
",",
"299",
",",
"299",
")",
"# Save the model",
"state",
"=",
"{",
"'similarity_model'",
":",
"nn_model",
",",
"'model'",
":",
"model",
",",
"'feature_extractor'",
":",
"feature_extractor",
",",
"'input_image_shape'",
":",
"input_image_shape",
",",
"'label'",
":",
"label",
",",
"'feature'",
":",
"feature",
",",
"'num_features'",
":",
"1",
",",
"'num_examples'",
":",
"nn_model",
".",
"num_examples",
",",
"'training_time'",
":",
"_time",
".",
"time",
"(",
")",
"-",
"start_time",
",",
"}",
"return",
"ImageSimilarityModel",
"(",
"state",
")"
] | Create a :class:`ImageSimilarityModel` model.
Parameters
----------
dataset : SFrame
Input data. The column named by the 'feature' parameter will be
extracted for modeling.
label : string
Name of the SFrame column with row labels to be used as uuid's to
identify the data. If 'label' is set to None, row numbers are used to
identify reference dataset rows when the model is queried.
feature : string
indicates that the SFrame has only column of Image type and that will
Name of the column containing the input images. 'None' (the default)
be used for similarity.
model: string, optional
Uses a pretrained model to bootstrap an image similarity model
- "resnet-50" : Uses a pretrained resnet model.
- "squeezenet_v1.1" : Uses a pretrained squeezenet model.
- "VisionFeaturePrint_Scene": Uses an OS internal feature extractor.
Only on available on iOS 12.0+,
macOS 10.14+ and tvOS 12.0+.
Models are downloaded from the internet if not available locally. Once
downloaded, the models are cached for future use.
verbose : bool, optional
If True, print progress updates and model details.
batch_size : int, optional
If you are getting memory errors, try decreasing this value. If you
have a powerful computer, increasing this value may improve performance.
Returns
-------
out : ImageSimilarityModel
A trained :class:`ImageSimilarityModel` model.
See Also
--------
ImageSimilarityModel
Examples
--------
.. sourcecode:: python
# Train an image similarity model
>>> model = turicreate.image_similarity.create(data)
# Query the model for similar images
>>> similar_images = model.query(data)
+-------------+-----------------+-------------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+-------------------+------+
| 0 | 0 | 0.0 | 1 |
| 0 | 519 | 12.5319706301 | 2 |
| 0 | 1619 | 12.5563764596 | 3 |
| 0 | 186 | 12.6132604915 | 4 |
| 0 | 1809 | 12.9180964745 | 5 |
| 1 | 1 | 2.02304872852e-06 | 1 |
| 1 | 1579 | 11.4288186151 | 2 |
| 1 | 1237 | 12.3764325949 | 3 |
| 1 | 80 | 12.7264363676 | 4 |
| 1 | 58 | 12.7675058558 | 5 |
+-------------+-----------------+-------------------+------+
[500 rows x 4 columns] | [
"Create",
"a",
":",
"class",
":",
"ImageSimilarityModel",
"model",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_similarity/image_similarity.py#L27-L162 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/image_similarity/image_similarity.py | ImageSimilarityModel._load_version | def _load_version(cls, state, version):
"""
A function to load a previously saved ImageClassifier
instance.
Parameters
----------
unpickler : GLUnpickler
A GLUnpickler file handler.
version : int
Version number maintained by the class writer.
"""
_tkutl._model_version_check(version, cls._PYTHON_IMAGE_SIMILARITY_VERSION)
from turicreate.toolkits.nearest_neighbors import NearestNeighborsModel
state['similarity_model'] = NearestNeighborsModel(state['similarity_model'])
# Correct models saved with a previous typo
if state['model'] == "VisionFeaturePrint_Screen":
state['model'] = "VisionFeaturePrint_Scene"
if state['model'] == "VisionFeaturePrint_Scene" and _mac_ver() < (10,14):
raise ToolkitError("Can not load model on this operating system. This model uses VisionFeaturePrint_Scene, "
"which is only supported on macOS 10.14 and higher.")
state['feature_extractor'] = _image_feature_extractor._create_feature_extractor(state['model'])
state['input_image_shape'] = tuple([int(i) for i in state['input_image_shape']])
return ImageSimilarityModel(state) | python | def _load_version(cls, state, version):
"""
A function to load a previously saved ImageClassifier
instance.
Parameters
----------
unpickler : GLUnpickler
A GLUnpickler file handler.
version : int
Version number maintained by the class writer.
"""
_tkutl._model_version_check(version, cls._PYTHON_IMAGE_SIMILARITY_VERSION)
from turicreate.toolkits.nearest_neighbors import NearestNeighborsModel
state['similarity_model'] = NearestNeighborsModel(state['similarity_model'])
# Correct models saved with a previous typo
if state['model'] == "VisionFeaturePrint_Screen":
state['model'] = "VisionFeaturePrint_Scene"
if state['model'] == "VisionFeaturePrint_Scene" and _mac_ver() < (10,14):
raise ToolkitError("Can not load model on this operating system. This model uses VisionFeaturePrint_Scene, "
"which is only supported on macOS 10.14 and higher.")
state['feature_extractor'] = _image_feature_extractor._create_feature_extractor(state['model'])
state['input_image_shape'] = tuple([int(i) for i in state['input_image_shape']])
return ImageSimilarityModel(state) | [
"def",
"_load_version",
"(",
"cls",
",",
"state",
",",
"version",
")",
":",
"_tkutl",
".",
"_model_version_check",
"(",
"version",
",",
"cls",
".",
"_PYTHON_IMAGE_SIMILARITY_VERSION",
")",
"from",
"turicreate",
".",
"toolkits",
".",
"nearest_neighbors",
"import",
"NearestNeighborsModel",
"state",
"[",
"'similarity_model'",
"]",
"=",
"NearestNeighborsModel",
"(",
"state",
"[",
"'similarity_model'",
"]",
")",
"# Correct models saved with a previous typo",
"if",
"state",
"[",
"'model'",
"]",
"==",
"\"VisionFeaturePrint_Screen\"",
":",
"state",
"[",
"'model'",
"]",
"=",
"\"VisionFeaturePrint_Scene\"",
"if",
"state",
"[",
"'model'",
"]",
"==",
"\"VisionFeaturePrint_Scene\"",
"and",
"_mac_ver",
"(",
")",
"<",
"(",
"10",
",",
"14",
")",
":",
"raise",
"ToolkitError",
"(",
"\"Can not load model on this operating system. This model uses VisionFeaturePrint_Scene, \"",
"\"which is only supported on macOS 10.14 and higher.\"",
")",
"state",
"[",
"'feature_extractor'",
"]",
"=",
"_image_feature_extractor",
".",
"_create_feature_extractor",
"(",
"state",
"[",
"'model'",
"]",
")",
"state",
"[",
"'input_image_shape'",
"]",
"=",
"tuple",
"(",
"[",
"int",
"(",
"i",
")",
"for",
"i",
"in",
"state",
"[",
"'input_image_shape'",
"]",
"]",
")",
"return",
"ImageSimilarityModel",
"(",
"state",
")"
] | A function to load a previously saved ImageClassifier
instance.
Parameters
----------
unpickler : GLUnpickler
A GLUnpickler file handler.
version : int
Version number maintained by the class writer. | [
"A",
"function",
"to",
"load",
"a",
"previously",
"saved",
"ImageClassifier",
"instance",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_similarity/image_similarity.py#L208-L234 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/image_similarity/image_similarity.py | ImageSimilarityModel.query | def query(self, dataset, label=None, k=5, radius=None, verbose=True, batch_size=64):
"""
For each image, retrieve the nearest neighbors from the model's stored
data. In general, the query dataset does not need to be the same as
the reference data stored in the model.
Parameters
----------
dataset : SFrame | SArray | turicreate.Image
Query data.
If dataset is an SFrame, it must contain columns with the same
names and types as the features used to train the model.
Additional columns are ignored.
label : str, optional
Name of the query SFrame column with row labels. If 'label' is not
specified, row numbers are used to identify query dataset rows in
the output SFrame.
k : int, optional
Number of nearest neighbors to return from the reference set for
each query observation. The default is 5 neighbors, but setting it
to ``None`` will return all neighbors within ``radius`` of the
query point.
radius : float, optional
Only neighbors whose distance to a query point is smaller than this
value are returned. The default is ``None``, in which case the
``k`` nearest neighbors are returned for each query point,
regardless of distance.
verbose: bool, optional
If True, print progress updates and model details.
batch_size : int, optional
If you are getting memory errors, try decreasing this value. If you
have a powerful computer, increasing this value may improve performance.
Returns
-------
out : SFrame
An SFrame with the k-nearest neighbors of each query observation.
The result contains four columns: the first is the label of the
query observation, the second is the label of the nearby reference
observation, the third is the distance between the query and
reference observations, and the fourth is the rank of the reference
observation among the query's k-nearest neighbors.
See Also
--------
similarity_graph
Notes
-----
- If both ``k`` and ``radius`` are set to ``None``, each query point
returns all of the reference set. If the reference dataset has
:math:`n` rows and the query dataset has :math:`m` rows, the output
is an SFrame with :math:`nm` rows.
Examples
--------
>>> model.query(queries, 'label', k=2)
+-------------+-----------------+----------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+----------------+------+
| 0 | 2 | 0.305941170816 | 1 |
| 0 | 1 | 0.771556867638 | 2 |
| 1 | 1 | 0.390128184063 | 1 |
| 1 | 0 | 0.464004310325 | 2 |
| 2 | 0 | 0.170293863659 | 1 |
| 2 | 1 | 0.464004310325 | 2 |
+-------------+-----------------+----------------+------+
"""
if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)):
raise TypeError('dataset must be either an SFrame, SArray or turicreate.Image')
if(batch_size < 1):
raise ValueError("'batch_size' must be greater than or equal to 1")
if isinstance(dataset, _tc.SArray):
dataset = _tc.SFrame({self.feature: dataset})
elif isinstance(dataset, _tc.Image):
dataset = _tc.SFrame({self.feature: [dataset]})
extracted_features = self._extract_features(dataset, verbose=verbose, batch_size=batch_size)
if label is not None:
extracted_features[label] = dataset[label]
return self.similarity_model.query(extracted_features, label, k, radius, verbose) | python | def query(self, dataset, label=None, k=5, radius=None, verbose=True, batch_size=64):
"""
For each image, retrieve the nearest neighbors from the model's stored
data. In general, the query dataset does not need to be the same as
the reference data stored in the model.
Parameters
----------
dataset : SFrame | SArray | turicreate.Image
Query data.
If dataset is an SFrame, it must contain columns with the same
names and types as the features used to train the model.
Additional columns are ignored.
label : str, optional
Name of the query SFrame column with row labels. If 'label' is not
specified, row numbers are used to identify query dataset rows in
the output SFrame.
k : int, optional
Number of nearest neighbors to return from the reference set for
each query observation. The default is 5 neighbors, but setting it
to ``None`` will return all neighbors within ``radius`` of the
query point.
radius : float, optional
Only neighbors whose distance to a query point is smaller than this
value are returned. The default is ``None``, in which case the
``k`` nearest neighbors are returned for each query point,
regardless of distance.
verbose: bool, optional
If True, print progress updates and model details.
batch_size : int, optional
If you are getting memory errors, try decreasing this value. If you
have a powerful computer, increasing this value may improve performance.
Returns
-------
out : SFrame
An SFrame with the k-nearest neighbors of each query observation.
The result contains four columns: the first is the label of the
query observation, the second is the label of the nearby reference
observation, the third is the distance between the query and
reference observations, and the fourth is the rank of the reference
observation among the query's k-nearest neighbors.
See Also
--------
similarity_graph
Notes
-----
- If both ``k`` and ``radius`` are set to ``None``, each query point
returns all of the reference set. If the reference dataset has
:math:`n` rows and the query dataset has :math:`m` rows, the output
is an SFrame with :math:`nm` rows.
Examples
--------
>>> model.query(queries, 'label', k=2)
+-------------+-----------------+----------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+----------------+------+
| 0 | 2 | 0.305941170816 | 1 |
| 0 | 1 | 0.771556867638 | 2 |
| 1 | 1 | 0.390128184063 | 1 |
| 1 | 0 | 0.464004310325 | 2 |
| 2 | 0 | 0.170293863659 | 1 |
| 2 | 1 | 0.464004310325 | 2 |
+-------------+-----------------+----------------+------+
"""
if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)):
raise TypeError('dataset must be either an SFrame, SArray or turicreate.Image')
if(batch_size < 1):
raise ValueError("'batch_size' must be greater than or equal to 1")
if isinstance(dataset, _tc.SArray):
dataset = _tc.SFrame({self.feature: dataset})
elif isinstance(dataset, _tc.Image):
dataset = _tc.SFrame({self.feature: [dataset]})
extracted_features = self._extract_features(dataset, verbose=verbose, batch_size=batch_size)
if label is not None:
extracted_features[label] = dataset[label]
return self.similarity_model.query(extracted_features, label, k, radius, verbose) | [
"def",
"query",
"(",
"self",
",",
"dataset",
",",
"label",
"=",
"None",
",",
"k",
"=",
"5",
",",
"radius",
"=",
"None",
",",
"verbose",
"=",
"True",
",",
"batch_size",
"=",
"64",
")",
":",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"(",
"_tc",
".",
"SFrame",
",",
"_tc",
".",
"SArray",
",",
"_tc",
".",
"Image",
")",
")",
":",
"raise",
"TypeError",
"(",
"'dataset must be either an SFrame, SArray or turicreate.Image'",
")",
"if",
"(",
"batch_size",
"<",
"1",
")",
":",
"raise",
"ValueError",
"(",
"\"'batch_size' must be greater than or equal to 1\"",
")",
"if",
"isinstance",
"(",
"dataset",
",",
"_tc",
".",
"SArray",
")",
":",
"dataset",
"=",
"_tc",
".",
"SFrame",
"(",
"{",
"self",
".",
"feature",
":",
"dataset",
"}",
")",
"elif",
"isinstance",
"(",
"dataset",
",",
"_tc",
".",
"Image",
")",
":",
"dataset",
"=",
"_tc",
".",
"SFrame",
"(",
"{",
"self",
".",
"feature",
":",
"[",
"dataset",
"]",
"}",
")",
"extracted_features",
"=",
"self",
".",
"_extract_features",
"(",
"dataset",
",",
"verbose",
"=",
"verbose",
",",
"batch_size",
"=",
"batch_size",
")",
"if",
"label",
"is",
"not",
"None",
":",
"extracted_features",
"[",
"label",
"]",
"=",
"dataset",
"[",
"label",
"]",
"return",
"self",
".",
"similarity_model",
".",
"query",
"(",
"extracted_features",
",",
"label",
",",
"k",
",",
"radius",
",",
"verbose",
")"
] | For each image, retrieve the nearest neighbors from the model's stored
data. In general, the query dataset does not need to be the same as
the reference data stored in the model.
Parameters
----------
dataset : SFrame | SArray | turicreate.Image
Query data.
If dataset is an SFrame, it must contain columns with the same
names and types as the features used to train the model.
Additional columns are ignored.
label : str, optional
Name of the query SFrame column with row labels. If 'label' is not
specified, row numbers are used to identify query dataset rows in
the output SFrame.
k : int, optional
Number of nearest neighbors to return from the reference set for
each query observation. The default is 5 neighbors, but setting it
to ``None`` will return all neighbors within ``radius`` of the
query point.
radius : float, optional
Only neighbors whose distance to a query point is smaller than this
value are returned. The default is ``None``, in which case the
``k`` nearest neighbors are returned for each query point,
regardless of distance.
verbose: bool, optional
If True, print progress updates and model details.
batch_size : int, optional
If you are getting memory errors, try decreasing this value. If you
have a powerful computer, increasing this value may improve performance.
Returns
-------
out : SFrame
An SFrame with the k-nearest neighbors of each query observation.
The result contains four columns: the first is the label of the
query observation, the second is the label of the nearby reference
observation, the third is the distance between the query and
reference observations, and the fourth is the rank of the reference
observation among the query's k-nearest neighbors.
See Also
--------
similarity_graph
Notes
-----
- If both ``k`` and ``radius`` are set to ``None``, each query point
returns all of the reference set. If the reference dataset has
:math:`n` rows and the query dataset has :math:`m` rows, the output
is an SFrame with :math:`nm` rows.
Examples
--------
>>> model.query(queries, 'label', k=2)
+-------------+-----------------+----------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+----------------+------+
| 0 | 2 | 0.305941170816 | 1 |
| 0 | 1 | 0.771556867638 | 2 |
| 1 | 1 | 0.390128184063 | 1 |
| 1 | 0 | 0.464004310325 | 2 |
| 2 | 0 | 0.170293863659 | 1 |
| 2 | 1 | 0.464004310325 | 2 |
+-------------+-----------------+----------------+------+ | [
"For",
"each",
"image",
"retrieve",
"the",
"nearest",
"neighbors",
"from",
"the",
"model",
"s",
"stored",
"data",
".",
"In",
"general",
"the",
"query",
"dataset",
"does",
"not",
"need",
"to",
"be",
"the",
"same",
"as",
"the",
"reference",
"data",
"stored",
"in",
"the",
"model",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_similarity/image_similarity.py#L295-L381 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/image_similarity/image_similarity.py | ImageSimilarityModel.similarity_graph | def similarity_graph(self, k=5, radius=None, include_self_edges=False,
output_type='SGraph', verbose=True):
"""
Construct the similarity graph on the reference dataset, which is
already stored in the model to find the top `k` similar images for each
image in your input dataset.
This is conceptually very similar to running `query` with the reference
set, but this method is optimized for the purpose, syntactically
simpler, and automatically removes self-edges.
WARNING: This method can take time.
Parameters
----------
k : int, optional
Maximum number of neighbors to return for each point in the
dataset. Setting this to ``None`` deactivates the constraint, so
that all neighbors are returned within ``radius`` of a given point.
radius : float, optional
For a given point, only neighbors within this distance are
returned. The default is ``None``, in which case the ``k`` nearest
neighbors are returned for each query point, regardless of
distance.
include_self_edges : bool, optional
For most distance functions, each point in the model's reference
dataset is its own nearest neighbor. If this parameter is set to
False, this result is ignored, and the nearest neighbors are
returned *excluding* the point itself.
output_type : {'SGraph', 'SFrame'}, optional
By default, the results are returned in the form of an SGraph,
where each point in the reference dataset is a vertex and an edge A
-> B indicates that vertex B is a nearest neighbor of vertex A. If
'output_type' is set to 'SFrame', the output is in the same form as
the results of the 'query' method: an SFrame with columns
indicating the query label (in this case the query data is the same
as the reference data), reference label, distance between the two
points, and the rank of the neighbor.
verbose : bool, optional
If True, print progress updates and model details.
Returns
-------
out : SFrame or SGraph
The type of the output object depends on the 'output_type'
parameter. See the parameter description for more detail.
Notes
-----
- If both ``k`` and ``radius`` are set to ``None``, each data point is
matched to the entire dataset. If the reference dataset has
:math:`n` rows, the output is an SFrame with :math:`n^2` rows (or an
SGraph with :math:`n^2` edges).
Examples
--------
>>> graph = model.similarity_graph(k=1) # an SGraph
>>>
>>> # Most similar image for each image in the input dataset
>>> graph.edges
+----------+----------+----------------+------+
| __src_id | __dst_id | distance | rank |
+----------+----------+----------------+------+
| 0 | 1 | 0.376430604494 | 1 |
| 2 | 1 | 0.55542776308 | 1 |
| 1 | 0 | 0.376430604494 | 1 |
+----------+----------+----------------+------+
"""
return self.similarity_model.similarity_graph(k, radius, include_self_edges, output_type, verbose) | python | def similarity_graph(self, k=5, radius=None, include_self_edges=False,
output_type='SGraph', verbose=True):
"""
Construct the similarity graph on the reference dataset, which is
already stored in the model to find the top `k` similar images for each
image in your input dataset.
This is conceptually very similar to running `query` with the reference
set, but this method is optimized for the purpose, syntactically
simpler, and automatically removes self-edges.
WARNING: This method can take time.
Parameters
----------
k : int, optional
Maximum number of neighbors to return for each point in the
dataset. Setting this to ``None`` deactivates the constraint, so
that all neighbors are returned within ``radius`` of a given point.
radius : float, optional
For a given point, only neighbors within this distance are
returned. The default is ``None``, in which case the ``k`` nearest
neighbors are returned for each query point, regardless of
distance.
include_self_edges : bool, optional
For most distance functions, each point in the model's reference
dataset is its own nearest neighbor. If this parameter is set to
False, this result is ignored, and the nearest neighbors are
returned *excluding* the point itself.
output_type : {'SGraph', 'SFrame'}, optional
By default, the results are returned in the form of an SGraph,
where each point in the reference dataset is a vertex and an edge A
-> B indicates that vertex B is a nearest neighbor of vertex A. If
'output_type' is set to 'SFrame', the output is in the same form as
the results of the 'query' method: an SFrame with columns
indicating the query label (in this case the query data is the same
as the reference data), reference label, distance between the two
points, and the rank of the neighbor.
verbose : bool, optional
If True, print progress updates and model details.
Returns
-------
out : SFrame or SGraph
The type of the output object depends on the 'output_type'
parameter. See the parameter description for more detail.
Notes
-----
- If both ``k`` and ``radius`` are set to ``None``, each data point is
matched to the entire dataset. If the reference dataset has
:math:`n` rows, the output is an SFrame with :math:`n^2` rows (or an
SGraph with :math:`n^2` edges).
Examples
--------
>>> graph = model.similarity_graph(k=1) # an SGraph
>>>
>>> # Most similar image for each image in the input dataset
>>> graph.edges
+----------+----------+----------------+------+
| __src_id | __dst_id | distance | rank |
+----------+----------+----------------+------+
| 0 | 1 | 0.376430604494 | 1 |
| 2 | 1 | 0.55542776308 | 1 |
| 1 | 0 | 0.376430604494 | 1 |
+----------+----------+----------------+------+
"""
return self.similarity_model.similarity_graph(k, radius, include_self_edges, output_type, verbose) | [
"def",
"similarity_graph",
"(",
"self",
",",
"k",
"=",
"5",
",",
"radius",
"=",
"None",
",",
"include_self_edges",
"=",
"False",
",",
"output_type",
"=",
"'SGraph'",
",",
"verbose",
"=",
"True",
")",
":",
"return",
"self",
".",
"similarity_model",
".",
"similarity_graph",
"(",
"k",
",",
"radius",
",",
"include_self_edges",
",",
"output_type",
",",
"verbose",
")"
] | Construct the similarity graph on the reference dataset, which is
already stored in the model to find the top `k` similar images for each
image in your input dataset.
This is conceptually very similar to running `query` with the reference
set, but this method is optimized for the purpose, syntactically
simpler, and automatically removes self-edges.
WARNING: This method can take time.
Parameters
----------
k : int, optional
Maximum number of neighbors to return for each point in the
dataset. Setting this to ``None`` deactivates the constraint, so
that all neighbors are returned within ``radius`` of a given point.
radius : float, optional
For a given point, only neighbors within this distance are
returned. The default is ``None``, in which case the ``k`` nearest
neighbors are returned for each query point, regardless of
distance.
include_self_edges : bool, optional
For most distance functions, each point in the model's reference
dataset is its own nearest neighbor. If this parameter is set to
False, this result is ignored, and the nearest neighbors are
returned *excluding* the point itself.
output_type : {'SGraph', 'SFrame'}, optional
By default, the results are returned in the form of an SGraph,
where each point in the reference dataset is a vertex and an edge A
-> B indicates that vertex B is a nearest neighbor of vertex A. If
'output_type' is set to 'SFrame', the output is in the same form as
the results of the 'query' method: an SFrame with columns
indicating the query label (in this case the query data is the same
as the reference data), reference label, distance between the two
points, and the rank of the neighbor.
verbose : bool, optional
If True, print progress updates and model details.
Returns
-------
out : SFrame or SGraph
The type of the output object depends on the 'output_type'
parameter. See the parameter description for more detail.
Notes
-----
- If both ``k`` and ``radius`` are set to ``None``, each data point is
matched to the entire dataset. If the reference dataset has
:math:`n` rows, the output is an SFrame with :math:`n^2` rows (or an
SGraph with :math:`n^2` edges).
Examples
--------
>>> graph = model.similarity_graph(k=1) # an SGraph
>>>
>>> # Most similar image for each image in the input dataset
>>> graph.edges
+----------+----------+----------------+------+
| __src_id | __dst_id | distance | rank |
+----------+----------+----------------+------+
| 0 | 1 | 0.376430604494 | 1 |
| 2 | 1 | 0.55542776308 | 1 |
| 1 | 0 | 0.376430604494 | 1 |
+----------+----------+----------------+------+ | [
"Construct",
"the",
"similarity",
"graph",
"on",
"the",
"reference",
"dataset",
"which",
"is",
"already",
"stored",
"in",
"the",
"model",
"to",
"find",
"the",
"top",
"k",
"similar",
"images",
"for",
"each",
"image",
"in",
"your",
"input",
"dataset",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_similarity/image_similarity.py#L383-L456 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/image_similarity/image_similarity.py | ImageSimilarityModel.export_coreml | def export_coreml(self, filename):
"""
Save the model in Core ML format.
The exported model calculates the distance between a query image and
each row of the model's stored data. It does not sort and retrieve
the k nearest neighbors of the query image.
See Also
--------
save
Examples
--------
>>> # Train an image similarity model
>>> model = turicreate.image_similarity.create(data)
>>>
>>> # Query the model for similar images
>>> similar_images = model.query(data)
+-------------+-----------------+---------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+---------------+------+
| 0 | 0 | 0.0 | 1 |
| 0 | 2 | 24.9664942809 | 2 |
| 0 | 1 | 28.4416069428 | 3 |
| 1 | 1 | 0.0 | 1 |
| 1 | 2 | 21.8715131191 | 2 |
| 1 | 0 | 28.4416069428 | 3 |
| 2 | 2 | 0.0 | 1 |
| 2 | 1 | 21.8715131191 | 2 |
| 2 | 0 | 24.9664942809 | 3 |
+-------------+-----------------+---------------+------+
[9 rows x 4 columns]
>>>
>>> # Export the model to Core ML format
>>> model.export_coreml('myModel.mlmodel')
>>>
>>> # Load the Core ML model
>>> import coremltools
>>> ml_model = coremltools.models.MLModel('myModel.mlmodel')
>>>
>>> # Prepare the first image of reference data for consumption
>>> # by the Core ML model
>>> import PIL
>>> image = tc.image_analysis.resize(data['image'][0], *reversed(model.input_image_shape))
>>> image = PIL.Image.fromarray(image.pixel_data)
>>>
>>> # Calculate distances using the Core ML model
>>> ml_model.predict(data={'image': image})
{'distance': array([ 0., 28.453125, 24.96875 ])}
"""
import numpy as _np
import coremltools as _cmt
from coremltools.models import datatypes as _datatypes, neural_network as _neural_network
from .._mxnet._mxnet_to_coreml import _mxnet_converter
from turicreate.toolkits import _coreml_utils
# Get the reference data from the model
proxy = self.similarity_model.__proxy__
reference_data = _np.array(_tc.extensions._nearest_neighbors._nn_get_reference_data(proxy))
num_examples, embedding_size = reference_data.shape
output_name = 'distance'
output_features = [(output_name, _datatypes.Array(num_examples))]
if self.model != 'VisionFeaturePrint_Scene':
# Convert the MxNet model to Core ML
ptModel = _pre_trained_models.MODELS[self.model]()
feature_extractor = _image_feature_extractor.MXFeatureExtractor(ptModel)
input_name = feature_extractor.data_layer
input_features = [(input_name, _datatypes.Array(*(self.input_image_shape)))]
# Create a neural network
builder = _neural_network.NeuralNetworkBuilder(
input_features, output_features, mode=None)
# Convert the feature extraction network
mx_feature_extractor = feature_extractor._get_mx_module(
feature_extractor.ptModel.mxmodel,
feature_extractor.data_layer,
feature_extractor.feature_layer,
feature_extractor.context,
self.input_image_shape
)
batch_input_shape = (1, ) + self.input_image_shape
_mxnet_converter.convert(mx_feature_extractor, mode=None,
input_shape=[(input_name, batch_input_shape)],
builder=builder, verbose=False)
feature_layer = feature_extractor.feature_layer
else: # self.model == VisionFeaturePrint_Scene
# Create a pipleline that contains a VisionFeaturePrint followed by a
# neural network.
BGR_VALUE = _cmt.proto.FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('BGR')
DOUBLE_ARRAY_VALUE = _cmt.proto.FeatureTypes_pb2.ArrayFeatureType.ArrayDataType.Value('DOUBLE')
INPUT_IMAGE_SHAPE = 299
top_spec = _cmt.proto.Model_pb2.Model()
top_spec.specificationVersion = 3
desc = top_spec.description
input = desc.input.add()
input.name = self.feature
input.type.imageType.width = INPUT_IMAGE_SHAPE
input.type.imageType.height = INPUT_IMAGE_SHAPE
input.type.imageType.colorSpace = BGR_VALUE
output = desc.output.add()
output.name = output_name
output.type.multiArrayType.shape.append(num_examples)
output.type.multiArrayType.dataType = DOUBLE_ARRAY_VALUE
# VisionFeaturePrint extractor
pipeline = top_spec.pipeline
scene_print = pipeline.models.add()
scene_print.specificationVersion = 3
scene_print.visionFeaturePrint.scene.version = 1
input = scene_print.description.input.add()
input.name = self.feature
input.type.imageType.width = 299
input.type.imageType.height = 299
input.type.imageType.colorSpace = BGR_VALUE
feature_layer = 'VisionFeaturePrint_Scene_output'
output = scene_print.description.output.add()
output.name = feature_layer
output.type.multiArrayType.dataType = DOUBLE_ARRAY_VALUE
output.type.multiArrayType.shape.append(2048)
# Neural network builder
input_features = [(feature_layer, _datatypes.Array(2048))]
builder = _neural_network.NeuralNetworkBuilder(input_features, output_features)
# To add the nearest neighbors model we add calculation of the euclidean
# distance between the newly extracted query features (denoted by the vector u)
# and each extracted reference feature (denoted by the rows of matrix V).
# Calculation of sqrt((v_i-u)^2) = sqrt(v_i^2 - 2v_i*u + u^2) ensues.
V = reference_data
v_squared = (V * V).sum(axis=1)
builder.add_inner_product('v^2-2vu', W=-2 * V, b=v_squared, has_bias=True,
input_channels=embedding_size, output_channels=num_examples,
input_name=feature_layer, output_name='v^2-2vu')
builder.add_unary('element_wise-u^2', mode='power', alpha=2,
input_name=feature_layer, output_name='element_wise-u^2')
# Produce a vector of length num_examples with all values equal to u^2
builder.add_inner_product('u^2', W=_np.ones((embedding_size, num_examples)),
b=None, has_bias=False,
input_channels=embedding_size, output_channels=num_examples,
input_name='element_wise-u^2', output_name='u^2')
builder.add_elementwise('v^2-2vu+u^2', mode='ADD',
input_names=['v^2-2vu', 'u^2'],
output_name='v^2-2vu+u^2')
# v^2-2vu+u^2=(v-u)^2 is non-negative but some computations on GPU may result in
# small negative values. Apply RELU so we don't take the square root of negative values.
builder.add_activation('relu', non_linearity='RELU',
input_name='v^2-2vu+u^2', output_name='relu')
builder.add_unary('sqrt', mode='sqrt', input_name='relu', output_name=output_name)
# Finalize model
if self.model != 'VisionFeaturePrint_Scene':
_mxnet_converter._set_input_output_layers(builder, [input_name], [output_name])
builder.set_input([input_name], [self.input_image_shape])
builder.set_output([output_name], [(num_examples,)])
_cmt.models.utils.rename_feature(builder.spec, input_name, self.feature)
builder.set_pre_processing_parameters(image_input_names=self.feature)
mlmodel = _cmt.models.MLModel(builder.spec)
else:
top_spec.pipeline.models.extend([builder.spec])
mlmodel = _cmt.models.MLModel(top_spec)
# Add metadata
model_type = 'image similarity'
mlmodel.short_description = _coreml_utils._mlmodel_short_description(model_type)
mlmodel.input_description[self.feature] = u'Input image'
mlmodel.output_description[output_name] = u'Distances between the input and reference images'
_coreml_utils._set_model_metadata(mlmodel, self.__class__.__name__, {
'model': self.model,
'num_examples': str(self.num_examples)
}, version=ImageSimilarityModel._PYTHON_IMAGE_SIMILARITY_VERSION)
mlmodel.save(filename) | python | def export_coreml(self, filename):
"""
Save the model in Core ML format.
The exported model calculates the distance between a query image and
each row of the model's stored data. It does not sort and retrieve
the k nearest neighbors of the query image.
See Also
--------
save
Examples
--------
>>> # Train an image similarity model
>>> model = turicreate.image_similarity.create(data)
>>>
>>> # Query the model for similar images
>>> similar_images = model.query(data)
+-------------+-----------------+---------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+---------------+------+
| 0 | 0 | 0.0 | 1 |
| 0 | 2 | 24.9664942809 | 2 |
| 0 | 1 | 28.4416069428 | 3 |
| 1 | 1 | 0.0 | 1 |
| 1 | 2 | 21.8715131191 | 2 |
| 1 | 0 | 28.4416069428 | 3 |
| 2 | 2 | 0.0 | 1 |
| 2 | 1 | 21.8715131191 | 2 |
| 2 | 0 | 24.9664942809 | 3 |
+-------------+-----------------+---------------+------+
[9 rows x 4 columns]
>>>
>>> # Export the model to Core ML format
>>> model.export_coreml('myModel.mlmodel')
>>>
>>> # Load the Core ML model
>>> import coremltools
>>> ml_model = coremltools.models.MLModel('myModel.mlmodel')
>>>
>>> # Prepare the first image of reference data for consumption
>>> # by the Core ML model
>>> import PIL
>>> image = tc.image_analysis.resize(data['image'][0], *reversed(model.input_image_shape))
>>> image = PIL.Image.fromarray(image.pixel_data)
>>>
>>> # Calculate distances using the Core ML model
>>> ml_model.predict(data={'image': image})
{'distance': array([ 0., 28.453125, 24.96875 ])}
"""
import numpy as _np
import coremltools as _cmt
from coremltools.models import datatypes as _datatypes, neural_network as _neural_network
from .._mxnet._mxnet_to_coreml import _mxnet_converter
from turicreate.toolkits import _coreml_utils
# Get the reference data from the model
proxy = self.similarity_model.__proxy__
reference_data = _np.array(_tc.extensions._nearest_neighbors._nn_get_reference_data(proxy))
num_examples, embedding_size = reference_data.shape
output_name = 'distance'
output_features = [(output_name, _datatypes.Array(num_examples))]
if self.model != 'VisionFeaturePrint_Scene':
# Convert the MxNet model to Core ML
ptModel = _pre_trained_models.MODELS[self.model]()
feature_extractor = _image_feature_extractor.MXFeatureExtractor(ptModel)
input_name = feature_extractor.data_layer
input_features = [(input_name, _datatypes.Array(*(self.input_image_shape)))]
# Create a neural network
builder = _neural_network.NeuralNetworkBuilder(
input_features, output_features, mode=None)
# Convert the feature extraction network
mx_feature_extractor = feature_extractor._get_mx_module(
feature_extractor.ptModel.mxmodel,
feature_extractor.data_layer,
feature_extractor.feature_layer,
feature_extractor.context,
self.input_image_shape
)
batch_input_shape = (1, ) + self.input_image_shape
_mxnet_converter.convert(mx_feature_extractor, mode=None,
input_shape=[(input_name, batch_input_shape)],
builder=builder, verbose=False)
feature_layer = feature_extractor.feature_layer
else: # self.model == VisionFeaturePrint_Scene
# Create a pipleline that contains a VisionFeaturePrint followed by a
# neural network.
BGR_VALUE = _cmt.proto.FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('BGR')
DOUBLE_ARRAY_VALUE = _cmt.proto.FeatureTypes_pb2.ArrayFeatureType.ArrayDataType.Value('DOUBLE')
INPUT_IMAGE_SHAPE = 299
top_spec = _cmt.proto.Model_pb2.Model()
top_spec.specificationVersion = 3
desc = top_spec.description
input = desc.input.add()
input.name = self.feature
input.type.imageType.width = INPUT_IMAGE_SHAPE
input.type.imageType.height = INPUT_IMAGE_SHAPE
input.type.imageType.colorSpace = BGR_VALUE
output = desc.output.add()
output.name = output_name
output.type.multiArrayType.shape.append(num_examples)
output.type.multiArrayType.dataType = DOUBLE_ARRAY_VALUE
# VisionFeaturePrint extractor
pipeline = top_spec.pipeline
scene_print = pipeline.models.add()
scene_print.specificationVersion = 3
scene_print.visionFeaturePrint.scene.version = 1
input = scene_print.description.input.add()
input.name = self.feature
input.type.imageType.width = 299
input.type.imageType.height = 299
input.type.imageType.colorSpace = BGR_VALUE
feature_layer = 'VisionFeaturePrint_Scene_output'
output = scene_print.description.output.add()
output.name = feature_layer
output.type.multiArrayType.dataType = DOUBLE_ARRAY_VALUE
output.type.multiArrayType.shape.append(2048)
# Neural network builder
input_features = [(feature_layer, _datatypes.Array(2048))]
builder = _neural_network.NeuralNetworkBuilder(input_features, output_features)
# To add the nearest neighbors model we add calculation of the euclidean
# distance between the newly extracted query features (denoted by the vector u)
# and each extracted reference feature (denoted by the rows of matrix V).
# Calculation of sqrt((v_i-u)^2) = sqrt(v_i^2 - 2v_i*u + u^2) ensues.
V = reference_data
v_squared = (V * V).sum(axis=1)
builder.add_inner_product('v^2-2vu', W=-2 * V, b=v_squared, has_bias=True,
input_channels=embedding_size, output_channels=num_examples,
input_name=feature_layer, output_name='v^2-2vu')
builder.add_unary('element_wise-u^2', mode='power', alpha=2,
input_name=feature_layer, output_name='element_wise-u^2')
# Produce a vector of length num_examples with all values equal to u^2
builder.add_inner_product('u^2', W=_np.ones((embedding_size, num_examples)),
b=None, has_bias=False,
input_channels=embedding_size, output_channels=num_examples,
input_name='element_wise-u^2', output_name='u^2')
builder.add_elementwise('v^2-2vu+u^2', mode='ADD',
input_names=['v^2-2vu', 'u^2'],
output_name='v^2-2vu+u^2')
# v^2-2vu+u^2=(v-u)^2 is non-negative but some computations on GPU may result in
# small negative values. Apply RELU so we don't take the square root of negative values.
builder.add_activation('relu', non_linearity='RELU',
input_name='v^2-2vu+u^2', output_name='relu')
builder.add_unary('sqrt', mode='sqrt', input_name='relu', output_name=output_name)
# Finalize model
if self.model != 'VisionFeaturePrint_Scene':
_mxnet_converter._set_input_output_layers(builder, [input_name], [output_name])
builder.set_input([input_name], [self.input_image_shape])
builder.set_output([output_name], [(num_examples,)])
_cmt.models.utils.rename_feature(builder.spec, input_name, self.feature)
builder.set_pre_processing_parameters(image_input_names=self.feature)
mlmodel = _cmt.models.MLModel(builder.spec)
else:
top_spec.pipeline.models.extend([builder.spec])
mlmodel = _cmt.models.MLModel(top_spec)
# Add metadata
model_type = 'image similarity'
mlmodel.short_description = _coreml_utils._mlmodel_short_description(model_type)
mlmodel.input_description[self.feature] = u'Input image'
mlmodel.output_description[output_name] = u'Distances between the input and reference images'
_coreml_utils._set_model_metadata(mlmodel, self.__class__.__name__, {
'model': self.model,
'num_examples': str(self.num_examples)
}, version=ImageSimilarityModel._PYTHON_IMAGE_SIMILARITY_VERSION)
mlmodel.save(filename) | [
"def",
"export_coreml",
"(",
"self",
",",
"filename",
")",
":",
"import",
"numpy",
"as",
"_np",
"import",
"coremltools",
"as",
"_cmt",
"from",
"coremltools",
".",
"models",
"import",
"datatypes",
"as",
"_datatypes",
",",
"neural_network",
"as",
"_neural_network",
"from",
".",
".",
"_mxnet",
".",
"_mxnet_to_coreml",
"import",
"_mxnet_converter",
"from",
"turicreate",
".",
"toolkits",
"import",
"_coreml_utils",
"# Get the reference data from the model",
"proxy",
"=",
"self",
".",
"similarity_model",
".",
"__proxy__",
"reference_data",
"=",
"_np",
".",
"array",
"(",
"_tc",
".",
"extensions",
".",
"_nearest_neighbors",
".",
"_nn_get_reference_data",
"(",
"proxy",
")",
")",
"num_examples",
",",
"embedding_size",
"=",
"reference_data",
".",
"shape",
"output_name",
"=",
"'distance'",
"output_features",
"=",
"[",
"(",
"output_name",
",",
"_datatypes",
".",
"Array",
"(",
"num_examples",
")",
")",
"]",
"if",
"self",
".",
"model",
"!=",
"'VisionFeaturePrint_Scene'",
":",
"# Convert the MxNet model to Core ML",
"ptModel",
"=",
"_pre_trained_models",
".",
"MODELS",
"[",
"self",
".",
"model",
"]",
"(",
")",
"feature_extractor",
"=",
"_image_feature_extractor",
".",
"MXFeatureExtractor",
"(",
"ptModel",
")",
"input_name",
"=",
"feature_extractor",
".",
"data_layer",
"input_features",
"=",
"[",
"(",
"input_name",
",",
"_datatypes",
".",
"Array",
"(",
"*",
"(",
"self",
".",
"input_image_shape",
")",
")",
")",
"]",
"# Create a neural network",
"builder",
"=",
"_neural_network",
".",
"NeuralNetworkBuilder",
"(",
"input_features",
",",
"output_features",
",",
"mode",
"=",
"None",
")",
"# Convert the feature extraction network",
"mx_feature_extractor",
"=",
"feature_extractor",
".",
"_get_mx_module",
"(",
"feature_extractor",
".",
"ptModel",
".",
"mxmodel",
",",
"feature_extractor",
".",
"data_layer",
",",
"feature_extractor",
".",
"feature_layer",
",",
"feature_extractor",
".",
"context",
",",
"self",
".",
"input_image_shape",
")",
"batch_input_shape",
"=",
"(",
"1",
",",
")",
"+",
"self",
".",
"input_image_shape",
"_mxnet_converter",
".",
"convert",
"(",
"mx_feature_extractor",
",",
"mode",
"=",
"None",
",",
"input_shape",
"=",
"[",
"(",
"input_name",
",",
"batch_input_shape",
")",
"]",
",",
"builder",
"=",
"builder",
",",
"verbose",
"=",
"False",
")",
"feature_layer",
"=",
"feature_extractor",
".",
"feature_layer",
"else",
":",
"# self.model == VisionFeaturePrint_Scene",
"# Create a pipleline that contains a VisionFeaturePrint followed by a",
"# neural network.",
"BGR_VALUE",
"=",
"_cmt",
".",
"proto",
".",
"FeatureTypes_pb2",
".",
"ImageFeatureType",
".",
"ColorSpace",
".",
"Value",
"(",
"'BGR'",
")",
"DOUBLE_ARRAY_VALUE",
"=",
"_cmt",
".",
"proto",
".",
"FeatureTypes_pb2",
".",
"ArrayFeatureType",
".",
"ArrayDataType",
".",
"Value",
"(",
"'DOUBLE'",
")",
"INPUT_IMAGE_SHAPE",
"=",
"299",
"top_spec",
"=",
"_cmt",
".",
"proto",
".",
"Model_pb2",
".",
"Model",
"(",
")",
"top_spec",
".",
"specificationVersion",
"=",
"3",
"desc",
"=",
"top_spec",
".",
"description",
"input",
"=",
"desc",
".",
"input",
".",
"add",
"(",
")",
"input",
".",
"name",
"=",
"self",
".",
"feature",
"input",
".",
"type",
".",
"imageType",
".",
"width",
"=",
"INPUT_IMAGE_SHAPE",
"input",
".",
"type",
".",
"imageType",
".",
"height",
"=",
"INPUT_IMAGE_SHAPE",
"input",
".",
"type",
".",
"imageType",
".",
"colorSpace",
"=",
"BGR_VALUE",
"output",
"=",
"desc",
".",
"output",
".",
"add",
"(",
")",
"output",
".",
"name",
"=",
"output_name",
"output",
".",
"type",
".",
"multiArrayType",
".",
"shape",
".",
"append",
"(",
"num_examples",
")",
"output",
".",
"type",
".",
"multiArrayType",
".",
"dataType",
"=",
"DOUBLE_ARRAY_VALUE",
"# VisionFeaturePrint extractor",
"pipeline",
"=",
"top_spec",
".",
"pipeline",
"scene_print",
"=",
"pipeline",
".",
"models",
".",
"add",
"(",
")",
"scene_print",
".",
"specificationVersion",
"=",
"3",
"scene_print",
".",
"visionFeaturePrint",
".",
"scene",
".",
"version",
"=",
"1",
"input",
"=",
"scene_print",
".",
"description",
".",
"input",
".",
"add",
"(",
")",
"input",
".",
"name",
"=",
"self",
".",
"feature",
"input",
".",
"type",
".",
"imageType",
".",
"width",
"=",
"299",
"input",
".",
"type",
".",
"imageType",
".",
"height",
"=",
"299",
"input",
".",
"type",
".",
"imageType",
".",
"colorSpace",
"=",
"BGR_VALUE",
"feature_layer",
"=",
"'VisionFeaturePrint_Scene_output'",
"output",
"=",
"scene_print",
".",
"description",
".",
"output",
".",
"add",
"(",
")",
"output",
".",
"name",
"=",
"feature_layer",
"output",
".",
"type",
".",
"multiArrayType",
".",
"dataType",
"=",
"DOUBLE_ARRAY_VALUE",
"output",
".",
"type",
".",
"multiArrayType",
".",
"shape",
".",
"append",
"(",
"2048",
")",
"# Neural network builder",
"input_features",
"=",
"[",
"(",
"feature_layer",
",",
"_datatypes",
".",
"Array",
"(",
"2048",
")",
")",
"]",
"builder",
"=",
"_neural_network",
".",
"NeuralNetworkBuilder",
"(",
"input_features",
",",
"output_features",
")",
"# To add the nearest neighbors model we add calculation of the euclidean ",
"# distance between the newly extracted query features (denoted by the vector u)",
"# and each extracted reference feature (denoted by the rows of matrix V).",
"# Calculation of sqrt((v_i-u)^2) = sqrt(v_i^2 - 2v_i*u + u^2) ensues.",
"V",
"=",
"reference_data",
"v_squared",
"=",
"(",
"V",
"*",
"V",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"builder",
".",
"add_inner_product",
"(",
"'v^2-2vu'",
",",
"W",
"=",
"-",
"2",
"*",
"V",
",",
"b",
"=",
"v_squared",
",",
"has_bias",
"=",
"True",
",",
"input_channels",
"=",
"embedding_size",
",",
"output_channels",
"=",
"num_examples",
",",
"input_name",
"=",
"feature_layer",
",",
"output_name",
"=",
"'v^2-2vu'",
")",
"builder",
".",
"add_unary",
"(",
"'element_wise-u^2'",
",",
"mode",
"=",
"'power'",
",",
"alpha",
"=",
"2",
",",
"input_name",
"=",
"feature_layer",
",",
"output_name",
"=",
"'element_wise-u^2'",
")",
"# Produce a vector of length num_examples with all values equal to u^2",
"builder",
".",
"add_inner_product",
"(",
"'u^2'",
",",
"W",
"=",
"_np",
".",
"ones",
"(",
"(",
"embedding_size",
",",
"num_examples",
")",
")",
",",
"b",
"=",
"None",
",",
"has_bias",
"=",
"False",
",",
"input_channels",
"=",
"embedding_size",
",",
"output_channels",
"=",
"num_examples",
",",
"input_name",
"=",
"'element_wise-u^2'",
",",
"output_name",
"=",
"'u^2'",
")",
"builder",
".",
"add_elementwise",
"(",
"'v^2-2vu+u^2'",
",",
"mode",
"=",
"'ADD'",
",",
"input_names",
"=",
"[",
"'v^2-2vu'",
",",
"'u^2'",
"]",
",",
"output_name",
"=",
"'v^2-2vu+u^2'",
")",
"# v^2-2vu+u^2=(v-u)^2 is non-negative but some computations on GPU may result in",
"# small negative values. Apply RELU so we don't take the square root of negative values.",
"builder",
".",
"add_activation",
"(",
"'relu'",
",",
"non_linearity",
"=",
"'RELU'",
",",
"input_name",
"=",
"'v^2-2vu+u^2'",
",",
"output_name",
"=",
"'relu'",
")",
"builder",
".",
"add_unary",
"(",
"'sqrt'",
",",
"mode",
"=",
"'sqrt'",
",",
"input_name",
"=",
"'relu'",
",",
"output_name",
"=",
"output_name",
")",
"# Finalize model",
"if",
"self",
".",
"model",
"!=",
"'VisionFeaturePrint_Scene'",
":",
"_mxnet_converter",
".",
"_set_input_output_layers",
"(",
"builder",
",",
"[",
"input_name",
"]",
",",
"[",
"output_name",
"]",
")",
"builder",
".",
"set_input",
"(",
"[",
"input_name",
"]",
",",
"[",
"self",
".",
"input_image_shape",
"]",
")",
"builder",
".",
"set_output",
"(",
"[",
"output_name",
"]",
",",
"[",
"(",
"num_examples",
",",
")",
"]",
")",
"_cmt",
".",
"models",
".",
"utils",
".",
"rename_feature",
"(",
"builder",
".",
"spec",
",",
"input_name",
",",
"self",
".",
"feature",
")",
"builder",
".",
"set_pre_processing_parameters",
"(",
"image_input_names",
"=",
"self",
".",
"feature",
")",
"mlmodel",
"=",
"_cmt",
".",
"models",
".",
"MLModel",
"(",
"builder",
".",
"spec",
")",
"else",
":",
"top_spec",
".",
"pipeline",
".",
"models",
".",
"extend",
"(",
"[",
"builder",
".",
"spec",
"]",
")",
"mlmodel",
"=",
"_cmt",
".",
"models",
".",
"MLModel",
"(",
"top_spec",
")",
"# Add metadata",
"model_type",
"=",
"'image similarity'",
"mlmodel",
".",
"short_description",
"=",
"_coreml_utils",
".",
"_mlmodel_short_description",
"(",
"model_type",
")",
"mlmodel",
".",
"input_description",
"[",
"self",
".",
"feature",
"]",
"=",
"u'Input image'",
"mlmodel",
".",
"output_description",
"[",
"output_name",
"]",
"=",
"u'Distances between the input and reference images'",
"_coreml_utils",
".",
"_set_model_metadata",
"(",
"mlmodel",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"{",
"'model'",
":",
"self",
".",
"model",
",",
"'num_examples'",
":",
"str",
"(",
"self",
".",
"num_examples",
")",
"}",
",",
"version",
"=",
"ImageSimilarityModel",
".",
"_PYTHON_IMAGE_SIMILARITY_VERSION",
")",
"mlmodel",
".",
"save",
"(",
"filename",
")"
] | Save the model in Core ML format.
The exported model calculates the distance between a query image and
each row of the model's stored data. It does not sort and retrieve
the k nearest neighbors of the query image.
See Also
--------
save
Examples
--------
>>> # Train an image similarity model
>>> model = turicreate.image_similarity.create(data)
>>>
>>> # Query the model for similar images
>>> similar_images = model.query(data)
+-------------+-----------------+---------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+---------------+------+
| 0 | 0 | 0.0 | 1 |
| 0 | 2 | 24.9664942809 | 2 |
| 0 | 1 | 28.4416069428 | 3 |
| 1 | 1 | 0.0 | 1 |
| 1 | 2 | 21.8715131191 | 2 |
| 1 | 0 | 28.4416069428 | 3 |
| 2 | 2 | 0.0 | 1 |
| 2 | 1 | 21.8715131191 | 2 |
| 2 | 0 | 24.9664942809 | 3 |
+-------------+-----------------+---------------+------+
[9 rows x 4 columns]
>>>
>>> # Export the model to Core ML format
>>> model.export_coreml('myModel.mlmodel')
>>>
>>> # Load the Core ML model
>>> import coremltools
>>> ml_model = coremltools.models.MLModel('myModel.mlmodel')
>>>
>>> # Prepare the first image of reference data for consumption
>>> # by the Core ML model
>>> import PIL
>>> image = tc.image_analysis.resize(data['image'][0], *reversed(model.input_image_shape))
>>> image = PIL.Image.fromarray(image.pixel_data)
>>>
>>> # Calculate distances using the Core ML model
>>> ml_model.predict(data={'image': image})
{'distance': array([ 0., 28.453125, 24.96875 ])} | [
"Save",
"the",
"model",
"in",
"Core",
"ML",
"format",
".",
"The",
"exported",
"model",
"calculates",
"the",
"distance",
"between",
"a",
"query",
"image",
"and",
"each",
"row",
"of",
"the",
"model",
"s",
"stored",
"data",
".",
"It",
"does",
"not",
"sort",
"and",
"retrieve",
"the",
"k",
"nearest",
"neighbors",
"of",
"the",
"query",
"image",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_similarity/image_similarity.py#L458-L644 | train |
apple/turicreate | src/unity/python/turicreate/meta/asttools/visitors/graph_visitor.py | make_graph | def make_graph(node, call_deps=False):
'''
Create a dependency graph from an ast node.
:param node: ast node.
:param call_deps: if true, then the graph will create a cyclic dependence for all
function calls. (i.e for `a.b(c)` a depends on b and b depends on a)
:returns: a tuple of (graph, undefined)
'''
gen = GraphGen(call_deps=call_deps)
gen.visit(node)
return gen.graph, gen.undefined | python | def make_graph(node, call_deps=False):
'''
Create a dependency graph from an ast node.
:param node: ast node.
:param call_deps: if true, then the graph will create a cyclic dependence for all
function calls. (i.e for `a.b(c)` a depends on b and b depends on a)
:returns: a tuple of (graph, undefined)
'''
gen = GraphGen(call_deps=call_deps)
gen.visit(node)
return gen.graph, gen.undefined | [
"def",
"make_graph",
"(",
"node",
",",
"call_deps",
"=",
"False",
")",
":",
"gen",
"=",
"GraphGen",
"(",
"call_deps",
"=",
"call_deps",
")",
"gen",
".",
"visit",
"(",
"node",
")",
"return",
"gen",
".",
"graph",
",",
"gen",
".",
"undefined"
] | Create a dependency graph from an ast node.
:param node: ast node.
:param call_deps: if true, then the graph will create a cyclic dependence for all
function calls. (i.e for `a.b(c)` a depends on b and b depends on a)
:returns: a tuple of (graph, undefined) | [
"Create",
"a",
"dependency",
"graph",
"from",
"an",
"ast",
"node",
".",
":",
"param",
"node",
":",
"ast",
"node",
".",
":",
"param",
"call_deps",
":",
"if",
"true",
"then",
"the",
"graph",
"will",
"create",
"a",
"cyclic",
"dependence",
"for",
"all",
"function",
"calls",
".",
"(",
"i",
".",
"e",
"for",
"a",
".",
"b",
"(",
"c",
")",
"a",
"depends",
"on",
"b",
"and",
"b",
"depends",
"on",
"a",
")",
":",
"returns",
":",
"a",
"tuple",
"of",
"(",
"graph",
"undefined",
")"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/visitors/graph_visitor.py#L393-L407 | train |
apple/turicreate | src/unity/python/turicreate/meta/bytecodetools/pyc_file.py | extract | def extract(binary):
'''
Extract a code object from a binary pyc file.
:param binary: a sequence of bytes from a pyc file.
'''
if len(binary) <= 8:
raise Exception("Binary pyc must be greater than 8 bytes (got %i)" % len(binary))
magic = binary[:4]
MAGIC = get_magic()
if magic != MAGIC:
raise Exception("Python version mismatch (%r != %r) Is this a pyc file?" % (magic, MAGIC))
modtime = time.asctime(time.localtime(struct.unpack('i', binary[4:8])[0]))
code = marshal.loads(binary[8:])
return modtime, code | python | def extract(binary):
'''
Extract a code object from a binary pyc file.
:param binary: a sequence of bytes from a pyc file.
'''
if len(binary) <= 8:
raise Exception("Binary pyc must be greater than 8 bytes (got %i)" % len(binary))
magic = binary[:4]
MAGIC = get_magic()
if magic != MAGIC:
raise Exception("Python version mismatch (%r != %r) Is this a pyc file?" % (magic, MAGIC))
modtime = time.asctime(time.localtime(struct.unpack('i', binary[4:8])[0]))
code = marshal.loads(binary[8:])
return modtime, code | [
"def",
"extract",
"(",
"binary",
")",
":",
"if",
"len",
"(",
"binary",
")",
"<=",
"8",
":",
"raise",
"Exception",
"(",
"\"Binary pyc must be greater than 8 bytes (got %i)\"",
"%",
"len",
"(",
"binary",
")",
")",
"magic",
"=",
"binary",
"[",
":",
"4",
"]",
"MAGIC",
"=",
"get_magic",
"(",
")",
"if",
"magic",
"!=",
"MAGIC",
":",
"raise",
"Exception",
"(",
"\"Python version mismatch (%r != %r) Is this a pyc file?\"",
"%",
"(",
"magic",
",",
"MAGIC",
")",
")",
"modtime",
"=",
"time",
".",
"asctime",
"(",
"time",
".",
"localtime",
"(",
"struct",
".",
"unpack",
"(",
"'i'",
",",
"binary",
"[",
"4",
":",
"8",
"]",
")",
"[",
"0",
"]",
")",
")",
"code",
"=",
"marshal",
".",
"loads",
"(",
"binary",
"[",
"8",
":",
"]",
")",
"return",
"modtime",
",",
"code"
] | Extract a code object from a binary pyc file.
:param binary: a sequence of bytes from a pyc file. | [
"Extract",
"a",
"code",
"object",
"from",
"a",
"binary",
"pyc",
"file",
".",
":",
"param",
"binary",
":",
"a",
"sequence",
"of",
"bytes",
"from",
"a",
"pyc",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/bytecodetools/pyc_file.py#L20-L39 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | _VarintSize | def _VarintSize(value):
"""Compute the size of a varint value."""
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value <= 0xffffffffffffff: return 8
if value <= 0x7fffffffffffffff: return 9
return 10 | python | def _VarintSize(value):
"""Compute the size of a varint value."""
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value <= 0xffffffffffffff: return 8
if value <= 0x7fffffffffffffff: return 9
return 10 | [
"def",
"_VarintSize",
"(",
"value",
")",
":",
"if",
"value",
"<=",
"0x7f",
":",
"return",
"1",
"if",
"value",
"<=",
"0x3fff",
":",
"return",
"2",
"if",
"value",
"<=",
"0x1fffff",
":",
"return",
"3",
"if",
"value",
"<=",
"0xfffffff",
":",
"return",
"4",
"if",
"value",
"<=",
"0x7ffffffff",
":",
"return",
"5",
"if",
"value",
"<=",
"0x3ffffffffff",
":",
"return",
"6",
"if",
"value",
"<=",
"0x1ffffffffffff",
":",
"return",
"7",
"if",
"value",
"<=",
"0xffffffffffffff",
":",
"return",
"8",
"if",
"value",
"<=",
"0x7fffffffffffffff",
":",
"return",
"9",
"return",
"10"
] | Compute the size of a varint value. | [
"Compute",
"the",
"size",
"of",
"a",
"varint",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L82-L93 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | _SignedVarintSize | def _SignedVarintSize(value):
"""Compute the size of a signed varint value."""
if value < 0: return 10
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value <= 0xffffffffffffff: return 8
if value <= 0x7fffffffffffffff: return 9
return 10 | python | def _SignedVarintSize(value):
"""Compute the size of a signed varint value."""
if value < 0: return 10
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value <= 0xffffffffffffff: return 8
if value <= 0x7fffffffffffffff: return 9
return 10 | [
"def",
"_SignedVarintSize",
"(",
"value",
")",
":",
"if",
"value",
"<",
"0",
":",
"return",
"10",
"if",
"value",
"<=",
"0x7f",
":",
"return",
"1",
"if",
"value",
"<=",
"0x3fff",
":",
"return",
"2",
"if",
"value",
"<=",
"0x1fffff",
":",
"return",
"3",
"if",
"value",
"<=",
"0xfffffff",
":",
"return",
"4",
"if",
"value",
"<=",
"0x7ffffffff",
":",
"return",
"5",
"if",
"value",
"<=",
"0x3ffffffffff",
":",
"return",
"6",
"if",
"value",
"<=",
"0x1ffffffffffff",
":",
"return",
"7",
"if",
"value",
"<=",
"0xffffffffffffff",
":",
"return",
"8",
"if",
"value",
"<=",
"0x7fffffffffffffff",
":",
"return",
"9",
"return",
"10"
] | Compute the size of a signed varint value. | [
"Compute",
"the",
"size",
"of",
"a",
"signed",
"varint",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L96-L108 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | _SimpleSizer | def _SimpleSizer(compute_value_size):
"""A sizer which uses the function compute_value_size to compute the size of
each value. Typically compute_value_size is _VarintSize."""
def SpecificSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
if is_packed:
local_VarintSize = _VarintSize
def PackedFieldSize(value):
result = 0
for element in value:
result += compute_value_size(element)
return result + local_VarintSize(result) + tag_size
return PackedFieldSize
elif is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
result += compute_value_size(element)
return result
return RepeatedFieldSize
else:
def FieldSize(value):
return tag_size + compute_value_size(value)
return FieldSize
return SpecificSizer | python | def _SimpleSizer(compute_value_size):
"""A sizer which uses the function compute_value_size to compute the size of
each value. Typically compute_value_size is _VarintSize."""
def SpecificSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
if is_packed:
local_VarintSize = _VarintSize
def PackedFieldSize(value):
result = 0
for element in value:
result += compute_value_size(element)
return result + local_VarintSize(result) + tag_size
return PackedFieldSize
elif is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
result += compute_value_size(element)
return result
return RepeatedFieldSize
else:
def FieldSize(value):
return tag_size + compute_value_size(value)
return FieldSize
return SpecificSizer | [
"def",
"_SimpleSizer",
"(",
"compute_value_size",
")",
":",
"def",
"SpecificSizer",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"tag_size",
"=",
"_TagSize",
"(",
"field_number",
")",
"if",
"is_packed",
":",
"local_VarintSize",
"=",
"_VarintSize",
"def",
"PackedFieldSize",
"(",
"value",
")",
":",
"result",
"=",
"0",
"for",
"element",
"in",
"value",
":",
"result",
"+=",
"compute_value_size",
"(",
"element",
")",
"return",
"result",
"+",
"local_VarintSize",
"(",
"result",
")",
"+",
"tag_size",
"return",
"PackedFieldSize",
"elif",
"is_repeated",
":",
"def",
"RepeatedFieldSize",
"(",
"value",
")",
":",
"result",
"=",
"tag_size",
"*",
"len",
"(",
"value",
")",
"for",
"element",
"in",
"value",
":",
"result",
"+=",
"compute_value_size",
"(",
"element",
")",
"return",
"result",
"return",
"RepeatedFieldSize",
"else",
":",
"def",
"FieldSize",
"(",
"value",
")",
":",
"return",
"tag_size",
"+",
"compute_value_size",
"(",
"value",
")",
"return",
"FieldSize",
"return",
"SpecificSizer"
] | A sizer which uses the function compute_value_size to compute the size of
each value. Typically compute_value_size is _VarintSize. | [
"A",
"sizer",
"which",
"uses",
"the",
"function",
"compute_value_size",
"to",
"compute",
"the",
"size",
"of",
"each",
"value",
".",
"Typically",
"compute_value_size",
"is",
"_VarintSize",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L126-L152 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | _FixedSizer | def _FixedSizer(value_size):
"""Like _SimpleSizer except for a fixed-size field. The input is the size
of one value."""
def SpecificSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
if is_packed:
local_VarintSize = _VarintSize
def PackedFieldSize(value):
result = len(value) * value_size
return result + local_VarintSize(result) + tag_size
return PackedFieldSize
elif is_repeated:
element_size = value_size + tag_size
def RepeatedFieldSize(value):
return len(value) * element_size
return RepeatedFieldSize
else:
field_size = value_size + tag_size
def FieldSize(value):
return field_size
return FieldSize
return SpecificSizer | python | def _FixedSizer(value_size):
"""Like _SimpleSizer except for a fixed-size field. The input is the size
of one value."""
def SpecificSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
if is_packed:
local_VarintSize = _VarintSize
def PackedFieldSize(value):
result = len(value) * value_size
return result + local_VarintSize(result) + tag_size
return PackedFieldSize
elif is_repeated:
element_size = value_size + tag_size
def RepeatedFieldSize(value):
return len(value) * element_size
return RepeatedFieldSize
else:
field_size = value_size + tag_size
def FieldSize(value):
return field_size
return FieldSize
return SpecificSizer | [
"def",
"_FixedSizer",
"(",
"value_size",
")",
":",
"def",
"SpecificSizer",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"tag_size",
"=",
"_TagSize",
"(",
"field_number",
")",
"if",
"is_packed",
":",
"local_VarintSize",
"=",
"_VarintSize",
"def",
"PackedFieldSize",
"(",
"value",
")",
":",
"result",
"=",
"len",
"(",
"value",
")",
"*",
"value_size",
"return",
"result",
"+",
"local_VarintSize",
"(",
"result",
")",
"+",
"tag_size",
"return",
"PackedFieldSize",
"elif",
"is_repeated",
":",
"element_size",
"=",
"value_size",
"+",
"tag_size",
"def",
"RepeatedFieldSize",
"(",
"value",
")",
":",
"return",
"len",
"(",
"value",
")",
"*",
"element_size",
"return",
"RepeatedFieldSize",
"else",
":",
"field_size",
"=",
"value_size",
"+",
"tag_size",
"def",
"FieldSize",
"(",
"value",
")",
":",
"return",
"field_size",
"return",
"FieldSize",
"return",
"SpecificSizer"
] | Like _SimpleSizer except for a fixed-size field. The input is the size
of one value. | [
"Like",
"_SimpleSizer",
"except",
"for",
"a",
"fixed",
"-",
"size",
"field",
".",
"The",
"input",
"is",
"the",
"size",
"of",
"one",
"value",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L184-L207 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | BytesSizer | def BytesSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a bytes field."""
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
local_len = len
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
l = local_len(element)
result += local_VarintSize(l) + l
return result
return RepeatedFieldSize
else:
def FieldSize(value):
l = local_len(value)
return tag_size + local_VarintSize(l) + l
return FieldSize | python | def BytesSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a bytes field."""
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
local_len = len
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
l = local_len(element)
result += local_VarintSize(l) + l
return result
return RepeatedFieldSize
else:
def FieldSize(value):
l = local_len(value)
return tag_size + local_VarintSize(l) + l
return FieldSize | [
"def",
"BytesSizer",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"tag_size",
"=",
"_TagSize",
"(",
"field_number",
")",
"local_VarintSize",
"=",
"_VarintSize",
"local_len",
"=",
"len",
"assert",
"not",
"is_packed",
"if",
"is_repeated",
":",
"def",
"RepeatedFieldSize",
"(",
"value",
")",
":",
"result",
"=",
"tag_size",
"*",
"len",
"(",
"value",
")",
"for",
"element",
"in",
"value",
":",
"l",
"=",
"local_len",
"(",
"element",
")",
"result",
"+=",
"local_VarintSize",
"(",
"l",
")",
"+",
"l",
"return",
"result",
"return",
"RepeatedFieldSize",
"else",
":",
"def",
"FieldSize",
"(",
"value",
")",
":",
"l",
"=",
"local_len",
"(",
"value",
")",
"return",
"tag_size",
"+",
"local_VarintSize",
"(",
"l",
")",
"+",
"l",
"return",
"FieldSize"
] | Returns a sizer for a bytes field. | [
"Returns",
"a",
"sizer",
"for",
"a",
"bytes",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L252-L271 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | GroupSizer | def GroupSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a group field."""
tag_size = _TagSize(field_number) * 2
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
result += element.ByteSize()
return result
return RepeatedFieldSize
else:
def FieldSize(value):
return tag_size + value.ByteSize()
return FieldSize | python | def GroupSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a group field."""
tag_size = _TagSize(field_number) * 2
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
result += element.ByteSize()
return result
return RepeatedFieldSize
else:
def FieldSize(value):
return tag_size + value.ByteSize()
return FieldSize | [
"def",
"GroupSizer",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"tag_size",
"=",
"_TagSize",
"(",
"field_number",
")",
"*",
"2",
"assert",
"not",
"is_packed",
"if",
"is_repeated",
":",
"def",
"RepeatedFieldSize",
"(",
"value",
")",
":",
"result",
"=",
"tag_size",
"*",
"len",
"(",
"value",
")",
"for",
"element",
"in",
"value",
":",
"result",
"+=",
"element",
".",
"ByteSize",
"(",
")",
"return",
"result",
"return",
"RepeatedFieldSize",
"else",
":",
"def",
"FieldSize",
"(",
"value",
")",
":",
"return",
"tag_size",
"+",
"value",
".",
"ByteSize",
"(",
")",
"return",
"FieldSize"
] | Returns a sizer for a group field. | [
"Returns",
"a",
"sizer",
"for",
"a",
"group",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L274-L289 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | MessageSizer | def MessageSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a message field."""
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
l = element.ByteSize()
result += local_VarintSize(l) + l
return result
return RepeatedFieldSize
else:
def FieldSize(value):
l = value.ByteSize()
return tag_size + local_VarintSize(l) + l
return FieldSize | python | def MessageSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a message field."""
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
l = element.ByteSize()
result += local_VarintSize(l) + l
return result
return RepeatedFieldSize
else:
def FieldSize(value):
l = value.ByteSize()
return tag_size + local_VarintSize(l) + l
return FieldSize | [
"def",
"MessageSizer",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"tag_size",
"=",
"_TagSize",
"(",
"field_number",
")",
"local_VarintSize",
"=",
"_VarintSize",
"assert",
"not",
"is_packed",
"if",
"is_repeated",
":",
"def",
"RepeatedFieldSize",
"(",
"value",
")",
":",
"result",
"=",
"tag_size",
"*",
"len",
"(",
"value",
")",
"for",
"element",
"in",
"value",
":",
"l",
"=",
"element",
".",
"ByteSize",
"(",
")",
"result",
"+=",
"local_VarintSize",
"(",
"l",
")",
"+",
"l",
"return",
"result",
"return",
"RepeatedFieldSize",
"else",
":",
"def",
"FieldSize",
"(",
"value",
")",
":",
"l",
"=",
"value",
".",
"ByteSize",
"(",
")",
"return",
"tag_size",
"+",
"local_VarintSize",
"(",
"l",
")",
"+",
"l",
"return",
"FieldSize"
] | Returns a sizer for a message field. | [
"Returns",
"a",
"sizer",
"for",
"a",
"message",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L292-L310 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | MessageSetItemSizer | def MessageSetItemSizer(field_number):
"""Returns a sizer for extensions of MessageSet.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
}
"""
static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) +
_TagSize(3))
local_VarintSize = _VarintSize
def FieldSize(value):
l = value.ByteSize()
return static_size + local_VarintSize(l) + l
return FieldSize | python | def MessageSetItemSizer(field_number):
"""Returns a sizer for extensions of MessageSet.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
}
"""
static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) +
_TagSize(3))
local_VarintSize = _VarintSize
def FieldSize(value):
l = value.ByteSize()
return static_size + local_VarintSize(l) + l
return FieldSize | [
"def",
"MessageSetItemSizer",
"(",
"field_number",
")",
":",
"static_size",
"=",
"(",
"_TagSize",
"(",
"1",
")",
"*",
"2",
"+",
"_TagSize",
"(",
"2",
")",
"+",
"_VarintSize",
"(",
"field_number",
")",
"+",
"_TagSize",
"(",
"3",
")",
")",
"local_VarintSize",
"=",
"_VarintSize",
"def",
"FieldSize",
"(",
"value",
")",
":",
"l",
"=",
"value",
".",
"ByteSize",
"(",
")",
"return",
"static_size",
"+",
"local_VarintSize",
"(",
"l",
")",
"+",
"l",
"return",
"FieldSize"
] | Returns a sizer for extensions of MessageSet.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
} | [
"Returns",
"a",
"sizer",
"for",
"extensions",
"of",
"MessageSet",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L317-L336 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | MapSizer | def MapSizer(field_descriptor, is_message_map):
"""Returns a sizer for a map field."""
# Can't look at field_descriptor.message_type._concrete_class because it may
# not have been initialized yet.
message_type = field_descriptor.message_type
message_sizer = MessageSizer(field_descriptor.number, False, False)
def FieldSize(map_value):
total = 0
for key in map_value:
value = map_value[key]
# It's wasteful to create the messages and throw them away one second
# later since we'll do the same for the actual encode. But there's not an
# obvious way to avoid this within the current design without tons of code
# duplication. For message map, value.ByteSize() should be called to
# update the status.
entry_msg = message_type._concrete_class(key=key, value=value)
total += message_sizer(entry_msg)
if is_message_map:
value.ByteSize()
return total
return FieldSize | python | def MapSizer(field_descriptor, is_message_map):
"""Returns a sizer for a map field."""
# Can't look at field_descriptor.message_type._concrete_class because it may
# not have been initialized yet.
message_type = field_descriptor.message_type
message_sizer = MessageSizer(field_descriptor.number, False, False)
def FieldSize(map_value):
total = 0
for key in map_value:
value = map_value[key]
# It's wasteful to create the messages and throw them away one second
# later since we'll do the same for the actual encode. But there's not an
# obvious way to avoid this within the current design without tons of code
# duplication. For message map, value.ByteSize() should be called to
# update the status.
entry_msg = message_type._concrete_class(key=key, value=value)
total += message_sizer(entry_msg)
if is_message_map:
value.ByteSize()
return total
return FieldSize | [
"def",
"MapSizer",
"(",
"field_descriptor",
",",
"is_message_map",
")",
":",
"# Can't look at field_descriptor.message_type._concrete_class because it may",
"# not have been initialized yet.",
"message_type",
"=",
"field_descriptor",
".",
"message_type",
"message_sizer",
"=",
"MessageSizer",
"(",
"field_descriptor",
".",
"number",
",",
"False",
",",
"False",
")",
"def",
"FieldSize",
"(",
"map_value",
")",
":",
"total",
"=",
"0",
"for",
"key",
"in",
"map_value",
":",
"value",
"=",
"map_value",
"[",
"key",
"]",
"# It's wasteful to create the messages and throw them away one second",
"# later since we'll do the same for the actual encode. But there's not an",
"# obvious way to avoid this within the current design without tons of code",
"# duplication. For message map, value.ByteSize() should be called to",
"# update the status.",
"entry_msg",
"=",
"message_type",
".",
"_concrete_class",
"(",
"key",
"=",
"key",
",",
"value",
"=",
"value",
")",
"total",
"+=",
"message_sizer",
"(",
"entry_msg",
")",
"if",
"is_message_map",
":",
"value",
".",
"ByteSize",
"(",
")",
"return",
"total",
"return",
"FieldSize"
] | Returns a sizer for a map field. | [
"Returns",
"a",
"sizer",
"for",
"a",
"map",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L343-L366 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | _VarintEncoder | def _VarintEncoder():
"""Return an encoder for a basic varint value (does not include tag)."""
def EncodeVarint(write, value):
bits = value & 0x7f
value >>= 7
while value:
write(six.int2byte(0x80|bits))
bits = value & 0x7f
value >>= 7
return write(six.int2byte(bits))
return EncodeVarint | python | def _VarintEncoder():
"""Return an encoder for a basic varint value (does not include tag)."""
def EncodeVarint(write, value):
bits = value & 0x7f
value >>= 7
while value:
write(six.int2byte(0x80|bits))
bits = value & 0x7f
value >>= 7
return write(six.int2byte(bits))
return EncodeVarint | [
"def",
"_VarintEncoder",
"(",
")",
":",
"def",
"EncodeVarint",
"(",
"write",
",",
"value",
")",
":",
"bits",
"=",
"value",
"&",
"0x7f",
"value",
">>=",
"7",
"while",
"value",
":",
"write",
"(",
"six",
".",
"int2byte",
"(",
"0x80",
"|",
"bits",
")",
")",
"bits",
"=",
"value",
"&",
"0x7f",
"value",
">>=",
"7",
"return",
"write",
"(",
"six",
".",
"int2byte",
"(",
"bits",
")",
")",
"return",
"EncodeVarint"
] | Return an encoder for a basic varint value (does not include tag). | [
"Return",
"an",
"encoder",
"for",
"a",
"basic",
"varint",
"value",
"(",
"does",
"not",
"include",
"tag",
")",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L372-L384 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | _SignedVarintEncoder | def _SignedVarintEncoder():
"""Return an encoder for a basic signed varint value (does not include
tag)."""
def EncodeSignedVarint(write, value):
if value < 0:
value += (1 << 64)
bits = value & 0x7f
value >>= 7
while value:
write(six.int2byte(0x80|bits))
bits = value & 0x7f
value >>= 7
return write(six.int2byte(bits))
return EncodeSignedVarint | python | def _SignedVarintEncoder():
"""Return an encoder for a basic signed varint value (does not include
tag)."""
def EncodeSignedVarint(write, value):
if value < 0:
value += (1 << 64)
bits = value & 0x7f
value >>= 7
while value:
write(six.int2byte(0x80|bits))
bits = value & 0x7f
value >>= 7
return write(six.int2byte(bits))
return EncodeSignedVarint | [
"def",
"_SignedVarintEncoder",
"(",
")",
":",
"def",
"EncodeSignedVarint",
"(",
"write",
",",
"value",
")",
":",
"if",
"value",
"<",
"0",
":",
"value",
"+=",
"(",
"1",
"<<",
"64",
")",
"bits",
"=",
"value",
"&",
"0x7f",
"value",
">>=",
"7",
"while",
"value",
":",
"write",
"(",
"six",
".",
"int2byte",
"(",
"0x80",
"|",
"bits",
")",
")",
"bits",
"=",
"value",
"&",
"0x7f",
"value",
">>=",
"7",
"return",
"write",
"(",
"six",
".",
"int2byte",
"(",
"bits",
")",
")",
"return",
"EncodeSignedVarint"
] | Return an encoder for a basic signed varint value (does not include
tag). | [
"Return",
"an",
"encoder",
"for",
"a",
"basic",
"signed",
"varint",
"value",
"(",
"does",
"not",
"include",
"tag",
")",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L387-L402 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | _VarintBytes | def _VarintBytes(value):
"""Encode the given integer as a varint and return the bytes. This is only
called at startup time so it doesn't need to be fast."""
pieces = []
_EncodeVarint(pieces.append, value)
return b"".join(pieces) | python | def _VarintBytes(value):
"""Encode the given integer as a varint and return the bytes. This is only
called at startup time so it doesn't need to be fast."""
pieces = []
_EncodeVarint(pieces.append, value)
return b"".join(pieces) | [
"def",
"_VarintBytes",
"(",
"value",
")",
":",
"pieces",
"=",
"[",
"]",
"_EncodeVarint",
"(",
"pieces",
".",
"append",
",",
"value",
")",
"return",
"b\"\"",
".",
"join",
"(",
"pieces",
")"
] | Encode the given integer as a varint and return the bytes. This is only
called at startup time so it doesn't need to be fast. | [
"Encode",
"the",
"given",
"integer",
"as",
"a",
"varint",
"and",
"return",
"the",
"bytes",
".",
"This",
"is",
"only",
"called",
"at",
"startup",
"time",
"so",
"it",
"doesn",
"t",
"need",
"to",
"be",
"fast",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L409-L415 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | _SimpleEncoder | def _SimpleEncoder(wire_type, encode_value, compute_value_size):
"""Return a constructor for an encoder for fields of a particular type.
Args:
wire_type: The field's wire type, for encoding tags.
encode_value: A function which encodes an individual value, e.g.
_EncodeVarint().
compute_value_size: A function which computes the size of an individual
value, e.g. _VarintSize().
"""
def SpecificEncoder(field_number, is_repeated, is_packed):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
size = 0
for element in value:
size += compute_value_size(element)
local_EncodeVarint(write, size)
for element in value:
encode_value(write, element)
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeRepeatedField(write, value):
for element in value:
write(tag_bytes)
encode_value(write, element)
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeField(write, value):
write(tag_bytes)
return encode_value(write, value)
return EncodeField
return SpecificEncoder | python | def _SimpleEncoder(wire_type, encode_value, compute_value_size):
"""Return a constructor for an encoder for fields of a particular type.
Args:
wire_type: The field's wire type, for encoding tags.
encode_value: A function which encodes an individual value, e.g.
_EncodeVarint().
compute_value_size: A function which computes the size of an individual
value, e.g. _VarintSize().
"""
def SpecificEncoder(field_number, is_repeated, is_packed):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
size = 0
for element in value:
size += compute_value_size(element)
local_EncodeVarint(write, size)
for element in value:
encode_value(write, element)
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeRepeatedField(write, value):
for element in value:
write(tag_bytes)
encode_value(write, element)
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeField(write, value):
write(tag_bytes)
return encode_value(write, value)
return EncodeField
return SpecificEncoder | [
"def",
"_SimpleEncoder",
"(",
"wire_type",
",",
"encode_value",
",",
"compute_value_size",
")",
":",
"def",
"SpecificEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"if",
"is_packed",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_LENGTH_DELIMITED",
")",
"local_EncodeVarint",
"=",
"_EncodeVarint",
"def",
"EncodePackedField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"tag_bytes",
")",
"size",
"=",
"0",
"for",
"element",
"in",
"value",
":",
"size",
"+=",
"compute_value_size",
"(",
"element",
")",
"local_EncodeVarint",
"(",
"write",
",",
"size",
")",
"for",
"element",
"in",
"value",
":",
"encode_value",
"(",
"write",
",",
"element",
")",
"return",
"EncodePackedField",
"elif",
"is_repeated",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_type",
")",
"def",
"EncodeRepeatedField",
"(",
"write",
",",
"value",
")",
":",
"for",
"element",
"in",
"value",
":",
"write",
"(",
"tag_bytes",
")",
"encode_value",
"(",
"write",
",",
"element",
")",
"return",
"EncodeRepeatedField",
"else",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_type",
")",
"def",
"EncodeField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"tag_bytes",
")",
"return",
"encode_value",
"(",
"write",
",",
"value",
")",
"return",
"EncodeField",
"return",
"SpecificEncoder"
] | Return a constructor for an encoder for fields of a particular type.
Args:
wire_type: The field's wire type, for encoding tags.
encode_value: A function which encodes an individual value, e.g.
_EncodeVarint().
compute_value_size: A function which computes the size of an individual
value, e.g. _VarintSize(). | [
"Return",
"a",
"constructor",
"for",
"an",
"encoder",
"for",
"fields",
"of",
"a",
"particular",
"type",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L428-L466 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | _StructPackEncoder | def _StructPackEncoder(wire_type, format):
"""Return a constructor for an encoder for a fixed-width field.
Args:
wire_type: The field's wire type, for encoding tags.
format: The format string to pass to struct.pack().
"""
value_size = struct.calcsize(format)
def SpecificEncoder(field_number, is_repeated, is_packed):
local_struct_pack = struct.pack
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
local_EncodeVarint(write, len(value) * value_size)
for element in value:
write(local_struct_pack(format, element))
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeRepeatedField(write, value):
for element in value:
write(tag_bytes)
write(local_struct_pack(format, element))
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeField(write, value):
write(tag_bytes)
return write(local_struct_pack(format, value))
return EncodeField
return SpecificEncoder | python | def _StructPackEncoder(wire_type, format):
"""Return a constructor for an encoder for a fixed-width field.
Args:
wire_type: The field's wire type, for encoding tags.
format: The format string to pass to struct.pack().
"""
value_size = struct.calcsize(format)
def SpecificEncoder(field_number, is_repeated, is_packed):
local_struct_pack = struct.pack
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
local_EncodeVarint(write, len(value) * value_size)
for element in value:
write(local_struct_pack(format, element))
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeRepeatedField(write, value):
for element in value:
write(tag_bytes)
write(local_struct_pack(format, element))
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeField(write, value):
write(tag_bytes)
return write(local_struct_pack(format, value))
return EncodeField
return SpecificEncoder | [
"def",
"_StructPackEncoder",
"(",
"wire_type",
",",
"format",
")",
":",
"value_size",
"=",
"struct",
".",
"calcsize",
"(",
"format",
")",
"def",
"SpecificEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"local_struct_pack",
"=",
"struct",
".",
"pack",
"if",
"is_packed",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_LENGTH_DELIMITED",
")",
"local_EncodeVarint",
"=",
"_EncodeVarint",
"def",
"EncodePackedField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"tag_bytes",
")",
"local_EncodeVarint",
"(",
"write",
",",
"len",
"(",
"value",
")",
"*",
"value_size",
")",
"for",
"element",
"in",
"value",
":",
"write",
"(",
"local_struct_pack",
"(",
"format",
",",
"element",
")",
")",
"return",
"EncodePackedField",
"elif",
"is_repeated",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_type",
")",
"def",
"EncodeRepeatedField",
"(",
"write",
",",
"value",
")",
":",
"for",
"element",
"in",
"value",
":",
"write",
"(",
"tag_bytes",
")",
"write",
"(",
"local_struct_pack",
"(",
"format",
",",
"element",
")",
")",
"return",
"EncodeRepeatedField",
"else",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_type",
")",
"def",
"EncodeField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"tag_bytes",
")",
"return",
"write",
"(",
"local_struct_pack",
"(",
"format",
",",
"value",
")",
")",
"return",
"EncodeField",
"return",
"SpecificEncoder"
] | Return a constructor for an encoder for a fixed-width field.
Args:
wire_type: The field's wire type, for encoding tags.
format: The format string to pass to struct.pack(). | [
"Return",
"a",
"constructor",
"for",
"an",
"encoder",
"for",
"a",
"fixed",
"-",
"width",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L503-L538 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | _FloatingPointEncoder | def _FloatingPointEncoder(wire_type, format):
"""Return a constructor for an encoder for float fields.
This is like StructPackEncoder, but catches errors that may be due to
passing non-finite floating-point values to struct.pack, and makes a
second attempt to encode those values.
Args:
wire_type: The field's wire type, for encoding tags.
format: The format string to pass to struct.pack().
"""
value_size = struct.calcsize(format)
if value_size == 4:
def EncodeNonFiniteOrRaise(write, value):
# Remember that the serialized form uses little-endian byte order.
if value == _POS_INF:
write(b'\x00\x00\x80\x7F')
elif value == _NEG_INF:
write(b'\x00\x00\x80\xFF')
elif value != value: # NaN
write(b'\x00\x00\xC0\x7F')
else:
raise
elif value_size == 8:
def EncodeNonFiniteOrRaise(write, value):
if value == _POS_INF:
write(b'\x00\x00\x00\x00\x00\x00\xF0\x7F')
elif value == _NEG_INF:
write(b'\x00\x00\x00\x00\x00\x00\xF0\xFF')
elif value != value: # NaN
write(b'\x00\x00\x00\x00\x00\x00\xF8\x7F')
else:
raise
else:
raise ValueError('Can\'t encode floating-point values that are '
'%d bytes long (only 4 or 8)' % value_size)
def SpecificEncoder(field_number, is_repeated, is_packed):
local_struct_pack = struct.pack
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
local_EncodeVarint(write, len(value) * value_size)
for element in value:
# This try/except block is going to be faster than any code that
# we could write to check whether element is finite.
try:
write(local_struct_pack(format, element))
except SystemError:
EncodeNonFiniteOrRaise(write, element)
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeRepeatedField(write, value):
for element in value:
write(tag_bytes)
try:
write(local_struct_pack(format, element))
except SystemError:
EncodeNonFiniteOrRaise(write, element)
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeField(write, value):
write(tag_bytes)
try:
write(local_struct_pack(format, value))
except SystemError:
EncodeNonFiniteOrRaise(write, value)
return EncodeField
return SpecificEncoder | python | def _FloatingPointEncoder(wire_type, format):
"""Return a constructor for an encoder for float fields.
This is like StructPackEncoder, but catches errors that may be due to
passing non-finite floating-point values to struct.pack, and makes a
second attempt to encode those values.
Args:
wire_type: The field's wire type, for encoding tags.
format: The format string to pass to struct.pack().
"""
value_size = struct.calcsize(format)
if value_size == 4:
def EncodeNonFiniteOrRaise(write, value):
# Remember that the serialized form uses little-endian byte order.
if value == _POS_INF:
write(b'\x00\x00\x80\x7F')
elif value == _NEG_INF:
write(b'\x00\x00\x80\xFF')
elif value != value: # NaN
write(b'\x00\x00\xC0\x7F')
else:
raise
elif value_size == 8:
def EncodeNonFiniteOrRaise(write, value):
if value == _POS_INF:
write(b'\x00\x00\x00\x00\x00\x00\xF0\x7F')
elif value == _NEG_INF:
write(b'\x00\x00\x00\x00\x00\x00\xF0\xFF')
elif value != value: # NaN
write(b'\x00\x00\x00\x00\x00\x00\xF8\x7F')
else:
raise
else:
raise ValueError('Can\'t encode floating-point values that are '
'%d bytes long (only 4 or 8)' % value_size)
def SpecificEncoder(field_number, is_repeated, is_packed):
local_struct_pack = struct.pack
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
local_EncodeVarint(write, len(value) * value_size)
for element in value:
# This try/except block is going to be faster than any code that
# we could write to check whether element is finite.
try:
write(local_struct_pack(format, element))
except SystemError:
EncodeNonFiniteOrRaise(write, element)
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeRepeatedField(write, value):
for element in value:
write(tag_bytes)
try:
write(local_struct_pack(format, element))
except SystemError:
EncodeNonFiniteOrRaise(write, element)
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeField(write, value):
write(tag_bytes)
try:
write(local_struct_pack(format, value))
except SystemError:
EncodeNonFiniteOrRaise(write, value)
return EncodeField
return SpecificEncoder | [
"def",
"_FloatingPointEncoder",
"(",
"wire_type",
",",
"format",
")",
":",
"value_size",
"=",
"struct",
".",
"calcsize",
"(",
"format",
")",
"if",
"value_size",
"==",
"4",
":",
"def",
"EncodeNonFiniteOrRaise",
"(",
"write",
",",
"value",
")",
":",
"# Remember that the serialized form uses little-endian byte order.",
"if",
"value",
"==",
"_POS_INF",
":",
"write",
"(",
"b'\\x00\\x00\\x80\\x7F'",
")",
"elif",
"value",
"==",
"_NEG_INF",
":",
"write",
"(",
"b'\\x00\\x00\\x80\\xFF'",
")",
"elif",
"value",
"!=",
"value",
":",
"# NaN",
"write",
"(",
"b'\\x00\\x00\\xC0\\x7F'",
")",
"else",
":",
"raise",
"elif",
"value_size",
"==",
"8",
":",
"def",
"EncodeNonFiniteOrRaise",
"(",
"write",
",",
"value",
")",
":",
"if",
"value",
"==",
"_POS_INF",
":",
"write",
"(",
"b'\\x00\\x00\\x00\\x00\\x00\\x00\\xF0\\x7F'",
")",
"elif",
"value",
"==",
"_NEG_INF",
":",
"write",
"(",
"b'\\x00\\x00\\x00\\x00\\x00\\x00\\xF0\\xFF'",
")",
"elif",
"value",
"!=",
"value",
":",
"# NaN",
"write",
"(",
"b'\\x00\\x00\\x00\\x00\\x00\\x00\\xF8\\x7F'",
")",
"else",
":",
"raise",
"else",
":",
"raise",
"ValueError",
"(",
"'Can\\'t encode floating-point values that are '",
"'%d bytes long (only 4 or 8)'",
"%",
"value_size",
")",
"def",
"SpecificEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"local_struct_pack",
"=",
"struct",
".",
"pack",
"if",
"is_packed",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_LENGTH_DELIMITED",
")",
"local_EncodeVarint",
"=",
"_EncodeVarint",
"def",
"EncodePackedField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"tag_bytes",
")",
"local_EncodeVarint",
"(",
"write",
",",
"len",
"(",
"value",
")",
"*",
"value_size",
")",
"for",
"element",
"in",
"value",
":",
"# This try/except block is going to be faster than any code that",
"# we could write to check whether element is finite.",
"try",
":",
"write",
"(",
"local_struct_pack",
"(",
"format",
",",
"element",
")",
")",
"except",
"SystemError",
":",
"EncodeNonFiniteOrRaise",
"(",
"write",
",",
"element",
")",
"return",
"EncodePackedField",
"elif",
"is_repeated",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_type",
")",
"def",
"EncodeRepeatedField",
"(",
"write",
",",
"value",
")",
":",
"for",
"element",
"in",
"value",
":",
"write",
"(",
"tag_bytes",
")",
"try",
":",
"write",
"(",
"local_struct_pack",
"(",
"format",
",",
"element",
")",
")",
"except",
"SystemError",
":",
"EncodeNonFiniteOrRaise",
"(",
"write",
",",
"element",
")",
"return",
"EncodeRepeatedField",
"else",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_type",
")",
"def",
"EncodeField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"tag_bytes",
")",
"try",
":",
"write",
"(",
"local_struct_pack",
"(",
"format",
",",
"value",
")",
")",
"except",
"SystemError",
":",
"EncodeNonFiniteOrRaise",
"(",
"write",
",",
"value",
")",
"return",
"EncodeField",
"return",
"SpecificEncoder"
] | Return a constructor for an encoder for float fields.
This is like StructPackEncoder, but catches errors that may be due to
passing non-finite floating-point values to struct.pack, and makes a
second attempt to encode those values.
Args:
wire_type: The field's wire type, for encoding tags.
format: The format string to pass to struct.pack(). | [
"Return",
"a",
"constructor",
"for",
"an",
"encoder",
"for",
"float",
"fields",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L541-L615 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | BoolEncoder | def BoolEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a boolean field."""
false_byte = b'\x00'
true_byte = b'\x01'
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
local_EncodeVarint(write, len(value))
for element in value:
if element:
write(true_byte)
else:
write(false_byte)
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)
def EncodeRepeatedField(write, value):
for element in value:
write(tag_bytes)
if element:
write(true_byte)
else:
write(false_byte)
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)
def EncodeField(write, value):
write(tag_bytes)
if value:
return write(true_byte)
return write(false_byte)
return EncodeField | python | def BoolEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a boolean field."""
false_byte = b'\x00'
true_byte = b'\x01'
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
local_EncodeVarint(write, len(value))
for element in value:
if element:
write(true_byte)
else:
write(false_byte)
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)
def EncodeRepeatedField(write, value):
for element in value:
write(tag_bytes)
if element:
write(true_byte)
else:
write(false_byte)
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)
def EncodeField(write, value):
write(tag_bytes)
if value:
return write(true_byte)
return write(false_byte)
return EncodeField | [
"def",
"BoolEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"false_byte",
"=",
"b'\\x00'",
"true_byte",
"=",
"b'\\x01'",
"if",
"is_packed",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_LENGTH_DELIMITED",
")",
"local_EncodeVarint",
"=",
"_EncodeVarint",
"def",
"EncodePackedField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"tag_bytes",
")",
"local_EncodeVarint",
"(",
"write",
",",
"len",
"(",
"value",
")",
")",
"for",
"element",
"in",
"value",
":",
"if",
"element",
":",
"write",
"(",
"true_byte",
")",
"else",
":",
"write",
"(",
"false_byte",
")",
"return",
"EncodePackedField",
"elif",
"is_repeated",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_VARINT",
")",
"def",
"EncodeRepeatedField",
"(",
"write",
",",
"value",
")",
":",
"for",
"element",
"in",
"value",
":",
"write",
"(",
"tag_bytes",
")",
"if",
"element",
":",
"write",
"(",
"true_byte",
")",
"else",
":",
"write",
"(",
"false_byte",
")",
"return",
"EncodeRepeatedField",
"else",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_VARINT",
")",
"def",
"EncodeField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"tag_bytes",
")",
"if",
"value",
":",
"return",
"write",
"(",
"true_byte",
")",
"return",
"write",
"(",
"false_byte",
")",
"return",
"EncodeField"
] | Returns an encoder for a boolean field. | [
"Returns",
"an",
"encoder",
"for",
"a",
"boolean",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L645-L679 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | StringEncoder | def StringEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a string field."""
tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
local_len = len
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
encoded = element.encode('utf-8')
write(tag)
local_EncodeVarint(write, local_len(encoded))
write(encoded)
return EncodeRepeatedField
else:
def EncodeField(write, value):
encoded = value.encode('utf-8')
write(tag)
local_EncodeVarint(write, local_len(encoded))
return write(encoded)
return EncodeField | python | def StringEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a string field."""
tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
local_len = len
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
encoded = element.encode('utf-8')
write(tag)
local_EncodeVarint(write, local_len(encoded))
write(encoded)
return EncodeRepeatedField
else:
def EncodeField(write, value):
encoded = value.encode('utf-8')
write(tag)
local_EncodeVarint(write, local_len(encoded))
return write(encoded)
return EncodeField | [
"def",
"StringEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"tag",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_LENGTH_DELIMITED",
")",
"local_EncodeVarint",
"=",
"_EncodeVarint",
"local_len",
"=",
"len",
"assert",
"not",
"is_packed",
"if",
"is_repeated",
":",
"def",
"EncodeRepeatedField",
"(",
"write",
",",
"value",
")",
":",
"for",
"element",
"in",
"value",
":",
"encoded",
"=",
"element",
".",
"encode",
"(",
"'utf-8'",
")",
"write",
"(",
"tag",
")",
"local_EncodeVarint",
"(",
"write",
",",
"local_len",
"(",
"encoded",
")",
")",
"write",
"(",
"encoded",
")",
"return",
"EncodeRepeatedField",
"else",
":",
"def",
"EncodeField",
"(",
"write",
",",
"value",
")",
":",
"encoded",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"write",
"(",
"tag",
")",
"local_EncodeVarint",
"(",
"write",
",",
"local_len",
"(",
"encoded",
")",
")",
"return",
"write",
"(",
"encoded",
")",
"return",
"EncodeField"
] | Returns an encoder for a string field. | [
"Returns",
"an",
"encoder",
"for",
"a",
"string",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L682-L703 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | GroupEncoder | def GroupEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a group field."""
start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP)
end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP)
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
write(start_tag)
element._InternalSerialize(write)
write(end_tag)
return EncodeRepeatedField
else:
def EncodeField(write, value):
write(start_tag)
value._InternalSerialize(write)
return write(end_tag)
return EncodeField | python | def GroupEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a group field."""
start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP)
end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP)
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
write(start_tag)
element._InternalSerialize(write)
write(end_tag)
return EncodeRepeatedField
else:
def EncodeField(write, value):
write(start_tag)
value._InternalSerialize(write)
return write(end_tag)
return EncodeField | [
"def",
"GroupEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"start_tag",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_START_GROUP",
")",
"end_tag",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_END_GROUP",
")",
"assert",
"not",
"is_packed",
"if",
"is_repeated",
":",
"def",
"EncodeRepeatedField",
"(",
"write",
",",
"value",
")",
":",
"for",
"element",
"in",
"value",
":",
"write",
"(",
"start_tag",
")",
"element",
".",
"_InternalSerialize",
"(",
"write",
")",
"write",
"(",
"end_tag",
")",
"return",
"EncodeRepeatedField",
"else",
":",
"def",
"EncodeField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"start_tag",
")",
"value",
".",
"_InternalSerialize",
"(",
"write",
")",
"return",
"write",
"(",
"end_tag",
")",
"return",
"EncodeField"
] | Returns an encoder for a group field. | [
"Returns",
"an",
"encoder",
"for",
"a",
"group",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L728-L746 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | MessageEncoder | def MessageEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a message field."""
tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
write(tag)
local_EncodeVarint(write, element.ByteSize())
element._InternalSerialize(write)
return EncodeRepeatedField
else:
def EncodeField(write, value):
write(tag)
local_EncodeVarint(write, value.ByteSize())
return value._InternalSerialize(write)
return EncodeField | python | def MessageEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a message field."""
tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
write(tag)
local_EncodeVarint(write, element.ByteSize())
element._InternalSerialize(write)
return EncodeRepeatedField
else:
def EncodeField(write, value):
write(tag)
local_EncodeVarint(write, value.ByteSize())
return value._InternalSerialize(write)
return EncodeField | [
"def",
"MessageEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"tag",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_LENGTH_DELIMITED",
")",
"local_EncodeVarint",
"=",
"_EncodeVarint",
"assert",
"not",
"is_packed",
"if",
"is_repeated",
":",
"def",
"EncodeRepeatedField",
"(",
"write",
",",
"value",
")",
":",
"for",
"element",
"in",
"value",
":",
"write",
"(",
"tag",
")",
"local_EncodeVarint",
"(",
"write",
",",
"element",
".",
"ByteSize",
"(",
")",
")",
"element",
".",
"_InternalSerialize",
"(",
"write",
")",
"return",
"EncodeRepeatedField",
"else",
":",
"def",
"EncodeField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"tag",
")",
"local_EncodeVarint",
"(",
"write",
",",
"value",
".",
"ByteSize",
"(",
")",
")",
"return",
"value",
".",
"_InternalSerialize",
"(",
"write",
")",
"return",
"EncodeField"
] | Returns an encoder for a message field. | [
"Returns",
"an",
"encoder",
"for",
"a",
"message",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L749-L767 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | MessageSetItemEncoder | def MessageSetItemEncoder(field_number):
"""Encoder for extensions of MessageSet.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
}
"""
start_bytes = b"".join([
TagBytes(1, wire_format.WIRETYPE_START_GROUP),
TagBytes(2, wire_format.WIRETYPE_VARINT),
_VarintBytes(field_number),
TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)])
end_bytes = TagBytes(1, wire_format.WIRETYPE_END_GROUP)
local_EncodeVarint = _EncodeVarint
def EncodeField(write, value):
write(start_bytes)
local_EncodeVarint(write, value.ByteSize())
value._InternalSerialize(write)
return write(end_bytes)
return EncodeField | python | def MessageSetItemEncoder(field_number):
"""Encoder for extensions of MessageSet.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
}
"""
start_bytes = b"".join([
TagBytes(1, wire_format.WIRETYPE_START_GROUP),
TagBytes(2, wire_format.WIRETYPE_VARINT),
_VarintBytes(field_number),
TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)])
end_bytes = TagBytes(1, wire_format.WIRETYPE_END_GROUP)
local_EncodeVarint = _EncodeVarint
def EncodeField(write, value):
write(start_bytes)
local_EncodeVarint(write, value.ByteSize())
value._InternalSerialize(write)
return write(end_bytes)
return EncodeField | [
"def",
"MessageSetItemEncoder",
"(",
"field_number",
")",
":",
"start_bytes",
"=",
"b\"\"",
".",
"join",
"(",
"[",
"TagBytes",
"(",
"1",
",",
"wire_format",
".",
"WIRETYPE_START_GROUP",
")",
",",
"TagBytes",
"(",
"2",
",",
"wire_format",
".",
"WIRETYPE_VARINT",
")",
",",
"_VarintBytes",
"(",
"field_number",
")",
",",
"TagBytes",
"(",
"3",
",",
"wire_format",
".",
"WIRETYPE_LENGTH_DELIMITED",
")",
"]",
")",
"end_bytes",
"=",
"TagBytes",
"(",
"1",
",",
"wire_format",
".",
"WIRETYPE_END_GROUP",
")",
"local_EncodeVarint",
"=",
"_EncodeVarint",
"def",
"EncodeField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"start_bytes",
")",
"local_EncodeVarint",
"(",
"write",
",",
"value",
".",
"ByteSize",
"(",
")",
")",
"value",
".",
"_InternalSerialize",
"(",
"write",
")",
"return",
"write",
"(",
"end_bytes",
")",
"return",
"EncodeField"
] | Encoder for extensions of MessageSet.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
} | [
"Encoder",
"for",
"extensions",
"of",
"MessageSet",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L774-L799 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | MapEncoder | def MapEncoder(field_descriptor):
"""Encoder for extensions of MessageSet.
Maps always have a wire format like this:
message MapEntry {
key_type key = 1;
value_type value = 2;
}
repeated MapEntry map = N;
"""
# Can't look at field_descriptor.message_type._concrete_class because it may
# not have been initialized yet.
message_type = field_descriptor.message_type
encode_message = MessageEncoder(field_descriptor.number, False, False)
def EncodeField(write, value):
for key in value:
entry_msg = message_type._concrete_class(key=key, value=value[key])
encode_message(write, entry_msg)
return EncodeField | python | def MapEncoder(field_descriptor):
"""Encoder for extensions of MessageSet.
Maps always have a wire format like this:
message MapEntry {
key_type key = 1;
value_type value = 2;
}
repeated MapEntry map = N;
"""
# Can't look at field_descriptor.message_type._concrete_class because it may
# not have been initialized yet.
message_type = field_descriptor.message_type
encode_message = MessageEncoder(field_descriptor.number, False, False)
def EncodeField(write, value):
for key in value:
entry_msg = message_type._concrete_class(key=key, value=value[key])
encode_message(write, entry_msg)
return EncodeField | [
"def",
"MapEncoder",
"(",
"field_descriptor",
")",
":",
"# Can't look at field_descriptor.message_type._concrete_class because it may",
"# not have been initialized yet.",
"message_type",
"=",
"field_descriptor",
".",
"message_type",
"encode_message",
"=",
"MessageEncoder",
"(",
"field_descriptor",
".",
"number",
",",
"False",
",",
"False",
")",
"def",
"EncodeField",
"(",
"write",
",",
"value",
")",
":",
"for",
"key",
"in",
"value",
":",
"entry_msg",
"=",
"message_type",
".",
"_concrete_class",
"(",
"key",
"=",
"key",
",",
"value",
"=",
"value",
"[",
"key",
"]",
")",
"encode_message",
"(",
"write",
",",
"entry_msg",
")",
"return",
"EncodeField"
] | Encoder for extensions of MessageSet.
Maps always have a wire format like this:
message MapEntry {
key_type key = 1;
value_type value = 2;
}
repeated MapEntry map = N; | [
"Encoder",
"for",
"extensions",
"of",
"MessageSet",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L806-L826 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/caffe/_caffe_converter.py | convert | def convert(model, image_input_names=[], is_bgr=False,
red_bias=0.0, blue_bias=0.0, green_bias=0.0, gray_bias=0.0,
image_scale=1.0, class_labels=None, predicted_feature_name=None, model_precision=_MLMODEL_FULL_PRECISION):
"""
Convert a Caffe model to Core ML format.
Parameters
----------
model: str | (str, str) | (str, str, str) | (str, str, dict)
A trained Caffe neural network model which can be represented as:
- Path on disk to a trained Caffe model (.caffemodel)
- A tuple of two paths, where the first path is the path to the .caffemodel
file while the second is the path to the deploy.prototxt.
- A tuple of three paths, where the first path is the path to the
trained .caffemodel file, the second is the path to the
deploy.prototxt while the third is a path to the mean image binary, data in
which is subtracted from the input image as a preprocessing step.
- A tuple of two paths to .caffemodel and .prototxt and a dict with image input names
as keys and paths to mean image binaryprotos as values. The keys should be same as
the input names provided via the argument 'image_input_name'.
image_input_names: [str] | str
The name(s) of the input blob(s) in the Caffe model that can be treated
as images by Core ML. All other inputs are treated as MultiArrays (N-D
Arrays) by Core ML.
is_bgr: bool | dict()
Flag indicating the channel order the model internally uses to represent
color images. Set to True if the internal channel order is BGR,
otherwise it will be assumed RGB. This flag is applicable only if
image_input_names is specified. To specify a different value for each
image input, provide a dictionary with input names as keys.
Note that this flag is about the models internal channel order.
An input image can be passed to the model in any color pixel layout
containing red, green and blue values (e.g. 32BGRA or 32ARGB). This flag
determines how those pixel values get mapped to the internal multiarray
representation.
red_bias: float | dict()
Bias value to be added to the red channel of the input image.
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
blue_bias: float | dict()
Bias value to be added to the the blue channel of the input image.
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
green_bias: float | dict()
Bias value to be added to the green channel of the input image.
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
gray_bias: float | dict()
Bias value to be added to the input image (in grayscale).
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
image_scale: float | dict()
Value by which the input images will be scaled before bias is added and
Core ML model makes a prediction. Defaults to 1.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
class_labels: str
Filepath where classes are parsed as a list of newline separated
strings. Class labels map the index of the output of a neural network to labels in a classifier.
Provide this argument to get a model of type classifier.
predicted_feature_name: str
Name of the output feature for the class labels exposed in the Core ML
model (applies to classifiers only). Defaults to 'classLabel'
model_precision: str
Precision at which model will be saved. Currently full precision (float) and half precision
(float16) models are supported. Defaults to '_MLMODEL_FULL_PRECISION' (full precision).
Returns
-------
model: MLModel
Model in Core ML format.
Examples
--------
.. sourcecode:: python
# Convert it with default input and output names
>>> import coremltools
>>> coreml_model = coremltools.converters.caffe.convert('my_caffe_model.caffemodel')
# Saving the Core ML model to a file.
>>> coreml_model.save('my_model.mlmodel')
Sometimes, critical information in the Caffe converter is missing from the
.caffemodel file. This information is present in the deploy.prototxt file.
You can provide us with both files in the conversion process.
.. sourcecode:: python
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_deploy.prototxt'))
Some models (like Resnet-50) also require a mean image file which is
subtracted from the input image before passing through the network. This
file can also be provided during conversion:
.. sourcecode:: python
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel',
... 'my_deploy.prototxt', 'mean_image.binaryproto'), image_input_names = 'image_input')
# Multiple mean images for preprocessing
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel',
... 'my_deploy.prototxt', {'image1': 'mean_image1.binaryproto', 'image2': 'mean_image2.binaryproto'}),
... image_input_names = ['image1', 'image2'])
# Multiple image inputs and bias/scale values
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_deploy.prototxt'),
... red_bias = {'image1': -100, 'image2': -110},
... green_bias = {'image1': -90, 'image2': -125},
... blue_bias = {'image1': -105, 'image2': -120},
... image_input_names = ['image1', 'image2'])
Input and output names used in the interface of the converted Core ML model are inferred from the .prototxt file,
which contains a description of the network architecture.
Input names are read from the input layer definition in the .prototxt. By default, they are of type MultiArray.
Argument "image_input_names" can be used to assign image type to specific inputs.
All the blobs that are "dangling", i.e.
which do not feed as input to any other layer are taken as outputs. The .prototxt file can be modified to specify
custom input and output names.
The converted Core ML model is of type classifier when the argument "class_labels" is specified.
Advanced usage with custom classifiers, and images:
.. sourcecode:: python
# Mark some inputs as Images
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_caffe_model.prototxt'),
... image_input_names = 'my_image_input')
# Export as a classifier with classes from a file
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_caffe_model.prototxt'),
... image_input_names = 'my_image_input', class_labels = 'labels.txt')
Sometimes the converter might return a message about not able to infer input data dimensions.
This happens when the input size information is absent from the deploy.prototxt file. This can be easily provided by editing
the .prototxt in a text editor. Simply add a snippet in the beginning, similar to the following, for each of the inputs to the model:
.. code-block:: bash
input: "my_image_input"
input_dim: 1
input_dim: 3
input_dim: 227
input_dim: 227
Here we have specified an input with dimensions (1,3,227,227), using Caffe's convention, in the order (batch, channel, height, width).
Input name string ("my_image_input") must also match the name of the input (or "bottom", as inputs are known in Caffe) of the first layer in the .prototxt.
"""
from ...models import MLModel
from ...models.utils import convert_neural_network_weights_to_fp16 as convert_neural_network_weights_to_fp16
if model_precision not in _VALID_MLMODEL_PRECISION_TYPES:
raise RuntimeError('Model precision {} is not valid'.format(model_precision))
import tempfile
model_path = tempfile.mktemp()
_export(model_path, model, image_input_names, is_bgr, red_bias,
blue_bias,
green_bias, gray_bias, image_scale, class_labels,
predicted_feature_name)
model = MLModel(model_path)
if model_precision == _MLMODEL_HALF_PRECISION and model is not None:
model = convert_neural_network_weights_to_fp16(model)
return model | python | def convert(model, image_input_names=[], is_bgr=False,
red_bias=0.0, blue_bias=0.0, green_bias=0.0, gray_bias=0.0,
image_scale=1.0, class_labels=None, predicted_feature_name=None, model_precision=_MLMODEL_FULL_PRECISION):
"""
Convert a Caffe model to Core ML format.
Parameters
----------
model: str | (str, str) | (str, str, str) | (str, str, dict)
A trained Caffe neural network model which can be represented as:
- Path on disk to a trained Caffe model (.caffemodel)
- A tuple of two paths, where the first path is the path to the .caffemodel
file while the second is the path to the deploy.prototxt.
- A tuple of three paths, where the first path is the path to the
trained .caffemodel file, the second is the path to the
deploy.prototxt while the third is a path to the mean image binary, data in
which is subtracted from the input image as a preprocessing step.
- A tuple of two paths to .caffemodel and .prototxt and a dict with image input names
as keys and paths to mean image binaryprotos as values. The keys should be same as
the input names provided via the argument 'image_input_name'.
image_input_names: [str] | str
The name(s) of the input blob(s) in the Caffe model that can be treated
as images by Core ML. All other inputs are treated as MultiArrays (N-D
Arrays) by Core ML.
is_bgr: bool | dict()
Flag indicating the channel order the model internally uses to represent
color images. Set to True if the internal channel order is BGR,
otherwise it will be assumed RGB. This flag is applicable only if
image_input_names is specified. To specify a different value for each
image input, provide a dictionary with input names as keys.
Note that this flag is about the models internal channel order.
An input image can be passed to the model in any color pixel layout
containing red, green and blue values (e.g. 32BGRA or 32ARGB). This flag
determines how those pixel values get mapped to the internal multiarray
representation.
red_bias: float | dict()
Bias value to be added to the red channel of the input image.
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
blue_bias: float | dict()
Bias value to be added to the the blue channel of the input image.
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
green_bias: float | dict()
Bias value to be added to the green channel of the input image.
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
gray_bias: float | dict()
Bias value to be added to the input image (in grayscale).
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
image_scale: float | dict()
Value by which the input images will be scaled before bias is added and
Core ML model makes a prediction. Defaults to 1.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
class_labels: str
Filepath where classes are parsed as a list of newline separated
strings. Class labels map the index of the output of a neural network to labels in a classifier.
Provide this argument to get a model of type classifier.
predicted_feature_name: str
Name of the output feature for the class labels exposed in the Core ML
model (applies to classifiers only). Defaults to 'classLabel'
model_precision: str
Precision at which model will be saved. Currently full precision (float) and half precision
(float16) models are supported. Defaults to '_MLMODEL_FULL_PRECISION' (full precision).
Returns
-------
model: MLModel
Model in Core ML format.
Examples
--------
.. sourcecode:: python
# Convert it with default input and output names
>>> import coremltools
>>> coreml_model = coremltools.converters.caffe.convert('my_caffe_model.caffemodel')
# Saving the Core ML model to a file.
>>> coreml_model.save('my_model.mlmodel')
Sometimes, critical information in the Caffe converter is missing from the
.caffemodel file. This information is present in the deploy.prototxt file.
You can provide us with both files in the conversion process.
.. sourcecode:: python
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_deploy.prototxt'))
Some models (like Resnet-50) also require a mean image file which is
subtracted from the input image before passing through the network. This
file can also be provided during conversion:
.. sourcecode:: python
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel',
... 'my_deploy.prototxt', 'mean_image.binaryproto'), image_input_names = 'image_input')
# Multiple mean images for preprocessing
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel',
... 'my_deploy.prototxt', {'image1': 'mean_image1.binaryproto', 'image2': 'mean_image2.binaryproto'}),
... image_input_names = ['image1', 'image2'])
# Multiple image inputs and bias/scale values
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_deploy.prototxt'),
... red_bias = {'image1': -100, 'image2': -110},
... green_bias = {'image1': -90, 'image2': -125},
... blue_bias = {'image1': -105, 'image2': -120},
... image_input_names = ['image1', 'image2'])
Input and output names used in the interface of the converted Core ML model are inferred from the .prototxt file,
which contains a description of the network architecture.
Input names are read from the input layer definition in the .prototxt. By default, they are of type MultiArray.
Argument "image_input_names" can be used to assign image type to specific inputs.
All the blobs that are "dangling", i.e.
which do not feed as input to any other layer are taken as outputs. The .prototxt file can be modified to specify
custom input and output names.
The converted Core ML model is of type classifier when the argument "class_labels" is specified.
Advanced usage with custom classifiers, and images:
.. sourcecode:: python
# Mark some inputs as Images
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_caffe_model.prototxt'),
... image_input_names = 'my_image_input')
# Export as a classifier with classes from a file
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_caffe_model.prototxt'),
... image_input_names = 'my_image_input', class_labels = 'labels.txt')
Sometimes the converter might return a message about not able to infer input data dimensions.
This happens when the input size information is absent from the deploy.prototxt file. This can be easily provided by editing
the .prototxt in a text editor. Simply add a snippet in the beginning, similar to the following, for each of the inputs to the model:
.. code-block:: bash
input: "my_image_input"
input_dim: 1
input_dim: 3
input_dim: 227
input_dim: 227
Here we have specified an input with dimensions (1,3,227,227), using Caffe's convention, in the order (batch, channel, height, width).
Input name string ("my_image_input") must also match the name of the input (or "bottom", as inputs are known in Caffe) of the first layer in the .prototxt.
"""
from ...models import MLModel
from ...models.utils import convert_neural_network_weights_to_fp16 as convert_neural_network_weights_to_fp16
if model_precision not in _VALID_MLMODEL_PRECISION_TYPES:
raise RuntimeError('Model precision {} is not valid'.format(model_precision))
import tempfile
model_path = tempfile.mktemp()
_export(model_path, model, image_input_names, is_bgr, red_bias,
blue_bias,
green_bias, gray_bias, image_scale, class_labels,
predicted_feature_name)
model = MLModel(model_path)
if model_precision == _MLMODEL_HALF_PRECISION and model is not None:
model = convert_neural_network_weights_to_fp16(model)
return model | [
"def",
"convert",
"(",
"model",
",",
"image_input_names",
"=",
"[",
"]",
",",
"is_bgr",
"=",
"False",
",",
"red_bias",
"=",
"0.0",
",",
"blue_bias",
"=",
"0.0",
",",
"green_bias",
"=",
"0.0",
",",
"gray_bias",
"=",
"0.0",
",",
"image_scale",
"=",
"1.0",
",",
"class_labels",
"=",
"None",
",",
"predicted_feature_name",
"=",
"None",
",",
"model_precision",
"=",
"_MLMODEL_FULL_PRECISION",
")",
":",
"from",
".",
".",
".",
"models",
"import",
"MLModel",
"from",
".",
".",
".",
"models",
".",
"utils",
"import",
"convert_neural_network_weights_to_fp16",
"as",
"convert_neural_network_weights_to_fp16",
"if",
"model_precision",
"not",
"in",
"_VALID_MLMODEL_PRECISION_TYPES",
":",
"raise",
"RuntimeError",
"(",
"'Model precision {} is not valid'",
".",
"format",
"(",
"model_precision",
")",
")",
"import",
"tempfile",
"model_path",
"=",
"tempfile",
".",
"mktemp",
"(",
")",
"_export",
"(",
"model_path",
",",
"model",
",",
"image_input_names",
",",
"is_bgr",
",",
"red_bias",
",",
"blue_bias",
",",
"green_bias",
",",
"gray_bias",
",",
"image_scale",
",",
"class_labels",
",",
"predicted_feature_name",
")",
"model",
"=",
"MLModel",
"(",
"model_path",
")",
"if",
"model_precision",
"==",
"_MLMODEL_HALF_PRECISION",
"and",
"model",
"is",
"not",
"None",
":",
"model",
"=",
"convert_neural_network_weights_to_fp16",
"(",
"model",
")",
"return",
"model"
] | Convert a Caffe model to Core ML format.
Parameters
----------
model: str | (str, str) | (str, str, str) | (str, str, dict)
A trained Caffe neural network model which can be represented as:
- Path on disk to a trained Caffe model (.caffemodel)
- A tuple of two paths, where the first path is the path to the .caffemodel
file while the second is the path to the deploy.prototxt.
- A tuple of three paths, where the first path is the path to the
trained .caffemodel file, the second is the path to the
deploy.prototxt while the third is a path to the mean image binary, data in
which is subtracted from the input image as a preprocessing step.
- A tuple of two paths to .caffemodel and .prototxt and a dict with image input names
as keys and paths to mean image binaryprotos as values. The keys should be same as
the input names provided via the argument 'image_input_name'.
image_input_names: [str] | str
The name(s) of the input blob(s) in the Caffe model that can be treated
as images by Core ML. All other inputs are treated as MultiArrays (N-D
Arrays) by Core ML.
is_bgr: bool | dict()
Flag indicating the channel order the model internally uses to represent
color images. Set to True if the internal channel order is BGR,
otherwise it will be assumed RGB. This flag is applicable only if
image_input_names is specified. To specify a different value for each
image input, provide a dictionary with input names as keys.
Note that this flag is about the models internal channel order.
An input image can be passed to the model in any color pixel layout
containing red, green and blue values (e.g. 32BGRA or 32ARGB). This flag
determines how those pixel values get mapped to the internal multiarray
representation.
red_bias: float | dict()
Bias value to be added to the red channel of the input image.
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
blue_bias: float | dict()
Bias value to be added to the the blue channel of the input image.
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
green_bias: float | dict()
Bias value to be added to the green channel of the input image.
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
gray_bias: float | dict()
Bias value to be added to the input image (in grayscale).
Defaults to 0.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
image_scale: float | dict()
Value by which the input images will be scaled before bias is added and
Core ML model makes a prediction. Defaults to 1.0.
Applicable only if image_input_names is specified.
To specify different values for each image input provide a dictionary with input names as keys.
class_labels: str
Filepath where classes are parsed as a list of newline separated
strings. Class labels map the index of the output of a neural network to labels in a classifier.
Provide this argument to get a model of type classifier.
predicted_feature_name: str
Name of the output feature for the class labels exposed in the Core ML
model (applies to classifiers only). Defaults to 'classLabel'
model_precision: str
Precision at which model will be saved. Currently full precision (float) and half precision
(float16) models are supported. Defaults to '_MLMODEL_FULL_PRECISION' (full precision).
Returns
-------
model: MLModel
Model in Core ML format.
Examples
--------
.. sourcecode:: python
# Convert it with default input and output names
>>> import coremltools
>>> coreml_model = coremltools.converters.caffe.convert('my_caffe_model.caffemodel')
# Saving the Core ML model to a file.
>>> coreml_model.save('my_model.mlmodel')
Sometimes, critical information in the Caffe converter is missing from the
.caffemodel file. This information is present in the deploy.prototxt file.
You can provide us with both files in the conversion process.
.. sourcecode:: python
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_deploy.prototxt'))
Some models (like Resnet-50) also require a mean image file which is
subtracted from the input image before passing through the network. This
file can also be provided during conversion:
.. sourcecode:: python
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel',
... 'my_deploy.prototxt', 'mean_image.binaryproto'), image_input_names = 'image_input')
# Multiple mean images for preprocessing
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel',
... 'my_deploy.prototxt', {'image1': 'mean_image1.binaryproto', 'image2': 'mean_image2.binaryproto'}),
... image_input_names = ['image1', 'image2'])
# Multiple image inputs and bias/scale values
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_deploy.prototxt'),
... red_bias = {'image1': -100, 'image2': -110},
... green_bias = {'image1': -90, 'image2': -125},
... blue_bias = {'image1': -105, 'image2': -120},
... image_input_names = ['image1', 'image2'])
Input and output names used in the interface of the converted Core ML model are inferred from the .prototxt file,
which contains a description of the network architecture.
Input names are read from the input layer definition in the .prototxt. By default, they are of type MultiArray.
Argument "image_input_names" can be used to assign image type to specific inputs.
All the blobs that are "dangling", i.e.
which do not feed as input to any other layer are taken as outputs. The .prototxt file can be modified to specify
custom input and output names.
The converted Core ML model is of type classifier when the argument "class_labels" is specified.
Advanced usage with custom classifiers, and images:
.. sourcecode:: python
# Mark some inputs as Images
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_caffe_model.prototxt'),
... image_input_names = 'my_image_input')
# Export as a classifier with classes from a file
>>> coreml_model = coremltools.converters.caffe.convert(('my_caffe_model.caffemodel', 'my_caffe_model.prototxt'),
... image_input_names = 'my_image_input', class_labels = 'labels.txt')
Sometimes the converter might return a message about not able to infer input data dimensions.
This happens when the input size information is absent from the deploy.prototxt file. This can be easily provided by editing
the .prototxt in a text editor. Simply add a snippet in the beginning, similar to the following, for each of the inputs to the model:
.. code-block:: bash
input: "my_image_input"
input_dim: 1
input_dim: 3
input_dim: 227
input_dim: 227
Here we have specified an input with dimensions (1,3,227,227), using Caffe's convention, in the order (batch, channel, height, width).
Input name string ("my_image_input") must also match the name of the input (or "bottom", as inputs are known in Caffe) of the first layer in the .prototxt. | [
"Convert",
"a",
"Caffe",
"model",
"to",
"Core",
"ML",
"format",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/caffe/_caffe_converter.py#L10-L197 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_svm_common.py | _set_kernel | def _set_kernel(model, spec):
"""
Takes the sklearn SVM model and returns the spec with the protobuf kernel for that model.
"""
def gamma_value(model):
if(model.gamma == 'auto'):
# auto gamma value is 1/num_features
return 1/float(len(model.support_vectors_[0]))
else:
return model.gamma
result = None
if(model.kernel == 'linear'):
spec.kernel.linearKernel.MergeFromString(b'') # hack to set kernel to an empty type
elif(model.kernel == 'rbf'):
spec.kernel.rbfKernel.gamma = gamma_value(model)
elif(model.kernel == 'poly'):
spec.kernel.polyKernel.gamma = gamma_value(model)
spec.kernel.polyKernel.c = model.coef0
spec.kernel.polyKernel.degree = model.degree
elif(model.kernel == 'sigmoid'):
spec.kernel.sigmoidKernel.gamma = gamma_value(model)
spec.kernel.sigmoidKernel.c = model.coef0
else:
raise ValueError('Unsupported kernel. The following kernel are supported: linear, RBF, polynomial and sigmoid.')
return result | python | def _set_kernel(model, spec):
"""
Takes the sklearn SVM model and returns the spec with the protobuf kernel for that model.
"""
def gamma_value(model):
if(model.gamma == 'auto'):
# auto gamma value is 1/num_features
return 1/float(len(model.support_vectors_[0]))
else:
return model.gamma
result = None
if(model.kernel == 'linear'):
spec.kernel.linearKernel.MergeFromString(b'') # hack to set kernel to an empty type
elif(model.kernel == 'rbf'):
spec.kernel.rbfKernel.gamma = gamma_value(model)
elif(model.kernel == 'poly'):
spec.kernel.polyKernel.gamma = gamma_value(model)
spec.kernel.polyKernel.c = model.coef0
spec.kernel.polyKernel.degree = model.degree
elif(model.kernel == 'sigmoid'):
spec.kernel.sigmoidKernel.gamma = gamma_value(model)
spec.kernel.sigmoidKernel.c = model.coef0
else:
raise ValueError('Unsupported kernel. The following kernel are supported: linear, RBF, polynomial and sigmoid.')
return result | [
"def",
"_set_kernel",
"(",
"model",
",",
"spec",
")",
":",
"def",
"gamma_value",
"(",
"model",
")",
":",
"if",
"(",
"model",
".",
"gamma",
"==",
"'auto'",
")",
":",
"# auto gamma value is 1/num_features",
"return",
"1",
"/",
"float",
"(",
"len",
"(",
"model",
".",
"support_vectors_",
"[",
"0",
"]",
")",
")",
"else",
":",
"return",
"model",
".",
"gamma",
"result",
"=",
"None",
"if",
"(",
"model",
".",
"kernel",
"==",
"'linear'",
")",
":",
"spec",
".",
"kernel",
".",
"linearKernel",
".",
"MergeFromString",
"(",
"b''",
")",
"# hack to set kernel to an empty type",
"elif",
"(",
"model",
".",
"kernel",
"==",
"'rbf'",
")",
":",
"spec",
".",
"kernel",
".",
"rbfKernel",
".",
"gamma",
"=",
"gamma_value",
"(",
"model",
")",
"elif",
"(",
"model",
".",
"kernel",
"==",
"'poly'",
")",
":",
"spec",
".",
"kernel",
".",
"polyKernel",
".",
"gamma",
"=",
"gamma_value",
"(",
"model",
")",
"spec",
".",
"kernel",
".",
"polyKernel",
".",
"c",
"=",
"model",
".",
"coef0",
"spec",
".",
"kernel",
".",
"polyKernel",
".",
"degree",
"=",
"model",
".",
"degree",
"elif",
"(",
"model",
".",
"kernel",
"==",
"'sigmoid'",
")",
":",
"spec",
".",
"kernel",
".",
"sigmoidKernel",
".",
"gamma",
"=",
"gamma_value",
"(",
"model",
")",
"spec",
".",
"kernel",
".",
"sigmoidKernel",
".",
"c",
"=",
"model",
".",
"coef0",
"else",
":",
"raise",
"ValueError",
"(",
"'Unsupported kernel. The following kernel are supported: linear, RBF, polynomial and sigmoid.'",
")",
"return",
"result"
] | Takes the sklearn SVM model and returns the spec with the protobuf kernel for that model. | [
"Takes",
"the",
"sklearn",
"SVM",
"model",
"and",
"returns",
"the",
"spec",
"with",
"the",
"protobuf",
"kernel",
"for",
"that",
"model",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_svm_common.py#L11-L37 | train |
apple/turicreate | src/unity/python/turicreate/data_structures/sframe_builder.py | SFrameBuilder.append | def append(self, data, segment=0):
"""
Append a single row to an SFrame.
Throws a RuntimeError if one or more column's type is incompatible with
a type appended.
Parameters
----------
data : iterable
An iterable representation of a single row.
segment : int
The segment to write this row. Each segment is numbered
sequentially, starting with 0. Any value in segment 1 will be after
any value in segment 0, and the order of rows in each segment is
preserved as they are added.
"""
# Assume this case refers to an SFrame with a single column
if not hasattr(data, '__iter__'):
data = [data]
self._builder.append(data, segment) | python | def append(self, data, segment=0):
"""
Append a single row to an SFrame.
Throws a RuntimeError if one or more column's type is incompatible with
a type appended.
Parameters
----------
data : iterable
An iterable representation of a single row.
segment : int
The segment to write this row. Each segment is numbered
sequentially, starting with 0. Any value in segment 1 will be after
any value in segment 0, and the order of rows in each segment is
preserved as they are added.
"""
# Assume this case refers to an SFrame with a single column
if not hasattr(data, '__iter__'):
data = [data]
self._builder.append(data, segment) | [
"def",
"append",
"(",
"self",
",",
"data",
",",
"segment",
"=",
"0",
")",
":",
"# Assume this case refers to an SFrame with a single column",
"if",
"not",
"hasattr",
"(",
"data",
",",
"'__iter__'",
")",
":",
"data",
"=",
"[",
"data",
"]",
"self",
".",
"_builder",
".",
"append",
"(",
"data",
",",
"segment",
")"
] | Append a single row to an SFrame.
Throws a RuntimeError if one or more column's type is incompatible with
a type appended.
Parameters
----------
data : iterable
An iterable representation of a single row.
segment : int
The segment to write this row. Each segment is numbered
sequentially, starting with 0. Any value in segment 1 will be after
any value in segment 0, and the order of rows in each segment is
preserved as they are added. | [
"Append",
"a",
"single",
"row",
"to",
"an",
"SFrame",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe_builder.py#L108-L129 | train |
apple/turicreate | src/unity/python/turicreate/data_structures/sframe_builder.py | SFrameBuilder.append_multiple | def append_multiple(self, data, segment=0):
"""
Append multiple rows to an SFrame.
Throws a RuntimeError if one or more column's type is incompatible with
a type appended.
Parameters
----------
data : iterable[iterable]
A collection of multiple iterables, each representing a single row.
segment : int
The segment to write the given rows. Each segment is numbered
sequentially, starting with 0. Any value in segment 1 will be after
any value in segment 0, and the order of rows in each segment is
preserved as they are added.
"""
if not hasattr(data, '__iter__'):
raise TypeError("append_multiple must be passed an iterable object")
tmp_list = []
# Avoid copy in cases that we are passed materialized data that is
# smaller than our block size
if hasattr(data, '__len__'):
if len(data) <= self._block_size:
self._builder.append_multiple(data, segment)
return
for i in data:
tmp_list.append(i)
if len(tmp_list) >= self._block_size:
self._builder.append_multiple(tmp_list, segment)
tmp_list = []
if len(tmp_list) > 0:
self._builder.append_multiple(tmp_list, segment) | python | def append_multiple(self, data, segment=0):
"""
Append multiple rows to an SFrame.
Throws a RuntimeError if one or more column's type is incompatible with
a type appended.
Parameters
----------
data : iterable[iterable]
A collection of multiple iterables, each representing a single row.
segment : int
The segment to write the given rows. Each segment is numbered
sequentially, starting with 0. Any value in segment 1 will be after
any value in segment 0, and the order of rows in each segment is
preserved as they are added.
"""
if not hasattr(data, '__iter__'):
raise TypeError("append_multiple must be passed an iterable object")
tmp_list = []
# Avoid copy in cases that we are passed materialized data that is
# smaller than our block size
if hasattr(data, '__len__'):
if len(data) <= self._block_size:
self._builder.append_multiple(data, segment)
return
for i in data:
tmp_list.append(i)
if len(tmp_list) >= self._block_size:
self._builder.append_multiple(tmp_list, segment)
tmp_list = []
if len(tmp_list) > 0:
self._builder.append_multiple(tmp_list, segment) | [
"def",
"append_multiple",
"(",
"self",
",",
"data",
",",
"segment",
"=",
"0",
")",
":",
"if",
"not",
"hasattr",
"(",
"data",
",",
"'__iter__'",
")",
":",
"raise",
"TypeError",
"(",
"\"append_multiple must be passed an iterable object\"",
")",
"tmp_list",
"=",
"[",
"]",
"# Avoid copy in cases that we are passed materialized data that is",
"# smaller than our block size",
"if",
"hasattr",
"(",
"data",
",",
"'__len__'",
")",
":",
"if",
"len",
"(",
"data",
")",
"<=",
"self",
".",
"_block_size",
":",
"self",
".",
"_builder",
".",
"append_multiple",
"(",
"data",
",",
"segment",
")",
"return",
"for",
"i",
"in",
"data",
":",
"tmp_list",
".",
"append",
"(",
"i",
")",
"if",
"len",
"(",
"tmp_list",
")",
">=",
"self",
".",
"_block_size",
":",
"self",
".",
"_builder",
".",
"append_multiple",
"(",
"tmp_list",
",",
"segment",
")",
"tmp_list",
"=",
"[",
"]",
"if",
"len",
"(",
"tmp_list",
")",
">",
"0",
":",
"self",
".",
"_builder",
".",
"append_multiple",
"(",
"tmp_list",
",",
"segment",
")"
] | Append multiple rows to an SFrame.
Throws a RuntimeError if one or more column's type is incompatible with
a type appended.
Parameters
----------
data : iterable[iterable]
A collection of multiple iterables, each representing a single row.
segment : int
The segment to write the given rows. Each segment is numbered
sequentially, starting with 0. Any value in segment 1 will be after
any value in segment 0, and the order of rows in each segment is
preserved as they are added. | [
"Append",
"multiple",
"rows",
"to",
"an",
"SFrame",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe_builder.py#L131-L166 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/stage.py | InstallTargetClass.update_location | def update_location(self, ps):
"""If <location> is not set, sets it based on the project data."""
loc = ps.get('location')
if not loc:
loc = os.path.join(self.project().get('location'), self.name())
ps = ps.add_raw(["<location>" + loc])
return ps | python | def update_location(self, ps):
"""If <location> is not set, sets it based on the project data."""
loc = ps.get('location')
if not loc:
loc = os.path.join(self.project().get('location'), self.name())
ps = ps.add_raw(["<location>" + loc])
return ps | [
"def",
"update_location",
"(",
"self",
",",
"ps",
")",
":",
"loc",
"=",
"ps",
".",
"get",
"(",
"'location'",
")",
"if",
"not",
"loc",
":",
"loc",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project",
"(",
")",
".",
"get",
"(",
"'location'",
")",
",",
"self",
".",
"name",
"(",
")",
")",
"ps",
"=",
"ps",
".",
"add_raw",
"(",
"[",
"\"<location>\"",
"+",
"loc",
"]",
")",
"return",
"ps"
] | If <location> is not set, sets it based on the project data. | [
"If",
"<location",
">",
"is",
"not",
"set",
"sets",
"it",
"based",
"on",
"the",
"project",
"data",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/stage.py#L41-L49 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/stage.py | InstallTargetClass.targets_to_stage | def targets_to_stage(self, source_targets, ps):
"""Given the list of source targets explicitly passed to 'stage', returns the
list of targets which must be staged."""
result = []
# Traverse the dependencies, if needed.
if ps.get('install-dependencies') == ['on']:
source_targets = self.collect_targets(source_targets)
# Filter the target types, if needed.
included_types = ps.get('install-type')
for r in source_targets:
ty = r.type()
if ty:
# Do not stage searched libs.
if ty != "SEARCHED_LIB":
if included_types:
if self.include_type(ty, included_types):
result.append(r)
else:
result.append(r)
elif not included_types:
# Don't install typeless target if there is an explicit list of
# allowed types.
result.append(r)
return result | python | def targets_to_stage(self, source_targets, ps):
"""Given the list of source targets explicitly passed to 'stage', returns the
list of targets which must be staged."""
result = []
# Traverse the dependencies, if needed.
if ps.get('install-dependencies') == ['on']:
source_targets = self.collect_targets(source_targets)
# Filter the target types, if needed.
included_types = ps.get('install-type')
for r in source_targets:
ty = r.type()
if ty:
# Do not stage searched libs.
if ty != "SEARCHED_LIB":
if included_types:
if self.include_type(ty, included_types):
result.append(r)
else:
result.append(r)
elif not included_types:
# Don't install typeless target if there is an explicit list of
# allowed types.
result.append(r)
return result | [
"def",
"targets_to_stage",
"(",
"self",
",",
"source_targets",
",",
"ps",
")",
":",
"result",
"=",
"[",
"]",
"# Traverse the dependencies, if needed.",
"if",
"ps",
".",
"get",
"(",
"'install-dependencies'",
")",
"==",
"[",
"'on'",
"]",
":",
"source_targets",
"=",
"self",
".",
"collect_targets",
"(",
"source_targets",
")",
"# Filter the target types, if needed.",
"included_types",
"=",
"ps",
".",
"get",
"(",
"'install-type'",
")",
"for",
"r",
"in",
"source_targets",
":",
"ty",
"=",
"r",
".",
"type",
"(",
")",
"if",
"ty",
":",
"# Do not stage searched libs.",
"if",
"ty",
"!=",
"\"SEARCHED_LIB\"",
":",
"if",
"included_types",
":",
"if",
"self",
".",
"include_type",
"(",
"ty",
",",
"included_types",
")",
":",
"result",
".",
"append",
"(",
"r",
")",
"else",
":",
"result",
".",
"append",
"(",
"r",
")",
"elif",
"not",
"included_types",
":",
"# Don't install typeless target if there is an explicit list of",
"# allowed types.",
"result",
".",
"append",
"(",
"r",
")",
"return",
"result"
] | Given the list of source targets explicitly passed to 'stage', returns the
list of targets which must be staged. | [
"Given",
"the",
"list",
"of",
"source",
"targets",
"explicitly",
"passed",
"to",
"stage",
"returns",
"the",
"list",
"of",
"targets",
"which",
"must",
"be",
"staged",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/stage.py#L139-L166 | train |
apple/turicreate | src/unity/python/turicreate/config/__init__.py | init_logger | def init_logger():
"""
Initialize the logging configuration for the turicreate package.
This does not affect the root logging config.
"""
import logging as _logging
import logging.config
# Package level logger
_logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s, %(lineno)s: %(message)s'
},
'brief': {
'format': '[%(levelname)s] %(name)s: %(message)s'
}
},
'handlers': {
'default': {
'class': 'logging.StreamHandler',
'formatter': 'brief'
},
'file': {
'class': 'logging.FileHandler',
'formatter': 'standard',
'filename': _client_log_file,
'encoding': 'UTF-8',
'delay': 'False',
}
},
'loggers': {
_root_package_name: {
'handlers': ['default', 'file'],
'propagate': 'True'
}
}
})
# Set module specific log levels
_logging.getLogger('requests').setLevel(_logging.CRITICAL)
if _i_am_a_lambda_worker():
_logging.getLogger(_root_package_name).setLevel(_logging.WARNING)
else:
_logging.getLogger(_root_package_name).setLevel(_logging.INFO) | python | def init_logger():
"""
Initialize the logging configuration for the turicreate package.
This does not affect the root logging config.
"""
import logging as _logging
import logging.config
# Package level logger
_logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s, %(lineno)s: %(message)s'
},
'brief': {
'format': '[%(levelname)s] %(name)s: %(message)s'
}
},
'handlers': {
'default': {
'class': 'logging.StreamHandler',
'formatter': 'brief'
},
'file': {
'class': 'logging.FileHandler',
'formatter': 'standard',
'filename': _client_log_file,
'encoding': 'UTF-8',
'delay': 'False',
}
},
'loggers': {
_root_package_name: {
'handlers': ['default', 'file'],
'propagate': 'True'
}
}
})
# Set module specific log levels
_logging.getLogger('requests').setLevel(_logging.CRITICAL)
if _i_am_a_lambda_worker():
_logging.getLogger(_root_package_name).setLevel(_logging.WARNING)
else:
_logging.getLogger(_root_package_name).setLevel(_logging.INFO) | [
"def",
"init_logger",
"(",
")",
":",
"import",
"logging",
"as",
"_logging",
"import",
"logging",
".",
"config",
"# Package level logger",
"_logging",
".",
"config",
".",
"dictConfig",
"(",
"{",
"'version'",
":",
"1",
",",
"'disable_existing_loggers'",
":",
"False",
",",
"'formatters'",
":",
"{",
"'standard'",
":",
"{",
"'format'",
":",
"'%(asctime)s [%(levelname)s] %(name)s, %(lineno)s: %(message)s'",
"}",
",",
"'brief'",
":",
"{",
"'format'",
":",
"'[%(levelname)s] %(name)s: %(message)s'",
"}",
"}",
",",
"'handlers'",
":",
"{",
"'default'",
":",
"{",
"'class'",
":",
"'logging.StreamHandler'",
",",
"'formatter'",
":",
"'brief'",
"}",
",",
"'file'",
":",
"{",
"'class'",
":",
"'logging.FileHandler'",
",",
"'formatter'",
":",
"'standard'",
",",
"'filename'",
":",
"_client_log_file",
",",
"'encoding'",
":",
"'UTF-8'",
",",
"'delay'",
":",
"'False'",
",",
"}",
"}",
",",
"'loggers'",
":",
"{",
"_root_package_name",
":",
"{",
"'handlers'",
":",
"[",
"'default'",
",",
"'file'",
"]",
",",
"'propagate'",
":",
"'True'",
"}",
"}",
"}",
")",
"# Set module specific log levels",
"_logging",
".",
"getLogger",
"(",
"'requests'",
")",
".",
"setLevel",
"(",
"_logging",
".",
"CRITICAL",
")",
"if",
"_i_am_a_lambda_worker",
"(",
")",
":",
"_logging",
".",
"getLogger",
"(",
"_root_package_name",
")",
".",
"setLevel",
"(",
"_logging",
".",
"WARNING",
")",
"else",
":",
"_logging",
".",
"getLogger",
"(",
"_root_package_name",
")",
".",
"setLevel",
"(",
"_logging",
".",
"INFO",
")"
] | Initialize the logging configuration for the turicreate package.
This does not affect the root logging config. | [
"Initialize",
"the",
"logging",
"configuration",
"for",
"the",
"turicreate",
"package",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/config/__init__.py#L34-L81 | train |
apple/turicreate | src/unity/python/turicreate/config/__init__.py | get_environment_config | def get_environment_config():
"""
Returns all the Turi Create configuration variables that can only
be set via environment variables.
- *TURI_FILEIO_WRITER_BUFFER_SIZE*: The file write buffer size.
- *TURI_FILEIO_READER_BUFFER_SIZE*: The file read buffer size.
- *OMP_NUM_THREADS*: The maximum number of threads to use for parallel processing.
Returns
-------
Returns a dictionary of {key:value,..}
"""
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
return unity.list_globals(False) | python | def get_environment_config():
"""
Returns all the Turi Create configuration variables that can only
be set via environment variables.
- *TURI_FILEIO_WRITER_BUFFER_SIZE*: The file write buffer size.
- *TURI_FILEIO_READER_BUFFER_SIZE*: The file read buffer size.
- *OMP_NUM_THREADS*: The maximum number of threads to use for parallel processing.
Returns
-------
Returns a dictionary of {key:value,..}
"""
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
return unity.list_globals(False) | [
"def",
"get_environment_config",
"(",
")",
":",
"from",
".",
".",
"_connect",
"import",
"main",
"as",
"_glconnect",
"unity",
"=",
"_glconnect",
".",
"get_unity",
"(",
")",
"return",
"unity",
".",
"list_globals",
"(",
"False",
")"
] | Returns all the Turi Create configuration variables that can only
be set via environment variables.
- *TURI_FILEIO_WRITER_BUFFER_SIZE*: The file write buffer size.
- *TURI_FILEIO_READER_BUFFER_SIZE*: The file read buffer size.
- *OMP_NUM_THREADS*: The maximum number of threads to use for parallel processing.
Returns
-------
Returns a dictionary of {key:value,..} | [
"Returns",
"all",
"the",
"Turi",
"Create",
"configuration",
"variables",
"that",
"can",
"only",
"be",
"set",
"via",
"environment",
"variables",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/config/__init__.py#L145-L160 | train |
apple/turicreate | src/unity/python/turicreate/config/__init__.py | set_log_level | def set_log_level(level):
"""
Sets the log level.
Lower log levels log more.
if level is 8, nothing is logged. If level is 0, everything is logged.
"""
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
return unity.set_log_level(level) | python | def set_log_level(level):
"""
Sets the log level.
Lower log levels log more.
if level is 8, nothing is logged. If level is 0, everything is logged.
"""
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
return unity.set_log_level(level) | [
"def",
"set_log_level",
"(",
"level",
")",
":",
"from",
".",
".",
"_connect",
"import",
"main",
"as",
"_glconnect",
"unity",
"=",
"_glconnect",
".",
"get_unity",
"(",
")",
"return",
"unity",
".",
"set_log_level",
"(",
"level",
")"
] | Sets the log level.
Lower log levels log more.
if level is 8, nothing is logged. If level is 0, everything is logged. | [
"Sets",
"the",
"log",
"level",
".",
"Lower",
"log",
"levels",
"log",
"more",
".",
"if",
"level",
"is",
"8",
"nothing",
"is",
"logged",
".",
"If",
"level",
"is",
"0",
"everything",
"is",
"logged",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/config/__init__.py#L162-L170 | train |
apple/turicreate | src/unity/python/turicreate/config/__init__.py | get_runtime_config | def get_runtime_config():
"""
Returns all the Turi Create configuration variables that can be set
at runtime. See :py:func:`turicreate.config.set_runtime_config()` to set these
values and for documentation on the effect of each variable.
Returns
-------
Returns a dictionary of {key:value,..}
See Also
--------
set_runtime_config
"""
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
return unity.list_globals(True) | python | def get_runtime_config():
"""
Returns all the Turi Create configuration variables that can be set
at runtime. See :py:func:`turicreate.config.set_runtime_config()` to set these
values and for documentation on the effect of each variable.
Returns
-------
Returns a dictionary of {key:value,..}
See Also
--------
set_runtime_config
"""
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
return unity.list_globals(True) | [
"def",
"get_runtime_config",
"(",
")",
":",
"from",
".",
".",
"_connect",
"import",
"main",
"as",
"_glconnect",
"unity",
"=",
"_glconnect",
".",
"get_unity",
"(",
")",
"return",
"unity",
".",
"list_globals",
"(",
"True",
")"
] | Returns all the Turi Create configuration variables that can be set
at runtime. See :py:func:`turicreate.config.set_runtime_config()` to set these
values and for documentation on the effect of each variable.
Returns
-------
Returns a dictionary of {key:value,..}
See Also
--------
set_runtime_config | [
"Returns",
"all",
"the",
"Turi",
"Create",
"configuration",
"variables",
"that",
"can",
"be",
"set",
"at",
"runtime",
".",
"See",
":",
"py",
":",
"func",
":",
"turicreate",
".",
"config",
".",
"set_runtime_config",
"()",
"to",
"set",
"these",
"values",
"and",
"for",
"documentation",
"on",
"the",
"effect",
"of",
"each",
"variable",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/config/__init__.py#L173-L189 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.