text
stringlengths
81
112k
Configures system behavior at runtime. These configuration values are also read from environment variables at program startup if available. See :py:func:`turicreate.config.get_runtime_config()` to get the current values for each variable. Note that defaults may change across versions and the names ...
Load SGraph from text file or previously saved SGraph binary. Parameters ---------- filename : string Location of the file. Can be a local path or a remote URL. format : {'binary', 'snap', 'csv', 'tsv'}, optional Format to of the file to load. - 'binary': native graph format o...
Convert a list of vertices into dataframe. def _vertex_list_to_dataframe(ls, id_column_name): """ Convert a list of vertices into dataframe. """ assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.' cols = reduce(set.union, (set(v.attr.keys()) for v in ls)...
Convert a list of vertices into an SFrame. def _vertex_list_to_sframe(ls, id_column_name): """ Convert a list of vertices into an SFrame. """ sf = SFrame() if type(ls) == list: cols = reduce(set.union, (set(v.attr.keys()) for v in ls)) sf[id_column_name] = [v.vid for v in ls] ...
Convert a list of edges into dataframe. def _edge_list_to_dataframe(ls, src_column_name, dst_column_name): """ Convert a list of edges into dataframe. """ assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.' cols = reduce(set.union, (set(e.attr.keys()) fo...
Convert a list of edges into an SFrame. def _edge_list_to_sframe(ls, src_column_name, dst_column_name): """ Convert a list of edges into an SFrame. """ sf = SFrame() if type(ls) == list: cols = reduce(set.union, (set(v.attr.keys()) for v in ls)) sf[src_column_name] = [e.src_vid for...
Convert dataframe into list of vertices, assuming that vertex ids are stored in _VID_COLUMN. def _dataframe_to_vertex_list(df): """ Convert dataframe into list of vertices, assuming that vertex ids are stored in _VID_COLUMN. """ cols = df.columns if len(cols): assert _VID_COLUMN in cols, "V...
Convert dataframe into list of edges, assuming that source and target ids are stored in _SRC_VID_COLUMN, and _DST_VID_COLUMN respectively. def _dataframe_to_edge_list(df): """ Convert dataframe into list of edges, assuming that source and target ids are stored in _SRC_VID_COLUMN, and _DST_VID_COLUMN respective...
Convert data into a vertex data sframe. Using vid_field to identify the id column. The returned sframe will have id column name '__id'. def _vertex_data_to_sframe(data, vid_field): """ Convert data into a vertex data sframe. Using vid_field to identify the id column. The returned sframe will have id co...
Convert data into an edge data sframe. Using src_field and dst_field to identify the source and target id column. The returned sframe will have id column name '__src_id', '__dst_id' def _edge_data_to_sframe(data, src_field, dst_field): """ Convert data into an edge data sframe. Using src_field and dst_...
get_vertices(self, ids=list(), fields={}, format='sframe') Return a collection of vertices and their attributes. Parameters ---------- ids : list [int | float | str] or SArray List of vertex IDs to retrieve. Only vertices in this list will be returned. Also acce...
get_edges(self, src_ids=list(), dst_ids=list(), fields={}, format='sframe') Return a collection of edges and their attributes. This function is used to find edges by vertex IDs, filter on edge attributes, or list in-out neighbors of vertex sets. Parameters ---------- src...
Add vertices to the SGraph. Vertices should be input as a list of :class:`~turicreate.Vertex` objects, an :class:`~turicreate.SFrame`, or a pandas DataFrame. If vertices are specified by SFrame or DataFrame, ``vid_field`` specifies which column contains the vertex ID. Remaining columns a...
Add edges to the SGraph. Edges should be input as a list of :class:`~turicreate.Edge` objects, an :class:`~turicreate.SFrame`, or a Pandas DataFrame. If the new edges are in an SFrame or DataFrame, then ``src_field`` and ``dst_field`` are required to specify the columns that contain the ...
Return a new SGraph with only the selected fields. Other fields are discarded, while fields that do not exist in the SGraph are ignored. Parameters ---------- fields : string | list [string] A single field name or a list of field names to select. Returns ---...
Apply a transform function to each edge and its associated source and target vertices in parallel. Each edge is visited once and in parallel. Modification to vertex data is protected by lock. The effect on the returned SGraph is equivalent to the following pseudocode: >>> PARALLEL FOR (...
Save the SGraph to disk. If the graph is saved in binary format, the graph can be re-loaded using the :py:func:`load_sgraph` method. Alternatively, the SGraph can be saved in JSON format for a human-readable and portable representation. Parameters ---------- filename : s...
Retrieve the graph neighborhood around a set of vertices, ignoring edge directions. Note that setting radius greater than two often results in a time-consuming query for a very large subgraph. Parameters ---------- ids : list [int | float | str] List of target vertex...
Create a (binary or multi-class) classifier model of type :class:`~turicreate.boosted_trees_classifier.BoostedTreesClassifier` using gradient boosted trees (sometimes known as GBMs). Parameters ---------- dataset : SFrame A training dataset containing feature columns and a target column. ...
Return a classification, for each example in the ``dataset``, using the trained boosted trees model. The output SFrame contains predictions as class labels (0 or 1) and probabilities associated with the the example. Parameters ---------- dataset : SFrame Dataset of n...
Export the model in Core ML format. Parameters ---------- filename: str A valid filename where the model can be saved. Examples -------- >>> model.export_coreml("MyModel.mlmodel") def export_coreml(self, filename): """ Export the model in Core...
Return the value for the queried field. Get the value of a given field. The list of all queryable fields is documented in the beginning of the model class. >>> out = m._get('graph') Parameters ---------- field : string Name of the field to be retrieved. ...
Return a dictionary for the class fields description. Fields should NOT be wrapped by _precomputed_field, if necessary def _describe_fields(cls): """ Return a dictionary for the class fields description. Fields should NOT be wrapped by _precomputed_field, if necessary """ ...
Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of list of tuples) A list of summary sections...
Check if the input is of expected type. Parameters ---------- arg : Input argument. expected_type : A type OR a list of types that the argument is expected to be. arg_name : The name of the variable in the function being used. No name is a...
Converts audio waveform into an array of examples for VGGish. Args: data: np.array of either one dimension (mono) or two dimensions (multi-channel, with the outer dimension representing channels). Each sample is generally expected to lie in the range [-1.0, +1.0], although this is not required....
Convenience wrapper around waveform_to_examples() for a common WAV format. Args: wav_file: String path to a file, or a file-like object. The file is assumed to contain WAV audio data with signed 16-bit PCM samples. Returns: See waveform_to_examples. def wavfile_to_examples(wav_file): """Convenience...
Expand the given build request by combining all property_sets which don't specify conflicting non-free features. def expand_no_defaults (property_sets): """ Expand the given build request by combining all property_sets which don't specify conflicting non-free features. """ assert is_iterabl...
Return the cross-product of all elements of property_sets, less any that would contain conflicting values for single-valued features. def __x_product (property_sets): """ Return the cross-product of all elements of property_sets, less any that would contain conflicting values for single-valued feat...
Returns non-conflicting combinations of property sets. property_sets is a list of PropertySet instances. seen_features is a set of Property instances. Returns a tuple of: - list of lists of Property instances, such that within each list, no two Property instance have the same feature, and no Prope...
Returns true if 'v' is either implicit value, or the part before the first '-' symbol is implicit value. def looks_like_implicit_value(v): """Returns true if 'v' is either implicit value, or the part before the first '-' symbol is implicit value.""" assert isinstance(v, basestring) if feature.is_im...
Takes the command line tokens (such as taken from ARGV rule) and constructs build request from it. Returns a list of two lists. First is the set of targets specified in the command line, and second is the set of requested build properties. def from_command_line(command_line): """Takes the command line ...
Format a human-readable error message from a regex def regex_to_error_msg(regex): """Format a human-readable error message from a regex""" return re.sub('([^\\\\])[()]', '\\1', regex) \ .replace('[ \t]*$', '') \ .replace('^', '') \ .replace('$', '') \ .replace('[ \t]*', ' ') \ ...
Generate random characters def random_chars(number): """Generate random characters""" char_map = { k: v for k, v in chars.CHARS.iteritems() if not format_character(k).startswith('\\x') } char_num = sum(char_map.values()) return ( format_character(nth_char(char_map, random.r...
Enumerate the templates found in path def templates_in(path): """Enumerate the templates found in path""" ext = '.cpp' return ( Template(f[0:-len(ext)], load_file(os.path.join(path, f))) for f in os.listdir(path) if f.endswith(ext) )
Returns the nth character of a character->occurrence map def nth_char(char_map, index): """Returns the nth character of a character->occurrence map""" for char in char_map: if index < char_map[char]: return char index = index - char_map[char] return None
Returns the C-formatting of the character def format_character(char): """Returns the C-formatting of the character""" if \ char in string.ascii_letters \ or char in string.digits \ or char in [ '_', '.', ':', ';', ' ', '!', '?', '+', '-', '/', '=', '<', '...
Create the file with the given content def write_file(filename, content): """Create the file with the given content""" print 'Generating {0}'.format(filename) with open(filename, 'wb') as out_f: out_f.write(content)
Determine the output filename def out_filename(template, n_val, mode): """Determine the output filename""" return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier)
The main function of the script def main(): """The main function of the script""" desc = 'Generate files to benchmark' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src_dir', default='src', help='The directory containing the templ...
Convert a BOOST_METAPARSE_STRING mode document into one with this mode def convert_from(self, base): """Convert a BOOST_METAPARSE_STRING mode document into one with this mode""" if self.identifier == 'bmp': return base elif self.identifier == 'man': resul...
Instantiates the template def instantiate(self, value_of_n): """Instantiates the template""" template = Cheetah.Template.Template( self.content, searchList={'n': value_of_n} ) template.random_string = random_string return str(template)
Returns the range for N def range(self): """Returns the range for N""" match = self._match(in_comment( 'n[ \t]+in[ \t]*\\[([0-9]+)\\.\\.([0-9]+)\\),[ \t]+' 'step[ \t]+([0-9]+)' )) return range( int(match.group(1)), int(match.group(2)), ...
Find the first line matching regex and return the match object def _match(self, regex): """Find the first line matching regex and return the match object""" cregex = re.compile(regex) for line in self.content.splitlines(): match = cregex.match(line) if match: ...
Add a protobuf spec or :py:class:`models.MLModel` instance to the pipeline. All input features of this model must either match the input_features of the pipeline, or match the outputs of a previous model. Parameters ---------- spec: [MLModel, Model_pb2] A protobuf s...
Gets the version from google/protobuf/__init__.py Do not import google.protobuf.__init__ directly, because an installed protobuf library may be loaded instead. def GetVersion(): """Gets the version from google/protobuf/__init__.py Do not import google.protobuf.__init__ directly, because an installed protob...
Invokes the Protocol Compiler to generate a _pb2.py from the given .proto file. Does nothing if the output already exists and is newer than the input. def generate_proto(source, require = True): """Invokes the Protocol Compiler to generate a _pb2.py from the given .proto file. Does nothing if the output alre...
Validate a row label column. Parameters ---------- label : str Name of the row label column. column_type_map : dict[str, type] Dictionary mapping the name of each column in an SFrame to the type of the values in the column. def _validate_row_label(label, column_type_map): ...
Generate a new column name that is guaranteed not to conflict with an existing set of column names. Parameters ---------- base_name : str The base of the new column name. Usually this does not conflict with the existing column names, in which case this function simply returns `b...
Utility function for selecting columns of only valid feature types. Parameters ---------- dataset: SFrame The input SFrame containing columns of potential features. features: list[str] List of feature column names. If None, the candidate feature set is taken to be all the colu...
Returns true if all of the elements in the list are equal. def _check_elements_equal(lst): """ Returns true if all of the elements in the list are equal. """ assert isinstance(lst, list), "Input value must be a list." return not lst or lst.count(lst[0]) == len(lst)
For a list-typed SArray, check whether the first elements are lists that - contain only the provided types - all have the same lengths (optionally) Parameters ---------- sa : SArray An SArray containing lists. allowed_types : list A list of types that are allowed in each list. ...
Create a summary string for the accessible fields in a model. Unlike `_toolkit_repr_print`, this function does not look up the values of the fields, it just formats the names and descriptions. Parameters ---------- field_descriptions : dict{str: str} Name of each field and its description, ...
Returns true if datatype_instance is a valid datatype object and false otherwise. def _is_valid_datatype(datatype_instance): """ Returns true if datatype_instance is a valid datatype object and false otherwise. """ # Remap so we can still use the python types for the simple cases global _simple_ty...
Translates a user specified datatype to an instance of the ones defined above. Valid data types are passed through, and the following type specifications are translated to the proper instances: str, "String" -> String() int, "Int64" -> Int64() float, "Double" -> Double() If a data type is not...
Convert a boosted tree model to protobuf format. Parameters ---------- decision_tree : GradientBoostingClassifier A trained scikit-learn tree model. feature_names: [str] Name of the input columns. target: str Name of the output column. Returns ------- model_sp...
Returns all symbols defined in an ast node. if ctx_types is given, then restrict the symbols to ones with that context. :param node: ast node :param ctx_types: type or tuple of types that may be found assigned to the `ctx` attribute of an ast Name node. def get_symbols(nod...
Given a list of objects, reorder them so that the constains specified by 'add_pair' are satisfied. The algorithm was adopted from an awk script by Nikita Youshchenko (yoush at cs dot msu dot su) def order (self, objects): """ Given a list of objects, reorder them so that th...
Eliminate constraints which mention objects not in 'objects'. In graph-theory terms, this is finding subgraph induced by ordered vertices. def __eliminate_unused_constraits (self, objects): """ Eliminate constraints which mention objects not in 'objects'. In graph-theory ter...
Returns true if there's no constraint in 'constraints' where 'obj' comes second. def __has_no_dependents (self, obj, constraints): """ Returns true if there's no constraint in 'constraints' where 'obj' comes second. """ failed = False while constraints and not fa...
Helper for as_path, below. Orders properties with the implicit ones first, and within the two sections in alphabetical order of feature name. def path_order (x, y): """ Helper for as_path, below. Orders properties with the implicit ones first, and within the two sections in alphabetical ord...
Refines 'properties' by overriding any non-free properties for which a different value is specified in 'requirements'. Conditional requirements are just added without modification. Returns the resulting list of properties. def refine (properties, requirements): """ Refines 'properties' by o...
Interpret all path properties in 'properties' as relative to 'path' The property values are assumed to be in system-specific form, and will be translated into normalized form. def translate_paths (properties, path): """ Interpret all path properties in 'properties' as relative to 'path' The...
Assumes that all feature values that start with '@' are names of rules, used in 'context-module'. Such rules can be either local to the module or global. Qualified local rules with the name of the module. def translate_indirect(properties, context_module): """Assumes that all feature values that start ...
Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties. def validate (properties): """ Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties. """ if isinstance(pr...
If 'property' is conditional property, returns condition and the property, e.g <variant>debug,<toolset>gcc:<inlining>full will become <variant>debug,<toolset>gcc <inlining>full. Otherwise, returns empty string. def split_conditional (property): """ If 'property' is conditional prope...
Selects properties which correspond to any of the given features. def select (features, properties): """ Selects properties which correspond to any of the given features. """ assert is_iterable_typed(properties, basestring) result = [] # add any missing angle brackets features = add_grist (fea...
Removes all conditional properties which conditions are not met For those with met conditions, removes the condition. Properies in conditions are looked up in 'context' def evaluate_conditionals_in_context (properties, context): """ Removes all conditional properties which conditions are not met ...
Returns a modified version of properties with all values of the given feature replaced by the given value. If 'value' is None the feature will be removed. def change (properties, feature, value = None): """ Returns a modified version of properties with all values of the given feature replac...
Exit with error if property is not valid. def __validate1 (property): """ Exit with error if property is not valid. """ assert isinstance(property, Property) msg = None if not property.feature.free: feature.validate_value_string (property.feature, property.value)
Returns a property sets which include all the elements in 'properties' that do not have attributes listed in 'attributes'. def remove(attributes, properties): """Returns a property sets which include all the elements in 'properties' that do not have attributes listed in 'attributes'.""" if isinstance(a...
Returns a property set which include all properties in 'properties' that have any of 'attributes'. def take(attributes, properties): """Returns a property set which include all properties in 'properties' that have any of 'attributes'.""" assert is_iterable_typed(attributes, basestring) assert is_it...
Associate value with properties. def insert (self, properties, value): """ Associate value with properties. """ assert is_iterable_typed(properties, basestring) assert isinstance(value, basestring) self.__properties.append(properties) self.__values.append(value)
Benchmark one command execution def benchmark_command(cmd, progress): """Benchmark one command execution""" full_cmd = '/usr/bin/time --format="%U %M" {0}'.format(cmd) print '{0:6.2f}% Running {1}'.format(100.0 * progress, full_cmd) (_, err) = subprocess.Popen( ['/bin/sh', '-c', full_cmd], ...
Benchmark one file def benchmark_file( filename, compiler, include_dirs, (progress_from, progress_to), iter_count, extra_flags = ''): """Benchmark one file""" time_sum = 0 mem_sum = 0 for nth_run in xrange(0, iter_count): (time_spent, mem_used) = benchmark_command( '...
Determine the name + version of the compiler def compiler_info(compiler): """Determine the name + version of the compiler""" (out, err) = subprocess.Popen( ['/bin/sh', '-c', '{0} -v'.format(compiler)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ).c...
Enumartes the files in path with the given extension def files_in_dir(path, extension): """Enumartes the files in path with the given extension""" ends = '.{0}'.format(extension) return (f for f in os.listdir(path) if f.endswith(ends))
Format a duration def format_time(seconds): """Format a duration""" minute = 60 hour = minute * 60 day = hour * 24 week = day * 7 result = [] for name, dur in [ ('week', week), ('day', day), ('hour', hour), ('minute', minute), ('second', 1) ]: if seconds...
Do the benchmarking def benchmark(src_dir, compiler, include_dirs, iter_count): """Do the benchmarking""" files = list(files_in_dir(src_dir, 'cpp')) random.shuffle(files) has_string_templates = True string_template_file_cnt = sum(1 for file in files if 'bmp' in file) file_count = len(files) + ...
Plot a diagram def plot(values, mode_names, title, (xlabel, ylabel), out_file): """Plot a diagram""" matplotlib.pyplot.clf() for mode, mode_name in mode_names.iteritems(): vals = values[mode] matplotlib.pyplot.plot( [x for x, _ in vals], [y for _, y in vals], ...
Enumerate all configs in src_dir def configs_in(src_dir): """Enumerate all configs in src_dir""" for filename in files_in_dir(src_dir, 'json'): with open(os.path.join(src_dir, filename), 'rb') as in_f: yield json.load(in_f)
Join the list of images into the out file def join_images(img_files, out_file): """Join the list of images into the out file""" images = [PIL.Image.open(f) for f in img_files] joined = PIL.Image.new( 'RGB', (sum(i.size[0] for i in images), max(i.size[1] for i in images)) ) left = 0 ...
Plot temporary diagrams def plot_temp_diagrams(config, results, temp_dir): """Plot temporary diagrams""" display_name = { 'time': 'Compilation time (s)', 'memory': 'Compiler memory usage (MB)', } files = config['files'] img_files = [] if any('slt' in result for result in resul...
Plot one diagram def plot_diagram(config, results, images_dir, out_filename): """Plot one diagram""" img_files = plot_temp_diagrams(config, results, images_dir) join_images(img_files, out_filename) for img_file in img_files: os.remove(img_file)
Plot all diagrams specified by the configs def plot_diagrams(results, configs, compiler, out_dir): """Plot all diagrams specified by the configs""" compiler_fn = make_filename(compiler) total = psutil.virtual_memory().total # pylint:disable=I0011,E1101 memory = int(math.ceil(byte_to_gb(total))) i...
The main function of the script def main(): """The main function of the script""" desc = 'Benchmark the files generated by generate.py' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src_dir', default='generated', help='The directo...
Load any Turi Create model that was previously saved. This function assumes the model (can be any model) was previously saved in Turi Create model format with model.save(filename). Parameters ---------- location : string Location of the model to load. Can be a local path or a remote URL. ...
Internal function to return a get_default_options function. Parameters ---------- unity_server_model_name: str Name of the class/toolkit as registered with the unity server module_name: str, optional Name of the module. python_class_name: str, optional Name of the Python c...
Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'. def reset (): """ Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'. """ global ...
The rule for checking toolset parameters. Trailing parameters should all be parameter name/value pairs. The rule will check that each parameter either has a value in each invocation or has no value in each invocation. Also, the rule will check that the combination of all parameter values is uniq...
A helper rule to get the command to invoke some tool. If 'user-provided-command' is not given, tries to find binary named 'tool' in PATH and in the passed 'additional-path'. Otherwise, verifies that the first element of 'user-provided-command' is an existing program. This rule returns t...
Same as get_invocation_command_nodefault, except that if no tool is found, returns either the user-provided-command, if present, or the 'tool' parameter. def get_invocation_command(toolset, tool, user_provided_command = [], additional_paths = [], path_last = False): """ Same as g...
Given an invocation command, return the absolute path to the command. This works even if commnad has not path element and is present in PATH. def get_absolute_tool_path(command): """ Given an invocation command, return the absolute path to the command. This works even if commnad ...
Attempts to find tool (binary) named 'name' in PATH and in 'additional-paths'. If found in path, returns 'name'. If found in additional paths, returns full name. If the tool is found in several directories, returns the first path found. Otherwise, returns the empty string. If 'path_l...
Checks if 'command' can be found either in path or is a full name to an existing file. def check_tool_aux(command): """ Checks if 'command' can be found either in path or is a full name to an existing file. """ assert isinstance(command, basestring) dirname = os.path.dirname(command) ...
Checks that a tool can be invoked by 'command'. If command is not an absolute path, checks if it can be found in 'path'. If comand is absolute path, check that it exists. Returns 'command' if ok and empty string otherwise. def check_tool(command): """ Checks that a tool can be invoked by 'c...
Handle common options for toolset, specifically sets the following flag variables: - CONFIG_COMMAND to 'command' - OPTIOns for compile to the value of <compileflags> in options - OPTIONS for compile.c to the value of <cflags> in options - OPTIONS for compile.c++ to the value of <...
returns the location of the "program files" directory on a windows platform def get_program_files_dir(): """ returns the location of the "program files" directory on a windows platform """ ProgramFiles = bjam.variable("ProgramFiles") if ProgramFiles: ProgramFiles = ' '.join(Prog...
Returns the command needed to set an environment variable on the current platform. The variable setting persists through all following commands and is visible in the environment seen by subsequently executed commands. In other words, on Unix systems, the variable is exported, which is consistent...
Returns a command to sets a named shell path variable to the given NATIVE paths on the current platform. def path_variable_setting_command(variable, paths): """ Returns a command to sets a named shell path variable to the given NATIVE paths on the current platform. """ assert isinst...