code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def device_mapping(cuda_device ): u""" In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU), you have to supply a `map_location` function. Call this with the desired `cuda_device` to get the function that `torch.load()` needs. """ def inner_device_mapping(storage ...
In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU), you have to supply a `map_location` function. Call this with the desired `cuda_device` to get the function that `torch.load()` needs.
device_mapping
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def combine_tensors(combination , tensors ) : u""" Combines a list of tensors using element-wise operations and concatenation, specified by a ``combination`` string. The string refers to (1-indexed) positions in the input tensor list, and looks like ``"1,2,1+2,3-1"...
Combines a list of tensors using element-wise operations and concatenation, specified by a ``combination`` string. The string refers to (1-indexed) positions in the input tensor list, and looks like ``"1,2,1+2,3-1"``. We allow the following kinds of combinations: ``x``, ``x*y``, ``x+y``, ``x-y``, and...
combine_tensors
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def get_combined_dim(combination , tensor_dims ) : u""" For use with :func:`combine_tensors`. This function computes the resultant dimension when calling ``combine_tensors(combination, tensors)``, when the tensor dimension is known. This is necessary for knowing the sizes of weight...
For use with :func:`combine_tensors`. This function computes the resultant dimension when calling ``combine_tensors(combination, tensors)``, when the tensor dimension is known. This is necessary for knowing the sizes of weight matrices when building models that use ``combine_tensors``. Parameter...
get_combined_dim
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def logsumexp(tensor , dim = -1, keepdim = False) : u""" A numerically stable computation of logsumexp. This is mathematically equivalent to `tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log pr...
A numerically stable computation of logsumexp. This is mathematically equivalent to `tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log probabilities. Parameters ---------- tensor : torch.FloatTensor, required. A tensor of arbitrary size. d...
logsumexp
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def get_device_of(tensor ) : u""" Returns the device of the tensor. """ if not tensor.is_cuda: return -1 else: return tensor.get_device()
Returns the device of the tensor.
get_device_of
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def flatten_and_batch_shift_indices(indices , sequence_length ) : u""" This is a subroutine for :func:`~batched_index_select`. The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which ...
This is a subroutine for :func:`~batched_index_select`. The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which has size ``(batch_size, sequence_length, embedding_size)``. This function returns a vector that correctly indexes into the flattened t...
flatten_and_batch_shift_indices
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def batched_index_select(target , indices , flattened_indices = None) : u""" The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence dimension (dimension...
The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence dimension (dimension 2) of the target, which has size ``(batch_size, sequence_length, embedding_size)``. This function returns selected values in the target with respect to the provided indices, which have size...
batched_index_select
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def flattened_index_select(target , indices ) : u""" The given ``indices`` of size ``(set_size, subset_size)`` specifies subsets of the ``target`` that each of the set_size rows should select. The `target` has size ``(batch_size, se...
The given ``indices`` of size ``(set_size, subset_size)`` specifies subsets of the ``target`` that each of the set_size rows should select. The `target` has size ``(batch_size, sequence_length, embedding_size)``, and the resulting selected tensor has size ``(batch_size, set_size, subset_size, embedding...
flattened_index_select
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def get_range_vector(size , device ) : u""" Returns a range vector with the desired size, starting at 0. The CUDA implementation is meant to avoid copy data from CPU to GPU. """ if device > -1: return torch.cuda.LongTensor(size, device=device).fill_(1).cumsum(0) - 1 ...
Returns a range vector with the desired size, starting at 0. The CUDA implementation is meant to avoid copy data from CPU to GPU.
get_range_vector
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def bucket_values(distances , num_identity_buckets = 4, num_total_buckets = 10) : u""" Places the given values (designed for distances) into ``num_total_buckets``semi-logscale buckets, with ``num_identity_buckets`` of these capturing ...
Places the given values (designed for distances) into ``num_total_buckets``semi-logscale buckets, with ``num_identity_buckets`` of these capturing single values. The default settings will bucket values into the following buckets: [0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+]. Parameters -----...
bucket_values
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def add_sentence_boundary_token_ids(tensor , mask , sentence_begin_token , sentence_end_token ) : u""" Add begin/end of sentence token...
Add begin/end of sentence tokens to the batch of sentences. Given a batch of sentences with size ``(batch_size, timesteps)`` or ``(batch_size, timesteps, dim)`` this returns a tensor of shape ``(batch_size, timesteps + 2)`` or ``(batch_size, timesteps + 2, dim)`` respectively. Returns both the new...
add_sentence_boundary_token_ids
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def remove_sentence_boundaries(tensor , mask ) : u""" Remove begin/end of sentence embeddings from the batch of sentences. Given a batch of sentences with size ``(batch_size, timesteps, dim)`` this returns a ten...
Remove begin/end of sentence embeddings from the batch of sentences. Given a batch of sentences with size ``(batch_size, timesteps, dim)`` this returns a tensor of shape ``(batch_size, timesteps - 2, dim)`` after removing the beginning and end sentence markers. The sentences are assumed to be padded o...
remove_sentence_boundaries
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def add_positional_features(tensor , min_timescale = 1.0, max_timescale = 1.0e4): # pylint: disable=line-too-long u""" Implements the frequency-based positional encoding described in `Attention is all you Need <https:...
Implements the frequency-based positional encoding described in `Attention is all you Need <https://www.semanticscholar.org/paper/Attention-Is-All-You-Need-Vaswani-Shazeer/0737da0767d77606169cbf4187b83e1ab62f6077>`_ . Adds sinusoids of different frequencies to a ``Tensor``. A sinusoid of a differe...
add_positional_features
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/util.py
MIT
def search(self, num_steps , initial_state , decoder_step , keep_final_unfinished_states = True) : u""" Parameters ---------- num_steps : ``int`` How...
Parameters ---------- num_steps : ``int`` How many steps should we take in our search? This is an upper bound, as it's possible for the search to run out of valid actions before hitting this number, or for all states on the beam to finish. initial_st...
search
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/beam_search.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/beam_search.py
MIT
def update(self, action ) : u""" Takes an action index, updates checklist and returns an updated state. """ checklist_addition = (self.terminal_actions == action).float() new_checklist = self.checklist + checklist_addition new_checklist_sta...
Takes an action index, updates checklist and returns an updated state.
update
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/checklist_state.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/checklist_state.py
MIT
def decode_mst(energy , length , has_labels = True) : u""" Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm fo...
Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for maximum spanning arboresences on graphs. Parameters ---------- energy : ``numpy.ndarray``, required. A tensor with shape (num_l...
decode_mst
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/chu_liu_edmonds.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/chu_liu_edmonds.py
MIT
def chu_liu_edmonds(length , score_matrix , current_nodes , final_edges , old_input , old_output , representatives ...
Applies the chu-liu-edmonds algorithm recursively to a graph with edge weights defined by score_matrix. Note that this function operates in place, so variables will be modified. Parameters ---------- length : ``int``, required. The number of nodes. score_matrix : ``numpy.ndarr...
chu_liu_edmonds
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/chu_liu_edmonds.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/chu_liu_edmonds.py
MIT
def search(self, initial_state , decoder_step ) : u""" Parameters ---------- initial_state : ``DecoderState`` The starting state of our search. This is assumed to be `batched`, and our bea...
Parameters ---------- initial_state : ``DecoderState`` The starting state of our search. This is assumed to be `batched`, and our beam search is batch-aware - we'll keep ``beam_size`` states around for each instance in the batch. decoder_step : ``DecoderStep`` ...
search
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/constrained_beam_search.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/constrained_beam_search.py
MIT
def take_step(self, state , max_actions = None, allowed_actions = None) : u""" The main method in the ``DecoderStep`` API. This function defines the computation done at each step of decoding and re...
The main method in the ``DecoderStep`` API. This function defines the computation done at each step of decoding and returns a ranked list of next states. The input state is `grouped`, to allow for efficient computation, but the output states should all have a ``group_size`` of 1, to m...
take_step
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/decoder_step.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/decoder_step.py
MIT
def get_valid_actions(self) : u""" Returns a list of valid actions (represented as integers) """ actions = self._valid_actions[self._nonterminal_stack[-1]] for type_, variable in self._lambda_stacks: if self._nonterminal_stack[-1] == type_: ...
Returns a list of valid actions (represented as integers)
get_valid_actions
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/grammar_state.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/grammar_state.py
MIT
def take_action(self, production_rule ) : u""" Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal stack a...
Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal stack and the context-dependent actions. Updating the non-terminal stack ...
take_action
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/grammar_state.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/grammar_state.py
MIT
def _get_productions_from_string(production_string ) : u""" Takes a string like '[<d,d>, d]' and parses it into a list like ['<d,d>', 'd']. For production strings that are not lists, like '<e,d>', we return a single-element list: ['<e,d>']. """ if product...
Takes a string like '[<d,d>, d]' and parses it into a list like ['<d,d>', 'd']. For production strings that are not lists, like '<e,d>', we return a single-element list: ['<e,d>'].
_get_productions_from_string
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/grammar_state.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/grammar_state.py
MIT
def construct_prefix_tree(targets , target_mask = None) : u""" Takes a list of valid target action sequences and creates a mapping from all possible (valid) action prefixes to...
Takes a list of valid target action sequences and creates a mapping from all possible (valid) action prefixes to allowed actions given that prefix. While the method is called ``construct_prefix_tree``, we're actually returning a map that has as keys the paths to `all internal nodes of the trie`, and a...
construct_prefix_tree
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/util.py
MIT
def decode(self, initial_state , decode_step , supervision ) : u""" Takes an initial state object, a means of transitioning from state to state, and a supervision signal, and uses the ...
Takes an initial state object, a means of transitioning from state to state, and a supervision signal, and uses the supervision to train the transition function to pick "good" states. This function should typically return a ``loss`` key during training, which the ``Model`` will...
decode
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/decoder_trainer.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/decoder_trainer.py
MIT
def _prune_beam(states , beam_size , sort_states = False) : u""" This method can be used to prune the set of unfinished states on a beam or finished states at the end of search. In the former case, the stat...
This method can be used to prune the set of unfinished states on a beam or finished states at the end of search. In the former case, the states need not be sorted because the all come from the same decoding step, which does the sorting. However, if the states are finished and this metho...
_prune_beam
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/expected_risk_minimization.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/expected_risk_minimization.py
MIT
def _get_best_action_sequences(self, finished_states ) : u""" Returns the best action sequences for each item based on model scores. We return at most ``self._max_num_decoded_sequences`` number of sequences per insta...
Returns the best action sequences for each item based on model scores. We return at most ``self._max_num_decoded_sequences`` number of sequences per instance.
_get_best_action_sequences
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/expected_risk_minimization.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/expected_risk_minimization.py
MIT
def __call__(self, module ) : u""" Parameters ---------- module : torch.nn.Module, required The module to regularize. """ accumulator = 0.0 # For each parameter find the first matching regex. for name, parameter i...
Parameters ---------- module : torch.nn.Module, required The module to regularize.
__call__
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/regularizers/regularizer_applicator.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/regularizers/regularizer_applicator.py
MIT
def from_params(cls, params = ()) : u""" Converts a List of pairs (regex, params) into an RegularizerApplicator. This list should look like [["regex1": {"type": "l2", "alpha": 0.01}], ["regex2": "l1"]] where each...
Converts a List of pairs (regex, params) into an RegularizerApplicator. This list should look like [["regex1": {"type": "l2", "alpha": 0.01}], ["regex2": "l1"]] where each parameter receives the penalty corresponding to the first regex that matches its name (which may be no re...
from_params
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/nn/regularizers/regularizer_applicator.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/regularizers/regularizer_applicator.py
MIT
def _json_to_instance(self, json_dict ) : u""" Expects JSON that looks like ``{"sentence": "..."}``. """ spacy_tokens = self._tokenizer.split_words(json_dict[u"sentence"]) sentence_text = [token.text for token in spacy_tokens] pos_tags = [token.tag_ fo...
Expects JSON that looks like ``{"sentence": "..."}``.
_json_to_instance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/biaffine_dependency_parser.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/biaffine_dependency_parser.py
MIT
def _build_hierplane_tree(words , heads , tags , pos ) : u""" Returns ------- A JSON dictionary render-able by Hierplane for the given tree. ...
Returns ------- A JSON dictionary render-able by Hierplane for the given tree.
_build_hierplane_tree
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/biaffine_dependency_parser.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/biaffine_dependency_parser.py
MIT
def _json_to_instance(self, json_dict ) : u""" Expects JSON that looks like ``{"question": "...", "passage": "..."}``. """ question_text = json_dict[u"question"] passage_text = json_dict[u"passage"] return self._dataset_reader.text_to_instance(question...
Expects JSON that looks like ``{"question": "...", "passage": "..."}``.
_json_to_instance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/bidaf.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/bidaf.py
MIT
def _json_to_instance(self, json_dict ) : u""" Expects JSON that looks like ``{"sentence": "..."}``. """ spacy_tokens = self._tokenizer.split_words(json_dict[u"sentence"]) sentence_text = [token.text for token in spacy_tokens] pos_tags = [token.tag_ fo...
Expects JSON that looks like ``{"sentence": "..."}``.
_json_to_instance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/constituency_parser.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/constituency_parser.py
MIT
def _build_hierplane_tree(self, tree , index , is_root ) : u""" Recursively builds a JSON dictionary from an NLTK ``Tree`` suitable for rendering trees using the `Hierplane library<https://allenai.github.io/hierplane/>`. Parameters ---------- tre...
Recursively builds a JSON dictionary from an NLTK ``Tree`` suitable for rendering trees using the `Hierplane library<https://allenai.github.io/hierplane/>`. Parameters ---------- tree : ``Tree``, required. The tree to convert into Hierplane JSON. index : int...
_build_hierplane_tree
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/constituency_parser.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/constituency_parser.py
MIT
def _json_to_instance(self, json_dict ) : u""" Expects JSON that looks like ``{"document": "string of document text"}`` """ document = json_dict[u"document"] spacy_document = self._spacy(document) sentences = [[token.text for token in sentence] for sen...
Expects JSON that looks like ``{"document": "string of document text"}``
_json_to_instance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/coref.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/coref.py
MIT
def _json_to_instance(self, json_dict ) : u""" Expects JSON that looks like ``{"premise": "...", "hypothesis": "..."}``. """ premise_text = json_dict[u"premise"] hypothesis_text = json_dict[u"hypothesis"] return self._dataset_reader.text_to_instance(pr...
Expects JSON that looks like ``{"premise": "...", "hypothesis": "..."}``.
_json_to_instance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/decomposable_attention.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/decomposable_attention.py
MIT
def _batch_json_to_instances(self, json_dicts ) : u""" Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s. By default, this expects that a "batch" consists of a list of JSON blobs which would individually be predicted...
Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s. By default, this expects that a "batch" consists of a list of JSON blobs which would individually be predicted by :func:`predict_json`. In order to use this method for batch prediction, :func:`_js...
_batch_json_to_instances
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/predictor.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/predictor.py
MIT
def from_archive(cls, archive , predictor_name = None) : u""" Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`; that is, from the result of training a model. Optionally specify which `Predictor` subclass; otherwise, the defaul...
Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`; that is, from the result of training a model. Optionally specify which `Predictor` subclass; otherwise, the default one for the model will be used.
from_archive
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/predictor.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/predictor.py
MIT
def _sentence_to_srl_instances(self, json_dict ) : u""" The SRL model has a slightly different API from other models, as the model is run forward for every verb in the sentence. This means that for a single sentence, we need to generate a ``List[Instance]``, whe...
The SRL model has a slightly different API from other models, as the model is run forward for every verb in the sentence. This means that for a single sentence, we need to generate a ``List[Instance]``, where the length of this list corresponds to the number of verbs in the sentence. Ad...
_sentence_to_srl_instances
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py
MIT
def predict_batch_json(self, inputs ) : u""" Expects JSON that looks like ``[{"sentence": "..."}, {"sentence": "..."}, ...]`` and returns JSON that looks like .. code-block:: js [ {"words": [...], "verbs": [ ...
Expects JSON that looks like ``[{"sentence": "..."}, {"sentence": "..."}, ...]`` and returns JSON that looks like .. code-block:: js [ {"words": [...], "verbs": [ {"verb": "...", "description": "...", "tags": [...]}, ...
predict_batch_json
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py
MIT
def predict_json(self, inputs ) : u""" Expects JSON that looks like ``{"sentence": "..."}`` and returns JSON that looks like .. code-block:: js {"words": [...], "verbs": [ {"verb": "...", "description": "...", "tags": [...]},...
Expects JSON that looks like ``{"sentence": "..."}`` and returns JSON that looks like .. code-block:: js {"words": [...], "verbs": [ {"verb": "...", "description": "...", "tags": [...]}, ... {"verb": "...", "description"...
predict_json
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py
MIT
def _json_to_instance(self, json_dict ) : u""" Expects JSON that looks like ``{"sentence": "..."}``. Runs the underlying model, and adds the ``"words"`` to the output. """ sentence = json_dict[u"sentence"] tokens = self._tokenizer.split_words(sentence)...
Expects JSON that looks like ``{"sentence": "..."}``. Runs the underlying model, and adds the ``"words"`` to the output.
_json_to_instance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/sentence_tagger.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/sentence_tagger.py
MIT
def _json_to_instance(self, json_dict ) : u""" Expects JSON that looks like ``{"question": "...", "table": "..."}``. """ question_text = json_dict[u"question"] table_rows = json_dict[u"table"].split(u'\n') # pylint: disable=protected-access to...
Expects JSON that looks like ``{"question": "...", "table": "..."}``.
_json_to_instance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/wikitables_parser.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/wikitables_parser.py
MIT
def _execute_logical_form_on_table(logical_form , table ): u""" The parameters are written out to files which the jar file reads and then executes the logical form. """ logical_form_filename = os.path.join(SEMPRE_DIR, u'logical_forms.txt') with open(logical_form_f...
The parameters are written out to files which the jar file reads and then executes the logical form.
_execute_logical_form_on_table
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/predictors/wikitables_parser.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/wikitables_parser.py
MIT
def _walk(self) : u""" Walk over action space to collect completed paths of at most ``self._max_path_length`` steps. """ # Buffer of NTs to expand, previous actions incomplete_paths = [([unicode(type_)], ["{START_SYMBOL} -> {type_}"]) for type_ in ...
Walk over action space to collect completed paths of at most ``self._max_path_length`` steps.
_walk
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/action_space_walker.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/action_space_walker.py
MIT
def lisp_to_nested_expression(lisp_string ) : u""" Takes a logical form as a lisp string and returns a nested list representation of the lisp. For example, "(count (division first))" would get mapped to ['count', ['division', 'first']]. """ stack = [] current_expression = ...
Takes a logical form as a lisp string and returns a nested list representation of the lisp. For example, "(count (division first))" would get mapped to ['count', ['division', 'first']].
lisp_to_nested_expression
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/util.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/util.py
MIT
def get_times_from_utterance(utterance , char_offset_to_token_index , indices_of_approximate_words ) : u""" Given an utterance, we get the numbers that correspond to times and convert them to values ...
Given an utterance, we get the numbers that correspond to times and convert them to values that may appear in the query. For example: convert ``7pm`` to ``1900``.
get_times_from_utterance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
MIT
def get_date_from_utterance(tokenized_utterance , year = 1993, month = None, day = None) : u""" When the year is not explicitly mentioned in the utterance, the query assumes that it is 1...
When the year is not explicitly mentioned in the utterance, the query assumes that it is 1993 so we do the same here. If there is no mention of the month or day then we do not return any dates from the utterance.
get_date_from_utterance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
MIT
def get_numbers_from_utterance(utterance , tokenized_utterance ) : u""" Given an utterance, this function finds all the numbers that are in the action space. Since we need to keep track of linking scores, we represent the numbers as a dictionary, where the keys are the...
Given an utterance, this function finds all the numbers that are in the action space. Since we need to keep track of linking scores, we represent the numbers as a dictionary, where the keys are the string representation of the number and the values are lists of the token indices that triggers that number. ...
get_numbers_from_utterance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
MIT
def digit_to_query_time(digit ) : u""" Given a digit in the utterance, return a list of the times that it corresponds to. """ if int(digit) % 12 == 0: return [0, 1200, 2400] return [int(digit) * HOUR_TO_TWENTY_FOUR, (int(digit) * HOUR_TO_TWENTY_FOUR + TWELVE_TO_TW...
Given a digit in the utterance, return a list of the times that it corresponds to.
digit_to_query_time
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
MIT
def get_approximate_times(times ) : u""" Given a list of times that follow a word such as ``about``, we return a list of times that could appear in the query as a result of this. For example if ``about 7pm`` appears in the utterance, then we also want to add ``1830`` and ``1930...
Given a list of times that follow a word such as ``about``, we return a list of times that could appear in the query as a result of this. For example if ``about 7pm`` appears in the utterance, then we also want to add ``1830`` and ``1930``.
get_approximate_times
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
MIT
def _time_regex_match(regex , utterance , char_offset_to_token_index , map_match_to_query_value , indices_of_approximate_words ) : ur""" Given...
Given a regex for matching times in the utterance, we want to convert the matches to the values that appear in the query and token indices they correspond to. ``char_offset_to_token_index`` is a dictionary that maps from the character offset to the token index, we use this to look up what token a rege...
_time_regex_match
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py
MIT
def initialize_valid_actions(self) : u""" We initialize the valid actions with the global actions. These include the valid actions that result from the grammar and also those that result from the tables provided. The keys represent the nonterminals in the grammar ...
We initialize the valid actions with the global actions. These include the valid actions that result from the grammar and also those that result from the tables provided. The keys represent the nonterminals in the grammar and the values are lists of the valid actions of that nonterminal...
initialize_valid_actions
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/sql_table_context.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/sql_table_context.py
MIT
def add_action(self, node ) : u""" For each node, we accumulate the rules that generated its children in a list. """ if node.expr.name and node.expr.name != u'ws': nonterminal = '{node.expr.name} -> ' if isinstance(node.expr, Literal): ...
For each node, we accumulate the rules that generated its children in a list.
add_action
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/sql_table_context.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/sql_table_context.py
MIT
def read_from_json(cls, json_object ) : u""" We read tables formatted as JSON objects (dicts) here. This is useful when you are reading data from a demo. The expected format is:: {"question": [token1, token2, ...], "columns...
We read tables formatted as JSON objects (dicts) here. This is useful when you are reading data from a demo. The expected format is:: {"question": [token1, token2, ...], "columns": [column1, column2, ...], "cells": [[row1_cell1, row1_cell2, ...], ...
read_from_json
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
MIT
def _normalize_string(string ) : u""" These are the transformation rules used to normalize cell in column names in Sempre. See ``edu.stanford.nlp.sempre.tables.StringNormalizationUtils.characterNormalize`` and ``edu.stanford.nlp.sempre.tables.TableTypeSystem.canonicalizeName``...
These are the transformation rules used to normalize cell in column names in Sempre. See ``edu.stanford.nlp.sempre.tables.StringNormalizationUtils.characterNormalize`` and ``edu.stanford.nlp.sempre.tables.TableTypeSystem.canonicalizeName``. We reproduce those rules here to normalize a...
_normalize_string
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
MIT
def _get_numbers_from_tokens(tokens ) : u""" Finds numbers in the input tokens and returns them as strings. We do some simple heuristic number recognition, finding ordinals and cardinals expressed as text ("one", "first", etc.), as well as numerals ("...
Finds numbers in the input tokens and returns them as strings. We do some simple heuristic number recognition, finding ordinals and cardinals expressed as text ("one", "first", etc.), as well as numerals ("7th", "3rd"), months (mapping "july" to 7), and units ("1ghz"). We also...
_get_numbers_from_tokens
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
MIT
def _get_cell_parts(cls, cell_text ) : u""" Splits a cell into parts and returns the parts of the cell. We return a list of ``(entity_name, entity_text)``, where ``entity_name`` is ``fb:part.[something]``, and ``entity_text`` is the text of the cell correspon...
Splits a cell into parts and returns the parts of the cell. We return a list of ``(entity_name, entity_text)``, where ``entity_name`` is ``fb:part.[something]``, and ``entity_text`` is the text of the cell corresponding to that part. For many cells, there is only one "part", and we re...
_get_cell_parts
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
MIT
def _should_split_cell(cls, cell_text ) : u""" Checks whether the cell should be split. We're just doing the same thing that SEMPRE did here. """ if u', ' in cell_text or u'\n' in cell_text or u'/' in cell_text: return True return False
Checks whether the cell should be split. We're just doing the same thing that SEMPRE did here.
_should_split_cell
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
MIT
def get_linked_agenda_items(self) : u""" Returns entities that can be linked to spans in the question, that should be in the agenda, for training a coverage based semantic parser. This method essentially does a heuristic entity linking, to provide weak supervision for a learn...
Returns entities that can be linked to spans in the question, that should be in the agenda, for training a coverage based semantic parser. This method essentially does a heuristic entity linking, to provide weak supervision for a learning to search parser.
get_linked_agenda_items
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py
MIT
def return_type(self) : u""" Gives the final return type for this function. If the function takes a single argument, this is just ``self.second``. If the function takes multiple arguments and returns a basic type, this should be the final ``.second`` after following all complex ...
Gives the final return type for this function. If the function takes a single argument, this is just ``self.second``. If the function takes multiple arguments and returns a basic type, this should be the final ``.second`` after following all complex types. That is the implementation ...
return_type
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
MIT
def argument_types(self) : u""" Gives the types of all arguments to this function. For functions returning a basic type, we grab all ``.first`` types until ``.second`` is no longer a ``ComplexType``. That logic is implemented here in the base class. If you have a higher-o...
Gives the types of all arguments to this function. For functions returning a basic type, we grab all ``.first`` types until ``.second`` is no longer a ``ComplexType``. That logic is implemented here in the base class. If you have a higher-order function that returns a function itself...
argument_types
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
MIT
def substitute_any_type(self, basic_types ) : u""" Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this complex type with each of those basic types. """ substitutions = [] for first_type in substitute_any_type(se...
Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this complex type with each of those basic types.
substitute_any_type
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
MIT
def _set_type(self, other_type = ANY_TYPE, signature=None) : u""" We override this method to do just one thing on top of ``ApplicationExpression._set_type``. In lambda expressions of the form /x F(x), where the function is F and the argument is x, we can use the type of F to...
We override this method to do just one thing on top of ``ApplicationExpression._set_type``. In lambda expressions of the form /x F(x), where the function is F and the argument is x, we can use the type of F to infer the type of x. That is, if F is of type <a, b>, we can resolve the type...
_set_type
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
MIT
def substitute_any_type(type_ , basic_types ) : u""" Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types, and returns a list with all possible combinations. Note that this substitution is unconstrained. That is,...
Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types, and returns a list with all possible combinations. Note that this substitution is unconstrained. That is, If you have a type with placeholders, <#1,#1> for example, this may substitute the p...
substitute_any_type
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
MIT
def _get_complex_type_production(complex_type ) : u""" Takes a complex type (without any placeholders), gets its return value, and returns a single production (perhaps with multiple arguments) that produces the return value. For example, if the complex is ``<a,<<b,c>,d>>`...
Takes a complex type (without any placeholders), gets its return value, and returns a single production (perhaps with multiple arguments) that produces the return value. For example, if the complex is ``<a,<<b,c>,d>>``, this gives the following tuple: ``('d', 'd -> [<a,<<b,c>,d>, a, <b,c>])``
_get_complex_type_production
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py
MIT
def get_strings_from_utterance(tokenized_utterance ) : u""" Based on the current utterance, return a dictionary where the keys are the strings in the utterance that map to lists of the token indices that they are linked to. """ string_linking_scores ...
Based on the current utterance, return a dictionary where the keys are the strings in the utterance that map to lists of the token indices that they are linked to.
get_strings_from_utterance
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py
MIT
def init_all_valid_actions(self) : u""" We initialize the valid actions with the global actions. We then iterate through the utterances up to and including the current utterance and add the valid strings. """ valid_actions = deepcopy(...
We initialize the valid actions with the global actions. We then iterate through the utterances up to and including the current utterance and add the valid strings.
init_all_valid_actions
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py
MIT
def get_grammar_str(self) : u""" Generate a string that can be used to instantiate a ``Grammar`` object. The string is a sequence of rules that define the grammar. """ grammar_str_with_context = self.sql_table_context.grammar_str numbers = [number.split(u" -> ")[1]....
Generate a string that can be used to instantiate a ``Grammar`` object. The string is a sequence of rules that define the grammar.
get_grammar_str
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py
MIT
def all_possible_actions(self) : u""" Return a sorted list of strings representing all possible actions of the form: nonterminal -> [right_hand_side] """ all_actions = set() for _, action_list in list(self.valid_actions.items()): for action in acti...
Return a sorted list of strings representing all possible actions of the form: nonterminal -> [right_hand_side]
all_possible_actions
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py
MIT
def get_agenda_for_sentence(self, sentence , add_paths_to_agenda = False) : u""" Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The ``agenda`` can be used while by a par...
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The ``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This is a simplistic mapping at this point, and can be expanded. Parameters ---------- sent...
get_agenda_for_sentence
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def _get_number_productions(sentence ) : u""" Gathers all the numbers in the sentence, and returns productions that lead to them. """ # The mapping here is very simple and limited, which also shouldn't be a problem # because numbers seem to be represented fairly r...
Gathers all the numbers in the sentence, and returns productions that lead to them.
_get_number_productions
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def _add_nonterminal_productions(self, agenda ) : u""" Given a partially populated agenda with (mostly) terminal productions, this method adds the nonterminal productions that lead from the root to the terminal productions. """ nonterminal_productions = set(...
Given a partially populated agenda with (mostly) terminal productions, this method adds the nonterminal productions that lead from the root to the terminal productions.
_add_nonterminal_productions
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def execute(self, logical_form ) : u""" Execute the logical form. The top level function is an assertion function (see below). We just parse the string into a list and pass the whole thing to ``_execute_assertion`` and let the method deal with it. This is because the dataset c...
Execute the logical form. The top level function is an assertion function (see below). We just parse the string into a list and pass the whole thing to ``_execute_assertion`` and let the method deal with it. This is because the dataset contains sentences (instead of questions), and they...
execute
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def _execute_assertion(self, sub_expression ) : u""" Assertion functions are boolean functions. They are of two types: 1) Exists functions: They take one argument, a set and check whether it is not empty. Syntax: ``(exists_function function_returning_entities)`` Examp...
Assertion functions are boolean functions. They are of two types: 1) Exists functions: They take one argument, a set and check whether it is not empty. Syntax: ``(exists_function function_returning_entities)`` Example: ``(object_exists (black (top all_objects)))`` ("There is a black obj...
_execute_assertion
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def _execute_box_filter(self, sub_expression ) : u""" Box filtering functions either apply a filter on a set of boxes and return the filtered set, or return all the boxes. The elements should evaluate to one of the following: ``(box_filtering_function ...
Box filtering functions either apply a filter on a set of boxes and return the filtered set, or return all the boxes. The elements should evaluate to one of the following: ``(box_filtering_function set_to_filter constant)`` or ``all_boxes`` In the first kind of forms, t...
_execute_box_filter
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def _execute_object_filter(self, sub_expression ) : u""" Object filtering functions should either be a string referring to all objects, or list which executes to a filtering operation. The elements should evaluate to one of the following: (objec...
Object filtering functions should either be a string referring to all objects, or list which executes to a filtering operation. The elements should evaluate to one of the following: (object_filtering_function object_set) ((negate_filter object_filtering_function) object_...
_execute_object_filter
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def _execute_constant(sub_expression ): u""" Acceptable constants are numbers or strings starting with `shape_` or `color_` """ if not isinstance(sub_expression, unicode): logger.error(u"Invalid constant: %s", sub_expression) raise ExecutionError(u"Invalid con...
Acceptable constants are numbers or strings starting with `shape_` or `color_`
_execute_constant
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def _get_objects_with_same_attribute(objects , attribute_function ) : u""" Returns the set of objects for which the attribute function returns an attribute value that is most frequent in the initial set, i...
Returns the set of objects for which the attribute function returns an attribute value that is most frequent in the initial set, if the frequency is greater than 1. If not, all objects have different attribute values, and this method returns an empty set.
_get_objects_with_same_attribute
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def touch_object(self, objects ) : u""" Returns all objects that touch the given set of objects. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set = set() for box, box_objects in list(objects_per_box.items()): ...
Returns all objects that touch the given set of objects.
touch_object
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def _objects_touch_each_other(cls, object1 , object2 ) : u""" Returns true iff the objects touch each other. """ in_vertical_range = object1.y_loc <= object2.y_loc + object2.size and\ object1.y_loc + object1.size >= object2.y_loc i...
Returns true iff the objects touch each other.
_objects_touch_each_other
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def top(self, objects ) : u""" Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each box. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set = set() for _, box_obje...
Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each box.
top
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def bottom(self, objects ) : u""" Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for each box. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set = set() for _, bo...
Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for each box.
bottom
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def above(self, objects ) : u""" Returns the set of objects in the same boxes that are above the given objects. That is, if the input is a set of two objects, one in each box, we will return a union of the objects above the first object in the first box, and tho...
Returns the set of objects in the same boxes that are above the given objects. That is, if the input is a set of two objects, one in each box, we will return a union of the objects above the first object in the first box, and those above the second object in the second box.
above
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def below(self, objects ) : u""" Returns the set of objects in the same boxes that are below the given objects. That is, if the input is a set of two objects, one in each box, we will return a union of the objects below the first object in the first box, and tho...
Returns the set of objects in the same boxes that are below the given objects. That is, if the input is a set of two objects, one in each box, we will return a union of the objects below the first object in the first box, and those below the second object in the second box.
below
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def _separate_objects_by_boxes(self, objects ) : u""" Given a set of objects, separate them by the boxes they belong to and return a dict. """ objects_per_box = defaultdict(list) for box in self._boxes: fo...
Given a set of objects, separate them by the boxes they belong to and return a dict.
_separate_objects_by_boxes
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py
MIT
def _remove_action_from_type(valid_actions , type_ , filter_function ) : u""" Finds the production rule matching the filter function in the given type's valid action list, and ...
Finds the production rule matching the filter function in the given type's valid action list, and removes it. If there is more than one matching function, we crash.
_remove_action_from_type
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/wikitables_world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/wikitables_world.py
MIT
def nltk_tree_to_logical_form(tree ) : u""" Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted into the correct number of parentheses. """ # nltk.Tr...
Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted into the correct number of parentheses.
nltk_tree_to_logical_form
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py
MIT
def is_terminal(self, symbol ) : u""" This function will be called on nodes of a logical form tree, which are either non-terminal symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True`` if the given symbol is a terminal symbol. """ ...
This function will be called on nodes of a logical form tree, which are either non-terminal symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True`` if the given symbol is a terminal symbol.
is_terminal
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py
MIT
def get_paths_to_root(self, action , max_path_length = 20, beam_size = 30, max_num_paths = 10) : u""" For a given action, returns at most ``max_num_paths`` paths t...
For a given action, returns at most ``max_num_paths`` paths to the root (production with ``START_SYMBOL``) that are not longer than ``max_path_length``.
get_paths_to_root
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py
MIT
def parse_logical_form(self, logical_form , remove_var_function = True) : u""" Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression. Parameters ---------- ...
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression. Parameters ---------- logical_form : ``str`` Logical form to parse remove_var_function : ``bool`` (optional) ``var`` is a special function that some lang...
parse_logical_form
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py
MIT
def get_action_sequence(self, expression ) : u""" Returns the sequence of actions (as strings) that resulted in the given expression. """ # Starting with the type of the whole expression return self._get_transitions(expression, ...
Returns the sequence of actions (as strings) that resulted in the given expression.
get_action_sequence
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py
MIT
def get_logical_form(self, action_sequence , add_var_function = True) : u""" Takes an action sequence and constructs a logical form from it. This is useful if you want to get a logical form from a decoded sequence of actions...
Takes an action sequence and constructs a logical form from it. This is useful if you want to get a logical form from a decoded sequence of actions generated by a transition based semantic parser. Parameters ---------- action_sequence : ``List[str]`` The seq...
get_logical_form
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py
MIT
def _construct_node_from_actions(self, current_node , remaining_actions , add_var_function ) : u""" Given a current node in the logical form tree, an...
Given a current node in the logical form tree, and a list of actions in an action sequence, this method fills in the children of the current node from the action sequence, then returns whatever actions are left. For example, we could get a node with type ``c``, and an action sequence t...
_construct_node_from_actions
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py
MIT
def _infer_num_arguments(cls, type_signature ) : u""" Takes a type signature and infers the number of arguments the corresponding function takes. Examples: e -> 0 <r,e> -> 1 <e,<e,t>> -> 2 <b,<<b,#1>,<#1,b>>> -> 3 """ if n...
Takes a type signature and infers the number of arguments the corresponding function takes. Examples: e -> 0 <r,e> -> 1 <e,<e,t>> -> 2 <b,<<b,#1>,<#1,b>>> -> 3
_infer_num_arguments
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py
MIT
def _process_nested_expression(self, nested_expression) : u""" ``nested_expression`` is the result of parsing a logical form in Lisp format. We process it recursively and return a string in the format that NLTK's ``LogicParser`` would understand. """ expression_is_l...
``nested_expression`` is the result of parsing a logical form in Lisp format. We process it recursively and return a string in the format that NLTK's ``LogicParser`` would understand.
_process_nested_expression
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py
MIT
def _add_name_mapping(self, name , translated_name , name_type = None): u""" Utility method to add a name and its translation to the local name mapping, and the corresponding signature, if available to the local type signatures. This method also updates the reverse name map...
Utility method to add a name and its translation to the local name mapping, and the corresponding signature, if available to the local type signatures. This method also updates the reverse name mapping.
_add_name_mapping
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/semparse/worlds/world.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py
MIT
def make_app(include_packages = ()) : u""" Creates a Flask app that serves up a simple configuration wizard. """ # Load modules for package_name in include_packages: import_submodules(package_name) app = Flask(__name__) # pylint: disable=invalid-name @app.er...
Creates a Flask app that serves up a simple configuration wizard.
make_app
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/service/config_explorer.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/service/config_explorer.py
MIT
def make_app(predictor , field_names = None, static_dir = None, sanitizer = None, title = u"AllenNLP Demo") : u""" Creates a Flask app that serves up the provided ``Predictor`` along wi...
Creates a Flask app that serves up the provided ``Predictor`` along with a front-end for interacting with it. If you want to use the built-in bare-bones HTML, you must provide the field names for the inputs (which will be used both as labels and as the keys in the JSON that gets sent to the predic...
make_app
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/service/server_simple.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/service/server_simple.py
MIT
def predict() : # pylint: disable=unused-variable u"""make a prediction using the specified model and return the results""" if request.method == u"OPTIONS": return Response(response=u"", status=200) data = request.get_json() prediction = predictor.predict_json(d...
make a prediction using the specified model and return the results
predict
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/service/server_simple.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/service/server_simple.py
MIT
def _html(title , field_names ) : u""" Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from the configured model. """ inputs = u''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name) for fie...
Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from the configured model.
_html
python
plasticityai/magnitude
pymagnitude/third_party/allennlp/service/server_simple.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/service/server_simple.py
MIT