INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Parameters ---------- term_dict: dict {metadataname: [term1, term2, ....], ...} Returns ------- None
def check_topic_model_string_format(term_dict): ''' Parameters ---------- term_dict: dict {metadataname: [term1, term2, ....], ...} Returns ------- None ''' if type(term_dict) != dict: raise TypeError("Argument for term_dict must be a dict, keyed on strings, and contain a li...
Inserts dictionary of meta data terms into object. Parameters ---------- term_dict: dict {metadataname: [term1, term2, ....], ...} Returns ------- self: ScatterChart
def inject_metadata_term_lists(self, term_dict): ''' Inserts dictionary of meta data terms into object. Parameters ---------- term_dict: dict {metadataname: [term1, term2, ....], ...} Returns ------- self: ScatterChart ''' check_topic_mod...
Inject custom x and y coordinates for each term into chart. Parameters ---------- x_coords: array-like positions on x-axis \in [0,1] y_coords: array-like positions on y-axis \in [0,1] rescale_x: lambda list[0,1]: list[0,1], default identity Re...
def inject_coordinates(self, x_coords, y_coords, rescale_x=None, rescale_y=None, original_x=None, original_y=None): ''' Inject custom x and y ...
Inserts a set of descriptions of meta data terms. These will be displayed below the scatter plot when a meta data term is clicked. All keys in the term dict must occur as meta data. Parameters ---------- term_dict: dict {metadataname: str: 'explanation to insert', ...} ...
def inject_metadata_descriptions(self, term_dict): ''' Inserts a set of descriptions of meta data terms. These will be displayed below the scatter plot when a meta data term is clicked. All keys in the term dict must occur as meta data. Parameters ---------- ter...
:param vec: array to jitter :return: array, jittered version of arrays
def _add_jitter(self, vec): """ :param vec: array to jitter :return: array, jittered version of arrays """ if self.scatterchartdata.jitter == 0 or self.scatterchartdata.jitter is None: return vec return vec + np.random.rand(1, len(vec))[0] * self.scatterchartd...
Outdated. MPLD3 drawing. Parameters ---------- category num_top_words_to_annotate words_to_annotate scores transform Returns ------- pd.DataFrame, html of fgure
def draw(self, category, num_top_words_to_annotate=4, words_to_annotate=[], scores=None, transform=percentile_alphabetical): '''Outdated. MPLD3 drawing. Parameters ---------- category num_top_words_to_annotate ...
Parameters ---------- y_i, np.array(int) Arrays of word counts of words occurring in positi ve class y_j, np.array(int) Returns ------- np.array of z-scores
def get_zeta_i_j_given_separate_counts(self, y_i, y_j): ''' Parameters ---------- y_i, np.array(int) Arrays of word counts of words occurring in positi ve class y_j, np.array(int) Returns ------- np.array of z-scores ''' n_i, n_j = y_i.sum(), y_j.sum() delta_i_j = (np.log((y_i + 1) / (1. + n_i...
Parameters ---------- tdm: TermDocMatrix category: str, category name Returns ------- pd.DataFrame(['coef', 'p-val'])
def get_scores_and_p_values(self, tdm, category): ''' Parameters ---------- tdm: TermDocMatrix category: str, category name Returns ------- pd.DataFrame(['coef', 'p-val']) ''' X = tdm._X y = self._make_response_variable_1_or_negative_1(category, tdm) pX = X / X.sum(axis=1) ansX = self._anscom...
>>> a = csr_matrix(np.array([[0, 1, 3, 0, 1, 0], [0, 0, 1, 0, 1, 1]]) >>> delete_columns(a, [1,2]).todense() matrix([[0, 0, 1, 0], [0, 0, 1, 1]]) Parameters ---------- mat : csr_matrix columns_to_delete : list[int] Returns ------- csr_matrix that is stripped of columns ...
def delete_columns(mat, columns_to_delete): ''' >>> a = csr_matrix(np.array([[0, 1, 3, 0, 1, 0], [0, 0, 1, 0, 1, 1]]) >>> delete_columns(a, [1,2]).todense() matrix([[0, 0, 1, 0], [0, 0, 1, 1]]) Parameters ---------- mat : csr_matrix columns_to_delete : list[int] Returns...
Parameters ---------- param last_col_idx : int number of columns
def set_last_col_idx(self, last_col_idx): ''' Parameters ---------- param last_col_idx : int number of columns ''' assert last_col_idx >= self._max_col self._max_col = last_col_idx return self
Parameters ---------- param last_row_idx : int number of rows
def set_last_row_idx(self, last_row_idx): ''' Parameters ---------- param last_row_idx : int number of rows ''' assert last_row_idx >= self._max_row self._max_row = last_row_idx return self
Parameters ---------- doc, Spacy Docs Returns ------- Counter noun chunk -> count
def get_feats(self, doc): ''' Parameters ---------- doc, Spacy Docs Returns ------- Counter noun chunk -> count ''' return Counter([str(c).lower() for c in doc.noun_chunks])
Parameters ---------- nltk_tokenizer : nltk.tokenize.* instance (e.g., nltk.TreebankWordTokenizer()) Returns ------- Doc of tweets Notes ------- Requires NLTK to be installed
def nltk_tokenzier_factory(nltk_tokenizer): ''' Parameters ---------- nltk_tokenizer : nltk.tokenize.* instance (e.g., nltk.TreebankWordTokenizer()) Returns ------- Doc of tweets Notes ------- Requires NLTK to be installed ''' def tokenize(text): toks = [] for tok in nltk_tokenizer.tokenize(text): ...
Specifies fixed set of embeddings :param embeddings: array-like, sparse or dense, shape should be (embedding size, # terms) :return: EmbeddingsResolver
def set_embeddings(self, embeddings): ''' Specifies fixed set of embeddings :param embeddings: array-like, sparse or dense, shape should be (embedding size, # terms) :return: EmbeddingsResolver ''' if self.embeddings_ is not None: raise Exception("You have alr...
:param projection_model: sklearn unsupervised model (e.g., PCA) by default the recommended model is umap.UMAP, which requires UMAP in to be installed :return: array, shape (num dimension, vocab size)
def project(self, projection_model=None): ''' :param projection_model: sklearn unsupervised model (e.g., PCA) by default the recommended model is umap.UMAP, which requires UMAP in to be installed :return: array, shape (num dimension, vocab size) ''' if self.embeddings_ i...
Parameters ---------- terms : list or None If terms is list, make these the seed terms for the topoics If none, use the first 30 terms in get_scaled_f_scores_vs_background num_terms_per_topic : int, default 10 Use this many terms per topic scorer : TermScorer Implements get_scores, default is RankDi...
def get_topics_from_terms(self, terms=None, num_terms_per_topic=10, scorer=RankDifference()): ''' Parameters ---------- terms : list or None If terms is list, make these the seed terms for the topoics If none, use the first 3...
Returns ------- pd.DataFrame
def get_ranks(self): ''' Returns ------- pd.DataFrame ''' if self._use_non_text_features: return self._term_doc_matrix.get_metadata_freq_df() else: return self._term_doc_matrix.get_term_freq_df()
Generate a TermDocMatrix from data in parameters. Returns ---------- term_doc_matrix : TermDocMatrix The object that this factory class builds.
def build(self): """Generate a TermDocMatrix from data in parameters. Returns ---------- term_doc_matrix : TermDocMatrix The object that this factory class builds. """ if self._category_text_iter is None: raise CategoryTextIterNotSetError() ...
Entity types to exclude from feature construction. Terms matching specificed entities, instead of labeled by their lower case orthographic form or lemma, will be labeled by their entity type. Parameters ---------- entity_types : set of entity types outputted by spaCy '...
def censor_entity_types(self, entity_types): # type: (set) -> TermDocMatrixFactory ''' Entity types to exclude from feature construction. Terms matching specificed entities, instead of labeled by their lower case orthographic form or lemma, will be labeled by their entity type. ...
Parameters ---------- category_doc_iter : iterator of (string category name, spacy.tokens.doc.Doc) pairs Returns ---------- t : TermDocMatrix
def _build_from_category_spacy_doc_iter(self, category_doc_iter): ''' Parameters ---------- category_doc_iter : iterator of (string category name, spacy.tokens.doc.Doc) pairs Returns ---------- t : TermDocMatrix ''' term_idx_store = IndexStore() ...
Parameters ---------- num_terms, int Returns ------- dict
def get_lexicons(self, num_terms=10): ''' Parameters ---------- num_terms, int Returns ------- dict ''' return {k: v.index[:num_terms] for k, v in self.lexicons.items()}
Parameters ---------- raw_text, uncleaned text for parsing out features Returns ------- csr_matrix, feature matrix
def feats_from_doc(self, raw_text): ''' Parameters ---------- raw_text, uncleaned text for parsing out features Returns ------- csr_matrix, feature matrix ''' parsed_text = self._nlp(self._clean_function(raw_text)) X_factory = CSRMatrixFac...
Parameters ---------- term_doc_matrix : TermDocMatrix Term document matrix object to compact Returns ------- TermDocMatrix
def compact(self, term_doc_matrix): ''' Parameters ---------- term_doc_matrix : TermDocMatrix Term document matrix object to compact Returns ------- TermDocMatrix ''' rank_df = self.scorer.get_rank_df(term_doc_matrix) return s...
Parameters ---------- doc, Spacy Docs Returns ------- Counter (unigram, bigram) -> count
def get_feats(self, doc): ''' Parameters ---------- doc, Spacy Docs Returns ------- Counter (unigram, bigram) -> count ''' ngram_counter = Counter() for sent in doc.sents: ngrams = self.phrases[str(sent)] for subphrases in self.phrases[1:]: ngrams = subphrases[str(sent)] for ngram in n...
Parameters ---------- corpus: Corpus for phrase augmentation Returns ------- New ParsedCorpus containing unigrams in corpus and new phrases
def add_phrases(self, corpus): ''' Parameters ---------- corpus: Corpus for phrase augmentation Returns ------- New ParsedCorpus containing unigrams in corpus and new phrases ''' from gensim.models import Phrases assert isinstance(corpus, ParsedCorpus) self.phrases = [Phrases(CorpusAdapterForGen...
Parameters ---------- epochs : int Number of epochs to train for. Default is 2000. training_iterations : int Number of times to repeat training process. Default is training_iterations. Returns ------- A trained word2vec model.
def train(self, epochs=2000, training_iterations=5): ''' Parameters ---------- epochs : int Number of epochs to train for. Default is 2000. training_iterations : int Number of times to repeat training process. Default is training_iterations. Returns ------- A trained word2vec model. ''' se...
Trains passive aggressive classifier
def passive_aggressive_train(self): '''Trains passive aggressive classifier ''' self._clf = PassiveAggressiveClassifier(n_iter=50, C=0.2, n_jobs=-1, random_state=0) self._clf.fit(self._term_doc_matrix._X, self._term_doc_matrix._y) y_dist = self._clf.decision_function(self._term_doc_matrix._X) pos_ecdf = EC...
Builds Depoyed Classifier
def build(self): '''Builds Depoyed Classifier ''' if self._clf is None: raise NeedToTrainExceptionBeforeDeployingException() return DeployedClassifier(self._category, self._term_doc_matrix._category_idx_store, self._term_doc_matrix._term_idx_store, ...
Parameters ---------- term_to_index_dict: term -> idx dictionary Returns ------- IndexStore
def build(term_to_index_dict): ''' Parameters ---------- term_to_index_dict: term -> idx dictionary Returns ------- IndexStore ''' idxstore = IndexStore() idxstore._val2i = term_to_index_dict idxstore._next_i = len(term_to_index_dict) idxstore._i2val = [None for _ in range(idxstore._next_i)] ...
Returns ------- Corpus
def build(self): ''' Returns ------- Corpus ''' constructor_kwargs = self._get_build_kwargs() if type(self.raw_texts) == list: constructor_kwargs['raw_texts'] = np.array(self.raw_texts) else: constructor_kwargs['raw_texts'] = self.raw_texts return Corpus(**constructor_kwargs)
Parameters ---------- y_i, np.array(int) Arrays of word counts of words occurring in positive class y_j, np.array(int) Returns ------- np.array of z-scores
def get_zeta_i_j_given_separate_counts(self, y_i, y_j): ''' Parameters ---------- y_i, np.array(int) Arrays of word counts of words occurring in positive class y_j, np.array(int) Returns ------- np.array of z-scores ''' n_i, n_j = y_i.sum(), y_j.sum() prior_scale_j = prior_scale_i = 1 if sel...
Parameters ---------- term_doc_matrix : TermDocMatrix Term document matrix object to compact Returns ------- New term doc matrix
def compact(self, term_doc_matrix): ''' Parameters ---------- term_doc_matrix : TermDocMatrix Term document matrix object to compact Returns ------- New term doc matrix ''' domain_mat = CombineDocsIntoDomains(term_doc_matrix).get_new_term_doc_mat(self.doc_domains) domain_count = (domain_mat > 0)...
Returns ------- pd.Series, all raw documents
def get_texts(self): ''' Returns ------- pd.Series, all raw documents ''' if sys.version_info[0] == 2: return self._df[self._parsed_col] return self._df[self._parsed_col].apply(str)
Returns a dataframe indexed on the number of groups a term occured in. Parameters ---------- group_col Returns ------- pd.DataFrame
def term_group_freq_df(self, group_col): # type: (str) -> pd.DataFrame ''' Returns a dataframe indexed on the number of groups a term occured in. Parameters ---------- group_col Returns ------- pd.DataFrame ''' group_idx_store = I...
Compute variance from :param X: :return:
def sparse_var(X): ''' Compute variance from :param X: :return: ''' Xc = X.copy() Xc.data **= 2 return np.array(Xc.mean(axis=0) - np.power(X.mean(axis=0), 2))[0]
Specify the category to score. Optionally, score against a specific set of categories.
def set_categories(self, category_name, not_category_names=[], neutral_category_names=[]): ''' Specify the category to score. Optionally, score against a specific set of categories. ''' tdf = self.term_ranker_.get_ranks...
In this case, parameters a and b aren't used, since this information is taken directly from the corpus categories. Returns -------
def get_t_statistics(self): ''' In this case, parameters a and b aren't used, since this information is taken directly from the corpus categories. Returns ------- ''' X = self._get_X() cat_X, ncat_X = self._get_cat_and_ncat(X) mean_delta = self...
Parameters ---------- X_factory mX_factory category_idx_store df parse_pipeline term_idx_store metadata_idx_store y Returns ------- CorpusDF
def _apply_pipeline_and_get_build_instance(self, X_factory, mX_factory, category_idx_store, df, pars...
Parameters ---------- background
def set_background_corpus(self, background): ''' Parameters ---------- background ''' if issubclass(type(background), TermDocMatrixWithoutCategories): self._background_corpus = pd.DataFrame(background .get_te...
Returns ------- A pd.DataFrame consisting of unigram term counts of words occurring in the TermDocumentMatrix and their corresponding background corpus counts. The dataframe has two columns, corpus and background. >>> corpus.get_unigram_corpus().get_term_and_background_counts...
def get_term_and_background_counts(self): ''' Returns ------- A pd.DataFrame consisting of unigram term counts of words occurring in the TermDocumentMatrix and their corresponding background corpus counts. The dataframe has two columns, corpus and background. ...
Returns ------- List of dicts. One dict for each document, keys are metadata, values are counts
def list_extra_features(self): ''' Returns ------- List of dicts. One dict for each document, keys are metadata, values are counts ''' return FeatureLister(self._mX, self._metadata_idx_store, self.get_num_docs())....
Returns ------- A new TermDocumentMatrix consisting of only terms which occur at least minimum_term_count.
def remove_infrequent_words(self, minimum_term_count, term_ranker=AbsoluteFrequencyRanker): ''' Returns ------- A new TermDocumentMatrix consisting of only terms which occur at least minimum_term_count. ''' tdf = term_ranker(self).get_ranks().sum(axis=1) return se...
Returns ------- A new TermDocumentMatrix consisting of only terms in the current TermDocumentMatrix that aren't spaCy entity tags. Note: Used if entity types are censored using FeatsFromSpacyDoc(tag_types_to_censor=...).
def remove_entity_tags(self): ''' Returns ------- A new TermDocumentMatrix consisting of only terms in the current TermDocumentMatrix that aren't spaCy entity tags. Note: Used if entity types are censored using FeatsFromSpacyDoc(tag_types_to_censor=...). ''' ...
Non destructive term removal. Parameters ---------- terms : list list of terms to remove ignore_absences : bool, False by default if term does not appear, don't raise an error, just move on. Returns ------- TermDocMatrix, new object with ...
def remove_terms(self, terms, ignore_absences=False): '''Non destructive term removal. Parameters ---------- terms : list list of terms to remove ignore_absences : bool, False by default if term does not appear, don't raise an error, just move on. ...
Parameters ---------- threshold: int Minimum number of documents term should appear in to be kept Returns ------- TermDocMatrix, new object with terms removed.
def remove_terms_used_in_less_than_num_docs(self, threshold): ''' Parameters ---------- threshold: int Minimum number of documents term should appear in to be kept Returns ------- TermDocMatrix, new object with terms removed. ''' term_...
Parameters ------- stoplist : list, optional Returns ------- A new TermDocumentMatrix consisting of only unigrams in the current TermDocumentMatrix.
def get_stoplisted_unigram_corpus(self, stoplist=None): ''' Parameters ------- stoplist : list, optional Returns ------- A new TermDocumentMatrix consisting of only unigrams in the current TermDocumentMatrix. ''' if stoplist is None: s...
Parameters ------- stoplist : list of lower-cased words, optional Returns ------- A new TermDocumentMatrix consisting of only unigrams in the current TermDocumentMatrix.
def get_stoplisted_unigram_corpus_and_custom(self, custom_stoplist): ''' Parameters ------- stoplist : list of lower-cased words, optional Returns ------- A new TermDocumentMatrix consisting of only unigrams in the...
Returns a list of document lengths in words Returns ------- np.array
def get_doc_lengths(self): ''' Returns a list of document lengths in words Returns ------- np.array ''' idx_to_delete_list = self._build_term_index_list(True, self._get_non_unigrams()) unigram_X, _ = self._get_X_after_delete_terms(idx_to_delete_list) ...
Parameters ---------- idx_to_delete_list, list Returns ------- TermDocMatrix
def remove_terms_by_indices(self, idx_to_delete_list): ''' Parameters ---------- idx_to_delete_list, list Returns ------- TermDocMatrix ''' new_X, new_term_idx_store = self._get_X_after_delete_terms(idx_to_delete_list) return self._make_n...
Returns ------- dict
def term_doc_lists(self): ''' Returns ------- dict ''' doc_ids = self._X.transpose().tolil().rows terms = self._term_idx_store.values() return dict(zip(terms, doc_ids))
Parameters ---------- term_ranker : TermRanker Returns ------- pd.Dataframe
def apply_ranker(self, term_ranker, use_non_text_features): ''' Parameters ---------- term_ranker : TermRanker Returns ------- pd.Dataframe ''' if use_non_text_features: return term_ranker(self).use_non_text_features().get_ranks() ...
:param doc_names: array-like[str], document names of reach document :return: Corpus-like object with doc names as metadata. If two documents share the same name (doc number) will be appended to their names.
def add_doc_names_as_metadata(self, doc_names): ''' :param doc_names: array-like[str], document names of reach document :return: Corpus-like object with doc names as metadata. If two documents share the same name (doc number) will be appended to their names. ''' if len(do...
Returns a new corpus with a the metadata matrix and index store integrated. :param metadata_matrix: scipy.sparse matrix (# docs, # metadata) :param meta_index_store: IndexStore of metadata values :return: TermDocMatrixWithoutCategories
def add_metadata(self, metadata_matrix, meta_index_store): ''' Returns a new corpus with a the metadata matrix and index store integrated. :param metadata_matrix: scipy.sparse matrix (# docs, # metadata) :param meta_index_store: IndexStore of metadata values :return: TermDocMatr...
Parameters ---------- doc, Spacy Docs Returns ------- Counter (unigram, bigram) -> count
def get_feats(self, doc): ''' Parameters ---------- doc, Spacy Docs Returns ------- Counter (unigram, bigram) -> count ''' ngram_counter = Counter() for sent in doc.sents: unigrams = self._get_unigram_feats(sent) bigrams = self._get_bigram_feats(unigrams) ngram_counter += Counter(chain(uni...
Computes Mann Whitney corrected p, z-values. Falls back to normal approximation when numerical limits are reached. :param correction_method: str or None, correction method from statsmodels.stats.multitest.multipletests 'fdr_bh' is recommended. :return: pd.DataFrame
def get_score_df(self, correction_method=None): ''' Computes Mann Whitney corrected p, z-values. Falls back to normal approximation when numerical limits are reached. :param correction_method: str or None, correction method from statsmodels.stats.multitest.multipletests 'fdr_bh' is re...
Parameters ---------- term_doc_matrix: TermDocMatrix or descendant scores: array-like Same length as number of terms in TermDocMatrix. num_term_to_keep: int, default=4000. Should be> 0. Number of terms to keep. Will keep between num_terms_to_keep/2 and num_terms_to_keep. Returns ------- TermDocMatr...
def reduce_terms(term_doc_matrix, scores, num_term_to_keep=None): ''' Parameters ---------- term_doc_matrix: TermDocMatrix or descendant scores: array-like Same length as number of terms in TermDocMatrix. num_term_to_keep: int, default=4000. Should be> 0. Number of terms to keep. Will keep between num...
Parameters ---------- term_doc_matrix: TermDocMatrix or descendant scores: array-like Same length as number of terms in TermDocMatrix. num_term_to_keep: int, default=4000. Should be> 0. Number of terms to keep. Will keep between num_terms_to_keep/2 and num_terms_to_keep. Returns ------- set, terms ...
def get_selected_terms(term_doc_matrix, scores, num_term_to_keep=None): ''' Parameters ---------- term_doc_matrix: TermDocMatrix or descendant scores: array-like Same length as number of terms in TermDocMatrix. num_term_to_keep: int, default=4000. Should be> 0. Number of terms to keep. Will keep betwe...
In this case, args aren't used, since this information is taken directly from the corpus categories. Returns ------- np.array, scores
def get_scores(self, *args): ''' In this case, args aren't used, since this information is taken directly from the corpus categories. Returns ------- np.array, scores ''' if self.tdf_ is None: raise Exception("Use set_category_name('category name', ['not category name', ...]) " + ...
Imputes p-values from the Z-scores of `ScaledFScore` scores. Assuming incorrectly that the scaled f-scores are normally distributed. Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,1] is the negative class. Retu...
def get_p_vals(self, X): ''' Imputes p-values from the Z-scores of `ScaledFScore` scores. Assuming incorrectly that the scaled f-scores are normally distributed. Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,...
Returns a projection of the categories :param term_doc_mat: a TermDocMatrix :return: CategoryProjection
def project(self, term_doc_mat, x_dim=0, y_dim=1): ''' Returns a projection of the categories :param term_doc_mat: a TermDocMatrix :return: CategoryProjection ''' return self._project_category_corpus(self._get_category_metadata_corpus(term_doc_mat), ...
Returns a projection of the :param term_doc_mat: a TermDocMatrix :return: CategoryProjection
def project_with_metadata(self, term_doc_mat, x_dim=0, y_dim=1): ''' Returns a projection of the :param term_doc_mat: a TermDocMatrix :return: CategoryProjection ''' return self._project_category_corpus(self._get_category_metadata_corpus_and_replace_terms(term_doc_mat), ...
In this case, parameters a and b aren't used, since this information is taken directly from the corpus categories. Returns -------
def get_scores(self, *args): ''' In this case, parameters a and b aren't used, since this information is taken directly from the corpus categories. Returns ------- ''' def jelinek_mercer_smoothing(cat): p_hat_w = self.tdf_[cat] * 1. / self.tdf_[cat].sum() c_hat_w = (self.smoothing_lambda_) * self...
Class decorator that ensures support for the special C{__cmp__} method. On Python 2 this does nothing. On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class, relying on C{__cmp__} to implement their comparisons.
def comparable(klass): """ Class decorator that ensures support for the special C{__cmp__} method. On Python 2 this does nothing. On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class, relying on C{__cmp__} to implement their comparisons. """ # On Python 2, __cmp__ will just...
Decorator to validate all the arguments to function are of the type of calling class for passed operator
def validate_class_type_arguments(operator): """ Decorator to validate all the arguments to function are of the type of calling class for passed operator """ def inner(function): def wrapper(self, *args, **kwargs): for arg in args + tuple(kwargs.values()): if no...
Decorator to validate the <type> of arguments in the calling function are of the `param_type` class. if `param_type` is None, uses `param_type` as the class where it is used. Note: Use this decorator on the functions of the class.
def validate_arguments_type_of_function(param_type=None): """ Decorator to validate the <type> of arguments in the calling function are of the `param_type` class. if `param_type` is None, uses `param_type` as the class where it is used. Note: Use this decorator on the functions of the class. "...
Returns the time offset from UTC accounting for DST Keyword Arguments: time_struct {time.struct_time} -- the struct time for which to return the UTC offset. If None, use current local time.
def utc_offset(time_struct=None): """ Returns the time offset from UTC accounting for DST Keyword Arguments: time_struct {time.struct_time} -- the struct time for which to return the UTC offset. If None, use current...
Returns a MayaDT instance for the human moment specified. Powered by dateparser. Useful for scraping websites. Examples: 'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015' Keyword Arguments: string -- string to be parsed timezone -- timezone referenced from (defaul...
def when(string, timezone='UTC', prefer_dates_from='current_period'): """"Returns a MayaDT instance for the human moment specified. Powered by dateparser. Useful for scraping websites. Examples: 'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015' Keyword Arguments: stri...
Returns a MayaDT instance for the machine-produced moment specified. Powered by pendulum. Accepts most known formats. Useful for working with data. Keyword Arguments: string -- string to be parsed timezone -- timezone referenced from (default: 'UTC') day_first -- if true, the first...
def parse(string, timezone='UTC', day_first=False, year_first=True, strict=False): """"Returns a MayaDT instance for the machine-produced moment specified. Powered by pendulum. Accepts most known formats. Useful for working with data. Keyword Arguments: string -- string to be parsed ti...
Returns `datetime.timedelta` object for the passed duration. Keyword Arguments: duration -- `datetime.timedelta` object or seconds in `int` format.
def _seconds_or_timedelta(duration): """Returns `datetime.timedelta` object for the passed duration. Keyword Arguments: duration -- `datetime.timedelta` object or seconds in `int` format. """ if isinstance(duration, int): dt_timedelta = timedelta(seconds=duration) elif isinstance(du...
Yields MayaDT objects between the start and end MayaDTs given, at a given interval (seconds or timedelta).
def intervals(start, end, interval): """ Yields MayaDT objects between the start and end MayaDTs given, at a given interval (seconds or timedelta). """ interval = _seconds_or_timedelta(interval) current_timestamp = start while current_timestamp.epoch < end.epoch: yield current_timest...
Returns a new MayaDT object with the given offsets.
def add(self, **kwargs): """Returns a new MayaDT object with the given offsets.""" return self.from_datetime( pendulum.instance(self.datetime()).add(**kwargs) )
Returns a new MayaDT object with the given offsets.
def subtract(self, **kwargs): """Returns a new MayaDT object with the given offsets.""" return self.from_datetime( pendulum.instance(self.datetime()).subtract(**kwargs) )
Returns a new MayaDT object modified by the given instruction. Powered by snaptime. See https://github.com/zartstrom/snaptime for a complete documentation about the snaptime instructions.
def snap(self, instruction): """ Returns a new MayaDT object modified by the given instruction. Powered by snaptime. See https://github.com/zartstrom/snaptime for a complete documentation about the snaptime instructions. """ return self.from_datetime(snaptime.snap(self....
Returns the name of the local timezone.
def local_timezone(self): """Returns the name of the local timezone.""" if self._local_tz.zone in pytz.all_timezones: return self._local_tz.zone return self.timezone
Converts a datetime into an epoch.
def __dt_to_epoch(dt): """Converts a datetime into an epoch.""" # Assume UTC if no datetime is provided. if dt.tzinfo is None: dt = dt.replace(tzinfo=pytz.utc) epoch_start = Datetime(*MayaDT.__EPOCH_START, tzinfo=pytz.timezone('UTC')) return (dt - epoch_start).total_s...
Returns MayaDT instance from a 9-tuple struct It's assumed to be from gmtime().
def from_struct(klass, struct, timezone=pytz.UTC): """Returns MayaDT instance from a 9-tuple struct It's assumed to be from gmtime(). """ struct_time = time.mktime(struct) - utc_offset(struct) dt = Datetime.fromtimestamp(struct_time, timezone) return klass(klass.__dt_to_...
Returns a timezone-aware datetime... Defaulting to UTC (as it should). Keyword Arguments: to_timezone {str} -- timezone to convert to (default: None/UTC) naive {bool} -- if True, the tzinfo is simply dropped (default: False)
def datetime(self, to_timezone=None, naive=False): """Returns a timezone-aware datetime... Defaulting to UTC (as it should). Keyword Arguments: to_timezone {str} -- timezone to convert to (default: None/UTC) naive {bool} -- if True, the tzinfo...
Returns an ISO 8601 representation of the MayaDT.
def iso8601(self): """Returns an ISO 8601 representation of the MayaDT.""" # Get a timezone-naive datetime. dt = self.datetime(naive=True) return '{}Z'.format(dt.isoformat())
Returns human slang representation of date. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English)
def slang_date(self, locale="en"): """"Returns human slang representation of date. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English) """ dt = pendulum.instance(self.datetime()) try: ...
Returns human slang representation of time. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English)
def slang_time(self, locale="en"): """"Returns human slang representation of time. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English) """ dt = self.datetime() return pendulum.instance(dt).diff_f...
Use sigmoid function to choose a delta that will help smoothly steer from current angle to target angle.
def angvel(target, current, scale): '''Use sigmoid function to choose a delta that will help smoothly steer from current angle to target angle.''' delta = target - current while delta < -180: delta += 360; while delta > 180: delta -= 360; return (old_div(2.0, (1.0 + math.exp(old_div(...
Steer towards the target pitch/yaw, return True when within the given tolerance threshold.
def pointTo(agent_host, ob, target_pitch, target_yaw, threshold): '''Steer towards the target pitch/yaw, return True when within the given tolerance threshold.''' pitch = ob.get(u'Pitch', 0) yaw = ob.get(u'Yaw', 0) delta_yaw = angvel(target_yaw, yaw, 50.0) delta_pitch = angvel(target_pitch, pitch, 5...
Download Malmo from github and optionaly build the Minecraft Mod. Args: branch: optional branch to clone. Default is release version. buildMod: don't build the Mod unless build arg is given as True. Returns: The path for the Malmo Minecraft mod.
def download(branch=None, buildMod=False): """Download Malmo from github and optionaly build the Minecraft Mod. Args: branch: optional branch to clone. Default is release version. buildMod: don't build the Mod unless build arg is given as True. Returns: The path for the Malmo Minecra...
Launch Malmo Minecraft Mod in one or more clients from the Minecraft directory on the (optionally) given ports. Args: ports: an optionsl list of ports to start minecraft clients on. Defaults to a single Minecraft client on port 10000. wait_timeout: optional time in secon...
def launch_minecraft(ports = [], wait_timeout = 360): """Launch Malmo Minecraft Mod in one or more clients from the Minecraft directory on the (optionally) given ports. Args: ports: an optionsl list of ports to start minecraft clients on. Defaults to a single Minecraft client o...
Set the MAMLMO_XSD_PATH environment variable in current process.
def set_malmo_xsd_path(): """Set the MAMLMO_XSD_PATH environment variable in current process.""" os.environ["MALMO_XSD_PATH"] = str(pathlib.Path(malmo_install_dir + "/Schemas").absolute()) print(os.environ["MALMO_XSD_PATH"])
Return the index in arr of the closest float value to val.
def indexOfClosest( arr, val ): '''Return the index in arr of the closest float value to val.''' i_closest = None for i,v in enumerate(arr): d = math.fabs( v - val ) if i_closest == None or d < d_closest: i_closest = i d_closest = d return i_closest
Before a command has been sent we wait for an observation of the world and a frame.
def waitForInitialState( self ): '''Before a command has been sent we wait for an observation of the world and a frame.''' # wait for a valid observation world_state = self.agent_host.peekWorldState() while world_state.is_mission_running and all(e.text=='{}' for e in world_state.observat...
After each command has been sent we wait for the observation to change as expected and a frame.
def waitForNextState( self ): '''After each command has been sent we wait for the observation to change as expected and a frame.''' # wait for the observation position to have changed print('Waiting for observation...', end=' ') while True: world_state = self.agent_host.peekW...
Take an action from the action_set and set the expected outcome so we can wait for it.
def act( self ): '''Take an action from the action_set and set the expected outcome so we can wait for it.''' if self.action_set == 'discrete_absolute': actions = ['movenorth 1', 'movesouth 1', 'movewest 1', 'moveeast 1'] elif self.action_set == 'discrete_relative': actio...
Simulate a left and right sensor output (from 0 to 1) given the input image.
def processFrame(frame): """Simulate a left and right sensor output (from 0 to 1) given the input image.""" # The pixels are grey-scale values from 0-255 - white = 255, black = 0 # We want to turn the image into two values, one for the left "sensor" and one for the right. # There are many possible ways ...
Build an XML string that contains a square for each city
def getCitiesDrawingXML(points): ''' Build an XML string that contains a square for each city''' xml = "" for p in points: x = str(p.x) z = str(p.y) xml += '<DrawBlock x="' + x + '" y="7" z="' + z + '" type="beacon"/>' xml += '<DrawItem x="' + x + '" y="10" z="' + z + '" type...
Sets a mission running. Parameters: mission_spec : MissionSpec instance, specifying the mission. mission_record_spec : MissionRecordSpec instance, specifying what should be recorded. role : int, the index of the role this human agent is to play. Zero based.
def runMission( self, mission_spec, mission_record_spec, role = 0 ): '''Sets a mission running. Parameters: mission_spec : MissionSpec instance, specifying the mission. mission_record_spec : MissionRecordSpec instance, specifying what should be recorded. role : int, the ...
Create the graphical user interface.
def createGUI( self ): '''Create the graphical user interface.''' our_font = "Helvetica 16 bold" small_font = "Helvetica 9 bold" self.root_frame = Frame(self.root) if self.action_space == 'continuous': desc = "Running continuous-action mission.\nUse the mouse to turn,...
Called when user presses the 'send' button or presses 'Enter' while the command entry box has focus.
def onSendCommand(self): '''Called when user presses the 'send' button or presses 'Enter' while the command entry box has focus.''' self.agent_host.sendCommand(self.command_entry.get()) self.command_entry.delete(0,END) self.canvas.focus_set()
Called at regular intervals to poll the mouse position to send continuous commands.
def update(self): '''Called at regular intervals to poll the mouse position to send continuous commands.''' if self.action_space == 'continuous': # mouse movement only used for continuous action space if self.world_state and self.world_state.is_mission_running: if self.mouse_...
Called when a key is pressed when the command entry box has focus.
def onKeyInCommandEntry(self, event): '''Called when a key is pressed when the command entry box has focus.''' if event.char == '\r': self.onSendCommand() self.canvas.focus_set()
Called when a key is pressed when the canvas has focus.
def onKeyPressInCanvas(self, event): '''Called when a key is pressed when the canvas has focus.''' char_map = { 'w':'move 1', 'a':'strafe -1', 's':'move -1', 'd':'strafe 1', ' ':'jump 1' } keysym_map = { 'continuous': { 'Left':'turn -1', 'Right':'turn 1', 'Up':'pitch -1', 'Down':'pitch 1', 'Shif...
Called when a key is released when the command entry box has focus.
def onKeyReleaseInCanvas(self, event): '''Called when a key is released when the command entry box has focus.''' char_map = { 'w':'move 0', 'a':'strafe 0', 's':'move 0', 'd':'strafe 0', ' ':'jump 0' } keysym_map = { 'Left':'turn 0', 'Right':'turn 0', 'Up':'pitch 0', 'Down':'pitch 0', 'Shift_L':'...
Return part of the XML string that defines the requested corner
def getCorner(index,top,left,expand=0,y=206): ''' Return part of the XML string that defines the requested corner''' x = str(-(expand+old_div(ARENA_WIDTH,2))) if left else str(expand+old_div(ARENA_WIDTH,2)) z = str(-(expand+old_div(ARENA_BREADTH,2))) if top else str(expand+old_div(ARENA_BREADTH,2)) retu...
Build an XML string that contains some randomly positioned goal items
def getItemXML(): ''' Build an XML string that contains some randomly positioned goal items''' xml="" for item in range(NUM_GOALS): x = str(random.randint(old_div(-ARENA_WIDTH,2),old_div(ARENA_WIDTH,2))) z = str(random.randint(old_div(-ARENA_BREADTH,2),old_div(ARENA_BREADTH,2))) xml ...