Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def merge_in_place(self, others): new_model_names = [] for predictor in others: for model in predictor.class1_pan_allele_models: model_name = self.model_name( "pan-class1", len(self...
[ "\n Add the models present other predictors into the current predictor.\n\n Parameters\n ----------\n others : list of Class1AffinityPredictor\n Other predictors to merge into the current predictor.\n\n Returns\n -------\n list of string : names of newly a...
Please provide a description of the function:def supported_alleles(self): if 'supported_alleles' not in self._cache: result = set(self.allele_to_allele_specific_models) if self.allele_to_fixed_length_sequence: result = result.union(self.allele_to_fixed_length_seq...
[ "\n Alleles for which predictions can be made.\n \n Returns\n -------\n list of string\n " ]
Please provide a description of the function:def supported_peptide_lengths(self): if 'supported_peptide_lengths' not in self._cache: length_ranges = set( network.supported_peptide_lengths for network in self.neural_networks) result = ( ...
[ "\n (minimum, maximum) lengths of peptides supported by *all models*,\n inclusive.\n\n Returns\n -------\n (int, int) tuple\n\n " ]
Please provide a description of the function:def save(self, models_dir, model_names_to_write=None, write_metadata=True): num_models = len(self.class1_pan_allele_models) + sum( len(v) for v in self.allele_to_allele_specific_models.values()) assert len(self.manifest_df) == num_models,...
[ "\n Serialize the predictor to a directory on disk. If the directory does\n not exist it will be created.\n \n The serialization format consists of a file called \"manifest.csv\" with\n the configurations of each Class1NeuralNetwork, along with per-network\n files giving th...
Please provide a description of the function:def load(models_dir=None, max_models=None): if models_dir is None: models_dir = get_default_class1_models_dir() manifest_path = join(models_dir, "manifest.csv") manifest_df = pandas.read_csv(manifest_path, nrows=max_models) ...
[ "\n Deserialize a predictor from a directory on disk.\n \n Parameters\n ----------\n models_dir : string\n Path to directory\n \n max_models : int, optional\n Maximum number of `Class1NeuralNetwork` instances to load\n\n Returns\n ...
Please provide a description of the function:def model_name(allele, num): random_string = hashlib.sha1( str(time.time()).encode()).hexdigest()[:16] return "%s-%d-%s" % (allele.upper(), num, random_string)
[ "\n Generate a model name\n \n Parameters\n ----------\n allele : string\n num : int\n\n Returns\n -------\n string\n\n " ]
Please provide a description of the function:def fit_allele_specific_predictors( self, n_models, architecture_hyperparameters_list, allele, peptides, affinities, inequalities=None, train_rounds=None, models_dir_f...
[ "\n Fit one or more allele specific predictors for a single allele using one\n or more neural network architectures.\n \n The new predictors are saved in the Class1AffinityPredictor instance\n and will be used on subsequent calls to `predict`.\n \n Parameters\n ...
Please provide a description of the function:def fit_class1_pan_allele_models( self, n_models, architecture_hyperparameters, alleles, peptides, affinities, inequalities, models_dir_for_save=None, verbose=1, ...
[ "\n Fit one or more pan-allele predictors using a single neural network\n architecture.\n \n The new predictors are saved in the Class1AffinityPredictor instance\n and will be used on subsequent calls to `predict`.\n \n Parameters\n ----------\n n_model...
Please provide a description of the function:def percentile_ranks(self, affinities, allele=None, alleles=None, throw=True): if allele is not None: try: transform = self.allele_to_percent_rank_transform[allele] return transform.transform(affinities) ...
[ "\n Return percentile ranks for the given ic50 affinities and alleles.\n\n The 'allele' and 'alleles' argument are as in the `predict` method.\n Specify one of these.\n\n Parameters\n ----------\n affinities : sequence of float\n nM affinities\n allele : s...
Please provide a description of the function:def predict( self, peptides, alleles=None, allele=None, throw=True, centrality_measure=DEFAULT_CENTRALITY_MEASURE): df = self.predict_to_dataframe( peptides=peptides, ...
[ "\n Predict nM binding affinities.\n \n If multiple predictors are available for an allele, the predictions are\n the geometric means of the individual model predictions.\n \n One of 'allele' or 'alleles' must be specified. If 'allele' is specified\n all predictions ...
Please provide a description of the function:def predict_to_dataframe( self, peptides, alleles=None, allele=None, throw=True, include_individual_model_predictions=False, include_percentile_ranks=True, include_confidence_inte...
[ "\n Predict nM binding affinities. Gives more detailed output than `predict`\n method, including 5-95% prediction intervals.\n \n If multiple predictors are available for an allele, the predictions are\n the geometric means of the individual model predictions.\n \n O...
Please provide a description of the function:def save_weights(weights_list, filename): numpy.savez( filename, **dict((("array_%d" % i), w) for (i, w) in enumerate(weights_list)))
[ "\n Save the model weights to the given filename using numpy's \".npz\"\n format.\n \n Parameters\n ----------\n weights_list : list of array\n \n filename : string\n Should end in \".npz\".\n \n " ]
Please provide a description of the function:def load_weights(filename): loaded = numpy.load(filename) weights = [ loaded["array_%d" % i] for i in range(len(loaded.keys())) ] loaded.close() return weights
[ "\n Restore model weights from the given filename, which should have been\n created with `save_weights`.\n \n Parameters\n ----------\n filename : string\n Should end in \".npz\".\n\n Returns\n ----------\n list of array\n " ]
Please provide a description of the function:def calibrate_percentile_ranks( self, peptides=None, num_peptides_per_length=int(1e5), alleles=None, bins=None): if bins is None: bins = to_ic50(numpy.linspace(1, 0, 1000)) if a...
[ "\n Compute the cumulative distribution of ic50 values for a set of alleles\n over a large universe of random peptides, to enable computing quantiles in\n this distribution later.\n\n Parameters\n ----------\n peptides : sequence of string or EncodableSequences, optional\n ...
Please provide a description of the function:def filter_networks(self, predicate): allele_to_allele_specific_models = {} for (allele, models) in self.allele_to_allele_specific_models.items(): allele_to_allele_specific_models[allele] = [ m for m in models if predicate...
[ "\n Return a new Class1AffinityPredictor containing a subset of this\n predictor's neural networks.\n\n Parameters\n ----------\n predicate : Class1NeuralNetwork -> boolean\n Function specifying which neural networks to include\n\n Returns\n -------\n ...
Please provide a description of the function:def model_select( self, score_function, alleles=None, min_models=1, max_models=10000): if alleles is None: alleles = self.supported_alleles dfs = [] allele_to_allele_sp...
[ "\n Perform model selection using a user-specified scoring function.\n\n Model selection is done using a \"step up\" variable selection procedure,\n in which models are repeatedly added to an ensemble until the score\n stops improving.\n\n Parameters\n ----------\n s...
Please provide a description of the function:def fit(self, values, bins): assert self.cdf is None assert self.bin_edges is None assert len(values) > 0 (hist, self.bin_edges) = numpy.histogram(values, bins=bins) self.cdf = numpy.ones(len(hist) + 3) * numpy.nan sel...
[ "\n Fit the transform using the given values (in our case ic50s).\n\n Parameters\n ----------\n values : ic50 values\n bins : bins for the cumulative distribution function\n Anything that can be passed to numpy.histogram's \"bins\" argument\n can be used here...
Please provide a description of the function:def transform(self, values): assert self.cdf is not None assert self.bin_edges is not None indices = numpy.searchsorted(self.bin_edges, values) result = self.cdf[indices] assert len(result) == len(values) return numpy....
[ "\n Return percent ranks (range [0, 100]) for the given values.\n " ]
Please provide a description of the function:def to_series(self): return pandas.Series( self.cdf, index=[numpy.nan] + list(self.bin_edges) + [numpy.nan])
[ "\n Serialize the fit to a pandas.Series.\n\n The index on the series gives the bin edges and the valeus give the CDF.\n\n Returns\n -------\n pandas.Series\n\n " ]
Please provide a description of the function:def from_series(series): result = PercentRankTransform() result.cdf = series.values result.bin_edges = series.index.values[1:-1] return result
[ "\n Deseralize a PercentRankTransform the given pandas.Series, as returned\n by `to_series()`.\n\n Parameters\n ----------\n series : pandas.Series\n\n Returns\n -------\n PercentRankTransform\n\n " ]
Please provide a description of the function:def get_default_class1_models_dir(test_exists=True): if _MHCFLURRY_DEFAULT_CLASS1_MODELS_DIR: result = join(get_downloads_dir(), _MHCFLURRY_DEFAULT_CLASS1_MODELS_DIR) if test_exists and not exists(result): raise IOError("No such directory...
[ "\n Return the absolute path to the default class1 models dir.\n\n If environment variable MHCFLURRY_DEFAULT_CLASS1_MODELS is set to an\n absolute path, return that path. If it's set to a relative path (i.e. does\n not start with /) then return that path taken to be relative to the mhcflurry\n downlo...
Please provide a description of the function:def get_current_release_downloads(): downloads = ( get_downloads_metadata() ['releases'] [get_current_release()] ['downloads']) return OrderedDict( (download["name"], { 'downloaded': exists(join(get_downloads_d...
[ "\n Return a dict of all available downloads in the current release.\n\n The dict keys are the names of the downloads. The values are a dict\n with two entries:\n\n downloaded : bool\n Whether the download is currently available locally\n\n metadata : dict\n Info about the download from...
Please provide a description of the function:def get_path(download_name, filename='', test_exists=True): assert '/' not in download_name, "Invalid download: %s" % download_name path = join(get_downloads_dir(), download_name, filename) if test_exists and not exists(path): raise RuntimeError( ...
[ "\n Get the local path to a file in a MHCflurry download\n\n Parameters\n -----------\n download_name : string\n\n filename : string\n Relative path within the download to the file of interest\n\n test_exists : boolean\n If True (default) throw an error telling the user how to downlo...
Please provide a description of the function:def configure(): global _DOWNLOADS_DIR global _CURRENT_RELEASE _CURRENT_RELEASE = None _DOWNLOADS_DIR = environ.get("MHCFLURRY_DOWNLOADS_DIR") if not _DOWNLOADS_DIR: metadata = get_downloads_metadata() _CURRENT_RELEASE = environ.get(...
[ "\n Setup various global variables based on environment variables.\n " ]
Please provide a description of the function:def make_worker_pool( processes=None, initializer=None, initializer_kwargs_per_process=None, max_tasks_per_worker=None): if not processes: processes = cpu_count() pool_kwargs = { 'processes': processes, } ...
[ "\n Convenience wrapper to create a multiprocessing.Pool.\n\n This function adds support for per-worker initializer arguments, which are\n not natively supported by the multiprocessing module. The motivation for\n this feature is to support allocating each worker to a (different) GPU.\n\n IMPLEMENTAT...
Please provide a description of the function:def from_ic50(ic50, max_ic50=50000.0): x = 1.0 - (numpy.log(ic50) / numpy.log(max_ic50)) return numpy.minimum( 1.0, numpy.maximum(0.0, x))
[ "\n Convert ic50s to regression targets in the range [0.0, 1.0].\n \n Parameters\n ----------\n ic50 : numpy.array of float\n\n Returns\n -------\n numpy.array of float\n\n " ]
Please provide a description of the function:def calibrate_percentile_ranks(allele, predictor, peptides=None): global GLOBAL_DATA if peptides is None: peptides = GLOBAL_DATA["calibration_peptides"] predictor.calibrate_percentile_ranks( peptides=peptides, alleles=[allele]) re...
[ "\n Private helper function.\n " ]
Please provide a description of the function:def set_keras_backend(backend=None, gpu_device_nums=None, num_threads=None): os.environ["KERAS_BACKEND"] = "tensorflow" original_backend = backend if not backend: backend = "tensorflow-default" if gpu_device_nums is not None: os.enviro...
[ "\n Configure Keras backend to use GPU or CPU. Only tensorflow is supported.\n\n Parameters\n ----------\n backend : string, optional\n one of 'tensorflow-default', 'tensorflow-cpu', 'tensorflow-gpu'\n\n gpu_device_nums : list of int, optional\n GPU devices to potentially use\n\n num...
Please provide a description of the function:def amino_acid_distribution(peptides, smoothing=0.0): peptides = pandas.Series(peptides) aa_counts = pandas.Series(peptides.map(collections.Counter).sum()) normalized = aa_counts / aa_counts.sum() if smoothing: normalized += smoothing nor...
[ "\n Compute the fraction of each amino acid across a collection of peptides.\n \n Parameters\n ----------\n peptides : list of string\n smoothing : float, optional\n Small number (e.g. 0.01) to add to all amino acid fractions. The higher\n the number the more uniform the distribution...
Please provide a description of the function:def random_peptides(num, length=9, distribution=None): if num == 0: return [] if distribution is None: distribution = pandas.Series( 1, index=sorted(amino_acid.COMMON_AMINO_ACIDS)) distribution /= distribution.sum() retur...
[ "\n Generate random peptides (kmers).\n\n Parameters\n ----------\n num : int\n Number of peptides to return\n\n length : int\n Length of each peptide\n\n distribution : pandas.Series\n Maps 1-letter amino acid abbreviations to\n probabilities. If not specified a unifor...
Please provide a description of the function:def uproot(tree): uprooted = tree.copy() uprooted.parent = None for child in tree.all_children(): uprooted.add_general_child(child) return uprooted
[ "\n Take a subranch of a tree and deep-copy the children\n of this subbranch into a new LabeledTree\n " ]
Please provide a description of the function:def copy(self): return LabeledTree( udepth = self.udepth, depth = self.depth, text = self.text, label = self.label, children = self.children.copy() if self.children != None else [], pare...
[ "\n Deep Copy of a LabeledTree\n " ]
Please provide a description of the function:def add_child(self, child): self.children.append(child) child.parent = self self.udepth = max([child.udepth for child in self.children]) + 1
[ "\n Adds a branch to the current tree.\n " ]
Please provide a description of the function:def lowercase(self): if len(self.children) > 0: for child in self.children: child.lowercase() else: self.text = self.text.lower()
[ "\n Lowercase all strings in this tree.\n Works recursively and in-place.\n " ]
Please provide a description of the function:def to_dict(self, index=0): index += 1 rep = {} rep["index"] = index rep["leaf"] = len(self.children) == 0 rep["depth"] = self.udepth rep["scoreDistr"] = [0.0] * len(LabeledTree.SCORE_MAPPING) # dirac distribut...
[ "\n Dict format for use in Javascript / Jason Chuang's display technology.\n " ]
Please provide a description of the function:def inject_visualization_javascript(tree_width=1200, tree_height=400, tree_node_radius=10): from .javascript import insert_sentiment_markup insert_sentiment_markup(tree_width=tree_width, tree_height=tree_height, tree_node_radius=tree_node_radius)
[ "\n In an Ipython notebook, show SST trees using the same Javascript\n code as used by Jason Chuang's visualisations.\n " ]
Please provide a description of the function:def delete_paths(paths): for path in paths: if exists(path): if isfile(path): remove(path) else: rmtree(path)
[ "\n Delete a list of paths that are files or directories.\n If a file/directory does not exist, skip it.\n\n Arguments:\n ----------\n\n paths : list<str>, names of files/directories to remove.\n\n " ]
Please provide a description of the function:def download_sst(path, url): local_files = { "train": join(path, "train.txt"), "test": join(path, "test.txt"), "dev": join(path, "dev.txt") } makedirs(path, exist_ok=True) if all(exists(fname) and stat(fname).st_size > 100 for fna...
[ "\"\n Download from `url` the zip file corresponding to the\n Stanford Sentiment Treebank and expand the resulting\n files into the directory `path` (Note: if the files are\n already present, the download is not actually run).\n\n Arguments\n ---------\n path : str, directory to save the tr...
Please provide a description of the function:def attribute_text_label(node, current_word): node.text = normalize_string(current_word) node.text = node.text.strip(" ") node.udepth = 1 if len(node.text) > 0 and node.text[0].isdigit(): split_sent = node.text.split(" ", 1) label = split...
[ "\n Tries to recover the label inside a string\n of the form '(3 hello)' where 3 is the label,\n and hello is the string. Label is not assigned\n if the string does not follow the expected\n format.\n\n Arguments:\n ----------\n node : LabeledTree, current node that should\n p...
Please provide a description of the function:def create_tree_from_string(line): depth = 0 current_word = "" root = None current_node = root for char in line: if char == '(': if current_node is not None and len(current_word) > 0: attribute_...
[ "\n Parse and convert a string representation\n of an example into a LabeledTree datastructure.\n\n Arguments:\n ----------\n line : str, string version of the tree.\n\n Returns:\n --------\n LabeledTree : parsed tree.\n " ]
Please provide a description of the function:def import_tree_corpus(path): tree_list = LabeledTreeCorpus() with codecs.open(path, "r", "UTF-8") as f: for line in f: tree_list.append(create_tree_from_string(line)) return tree_list
[ "\n Import a text file of treebank trees.\n\n Arguments:\n ----------\n path : str, filename for tree corpus.\n\n Returns:\n --------\n list<LabeledTree> : loaded examples.\n " ]
Please provide a description of the function:def load_sst(path=None, url='http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip'): if path is None: # find a good temporary path path = os.path.expanduser("~/stanford_sentiment_treebank/") makedirs(path, exist_ok=True) ...
[ "\n Download and read in the Stanford Sentiment Treebank dataset\n into a dictionary with a 'train', 'dev', and 'test' keys. The\n dictionary keys point to lists of LabeledTrees.\n\n Arguments:\n ----------\n path : str, (optional defaults to ~/stanford_sentiment_treebank),\n direct...
Please provide a description of the function:def labels(self): labelings = OrderedDict() for tree in self: for label, line in tree.to_labeled_lines(): labelings[line] = label return labelings
[ "\n Construct a dictionary of string -> labels\n\n Returns:\n --------\n OrderedDict<str, int> : string label pairs.\n " ]
Please provide a description of the function:def to_file(self, path, mode="w"): with open(path, mode=mode) as f: for tree in self: for label, line in tree.to_labeled_lines(): f.write(line + "\n")
[ "\n Save the corpus to a text file in the\n original format.\n\n Arguments:\n ----------\n path : str, where to save the corpus.\n mode : str, how to open the file.\n " ]
Please provide a description of the function:def import_tree_corpus(labels_path, parents_path, texts_path): with codecs.open(labels_path, "r", "UTF-8") as f: label_lines = f.readlines() with codecs.open(parents_path, "r", "UTF-8") as f: parent_lines = f.readlines() with codecs.open(text...
[ "\n Import dataset from the TreeLSTM data generation scrips.\n\n Arguments:\n ----------\n labels_path : str, where are labels are stored (should be in\n data/sst/labels.txt).\n parents_path : str, where the parent relationships are stored\n (should be in data/sst/parent...
Please provide a description of the function:def assign_texts(node, words, next_idx=0): if len(node.children) == 0: node.text = words[next_idx] return next_idx + 1 else: for child in node.children: next_idx = assign_texts(child, words, next_idx) return next_idx
[ "\n Recursively assign the words to nodes by finding and\n assigning strings to the leaves of a tree in left\n to right order.\n " ]
Please provide a description of the function:def read_tree(parents, labels, words): trees = {} root = None for i in range(1, len(parents) + 1): if not i in trees and parents[i - 1] != - 1: idx = i prev = None while True: parent = parents[idx -...
[ "\n Take as input a list of integers for parents\n and labels, along with a list of words, and\n reconstruct a LabeledTree.\n " ]
Please provide a description of the function:def set_initial_status(self, configuration=None): super(CognitiveOpDynModel, self).set_initial_status(configuration) # set node status for node in self.status: self.status[node] = np.random.random_sample() self.initial_st...
[ "\n Override behaviour of methods in class DiffusionModel.\n Overwrites initial status using random real values.\n Generates random node profiles.\n " ]
Please provide a description of the function:def iteration(self, node_status=True): # One iteration changes the opinion of all agents using the following procedure: # - first all agents communicate with institutional information I using a deffuant like rule # - then random pairs of agen...
[ "\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: self.actu...
[ "\n Execute a single model iteration\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def add_node_configuration(self, param_name, node_id, param_value): if param_name not in self.config['nodes']: self.config['nodes'][param_name] = {node_id: param_value} else: self.config['nodes'][param_name][node_id] = param_v...
[ "\n Set a parameter for a given node\n\n :param param_name: parameter identifier (as specified by the chosen model)\n :param node_id: node identifier\n :param param_value: parameter value\n " ]
Please provide a description of the function:def add_node_set_configuration(self, param_name, node_to_value): for nid, val in future.utils.iteritems(node_to_value): self.add_node_configuration(param_name, nid, val)
[ "\n Set Nodes parameter\n\n :param param_name: parameter identifier (as specified by the chosen model)\n :param node_to_value: dictionary mapping each node a parameter value\n " ]
Please provide a description of the function:def add_edge_configuration(self, param_name, edge, param_value): if param_name not in self.config['edges']: self.config['edges'][param_name] = {edge: param_value} else: self.config['edges'][param_name][edge] = param_value
[ "\n Set a parameter for a given edge\n\n :param param_name: parameter identifier (as specified by the chosen model)\n :param edge: edge identifier\n :param param_value: parameter value\n " ]
Please provide a description of the function:def add_edge_set_configuration(self, param_name, edge_to_value): for edge, val in future.utils.iteritems(edge_to_value): self.add_edge_configuration(param_name, edge, val)
[ "\n Set Edges parameter\n\n :param param_name: parameter identifier (as specified by the chosen model)\n :param edge_to_value: dictionary mapping each edge a parameter value\n " ]
Please provide a description of the function:def iteration(self, node_status=True): # One iteration changes the opinion of several voters using the following procedure: # - select randomly one voter (speaker 1) # - select randomly one of its neighbours (speaker 2) # - if the two...
[ "\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def multi_runs(model, execution_number=1, iteration_number=50, infection_sets=None, nprocesses=multiprocessing.cpu_count()): if nprocesses > multiprocessing.cpu_count(): nprocesses = multiprocessing.cpu_count() executions = [] if in...
[ "\n Multiple executions of a given model varying the initial set of infected nodes\n\n :param model: a configured diffusion model\n :param execution_number: number of instantiations\n :param iteration_number: number of iterations per execution\n :param infection_sets: predefined set of infected nodes...
Please provide a description of the function:def __execute(model, iteration_number): iterations = model.iteration_bunch(iteration_number, False) trends = model.build_trends(iterations)[0] del iterations del model return trends
[ "\n Execute a simulation model\n\n :param model: a configured diffusion model\n :param iteration_number: number of iterations\n :return: computed trends\n " ]
Please provide a description of the function:def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: self.actua...
[ "\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def plot(self, ncols=2): grid = gridplot(self.plots, ncols=ncols) return grid
[ "\n :param ncols: Number of grid columns\n :return: a bokeh figure image\n " ]
Please provide a description of the function:def iteration(self, node_status=True): # One iteration changes the opinion of at most q voters using the following procedure: # - select randomly q voters # - compute majority opinion # - if tie all agents take opinion +1 # -...
[ "\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} # streaming if self.stream_execution: ...
[ "\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: self.actua...
[ "\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: if min(ac...
[ "\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} # streaming if self.stream_execution: ...
[ "\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def set_initial_status(self, configuration=None): super(AlgorithmicBiasModel, self).set_initial_status(configuration) # set node status for node in self.status: self.status[node] = np.random.random_sample() self.initial_s...
[ "\n Override behaviour of methods in class DiffusionModel.\n Overwrites initial status using random real values.\n " ]
Please provide a description of the function:def iteration(self, node_status=True): # One iteration changes the opinion of N agent pairs using the following procedure: # - first one agent is selected # - then a second agent is selected based on a probability that decreases with the dist...
[ "\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: self.actu...
[ "\n Execute a single model iteration\n\n :return: Iteration_id, Incremental node status (dictionary node->status)\n " ]
Please provide a description of the function:def names(self): if self.name == self.UNKNOWN_HUMAN_PLAYER: return "", "" if not self.is_ai and " " in self.name: return "", self.name return self.name, ""
[ "\n\t\tReturns the player's name and real name.\n\t\tReturns two empty strings if the player is unknown.\n\t\tAI real name is always an empty string.\n\t\t" ]
Please provide a description of the function:def _getitem(string, depth=0): out = [""] while string: char = string[0] if depth and (char == ',' or char == '}'): return out, string if char == '{': groups_string = _getgroup(string[1:], depth+1) if g...
[ "\n Get an item from the string (where item is up to the next ',' or '}' or the\n end of the string)\n " ]
Please provide a description of the function:def _getgroup(string, depth): out, comma = [], False while string: items, string = _getitem(string, depth) if not string: break out += items if string[0] == '}': if comma: return out, stri...
[ "\n Get a group from the string, where group is a list of all the comma\n separated substrings up to the next '}' char or the brace enclosed substring\n if there is no comma\n " ]
Please provide a description of the function:def filter_noexpand_columns(columns): prefix_len = len(NOEXPAND_PREFIX) noexpand = [c[prefix_len:] for c in columns if c.startswith(NOEXPAND_PREFIX)] other = [c for c in columns if not c.startswith(NOEXPAND_PREFIX)] return other, noexpand
[ "Return columns not containing and containing the noexpand prefix.\n\n Parameters\n ----------\n columns: sequence of str\n A sequence of strings to be split\n\n Returns\n -------\n Two lists, the first containing strings without the noexpand prefix, the\n second containing those that ...
Please provide a description of the function:def read_root(paths, key=None, columns=None, ignore=None, chunksize=None, where=None, flatten=False, *args, **kwargs): if not isinstance(paths, list): paths = [paths] # Use a single file to search for trees and branches, ensuring the key exists for ...
[ "\n Read a ROOT file, or list of ROOT files, into a pandas DataFrame.\n Further *args and *kwargs are passed to root_numpy's root2array.\n If the root file contains a branch matching __index__*, it will become the DataFrame's index.\n\n Parameters\n ----------\n paths: string or list\n The ...
Please provide a description of the function:def to_root(df, path, key='my_ttree', mode='w', store_index=True, *args, **kwargs): if mode == 'a': mode = 'update' elif mode == 'w': mode = 'recreate' else: raise ValueError('Unknown mode: {}. Must be "a" or "w".'.format(mode)) ...
[ "\n Write DataFrame to a ROOT file.\n\n Parameters\n ----------\n path: string\n File path to new ROOT file (will be overwritten)\n key: string\n Name of tree that the DataFrame will be saved as\n mode: string, {'w', 'a'}\n Mode that the file should be opened in (default: 'w')...
Please provide a description of the function:def run(self, symbol: str) -> SecurityDetailsViewModel: from pydatum import Datum svc = self._svc sec_agg = svc.securities.get_aggregate_for_symbol(symbol) model = SecurityDetailsViewModel() model.symbol = sec_agg.security....
[ " Loads the model for security details " ]
Please provide a description of the function:def get_next_occurrence(tx: ScheduledTransaction) -> date: # Reference documentation: # https://github.com/MisterY/gnucash-portfolio/issues/3 # Preparing ref day is an important part before the calculation. # It should be: # a) the last occurrence...
[ " Calculates the next occurrence date for scheduled transaction.\n Mimics the recurrenceNextInstance() function from GnuCash.\n Still not fully complete but handles the main cases I use. " ]
Please provide a description of the function:def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum): assert isinstance(next_date, Datum) assert isinstance(start_date, Datum) # Starting from line 220. tmp_sat = next_date.clone() tmp_sat.add_days(1) tmp_sun = next_da...
[ " Extracted the calculation for when the next_day is Friday " ]
Please provide a description of the function:def get_next_occurrence(self) -> date: result = get_next_occurrence(self.transaction) assert isinstance(result, date) return result
[ " Returns the next occurrence date for transaction " ]
Please provide a description of the function:def get_upcoming(self, count: int) -> List[ScheduledTransaction]: # load all enabled scheduled transactions all_tx = self.query.filter(ScheduledTransaction.enabled == 1).all() # calculate next occurrence date for tx in all_tx: ...
[ " Returns <count> upcoming scheduled transactions " ]
Please provide a description of the function:def get_enabled(self) -> List[ScheduledTransaction]: query = ( self.query .filter(ScheduledTransaction.enabled == True) ) return query.all()
[ " Returns only enabled scheduled transactions " ]
Please provide a description of the function:def get_by_id(self, tx_id: str) -> ScheduledTransaction: return self.query.filter(ScheduledTransaction.guid == tx_id).first()
[ " Fetches a tx by id " ]
Please provide a description of the function:def get_aggregate_by_id(self, tx_id: str) -> ScheduledTxAggregate: tran = self.get_by_id(tx_id) return self.get_aggregate_for(tran)
[ " Creates an aggregate for single entity " ]
Please provide a description of the function:def get_avg_price_stat(self) -> Decimal: avg_price = Decimal(0) price_total = Decimal(0) price_count = 0 for account in self.security.accounts: # Ignore trading accounts. if account.type == AccountType.TRADIN...
[ "\n Calculates the statistical average price for the security,\n by averaging only the prices paid. Very simple first implementation.\n " ]
Please provide a description of the function:def get_avg_price_fifo(self) -> Decimal: balance = self.get_quantity() if not balance: return Decimal(0) paid = Decimal(0) accounts = self.get_holding_accounts() # get unused splits (quantity and total paid) per a...
[ "\n Calculates the average price paid for the security.\n security = Commodity\n Returns Decimal value.\n " ]
Please provide a description of the function:def get_available_splits_for_account(self, account: Account) -> List[Split]: available_splits = [] # get all purchase splits in the account query = ( self.get_splits_query() .filter(Split.account == account) ) ...
[ " Returns all unused splits in the account. Used for the calculation of avg.price.\n The split that has been partially used will have its quantity reduced to available\n quantity only. " ]
Please provide a description of the function:def get_num_shares(self) -> Decimal: from pydatum import Datum today = Datum().today() return self.get_num_shares_on(today)
[ " Returns the number of shares at this time " ]
Please provide a description of the function:def get_num_shares_on(self, on_date: datetime) -> Decimal: total_quantity = Decimal(0) accounts = self.get_holding_accounts() for account in accounts: acct_svc = AccountAggregate(self.book, account) quantity = acct_sv...
[ " Returns the number of shares for security on (and including) the given date. " ]
Please provide a description of the function:def get_last_available_price(self) -> PriceModel: price_db = PriceDbApplication() symbol = SecuritySymbol(self.security.namespace, self.security.mnemonic) result = price_db.get_latest_price(symbol) return result
[ " Finds the last available price for security. Uses PriceDb. " ]
Please provide a description of the function:def get_holding_accounts(self) -> List[Account]: if not self.__holding_accounts: self.__holding_accounts = self.__get_holding_accounts_query().all() return self.__holding_accounts
[ " Returns the (cached) list of holding accounts " ]
Please provide a description of the function:def __get_holding_accounts_query(self): query = ( self.book.session.query(Account) .filter(Account.commodity == self.security) .filter(Account.type != AccountType.trading.value) ) # generic.print_sql(query)...
[ " Returns all holding accounts, except Trading accounts. " ]
Please provide a description of the function:def get_income_accounts(self) -> List[Account]: # trading = self.book.trading_account(self.security) # log(DEBUG, "trading account = %s, %s", trading.fullname, trading.guid) # Example on how to self-link, i.e. parent account, using alias. ...
[ "\n Returns all income accounts for this security.\n Income accounts are accounts not under Trading, expressed in currency, and\n having the same name as the mnemonic.\n They should be under Assets but this requires a recursive SQL query.\n " ]
Please provide a description of the function:def get_income_total(self) -> Decimal: accounts = self.get_income_accounts() # log(DEBUG, "income accounts: %s", accounts) income = Decimal(0) for acct in accounts: income += acct.get_balance() return income
[ " Sum of all income = sum of balances of all income accounts. " ]
Please provide a description of the function:def get_income_in_period(self, start: datetime, end: datetime) -> Decimal: accounts = self.get_income_accounts() income = Decimal(0) for acct in accounts: acc_agg = AccountAggregate(self.book, acct) acc_bal = acc_agg.g...
[ " Returns all income in the given period " ]
Please provide a description of the function:def get_prices(self) -> List[PriceModel]: # return self.security.prices.order_by(Price.date) from pricedb.dal import Price pricedb = PriceDbApplication() repo = pricedb.get_price_repository() query = (repo.query(Price) ...
[ " Returns all available prices for security " ]
Please provide a description of the function:def get_quantity(self) -> Decimal: from pydatum import Datum # Use today's date but reset hour and lower. today = Datum() today.today() today.end_of_day() return self.get_num_shares_on(today.value)
[ "\n Returns the number of shares for the given security.\n It gets the number from all the accounts in the book.\n " ]
Please provide a description of the function:def get_splits_query(self): query = ( self.book.session.query(Split) .join(Account) .filter(Account.type != AccountType.trading.value) .filter(Account.commodity_guid == self.security.guid) ) ret...
[ " Returns the query for all splits for this security " ]
Please provide a description of the function:def get_total_paid_for_remaining_stock(self) -> Decimal: paid = Decimal(0) accounts = self.get_holding_accounts() for acc in accounts: splits = self.get_available_splits_for_account(acc) paid += sum(split.value for sp...
[ " Returns the amount paid only for the remaining stock " ]
Please provide a description of the function:def get_value(self) -> Decimal: quantity = self.get_quantity() price = self.get_last_available_price() if not price: # raise ValueError("no price found for", self.full_symbol) return Decimal(0) value = quantit...
[ " Returns the current value of stocks " ]
Please provide a description of the function:def get_value_in_base_currency(self) -> Decimal: # check if the currency is the base currency. amt_orig = self.get_value() # Security currency sec_cur = self.get_currency() #base_cur = self.book.default_currency cur_sv...
[ " Calculates the value of security holdings in base currency " ]
Please provide a description of the function:def get_return_of_capital(self) -> Decimal: txs: List[Split] = self.get_splits_query().all() roc_tx: List[Split] = [] sum = Decimal(0) for tx in txs: if tx.quantity == Decimal(0) and tx.value != Decimal(0): ...
[ " Fetches and adds all Return-of-Capital amounts.\n These are the cash transactions that do not involve security amounts \n (0 value for shares). " ]
Please provide a description of the function:def accounts(self) -> List[Account]: # use only Assets sub-accounts result = ( [acct for acct in self.security.accounts if acct.fullname.startswith('Assets')] ) return result
[ " Returns the asset accounts in which the security is held " ]