docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Creates a new intent, optionally checking the cache first
Args:
name (str): The associated name of the intent
lines (list<str>): All the sentences that should activate the intent
reload_cache: Whether to ignore cached intent if exists | def add_intent(self, name, lines, reload_cache=False):
self.intents.add(name, lines, reload_cache)
self.padaos.add_intent(name, lines)
self.must_train = True | 586,398 |
Adds an entity that matches the given lines.
Example:
self.add_intent('weather', ['will it rain on {weekday}?'])
self.add_entity('{weekday}', ['monday', 'tuesday', 'wednesday']) # ...
Args:
name (str): The name of the entity
lines (list<str>): Lines of ... | def add_entity(self, name, lines, reload_cache=False):
Entity.verify_name(name)
self.entities.add(Entity.wrap_name(name), lines, reload_cache)
self.padaos.add_entity(name, lines)
self.must_train = True | 586,399 |
Loads an entity, optionally checking the cache first
Args:
name (str): The associated name of the entity
file_name (str): The location of the entity file
reload_cache (bool): Whether to refresh all of cache | def load_entity(self, name, file_name, reload_cache=False):
Entity.verify_name(name)
self.entities.load(Entity.wrap_name(name), file_name, reload_cache)
with open(file_name) as f:
self.padaos.add_entity(name, f.read().split('\n'))
self.must_train = True | 586,400 |
Loads an intent, optionally checking the cache first
Args:
name (str): The associated name of the intent
file_name (str): The location of the intent file
reload_cache (bool): Whether to refresh all of cache | def load_intent(self, name, file_name, reload_cache=False):
self.intents.load(name, file_name, reload_cache)
with open(file_name) as f:
self.padaos.add_intent(name, f.read().split('\n'))
self.must_train = True | 586,401 |
Trains in a subprocess which provides a timeout guarantees everything shuts down properly
Args:
See <train>
Returns:
bool: True for success, False if timed out | def train_subprocess(self, *args, **kwargs):
ret = call([
sys.executable, '-m', 'padatious', 'train', self.cache_dir,
'-d', json.dumps(self.serialized_args),
'-a', json.dumps(args),
'-k', json.dumps(kwargs),
])
if ret == 2:
rai... | 586,406 |
Tests all the intents against the query and returns
data on how well each one matched against the query
Args:
query (str): Input sentence to test against intents
Returns:
list<MatchData>: List of intent matches
See calc_intent() for a description of the returned ... | def calc_intents(self, query):
if self.must_train:
self.train()
intents = {} if self.train_thread and self.train_thread.is_alive() else {
i.name: i for i in self.intents.calc_intents(query, self.entities)
}
sent = tokenize(query)
for perfect_match... | 586,407 |
Tests all the intents against the query and returns
match data of the best intent
Args:
query (str): Input sentence to test against intents
Returns:
MatchData: Best intent match | def calc_intent(self, query):
matches = self.calc_intents(query)
if len(matches) == 0:
return MatchData('', '')
best_match = max(matches, key=lambda x: x.conf)
best_matches = (match for match in matches if match.conf == best_match.conf)
return min(best_matche... | 586,408 |
Creates a unique binary id for the given lines
Args:
lines (list<str>): List of strings that should be collectively hashed
Returns:
bytearray: Binary hash | def lines_hash(lines):
x = xxh32()
for i in lines:
x.update(i.encode())
return x.digest() | 586,447 |
Converts a single sentence into a list of individual significant units
Args:
sentence (str): Input string ie. 'This is a sentence.'
Returns:
list<str>: List of tokens ie. ['this', 'is', 'a', 'sentence'] | def tokenize(sentence):
tokens = []
class Vars:
start_pos = -1
last_type = 'o'
def update(c, i):
if c.isalpha() or c in '-{}':
t = 'a'
elif c.isdigit() or c == '#':
t = 'n'
elif c.isspace():
t = 's'
else:
... | 586,448 |
Checks for duplicate inputs and if there are any,
remove one and set the output to the max of the two outputs
Args:
inputs (list<list<float>>): Array of input vectors
outputs (list<list<float>>): Array of output vectors
Returns:
tuple<inputs, outputs>: The modified inputs and outputs | def resolve_conflicts(inputs, outputs):
data = {}
for inp, out in zip(inputs, outputs):
tup = tuple(inp)
if tup in data:
data[tup].append(out)
else:
data[tup] = [out]
inputs, outputs = [], []
for inp, outs in data.items():
inputs.append(list(... | 586,449 |
Parse a time expression, returning it as a number of seconds. If
possible, the return value will be an `int`; if this is not
possible, the return will be a `float`. Returns `None` if a time
expression cannot be parsed from the given string.
Arguments:
- `sval`: the string value to parse
>>> ti... | def timeparse(sval):
match = re.match(r'\s*' + TIMEFORMAT + r'\s*$', sval, re.I)
if not match or not match.group(0).strip():
return
mdict = match.groupdict()
return sum(
MULTIPLIERS[k] * cast(v) for (k, v) in mdict.items() if v is not None) | 586,759 |
``flake8`` api method to register new plugin options.
See :class:`.Configuration` docs for detailed options reference.
Arguments:
parser: ``flake8`` option parser instance. | def add_options(cls, parser: OptionManager) -> None:
parser.add_option(
'--eradicate-aggressive',
default=False,
help=(
'Enables aggressive mode for eradicate; '
'this may result in false positives'
),
action='s... | 586,763 |
N-hot-encoded feature hashing.
Args:
feature (str): Target feature represented as string.
dims (list of int): Number of dimensions for each hash value.
seeds (list of float): Seed of each hash function (mmh3).
Returns:
numpy 1d array: n-hot-encoded feature vector for `s`. | def n_feature_hash(feature, dims, seeds):
vec = np.zeros(sum(dims))
offset = 0
for seed, dim in zip(seeds, dims):
vec[offset:(offset + dim)] = feature_hash(feature, dim, seed)
offset += dim
return vec | 586,914 |
Feature hashing.
Args:
feature (str): Target feature represented as string.
dim (int): Number of dimensions for a hash value.
seed (float): Seed of a MurmurHash3 hash function.
Returns:
numpy 1d array: one-hot-encoded feature vector for `s`. | def feature_hash(feature, dim, seed=123):
vec = np.zeros(dim)
i = mmh3.hash(feature, seed) % dim
vec[i] = 1
return vec | 586,915 |
Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives. | def count_true_positive(truth, recommend):
tp = 0
for r in recommend:
if r in truth:
tp += 1
return tp | 586,935 |
Recall@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Recall@k. | def recall(truth, recommend, k=None):
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(truth.size) | 586,936 |
Precision@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Precision@k. | def precision(truth, recommend, k=None):
if len(recommend) == 0:
if len(truth) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(k) | 586,937 |
Average Precision (AP).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AP. | def average_precision(truth, recommend):
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
tp = accum = 0.
for n in range(recommend.size):
if recommend[n] in truth:
tp += 1.
accum += (tp / (n + 1.))
return accum / truth.size | 586,938 |
Area under the ROC curve (AUC).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AUC. | def auc(truth, recommend):
tp = correct = 0.
for r in recommend:
if r in truth:
# keep track number of true positives placed before
tp += 1.
else:
correct += tp
# number of all possible tp-fp pairs
pairs = tp * (recommend.size - tp)
# if ther... | 586,939 |
Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR. | def reciprocal_rank(truth, recommend):
for n in range(recommend.size):
if recommend[n] in truth:
return 1. / (n + 1)
return 0. | 586,940 |
Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR. | def mpr(truth, recommend):
if len(recommend) == 0 and len(truth) == 0:
return 0. # best
elif len(truth) == 0 or len(truth) == 0:
return 100. # worst
accum = 0.
n_recommend = recommend.size
for t in truth:
r = np.where(recommend == t)[0][0] / float(n_recommend)
... | 586,941 |
Normalized Discounted Cumulative Grain (NDCG).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: NDCG. | def ndcg(truth, recommend, k=None):
if k is None:
k = len(recommend)
def idcg(n_possible_truth):
res = 0.
for n in range(n_possible_truth):
res += 1. / np.log2(n + 2)
return res
dcg = 0.
for n, r in enumerate(recommend[:k]):
if r not in truth:
... | 586,942 |
For new users, append their information into the dictionaries.
Args:
user (User): User. | def register_user(self, user):
self.users[user.index] = {'known_items': set()}
self.n_user += 1 | 586,947 |
Set/initialize parameters.
Args:
recommender (Recommender): Instance of a recommender which has been initialized.
repeat (boolean): Choose whether the same item can be repeatedly interacted by the same user.
maxlen (int): Size of an item buffer which stores most recently obs... | def __init__(self, recommender, repeat=True, maxlen=None, debug=False):
self.rec = recommender
self.feature_rec = issubclass(recommender.__class__, FeatureRecommenderMixin)
self.repeat = repeat
# create a ring buffer
# save items which are observed in most recent `maxl... | 586,949 |
Train a model using the first 30% positive events to avoid cold-start.
Evaluation of this batch training is done by using the next 20% positive events.
After the batch SGD training, the models are incrementally updated by using the 20% test events.
Args:
train_events (list of Event... | def fit(self, train_events, test_events, n_epoch=1):
# make initial status for batch training
for e in train_events:
self.__validate(e)
self.rec.users[e.user.index]['known_items'].add(e.item.index)
self.item_buffer.append(e.item.index)
# for batch ev... | 586,950 |
Iterate recommend/update procedure and compute incremental recall.
Args:
test_events (list of Event): Positive test events.
Returns:
list of tuples: (rank, recommend time, update time) | def evaluate(self, test_events):
for i, e in enumerate(test_events):
self.__validate(e)
# target items (all or unobserved depending on a detaset)
unobserved = set(self.item_buffer)
if not self.repeat:
unobserved -= self.rec.users[e.user.i... | 586,951 |
Batch update called by the fitting method.
Args:
train_events (list of Event): Positive training events.
test_events (list of Event): Test events.
n_epoch (int): Number of epochs for the batch training. | def __batch_update(self, train_events, test_events, n_epoch):
for epoch in range(n_epoch):
# SGD requires us to shuffle events in each iteration
# * if n_epoch == 1
# => shuffle is not required because it is a deterministic training (i.e. matrix sketching)
... | 586,955 |
Evaluate the current model by using the given test events.
Args:
test_events (list of Event): Current model is evaluated by these events.
Returns:
float: Mean Percentile Rank for the test set. | def __batch_evaluate(self, test_events):
percentiles = np.zeros(len(test_events))
all_items = set(self.item_buffer)
for i, e in enumerate(test_events):
# check if the data allows users to interact the same items repeatedly
unobserved = all_items
if ... | 586,956 |
Create a CommutativePatternsParts instance.
Args:
operation:
The type of the commutative operation. Must be a subclass of :class:`.Operation` with
:attr:`~.Operation.commutative` set to ``True``.
*expressions:
The operands of the commutati... | def __init__(self, operation: Type[Operation], *expressions: Expression) -> None:
self.operation = operation
self.length = len(expressions)
self.constant = Multiset() # type: Multiset
self.syntactic = Multiset() # type: Multiset
self.sequence_variables = Multiset() #... | 586,968 |
Check whether the given *subject* matches given *pattern*.
Args:
subject:
The subject.
pattern:
The pattern.
Returns:
True iff the subject matches the pattern. | def is_match(subject: Expression, pattern: Expression) -> bool:
return any(True for _ in match(subject, pattern)) | 586,978 |
Rename the variables in the expression according to the given dictionary.
Args:
expression:
The expression in which the variables are renamed.
renaming:
The renaming dictionary. Maps old variable names to new ones.
Variable names not occuring in the dictionary ar... | def rename_variables(expression: Expression, renaming: Dict[str, str]) -> Expression:
if isinstance(expression, Operation):
if hasattr(expression, 'variable_name'):
variable_name = renaming.get(expression.variable_name, expression.variable_name)
return create_operation_expressio... | 587,013 |
Concatenate the given flatterms to a single flatterm.
Args:
*flatterms:
The flatterms which are concatenated.
Returns:
The concatenated flatterms. | def merged(cls, *flatterms: 'FlatTerm') -> 'FlatTerm':
return cls(cls._combined_wildcards_iter(sum(flatterms, cls.empty()))) | 587,076 |
Match the given subject against all patterns in the net.
Args:
subject:
The subject that is matched. Must be constant.
Yields:
A tuple :code:`(final label, substitution)`, where the first component is the final label associated with
the pattern as gi... | def match(self, subject: Union[Expression, FlatTerm]) -> Iterator[Tuple[T, Substitution]]:
for index in self._match(subject):
pattern, label = self._patterns[index]
subst = Substitution()
if subst.extract_substitution(subject, pattern.expression):
for... | 587,097 |
Check if the given subject matches any pattern in the net.
Args:
subject:
The subject that is matched. Must be constant.
Returns:
True, if any pattern matches the subject. | def is_match(self, subject: Union[Expression, FlatTerm]) -> bool:
try:
next(self.match(subject))
except StopIteration:
return False
return True | 587,098 |
Add a pattern that will be recognized by the matcher.
Args:
pattern:
The pattern to add.
Returns:
An internal index for the pattern.
Raises:
ValueError:
If the pattern does not have the correct form.
TypeError:
... | def add(self, pattern: Pattern) -> int:
inner = pattern.expression
if self.operation is None:
if not isinstance(inner, Operation) or isinstance(inner, CommutativeOperation):
raise TypeError("Pattern must be a non-commutative operation.")
self.operation = ... | 587,101 |
Check if a pattern can be matched with a sequence matcher.
Args:
pattern:
The pattern to check.
Returns:
True, iff the pattern can be matched with a sequence matcher. | def can_match(cls, pattern: Pattern) -> bool:
if not isinstance(pattern.expression, Operation) or isinstance(pattern.expression, CommutativeOperation):
return False
if op_len(pattern.expression) < 3:
return False
first, *_, last = op_iter(pattern.expression)
... | 587,103 |
Match the given subject against all patterns in the sequence matcher.
Args:
subject:
The subject that is matched. Must be constant.
Yields:
A tuple :code:`(pattern, substitution)` for every matching pattern. | def match(self, subject: Expression) -> Iterator[Tuple[Pattern, Substitution]]:
if not isinstance(subject, self.operation):
return
subjects = list(op_iter(subject))
flatterms = [FlatTerm(o) for o in subjects]
for i in range(len(flatterms)):
flatterm = F... | 587,104 |
r"""Tries to match the given *pattern* to the given *subject*.
Yields each match in form of a substitution.
Parameters:
subject:
An subject to match.
pattern:
The pattern to match.
Yields:
All possible match substitutions.
Raises:
ValueError:
... | def match(subject: Expression, pattern: Pattern) -> Iterator[Substitution]:
r
if not is_constant(subject):
raise ValueError("The subject for matching must be constant.")
global_constraints = [c for c in pattern.constraints if not c.variables]
local_constraints = set(c for c in pattern.constraint... | 587,105 |
Add a new pattern to the matcher.
Equivalent patterns are not added again. However, patterns that are structurally equivalent,
but have different constraints or different variable names are distinguished by the matcher.
Args:
pattern: The pattern to add.
Returns:
... | def _internal_add(self, pattern: Pattern, label, renaming) -> int:
pattern_index = len(self.patterns)
renamed_constraints = [c.with_renamed_vars(renaming) for c in pattern.local_constraints]
constraint_indices = [self._add_constraint(c, pattern_index) for c in renamed_constraints]
... | 587,133 |
Match the subject against all the matcher's patterns.
Args:
subject: The subject to match.
Yields:
For every match, a tuple of the matching pattern and the match substitution. | def match(self, subject: Expression) -> Iterator[Tuple[Expression, Substitution]]:
return _MatchIter(self, subject) | 587,136 |
Add a new rule to the replacer.
Args:
rule:
The rule to add. | def add(self, rule: 'functions.ReplacementRule') -> None:
self.matcher.add(rule.pattern, rule.replacement) | 587,150 |
Create a `Wildcard` that matches a single argument with a default value.
If the wildcard does not match, the substitution will contain the
default value instead.
Args:
name:
The name for the wildcard.
default:
The default value of the wil... | def optional(name, default) -> 'Wildcard':
return Wildcard(min_count=1, fixed_size=True, variable_name=name, optional=default) | 587,202 |
Create a `SymbolWildcard` that matches a single `Symbol` argument.
Args:
name:
Optional variable name for the wildcard.
symbol_type:
An optional subclass of `Symbol` to further limit which kind of symbols are
matched by the wildcard.
... | def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard':
if isinstance(name, type) and issubclass(name, Symbol) and symbol_type is Symbol:
return SymbolWildcard(name)
return SymbolWildcard(symbol_type, variable_name=name) | 587,203 |
Encode int into a string preserving order
It is using 2, 4 or 6 bits per coding character (default 6).
Parameters:
code: int Positive integer.
bits_per_char: int The number of bits per coding character.
Returns:
str: the encoded integer | def encode_int(code, bits_per_char=6):
if code < 0:
raise ValueError('Only positive ints are allowed!')
if bits_per_char == 6:
return _encode_int64(code)
if bits_per_char == 4:
return _encode_int16(code)
if bits_per_char == 2:
return _encode_int4(code)
raise Va... | 587,291 |
Decode string into int assuming encoding with `encode_int()`
It is using 2, 4 or 6 bits per coding character (default 6).
Parameters:
tag: str Encoded integer.
bits_per_char: int The number of bits per coding character.
Returns:
int: the decoded string | def decode_int(tag, bits_per_char=6):
if bits_per_char == 6:
return _decode_int64(tag)
if bits_per_char == 4:
return _decode_int16(tag)
if bits_per_char == 2:
return _decode_int4(tag)
raise ValueError('`bits_per_char` must be in {6, 4, 2}') | 587,292 |
Convert hashcode to (x, y).
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
Pure python implementation.
Parameters:
hashcode: int Hashcode to decode [0, dim**2)
dim: int Number of coding points each x, y value can t... | def _hash2xy(hashcode, dim):
assert(hashcode <= dim * dim - 1)
x = y = 0
lvl = 1
while (lvl < dim):
rx = 1 & (hashcode >> 1)
ry = 1 & (hashcode ^ rx)
x, y = _rotate(lvl, x, y, rx, ry)
x += lvl * rx
y += lvl * ry
hashcode >>= 2
lvl <<= 1
re... | 587,303 |
Get user info for GBDX S3, put into instance vars for convenience.
Args:
None.
Returns:
Dictionary with S3 access key, S3 secret key, S3 session token,
user bucket and user prefix (dict). | def _load_info(self):
url = '%s/prefix?duration=36000' % self.base_url
r = self.gbdx_connection.get(url)
r.raise_for_status()
return r.json() | 587,612 |
Download content from bucket/prefix/location.
Location can be a directory or a file (e.g., my_dir or my_dir/my_image.tif)
If location is a directory, all files in the directory are
downloaded. If it is a file, then that file is downloaded.
Args:
location (str)... | def download(self, location, local_dir='.'):
self.logger.debug('Getting S3 info')
bucket = self.info['bucket']
prefix = self.info['prefix']
self.logger.debug('Connecting to S3')
s3conn = self.client
# remove head and/or trail backslash from location
lo... | 587,613 |
Delete content in bucket/prefix/location.
Location can be a directory or a file (e.g., my_dir or my_dir/my_image.tif)
If location is a directory, all files in the directory are deleted.
If it is a file, then that file is deleted.
Args:
location (str): S3 locat... | def delete(self, location):
bucket = self.info['bucket']
prefix = self.info['prefix']
self.logger.debug('Connecting to S3')
s3conn = self.client
# remove head and/or trail backslash from location
if location[0] == '/':
location = location[1:]
... | 587,614 |
Retrieves the IDAHO image records associated with a given catid.
Args:
catid (str): The source catalog ID from the platform catalog.
aoi_wkt (str): The well known text of the area of interest.
Returns:
results (json): The full catalog-search response for IDAHO images
... | def get_images_by_catid_and_aoi(self, catid, aoi_wkt):
self.logger.debug('Retrieving IDAHO metadata')
# use the footprint to get the IDAHO id
url = '%s/search' % self.base_url
body = {"filters": ["catalogID = '%s'" % catid],
"types": ["IDAHOImage"],
... | 587,660 |
Retrieves the IDAHO image records associated with a given catid.
Args:
catid (str): The source catalog ID from the platform catalog.
Returns:
results (json): The full catalog-search response for IDAHO images
within the catID. | def get_images_by_catid(self, catid):
self.logger.debug('Retrieving IDAHO metadata')
# get the footprint of the catid's strip
footprint = self.catalog.get_strip_footprint_wkt(catid)
# try to convert from multipolygon to polygon:
try:
footprint = from_wkt(f... | 587,661 |
Describe the result set of a catalog search for IDAHO images.
Args:
idaho_image_results (dict): Result set of catalog search.
Returns:
results (json): The full catalog-search response for IDAHO images
corresponding to the given catID. | def describe_images(self, idaho_image_results):
results = idaho_image_results['results']
# filter only idaho images:
results = [r for r in results if 'IDAHOImage' in r['type']]
self.logger.debug('Describing %s IDAHO images.' % len(results))
# figure out which catids a... | 587,662 |
Create a leaflet viewer html file for viewing idaho images.
Args:
idaho_image_results (dict): IDAHO image result set as returned from
the catalog.
filename (str): Where to save output html file. | def create_leaflet_viewer(self, idaho_image_results, filename):
description = self.describe_images(idaho_image_results)
if len(description) > 0:
functionstring = ''
for catid, images in description.items():
for partnum, part in images['parts'].items():
... | 587,665 |
Checks to see if a CatalogID has been ordered or not.
Args:
catalogID (str): The catalog ID from the platform catalog.
Returns:
ordered (bool): Whether or not the image has been ordered | def is_ordered(cat_id):
url = 'https://rda.geobigdata.io/v1/stripMetadata/{}'.format(cat_id)
auth = Auth()
r = _req_with_retries(auth.gbdx_connection, url)
if r is not None:
return r.status_code == 200
return False | 587,669 |
Checks to see if a CatalogID can be atmos. compensated or not.
Args:
catalogID (str): The catalog ID from the platform catalog.
Returns:
available (bool): Whether or not the image can be acomp'd | def can_acomp(cat_id):
url = 'https://rda.geobigdata.io/v1/stripMetadata/{}/capabilities'.format(cat_id)
auth = Auth()
r = _req_with_retries(auth.gbdx_connection, url)
try:
data = r.json()
return data['acompVersion'] is not None
except:
return False | 587,670 |
Construct an instance of GBDX Task
Args:
__task_type: name of the task
**kwargs: key=value pairs for inputs to set on the task
Returns:
An instance of Task. | def __init__(self, __task_type, **kwargs):
self.name = __task_type + '_' + str(uuid.uuid4())[:8]
self.name = self.name.replace(':','_') # keep colon out of task name
self.type = __task_type
task_registry = TaskRegistry()
self.definition = task_registry.get_definition(_... | 587,685 |
Set input values on task
Args:
arbitrary_keys: values for the keys
Returns:
None | def set(self, **kwargs):
for port_name, port_value in kwargs.items():
# Support both port and port.value
if hasattr(port_value, 'value'):
port_value = port_value.value
self.inputs.__setattr__(port_name, port_value) | 587,686 |
Get a list of outputs from the workflow that are saved to S3. To get resolved locations call workflow status.
Args:
None
Returns:
list | def list_workflow_outputs(self):
workflow_outputs = []
for task in self.tasks:
for output_port_name in task.outputs._portnames:
if task.outputs.__getattribute__(output_port_name).persist:
workflow_outputs.append(task.name + ':' + output_port_name)... | 587,691 |
Generate workflow json for launching the workflow against the gbdx api
Args:
None
Returns:
json string | def generate_workflow_description(self):
if not self.tasks:
raise WorkflowError('Workflow contains no tasks, and cannot be executed.')
self.definition = self.workflow_skeleton()
if self.batch_values:
self.definition["batch_values"] = self.batch_values
... | 587,692 |
Execute the workflow.
Args:
None
Returns:
Workflow_id | def execute(self):
# if not self.tasks:
# raise WorkflowError('Workflow contains no tasks, and cannot be executed.')
# for task in self.tasks:
# self.definition['tasks'].append( task.generate_task_workflow_json() )
self.generate_workflow_description()
... | 587,693 |
Get the task IDs of a running workflow
Args:
None
Returns:
List of task IDs | def task_ids(self):
if not self.id:
raise WorkflowError('Workflow is not running. Cannot get task IDs.')
if self.batch_values:
raise NotImplementedError("Query Each Workflow Id within the Batch Workflow for task IDs.")
wf = self.workflow.get(self.id)
... | 587,694 |
Cancel a running workflow.
Args:
None
Returns:
None | def cancel(self):
if not self.id:
raise WorkflowError('Workflow is not running. Cannot cancel.')
if self.batch_values:
self.workflow.batch_workflow_cancel(self.id)
else:
self.workflow.cancel(self.id) | 587,695 |
Helper method for handling projection codes that are unknown to pyproj
Args:
prj_code (str): an epsg proj code
Returns:
projection: a pyproj projection | def get_proj(prj_code):
if prj_code in CUSTOM_PRJ:
proj = pyproj.Proj(CUSTOM_PRJ[prj_code])
else:
proj = pyproj.Proj(init=prj_code)
return proj | 587,720 |
Show a slippy map preview of the image. Requires iPython.
Args:
image (image): image object to display
zoom (int): zoom level to intialize the map, default is 16
center (list): center coordinates to initialize the map, defaults to center of image
bands (list): bands of image to disp... | def preview(image, **kwargs):
try:
from IPython.display import Javascript, HTML, display
from gbdxtools.rda.interface import RDA
from gbdxtools import Interface
gbdx = Interface()
except:
print("IPython is required to produce maps.")
return
zoom = k... | 587,721 |
Materializes images into gbdx user buckets in s3.
Note: This method is only available to RDA based image classes.
Args:
node (str): the node in the graph to materialize
bounds (list): optional bbox for cropping what gets materialized in s3
out_format (str): VECT... | def materialize(self, node=None, bounds=None, callback=None, out_format='TILE_STREAM', **kwargs):
kwargs.update({
"node": node,
"bounds": bounds,
"callback": callback,
"out_format": out_format
})
return self.rda._materialize(**kwargs) | 587,754 |
Registers a new GBDX task.
Args:
task_json (dict): Dictionary representing task definition.
json_filename (str): A full path of a file with json representing the task definition.
Only one out of task_json and json_filename should be provided.
Returns:
Res... | def register(self, task_json=None, json_filename=None):
if not task_json and not json_filename:
raise Exception("Both task json and filename can't be none.")
if task_json and json_filename:
raise Exception("Both task json and filename can't be provided.")
if js... | 587,772 |
Gets definition of a registered GBDX task.
Args:
task_name (str): Task name.
Returns:
Dictionary representing the task definition. | def get_definition(self, task_name):
r = self.gbdx_connection.get(self._base_url + '/' + task_name)
raise_for_status(r)
return r.json() | 587,773 |
Deletes a GBDX task.
Args:
task_name (str): Task name.
Returns:
Response (str). | def delete(self, task_name):
r = self.gbdx_connection.delete(self._base_url + '/' + task_name)
raise_for_status(r)
return r.text | 587,774 |
Updates a GBDX task.
Args:
task_name (str): Task name.
task_json (dict): Dictionary representing updated task definition.
Returns:
Dictionary representing the updated task definition. | def update(self, task_name, task_json):
r = self.gbdx_connection.put(self._base_url + '/' + task_name, json=task_json)
raise_for_status(r)
return r.json() | 587,775 |
Write out a geotiff file of the image
Args:
path (str): path to write the geotiff file to, default is ./output.tif
proj (str): EPSG string of projection to reproject to
spec (str): if set to 'rgb', write out color-balanced 8-bit RGB tif
bands (list): list of bands to export. If spec... | def to_geotiff(arr, path='./output.tif', proj=None, spec=None, bands=None, **kwargs):
assert has_rasterio, "To create geotiff images please install rasterio"
try:
img_md = arr.rda.metadata["image"]
x_size = img_md["tileXSize"]
y_size = img_md["tileYSize"]
except (Attr... | 587,776 |
Retrieves an AnswerFactory Recipe by id
Args:
recipe_id The id of the recipe
Returns:
A JSON representation of the recipe | def get(self, recipe_id):
self.logger.debug('Retrieving recipe by id: ' + recipe_id)
url = '%(base_url)s/recipe/%(recipe_id)s' % {
'base_url': self.base_url, 'recipe_id': recipe_id
}
r = self.gbdx_connection.get(url)
r.raise_for_status()
return r.json... | 587,819 |
Saves an AnswerFactory Recipe
Args:
recipe (dict): Dictionary specifying a recipe
Returns:
AnswerFactory Recipe id | def save(self, recipe):
# test if this is a create vs. an update
if 'id' in recipe and recipe['id'] is not None:
# update -> use put op
self.logger.debug("Updating existing recipe: " + json.dumps(recipe))
url = '%(base_url)s/recipe/json/%(recipe_id)s' % {
... | 587,820 |
Saves an AnswerFactory Project
Args:
project (dict): Dictionary specifying an AnswerFactory Project.
Returns:
AnswerFactory Project id | def save(self, project):
# test if this is a create vs. an update
if 'id' in project and project['id'] is not None:
# update -> use put op
self.logger.debug('Updating existing project: ' + json.dumps(project))
url = '%(base_url)s/%(project_id)s' % {
... | 587,821 |
Deletes a project by id
Args:
project_id: The project id to delete
Returns:
Nothing | def delete(self, project_id):
self.logger.debug('Deleting project by id: ' + project_id)
url = '%(base_url)s/%(project_id)s' % {
'base_url': self.base_url, 'project_id': project_id
}
r = self.gbdx_connection.delete(url)
r.raise_for_status() | 587,822 |
Create a single vector in the vector service
Args:
wkt (str): wkt representation of the geometry
item_type (str): item_type of the vector
ingest_source (str): source of the vector
attributes: a set of key-value pairs of attributes
Returns:
id... | def create_from_wkt(self, wkt, item_type, ingest_source, **attributes):
# verify the "depth" of the attributes is single layer
geojson = load_wkt(wkt).__geo_interface__
vector = {
'type': "Feature",
'geometry': geojson,
'properties': {
... | 587,835 |
Retrieves a vector. Not usually necessary because searching is the best way to find & get stuff.
Args:
ID (str): ID of the vector object
index (str): Optional. Index the object lives in. defaults to 'vector-web-s'
Returns:
record (dict): A dict object identical t... | def get(self, ID, index='vector-web-s'):
url = self.get_url % index
r = self.gbdx_connection.get(url + ID)
r.raise_for_status()
return r.json() | 587,836 |
Perform a vector services query using the QUERY API
(https://gbdxdocs.digitalglobe.com/docs/vs-query-list-vector-items-returns-default-fields)
Args:
searchAreaWkt: WKT Polygon of area to search
query: Elastic Search query
count: Maximum number of results to return
... | def query(self, searchAreaWkt, query, count=100, ttl='5m', index=default_index):
if count < 1000:
# issue a single page query
search_area_polygon = from_wkt(searchAreaWkt)
left, lower, right, upper = search_area_polygon.bounds
params = {
... | 587,837 |
Perform a vector services query using the QUERY API
(https://gbdxdocs.digitalglobe.com/docs/vs-query-list-vector-items-returns-default-fields)
Args:
searchAreaWkt: WKT Polygon of area to search
query: Elastic Search query
count: Maximum number of results to return
... | def query_iteratively(self, searchAreaWkt, query, count=100, ttl='5m', index=default_index):
search_area_polygon = from_wkt(searchAreaWkt)
left, lower, right, upper = search_area_polygon.bounds
params = {
"q": query,
"count": min(count,1000),
"ttl":... | 587,838 |
Reads data from a dask array and returns the computed ndarray matching the given bands
Args:
bands (list): band indices to read from the image. Returns bands in the order specified in the list of bands.
Returns:
ndarray: a numpy array of image data | def read(self, bands=None, **kwargs):
arr = self
if bands is not None:
arr = self[bands, ...]
return arr.compute(scheduler=threaded_get) | 587,852 |
Get a random window of a given shape from within an image
Args:
window_shape (tuple): The desired shape of the returned image as (height, width) in pixels.
Returns:
image: a new image object of the specified shape and same type | def randwindow(self, window_shape):
row = random.randrange(window_shape[0], self.shape[1])
col = random.randrange(window_shape[1], self.shape[2])
return self[:, row-window_shape[0]:row, col-window_shape[1]:col] | 587,853 |
Iterate over random windows of an image
Args:
count (int): the number of the windows to generate. Defaults to 64, if `None` will continue to iterate over random windows until stopped.
window_shape (tuple): The desired shape of each image as (height, width) in pixels.
Yields:
... | def iterwindows(self, count=64, window_shape=(256, 256)):
if count is None:
while True:
yield self.randwindow(window_shape)
else:
for i in xrange(count):
yield self.randwindow(window_shape) | 587,854 |
Return a subsetted window of a given size, centered on a geometry object
Useful for generating training sets from vector training data
Will throw a ValueError if the window is not within the image bounds
Args:
geom (shapely,geometry): Geometry to center the image on
win... | def window_at(self, geom, window_shape):
# Centroids of the input geometry may not be centered on the object.
# For a covering image we use the bounds instead.
# This is also a workaround for issue 387.
y_size, x_size = window_shape[0], window_shape[1]
bounds = box(*geom... | 587,855 |
Subsets the Image by the given bounds
Args:
bbox (list): optional. A bounding box array [minx, miny, maxx, maxy]
wkt (str): optional. A WKT geometry string
geojson (str): optional. A GeoJSON geometry dictionary
Returns:
image: an image instance of the sa... | def aoi(self, **kwargs):
g = self._parse_geoms(**kwargs)
if g is None:
return self
else:
return self[g] | 587,858 |
Returns the bounds of a geometry object in pixel coordinates
Args:
geom: Shapely geometry object or GeoJSON as Python dictionary or WKT string
clip (bool): Clip the bounds to the min/max extent of the image
Returns:
list: bounds in pixels [min x, min y, max x, max y... | def pxbounds(self, geom, clip=False):
try:
if isinstance(geom, dict):
if 'geometry' in geom:
geom = shape(geom['geometry'])
else:
geom = shape(geom)
elif isinstance(geom, BaseGeometry):
geom... | 587,859 |
Delayed warp across an entire AOI or Image
Creates a new dask image by deferring calls to the warp_geometry on chunks
Args:
dem (ndarray): optional. A DEM for warping to specific elevation planes
proj (str): optional. An EPSG proj string to project the image data into ("EPSG:32... | def warp(self, dem=None, proj="EPSG:4326", **kwargs):
try:
img_md = self.rda.metadata["image"]
x_size = img_md["tileXSize"]
y_size = img_md["tileYSize"]
except (AttributeError, KeyError):
x_size = kwargs.get("chunk_size", 256)
y_size =... | 587,861 |
Launches GBDX workflow.
Args:
workflow (dict): Dictionary specifying workflow tasks.
Returns:
Workflow id (str). | def launch(self, workflow):
# hit workflow api
try:
r = self.gbdx_connection.post(self.workflows_url, json=workflow)
try:
r.raise_for_status()
except:
print("GBDX API Status Code: %s" % r.status_code)
print("GB... | 587,901 |
Checks workflow status.
Args:
workflow_id (str): Workflow id.
Returns:
Workflow status (str). | def status(self, workflow_id):
self.logger.debug('Get status of workflow: ' + workflow_id)
url = '%(wf_url)s/%(wf_id)s' % {
'wf_url': self.workflows_url, 'wf_id': workflow_id
}
r = self.gbdx_connection.get(url)
r.raise_for_status()
return r.json()['st... | 587,902 |
Get stdout for a particular task.
Args:
workflow_id (str): Workflow id.
task_id (str): Task id.
Returns:
Stdout of the task (string). | def get_stdout(self, workflow_id, task_id):
url = '%(wf_url)s/%(wf_id)s/tasks/%(task_id)s/stdout' % {
'wf_url': self.workflows_url, 'wf_id': workflow_id, 'task_id': task_id
}
r = self.gbdx_connection.get(url)
r.raise_for_status()
return r.text | 587,903 |
Cancels a running workflow.
Args:
workflow_id (str): Workflow id.
Returns:
Nothing | def cancel(self, workflow_id):
self.logger.debug('Canceling workflow: ' + workflow_id)
url = '%(wf_url)s/%(wf_id)s/cancel' % {
'wf_url': self.workflows_url, 'wf_id': workflow_id
}
r = self.gbdx_connection.post(url, data='')
r.raise_for_status() | 587,904 |
Launches GBDX batch workflow.
Args:
batch_workflow (dict): Dictionary specifying batch workflow tasks.
Returns:
Batch Workflow id (str). | def launch_batch_workflow(self, batch_workflow):
# hit workflow api
url = '%(base_url)s/batch_workflows' % {
'base_url': self.base_url
}
try:
r = self.gbdx_connection.post(url, json=batch_workflow)
batch_workflow_id = r.json()['batch_workflow... | 587,905 |
Checks GBDX batch workflow status.
Args:
batch workflow_id (str): Batch workflow id.
Returns:
Batch Workflow status (str). | def batch_workflow_status(self, batch_workflow_id):
self.logger.debug('Get status of batch workflow: ' + batch_workflow_id)
url = '%(base_url)s/batch_workflows/%(batch_id)s' % {
'base_url': self.base_url, 'batch_id': batch_workflow_id
}
r = self.gbdx_connection.get(u... | 587,906 |
Cancels GBDX batch workflow.
Args:
batch workflow_id (str): Batch workflow id.
Returns:
Batch Workflow status (str). | def batch_workflow_cancel(self, batch_workflow_id):
self.logger.debug('Cancel batch workflow: ' + batch_workflow_id)
url = '%(base_url)s/batch_workflows/%(batch_id)s/cancel' % {
'base_url': self.base_url, 'batch_id': batch_workflow_id
}
r = self.gbdx_connection.post(... | 587,907 |
Checks imagery order status. There can be more than one image per
order and this function returns the status of all images
within the order.
Args:
order_id (str): The id of the order placed.
Returns:
List of dictionaries, one per image. Each di... | def status(self, order_id):
self.logger.debug('Get status of order ' + order_id)
url = '%(base_url)s/order/%(order_id)s' % {
'base_url': self.base_url, 'order_id': order_id
}
r = self.gbdx_connection.get(url)
r.raise_for_status()
return r.json().get(... | 587,910 |
Retrieves the strip footprint WKT string given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
includeRelationships (bool): whether to include graph links to related objects. Default False.
Returns:
record (dict): A dict object identic... | def get(self, catID, includeRelationships=False):
url = '%(base_url)s/record/%(catID)s' % {
'base_url': self.base_url, 'catID': catID
}
r = self.gbdx_connection.get(url)
r.raise_for_status()
return r.json() | 587,919 |
Retrieves the strip catalog metadata given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
Returns:
metadata (dict): A metadata dictionary .
TODO: have this return a class object with interesting information exposed. | def get_strip_metadata(self, catID):
self.logger.debug('Retrieving strip catalog metadata')
url = '%(base_url)s/record/%(catID)s?includeRelationships=false' % {
'base_url': self.base_url, 'catID': catID
}
r = self.gbdx_connection.get(url)
if r.status_code ==... | 587,920 |
Use the google geocoder to get latitude and longitude for an address string
Args:
address: any address string
Returns:
A tuple of (lat,lng) | def get_address_coords(self, address):
url = "https://maps.googleapis.com/maps/api/geocode/json?&address=" + address
r = requests.get(url)
r.raise_for_status()
results = r.json()['results']
lat = results[0]['geometry']['location']['lat']
lng = results[0]['geometr... | 587,921 |
Find and return the S3 data location given a catalog_id.
Args:
catalog_id: The catalog ID
Returns:
A string containing the s3 location of the data associated with a catalog ID. Returns
None if the catalog ID is not found, or if there is no data yet associated with ... | def get_data_location(self, catalog_id):
try:
record = self.get(catalog_id)
except:
return None
# Handle Landsat8
if 'Landsat8' in record['type'] and 'LandsatAcquisition' in record['type']:
bucket = record['properties']['bucketName']
... | 587,924 |
Return the most recent image
Args:
results: a catalog resultset, as returned from a search
types: array of types you want. optional.
sensors: array of sensornames. optional.
N: number of recent images to return. defaults to 1.
Returns:
singl... | def get_most_recent_images(self, results, types=[], sensors=[], N=1):
if not len(results):
return None
# filter on type
if types:
results = [r for r in results if r['type'] in types]
# filter on sensor
if sensors:
results = [r for r ... | 587,926 |
Instantiate a result structure.
Parameters
----------
args :
kwargs : | def __init__(self, *args, **kwargs):
super(MemoteResult, self).__init__(*args, **kwargs)
self.meta = self.setdefault("meta", dict())
self.cases = self.setdefault("tests", dict()) | 589,140 |
Instantiate a configuration structure.
Parameters
----------
args :
kwargs : | def __init__(self, *args, **kwargs):
super(ReportConfiguration, self).__init__(*args, **kwargs) | 589,216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.