INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Parameters ---------- doc Spacy Docs
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 () )
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
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 RankDifferce which tends to work ...
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.
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.
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
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 ---------- raw_text uncleaned text for parsing out features
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 ---------- num_terms int
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 ---------- 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 ''' rank_df = self.scorer.get_rank_df(term_doc_matrix) opti...
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
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
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.
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
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 )
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
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.
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.
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
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.
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.
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.
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
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
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
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
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
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
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.
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
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.
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.
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.
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.
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.
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
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
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.
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.
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
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.
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.
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.
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.
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
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 ).
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.
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.
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 seconds to wait ( defaults to 3 mins ).
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':'...
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 ...
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 mission string.
def getMissionXML(summary): ''' Build an XML mission string.''' spawn_end_tag = ' type="mob_spawner" variant="' + MOB_TYPE + '"/>' return '''<?xml version="1.0" encoding="UTF-8" ?> <Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <About> ...
Scan through 360 degrees looking for the best direction in which to take the next step.
def getBestAngle(entities, current_yaw, current_health): '''Scan through 360 degrees, looking for the best direction in which to take the next step.''' us = findUs(entities) scores=[] # Normalise current yaw: while current_yaw < 0: current_yaw += 360 while current_yaw > 360: curr...
Attempt to quit mission if running and kill the client
def restart_minecraft(world_state, agent_host, client_info, message): """"Attempt to quit mission if running and kill the client""" if world_state.is_mission_running: agent_host.sendCommand("quit") time.sleep(10) agent_host.killClient(client_info) raise MissionTimeoutException(message)
Initialize a Malmo environment. xml - the mission xml. port - the MalmoEnv service s port. server - the MalmoEnv service address. Default is localhost. server2 - the MalmoEnv service address for given role if not 0. port2 - the MalmoEnv service port for given role if not 0. role - the agent role ( 0.. N - 1 ) for missi...
def init(self, xml, port, server=None, server2=None, port2=None, role=0, exp_uid=None, episode=0, action_filter=None, resync=0, step_options=0, action_space=None): """"Initialize a Malmo environment. xml - the mission xml. port - the MalmoEnv servic...
gym api reset
def reset(self): """gym api reset""" if self.resync_period > 0 and (self.resets + 1) % self.resync_period == 0: self._exit_resync() while not self.done: self.done = self._quit_episode() if not self.done: time.sleep(0.1) return self._...
gym api step
def step(self, action): """gym api step""" obs = None reward = None info = None turn = True withturnkey = self.step_options < 2 withinfo = self.step_options == 0 or self.step_options == 2 while not self.done and \ ((obs is None or len(obs)...
gym api close
def close(self): """gym api close""" try: # Purge last token from head node with <Close> message. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.server, self.port)) self._hello(sock) comms.send_message(sock, ("<Clo...
Use carefully to reset the episode count to 0.
def reinit(self): """Use carefully to reset the episode count to 0.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.server, self.port)) self._hello(sock) comms.send_message(sock, ("<Init>" + self._get_token() + "</Init>").encode()) reply = ...
Get status from server. head - Ping the the head node if True.
def status(self, head): """Get status from server. head - Ping the the head node if True. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if head: sock.connect((self.server, self.port)) else: sock.connect((self.server2, self.port2)) ...
Use carefully to cause the Minecraft service to exit ( and hopefully restart ). Likely to throw communication errors so wrap in exception handler.
def exit(self): """Use carefully to cause the Minecraft service to exit (and hopefully restart). Likely to throw communication errors so wrap in exception handler. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.server2, self.port2)) self._...