input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
(time.time(), shard_key, rpc)
rpc.callback = _MakeBackendCallback(
_HandleBackendSearchResponse, query_project_names, rpc_tuple,
rpc_tuples, settings.backend_retries, unfiltered_iids_dict,
search_limit_reached_dict,
services.cache_manager.processed_invalidations_up_to,
error_responses, me_user_ids, logged_in_user_id, new_url_num,
url_params)
rpc_tuples.append(rpc_tuple)
return rpc_tuples
def _FinishBackendSearch(rpc_tuples):
"""Wait for all backend calls to complete, including any retries."""
while rpc_tuples:
active_rpcs = [rpc for (_time, _shard_key, rpc) in rpc_tuples]
# Wait for any active RPC to complete. It's callback function will
# automatically be called.
finished_rpc = real_wait_any(active_rpcs)
# Figure out which rpc_tuple finished and remove it from our list.
for rpc_tuple in rpc_tuples:
_time, _shard_key, rpc = rpc_tuple
if rpc == finished_rpc:
rpc_tuples.remove(rpc_tuple)
break
else:
raise ValueError('We somehow finished an RPC that is not in rpc_tuples')
def real_wait_any(active_rpcs):
"""Work around the blocking nature of wait_any().
wait_any() checks for any finished RPCs, and returns one if found.
If no RPC is finished, it simply blocks on the last RPC in the list.
This is not the desired behavior because we are not able to detect
FAST-FAIL RPC results and retry them if wait_any() is blocked on a
request that is taking a long time to do actual work.
Instead, we do the same check, without blocking on any individual RPC.
"""
if settings.local_mode:
# The development server has very different code for RPCs than the
# code used in the hosted environment.
return apiproxy_stub_map.UserRPC.wait_any(active_rpcs)
while True:
finished, _ = apiproxy_stub_map.UserRPC._UserRPC__check_one(active_rpcs)
if finished:
return finished
time.sleep(DELAY_BETWEEN_RPC_COMPLETION_POLLS)
def _GetProjectTimestamps(query_project_ids, needed_shard_keys):
"""Get a dict of modified_ts values for all specified project-shards."""
project_shard_timestamps = {}
if query_project_ids:
keys = []
for pid in query_project_ids:
for sid, _subquery in needed_shard_keys:
keys.append('%d;%d' % (pid, sid))
else:
keys = [('all;%d' % sid)
for sid, _subquery in needed_shard_keys]
timestamps_for_project = memcache.get_multi(
keys=keys, namespace=settings.memcache_namespace)
for key, timestamp in timestamps_for_project.items():
pid_str, sid_str = key.split(';')
if pid_str == 'all':
project_shard_timestamps['all', int(sid_str)] = timestamp
else:
project_shard_timestamps[int(pid_str), int(sid_str)] = timestamp
return project_shard_timestamps
def _GetNonviewableIIDs(
query_project_ids, logged_in_user_id, needed_shard_ids, rpc_tuples,
nonviewable_iids, project_shard_timestamps, invalidation_timestep,
use_cached_searches):
"""Build a set of at-risk IIDs, and accumulate RPCs to get uncached ones."""
if query_project_ids:
keys = []
for pid in query_project_ids:
for sid in needed_shard_ids:
keys.append('%d;%d;%d' % (pid, logged_in_user_id, sid))
else:
keys = [('all;%d;%d' % sid)
for (logged_in_user_id, sid) in needed_shard_ids]
if use_cached_searches:
cached_dict = memcache.get_multi(
keys, key_prefix='nonviewable:', namespace=settings.memcache_namespace)
else:
cached_dict = {}
for sid in needed_shard_ids:
if query_project_ids:
for pid in query_project_ids:
_AccumulateNonviewableIIDs(
pid, logged_in_user_id, sid, cached_dict, nonviewable_iids,
project_shard_timestamps, rpc_tuples, invalidation_timestep)
else:
_AccumulateNonviewableIIDs(
None, logged_in_user_id, sid, cached_dict, nonviewable_iids,
project_shard_timestamps, rpc_tuples, invalidation_timestep)
def _AccumulateNonviewableIIDs(
pid, logged_in_user_id, sid, cached_dict, nonviewable_iids,
project_shard_timestamps, rpc_tuples, invalidation_timestep):
"""Use one of the retrieved cache entries or call a backend if needed."""
if pid is None:
key = 'all;%d;%d' % (logged_in_user_id, sid)
else:
key = '%d;%d;%d' % (pid, logged_in_user_id, sid)
if key in cached_dict:
issue_ids, cached_ts = cached_dict.get(key)
modified_ts = project_shard_timestamps.get((pid, sid))
if modified_ts is None or modified_ts > cached_ts:
logging.info('nonviewable too stale on (project %r, shard %r)',
pid, sid)
else:
logging.info('adding %d nonviewable issue_ids', len(issue_ids))
nonviewable_iids[sid] = set(issue_ids)
if sid not in nonviewable_iids:
logging.info('nonviewable for %r not found', key)
logging.info('starting backend call for nonviewable iids %r', key)
rpc = _StartBackendNonviewableCall(
pid, logged_in_user_id, sid, invalidation_timestep)
rpc_tuple = (time.time(), sid, rpc)
rpc.callback = _MakeBackendCallback(
_HandleBackendNonviewableResponse, pid, logged_in_user_id, sid,
rpc_tuple, rpc_tuples, settings.backend_retries, nonviewable_iids,
invalidation_timestep)
rpc_tuples.append(rpc_tuple)
def _GetCachedSearchResults(
cnxn, query_project_ids, needed_shard_keys, harmonized_config,
project_shard_timestamps, services, me_user_ids, can, group_by_spec,
sort_spec, warnings):
"""Return a dict of cached search results that are not already stale.
If it were not for cross-project search, we would simply cache when we do a
search and then invalidate when an issue is modified. But, with
cross-project search we don't know all the memcache entries that would
need to be invalidated. So, instead, we write the search result cache
entries and then an initial modified_ts value for each project if it was
not already there. And, when we update an issue we write a new
modified_ts entry, which implicitly invalidate all search result
cache entries that were written earlier because they are now stale. When
reading from the cache, we ignore any query project with modified_ts
after its search result cache timestamp, because it is stale.
Args:
cnxn: monorail connection to the database.
query_project_ids: list of project ID numbers for all projects being
searched.
needed_shard_keys: set of shard keys that need to be checked.
harmonized_config: ProjectIsueConfig with combined information for all
projects involved in this search.
project_shard_timestamps: a dict {(project_id, shard_id): timestamp, ...}
that tells when each shard was last invalidated.
services: connections to backends.
me_user_ids: Empty list when no user is logged in, or user ID of the logged
in user when doing an interactive search, or the viewed user ID when
viewing someone else's dashboard, or the subscribing user's ID when
evaluating subscriptions. And, any linked accounts.
can: "canned query" number to scope the user's search.
group_by_spec: string that lists the grouping order.
sort_spec: string that lists the sort order.
warnings: list to accumulate warning messages.
Returns:
Tuple consisting of:
A dictionary {shard_id: [issue_id, ...], ...} of unfiltered search result
issue IDs. Only shard_ids found in memcache will be in that dictionary.
The result issue IDs must be permission checked before they can be
considered to be part of the user's result set.
A dictionary {shard_id: bool, ...}. The boolean is set to True if
the search results limit of the shard is hit.
"""
projects_str = ','.join(str(pid) for pid in sorted(query_project_ids))
projects_str = projects_str or 'all'
canned_query = savedqueries_helpers.SavedQueryIDToCond(
cnxn, services.features, can)
canned_query, warnings = searchpipeline.ReplaceKeywordsWithUserIDs(
me_user_ids, canned_query)
warnings.extend(warnings)
sd = sorting.ComputeSortDirectives(
harmonized_config, group_by_spec, sort_spec)
sd_str = ' '.join(sd)
memcache_key_prefix = '%s;%s' % (projects_str, canned_query)
limit_reached_key_prefix = '%s;%s' % (projects_str, canned_query)
cached_dict = memcache.get_multi(
['%s;%s;%s;%d' % (memcache_key_prefix, subquery, sd_str, sid)
for sid, subquery in needed_shard_keys],
namespace=settings.memcache_namespace)
cached_search_limit_reached_dict = memcache.get_multi(
['%s;%s;%s;search_limit_reached;%d' % (
limit_reached_key_prefix, subquery, sd_str, sid)
for sid, subquery in needed_shard_keys],
namespace=settings.memcache_namespace)
unfiltered_dict = {}
search_limit_reached_dict = {}
for shard_key in needed_shard_keys:
shard_id, subquery = shard_key
memcache_key = '%s;%s;%s;%d' % (
memcache_key_prefix, subquery, sd_str, shard_id)
limit_reached_key = '%s;%s;%s;search_limit_reached;%d' % (
limit_reached_key_prefix, subquery, sd_str, shard_id)
if memcache_key not in cached_dict:
logging.info('memcache miss on shard %r', shard_key)
continue
cached_iids, cached_ts = cached_dict[memcache_key]
if cached_search_limit_reached_dict.get(limit_reached_key):
search_limit_reached, _ = cached_search_limit_reached_dict[
limit_reached_key]
else:
search_limit_reached = False
stale = False
if query_project_ids:
for project_id in query_project_ids:
modified_ts = project_shard_timestamps.get((project_id, shard_id))
if modified_ts is None or modified_ts > cached_ts:
stale = True
logging.info('memcache too stale on shard %r because of %r',
shard_id, project_id)
break
else:
modified_ts = project_shard_timestamps.get(('all', shard_id))
if modified_ts is None or modified_ts > cached_ts:
stale = True
logging.info('memcache too stale on shard %r because of all',
shard_id)
if not stale:
logging.info('memcache hit on %r', shard_key)
unfiltered_dict[shard_key] = cached_iids
search_limit_reached_dict[shard_key] = search_limit_reached
return unfiltered_dict, search_limit_reached_dict
def _MakeBackendRequestHeaders(failfast):
headers = {
# This is needed to allow frontends to talk to backends without going
# through a login screen on googleplex.com.
# http://wiki/Main/PrometheusInternal#Internal_Applications_and_APIs
'X-URLFetch-Service-Id': 'GOOGLEPLEX',
}
if failfast:
headers['X-AppEngine-FailFast'] = 'Yes'
return headers
def _StartBackendSearchCall(
query_project_names, shard_key, invalidation_timestep,
me_user_ids, logged_in_user_id, new_url_num, url_params,
deadline=None, failfast=True):
"""Ask a backend to query one shard of the database."""
shard_id, subquery = shard_key
backend_host = modules.get_hostname(module='besearch')
url = 'http://%s%s' % (backend_host, framework_helpers.FormatURL(
url_params, urls.BACKEND_SEARCH,
projects=','.join(query_project_names),
q=subquery, start=0, num=new_url_num,
logged_in_user_id=logged_in_user_id,
me_user_ids=','.join(str(uid) for uid in me_user_ids),
shard_id=shard_id, invalidation_timestep=invalidation_timestep))
logging.info('\n\nCalling backend: %s', url)
rpc = urlfetch.create_rpc(
deadline=deadline or settings.backend_deadline)
headers = _MakeBackendRequestHeaders(failfast)
# follow_redirects=False is needed to avoid a login screen on googleplex.
urlfetch.make_fetch_call(rpc, url, follow_redirects=False, headers=headers)
return rpc
def _StartBackendNonviewableCall(
project_id, logged_in_user_id, shard_id, invalidation_timestep,
deadline=None, failfast=True):
"""Ask a backend to query one shard of the database."""
backend_host = modules.get_hostname(module='besearch')
url = 'http://%s%s' % (backend_host, framework_helpers.FormatURL(
None, urls.BACKEND_NONVIEWABLE,
project_id=project_id or '',
logged_in_user_id=logged_in_user_id or '',
shard_id=shard_id,
invalidation_timestep=invalidation_timestep))
logging.info('Calling backend nonviewable: %s', url)
rpc = urlfetch.create_rpc(deadline=deadline or settings.backend_deadline)
headers = _MakeBackendRequestHeaders(failfast)
# follow_redirects=False is needed to avoid a login screen on googleplex.
urlfetch.make_fetch_call(rpc, url, follow_redirects=False, headers=headers)
return rpc
def _HandleBackendSearchResponse(
query_project_names, rpc_tuple, rpc_tuples, remaining_retries,
unfiltered_iids, search_limit_reached, invalidation_timestep,
error_responses, me_user_ids, logged_in_user_id, new_url_num, url_params):
"""Process one backend response and retry if there was an error."""
start_time, shard_key, rpc = rpc_tuple
duration_sec = time.time() - start_time
try:
response = | |
500
feature1 = tl.layers.BatchNormLayer(feature1, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn1')
feature1 = PReluLayer(feature1, channel_shared = True, name='conv1_relu')
'''
if config.TRAIN.DROPOUT:
feature1 = DropoutLayer(feature1, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features1', is_fix = True)
'''
# used to simulate gapped kmer
feature2 = Conv1d(embedding, 300, int(kernels[1]), stride = 1, dilation_rate = 2, act = None, name = 'conv_8_2') # 500
feature2 = tl.layers.BatchNormLayer(feature2, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='feature2_bn')
feature2 = PReluLayer(feature2, channel_shared = True, name='conv1_2_relu')
'''
if config.TRAIN.DROPOUT:
feature2 = DropoutLayer(feature2, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features2', is_fix = True)
'''
feature3 = Conv1d(embedding, 300, int(kernels[2]), stride = 1, dilation_rate = 4, act = None, name = 'conv_16_2') # 500
feature3 = tl.layers.BatchNormLayer(feature3, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn2')
feature3 = PReluLayer(feature3, channel_shared = True, name='conv1_3_relu')
'''
if config.TRAIN.DROPOUT:
feature3 = DropoutLayer(feature3, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features3', is_fix = True)
'''
features = ConcatLayer([feature1, feature2, feature3], name = 'concat')
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conva_250') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bna3')
con_features = PReluLayer(features, channel_shared = True, name='conv2a_relu')
'''
if config.TRAIN.DROPOUT:
con_features = DropoutLayer(con_features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_features4', is_fix = True)
'''
features = Conv1d(con_features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conva_250_c') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bna3_c')
features = PReluLayer(features, channel_shared = True, name='conv2a_relu_c')
'''
if config.TRAIN.DROPOUT:
features = DropoutLayer(features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_featuress1', is_fix = True)
'''
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conv_250') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn4')
features = PReluLayer(features, channel_shared = True, name='conv2_relu')
'''
if config.TRAIN.DROPOUT:
features = DropoutLayer(features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_featuresss2', is_fix = True)
'''
features = ElementwiseLayer([features, con_features], tf.add, name = 'elem_add')
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conv_125') # 125
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn5')
features = PReluLayer(features, channel_shared = True, name='conv3_relu')
'''
if config.TRAIN.DROPOUT:
features = DropoutLayer(features, keep = config.TRAIN.DROPOUT_KEEP, name = 'drop_featuresss3', is_fix = True)
'''
#sequences = Conv1d(sequences, 32, KERNEL_SIZE, stride = 4, dilation_rate = 1, act = act, name = 'conv_63') # 125
#sequences = Conv1d(sequences, 32, KERNEL_SIZE, stride = 4, dilation_rate = 1, act = act, name = 'conv_31') # 125
# stacking 3 bi-directiona,l lstm here
'''
features = BiRNNLayer(features, cell_fn = tf.contrib.rnn.LSTMCell, n_hidden = config.TRAIN.RNN_HIDDEN, n_steps = config.TRAIN.RNN_STEPS + 1, return_last = False, name = 'bi1')
features = SelfAttentionLayer(features, 8 , 128,name='self-attention')
#features = PReluLayer(features, channel_shared = True, name='prelu1')
#features = BiRNNLayer(features, cell_fn = tf.contrib.rnn.LSTMCell, n_hidden = config.TRAIN.RNN_HIDDEN, n_steps = config.TRAIN.RNN_STEPS + 1, return_last = False, name = 'bi2')
#
'''
def my_rev(inputs):
return tf.reverse(inputs, [1])
rev_features = LambdaLayer(features, my_rev, name ='reverse')
rev_features = SelfAttentionLayer(rev_features, 8 , 128,name='rev_self-attention')
#rev_features = TimeDistributedLayer(rev_features, layer_class=tl.layers.DenseLayer, args={'n_units':50, 'name':'dense_rev'}, name='time_dense_rev')
#DenseLayer(hidden, 2, act = None, name = 'predicting')
features = SelfAttentionLayer(features, 8 , 128,name='self-attention')
#rev_features = TimeDistributedLayer(rev_features, layer_class=tl.layers.DenseLayer, args={'n_units':50, 'name':'dense1'}, name='time_dense')
features = ConcatLayer([features, rev_features], name = 'attention_concat')
'''
features = Conv1d(sequences, 32, KERNEL_SIZE, stride = 2, dilation_rate = 1, act = None, name = 'conv1')
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn1')
features = PReluLayer(features, channel_shared = True, name='conv1_relu')
features = Conv1d(features, 64, KERNEL_SIZE, stride = 2, act = None, name = 'conv1_stride')
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn2')
features = PReluLayer(features, channel_shared = True, name='conv2_relu')
features = Conv1d(features, 64, KERNEL_SIZE, stride = 2, act = None, name = 'conv2_stride')
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn3')
features = PReluLayer(features, channel_shared = True, name='conv3_relu')
'''
return features, feature1.outputs
def AttentionSeqs(t_sequences, name, is_train= True, reuse = False):
with tf.variable_scope(name, reuse=reuse) as vs:
sequences = InputLayer(t_sequences, name='in')
embedding = EmbeddingInputlayer(sequences, 5, 32)
def my_rev(inputs):
return tf.reverse(inputs, [1])
def pe(inputs):
return Position_Embedding(inputs, 32)
rev_features = LambdaLayer(embedding, my_rev, name ='reverse')
rev_pos_embed = LambdaLayer(rev_features, pe, name='rev_position-embedding')
rev_features = ConcatLayer([rev_features, rev_pos_embed], name = 'rev_embedding_concat')
for i in range(6):
rev_features = SelfAttentionLayer(rev_features, 8 , 128,name='rev_self-attention%d'%i)
#rev_features = TimeDistributedLayer(rev_features, layer_class=tl.layers.DenseLayer, args={'n_units':50, 'name':'dense1'}, name='time_dense')
rev_features = Conv1d(rev_features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = tf.nn.relu, name = 'rev_conv_125_%d'%i)
pos_embed = LambdaLayer(embedding, pe, name='position-embedding')
features = ConcatLayer([pos_embed, embedding], name = 'embedding_concat')
for i in range(6):
features = SelfAttentionLayer(features, 8 , 128,name='self-attention%d'%i)
#rev_features = TimeDistributedLayer(rev_features, layer_class=tl.layers.DenseLayer, args={'n_units':50, 'name':'dense1'}, name='time_dense')
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = tf.nn.relu, name = 'conv_125_%d'%i)
features = ConcatLayer([rev_features, features], name = 'embedding_concat')
return features, features.outputs
def sharedFeatureExtractor_nodropout(t_sequences, name, reuse = False, is_train = True):
w_init = tf.random_normal_initializer(stddev=stddev)
b_init = None
g_init = tf.random_normal_initializer(1., stddev)
act = lambda x: tf.nn.leaky_relu(x, 0.2)
kernels = config.TRAIN.KERNEL.split('_')
with tf.variable_scope(name, reuse=reuse) as vs:
sequences = InputLayer(t_sequences, name='in')
#return sequences, sequences.outputs
#return sequences
# user larger kernel size for the first layer
feature1 = Conv1d(sequences, 300, int(kernels[0]), stride = 1, dilation_rate = 1, act = None, name = 'conv_500') # 500
feature1 = tl.layers.BatchNormLayer(feature1, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn1')
feature1 = PReluLayer(feature1, channel_shared = True, name='conv1_relu')
# used to simulate gapped kmer
feature2 = Conv1d(sequences, 300, int(kernels[1]), stride = 1, dilation_rate = 2, act = None, name = 'conv_8_2') # 500
feature2 = tl.layers.BatchNormLayer(feature2, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='feature2_bn')
feature2 = PReluLayer(feature2, channel_shared = True, name='conv1_2_relu')
feature3 = Conv1d(sequences, 300, int(kernels[2]), stride = 1, dilation_rate = 4, act = None, name = 'conv_16_2') # 500
feature3 = tl.layers.BatchNormLayer(feature3, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn2')
feature3 = PReluLayer(feature3, channel_shared = True, name='conv1_3_relu')
features = ConcatLayer([feature1, feature2, feature3], name = 'concat')
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conva_250') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bna3')
con_features = PReluLayer(features, channel_shared = True, name='conv2a_relu')
features = Conv1d(con_features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conva_250_c') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bna3_c')
features = PReluLayer(features, channel_shared = True, name='conv2a_relu_c')
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conv_250') # 250
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn4')
features = PReluLayer(features, channel_shared = True, name='conv2_relu')
features = ElementwiseLayer([features, con_features], tf.add, name = 'elem_add')
features = Conv1d(features, 32, KERNEL_SIZE, stride = 1, dilation_rate = 1, act = None, name = 'conv_125') # 125
features = tl.layers.BatchNormLayer(features, beta_init = w_init, gamma_init = w_init, is_train = is_train, name='bn5')
features = PReluLayer(features, channel_shared = True, name='conv3_relu')
#sequences = Conv1d(sequences, 32, KERNEL_SIZE, stride = 4, dilation_rate = 1, act = act, name = 'conv_63') # 125
#sequences = Conv1d(sequences, 32, KERNEL_SIZE, stride = 4, dilation_rate = 1, act = act, name = 'conv_31') # 125
# stacking 3 bi-directiona,l lstm here
features = BiRNNLayer(features, cell_fn = tf.contrib.rnn.LSTMCell, n_hidden = config.TRAIN.RNN_HIDDEN, n_steps = config.TRAIN.RNN_STEPS + 1, return_last = False, name = 'bi1')
#features = PReluLayer(features, channel_shared = True, name='prelu1')
#features = BiRNNLayer(features, cell_fn = tf.contrib.rnn.LSTMCell, n_hidden = config.TRAIN.RNN_HIDDEN, n_steps = config.TRAIN.RNN_STEPS + 1, return_last = False, name = 'bi2')
#
features = SelfAttentionLayer(features, 8 , 128,name='self-attention')
'''
features = Conv1d(sequences, 32, KERNEL_SIZE, stride = 2, dilation_rate = 1, act = None, name | |
= 'WOA_Nitrate'
ds_lat = ds_tmp[var2use].dropna(dim='lat', how='all')
min_lat = ds_lat['lat'].min() - 2
max_lat = ds_lat['lat'].max() + 2
ds_lon = ds_tmp[var2use].dropna(dim='lon', how='all')
min_lon = ds_lon['lon'].min() - 2
max_lon = ds_lon['lon'].max() + 2
# - Now save by species
vars2save = [i for i in ds_tmp.data_vars if i != 'LonghurstProvince']
for var_ in vars2save:
print(var_)
da = ds_tmp[var_]
# select the minimum area for the areas
da = da.sel(lat=(da.lat >= min_lat))
da = da.sel(lat=(da.lat < max_lat))
if key_ in ('SubT_NP' 'SubT_SP'):
print('just limiting lat for: {}'.format(key_))
else:
da = da.sel(lon=(da.lon >= min_lon))
da = da.sel(lon=(da.lon < max_lon))
# Save the data to NetCDF.
filename = file_str.format(key_, var_, res, '')
filename = AC.rm_spaces_and_chars_from_str(filename)
da.to_netcdf(filename+'.nc')
# ---------------------------------------------------------------------------
# --------------- Functions for Atmospheric impacts work -------------------
# ---------------------------------------------------------------------------
def Do_analysis_and_mk_plots_for_EGU19_poster():
"""
Driver function for analysis and plotting for EGU poster
"""
# - Get data
# data locations and names as a dictionary
wds = get_run_dict4EGU_runs()
runs = list(sorted(wds.keys()))
# Get emissions
dsDH = GetEmissionsFromHEMCONetCDFsAsDatasets(wds=wds)
# Process the datasets?
# a = [ AC.get_O3_burden( wd=wds[i] ) for i in runs ]
# Get datasets objects from directories and in a dictionary
dsD = {}
for run in runs:
ds = xr.open_dataset(wds[run]+'ctm.nc')
dsD[run] = ds
# - Do analysis
# Get summary emission stats
Check_global_statistics_on_emissions(dsDH=dsDH)
# Look at differences in surface concentration.
extra_str = 'EGU_runs_surface_Iy_stats_'
df = evalulate_burdens_and_surface_conc(run_dict=wds, extra_str=extra_str)
# Get general statistics about the emissions vs. Macdoanld et al 2014
REF1 = 'Macdonald2014'
extra_str = 'EGU_runs_general_stats_vs_{}_'.format(REF1)
df = AC.get_general_stats4run_dict_as_df(run_dict=wds, REF1=REF1,
extra_str=extra_str)
# Get general statistics about the emissions vs. Macdoanld et al 2014
REF1 = 'Chance2014'
extra_str = 'EGU_runs_general_stats_vs_{}_'.format(REF1)
df = AC.get_general_stats4run_dict_as_df(run_dict=wds, REF1=REF1,
extra_str=extra_str)
# Get general statistics about the emissions vs. Macdoanld et al 2014
REF1 = 'ML_Iodide'
extra_str = 'EGU_runs_general_stats_vs_{}_'.format(REF1)
df = AC.get_general_stats4run_dict_as_df(run_dict=wds, REF1=REF1,
extra_str=extra_str)
# Get general statistics about the emissions vs. Macdoanld et al 2014
REF1 = 'No_HOI_I2'
extra_str = 'EGU_runs_general_stats_vs_{}_'.format(REF1)
df = AC.get_general_stats4run_dict_as_df(run_dict=wds, REF1=REF1,
extra_str=extra_str)
# - Get spatial plots
# plot up emissions
plot_up_surface_emissions(dsDH=dsDH)
# - Do diferences plots
# - look at the HOI/I2 surface values and IO.
# species to look at?
specs = ['O3', 'NO2', 'IO', 'HOI', 'I2']
# Chance vs. ML_iodide
AC.plot_up_surface_changes_between2runs(ds_dict=dsD, BASE='Chance2014',
NEW='ML_Iodide', specs=specs,
update_PyGChem_format2COARDS=True)
# Macdonald vs. ML_iodide
AC.plot_up_surface_changes_between2runs(ds_dict=dsD, BASE='Macdonald2014',
NEW='ML_Iodide', specs=specs,
update_PyGChem_format2COARDS=True)
# Macdonald vs. Chance
AC.plot_up_surface_changes_between2runs(ds_dict=dsD, BASE='Macdonald2014',
NEW='Chance2014', specs=specs,
update_PyGChem_format2COARDS=True)
# Macdonald vs. No_HOI_I2
AC.plot_up_surface_changes_between2runs(ds_dict=dsD, BASE='Macdonald2014',
NEW='No_HOI_I2', specs=specs,
update_PyGChem_format2COARDS=True)
# ML_iodide vs. No_HOI_I2
AC.plot_up_surface_changes_between2runs(ds_dict=dsD, BASE='No_HOI_I2',
NEW='ML_Iodide', specs=specs,
update_PyGChem_format2COARDS=True)
# ds_dict=dsD.copy(); BASE='Macdonald2014'; NEW='ML_Iodide'
# - Get production figures.
# surface ozone figure - made in powerpoint for now...
# Plot up emissions for EGU presentation
BASE = 'ML_Iodide'
DIFF1 = 'Chance2014'
DIFF2 = 'Macdonald2014'
plot_up_EGU_fig05_emiss_change(ds_dict=dsD, BASE=BASE, DIFF1=DIFF1, DIFF2=DIFF2,
update_PyGChem_format2COARDS=True)
def plot_up_EGU_fig05_emiss_change(ds_dict=None, levs=[1], specs=[],
BASE='', DIFF1='', DIFF2='', prefix='IJ_AVG_S__',
update_PyGChem_format2COARDS=False):
"""
Plot up the change in emissions for EGU poster
"""
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
# Species to plot
vars2use = [prefix+i for i in specs]
unit = None
PDFfilenameStr = 'Oi_surface_change_{}_vs_{}_lev_{:0>2}'
# Set datasets to use and Just include the variables to plot in the dataset
title1 = BASE
title2 = DIFF1
title2 = DIFF2
ds1 = ds_dict[BASE][vars2use].copy()
ds2 = ds_dict[DIFF1][vars2use].copy()
ds2 = ds_dict[DIFF2][vars2use].copy()
# Average over time
print(ds1, ds2, ds3)
ds1 = ds1.mean(dim='time')
ds2 = ds2.mean(dim='time')
ds3 = ds3.mean(dim='time')
# Remove vestigial coordinates.
# (e.g. the time_0 coord... what is this?)
vars2drop = ['time_0']
dsL = [ds1, ds2, ds3]
for var2drop in vars2drop:
for n, ds in enumerate(dsL):
CoordVars = [i for i in ds.coords]
if var2drop in CoordVars:
ds = ds.drop(var2drop)
dsL[n] = ds
ds1, ds2, ds3 = dsL
# Update dimension names
if update_PyGChem_format2COARDS:
ds1 = Convert_PyGChem_Iris_DataSet2COARDS_NetCDF(ds=ds1)
ds2 = Convert_PyGChem_Iris_DataSet2COARDS_NetCDF(ds=ds2)
ds3 = Convert_PyGChem_Iris_DataSet2COARDS_NetCDF(ds=ds3)
# Setup plot
# plot up map with mask present
fig = plt.figure(figsize=(10, 6))
vmin = -100
vmax = 100
# Add initial plot
axn = [1, 1, 1]
ax = fig.add_subplot(*axn, projection=ccrs.Robinson(), aspect='auto')
ax.plot.imshow(x='lon', y='lat', ax=ax,
vmin=vmin, vmax=vmax,
transform=ccrs.PlateCarree())
plt.title(savename)
plt.savefig(savename+'.png')
plt.close()
def evalulate_burdens_and_surface_conc(run_dict=None, extra_str='', REF1=None,
REF2=None, REF_wd=None, res='4x5', trop_limit=True,
save2csv=True, prefix='GC_', run_names=None,
debug=False):
"""
Check general statistics on the CTM model runs
"""
# Extract names and locations of data
if isinstance(run_dict, type(None)):
run_dict = get_run_dict4EGU_runs()
if isinstance(run_names, type(None)):
run_names = sorted(run_dict.keys())
wds = [run_dict[i] for i in run_names]
# Mass unit scaling
mass_scale = 1E3
mass_unit = 'Tg'
# v/v scaling?
ppbv_unit = 'ppbv'
ppbv_scale = 1E9
pptv_unit = 'pptv'
pptv_scale = 1E12
# Get shared variables from a single model run
if isinstance(REF_wd, type(None)):
REF_wd = wds[0]
# get time in the troposphere diagnostic
t_p = AC.get_GC_output(wd=REF_wd, vars=[u'TIME_TPS__TIMETROP'],
trop_limit=True)
# Temperature
K = AC.get_GC_output(wd=REF_wd, vars=[u'DAO_3D_S__TMPU'], trop_limit=True)
# airmass
a_m = AC.get_air_mass_np(wd=REF_wd, trop_limit=True)
# Surface area?
s_area = AC.get_surface_area(res)[..., 0] # m2 land map
# ----
# - Now build analysis in pd.DataFrame
#
# - Tropospheric burdens?
# Get tropospheric burden for run
varname = 'O3 burden ({})'.format(mass_unit)
ars = [AC.get_O3_burden(i, t_p=t_p).sum() for i in wds]
df = pd.DataFrame(ars, columns=[varname], index=run_names)
# Get NO2 burden
NO2_varname = 'NO2 burden ({})'.format(mass_unit)
ars = [AC.get_trop_burden(spec='NO2', t_p=t_p, wd=i, all_data=False).sum()
for i in wds]
# convert to N equivalent
ars = [i/AC.species_mass('NO2')*AC.species_mass('N') for i in ars]
df[NO2_varname] = ars
# Get NO burden
NO_varname = 'NO burden ({})'.format(mass_unit)
ars = [AC.get_trop_burden(spec='NO', t_p=t_p, wd=i, all_data=False).sum()
for i in wds]
# convert to N equivalent
ars = [i/AC.species_mass('NO')*AC.species_mass('N') for i in ars]
df[NO_varname] = ars
# Combine NO and NO2 to get NOx burden
NOx_varname = 'NOx burden ({})'.format(mass_unit)
df[NOx_varname] = df[NO2_varname] + df[NO_varname]
# Get HOI burden
varname = 'HOI burden ({})'.format(mass_unit)
ars = [AC.get_trop_burden(spec='HOI', t_p=t_p, wd=i, all_data=False).sum()
for i in wds]
# convert to I equivalent
ars = [i/AC.species_mass('HOI')*AC.species_mass('I') for i in ars]
df[varname] = ars
# Get I2 burden
varname = 'I2 burden ({})'.format(mass_unit)
ars = [AC.get_trop_burden(spec='I2', t_p=t_p, wd=i, all_data=False).sum()
for i in wds]
# convert to I equivalent
ars = [i/AC.species_mass('I2')*AC.species_mass('I') for i in ars]
df[varname] = ars
# Get I2 burden
varname = 'IO burden ({})'.format(mass_unit)
ars = [AC.get_trop_burden(spec='IO', t_p=t_p, wd=i, all_data=False).sum()
for i in wds]
# convert to I equivalent
ars = [i/AC.species_mass('IO')*AC.species_mass('I') for i in ars]
df[varname] = ars
# Scale units
for col_ in df.columns:
if 'Tg' in col_:
df.loc[:, col_] = df.loc[:, col_].values/mass_scale
# - Surface concentrations?
# Surface ozone
O3_sur_varname = 'O3 surface ({})'.format(ppbv_unit)
ars = [AC.get_avg_surface_conc_of_X(spec='O3', wd=i, s_area=s_area)
for i in wds]
df[O3_sur_varname] = ars
# Surface NOx
NO_sur_varname = 'NO surface ({})'.format(ppbv_unit)
ars = [AC.get_avg_surface_conc_of_X(spec='NO', wd=i, s_area=s_area)
for i in wds]
df[NO_sur_varname] = ars
NO2_sur_varname = 'NO2 surface ({})'.format(ppbv_unit)
ars = [AC.get_avg_surface_conc_of_X(spec='NO2', wd=i, s_area=s_area)
for i in wds]
df[NO2_sur_varname] = ars
NOx_sur_varname = 'NOx surface ({})'.format(ppbv_unit)
df[NOx_sur_varname] = df[NO2_sur_varname] + df[NO_sur_varname]
# Surface HOI
HOI_sur_varname = 'HOI surface ({})'.format(pptv_unit)
ars = [AC.get_avg_surface_conc_of_X(spec='HOI', wd=i, s_area=s_area)
for i in wds]
df[HOI_sur_varname] = ars
# Surface I2
I2_sur_varname = 'I2 surface ({})'.format(pptv_unit)
ars = [AC.get_avg_surface_conc_of_X(spec='I2', wd=i, s_area=s_area)
for i in wds]
df[I2_sur_varname] = ars
# Surface I2
I2_sur_varname = 'IO surface ({})'.format(pptv_unit)
ars = [AC.get_avg_surface_conc_of_X(spec='IO', wd=i, s_area=s_area)
for i in wds]
df[I2_sur_varname] = ars
# - Scale units
for col_ in df.columns:
if 'ppbv' in col_:
df.loc[:, col_] = df.loc[:, col_].values*ppbv_scale
if 'pptv' in col_:
df.loc[:, col_] = df.loc[:, col_].values*pptv_scale
# - Processing and save?
# Calculate % change from base case for each variable
if not isinstance(REF1, type(None)):
for col_ in df.columns:
pcent_var = col_+' (% vs. {})'.format(REF1)
df[pcent_var] = (df[col_]-df[col_][REF1]) / df[col_][REF1] * 100
if not isinstance(REF2, type(None)):
for col_ in df.columns:
pcent_var = col_+' (% vs. {})'.format(REF2)
df[pcent_var] = (df[col_]-df[col_][REF2]) / df[col_][REF2] * 100
# Re-order columns
df = df.reindex_axis(sorted(df.columns), axis=1)
# Reorder index
df = df.T.reindex_axis(sorted(df.T.columns), axis=1).T
# Now round the numbers
df = df.round(3)
# Save csv to disk
csv_filename = '{}_summary_statistics{}.csv'.format(prefix, extra_str)
df.to_csv(csv_filename)
# return the DataFrame too
return df
def Check_sensitivity_of_HOI_I2_param2WS():
"""
Check the sensitivity of the Carpenter et al 2013 parameterisation to wind speed
"""
import seaborn as sns
sns.set(color_codes=True)
sns.set_context("paper", font_scale=1.75)
import matplotlib.pyplot as plt
# Core | |
(
x ** (n * (m + 1) - m) * (f(x).diff(x)) - a * f(x) ** n - b * x ** (n * (m + 1))
)
i = infinitesimals(eq, hint="linear")
assert checkinfsol(eq, i)[0]
@XFAIL
def test_kamke():
a, b, alpha, c = symbols("a b alpha c")
eq = x ** 2 * (a * f(x) ** 2 + (f(x).diff(x))) + b * x ** alpha + c
i = infinitesimals(eq, hint="sum_function")
assert checkinfsol(eq, i)[0]
def test_series():
C1 = Symbol("C1")
eq = f(x).diff(x) - f(x)
sol = Eq(
f(x),
C1
+ C1 * x
+ C1 * x ** 2 / 2
+ C1 * x ** 3 / 6
+ C1 * x ** 4 / 24
+ C1 * x ** 5 / 120
+ O(x ** 6),
)
assert dsolve(eq, hint="1st_power_series") == sol
assert checkodesol(eq, sol, order=1)[0]
eq = f(x).diff(x) - x * f(x)
sol = Eq(f(x), C1 * x ** 4 / 8 + C1 * x ** 2 / 2 + C1 + O(x ** 6))
assert dsolve(eq, hint="1st_power_series") == sol
assert checkodesol(eq, sol, order=1)[0]
eq = f(x).diff(x) - sin(x * f(x))
sol = Eq(
f(x), (x - 2) ** 2 * (1 + sin(4)) * cos(4) + (x - 2) * sin(4) + 2 + O(x ** 3)
)
assert dsolve(eq, hint="1st_power_series", ics={f(2): 2}, n=3) == sol
# FIXME: The solution here should be O((x-2)**3) so is incorrect
# assert checkodesol(eq, sol, order=1)[0]
@XFAIL
@SKIP
def test_lie_group_issue17322():
eq = x * f(x).diff(x) * (f(x) + 4) + (f(x) ** 2) - 2 * f(x) - 2 * x
sol = dsolve(eq, f(x))
assert checkodesol(eq, sol) == (True, 0)
eq = x * f(x).diff(x) * (f(x) + 4) + (f(x) ** 2) - 2 * f(x) - 2 * x
sol = dsolve(eq)
assert checkodesol(eq, sol) == (True, 0)
eq = Eq(
x ** 7 * Derivative(f(x), x)
+ 5 * x ** 3 * f(x) ** 2
- (2 * x ** 2 + 2) * f(x) ** 3,
0,
)
sol = dsolve(eq)
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x) - (f(x) - x * log(x)) ** 2 / x ** 2 + log(x)
sol = dsolve(eq)
assert checkodesol(eq, sol) == (True, 0)
@slow
def test_lie_group():
C1 = Symbol("C1")
x = Symbol("x") # assuming x is real generates an error!
a, b, c = symbols("a b c")
eq = f(x).diff(x) ** 2
sol = dsolve(eq, f(x), hint="lie_group")
assert checkodesol(eq, sol) == (True, 0)
eq = Eq(f(x).diff(x), x ** 2 * f(x))
sol = dsolve(eq, f(x), hint="lie_group")
assert sol == Eq(f(x), C1 * exp(x ** 3) ** Rational(1, 3))
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x) + a * f(x) - c * exp(b * x)
sol = dsolve(eq, f(x), hint="lie_group")
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x) + 2 * x * f(x) - x * exp(-(x ** 2))
sol = dsolve(eq, f(x), hint="lie_group")
actual_sol = Eq(f(x), (C1 + x ** 2 / 2) * exp(-(x ** 2)))
errstr = str(eq) + " : " + str(sol) + " == " + str(actual_sol)
assert sol == actual_sol, errstr
assert checkodesol(eq, sol) == (True, 0)
eq = (1 + 2 * x) * (f(x).diff(x)) + 2 - 4 * exp(-f(x))
sol = dsolve(eq, f(x), hint="lie_group")
assert sol == Eq(f(x), log(C1 / (2 * x + 1) + 2))
assert checkodesol(eq, sol) == (True, 0)
eq = x ** 2 * (f(x).diff(x)) - f(x) + x ** 2 * exp(x - (1 / x))
sol = dsolve(eq, f(x), hint="lie_group")
assert checkodesol(eq, sol)[0]
eq = x ** 2 * f(x) ** 2 + x * Derivative(f(x), x)
sol = dsolve(eq, f(x), hint="lie_group")
assert sol == Eq(f(x), 2 / (C1 + x ** 2))
assert checkodesol(eq, sol) == (True, 0)
eq = diff(f(x), x) + 2 * x * f(x) - x * exp(-(x ** 2))
sol = Eq(f(x), exp(-(x ** 2)) * (C1 + x ** 2 / 2))
assert sol == dsolve(eq, hint="lie_group")
assert checkodesol(eq, sol) == (True, 0)
eq = diff(f(x), x) + f(x) * cos(x) - exp(2 * x)
sol = Eq(f(x), exp(-sin(x)) * (C1 + Integral(exp(2 * x) * exp(sin(x)), x)))
assert sol == dsolve(eq, hint="lie_group")
assert checkodesol(eq, sol) == (True, 0)
eq = diff(f(x), x) + f(x) * cos(x) - sin(2 * x) / 2
sol = Eq(f(x), C1 * exp(-sin(x)) + sin(x) - 1)
assert sol == dsolve(eq, hint="lie_group")
assert checkodesol(eq, sol) == (True, 0)
eq = x * diff(f(x), x) + f(x) - x * sin(x)
sol = Eq(f(x), (C1 - x * cos(x) + sin(x)) / x)
assert sol == dsolve(eq, hint="lie_group")
assert checkodesol(eq, sol) == (True, 0)
eq = x * diff(f(x), x) - f(x) - x / log(x)
sol = Eq(f(x), x * (C1 + log(log(x))))
assert sol == dsolve(eq, hint="lie_group")
assert checkodesol(eq, sol) == (True, 0)
eq = (f(x).diff(x) - f(x)) * (f(x).diff(x) + f(x))
sol = [Eq(f(x), C1 * exp(x)), Eq(f(x), C1 * exp(-x))]
assert set(sol) == set(dsolve(eq, hint="lie_group"))
assert checkodesol(eq, sol[0]) == (True, 0)
assert checkodesol(eq, sol[1]) == (True, 0)
eq = f(x).diff(x) * (f(x).diff(x) - f(x))
sol = [Eq(f(x), C1 * exp(x)), Eq(f(x), C1)]
assert set(sol) == set(dsolve(eq, hint="lie_group"))
assert checkodesol(eq, sol[0]) == (True, 0)
assert checkodesol(eq, sol[1]) == (True, 0)
@XFAIL
def test_lie_group_issue15219():
eqn = exp(f(x).diff(x) - f(x))
assert "lie_group" not in classify_ode(eqn, f(x))
def test_user_infinitesimals():
x = Symbol("x") # assuming x is real generates an error
eq = x * (f(x).diff(x)) + 1 - f(x) ** 2
sol = Eq(f(x), (C1 + x ** 2) / (C1 - x ** 2))
infinitesimals = {"xi": sqrt(f(x) - 1) / sqrt(f(x) + 1), "eta": 0}
assert dsolve(eq, hint="lie_group", **infinitesimals) == sol
assert checkodesol(eq, sol) == (True, 0)
def test_issue_7081():
eq = x * (f(x).diff(x)) + 1 - f(x) ** 2
s = Eq(f(x), -1 / (-C1 + x ** 2) * (C1 + x ** 2))
assert dsolve(eq) == s
assert checkodesol(eq, s) == (True, 0)
@slow
def test_2nd_power_series_ordinary():
C1, C2 = symbols("C1 C2")
eq = f(x).diff(x, 2) - x * f(x)
assert classify_ode(eq) == ("2nd_linear_airy", "2nd_power_series_ordinary")
sol = Eq(f(x), C2 * (x ** 3 / 6 + 1) + C1 * x * (x ** 3 / 12 + 1) + O(x ** 6))
assert dsolve(eq, hint="2nd_power_series_ordinary") == sol
assert checkodesol(eq, sol) == (True, 0)
sol = Eq(
f(x),
C2 * ((x + 2) ** 4 / 6 + (x + 2) ** 3 / 6 - (x + 2) ** 2 + 1)
+ C1 * (x + (x + 2) ** 4 / 12 - (x + 2) ** 3 / 3 + S(2))
+ O(x ** 6),
)
assert dsolve(eq, hint="2nd_power_series_ordinary", x0=-2) == sol
# FIXME: Solution should be O((x+2)**6)
# assert checkodesol(eq, sol) == (True, 0)
sol = Eq(f(x), C2 * x + C1 + O(x ** 2))
assert dsolve(eq, hint="2nd_power_series_ordinary", n=2) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = (1 + x ** 2) * (f(x).diff(x, 2)) + 2 * x * (f(x).diff(x)) - 2 * f(x)
assert classify_ode(eq) == ("2nd_power_series_ordinary",)
sol = Eq(f(x), C2 * (-(x ** 4) / 3 + x ** 2 + 1) + C1 * x + O(x ** 6))
assert dsolve(eq) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + x * (f(x).diff(x)) + f(x)
assert classify_ode(eq) == ("2nd_power_series_ordinary",)
sol = Eq(
f(x),
C2 * (x ** 4 / 8 - x ** 2 / 2 + 1) + C1 * x * (-(x ** 2) / 3 + 1) + O(x ** 6),
)
assert dsolve(eq) == sol
# FIXME: checkodesol fails for this solution...
# assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + f(x).diff(x) - x * f(x)
assert classify_ode(eq) == ("2nd_power_series_ordinary",)
sol = Eq(
f(x),
| |
= 0
for actor in Characters.query({"online": True}):
count += 1
self.echo(f"{{x{actor.stats.level.base:>3} {actor.gender.colored_short_name:>1} {actor.races[0].colored_short_name:>5} {actor.classes[0].colored_short_name} {{x[.{{RP{{x......] {actor.name} {actor.title}")
self.echo()
self.echo(
f"{{GPlayers found: {{x{count} "
f"{{GTotal online: {{x{count} "
f"{{GMost on today: {{x{count}")
@inject("Characters")
def delete_command(self, Characters, **kwargs):
self.echo("Removing your character from the game.")
Characters.delete(self)
self.quit(skip_save=True)
@inject("Characters")
def finger_command(self, args, Characters, **kwargs):
if not args:
self.echo("Finger whom?")
return
name = args.pop(0).lower().title()
actor = Characters.get({"name": name})
if not actor:
self.echo("No such player: {}".format(name))
return
output = """ \
+-----------------------[ WaterdeepMUD Character Info ]-----------------------+
Name {} : {} {}
Class : {} Clan : {}
Race : {} Rank : {}
Level : {} Deity : {}
Age : {} Arena : {} Wins
Height : {} {} Losses
Weight : {} Hours : {}
Hair : {} Birthday: {}
Eyes : {} Old Clan: {}
PK Rank : {} NPK Rank: {}
RP Status: {}
+-------------------------------| DESCRIPTION |-------------------------------+
{}
+-----------------------------------------------------------------------------+
{} is currently {} from {}.
+-----------------------------------------------------------------------------+\
""".format(
actor.gender.colored_short_name,
actor.name,
actor.title,
actor.classes[0].name,
"",
actor.races[0].name,
"",
str(actor.stats.level.base),
"",
"",
str(0),
"",
str(0),
"",
str(0),
"",
"",
"",
"",
"",
"",
"",
"\n".join(actor.description or []),
actor.name,
"ONLINE",
""
)
self.echo(output)
def title_command(self, message, **kwargs):
self.title = message
self.save()
if message:
self.echo("Title set to: {}".format(self.title))
else:
self.echo("Title cleared.")
@inject("Areas")
def om_recall(self, args, Areas, **kwargs):
args = list(map(lambda a: a.lower(), args))
command = ""
if not args:
self.overmap_x = None
self.overmap_y = None
self.overmap = None
self.echo("You pray for transportation and Recall!")
goto_command(self, [settings.INITIAL_ROOM_VNUM])
return
else:
command = args.pop(0)
print(f"command:{command}")
for area in Areas.query():
if area.name.lower() == command:
self.overmap = command
self.overmap_x = 0
self.overmap_y = 0
o_recall(self, area)
return
self.echo("Recall Area not found.")
class ActorStat(object):
def __init__(self, id, value, actor):
self.id = id
self.value = value
self.actor = actor
@property
def base(self):
return self.value
@base.setter
def base(self, value):
self.actor.data["stats"][self.id] = value
@property
def bonus(self):
return 0
@property
def total(self):
return self.base + self.bonus
class ActorStats(object):
def __init__(self, stats, actor):
self.stats = stats
self.actor = actor
def __getattr__(self, key):
if key not in self.stats:
self.stats[key] = 0
return ActorStat(key, self.stats[key], self.actor)
class Actor(Entity):
DEFAULT_DATA = {
"name": "",
"title": "",
"bracket": "",
"experience": 0,
"experience_per_level": 3000,
"room_id": "",
"room_vnum": settings.INITIAL_ROOM_VNUM,
"race_ids": ["human"],
"class_ids": ["adventurer"],
"stats": {},
"settings": {},
"gender_id": "male",
}
def die(self):
self.recall()
self.stats.hp.current = 1
@inject("Rooms")
def recall(self, Rooms=None):
room = Rooms.get({"vnum": settings.INITIAL_ROOM_VNUM})
self.room = room
def find_targets(self):
"""
Returns a list of lists of potential targets.
:param target:
:return:
"""
room = self.room
return room.actors
def find_target(self, prop_target):
"""
This should call find_targets and select the very first target.
:param prop_target: proposed target
:return:
"""
self.echo("{{BYou try to target '{{W{}'!{{x".format(prop_target))
if "self" == prop_target.strip().lower() or "myself" == prop_target.lower:
target = self
return target
else:
target = None
for actor in self.find_targets():
if target:
break
keywords = actor.name.lower().split()
for keyword in keywords:
#self.echo("keyword: {} | prop_target: {}".format(keyword, prop_target.lower())) # troubleshoot
if keyword.startswith(prop_target.lower()):
target = actor
break
return target
def replace_tokens(self, msg=None, target=None):
"""
This will replace interactive tokens like <subject>, <object>, $n, $m with "his" "her", etc.
:param msg: The starting msg string to be altered.
:param target: this should be the targeted Actor, whose gender may also be checked.
:return:
$n = actor.name
$s = actor.gender.possessive -- his, her, its
$m = actor.gender.object -- him, her, it
$e = actor.gender.subject -- he, she, it
$N = target.name
$S = target.gender.possessive
$M = target.gender.object
$E = actor.gender.subject
"""
if msg:
#self.echo("replace tokens: name:{} gender:{} object:{}".format(self.name, self.gender, self.gender.object))
msg = msg.replace('$n', self.name)
msg = msg.replace('$s', self.gender.possessive)
msg = msg.replace('$m', self.gender.object)
msg = msg.replace('$e', self.gender.subject)
if target: # Do this later.
msg = msg.replace('$N', target.name)
msg = msg.replace('$S', target.gender.possessive)
msg = msg.replace('$M', target.gender.object)
msg = msg.replace('$E', target.gender.subject)
return msg
else:
return
def gain_experience(self, amount):
amount = int(abs(amount))
self.echo("{{BYou gain {{W{} {{Bexperience points!{{x".format(amount))
self.experience += amount
while self.stats.level.base < settings.LEVEL_MAXIMUM and \
self.experience >= self.experience_per_level:
self.stats.level.base += 1
# TODO add class specific level gains, roll_level(self)
mana_gain = randint(10, 85)
hp_gain = randint(20, 45)
move_gain = randint(10, 40)
practice_gain = randint(1, 6)
train_gain = randint(0, 2)
self.echo("You raise a level!! Your gain is: {}/{} hp, {}/{} m, {}/{} mv .".format(
hp_gain,
self.stats.hp.total,
mana_gain,
self.stats.mana.total,
move_gain,
self.stats.move.total))
self.echo("You gained a level! You are now level {}. {}/{} pracs {}/{} trains".format(
self.stats.level.base,
practice_gain,
self.stats.practices.base,
train_gain,
self.stats.trains.base))
# level gain
self.stats.hp.base += hp_gain
self.stats.mana.base += mana_gain
self.stats.move.base += move_gain
self.stats.practices.base += practice_gain
self.stats.trains.base += train_gain
self.experience -= self.experience_per_level
if self.stats.level.base >= settings.LEVEL_MAXIMUM:
self.echo("Congratulations, you made it to the maximum level!")
if self.stats.level.base >= settings.LEVEL_MAXIMUM:
self.experience = 0
@inject("Actors")
def spawn_actor(self, data, Actors):
room = self.room
data["room_id"] = room.id
data["room_vnum"] = room.vnum
area = room.area
data["area_id"] = area.id
data["area_vnum"] = area.vnum
return Actors.save(data)
@property
@inject("Actors", "Characters")
def targets(self, Actors, Characters):
for id in self.get("target_ids", []):
for coll in (Actors, Characters):
actor = coll.get(id)
if not actor:
continue
yield actor
break
@targets.setter
def targets(self, targets):
self.target_ids = [target.id for target in targets]
@property
@inject("Classes")
def classes(self, Classes):
return [Classes.get(class_id) for class_id in self.class_ids]
@property
@inject("Races")
def races(self, Races):
return [Races.get(race_id) for race_id in self.race_ids]
@property
@inject("Genders")
def gender(self, Genders):
return Genders.get(self.gender_id)
@property
@inject("Rooms")
def room(self, Rooms):
room = Rooms.get(self.room_id)
save_room = False
if not room:
save_room = True
room = Rooms.get({"vnum": self.room_vnum})
if not room:
save_room = True
room = Rooms.get({"vnum": settings.INITIAL_ROOM_VNUM})
if not room:
room = Rooms.get({"vnum": "void"})
if save_room:
self.room_id = room.id
self.room_vnum = room.vnum
self.save()
return room
@room.setter
def room(self, provided):
self.room_id = provided.id
self.room_vnum = provided.vnum
@property
def connection(self):
return self.game.connections.get(self.connection_id, None)
@property
def client(self):
if not self.connection:
return None
return self.connection.client
def say(self, message):
say_command(self, message=message)
def save(self):
self.collection.save(self)
def quit(self, skip_save=False):
if not self.client:
return
self.client.quit()
self.online = False
if not skip_save:
self.save()
def force(self, message):
if not self.client:
return
self.client.handle_input(message)
def echo(self, message=""):
if not self.client:
return
if isinstance(message, list):
for line in message:
self.echo(line)
else:
self.client.writeln(str(message))
def act_to(self, target, template: str, **data):
"""Perform an acting emote towards a target.
:param target: Actor
:param template: a template string containing act tokens
:param **data: a dictionary of extra act data
See: self.act
"""
message = template
# Attribute names and functions to run on self, it will provide the
# target as the parameter-- this can allow visibility checks, etc.
OBJECT_ATTRIBUTES = {
"name": "name_to",
}
data["self"] = self
# Iterate over the data provided
for key, value in data.items():
# If string, do a simple token replace
if isinstance(value, str):
token = "{{{}}}".format(key)
if token in message:
message = message.replace(token, value) # {$N} -->
# If object, look up OBJECT_ATTRIBUTES to replace with function
# calls as needed.
elif isinstance(value, object):
for attr_name, attr_func in OBJECT_ATTRIBUTES.items():
token = "{{{}.{}}}".format(key, attr_name)
if token in message:
func = getattr(self, attr_func)
message = message.replace(token, func(target))
# Otherwise, it's invalid data.
else:
raise Exception("Invalid data '{}'.".format(key))
target.echo(message)
def act(self, template: str, **data):
"""Perform an acting emote towards an entire room.
:param target: Actor
:param template: a template string containing act tokens
:param exclude: a list of people to exclude from the to-room act
:param **data: a dictionary of extra act data
"""
Actors, Characters = self.game.get_injectors("Actors", "Characters")
if data is None:
data = {}
data["actor"] = self
# Exclude people from the display of this
exclude = data.pop("exclude", [self])
if exclude is None:
exclude = [self]
# Iterate over actors and act_to them
for collection in (Characters, Actors):
for actor in collection.query({"room_id": self.room_id}):
if not exclude:
continue
if actor in exclude:
continue
# TODO: Visibility?
self.act_to(actor, template, **data)
def name_to(self, target):
"""Format an Actor's name towards a target.
Takes visibility into account.
:param target: the target to format for
"""
return self.name
@property
def stats(self):
data = self.data
if "stats" not in data:
data["stats"] = {}
return ActorStats(data["stats"], self)
@property
def parents(self):
return [self.room]
class Account(Entity):
pass
class Accounts(Collection):
ENTITY_CLASS = Account
STORAGE_CLASS = FileStorage
class Object(Entity):
pass
class Character(Actor):
pass
class Area(Entity):
DEFAULT_DATA = {
"name": "Unnamed",
}
@property
@inject("Rooms")
def rooms(self, Rooms):
return Rooms.query({"area_id": self.id})
@property
def children(self):
return | |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
from typing import List, Any, Union
class DestinationRange(Base):
"""Describes a set of routers that are the destination of MPLS tunnels. Destination ranges correspond to Ingress or Egress routers.
The DestinationRange class encapsulates a list of destinationRange resources that are managed by the user.
A list of resources can be retrieved from the server using the DestinationRange.find() method.
The list can be managed by using the DestinationRange.add() and DestinationRange.remove() methods.
"""
__slots__ = ()
_SDM_NAME = 'destinationRange'
_SDM_ATT_MAP = {
'Behavior': 'behavior',
'EmulationType': 'emulationType',
'EnableReplyingLspPing': 'enableReplyingLspPing',
'Enabled': 'enabled',
'IpAddressFrom': 'ipAddressFrom',
'IpCount': 'ipCount',
'IsConnectedIpAppended': 'isConnectedIpAppended',
'IsHeadIpPrepended': 'isHeadIpPrepended',
'IsLeafIpPrepended': 'isLeafIpPrepended',
'IsSendingAsRro': 'isSendingAsRro',
'IsSendingAsSrro': 'isSendingAsSrro',
'P2mpId': 'p2mpId',
}
_SDM_ENUM_MAP = {
'behavior': ['ingress', 'egress'],
'emulationType': ['reserved', 'rsvpTe', 'rsvpTeP2mP'],
}
def __init__(self, parent, list_op=False):
super(DestinationRange, self).__init__(parent, list_op)
@property
def Egress(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.egress_eafa79ad778e0a6c6cd87e7f67bde5ec.Egress): An instance of the Egress class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.egress_eafa79ad778e0a6c6cd87e7f67bde5ec import Egress
if self._properties.get('Egress', None) is not None:
return self._properties.get('Egress')
else:
return Egress(self)._select()
@property
def Ingress(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.ingress_da8eb3f5bded227d4615e7b9e030b32d.Ingress): An instance of the Ingress class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.ingress_da8eb3f5bded227d4615e7b9e030b32d import Ingress
if self._properties.get('Ingress', None) is not None:
return self._properties.get('Ingress')
else:
return Ingress(self)._select()
@property
def TunnelLeafRange(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.tunnelleafrange_66cac69e2e026fc7d2fdc68b1e28e7ca.TunnelLeafRange): An instance of the TunnelLeafRange class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.tunnelleafrange_66cac69e2e026fc7d2fdc68b1e28e7ca import TunnelLeafRange
if self._properties.get('TunnelLeafRange', None) is not None:
return self._properties.get('TunnelLeafRange')
else:
return TunnelLeafRange(self)
@property
def TunnelTailTrafficEndPoint(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.tunneltailtrafficendpoint_284f93fd059aad011661455f3f6293cb.TunnelTailTrafficEndPoint): An instance of the TunnelTailTrafficEndPoint class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.tunneltailtrafficendpoint_284f93fd059aad011661455f3f6293cb import TunnelTailTrafficEndPoint
if self._properties.get('TunnelTailTrafficEndPoint', None) is not None:
return self._properties.get('TunnelTailTrafficEndPoint')
else:
return TunnelTailTrafficEndPoint(self)
@property
def Behavior(self):
# type: () -> str
"""
Returns
-------
- str(ingress | egress): Indicates whether the destination range corresponds to an Ingress or Egress router.
"""
return self._get_attribute(self._SDM_ATT_MAP['Behavior'])
@Behavior.setter
def Behavior(self, value):
# type: (str) -> None
self._set_attribute(self._SDM_ATT_MAP['Behavior'], value)
@property
def EmulationType(self):
# type: () -> str
"""
Returns
-------
- str(reserved | rsvpTe | rsvpTeP2mP): The emulation type selected, the values being RSVP-TE, RSVP-TE P2MP.
"""
return self._get_attribute(self._SDM_ATT_MAP['EmulationType'])
@EmulationType.setter
def EmulationType(self, value):
# type: (str) -> None
self._set_attribute(self._SDM_ATT_MAP['EmulationType'], value)
@property
def EnableReplyingLspPing(self):
# type: () -> bool
"""
Returns
-------
- bool: NOT DEFINED
"""
return self._get_attribute(self._SDM_ATT_MAP['EnableReplyingLspPing'])
@EnableReplyingLspPing.setter
def EnableReplyingLspPing(self, value):
# type: (bool) -> None
self._set_attribute(self._SDM_ATT_MAP['EnableReplyingLspPing'], value)
@property
def Enabled(self):
# type: () -> bool
"""
Returns
-------
- bool: Enables or disables the use of the destination range.
"""
return self._get_attribute(self._SDM_ATT_MAP['Enabled'])
@Enabled.setter
def Enabled(self, value):
# type: (bool) -> None
self._set_attribute(self._SDM_ATT_MAP['Enabled'], value)
@property
def IpAddressFrom(self):
# type: () -> str
"""
Returns
-------
- str: The IP address of the first destination router.
"""
return self._get_attribute(self._SDM_ATT_MAP['IpAddressFrom'])
@IpAddressFrom.setter
def IpAddressFrom(self, value):
# type: (str) -> None
self._set_attribute(self._SDM_ATT_MAP['IpAddressFrom'], value)
@property
def IpCount(self):
# type: () -> int
"""
Returns
-------
- number: The number of destination routers. Each router's address is one greater than the previous one's.
"""
return self._get_attribute(self._SDM_ATT_MAP['IpCount'])
@IpCount.setter
def IpCount(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['IpCount'], value)
@property
def IsConnectedIpAppended(self):
# type: () -> bool
"""
Returns
-------
- bool: Append the connected IP as RRO/SRRO subobject at the end of the RRo/SRRO list in the packet.
"""
return self._get_attribute(self._SDM_ATT_MAP['IsConnectedIpAppended'])
@IsConnectedIpAppended.setter
def IsConnectedIpAppended(self, value):
# type: (bool) -> None
self._set_attribute(self._SDM_ATT_MAP['IsConnectedIpAppended'], value)
@property
def IsHeadIpPrepended(self):
# type: () -> bool
"""
Returns
-------
- bool: If true, prepend the tunnel head IP as a RRO/SERO subobject at the beginning of the RRO/SRRO list in the packet.
"""
return self._get_attribute(self._SDM_ATT_MAP['IsHeadIpPrepended'])
@IsHeadIpPrepended.setter
def IsHeadIpPrepended(self, value):
# type: (bool) -> None
self._set_attribute(self._SDM_ATT_MAP['IsHeadIpPrepended'], value)
@property
def IsLeafIpPrepended(self):
# type: () -> bool
"""
Returns
-------
- bool: If true, prepend the tunnel leaf IP as a RRO/SRRO subobject at the beginning of the RRO/SRRO list in the packet.
"""
return self._get_attribute(self._SDM_ATT_MAP['IsLeafIpPrepended'])
@IsLeafIpPrepended.setter
def IsLeafIpPrepended(self, value):
# type: (bool) -> None
self._set_attribute(self._SDM_ATT_MAP['IsLeafIpPrepended'], value)
@property
def IsSendingAsRro(self):
# type: () -> bool
"""
Returns
-------
- bool: If true, send this as a RRO. True only if emulation type is RSVP-TE P2MP.
"""
return self._get_attribute(self._SDM_ATT_MAP['IsSendingAsRro'])
@IsSendingAsRro.setter
def IsSendingAsRro(self, value):
# type: (bool) -> None
self._set_attribute(self._SDM_ATT_MAP['IsSendingAsRro'], value)
@property
def IsSendingAsSrro(self):
# type: () -> bool
"""
Returns
-------
- bool: If true, send this as a SRRO. Note that both Send as RRO and Send as SRRO can be selected at the same time if so required by the user. True only if emulation type is RSVP-TE P2MP.
"""
return self._get_attribute(self._SDM_ATT_MAP['IsSendingAsSrro'])
@IsSendingAsSrro.setter
def IsSendingAsSrro(self, value):
# type: (bool) -> None
self._set_attribute(self._SDM_ATT_MAP['IsSendingAsSrro'], value)
@property
def P2mpId(self):
# type: () -> str
"""
Returns
-------
- str: The P2MP id represented in IP address format.
"""
return self._get_attribute(self._SDM_ATT_MAP['P2mpId'])
@P2mpId.setter
def P2mpId(self, value):
# type: (str) -> None
self._set_attribute(self._SDM_ATT_MAP['P2mpId'], value)
def update(self, Behavior=None, EmulationType=None, EnableReplyingLspPing=None, Enabled=None, IpAddressFrom=None, IpCount=None, IsConnectedIpAppended=None, IsHeadIpPrepended=None, IsLeafIpPrepended=None, IsSendingAsRro=None, IsSendingAsSrro=None, P2mpId=None):
# type: (str, str, bool, bool, str, int, bool, bool, bool, bool, bool, str) -> DestinationRange
"""Updates destinationRange resource on the server.
Args
----
- Behavior (str(ingress | egress)): Indicates whether the destination range corresponds to an Ingress or Egress router.
- EmulationType (str(reserved | rsvpTe | rsvpTeP2mP)): The emulation type selected, the values being RSVP-TE, RSVP-TE P2MP.
- EnableReplyingLspPing (bool): NOT DEFINED
- Enabled (bool): Enables or disables the use of the destination range.
- IpAddressFrom (str): The IP address of the first destination router.
- IpCount (number): The number of destination routers. Each router's address is one greater than the previous one's.
- IsConnectedIpAppended (bool): Append the connected IP as RRO/SRRO subobject at the end of the RRo/SRRO list in the packet.
- IsHeadIpPrepended (bool): If true, prepend the tunnel head IP as a RRO/SERO subobject at the beginning of the RRO/SRRO list in the packet.
- IsLeafIpPrepended (bool): If true, prepend the tunnel leaf IP as a RRO/SRRO subobject at the beginning of the RRO/SRRO list in the packet.
- IsSendingAsRro (bool): If true, send this as a RRO. True only if emulation type is RSVP-TE P2MP.
- IsSendingAsSrro (bool): If true, send this as a SRRO. Note that both Send as RRO and Send as SRRO can be selected at the same time if so required by the user. True only if emulation type is RSVP-TE P2MP.
- P2mpId (str): The P2MP id represented in IP address format.
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))
def add(self, Behavior=None, EmulationType=None, EnableReplyingLspPing=None, Enabled=None, IpAddressFrom=None, IpCount=None, IsConnectedIpAppended=None, IsHeadIpPrepended=None, IsLeafIpPrepended=None, IsSendingAsRro=None, IsSendingAsSrro=None, P2mpId=None):
# type: (str, str, bool, bool, str, int, bool, bool, bool, bool, bool, str) -> DestinationRange
"""Adds a new destinationRange resource | |
<reponame>LiuHao-THU/frame2d
"""
Time: 2017.12.27
Author: LiuHao
Institution:THU
"""
"""
dense net name
conv1/bn + conv1/scale + conv1//relu + conv1 + pool2(max)
conv2_1/x1.2(/bn+/scale+relu+conv)
...
conv2_6/x1.2(/bn+/scale+relu+conv) concat
conv2_blk/bn + conv2_blk/scale + conv2_blk/relu + conv2_blk + pool2(avg)
conv3_1/x1.2(/bn+/scale+relu+conv)
...
conv3_12/x1.2(/bn+/scale+relu+conv) concat
conv3_blk/bn + conv3_blk/scale + conv3_blk/relu + conv3_blk + pool3(avg)
conv4_1/x1.2(/bn+/scale+relu+conv)
...
conv4_2/x1.2(/bn+/scale+relu+conv) concat
conv4_blk/bn + conv4_blk/scale + conv4_blk/relu + conv4_blk + pool4(avg)
conv5_1/x1.2(/bn+/scale+relu+conv)
...
conv5_16/x1.2(/bn+/scale+relu+conv) concat
"""
# input dimension batch_size * 224 * 224 * channels
# out_size batch_size * 8 * 8 * 1024
"""
This code is the first edition of the dense net for segmentation
The encode part use the pretrained network from the "https://github.com/shicai/DenseNet-Caffe"
we use transpose convolution and deconv operation
"""
import math
import numpy as np
import tensorflow as tf
from functools import reduce
from tensorflow.python.ops import random_ops
import six
from tensorflow.python.training.moving_averages import assign_moving_average
from .configs import configs
K = 32
middle_layer = K * 4
class Dense_Linknet:
# some properties
"""
Initialize function
"""
def __init__(self, npy_path=None, trainable=True, open_tensorboard=False, dropout=0.8):
if npy_path is not None:
self.data_dict = np.load(npy_path, encoding='latin1').item()
else:
self.data_dict = None
self.var_dict = {}
self.trainable = trainable
self.open_tensorboard = open_tensorboard
self.dropout = dropout
def set_is_training(self, isTrain):
self.is_training = isTrain
def build(self, rgb, label_num, train_mode=None, last_layer_type = "softmax"):
"""
load variable from npy to build the Resnet or Generate a new one
:param rgb: rgb image [batch, height, width, 3] values scaled [0, 1]
:param train_mode: a bool tensor, usually a placeholder: if True, dropout will be turned on
"""
self.train_mode = train_mode
red, green, blue = tf.split(axis=3, num_or_size_splits=3, value=rgb)
assert red.get_shape().as_list()[1:] == [224, 224, 1]
assert green.get_shape().as_list()[1:] == [224, 224, 1]
assert blue.get_shape().as_list()[1:] == [224, 224, 1]
bgr = tf.concat(axis=3, values=[
blue - configs['VGG_MEAN'][0],
green - configs['VGG_MEAN'][1],
red - configs['VGG_MEAN'][2],
])
print(bgr.get_shape().as_list())
assert bgr.get_shape().as_list()[1:] == [224, 224, 3]
self.conv1_1 = self.Conv_Relu(name = "conv1_1", bottom = bgr, out_channels = 64, kernel_size = 3, stride = 1)
self.conv1_2 = self.Conv_Relu(name = "conv1_2", bottom = self.conv1_1, out_channels = 64, kernel_size = 3, stride = 1)#224 224
self.pool1 = self.max_pool(self.conv1_2, kernel_size = 2, stride = 2, name = "pool1")
self.conv2_1 = self.Conv_Relu(name = "conv2_1", bottom = self.pool1, out_channels = 128, kernel_size = 3, stride = 1)
self.conv2_2 = self.Conv_Relu(name = "conv2_2", bottom = self.conv2_1, out_channels = 128, kernel_size = 3, stride = 1)#112 112
self.pool2 = self.max_pool(self.conv2_2, kernel_size = 2, stride = 2, name = "pool2")
self.conv3_1 = self.Conv_Relu(name = "conv3_1", bottom = self.pool2, out_channels = 256, kernel_size = 3, stride = 1)
self.conv3_2 = self.Conv_Relu(name = "conv3_2", bottom = self.conv3_1, out_channels = 256, kernel_size = 3, stride = 1)
self.conv3_3 = self.Conv_Relu(name = "conv3_3", bottom = self.conv3_2, out_channels = 256, kernel_size = 3, stride = 1)#56 56
self.pool3 = self.max_pool(self.conv3_3, kernel_size = 2, stride = 2, name = "pool3")
self.conv4_1 = self.Conv_Relu(name = "conv4_1", bottom = self.pool3, out_channels = 512, kernel_size = 3, stride = 1)
self.conv4_2 = self.Conv_Relu(name = "conv4_2", bottom = self.conv4_1, out_channels = 512, kernel_size = 3, stride = 1)
self.conv4_3 = self.Conv_Relu(name = "conv4_3", bottom = self.conv4_2, out_channels = 512, kernel_size = 3, stride = 1)#28 28
self.pool4 = self.max_pool(self.conv4_3, kernel_size = 2, stride = 2, name = "pool4")
self.conv5_1 = self.Conv_Relu(name = "conv5_1", bottom = self.pool4, out_channels = 512, kernel_size = 3, stride = 1)
self.conv5_2 = self.Conv_Relu(name = "conv5_2", bottom = self.conv5_1, out_channels = 512, kernel_size = 3, stride = 1)
self.conv5_3 = self.Conv_Relu(name = "conv5_3", bottom = self.conv5_2, out_channels = 512, kernel_size = 3, stride = 1)#14 14
self.pool5 = self.max_pool(self.conv5_3, kernel_size = 2, stride = 2, name = "pool5") #512 7 7
def fc_layer(self, bottom, out_channels, relu):
input_shape = bottom.get_shape().as_list()
conv = self.conv_layer(bottom = bottom, kernel_size = kernel_size, in_channels = input_shape[-1],
out_channels = output_channels, stride = stride, name = name)
if relu == True:
relu = tf.nn.relu(conv)
else:
relu = conv
return relu
self.fc6 = self._fc_layer(self.pool5, "fc6")
if train:
self.fc6 = tf.nn.dropout(self.fc6, 0.5)
self.fc7 = self._fc_layer(self.fc6, "fc7")
if train:
self.fc7 = tf.nn.dropout(self.fc7, 0.5)
if use_dilated:
self.pool5 = tf.batch_to_space(self.pool5, crops=pad, block_size=2)
self.pool5 = tf.batch_to_space(self.pool5, crops=pad, block_size=2)
self.fc7 = tf.batch_to_space(self.fc7, crops=pad, block_size=2)
self.fc7 = tf.batch_to_space(self.fc7, crops=pad, block_size=2)
return
if random_init_fc8:
self.score_fr = self._score_layer(self.fc7, "score_fr",
num_classes)
else:
self.score_fr = self._fc_layer(self.fc7, "score_fr",
num_classes=num_classes,
relu=False)
self.pred = tf.argmax(self.score_fr, dimension=3)
self.upscore2 = self._upscore_layer(self.score_fr,
shape=tf.shape(self.pool4),
num_classes=num_classes,
debug=debug, name='upscore2',
ksize=4, stride=2)
self.score_pool4 = self._score_layer(self.pool4, "score_pool4",
num_classes=num_classes)
self.fuse_pool4 = tf.add(self.upscore2, self.score_pool4)
self.upscore4 = self._upscore_layer(self.fuse_pool4,
shape=tf.shape(self.pool3),
num_classes=num_classes,
debug=debug, name='upscore4',
ksize=4, stride=2)
self.score_pool3 = self._score_layer(self.pool3, "score_pool3",
num_classes=num_classes)
self.fuse_pool3 = tf.add(self.upscore4, self.score_pool3)
self.upscore32 = self._upscore_layer(self.fuse_pool3,
shape=tf.shape(bgr),
num_classes=num_classes,
debug=debug, name='upscore32',
ksize=16, stride=8)
self.pred_up = tf.argmax(self.upscore32, dimension=3)
self.y_soft = tf.nn.softmax(self.final_layer)
output_shape = self.final_layer.get_shape().as_list()
self.logits = tf.reshape(self.final_layer,[output_shape[0],-1, 21])
# self.logits = tf.reshape(self.final_layer, (-1, 3))
self.pred = tf.argmax(self.y_soft, axis = 3)
def Conv_Relu(self, name, bottom, out_channels, kernel_size, stride = 1):
input_shape = bottom.get_shape().as_list()
conv = self.conv_layer(bottom = bottom, kernel_size = kernel_size, in_channels = input_shape[-1],
out_channels = output_channels, stride = stride, name = name)
relu = tf.nn.relu(conv)
return relu
def ResNet_Block(self, bottom, channel_list, name):
input_filter = bottom.get_shape().as_list()[-1]
conv_bn_relu1 = self.Conv_Bn_Relu(name = name + '_branch2a', bottom = bottom, output_channels = channel_list[0], kernel_size = 1, stride = 1, relu = True, bn = True)
conv_bn_relu2 = self.Conv_Bn_Relu(name = name + '_branch2b', bottom = conv_bn_relu1, output_channels = channel_list[1], kernel_size = 3, stride = 1, relu = True, bn = True)
block_conv_3 = self.conv_layer(conv_bn_relu2, 1, channel_list[1], channel_list[2], 1, name + '_branch2c')
relu = tf.nn.relu(block_conv_3)
block_res = tf.add(bottom, relu)
return block_res
def _upscore_layer(self, bottom, shape, num_classes, name, debug, ksize=4, stride=2):
strides = [1, stride, stride, 1]
with tf.variable_scope(name):
in_features = bottom.get_shape()[3].value
if shape is None:
# Compute shape out of Bottom
in_shape = tf.shape(bottom)
h = ((in_shape[1] - 1) * stride) + 1
w = ((in_shape[2] - 1) * stride) + 1
new_shape = [in_shape[0], h, w, num_classes]
else:
new_shape = [shape[0], shape[1], shape[2], num_classes]
output_shape = tf.stack(new_shape)
logging.debug("Layer: %s, Fan-in: %d" % (name, in_features))
f_shape = [ksize, ksize, num_classes, in_features]
# create
num_input = ksize * ksize * in_features / stride
stddev = (2 / num_input)**0.5
weights = self.get_deconv_filter(f_shape)
# self._add_wd_and_summary(weights, self.wd, "fc_wlosses")
deconv = tf.nn.conv2d_transpose(bottom, weights, output_shape,
strides=strides, padding='SAME')
_activation_summary(deconv)
return deconv
def get_deconv_filter(self, f_shape):
width = f_shape[0]
height = f_shape[1]
f = ceil(width/2.0)
c = (2 * f - 1 - f % 2) / (2.0 * f)
bilinear = np.zeros([f_shape[0], f_shape[1]])
for x in range(width):
for y in range(height):
value = (1 - abs(x / f - c)) * (1 - abs(y / f - c))
bilinear[x, y] = value
weights = np.zeros(f_shape)
for i in range(f_shape[2]):
weights[:, :, i, i] = bilinear
init = tf.constant_initializer(value=weights,
dtype=tf.float32)
var = tf.get_variable(name="up_filter", initializer=init,
shape=weights.shape)
return var
def Dense_Block(self, bottom, name, stride = 1):
"""
dense block composed with a down channel convlution with fiter_size =1
and a up channel convolution with fiter_size = 3
"""
input_channels = bottom.get_shape().as_list()[-1]
dense_block_1 = self.BN_Relu_Conv(name + '_x1', bottom, input_channels = input_channels,
output_channels = K*4, kernel_size = 1, stride = 1)
dense_block_2 = self.BN_Relu_Conv(name + '_x2', dense_block_1, input_channels = K*4,
output_channels = K, kernel_size = 3, stride = 1)
dense_block = tf.concat([bottom, dense_block_2], axis = 3)
print('Dense_Block layer {0} -> {1}'.format(bottom.get_shape().as_list(),dense_block.get_shape().as_list()))
return dense_block
def BN_Relu_Conv(self, name, bottom, input_channels, output_channels, kernel_size, stride = 1):
batch_norm_scale = self.batch_norm_layer(name, bottom,phase_train = self.train_mode)
relu = tf.nn.relu(batch_norm_scale)
conv = self.conv_layer(bottom = relu, kernel_size = kernel_size, in_channels = input_channels,
out_channels = output_channels, stride = stride, name = name)
return conv
def Conv_Bn_Relu(self, name, bottom, output_channels, kernel_size, stride = 1, relu = True, bn = True):
input_channels = bottom.get_shape().as_list()[-1]
conv_layer = self.conv_layer(bottom = bottom, kernel_size = kernel_size, in_channels = input_channels,
out_channels = output_channels, stride = stride, regularizer=tf.contrib.layers.l2_regularizer(0.0005) ,name = name)
if bn == True:
batch_norm_scale = self.batch_norm_layer(name = name, bottom = conv_layer, phase_train = self.train_mode)
else:
batch_norm_scale = conv_layer
if relu == True:
relu_layer = tf.nn.relu(batch_norm_scale)
else:
relu_layer = batch_norm_scale
return relu_layer
def avg_pool(self,bottom, kernel_size = 2, stride = 2, name = "avg"):
avg_pool = tf.nn.avg_pool(bottom, ksize=[1, kernel_size, kernel_size, 1], strides=[1, stride, stride, 1], padding='SAME', name=name)
print('avg_pool layer {0} -> {1}'.format(bottom.get_shape().as_list(),avg_pool.get_shape().as_list()))
return avg_pool
def max_pool(self,bottom, kernel_size = 3, stride = 2, name = "max"):
max_pool = tf.nn.max_pool(bottom, ksize=[1, kernel_size, kernel_size, 1], | |
<filename>caption_vae/models/transformer.py
# -*- coding: utf-8 -*-
"""
Created on 28 Dec 2020 18:00:01
@author: jiahuei
Based on `The Annotated Transformer`
https://nlp.seas.harvard.edu/2018/04/03/attention.html
"""
import logging
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from argparse import ArgumentParser, _ArgumentGroup
from typing import Union, Dict, Callable
from copy import deepcopy
from itertools import chain
from models import register_model
from models.caption_model import CaptionModel
from data.collate import UpDownCollate
from utils.model_utils import repeat_tensors, clones
logger = logging.getLogger(__name__)
# noinspection PyAbstractClass
class EncoderDecoder(nn.Module):
"""
A standard Encoder-Decoder architecture.
Base for this and many other models.
"""
def __init__(
self, encoder: Callable, decoder: Callable,
src_embed: Callable, tgt_embed: Callable, generator: Callable,
autoregressive: bool = True, pad_idx: int = 0
):
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.src_embed = src_embed
self.tgt_embed = tgt_embed
self.generator = generator
self.autoregressive = autoregressive
self.pad_idx = pad_idx
def forward(self, src: Tensor, src_mask: Tensor, tgt: Tensor):
"""
Args:
src: (N, S, E)
src_mask: (N, S)
tgt: (N, T)
Returns:
"""
memory, memory_mask = self.encode(src, src_mask)
decoder_output = self.decode(tgt, memory, memory_mask)
outputs = self.generator(decoder_output)
return outputs
def encode(self, src: Tensor, src_mask: Tensor):
"""
Args:
src: (N, S, E)
src_mask: (N, S)
Returns:
"""
assert src_mask.ndimension() == 2, (
f"{self.__class__.__name__}: Expected `src_mask` has shape (N, S), saw `{src_mask.shape}`"
)
src_mask = src_mask.unsqueeze(-2)
src = self.src_embed(src)
encoder_output = self.encoder(x=src, mask=src_mask)
if logger.isEnabledFor(logging.DEBUG):
logger.debug(
f"{self.__class__.__name__}: "
f"src.shape = `{src.shape}` "
f"src_mask.shape = `{src_mask.shape}` "
f"encoder_output.shape = `{encoder_output.shape}` "
)
return encoder_output, src_mask
def decode(self, tgt: Tensor, memory: Tensor, memory_mask: Tensor):
"""
Args:
tgt: (N, T)
memory: (N, S, E)
memory_mask: (N, S)
Returns:
"""
assert tgt.ndimension() == 2, (
f"{self.__class__.__name__}: Expected `tgt` has shape (N, T), saw `{tgt.shape}`"
)
if memory.size(0) != tgt.size(0):
assert tgt.size(0) % memory.size(0) == 0
seq_per_img = int(tgt.size(0) / memory.size(0))
memory, memory_mask = repeat_tensors(seq_per_img, (memory, memory_mask))
tgt_mask = tgt.ne(self.pad_idx).unsqueeze(-2)
if self.autoregressive:
subsequent_mask = memory.new_ones((1, tgt.size(-1), tgt.size(-1)))
subsequent_mask = torch.triu(subsequent_mask, diagonal=1).eq(0)
tgt_mask = tgt_mask & subsequent_mask
tgt_embed = self.tgt_embed(tgt)
decoder_output = self.decoder(
x=tgt_embed, memory=memory, src_mask=memory_mask, tgt_mask=tgt_mask
)
if logger.isEnabledFor(logging.DEBUG):
logger.debug(
f"{self.__class__.__name__}: "
f"tgt.shape = `{tgt.shape}` "
f"tgt_mask.shape = `{tgt_mask.shape}` "
f"tgt_embed.shape = `{tgt_embed.shape}` "
f"memory.shape = `{memory.shape}` "
f"memory_mask.shape = `{memory_mask.shape}` "
f"decoder_output.shape = `{decoder_output.shape}` "
)
return decoder_output
def generate(self, x):
return self.generator(x)
# noinspection PyAbstractClass
class Encoder(nn.Module):
"""
Core encoder is a stack of N layers
"""
def __init__(self, layer, N):
super().__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, mask):
"""Pass the input (and mask) through each layer in turn."""
for layer in self.layers:
x = layer(x, mask)
return self.norm(x)
# noinspection PyAbstractClass
class EncoderLayer(nn.Module):
"""
Encoder is made up of self-attn and feed forward
"""
def __init__(self, size, self_attn, feed_forward, dropout):
super().__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 2)
self.size = size
def forward(self, x, mask):
"""Follow Figure 1 (left) for connections."""
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
return self.sublayer[1](x, self.feed_forward)
# noinspection PyAbstractClass
class Decoder(nn.Module):
"""Generic N layer decoder with masking."""
def __init__(self, layer, N):
super().__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, memory, src_mask, tgt_mask):
for layer in self.layers:
x = layer(x, memory, src_mask, tgt_mask)
return self.norm(x)
# noinspection PyAbstractClass
class DecoderLayer(nn.Module):
"""Decoder is made of self-attn, src-attn, and feed forward (defined below)"""
def __init__(self, size, self_attn, src_attn, feed_forward, dropout):
super().__init__()
self.size = size
self.self_attn = self_attn
self.src_attn = src_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 3)
def forward(self, x, memory, src_mask, tgt_mask):
"""Follow Figure 1 (right) for connections."""
m = memory
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))
x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask))
return self.sublayer[2](x, self.feed_forward)
# noinspection PyAbstractClass
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1, self_attention=False):
"""Take in model size and number of heads."""
super().__init__()
assert d_model % h == 0
# We assume d_v always equals d_k
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.self_attention = self_attention
self.dropout = nn.Dropout(p=dropout)
self.cache = [None, None]
self.cache_size = 2
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
if mask is not None:
# Same mask applied to all h heads.
mask = mask.unsqueeze(1)
nbatches = query.size(0)
# 1) Do all the linear projections in batch from d_model => h x d_k
query = self._project_qkv(self.linears[0], query)
# Maybe need to repeat cache along batch dim
if isinstance(self.cache[0], Tensor) and self.cache[0].size(0) != key.size(0):
cache_batch = self.cache[0].size(0)
assert cache_batch < key.size(0), (
f"cat_output_with_cache: "
f"Expected dim {0} of cached tensor to be smaller than that of key. "
f"Saw self.cache[0] = {self.cache[0].size()}, key = {key.size()}"
)
assert key.size(0) % cache_batch == 0, (
f"cat_output_with_cache: "
f"Expected dim {0} of key tensor to be divisible by that of cached tensor. "
f"Saw self.cache[0] = {self.cache[0].size()}, key = {key.size()}"
)
self.cache = repeat_tensors(key.size(0) // cache_batch, self.cache)
# Only encoder-attention may skip projection and directly reuse from cache
if not self.self_attention and isinstance(self.cache[0], Tensor):
key, value = self.cache
else:
key = self._project_qkv(self.linears[1], key)
value = self._project_qkv(self.linears[2], value)
if self.self_attention and isinstance(self.cache[0], Tensor):
# Concat with previous keys and values
key = torch.cat((self.cache[0], key), dim=2)
value = torch.cat((self.cache[1], value), dim=2)
mask = None
# Cache key and value tensors
if getattr(self, "incremental_decoding", False):
self.cache = [key, value]
# 2) Apply attention on all the projected vectors in batch.
x, attn = self.attention(query, key, value, mask=mask, dropout=self.dropout)
# 3) "Concat" using a view and apply a final linear.
x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)
return self.linears[-1](x)
def _project_qkv(self, layer, x):
return layer(x).view(x.size(0), -1, self.h, self.d_k).transpose(1, 2)
@staticmethod
def attention(query, key, value, mask=None, dropout=None):
"""Compute 'Scaled Dot Product Attention'"""
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
p_attn = F.softmax(scores, dim=-1)
if dropout is not None:
p_attn = dropout(p_attn)
return torch.matmul(p_attn, value), p_attn
# noinspection PyAbstractClass
class CachedMultiHeadedAttention(MultiHeadedAttention):
def __init__(self, *args, **kwargs):
"""Take in model size and number of heads."""
super().__init__(*args, **kwargs)
self.incremental_decoding = False
def reset_cache(self):
self.cache = [None, None]
# Aliases
MHA = MultiHeadedAttention
CMHA = CachedMultiHeadedAttention
# noinspection PyAbstractClass
class PositionwiseFeedForward(nn.Module):
"""Implements FFN equation."""
def __init__(self, d_model, d_ff, dropout=0.1):
super().__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
return self.w_2(self.dropout(F.relu(self.w_1(x))))
# noinspection PyAbstractClass
class LayerNorm(nn.Module):
"""Construct a layernorm module (See citation for details)."""
def __init__(self, features, eps=1e-6):
super().__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
# noinspection PyAbstractClass
class SublayerConnection(nn.Module):
"""
A residual connection followed by a layer norm.
Note for code simplicity the norm is first as opposed to last.
"""
def __init__(self, size, dropout):
super().__init__()
self.norm = LayerNorm(size)
self.dropout = nn.Dropout(dropout)
def forward(self, x, sublayer):
"""Apply residual connection to any sublayer with the same size."""
return x + self.dropout(sublayer(self.norm(x)))
# noinspection PyAbstractClass
class PositionalEncoding(nn.Module):
"""Implement the PE function."""
def __init__(self, d_model, dropout, max_len=5000):
super().__init__()
self.dropout = nn.Dropout(p=dropout)
# Compute the positional encodings once in log space.
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len).unsqueeze(1).float()
div_term = torch.exp(
torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)
)
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer("pe", pe)
self.incremental_decoding = False
self.current_time_step = 0
def reset_cache(self):
self.current_time_step = 0
def forward(self, x):
if self.incremental_decoding:
assert x.size(1) == 1, \
f"{self.__class__.__name__}: Expected input to have shape (M, 1, N), saw {x.shape}"
x = x + self.pe[:, self.current_time_step:self.current_time_step + 1]
self.current_time_step += 1
else:
x = x + self.pe[:, :x.size(1)]
return self.dropout(x)
# noinspection PyAbstractClass
class InputEmbedding(nn.Module):
def __init__(self, d_model, vocab):
super().__init__()
self.lut = nn.Embedding(vocab, d_model)
self.d_model = d_model
def forward(self, x):
return self.lut(x) * math.sqrt(self.d_model)
# noinspection PyAbstractClass
class OutputEmbedding(nn.Module):
"""Define standard linear + softmax generation step."""
def __init__(self, d_model, vocab):
super().__init__()
self.proj = nn.Linear(d_model, vocab)
def forward(self, x):
return F.log_softmax(self.proj(x), dim=-1)
# noinspection PyAbstractClass,PyAttributeOutsideInit
class CachedTransformerBase(CaptionModel):
def __init__(self, config):
super().__init__()
self.config = config
self.d_model = config.d_model # default: 512
self.dim_feedforward = config.dim_feedforward # default: 2048
self.num_layers = config.num_layers # default: 6
self.drop_prob_src = config.drop_prob_src
self.seq_length = config.max_seq_length
self.att_feat_size = config.att_feat_size
self.vocab_size = | |
"""
Generated API Documentation for Server API using server_doc_gen.py."""
doc = {
"@context": {
"ApiDocumentation": "hydra:ApiDocumentation",
"description": "hydra:description",
"domain": {
"@id": "rdfs:domain",
"@type": "@id"
},
"expects": {
"@id": "hydra:expects",
"@type": "@id"
},
"expectsHeader": "hydra:expectsHeader",
"hydra": "http://www.w3.org/ns/hydra/core#",
"label": "rdfs:label",
"manages": "hydra:manages",
"method": "hydra:method",
"possibleStatus": "hydra:possibleStatus",
"property": {
"@id": "hydra:property",
"@type": "@id"
},
"range": {
"@id": "rdfs:range",
"@type": "@id"
},
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"readable": "hydra:readable",
"required": "hydra:required",
"returns": {
"@id": "hydra:returns",
"@type": "@id"
},
"returnsHeader": "hydra:returnsHeader",
"statusCode": "hydra:statusCode",
"subClassOf": {
"@id": "rdfs:subClassOf",
"@type": "@id"
},
"supportedClass": "hydra:supportedClass",
"supportedOperation": "hydra:supportedOperation",
"supportedProperty": "hydra:supportedProperty",
"title": "hydra:title",
"vocab": "http://localhost:8080/api/vocab#",
"writeable": "hydra:writeable"
},
"@id": "http://localhost:8080/api/vocab",
"@type": "ApiDocumentation",
"description": "API Documentation for the server side system",
"possibleStatus": [],
"supportedClass": [
{
"@id": "vocab:Drone",
"@type": "hydra:Class",
"description": "Class for a drone",
"supportedOperation": [
{
"@type": "http://schema.org/UpdateAction",
"expects": "vocab:Drone",
"expectsHeader": [
{
"description": "Drone updated",
"statusCode": 200
}
],
"method": "POST",
"possibleStatus": [],
"returns": "null",
"returnsHeader": [],
"title": "SubmitDrone"
},
{
"@type": "http://schema.org/AddAction",
"expects": "vocab:Drone",
"expectsHeader": [
{
"description": "Drone updated",
"statusCode": 200
}
],
"method": "PUT",
"possibleStatus": [],
"returns": "null",
"returnsHeader": [],
"title": "UpdateDrone"
},
{
"@type": "http://schema.org/FindAction",
"expects": "null",
"expectsHeader": [
{
"description": "Drone not found",
"statusCode": 404
},
{
"description": "Drone Returned",
"statusCode": 200
}
],
"method": "GET",
"possibleStatus": [],
"returns": "vocab:Drone",
"returnsHeader": [],
"title": "GetDrone"
},
{
"@type": "http://schema.org/DeleteAction",
"expects": "null",
"expectsHeader": [
{
"description": "Drone not found",
"statusCode": 404
},
{
"description": "Drone successfully deleted.",
"statusCode": 200
}
],
"method": "DELETE",
"possibleStatus": [],
"returns": "null",
"returnsHeader": [],
"title": "DeleteDrone"
}
],
"supportedProperty": [
{
"@type": "SupportedProperty",
"property": "vocab:State",
"readable": "false",
"required": "true",
"title": "State",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/name",
"readable": "false",
"required": "true",
"title": "name",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/model",
"readable": "false",
"required": "true",
"title": "model",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://auto.schema.org/speed",
"readable": "false",
"required": "true",
"title": "MaxSpeed",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/device",
"readable": "false",
"required": "true",
"title": "Sensor",
"writeable": "false"
}
],
"title": "Drone"
},
{
"@id": "vocab:State",
"@type": "hydra:Class",
"description": "Class for drone state objects",
"supportedOperation": [
{
"@type": "http://schema.org/FindAction",
"expects": "null",
"expectsHeader": [
{
"description": "State not found",
"statusCode": 404
},
{
"description": "State Returned",
"statusCode": 200
}
],
"method": "GET",
"possibleStatus": [],
"returns": "vocab:State",
"returnsHeader": [],
"title": "GetState"
}
],
"supportedProperty": [
{
"@type": "SupportedProperty",
"property": "http://auto.schema.org/speed",
"readable": "false",
"required": "true",
"title": "Speed",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/geo",
"readable": "false",
"required": "true",
"title": "Position",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/Property",
"readable": "false",
"required": "true",
"title": "Direction",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/fuelCapacity",
"readable": "false",
"required": "true",
"title": "Battery",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "https://schema.org/status",
"readable": "false",
"required": "true",
"title": "Status",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/identifier",
"readable": "false",
"required": "true",
"title": "DroneID",
"writeable": "false"
}
],
"title": "State"
},
{
"@id": "vocab:Datastream",
"@type": "hydra:Class",
"description": "Class for a datastream entry",
"supportedOperation": [
{
"@type": "http://schema.org/FindAction",
"expects": "null",
"expectsHeader": [
{
"description": "Data not found",
"statusCode": 404
},
{
"description": "Data returned",
"statusCode": 200
}
],
"method": "GET",
"possibleStatus": [],
"returns": "vocab:Datastream",
"returnsHeader": [],
"title": "ReadDatastream"
}
],
"supportedProperty": [
{
"@type": "SupportedProperty",
"property": "http://schema.org/QuantitativeValue",
"readable": "false",
"required": "true",
"title": "Temperature",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/identifier",
"readable": "false",
"required": "true",
"title": "DroneID",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/geo",
"readable": "false",
"required": "true",
"title": "Position",
"writeable": "false"
}
],
"title": "Datastream"
},
{
"@id": "vocab:DroneLog",
"@type": "hydra:Class",
"description": "Class for a drone log entry",
"supportedOperation": [
{
"@type": "http://schema.org/FindAction",
"expects": "null",
"expectsHeader": [
{
"description": "DroneLog not found",
"statusCode": 404
},
{
"description": "DroneLog returned",
"statusCode": 200
}
],
"method": "GET",
"possibleStatus": [],
"returns": "vocab:DroneLog",
"returnsHeader": [],
"title": "ReadDroneLog"
}
],
"supportedProperty": [
{
"@type": "SupportedProperty",
"property": "http://schema.org/identifier",
"readable": "false",
"required": "true",
"title": "DroneID",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/Text",
"readable": "false",
"required": "true",
"title": "LogString",
"writeable": "false"
}
],
"title": "DroneLog"
},
{
"@id": "vocab:ControllerLog",
"@type": "hydra:Class",
"description": "Class for a controller log entry",
"supportedOperation": [
{
"@type": "http://schema.org/FindAction",
"expects": "null",
"expectsHeader": [
{
"description": "ControllerLog not found",
"statusCode": 404
},
{
"description": "ControllerLog returned",
"statusCode": 200
}
],
"method": "GET",
"possibleStatus": [],
"returns": "vocab:ControllerLog",
"returnsHeader": [],
"title": "ReadControllerLog"
}
],
"supportedProperty": [
{
"@type": "SupportedProperty",
"property": "http://schema.org/Text",
"readable": "false",
"required": "true",
"title": "LogString",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/identifier",
"readable": "false",
"required": "true",
"title": "DroneID",
"writeable": "false"
}
],
"title": "ControllerLog"
},
{
"@id": "vocab:HttpApiLog",
"@type": "hydra:Class",
"description": "Class for a http api log entry",
"supportedOperation": [
{
"@type": "http://schema.org/FindAction",
"expects": "null",
"expectsHeader": [
{
"description": "HttpApiLog not found",
"statusCode": 404
},
{
"description": "HttpApiLog returned",
"statusCode": 200
}
],
"method": "GET",
"possibleStatus": [],
"returns": "vocab:HttpApiLog",
"returnsHeader": [],
"title": "ReadHttpApiLog"
}
],
"supportedProperty": [
{
"@type": "SupportedProperty",
"property": "http://schema.org/identifier",
"readable": "false",
"required": "true",
"title": "Subject",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/Action",
"readable": "false",
"required": "true",
"title": "Predicate",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "http://schema.org/identifier",
"readable": "false",
"required": "true",
"title": "Object",
"writeable": "false"
}
],
"title": "HttpApiLog"
},
{
"@id": "vocab:Location",
"@type": "hydra:Class",
"description": "Class for location of the central controller.",
"supportedOperation": [
{
"@type": "http://schema.org/UpdateAction",
"expects": "vocab:Location",
"expectsHeader": [
{
"description": "Controller location updated successfully.",
"statusCode": 200
}
],
"method": "POST",
"possibleStatus": [],
"returns": "null",
"returnsHeader": [],
"title": "UpdateLocation"
},
{
"@type": "http://schema.org/AddAction",
"expects": "vocab:Location",
"expectsHeader": [
{
"description": "Controller location added successfully.",
"statusCode": 200
}
],
"method": "PUT",
"possibleStatus": [],
"returns": "null",
"returnsHeader": [],
"title": "AddLocation"
},
{
"@type": "http://schema.org/FindAction",
"expects": "null",
"expectsHeader": [
{
"description": "Location of Controller not found.",
"statusCode": 404
},
{
"description": "Location of controller returned.",
"statusCode": 200
}
],
"method": "GET",
"possibleStatus": [],
"returns": "vocab:Location",
"returnsHeader": [],
"title": "GetLocation"
}
],
"supportedProperty": [
{
"@type": "SupportedProperty",
"property": "http://schema.org/geo",
"readable": "false",
"required": "true",
"title": "Location",
"writeable": "false"
}
],
"title": "Location"
},
{
"@id": "vocab:Command",
"@type": "hydra:Class",
"description": "Class for drone commands",
"supportedOperation": [
{
"@type": "http://schema.org/FindAction",
"expects": "null",
"expectsHeader": [
{
"description": "Command not found",
"statusCode": 404
},
{
"description": "Command Returned",
"statusCode": 200
}
],
"method": "GET",
"possibleStatus": [],
"returns": "vocab:Command",
"returnsHeader": [],
"title": "GetCommand"
},
{
"@type": "http://schema.org/AddAction",
"expects": "vocab:Command",
"expectsHeader": [
{
"description": "Command added",
"statusCode": 201
}
],
"method": "PUT",
"possibleStatus": [],
"returns": "null",
"returnsHeader": [],
"title": "AddCommand"
}
],
"supportedProperty": [
{
"@type": "SupportedProperty",
"property": "http://schema.org/identifier",
"readable": "false",
"required": "true",
"title": "DroneID",
"writeable": "false"
},
{
"@type": "SupportedProperty",
"property": "vocab:State",
"readable": "false",
"required": "true",
"title": "State",
"writeable": "false"
}
],
"title": "Command"
},
{
"@id": "vocab:Message",
"@type": "hydra:Class",
"description": "Class for messages received by the GUI interface",
"supportedOperation": [
{
"@type": "http://schema.org/FindAction",
"expects": "null",
"expectsHeader": [
{
"description": "Message not found",
"statusCode": 404
},
{
"description": "Message returned",
"statusCode": 200
}
],
"method": "GET",
"possibleStatus": [],
"returns": "vocab:Message",
"returnsHeader": [],
"title": "GetMessage"
},
{
"@type": "http://schema.org/DeleteAction",
"expects": "null",
"expectsHeader": [
{
"description": "Message not found",
"statusCode": 404
},
{
"description": "Message successfully deleted.",
"statusCode": 200
}
],
"method": "DELETE",
"possibleStatus": [],
"returns": "null",
"returnsHeader": [],
"title": "DeleteMessage"
}
],
"supportedProperty": [
{
"@type": "SupportedProperty",
"property": "http://schema.org/Text",
"readable": "false",
"required": "true",
"title": "MessageString",
"writeable": "false"
}
],
"title": "Message"
},
{
"@id": "vocab:Anomaly",
"@type": "hydra:Class",
"description": "Class for Temperature anomalies that need to be confirmed",
"supportedOperation": [
{
"@type": "http://schema.org/FindAction",
"expects": "null",
"expectsHeader": [
{
"description": "Anomaly not found",
"statusCode": 404
},
{
"description": "Anomaly returned",
"statusCode": 200
}
],
"method": "GET",
"possibleStatus": [],
"returns": "vocab:Anomaly",
"returnsHeader": [],
"title": "GetAnomaly"
},
{
"@type": "http://schema.org/AddAction",
"expects": "vocab:Anomaly",
"expectsHeader": [
{
"description": "Anomaly added successfully.",
"statusCode": 200
}
],
"method": "PUT",
"possibleStatus": [],
"returns": "null",
"returnsHeader": [],
"title": "AddAnomaly"
},
{
"@type": "http://schema.org/UpdateAction",
"expects": "vocab:Anomaly",
"expectsHeader": [
{
"description": "Anomaly updated successfully.",
"statusCode": 201
}
],
"method": "POST",
"possibleStatus": [],
"returns": "null",
"returnsHeader": [],
"title": "UpdateAnomaly"
},
{
"@type": "http://schema.org/DeleteAction",
"expects": "null",
"expectsHeader": [
{
"description": "Anomaly not found",
"statusCode": | |
#%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
print(tf.__version__)
## Load Data
#The MNIST data-set is about 12 MB and will be downloaded automatically if it is not located in the given dir.
from mnist import MNIST
data = MNIST(data_dir="data/MNIST/")
#The MNIST data-set has now been loaded and consists of 70.000 images and class-numbers for the images. The data-set is split into 3 mutually exclusive sub-sets. We will only use the training and test-sets in this tutorial.
print("Size of:")
print("- Training-set:\t\t{}".format(data.num_train))
print("- Validation-set:\t{}".format(data.num_val))
print("- Test-set:\t\t{}".format(data.num_test))
#Copy some of the data-dimensions for convenience.
# The number of pixels in each dimension of an image.
img_size = data.img_size
# The images are stored in one-dimensional arrays of this length.
img_size_flat = data.img_size_flat
# Tuple with height and width of images used to reshape arrays.
img_shape = data.img_shape
# Number of classes, one class for each of 10 digits.
num_classes = data.num_classes
# Number of colour channels for the images: 1 channel for gray-scale.
num_channels = data.num_channels
### Helper-function for plotting images
#Function used to plot 9 images in a 3x3 grid, and writing the true and predicted classes below each image.
def plot_images(images, cls_true, cls_pred=None):
assert len(images) == len(cls_true) == 9
# Create figure with 3x3 sub-plots.
fig, axes = plt.subplots(3, 3)
fig.subplots_adjust(hspace=0.3, wspace=0.3)
for i, ax in enumerate(axes.flat):
# Plot image.
ax.imshow(images[i].reshape(img_shape), cmap='binary')
# Show true and predicted classes.
if cls_pred is None:
xlabel = "True: {0}".format(cls_true[i])
else:
xlabel = "True: {0}, Pred: {1}".format(cls_true[i], cls_pred[i])
# Show the classes as the label on the x-axis.
ax.set_xlabel(xlabel)
# Remove ticks from the plot.
ax.set_xticks([])
ax.set_yticks([])
# Ensure the plot is shown correctly with multiple plots
# in a single Notebook cell.
plt.show()
### Plot a few images to see if data is correct
# Get the first images from the test-set.
images = data.x_test[0:9]
# Get the true classes for those images.
cls_true = data.y_test_cls[0:9]
# Plot the images and labels using our helper-function above.
plot_images(images=images, cls_true=cls_true)
## Input Functions for the Estimator
#Rather than providing raw data directly to the Estimator, we must provide functions that return the data. This allows for more flexibility in data-sources and how the data is randomly shuffled and iterated.
#
#Note that we will create an Estimator using the `DNNClassifier` which assumes the class-numbers are integers so we use `data.y_train_cls` instead of `data.y_train` which are one-hot encoded arrays.
#
#The function also has parameters for `batch_size`, `queue_capacity` and `num_threads` for finer control of the data reading. In our case we take the data directly from a numpy array in memory, so it is not needed.
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(data.x_train)},
y=np.array(data.y_train_cls),
num_epochs=None,
shuffle=True)
#This actually returns a function:
train_input_fn
#Calling this function returns a tuple with TensorFlow ops for returning the input and output data:
print(train_input_fn())
#Similarly we need to create a function for reading the data for the test-set. Note that we only want to process these images once so `num_epochs=1` and we do not want the images shuffled so `shuffle=False`.
test_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(data.x_test)},
y=np.array(data.y_test_cls),
num_epochs=1,
shuffle=False)
#An input-function is also needed for predicting the class of new data. As an example we just use a few images from the test-set.
some_images = data.x_test[0:9]
predict_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": some_images},
num_epochs=1,
shuffle=False)
#The class-numbers are actually not used in the input-function as it is not needed for prediction. However, the true class-number is needed when we plot the images further below.
some_images_cls = data.y_test_cls[0:9]
## Pre-Made / Canned Estimator
#When using a pre-made Estimator, we need to specify the input features for the data. In this case we want to input images from our data-set which are numeric arrays of the given shape.
feature_x = tf.feature_column.numeric_column("x", shape=img_shape)
#You can have several input features which would then be combined in a list:
feature_columns = [feature_x]
#In this example we want to use a 3-layer DNN with 512, 256 and 128 units respectively.
num_hidden_units = [512, 256, 128]
#The `DNNClassifier` then constructs the neural network for us. We can also specify the activation function and various other parameters (see the docs). Here we just specify the number of classes and the directory where the checkpoints will be saved.
model = tf.estimator.DNNClassifier(feature_columns=feature_columns,
hidden_units=num_hidden_units,
activation_fn=tf.nn.relu,
n_classes=num_classes,
model_dir="./checkpoints_tutorial17-1/")
### Training
#We can now train the model for a given number of iterations. This automatically loads and saves checkpoints so we can continue the training later.
#Note that the text `INFO:tensorflow:` is printed on every line and makes it harder to quickly read the actual progress. It should have been printed on a single line instead.
model.train(input_fn=train_input_fn, steps=2000)
### Evaluation
#Once the model has been trained, we can evaluate its performance on the test-set.
result = model.evaluate(input_fn=test_input_fn)
print(result)
print("Classification accuracy: {0:.2%}".format(result["accuracy"]))
### Predictions
#The trained model can also be used to make predictions on new data.
#
#Note that the TensorFlow graph is recreated and the checkpoint is reloaded every time we make predictions on new data. If the model is very large then this could add a significant overhead.
#
#It is unclear why the Estimator is designed this way, possibly because it will always use the latest checkpoint and it can also be distributed easily for use on multiple computers.
predictions = model.predict(input_fn=predict_input_fn)
cls = [p['classes'] for p in predictions]
cls_pred = np.array(cls, dtype='int').squeeze()
cls_pred
plot_images(images=some_images,
cls_true=some_images_cls,
cls_pred=cls_pred)
# ----------------------------------------------------------------------------------------------------------------------
# New Estimator
# ----------------------------------------------------------------------------------------------------------------------
#If you cannot use one of the built-in Estimators, then you can create an arbitrary TensorFlow model yourself.
# To do this, you first need to create a function which defines the following:
#
#1. The TensorFlow model, e.g. a Convolutional Neural Network.
#2. The output of the model.
#3. The loss-function used to improve the model during optimization.
#4. The optimization method.
#5. Performance metrics.
#
#The Estimator can be run in three modes: Training, Evaluation, or Prediction. The code is mostly the same,
# but in Prediction-mode we do not need to setup the loss-function and optimizer.
#
#This is another aspect of the Estimator API that is poorly designed and resembles how we did ANSI C programming
# using structs in the old days. It would probably have been more elegant to split this into several functions and
# sub-classed the Estimator-class.
def model_fn(features, labels, mode, params):
# Args:
#
# features: This is the x-arg from the input_fn.
# labels: This is the y-arg from the input_fn,
# see e.g. train_input_fn for these two.
# mode: Either TRAIN, EVAL, or PREDICT
# params: User-defined hyper-parameters, e.g. learning-rate.
# Reference to the tensor named "x" in the input-function.
x = features["x"]
# The convolutional layers expect 4-rank tensors
# but x is a 2-rank tensor, so reshape it.
net = tf.reshape(x, [-1, img_size, img_size, num_channels])
# First convolutional layer.
net = tf.layers.conv2d(inputs=net, name='layer_conv1',
filters=16, kernel_size=5,
padding='same', activation=tf.nn.relu)
net = tf.layers.max_pooling2d(inputs=net, pool_size=2, strides=2)
# Second convolutional layer.
net = tf.layers.conv2d(inputs=net, name='layer_conv2',
filters=36, kernel_size=5,
padding='same', activation=tf.nn.relu)
net = tf.layers.max_pooling2d(inputs=net, pool_size=2, strides=2)
# Flatten to a 2-rank tensor.
net = tf.contrib.layers.flatten(net)
# Eventually this should be replaced with:
# net = tf.layers.flatten(net)
# First fully-connected / dense layer.
# This uses the ReLU activation function.
net = tf.layers.dense(inputs=net, name='layer_fc1',
units=128, activation=tf.nn.relu)
# Second fully-connected / dense layer.
# This is the last layer so it does not use an activation function.
net = tf.layers.dense(inputs=net, name='layer_fc2',
units=10)
# Logits output of the neural network.
logits = net
# Softmax output of the neural network.
y_pred = tf.nn.softmax(logits=logits)
# Classification output of the neural network.
y_pred_cls = tf.argmax(y_pred, axis=1)
if mode == tf.estimator.ModeKeys.PREDICT:
# If the estimator is supposed to be in prediction-mode
# then use the predicted class-number that is output by
# the neural network. Optimization etc. is not needed.
spec = tf.estimator.EstimatorSpec(mode=mode,
predictions=y_pred_cls)
else:
# Otherwise the estimator is supposed to be in either
# training or evaluation-mode. Note that the loss-function
# is also required in Evaluation mode.
# Define the loss-function to be optimized, by first
# calculating the cross-entropy between the output of
# the neural network and the true labels for the input data.
# This gives the cross-entropy for each image in the batch.
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels,
logits=logits)
# Reduce the cross-entropy batch-tensor to a single number
# which can be used in optimization of the neural network.
loss = | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
import os
import json
import shutil
import hashlib
import io
from django.test import TestCase, RequestFactory
from django.urls import reverse
from django.template import Template, Context
from django.core.exceptions import PermissionDenied
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test.utils import override_settings
from . import forms as comment_forms
from ..core.conf import settings
from ..core.tests import utils
from .models import Comment
from .forms import (
CommentForm,
CommentMoveForm,
CommentImageForm,
CommentFileForm)
from .tags import render_comments_form
from ..core.utils import markdown
from .views import delete as comment_delete
from ..topic.models import Topic
from ..category.models import Category
from ..user.models import UserProfile
from .history.models import CommentHistory
from .utils import comment_posted, pre_comment_update, post_comment_update
from ..topic.notification.models import TopicNotification, MENTION
from ..topic.unread.models import TopicUnread
from .poll.models import CommentPoll
from . import views
User = get_user_model()
class CommentViewTest(TestCase):
def setUp(self):
utils.cache_clear()
self.user = utils.create_user()
self.category = utils.create_category()
self.topic = utils.create_topic(category=self.category, user=self.user)
def tearDown(self):
media_test = os.path.join(settings.BASE_DIR, 'media_test')
shutil.rmtree(media_test, ignore_errors=True)
@override_settings(ST_TESTS_RATELIMIT_NEVER_EXPIRE=True)
def test_comment_publish(self):
"""
create comment
"""
utils.login(self)
form_data = {'comment': 'foobar', }
response = self.client.post(reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk, }),
form_data)
comment = Comment.objects.all().order_by('-pk').last()
expected_url = reverse('spirit:comment:find', kwargs={'pk': comment.pk, })
self.assertRedirects(response, expected_url, status_code=302, target_status_code=302)
self.assertEqual(len(Comment.objects.all()), 1)
# ratelimit
self.client.post(
reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk, }), form_data)
self.assertEqual(len(Comment.objects.all()), 1)
# get
response = self.client.get(reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk, }))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['topic'], self.topic)
def test_comment_publish_comment_posted(self):
"""
Should call comment_posted
"""
res = []
def mocked_comment_posted(comment, mentions):
res.append(comment)
res.append(mentions)
org_comment_posted, views.comment_posted = views.comment_posted, mocked_comment_posted
try:
utils.login(self)
form_data = {'comment': 'foobar', }
self.client.post(reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk, }),
form_data)
self.assertEqual(len(Comment.objects.all()), 1)
self.assertEqual(res[0], Comment.objects.first())
self.assertEqual(res[1], {})
finally:
views.comment_posted = org_comment_posted
@override_settings(ST_DOUBLE_POST_THRESHOLD_MINUTES=10)
def test_comment_publish_double_post(self):
"""
Should prevent double posts
"""
utils.login(self)
comment_txt = 'foobar'
utils.create_comment(topic=self.topic)
self.assertEqual(len(Comment.objects.all()), 1)
# First post
self.client.post(
reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk}),
{'comment': comment_txt})
self.assertEqual(len(Comment.objects.all()), 2)
# Double post
utils.cache_clear() # Clear rate limit
response = self.client.post(
reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk}),
{'comment': comment_txt})
self.assertEqual(len(Comment.objects.all()), 2) # Prevented!
self.assertRedirects(
response,
expected_url=Comment.get_last_for_topic(self.topic.pk).get_absolute_url(),
status_code=302,
target_status_code=302)
# New post
utils.cache_clear() # Clear rate limit
self.client.post(
reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk}),
{'comment': 'not a foobar'})
self.assertEqual(len(Comment.objects.all()), 3)
@override_settings(ST_DOUBLE_POST_THRESHOLD_MINUTES=10)
def test_comment_publish_same_post_into_another_topic(self):
"""
Should not prevent from posting the same comment into another topic
"""
utils.login(self)
topic_another = utils.create_topic(category=self.topic.category)
comment_txt = 'foobar'
self.client.post(
reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk}),
{'comment': comment_txt})
self.assertEqual(len(Comment.objects.all()), 1)
utils.cache_clear() # Clear rate limit
self.client.post(
reverse('spirit:comment:publish', kwargs={'topic_id': topic_another.pk}),
{'comment': comment_txt})
self.assertEqual(len(Comment.objects.all()), 2)
def test_comment_publish_on_private(self):
"""
create comment on private topic
"""
private = utils.create_private_topic(user=self.user)
utils.login(self)
form_data = {'comment': 'foobar', }
response = self.client.post(reverse('spirit:comment:publish', kwargs={'topic_id': private.topic.pk, }),
form_data)
comment = Comment.objects.all().order_by('-pk').last()
expected_url = reverse('spirit:comment:find', kwargs={'pk': comment.pk, })
self.assertRedirects(response, expected_url, status_code=302, target_status_code=302)
self.assertEqual(len(Comment.objects.all()), 1)
def test_comment_publish_on_closed_topic(self):
"""
should not be able to create a comment on a closed topic
"""
Topic.objects.filter(pk=self.topic.pk).update(is_closed=True)
utils.login(self)
form_data = {'comment': 'foobar', }
response = self.client.post(reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk, }),
form_data)
self.assertEqual(response.status_code, 404)
def test_comment_publish_on_closed_category(self):
"""
should be able to create a comment on a closed category (if topic is not closed)
"""
Category.objects.filter(pk=self.category.pk).update(is_closed=True)
utils.login(self)
form_data = {'comment': 'foobar', }
response = self.client.post(reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk, }),
form_data)
self.assertEqual(response.status_code, 302)
self.assertEqual(len(Comment.objects.all()), 1)
def test_comment_publish_on_removed_topic_or_category(self):
"""
should not be able to create a comment
"""
# removed category
Category.objects.all().update(is_removed=True)
utils.login(self)
form_data = {'comment': 'foobar', }
response = self.client.post(reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk, }),
form_data)
self.assertEqual(response.status_code, 404)
# removed subcategory
Category.objects.all().update(is_removed=False)
subcategory = utils.create_category(parent=self.category, is_removed=True)
topic2 = utils.create_topic(subcategory)
utils.login(self)
form_data = {'comment': 'foobar', }
response = self.client.post(reverse('spirit:comment:publish', kwargs={'topic_id': topic2.pk, }),
form_data)
self.assertEqual(response.status_code, 404)
# removed topic
Category.objects.all().update(is_removed=False)
Topic.objects.all().update(is_removed=True)
utils.login(self)
form_data = {'comment': 'foobar', }
response = self.client.post(reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk, }),
form_data)
self.assertEqual(response.status_code, 404)
def test_comment_publish_no_access(self):
"""
should not be able to create a comment on a private topic if has no access
"""
private = utils.create_private_topic(user=self.user)
private.delete()
utils.login(self)
form_data = {'comment': 'foobar', }
response = self.client.post(reverse('spirit:comment:publish', kwargs={'topic_id': private.topic.pk, }),
form_data)
self.assertEqual(response.status_code, 404)
def test_comment_publish_quote(self):
"""
create comment quote
"""
utils.login(self)
comment = utils.create_comment(topic=self.topic)
response = self.client.get(
reverse('spirit:comment:publish', kwargs={
'topic_id': self.topic.pk,
'pk': comment.pk}))
self.assertEqual(
response.context['form'].initial['comment'],
markdown.quotify(comment.comment, comment.user.username))
def test_comment_publish_next(self):
"""
next on create comment
"""
utils.login(self)
form_data = {'comment': 'foobar', 'next': '/fakepath/'}
response = self.client.post(
reverse('spirit:comment:publish', kwargs={'topic_id': self.topic.pk, }),
form_data)
self.assertRedirects(response, '/fakepath/', status_code=302, target_status_code=404)
def test_comment_update(self):
"""
update comment
"""
comment = utils.create_comment(user=self.user, topic=self.topic)
utils.login(self)
form_data = {'comment': 'barfoo', }
response = self.client.post(reverse('spirit:comment:update', kwargs={'pk': comment.pk, }),
form_data)
expected_url = reverse('spirit:comment:find', kwargs={'pk': comment.pk, })
self.assertRedirects(response, expected_url, status_code=302, target_status_code=302)
self.assertEqual(Comment.objects.get(pk=comment.pk).comment, 'barfoo')
# next
form_data.update({'next': '/fakepath/', })
response = self.client.post(
reverse('spirit:comment:update', kwargs={'pk': comment.pk, }),
form_data)
self.assertRedirects(response, '/fakepath/', status_code=302, target_status_code=404)
def test_comment_update_not_moderator(self):
"""
non moderators can not update other people comments
"""
user = utils.create_user()
comment = utils.create_comment(user=user, topic=self.topic)
utils.login(self)
form_data = {'comment': 'barfoo', }
response = self.client.post(
reverse('spirit:comment:update', kwargs={'pk': comment.pk, }),
form_data)
self.assertEqual(response.status_code, 404)
def test_comment_update_moderator(self):
"""
moderators can update other people comments
"""
UserProfile.objects.filter(user__pk=self.user.pk).update(is_moderator=True)
user = utils.create_user()
comment = utils.create_comment(user=user, topic=self.topic)
utils.login(self)
form_data = {'comment': 'barfoo', }
response = self.client.post(
reverse('spirit:comment:update', kwargs={'pk': comment.pk, }),
form_data)
expected_url = reverse('spirit:comment:find', kwargs={'pk': comment.pk, })
self.assertRedirects(response, expected_url, status_code=302, target_status_code=302)
self.assertEqual(Comment.objects.get(pk=comment.pk).comment, 'barfoo')
def test_comment_update_moderator_private(self):
"""
moderators can not update comments in private topics they has no access
"""
UserProfile.objects.filter(user__pk=self.user.pk).update(is_moderator=True)
user = utils.create_user()
topic_private = utils.create_private_topic()
comment = utils.create_comment(user=user, topic=topic_private.topic)
utils.login(self)
form_data = {'comment': 'barfoo', }
response = self.client.post(reverse('spirit:comment:update', kwargs={'pk': comment.pk, }),
form_data)
self.assertEqual(response.status_code, 404)
def test_comment_update_increase_modified_count(self):
"""
Should increase the modified count after an update
"""
utils.login(self)
comment_posted = utils.create_comment(user=self.user, topic=self.topic)
form_data = {'comment': 'my comment, oh!', }
self.client.post(
reverse('spirit:comment:update', kwargs={'pk': comment_posted.pk, }),
form_data)
self.assertEqual(Comment.objects.get(pk=comment_posted.pk).modified_count, 1)
def test_comment_update_history(self):
"""
Should add the *first* and *modified* comments to the history
"""
utils.login(self)
comment_posted = utils.create_comment(user=self.user, topic=self.topic)
form_data = {'comment': 'my comment, oh!', }
self.client.post(reverse('spirit:comment:update', kwargs={'pk': comment_posted.pk, }),
form_data)
comments_history = CommentHistory.objects.filter(comment_fk=comment_posted).order_by('pk')
self.assertEqual(len(comments_history), 2) # first and edited
self.assertIn(comment_posted.comment_html, comments_history[0].comment_html) # first
self.assertIn('my comment, oh!', comments_history[1].comment_html) # modified
def test_comment_delete_permission_denied_to_non_moderator(self):
req = RequestFactory().get('/')
req.user = self.user
req.user.st.is_moderator = False
self.assertRaises(PermissionDenied, comment_delete, req)
def test_comment_delete(self):
"""
comment delete
"""
self.user = utils.create_user()
self.user.st.is_moderator = True
self.user.st.save()
comment = utils.create_comment(user=self.user, topic=self.topic)
utils.login(self)
form_data = {}
response = self.client.post(reverse('spirit:comment:delete', kwargs={'pk': comment.pk, }),
form_data)
expected_url = comment.get_absolute_url()
self.assertRedirects(response, expected_url, status_code=302, target_status_code=302)
response = self.client.get(reverse('spirit:comment:delete', kwargs={'pk': comment.pk, }))
self.assertEqual(response.status_code, 200)
def test_comment_undelete(self):
"""
comment undelete
"""
self.user = utils.create_user()
self.user.st.is_moderator = True
self.user.st.save()
comment = utils.create_comment(user=self.user, topic=self.topic, is_removed=True)
utils.login(self)
form_data = {}
response = self.client.post(reverse('spirit:comment:undelete', kwargs={'pk': comment.pk, }),
form_data)
expected_url = comment.get_absolute_url()
self.assertRedirects(response, expected_url, status_code=302, target_status_code=302)
response = self.client.get(reverse('spirit:comment:undelete', kwargs={'pk': comment.pk, }))
self.assertEqual(response.status_code, 200)
def test_comment_move(self):
"""
comment move to another topic
"""
utils.login(self)
self.user.st.is_moderator = True
self.user.save()
Topic.objects.filter(pk=self.topic.pk).update(comment_count=2)
comment = utils.create_comment(user=self.user, topic=self.topic)
comment2 = utils.create_comment(user=self.user, topic=self.topic)
to_topic = utils.create_topic(category=self.category)
form_data = {'topic': to_topic.pk,
'comments': [comment.pk, comment2.pk], }
response = self.client.post(reverse('spirit:comment:move', kwargs={'topic_id': self.topic.pk, }),
form_data)
expected_url = self.topic.get_absolute_url()
self.assertRedirects(response, expected_url, status_code=302)
self.assertEqual(Comment.objects.filter(topic=to_topic.pk).count(), 2)
self.assertEqual(Comment.objects.filter(topic=self.topic.pk).count(), 0)
self.assertEqual(Topic.objects.get(pk=self.topic.pk).comment_count, 0)
def test_comment_find(self):
"""
comment absolute and lazy url
"""
comment = utils.create_comment(user=self.user, topic=self.topic)
response = self.client.post(reverse('spirit:comment:find', kwargs={'pk': comment.pk, }))
expected_url = comment.topic.get_absolute_url() + "#c1"
self.assertRedirects(response, expected_url, status_code=302)
@override_settings(
MEDIA_ROOT=os.path.join(settings.BASE_DIR, 'media_test'),
ST_PREVENT_SOME_FILE_DUPLICATION=True)
def test_comment_image_upload(self):
"""
comment image upload
"""
utils.login(self)
img = io.BytesIO(
b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
b'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
files = {'image': SimpleUploadedFile(
'image.gif', img.read(), content_type='image/gif'), }
response = self.client.post(
reverse('spirit:comment:image-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data=files)
res = json.loads(response.content.decode('utf-8'))
image_url = os.path.join(
settings.MEDIA_URL, 'spirit', 'images', str(self.user.pk),
"bf21c3043d749d5598366c26e7e4ab44.gif"
).replace("\\", "/")
self.assertEqual(res['url'], image_url)
image_path = os.path.join(
settings.MEDIA_ROOT, 'spirit', 'images', str(self.user.pk),
"bf21c3043d749d5598366c26e7e4ab44.gif"
)
self.assertTrue(os.path.isfile(image_path))
shutil.rmtree(settings.MEDIA_ROOT) # cleanup
@override_settings(MEDIA_ROOT=os.path.join(settings.BASE_DIR, 'media_test'))
def test_comment_image_upload_unique(self):
user_images_parts = ('spirit', 'images', str(self.user.pk))
user_images_base = os.path.join(*user_images_parts)
user_media = os.path.join(settings.MEDIA_ROOT, user_images_base)
self.assertFalse(os.path.isdir(user_media))
utils.login(self)
img = io.BytesIO(
b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
b'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
image_name = 'foo_image.gif'
file = SimpleUploadedFile(
image_name, img.read(), content_type='image/gif')
response = self.client.post(
reverse('spirit:comment:image-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'image': file})
res = json.loads(response.content.decode('utf-8'))
self.assertTrue(os.path.isdir(user_media))
url_parts = res['url'].split('/')
self.assertEqual(
url_parts[:-2],
(settings.MEDIA_URL + '/'.join(user_images_parts)).split('/'))
self.assertEqual(len(url_parts[-2]), 32) # uuid
self.assertEqual(url_parts[-1], image_name)
self.assertEqual(len(os.listdir(user_media)), 1)
self.assertTrue(os.path.join(
user_media, os.listdir(user_media)[0], image_name))
shutil.rmtree(settings.MEDIA_ROOT) # cleanup
@override_settings(MEDIA_ROOT=os.path.join(settings.BASE_DIR, 'media_test'))
def test_comment_image_upload_unique_no_duplication(self):
utils.login(self)
img = io.BytesIO(
b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
b'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
image_name = 'foo_image.gif'
file = SimpleUploadedFile(
image_name, img.read(), content_type='image/gif')
response = self.client.post(
reverse('spirit:comment:image-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'image': file})
res = json.loads(response.content.decode('utf-8'))
first_url = res['url']
utils.cache_clear()
file.seek(0)
response = self.client.post(
reverse('spirit:comment:image-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'image': file})
res = json.loads(response.content.decode('utf-8'))
second_url = res['url']
self.assertNotEqual(first_url, second_url)
@override_settings(MEDIA_ROOT=os.path.join(settings.BASE_DIR, 'media_test'))
def test_comment_image_upload_mixed_case_ext(self):
utils.login(self)
img = io.BytesIO(
b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
b'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
image_name = 'foo_image.GiF'
file = SimpleUploadedFile(
image_name, img.read(), content_type='image/gif')
response = self.client.post(
reverse('spirit:comment:image-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'image': file})
res = json.loads(response.content.decode('utf-8'))
self.assertTrue(res['url'].endswith('/foo_image.gif'))
@override_settings(MEDIA_ROOT=os.path.join(settings.BASE_DIR, 'media_test'))
def test_comment_image_upload_unique_no_name(self):
utils.login(self)
img = io.BytesIO(
b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
b'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
image_name = '.gif'
file = SimpleUploadedFile(
image_name, img.read(), content_type='image/gif')
response = self.client.post(
reverse('spirit:comment:image-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'image': file})
res = json.loads(response.content.decode('utf-8'))
# django | |
<filename>ample/util/tm_util.py<gh_stars>1-10
#!/usr/bin/env ccp4-python
from __future__ import division
__author__ = "<NAME> & <NAME>"
__date__ = "11 Apr 2018"
__version__ = 1.1
import itertools
import logging
import operator
import os
import random
import string
import sys
import warnings
from ample.parsers import alignment_parser, tm_parser
from ample.util import ample_util, pdb_edit
from pyjob.factory import TaskFactory
from pyjob.script import ScriptCollector, Script
try:
from Bio import PDB, SeqIO
BIOPYTHON_AVAILABLE = True
except ImportError:
BIOPYTHON_AVAILABLE = False
logger = logging.getLogger(__name__)
class ModelData(object):
"""Class to store model data"""
__slots__ = (
'model_name',
'structure_name',
'model_fname',
'structure_fname',
'log_fname',
'tmscore',
'rmsd',
'nr_residues_common',
'gdtts',
'gdtha',
'maxsub',
'seq_id',
)
def __init__(
self, model_name, structure_name, model_fname, structure_fname, log_fname, tmscore, rmsd, nr_residues_common
):
self.model_name = model_name
self.structure_name = structure_name
self.model_fname = model_fname
self.structure_fname = structure_fname
self.log_fname = log_fname
self.tmscore = tmscore
self.rmsd = rmsd
self.nr_residues_common = nr_residues_common
self.gdtts = 0.0
self.gdtha = 0.0
self.maxsub = 0.0
self.seq_id = 0
def _asdict(self):
"""Convert the object to a dictionary"""
return {k: getattr(self, k) for k in self.__slots__}
class TMapps(object):
"""
Superclass of TMscore and TMalign
Attributes
----------
entries : list
List containing the TMscore entries on a per-model basis
structure : str
Path to the reference structure
method : str
One of [TMscore|TMalign]
executable : str
Path to the TMscore executable
work_dir : str
Path to the working directory
Todo
----
* Function to return the entries as numpy matrix
* Function to return the entries in a pandas dataframe
"""
def __init__(self, executable, method, wdir=".", **kwargs):
"""
Parameters
----------
executable : str
Path to the executable
method : str
One of [TMscore|TMalign]
work_dir : str
Path to the working directory
"""
self.entries = []
self.executable = executable
self.method = method.lower()
self.tmp_dir = None
if wdir:
self.work_dir = os.path.abspath(wdir)
else:
self.work_dir = os.getcwd()
self._nproc = 1
self._qtype = 'local'
self._queue = None
self._max_array_jobs = None
if 'nproc' in kwargs:
self._nproc = kwargs.pop('nproc')
# if 'submit_cluster' in kwargs:
# self._qtype = kwargs.pop('submit_cluster')
# if 'submit_queue' in kwargs:
# self._queue = kwargs.pop('submit_queue')
# if 'submit_max_array' in kwargs:
# self._max_array_jobs = kwargs.pop('submit_max_array')
if len(kwargs) > 0:
logger.debug('Ignoring keyword arguments: %s', ' '.join(kwargs.keys()))
self.tmp_dir = os.path.join(self.work_dir, "tm_util_pdbs")
if not os.path.isdir(self.tmp_dir):
os.mkdir(self.tmp_dir)
def comparison(self, models, structures):
"""
Compare a list of model structures to a second list of reference structures
Parameters
----------
models : list
List containing the paths to the model structure files
structures : list
List containing the paths to the reference structure files
Returns
-------
entries : list
List of TMscore data entries on a per-model basis
"""
if len(models) < 1 or len(structures) < 1:
msg = 'No model structures provided' if len(models) < 1 else 'No reference structures provided'
logger.critical(msg)
raise RuntimeError(msg)
elif len(structures) == 1:
logger.info('Using single structure provided for all model comparisons')
structures = [structures[0] for _ in xrange(len(models))]
elif len(models) != len(structures):
msg = "Unequal number of models and structures!"
logger.critical(msg)
raise RuntimeError(msg)
if self.method == "tmalign":
pt = tm_parser.TMalignLogParser()
elif self.method == "tmscore":
pt = tm_parser.TMscoreLogParser()
else:
msg = "Invalid method selected: %s", self.method
logger.critical(msg)
raise RuntimeError(msg)
logger.info('Using algorithm: {0}'.format(self.method))
logger.info('------- Evaluating decoys -------')
data_entries, log_files = [], []
collector = ScriptCollector(None)
for model_pdb, structure_pdb in zip(models, structures):
model_name = os.path.splitext(os.path.basename(model_pdb))[0]
structure_name = os.path.splitext(os.path.basename(structure_pdb))[0]
stem = "_".join([model_name, structure_name, self.method])
if os.path.isfile(model_pdb) and os.path.isfile(structure_pdb):
data_entries.append([model_name, structure_name, model_pdb, structure_pdb])
script = Script(directory=self.tmp_dir, prefic="tmscore_", stem=stem)
script.append(" ".join([self.executable, model_pdb, structure_pdb]))
collector.add(script)
log_files.append(os.path.splitext(script)[0] + ".log")
else:
if not os.path.isfile(model_pdb):
logger.warning("Cannot find: %s", model_pdb)
if not os.path.isfile(structure_pdb):
logger.warning("Cannot find: %s", structure_pdb)
continue
logger.info('Executing TManalysis scripts')
j = Job(self._qtype)
j.submit(job_scripts, nproc=self._nproc, max_array_jobs=self._max_array_jobs, queue=self._queue, name="tmscore")
j.wait(interval=1)
with TaskFactory(
self._qtype,
collector,
name="tmscore",
nprocesses=self._nproc,
max_array_size=self._max_array_jobs,
queue=self._queue,
shell="/bin/bash",
) as task:
task.run()
task.wait(interval=1)
self.entries = []
for entry, log, script in zip(data_entries, log_files, job_scripts):
try:
pt.reset()
pt.parse(log)
except Exception:
logger.critical("Error processing the %s log file: %s", self.method, log)
log = "None"
model_name, structure_name, model_pdb, structure_pdb = entry
_entry = self._store(model_name, structure_name, model_pdb, structure_pdb, log, pt)
self.entries.append(_entry)
os.unlink(script)
return self.entries
def _get_iterator(self, all_vs_all):
"""
Parameters
----------
all_vs_all: bool
Returns
-------
function
"""
if all_vs_all:
logger.info("All-vs-all comparison of models and structures")
return itertools.product
else:
logger.info("Direct comparison of models and structures")
return itertools.izip
def _store(self, model_name, structure_name, model_pdb, structure_pdb, logfile, pt):
model = ModelData(
model_name, structure_name, model_pdb, structure_pdb, logfile, pt.tm, pt.rmsd, pt.nr_residues_common
)
if hasattr(pt, 'gdtts'):
model.gdtts = pt.gdtts
if hasattr(pt, 'gdtha'):
model.gdtha = pt.gdtha
if hasattr(pt, 'maxsub'):
model.maxsub = pt.maxsub
if hasattr(pt, 'seq_id'):
model.seq_id = pt.seq_id
return model._asdict()
@staticmethod
def binary_avail(binary):
"""Check if TM binary is available
Paramaters
----------
binary : str
The binary name of `TMscore` or `TMalign`
Returns
-------
bool
Raises
------
ValueError
The binary is not `TMalign` or `TMscore`
"""
if binary.lower() == 'tmalign':
exe_name = "TMalign" + ample_util.EXE_EXT
elif binary.lower() == 'tmscore':
exe_name = "TMscore" + ample_util.EXE_EXT
else:
raise ValueError('Provide one of TMalign or TMscore')
try:
ample_util.find_exe(exe_name)
except:
return False
return True
class TMalign(TMapps):
"""
Wrapper to handle TMalign scoring for one or more structures
Examples
--------
>>> models = ["<MODEL_1>", "<MODEL_2>", "<MODEL_3>"]
>>> references = ["<REFERENCE_1>", "<REFERENCE>", "<REFERENCE>"]
>>> tm = TMalign("<PATH_TO_EXE>")
>>> entries = tm.compare_structures(models, references)
"""
def __init__(self, executable, wdir=None, **kwargs):
super(TMalign, self).__init__(executable, "TMalign", wdir=wdir, **kwargs)
def compare_structures(self, models, structures, all_vs_all=False):
"""
Compare a list of model structures to a second list of reference structures
Parameters
----------
models : list
List containing the paths to the model structure files
structures : list
List containing the paths to the reference structure files
all_vs_all : bool
Flag to compare all models against all structures
Returns
-------
entries : list
"""
if len(structures) == 1:
logger.info('Using single structure provided for all model comparisons')
structures = [structures[0] for _ in xrange(len(models))]
models_to_compare, structures_to_compare = [], []
combination_iterator = self._get_iterator(all_vs_all)
for (model, structure) in combination_iterator(models, structures):
models_to_compare.append(model)
structures_to_compare.append(structure)
return self.comparison(models_to_compare, structures_to_compare)
class TMscore(TMapps):
"""
Wrapper to handle TMscoring for one or more structures
Examples
--------
>>> models = ["<MODEL_1>", "<MODEL_2>", "<MODEL_3>"]
>>> references = ["<REFERENCE_1>", "<REFERENCE>", "<REFERENCE>"]
>>> tm = TMscore("<PATH_TO_EXE>")
>>> entries = tm.compare_structures(models, references)
"""
def __init__(self, executable, wdir=None, **kwargs):
super(TMscore, self).__init__(executable, "TMscore", wdir=wdir, **kwargs)
def compare_structures(self, models, structures, fastas=None, all_vs_all=False):
"""
Compare a list of model structures to a second list of reference structures
Parameters
----------
models : list
List containing the paths to the model structure files
structures : list
List containing the paths to the reference structure files
fastas : list
List containing the paths to the FASTA files
all_vs_all : bool
Flag to compare all models against all structures
Returns
-------
entries : list
List of TMscore data entries on a per-model basis
Notes
-----
If a FASTA sequence is provided, a much more accurate comparison can be carried out. However, to by-pass this
there is also an option to run the comparison without it. This might work just fine for larger models.
"""
if not BIOPYTHON_AVAILABLE:
raise RuntimeError("Biopython is not available")
if structures and len(structures) == 1:
logger.info('Using single structure provided for all model comparisons')
structures = [structures[0] for _ in xrange(len(models))]
if fastas and len(fastas) == 1:
logger.info('Using single FASTA provided for all model comparisons')
fastas = [fastas[0] for _ in xrange(len(models))]
models_to_compare, structures_to_compare = [], []
combination_iterator = self._get_iterator(all_vs_all)
if fastas:
for (model, structure, fasta) in combination_iterator(models, structures, fastas):
fasta_record = list(SeqIO.parse(open(fasta, 'r'), 'fasta'))[0]
fasta_data = [(i + 1, j) for i, j in enumerate(str(fasta_record.seq))]
model_data = list(self._pdb_info(model))
structure_data = list(self._pdb_info(structure))
for fasta_pos in fasta_data:
if fasta_pos not in model_data:
model_data.append((fasta_pos[0], "-"))
model_data.sort(key=operator.itemgetter(0))
aln_parser = alignment_parser.AlignmentParser()
fasta_structure_aln = aln_parser.align_sequences(
"".join(zip(*model_data)[1]), "".join(zip(*structure_data)[1])
)
to_remove = []
_alignment = zip(fasta_structure_aln[0], fasta_structure_aln[1])
for i, (model_res, structure_res) in enumerate(_alignment):
if model_res == "-" and structure_res == "-":
to_remove.append(i)
for i in reversed(to_remove):
_alignment.pop(i)
model_aln = "".join(zip(*_alignment)[0])
structure_aln = "".join(zip(*_alignment)[1])
if len(model_aln) != len(structure_aln):
msg = "Unequal lengths of your model and structure sequences"
logger.critical(msg)
raise RuntimeError(msg)
pdb_combo = self._mod_structures(model_aln, structure_aln, model, structure)
models_to_compare.append(pdb_combo[0])
structures_to_compare.append(pdb_combo[1])
else:
for (model, structure) in combination_iterator(models, structures):
model_data = list(self._pdb_info(model))
structure_data = list(self._pdb_info(structure))
alignment = alignment_parser.AlignmentParser().align_sequences(
"".join(zip(*model_data)[1]), "".join(zip(*structure_data)[1])
)
alignment = zip(alignment[0], alignment[1])
model_aln = "".join(zip(*alignment)[0])
structure_aln = "".join(zip(*alignment)[1])
if len(model_aln) != len(structure_aln):
msg = "Unequal lengths of your | |
#!/usr/bin/python
"""
Description: Tool for transforming JSON dumps from Sparrow Compiler into Graphviz dot diagrams
Copyright (c) 2016, <NAME>
"""
import os, subprocess, sys, json, argparse, cgi
def parseArgs():
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
parser = argparse.ArgumentParser(description='Generates dot trees from Sparrow json dumps')
parser.register('type','bool',str2bool)
parser.add_argument('jsonFile', metavar='jsonFile', type=str,
help='the .json file to process')
parser.add_argument('--open', action='store_true',
help='translate the dot file to pdf and open it')
parser.add_argument('--showNodeIds', action='store_true',
help='shows the Ids of the nodes')
parser.add_argument('--startNode', metavar='ID', type=int,
help='the node we should start expanding from')
parser.add_argument('--maxNodes', metavar='N', type=int, default=10000,
help='max number of nodes to process (default: 10000)')
parser.add_argument('--maxLevels', metavar='N', type=int, default=30,
help='max levels to expand (default: 30)')
parser.add_argument('--showReferredNodes', metavar='B', type='bool', default=False,
help='whether should show referred nodes (default: False)')
parser.add_argument('--showPropNodes', metavar='B', type='bool', default=False,
help='whether should show properties node links (default: False)')
parser.add_argument('--showExplanation', metavar='B', type='bool', default=True,
help='whether should show explanation node links (default: True)')
parser.add_argument('--expandClassAndFun', metavar='B', type='bool', default=True,
help='whether to expand class and function nodes (default: True)')
return parser.parse_args()
class AstData:
""" Class that represents the data read from the .json file; holds all the nodes and all the types """
def __init__(self):
self.nodes = {}
self.types = {}
def readNodePtr(astData, jsonNodePtr):
"""Reads a node pointer json node"""
ref = jsonNodePtr['ref'] if jsonNodePtr.get('ref') else None
obj = jsonNodePtr['obj'] if jsonNodePtr.get('obj') else None
if not ref:
return None
# If we already have the node object for this, return it
if ref in astData.nodes.keys():
return astData.nodes[ref]
if not obj:
return None
# Read the node
node = Node(ref, obj, astData)
astData.nodes[ref] = node
return node
class Type:
"""Class that holds the type information"""
def __init__(self, astData, jsonType):
self.ref = jsonType['ref'] if jsonType.get('ref') else None
self.desc = jsonType['desc'] if jsonType.get('desc') else None
astData.types[self.ref] = self
class Node:
"""Class that holds the info corresponding to a node"""
def __init__(self, ref, jsonNode, astData):
self.ref = ref
self.kind = ''
self.name = ''
self.isDefinition = False
self.children = []
self.referredNodes = []
self.explanation = []
self.properties = {}
self._parseJsonNode(jsonNode, astData)
def _parseJsonNode(self, jsonNode, astData):
if jsonNode.get('children'):
for child in jsonNode['children']:
n = readNodePtr(astData, child)
if n:
self.children.append(n)
if jsonNode.get('referredNodes'):
for child in jsonNode['referredNodes']:
n = readNodePtr(astData, child)
if n:
self.referredNodes.append(n)
if jsonNode.get('type'):
self.type = Type(astData, jsonNode['type'])
if jsonNode.get('explanation'):
self.explanation = readNodePtr(astData, jsonNode['explanation'])
# Also walk the properties; look for nodes
if jsonNode.get('properties'):
for prop in jsonNode['properties']:
val = prop['val']
kind = prop['kind']
if kind == 2:
val = readNodePtr(astData, val)
if kind == 3:
val = Type(astData, val)
if val:
self.properties[prop['name']] = val
self.kind = jsonNode['kind']
self.name = self._getName()
self.isDefinition = self._isDefinition()
def _getName(self):
idx = self.kind.rfind('.')
res = self.kind[idx+1:]
name = self._getPropertyString('name')
if name == '':
name = self._getPropertyString('spr.operation')
if name == '' and self.kind == 'typeNode':
name = self.type.desc if self.type else ''
return res if name == '' else res + ': ' + name
def _getPropertyString(self, name):
if name in self.properties.keys():
return self.properties[name]
return ''
def _isDefinition(self):
return self.kind == 'spr.sprCompilationUnit' \
or self.kind == 'spr.package' \
or self.kind == 'spr.using' \
or self.kind == 'spr.sprClass' \
or self.kind == 'spr.sprFunction' \
or self.kind == 'spr.sprParameter' \
or self.kind == 'fun' \
or self.kind == 'var'
class LinkType:
""" The type of a link """
children = 1
referred = 2
prop = 3
explanation = 4
class Filter:
""" Class that helps us filter what nodes we want to process during an AST traversal """
def __init__(self, args = None, showReferredNodes = True, showPropNodes = True, showExplanation = True, expandClassAndFun = True):
if args:
self.maxNodes = args.maxNodes
self.maxLevels = args.maxLevels
self.showReferredNodes = args.showReferredNodes and showReferredNodes
self.showPropNodes = args.showPropNodes and showPropNodes
self.showExplanation = args.showExplanation and showExplanation
self.expandClassAndFun = args.expandClassAndFun and expandClassAndFun
else:
self.maxNodes = 999999
self.maxLevels = 999999
self.showReferredNodes = showReferredNodes
self.showPropNodes = showPropNodes
self.showExplanation = showExplanation
self.expandClassAndFun = expandClassAndFun
self.numNodes = 0
def onTraversalStart(self):
""" Called when the traversal starts """
self.numNodes = 0
def onNodeAdded(self):
""" Called when a node is actually traversed """
self.numNodes += 1
def canAddNewNode(self):
""" Called to check if we can add a new node """
return self.numNodes < self.maxNodes
def canAddNode(self, level, linkType):
""" Called to check if we can add a node of the given level and link type """
return self.numNodes < self.maxNodes \
and level < self.maxLevels \
and ((linkType == LinkType.children) \
or (linkType == LinkType.referred and self.showReferredNodes) \
or (linkType == LinkType.prop and self.showPropNodes) \
or (linkType == LinkType.explanation and self.showExplanation))
def canExpandNode(self, node):
classAndFun = ['spr.sprClass', 'spr.sprFunction', 'sprClass', 'sprFunction', 'Class', 'Function' ]
return self.expandClassAndFun or (not node.kind in classAndFun)
class AstTraversal:
""" Class that defines a traversal over the AST """
def __init__(self, filter):
self.filter = filter
self._traversed = {}
self._toTraverse = {}
def traverse(self, node, fun):
self._traversed = {}
self._toTraverse = [ (node, 0) ]
self.filter.onTraversalStart()
while len(self._toTraverse) > 0 and self.filter.canAddNewNode():
nodeLevel = self._toTraverse.pop()
self._visitNode(nodeLevel[0], nodeLevel[1], fun)
def _visitNode(self, node, level, fun):
if node in self._traversed.keys():
return
# Apply the traverse function
fun(node)
self._traversed[node] = True
self.filter.onNodeAdded()
if not self.filter.canExpandNode(node):
return
for n in node.children:
self._addNewNodeToTraverse(n, level+1, LinkType.children)
for n in node.referredNodes:
self._addNewNodeToTraverse(n, 0, LinkType.referred)
for kv in node.properties.items():
k = kv[0]
v = kv[1]
if isinstance(v, Node):
self._addNewNodeToTraverse(v, 0, LinkType.prop)
self._addNewNodeToTraverse(node.explanation, level+1, LinkType.explanation)
def _addNewNodeToTraverse(self, node, level, linkType):
if node and node not in self._traversed.keys() and self.filter.canAddNode(level, linkType):
self._toTraverse.append((node, level))
class DotGeneration:
""" Class that generates the dot file corresponding to the given AST """
def __init__(self, out, args):
self.out = out
self.args = args
self.backboneNodes = {} # Children nodes + explanations
self.visibleNodes = {} # directly reachable + 1 level of other visible nodes
def generateDot(self, rootNode):
print >>self.out, """digraph tree
{
nodesep=0.5;
charset="latin1";
rankdir=LR;
fixedsize=true;
node [style="rounded,filled", width=0, height=0, shape=box, fillcolor="#E5E5E5", concentrate=true]
"""
def _addToDict(dict, n):
dict[n] = True
# Gather the nodes that are directly reachable by a children/expl traversal
self.backboneNodes = {}
trav = AstTraversal(Filter(self.args, False, False))
trav.traverse(rootNode, (lambda n: _addToDict(self.backboneNodes, n)))
# Gather the nodes that should be visible
# Expand max one level out of the directly reachable nodes
self.visible = {}
f = Filter(self.args)
f.maxLevels = 1
trav = AstTraversal(f)
for n in self.backboneNodes:
trav.traverse(n, (lambda n: _addToDict(self.visible, n)))
# Check if we have directly reachable nodes that are not visible
for n in self.backboneNodes.keys():
if n not in self.visible:
print 'Node %s (%s) is reachable, but not visible!' % (n.name, n.ref)
# Print all the visible nodes
for n in self.visible.keys():
self._printNode(n)
print >>self.out, '}'
def _printNode(self, node):
# Print the node
ref = node.ref
name = node.name
style = ''
if self.args.showNodeIds:
style = 'label=<<FONT POINT-SIZE="10">%s</FONT><BR/>%s >' % (ref, self._escape(name))
else:
style = 'label="%s"' % self._escape(name)
if node.isDefinition:
style += ' fillcolor=lemonchiffon'
print >>self.out, 'n_%s [%s]' % (ref, style)
styleChild = ''
styleRefMain = '[style=dashed, constraint=false, minlen=1]' # Back/forth references
styleRefAux = '[style=dashed]' # Aux nodes are drawn based on constraints
stylePropMain = '[style=dotted]'
stylePropAux = '[style=dotted, constraint=false, minlen=1]'
styleExpl = '[style=bold, arrowhead=vee, arrowtail=inv, dir=both]'
# Print links to the children nodes
dest = [n for n in node.children if n in self.visible]
self._printLinks(ref, dest, styleChild)
# Print links to the referred nodes
if self.args.showReferredNodes:
dest = [n for n in node.referredNodes if n in self.visible]
mainRefs = [n for n in dest if n in self.backboneNodes]
auxRefs = [n for n in dest if n not in self.backboneNodes]
self._printLinks(ref, mainRefs, styleRefMain)
self._printLinks(ref, auxRefs, styleRefAux)
# Print links to the nodes in the properties
if self.args.showPropNodes:
for kv in node.properties.items():
k = kv[0]
v = kv[1]
if isinstance(v, Node) and v in self.visible:
style = stylePropAux if v in self.backboneNodes else stylePropMain
self._printLink(ref, v.ref, k, style)
# Print connections with the explanation
if self.args.showExplanation:
if node.explanation:
self._printLink(ref, node.explanation.ref, '', styleExpl)
def _escape(self, name):
res = cgi.escape(name).encode('ascii', 'xmlcharrefreplace')
res = res.replace('\\', '\\\\')
return res
def _printLink(self, srcRef, destRef, name, style):
if name != '':
print >>self.out, 'n_%s -> n_%s [label="%s"] %s' % (srcRef, destRef, self._escape(name), style)
else:
print >>self.out, 'n_%s -> | |
<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# flake8: noqa
import argparse
import dask
import dask.array as da
import numpy as np
from astropy.io import fits
import warnings
from africanus.model.spi.dask import fit_spi_components
iFs = np.fft.ifftshift
Fs = np.fft.fftshift
# we want to fall back to numpy if pypocketfft is not installed
# so set up functions to have the same call signatures
try:
from pypocketfft import r2c, c2r
def fft(x, ax, ncpu):
return r2c(x, axes=ax, forward=True,
nthreads=ncpu, inorm=0)
def ifft(y, ax, ncpu, lastsize):
return c2r(y, axes=ax, forward=False, lastsize=lastsize,
nthreads=args.ncpu, inorm=2)
except BaseException:
warnings.warn("No pypocketfft installation found. "
"FFT's will be performed in serial. "
"Install pypocketfft from "
"https://gitlab.mpcdf.mpg.de/mtr/pypocketfft "
"for optimal performance.",
ImportWarning)
from numpy.fft import rfftn, irfftn
# additional arguments will have no effect
def fft(x, ax, ncpu):
return rfftn(x, axes=ax)
def ifft(y, ax, ncpu, lastsize):
return irfftn(y, axes=ax)
def Gaussian2D(xin, yin, GaussPar=(1., 1., 0.)):
S0, S1, PA = GaussPar
PA = 90 + PA
SMaj = np.max([S0, S1])
SMin = np.min([S0, S1])
A = np.array([[1. / SMaj ** 2, 0],
[0, 1. / SMin ** 2]])
c, s, t = np.cos, np.sin, PA
R = np.array([[c(t), -s(t)],
[s(t), c(t)]])
A = np.dot(np.dot(R.T, A), R)
sOut = xin.shape
# only compute the result where necessary
extent = (5 * SMaj)**2
xflat = xin.squeeze()
yflat = yin.squeeze()
ind = np.argwhere(xflat**2 + yflat**2 <= extent).squeeze()
idx = ind[:, 0]
idy = ind[:, 1]
x = np.array([xflat[idx, idy].ravel(), yflat[idx, idy].ravel()])
R = np.einsum('nb,bc,cn->n', x.T, A, x)
# need to adjust for the fact that GaussPar corresponds to FWHM
fwhm_conv = 2*np.sqrt(2*np.log(2))
tmp = np.exp(-fwhm_conv*R)
gausskern = np.zeros_like(xflat, dtype=np.float64)
gausskern[idx, idy] = tmp
return np.ascontiguousarray(gausskern.reshape(sOut),
dtype=np.float64)
def convolve_model(model, gausskern, args):
print("Doing FFT's")
# get padding
_, npix_l, npix_m = model.shape
pfrac = args.padding_frac/2.0
npad_l = int(pfrac*npix_l)
npad_m = int(pfrac*npix_m)
# get fast FFT sizes
try:
from scipy.fftpack import next_fast_len
nfft = next_fast_len(npix_l + 2*npad_l)
npad_ll = (nfft - npix_l)//2
npad_lr = nfft - npix_l - npad_ll
nfft = next_fast_len(npix_m + 2*npad_m)
npad_ml = (nfft - npix_m)//2
npad_mr = nfft - npix_m - npad_ml
padding = ((0, 0), (npad_ll, npad_lr), (npad_ml, npad_mr))
unpad_l = slice(npad_ll, -npad_lr)
unpad_m = slice(npad_ml, -npad_mr)
except BaseException:
warnings.warn("Could not determine fast fft size. "
"Install scipy for optimal performance.",
ImportWarning)
padding = ((0, 0), (npad_l, npad_l), (npad_m, npad_m))
unpad_l = slice(npad_l, -npad_l)
unpad_m = slice(npad_m, -npad_m)
ax = (1, 2) # axes over which to perform fft
lastsize = npix_m + np.sum(padding[-1])
# get FT of convolution kernel
gausskernhat = fft(iFs(np.pad(gausskern[None], padding, mode='constant'),
axes=ax), ax, args.ncpu)
# Convolve model with Gaussian kernel
convmodel = fft(iFs(np.pad(model, padding, mode='constant'), axes=ax),
ax, args.ncpu)
convmodel *= gausskernhat
return Fs(ifft(convmodel, ax, args.ncpu, lastsize),
axes=ax)[:, unpad_l, unpad_m]
def interpolate_beam(xx, yy, maskindices, freqs, args):
print("Interpolating beam")
l_source = xx[maskindices[:, 0], maskindices[:, 1]]
m_source = yy[maskindices[:, 0], maskindices[:, 1]]
lm_source = np.vstack((l_source.ravel(), m_source.ravel())).T
ntime = 1
nant = 1
nband = freqs.size
parangles = np.zeros((ntime, nant,), dtype=np.float64)
ant_scale = np.ones((nant, nband, 2), dtype=np.float64)
point_errs = np.zeros((ntime, nant, nband, 2), dtype=np.float64)
if args.beammodel == "eidos":
raise NotImplementedError("eidos is coming!!!")
else:
print("Loading fits beam patterns from %s" % args.beammodel)
from glob import glob
paths = glob(args.beammodel + '_**_**.fits')
beam_hdr = None
for path in paths:
if 'xx' in path or 'XX' in path or 'rr' in path or 'RR' in path:
if 're' in path:
corr1_re = fits.getdata(path)
if beam_hdr is None:
beam_hdr = fits.getheader(path)
elif 'im' in path:
corr1_im = fits.getdata(path)
else:
raise NotImplementedError("Only re/im patterns supported")
elif 'yy' in path or 'YY' in path or 'll' in path or 'LL' in path:
if 're' in path:
corr2_re = fits.getdata(path)
elif 'im' in path:
corr2_im = fits.getdata(path)
else:
raise NotImplementedError("Only re/im patterns supported")
# get Stokes I amplitude
beam_amp = (corr1_re**2 + corr1_im**2 + corr2_re**2 + corr2_im**2)/2.0
# get cube in correct shape for interpolation code
beam_amp = np.ascontiguousarray(np.transpose(beam_amp, (1, 2, 0))
[:, :, :, None, None])
# get cube info
if beam_hdr['CUNIT1'] != "DEG" and beam_hdr['CUNIT1'] != "deg":
raise ValueError("Beam image units must be in degrees")
npix_l = beam_hdr['NAXIS1']
refpix_l = beam_hdr['CRPIX1']
delta_l = beam_hdr['CDELT1']
l_min = (1 - refpix_l)*delta_l
l_max = (1 + npix_l - refpix_l)*delta_l
if beam_hdr['CUNIT2'] != "DEG" and beam_hdr['CUNIT2'] != "deg":
raise ValueError("Beam image units must be in degrees")
npix_m = beam_hdr['NAXIS2']
refpix_m = beam_hdr['CRPIX2']
delta_m = beam_hdr['CDELT2']
m_min = (1 - refpix_m)*delta_m
m_max = (1 + npix_m - refpix_m)*delta_m
if (l_min > l_source.min() or m_min > m_source.min() or
l_max < l_source.max() or m_max < m_source.max()):
raise ValueError("The supplied beam is not large enough")
beam_extents = np.array([[l_min, l_max], [m_min, m_max]])
# get frequencies
if beam_hdr["CTYPE3"] != 'FREQ':
raise ValueError(
"Cubes are assumed to be in format [nchan, nx, ny]")
nchan = beam_hdr['NAXIS3']
refpix = beam_hdr['CRPIX3']
delta = beam_hdr['CDELT3'] # assumes units are Hz
freq0 = beam_hdr['CRVAL3']
bfreqs = freq0 + np.arange(1 - refpix, 1 + nchan - refpix) * delta
if bfreqs[0] > freqs[0] or bfreqs[-1] < freqs[-1]:
warnings.warn("The supplied beam does not have sufficient "
"bandwidth. Beam frequencies:")
with np.printoptions(precision=2):
print(bfreqs)
# LB - dask probably not necessary for small problem
from africanus.rime.fast_beam_cubes import beam_cube_dde
beam_source = beam_cube_dde(beam_amp, beam_extents, bfreqs,
lm_source, parangles, point_errs,
ant_scale, freqs).squeeze()
return beam_source
def create_parser():
p = argparse.ArgumentParser(description='Simple spectral index fitting'
'tool.',
formatter_class=argparse.RawTextHelpFormatter)
p.add_argument("--fitsmodel", type=str, required=True)
p.add_argument("--fitsresidual", type=str)
p.add_argument('--outfile', type=str,
help="Path to output directory. \n"
"Placed next to input model if outfile not provided.")
p.add_argument('--beampars', default=None, nargs='+', type=float,
help="Beam parameters matching FWHM of restoring beam "
"specified as emaj emin pa. \n"
"By default these are taken from the fits header "
"of the residual image.")
p.add_argument('--threshold', default=5, type=float,
help="Multiple of the rms in the residual to threshold "
"on. \n"
"Only components above threshold*rms will be fit.")
p.add_argument('--maxDR', default=100, type=float,
help="Maximum dynamic range used to determine the "
"threshold above which components need to be fit. \n"
"Only used if residual is not passed in.")
p.add_argument('--ncpu', default=0, type=int,
help="Number of threads to use. \n"
"Default of zero means use all threads")
p.add_argument('--beammodel', default=None, type=str,
help="Fits beam model to use. \n"
"It is assumed that the pattern is path_to_beam/"
"name_corr_re/im.fits. \n"
"Provide only the path up to name "
"e.g. /home/user/beams/meerkat_lband. \n"
"Patterns mathing corr are determined "
"automatically. \n"
"Only real and imaginary beam models currently "
"supported.")
p.add_argument('--output', default='aiIbc', type=str,
help="Outputs to write. Letter correspond to: \n"
"a - alpha map \n"
"i - I0 map \n"
"I - reconstructed cube form alpha and I0 \n"
"b - interpolated beam \n"
"c - restoring beam used for convolution \n"
"Default is to write all of them")
p.add_argument("--padding_frac", default=0.2, type=float,
help="Padding factor for FFT's.")
return p
def main(args):
ref_hdr = fits.getheader(args.fitsresidual)
if args.beampars is None:
print("Attempting to take beampars from residual fits header")
emaj = ref_hdr['BMAJ1']
emin = ref_hdr['BMIN1']
pa = ref_hdr['BPA1']
beampars = (emaj, emin, pa)
else:
beampars = tuple(args.beampars)
# emaj, emin, pa = args.beampars
print("Using emaj = %3.2e, emin = %3.2e, PA = %3.2e" % beampars)
# load images
model = np.ascontiguousarray(fits.getdata(args.fitsmodel).squeeze(),
dtype=np.float64)
mhdr = fits.getheader(args.fitsmodel)
if mhdr['CUNIT1'] != "DEG" and mhdr['CUNIT1'] != "deg":
raise ValueError("Image units must be in degrees")
npix_l = mhdr['NAXIS1']
refpix_l = mhdr['CRPIX1']
delta_l = mhdr['CDELT1']
l_coord = np.arange(1 - refpix_l, 1 + npix_l - refpix_l)*delta_l
if mhdr['CUNIT2'] != "DEG" and mhdr['CUNIT2'] != "deg":
raise ValueError("Image units must be in degrees")
npix_m = mhdr['NAXIS2']
refpix_m = mhdr['CRPIX2']
delta_m = mhdr['CDELT2']
m_coord = np.arange(1 - refpix_m, 1 + npix_m - refpix_m)*delta_m
print("Image shape = ", (npix_l, npix_m))
# get frequencies
if mhdr["CTYPE4"] == 'FREQ':
freq_axis = 4
nband = mhdr['NAXIS4']
refpix_nu = mhdr['CRPIX4']
delta_nu = mhdr['CDELT4'] # assumes units are Hz
ref_freq = mhdr['CRVAL4']
ncorr = mhdr['NAXIS3']
elif mhdr["CTYPE3"] == 'FREQ':
freq_axis = 3
nband = mhdr['NAXIS3']
refpix_nu = mhdr['CRPIX3']
delta_nu = mhdr['CDELT3'] # assumes units are Hz
ref_freq = mhdr['CRVAL3']
ncorr = mhdr['NAXIS4']
else:
raise ValueError("Freq axis must be 3rd or 4th")
if ncorr > 1:
raise ValueError("Only Stokes I cubes supported")
freqs = ref_freq + np.arange(1 - refpix_nu,
| |
<gh_stars>0
"""Overlapping (non-nested) tandem network."""
from math import inf
from typing import List
from nc_arrivals.arrival_distribution import ArrivalDistribution
from nc_arrivals.regulated_arrivals import DetermTokenBucket
from nc_operations.aggregate import AggregateTwo
from nc_operations.arb_scheduling import LeftoverARB
from nc_operations.convolve import Convolve
from nc_operations.deconvolve import Deconvolve
from nc_operations.e2e_enum import E2EEnum
from nc_operations.gps_scheduling import LeftoverGPSPG
from nc_operations.sfa_tandem_bound import sfa_tandem_bound
from nc_operations.single_hop_bound import single_hop_bound
from nc_server.constant_rate_server import ConstantRateServer
from utils.exceptions import IllegalArgumentError
from utils.perform_parameter import PerformParameter
from utils.setting_sfa import SettingSFA
from msob_and_fp.setting_msob_fp import SettingMSOBFP
class OverlappingTandem(SettingMSOBFP):
"""Tandem with priorities f_1 <= f_2 <= f_3"""
def __init__(self, arr_list: List[ArrivalDistribution],
ser_list: List[ConstantRateServer],
perform_param: PerformParameter) -> None:
self.arr_list = arr_list
self.ser_list = ser_list
self.perform_param = perform_param
def standard_bound(self, param_list: List[float]) -> float:
"""conducts a PMOO analysis -> case distinction necessary"""
theta = param_list[0]
p = param_list[1]
foi = self.arr_list[0]
a_2 = self.arr_list[1]
a_3 = self.arr_list[2]
s_1 = self.ser_list[0]
s_2 = self.ser_list[1]
s_3 = self.ser_list[2]
conv_s1_s2_lo = LeftoverARB(ser=Convolve(ser1=s_1,
ser2=LeftoverARB(
ser=s_2, cross_arr=a_3)),
cross_arr=a_2)
d_3_2 = Deconvolve(arr=a_3, ser=s_2)
s3_lo = LeftoverARB(ser=s_3, cross_arr=d_3_2)
s_e2e_1 = Convolve(ser1=conv_s1_s2_lo, ser2=s3_lo, indep=False, p=p)
res_1 = single_hop_bound(foi=foi,
s_e2e=s_e2e_1,
theta=theta,
perform_param=self.perform_param,
indep=True)
d_2_1 = Deconvolve(arr=a_2, ser=s_1)
conv_s2_s3_lo = LeftoverARB(ser=Convolve(ser1=LeftoverARB(
ser=s_2, cross_arr=d_2_1),
ser2=s_3),
cross_arr=a_3)
s1_lo = LeftoverARB(ser=s_1, cross_arr=a_2)
s_e2e_2 = Convolve(ser1=s1_lo, ser2=conv_s2_s3_lo, indep=False, p=p)
res_2 = single_hop_bound(foi=foi,
s_e2e=s_e2e_2,
theta=theta,
perform_param=self.perform_param,
indep=True)
return min(res_1, res_2)
def server_bound(self, param_list: List[float]) -> float:
theta = param_list[0]
foi = self.arr_list[0]
a_2 = self.arr_list[1]
a_3 = self.arr_list[2]
s_1 = self.ser_list[0]
s_2 = self.ser_list[1]
s_3 = self.ser_list[2]
conv_s1_s2_lo = LeftoverARB(ser=Convolve(ser1=s_1,
ser2=LeftoverARB(
ser=s_2, cross_arr=a_3)),
cross_arr=a_2)
d_3_2 = DetermTokenBucket(sigma_single=0.0, rho_single=s_2.rate, m=1)
s3_lo = LeftoverARB(ser=s_3, cross_arr=d_3_2)
s_e2e_1 = Convolve(ser1=conv_s1_s2_lo, ser2=s3_lo)
res_1 = single_hop_bound(foi=foi,
s_e2e=s_e2e_1,
theta=theta,
perform_param=self.perform_param,
indep=True)
d_2_1 = DetermTokenBucket(sigma_single=0.0, rho_single=s_1.rate, m=1)
conv_s2_s3_lo = LeftoverARB(ser=Convolve(ser1=LeftoverARB(
ser=s_2, cross_arr=d_2_1),
ser2=s_3),
cross_arr=a_3)
s1_lo = LeftoverARB(ser=s_1, cross_arr=a_2)
s_e2e_2 = Convolve(ser1=s1_lo, ser2=conv_s2_s3_lo)
res_2 = single_hop_bound(foi=self.arr_list[0],
s_e2e=s_e2e_2,
theta=theta,
perform_param=self.perform_param,
indep=True)
return min(res_1, res_2)
def fp_bound(self, param_list: List[float]) -> float:
theta = param_list[0]
foi = self.arr_list[0]
a_2 = self.arr_list[1]
a_3 = self.arr_list[2]
s_1 = self.ser_list[0]
s_2 = self.ser_list[1]
s_3 = self.ser_list[2]
s_23_conv = Convolve(ser1=s_2, ser2=s_3)
s_23_lo = LeftoverARB(ser=s_23_conv, cross_arr=a_3)
s_123_conv = Convolve(ser1=s_1, ser2=s_23_lo)
s_e2e = LeftoverARB(ser=s_123_conv, cross_arr=a_2)
return single_hop_bound(foi=foi,
s_e2e=s_e2e,
theta=theta,
perform_param=self.perform_param,
indep=True)
def approximate_utilization(self) -> float:
foi_rate = self.arr_list[0].average_rate()
a_2_rate = self.arr_list[1].average_rate()
a_3_rate = self.arr_list[2].average_rate()
c_1 = self.ser_list[0].rate
c_2 = self.ser_list[1].rate
c_3 = self.ser_list[2].rate
util_s_1 = (foi_rate + a_2_rate) / c_1
util_s_2 = (foi_rate + a_2_rate + a_3_rate) / c_2
util_s_3 = (foi_rate + a_3_rate) / c_3
return max(util_s_1, util_s_2, util_s_3)
def server_util(self, server_index: int) -> float:
a_foi_rate = self.arr_list[0].average_rate()
a_2_rate = self.arr_list[1].average_rate()
a_3_rate = self.arr_list[2].average_rate()
c_1 = self.ser_list[0].rate
c_2 = self.ser_list[1].rate
c_3 = self.ser_list[2].rate
if server_index == 0:
return (a_foi_rate + a_2_rate) / c_1
elif server_index == 1:
return (a_foi_rate + a_2_rate + a_3_rate) / c_2
elif server_index == 2:
return (a_foi_rate + a_3_rate) / c_3
else:
raise IllegalArgumentError("Wrong server index")
def to_string(self) -> str:
for arr in self.arr_list:
print(arr.to_value())
for ser in self.ser_list:
print(ser.to_value())
return self.to_name() + "_" + self.perform_param.__str__()
class OverlappingTandemSFAPerform(SettingSFA):
def __init__(self, arr_list: List[ArrivalDistribution],
ser_list: List[ConstantRateServer],
perform_param: PerformParameter) -> None:
self.arr_list = arr_list
self.ser_list = ser_list
self.perform_param = perform_param
def standard_bound(self, param_list: List[float]) -> float:
"""conducts an SFA analysis"""
theta = param_list[0]
foi = self.arr_list[0]
a_2 = self.arr_list[1]
a_3 = self.arr_list[2]
s_1 = self.ser_list[0]
s_2 = self.ser_list[1]
s_3 = self.ser_list[2]
s1_lo = LeftoverARB(ser=s_1, cross_arr=a_2)
d_2_1 = Deconvolve(arr=a_2, ser=s_1)
s2_lo = LeftoverARB(ser=s_2,
cross_arr=AggregateTwo(arr1=d_2_1, arr2=a_3))
d_3_2 = Deconvolve(arr=a_3, ser=s_2)
# d_3_2 = Deconvolve(arr=a_3, ser=Leftover(ser=s_2, arr=a_2))
s3_lo = LeftoverARB(ser=s_3, cross_arr=d_3_2)
s_23_lo = Convolve(ser1=s2_lo,
ser2=s3_lo,
indep=False,
p=param_list[1])
s_e2e = Convolve(ser1=s1_lo,
ser2=s_23_lo,
indep=False,
p=param_list[2])
return single_hop_bound(foi=foi,
s_e2e=s_e2e,
theta=theta,
perform_param=self.perform_param,
indep=True)
def sfa_arr_bound(self, param_list: List[float]) -> float:
theta = param_list[0]
foi = self.arr_list[0]
a_2 = self.arr_list[1]
a_3 = self.arr_list[2]
s_1 = self.ser_list[0]
s_2 = self.ser_list[1]
s_3 = self.ser_list[2]
s1_lo = LeftoverARB(ser=s_1, cross_arr=a_2)
d_2_1 = Deconvolve(arr=a_2, ser=s_1)
s2_lo = LeftoverARB(ser=s_2,
cross_arr=AggregateTwo(arr1=d_2_1, arr2=a_3))
d_3_2 = Deconvolve(arr=a_3, ser=s_2)
# d_3_2 = Deconvolve(arr=a_3, ser=Leftover(ser=s_2, arr=a_2))
s3_lo = LeftoverARB(ser=s_3, cross_arr=d_3_2)
return sfa_tandem_bound(foi=foi,
leftover_service_list=[s1_lo, s2_lo, s3_lo],
theta=theta,
perform_param=self.perform_param,
p_list=param_list[1:],
e2e_enum=E2EEnum.ARR_RATE,
indep=False)
def sfa_min_bound(self, param_list: List[float]) -> float:
theta = param_list[0]
foi = self.arr_list[0]
a_2 = self.arr_list[1]
a_3 = self.arr_list[2]
s_1 = self.ser_list[0]
s_2 = self.ser_list[1]
s_3 = self.ser_list[2]
s1_lo = LeftoverARB(ser=s_1, cross_arr=a_2)
d_2_1 = Deconvolve(arr=a_2, ser=s_1)
s2_lo = LeftoverARB(ser=s_2,
cross_arr=AggregateTwo(arr1=d_2_1, arr2=a_3))
d_3_2 = Deconvolve(arr=a_3, ser=s_2)
# d_3_2 = Deconvolve(arr=a_3, ser=Leftover(ser=s_2, arr=a_2))
s3_lo = LeftoverARB(ser=s_3, cross_arr=d_3_2)
return sfa_tandem_bound(foi=foi,
leftover_service_list=[s1_lo, s2_lo, s3_lo],
theta=theta,
perform_param=self.perform_param,
p_list=param_list[1:],
e2e_enum=E2EEnum.MIN_RATE,
indep=False)
def sfa_rate_diff_bound(self, param_list: List[float]) -> float:
theta = param_list[0]
foi = self.arr_list[0]
a_2 = self.arr_list[1]
a_3 = self.arr_list[2]
s_1 = self.ser_list[0]
s_2 = self.ser_list[1]
s_3 = self.ser_list[2]
s1_lo = LeftoverARB(ser=s_1, cross_arr=a_2)
d_2_1 = Deconvolve(arr=a_2, ser=s_1)
s2_lo = LeftoverARB(ser=s_2,
cross_arr=AggregateTwo(arr1=d_2_1, arr2=a_3))
d_3_2 = Deconvolve(arr=a_3, ser=s_2)
# d_3_2 = Deconvolve(arr=a_3, ser=Leftover(ser=s_2, arr=a_2))
s3_lo = LeftoverARB(ser=s_3, cross_arr=d_3_2)
return sfa_tandem_bound(foi=foi,
leftover_service_list=[s1_lo, s2_lo, s3_lo],
theta=theta,
perform_param=self.perform_param,
p_list=param_list[1:],
e2e_enum=E2EEnum.RATE_DIFF,
indep=False)
def sfa_ac_bound(self, param_list: List[float]) -> float:
theta = param_list[0]
foi = self.arr_list[0]
a_2 = self.arr_list[1]
a_3 = self.arr_list[2]
s_1 = self.ser_list[0]
s_2 = self.ser_list[1]
s_3 = self.ser_list[2]
s1_lo = LeftoverARB(ser=s_1, cross_arr=a_2)
d_2_1 = Deconvolve(arr=a_2, ser=s_1)
s2_lo = LeftoverARB(ser=s_2,
cross_arr=AggregateTwo(arr1=d_2_1, arr2=a_3))
d_3_2 = Deconvolve(arr=a_3, ser=s_2)
# d_3_2 = Deconvolve(arr=a_3, ser=Leftover(ser=s_2, arr=a_2))
s3_lo = LeftoverARB(ser=s_3, cross_arr=d_3_2)
return sfa_tandem_bound(foi=foi,
leftover_service_list=[s1_lo, s2_lo, s3_lo],
theta=theta,
perform_param=self.perform_param,
p_list=param_list[1:],
e2e_enum=E2EEnum.ANALYTIC_COMBINATORICS,
indep=False)
def sfa_explicit(self, param_list: List[float]) -> float:
raise NotImplementedError("This is not implemented")
def approximate_utilization(self) -> float:
foi_rate = self.arr_list[0].average_rate()
a_2_rate = self.arr_list[1].average_rate()
a_3_rate = self.arr_list[2].average_rate()
c_1 = self.ser_list[0].rate
c_2 = self.ser_list[1].rate
c_3 = self.ser_list[2].rate
util_s_1 = (foi_rate + a_2_rate) / c_1
util_s_2 = (foi_rate + a_2_rate + a_3_rate) / c_2
util_s_3 = (foi_rate + a_3_rate) / c_3
return max(util_s_1, util_s_2, util_s_3)
def server_util(self, server_index: int) -> float:
a_foi_rate = self.arr_list[0].average_rate()
a_2_rate = self.arr_list[1].average_rate()
a_3_rate = self.arr_list[2].average_rate()
c_1 = self.ser_list[0].rate
c_2 = self.ser_list[1].rate
c_3 = self.ser_list[2].rate
if server_index == 0:
return (a_foi_rate + a_2_rate) / c_1
elif server_index == 1:
return (a_foi_rate + a_2_rate + a_3_rate) / c_2
elif server_index == 2:
return (a_foi_rate + a_3_rate) / c_3
else:
raise IllegalArgumentError("Wrong server index")
def to_string(self) -> str:
for arr in self.arr_list:
print(arr.to_value())
for ser in self.ser_list:
print(ser.to_value())
return self.to_name() + "_" + self.perform_param.__str__()
def gps_sfa_bound(param_list: [float], arr_list: List[ArrivalDistribution],
ser_list: List[ConstantRateServer],
perform_param: PerformParameter) -> float:
theta = param_list[0]
foi = arr_list[0]
a_2 = arr_list[1]
a_3 = arr_list[2]
s_1 = ser_list[0]
s_2 = ser_list[1]
s_3 = ser_list[2]
phi_list_1 = [foi.rho(theta=theta), a_2.rho(theta=theta)]
phi_list_2 = [
foi.rho(theta=theta),
a_2.rho(theta=theta),
a_3.rho(theta=theta)
]
phi_list_3 = [foi.rho(theta=theta), a_3.rho(theta=theta)]
s1_lo = LeftoverGPSPG(ser=s_1, phi_list=phi_list_1)
s2_lo = LeftoverGPSPG(ser=s_2, phi_list=phi_list_2)
s3_lo = LeftoverGPSPG(ser=s_3, phi_list=phi_list_3)
conv_s1_s2 = Convolve(ser1=s1_lo, ser2=s2_lo)
s_e2e = Convolve(ser1=conv_s1_s2, ser2=s3_lo)
return single_hop_bound(foi=foi,
s_e2e=s_e2e,
theta=theta,
perform_param=perform_param)
def gps_sfa_bound_full_param(param_list: [float, float, float, float, float],
arr_list: List[ArrivalDistribution],
ser_list: List[ConstantRateServer],
perform_param: PerformParameter) -> float:
if min(param_list) <= 0 or max(param_list[1:]) >= 1:
return inf
theta = param_list[0]
foi = arr_list[0]
s_1 = ser_list[0]
s_2 = ser_list[1]
s_3 = ser_list[2]
phi_list_1 = [param_list[1], 1 - param_list[1]]
phi_list_2 = [
param_list[2], param_list[3], 1 - sum([param_list[2], param_list[3]])
]
phi_list_3 = [param_list[4], 1 - param_list[4]]
s1_lo = LeftoverGPSPG(ser=s_1, phi_list=phi_list_1)
s2_lo = LeftoverGPSPG(ser=s_2, phi_list=phi_list_2)
s3_lo = LeftoverGPSPG(ser=s_3, phi_list=phi_list_3)
conv_s1_s2 = Convolve(ser1=s1_lo, ser2=s2_lo)
s_e2e = Convolve(ser1=conv_s1_s2, ser2=s3_lo)
return single_hop_bound(foi=foi,
s_e2e=s_e2e,
theta=theta,
perform_param=perform_param)
if __name__ == '__main__':
# from nc_arrivals.qt import DM1
# from nc_arrivals.qt import DPoisson1
from nc_arrivals.markov_modulated import MMOODisc
# from nc_arrivals.regulated_arrivals import LeakyBucketMassOne
from nc_operations.perform_enum import PerformEnum
from nc_server.constant_rate_server import ConstantRateServer
from optimization.optimize import Optimize
from optimization.optimize_sfa_bound import OptimizeSFABound
from msob_and_fp.optimize_fp_bound import OptimizeFPBound
from msob_and_fp.optimize_server_bound import OptimizeServerBound
DELAY_PROB_TIME = PerformParameter(perform_metric=PerformEnum.DELAY,
value=10**(-6))
# ARR_LIST = [DM1(lamb=2.3), DM1(lamb=4.5), DM1(lamb=1.7)]
# ARR_LIST = [DPoisson1(lamb=0.5), DPoisson1(lamb=0.2), DPoisson1(lamb=0.3)]
ARR_LIST = [
MMOODisc(stay_on=0.6, stay_off=0.4, peak_rate=0.9),
MMOODisc(stay_on=0.6, stay_off=0.4, peak_rate=0.5),
MMOODisc(stay_on=0.6, stay_off=0.4, peak_rate=0.7)
]
# ARR_LIST = [LeakyBucketMassOne(sigma_single=1.0, rho_single=0.5),
# LeakyBucketMassOne(sigma_single=1.0, rho_single=0.2),
# LeakyBucketMassOne(sigma_single=1.0, rho_single=0.3)]
# ARR_LIST = [
# TokenBucketConstant(sigma_single=1.0, rho_single=0.5),
# TokenBucketConstant(sigma_single=1.0, rho_single=0.2),
# TokenBucketConstant(sigma_single=1.0, rho_single=0.3)
# ]
SER_LIST = [
ConstantRateServer(rate=1.2),
ConstantRateServer(rate=6.2),
ConstantRateServer(rate=7.3)
]
if ARR_LIST[0].is_discrete() is False:
raise ValueError("Distribution must be discrete")
RANGES_1 = [slice(0.1, 10.0, 0.1)]
RANGES_2 = [slice(0.1, 10.0, 0.1), slice(1.1, 10.0, 0.1)]
RANGES_3 = [
slice(0.1, 10.0, 0.1),
slice(1.1, 10.0, 0.1),
slice(1.1, 10.0, 0.1)
]
RANGES_GPS = [
slice(0.1, 10.0, 0.1),
slice(0.1, 0.9, 0.05),
slice(0.1, 0.9, 0.05),
slice(0.1, 0.9, 0.05),
slice(0.1, 0.9, 0.05)
]
PRINT_X = True
print("Utilization:")
print(
OverlappingTandem(
arr_list=ARR_LIST,
ser_list=SER_LIST,
perform_param=DELAY_PROB_TIME).approximate_utilization())
OVERLAPPING_TANDEM = OverlappingTandem(arr_list=ARR_LIST,
ser_list=SER_LIST,
perform_param=DELAY_PROB_TIME)
OVERLAPPING_TANDEM_SFA = OverlappingTandemSFAPerform(
arr_list=ARR_LIST, ser_list=SER_LIST, perform_param=DELAY_PROB_TIME)
print("Standard Approach with PMOO:")
print(
| |
<reponame>neutrinoceros/AMICAL
import glob
import logging
import matplotlib.pyplot as plt
import numpy as np
import scipy
from scipy.io.idl import readsav
from termcolor import cprint
from . import oifits
from .cp_tools import project_cps
# import pymask.oifits
"""------------------------------------------------------------------------
cpo.py - Python class for manipulating oifits format closure phase data.
------------------------------------------------------------------------"""
class CustomFormatter(logging.Formatter):
"""Logging Formatter to add colors and count warning / errors"""
grey = "\x1b[38;21m"
yellow = "\x1b[33;21m"
red = "\x1b[31;21m"
green = "\x1b[32;5m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
format = (
"%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
)
FORMATS = {
logging.DEBUG: grey + format + reset,
logging.INFO: green + format + reset,
logging.WARNING: yellow + format + reset,
logging.ERROR: red + format + reset,
logging.CRITICAL: bold_red + format + reset,
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)
# create logger with 'spam_application'
log = logging.getLogger("PYMASK")
log.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(CustomFormatter())
log.addHandler(ch)
# log.debug("A quirky message only developers care about")
# log.info("Curious users might want to know this")
# log.warn("Something is wrong and any user should be informed")
# log.error("Serious stuff, this is red for a reason")
# log.critical("OH NO everything is on fire")
class cpo:
"""Class used to manipulate multiple closure phase datasets"""
def __init__(self, oifits):
# Default instantiation.
if type(oifits) == str:
oifits = [oifits]
if isinstance(oifits, str):
self.extract_from_oifits(oifits)
elif isinstance(oifits, list):
self.extract_multi_oifits(oifits)
else:
log.error("inputs must be an oifits file or a list of oifits files.")
def extract_from_oifits(self, filename):
"""Extract closure phase data from an oifits file."""
data = oifits.open(filename)
self.name = ""
self.ndata = len(data.t3)
for j in data.wavelength:
wavel = data.wavelength[j].eff_wave
self.wavel = wavel
self.nwavs = len(self.wavel)
self.target = data.target[0].target
t3data = []
t3err = []
self.u = np.zeros((self.ndata, 3))
self.v = np.zeros((self.ndata, 3))
for j, t3 in enumerate(data.t3):
t3data.append(t3.t3phi)
t3err.append(t3.t3phierr)
self.u[j, :] = [t3.u1coord, t3.u2coord, -(t3.u1coord + t3.u2coord)]
self.v[j, :] = [t3.v1coord, t3.v2coord, -(t3.v1coord + t3.v2coord)]
self.t3data = np.array(t3data)
self.t3err = np.array(t3err)
# Also load the v2
nv2 = len(data.vis2)
vis2data = []
vis2err = []
self.v2_u = np.zeros(nv2)
self.v2_v = np.zeros(nv2)
for j, v2 in enumerate(data.vis2):
vis2data.append(v2.vis2data)
vis2err.append(v2.vis2err)
self.v2_u[j] = v2.ucoord
self.v2_v[j] = v2.vcoord
self.vis2data = np.array(vis2data)
self.vis2err = np.array(vis2err)
def extract_multi_oifits(self, lfiles, verbose=True):
"""Extract closure phase data from a list of oifits files."""
U, V, t3data, t3err = [], [], [], []
for f in lfiles:
self.extract_from_oifits(f)
U.extend(self.u)
V.extend(self.v)
t3data.extend(self.t3data)
t3err.extend(self.t3err)
nbl = len(self.u)
self.u = np.array(U)
self.v = np.array(V)
self.t3data = np.array(t3data)
self.t3err = np.array(t3err)
if verbose:
cprint(
r"PYMASK - %i oifits loaded : n=%ix%i=%i closure phases."
% (len(lfiles), len(lfiles), nbl, len(t3data)),
"green",
)
class icpo:
"""Class used to manipulate multiple closure phase datasets.
This one structures the data differently, so it can be used with a covariance
matrix, or with projected closure phases"""
def __init__(self, oifits=None, directory=None, tsize_targ=None, tsize_cal=None):
# Default instantiation.
# if the file is a complete (kpi + kpd) structure
# additional data can be loaded.
if oifits:
try:
self.extract_from_oifits(oifits)
except Exception:
print("Invalid file.")
else:
# Otherwise load directory from the IDL bs files
self.extract_from_idl_directory(
directory, tsize_targ=tsize_targ, tsize_cal=tsize_cal
)
def extract_from_oifits(self, filename):
"""Extract closure phase data from an oifits file."""
data = oifits.open(filename)
self.name = ""
self.ndata = len(data.t3)
for j in data.wavelength:
wavel = data.wavelength[j].eff_wave
self.wavel = wavel
break
self.nwavs = len(self.wavel)
self.target = data.target[0].target
t3data = []
t3err = []
self.u = np.zeros((self.ndata, 3))
self.v = np.zeros((self.ndata, 3))
for j, t3 in enumerate(data.t3):
t3data.append(t3.t3phi)
t3err.append(t3.t3phierr)
self.u[j, :] = [t3.u1coord, t3.u2coord, -(t3.u1coord + t3.u2coord)]
self.v[j, :] = [t3.v1coord, t3.v2coord, -(t3.v1coord + t3.v2coord)]
self.t3data = np.array(t3data)
self.t3err = np.array(t3err)
# Also load the v2
nv2 = len(data.vis2)
vis2data = []
vis2err = []
self.v2_u = np.zeros(nv2)
self.v2_v = np.zeros(nv2)
for j, v2 in enumerate(data.vis2):
vis2data.append(v2.vis2data)
vis2err.append(v2.vis2err)
self.v2_u[j] = v2.ucoord
self.v2_v[j] = v2.vcoord
self.vis2data = np.array(vis2data)
self.vis2err = np.array(vis2err)
print(" This probably doesnt work...")
#########
def extract_from_idl_directory(
self,
analysis_dir,
tsize_targ=None,
tsize_cal=None,
idl_masking_dir="/Users/cheetham/code/masking/",
):
"""Import the closure phase data from the IDL pipeline directly
from the bispectrum (bs) files"""
# Get all of the bispectrum files
bs_files = glob.glob(analysis_dir + "bs*.idlvar")
bs_files.sort()
# Load the cubeinfo file
cubeinfo_file = glob.glob(analysis_dir + "cubeinfo*.idlvar")
cubeinfo = readsav(cubeinfo_file[0])
tsize = cubeinfo["olog"]["tsize"][0]
uflip = cubeinfo["olog"]["uflip"][0]
pa = cubeinfo["olog"]["pa"][0]
del_pa = cubeinfo["olog"]["del_pa"][0]
# Check that tsize is the right size (i.e. that we found all the files)
assert len(bs_files) == len(tsize)
# Find which ones are the targets and calibrators
# Default is that targets are all objects with tsize < 0
if tsize_targ is None:
targ_ix = tsize < 0
else:
targ_ix = np.zeros(len(tsize), dtype=bool)
for ix in tsize_targ:
targ_ix[tsize == ix] = True
# Default is that cals are all objects with tsize > 0
if tsize_cal is None:
cal_ix = tsize > 0
else:
cal_ix = np.zeros(len(tsize), dtype=bool)
for ix in tsize_cal:
cal_ix[tsize == ix] = True
# Set up all the arrays
# CPs
n_data_per_obs = []
cal_cps = []
targ_cps = []
print(f"Found {len(bs_files):4d} bs files from IDL")
# Loop through and load them
for ix, f in enumerate(bs_files):
data = readsav(f)
cps = np.angle(data["bs_all"], deg=True)
mean_cp = data["cp"]
err_cp = data["cp_sig"]
# Add a wavelength dimension to non-IFU data
if mean_cp.ndim == 1:
cps = cps[np.newaxis, :]
mean_cp = mean_cp[np.newaxis, :]
err_cp = err_cp[np.newaxis, :]
# Check if targ or cal, then add the cps there
if cal_ix[ix]:
if len(cal_cps) == 0:
cal_cps = cps
mean_cal_cps = mean_cp[:, :, np.newaxis]
std_cal_cps = err_cp[:, :, np.newaxis]
else:
cal_cps = np.append(cal_cps, cps, axis=2)
mean_cal_cps = np.append(
mean_cal_cps, mean_cp[:, :, np.newaxis], axis=2
)
std_cal_cps = np.append(
std_cal_cps, err_cp[:, :, np.newaxis], axis=2
)
elif targ_ix[ix]:
if len(targ_cps) == 0:
# We have lots of setup to do for the first file, and then we'll reuse it for the rest
# Load the matched filter file since it contains some useful info
mf_file = idl_masking_dir + "templates/" + data["mf_file"]
mf_data = readsav(mf_file)
# Work out the wavelengths now
# u_ideal is the baseline divided by lambda so we can get them back from the first baseline like this
xy_coords = mf_data["xy_coords"]
bl2h_ix = mf_data["bl2h_ix"]
if "u_ideal" in mf_data.keys(): # For the closing triangle approach
wavs = (
float(xy_coords[0, bl2h_ix[0, 0]])
- xy_coords[0, bl2h_ix[0, 1]]
) / mf_data["u_ideal"][..., 0]
else: # For the matched filter approach
wavs = (
float(xy_coords[0, bl2h_ix[0, 0]])
- xy_coords[0, bl2h_ix[0, 1]]
) / mf_data["u"][..., 0]
wavs = np.atleast_1d(wavs)
# Get the uv coords from the matched filter file
# This should be the same at all wavelengths
if data["u"].ndim == 1:
# in metres
u_coords = data["u"][mf_data["bs2bl_ix"]] * wavs[0]
# in metres
v_coords = data["v"][mf_data["bs2bl_ix"]] * wavs[0]
else:
# in metres
u_coords = data["u"][0, mf_data["bs2bl_ix"]] * wavs[0]
# in metres
v_coords = data["v"][0, mf_data["bs2bl_ix"]] * wavs[0]
# Rotate the uv coords
pa_rad = (pa[ix] - 0.5 * del_pa[ix]) * np.pi / 180.0
u_coords1 = uflip * u_coords * np.cos(pa_rad) + v_coords * np.sin(
pa_rad
)
v_coords1 = -uflip * u_coords * np.sin(pa_rad) + v_coords * np.cos(
pa_rad
)
if len(targ_cps) == 0:
# keep this a list to make it easier to separate them
targ_cps = [cps.transpose((1, 2, 0))]
mean_targ_cps = mean_cp[:, :, np.newaxis]
std_targ_cps = err_cp[:, :, np.newaxis]
targ_u_coords = u_coords1[:, np.newaxis, :]
targ_v_coords = v_coords1[:, np.newaxis, :]
else:
# targ_cps = np.append(targ_cps,cps,axis=2)
targ_cps.append(cps.transpose((1, 2, 0)))
mean_targ_cps = np.append(
mean_targ_cps, mean_cp[:, :, np.newaxis], axis=2
)
std_targ_cps = np.append(
std_targ_cps, err_cp[:, :, np.newaxis], axis=2
)
targ_u_coords = np.append(
targ_u_coords, u_coords1[:, np.newaxis, :], axis=1
)
targ_v_coords = np.append(
targ_v_coords, v_coords1[:, np.newaxis, :], axis=1
)
n_data_per_obs.append(cps.shape[2])
# Convert to the right units
mean_targ_cps *= 180.0 / np.pi
mean_cal_cps *= 180.0 / np.pi
std_targ_cps *= 180.0 / np.pi
std_cal_cps *= 180.0 / np.pi
cal_cov = np.zeros((cal_cps.shape[0], cal_cps.shape[1], cal_cps.shape[1]))
cal_cov_inv = 0 * cal_cov
for wav_ix, wav_clps in enumerate(cal_cps):
# Get the covariance and its inverse
wav_cov = np.cov(wav_clps)
wav_cov_inv = np.linalg.inv(wav_cov)
cal_cov[wav_ix] = wav_cov
cal_cov_inv[wav_ix] = wav_cov_inv
# Bug fix:
# The uv coordinates above are all positive. The third baseline should be flipped
targ_u_coords[:, :, | |
not " + typeof(fillchar)));
}
if (this['length'] >= width) return this;
return this + new Array(width+1 - this['length'])['join'](fillchar);
}
pyjslib['String_rjust'] = function(width, fillchar) {
if (typeof(width) != 'number' ||
parseInt(width) != width) {
throw (pyjslib['TypeError']("an integer is required"));
}
if (pyjslib['isUndefined'](fillchar)) fillchar = ' ';
if (typeof(fillchar) != 'string' ||
fillchar['length'] != 1) {
throw (pyjslib['TypeError']("rjust() argument 2 must be char, not " + typeof(fillchar)));
}
if (this['length'] >= width) return this;
return new Array(width + 1 - this['length'])['join'](fillchar) + this;
}
pyjslib['String_center'] = function(width, fillchar) {
if (typeof(width) != 'number' ||
parseInt(width) != width) {
throw (pyjslib['TypeError']("an integer is required"));
}
if (pyjslib['isUndefined'](fillchar)) fillchar = ' ';
if (typeof(fillchar) != 'string' ||
fillchar['length'] != 1) {
throw (pyjslib['TypeError']("center() argument 2 must be char, not " + typeof(fillchar)));
}
if (this['length'] >= width) return this;
var padlen = width - this['length'];
var right = Math['ceil'](padlen / 2);
var left = padlen - right;
return new Array(left+1)['join'](fillchar) + this + new Array(right+1)['join'](fillchar);
}
pyjslib['abs'] = Math['abs'];
""")
class Class:
def __init__(self, name):
self.name = name
def __str___(self):
return self.name
@noSourceTracking
def eq(a,b):
# All 'python' classes and types are implemented as objects/functions.
# So, for speed, do a typeof X / X.__cmp__ on a/b.
# Checking for the existance of .__cmp__ is expensive...
JS("""
if (@{{a}} === null) {
if (@{{b}} === null) return true;
return false;
}
if (@{{b}} === null) {
return false;
}
if ((typeof @{{a}} == 'object' || typeof @{{a}} == 'function') && typeof @{{a}}['__cmp__'] == 'function') {
return @{{a}}['__cmp__'](@{{b}}) == 0;
} else if ((typeof @{{b}} == 'object' || typeof @{{b}} == 'function') && typeof @{{b}}['__cmp__'] == 'function') {
return @{{b}}['__cmp__'](@{{a}}) == 0;
}
return @{{a}} == @{{b}};
""")
@noSourceTracking
def cmp(a,b):
JS("""
if (@{{a}} === null) {
if (@{{b}} === null) return 0;
return -1;
}
if (@{{b}} === null) {
return 1;
}
if ((typeof @{{a}} == 'object' || typeof @{{a}} == 'function') && typeof @{{a}}['__cmp__'] == 'function') {
return @{{a}}['__cmp__'](@{{b}});
} else if ((typeof @{{b}} == 'object' || typeof @{{b}} == 'function') && typeof @{{b}}['__cmp__'] == 'function') {
return -@{{b}}['__cmp__'](@{{a}});
}
if (@{{a}} > @{{b}}) return 1;
if (@{{b}} > @{{a}}) return -1;
return 0;
""")
# For list.sort()
__cmp = cmp
@noSourceTracking
def bool(v):
# this needs to stay in native code without any dependencies here,
# because this is used by if and while, we need to prevent
# recursion
JS("""
if (!@{{v}}) return false;
switch(typeof @{{v}}){
case 'boolean':
return @{{v}};
case 'object':
if (@{{v}}['__nonzero__']){
return @{{v}}['__nonzero__']();
}else if (@{{v}}['__len__']){
return @{{v}}['__len__']()>0;
}
return true;
}
return Boolean(@{{v}});
""")
class List:
@noSourceTracking
def __init__(self, data=None):
JS("""
this['l'] = [];
this['extend'](@{{data}});
""")
@noSourceTracking
def append(self, item):
JS(""" this['l'][this['l']['length']] = @{{item}};""")
@noSourceTracking
def extend(self, data):
JS("""
if (pyjslib['isArray'](@{{data}})) {
var n = this['l']['length'];
for (var i=0; i < @{{data}}['length']; i++) {
this['l'][n+i]=@{{data}}[i];
}
}
else if (pyjslib['isIteratable'](@{{data}})) {
var iter=@{{data}}['__iter__']();
var i=this['l']['length'];
try {
while (true) {
var item=iter['next']();
this['l'][i++]=item;
}
}
catch (e) {
if (e['__name__'] != 'StopIteration') throw e;
}
}
""")
@noSourceTracking
def remove(self, value):
JS("""
var index=this['index'](@{{value}});
if (index<0) return false;
this['l']['splice'](index, 1);
return true;
""")
@noSourceTracking
def index(self, value, start=0):
JS("""
var length=this['l']['length'];
for (var i=@{{start}}; i<length; i++) {
if (this['l'][i]==@{{value}}) {
return i;
}
}
return -1;
""")
@noSourceTracking
def insert(self, index, value):
JS(""" var a = this['l']; this['l']=a['slice'](0, @{{index}})['concat'](@{{value}}, a['slice'](@{{index}}));""")
@noSourceTracking
def pop(self, index = -1):
JS("""
if (@{{index}}<0) @{{index}} = this['l']['length'] + @{{index}};
var a = this['l'][@{{index}}];
this['l']['splice'](@{{index}}, 1);
return a;
""")
@noSourceTracking
def __cmp__(self, l):
if not isinstance(l, List):
return -1
ll = len(self) - len(l)
if ll != 0:
return ll
for x in range(len(l)):
ll = cmp(self.__getitem__(x), l[x])
if ll != 0:
return ll
return 0
@noSourceTracking
def slice(self, lower, upper):
JS("""
if (@{{upper}}==null) return pyjslib['List'](this['l']['slice'](@{{lower}}));
return pyjslib['List'](this['l']['slice'](@{{lower}}, @{{upper}}));
""")
@noSourceTracking
def __getitem__(self, index):
JS("""
if (@{{index}}<0) @{{index}} = this['l']['length'] + @{{index}};
return this['l'][@{{index}}];
""")
@noSourceTracking
def __setitem__(self, index, value):
JS(""" this['l'][@{{index}}]=@{{value}};""")
@noSourceTracking
def __delitem__(self, index):
JS(""" this['l']['splice'](@{{index}}, 1);""")
@noSourceTracking
def __len__(self):
JS(""" return this['l']['length'];""")
@noSourceTracking
def __contains__(self, value):
return self.index(value) >= 0
@noSourceTracking
def __iter__(self):
JS("""
var i = 0;
var l = this['l'];
return {
'next': function() {
if (i >= l['length']) {
throw pyjslib['StopIteration'];
}
return l[i++];
},
'__iter__': function() {
return this;
}
};
""")
@noSourceTracking
def reverse(self):
JS(""" this['l']['reverse']();""")
def sort(self, cmp=None, key=None, reverse=False):
if not cmp:
cmp = __cmp
if key and reverse:
def thisSort1(a,b):
return -cmp(key(a), key(b))
self.l.sort(thisSort1)
elif key:
def thisSort2(a,b):
return cmp(key(a), key(b))
self.l.sort(thisSort2)
elif reverse:
def thisSort3(a,b):
return -cmp(a, b)
self.l.sort(thisSort3)
else:
self.l.sort(cmp)
@noSourceTracking
def getArray(self):
"""
Access the javascript Array that is used internally by this list
"""
return self.l
@noSourceTracking
def __str__(self):
return self.__repr__()
@noSourceTracking
def toString(self):
return self.__repr__()
def __repr__(self):
#r = []
#for item in self:
# r.append(repr(item))
#return '[' + ', '.join(r) + ']'
JS("""
var s = "[";
for (var i=0; i < @{{self}}['l']['length']; i++) {
s += pyjslib['repr'](@{{self}}['l'][i]);
if (i < @{{self}}['l']['length'] - 1)
s += ", ";
};
s += "]"
return s;
""")
class Tuple:
@noSourceTracking
def __init__(self, data=None):
JS("""
this['l'] = [];
this['extend'](@{{data}});
""")
@noSourceTracking
def append(self, item):
JS(""" this['l'][this['l']['length']] = @{{item}};""")
@noSourceTracking
def extend(self, data):
JS("""
if (pyjslib['isArray'](@{{data}})) {
var n = this['l']['length'];
for (var i=0; i < @{{data}}['length']; i++) {
this['l'][n+i]=@{{data}}[i];
}
}
else if (pyjslib['isIteratable'](@{{data}})) {
var iter=@{{data}}['__iter__']();
var i=this['l']['length'];
try {
while (true) {
var item=iter['next']();
this['l'][i++]=item;
}
}
catch (e) {
if (e['__name__'] != 'StopIteration') throw e;
}
}
""")
@noSourceTracking
def remove(self, value):
JS("""
var index=this['index'](@{{value}});
if (index<0) return false;
this['l']['splice'](index, 1);
return true;
""")
@noSourceTracking
def index(self, value, start=0):
JS("""
var length=this['l']['length'];
for (var i=@{{start}}; i<length; i++) {
if (this['l'][i]==@{{value}}) {
return i;
}
}
return -1;
""")
@noSourceTracking
def insert(self, index, value):
JS(""" var a = this['l']; this['l']=a['slice'](0, @{{index}})['concat'](@{{value}}, a['slice'](@{{index}}));""")
@noSourceTracking
def pop(self, index = -1):
JS("""
if (@{{index}}<0) @{{index}} = this['l']['length'] + @{{index}};
var a = this['l'][@{{index}}];
this['l']['splice'](@{{index}}, 1);
return a;
""")
@noSourceTracking
def __cmp__(self, l):
if not isinstance(l, Tuple):
return 1
ll = len(self) - len(l)
if ll != 0:
return ll
for x in range(len(l)):
ll = cmp(self.__getitem__(x), l[x])
if ll != 0:
return ll
return 0
@noSourceTracking
def slice(self, lower, upper):
JS("""
if (@{{upper}}==null) return pyjslib['Tuple'](this['l']['slice'](@{{lower}}));
return pyjslib['Tuple'](this['l']['slice'](@{{lower}}, @{{upper}}));
""")
@noSourceTracking
def __getitem__(self, index):
JS("""
if (@{{index}}<0) @{{index}} = this['l']['length'] + @{{index}};
return this['l'][@{{index}}];
""")
@noSourceTracking
def __setitem__(self, index, value):
JS(""" this['l'][@{{index}}]=@{{value}};""")
@noSourceTracking
def __delitem__(self, index):
JS(""" this['l']['splice'](@{{index}}, 1);""")
@noSourceTracking
def __len__(self):
JS(""" return this['l']['length'];""")
@noSourceTracking
def __contains__(self, value):
return self.index(value) >= 0
@noSourceTracking
def __iter__(self):
JS("""
var i = 0;
var l = this['l'];
return {
'next': function() {
if (i >= l['length']) {
throw pyjslib['StopIteration'];
}
return l[i++];
},
'__iter__': function() {
return this;
}
};
""")
@noSourceTracking
def reverse(self):
JS(""" this['l']['reverse']();""")
def sort(self, cmp=None, key=None, reverse=False):
if not cmp:
cmp = cmp
if key and reverse:
def thisSort1(a,b):
return -cmp(key(a), key(b))
self.l.sort(thisSort1)
elif key:
def thisSort2(a,b):
return cmp(key(a), key(b))
self.l.sort(thisSort2)
elif reverse:
def thisSort3(a,b):
return -cmp(a, b)
self.l.sort(thisSort3)
else:
self.l.sort(cmp)
@noSourceTracking
def getArray(self):
"""
Access the javascript Array that is used internally by this list
"""
return self.l
@noSourceTracking
def __str__(self):
return self.__repr__()
@noSourceTracking
def toString(self):
return self.__repr__()
def __repr__(self):
#r = []
#for item in self:
# r.append(repr(item))
#if len(r) == 1:
# return '(' + ', '.join(r) + ',)'
#return '(' + ', '.join(r) + ')'
JS("""
var s = "(";
for (var i=0; i < @{{self}}['l']['length']; i++) {
s += pyjslib['repr'](@{{self}}['l'][i]);
if (i < @{{self}}['l']['length'] - 1)
s += ", ";
};
if (@{{self}}['l']['length'] == 1)
s += ",";
s += ")"
return s;
""")
class Dict:
@noSourceTracking
def __init__(self, data=None):
JS("""
this['d'] = {};
if (pyjslib['isArray'](@{{data}})) {
for (var i in @{{data}}) {
var item=@{{data}}[i];
this['__setitem__'](item[0], item[1]);
//var sKey=pyjslib['hash'](item[0]);
//this['d'][sKey]=item[1];
}
}
else if (pyjslib['isIteratable'](@{{data}})) {
var iter=@{{data}}['__iter__']();
try {
while (true) {
var item=iter['next']();
this['__setitem__'](item['__getitem__'](0), item['__getitem__'](1));
}
}
catch (e) {
| |
#!/usr/bin/env python
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from io import BytesIO
zeroconfExists = False
try:
from zeroconf import ServiceBrowser, Zeroconf
zeroconfExists = True
except Exception as e:
# print ( e )
zeroconfExists = False
import json
import inspect
import time
import datetime
import socket
import sys
import os
import threading
import types
import numbers
import collections
resourceExists = True
try:
import resource
except Exception as e:
# print ( e )
resourceExists = False
dateutil_exists = False
try:
import dateutil.parser
dateutil_exists = True
except ImportError:
pass
try:
basestring
except NameError:
basestring = str
def isInt(i):
try:
int(i)
except:
return False
return True
class Event ( object ):
def __init__ (self,name,type=None,body=None):
self.name = None
self.type = None
self.user = None
self.control = None
self.body = None
if isinstance ( name, dict ):
obj = name
self.className = self.__class__.__name__
self.name = obj["name"]
if 'type' in obj and obj["type"] != None:
self.type = obj["type"]
self.user = obj.get('user')
self.control = obj["control"]
self.body = obj["body"]
return
if not isinstance ( name, basestring):
raise ValueError ( "name must be a non empty string, not: " + str(name) + "(" + name.__class__.__name__ + ")" )
if type != None and not isinstance ( type, basestring):
raise ValueError ( "type must be None or a non empty string, not: " + str(type) + "(" + type.__class__.__name__ + ")" )
self.className = self.__class__.__name__
self.name = name
self.type = type
if body == None:
self.body = {}
elif isinstance ( body, dict ):
self.body = body
else:
raise ValueError ( "body must be None or a dict, not: " + str(body) + "(" + body.__class__.__name__ + ")" )
self.user = None
self.control = { "createdAt": datetime.datetime.now(), "hostname": socket.gethostname(), "plang": "python" }
self.channel = None
self.sid = None
def jsa(self):
if "_JSAcc" in self.__dict__:
return self._JSAcc
self._JSAcc = JSAcc ( self.__dict__ )
return self._JSAcc
def __str__(self):
s = StringIO()
s.write("(")
s.write(self.__class__.__name__)
s.write(")")
s.write("[name='" + self.name + ",type='" + str(self.type) + "']\n" )
s.write(" control:\n" )
s.write(" " + str(self.control) )
if isinstance ( self.user, User ):
s.write("\n user:\n " + str(self.user) )
s.write("\n body:\n " + str(self.body) )
s.write("]")
return s.getvalue()
def getBody(self):
return self.body
def getCreatedAt(self):
return self.control["createdAt"]
def getName ( self ):
return self.name
def setName ( self, name ):
self.name = name
def getType ( self ):
return self.type
def setType ( self, type ):
self.type = type
def setUser ( self, user ):
self.user = user
def getUser ( self ):
return self.user
def setBody(self,body):
if not isinstance ( body, dict ):
raise ValueError ( "body must be a dict, not: " + str(body) )
self.body = body
def getHostname ( self ):
return self.control["hostname"]
def putValue ( self, name, value ):
if not isinstance ( name, basestring):
raise ValueError ( "name must be a non empty string, not: " + str(name) + "(" + name.__class__.__name__ + ")" )
self.body[name] = value
def getValue ( self, name ):
if not isinstance ( name, basestring):
raise ValueError ( "name must be a non empty string, not: " + str(name) + "(" + name.__class__.__name__ + ")" )
if name not in self.body:
return None
return self.body[name]
def removeValue ( self, name ):
if not isinstance ( name, basestring):
raise ValueError ( "name must be a non empty string, not: " + str(name) + "(" + name.__class__.__name__ + ")" )
if name not in self.body:
return None
obj = self.body[name]
del self.body[name]
return obj
def getClient(self):
return self._Client
def sendBack(self):
self._Client.sendResult ( self )
def serialize(self):
if "_Client" in self.__dict__:
del self._Client
if "_JSAcc" in self.__dict__:
del self._JSAcc
s = json.dumps ( self, default=self.toJSON )
return s
def setUniqueId ( self, uid ):
if "uniqueId" in self.control and self.control["uniqueId"] != None:
return
self.control["uniqueId"] = uid
def getUniqueId ( self ):
return self.control.get ("uniqueId")
def isBad ( self ):
code = self.getStatusCode()
if code == None: return False
return code != 0
def getStatus ( self ):
return self.jsa().value ( "control/status" )
def getStatusCode ( self ):
return self.jsa().value ( "control/status/code" )
def getStatusReason ( self ):
return self.jsa().value ( "control/status/reason" )
def getStatusName ( self ):
return self.jsa().value ( "control/status/name" )
def setStatus ( self, code=0, name="success", reason=""):
self.jsa().add ( "control/status/code", code )
self.jsa().add ( "control/status/name", name )
self.jsa().add ( "control/status/reason", reason )
def setIsResult ( self ):
self.control["_isResult"] = True
def isResult ( self ):
return self.jsa().value ( "control/_isResult", False )
def setResultRequested ( self ):
self.control["_isResultRequested"] = True
def isResultRequested ( self ):
if "_isResultRequested" not in self.control: return False
return self.control["_isResultRequested"]
def setFailureInfoRequested(self):
self.control["_isFailureInfoRequested"] = True
def isFailureInfoRequested(self):
if "_isFailureInfoRequested" not in self.control: return False
return self.control["_isFailureInfoRequested"]
def setStatusInfoRequested(self):
self.control["_isStatusInfoRequested"] = True
def isStatusInfoRequested(self):
if "_isStatusInfoRequested" not in self.control: return False
return self.control["_isStatusInfoRequested"]
def isStatusInfo(self):
if "_isStatusInfo" not in self.control: return False
return self.control["_isStatusInfo"]
def setChannel ( self, channel ):
if self.control.get ( "channel" ) != None:
return
self.control["channel"] = channel
def getChannel ( self ):
return self.control.get ("channel")
@staticmethod
def deserialize ( s ):
obj = json.loads ( s, object_hook=Event.fromJSON )
e = Event ( obj )
return e
@staticmethod
def toJSON(obj):
if isinstance ( obj, bytes ):
return { 'type': 'Buffer'
, 'data': list(obj)
}
if isinstance ( obj, bytearray ):
return { 'type': 'Buffer'
, 'data': list(obj)
}
if isinstance ( obj, datetime.datetime ):
return { 'type': 'Date'
, 'value': obj.isoformat()
}
if isinstance ( obj, Event ):
juser = None
if obj.user != None:
juser = obj.user.toJSON()
ju = { 'className': obj.className
, 'name':obj.name
, "type":obj.type
, "body":obj.body
, "control":obj.control
, "user":juser
}
return ju
if hasattr ( obj, "toJSON" ) and callable ( getattr ( obj, "toJSON" ) ):
m = getattr ( obj, "toJSON" )
if m != None:
o = obj.toJSON()
return o
raise TypeError ( repr(obj) + ' is not JSON serializable' )
@staticmethod
def fromJSON ( obj ):
if 'type' in obj:
if obj['type'] == 'time.asctime':
return time.strptime(obj['data'])
if obj['type'] == 'Date':
if dateutil_exists:
return dateutil.parser.parse(obj['value'])
return obj['value']
if obj['type'] == 'bytes':
return bytes(obj['data'])
if obj['type'] == 'Buffer':
return bytes(obj['data'])
if 'className' in obj:
className = obj['className']
try:
if className != "Event":
clazz = globals()[className]
u = clazz(obj)
return u
except Exception as exc:
# print ( exc )
pass
return obj
class User ( object ):
def __init__ ( self, id, key=None, pwd=<PASSWORD>, rights=None ):
if isinstance ( id, dict ):
obj = id
self.className = self.__class__.__name__
self.id = obj.get("id")
self.key = obj.get("key")
self._pwd = obj.get("_<PASSWORD>")
self.rights = obj.get("rights")
self.groups = obj.get("groups")
self.attributes = obj.get("attributes")
return
self.className = "User"
self.id = id
self.key = key
self._pwd = <PASSWORD>
self.rights = {}
self.groups = {}
self.attributes = {}
if rights == None:
self.rights = {}
elif isinstance ( rights, dict ):
self.rights = rights
else:
raise ValueError ( "rights must be None or a dict, not: " + str(rights) + "(" + rights.__class__.__name__ + ")" )
def __str__(self):
s = StringIO()
s.write("(")
s.write(self.__class__.__name__)
s.write(")")
s.write("[id=" + str(self.id) )
s.write(",_pwd=" + "******" )
s.write(",key=" + str(self.key) )
s.write(",rights=" + str(self.rights) )
s.write(",groups=" + str(self.groups) )
s.write("]")
return s.getvalue()
def toJSON(self):
ju = { 'className': self.className
, "id":self.id
, "key":self.key
, "_pwd":<PASSWORD>
, "rights":self.rights
}
return ju
def addRight ( self, name, value ):
self.rights[name] = value
def getRight ( self, name ):
return self.rights[name]
def getAttributes(self):
return self.attributes
def getAttribute(self,name):
return self.attributes[name]
def getLanguage(self):
return self.getAttribute("lang")
import socket, struct
class CallbackWorker:
def __init__(self,client):
self.counter = 0
self.client = client
def run(self):
while True:
e = None
callback = None
try:
e = self.client._CallbackIsolator.get()
# print ( "counter=" + str(self.counter) )
if e == None:
break
except Exception as exc:
print ( exc )
break
try:
if e.isStatusInfo():
callback = self.client.callbacks.get ( e.getUniqueId() )
if callback == None:
print ( "No callback found for:\n" + e )
continue
if "status" in callback:
del self.client.callbacks[e.getUniqueId()]
callback["status"] ( e )
continue
if e.isBad():
if e.isResult():
callback = self.client.callbacks.get ( e.getUniqueId() )
if callback == None:
print ( "No callback found for:\n" + e )
continue
del self.client.callbacks[e.getUniqueId()]
if e.isFailureInfoRequested() and "failure" in callback:
callback["failure"] ( e )
elif "error" in callback:
callback["error"] ( e )
elif "result" in callback:
callback["result"] ( e )
continue
if e.isResult():
callback = self.client.callbacks.get ( e.getUniqueId() )
if callback == None:
print ( "No callback found for:\n" + e )
continue
del self.client.callbacks[e.getUniqueId()]
if "result" in callback:
callback["result"] ( e )
else:
print ( "No result callback found for:\n" + e )
continue
callbackList = self.client.eventListenerFunctions.get ( e.getName() )
if e.getChannel() != None:
callbackList2 = self.client.eventListenerFunctions.get ( e.getChannel() + "::" + e.getName() )
if callbackList2 != None:
if callbackList != None:
callbackList = callbackList2 + callbackList
else:
callbackList = callbackList2 + []
found = False
for function in callbackList:
found = True
function ( e )
if e.isResultRequested():
break
for pc in self.client.patternContextList:
if pc.matches ( e.getName() ):
if e.isResultRequested():
if not found:
pc.cb ( e )
found = True
break
else:
pc.cb ( e )
found = True
if not found:
print ( "listener function list for " + e.getName() + " not found." )
print ( e )
except Exception as exc:
print ( exc )
def decoratedTimerCallback(_self):
def deco ():
_self._checkReconnect()
return deco
def localTracer(t):
print ( t )
def remoteTracer(_self):
def log ( t ):
try:
_self.log ( t )
except Exception as exc:
print ( exc )
return log
class ActionCmd:
def __init__(self,parameter):
self.parameter = parameter
self.cmd = parameter.get ( "cmd" )
self.args = parameter.get ( "args" )
self.result = ""
def getCmd ( self ):
return self.cmd
def setResult(self,text):
self.result = text
def getArgs(self):
return self.args
class ActionCmdCtx:
def __init__ ( self, cmd, desc, cb ):
self.cmd = cmd
self.desc = desc
self.cb = cb
import re
class PatternContext:
def __init__ ( self, eventName, cb ):
self.originalEventName = eventName
if eventName[0] == '/' and eventName[-1] == '/':
self.p = re.compile ( eventName[1:-2] ) ;
elif eventName.find ( '.*' ) >= 0:
self.p = re.compile ( eventName ) ;
elif eventName.find ( '*' ) >= 0 or eventName.find ( '?' ) >= 0:
self.eventName = eventName.replace ( ".", "\\." ).replace ( "*", ".*" ).replace ( '?', '.' )
self.p = re.compile ( eventName ) ;
else:
self.p = re.compile ( eventName ) ;
self.cb = cb ;
def matches ( self, t ):
return self.p.match ( t )
# -----------------------------------------------------------------------------------------
class ZeroconfFindServiceAdapter(object):
def __init__(self,client,callback,first=True):
self.client = client
self.callback = callback
self.host = None
self.port = None
self.TOPICS = | |
<reponame>GreenFarmCsa/greenfarm
"""
AI API FOR Green Farm BACKEND
"""
import json
import datetime
import requests
import pandas as pd
from flask import Flask, request
app = Flask(__name__)
aggregated_products = sorted(['Corn', 'Cucumber', 'Tomato', 'Onion', 'Spinach'])
aggregated_farm_location = sorted(
['Austin,Texas', 'Moorpark,California', 'Casa Grande,Arizona', 'Shropshire,West Midlands', 'Uphall,Scotland',
'Norfolk,East Anglia', 'Changping district,Beijing', 'Jinan,Shandong Province', 'Zhangjiajie,Hunan Province',
'Wyong Creek,New South Wales', 'Red Hill,Victoria'])
aggregated_user_location = sorted(['Cantwell city,Alaska,USA', 'Queens,New York,NY,USA'])
aggregated_category = sorted(['vegetables', 'fruit'])
aggregated_identification = sorted(['1', '2', '3', '4', '5', '6', '7'])
def aggregate_comment_products(comment_products):
"""
This function applies one-hot-encoding on comment products
return integer representations
"""
# comment_products: ["Corn", "Tomato"]
encoding = ''
for product in aggregated_products:
if product in comment_products:
encoding = encoding + '1'
else:
encoding = encoding + '0'
return int(encoding)
def aggregate_product_identification(product_identification):
"""
This function applies one-hot-encoding on products category
"""
encoding = ''
category = product_identification.split(",")
for identification in aggregated_identification:
if identification in category:
encoding = encoding + '1'
else:
encoding = encoding + '0'
return int(encoding)
def preprocess_location(location):
"""
get rid of possible spaces around farm location string
"""
locations = location.split(',')
res = ""
for location in locations:
res = res + location.strip() + ","
res = res[:-1]
return res
def combine_data(get_data):
"""
combine user data with each farm
preprocess attributes to generate the prediction set
"""
try:
values = []
user_location = preprocess_location(get_data.get('location'))
location = 1
if user_location in aggregated_user_location:
location = aggregated_user_location.index(user_location)
community_id = int(get_data.get('community_id'))
carbon_credit = int(get_data.get('carbon_credit'))
carbon_medals = int(get_data.get('carbon_medals'))
comment_products = aggregate_comment_products(get_data.get('comment_products'))
farms = get_data.get('farm')
farm_ids = []
for i in range(0, len(farms)):
value = []
farm = farms[i]
farm_ids.append(str(farm.get('farm_id')))
value.append(community_id)
value.append(location)
value.append(carbon_credit)
value.append(carbon_medals)
value.append(comment_products)
farm_location = farm.get('location')
farm_location_processed = 0
if preprocess_location(farm_location) in aggregated_farm_location:
farm_location_processed = aggregated_farm_location.index(preprocess_location(farm_location))
suited_crops = aggregate_comment_products(farm.get('suited_crops'))
rent_period = 0
total_area = int(farm.get('total_area'))
idle_area = farm.get('idle_area')
if idle_area is None:
idle_area = 0
idle_area = int(idle_area)
value.append(farm_location_processed)
value.append(suited_crops)
value.append(rent_period)
value.append(total_area)
value.append(idle_area)
values.append(value)
return values, farm_ids
except:
return [], []
def make_predictions(predictions, ids):
"""
sort id according to prediction scores
from high to low
"""
farm_score = {}
p_text = json.loads(predictions.text)
prediction = p_text['predictions'][0]['values']
num_prediction = len(prediction)
for i in range(0, num_prediction):
pred_score = prediction[i][1]
if pred_score[1] > pred_score[0]:
farm_score[ids[i]] = pred_score[1]
sorted_farm_score = sorted(farm_score, key=farm_score.get, reverse=True)
return sorted_farm_score
def recommend_top_three_farms(sorted_farm_score, username, rent_list, all_farms):
"""
recommend three farms with highest prediction scores
if not enough farm, recommend first three farms
"""
count = 0
recommend_farms = set()
for farm in sorted_farm_score:
recommend_farms.add(farm)
count += 1
if count == 3:
return recommend_farms
farm_ids = check_rent_history(rent_list, username)
for i in range(0, len(farm_ids)):
# check the history rent history
recommend_farms.add(farm_ids[i])
current = 0
while len(recommend_farms) < 3 and current < len(all_farms):
recommend_farms.add(all_farms[current])
current = current + 1
return recommend_farms
def check_rent_history(rent_list, username):
"""
return farm ids that the given username has rented before
"""
farm_rent_before = []
for rent in rent_list:
if rent.get('username') == username:
farm_rent_before.append(str(rent.get('farm_id')))
return farm_rent_before
def fill_answer(recommend_farms, result):
"""
fill the return json with recommended farm ids
"""
for farm in recommend_farms:
result.append({'farm_id': farm, 'description': 'recommended farm'})
return result
def combine_product_data(get_data):
"""
combine user information with agricultural products
"""
try:
community_id = int(get_data['community_id'])
user_location = preprocess_location(get_data['location'])
location = 1
if user_location in aggregated_user_location:
location = aggregated_user_location.index(user_location)
carbon_credit = int(get_data['carbon_credit'])
carbon_medals = int(get_data['carbon_medals'])
comment_products = aggregate_comment_products(get_data['comment_products'])
orders = get_data['order_list']
product_ids = ['1', '2', '3', '4', '5', '6']
values = []
for i in range(0, len(orders)):
value = [community_id, location, carbon_credit, carbon_medals, comment_products]
order = orders[i]
product_id = int(order['product_id'])
farm_id = int(order['farm_id'])
product_name = aggregated_products.index(order['product_name'])
category = aggregated_category.index(order['category'])
price = int(float(order['price']))
carbon_credit_needed = int(order['carbon_credit'])
number = int(order['number'])
sale_number = int(order['sale_number'])
identifications = aggregate_product_identification(order['identifications'])
carbon_emission = int(float(order['carbon_emission']))
donate_amount = int(float(order['donate_amount']))
if order['create_time'] is None:
create_time_processed = 2021
else:
create_time = datetime.datetime.strptime(order['create_time'], '%Y-%m-%d %H:%M:%S')
create_time_processed = 10000 * create_time.year + 100 * create_time.month
if order['modify_time'] is None:
modify_time_processed = 2021
else:
modify_time = datetime.datetime.strptime(order['modify_time'], '%Y-%m-%d %H:%M:%S')
modify_time_processed = 10000 * modify_time.year + 100 * modify_time.month
value.append(product_id)
value.append(farm_id)
value.append(product_name)
value.append(category)
value.append(price)
value.append(carbon_credit_needed)
value.append(number)
value.append(sale_number)
value.append(identifications)
value.append(carbon_emission)
value.append(donate_amount)
value.append(create_time_processed)
value.append(modify_time_processed)
values.append(value)
return values, product_ids
except:
return [], []
def recommend_top_three(sorted_product_score, username, order_list, all_products):
"""
recommend three products with highest prediction scores
if not enough products, recommend first three products
"""
count = 0
recommend_products = set()
for product in sorted_product_score:
recommend_products.add(product)
count += 1
if count == 3:
return recommend_products
product_ids = check_order_history_product(order_list, username)
for product in product_ids:
# check the history rent history
recommend_products.add(product)
current = 0
while len(recommend_products) < 3 and current < len(all_products):
recommend_products.add(all_products[current])
current = current + 1
return recommend_products
def check_order_history_product(order_list, username):
"""
check order history and returns products same as\
or similar to the given username ordered
"""
category_purchased = set()
product_ids = set()
for order in order_list:
if order['username'] == username:
category_purchased.add(order['category'])
for order in order_list:
if order['category'] in category_purchased:
product_id = order['product_id']
product_ids.add(product_id)
return product_ids
def fill_answer_product(recommend_products, result):
"""
fill the return json with recommended product ids
"""
for farm in recommend_products:
result.append({'product_id': farm, 'description': 'recommended product'})
return result
def cal_period(period):
"""
calculate period(month)
"""
begin_end = period.split('-')
begin = begin_end[0].split('/')
end = begin_end[1].split('/')
begin_month = begin[1]
begin_year = begin[2]
end_month = end[1]
end_year = end[2]
result = int(end_year) * 12 + int(end_month) - int(begin_year) * 12 - int(begin_month)
return result
def normalization(value, maxvalue, minvalue):
"""
normalization method
"""
value = (value - minvalue) / (maxvalue - minvalue)
return value
@app.route("/recommend-farm", methods=['POST'])
def recommend_farm():
"""
recommend_farm
"""
# default result
return_dict = {'rescode': '200', 'recommend_farm_list': []}
# check if the input is none
if request.get_data() is None:
return_dict['rescode'] = '5004'
return json.dumps(return_dict, ensure_ascii=False)
get_data = request.get_data()
get_data = json.loads(get_data)
username = get_data.get('username')
rent_list = get_data.get('rent_list')
values, all_farms = combine_data(get_data)
if len(values) == 0:
result_farm = []
recommend_farms = ['1', '2', '3']
result_farm = fill_answer(recommend_farms, result_farm)
return_dict['recommend_farm_list'] = result_farm
return json.dumps(return_dict, ensure_ascii=False)
result = []
api_key = "YOUR_API_KEY"
token_response = requests.post('https://iam.cloud.ibm.com/identity/token',
data={"apikey": api_key, "grant_type": 'urn:ibm:params:oauth:grant-type:apikey'})
ml_token = token_response.json()["access_token"]
payload_scoring = {"input_data": [
{"fields": ["community_id", "location", "carbon_credit", "carbon_medals", "comment_products",
"farm_location", "suited_product", "rent_period", "total_area", "idle_area"],
"values": values}
]}
# You could obtain the url after model deployed on IBM Cloud platform.
response_scoring = requests.post(
'https://us-south.ml.cloud.ibm.com/ml/v4/deployments/XXXXX',
json=payload_scoring, headers={'Authorization': 'Bearer ' + ml_token})
prediction_score = make_predictions(response_scoring, all_farms)
recommend_farms = recommend_top_three_farms(prediction_score, username, rent_list, all_farms)
result = fill_answer(recommend_farms, result)
return_dict['recommend_farm_list'] = result
return json.dumps(return_dict, ensure_ascii=False)
@app.route("/recommend-product", methods=['POST'])
def recommend_product():
"""
recommend_product
"""
# default result
return_dict = {'rescode': '200', 'recommend_product_list': []}
# check if the input is none
if request.get_data() is None:
return_dict['rescode'] = '5004'
return json.dumps(return_dict, ensure_ascii=False)
get_data = request.get_data()
get_data = json.loads(get_data)
username = get_data.get('username')
order_list = get_data.get('order_list')
values, all_products = combine_product_data(get_data)
if len(values) == 0:
result_products = []
recommend_products = ['1', '2', '3']
result_products = fill_answer_product(recommend_products, result_products)
return_dict['recommend_product_list'] = result_products
return json.dumps(return_dict, ensure_ascii=False)
result = []
api_key = "YOUR_API_KEY"
token_response = requests.post('https://iam.cloud.ibm.com/identity/token',
data={"apikey": api_key, "grant_type": 'urn:ibm:params:oauth:grant-type:apikey'})
ml_token = token_response.json()["access_token"]
payload_scoring = {"input_data": [
{"fields": ["community_id", "location", "carbon_credit", "carbon_medals", "comment_products",
"product_id", "farm_id", "plantername", "product_name", "category", "price", "carbon_credit_needed",
"number", "sale_number", "identifications", "carbon_emission", "donate_amount", "create_time",
"modify_time"],
"values": values}
]}
# You could obtain the url after model deployed on IBM Cloud platform.
response_scoring = requests.post(
'https://us-south.ml.cloud.ibm.com/ml/v4/deployments/XXXXX',
json=payload_scoring, headers={'Authorization': 'Bearer ' + ml_token})
prediction_score = make_predictions(response_scoring, all_products)
recommend_products = recommend_top_three(prediction_score, username, order_list, all_products)
result = fill_answer_product(recommend_products, result)
return_dict['recommend_product_list'] = result
return json.dumps(return_dict, ensure_ascii=False)
@app.route("/recommend-financial-product", methods=['POST'])
def recommend_financial_product():
"""
recommend_financial_product http api
"""
return_dict = {'rescode': '200', 'finance_product_list': []}
if request.get_data() is None:
return_dict['rescode'] = '5004'
return json.dumps(return_dict, ensure_ascii=False)
role_dict = {'farmer': 1, 'consumer': 2}
sex_dict = {'male': 1, 'female': 2}
location_dict = {'Cantwell city, Alaska, USA': 1, 'Queens, New York, NY, USA': 2}
org_dict = {'Agriculture Bank of China': 1, 'CHASE Bank': 2, 'PICC': 3}
get_data = request.get_data()
get_data = json.loads(get_data)
role_name = get_data.get('rolename')
sex = get_data.get('sex')
location = get_data.get('location')
carbon_credit = get_data.get('carbon_credit')
finance_products = get_data.get('finance_products')
user_info_array = [sex_dict.get(sex), role_dict.get(role_name),
location_dict.get(location), int(carbon_credit)]
res_df = pd.DataFrame(columns=('finance_product_id', 'value'))
product_id_list = []
value_list = []
for finance_product in finance_products:
temp_list = []
limit = finance_product.get('finance_limit').lstrip('$')
period = finance_product.get('valid_period')
product_id = finance_product.get('finance_product_id')
product_id_list.append(product_id)
org = finance_product.get('org_name')
temp_list.append(sex_dict.get(sex))
temp_list.append(role_dict.get(role_name))
temp_list.append(location_dict.get(location))
temp_list.append(int(carbon_credit))
temp_list.append(int(float(limit)))
temp_list.append(cal_period(period))
temp_list.append(org_dict.get(org))
value_list.append(temp_list)
response_str = finance_product_recommend_api(value_list)
response_str = json.loads(response_str.text)
predictions = response_str.get('predictions')
values = predictions[0].get('values')
for i in range(0, len(product_id_list)):
value = values[i][0]
res_df | |
"""
Chi-squared and related functions
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
import numpy as _np
from pygsti.tools.legacytools import deprecate as _deprecated_fn
def chi2(model, dataset, circuits=None,
min_prob_clip_for_weighting=1e-4, prob_clip_interval=(-10000, 10000),
op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None):
"""
Computes the total (aggregate) chi^2 for a set of circuits.
The chi^2 test statistic obtained by summing up the
contributions of a given set of circuits or all
the circuits available in a dataset. For the gradient or
Hessian, see the :function:`chi2_jacobian` and
:function:`chi2_hessian` functions.
Parameters
----------
model : Model
The model used to specify the probabilities and SPAM labels
dataset : DataSet
The data used to specify frequencies and counts
circuits : list of Circuits or tuples, optional
List of circuits whose terms will be included in chi^2 sum.
Default value (None) means "all strings in dataset".
min_prob_clip_for_weighting : float, optional
defines the clipping interval for the statistical weight.
prob_clip_interval : tuple, optional
A `(min, max)` tuple that specifies the minium (possibly negative) and maximum values
allowed for probabilities generated by the model. If the model gives probabilities
outside this range they are clipped to `min` or `max`. These values can be quite
generous, as the optimizers are quite tolerant of badly behaved probabilities.
op_label_aliases : dictionary, optional
Dictionary whose keys are operation label "aliases" and whose values are tuples
corresponding to what that operation label should be expanded into before querying
the dataset. Defaults to the empty dictionary (no aliases defined)
e.g. op_label_aliases['Gx^3'] = ('Gx','Gx','Gx')
mdc_store : ModelDatasetCircuitsStore, optional
An object that bundles cached quantities along with a given model, dataset, and circuit
list. If given, `model` and `dataset` and `circuits` should be set to None.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
mem_limit : int, optional
A rough memory limit in bytes which restricts the amount of intermediate
values that are computed and stored.
Returns
-------
chi2 : float
chi^2 value, equal to the sum of chi^2 terms from all specified circuits
"""
from ..objectivefns import objectivefns as _objfns
return _objfns._objfn(_objfns.Chi2Function, model, dataset, circuits,
{'min_prob_clip_for_weighting': min_prob_clip_for_weighting},
{'prob_clip_interval': prob_clip_interval},
op_label_aliases, comm, mem_limit, ('fn',), (), mdc_store).fn() # gathers internally
def chi2_per_circuit(model, dataset, circuits=None,
min_prob_clip_for_weighting=1e-4, prob_clip_interval=(-10000, 10000),
op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None):
"""
Computes the per-circuit chi^2 contributions for a set of cirucits.
This function returns the same value as :func:`chi2` except the
contributions from different circuits are not summed but
returned as an array (the contributions of all the outcomes of a
given cirucit *are* summed together).
Parameters
----------
model : Model
The model used to specify the probabilities and SPAM labels
dataset : DataSet
The data used to specify frequencies and counts
circuits : list of Circuits or tuples, optional
List of circuits whose terms will be included in chi^2 sum.
Default value (None) means "all strings in dataset".
min_prob_clip_for_weighting : float, optional
defines the clipping interval for the statistical weight.
prob_clip_interval : tuple, optional
A `(min, max)` tuple that specifies the minium (possibly negative) and maximum values
allowed for probabilities generated by the model. If the model gives probabilities
outside this range they are clipped to `min` or `max`. These values can be quite
generous, as the optimizers are quite tolerant of badly behaved probabilities.
op_label_aliases : dictionary, optional
Dictionary whose keys are operation label "aliases" and whose values are tuples
corresponding to what that operation label should be expanded into before querying
the dataset. Defaults to the empty dictionary (no aliases defined)
e.g. op_label_aliases['Gx^3'] = ('Gx','Gx','Gx')
mdc_store : ModelDatasetCircuitsStore, optional
An object that bundles cached quantities along with a given model, dataset, and circuit
list. If given, `model` and `dataset` and `circuits` should be set to None.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
mem_limit : int, optional
A rough memory limit in bytes which restricts the amount of intermediate
values that are computed and stored.
Returns
-------
chi2 : numpy.ndarray
Array of length either `len(circuits)` or `len(dataset.keys())`.
Values are the chi2 contributions of the corresponding circuit
aggregated over outcomes.
"""
from ..objectivefns import objectivefns as _objfns
obj = _objfns._objfn(_objfns.Chi2Function, model, dataset, circuits,
{'min_prob_clip_for_weighting': min_prob_clip_for_weighting},
{'prob_clip_interval': prob_clip_interval},
op_label_aliases, comm, mem_limit, ('percircuit',), (), mdc_store)
return obj.layout.allgather_local_array('c', obj.percircuit())
def chi2_jacobian(model, dataset, circuits=None,
min_prob_clip_for_weighting=1e-4, prob_clip_interval=(-10000, 10000),
op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None):
"""
Compute the gradient of the chi^2 function computed by :function:`chi2`.
The returned value holds the derivatives of the chi^2 function with
respect to `model`'s parameters.
Parameters
----------
model : Model
The model used to specify the probabilities and SPAM labels
dataset : DataSet
The data used to specify frequencies and counts
circuits : list of Circuits or tuples, optional
List of circuits whose terms will be included in chi^2 sum.
Default value (None) means "all strings in dataset".
min_prob_clip_for_weighting : float, optional
defines the clipping interval for the statistical weight.
prob_clip_interval : tuple, optional
A `(min, max)` tuple that specifies the minium (possibly negative) and maximum values
allowed for probabilities generated by the model. If the model gives probabilities
outside this range they are clipped to `min` or `max`. These values can be quite
generous, as the optimizers are quite tolerant of badly behaved probabilities.
op_label_aliases : dictionary, optional
Dictionary whose keys are operation label "aliases" and whose values are tuples
corresponding to what that operation label should be expanded into before querying
the dataset. Defaults to the empty dictionary (no aliases defined)
e.g. op_label_aliases['Gx^3'] = ('Gx','Gx','Gx')
mdc_store : ModelDatasetCircuitsStore, optional
An object that bundles cached quantities along with a given model, dataset, and circuit
list. If given, `model` and `dataset` and `circuits` should be set to None.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
mem_limit : int, optional
A rough memory limit in bytes which restricts the amount of intermediate
values that are computed and stored.
Returns
-------
numpy array
The gradient vector of length `model.num_params`, the number of model parameters.
"""
from ..objectivefns import objectivefns as _objfns
obj = _objfns._objfn(_objfns.Chi2Function, model, dataset, circuits,
{'min_prob_clip_for_weighting': min_prob_clip_for_weighting},
{'prob_clip_interval': prob_clip_interval},
op_label_aliases, comm, mem_limit, ('jacobian',), (), mdc_store)
return obj.layout.allgather_local_array('ep', obj.jacobian())
def chi2_hessian(model, dataset, circuits=None,
min_prob_clip_for_weighting=1e-4, prob_clip_interval=(-10000, 10000),
op_label_aliases=None, mdc_store=None, comm=None, mem_limit=None):
"""
Compute the Hessian matrix of the :func:`chi2` function.
Parameters
----------
model : Model
The model used to specify the probabilities and SPAM labels
dataset : DataSet
The data used to specify frequencies and counts
circuits : list of Circuits or tuples, optional
List of circuits whose terms will be included in chi^2 sum.
Default value (None) means "all strings in dataset".
min_prob_clip_for_weighting : float, optional
defines the clipping interval for the statistical weight.
prob_clip_interval : tuple, optional
A `(min, max)` tuple that specifies the minium (possibly negative) and maximum values
allowed for probabilities generated by the model. If the model gives probabilities
outside this range they are clipped to `min` or `max`. These values can be quite
generous, as the optimizers are quite tolerant of badly behaved probabilities.
op_label_aliases : dictionary, optional
Dictionary whose keys are operation label "aliases" and whose values are tuples
corresponding to what that operation label should be expanded into before querying
the dataset. Defaults to the empty dictionary (no aliases defined)
e.g. op_label_aliases['Gx^3'] = ('Gx','Gx','Gx')
mdc_store : ModelDatasetCircuitsStore, optional
An object that bundles cached quantities along with a given model, dataset, and circuit
list. If given, `model` and `dataset` and `circuits` should be set to None.
comm : mpi4py.MPI.Comm, optional
When not None, an | |
<filename>empirical_lsm/plots.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
File: plots.py
Author: <NAME>
Email: <EMAIL>
Github: https://github.com/naught101/empirical_lsm
Description: diagnostic plots for evaluating models
"""
import matplotlib as mpl
import matplotlib.pyplot as pl
import seaborn as sns
import pandas as pd
import os
import numpy as np
import xarray as xr
from dateutil.parser import parse
from pals_utils.data import pals_site_name, pals_xr_to_df
from .utils import print_warn
from .evaluate import get_PLUMBER_metrics, subset_metric_df, quantile_normalise
def empirical_lsm_palette(name="Final ensemble"):
if name == "Final ensemble":
colours = ['hotpink', 'red', 'orange', 'gold',
'lightseagreen', 'cornflowerblue', 'mediumblue',
'darkblue', 'black']
palette = color_names_to_palette(colours)
sns.set_palette(palette)
return palette
def color_names_to_palette(colours):
hex_cols = [mpl.colors.cnames[c] for c in colours]
palette = [mpl.colors.hex2color(c) for c in hex_cols]
# mpl.colors.rgb_to_hsv()
return palette
def save_figure(path, fig=None):
if fig is None:
fig = pl.gcf()
dir_path = os.path.dirname(path)
os.makedirs(dir_path, exist_ok=True)
fig.savefig(path)
print('Figure saved to ' + os.path.abspath(path))
pl.close(fig)
def save_plot(base_path, rel_path, filename):
"""Save a figure and return the relative path (for rst)
:base_path: path to directory with final RST
:rel_path: relative path to figure directory
:filename: plot filename
:returns: rel_path/filename.png for RST
"""
dir_path = os.path.join(base_path, rel_path)
os.makedirs(dir_path, exist_ok=True)
plot_path = os.path.join(dir_path, filename)
pl.savefig(plot_path)
pl.close()
return os.path.join(rel_path, filename)
def get_benchmark(name, site):
"""returns an xarray dataset
:name: mode name
:site: fluxnet site name
:returns: xarray dataset
"""
file_path = 'model_data/{name}/{name}_{site}.nc'
benchmark = xr.open_dataset(file_path.format(name=name, site=site))
return benchmark
def diagnostic_plots(sim_data, flux_data, name):
"""Plot standard diagnostic plots for a single site
:sim_data: xarray dataset
:flux_data: xarray dataset
:name: mode name
:returns: list of paths to plots
"""
site = pals_site_name(flux_data)
print('Running standard plots for %s at %s' % (name, site))
base_path = 'source/models/{n}'.format(n=name)
rel_path = 'figures/{s}'.format(s=site)
fig_path = os.path.join(base_path, rel_path)
os.makedirs(fig_path, exist_ok=True)
files = []
# benchmark_names = ['1lin', '2lin', '3km27']
benchmark_names = ['S_lin', 'ST_lin', 'STH_km27']
try:
benchmarks = [get_benchmark(bname, site) for bname in benchmark_names]
except RuntimeError as e:
print_warn("Benchmark(s) not available at {s}, skipping. {e}".format(s=site, e=e))
return
sns.set_palette(sns.color_palette(['red', 'pink', 'orange', 'black', 'blue']))
# Generalise if more multi-variable plots needed
metric_df = get_PLUMBER_metrics(name, site)
for plot in [p_plumber_metrics, p_metric_rank_counts]:
filename = plot(metric_df, name, site)
rel_plot_path = save_plot(base_path, rel_path, filename)
files.append(rel_plot_path)
flux_vars = ['Qle', 'Qh', 'NEE']
for var in flux_vars:
try:
data = pd.concat([pals_xr_to_df(ds, [var]) for ds in
benchmarks + [flux_data, sim_data]], axis=1)
except Exception as e:
print_warn('Data missing for {v} at {s}, skipping. {e}'.format(v=var, s=site, e=e))
continue
data.columns = benchmark_names + ['observed', 'modelled']
for plot in DIAGNOSTIC_PLOTS.values():
filename = plot(data, name, var, site)
rel_plot_path = save_plot(base_path, rel_path, filename)
files.append(rel_plot_path)
return files
def plot_weekly_timeseries(data, name, var, site):
data.resample('1W').mean().plot()
pl.title('{n}: Weekly average {v} at {s}'.format(n=name, v=var, s=site))
filename = '{n}_{v}_{s}_weekly_timeseries.png'.format(n=name, v=var, s=site)
return filename
def plot_scatter(data, name, var, site):
data.plot.scatter('observed', 'modelled', c='black', s=1, alpha=0.5)
pl.title('{n}: Scatterplot of {v} at {s}'.format(n=name, v=var, s=site))
filename = '{n}_{v}_{s}_scatterplot.png'.format(n=name, v=var, s=site)
return filename
def plot_annual_cycle(data, name, var, site):
data.groupby(data.index.month).mean().plot()
pl.title('{n}: Annual average {v} cycle at {s}'.format(n=name, v=var, s=site))
filename = '{n}_{v}_{s}_annual_cycle.png'.format(n=name, v=var, s=site)
return filename
def plot_daily_cycle(data, name, var, site):
data.groupby(data.index.time).mean().plot()
pl.title('{n}: daily average {v} cycle at {s}'.format(n=name, v=var, s=site))
filename = '{n}_{v}_{s}_daily_cycle.png'.format(n=name, v=var, s=site)
return filename
def plot_qq_plot(data, name, var, site):
"""qqplot!
"""
data.apply(sorted).plot.scatter('observed', 'modelled', c='black', s=1, alpha=0.5)
pl.title('{n}: Quantile-quantile plot for {v} at {s}'.format(n=name, v=var, s=site))
filename = '{n}_{v}_{s}_qq_plot.png'.format(n=name, v=var, s=site)
return filename
def plot_residuals(data, name, var, site):
"""Residual errors plot
"""
residuals = data[['observed']].copy()
residuals['residuals'] = data['modelled'] - data['observed']
residuals.plot.scatter('observed', 'residuals', c='black', s=1, alpha=0.5)
pl.title('{n}: residual plot for {v} at {s}'.format(n=name, v=var, s=site))
filename = '{n}_{v}_{s}_residual_plot.png'.format(n=name, v=var, s=site)
return filename
DIAGNOSTIC_PLOTS = {
"source/models/{n}/figures/{s}/{n}_{v}_{s}_annual_cycle.png": plot_annual_cycle,
"source/models/{n}/figures/{s}/{n}_{v}_{s}_daily_cycle.png": plot_daily_cycle,
"source/models/{n}/figures/{s}/{n}_{v}_{s}_qq_plot.png": plot_qq_plot,
"source/models/{n}/figures/{s}/{n}_{v}_{s}_residual_plot.png": plot_residuals,
"source/models/{n}/figures/{s}/{n}_{v}_{s}_scatterplot.png": plot_scatter,
"source/models/{n}/figures/{s}/{n}_{v}_{s}_weekly_timeseries.png": plot_weekly_timeseries,
}
#######################
# metric plots
#######################
def get_PLUMBER_plot(model_dir, site='all'):
"""generate PLUMBER plot and get filename
:name: model name
"""
name = model_dir.replace('source/models/', '')
sns.set_palette(sns.color_palette(['red', 'pink', 'orange', 'black', 'blue']))
metric_df = get_PLUMBER_metrics(name, site)
for metrics in ['all', 'standard', 'distribution']:
filename = p_plumber_metrics(metric_df, name, site, metrics)
save_plot('source/models', name + '/figures', filename)
filename = p_metric_rank_counts(metric_df, name, site, metrics)
save_plot('source/models', name + '/figures', filename)
def plot_PLUMBER_sim_metrics(name, site, metrics='all'):
"""Plot metrics from a site, with benchmarks for comparison
:name: model name
:site: fluxnet site name
:returns: path to plotted file
"""
metric_df = get_PLUMBER_metrics(name, site)
filename = p_plumber_metrics(metric_df, name, site, metrics)
return filename
def p_plumber_metrics(metric_df, name, site='all', metrics='all'):
"""Plot metric results as averages over site and metric
:metric_df: pandas dataframe of results
:name: site name for title
:metrics: metrics to include: 'all', 'standard', 'distribution'
:returns: plotted filename
"""
models = ['S_lin', 'ST_lin', 'STH_km27', name]
metric_df = subset_metric_df(metric_df, metrics)
n_sites = len(metric_df.site.unique())
mean_df = metric_df.groupby(['variable', 'name'])['rank'].mean().reset_index()
mean_df_wide = mean_df.pivot(index='variable', columns='name', values='rank')
ax = mean_df_wide[models].plot()
ax.set_ylim([1.5, len(models) - 0.5])
site_name = "{n} sites".format(n=n_sites) if (site == "all") else site
pl.title('{n}: PLUMBER plot: {m} metrics at {s}'.format(n=name, s=site_name, m=metrics))
filename = '{n}_{s}_PLUMBER_plot_{m}_metrics.png'.format(n=name, s=site, m=metrics)
return filename
def p_metric_rank_counts(metric_df, name, site='all', metrics='all'):
"""plots hostograms of ranks for each variable and model
"""
models = ['S_lin', 'ST_lin', 'STH_km27']
if name not in models:
models.append(name)
metric_df = subset_metric_df(metric_df, metrics)
n_sites = len(metric_df.site.unique())
metric_df['name'] = pd.Categorical(metric_df['name'], models)
metric_df.sort_values('name', inplace=True)
count_df = (metric_df[['rank', 'name', 'variable', 'value']]
.groupby(['rank', 'variable', 'name'])
.agg('count')
.fillna(0)
.reset_index()
.rename(columns={'value': 'count'}))
g = sns.factorplot(y="rank", x="count", col="variable", hue="name", data=count_df, orient='h', legen=False)
g.axes[0, 0].invert_yaxis()
g.fig.legend(loc='lower center', *g.axes[0, 0].get_legend_handles_labels(), ncol=10)
site_name = "{n} sites".format(n=n_sites) if (site == "all") else site
pl.suptitle('{n}: Rank counts: {m} metrics at {s}'.format(n=name, s=site_name, m=metrics))
filename = '{n}_{s}_rank_counts_{m}_metrics.png'.format(n=name, s=site, m=metrics)
return filename
def p_metric_normalised_violins(metric_df, name, site='all', metrics='all'):
"""plots violins of metrics normalised for each variable and model
"""
models = ['S_lin', 'ST_lin', 'STH_km27', name]
metric_df = subset_metric_df(metric_df, metrics)
n_sites = len(metric_df.site.unique())
metric_df['name'] = pd.Categorical(metric_df['name'], models)
metric_df.sort_values('name', inplace=True)
one_metrics = ['corr', 'overlap']
metric_df.ix[metric_df['metric'].isin(one_metrics), 'value'] = 1 - metric_df.ix[metric_df['metric'].isin(one_metrics), 'value']
metric_df['value'] = (metric_df
.groupby(['site', 'variable', 'metric'])['value']
.apply(lambda x: (x - x.min()) / (x.max() - x.min())))
fg = sns.factorplot(y="value", x="variable", hue="name", data=metric_df, orient='v', kind='violin', bw=0.1)
sns.factorplot(y="value", x="variable", hue="name", data=metric_df, orient='v', kind='point', ax=fg.ax, ci=None)
fg.ax.legend().set_visible(False)
site_name = "{n} sites".format(n=n_sites) if (site == "all") else site
pl.suptitle('{n}: Minmax normalised metrics: {m} metrics at {s}'.format(n=name, s=site_name, m=metrics))
filename = '{n}_{s}_minmax_normalised_{m}_metrics.png'.format(n=name, s=site, m=metrics)
return filename
PLUMBER_PLOTS = {
"source/models/{n}/figures/{n}_all_PLUMBER_plot_{m}_metrics.png": get_PLUMBER_plot,
"source/models/{n}/figures/{s}/{n}_{s}_PLUMBER_plot_{m}_metrics.png": plot_PLUMBER_sim_metrics,
}
# Drought workshop plots
def plot_drydown(sim_data, flux_data, met_data, name, date_range):
"""Plot behaviour during dry-downs.
Plots rainfall, as well as Qh and Qle for obs and simulations.
:sim_data: xarray dataset from a simulation
:flux_data: xarray dataset from a simulation
:met_data: xarray dataset from a simulation
:name: model name
:returns: plot filename
"""
year_range = [parse(d).year for d in date_range]
year_range[1] += 1
year_range = ['%s-01-01' % d for d in year_range]
site = pals_site_name(met_data)
sns.set_palette(sns.color_palette(['#aa0000', '#ff4444', '#0000aa', '#4477ff']))
# Plot rainfall in mm
Rainf = (pals_xr_to_df(met_data.sel(time=slice(*year_range)), ['Rainf'])
.resample('1W', how='sum') * 1000).mean()
obs = (pals_xr_to_df(flux_data.sel(time=slice(*year_range)), ['Qh', 'Qle'])
.resample('1D')).mean()
sim = (pals_xr_to_df(sim_data.sel(time=slice(*year_range)), ['Qh', 'Qle'])
.resample('1D')).mean()
x_vals = Rainf.index.to_pydatetime()
fig, ax = pl.subplots()
ax.bar(x_vals, Rainf.values, width=7, color='lightblue', linewidth=0)
x_vals = obs.index.to_pydatetime()
for c in obs:
if c == 'Qle':
offset = 0
if c == 'Qh':
offset = 100
ax.plot(x_vals, pd.rolling_mean(obs[c], 14) + offset, label='Obs %s + %d' % (c, offset))
ax.plot(x_vals, pd.rolling_mean(sim[c], 14) + offset, label='Sim %s + %d' % (c, offset))
ax.axvspan(parse(date_range[0]), parse(date_range[1]), color='black', alpha=0.1, zorder=-100)
pl.legend(loc=0)
pl.title('{n}: drydown plot at {s}'.format(n=name, s=site))
filename = '{n}_{s}_drydown_timeseries_plot.png'.format(n=name, s=site)
return filename
def plot_drydown_daily_cycles(sim_data, flux_data, met_data, name, date_range):
"""Plot daily cycle behaviour during dry-downs.
Plots rainfall, as well as Qh and Qle for obs and simulations.
:sim_data: xarray dataset from a simulation
:flux_data: xarray dataset from a simulation
:met_data: xarray dataset from a simulation
:name: model name
:returns: plot filename
"""
d_range = [np.datetime64(parse(d)) for d in date_range]
del_t = np.timedelta64(7, 'D')
first_cycle = d_range[0] + [-del_t, del_t]
last_cycle = d_range[1] + [-del_t, del_t]
site = pals_site_name(met_data)
sns.set_palette(sns.color_palette(['#aa0000', '#ff4444', '#0000aa', '#4477ff']))
fig, _ = pl.subplots(2, 1, sharey=True)
periods = {0: 'start', 1: 'end'}
flux_vars = list(set(['Qh', 'Qle']).intersection(list(sim_data.data_vars))
.intersection(list(sim_data.data_vars)))
for i, dr in enumerate([first_cycle, last_cycle]):
obs_df = pals_xr_to_df(flux_data.sel(time=slice(*dr)), flux_vars)
obs = obs_df.groupby(obs_df.index.time).mean()
sim_df = pals_xr_to_df(sim_data.sel(time=slice(*dr)), flux_vars)
sim = sim_df.groupby(sim_df.index.time).mean()
x_vals = obs.index.values
ax = pl.subplot(2, 1, i + 1)
for c in obs:
if c == 'Qle':
offset = 0
if c == 'Qh':
offset = 100
ax.plot(x_vals, obs[c] + offset, label='Obs %s + %d' % (c, offset))
ax.plot(x_vals, sim[c] + offset, label='Sim %s + %d' % (c, offset))
pl.title('{n}: daily cycles for {p} of drydown at {s}'.format(n=name, s=site, p=periods[i]))
pl.legend(loc=0)
fig.tight_layout()
filename = '{n}_{s}_drydown_daily_cycles_plot.png'.format(n=name, s=site)
return filename
DRYDOWN_PLOTS = | |
import os.path
import random
import cv2
import numpy as np
import dito.io
####
#%%% resource filenames
####
RESOURCES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources")
RESOURCES_FILENAMES = {
# colormaps (self-defined)
"colormap:plot": os.path.join(RESOURCES_DIR, "colormaps", "plot.png"),
"colormap:plot2": os.path.join(RESOURCES_DIR, "colormaps", "plot2.png"),
# colorbrewer colormaps (note: this product includes color specifications and designs developed by Cynthia Brewer (http://colorbrewer.org/).)
"colormap:accent": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "accent.png"),
"colormap:blues": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "blues.png"),
"colormap:brbg": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "brbg.png"),
"colormap:bugn": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "bugn.png"),
"colormap:bupu": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "bupu.png"),
"colormap:dark2": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "dark2.png"),
"colormap:gnbu": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "gnbu.png"),
"colormap:greens": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "greens.png"),
"colormap:greys": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "greys.png"),
"colormap:orrd": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "orrd.png"),
"colormap:oranges": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "oranges.png"),
"colormap:prgn": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "prgn.png"),
"colormap:paired": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "paired.png"),
"colormap:pastel1": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "pastel1.png"),
"colormap:pastel2": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "pastel2.png"),
"colormap:piyg": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "piyg.png"),
"colormap:pubu": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "pubu.png"),
"colormap:pubugn": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "pubugn.png"),
"colormap:puor": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "puor.png"),
"colormap:purd": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "purd.png"),
"colormap:purples": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "purples.png"),
"colormap:rdbu": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "rdbu.png"),
"colormap:rdgy": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "rdgy.png"),
"colormap:rdpu": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "rdpu.png"),
"colormap:rdylbu": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "rdylbu.png"),
"colormap:rdylgn": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "rdylgn.png"),
"colormap:reds": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "reds.png"),
"colormap:set1": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "set1.png"),
"colormap:set2": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "set2.png"),
"colormap:set3": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "set3.png"),
"colormap:spectral": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "spectral.png"),
"colormap:ylgn": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "ylgn.png"),
"colormap:ylgnbu": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "ylgnbu.png"),
"colormap:ylorbr": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "ylorbr.png"),
"colormap:ylorrd": os.path.join(RESOURCES_DIR, "colormaps", "colorbrewer", "ylorrd.png"),
# fonts: Scientifica
"font:scientifica-12": os.path.join(RESOURCES_DIR, "fonts", "scientifica", "scientifica_df2.png"),
# font: Source Code Pro
"font:source-10": os.path.join(RESOURCES_DIR, "fonts", "source_code_pro", "10_df2.png"),
"font:source-15": os.path.join(RESOURCES_DIR, "fonts", "source_code_pro", "15_df2.png"),
"font:source-20": os.path.join(RESOURCES_DIR, "fonts", "source_code_pro", "20_df2.png"),
"font:source-25": os.path.join(RESOURCES_DIR, "fonts", "source_code_pro", "25_df2.png"),
"font:source-30": os.path.join(RESOURCES_DIR, "fonts", "source_code_pro", "30_df2.png"),
"font:source-35": os.path.join(RESOURCES_DIR, "fonts", "source_code_pro", "35_df2.png"),
"font:source-40": os.path.join(RESOURCES_DIR, "fonts", "source_code_pro", "40_df2.png"),
"font:source-50": os.path.join(RESOURCES_DIR, "fonts", "source_code_pro", "50_df2.png"),
"font:source-70": os.path.join(RESOURCES_DIR, "fonts", "source_code_pro", "70_df2.png"),
# font: Terminus
"font:terminus-12": os.path.join(RESOURCES_DIR, "fonts", "terminus", "ter-u12_df2.png"),
"font:terminus-14": os.path.join(RESOURCES_DIR, "fonts", "terminus", "ter-u14_df2.png"),
"font:terminus-16": os.path.join(RESOURCES_DIR, "fonts", "terminus", "ter-u16_df2.png"),
"font:terminus-18": os.path.join(RESOURCES_DIR, "fonts", "terminus", "ter-u18_df2.png"),
"font:terminus-20": os.path.join(RESOURCES_DIR, "fonts", "terminus", "ter-u20_df2.png"),
"font:terminus-22": os.path.join(RESOURCES_DIR, "fonts", "terminus", "ter-u22_df2.png"),
"font:terminus-24": os.path.join(RESOURCES_DIR, "fonts", "terminus", "ter-u24_df2.png"),
"font:terminus-28": os.path.join(RESOURCES_DIR, "fonts", "terminus", "ter-u28_df2.png"),
"font:terminus-32": os.path.join(RESOURCES_DIR, "fonts", "terminus", "ter-u32_df2.png"),
# test images
"image:PM5544": os.path.join(RESOURCES_DIR, "images", "PM5544.png"),
"image:USC-SIPI-4.1.07": os.path.join(RESOURCES_DIR, "images", "USC_SIPI_4.1.07.png"),
}
####
#%%% synthetic images
####
def constant_image(size=(512, 288), color=(0, 255, 0), dtype=np.uint8):
"""
Returns an image where each color channel is constant (but the channel
values may vary).
"""
channel_count = len(color)
image = np.zeros(shape=(size[1], size[0]) + (channel_count,), dtype=dtype)
for n_channel in range(channel_count):
image[:, :, n_channel] = color[n_channel]
if channel_count == 1:
image = image[:, :, 0]
return image
def grid(size=(512, 288), grid_size=16, background_color=(0,), grid_color=(255,), offset=None, dtype=np.uint8):
"""
Returns a gray-scale image of the given `size` containing a grid with a
pitch of size `block_size`.
"""
image = constant_image(size=size, color=background_color, dtype=dtype)
if offset is None:
offset = (0, 0)
else:
offset = dito.utils.get_validated_tuple(x=offset, type_=int, count=2, min_value=0)
for x in range(offset[0] % grid_size, size[0], grid_size):
image[:, x, ...] = grid_color
for y in range(offset[1] % grid_size, size[1], grid_size):
image[y, :, ...] = grid_color
return image
def checkerboard(size=(512, 288), block_size=16, low=0, high=255):
"""
Returns a gray-scale image of the given `size` containing a checkerboard
grid with squares of size `block_size`. The arguments `low` and `high`
specify the gray scale values to be used for the squares.
"""
image = np.zeros(shape=(size[1], size[0]), dtype=np.uint8) + low
for (n_row, y) in enumerate(range(0, size[1], block_size)):
offset = block_size if ((n_row % 2) == 0) else 0
for x in range(offset, size[0], 2 * block_size):
image[y:(y + block_size), x:(x + block_size)] = high
return image
def background_checkerboard(size=(512, 288), block_size=16):
"""
Returns a gray-scale image of the given `shape` containing a checkerboard
grid of light and dark gray squares of size `block_size`.
"""
return checkerboard(size=size, block_size=block_size, low=80, high=120)
def xslope(height=32, width=256, dtype=np.uint8):
"""
Return image containing values increasing from 0 to 255 along the x axis.
"""
dtype_range = dito.core.dtype_range(dtype=dtype)
slope = np.linspace(start=dtype_range[0], stop=dtype_range[1], num=width, endpoint=True, dtype=dtype)
slope.shape = (1,) + slope.shape
slope = np.repeat(a=slope, repeats=height, axis=0)
return slope
def yslope(width=32, height=256, dtype=np.uint8):
"""
Return image containing values increasing from 0 to 255 along the y axis.
"""
return xslope(height=width, width=height, dtype=dtype).T
def random_image(size=(512, 288), color=True, dtype=np.uint8, use_standard_library=False):
"""
Returns a random image of the given `size` and `dtype`.
"""
shape = tuple(size[::-1])
if color:
shape = shape + (3,)
if use_standard_library:
image_random = np.array([random.random() for _ in range(np.prod(shape))], dtype=np.float32).reshape(*shape)
else:
image_random = np.random.rand(*shape)
return dito.core.convert(image=image_random, dtype=dtype)
def test_image_segments():
image = np.zeros(shape=(288, 512), dtype=np.uint8)
sep = 8
count = 10
radii = [round(2**(2 + n_circle / 4)) for n_circle in range(count)]
color = (255,)
# draw series of circles
center_x = sep + max(radii)
center_y = sep
for radius in radii:
center_y += radius
cv2.circle(img=image, center=(center_x, center_y), radius=radius, color=color, thickness=cv2.FILLED, lineType=cv2.LINE_8)
center_y += radius + sep
# draw series of squares
center_x = 2 * sep + 3 * max(radii)
center_y = sep
for radius in radii:
center_y += radius
cv2.rectangle(img=image, pt1=dito.core.tir(center_x - radius, center_y - radius), pt2=dito.core.tir(center_x + radius, center_y + radius), color=color, thickness=cv2.FILLED, lineType=cv2.LINE_8)
center_y += radius + sep
# draw series of ellipses
center_x = 3 * sep + 6 * max(radii)
center_y = sep
for radius in radii:
center_y += radius
cv2.ellipse(img=image, center=(center_x, center_y), axes=(radius * 2, radius), angle=0.0, startAngle=0.0, endAngle=360.0, color=color, thickness=cv2.FILLED, lineType=cv2.LINE_8)
center_y += radius + sep
# draw series of rectangles
center_x = 4 * sep + 10 * max(radii)
center_y = sep
for radius in radii:
center_y += radius
cv2.rectangle(img=image, pt1=dito.core.tir(center_x - radius * 2, center_y - radius), pt2=dito.core.tir(center_x + radius * 2, center_y + radius), color=color, thickness=cv2.FILLED, lineType=cv2.LINE_8)
center_y += radius + sep
return image
class DitoTestImageGeneratorV1():
"""
Generates an image which is useful as a test input for processing functions.
It features:
* background color slope for absolute image position/crop assessment
* grid for assessment of deformations
* corner indicators for image flip/reflection assessment
* pixel ruler for length measurements
* crosshair for image center localization
* gray slopes for gamma measurements
* color areas for channel order assessment
* random color areas for assessment of random seed values of the `random` module and for NumPy.
* lines with different inclinations for rotation assessment
* letters/numbers for text appearance assessment
TODO:
* checkerboard patterns with different resolutions
* lines with different widths/separations for resolution measurements
* OpenCV checkerboard pattern for possible automated detection
* color wheel for color mapping assessment
"""
def __init__(self, size, dtype):
# settings
self.grid_size = 16
self.ruler_size = 16
self.line_color = (240, 240, 240)
# arguments
self.size = size
self.dtype = dtype
# checks
if min(self.size) < 2 * self.grid_size:
raise RuntimeError("Size '{}' is too small".format(self.size))
assert (self.dtype in (np.uint8, np.uint16)) or dito.core.is_float_dtype(dtype=self.dtype)
# derived properties
self.size_min = min(self.size)
self.image_center = (self.size[0] // 2, self.size[1] // 2)
self.dtype_range = dito.core.dtype_range(dtype=self.dtype)
(self.grid_offset, self.grid_inner_offset, self.grid_inner_count) = self.calculate_grid_parameters()
self.min_inner_count = min(self.grid_inner_count)
self.max_inner_count = max(self.grid_inner_count)
# image construction
self.image = self.generate_base_image()
if self.min_inner_count >= 2:
self.draw_corner_identifier_texts()
if self.min_inner_count >= 2:
self.draw_rulers()
if self.max_inner_count >= 4:
self.draw_center_crosshair()
if self.min_inner_count >= 4:
self.draw_gray_slopes()
if self.min_inner_count >= 6:
self.draw_color_areas()
if self.min_inner_count >= 8:
self.draw_rotation_indicators()
#self.draw_checkerboard_patterns()
def adapt_color_for_dtype(self, color):
"""
Map a uint8 color (range [0, 255]) to the correct range of the dtype of
this image.
"""
try:
len(color)
except TypeError:
# color is a scalar
return_scalar = True
color = (color,)
else:
# color is vector-like
return_scalar = False
if self.dtype == np.uint8:
pass
elif self.dtype == np.uint16:
color = tuple(value * 257 for value in color)
elif dito.core.is_float_dtype(dtype=self.dtype):
color = tuple(value / 255.0 for value in color)
else:
raise TypeError("Invalid dtype '{}'".format(self.dtype))
if return_scalar:
assert len(color) == 1
return color[0]
else:
return color
def calculate_grid_parameters(self):
grid_offset = [(self.size[n_dim] % (2 * self.grid_size)) // 2 for n_dim in range(2)]
grid_inner_offset = [grid_offset[n_dim] + self.grid_size if self.ruler_size > grid_offset[n_dim] else grid_offset[n_dim] for n_dim in range(2)]
grid_inner_count = [(self.size[n_dim] - 2 * grid_offset[n_dim]) // self.grid_size - 2 if self.ruler_size > grid_offset[n_dim] else (self.size[n_dim] - 2 * grid_offset[n_dim]) // self.grid_size for n_dim in range(2)]
return (grid_offset, grid_inner_offset, grid_inner_count)
def get_grid_coords(self, index_x, index_y):
# negative values wrap around from the end, just | |
re.sub("’", self.CSQ, common)
self.wb[i] = re.sub(r"({}){}({})".format(
self.OP, common, self.CP), r"\1{}\2".format(c2), self.wb[i])
for _, common in enumerate(commons_tail):
c2 = re.sub("’", self.CSQ, common)
self.wb[i] = re.sub(r"({}){}({})".format(
self.OP, common, self.CP), r"\1{}\2".format(c2), self.wb[i])
# leading capital tests
common = "{}{}".format(common[0].upper(), common[1:])
c2 = re.sub("’", self.CSQ, common)
self.wb[i] = re.sub(r"({}){}({})".format(
self.OP, common, self.CP), r"\1{}\2".format(c2), self.wb[i])
for _, common in enumerate(commons_both):
c2 = re.sub("’", self.CSQ, common)
self.wb[i] = re.sub(r"({}){}({})".format(
self.OP, common, self.CP), r"\1{}\2".format(c2), self.wb[i])
# leading capital tests
common = "{}{}{}".format(
common[0], common[1].upper(), common[2:])
c2 = re.sub("’", self.CSQ, common)
self.wb[i] = re.sub(r"({}){}({})".format(
self.OP, common, self.CP), r"\1{}\2".format(c2), self.wb[i])
# proper names
#
def proper_names(self):
nmap = {}
pnlist = []
# capitalized word that ends in an apostrophe
re0 = re.compile(r"{}([A-Z]\w+’){}".format(self.OP, self.CP))
for i, line in enumerate(self.wb):
hits = re0.finditer(line)
for _, t in enumerate(hits):
# keep track of how frequently the word+apost occurs
wd = t.group(1)
if wd not in self.wl and wd.lower() not in self.wl:
if wd in nmap:
nmap[wd] += 1
else:
nmap[wd] = 1
for z in nmap:
if nmap[z] >= 4:
pnlist.append(z)
for z in pnlist:
for i, line in enumerate(self.wb):
rz = re.sub("’", self.CSQ, z)
self.wb[i] = re.sub(z, rz, self.wb[i])
# logic here is to strip off the last two characters
# if what's left is a dictionary word, then conclude it is
# plural possessive
def plural_possessive(self):
re9 = re.compile(r"{}(\w+)s’{}".format(self.OP, self.CP))
for i, line in enumerate(self.wb):
hits = re9.finditer(line)
for _, hit in enumerate(hits):
if hit.group(1) in self.wl or hit.group(1).lower() in self.wl:
self.wb[i] = re.sub(hit.group(1)+"s’",
hit.group(1)+"s"+self.CSQ, self.wb[i])
# logic here is if it's a word with an opening and closing quote, then
# conclude that they are quotes.
def single_words(self):
re9 = re.compile(r"(‘\w+’)")
for i, line in enumerate(self.wb):
hits = re9.finditer(line)
for _, hit in enumerate(hits):
self.wb[i] = re.sub(hit.group(1), self.OSQ +
hit.group(1)[1:-1] + self.CSQ, self.wb[i])
# logic here is if it's two words with an opening and closing quote, then
# conclude that they are in single quotes.
# doesn't work if two words split over two lines, which generates a false positive
def double_words(self):
re9 = re.compile(r"(‘\w+\s\w+’)")
for i, line in enumerate(self.wb):
hits = re9.finditer(line)
for _, hit in enumerate(hits):
self.wb[i] = re.sub(hit.group(1), self.OSQ +
hit.group(1)[1:-1] + self.CSQ, self.wb[i])
def cont_quotes(self):
empty = re.compile("^$")
state = 0 # consider starting on a blank line
lqc = rqc = 0
for i, line in enumerate(self.wb):
if state == 0 and not empty.match(line):
# transition to non-blank line, i.e. first line of paragraph
state = 1
lqc = rqc = 0
lqc = line.count("“")
rqc = line.count("”")
continue
# another line in the paragraph
if state == 1 and not empty.match(line):
lqc += line.count("“")
rqc += line.count("”")
continue
if state == 1 and empty.match(line):
# transition from non-blank line to blank line
lqc += line.count("“")
rqc += line.count("”")
if lqc == rqc:
# leaving a balanced paragraph
# look to see it this is closing a continued quote
if len(self.tcqlocs) >= 2:
for _, j in enumerate(self.tcqlocs):
self.wb[j] += "”"
# save those to be removed at end
self.stcqlocs.append(j)
del self.tcqlocs[:] # temporary locs cleared
continue
if lqc == rqc + 1: # one more open than close double quote
self.tcqlocs.append(i-1)
state = 0
def undo_cont_quotes(self):
for _, loc in enumerate(self.stcqlocs):
where = self.wb[loc].rfind("”") # take back the one we put on
self.wb[loc] = self.wb[loc][:where] + self.wb[loc][where+1:]
def deobfuscate(self):
for i, _ in enumerate(self.wb):
self.wb[i] = re.sub(self.OSQ, "‘", self.wb[i])
self.wb[i] = re.sub(self.CSQ, "’", self.wb[i])
# the bizarre code in this is to handle consecutive -ing replacements
# without resorting to overlap=True in regex
def truncated_g(self):
gmap = {}
re9 = re.compile(r"{}(\w+?in)’{}".format(self.OP, self.CP))
for i, _ in enumerate(self.wb):
m = re9.search(self.wb[i])
while m:
hg1 = m.group(1)
testword = hg1 + 'g'
if testword.lower() in self.wl:
self.wb[i] = re.sub(hg1+'’', hg1+self.CSQ, self.wb[i], 1)
else:
# it isn't an -ing word but does it occur a lot?
if hg1 in gmap:
gmap[hg1] += 1
else:
gmap[hg1] = 1
# knock it out of the regex match
self.wb[i] = re.sub(hg1+'’', hg1+'\u274f', self.wb[i], 1)
m = re9.search(self.wb[i])
self.wb[i] = re.sub('\u274f', '’', self.wb[i])
# print(gmap)
# if a potential -ing word occurs 5 or more times, accept it.
for k in gmap.keys():
if gmap[k] >= 5:
# we have something like "figgerin" or "gittin"
# protect it (ouch)
for i, _ in enumerate(self.wb):
self.wb[i] = re.sub(k+"’", k+self.CSQ, self.wb[i])
return
# main scanning routine
def scan(self):
sk = Stack()
cg = Cget(self.wb)
ch = cg.getc()
while ch != -1: # EOF
if ch == '“': # open double quote
if sk.size() > 0 and sk.peek() == '“':
# consecutive open dq
self.rp.append(
"[CODQ] consec open double quote {}".format(cg.where()))
ch = cg.getc()
continue
sk.push(ch)
if ch == '”': # close double quote
if sk.size() > 0 and sk.peek() == '“':
sk.pop() # normal behavior
else:
# close double quote without matching open quote
self.rp.append(
"[UCDQ] unbalanced close double quote {}".format(cg.where()))
ch = cg.getc()
continue
if ch == '‘': # open single quote
if sk.size() > 0 and sk.peek() == '‘':
# consecutive open sq
self.rp.append(
"[COSQ] consec open single quote {}".format(cg.where()))
ch = cg.getc()
continue
sk.push(ch)
if ch == '’': # close single quote
if sk.size() > 0 and sk.peek() == '‘':
sk.pop() # normal behavior
else:
# close single quote without matching open quote
self.rp.append(
"[UCSQ] unbalanced close single quote {}".format(cg.where()))
ch = cg.getc()
continue
if ch == '[': # open brace
if sk.size() > 0 and sk.peek == '[':
self.rp.append(
"[COPB] consecutive open brace {}".format(cg.where()))
ch = cg.getc()
continue
sk.push(ch)
if ch == ']': # close brace
if sk.size() > 0 and sk.peek() == '[':
sk.pop() # the correct closing brace
else:
self.rp.append(
"[CCLB] consecutive closing brace {}".format(cg.where()))
ch = cg.getc()
continue
if ch == '(': # open parenthesis
if sk.size() > 0 and sk.peek() == '(':
self.rp.append(
"[COPN] consecutive open parenthesis {}".format(cg.where()))
ch = cg.getc()
continue
sk.push(ch)
if ch == ')': # close parenthesis
if sk.size() > 0 and sk.peek() == '(':
sk.pop()
else:
self.rp.append(
"[CCPN] consecutive closing parenthesis {}".format(cg.where()))
ch = cg.getc()
continue
# we are at the end of a paragraph
# the stack should be empty
# originally allowed for continued quotes but that can hide an unclosed
# first speaker quote. retrieve that code with commit "master 470ce18"
if ch == '\n':
if sk.size() > 0:
ln, cp = cg.where()
ln -= 2
cp = len(self.wb[ln])
w2 = (ln, cp)
self.rp.append(
"[UNCP] unclosed punctuation {} {}".format(sk.show(), w2))
while sk.size() > 0:
sk.pop()
ch = cg.getc()
# here we have recorded all potential errors in list "rp"
# now populate the working buffer
rpr = list(reversed(self.rp))
for _, item in enumerate(rpr):
m = re.search(r"^\[(....)\] (.*?) \((\d+), (\d+)\)", item)
if m:
ac = m.group(1)
tl = int(m.group(3)) # the line
tp = int(m.group(4)) # the position on the line
if self.desc:
self.wb[tl] = self.wb[tl][:tp] + \
'[@{}]'.format(ac) + self.wb[tl][tp:]
else:
self.wb[tl] = self.wb[tl][:tp] + '@' + self.wb[tl][tp:]
return
# save wb to self.outfile
def saveFile(self):
empty = re.compile("^$")
while empty.match(self.wb[-1]):
del self.wb[-1]
f1 = open(self.outfile, "w", encoding=self.encoding)
if self.encoding == "UTF-8":
f1.write('\ufeff') # BOM mark
f1.write("PP Workbench report generated by ppscan (version {})\r\n".format(self.VERSION))
f1.write("source file: {}\r\n".format(os.path.basename(self.srcfile)))
f1.write("using wordlist: {}\r\n".format(self.wfile))
if self.bothsq:
f1.write("WARNING: both straight and curly quotes found in text\r\n")
f1.write("-"*80+"\r\n")
for t in self.wb:
f1.write("{:s}\r\n".format(t)) # use CR/LF
# printout of errors
if self.verbose:
f1.write("-"*80+"\r\n")
f1.write("\r\nerror details:\r\n")
f1.write(" line cp description\r\n")
for _, item in enumerate(self.rp):
m = re.search(r"^\[(....)\] (.*?)\((\d+), (\d+)\)", item)
if m:
# mnemonic = m.group(1)
msg = m.group(2)
line = int(m.group(3))+1
cpos = int(m.group(4))
f1.write(" {:5d} {:3d} {:s}\r\n".format(line, cpos, msg))
f1.write("-"*80+"\r\n")
f1.write("\r\nmnemonic description within [@....] markup:\r\n")
f1.write(" CODQ: consec open double quote\r\n")
f1.write(" UCDQ: unbalanced close double quote\r\n")
f1.write(" COSQ: consec open single quote\r\n")
f1.write(" UCSQ: unbalanced close double quote\r\n")
f1.write(" COPB: consecutive open brace\r\n")
f1.write(" CCLB: consecutive closing brace\r\n")
f1.write(" | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from pandagg._decorators import Substitution
from pandagg.node.query._parameter_clause import ParentParameterClause
from pandagg.node.query.abstract import QueryClause, LeafQueryClause, Q
from pandagg.node.query.compound import CompoundClause, Bool
from pandagg.node.query.joining import Nested
from pandagg.tree._tree import Tree
from pandagg.tree.mappings import _mappings
ADD = "add"
REPLACE = "replace"
REPLACE_ALL = "replace_all"
sub_insertion = Substitution(
location_kwargs="""
* *insert_below* (``str``) --
named query clause under which the inserted clauses should be placed.
* *compound_param* (``str``) --
param under which inserted clause will be placed in compound query
* *on* (``str``) --
named compound query clause on which the inserted compound clause should be merged.
* *mode* (``str`` one of 'add', 'replace', 'replace_all') --
merging strategy when inserting clauses on a existing compound clause.
- 'add' (default) : adds new clauses keeping initial ones
- 'replace' : for each parameter (for instance in 'bool' case : 'filter', 'must', 'must_not', 'should'),
replace existing clauses under this parameter, by new ones only if declared in inserted compound query
- 'replace_all' : existing compound clause is completely replaced by the new one
"""
)
class Query(Tree):
node_class = QueryClause
def __init__(self, q=None, mappings=None, nested_autocorrect=False):
"""
Combination of query clauses.
Mappings declaration is optional, but doing so validates query consistency.
:param q: optional, query (dict, or Query instance)
:param mappings: ``dict`` or ``pandagg.tree.mappings.Mappings``
Mappings of requested indice(s). Providing it will add validation features.
:param nested_autocorrect: add required nested clauses if missing. Ignored if mappings is not provided.
"""
self.mappings = _mappings(mappings)
self.nested_autocorrect = nested_autocorrect
super(Query, self).__init__()
if q:
self._insert_query(q)
@sub_insertion
def query(
self,
type_or_query,
insert_below=None,
on=None,
mode=ADD,
compound_param=None,
**body
):
r"""
Insert provided clause in copy of initial Query.
>>> from pandagg.query import Query
>>> Query().query('term', some_field=23)
{'term': {'some_field': 23}}
>>> from pandagg.query import Term
>>> Query()\
>>> .query({'term': {'some_field': 23})\
>>> .query(Term(other_field=24))\
{'bool': {'must': [{'term': {'some_field': 23}}, {'term': {'other_field': 24}}]}}
:Keyword Arguments:
%(location_kwargs)s
"""
q = self.clone(with_nodes=True)
node = self._q(type_or_query, **body)
q._insert_query_at(
node,
mode=mode,
on=on,
insert_below=insert_below,
compound_param=compound_param,
)
return q
@sub_insertion
def must(
self,
type_or_query,
insert_below=None,
on=None,
mode=ADD,
bool_body=None,
**body
):
r"""
Create copy of initial Query and insert provided clause under "bool" query "must".
>>> Query().must('term', some_field=1)
>>> Query().must({'term': {'some_field': 1}})
>>> from pandagg.query import Term
>>> Query().must(Term(some_field=1))
:Keyword Arguments:
%(location_kwargs)s
"""
return self._compound_param_insert(
"bool", "must", mode, type_or_query, insert_below, on, bool_body, **body
)
def should(
self,
type_or_query,
insert_below=None,
on=None,
mode=ADD,
bool_body=None,
**body
):
return self._compound_param_insert(
"bool", "should", mode, type_or_query, insert_below, on, bool_body, **body
)
def must_not(
self,
type_or_query,
insert_below=None,
on=None,
mode=ADD,
bool_body=None,
**body
):
return self._compound_param_insert(
"bool", "must_not", mode, type_or_query, insert_below, on, bool_body, **body
)
def filter(
self,
type_or_query,
insert_below=None,
on=None,
mode=ADD,
bool_body=None,
**body
):
return self._compound_param_insert(
"bool", "filter", mode, type_or_query, insert_below, on, bool_body, **body
)
# compound
def bool(
self,
must=None,
should=None,
must_not=None,
filter=None,
insert_below=None,
on=None,
mode=ADD,
**body
):
"""
>>> Query().bool(must={"term": {"some_field": "yolo"}})
"""
return self.query(
"bool",
must=must,
should=should,
must_not=must_not,
filter=filter,
insert_below=insert_below,
on=on,
mode=mode,
**body
)
def boosting(
self, positive=None, negative=None, insert_below=None, on=None, mode=ADD, **body
):
if not positive and not negative:
raise ValueError('Expect at least one of "positive", "negative"')
return self.query(
"boosting",
positive=positive,
negative=negative,
insert_below=insert_below,
on=on,
mode=mode,
**body
)
def constant_score(
self, filter=None, boost=None, insert_below=None, on=None, mode=ADD, **body
):
if not filter and not boost:
raise ValueError('Expect at least one of "filter", "boost"')
return self.query(
"constant_score",
filter=filter,
boost=boost,
insert_below=insert_below,
on=on,
mode=mode,
**body
)
def dis_max(self, queries, insert_below=None, on=None, mode=ADD, **body):
return self.query(
"dis_max",
queries=queries,
insert_below=insert_below,
on=on,
mode=mode,
**body
)
def function_score(self, query, insert_below=None, on=None, mode=ADD, **body):
return self.query(
"function_score",
query=query,
insert_below=insert_below,
on=on,
mode=mode,
**body
)
def nested(self, path, query=None, insert_below=None, on=None, mode=ADD, **body):
return self.query(
"nested",
query=query,
insert_below=insert_below,
on=on,
mode=mode,
path=path,
**body
)
def has_child(self, query, insert_below=None, on=None, mode=ADD, **body):
return self.query(
"has_child",
query=query,
insert_below=insert_below,
on=on,
mode=mode,
**body
)
def has_parent(self, query, insert_below=None, on=None, mode=ADD, **body):
return self.query(
"has_parent",
query=query,
insert_below=insert_below,
on=on,
mode=mode,
**body
)
def script_score(self, query, insert_below=None, on=None, mode=ADD, **body):
return self.query(
"script_score",
query=query,
insert_below=insert_below,
on=on,
mode=mode,
**body
)
def pinned_query(self, organic, insert_below=None, on=None, mode=ADD, **body):
return self.query(
"pinned_query",
organic=organic,
insert_below=insert_below,
on=on,
mode=mode,
**body
)
def show(self, *args, line_max_length=80, **kwargs):
"""
Return compact representation of Query.
>>> Query()\
>>> .must({"exists": {"field": "some_field"}})\
>>> .must({"term": {"other_field": {"value": 5}}})\
>>> .show()
<Query>
bool
└── must
├── exists field=some_field
└── term field=other_field, value=5
All *args and **kwargs are propagated to `lighttree.Tree.show` method.
:return: str
"""
return "<Query>\n%s" % str(
super(Tree, self).show(*args, line_max_length=line_max_length, **kwargs)
)
def applied_nested_path_at_node(self, nid):
"""
Return nested path applied at a clause.
:param nid: clause identifier
:return: None if no nested is applied, else applied path (str)
"""
# from current node to root
for id_ in self.ancestors_ids(nid, include_current=True):
_, node = self.get(id_)
if isinstance(node, Nested):
return node.path
return None
def to_dict(self, from_=None):
"""
Serialize Query as dict.
"""
if self.root is None:
return None
from_ = self.root if from_ is None else from_
key, node = self.get(from_)
if isinstance(node, LeafQueryClause):
return node.to_dict()
if not isinstance(node, CompoundClause):
raise ValueError("Unexpected %s" % node.__class__)
d = {}
is_empty = True
for param_key, param_node in self.children(node.identifier):
children_serialized = [
self.to_dict(child_node.identifier)
for _, child_node in self.children(param_node.identifier)
]
children_serialized = [c for c in children_serialized if c]
if not children_serialized:
continue
is_empty = False
if not param_node.MULTIPLE:
d[param_key] = children_serialized[0]
continue
d[param_key] = children_serialized
# a compound query clause can exist, without children clauses, in that case, just ignore it
if is_empty:
return None
q = node.to_dict()
q[node.KEY].update(d)
return q
# compound parameters
def _compound_param_insert(
self,
compound_key,
compound_param_key,
mode,
type_or_query,
insert_below=None,
on=None,
compound_body=None,
**body
):
q = self.clone(with_nodes=True)
node = self._q(type_or_query, **body)
compound_body = compound_body or {}
compound_body[compound_param_key] = node
compound_node = self.get_node_dsl_class(compound_key)(**compound_body)
q._insert_query_at(compound_node, on=on, insert_below=insert_below, mode=mode)
return q
def __nonzero__(self):
return bool(self.to_dict())
__bool__ = __nonzero__
def _clone_init(self, deep=False):
return Query(
mappings=None
if self.mappings is None
else self.mappings.clone(with_nodes=True, deep=deep),
nested_autocorrect=self.nested_autocorrect,
)
def _has_bool_root(self):
if not self.root:
return False
_, r = self.get(self.root)
return isinstance(r, Bool)
def _compound_param_id(self, nid, key, create_if_not_exists=True):
"""
:param nid: id of compound node
:param key: param key, for instance if compound if bool, can be 'must', 'should', 'must_not' etc
:return: param node id
"""
try:
return self.child_id(nid, key)
except ValueError:
if not create_if_not_exists:
raise
# add key
param_node = self.get_node_dsl_class(key)()
self._insert_node_below(param_node, parent_id=nid, key=key, by_path=False)
return param_node.identifier
@classmethod
def _q(cls, type_or_query, **body):
"""
Convert to QueryClause instance.
"""
if isinstance(type_or_query, Query):
type_or_query = type_or_query.to_dict()
return Q(type_or_query, **body)
def _insert_query_at(
self, node, mode, on=None, insert_below=None, compound_param=None
):
"""
Insert clause (and its children) in Query.
If compound query with on specified: merge according to mode.
If insert_below is not specified, place on top (wrapped in bool-must if necessary).
If insert_below is provided (only under compound query): place under it.
"""
if mode not in (ADD, REPLACE, REPLACE_ALL):
raise ValueError("Invalid mode %s" % mode)
if (
isinstance(node, Bool)
and not on
and not insert_below
and self._has_bool_root()
):
on = self.root
if isinstance(node, CompoundClause) and on:
# ensure we try to merge on same type of clause
_, existing = self.get(on)
if existing.KEY != node.KEY:
raise ValueError(
"Cannot merge compound clause %s on %s. Must be the same."
% (node.KEY, existing.KEY)
)
if mode == REPLACE_ALL:
pid = self.parent_id(on)
existing_k, _ = self.drop_subtree(on)
self._insert_query(node, insert_below=pid)
existing.body = node.body
return
# merge
existing.body.update(node.body)
for param_key, children in node._children.items():
if not children:
continue
param_id = self._compound_param_id(on, param_key)
# here, possible modes are either ADD, or REPLACE
if mode == REPLACE:
existing_clauses_ids = self.children_ids(param_id)
for eid in existing_clauses_ids:
self.drop_node(eid)
for child in children:
self._insert_query(child, insert_below=param_id)
return
if insert_below:
# below node, with compound_param
_, pnode = self.get(insert_below)
if not isinstance(pnode, CompoundClause):
raise ValueError(
"Cannot insert clause below %s clause (only compound clauses can have children clauses)."
% pnode.KEY
)
compound_param = compound_param or pnode._default_operator
if compound_param not in pnode._parent_params.keys():
raise ValueError(
"<%s> parameter for <%s> compound clause does not accept children clauses."
% (compound_param, pnode.KEY)
)
param_id = self._compound_param_id(insert_below, compound_param)
_, p = self.get(param_id)
if not p.MULTIPLE:
# inserting a clause, under a parameter allowing a single clause (for instance below nested query)
cids = self.children_ids(param_id)
| |
<gh_stars>0
import base64
import dateutil.parser
import email
import hashlib
import logging
import os
import re
from dateutil import tz
from email.header import decode_header, make_header
from urlfinderlib import find_urls
from lib import RegexHelpers
from lib.config import config
from lib.constants import HOME_DIR
from lib.indicator import Indicator
from lib.indicator import make_url_indicators
class EmailParser():
def __init__(self, smtp_path, whitelist):
# Initiate logging.
self.logger = logging.getLogger()
# Save the whitelist.
self.whitelist = whitelist
# Items we parse out of the email.
self.ace_url = ''
self.attachments = []
self.body = ''
self.cc_addresses = []
self.envelope_from = ''
self.envelope_to = ''
self.from_address = ''
self.headers = ''
self.html = ''
self.indicators = []
self.message_id = ''
self.original_recipient = ''
self.path = smtp_path
self.received = ''
self.received_time = ''
self.remediated = False
self.reply_to = ''
self.return_path = ''
self.screenshots = []
self.subject = ''
self.subject_decoded = ''
self.to_addresses = []
self.urls = []
self.x_auth_id = ''
self.x_mailer = ''
self.x_original_sender = ''
self.x_originating_ip = ''
self.x_sender = ''
self.x_sender_id = ''
self.x_sender_ip = ''
# Build the URL to the ACE alert.
ace_uuid_pattern = re.compile(r'([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})')
match = ace_uuid_pattern.search(self.path)
if match:
self.ace_url = '{}{}'.format(config['ace']['ace_alert_url'], match.group(1))
with open(self.path, encoding='utf-8', errors='ignore') as s:
smtp_stream = s.read().splitlines()
# Locate any screenshots for this email.
email_dir = os.path.dirname(self.path)
files = os.listdir(email_dir)
for f in files:
if 'text_html' in f and f.endswith('.png') and not f.startswith('email_screenshot'):
self.logger.debug('Found email screenshot: {}'.format(os.path.join(email_dir, f)))
self.screenshots.append(os.path.join(email_dir, f))
# Find the envelope from/to addresses. This will only work if given an
# "smtp.stream" file, since otherwise the SMTP commands will not exist.
envelope_address_pattern = re.compile(r'.*<(.*)>.*')
for line in smtp_stream:
if line.startswith('MAIL FROM:'):
try:
self.envelope_from = envelope_address_pattern.match(line).group(1)
except:
self.logger.exception('Unable to parse envelope from.')
if line.startswith('RCPT TO:'):
try:
self.envelope_to = envelope_address_pattern.match(line).group(1)
except:
self.logger.exception('Unable to parse envelope to.')
# Just in case we are dealing with an "smtp.stream" file that still has
# the SMTP commands above the actual e-mail, we need to strip those out.
# This will remove all lines prior to the Received: headers so that the
# email.parser can properly parse out the e-mail. If we were given an
# "smtp.email" type of file with the SMTP commands already removed, this
# should not affect anything. This is legacy code at this point.
try:
while not smtp_stream[0].startswith('Received:'):
smtp_stream.pop(0)
except IndexError:
smtp_stream = []
# Join the header lines into a single string.
self.email_text = '\n'.join(smtp_stream)
# Create the e-mail object.
email_obj = email.message_from_string(self.email_text)
# We want to try and parse an embedded/attached e-mail if there is one.
# Walk the full e-mail's parts.
for part in email_obj.walk():
# Continue if the part looks like a valid e-mail.
if part.get_content_type() == 'message/rfc822':
# Split the part lines into a list.
part_text = str(part).splitlines()
if any('Received:' in line for line in part_text):
# Make sure our part starts with the Received: headers.
try:
while not part_text[0].startswith('Received:'):
part_text.pop(0)
except IndexError:
pass
part_text = '\n'.join(part_text)
# Make the new e-mail object.
email_obj = email.message_from_string(part_text)
# Parse the e-mail object for its content.
parsed_email = self._parse_content(email_obj)
# Now that we have the e-mail object, parse out some of the interesting parts.
self.headers = self._get_all_headers_string(email_obj)
self.received = self.get_header(email_obj, 'received')
# Get the e-mail's plaintext body, HTML body, and the visible text from the HTML.
self.body = parsed_email['body']
self.html = parsed_email['html']
# Get any e-mail attachments.
self.attachments = parsed_email['attachments']
# From address
try:
self.from_address = self._get_address_list(email_obj, 'from')[0][1]
self.indicators.append(Indicator('Email - Address', self.from_address, tags=['from_address']))
except:
pass
# From domain
try:
self.indicators.append(Indicator('URI - Domain Name', self.from_address.split('@')[1], tags=['from_domain']))
except:
pass
# Reply-To address
try:
self.reply_to = self._get_address_list(email_obj, 'reply-to')[0][1]
self.indicators.append(Indicator('Email - Address', self.reply_to, tags=['reply_to']))
except:
pass
# X-Sender address
try:
self.x_sender = self._get_address_list(email_obj, 'X-Sender')[0][1]
self.indicators.append(Indicator('Email - Address', self.x_sender, tags=['x_sender']))
except:
pass
# X-Sender-Id address
try:
self.x_sender_id = self._get_address_list(email_obj, 'X-Sender-Id')[0][1]
self.indicators.append(Indicator('Email - Address', self.x_sender_id, tags=['x_sender_id']))
except:
pass
# X-Auth-Id address
try:
self.x_auth_id = self._get_address_list(email_obj, 'X-Auth-ID')[0][1]
self.indicators.append(Indicator('Email - Address', self.x_auth_id, tags=['x_auth_id']))
except:
pass
# Return-Path address
try:
self.return_path = self._get_address_list(email_obj, 'return_path')[0][1]
self.indicators.append(Indicator('Email - Address', self.return_path, tags=['return_path']))
except:
pass
# X-MS-Exchange-Organization-OriginalEnvelopeRecipients address
try:
self.original_recipient = self._get_address_list(email_obj, 'X-MS-Exchange-Organization-OriginalEnvelopeRecipients')[0][1].lower()
self.indicators.append(Indicator('Email - Address', self.original_recipient, status='Informational', tags=['original_recipient']))
except:
pass
# If the original_recipient was not found, check if this is a POTENTIAL PHISH e-mail and use the from address.
if not self.original_recipient and 'Subject: [POTENTIAL PHISH]' in self.email_text:
try:
temp_email_obj = email.message_from_string(self.email_text)
self.original_recipient = self._get_address_list(temp_email_obj, 'from')[0][1]
self.indicators.append(Indicator('Email - Address', self.original_recipient, status='Informational', tags=['original_recipient']))
except:
self.logger.exception('Error parsing original recipient from POTENTIAL PHISH e-mail.')
# Subject
try:
self.subject = ''.join(self.get_header(email_obj, 'subject')[0].splitlines())
if not self.subject.startswith('[POTENTIAL PHISH]'):
self.indicators.append(Indicator('Email - Subject', self.subject))
except:
pass
# Decoded subject
try:
self.subject_decoded = ''.join(str(make_header(decode_header(self.get_header(email_obj, 'subject')[0]))).splitlines())
if not self.subject_decoded.startswith('[POTENTIAL PHISH]'):
self.indicators.append(Indicator('Email - Subject', self.subject_decoded))
except:
pass
# To addresses
self.to_addresses = [x[1].lower() for x in self._get_address_list(email_obj, 'to')]
# CC addresses
self.cc_addresses = [x[1].lower() for x in self._get_address_list(email_obj, 'cc')]
# Message-Id
try:
self.message_id = self.get_header(email_obj, 'message-id')[0]
self.indicators.append(Indicator('Email Message ID', self.message_id, status='Informational'))
except:
pass
# X-Mailer
try:
self.x_mailer = self.get_header(email_obj, 'x-mailer')[0]
self.indicators.append(Indicator('Email - Xmailer', self.x_mailer, status='Informational'))
except:
pass
# X-Original-Sender address
try:
self.x_original_sender = self.get_header(email_obj, 'x-original-sender')[0]
self.indicators.append(Indicator('Email - Address', self.x_original_sender, tags=['x_original_sender']))
except:
pass
# X-Originating-Ip
try:
x_originating_ip = self.get_header(email_obj, 'x-originating-ip')[0]
# Sometimes this field is in the form: [1.1.1.1]
# Make sure we remove any non-IP characters.
ip = RegexHelpers.find_ip_addresses(x_originating_ip)
if ip:
self.x_originating_ip = ip[0]
self.indicators.append(Indicator('Address - ipv4-addr', self.x_originating_ip, tags=['x_originating_ip']))
except:
pass
# X-Sender-Ip
try:
x_sender_ip = self.get_header(email_obj, 'x-sender-ip')[0]
# Make sure like the X-Originating-IP that we only
# get the IP address and no other characters.
ip = RegexHelpers.find_ip_addresses(x_sender_ip)
if ip:
self.x_sender_ip = ip[0]
self.indicators.append(Indicator('Address - ipv4-addr', self.x_sender_ip, tags=['x_sender_ip']))
except:
pass
self.received_time = self._get_received_time(email_obj)
if not self.received_time:
self.received_time = self._get_date_time()
# Find any URLs in the plaintext body.
text_urls = find_urls(self.body)
# Find any URLs in the HTML body.
html_urls = find_urls(self.html)
# Get any strings URLs.
strings_urls = []
"""
for file in self.attachments:
try:
strings_urls += file['strings_urls']
except:
pass
"""
# Try and remove any URLs that look like partial versions of other URLs.
all_urls = set.union(text_urls, html_urls)
unique_urls = set()
for u in all_urls:
if not any(other_url.startswith(u) and other_url != u for other_url in all_urls):
unique_urls.add(u)
# Get rid of any invalid URLs.
self.urls = [u for u in unique_urls if RegexHelpers.is_url(u)]
# Make indicators for the URLs.
self.indicators += make_url_indicators(self.urls, from_email_content=True)
# Get rid of any invalid indicators.
self.indicators = [i for i in self.indicators if i.value]
# Add any extra tags to each indicator.
for i in self.indicators:
i.tags.append('phish')
def __eq__(self, other):
""" Returns True if the headers are equal. """
return self.headers.lower() == other.headers.lower()
def __hash__(self):
""" Use the headers as the hash. """
return hash((self.headers.lower()))
@property
def json(self):
""" Return a JSON compatible view of the email. """
json = {}
json['ace_url'] = self.ace_url
json['attachments'] = self.attachments
json['body'] = self.body
json['cc_addresses'] = self.cc_addresses
json['envelope_from'] = self.envelope_from
json['envelope_to'] = self.envelope_to
json['from_address'] = self.from_address
json['headers'] = self.headers
json['html'] = self.html
json['message_id'] = self.message_id
json['original_recipient'] = self.original_recipient
json['path'] = self.path
json['received'] = self.received
json['received_time'] = self.received_time
json['remediated'] = self.remediated
json['reply_to'] = self.reply_to
json['return_path'] = self.return_path
json['screenshots'] = self.screenshots
json['subject'] = self.subject
json['subject_decoded'] = self.subject_decoded
json['to_addresses'] = self.to_addresses
json['urls'] = self.urls
json['x_auth_id'] = self.x_auth_id
json['x_mailer'] = self.x_mailer
json['x_original_sender'] = self.x_original_sender
json['x_originating_ip'] = self.x_originating_ip
json['x_sender'] = self.x_sender
json['x_sender_id'] = self.x_sender_id
json['x_sender_ip'] = self.x_sender_ip
return json
def get_header(self, email_obj, header_name):
return email_obj.get_all(header_name, [])
def _get_all_headers_string(self, email_obj):
header_string = ''
try:
bad_headers = config['wiki']['ignore_headers']
except:
bad_headers = []
for header in email_obj.items():
if not any(bad_header in header[0] for bad_header in bad_headers):
header_string += ': '.join(header) + '\n'
return header_string
def _get_address_list(self, email_obj, header_name):
header = email_obj.get_all(header_name, [])
return email.utils.getaddresses(header)
def _get_date_time(self):
for line in self.email_text.splitlines():
if 'Date:' in line:
date_pattern = re.compile(r'[A-Z][a-z]{2,3},\s+\d+\s+[A-Z][a-z]{2,3}\s+[0-9]{4}\s+[0-9]{2}:[0-9]{2}:[0-9]{2}\s*(\+\d+|\-\d+)*')
date_time = re.search(date_pattern, line)
if date_time:
datetime_obj = dateutil.parser.parse(date_time.group(0), ignoretz=False)
localtime = dateutil.tz.tzlocal()
try:
localtime_string = str(datetime_obj.astimezone(localtime))
except ValueError:
localtime_string = str(datetime_obj)
return localtime_string
return ''
def _get_received_time(self, email_obj):
header=email_obj.get_all('received', [])
try:
last_received_lines = header[0]
except IndexError:
last_received_lines = ''
received_time_pattern = re.compile(r'[A-Z][a-z]{2,3},\s+\d+\s+[A-Z][a-z]{2,3}\s+[0-9]{4}\s+[0-9]{2}:[0-9]{2}:[0-9]{2}\s*(\+\d+|\-\d+)*')
last_received_time = re.search(received_time_pattern, last_received_lines)
if last_received_time:
datetime_obj = dateutil.parser.parse(last_received_time.group(0), ignoretz=False)
localtime = dateutil.tz.tzlocal()
try:
localtime_string = str(datetime_obj.astimezone(localtime))
except ValueError:
localtime_string = | |
<reponame>drmegannewsome/lcogtsnpipe
import sys
import os
from astropy.io import fits
from astropy.nddata import Cutout2D
from astropy.wcs import WCS
import lsc
from glob import glob
import pkg_resources
workdirectory = os.getenv('LCOSNDIR', '/supernova/')
configfile = os.path.join(workdirectory, 'configure')
if not os.path.exists(configfile):
configfile = pkg_resources.resource_filename('lsc', 'configure')
def readpasswd(configfile):
""" read all information to connect to database from configuration file
"""
from numpy import genfromtxt
data = genfromtxt(configfile, str)
gg= {}
for i in data:
try:
gg[i[0]] = eval(i[1])
except:
gg[i[0]] = i[1]
return gg
#############################################################################################
# read information from configuration file
#######################################################################################
readpass = readpasswd(configfile)
proposal = readpass['proposal']
users = readpass['users']
triggerpass = readpass['triggerpass']
extraobject = readpass['extraobject']
skipobjects = readpass['skipobjects']
proposalingestion = readpass['proposalingestion']
#############################################################################################
def ReadAscii2(ascifile):
import string
f=open(ascifile,'r')
ss=f.readlines()
f.close()
vec1,vec2=[],[]
for line in ss:
if line[0]!='#':
vec1.append(float(string.split(line)[0]))
vec2.append(float(string.split(line)[1]))
return vec1,vec2
#########################################################################
def readlist(listfile):
import string,os,sys,re,glob
if '*' in listfile:
imglist=glob.glob(listfile)
elif ',' in listfile: imglist = string.split(listfile,sep=',')
else:
try: hdulist= fits.open(listfile)
except: hdulist=[]
if hdulist: imglist = [listfile]
else:
try:
ff = open(listfile,'r')
files = ff.readlines()
ff.close()
imglist = []
for ff in files:
ff=re.sub(' ','',ff)
if not ff=='\n' and ff[0]!='#':
ff=re.sub('\n','',ff)
try:
hdulist= fits.open(ff)
imglist.append(ff)
except Exception as e:
print 'problem reading header of', ff
print e
except: sys.exit('\n##### Error ###\n file '+str(listfile)+' do not exist\n')
if len(imglist)==0:
sys.exit('\n##### Error ###\nIf "'+str(listfile)\
+'" is an image, it is corrupted \n or is not a list of image\n')
return imglist
##############################################################################
def delete(listfile):
import os,string,re,glob
if listfile[0]=='@':
ff = open(listfile[1:])
files = ff.readlines()
imglist = []
for ff in files:
ff=re.sub(' ','',ff)
if not ff=='\n' and ff[0]!='#':
ff=re.sub('\n','',ff)
imglist.append(ff)
elif ',' in listfile: imglist = string.split(listfile,sep=',')
else: imglist=[listfile]
lista=[]
for _file in imglist: lista=lista+glob.glob(_file)
if lista:
for _file in lista:
try: os.system('rm '+_file)
except: pass
def imcopy(imgin, imgout, center=None, cutout_size=None, ext=0):
'''iraf.imcopy equivalent
center = (x, y) of center of cutout
cutout_size = (dy, dx) or single value for square
By default, the entire 0th extension is copied.'''
hdulist = fits.open(imgin)
data = hdulist[ext].data
hdr = hdulist[ext].header
if center is not None and cutout_size is not None:
cutout = Cutout2D(data, center, cutout_size, WCS(hdr))
data = cutout.data
hdr['CRPIX1'] = cutout.wcs.wcs.crpix[0]
hdr['CRPIX2'] = cutout.wcs.wcs.crpix[1]
fits.writeto(imgout, data, hdr)
hdulist.close()
###############################################################
def readhdr(img):
try:
hdr = fits.getheader(img)
except Exception as e:
print "Couldn't read header of {}. Try deleting it and starting over.".format(img)
raise e
return hdr
missingvalues = ['NaN', 'UNKNOWN', None, '', 'UNSPECIFIED', 'N/A']
def readkey3(hdr,keyword):
from astropy.coordinates import Angle
from astropy import units as u
try:
_instrume=hdr.get('INSTRUME').lower()
except:
_instrume='none'
if 'kb' in _instrume: # SBIG
useful_keys = {'object' : 'OBJECT',\
'date-obs' : 'DATE-OBS',\
'ut' : 'DATE-OBS',\
'date-night': 'DAY-OBS',\
'RA' : 'RA',\
'DEC' : 'DEC',\
'CAT-RA' : 'CAT-RA',\
'CAT-DEC' : 'CAT-DEC',\
'datamin' : -100.0,\
'datamax' : 'SATURATE',\
'observer' : 'OBSERVER',\
'exptime' : 'EXPTIME',\
'wcserr' : 'WCSERR',\
'instrume' : 'INSTRUME',\
'JD' : 'MJD-OBS',\
'mjd' : 'MJD-OBS',\
'filter' : 'FILTER',\
'gain' : 'GAIN',\
'ron' : 'RDNOISE',\
'airmass' : 'AIRMASS',\
'type' : 'OBSTYPE',\
'propid' : 'PROPID',\
'userid' : 'USERID',\
'telescop' : 'TELESCOP'}
elif 'fl' in _instrume or 'fa' in _instrume: # sinistro
useful_keys = {'object' : 'OBJECT',\
'date-obs' : 'DATE-OBS',\
'ut' : 'DATE-OBS',\
'date-night': 'DAY-OBS',\
'RA' : 'RA',\
'DEC' : 'DEC',\
'CAT-RA' : 'CAT-RA',\
'CAT-DEC' : 'CAT-DEC',\
'datamin' : -100.0,\
'datamax' : 'SATURATE',\
'observer' : 'OBSERVER',\
'exptime' : 'EXPTIME',\
'wcserr' : 'WCSERR',\
'instrume' : 'INSTRUME',\
'JD' : 'MJD-OBS',\
'mjd' : 'MJD-OBS',\
'filter' : 'FILTER',\
'gain' : 'GAIN',\
'ron' : 'RDNOISE',\
'airmass' : 'AIRMASS',\
'type' : 'OBSTYPE',\
'propid' : 'PROPID',\
'userid' : 'USERID',\
'telescop' : 'TELESCOP'}
elif 'ep' in _instrume: # muscat
useful_keys = {'object': 'OBJECT',
'date-obs': 'DATE-OBS',
'ut': 'DATE-OBS',
'date-night': 'DAY-OBS',
'RA': 'RA',
'DEC': 'DEC',
'CAT-RA': 'CAT-RA',
'CAT-DEC': 'CAT-DEC',
'datamin': -100.0,
'datamax': 'SATURATE',
'observer': 'OBSERVER',
'exptime': 'EXPTIME',
'wcserr': 'WCSERR',
'instrume': 'INSTRUME',
'JD': 'MJD-OBS',
'mjd': 'MJD-OBS',
'filter': 'FILTER',
'gain': 'GAIN',
'ron': 'RDNOISE',
'airmass': 'AIRMASS',
'type': 'OBSTYPE',
'propid': 'PROPID',
'userid': 'USERID',
'telescop': 'TELESCOP'}
elif 'fs' in _instrume or 'em' in _instrume:
if hdr.get('DATE-OBS') < '2014-04-01':
if 'RDNOISE' in hdr: ron='RDNOISE'
elif 'READNOIS' in hdr: ron='READNOIS'
else: ron='ron'
useful_keys = {'object' : 'OBJECT',\
'date-obs' : 'DATE-OBS',\
'ut' : 'DATE-OBS',\
'date-night': 'DAY-OBS',\
'RA' : 'RA',\
'DEC' : 'DEC',\
'CAT-RA' : 'CAT-RA',\
'CAT-DEC' : 'CAT-DEC',\
'datamin' : -100.0,\
'datamax' : 60000.0,\
'wcserr' : 'WCS_ERR',\
'observer' : 'OBSERVER',\
'exptime' : 'EXPTIME',\
'instrume' : 'INSTRUME',\
'JD' : 'MJD',\
'mjd' : 'MJD',\
'filter' : 'FILTER',\
'gain' : 'GAIN',\
'ron' : ron,\
'airmass' : 'AIRMASS',\
'userid' : 'USERID',\
'propid' : 'PROPID',\
'type' : 'OBSTYPE',\
'telescop' : 'TELID'}
if _instrume == 'fs02': # OGG
useful_keys['pixscale'] = 0.30104
elif _instrume in ['fs01', 'fs03']: # COJ
useful_keys['pixscale'] = 0.304
else:
useful_keys = {'object' : 'OBJECT',\
'date-obs' : 'DATE-OBS',\
'ut' : 'DATE-OBS',\
'date-night': 'DAY-OBS',\
'RA' : 'RA',\
'DEC' : 'DEC',\
'CAT-RA' : 'CAT-RA',\
'CAT-DEC' : 'CAT-DEC',\
'datamin' : -100.0,\
'datamax' : 'SATURATE',\
'observer' : 'OBSERVER',\
'exptime' : 'EXPTIME',\
'wcserr' : 'WCSERR',\
'instrume' : 'INSTRUME',\
'JD' : 'MJD-OBS',\
'mjd' : 'MJD-OBS',\
'filter' : 'FILTER',\
'gain' : 'GAIN',\
'ron' : 'RDNOISE',\
'airmass' : 'AIRMASS',\
'type' : 'OBSTYPE',\
'propid' : 'PROPID',\
'userid' : 'USERID',\
'telescop' : 'TELESCOP'}
else:
useful_keys = {'object' : 'OBJECT',\
'RA' : 'RA',\
'DEC' : 'DEC',\
'CAT-RA' : 'RA',\
'CAT-DEC' : 'DEC',\
'ron' : 'RDNOISE',\
'date-obs' : 'DATE-OBS',\
'date-night': 'DAY-OBS',\
'datamax' : 'SATURATE'}
if keyword in useful_keys:
if type(useful_keys[keyword])==float:
value=useful_keys[keyword]
else:
value=hdr.get(useful_keys[keyword])
if keyword=='date-obs':
try:
value = value.split('T')[0].replace('-', '')
except:
pass
elif keyword=='ut':
try:
value = value.split('T')[1]
except:
pass
elif keyword=='object':
value = value.translate(None, ' }{][)(')
elif keyword=='JD':
value=value+0.5
elif keyword=='instrume': value=value.lower()
elif keyword=='filter' and value in [None, 'air']:
for key in ['FILTER2', 'FILTER1', 'FILTER3']:
if hdr.get(key) not in [None, 'air']:
value = hdr[key]
break
elif keyword in ['RA', 'CAT-RA'] and type(value) == str and ':' in value:
value = Angle(value, u.hourangle).deg
elif keyword in ['RA', 'CAT-RA', 'DEC', 'CAT-DEC'] and value not in missingvalues:
value = Angle(value, u.deg).deg
elif keyword in hdr:
value=hdr.get(keyword)
else:
value=''
if type(value) == str:
value = value.replace('\#', '')
if value == 'ftn':
value = '2m0-01'
elif value == 'fts':
value = '2m0-02'
return value
#######################################################
def writeinthelog(text,logfile):
f=open(logfile,'a')
f.write(text)
f.close()
def updateheader(filename, dimension, headerdict):
try:
hdulist = fits.open(filename, mode='update')
header = hdulist[dimension].header
header.update(headerdict)
hdulist.close()
except Exception as e:
print 'header of', filename, 'not updated:'
print e
#################################################################################################
def display_image(img,frame,_z1,_z2,scale,_xcen=0.5,_ycen=0.5,_xsize=1,_ysize=1,_erase='yes'):
goon='True'
import glob, subprocess, os, time
# removing u : this option does not work on mac
ds9 = subprocess.Popen("ps -U {:d} | grep -v grep | grep ds9".format(os.getuid()),shell=True,stdout=subprocess.PIPE).stdout.readlines()
if len(ds9)== 0 :
subproc = subprocess.Popen('ds9',shell=True)
time.sleep(3)
if glob.glob(img):
from pyraf import iraf
iraf.images(_doprint=0)
iraf.tv(_doprint=0)
import string,os
if _z2:
try:
sss=iraf.display(img + '[0]', frame, xcen=_xcen, ycen=_ycen, xsize=_xsize, ysize=_ysize, erase=_erase,\
fill='yes', zscale='no', zrange='no', z1=_z1, z2=_z2,Stdout=1)
except:
print ''
print '### ERROR: PROBLEM OPENING DS9'
print ''
goon='False'
else:
try:
sss=iraf.display(img + '[0]', frame, xcen=_xcen, ycen=_ycen, xsize=_xsize, ysize=_ysize, erase=_erase, fill='yes', Stdout=1)
except:
print ''
print '### ERROR: PROBLEM OPENING DS9'
print ''
goon=False
if scale and goon:
answ0 = raw_input('>>> Cuts OK ? [y/n] ? [y] ')
if not answ0: answ0='y'
elif answ0=='no' or answ0=='NO': answ0='n'
while answ0=='n':
_z11=float(string.split(string.split(sss[0])[0],'=')[1])
_z22=float(string.split(string.split(sss[0])[1],'=')[1])
z11 = raw_input('>>> z1 = ? ['+str(_z11)+'] ? ')
z22 = raw_input('>>> z2 = ? ['+str(_z22)+'] ? ')
if not z11: z11=_z11
else: z11=float(z11)
if not z22: z22=_z22
else: z22=float(z22)
print z11,z22
sss=iraf.display(img + '[0]',frame,fill='yes', xcen=_xcen, ycen=_ycen, xsize=_xsize, ysize=_ysize, erase=_erase,\
zrange='no', zscale='no', z1=z11, z2=z22, Stdout=1)
answ0 = raw_input('>>> Cuts OK ? [y/n] ? [y] ')
if not answ0: answ0='y'
elif answ0=='no' or answ0=='NO': answ0='n'
if goon:
_z1,_z2=string.split(string.split(sss[0])[0],'=')[1],string.split(string.split(sss[0])[1],'=')[1]
else:
print 'Warning: image '+str(img)+' not found in the directory '
return _z1,_z2,goon
###########################################################################
def readstandard(standardfile):
import lsc
from numpy import array,abs
import string,os
if os.path.isfile(standardfile):
listastandard=standardfile
elif standardfile[0]=='/':
listastandard=standardfile
else:
listastandard=lsc.__path__[0]+'/standard/stdlist/'+standardfile
f=open(listastandard,'r')
liststd=f.readlines()
f.close()
star,ra,dec=[],[],[]
magnitude=[]
for i in liststd:
if i[0]!='#':
star.append(string.split(i)[0])
_ra=string.split(string.split(i)[1],':')
_dec=string.split(string.split(i)[2],':')
ra.append((float(_ra[0])+((float(_ra[1])+(float(_ra[2])/60.))/60.))*15)
if '-' in str(_dec[0]):
dec.append((-1)*(abs(float(_dec[0]))+((float(_dec[1])+(float(_dec[2])/60.))/60.)))
else:
dec.append(float(_dec[0])+((float(_dec[1])+(float(_dec[2])/60.))/60.))
try: magnitude.append(string.split(i)[3])
except: magnitude.append(999)
return array(star),array(ra),array(dec),array(magnitude)
#################################################################################################
def readspectrum(img):
from numpy import array
import string
fl=''
lam=''
graf=1
spec = fits.open(img)
head = spec[0].header
try:
if spec[0].data.ndim == 1: fl = spec[0].data
elif spec[0].data.ndim == 2: fl = spec[0].data[:,0]
elif spec[0].data.ndim == 3: fl = spec[0].data[0,0,:]
except:
if spec[0].data.rank == 1: fl = spec[0].data
| |
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import with_statement
import logging
from django.db.utils import IntegrityError
from networkapi.admin_permission import AdminPermission
from networkapi.ambiente.models import Ambiente
from networkapi.ambiente.models import AmbienteNotFoundError
from networkapi.auth import has_perm
from networkapi.distributedlock import distributedlock
from networkapi.distributedlock import LOCK_IP_EQUIPMENT
from networkapi.equipamento.models import Equipamento
from networkapi.equipamento.models import EquipamentoError
from networkapi.equipamento.models import EquipamentoNotFoundError
from networkapi.exception import InvalidValueError
from networkapi.grupo.models import GrupoError
from networkapi.infrastructure.ipaddr import IPAddress
from networkapi.infrastructure.xml_utils import dumps_networkapi
from networkapi.infrastructure.xml_utils import loads
from networkapi.infrastructure.xml_utils import XMLError
from networkapi.ip.models import Ip
from networkapi.ip.models import IpCantBeRemovedFromVip
from networkapi.ip.models import IpCantRemoveFromServerPool
from networkapi.ip.models import IpEquipamento
from networkapi.ip.models import IpEquipamentoDuplicatedError
from networkapi.ip.models import IpEquipCantDissociateFromVip
from networkapi.ip.models import IpEquipmentNotFoundError
from networkapi.ip.models import IpError
from networkapi.ip.models import IpNotAvailableError
from networkapi.ip.models import IpNotFoundError
from networkapi.ip.models import NetworkIPv4NotFoundError
from networkapi.requisicaovips.models import ServerPoolMember
from networkapi.rest import RestResource
from networkapi.rest import UserNotAuthorizedError
from networkapi.util import destroy_cache_function
from networkapi.util import is_valid_int_greater_zero_param
from networkapi.util import is_valid_ipv4
from networkapi.util import is_valid_string_maxsize
from networkapi.util import is_valid_string_minsize
from networkapi.util import mount_ipv4_string
from networkapi.vlan.models import VlanError
from networkapi.vlan.models import VlanNotFoundError
def insert_ip(ip_map, user):
"""Insere um IP e o relacionamento entre o IP e o equipamento.
@param ip_map: Map com as chaves: id_equipamento, id_vlan e descricao
@param user: Usuário autenticado na API.
@return Em caso de erro retorna a tupla: (código da mensagem de erro, argumento01, argumento02, ...)
Em caso de sucesso retorna a tupla: (0, <mapa com os dados do IP>)
@raise VlanNotFoundError: VLAN não cadastrada.
@raise VlanError: Falha ao pesquisar a VLAN.
@raise EquipamentoNotFoundError: Equipamento não cadastrado.
@raise EquipamentoError: Falha ao pesquisar o Equipamento.
@raise IpNotAvailableError: Não existe um IP disponível para a VLAN.
@raise IpError: Falha ao inserir no banco de dados.
@raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.
"""
log = logging.getLogger('insert_ip')
equip_id = ip_map.get('id_equipamento')
if not is_valid_int_greater_zero_param(equip_id):
log.error(
u'The equip_id parameter is not a valid value: %s.', equip_id)
raise InvalidValueError(None, 'equip_id', equip_id)
else:
equip_id = int(equip_id)
if not has_perm(user,
AdminPermission.IPS,
AdminPermission.WRITE_OPERATION,
None,
equip_id,
AdminPermission.EQUIP_WRITE_OPERATION):
raise UserNotAuthorizedError(
None, u'Usuário não tem permissão para executar a operação.')
vlan_id = ip_map.get('id_vlan')
if not is_valid_int_greater_zero_param(vlan_id):
log.error(u'The vlan_id parameter is not a valid value: %s.', vlan_id)
raise InvalidValueError(None, 'vlan_id', vlan_id)
else:
vlan_id = int(vlan_id)
desc_ip = ip_map.get('descricao')
if desc_ip is not None:
if not is_valid_string_maxsize(desc_ip, 100) or not is_valid_string_minsize(desc_ip, 3):
log.error(u'Parameter desc_ip is invalid. Value: %s.', desc_ip)
raise InvalidValueError(None, 'desc_ip', desc_ip)
ip = Ip()
ip.descricao = desc_ip
ip.create(user, equip_id, vlan_id, False)
ip_map = dict()
ip_map['id'] = ip.id
ip_map['id_redeipv4'] = ip.networkipv4.id
ip_map['oct4'] = ip.oct4
ip_map['oct3'] = ip.oct3
ip_map['oct2'] = ip.oct2
ip_map['oct1'] = ip.oct1
ip_map['descricao'] = ip.descricao
return 0, ip_map
def insert_ip_equipment(ip_id, equip_id, user):
"""Insere o relacionamento entre o IP e o equipamento.
@param ip_id: Identificador do IP.
@param equip_id: Identificador do equipamento.
@param user: Usuário autenticado.
@return: O ip_equipamento criado.
@raise IpError: Falha ao inserir.
@raise EquipamentoNotFoundError: Equipamento não cadastrado.
@raise IpNotFoundError: Ip não cadastrado.
@raise IpEquipamentoDuplicatedError: IP já cadastrado para o equipamento.
@raise EquipamentoError: Falha ao pesquisar o equipamento.
@raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.
"""
if not has_perm(user,
AdminPermission.IPS,
AdminPermission.WRITE_OPERATION,
None,
equip_id,
AdminPermission.EQUIP_WRITE_OPERATION):
raise UserNotAuthorizedError(
None, u'Usuário não tem permissão para executar a operação.')
ip_equipment = IpEquipamento()
ip_equipment.create(user, ip_id, equip_id)
return ip_equipment
def remove_ip_equipment(ip_id, equipment_id, user):
""" Remove o relacionamento entre um ip e um equipamento.
@param ip_id: Identificador do IP.
@param equipment_id: Identificador do equipamento.
@param user: Usuário autenticado.
@return: Nothing.
@raise IpEquipmentNotFoundError: Relacionamento não cadastrado.
@raise IpEquipCantDissociateFromVip: Equip is the last balancer in a created Vip Request, the relationship cannot be removed.
@raise EquipamentoNotFoundError: Equipamento não cadastrado.
@raise IpError, GrupoError: Falha na pesquisa dos dados ou na operação de remover.
@raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.
"""
if not has_perm(user,
AdminPermission.IPS,
AdminPermission.WRITE_OPERATION,
None,
equipment_id,
AdminPermission.EQUIP_WRITE_OPERATION):
raise UserNotAuthorizedError(
None, u'Usuário não tem permissão para executar a operação.')
IpEquipamento().remove(user, ip_id, equipment_id)
return
class IpResource(RestResource):
log = logging.getLogger('IpResource')
def handle_put(self, request, user, *args, **kwargs):
"""Trata as requisições de PUT para inserir o relacionamento entre IP e Equipamento.
URL: ip/<id_ip>/equipamento/<id_equipamento>/$
"""
try:
ip_id = kwargs.get('id_ip')
equip_id = kwargs.get('id_equipamento')
if not is_valid_int_greater_zero_param(ip_id):
self.log.error(
u'The ip_id parameter is not a valid value: %s.', ip_id)
raise InvalidValueError(None, 'ip_id', ip_id)
if not is_valid_int_greater_zero_param(equip_id):
self.log.error(
u'The equip_id parameter is not a valid value: %s.', equip_id)
raise InvalidValueError(None, 'equip_id', equip_id)
Ip.get_by_pk(ip_id)
with distributedlock(LOCK_IP_EQUIPMENT % (ip_id, equip_id)):
ip_equipment = insert_ip_equipment(ip_id, equip_id, user)
ipequipamento_map = dict()
ipequipamento_map['id'] = ip_equipment.id
map = dict()
map['ip_equipamento'] = ipequipamento_map
return self.response(dumps_networkapi(map))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except IpNotFoundError:
return self.response_error(119)
except EquipamentoNotFoundError:
return self.response_error(117, equip_id)
except IpEquipamentoDuplicatedError:
return self.response_error(120)
except UserNotAuthorizedError:
return self.not_authorized()
except (IpError, EquipamentoError, GrupoError):
return self.response_error(1)
def handle_post(self, request, user, *args, **kwargs):
"""Trata as requisições de POST para inserir um IP e associá-lo a um equipamento.
URL: ip/
"""
try:
xml_map, attrs_map = loads(request.raw_post_data)
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisição.')
return self.response_error(3, x)
networkapi_map = xml_map.get('networkapi')
if networkapi_map is None:
return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.')
ip_map = networkapi_map.get('ip')
if ip_map is None:
return self.response_error(3, u'Não existe valor para a tag ip do XML de requisição.')
try:
response = insert_ip(ip_map, user)
if response[0] == 0:
return self.response(dumps_networkapi({'ip': response[1]}))
else:
return self.response_error(response[0])
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except VlanNotFoundError:
return self.response_error(116)
except NetworkIPv4NotFoundError, e:
return self.response_error(281)
except EquipamentoNotFoundError:
return self.response_error(117, ip_map.get('id_equipamento'))
except IpNotAvailableError, e:
return self.response_error(150, e.message)
except UserNotAuthorizedError:
return self.not_authorized()
except (IpError, VlanError, EquipamentoError, GrupoError), e:
return self.response_error(1, e)
except Exception, e:
return self.response_error(1, e)
def handle_delete(self, request, user, *args, **kwargs):
"""Treat DELETE requests to remove IP and Equipment relationship.
URL: ip/<id_ip>/equipamento/<id_equipamento>/$
"""
try:
ip_id = kwargs.get('id_ip')
equip_id = kwargs.get('id_equipamento')
if not is_valid_int_greater_zero_param(ip_id):
self.log.error(
u'The ip_id parameter is not a valid value: %s.', ip_id)
raise InvalidValueError(None, 'ip_id', ip_id)
if not is_valid_int_greater_zero_param(equip_id):
self.log.error(
u'The equip_id parameter is not a valid value: %s.', equip_id)
raise InvalidValueError(None, 'equip_id', equip_id)
Ip.get_by_pk(ip_id)
Equipamento.get_by_pk(equip_id)
with distributedlock(LOCK_IP_EQUIPMENT % (ip_id, equip_id)):
ipv4 = Ip.get_by_pk(ip_id)
equipament = Equipamento.get_by_pk(equip_id)
# Delete vlan's cache
destroy_cache_function([ipv4])
# delete equipment's cache
destroy_cache_function([equip_id], True)
server_pool_member_list = ServerPoolMember.objects.filter(
ip=ipv4)
if server_pool_member_list.count() != 0:
# IP associated with Server Pool
server_pool_name_list = set()
for member in server_pool_member_list:
item = '{}: {}'.format(
member.server_pool.id, member.server_pool.identifier)
server_pool_name_list.add(item)
server_pool_name_list = list(server_pool_name_list)
server_pool_identifiers = ', '.join(server_pool_name_list)
raise IpCantRemoveFromServerPool({'ip': mount_ipv4_string(ipv4), 'equip_name': equipament.nome, 'server_pool_identifiers': server_pool_identifiers},
'Ipv4 não pode ser disassociado do equipamento %s porque ele está sendo utilizando nos Server Pools (id:identifier) %s' % (equipament.nome, server_pool_identifiers))
remove_ip_equipment(ip_id, equip_id, user)
return self.response(dumps_networkapi({}))
except IpCantRemoveFromServerPool, e:
return self.response_error(385, e.cause.get('ip'), e.cause.get('equip_name'), e.cause.get('server_pool_identifiers'))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
except EquipamentoNotFoundError, e:
return self.response_error(117, e.message)
except IpEquipmentNotFoundError:
return self.response_error(118, ip_id, equip_id)
except IpNotFoundError:
return self.response_error(119)
except IpCantBeRemovedFromVip, e:
return self.response_error(319, 'ip', 'ipv4', ip_id)
except IpEquipCantDissociateFromVip, e:
return self.response_error(352, e.cause['ip'], e.cause['equip_name'], e.cause['vip_id'])
except UserNotAuthorizedError:
return self.not_authorized()
except (IpError, GrupoError, EquipamentoError, IntegrityError), e:
if isinstance(e.cause, IntegrityError):
# IP associated VIP
self.log.error(u'Failed to update the request vip.')
return self.response_error(354, ip_id)
else:
return self.response_error(1)
def handle_get(self, request, user, *args, **kwargs):
"""Treat requests GET to verify that the IP belongs to environment.
URLs: /ip/x1.x2.x3.x4/ambiente/<id_amb>
URLs: /ip/<ip>/ambiente/<id_amb>
"""
self.log.info('GET to verify that the IP belongs to environment')
try:
# User permission
if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION):
self.log.error(
u'User does not have permission to perform the operation.')
return self.not_authorized()
environment_id = kwargs.get('id_amb')
# Valid Environment ID
if not is_valid_int_greater_zero_param(environment_id):
self.log.error(
u'The id_environment parameter is not a valid value: %s.', environment_id)
raise InvalidValueError(None, 'id_environment', environment_id)
ip = kwargs.get('ip')
# Valid IP
if not is_valid_ipv4(ip):
self.log.error(u'Parameter ip is invalid. Value: %s.', ip)
raise InvalidValueError(None, 'ip', ip)
# Find Environment by ID to | |
# -*- coding: utf-8 -*-
"""
pyte.streams
~~~~~~~~~~~~
This module provides three stream implementations with different
features; for starters, here's a quick example of how streams are
typically used:
>>> import pyte
>>>
>>> class Dummy(object):
... def __init__(self):
... self.y = 0
...
... def cursor_up(self, count=None):
... self.y += count or 1
...
>>> dummy = Dummy()
>>> stream = pyte.Stream()
>>> stream.attach(dummy)
>>> stream.feed(u"\u001B[5A") # Move the cursor up 5 rows.
>>> dummy.y
5
:copyright: (c) 2011-2013 by Selectel, see AUTHORS for details.
:license: LGPL, see LICENSE for more details.
"""
from __future__ import absolute_import, unicode_literals
import os
import codecs
import sys
from . import control as ctrl, escape as esc
if sys.version_info[0] == 2:
str = unicode
class Stream(object):
"""A stream is a state machine that parses a stream of characters
and dispatches events based on what it sees.
.. note::
Stream only accepts strings as input, but if, for some reason,
you need to feed it with bytes, consider using
:class:`~pyte.streams.ByteStream` instead.
.. seealso::
`man console_codes <http://linux.die.net/man/4/console_codes>`_
For details on console codes listed bellow in :attr:`basic`,
:attr:`escape`, :attr:`csi`, :attr:`sharp` and :attr:`percent`.
"""
#: Control sequences, which don't require any arguments.
basic = {
ctrl.BEL: "bell",
ctrl.BS: "backspace",
ctrl.HT: "tab",
ctrl.LF: "linefeed",
ctrl.VT: "linefeed",
ctrl.FF: "linefeed",
ctrl.CR: "carriage_return",
ctrl.SO: "shift_out",
ctrl.SI: "shift_in",
}
#: non-CSI escape sequences.
escape = {
esc.RIS: "reset",
esc.IND: "index",
esc.NEL: "linefeed",
esc.RI: "reverse_index",
esc.HTS: "set_tab_stop",
esc.DECSC: "save_cursor",
esc.DECRC: "restore_cursor",
}
#: "sharp" escape sequences -- ``ESC # <N>``.
sharp = {
esc.DECALN: "alignment_display",
}
#: "percent" escape sequences (Linux sequence to select character
# set) -- ``ESC % <C>``.
percent = {
esc.DEFAULT: "charset_default",
esc.UTF8: "charset_utf8",
esc.UTF8_OBSOLETE: "charset_utf8",
}
#: CSI escape sequences -- ``CSI P1;P2;...;Pn <fn>``.
csi = {
esc.ICH: "insert_characters",
esc.CUU: "cursor_up",
esc.CUD: "cursor_down",
esc.CUF: "cursor_forward",
esc.CUB: "cursor_back",
esc.CNL: "cursor_down1",
esc.CPL: "cursor_up1",
esc.CHA: "cursor_to_column",
esc.CUP: "cursor_position",
esc.ED: "erase_in_display",
esc.EL: "erase_in_line",
esc.IL: "insert_lines",
esc.DL: "delete_lines",
esc.DCH: "delete_characters",
esc.ECH: "erase_characters",
esc.HPR: "cursor_forward",
esc.VPA: "cursor_to_line",
esc.VPR: "cursor_down",
esc.HVP: "cursor_position",
esc.TBC: "clear_tab_stop",
esc.SM: "set_mode",
esc.RM: "reset_mode",
esc.SGR: "select_graphic_rendition",
esc.DECSTBM: "set_margins",
esc.HPA: "cursor_to_column"
}
def __init__(self):
self.handlers = {
"stream": self._stream,
"escape": self._escape,
"arguments": self._arguments,
"sharp": self._sharp,
"percent": self._percent,
"charset": self._charset
}
self.listeners = []
self.reset()
def reset(self):
"""Reset state to ``"stream"`` and empty parameter attributes."""
self.state = "stream"
self.flags = {}
self.params = []
self.current = ""
def consume(self, char):
"""Consumes a single string character and advance the state as
necessary.
:param str char: a character to consume.
"""
if not isinstance(char, str):
raise TypeError("%s requires str input" % self.__class__.__name__)
try:
self.handlers.get(self.state)(char)
except TypeError:
pass
except KeyError:
if __debug__:
self.flags["state"] = self.state
self.flags["unhandled"] = char
self.dispatch("debug", *self.params)
self.reset()
else:
raise
def feed(self, chars):
"""Consumes a string and advance the state as necessary.
:param str chars: a string to feed from.
"""
if not isinstance(chars, str):
raise TypeError("%s requires text input" % self.__class__.__name__)
for char in chars:
self.consume(char)
def attach(self, screen, only=()):
"""Adds a given screen to the listeners queue.
:param pyte.screens.Screen screen: a screen to attach to.
:param list only: a list of events you want to dispatch to a
given screen (empty by default, which means
-- dispatch all events).
"""
self.listeners.append((screen, set(only)))
def detach(self, screen):
"""Removes a given screen from the listeners queue and failes
silently if it's not attached.
:param pyte.screens.Screen screen: a screen to detach.
"""
for idx, (listener, _) in enumerate(self.listeners):
if screen is listener:
self.listeners.pop(idx)
def dispatch(self, event, *args, **kwargs):
"""Dispatches an event.
Event handlers are looked up implicitly in the listeners'
``__dict__``, so, if a listener only wants to handle ``DRAW``
events it should define a ``draw()`` method or pass
``only=["draw"]`` argument to :meth:`attach`.
.. warning::
If any of the attached listeners throws an exception, the
subsequent callbacks are be aborted.
:param str event: event to dispatch.
:param list args: arguments to pass to event handlers.
"""
for listener, only in self.listeners:
if only and event not in only:
continue
try:
handler = getattr(listener, event)
except AttributeError:
continue
if hasattr(listener, "__before__"):
listener.__before__(event)
handler(*args, **self.flags)
if hasattr(listener, "__after__"):
listener.__after__(event)
else:
if kwargs.get("reset", True):
self.reset()
# State transformers.
# ...................
def _stream(self, char):
"""Processes a character when in the default ``"stream"`` state."""
if char in self.basic:
self.dispatch(self.basic[char])
elif char == ctrl.ESC:
self.state = "escape"
elif char == ctrl.CSI:
self.state = "arguments"
elif char not in [ctrl.NUL, ctrl.DEL]:
self.dispatch("draw", char)
def _escape(self, char):
"""Handles characters seen when in an escape sequence.
Most non-VT52 commands start with a left-bracket after the
escape and then a stream of parameters and a command; with
a single notable exception -- :data:`escape.DECOM` sequence,
which starts with a sharp.
.. versionchanged:: 0.4.10
For compatibility with Linux terminal stream also recognizes
``ESC % C`` sequences for selecting control character set.
However, in the current version these are no-op.
"""
if char == "#":
self.state = "sharp"
elif char == "%":
self.state = "percent"
elif char == "[":
self.state = "arguments"
elif char in "()":
self.state = "charset"
self.flags["mode"] = char
else:
self.dispatch(self.escape[char])
def _sharp(self, char):
"""Parses arguments of a `"#"` sequence."""
self.dispatch(self.sharp[char])
def _percent(self, char):
"""Parses arguments of a `"%"` sequence."""
self.dispatch(self.percent[char])
def _charset(self, char):
"""Parses ``G0`` or ``G1`` charset code."""
self.dispatch("set_charset", char)
def _arguments(self, char):
"""Parses arguments of an escape sequence.
All parameters are unsigned, positive decimal integers, with
the most significant digit sent first. Any parameter greater
than 9999 is set to 9999. If you do not specify a value, a 0
value is assumed.
.. seealso::
`VT102 User Guide <http://vt100.net/docs/vt102-ug/>`_
For details on the formatting of escape arguments.
`VT220 Programmer Reference <http://http://vt100.net/docs/vt220-rm/>`_
For details on the characters valid for use as arguments.
"""
if char == "?":
self.flags["private"] = True
elif char in [ctrl.BEL, ctrl.BS, ctrl.HT, ctrl.LF, ctrl.VT,
ctrl.FF, ctrl.CR]:
# Not sure why, but those seem to be allowed between CSI
# sequence arguments.
self.dispatch(self.basic[char], reset=False)
elif char == ctrl.SP:
pass
elif char in [ctrl.CAN, ctrl.SUB]:
# If CAN or SUB is received during a sequence, the current
# sequence is aborted; terminal displays the substitute
# character, followed by characters in the sequence received
# after CAN or SUB.
self.dispatch("draw", char)
self.state = "stream"
elif char.isdigit():
self.current += char
else:
self.params.append(min(int(self.current or 0), 9999))
if char == ";":
self.current = ""
else:
self.dispatch(self.csi[char], *self.params)
class ByteStream(Stream):
"""A stream, which takes bytes (instead of strings) as input
and tries to decode them using a given list of possible encodings.
It uses :class:`codecs.IncrementalDecoder` internally, so broken
bytes are not an issue.
By default, the following decoding strategy is used:
* First, try strict ``"utf-8"``, proceed if received and
:exc:`UnicodeDecodeError` ...
* Try strict ``"cp437"``, failed? move on ...
* Use ``"utf-8"`` with invalid bytes replaced -- this one will
always succeed.
>>> stream = ByteStream()
>>> stream.feed(b"foo".decode("utf-8"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pyte/streams.py", line 323, in feed
"%s requires input in bytes" % self.__class__.__name__)
TypeError: ByteStream requires input in bytes
>>> stream.feed(b"foo")
:param list encodings: a list of ``(encoding, errors)`` pairs,
where the first element is encoding name,
ex: ``"utf-8"`` and second defines how
decoding errors should be handeld; see
:meth:`str.decode` for possible values.
"""
def __init__(self, encodings=None):
encodings = encodings or [
("utf-8", "strict"),
("cp437", "strict"),
("utf-8", "replace")
]
self.buffer = b"", 0
self.decoders = [codecs.getincrementaldecoder(encoding)(errors)
for encoding, errors in encodings]
super(ByteStream, self).__init__()
def feed(self, chars):
if not isinstance(chars, bytes):
raise TypeError(
"%s requires input in bytes" % self.__class__.__name__)
for decoder in self.decoders:
decoder.setstate(self.buffer)
try:
chars = decoder.decode(chars)
except UnicodeDecodeError:
continue
self.buffer = decoder.getstate()
return super(ByteStream, self).feed(chars)
else:
raise
class DebugStream(ByteStream):
r"""Stream, which dumps a subset of the dispatched events to a given
file-like object (:data:`sys.stdout` by default).
>>> stream = DebugStream()
>>> stream.feed("\x1b[1;24r\x1b[4l\x1b[24;1H\x1b[0;10m")
SET_MARGINS 1; 24
RESET_MODE 4
CURSOR_POSITION 24; 1
SELECT_GRAPHIC_RENDITION 0; 10
:param file to: a file-like object to write debug information to.
:param list only: a list of events you want to | |
<filename>arraytool/documentation/examples/examples.py
#! /usr/bin/env python
# Author: <NAME> (srinivas . zinka [at] gmail . com)
# Copyright (c) 2011 <NAME>
# License: New BSD License.
def at_import_ex():
"""
:func:`at_import() <planar.at_import>` is a simple function to import CSV
text files as Numpy ndarrays. This will open a simple GUI dialog box asking
for the place where your CSV file is located::
import arraytool.planar as planar
planar.at_import()
"""
planar.at_import()
def at_export_ex():
"""
Similarly, :func:`at_export() <planar.at_export>` can be used to export any
Numpy ndarray data to a CSV file. This will open a simple GUI dialog box
asking for the location where the CSV file needs to be saved::
import arraytool.planar as planar
planar.at_export()
"""
planar.at_export()
def ip_format_ex():
"""
One way to generate Arraytool's input format is to use the function :func:`ip_format() <planar.ip_format>`::
import arraytool.planar as planar
import numpy as np
# Array lattice parameters (a & b are normalized with respect to the wavelength)
a = 0.5 # separation between the elements along x-axis
b = 0.7 # separation between the elements along y-axis
gamma = np.pi / 2 # lattice angle in radians
# Array Excitation information
M = 1 # no. of elements along x-axis
N = 11 # no. of elements along y-axis
A = np.ones((N, M)) # A simple uniform planar excitation
# Generating Arraytool input format
array_ip = planar.ip_format(a, b, A, gamma)
print array_ip
In the above coding, matrix A represents the planar array arrangement which is
shown below.
To be done!
Also, if needed, one can plot the array excitation using the option ``plot`` of
:func:`ip_format() <planar.ip_format>`. If the array is linear (either along x or y axis), a 2D plot
is generated using `Matplotlib`. If the given array is planar, a 3D stem plot is
generated using `Mayavi`. Two such simple plots are shown below.
To be done!
Another way is, to simply make a CSV file in the below format and and import it
using the function :func:`at_import() <planar.at_import>`.
"""
# Array lattice parameters (a & b are normalized with respect to the wavelength)
a = 0.5 # separation between the elements along x-axis
b = 0.7 # separation between the elements along y-axis
gamma = np.pi / 2 # lattice angle in radians
# Array Excitation information
M = 1 # no. of elements along x-axis
N = 11 # no. of elements along y-axis
A = np.ones((N, M)) # A simple uniform planar excitation
# Generating Arraytool input format
array_ip = planar.ip_format(a, b, A, gamma)
print(array_ip)
def AF_zeros_ex():
"""
Array factor of a `linear discrete` array (neglecting any normalization factor)
is defined as
.. math::
AF(u) = \sum_{m=1}^{M}\ [A_{m}\exp(jk_{0}ux_{m}].
Some of the array factor properties, assuming that the array elements are `uniformly
placed`, are given as:
- Array factor :math:`AF\left(u\\right)` is a periodic function in the
:math:`u` - domain with a period of :math:`\lambda/a`, where :math:`a` is the
separation between elements.
- Since :math:`AF\left(u\\right)` is a polynomial of the order :math:`M-1` in
:math:`\exp(jk_{0}ua)`, if we know :math:`M-1` zeros of the array factor
(with in a period), we can easily evaluate all the array coefficients :math:`A_m`.
In addition, in most of the cases (except shaped beam synthesis, etc), these
zeros are symmetrically located on the :math:`u` axis. So, in symmetric cases,
we need only :math:`\mathrm{ceil}\left[(M-1)/2\\right)]` zeros. If the pattern
is a difference pattern, then zero at the origin also should be taken into
consideration.
In Arraytool, the function :func:`AF_zeros() <planar.AF_zeros>` provides these :math:`\mathrm{ceil}\left[(M-1)/2\\right)]`
zeros. So, let us get the array factor zeros for some simple array excitations::
import arraytool.planar as planar
a = 0.5 # separation between the elements along x-axis (normalized WRS wavelength)
M = 10 # no. of elements along x-axis
SLR = 25 # side-lobe ratio in dB
R = 10 ** (SLR / 20) # converting SLR from dB scale to linear scale
U0 = planar.AF_zeros(a, M, R, dist_type="Dolph-Chebyshev")
print 'arrayfactor zeros:', '\\n', U0
The output is as shown below::
>>> arrayfactor zeros:
array([[ 0.2348126 ],
[ 0.38767709],
[ 0.58329742],
[ 0.78998547]])
"""
a = 0.5 # separation between the elements along x-axis (normalized WRS wavelength)
M = 10 # no. of elements along x-axis
SLR = 25 # side-lobe ratio in dB
R = 10 ** (SLR / 20) # converting SLR from dB scale to linear scale
U0 = planar.AF_zeros(a, M, R, dist_type="Dolph-Chebyshev")
print('arrayfactor zeros:', '\n', U0)
def A_frm_zeros_ex():
"""
In the previous section we obtained the array factor zeros. Now, we can use those
zeros to obtain the array excitation using the function :func:`A_frm_zeros() <planar.A_frm_zeros>` as
shown below::
import arraytool.planar as planar
a = 0.5 # separation between the elements along x-axis (normalized WRS wavelength)
M = 10 # no. of elements along x-axis
SLR = 25 # side-lobe ratio in dB
R = 10 ** (SLR / 20) # converting SLR from dB scale to linear scale
U0 = planar.AF_zeros(a, M, R, dist_type="Dolph-Chebyshev")
A = planar.A_frm_zeros(U0, a, M, symmetry="even").T # finding excitation coefficients
print 'array coefficients:', '\\n', A.T
The output is as shown below::
>>> array coefficients:
array([[ 0.64163439],
[ 0.59442917],
[ 0.77799478],
[ 0.921367 ],
[ 1. ],
[ 1. ],
[ 0.921367 ],
[ 0.77799478],
[ 0.59442917],
[ 0.64163439]])
As can be seen above, array coefficients at the center are normalized to the value 1.
"""
a = 0.5 # separation between the elements along x-axis (normalized WRS wavelength)
M = 10 # no. of elements along x-axis
SLR = 25 # side-lobe ratio in dB
R = 10 ** (SLR / 20) # converting SLR from dB scale to linear scale
U0 = planar.AF_zeros(a, M, R, dist_type="Dolph-Chebyshev")
A = planar.A_frm_zeros(U0, a, M, symmetry="even").T # finding excitation coefficients
print('array coefficients:', '\n', A.T)
def dist_ex():
"""
Most of the times, we don't have to go through the process given in the last
two sections. Instead, we can get the excitation values in one single step using
the function :func:`dist() <planar.dist>`. This function gives array excitation coefficients
corresponding to various array distribution types such as Dolph-Chebyshev,
McNamara-Zolotarev-sum, McNamara-Zolotarev-diff-f, McNamara-Zolotarev-diff-s,
Taylor, Bayliss, Pritchard-Chebyshev-be, Pritchard-Chebyshev-ue, etc. A simple
example to obtain Taylor n-bar (also known as `Villeneuve`) distribution is shown below::
import arraytool.planar as planar
a = 0.5 # separation between the elements along x-axis (normalized WRS wavelength)
M = 10 # no. of elements along x-axis
SLR = 25 # side-lobe ratio in dB
R = 10 ** (SLR / 20) # converting SLR from dB scale to linear scale
A = planar.dist(a, M, R, dist_type_x="Taylor", mbar=2, alpha_x=0)
print 'array coefficients:', '\\n', A.T
The output is as shown below::
>>> array coefficients:
array([[ 0.52917308],
[ 0.61909302],
[ 0.76458654],
[ 0.91008006],
[ 1. ],
[ 1. ],
[ 0.91008006],
[ 0.76458654],
[ 0.61909302],
[ 0.52917308]])
.. note::
However, the function :func:`dist() <planar.dist>` will not provide any information regarding the
array factor zeros. If this information is necessary, for the time being, there
is no other option but to use the function :func:`AF_zeros() <planar.AF_zeros>`
"""
a = 0.5 # separation between the elements along x-axis (normalized WRS wavelength)
M = 10 # no. of elements along x-axis
SLR = 25 # side-lobe ratio in dB
R = 10 ** (SLR / 20) # converting SLR from dB scale to linear scale
A = planar.dist(a, M, R, dist_type_x="Taylor", mbar=2, alpha_x=0)
print('array coefficients:', '\n', A.T)
def pattern_u_ex():
"""
Obviously, the most important task in array analysis and design is to plot the actual
array factor. In order to accomplish this | |
# -*- coding: utf-8 -*-
import os
import dash_core_components as dcc
import dash_html_components as html
from dash_docs.tutorial.components import Example, Syntax
from dash_docs import tools
from dash_docs import reusable_components
def get_example_name(path):
"""Returns the name of an example given its path."""
# name is the filename without the suffix
return os.path.splitext(os.path.basename(path))[0]
examples = {get_example_name(path): tools.load_example(path) for path in
['tutorial/examples/faqs/last_clicked_button.py']}
layout = html.Div([
reusable_components.Markdown('''
# FAQs and Gotchas
<blockquote>
This is the 7th and final chapter of the essential
<dccLink children="Dash Tutorial" href="/"/>.
The <dccLink children="previous chapter" href="/sharing-data-between-callbacks"/>
described how to share data between callbacks.
The <dccLink children="rest of the Dash documentation" href="/"/>
covers other topics like multi-page apps and component libraries.
</blockquote>
## Frequently Asked Questions
**Q:** *How can I customize the appearance of my Dash app?*
**A:** Dash apps are rendered in the browser as modern standards-compliant
web apps. This means that you can use CSS to style your Dash app as you
would standard HTML.
All `dash-html-components` support inline CSS styling through a `style`
attribute. An external CSS stylesheet can also be used to style
`dash-html-components` and `dash-core-components` by targeting the ID or
class names of your components. Both `dash-html-components` and
`dash-core-components` accept the attribute `className`, which corresponds
to the HTML element attribute `class`.
The <dccLink children="Dash HTML Components" href="/dash-html-components"/>
section in the Dash User
Guide explains how to supply `dash-html-components` with both inline
styles and CSS class names that you can target with CSS style sheets. The
<dccLink children="Adding CSS & JS and Overriding the Page-Load
Template" href="/external-resources"/> section in the Dash Guide explains how you
can link your own style sheets to Dash apps.
------------------------
**Q:** *How can I add JavaScript to my Dash app?*
**A:** You can add your own scripts to your Dash app, just like you would
add a JavaScript file to an HTML document. See the <dccLink children="Adding CSS & JS and
Overriding the Page-Load Template" href="/external-resources"/> section in the
Dash Guide.
------------------------
**Q:** *Can I make a Dash app with multiple pages?*
**A:** Yes! Dash has support for multi-page apps. See the <dccLink children="Multi-Page Apps
and URL Support" href="/urls"/> section in the Dash User Guide.
------------------------
**Q:** *How I can I organise my Dash app into multiple files?*
**A:** A strategy for doing this can be found in the <dccLink children="Multi-Page Apps
and URL Support" href="/urls"/> section in the Dash User Guide.
------------------------
**Q:** *How do I determine which `Input` has changed?*
**A:** *New in v0.38.0!* In addition to event properties like `n_clicks`
that change whenever an event happens (in this case a click), there is a
global variable `dash.callback_context`, available only inside a callback.
It has properties:
- `triggered`: list of changed properties. This will be empty on initial
load, unless an `Input` prop got its value from another initial callback.
After a user action it is a length-1 list, unless two properties of a
single component update simultaneously, such as a value and a timestamp
or event counter.
- `inputs` and `states`: allow you to access the callback params
by id and prop instead of through the function args. These have the form
of dictionaries `{ 'component_id.prop_name': value }`
Here's an example of how this can be done:'''),
Syntax(examples['last_clicked_button'][0]),
Example(examples['last_clicked_button'][1]),
reusable_components.Markdown('''
Prior to v0.38.0, you needed to compare timestamp properties like
`n_clicks_timestamp` to find the most recent click. While existing uses of
`*_timestamp` continue to work for now, this approach is deprecated, and
may be removed in a future update. The one exception is
`modified_timestamp` from `dcc.Store`, which is safe to use, it is NOT
deprecated.
------------------------
**Q:** *Can I use Jinja2 templates with Dash?*
**A:** Jinja2 templates are rendered on the server (often in a Flask app)
before being sent to the client as HTML pages. Dash apps, on the other
hand, are rendered on the client using React. This makes these
fundamentally different approaches to displaying HTML in a browser, which
means the two approaches can't be combined directly. You can however
integrate a Dash app with an existing Flask app such that the Flask app
handles some URL endpoints, while your Dash app lives at a specific
URL endpoint.
------------------------
**Q:** *Can I use jQuery with Dash?*
**A:** For the most part, you can't. Dash uses React to render your app on
the client browser. React is fundamentally different to jQuery in that it
makes use of a virtual DOM (Document Object Model) to manage page
rendering. Since jQuery doesn't speak React's virtual DOM, you can't use
any of jQuery's DOM manipulation facilities to change the page layout,
which is frequently why one might want to use jQuery. You can however use
parts of jQuery's functionality that do not touch the DOM, such as
registering event listeners to cause a page redirect on a keystroke.
In general, if you are looking to add custom clientside behavior in your
application, we recommend encapsulating that behavior in a
<dccLink children="custom Dash component" href="/plugins"/>.
------------------------
**Q:** *Where did those cool undo and redo buttons go?*
**A:** OK, mostly we got the opposite question:
[How do I get rid of the undo/redo buttons](https://community.plot.ly/t/is-it-possible-to-hide-the-floating-toolbar/4911/10).
While this feature is neat from a technical standpoint most people don't
find it valuable in practice. As of Dash 1.0 the buttons are removed by
default, no hacky CSS tricks needed. If you want them back, use
`show_undo_redo`:
`app = Dash(show_undo_redo=True)`
------------------------
**Q:** *I have more questions! Where can I go to ask them?*
**A:** The [Dash Community forums](https://community.plot.ly/c/dash) is full
of people discussing Dash topics, helping each other with questions, and
sharing Dash creations. Jump on over and join the discussion.
## Gotchas
There are some aspects of how Dash works that can be counter-intuitive. This
can be especially true of how the callback system works. This section
outlines some common Dash gotchas that you might encounter as you start
building out more complex Dash apps. If you have read through the rest of
the <dccLink children="Dash Tutorial" href="/"/> and are encountering unexpected behaviour, this is a
good section to read through. If you still have residual questions, the
[Dash Community forums](https://community.plot.ly/c/dash) is a great place
to ask them.
### Callbacks require their `Inputs`, `States`, and `Output` to be present in the layout
By default, Dash applies validation to your callbacks, which performs checks
such as validating the types of callback arguments and checking to see
whether the specified `Input` and `Output` components actually have the
specified properties. For full validation, all components within your
callback must therefore appear in the initial layout of your app, and you
will see an error if they do not.
However, in the case of more complex Dash apps that involve dynamic
modification of the layout (such as multi-page apps), not every component
appearing in your callbacks will be included in the initial layout. You can
remove this restriction by disabling callback validation like this:
app.config.suppress_callback_exceptions = True
### Callbacks require *all* `Inputs`, `States`, and `Output` to be rendered on the page
If you have disabled callback validation in order to support dynamic
layouts, then you won't be automatically alerted to the situation where a
component within a callback is not found within a layout. In this situation,
where a component registered with a callback is missing from the layout, the
callback will fail to fire. For example, if you define a callback with only
a subset of the specified `Inputs` present in the current page layout, the
callback will simply not fire at all.
### A component/property pair can only be the `Output` of one callback
For a given component/property pair (eg `'my-graph'`, `'figure'`), it can
only be registered as the `Output` of one callback. If you want to associate
two logically separate sets of `Inputs` with the one output
component/property pair, you’ll have to bundle them up into | |
<gh_stars>0
from flask import render_template, request, redirect, url_for, abort, flash, session, g, send_from_directory
from flask.globals import session as session_obj
from flask_login import login_user, login_required, logout_user, current_user
from sqlalchemy.orm import exc
from sqlalchemy import and_
import json, os, time, smtplib, bcrypt, hashlib
from collections import OrderedDict
from app import *
from random import choice
from string import ascii_uppercase
from logger import logger
from db.samplev2 import generate_sample_db
from werkzeug.utils import secure_filename
from grader.grader import get_predicted_grade, genGrade
# General Function
def process_student_data(db_session, course_id, student_id):
course = db_session.query(Course). \
filter_by(id=course_id).one()
scores = db_session.query(Score). \
filter(Score.student_id == student_id). \
filter(Score.course_id == course_id). \
filter(Score.course_id == MaxScore.course_id). \
filter(Score.name == MaxScore.name). \
order_by(MaxScore.priority.asc()).all()
max_scores = db_session.query(MaxScore). \
filter_by(course_id=course_id). \
order_by(MaxScore.priority.asc()).all()
student = db_session.query(Student). \
filter_by(id=student_id).one()
course_total = db_session.query(MaxScore.maxscore).filter_by(course_id=course_id,
name='Total').one()[0]
average_query_unsorted = db_session.query(Score.name, func.avg(Score.score).label('Sums')). \
filter_by(course_id=course_id). \
group_by(Score.name). \
subquery()
average_query_sorted = db_session.query(average_query_unsorted.c.name,
average_query_unsorted.c.Sums.label('average')). \
filter(average_query_unsorted.c.name == MaxScore.name). \
filter(MaxScore.course_id == course_id). \
order_by(MaxScore.priority.asc()). \
all()
course_averages = OrderedDict(average_query_sorted)
# Course Average Pre processing
for key in course_averages:
course_averages[key] = round(course_averages[key], 2)
# Get Mid Term Average and Final Average
try:
course_final_average = course_averages['Total']
except KeyError:
course_final_average = 'Average Pending'
try:
course_mid_term_average = course_averages['Mid Term Total']
except KeyError:
course_mid_term_average = 'Average Pending'
logger(course_mid_term_average=course_mid_term_average,
course_final_average=course_final_average)
# Scores with Total in their score name are stripped
scores_actual_json = json.dumps(
[scores[i].score for i in range(len(scores)) if 'tal' not in str(scores[i].name).lower()])
scores_percentages = json.dumps(
[round(float(scores[i].score) * 100 / float(max_scores[i].maxscore), 2) for i in range(len(scores))
if 'tal' not in str(scores[i].name).lower()])
scores_names = json.dumps([i.name for i in scores if 'tal' not in str(i.name).lower()])
scores_distribution_percentages = json.dumps([i.maxscore for i in max_scores if 'tal' not in str(i.name).lower()])
course_averages_for_plot = json.dumps(course_averages)
return scores, \
course, \
scores_distribution_percentages, \
course_total, \
student, \
scores_names, \
scores_percentages, \
scores_actual_json, \
course_averages, \
course_averages_for_plot, \
course_mid_term_average, \
course_final_average
def get_grading(db_session, course_id):
maxscore_by_subject = db_session.query(MaxScore).filter_by(course_id=course_id).all()
score_names = [i.name for i in maxscore_by_subject]
name = score_names[-1]
maximum_scores_unsorted = db_session.query(Score.name, func.max(Score.score).label('Maxs')). \
filter_by(course_id=course_id). \
group_by(Score.name). \
subquery()
maximum_scores_sorted = db_session.query(maximum_scores_unsorted.c.name,
maximum_scores_unsorted.c.Maxs.label('Maximum')). \
filter(maximum_scores_unsorted.c.name == MaxScore.name). \
filter(MaxScore.course_id == course_id). \
order_by(MaxScore.priority.asc()). \
all()
minimum_scores_unsorted = db_session.query(Score.name, func.min(Score.score).label('Mins')). \
filter_by(course_id=course_id). \
group_by(Score.name). \
subquery()
minimum_scores_sorted = db_session.query(minimum_scores_unsorted.c.name,
minimum_scores_unsorted.c.Mins.label('Minimum')). \
filter(minimum_scores_unsorted.c.name == MaxScore.name). \
filter(MaxScore.course_id == course_id). \
order_by(MaxScore.priority.asc()). \
all()
course_total = db_session.query(MaxScore.maxscore).filter_by(course_id=course_id,
name=name).one()[0]
average_query_unsorted = db_session.query(Score.name, func.avg(Score.score).label('Sums')). \
filter_by(course_id=course_id). \
group_by(Score.name). \
subquery()
average_query_sorted = db_session.query(average_query_unsorted.c.name,
average_query_unsorted.c.Sums.label('average')). \
filter(average_query_unsorted.c.name == MaxScore.name). \
filter(MaxScore.course_id == course_id). \
order_by(MaxScore.priority.asc()). \
all()
course_averages = OrderedDict(average_query_sorted)
course_maximums = OrderedDict(maximum_scores_sorted)
course_minimums = OrderedDict(minimum_scores_sorted)
# Course Maximum Preprocessing
for key in course_maximums:
course_maximums[key] = round(course_maximums[key], 2)
try:
course_final_maximum = float(course_maximums[name])
except KeyError:
course_final_maximum = 'Maximum Pending'
# Course Minimum Preprocessing
for key in course_minimums:
course_minimums[key] = round(course_minimums[key], 2)
try:
course_final_minimum = float(course_minimums[name])
except KeyError:
course_final_minimum = 'Minimum Pending'
# Course Average Pre processing
for key in course_averages:
course_averages[key] = round(course_averages[key], 2)
# Get Mid Term Average and Final Average
try:
course_final_average = course_averages[name]
except KeyError:
course_final_average = 'Average Pending'
course_maximum, a, a_minus, b, b_minus, c, c_minus = get_predicted_grade(course_final_average, course_final_minimum,
course_final_maximum)
return course_maximum, a, a_minus, b, b_minus, c, c_minus
def get_last_column(db_session, course_id):
maxscore_by_subject = db_session.query(MaxScore).filter_by(course_id=course_id).all()
score_names = [i.name for i in maxscore_by_subject]
name = score_names[-1]
course_total = db_session.query(MaxScore.maxscore).filter_by(course_id=course_id,
name=name).one()[0]
return name, course_total
"""
Views Start Here
"""
@app.before_request
def make_session_permanent():
"""
Session timeout is defined as 15 minutes and timeout is after inactivity
"""
session.permanent = True
app.permanent_session_lifetime = datetime.timedelta(minutes=15)
session.modified = True
g.user = current_user
def login_prepocess(db_session, user_credentials):
"""
This pre processor is used to identify if a user exists in the faculty or the student table
:param db_session: Database session for the db
:param user_credentials: User credentials of the user logging in
"""
session_obj['userid'] = user_credentials.id.encode('utf-8')
session_obj['isAdmin'] = db_session.query(AuthStore.isAdmin).filter_by(id=session_obj['userid']).one()[0]
try:
session_obj['isSuper'] = db_session.query(Admin.isSuper).filter_by(id=session_obj['userid']).one()[0]
except exc.NoResultFound:
session_obj['isSuper'] = False
# Check is user is faculty or student
isStudent = False
isFaculty = False
try:
db_session.query(Student).filter_by(id=session_obj['userid']).one()
isStudent = True
except exc.NoResultFound:
pass
try:
db_session.query(Faculty).filter_by(id=session_obj['userid']).one()
isFaculty = True
except exc.NoResultFound:
pass
session_obj['isStudent'] = isStudent
session_obj['isFaculty'] = isFaculty
@app.route('/', methods=['GET', 'POST'])
def getHomePage():
if request.method == 'GET':
return render_template('homepage.html')
elif request.method == 'POST':
db_session = DBSession()
''' Password can either be an existing password or a token to be used for password resets '''
userid = request.form['bits-id'].encode('utf-8')
password = request.form['password'].encode('<PASSWORD>')
logger(userid=userid, password=password)
try:
user_credentials = db_session.query(AuthStore).filter_by(id=userid).one()
user_credential_salt = user_credentials.salt.encode('utf-8')
user_credential_phash = user_credentials.phash.encode('utf-8')
user_credential_token_hash = user_credentials.tokenHash
logger(Password=password,
Salt=user_credential_salt,
Phash_DB=user_credential_phash,
Phash_gen=bcrypt.hashpw(password, user_credential_salt))
if bcrypt.hashpw(password, user_credential_phash) == user_credential_phash:
login_user(user_credentials)
login_prepocess(db_session,
user_credentials)
return redirect(url_for('getCourses'))
elif user_credential_token_hash is not None:
sha256object = hashlib.sha256(password)
tokenHash_obtained = sha256object.hexdigest()
token_existence_time = str(db_session.query(func.now()).scalar() - user_credentials.tokenTimeStamp)
logger(tokenHash_actual=user_credential_token_hash,
tokenHash_obtain=tokenHash_obtained,
token_existence_time=token_existence_time)
# Handle token expiry and validity
if tokenHash_obtained == user_credential_token_hash:
if TOKEN_LIFETIME > token_existence_time:
login_user(user_credentials)
login_prepocess(db_session,
user_credentials)
return redirect(url_for('getDashboard'))
else:
error = "Token Expired! Get new token"
return render_template('homepage.html',
error=error)
else:
error = "Wrong username or Password!"
return render_template('homepage.html', error=error)
except exc.NoResultFound:
error = "No such user exists!"
return render_template('homepage.html', error=error)
finally:
db_session.close()
@login_required
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('getHomePage'))
@celery.task
def upload_async(upload_file_filename_secure):
"""
Celery task to upload files and populate database asynchronously
:param upload_file_filename_secure: Secure file name to load filename
:return:
"""
with app.app_context():
print "Started"
db_session = DBSession()
path = os.path.join(app.config['UPLOAD_FOLDER'], upload_file_filename_secure)
course_id, course_name_unformatted, semester, year = upload_file_filename_secure.split('_')
course_name = " ".join(course_name_unformatted.split('.'))
logger(year=year)
year, _ = year.split('.')
logger(year=year)
print "The path is: " + path
while not os.path.exists(path):
print "Waiting for file to be visible"
time.sleep(1)
if os.path.isfile(path):
print "Now the file is available"
generate_sample_db(path,
course_id,
course_name,
semester,
year,
db_session)
else:
raise ValueError("%s isn't a file!" % path)
db_session.close()
print "Finished"
@login_required
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
if session_obj['isAdmin']:
return render_template('upload.html')
else:
return redirect(url_for('getHomePage'))
elif request.method == 'POST':
if session_obj['isAdmin']:
if 'file' not in request.files:
logger(request=request)
print "No file was sent"
upload_file = request.files['file']
if upload_file.filename == '':
error = "File wasn't selected!"
print "File wasn't selected"
return render_template('upload.html', error=error)
elif upload_file and allowed_file(upload_file.filename):
upload_file_filename_secure = secure_filename(upload_file.filename)
upload_file.save(os.path.join(app.config['UPLOAD_FOLDER'], upload_file_filename_secure))
print "Uploaded file successfully"
flash('Upload Successfull!')
upload_async.delay(upload_file_filename_secure)
return redirect(url_for('upload'))
error = "Incorrect file format was chosen!"
return render_template('upload.html', error=error)
else:
print request.path
abort(400)
def download(filename):
uploads = os.path.join(app.config['UPLOAD_FOLDER'], filename)
print uploads
return send_from_directory(directory=uploads, filename=filename)
@app.route('/grade/<string:course_id>', methods=['GET', 'POST'])
@login_required
def grade(course_id):
if request.method == 'GET':
if session_obj['isAdmin']:
db_session = DBSession()
a_max, a, a_minus, b, b_minus, c, c_minus = get_grading(db_session, course_id=course_id)
course_data = db_session.query(Course).filter_by(id=course_id).one()
course_name = course_data.name
course_name = '.'.join(course_name.split(' '))
filename = course_id + '_' + course_name + '_' + course_data.semester + '_' + course_data.year + '.csv'
logger(filename=filename)
db_session.close()
return render_template('grade.html', course_id=course_id, a_max=a_max, a_min=a, a_minus_max=a,
a_minus_min=a_minus, b_max=a_minus, b_min=b, b_minus_max=b, b_minus_min=b_minus,
c_max=b_minus, c_min=c, c_minus_max=c, c_minus_min=c_minus, filename=filename)
else:
return redirect(url_for('getHomePage'))
elif request.method == 'POST':
print request.form
if session_obj['isAdmin']:
a_max = float(request.form['A_max'])
a_min = float(request.form['A_min'])
a_minus_max = float(request.form['A-_max'])
a_minus_min = float(request.form['A-_min'])
b_max = float(request.form['B_max'])
b_min = float(request.form['B_min'])
b_minus_max = float(request.form['B-_max'])
b_minus_min = float(request.form['B-_min'])
c_max = float(request.form['C_max'])
c_min = float(request.form['C_min'])
c_minus_max = float(request.form['C-_max'])
c_minus_min = float(request.form['C-_min'])
db_session = DBSession()
course_data = db_session.query(Course).filter_by(id=course_id).one()
course_name = course_data.name
course_name = '.'.join(course_name.split(' '))
filename = course_id + '_' + course_name + '_' + course_data.semester + '_' + course_data.year + '.csv'
logger(filename=filename)
name, total = get_last_column(db_session, course_id)
column = name + '-' + str(total)
genGrade(filename=filename, column=column, a_min=a_min, a_minus_min=a_minus_min, b_min=b_min,
b_minus_min=b_minus_min, c_min=c_min, db_session=db_session)
db_session.close()
uploads = os.path.join(app.config['UPLOAD_FOLDER'])
print uploads
return send_from_directory(directory=uploads, filename=filename, as_attachment=True)
else:
print request.path
abort(400)
@app.route('/courses')
@login_required
def getCourses():
db_session = DBSession()
try:
# If session is not created by an admin user then load student courses else load all courses
if not session_obj['isAdmin']:
course_ids = db_session.query(Score.course_id).filter_by(student_id=session_obj['user_id']).distinct()
courses = db_session.query(Course).filter(Course.id.in_(course_ids)).all()
return render_template('courses.html',
courses=courses,
user_id=session_obj['userid'],
admin=False, super=False)
elif session_obj['isSuper']:
courses = db_session.query(Course).all()
return render_template('courses.html',
courses=courses,
user_id=session_obj['userid'],
admin=True,
super=True)
elif session_obj['isAdmin']:
courses = db_session.query(Course).all()
return render_template('courses.html',
courses=courses,
user_id=session_obj['userid'],
admin=True,
super=False)
except exc.NoResultFound:
return render_template('courses.html')
finally:
db_session.close()
# Need this for admin only
@app.route('/courses/<string:course_id>')
@login_required
def getStudentsByCourse(course_id):
if session_obj['isAdmin']:
db_session = DBSession()
students = db_session.query(Student).filter(
and_(Student.id == Score.student_id, Score.course_id == Course.id, Course.id == course_id)).all()
db_session.close()
return render_template('students.html',
students=students,
course_id=course_id)
else:
# If not a admin raise a 404 Not Found
abort(404)
@app.route('/courses/<string:course_id>/<string:student_id>')
@login_required
def getScoresByStudent(course_id, student_id):
db_session = DBSession()
scores, \
course, \
scores_distribution_percentages, \
course_total, \
student, \
scores_names, \
scores_percentages, \
scores_actual_json, \
course_averages, \
course_averages_for_plot, \
course_mid_term_average, course_final_average = process_student_data(db_session, course_id, student_id)
db_session.close()
return render_template('studentScore.html',
scores=scores,
course=course,
max_scores=scores_distribution_percentages,
course_total=course_total,
student=student,
x_=scores_names,
y_percentages=scores_percentages,
y_actual=scores_actual_json,
course_averages=course_averages,
course_averages_for_plot=course_averages_for_plot,
course_mid_term_average=course_mid_term_average,
course_final_average=course_final_average,
isAdmin=session_obj['isAdmin'])
@app.route('/predictions')
@login_required
def getPredictions():
return "<h1>Predictions</h1>"
@app.route('/admins')
@login_required
def getAllAdmins():
if request.method | |
2,
"course_project": False
},
{
"id": 35889,
"name": "Рамановское и Мандельштам-бриллюэновское рассеяния в оптических волокнах и их применение",
"term": 2,
"course_project": False
},
{
"id": 30153,
"name": "Распознавание и генерация речи",
"term": 4,
"course_project": False
},
{
"id": 26385,
"name": "Распределенные алгоритмы и системы",
"term": 2,
"course_project": False
},
{
"id": 26385,
"name": "Распределенные алгоритмы и системы",
"term": 6,
"course_project": False
},
{
"id": 32577,
"name": "Распределенные базы данных и знаний",
"term": 2,
"course_project": False
},
{
"id": 32577,
"name": "Распределенные базы данных и знаний",
"term": 2,
"course_project": True
},
{
"id": 35576,
"name": "Распределенные системы / Distributed Systems",
"term": 2,
"course_project": False
},
{
"id": 30295,
"name": "Распределенные системы хранения данных",
"term": 6,
"course_project": False
},
{
"id": 34026,
"name": "Распространение и прием радиоволн",
"term": 8,
"course_project": False
},
{
"id": 6760,
"name": "Расчет допусков на оптические элементы",
"term": 8,
"course_project": False
},
{
"id": 27394,
"name": "Расчет и автоматизация проектирования оптических систем",
"term": 2,
"course_project": False
},
{
"id": 34501,
"name": "Расчет и автоматизация проектирования оптических систем / Optical system design",
"term": 2,
"course_project": False
},
{
"id": 9703,
"name": "Расчет и конструирование динамических компрессоров",
"term": 8,
"course_project": False
},
{
"id": 8897,
"name": "Расчет и конструирование объемных компрессоров",
"term": 8,
"course_project": False
},
{
"id": 26382,
"name": "Расчет и проектирование машин и аппаратов систем жизнеобеспечения",
"term": 2,
"course_project": False
},
{
"id": 26382,
"name": "Расчет и проектирование машин и аппаратов систем жизнеобеспечения",
"term": 2,
"course_project": True
},
{
"id": 9711,
"name": "Регулирование и автоматизация криогенных машин и установок",
"term": 8,
"course_project": False
},
{
"id": 18816,
"name": "Регулирование и автоматизация машин и установок систем жизнеобеспечения",
"term": 8,
"course_project": False
},
{
"id": 34945,
"name": "Регулирование предпринимательства в сфере транспорта",
"term": 2,
"course_project": False
},
{
"id": 34366,
"name": "Регулирование разработок в сфере Life Sciences",
"term": 2,
"course_project": False
},
{
"id": 31580,
"name": "<NAME>нес-процессов",
"term": 2,
"course_project": False
},
{
"id": 9834,
"name": "<NAME> и обслуживание машин и оборудования биотехнологий",
"term": 8,
"course_project": False
},
{
"id": 31603,
"name": "Реология",
"term": 2,
"course_project": False
},
{
"id": 9772,
"name": "Реология в производстве хлебобулочных и кондитерских изделий",
"term": 8,
"course_project": False
},
{
"id": 20008,
"name": "Ресурсосберегающие технологии при переработке растительного сырья",
"term": 8,
"course_project": False
},
{
"id": 20008,
"name": "Ресурсосберегающие технологии при переработке растительного сырья",
"term": 10,
"course_project": False
},
{
"id": 30635,
"name": "Речевая культура интернет-среды",
"term": 6,
"course_project": False
},
{
"id": 1634,
"name": "Русский язык",
"term": 2,
"course_project": False
},
{
"id": 1634,
"name": "Русский язык",
"term": 4,
"course_project": False
},
{
"id": 31348,
"name": "САПР систем на кристалле",
"term": 2,
"course_project": False
},
{
"id": 7664,
"name": "<NAME> на пищевых предприятиях",
"term": 10,
"course_project": False
},
{
"id": 13268,
"name": "<NAME> на предприятиях бродильных производств",
"term": 8,
"course_project": False
},
{
"id": 13268,
"name": "<NAME> на предприятиях бродильных производств",
"term": 10,
"course_project": False
},
{
"id": 9855,
"name": "<NAME> предприятий молочной отрасли",
"term": 8,
"course_project": False
},
{
"id": 19129,
"name": "<NAME> при производстве мучных изделий",
"term": 8,
"course_project": False
},
{
"id": 19129,
"name": "<NAME> при производстве мучных изделий",
"term": 10,
"course_project": False
},
{
"id": 10389,
"name": "<NAME> при производстве хлебобулочных и кондитерских изделий",
"term": 8,
"course_project": False
},
{
"id": 29997,
"name": "Свет в искусстве и фотографии",
"term": 2,
"course_project": False
},
{
"id": 32971,
"name": "Световая культура / Light in Culture",
"term": 2,
"course_project": False
},
{
"id": 32970,
"name": "Световые устройства и системы управления / Lighting Devices and Control Systems",
"term": 2,
"course_project": False
},
{
"id": 26428,
"name": "<NAME>",
"term": 2,
"course_project": False
},
{
"id": 30157,
"name": "<NAME>ыков программирования",
"term": 4,
"course_project": False
},
{
"id": 27178,
"name": "<NAME>",
"term": 2,
"course_project": False
},
{
"id": 27178,
"name": "<NAME>",
"term": 2,
"course_project": True
},
{
"id": 30895,
"name": "<NAME>ка / Sensors photonics",
"term": 2,
"course_project": False
},
{
"id": 30895,
"name": "Сенсорная фотоника / Sensors photonics",
"term": 2,
"course_project": True
},
{
"id": 34355,
"name": "Сенсоры в робототехнических системах",
"term": 2,
"course_project": False
},
{
"id": 20842,
"name": "Сенсоры и энкодеры в задачах фотоники",
"term": 8,
"course_project": False
},
{
"id": 6952,
"name": "Сервис-ориентированная архитектура",
"term": 8,
"course_project": False
},
{
"id": 31390,
"name": "Сервисно-ориентированные интеллектуальные системы (часть 1) / Service-oriented Intelligent Systems (part 1)",
"term": 2,
"course_project": False
},
{
"id": 31393,
"name": "Сервисно-ориентированные интеллектуальные системы (часть 2) / Service-oriented Intelligent Systems (part 2)",
"term": 2,
"course_project": False
},
{
"id": 35681,
"name": "Сервисно-ориентированные интеллектуальные системы (часть 3) / Service-oriented Intelligent Systems (part 3)",
"term": 2,
"course_project": False
},
{
"id": 1401,
"name": "<NAME>",
"term": 8,
"course_project": False
},
{
"id": 6977,
"name": "Сетевое системное администрирование",
"term": 6,
"course_project": False
},
{
"id": 34403,
"name": "Сетевые технологии в системах хранения данных",
"term": 2,
"course_project": False
},
{
"id": 30296,
"name": "Сетевые технологии интернета вещей",
"term": 6,
"course_project": False
},
{
"id": 2245,
"name": "Сети ЭВМ и телекоммуникации",
"term": 6,
"course_project": False
},
{
"id": 6677,
"name": "<NAME>",
"term": 6,
"course_project": False
},
{
"id": 26444,
"name": "<NAME>п<NAME>",
"term": 2,
"course_project": False
},
{
"id": 6670,
"name": "Система менеджмента качества на предприятии",
"term": 8,
"course_project": False
},
{
"id": 27376,
"name": "Системная биология/ Systems Biology",
"term": 2,
"course_project": False
},
{
"id": 27376,
"name": "Системная биология/ Systems Biology",
"term": 2,
"course_project": True
},
{
"id": 34189,
"name": "Системная химия / System chemistry",
"term": 2,
"course_project": False
},
{
"id": 26467,
"name": "Системное администрирование",
"term": 6,
"course_project": False
},
{
"id": 16882,
"name": "Системное программирование",
"term": 6,
"course_project": False
},
{
"id": 26468,
"name": "Системное программное обеспечение",
"term": 6,
"course_project": False
},
{
"id": 26468,
"name": "Системное программное обеспечение",
"term": 6,
"course_project": True
},
{
"id": 6836,
"name": "Системное программное обеспечение защищённых инфокоммуникационных систем",
"term": 8,
"course_project": False
},
{
"id": 26456,
"name": "Системное проектирование оптико-электронных приборов и систем",
"term": 2,
"course_project": False
},
{
"id": 35671,
"name": "Системное проектирование оптико-электронных приборов и систем / Digital signal processing in optoelectronics",
"term": 2,
"course_project": False
},
{
"id": 26448,
"name": "Системный анализ и моделирование информационных процессов и систем",
"term": 2,
"course_project": False
},
{
"id": 26447,
"name": "Системный анализ и обработка информации",
"term": 2,
"course_project": False
},
{
"id": 26447,
"name": "Системный анализ и обработка информации",
"term": 2,
"course_project": True
},
{
"id": 26463,
"name": "Системный анализ и принятие решений",
"term": 4,
"course_project": False
},
{
"id": 31190,
"name": "Системный анализ территорий",
"term": 2,
"course_project": False
},
{
"id": 26459,
"name": "Системы автоматизированного проектирования",
"term": 2,
"course_project": False
},
{
"id": 26459,
"name": "Системы автоматизированного проектирования",
"term": 4,
"course_project": False
},
{
"id": 26459,
"name": "Системы автоматизированного проектирования",
"term": 6,
"course_project": False
},
{
"id": 31330,
"name": "Системы автоматизированного проектирования / Computer Aided Design",
"term": 2,
"course_project": False
},
{
"id": 26446,
"name": "Системы автоматизированного проектирования электронных схем",
"term": 2,
"course_project": False
},
{
"id": 26446,
"name": "Системы автоматизированного проектирования электронных схем",
"term": 2,
"course_project": True
},
{
"id": 32750,
"name": "Системы автоматизированного проектирования электронных схем / CAD systems for electronic circuits",
"term": 2,
"course_project": False
},
{
"id": 26476,
"name": "Системы ввода-вывода",
"term": 6,
"course_project": False
},
{
"id": 18665,
"name": "Системы ввода/вывода",
"term": 8,
"course_project": False
},
{
"id": 19033,
"name": "Системы записи и воспроизведения информации",
"term": 8,
"course_project": False
},
{
"id": 19208,
"name": "Системы и архитектуры резервного копирования и восстановления",
"term": 8,
"course_project": False
},
{
"id": 30915,
"name": "Системы инженерного анализа и компьютерного моделирования",
"term": 2,
"course_project": False
},
{
"id": 26477,
"name": "Системы искусственного интеллекта",
"term": 6,
"course_project": False
},
{
"id": 26480,
"name": "Системы компьютерного моделирования и инженерный анализ",
"term": 2,
"course_project": False
},
{
"id": 26481,
"name": "Системы компьютерной обработки изображений",
"term": 6,
"course_project": False
},
{
"id": 9882,
"name": "Системы кондиционирования",
"term": 8,
"course_project": False
},
{
"id": 18839,
"name": "Системы охлаждения и термостатирования",
"term": 8,
"course_project": False
| |
<filename>python/example_code/lambda/lambda_with_api_gateway.py
# snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
# snippet-sourcedescription:[lambda_with_api_gateway.py demonstrates how to create an AWS Lambda function and an API Gateway REST API interface.]
# snippet-service:[lambda]
# snippet-keyword:[AWS Lambda]
# snippet-keyword:[API Gateway]
# snippet-keyword:[Python]
# snippet-keyword:[Code Sample]
# snippet-sourcetype:[snippet]
# snippet-sourcedate:[2019-06-14]
# snippet-sourceauthor:[AWS]
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import json
import logging
import os
import zipfile
import zlib
import boto3
from botocore.exceptions import ClientError
import requests
def create_lambda_deployment_package(srcfile, deployment_package):
"""Create a Lambda deployment package (ZIP file)
:param srcfile: Lambda function source file
:param deployment_package: Name of generated deployment package
:return: True if deployment package created. Otherwise, False.
"""
# Create the deployment package
with zipfile.ZipFile(deployment_package, mode='w',
compression=zipfile.ZIP_DEFLATED,
compresslevel=zlib.Z_DEFAULT_COMPRESSION) as deploy_pkg:
try:
deploy_pkg.write(srcfile)
except Exception as e:
logging.error(e)
return False
return True
def get_iam_role_arn(iam_role_name):
"""Retrieve the ARN of the specified IAM role
:param iam_role_name: IAM role name
:return: If the IAM role exists, return ARN, else None
"""
# Try to retrieve information about the role
iam_client = boto3.client('iam')
try:
result = iam_client.get_role(RoleName=iam_role_name)
except ClientError as e:
logging.error(e)
return None
return result['Role']['Arn']
def iam_role_exists(iam_role_name):
"""Check if the specified IAM role exists
:param iam_role_name: IAM role name
:return: True if IAM role exists, else False
"""
# Try to retrieve information about the role
if get_iam_role_arn(iam_role_name) is None:
return False
return True
def create_iam_role_for_lambda(iam_role_name):
"""Create an IAM role to enable a Lambda function to call AWS services
:param iam_role_name: Name of IAM role
:return: ARN of IAM role. If error, returns None.
"""
# Lambda trusted relationship policy document
lambda_assume_role = {
'Version': '2012-10-17',
'Statement': [
{
'Sid': '',
'Effect': 'Allow',
'Principal': {
'Service': 'lambda.amazonaws.com'
},
'Action': 'sts:AssumeRole'
}
]
}
iam_client = boto3.client('iam')
try:
result = iam_client.create_role(RoleName=iam_role_name,
AssumeRolePolicyDocument=json.dumps(lambda_assume_role))
except ClientError as e:
logging.error(e)
return None
lambda_role_arn = result['Role']['Arn']
# Attach the AWSLambdaBasicExecutionRole policy to the role
# If planning to use AWS X-Ray, also attach the AWSXrayWriteOnlyAccess policy
lambda_policy_arn = 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
try:
iam_client.attach_role_policy(RoleName=iam_role_name,
PolicyArn=lambda_policy_arn)
except ClientError as e:
logging.error(e)
return None
# Return the ARN of the created IAM role
return lambda_role_arn
def deploy_lambda_function(name, iam_role, handler, deployment_package):
"""Deploy the Lambda function
:param name: Descriptive Lambda function name
:param iam_role: IAM Lambda role
:param handler: Name of Lambda handler function
:param deployment_package: Name of deployment package
:return: Dictionary containing information about the function, else None
"""
# Load the deployment package into memory
# Alternatively, upload it to S3
with open(deployment_package, mode='rb') as pkg:
deploy_pkg = pkg.read()
# Create the Lambda function
lambda_client = boto3.client('lambda')
try:
result = lambda_client.create_function(FunctionName=name,
Runtime='python3.7',
Role=iam_role,
Handler=handler,
Code={'ZipFile': deploy_pkg})
except ClientError as e:
logging.error(e)
return None
return result
def create_lambda_function(function_name, srcfile, handler_name, role_name):
"""Create a Lambda function
It is assumed that srcfile includes an extension, such as source.py or
source.js. The filename minus the extension is used to construct the
ZIP file deployment package, e.g., source.zip.
If the role_name exists, the existing role is used. Otherwise, an
appropriate role is created.
:param function_name: Lambda function name
:param srcfile: Lambda source file
:param handler_name: Lambda handler name
:param role_name: Lambda role name
:return: String ARN of the created Lambda function. If error, returns None.
"""
# Parse the filename and extension in srcfile
filename, _ = os.path.splitext(srcfile)
# Create a deployment package
deployment_package = f'{filename}.zip'
if not create_lambda_deployment_package(srcfile, deployment_package):
return None
# Create Lambda IAM role if necessary
if iam_role_exists(role_name):
# Retrieve its ARN
iam_role_arn = get_iam_role_arn(role_name)
else:
iam_role_arn = create_iam_role_for_lambda(role_name)
if iam_role_arn is None:
# Error creating IAM role
return None
# Deploy the Lambda function
microservice = deploy_lambda_function(function_name, iam_role_arn,
f'{filename}.{handler_name}',
deployment_package)
if microservice is None:
return None
lambda_arn = microservice['FunctionArn']
logging.info(f'Created Lambda function: {function_name}')
logging.info(f'ARN: {lambda_arn}')
return lambda_arn
def delete_lambda_function(function_name):
"""Delete all versions of a Lambda function
:param function_name: Lambda function to delete
:return: True if function was deleted, else False
"""
# Delete all versions of the Lambda function
lambda_client = boto3.client('lambda')
try:
lambda_client.delete_function(FunctionName=function_name)
except ClientError as e:
logging.error(e)
return False
return True
def invoke_lambda_function_synchronous(name, parameters):
"""Invoke a Lambda function synchronously
:param name: Lambda function name or ARN or partial ARN
:param parameters: Dict of parameters and values to pass to function
:return: Dict of response parameters and values. If error, returns None.
"""
# Convert the parameters from dict -> string -> bytes
params_bytes = json.dumps(parameters).encode()
# Invoke the Lambda function
lambda_client = boto3.client('lambda')
try:
response = lambda_client.invoke(FunctionName=name,
InvocationType='RequestResponse',
LogType='Tail',
Payload=params_bytes)
except ClientError as e:
logging.error(e)
return None
return response
def get_lambda_arn(lambda_name):
"""Retrieve the ARN of a Lambda function
:param lambda_name: Name of Lambda function
:return: String ARN of Lambda function. If error, returns None.
"""
# Retrieve information about the Lambda function
lambda_client = boto3.client('lambda')
try:
response = lambda_client.get_function(FunctionName=lambda_name)
except ClientError as e:
logging.error(e)
return None
return response['Configuration']['FunctionArn']
def create_rest_api(api_name, lambda_name):
"""Create a REST API for a Lambda function
The REST API defines a child called /example and a stage called prod.
:param api_name: Name of the REST API
:param lambda_name: Name of existing Lambda function
:return: URL of API. If error, returns None.
"""
# Specify child resource name under root and stage name
child_resource_name = 'example'
stage_name = 'prod'
# Create initial REST API
api_client = boto3.client('apigateway')
try:
result = api_client.create_rest_api(name=api_name)
except ClientError as e:
logging.error(e)
return None
api_id = result['id']
logging.info(f'Created REST API: {result["name"]}, ID: {api_id}')
# Get the ID of the API's root resource
try:
result = api_client.get_resources(restApiId=api_id)
except ClientError as e:
logging.error(e)
return None
root_id = None
for item in result['items']:
if item['path'] == '/':
root_id = item['id']
if root_id is None:
logging.error('Could not retrieve the ID of the API\'s root resource.')
return None
# Define a child resource called /example under the root resource
try:
result = api_client.create_resource(restApiId=api_id,
parentId=root_id,
pathPart=child_resource_name)
except ClientError as e:
logging.error(e)
return None
example_id = result['id']
# Define an ANY method on the /example resource
try:
api_client.put_method(restApiId=api_id,
resourceId=example_id,
httpMethod='ANY',
authorizationType='NONE')
except ClientError as e:
logging.error(e)
return None
# Set the content-type of the API's ANY method response to JSON
content_type = {'application/json': 'Empty'}
try:
api_client.put_method_response(restApiId=api_id,
resourceId=example_id,
httpMethod='ANY',
statusCode='200',
responseModels=content_type)
except ClientError as e:
logging.error(e)
return None
# Set the Lambda function as the destination for the ANY method
# Extract the Lambda region and AWS account ID from the Lambda ARN
# ARN format="arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME"
lambda_arn = get_lambda_arn(lambda_name)
if lambda_arn is None:
return None
sections = lambda_arn.split(':')
region = sections[3]
account_id = sections[4]
# Construct the Lambda function's URI
lambda_uri = f'arn:aws:apigateway:{region}:lambda:path/2015-03-31/' \
f'functions/{lambda_arn}/invocations'
try:
api_client.put_integration(restApiId=api_id,
resourceId=example_id,
httpMethod='ANY',
type='AWS',
integrationHttpMethod='POST',
uri=lambda_uri)
except ClientError as e:
logging.error(e)
return None
# Set the content-type of the Lambda function to JSON
content_type = {'application/json': ''}
try:
api_client.put_integration_response(restApiId=api_id,
resourceId=example_id,
httpMethod='ANY',
statusCode='200',
responseTemplates=content_type)
except ClientError as e:
logging.error(e)
return None
# Deploy the API
try:
api_client.create_deployment(restApiId=api_id,
stageName=stage_name)
except ClientError as e:
logging.error(e)
return None
# Grant invoke permissions on the Lambda function so it can be called by
# API Gateway.
# Note: To retrieve the Lambda function's permissions, call
# Lambda.Client.get_policy()
source_arn = f'arn:aws:execute-api:{region}:{account_id}:{api_id}/*/*/{child_resource_name}'
lambda_client = boto3.client('lambda')
try:
lambda_client.add_permission(FunctionName=lambda_name,
StatementId=f'{lambda_name}-invoke',
Action='lambda:InvokeFunction',
Principal='apigateway.amazonaws.com',
SourceArn=source_arn)
except ClientError as e:
logging.error(e)
return None
# Construct the API URL
api_url = f'https://{api_id}.execute-api.{region}.amazonaws.com/{stage_name}/{child_resource_name}'
logging.info(f'API base URL: {api_url}')
return api_url
def get_rest_api_id(api_name):
"""Retrieve the ID of an API Gateway REST API
:param api_name: Name of API Gateway REST API
:return: Retrieved API ID. If API not found or error, returns None.
"""
# Retrieve a batch of APIs
api_client = boto3.client('apigateway')
try:
apis = api_client.get_rest_apis()
except ClientError as e:
logging.error(e)
return None
# Search the batch
while True:
for api in apis['items']:
if api['name'] == api_name:
# Found | |
# This file is part of COFFEE
#
# COFFEE is Copyright (c) 2014, Imperial College London.
# Please see the AUTHORS file in the main source directory for
# a full list of copyright holders. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * The name of Imperial College London or that of other
# contributors may not be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTERS
# ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import, print_function, division
from six.moves import zip
import operator
import resource
from collections import OrderedDict
from itertools import combinations
from math import factorial as fact
from . import system
from .base import *
from .utils import *
from .scheduler import ExpressionFissioner, ZeroRemover, SSALoopMerger
from .rewriter import ExpressionRewriter
from .cse import CSEUnpicker
from .logger import warn
from coffee.visitors import Find, ProjectExpansion
from functools import reduce
class LoopOptimizer(object):
def __init__(self, loop, header, exprs):
"""Initialize the LoopOptimizer.
:param loop: root AST node of a loop nest
:param header: the kernel's top node
:param exprs: list of expressions to be optimized
"""
self.loop = loop
self.header = header
self.exprs = exprs
# Track nonzero regions accessed in each symbol
self.nz_syms = {}
# Track hoisted expressions
self.hoisted = StmtTracker()
def rewrite(self, mode):
"""Rewrite all compute-intensive expressions detected in the loop nest to
minimize the number of floating point operations performed.
:param mode: Any value in (0, 1, 2, 3, 4). Each ``mode`` corresponds to a
different expression rewriting strategy.
* mode == 0: no rewriting is performed.
* mode == 1: generalized loop-invariant code motion.
* mode == 2: apply four passes: generalized loop-invariant code motion;
expansion of inner-loop dependent expressions; factorization of
inner-loop dependent terms; generalized loop-invariant code motion.
* mode == 3: apply multiple passes; aims at pre-evaluating sub-expressions
that fully depend on reduction loops.
* mode == 4: rewrite an expression based on its sharing graph
"""
# Set a rewrite mode for each expression
for stmt, expr_info in self.exprs.items():
expr_info.mode = mode
# Analyze the individual expressions and try to select an optimal rewrite
# mode for each of them. A preliminary transformation of the loop nest may
# take place in this pass (e.g., injection)
if mode == 'auto':
self._dissect('greedy')
elif mode == 'auto-aggressive':
self._dissect('aggressive')
# Search for factorization opportunities across temporaries in the kernel
if mode > 1 and self.exprs:
self._unpick_cse()
# Expression rewriting, expressed as a sequence of AST transformation passes
for stmt, expr_info in self.exprs.items():
ew = ExpressionRewriter(stmt, expr_info, self.header, self.hoisted)
if expr_info.mode == 1:
if expr_info.dimension in [0, 1]:
ew.licm(mode='only_outlinear')
else:
ew.licm()
elif expr_info.mode == 2:
if expr_info.dimension > 0:
ew.replacediv()
ew.sharing_graph_rewrite()
ew.licm(mode='reductions')
elif expr_info.mode == 3:
ew.expand(mode='all')
ew.factorize(mode='all')
ew.licm(mode='only_const')
ew.factorize(mode='constants')
ew.licm(mode='aggressive')
ew.preevaluate()
ew.factorize(mode='linear')
ew.licm(mode='only_const')
elif expr_info.mode == 4:
ew.replacediv()
ew.factorize()
ew.licm(mode='only_outlinear')
if expr_info.dimension > 0:
ew.licm(mode='only_linear', iterative=False, max_sharing=True)
ew.sharing_graph_rewrite()
ew.expand()
# Try merging the loops created by expression rewriting
merged_loops = SSALoopMerger().merge(self.header)
# Update the trackers
for merged, merged_in in merged_loops:
for l in merged:
self.hoisted.update_loop(l, merged_in)
# Was /merged/ an expression loops? If so, need to update the
# corresponding MetaExpr
for stmt, expr_info in self.exprs.items():
if expr_info.loops[-1] == l:
expr_info._loops_info[-1] = (merged_in, expr_info.loops_parents[-1])
expr_info._parent = merged_in.children[0]
# Reduce memory pressure by avoiding useless temporaries
self._min_temporaries()
# Handle the effects, at the C-level, of the AST transformation
self._recoil()
def eliminate_zeros(self):
"""Restructure the iteration spaces nested in this LoopOptimizer to
avoid evaluation of arithmetic operations involving zero-valued blocks
in statically initialized arrays."""
zls = ZeroRemover(self.exprs, self.hoisted)
self.nz_syms = zls.reschedule(self.header)
def _unpick_cse(self):
"""Search for factorization opportunities across temporaries created by
common sub-expression elimination. If a gain in operation count is detected,
unpick CSE and apply factorization + code motion."""
cse_unpicker = CSEUnpicker(self.exprs, self.header, self.hoisted)
cse_unpicker.unpick()
def _min_temporaries(self):
"""Remove unnecessary temporaries, thus relieving memory pressure.
A temporary is removed iff:
* it is written once, AND
* it is read once OR it is read n times, but it hosts only a Symbol
"""
occurrences = count(self.header, mode='symbol_id', read_only=True)
for l in self.hoisted.all_loops:
info = visit(l, info_items=['symbol_refs', 'symbols_mode'])
to_replace, to_remove = {}, []
for (temporary, _, _), c in count(l, read_only=True).items():
if temporary not in self.hoisted:
continue
if self.hoisted[temporary].loop is not l:
continue
if occurrences.get(temporary) != c:
continue
decl = self.hoisted[temporary].decl
place = self.hoisted[temporary].place
expr = self.hoisted[temporary].stmt.rvalue
if c > 1 and explore_operator(expr):
continue
references = info['symbol_refs'][temporary]
syms_mode = info['symbols_mode']
# Note: only one write is possible at this point
write = [(s, p) for s, p in references if syms_mode[s][0] == WRITE][0]
to_replace[write[0]] = expr
to_remove.append(write[1])
place.children.remove(decl)
# Update trackers
self.hoisted.pop(temporary)
# Replace temporary symbols and clean up
l_innermost_body = inner_loops(l)[-1].body
for stmt in l_innermost_body:
if stmt.lvalue in to_replace:
continue
while ast_replace(stmt, to_replace, copy=True):
pass
for stmt in to_remove:
l_innermost_body.remove(stmt)
def _dissect(self, heuristics):
"""Analyze the set of expressions in the LoopOptimizer and infer an
optimal rewrite mode for each of them.
If an expression is embedded in a non-perfect loop nest, then injection
may be performed. Injection consists of unrolling any loops outside of
the expression iteration space into the expression itself.
For example: ::
for i
for r
a += B[r]*C[i][r]
for j
for k
A[j][k] += ...f(a)... // the expression at hand
gets transformed into:
for i
for j
for k
A[j][k] += ...f(B[0]*C[i][0] + B[1]*C[i][1] + ...)...
Injection could be necessary to maximize the impact of rewrite mode=3,
which tries to pre-evaluate subexpressions whose values are known at
code generation time. Injection is essential to factorize such subexprs.
:arg heuristic: any value in ['greedy', 'aggressive']. With 'greedy', a greedy
approach is used to decide which of the expressions for which injection
looks beneficial should be dissected (e.g., injection increases the memory
footprint, and some memory constraints must always be preserved).
With 'aggressive', the whole space of possibilities is analyzed.
"""
# The memory threshold. The total size of temporaries will not have to
# be greated than this value. If we predict that injection will lead
# to too much temporary space, we have to partially drop it
threshold = system.architecture['cache_size'] * 1.2
expr_graph = ExpressionGraph(header)
# 1) Find out and unroll injectable loops. For unrolling we create new
# expressions; that is, for now, we do not modify the AST in place.
analyzed, injectable = [], {}
for stmt, expr_info in self.exprs.items():
# Get all loop nests, then discard the one enclosing the expression
nests = [n for n in visit(expr_info.loops_parents[0])['fors']]
injectable_nests = [n for n in nests if list(zip(*n))[0] != expr_info.loops]
for nest in injectable_nests:
to_unroll = [(l, p) for l, p in nest if l not in expr_info.loops]
unroll_cost = reduce(operator.mul, (l.size for l, p in to_unroll))
nest_writers = Find(Writer).visit(to_unroll[0][0])
for op, i_stmts in nest_writers.items():
# Check safety of unrolling
if op in [Assign, IMul, IDiv]:
continue
assert op in [Incr, Decr]
for i_stmt in i_stmts:
i_sym, i_expr = i_stmt.children
# Avoid injecting | |
arg1 provided. Assuming the caller needs assistance....\n--')
UserErr(str(name) + ' tried to move, but didn\'t provide an arg1. I\'ll assume the caller needs help.\n')
try:
embedVal = generateEmbed(title=":grey_question: **Help: `" + str(pre) + " " + str(clr) + "`**",desc="(You're seeing this message because no arguments were provided.)\n",f1e=1,f1t="This command will let you get a super fancy " + str(clr) + "ed name! In order to help me make your " + str(clr) + " role, you'll need to give me one of two things:",f1c="> A color name that's in our library (click the button below to see a list)\n> A hexadecimal code (e.g. \n",f2e=1,f2t="PLEASE NOTE: I can't set your " + str(clr) + " to `#000000`, as this will remove your " + str(clr) + "!",f2c="Once I have this info, I'll be able to create a " + str(clr) + " role just for you! (And for whoever else decides to use it.)")
except discord.Forbidden:
await source.send(embed=dmerror)
await setStatus()
return
# First, I'll clean up the input if necessary.
try:
hxc = hx.split('#')[1]
except IndexError: # If there's no #, we don't need to do this.
hxc = hx
# Now, I'll prepare the input.
try:
hxc = int(hxc, 16)
hxh = hex(hxc)
# If the input is invalid...
except ValueError:
# ...it may be a color name. Let's check.
try:
hxh = getKey(hxc)
# If not...
except KeyError:
# ...it's time for an error DM!
try:
await sendDebug(':grey_exclamation: A valid input wasn\'t provided. Command halted.\n--')
UserErr('They didn\'t provide a valid input.\n\n')
embedVal = generateEmbed(clr=0xffcc00,title=":warning: **That didn't work...**",desc="An error occurred while processing your command.\n",f1e=1,f1t="**Problem:** You tried to set or change your " + str(clr) + ", but provided an invalid input.",f1c="You need to provide a valid hex code or " + str(clr) + " name.\n",f2e=1,f2t="**Solution:** Try running the command again, but make sure your input is valid.",f2c="(If you need help with hex codes, hit up the Internet!)")
await ctx.send(embed=embedVal)
except discord.Forbidden:
await source.send(embed=dmerror)
await setStatus()
return
# Once that's done, I'll see if a role for that color exists. If not, I'll create said role.
try:
await sendDebug('Getting color role for ' + str(hxc) + ' ready...')
if hxh in colorset:
Information(f'The input is in the ' + str(clr) + ' library.')
colorset.get(hx)
if colorset[hxh] == 'tooblack':
UserErr(f'The ' + str(clr) + ' is too black - no worries, easy fix!')
hx = '010101'
hxc = int(hx, 16)
hxh = hex(hxc)
hx = colorset.get(hxh)
role = [a for a in sv.roles if a.name == 'clr-' + str(hxh)][0]
else:
Information(f'The input isn\'t in the ' + str(clr) + ' library.')
role = [a for a in sv.roles if a.name == 'clr-' + str(hxh)][0]
await sendDebug('Role ' + str(role) + ' matches.')
Success(f'Found an associated role. Continuing...')
except IndexError:
await sendDebug('No associated role was found. Creating role...')
Intent('I couldn\'t find the role, so I\'ll need to create it.')
try:
if hxh in colorset:
hxc = int(getKey(hx), 16)
role = await sv.create_role(name='clr-' + str(hxh), color=discord.Colour(hxc))
await sendDebug('Role ' + str(role) + ' was created.')
Success('Role created. Continuing...')
except discord.errors.HTTPException:
await sendDebug(':grey_exclamation: Provided input ended up being out of bounds. Command halted.\n--')
UserErr('That ended up not working because it\'s invalid...')
embedVal = generateEmbed(clr=0xffcc00,title=":warning: **That didn't work...**",desc="An error occurred while processing your command.\n",f1e=1,f1t="**Problem:** You tried to set or change your " + str(clr) + ", but provided an invalid code.",f1c="You need to provide a valid hex code - " + str(hxh) + " isn't valid.\n",f2e=1,f2t="**Solution:** Try running the command again, but make sure your " + str(clr) + " code is valid.",f2c="(Hit up the Internet if you need help!)")
await ctx.send(embed=embedVal)
await setStatus()
return
# Time to assign the role! First, I'll remove the user from any current color role they have.
roles = [a for a in name.roles if not a.name.startswith('clr-')] # This ignores any color role the user has.
roles.append(role)
# Then, I'll give them the new role.
try:
await name.edit(roles=roles)
await sendDebug(':white_check_mark: Role assigned successfully.')
Success('The role\'s been assigned!\n')
except:
await sendDebug(':grey_exclamation_mark: Application unnecessary.')
Success('Chances are, they already have that color.\n')
# Finally, I'll delete any unused color roles.
clroles = [a for a in sv.roles if a.name.startswith('clr-')]
unused = [a for a in clroles if len(a.members) == 0]
if len(unused) > 0:
await sendDebug(':wastebasket: Preparing to delete ' + str(len(unused)) + ' unused roles...')
Information(str(len(unused)) + ' unused roles need to be deleted.\n')
await setStatus("busy")
fofs = 'no'
counter = 0
while len(unused) > 0:
try:
next = unused[counter]
await next.delete()
await sendDebug('Deleted role ' + str(next) + '.')
Information(str(next) + ' was deleted.\n')
counter = counter + 1
except discord.errors.NotFound:
if fofs == 'no':
fofs = 1
else:
fofs = fofs + 1
except IndexError:
break
await sendDebug('Successfully deleted ' + str(counter) + ' unused roles, receiving ' + str(fofs) + ' 404 error(s).')
Success(str(counter) + ' unused role(s) were deleted, with ' + str(fofs) + ' 404 error(s) occurring.\n')
await setStatus()
return
## This command will allow a user to move between specific categories and channels, called "floors" and "rooms" respectively.
@bot.command(name='goto',aliases=['move'])
async def goto(ctx, arg1 = '[none]', arg2 = '[none]'):
Information(str(ctx.message.author) + ' ran command "goto" with arg1 = `' + str(arg1) + '` and arg2 = `' + str(arg2) + '`.\n')
await sendDebug(':arrow_forward: ' + str(ctx.message.author) + ' ran command "goto" with arg1 = `' + str(arg1) + '` and arg2 = `' + str(arg2) + '`.')
# I need to make sure this was sent in the server.
if not ctx.guild:
# If not, I won't have any idea what to do, so I'll stop the command here and let them know.
try:
UserErr(str(ctx.message.author) + ' tried to move, but sent the command in DMs and not in the server.\n')
await sendDebug(':grey_exclamation: Command sent in DMs, so context can\'t be found. Command halted.\n--')
embedVal = generateEmbed(clr=0xffcc00,title=":warning: **That didn't work...**",desc="An error occurred while processing your command.\n",f1e=1,f1t="**Problem:** You tried to move, but sent the command in DMs and not the server.",f1c="I need to know where you are so I can point you in the right direction...\n",f2e=1,f2t="**Solution:** Try running the command again, but in the room you want to move from.",f2c="(For reference, your arg2 (the floor/room you want to move *to*) was `" + str(arg2) + "`.)")
await ctx.send(embed=embedVal)
return
except discord.Forbidden:
return
# Otherwise, I'll start the command!
else:
await setStatus("busy")
await ctx.message.delete()
# Defining consistent variables here.
name = ctx.message.author
source = ctx.message.channel
src = str(source)
dmerror = defaultEmbeds('dmerror', name)
## For floor movement...
if arg1 == 'floor':
# First, I'll make sure the user didn't forget arg2, and send a DM if they did.
if arg2 == '[none]':
await sendDebug(':grey_exclamation: No arg2 provided. Command halted.\n--')
UserErr(str(name) + ' tried to move, but didn\'t say which floor to move to.\n')
try:
embedVal = generateEmbed(clr=0xffcc00,title=":warning: **That didn't work...**",desc="An error occurred while processing your command.\n",f1e=1,f1t="**Problem:** You tried to go to a different floor, but didn't tell me which one.",f1c="I need to know where you wanna go so I can point you in the right direction...\n",f2e=1,f2t="**Solution:** Try running the command again, but specify the floor you want to move to.",f2c="(For reference, there are currently two floors.)")
await name.send(embed=embedVal)
except discord.Forbidden:
await source.send(embed=dmerror)
await setStatus()
return
# Then, I'll let the terminal know I'm starting.
destination = arg2.lower()
Intent('I\'m starting floor movement... ')
await sendDebug('Starting...')
# Next, I'll check to make sure the user is in that floor's lobby.
sch = str(src.split('-')[0])
lobby = 'lobby'
# If they aren't in the lobby...
if sch != lobby:
# ...I'll send an error in a DM.
await sendDebug(':grey_exclamation: The user isn\'t in the lobby. Command halted.\n--')
UserErr('They weren\'t in the lobby.\n')
try:
embedVal = generateEmbed(clr=0xffcc00,title=":warning: **That didn't work...**",desc="An error occurred while processing your command.\n",f1e=1,f1t="**Problem:** You tried to go to a different floor, but you're not in the lobby.",f1c="The elevators are in the lobby - not literally, but...you get the point.\n",f2e=1,f2t="**Solution:** Run `" + str(pre) + "goto room | |
"""Tests for concat_op_handler."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import mock
from morph_net.framework import concat_op_handler
from morph_net.framework import op_regularizer_manager as orm
import tensorflow.compat.v1 as tf
from tensorflow.contrib import framework
from tensorflow.contrib import layers
arg_scope = framework.arg_scope
class ConcatOpHandlerTest(tf.test.TestCase):
def setUp(self):
super(ConcatOpHandlerTest, self).setUp()
# This tests 3 Conv2D ops being concatenated.
inputs = tf.zeros([2, 4, 4, 3])
c1 = layers.conv2d(inputs, num_outputs=5, kernel_size=3, scope='conv1')
c2 = layers.conv2d(inputs, num_outputs=6, kernel_size=3, scope='conv2')
c3 = layers.conv2d(inputs, num_outputs=7, kernel_size=3, scope='conv3')
net = tf.concat([c1, c2, c3], axis=3)
layers.batch_norm(net)
g = tf.get_default_graph()
# Declare OpSlice and OpGroup for ops of interest.
self.concat_op = g.get_operation_by_name('concat')
self.concat_op_slice = orm.OpSlice(self.concat_op, orm.Slice(0, 18))
self.concat_op_slice_0_5 = orm.OpSlice(self.concat_op, orm.Slice(0, 5))
self.concat_op_slice_5_11 = orm.OpSlice(self.concat_op, orm.Slice(5, 6))
self.concat_op_slice_11_18 = orm.OpSlice(self.concat_op, orm.Slice(11, 7))
self.concat_op_group1 = orm.OpGroup(
self.concat_op_slice_0_5,
omit_source_op_slices=[self.concat_op_slice_0_5])
self.concat_op_group2 = orm.OpGroup(
self.concat_op_slice_5_11,
omit_source_op_slices=[self.concat_op_slice_5_11])
self.concat_op_group3 = orm.OpGroup(
self.concat_op_slice_11_18,
omit_source_op_slices=[self.concat_op_slice_11_18])
self.relu1_op = g.get_operation_by_name('conv1/Relu')
self.relu1_op_slice = orm.OpSlice(self.relu1_op, orm.Slice(0, 5))
self.relu1_op_group = orm.OpGroup(
self.relu1_op_slice, omit_source_op_slices=[self.relu1_op_slice])
self.relu2_op = g.get_operation_by_name('conv2/Relu')
self.relu2_op_slice = orm.OpSlice(self.relu2_op, orm.Slice(0, 6))
self.relu2_op_group = orm.OpGroup(
self.relu2_op_slice, omit_source_op_slices=[self.relu2_op_slice])
self.relu3_op = g.get_operation_by_name('conv3/Relu')
self.relu3_op_slice = orm.OpSlice(self.relu3_op, orm.Slice(0, 7))
self.relu3_op_group = orm.OpGroup(
self.relu3_op_slice, omit_source_op_slices=[self.relu3_op_slice])
self.axis_op = g.get_operation_by_name('concat/axis')
self.batch_norm_op = g.get_operation_by_name('BatchNorm/FusedBatchNormV3')
self.batch_norm_op_slice = orm.OpSlice(self.batch_norm_op, orm.Slice(0, 18))
self.batch_norm_op_group = orm.OpGroup(
self.batch_norm_op_slice,
omit_source_op_slices=[self.batch_norm_op_slice])
self.batch_norm_op_slice_0_5 = orm.OpSlice(
self.batch_norm_op, orm.Slice(0, 5))
self.batch_norm_op_slice_5_11 = orm.OpSlice(
self.batch_norm_op, orm.Slice(5, 6))
self.batch_norm_op_slice_11_18 = orm.OpSlice(
self.batch_norm_op, orm.Slice(11, 7))
self.batch_norm_op_group1 = orm.OpGroup(
self.batch_norm_op_slice_0_5,
omit_source_op_slices=[self.batch_norm_op_slice_0_5])
self.batch_norm_op_group2 = orm.OpGroup(
self.batch_norm_op_slice_5_11,
omit_source_op_slices=[self.batch_norm_op_slice_5_11])
self.batch_norm_op_group3 = orm.OpGroup(
self.batch_norm_op_slice_11_18,
omit_source_op_slices=[self.batch_norm_op_slice_11_18])
# Create mock OpRegularizerManager with custom mapping of OpSlice and
# OpGroup.
self.mock_op_reg_manager = mock.create_autospec(orm.OpRegularizerManager)
def get_op_slices(op):
return self.op_slice_dict.get(op, [])
def get_op_group(op_slice):
return self.op_group_dict.get(op_slice)
# Update op_slice_dict when an op is sliced.
def slice_op(op, _):
if op == self.batch_norm_op:
self.op_slice_dict[self.batch_norm_op] = [
self.batch_norm_op_slice_0_5,
self.batch_norm_op_slice_5_11,
self.batch_norm_op_slice_11_18]
if op == self.concat_op:
self.op_slice_dict[self.concat_op] = [
self.concat_op_slice_0_5,
self.concat_op_slice_5_11,
self.concat_op_slice_11_18]
self.mock_op_reg_manager.get_op_slices.side_effect = get_op_slices
self.mock_op_reg_manager.get_op_group.side_effect = get_op_group
self.mock_op_reg_manager.is_source_op.return_value = False
self.mock_op_reg_manager.slice_op.side_effect = slice_op
self.mock_op_reg_manager.is_passthrough.return_value = True
self.mock_op_reg_manager.ops = [
self.concat_op, self.relu1_op, self.relu2_op, self.relu3_op,
self.batch_norm_op]
def testAssignGrouping_AllNeighborsGrouped_SlicesAligned(self):
# In this test, the output op (batch norm) has size 18 and is sliced into
# sizes [5, 6, 7] which matches the Conv2D sizes which are [5, 6, 7].
# Map ops to slices. Batch norm op is composed of multiple slices.
self.op_slice_dict = {
self.relu1_op: [self.relu1_op_slice],
self.relu2_op: [self.relu2_op_slice],
self.relu3_op: [self.relu3_op_slice],
self.concat_op: [self.concat_op_slice],
self.batch_norm_op: [self.batch_norm_op_slice_0_5,
self.batch_norm_op_slice_5_11,
self.batch_norm_op_slice_11_18],
}
# Map each slice to a group.
self.op_group_dict = {
self.relu1_op_slice: self.relu1_op_group,
self.relu2_op_slice: self.relu2_op_group,
self.relu3_op_slice: self.relu3_op_group,
self.batch_norm_op_slice_0_5: self.batch_norm_op_group1,
self.batch_norm_op_slice_5_11: self.batch_norm_op_group2,
self.batch_norm_op_slice_11_18: self.batch_norm_op_group3,
}
# Call handler to assign grouping.
handler = concat_op_handler.ConcatOpHandler()
handler.assign_grouping(self.concat_op, self.mock_op_reg_manager)
# Verify manager looks up OpSlice for ops of interest.
self.mock_op_reg_manager.get_op_slices.assert_has_calls(
# Checking for ops to process.
[mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
# Initial slice data.
mock.call(self.concat_op),
mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
# Reslicing.
mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
mock.call(self.concat_op),
# Refreshing slice data.
mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
# Group concat op.
mock.call(self.concat_op)])
# Verify manager only slices the concat op.
self.mock_op_reg_manager.slice_op.assert_called_once_with(
self.concat_op, [5, 6, 7])
# Verify manager groups the new slices.
self.mock_op_reg_manager.group_op_slices.assert_has_calls(
[mock.call([self.concat_op_slice_0_5, self.relu1_op_slice,
self.batch_norm_op_slice_0_5]),
mock.call([self.concat_op_slice_5_11, self.relu2_op_slice,
self.batch_norm_op_slice_5_11]),
mock.call([self.concat_op_slice_11_18, self.relu3_op_slice,
self.batch_norm_op_slice_11_18])])
def testAssignGrouping_AllNeighborsGrouped_SlicesAligned_SameGroup(self):
# This test verifies that no slicing or grouping occurs.
# Map ops to slices. Batch norm op is composed of multiple slices.
self.op_slice_dict = {
self.relu1_op: [self.relu1_op_slice],
self.relu2_op: [self.relu2_op_slice],
self.relu3_op: [self.relu3_op_slice],
self.concat_op: [self.concat_op_slice_0_5, self.concat_op_slice_5_11,
self.concat_op_slice_11_18],
self.batch_norm_op: [self.batch_norm_op_slice_0_5,
self.batch_norm_op_slice_5_11,
self.batch_norm_op_slice_11_18],
}
# Map each slice to a group. Corresponding op slices have the same group.
self.op_group_dict = {
self.relu1_op_slice: self.batch_norm_op_group1,
self.relu2_op_slice: self.batch_norm_op_group2,
self.relu3_op_slice: self.batch_norm_op_group3,
self.concat_op_slice_0_5: self.batch_norm_op_group1,
self.concat_op_slice_5_11: self.batch_norm_op_group2,
self.concat_op_slice_11_18: self.batch_norm_op_group3,
self.batch_norm_op_slice_0_5: self.batch_norm_op_group1,
self.batch_norm_op_slice_5_11: self.batch_norm_op_group2,
self.batch_norm_op_slice_11_18: self.batch_norm_op_group3,
}
# Call handler to assign grouping.
handler = concat_op_handler.ConcatOpHandler()
handler.assign_grouping(self.concat_op, self.mock_op_reg_manager)
# Verify manager looks up OpSlice for ops of interest.
self.mock_op_reg_manager.get_op_slices.assert_has_calls(
# Checking for ops to process.
[mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
# Initial slice data.
mock.call(self.concat_op),
mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
# Reslicing.
mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
mock.call(self.concat_op),
# Refreshing slice data.
mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
# Group concat op.
mock.call(self.concat_op)])
# Verify manager does not slice any ops.
self.mock_op_reg_manager.slice_op.assert_not_called()
# Verify manager does not group any ops.
self.mock_op_reg_manager.group_op_slices.assert_not_called()
def testAssignGrouping_AllNeighborsGrouped_OutputSlicesNotAligned(self):
# The output (batch norm) has sizes [9, 4, 5] which are not aligned. This
# test verifies that the concat, batch norm, and Conv2D ops are sliced in
# alignment.
concat_op_slice_0_5 = orm.OpSlice(self.concat_op, orm.Slice(0, 5))
concat_op_slice_5_9 = orm.OpSlice(self.concat_op, orm.Slice(5, 4))
concat_op_slice_9_11 = orm.OpSlice(self.concat_op, orm.Slice(9, 2))
concat_op_slice_11_13 = orm.OpSlice(self.concat_op, orm.Slice(11, 2))
concat_op_slice_13_18 = orm.OpSlice(self.concat_op, orm.Slice(13, 5))
relu2_op_slice_0_4 = orm.OpSlice(self.relu2_op, orm.Slice(0, 4))
relu2_op_slice_4_6 = orm.OpSlice(self.relu2_op, orm.Slice(4, 2))
relu3_op_slice_0_2 = orm.OpSlice(self.relu3_op, orm.Slice(0, 2))
relu3_op_slice_2_7 = orm.OpSlice(self.relu3_op, orm.Slice(2, 5))
batch_norm_op_slice_0_9 = orm.OpSlice(self.batch_norm_op, orm.Slice(0, 9))
batch_norm_op_group1 = orm.OpGroup(
batch_norm_op_slice_0_9,
omit_source_op_slices=[batch_norm_op_slice_0_9])
batch_norm_op_slice_9_13 = orm.OpSlice(self.batch_norm_op, orm.Slice(9, 4))
batch_norm_op_group2 = orm.OpGroup(
batch_norm_op_slice_9_13,
omit_source_op_slices=[batch_norm_op_slice_9_13])
batch_norm_op_slice_13_18 = orm.OpSlice(
self.batch_norm_op, orm.Slice(13, 5))
batch_norm_op_group3 = orm.OpGroup(
batch_norm_op_slice_13_18,
omit_source_op_slices=[batch_norm_op_slice_13_18])
batch_norm_op_slice_0_5 = orm.OpSlice(self.batch_norm_op, orm.Slice(0, 5))
batch_norm_op_group4 = orm.OpGroup(
batch_norm_op_slice_0_5,
omit_source_op_slices=[batch_norm_op_slice_0_5])
batch_norm_op_slice_5_9 = orm.OpSlice(self.batch_norm_op, orm.Slice(5, 4))
batch_norm_op_group5 = orm.OpGroup(
batch_norm_op_slice_5_9,
omit_source_op_slices=[batch_norm_op_slice_5_9])
batch_norm_op_slice_9_11 = orm.OpSlice(self.batch_norm_op, orm.Slice(9, 2))
batch_norm_op_group6 = orm.OpGroup(
batch_norm_op_slice_9_11,
omit_source_op_slices=[batch_norm_op_slice_9_11])
batch_norm_op_slice_11_13 = orm.OpSlice(
self.batch_norm_op, orm.Slice(11, 2))
batch_norm_op_group7 = orm.OpGroup(
batch_norm_op_slice_11_13,
omit_source_op_slices=[batch_norm_op_slice_11_13])
batch_norm_op_slice_13_18 = orm.OpSlice(
self.batch_norm_op, orm.Slice(11, 5))
batch_norm_op_group8 = orm.OpGroup(
batch_norm_op_slice_13_18,
omit_source_op_slices=[batch_norm_op_slice_13_18])
# Map ops to slices. Batch norm op is composed of multiple slices.
self.op_slice_dict = {
self.relu1_op: [self.relu1_op_slice],
self.relu2_op: [self.relu2_op_slice],
self.relu3_op: [self.relu3_op_slice],
self.concat_op: [self.concat_op_slice],
self.batch_norm_op: [batch_norm_op_slice_0_9, batch_norm_op_slice_9_13,
batch_norm_op_slice_13_18],
}
# Map each slice to a group.
self.op_group_dict = {
self.relu1_op_slice: self.relu1_op_group,
self.relu2_op_slice: self.relu2_op_group,
self.relu3_op_slice: self.relu3_op_group,
batch_norm_op_slice_0_9: batch_norm_op_group1,
batch_norm_op_slice_9_13: batch_norm_op_group2,
batch_norm_op_slice_13_18: batch_norm_op_group3,
batch_norm_op_slice_0_5: batch_norm_op_group4,
batch_norm_op_slice_5_9: batch_norm_op_group5,
batch_norm_op_slice_9_11: batch_norm_op_group6,
batch_norm_op_slice_11_13: batch_norm_op_group7,
batch_norm_op_slice_13_18: batch_norm_op_group8,
}
# Update op_slice_dict when an op is sliced.
def slice_op(op, _):
if op == self.batch_norm_op:
self.op_slice_dict[self.batch_norm_op] = [
batch_norm_op_slice_0_5,
batch_norm_op_slice_5_9,
batch_norm_op_slice_9_11,
batch_norm_op_slice_11_13,
batch_norm_op_slice_13_18]
if op == self.concat_op:
self.op_slice_dict[self.concat_op] = [
concat_op_slice_0_5,
concat_op_slice_5_9,
concat_op_slice_9_11,
concat_op_slice_11_13,
concat_op_slice_13_18]
if op == self.relu2_op:
self.op_slice_dict[self.relu2_op] = [
relu2_op_slice_0_4,
relu2_op_slice_4_6]
if op == self.relu3_op:
self.op_slice_dict[self.relu3_op] = [
relu3_op_slice_0_2,
relu3_op_slice_2_7]
self.mock_op_reg_manager.slice_op.side_effect = slice_op
# Call handler to assign grouping.
handler = concat_op_handler.ConcatOpHandler()
handler.assign_grouping(self.concat_op, self.mock_op_reg_manager)
# Verify manager looks up OpSlice for ops of interest.
self.mock_op_reg_manager.get_op_slices.assert_has_calls(
# Checking for ops to process.
[mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
# Initial slice data.
mock.call(self.concat_op),
mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
# Reslicing.
mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
mock.call(self.concat_op),
# Refreshing slice data.
mock.call(self.relu1_op),
mock.call(self.relu2_op),
mock.call(self.relu3_op),
mock.call(self.batch_norm_op),
# Group concat op.
mock.call(self.concat_op)])
# Verify manager slices ops that do not have aligned OpSlice sizes.
self.mock_op_reg_manager.slice_op.assert_has_calls(
[mock.call(self.relu2_op, [4, 2]),
mock.call(self.relu3_op, [2, 5]),
mock.call(self.batch_norm_op, [5, 4, 2, 2, 5]),
mock.call(self.concat_op, [5, 4, 2, 2, 5])])
# Verify manager groups the new slices.
self.mock_op_reg_manager.group_op_slices.assert_has_calls(
[mock.call([concat_op_slice_0_5, self.relu1_op_slice,
batch_norm_op_slice_0_5]),
mock.call([concat_op_slice_5_9, relu2_op_slice_0_4,
batch_norm_op_slice_5_9]),
mock.call([concat_op_slice_9_11, relu2_op_slice_4_6,
batch_norm_op_slice_9_11]),
mock.call([concat_op_slice_11_13, relu3_op_slice_0_2,
batch_norm_op_slice_11_13]),
mock.call([concat_op_slice_13_18, relu3_op_slice_2_7,
batch_norm_op_slice_13_18])])
def testAssignGrouping_AllNeighborsGrouped_InputSlicesNotAligned(self):
# In this test, the op c2 has size 6 but is split into 2 slices of size 3.
# The concat op (and its output, the batch norm) both have size 18. This
# test verifies that the concat and batch norm are sliced according to the
# sizes of c1, c2, and c3, and takes into account that c2 is also composed
# of multiple slices.
concat_op_slice_0_5 = orm.OpSlice(self.concat_op, orm.Slice(0, 5))
concat_op_slice_5_8 = orm.OpSlice(self.concat_op, orm.Slice(5, 3))
concat_op_slice_8_11 = orm.OpSlice(self.concat_op, orm.Slice(8, 3))
concat_op_slice_11_18 = orm.OpSlice(self.concat_op, orm.Slice(11, 7))
relu2_op_slice_0_3 = orm.OpSlice(self.relu2_op, orm.Slice(0, 3))
relu2_op_slice_3_6 = orm.OpSlice(self.relu2_op, orm.Slice(3, 3))
relu2_op_group1 = orm.OpGroup(
relu2_op_slice_0_3, omit_source_op_slices=[relu2_op_slice_0_3])
relu2_op_group2 = orm.OpGroup(
relu2_op_slice_3_6, omit_source_op_slices=[relu2_op_slice_3_6])
batch_norm_op_slice = orm.OpSlice(self.batch_norm_op, orm.Slice(0, 18))
batch_norm_op_group = orm.OpGroup(
batch_norm_op_slice, omit_source_op_slices=[batch_norm_op_slice])
batch_norm_op_slice_0_5 = orm.OpSlice(self.batch_norm_op, orm.Slice(0, 5))
batch_norm_op_group1 = orm.OpGroup(
batch_norm_op_slice_0_5,
omit_source_op_slices=[batch_norm_op_slice_0_5])
batch_norm_op_slice_5_8 = orm.OpSlice(self.batch_norm_op, orm.Slice(5, 3))
batch_norm_op_group2 = orm.OpGroup(
batch_norm_op_slice_5_8,
omit_source_op_slices=[batch_norm_op_slice_5_8])
batch_norm_op_slice_8_11 = orm.OpSlice(self.batch_norm_op, orm.Slice(8, 3))
batch_norm_op_group3 = orm.OpGroup(
batch_norm_op_slice_8_11,
omit_source_op_slices=[batch_norm_op_slice_8_11])
batch_norm_op_slice_11_18 = orm.OpSlice(
self.batch_norm_op, orm.Slice(11, 7))
batch_norm_op_group4 = orm.OpGroup(
batch_norm_op_slice_11_18,
omit_source_op_slices=[batch_norm_op_slice_11_18])
# Map ops to slices. The op c2 is composed of multiple slices.
self.op_slice_dict = {
self.relu1_op: [self.relu1_op_slice],
self.relu2_op: [relu2_op_slice_0_3, relu2_op_slice_3_6],
self.relu3_op: [self.relu3_op_slice],
self.concat_op: [self.concat_op_slice],
self.batch_norm_op: [batch_norm_op_slice],
}
# Map each slice to a group.
self.op_group_dict = {
self.relu1_op_slice: self.relu1_op_group,
relu2_op_slice_0_3: relu2_op_group1,
relu2_op_slice_3_6: relu2_op_group2,
self.relu3_op_slice: self.relu3_op_group,
batch_norm_op_slice: batch_norm_op_group,
batch_norm_op_slice_0_5: batch_norm_op_group1,
batch_norm_op_slice_5_8: batch_norm_op_group2,
batch_norm_op_slice_8_11: batch_norm_op_group3,
batch_norm_op_slice_11_18: batch_norm_op_group4,
}
# Update op_slice_dict when an op is sliced.
def slice_op(op, _):
if op == self.batch_norm_op:
self.op_slice_dict[self.batch_norm_op] = [
batch_norm_op_slice_0_5,
batch_norm_op_slice_5_8,
batch_norm_op_slice_8_11,
batch_norm_op_slice_11_18]
if op == self.concat_op:
self.op_slice_dict[self.concat_op] = [
concat_op_slice_0_5,
concat_op_slice_5_8,
concat_op_slice_8_11,
concat_op_slice_11_18]
self.mock_op_reg_manager.slice_op.side_effect = slice_op
# Call handler to assign grouping.
| |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Copyright 2018-2019, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
import torch
from numba import cuda
from warprnnt_numba.rnnt_loss.utils import rnnt_helper
from warprnnt_numba.rnnt_loss.utils.cuda_utils.gpu_rnnt_kernel import logp
GPU_RNNT_THREAD_SIZE = 256
@cuda.jit(device=True, inline=True)
def logp(
denom: torch.Tensor, acts: torch.Tensor, maxT: int, maxU: int, alphabet_size: int, mb: int, t: int, u: int, v: int
):
"""
Compute the sum of log probability from the activation tensor and its denominator.
Args:
denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor
across entire vocabulary.
acts: Tensor of shape [B, T, U, V+1] flattened. Represents the logprobs activation tensor.
maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor.
maxU: The maximum possible target sequence length. Represents U in the logprobs tensor.
alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank).
mb: Batch indexer.
t: Acoustic sequence timestep indexer.
u: Target sequence timestep indexer.
v: Vocabulary token indexer.
Returns:
The sum of logprobs[mb, t, u, v] + denom[mb, t, u]
"""
col = (mb * maxT + t) * maxU + u
return denom[col] + acts[col * alphabet_size + v]
@cuda.jit()
def compute_alphas_kernel_atomic_locks(
acts: torch.Tensor,
denom: torch.Tensor,
alphas: torch.Tensor,
llForward: torch.Tensor,
xlen: torch.Tensor,
ylen: torch.Tensor,
mlabels: torch.Tensor, # [B]
minibatch: int,
maxT: int,
maxU: int,
alphabet_size: int,
blank: int,
lock: torch.Tensor,
):
"""
Compute alpha (forward variable) probabilities over the transduction step in loop,
with CUDA atomic locks.
Baseline reference from SpeechBrain implementation -
https://github.com/speechbrain/speechbrain/blob/develop/speechbrain/nnet/loss/transducer_loss.py
Args:
acts: Tensor of shape [B, T, U, V+1]. Represents the logprobs activation tensor.
denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor
across entire vocabulary.
alphas: Zero tensor of shape [B, T, U]. Will be updated inside the kernel with the forward variable
probabilities.
llForward: Zero tensor of shape [B]. Represents the log-likelihood of the forward pass.
Returned as the forward pass loss that is reduced by the optimizer.
xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded
activation tensor.
ylen: Vector of length B which contains the actual target sequence lengths in the padded
activation tensor.
mlabels: Matrix of shape [B, U+1] (+1 here is due to <SOS> token - usually the RNNT blank).
The matrix contains the padded target transcription that must be predicted.
minibatch: Int representing the batch size.
maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor.
maxU: The maximum possible target sequence length. Represents U in the logprobs tensor.
alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank).
blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab.
lock: Tensor of shape [B, U+1]. Bool values, used for CUDA atomic locking.
Updates:
Kernel inplace updates the following inputs:
- alphas: forward variable scores.
- llForward: log-likelihood of forward variable.
"""
# // launch B blocks, each block has U threads
b = cuda.blockIdx.x
u = cuda.threadIdx.x
T = xlen[b] # select AM length of current sample
U = ylen[b] + 1 # select target length of current sample, +1 for the blank token
labels: torch.Tensor = mlabels[b] # mb label start point, equivalent to mlabels + b * (maxU - 1)
offset = b * maxT * maxU # pointer indexing offset
t = 0
# Ordinary alpha calculations, broadcast across B=b and U=u
# Look up forward variable calculation from rnnt_numpy.forward_pass()
if u < U:
# for each (B,U) Thread
# wait the unlock of the previous computation of Alpha[b,U-1,:]
# Do the computation over the whole Time sequence on alpha[B,U,:]
# and then unlock the target U+1 for computation
while t < T:
if u == 0:
# for t in range(1, T) step to initialize alphas[b, t, 0]
if t > 0:
alphas[offset + t * maxU] = (
alphas[offset + (t - 1) * maxU]
+ logp(denom, acts, maxT, maxU, alphabet_size, b, t - 1, 0, blank)
)
cuda.atomic.add(lock, (b, u + 1), -1)
t += 1
else:
if cuda.atomic.add(lock, (b, u), 0) < 0:
# for u in range(1, U) step to initialize alphas[b, 0, u]
if t == 0:
alphas[offset + u] = (
alphas[offset + u - 1]
+ logp(denom, acts, maxT, maxU, alphabet_size, b, 0, u - 1, labels[u - 1])
)
else:
# for t in range(1, T) for u in range(1, U) step to compute alphas[b, t, u]
emit = (
alphas[offset + t * maxU + u - 1]
+ logp(denom, acts, maxT, maxU, alphabet_size, b, t, u - 1, labels[u - 1])
)
no_emit = (
alphas[offset + (t - 1) * maxU + u]
+ logp(denom, acts, maxT, maxU, alphabet_size, b, t - 1, u, blank)
)
alphas[offset + t * maxU + u] = max(no_emit, emit) + math.log1p(
math.exp(-abs(no_emit - emit))
)
if u < U:
cuda.atomic.add(lock, (b, u + 1), -1)
cuda.atomic.add(lock, (b, u), 1)
t += 1
# After final sync, alphas[b, T-1, U - 1] + logprobs[b, T-1, U-1, blank] + denom[b, T-1, U-1] gives
# log-likelihood of forward pass.
if u == U - 1:
# for each thread b (utterance)
llForward[b] = (
alphas[offset + (T - 1) * maxU + U - 1]
+ logp(denom, acts, maxT, maxU, alphabet_size, b, T - 1, U - 1, blank)
)
@cuda.jit()
def compute_betas_kernel_atomic_locks(
acts: torch.Tensor,
denom: torch.Tensor,
betas: torch.Tensor,
llBackward: torch.Tensor,
xlen: torch.Tensor,
ylen: torch.Tensor,
mlabels: torch.Tensor, # [B, U]
minibatch: int,
maxT: int,
maxU: int,
alphabet_size: int,
blank_: int,
lock: torch.Tensor,
):
"""
Compute beta (backward variable) probabilities over the transduction step.
Args:
acts: Tensor of shape [B, T, U, V+1] flattened. Represents the logprobs activation tensor.
denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor
across entire vocabulary.
betas: Zero tensor of shape [B, T, U]. Will be updated inside the kernel with the backward variable
probabilities.
llBackward: Zero tensor of shape [B]. Represents the log-likelihood of the backward pass.
Returned as the backward pass loss that is reduced by the optimizer.
xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded
activation tensor.
ylen: Vector of length B which contains the actual target sequence lengths in the padded
activation tensor.
mlabels: Matrix of shape [B, U+1] (+1 here is due to <SOS> token - usually the RNNT blank).
The matrix contains the padded target transcription that must be predicted.
minibatch: Int representing the batch size.
maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor.
maxU: The maximum possible target sequence length. Represents U in the logprobs tensor.
alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank).
blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab.
lock: Tensor of shape [B, U+1]. Bool values, used for CUDA atomic locking.
Updates:
| |
<reponame>ddesvillechabrol/sequana
# -*- coding: utf-8 -*-
#
# This file is part of Sequana software
#
# Copyright (c) 2016-2020 - Sequana Development Team
#
# File author(s):
# <NAME> <<EMAIL>>
#
# Distributed under the terms of the 3-clause BSD license.
# The full license is in the LICENSE file, distributed with this software.
#
# website: https://github.com/sequana/sequana
# documentation: http://sequana.readthedocs.io
#
##############################################################################
import re
import os
# from bioconvert/io/gff3 and adapted later on
from sequana.annotations import Annotation
from easydev import do_profile
import colorlog
logger = colorlog.getLogger(__name__)
__all__ = ["GFF3"]
class GFF3(Annotation):
"""Read a GFF file, version 3
.. seealso:: https://github.com/The-Sequence-Ontology/Specifications/blob/master/gff3.md
::
g = GFF3(filename)
# first call is slow
g.df
# print info about the different feature types
g.features
# prints info about duplicated attributes:
g.get_duplicated_attributes_per_type(self)
On eukaryotes, the reading and processing of the GFF may take a while.
On prokaryotes, it should be pretty fast (a few seconds).
To speed up the eukaryotes case, we skip the processing biological_regions
(50% of the data in mouse).
"""
def __init__(self, filename, skip_types=['biological_region']):
self.filename = filename
assert os.path.exists(filename)
self._df = None
self._features = set()
self._attributes = set()
self.skip_types = skip_types
def _get_features(self):
"""Extract unique GFF feature types
This is equivalent to awk '{print $3}' | sort | uniq to extract unique GFF
types. No sanity check, this is suppose to be fast.
Less than a few seconds for mammals.
"""
# This is used by the rnaseq pipeline and should be kept fast
count = 0
if self._features:
features = self._features
else:
features = set()
with open(self.filename, "r") as reader:
for line in reader:
# Skip metadata and comments
if line.startswith("#"):
continue
# Skip empty lines
if not line.strip(): # pragma: no cover
continue
split = line.rstrip().split("\t")
L = len(split)
if L == 9:
features.add(split[2])
count += 1
# FIXME may be overwritten by get_df
self._features = features
return sorted(features)
features = property(_get_features)
def get_attributes(self, feature=None, sep=";"):
"""Return list of possible attributes
If feature is provided, must be valid and used as a filter
to keep only entries for that feature.
"""
# This is used by the rnaseq pipeline and should be kept fast
if self._attributes:
return self._attributes
attributes = set()
with open(self.filename, "r") as reader:
for line in reader:
# Skip metadata and comments and empty lines
if line.startswith("#") or not line.strip():
continue
split = line.rstrip().split("\t")
if feature and split[2] != feature:
continue
for item in split[8].split(sep):
item = item.strip()
if len(item) == 0: # empty final string #pragma: no cover
continue
# Here, some GFF use = some others use spaces... very
# annoying.
if "=" in item:
item = item.split("=")[0].strip()
else:
item = item.split()[0].strip()
attributes.add(item)
self._attributes = sorted(attributes)
return self._attributes
attributes = property(get_attributes)
""" THis is a multiprocess version but is twice as slow as normal version...
keep this code for book-keeping for now
def _process_chunk(self, chunk, queue):
results = []
print('processing')
for line in chunk:
line = line.strip()
if line.startswith("#"):
continue
# Skip empty lines
if not line.strip():
continue
# Format checking
split = line.rstrip().split("\t")
annotation = self._process_main_fields(split[0:8])
# + 15 seconds
annotation["attributes"] = self._process_attributes(split[8])
results.append(annotation)
queue.put(results)
def _queue_reader(self, q):
return q.get()
def read_large_gff(self, chunksize=2000000):
from itertools import islice
S = 0
import multiprocessing as mp
pool = mp.Pool(4)
manager = mp.Manager()
queue = manager.Queue()
count = 0
with open(self.filename, "r") as reader:
while True:
chunk = list(islice(reader, chunksize))
count += 1
print(len(chunk))
mp.Process(target=self._process_chunk, args=(chunk, queue)).start()
if len(chunk) < chunksize:
break
print(1)
readers = []
for i in range(count):
readers.append(pool.apply_async(self._queue_reader, (queue, )))
results = []
for r in readers:
results.extend(r.get())
return results
"""
def read(self):
""" Read annotations one by one creating a generator """
count = 0
self._features = set()
# we could use a yield but gff for eukaryotes can be read on a laptop
results = []
with open(self.filename, "r") as reader:
line = None
for line in reader:
# Skip metadata and comments
if line.startswith("#"):
continue
# Skip empty lines
if not line.strip():
continue
# Format checking
split = line.rstrip().split("\t")
#if split[2].strip() in self.skip_types:
# continue
L = len(split)
if L != 9 and L != 0: # pragma: no cover
msg = "Incorrect format on line ({}). Expected 9 items, found {}. Skipped"
print(msg.format(count, L))
print(line.strip())
count += 1
continue
# 9 seconds without annotation
# + 3 seconds for process_main
self._features.add(split[2])
annotation = self._process_main_fields(split[0:8])
# + 15 seconds
annotation["attributes"] = self._process_attributes(split[8])
count += 1
results.append(annotation)
return results
def _get_df(self):
if self._df is not None:
return self._df
logger.info("Processing GFF file. 1. Reading the input file. Please be patient")
# ~ 30 seconds on mouse
data = self.read()
# ~ 6 seconds on mouse
logger.info("Processing GFF file. 2. Transforming into dataframe")
import pandas as pd
df = pd.DataFrame(data)
def get_attr(x, name):
if name in x:
# some GFF adds " around names which is annoying
return x[name].replace("'", "").replace('"', "")
else:
return None
logger.info("Processing GFF file. 3. Processing attributes")
try:
# 10 seconds on mm10
attributes = self.attributes
for attribute in attributes:
df[attribute] = [get_attr(x, attribute) for x in df["attributes"]]
except Exception as err: # pragma: no cover
print(err)
df["ID"] = [get_attr(x, "ID") for x in df["attributes"]]
df["description"] = [get_attr(x, "description") for x in df["attributes"]]
self._df = df
return self._df
df = property(_get_df)
def get_duplicated_attributes_per_type(self):
results = {}
for typ in self.features:
results[typ] = {}
print("{}: {} entries".format(typ, len(self.df.query("type==@typ"))))
for attr in sorted(self.attributes):
dups = self.df.query("type==@typ")[attr].dropna().duplicated().sum()
if dups > 0:
print(" - {}:{} duplicates".format(attr, dups))
else:
print(" - {}:No duplicates".format(attr))
results[typ][attr] = dups
import pandas as pd
df = pd.DataFrame(results)
return df
def transcript_to_gene_mapping(self, feature="all", attribute="transcript_id"):
"""
:param feature: not used yet
:param attribute: the attribute to be usde. should be transcript_id for
salmon compatability but could use soething different.
"""
# entries may have transcripts set to None
transcripts = [x for x in self.df[attribute] if x]
# retrieve only the data with transcript id defined
transcripts_df = self.df.set_index(attribute)
transcripts_df = transcripts_df.loc[transcripts]
transcripts_df = transcripts_df.reset_index()
results = {}
from collections import defaultdict
results2 = defaultdict(list)
for _id, data in transcripts_df[['ID', 'Parent']].iterrows():
results[data.values[0]] = data.values[1]
results2[data.values[1]].append(data.values[0])
return results, results2
def save_annotation_to_csv(self, filename="annotations.csv"):
self.df.to_csv(filename, index=False)
def save_gff_filtered(
self, filename="filtered.gff", features=["gene"], replace_seqid=None
):
"""
save_gff_filtered("test.gff", features=['misc_RNA', 'rRNA'],
replace_seqid='locus_tag')
"""
with open(filename, "w") as fout:
fout.write("#gff-version 3\n#Custom gff from sequana\n")
count = 0
from collections import defaultdict
counter = defaultdict(int)
for x, y in self.df.iterrows():
if y["type"] in features:
if replace_seqid:
y["seqid"] = y["attributes"][replace_seqid]
fout.write(
"{}\tfeature\tcustom\t{}\t{}\t.\t{}\t{}\t{}\n".format(
y["seqid"],
y["start"],
y["stop"],
y["strand"],
y["phase"],
";".join([f"{a}={b}" for a, b in y["attributes"].items()]),
)
)
counter[y["type"]] += 1
count += 1
logger.info("# kept {} entries".format(count))
for feature in features:
counter[feature] += 0
logger.info("# {}: {} entries".format(feature, counter[feature]))
def _process_main_fields(self, fields):
annotation = {}
# Unique id of the sequence
annotation["seqid"] = fields[0]
# Optional source
if fields[1] != ".":
annotation["source"] = fields[1]
# Annotation type
annotation["type"] = fields[2]
# Start and stop
annotation["start"] = int(fields[3])
annotation["stop"] = int(fields[4])
# Optional score field
if fields[5] != ".":
annotation["score"] = float(fields[5])
# Strand
if fields[6] == "+" or fields[6] == "-" or fields[6] == "?" or fields[6] == ".":
annotation["strand"] = fields[6]
# Phase
if fields[7] != ".":
annotation["phase"] = int(fields[7]) % 3
else:
annotation["phase"] = fields[7]
return annotation
def _process_attributes(self, text):
attributes = {}
# double the separators to keep track of them
text = text.replace("=", "===").replace(";", ";;;")
# ugly but fast replacement
text = text.replace("%09", "\t").replace("%0A", "\n").replace("%0D", "\r").replace("%25", "%")
text = text.replace("%3B", ";").replace("%3D", "=").replace("%26", "&").replace("%2C", ",")
# split into mutliple attributes
split = text.split(";;;")
for attr in split:
# make sure there is no trailing spaces
attr = attr.strip()
# find the separator. Sometimes it is spaces, sometimes a = sign
idx = attr.find("===")
if idx == -1:
idx = attr.find(" ")
# parse tags and associated values
#value = self.decode_complete(attr[idx + 1 :])
value = attr[idx + 3 :]
if len(value) == 1:
value = value[0]
#attributes[self.decode_complete(attr[:idx])] = value
attributes[attr[:idx]] = value
return attributes
def create_files_for_rnadiff(
self,
outname,
genetic_type="gene",
ID="Name",
fields=["Name"],
merge_identical_id=True,
| |
<gh_stars>1000+
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
""" test nn ops """
import numpy as np
import pytest
import mindspore
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor, Parameter
from mindspore.common.initializer import initializer
from mindspore.ops import composite as C
from mindspore.ops import operations as P
from mindspore.ops import functional as F
from mindspore.ops.operations import _grad_ops as G
from mindspore.ops import prim_attr_register, PrimitiveWithInfer
from mindspore._c_expression import security
from tests.security_utils import security_off_wrap
from ..ut_filter import non_graph_engine
from ....mindspore_test_framework.mindspore_test import mindspore_test
from ....mindspore_test_framework.pipeline.forward.compile_forward \
import pipeline_for_compile_forward_ge_graph_for_case_by_case_config
from ....mindspore_test_framework.pipeline.forward.verify_exception \
import pipeline_for_verify_exception_for_case_by_case_config
context.set_context(mode=context.GRAPH_MODE)
def conv3x3(in_channels, out_channels, stride=1, padding=1):
"""3x3 convolution """
return nn.Conv2d(in_channels, out_channels,
kernel_size=3, stride=stride, padding=padding)
def conv1x1(in_channels, out_channels, stride=1, padding=0):
"""1x1 convolution"""
return nn.Conv2d(in_channels, out_channels,
kernel_size=1, stride=stride, padding=padding)
grad = C.GradOperation()
grad_all_with_sens = C.GradOperation(get_all=True, sens_param=True)
class ResidualBlock(nn.Cell):
"""
residual Block
"""
expansion = 4
def __init__(self,
in_channels,
out_channels,
stride=1,
down_sample=False):
super(ResidualBlock, self).__init__()
out_chls = out_channels // self.expansion
self.conv1 = conv1x1(in_channels, out_chls, stride=1, padding=0)
self.bn1 = nn.BatchNorm2d(out_chls)
self.conv2 = conv3x3(out_chls, out_chls, stride=stride, padding=0)
self.bn2 = nn.BatchNorm2d(out_chls)
self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
self.bn3 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU()
self.downsample = down_sample
self.conv_down_sample = conv1x1(in_channels, out_channels,
stride=stride, padding=0)
self.bn_down_sample = nn.BatchNorm2d(out_channels)
self.add = P.Add()
def construct(self, x):
"""
:param x:
:return:
"""
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample:
identity = self.conv_down_sample(identity)
identity = self.bn_down_sample(identity)
out = self.add(out, identity)
out = self.relu(out)
return out
class VirtualLossGrad(PrimitiveWithInfer):
""" VirtualLossGrad definition """
@prim_attr_register
def __init__(self):
"""init VirtualLossGrad"""
def __call__(self, x, out, dout):
raise NotImplementedError
def infer_shape(self, x_shape, out_shape, dout_shape):
return x_shape
def infer_dtype(self, x_dtype, out_dtype, dout_dtype):
return x_dtype
class VirtualLoss(PrimitiveWithInfer):
""" VirtualLoss definition """
@prim_attr_register
def __init__(self):
"""init VirtualLoss"""
def __call__(self, x):
raise NotImplementedError
def get_bprop(self):
loss_grad = VirtualLossGrad()
def bprop(x, out, dout):
# pylint: disable=unused-argument
dx = loss_grad(x, out, dout)
return (dx,)
return bprop
def infer_shape(self, x_shape):
return []
def infer_dtype(self, x_dtype):
return x_dtype
class VirtualNetWithLoss(nn.Cell):
""" VirtualNetWithLoss definition """
def __init__(self, network):
super(VirtualNetWithLoss, self).__init__()
self.loss = VirtualLoss()
self.network = network
def construct(self, x):
predict = self.network(x)
return self.loss(predict)
class SoftMaxGrad(nn.Cell):
""" SoftMaxGrad definition """
def __init__(self, network):
super(SoftMaxGrad, self).__init__()
self.network = network
def construct(self, x):
return grad(self.network)(x)
class DropoutGrad(nn.Cell):
""" DropoutGrad definition """
def __init__(self, network):
super(DropoutGrad, self).__init__()
self.network = network
def construct(self, x):
return grad(self.network)(x)
class ScalarSummaryNet(nn.Cell):
""" ScalarSummaryNet definition """
def __init__(self):
super(ScalarSummaryNet, self).__init__()
self.summary = P.ScalarSummary()
def construct(self, scalar):
string_in = "bias_value"
out = self.summary(string_in, scalar)
return out
class L2NormalizeNet(nn.Cell):
""" L2NormalizeNet definition """
def __init__(self):
super(L2NormalizeNet, self).__init__()
self.l2_normalize = P.L2Normalize()
def construct(self, x):
out = self.l2_normalize(x)
return out
class HistogramSummaryNet(nn.Cell):
"""HistogramSummaryNet definition"""
def __init__(self):
super(HistogramSummaryNet, self).__init__()
self.summary = P.HistogramSummary()
def construct(self, tensor):
string_in = "wight_value"
out = self.summary(string_in, tensor)
return out
class FusedBatchNormGrad(nn.Cell):
""" FusedBatchNormGrad definition """
def __init__(self, network):
super(FusedBatchNormGrad, self).__init__()
self.grad = C.GradOperation(get_all=True, sens_param=True)
self.network = network
def construct(self, inp, output_grad):
return self.grad(self.network)(inp, output_grad)
class NetWithLoss(nn.Cell):
""" NetWithLoss definition """
def __init__(self, network):
super(NetWithLoss, self).__init__()
self.loss = P.SmoothL1Loss()
self.network = network
def construct(self, x, label):
predict = self.network(x)
return self.loss(predict, label)
class Grad(nn.Cell):
""" GradWrap definition """
def __init__(self, network):
super(Grad, self).__init__()
self.network = network
self.network.set_train()
def construct(self, x, label):
return grad(self.network)(x, label)
class BatchnormNet(nn.Cell):
""" BatchnormNet definition """
def __init__(self):
super(BatchnormNet, self).__init__()
self.conv1 = nn.Conv2d(3, 4, kernel_size=8, stride=2, pad_mode="pad", padding=3)
self.bn1 = nn.BatchNorm2d(4)
self.flatten = P.Flatten()
self.weight = Parameter(Tensor(np.ones([64, 10], np.float32)), name="weight")
self.bias = Parameter(Tensor(np.ones([10], np.float32)), name="bias")
self.fc = P.MatMul()
self.biasAdd = P.BiasAdd()
def construct(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.flatten(x)
x = self.biasAdd(self.fc(x, self.weight), self.bias)
return x
class NetWithLossClass(nn.Cell):
""" NetWithLossClass definition """
def __init__(self, network):
super(NetWithLossClass, self).__init__(auto_prefix=False)
self.loss = nn.SoftmaxCrossEntropyWithLogits()
self.network = network
def construct(self, x, label):
predict = self.network(x)
return self.loss(predict, label)
class BlockNet(nn.Cell):
""" BlockNet definition """
def __init__(self):
super(BlockNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, pad_mode="pad", padding=3)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU()
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2)
self.block_down_sample = ResidualBlock(
64, 256, stride=1, down_sample=True
)
self.flatten = P.Flatten()
self.weight = Parameter(Tensor(np.ones([1024, 10]).astype(np.float32)), name="weight")
self.bias = Parameter(Tensor(np.ones([10]).astype((np.float32))), name="bias")
self.fc = P.MatMul()
self.biasAdd = P.BiasAdd()
def construct(self, x):
x = self.conv1(x)
return x
class Conv2dWithBiasNet(nn.Cell):
""" Conv2dWithBiasNet definition """
def __init__(self):
super(Conv2dWithBiasNet, self).__init__()
self.conv = nn.Conv2d(3, 10, 1, bias_init='zeros')
self.flatten = P.Flatten()
def construct(self, input_x):
return self.flatten(self.conv(input_x))
class Conv2dNativeNet(nn.Cell):
""" Conv2dNativeNet definition """
def __init__(self):
super(Conv2dNativeNet, self).__init__()
self.conv = P.DepthwiseConv2dNative(channel_multiplier=3, kernel_size=(3, 3))
self.flatten = P.Flatten()
channel_multipliers = 1
in_channels = 3
kernel_size = (3, 3)
self.weight = Parameter(initializer(
Tensor(np.ones([channel_multipliers, in_channels, *kernel_size], dtype=np.float32)),
[channel_multipliers, in_channels, *kernel_size]), name='weight')
def construct(self, input_x):
return self.flatten(self.conv(input_x, self.weight))
class StateNet(nn.Cell):
""" StateTestTensor definition """
def __init__(self):
super(StateNet, self).__init__()
weight = Tensor(np.ones([2, 1, 2, 2], np.float32))
self.s1 = Parameter(weight, name="s1")
self.s2 = Parameter(weight, name="s2")
self.sub = P.Sub()
self.loss = nn.SoftmaxCrossEntropyWithLogits()
self.assign = P.Assign()
def construct(self, x):
x = F.depend(x, self.assign(self.s1, x + self.s1))
self.s1 = self.sub(self.s1, x)
self.s2 = self.sub(self.s2, x)
return x
def test_conv2d_same_primitive():
class Conv2DSameNet(nn.Cell):
def __init__(self):
super(Conv2DSameNet, self).__init__()
self.conv1 = nn.Conv2d(16, 64, (1, 41), (1, 4), "same", 0, 1, has_bias=True)
self.conv2 = nn.Conv2d(16, 64, (1, 41), (1, 4), "same", 0, 1, has_bias=True)
def construct(self, x, y):
r1 = self.conv1(x)
r2 = self.conv2(y)
return (r1, r2)
t1 = Tensor(np.ones([1, 16, 1, 1918]).astype(np.float32))
t2 = Tensor(np.ones([1, 16, 1, 3840]).astype(np.float32))
net = Conv2DSameNet()
net(t1, t2)
class ComparisonNet(nn.Cell):
def __init__(self):
""" ComparisonNet definition """
super(ComparisonNet, self).__init__()
def construct(self, x, y):
ret = x <= y
return ret
def test_max_pool_with_arg_max():
class NetMaxPoolWithArgMax(nn.Cell):
def __init__(self):
""" ComparisonNet definition """
super(NetMaxPoolWithArgMax, self).__init__()
self.max_pool_with_arg_max = P.MaxPoolWithArgmax(pad_mode="valid", kernel_size=2, strides=1)
def construct(self, x):
ret = self.max_pool_with_arg_max(x)
return ret
x = Tensor(np.ones([1, 1, 3, 3], np.float32))
net = NetMaxPoolWithArgMax()
context.set_context(mode=context.GRAPH_MODE)
ret = net(x)
print(ret)
class GradWrapUnfold(nn.Cell):
""" GradWrapUnfold definition """
def __init__(self, network):
super(GradWrapUnfold, self).__init__()
self.network = network
self.sens = Tensor(np.ones([1, 4, 2, 2], np.float32))
def construct(self, x):
return grad_all_with_sens(self.network)(x, self.sens)
class UnfoldNetValid(nn.Cell):
""" UnfoldNetValid definition """
def __init__(self):
super(UnfoldNetValid, self).__init__()
self.unfold = nn.Unfold(ksizes=[1, 2, 2, 1],
strides=[1, 1, 1, 1],
rates=[1, 1, 1, 1],
padding='VALID')
def construct(self, x):
return self.unfold(x)
class UnfoldNetSame(nn.Cell):
""" UnfoldNetSame definition """
def __init__(self):
super(UnfoldNetSame, self).__init__()
self.unfold = nn.Unfold(ksizes=[1, 2, 2, 1],
strides=[1, 1, 1, 1],
rates=[1, 1, 1, 1],
padding='SAME')
def construct(self, x):
return self.unfold(x)
class FlattenNet(nn.Cell):
""" FlattenNet definition """
def __init__(self):
super(FlattenNet, self).__init__()
self.flatten = P.Flatten()
def construct(self, x):
return self.flatten(x)
class PReLUNet(nn.Cell):
""" PReLUNet definition """
def __init__(self):
super(PReLUNet, self).__init__()
self.prelu = P.PReLU()
self.w = Tensor(np.ones(3, np.float32))
def construct(self, x):
return self.prelu(x, self.w)
class PReLUGradNet(nn.Cell):
""" PReLUGradNet definition """
def __init__(self):
super(PReLUGradNet, self).__init__()
self.prelu_grad = G.PReLUGrad()
def construct(self, dout, x, w):
return self.prelu_grad(dout, x, w)
class LRNNet(nn.Cell):
""" LRNNet definition """
def __init__(self):
super(LRNNet, self).__init__()
self.lrn = P.LRN()
def construct(self, x):
return self.lrn(x)
class LRNGradNet(nn.Cell):
""" LRNGradNet definition """
def __init__(self):
super(LRNGradNet, self).__init__()
self.lrn_grad = G.LRNGrad()
def construct(self, dout, x, out):
return self.lrn_grad(dout, x, out)
test_cases = [
('SoftMaxGrad', {
'block': SoftMaxGrad(VirtualNetWithLoss(P.Softmax())),
'desc_inputs': [[128, 32, 32, 64]],
'desc_bprop': [[128, 32, 32, 64]],
}),
('DropoutGrad', {
'block': DropoutGrad(VirtualNetWithLoss(nn.Dropout())),
'desc_inputs': [[128, 32, 32, 64]],
'desc_bprop': [[128, 32, 32, 64]],
}),
('L2Normalize', {
'block': L2NormalizeNet(),
'desc_inputs': [Tensor(np.array([[1.0, 2, 3], [4.0, 5, 6], [7.0, 8, 9]]), mindspore.float32)],
}),
('FusedBatchNormGrad', {
'block': FusedBatchNormGrad(nn.BatchNorm2d(num_features=512, eps=1e-5, momentum=0.1)),
'desc_inputs': [[64, 512, 7, 7], [64, 512, 7, 7]],
'desc_bprop': [[64, 512, 7, 7]],
}),
('BatchnormGrad', {
'block': Grad(NetWithLoss(BatchnormNet())),
'desc_inputs': [Tensor(np.ones([1, 3, 8, 8], np.float32)), Tensor(np.zeros([1, 10], np.float32))],
}),
('BlockGrad', {
'block': Grad(NetWithLossClass(BlockNet())),
'desc_inputs': [Tensor(np.ones([1, 3, 8, 8], np.float32)), Tensor(np.zeros([1, 64, 4, 4], np.float32))],
}),
('Conv2dWithBiasGrad', {
'block': Grad(NetWithLossClass(Conv2dWithBiasNet())),
'desc_inputs': [Tensor(np.ones([1, 3, 16, 16], np.float32)), Tensor(np.zeros([1, 2560], np.float32))],
}),
('Conv2dNativeGrad', {
'block': Grad(NetWithLossClass(Conv2dNativeNet())),
'desc_inputs': [Tensor(np.ones([1, 3, 16, 16], np.float32)), Tensor(np.zeros([1, 1764], np.float32))],
}),
('StateTest', {
'block': StateNet(),
'desc_inputs': [Tensor(np.ones([2, 1, 2, 2]).astype(np.float32))],
}),
('StateGrad', | |
the daily maintenance window for a cluster."""
# Special behavior for removing the window. This actually removes the
# recurring window too, if set (since anyone using this command if there's
# actually a recurring window probably intends that!).
if maintenance_window == 'None':
daily_window = None
else:
daily_window = self.messages.DailyMaintenanceWindow(
startTime=maintenance_window)
if existing_policy is None:
existing_policy = self.messages.MaintenancePolicy()
if existing_policy.window is None:
existing_policy.window = self.messages.MaintenanceWindow()
# Temporary until in GA:
if hasattr(existing_policy.window, 'recurringWindow'):
existing_policy.window.recurringWindow = None
existing_policy.window.dailyMaintenanceWindow = daily_window
return self._SendMaintenancePolicyRequest(cluster_ref, existing_policy)
def DeleteCluster(self, cluster_ref):
"""Delete a running cluster.
Args:
cluster_ref: cluster Resource to describe
Returns:
Cluster message.
Raises:
Error: if cluster cannot be found or caller is missing permissions. Will
attempt to find similar clusters in other zones for a more useful error
if the user has list permissions.
"""
try:
operation = self.client.projects_locations_clusters.Delete(
self.messages.ContainerProjectsLocationsClustersDeleteRequest(
name=ProjectLocationCluster(cluster_ref.projectId, cluster_ref
.zone, cluster_ref.clusterId)))
return self.ParseOperation(operation.name, cluster_ref.zone)
except apitools_exceptions.HttpNotFoundError as error:
api_error = exceptions.HttpException(error, util.HTTP_ERROR_FORMAT)
# Cluster couldn't be found, maybe user got the location wrong?
self.CheckClusterOtherZones(cluster_ref, api_error)
def ListClusters(self, project, location=None):
if not location:
location = '-'
req = self.messages.ContainerProjectsLocationsClustersListRequest(
parent=ProjectLocation(project, location))
return self.client.projects_locations_clusters.List(req)
def CreateNodePoolCommon(self, node_pool_ref, options):
"""Returns a CreateNodePool operation."""
node_config = self.messages.NodeConfig()
if options.machine_type:
node_config.machineType = options.machine_type
if options.disk_size_gb:
node_config.diskSizeGb = options.disk_size_gb
if options.disk_type:
node_config.diskType = options.disk_type
if options.image_type:
node_config.imageType = options.image_type
custom_config = self.messages.CustomImageConfig()
if options.image:
custom_config.image = options.image
if options.image_project:
custom_config.imageProject = options.image_project
if options.image_family:
custom_config.imageFamily = options.image_family
if options.image or options.image_project or options.image_family:
node_config.nodeImageConfig = custom_config
NodeIdentityOptionsToNodeConfig(options, node_config)
if options.local_ssd_count:
node_config.localSsdCount = options.local_ssd_count
if options.local_ssd_volume_configs:
self._AddLocalSSDVolumeConfigsToNodeConfig(node_config, options)
if options.boot_disk_kms_key:
node_config.bootDiskKmsKey = options.boot_disk_kms_key
if options.tags:
node_config.tags = options.tags
else:
node_config.tags = []
if options.accelerators is not None:
type_name = options.accelerators['type']
# Accelerator count defaults to 1.
count = int(options.accelerators.get('count', 1))
node_config.accelerators = [
self.messages.AcceleratorConfig(
acceleratorType=type_name, acceleratorCount=count)
]
_AddMetadataToNodeConfig(node_config, options)
_AddNodeLabelsToNodeConfig(node_config, options)
self._AddNodeTaintsToNodeConfig(node_config, options)
if options.preemptible:
node_config.preemptible = options.preemptible
if options.min_cpu_platform is not None:
node_config.minCpuPlatform = options.min_cpu_platform
_AddWorkloadMetadataToNodeConfig(node_config, options, self.messages)
_AddLinuxNodeConfigToNodeConfig(node_config, options, self.messages)
_AddShieldedInstanceConfigToNodeConfig(node_config, options, self.messages)
_AddReservationAffinityToNodeConfig(node_config, options, self.messages)
_AddSandboxConfigToNodeConfig(node_config, options, self.messages)
pool = self.messages.NodePool(
name=node_pool_ref.nodePoolId,
initialNodeCount=options.num_nodes,
config=node_config,
version=options.node_version,
management=self._GetNodeManagement(options))
if options.enable_autoscaling:
pool.autoscaling = self.messages.NodePoolAutoscaling(
enabled=options.enable_autoscaling,
minNodeCount=options.min_nodes,
maxNodeCount=options.max_nodes)
if options.max_pods_per_node is not None:
pool.maxPodsConstraint = self.messages.MaxPodsConstraint(
maxPodsPerNode=options.max_pods_per_node)
if (options.max_surge_upgrade is not None or
options.max_unavailable_upgrade is not None):
pool.upgradeSettings = self.messages.UpgradeSettings()
pool.upgradeSettings.maxSurge = options.max_surge_upgrade
pool.upgradeSettings.maxUnavailable = options.max_unavailable_upgrade
if options.node_locations is not None:
pool.locations = sorted(options.node_locations)
if options.node_config is not None:
util.LoadNodeConfigFromYAML(node_config, options.node_config,
self.messages)
return pool
def CreateNodePool(self, node_pool_ref, options):
"""CreateNodePool creates a node pool and returns the operation."""
pool = self.CreateNodePoolCommon(node_pool_ref, options)
if options.enable_autoprovisioning is not None:
pool.autoscaling.autoprovisioned = options.enable_autoprovisioning
req = self.messages.CreateNodePoolRequest(
nodePool=pool,
parent=ProjectLocationCluster(node_pool_ref.projectId,
node_pool_ref.zone,
node_pool_ref.clusterId))
operation = self.client.projects_locations_clusters_nodePools.Create(req)
return self.ParseOperation(operation.name, node_pool_ref.zone)
def ListNodePools(self, cluster_ref):
req = self.messages.ContainerProjectsLocationsClustersNodePoolsListRequest(
parent=ProjectLocationCluster(cluster_ref.projectId, cluster_ref.zone,
cluster_ref.clusterId))
return self.client.projects_locations_clusters_nodePools.List(req)
def GetNodePool(self, node_pool_ref):
req = self.messages.ContainerProjectsLocationsClustersNodePoolsGetRequest(
name=ProjectLocationClusterNodePool(
node_pool_ref.projectId, node_pool_ref.zone,
node_pool_ref.clusterId, node_pool_ref.nodePoolId))
return self.client.projects_locations_clusters_nodePools.Get(req)
def UpdateNodePoolNodeManagement(self, node_pool_ref, options):
"""Updates node pool's node management configuration.
Args:
node_pool_ref: node pool Resource to update.
options: node pool update options
Returns:
Updated node management configuration.
"""
pool = self.GetNodePool(node_pool_ref)
node_management = pool.management
if node_management is None:
node_management = self.messages.NodeManagement()
if options.enable_autorepair is not None:
node_management.autoRepair = options.enable_autorepair
if options.enable_autoupgrade is not None:
node_management.autoUpgrade = options.enable_autoupgrade
return node_management
def UpdateNodePoolAutoscaling(self, node_pool_ref, options):
"""Update node pool's autoscaling configuration.
Args:
node_pool_ref: node pool Resource to update.
options: node pool update options
Returns:
Updated autoscaling configuration for the node pool.
"""
pool = self.GetNodePool(node_pool_ref)
autoscaling = pool.autoscaling
if autoscaling is None:
autoscaling = self.messages.NodePoolAutoscaling()
if options.enable_autoscaling is not None:
autoscaling.enabled = options.enable_autoscaling
if not autoscaling.enabled:
# clear limits and autoprovisioned when disabling autoscaling
autoscaling.minNodeCount = 0
autoscaling.maxNodeCount = 0
autoscaling.autoprovisioned = False
if options.enable_autoprovisioning is not None:
autoscaling.autoprovisioned = options.enable_autoprovisioning
if autoscaling.autoprovisioned:
# clear min nodes limit when enabling autoprovisioning
autoscaling.minNodeCount = 0
if options.max_nodes is not None:
autoscaling.maxNodeCount = options.max_nodes
if options.min_nodes is not None:
autoscaling.minNodeCount = options.min_nodes
return autoscaling
def UpdateUpgradeSettings(self, node_pool_ref, options):
"""Updates node pool's upgrade setting."""
pool = self.GetNodePool(node_pool_ref)
upgrade_settings = pool.upgradeSettings
if upgrade_settings is None:
upgrade_settings = self.messages.UpgradeSettings()
if options.max_surge_upgrade is not None:
upgrade_settings.maxSurge = options.max_surge_upgrade
if options.max_unavailable_upgrade is not None:
upgrade_settings.maxUnavailable = options.max_unavailable_upgrade
return upgrade_settings
def UpdateNodePool(self, node_pool_ref, options):
"""Updates nodePool on a cluster."""
if options.IsAutoscalingUpdate():
autoscaling = self.UpdateNodePoolAutoscaling(node_pool_ref, options)
update = self.messages.ClusterUpdate(
desiredNodePoolId=node_pool_ref.nodePoolId,
desiredNodePoolAutoscaling=autoscaling)
operation = self.client.projects_locations_clusters.Update(
self.messages.UpdateClusterRequest(
name=ProjectLocationCluster(node_pool_ref.projectId,
node_pool_ref.zone,
node_pool_ref.clusterId),
update=update))
return self.ParseOperation(operation.name, node_pool_ref.zone)
elif options.IsNodePoolManagementUpdate():
management = self.UpdateNodePoolNodeManagement(node_pool_ref, options)
req = (
self.messages.SetNodePoolManagementRequest(
name=ProjectLocationClusterNodePool(node_pool_ref.projectId,
node_pool_ref.zone,
node_pool_ref.clusterId,
node_pool_ref.nodePoolId),
management=management))
operation = (
self.client.projects_locations_clusters_nodePools.SetManagement(req))
else:
raise util.Error('Unhandled node pool update mode')
return self.ParseOperation(operation.name, node_pool_ref.zone)
def DeleteNodePool(self, node_pool_ref):
operation = self.client.projects_locations_clusters_nodePools.Delete(
self.messages.ContainerProjectsLocationsClustersNodePoolsDeleteRequest(
name=ProjectLocationClusterNodePool(
node_pool_ref.projectId, node_pool_ref.zone,
node_pool_ref.clusterId, node_pool_ref.nodePoolId)))
return self.ParseOperation(operation.name, node_pool_ref.zone)
def RollbackUpgrade(self, node_pool_ref):
operation = self.client.projects_locations_clusters_nodePools.Rollback(
self.messages.RollbackNodePoolUpgradeRequest(
name=ProjectLocationClusterNodePool(
node_pool_ref.projectId, node_pool_ref.zone,
node_pool_ref.clusterId, node_pool_ref.nodePoolId)))
return self.ParseOperation(operation.name, node_pool_ref.zone)
def CancelOperation(self, op_ref):
req = self.messages.CancelOperationRequest(
name=ProjectLocationOperation(op_ref.projectId, op_ref.zone,
op_ref.operationId))
return self.client.projects_locations_operations.Cancel(req)
def IsRunning(self, cluster):
return (
cluster.status == self.messages.Cluster.StatusValueValuesEnum.RUNNING)
def IsDegraded(self, cluster):
return (
cluster.status == self.messages.Cluster.StatusValueValuesEnum.DEGRADED)
def GetDegradedWarning(self, cluster):
if cluster.conditions:
codes = [condition.code for condition in cluster.conditions]
messages = [condition.message for condition in cluster.conditions]
return ('Codes: {0}\n' 'Messages: {1}.').format(codes, messages)
else:
return gke_constants.DEFAULT_DEGRADED_WARNING
def GetOperationError(self, operation):
return operation.statusMessage
def ListOperations(self, project, location=None):
if not location:
location = '-'
req = self.messages.ContainerProjectsLocationsOperationsListRequest(
parent=ProjectLocation(project, location))
return self.client.projects_locations_operations.List(req)
def IsOperationFinished(self, operation):
return (
operation.status == self.messages.Operation.StatusValueValuesEnum.DONE)
def GetServerConfig(self, project, location):
req = self.messages.ContainerProjectsLocationsGetServerConfigRequest(
name=ProjectLocation(project, location))
return self.client.projects_locations.GetServerConfig(req)
def ResizeNodePool(self, cluster_ref, pool_name, size):
req = self.messages.SetNodePoolSizeRequest(
name=ProjectLocationClusterNodePool(cluster_ref.projectId,
cluster_ref.zone,
cluster_ref.clusterId, pool_name),
nodeCount=size)
operation = self.client.projects_locations_clusters_nodePools.SetSize(req)
return self.ParseOperation(operation.name, cluster_ref.zone)
def _GetNodeManagement(self, options):
"""Gets a wrapper containing the options for how nodes are managed.
Args:
options: node management options
Returns:
A NodeManagement object that contains the options indicating how nodes
are managed. This is currently quite simple, containing only two options.
However, there are more options planned for node management.
"""
if options.enable_autorepair is None and options.enable_autoupgrade is None:
return None
node_management = self.messages.NodeManagement()
node_management.autoRepair = options.enable_autorepair
node_management.autoUpgrade = options.enable_autoupgrade
return node_management
def UpdateLabelsCommon(self, cluster_ref, update_labels):
"""Update labels on a cluster.
Args:
cluster_ref: cluster to update.
update_labels: labels to set.
Returns:
Operation ref for label set operation.
"""
clus = None
try:
clus = self.GetCluster(cluster_ref)
except apitools_exceptions.HttpNotFoundError:
pass
except apitools_exceptions.HttpError as error:
raise exceptions.HttpException(error, util.HTTP_ERROR_FORMAT)
labels = self.messages.SetLabelsRequest.ResourceLabelsValue()
props = []
for k, v in sorted(six.iteritems(update_labels)):
props.append(labels.AdditionalProperty(key=k, value=v))
labels.additionalProperties = props
return labels, clus.labelFingerprint
def UpdateLabels(self, cluster_ref, update_labels):
"""Updates labels for a cluster."""
labels, fingerprint = self.UpdateLabelsCommon(cluster_ref, update_labels)
operation = self.client.projects_locations_clusters.SetResourceLabels(
self.messages.SetLabelsRequest(
name=ProjectLocationCluster(cluster_ref.projectId, cluster_ref.zone,
cluster_ref.clusterId),
resourceLabels=labels,
labelFingerprint=fingerprint))
return self.ParseOperation(operation.name, cluster_ref.zone)
def RemoveLabelsCommon(self, cluster_ref, remove_labels):
"""Removes labels from a cluster.
Args:
cluster_ref: cluster to update.
remove_labels: labels to remove.
Returns:
Operation ref for label set operation.
"""
clus = None
try:
clus = self.GetCluster(cluster_ref)
except apitools_exceptions.HttpNotFoundError:
pass
except apitools_exceptions.HttpError as error:
raise exceptions.HttpException(error, util.HTTP_ERROR_FORMAT)
clus_labels = {}
if clus.resourceLabels:
for item in clus.resourceLabels.additionalProperties:
clus_labels[item.key] = str(item.value)
# if clusLabels empty, nothing to do
if not clus_labels:
raise util.Error(NO_LABELS_ON_CLUSTER_ERROR_MSG.format(cluster=clus.name))
for k in remove_labels:
try:
clus_labels.pop(k)
except KeyError as error:
# if at least one label not found on cluster, raise error
raise util.Error(
NO_SUCH_LABEL_ERROR_MSG.format(cluster=clus.name, name=k))
labels = self.messages.SetLabelsRequest.ResourceLabelsValue()
for k, v in sorted(six.iteritems(clus_labels)):
labels.additionalProperties.append(
labels.AdditionalProperty(key=k, value=v))
return labels, clus.labelFingerprint
def RemoveLabels(self, cluster_ref, remove_labels):
"""Removes labels from a cluster."""
labels, fingerprint = self.RemoveLabelsCommon(cluster_ref, remove_labels)
operation = self.client.projects_locations_clusters.SetResourceLabels(
self.messages.SetLabelsRequest(
name=ProjectLocationCluster(cluster_ref.projectId, cluster_ref.zone,
cluster_ref.clusterId),
resourceLabels=labels,
labelFingerprint=fingerprint))
return self.ParseOperation(operation.name, cluster_ref.zone)
def GetIamPolicy(self, cluster_ref):
raise NotImplementedError('GetIamPolicy is not overridden')
def SetIamPolicy(self, cluster_ref):
raise NotImplementedError('GetIamPolicy is not overridden')
def SetRecurringMaintenanceWindow(self, cluster_ref, existing_policy,
window_start, window_end,
window_recurrence):
"""Sets a recurring maintenance window as the maintenance policy for a cluster.
Args:
cluster_ref: The cluster to update.
existing_policy: The existing maintenance policy, if any.
window_start: Start time of the window as a datetime.datetime.
window_end: End time of the window as a datetime.datetime.
window_recurrence: RRULE str defining how the window will recur.
Returns:
The operation from this cluster update.
"""
recurring_window = self.messages.RecurringTimeWindow(
window=self.messages.TimeWindow(
startTime=window_start.isoformat(),
endTime=window_end.isoformat()),
recurrence=window_recurrence)
if existing_policy is None:
existing_policy = self.messages.MaintenancePolicy()
if existing_policy.window is None:
existing_policy.window = self.messages.MaintenanceWindow()
existing_policy.window.dailyMaintenanceWindow = None
existing_policy.window.recurringWindow = recurring_window
return self._SendMaintenancePolicyRequest(cluster_ref, existing_policy)
def RemoveMaintenanceWindow(self, cluster_ref, existing_policy):
"""Removes the recurring or daily maintenance policy."""
if (existing_policy | |
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This module uprevs Chrome for cbuildbot.
After calling, it prints outs CHROME_VERSION_ATOM=(version atom string). A
caller could then use this atom with emerge to build the newly uprevved version
of Chrome e.g.
./cros_mark_chrome_as_stable tot
Returns chrome-base/chromeos-chrome-8.0.552.0_alpha_r1
emerge-x86-generic =chrome-base/chromeos-chrome-8.0.552.0_alpha_r1
"""
from __future__ import print_function
import base64
import distutils.version
import filecmp
import optparse # pylint: disable=deprecated-module
import os
import re
import urlparse
from chromite.cbuildbot import constants
from chromite.lib import cros_build_lib
from chromite.lib import cros_logging as logging
from chromite.lib import git
from chromite.lib import gob_util
from chromite.lib import portage_util
from chromite.lib import timeout_util
from chromite.scripts import cros_mark_as_stable
# Helper regex's for finding ebuilds.
_CHROME_VERSION_REGEX = r'\d+\.\d+\.\d+\.\d+'
_NON_STICKY_REGEX = r'%s[(_rc.*)|(_alpha.*)]+' % _CHROME_VERSION_REGEX
# Dir where all the action happens.
_OVERLAY_DIR = '%(srcroot)s/third_party/chromiumos-overlay/'
_GIT_COMMIT_MESSAGE = ('Marking %(chrome_rev)s for %(chrome_pn)s ebuild '
'with version %(chrome_version)s as stable.')
# URLs that print lists of chrome revisions between two versions of the browser.
_CHROME_VERSION_URL = ('http://omahaproxy.appspot.com/changelog?'
'old_version=%(old)s&new_version=%(new)s')
# Only print links when we rev these types.
_REV_TYPES_FOR_LINKS = [constants.CHROME_REV_LATEST,
constants.CHROME_REV_STICKY]
# TODO(szager): This is inaccurate, but is it safe to change? I have no idea.
_CHROME_SVN_TAG = 'CROS_SVN_COMMIT'
def _GetVersionContents(chrome_version_info):
"""Returns the current Chromium version, from the contents of a VERSION file.
Args:
chrome_version_info: The contents of a chromium VERSION file.
"""
chrome_version_array = []
for line in chrome_version_info.splitlines():
chrome_version_array.append(line.rpartition('=')[2])
return '.'.join(chrome_version_array)
def _GetSpecificVersionUrl(git_url, revision, time_to_wait=600):
"""Returns the Chromium version, from a repository URL and version.
Args:
git_url: Repository URL for chromium.
revision: the git revision we want to use.
time_to_wait: the minimum period before abandoning our wait for the
desired revision to be present.
"""
parsed_url = urlparse.urlparse(git_url)
host = parsed_url[1]
path = parsed_url[2].rstrip('/') + (
'/+/%s/chrome/VERSION?format=text' % revision)
# Allow for git repository replication lag with sleep/retry loop.
def _fetch():
fh = gob_util.FetchUrl(host, path, ignore_404=True)
return fh.read() if fh else None
def _wait_msg(_remaining):
logging.info('Repository does not yet have revision %s. Sleeping...',
revision)
content = timeout_util.WaitForSuccess(
retry_check=lambda x: not bool(x),
func=_fetch,
timeout=time_to_wait,
period=30,
side_effect_func=_wait_msg)
return _GetVersionContents(base64.b64decode(content))
def _GetTipOfTrunkVersionFile(root):
"""Returns the current Chromium version, from a file in a checkout.
Args:
root: path to the root of the chromium checkout.
"""
version_file = os.path.join(root, 'src', 'chrome', 'VERSION')
chrome_version_info = cros_build_lib.RunCommand(
['cat', version_file],
redirect_stdout=True,
error_message='Could not read version file at %s.' % version_file).output
return _GetVersionContents(chrome_version_info)
def CheckIfChromeRightForOS(deps_content):
"""Checks if DEPS is right for Chrome OS.
This function checks for a variable called 'buildspec_platforms' to
find out if its 'chromeos' or 'all'. If any of those values,
then it chooses that DEPS.
Args:
deps_content: Content of release buildspec DEPS file.
Returns:
True if DEPS is the right Chrome for Chrome OS.
"""
platforms_search = re.search(r'buildspec_platforms.*\s.*\s', deps_content)
if platforms_search:
platforms = platforms_search.group()
if 'chromeos' in platforms or 'all' in platforms:
return True
return False
def GetLatestRelease(git_url, branch=None):
"""Gets the latest release version from the release tags in the repository.
Args:
git_url: URL of git repository.
branch: If set, gets the latest release for branch, otherwise latest
release.
Returns:
Latest version string.
"""
# TODO(szager): This only works for public release buildspecs in the chromium
# src repository. Internal buildspecs are tracked differently. At the time
# of writing, I can't find any callers that use this method to scan for
# internal buildspecs. But there may be something lurking...
parsed_url = urlparse.urlparse(git_url)
path = parsed_url[2].rstrip('/') + '/+refs/tags?format=JSON'
j = gob_util.FetchUrlJson(parsed_url[1], path, ignore_404=False)
if branch:
chrome_version_re = re.compile(r'^%s\.\d+.*' % branch)
else:
chrome_version_re = re.compile(r'^[0-9]+\..*')
matching_versions = [key for key in j.keys() if chrome_version_re.match(key)]
matching_versions.sort(key=distutils.version.LooseVersion)
for chrome_version in reversed(matching_versions):
path = parsed_url[2].rstrip() + (
'/+/refs/tags/%s/DEPS?format=text' % chrome_version)
fh = gob_util.FetchUrl(parsed_url[1], path, ignore_404=False)
content = fh.read() if fh else None
if content:
deps_content = base64.b64decode(content)
if CheckIfChromeRightForOS(deps_content):
return chrome_version
return None
def _GetStickyEBuild(stable_ebuilds):
"""Returns the sticky ebuild."""
sticky_ebuilds = []
non_sticky_re = re.compile(_NON_STICKY_REGEX)
for ebuild in stable_ebuilds:
if not non_sticky_re.match(ebuild.version):
sticky_ebuilds.append(ebuild)
if not sticky_ebuilds:
raise Exception('No sticky ebuilds found')
elif len(sticky_ebuilds) > 1:
logging.warning('More than one sticky ebuild found')
return portage_util.BestEBuild(sticky_ebuilds)
class ChromeEBuild(portage_util.EBuild):
"""Thin sub-class of EBuild that adds a chrome_version field."""
chrome_version_re = re.compile(r'.*-(%s|9999).*' % (
_CHROME_VERSION_REGEX))
chrome_version = ''
def __init__(self, path):
portage_util.EBuild.__init__(self, path)
re_match = self.chrome_version_re.match(self.ebuild_path_no_revision)
if re_match:
self.chrome_version = re_match.group(1)
def __str__(self):
return self.ebuild_path
def FindChromeCandidates(package_dir):
"""Return a tuple of chrome's unstable ebuild and stable ebuilds.
Args:
package_dir: The path to where the package ebuild is stored.
Returns:
Tuple [unstable_ebuild, stable_ebuilds].
Raises:
Exception: if no unstable ebuild exists for Chrome.
"""
stable_ebuilds = []
unstable_ebuilds = []
for path in [
os.path.join(package_dir, entry) for entry in os.listdir(package_dir)]:
if path.endswith('.ebuild'):
ebuild = ChromeEBuild(path)
if not ebuild.chrome_version:
logging.warning('Poorly formatted ebuild found at %s' % path)
else:
if '9999' in ebuild.version:
unstable_ebuilds.append(ebuild)
else:
stable_ebuilds.append(ebuild)
# Apply some sanity checks.
if not unstable_ebuilds:
raise Exception('Missing 9999 ebuild for %s' % package_dir)
if not stable_ebuilds:
logging.warning('Missing stable ebuild for %s' % package_dir)
return portage_util.BestEBuild(unstable_ebuilds), stable_ebuilds
def FindChromeUprevCandidate(stable_ebuilds, chrome_rev, sticky_branch):
"""Finds the Chrome uprev candidate for the given chrome_rev.
Using the pre-flight logic, this means the stable ebuild you are uprevving
from. The difference here is that the version could be different and in
that case we want to find it to delete it.
Args:
stable_ebuilds: A list of stable ebuilds.
chrome_rev: The chrome_rev designating which candidate to find.
sticky_branch: The the branch that is currently sticky with Major/Minor
components. For example: 9.0.553. Can be None but not if chrome_rev
is CHROME_REV_STICKY.
Returns:
The EBuild, otherwise None if none found.
"""
candidates = []
if chrome_rev in [constants.CHROME_REV_LOCAL, constants.CHROME_REV_TOT,
constants.CHROME_REV_SPEC]:
# These are labelled alpha, for historic reasons,
# not just for the fun of confusion.
chrome_branch_re = re.compile(r'%s.*_alpha.*' % _CHROME_VERSION_REGEX)
for ebuild in stable_ebuilds:
if chrome_branch_re.search(ebuild.version):
candidates.append(ebuild)
elif chrome_rev == constants.CHROME_REV_STICKY:
assert sticky_branch is not None
chrome_branch_re = re.compile(r'%s\..*' % sticky_branch)
for ebuild in stable_ebuilds:
if chrome_branch_re.search(ebuild.version):
candidates.append(ebuild)
else:
chrome_branch_re = re.compile(r'%s.*_rc.*' % _CHROME_VERSION_REGEX)
for ebuild in stable_ebuilds:
if chrome_branch_re.search(ebuild.version):
candidates.append(ebuild)
if candidates:
return portage_util.BestEBuild(candidates)
else:
return None
def GetChromeRevisionLinkFromVersions(old_chrome_version, chrome_version):
"""Return appropriately formatted link to revision info, given versions
Given two chrome version strings (e.g. 9.0.533.0), generate a link to a
page that prints the Chromium revisions between those two versions.
Args:
old_chrome_version: version to diff from
chrome_version: version to which to diff
Returns:
The desired URL.
"""
return _CHROME_VERSION_URL % {'old': old_chrome_version,
'new': chrome_version}
def GetChromeRevisionListLink(old_chrome, new_chrome, chrome_rev):
"""Returns a link to the list of revisions between two Chromium versions
Given two ChromeEBuilds and the kind of rev we're doing, generate a
link to a page that prints the Chromium changes between those two
revisions, inclusive.
Args:
old_chrome: ebuild for the version to diff from
new_chrome: ebuild for the version to which to diff
chrome_rev: one of constants.VALID_CHROME_REVISIONS
Returns:
The desired URL.
"""
assert chrome_rev in _REV_TYPES_FOR_LINKS
return GetChromeRevisionLinkFromVersions(old_chrome.chrome_version,
new_chrome.chrome_version)
def MarkChromeEBuildAsStable(stable_candidate, unstable_ebuild, chrome_pn,
chrome_rev, chrome_version, commit, package_dir):
r"""Uprevs the chrome ebuild specified by chrome_rev.
This is the main function that uprevs the chrome_rev from a stable candidate
to its new version.
Args:
stable_candidate: ebuild that corresponds to the stable ebuild we are
revving from. If None, builds the a new ebuild given the version
and logic for chrome_rev type with revision set to 1.
unstable_ebuild: ebuild corresponding to the unstable ebuild for chrome.
chrome_pn: package name.
chrome_rev: one of constants.VALID_CHROME_REVISIONS or LOCAL
constants.CHROME_REV_SPEC - Requires commit value. Revs the ebuild for
the specified version and uses the portage suffix of _alpha.
constants.CHROME_REV_TOT - Requires commit value. Revs the ebuild for
the TOT version and uses the portage suffix of _alpha.
constants.CHROME_REV_LOCAL - Requires a chrome_root. Revs the ebuild for
the local version and uses the portage suffix of _alpha.
constants.CHROME_REV_LATEST - This uses the portage suffix of _rc as they
are release candidates for the next sticky version.
constants.CHROME_REV_STICKY - Revs the sticky version.
chrome_version: The \d.\d.\d.\d version of Chrome.
commit: Used with constants.CHROME_REV_TOT. The git revision of chrome.
package_dir: Path to the chromeos-chrome package dir.
Returns:
Full portage version atom (including rc's, etc) that was revved.
"""
def IsTheNewEBuildRedundant(new_ebuild, stable_ebuild):
"""Returns True if the new ebuild is redundant.
This | |
== "entbasek9":
subdirectory = "ENTERPRISE-BASE"
elif imagecode == "entbase":
subdirectory = "ENTERPRISE-BASE-NO-CRYPTO"
elif imagecode == "j1s3":
subdirectory = "ENTERPRISE-BASIC"
elif imagecode == "k2":
subdirectory = "ENTERPRISE-CIP2"
elif imagecode == "k2o3sv3y":
subdirectory = "IP-FW-VOICE-PLUS-IPSEC-3DES"
elif imagecode == "k2sv3y":
subdirectory = "IP-VOICE-PLUS-IPSEC-3DES"
elif imagecode == "bk2no3r2sy":
subdirectory = "IP-IPX-AT-IBM-FW-PLUS-IPSEC-3DES"
elif imagecode == "sv3y56i":
subdirectory = "IP-VOICE-PLUS-IPSEC-56"
elif imagecode == "o3sv3y56i":
subdirectory = "IP-FW-VOICE-PLUS-IPSEC-56"
elif imagecode == "k2o3sy":
subdirectory = "IP-FW-PLUS-IPSEC-3DES"
elif imagecode == "sv3y756i":
subdirectory = "IP-VOICE-PLUS-IPSEC-56-ADSL"
elif imagecode == "bno3r2sv3y56i":
subdirectory = "IP-IPX-AT-IBM-FW-VOICE-PLUS-IPSEC-56"
elif imagecode == "bk2no3r2sv3y":
subdirectory = "IP-IPX-AT-IBM-FW-VOICE-PLUS-IPSEC-3DES"
elif imagecode == "isv":
subdirectory = "IP"
# elif imagecode == "is":
# subdirectory = "IP"
elif imagecode == "isv40":
subdirectory = "IP-40"
elif imagecode == "isv56":
subdirectory = "IP-56"
elif imagecode == "c3h2s":
subdirectory = "ENTERPRISE-COMMAND-CAPABLE"
elif imagecode == "jo3s":
subdirectory = "ENTERPRISE-FW-IDS"
elif imagecode == "ainr":
subdirectory = "IP-IPX-IBM-APPN"
elif imagecode == "jo3sv":
subdirectory = "ENTERPRISE-FW-IDS"
elif imagecode == "bnr2y":
subdirectory = "IP-IPX-AT-IBM"
elif imagecode == "bnr2sy":
subdirectory = "IP-IPX-AT-IBM-PLUS"
elif imagecode == "bnr2sy40":
subdirectory = "IP-IPX-AT-IBM-PLUS-40"
elif imagecode == "bnr2sy56":
subdirectory = "IP-IPX-AT-IBM-PLUS-56"
elif imagecode == "jk2o3sv":
subdirectory = "ENTERPRISE-FW-IDS-IPSEC-3DES"
elif imagecode == "jk9o3s":
subdirectory = "ENTERPRISE-FW-IDS-IPSEC-3DES"
elif imagecode == "io3s56i":
subdirectory = "IP-FW-PLUS-IPSEC-56"
elif imagecode == "jk8o3s":
subdirectory = "ENTERPRISE-FW-IDS-IPSEC-56"
elif imagecode == "jk8o3sv":
subdirectory = "ENTERPRISE-FW-IDS-IPSEC-56"
elif imagecode == "jo3s56i":
subdirectory = "ENTERPRISE-FW-IDS-IPSEC-56"
elif imagecode == "jo3sv56i":
subdirectory = "ENTERPRISE-FW-IDS-IPSEC-56"
elif imagecode == "jk2o3s":
subdirectory = "ENTERPRISE-FW-IDS-PLUS-IPSEC-3DES"
elif imagecode == "jk9o3sv":
subdirectory = "ENTERPRISE-FW-MPLS-IPV6-SSH-3DES"
elif imagecode == "jk8os":
subdirectory = "ENTERPRISE-FW-PLUS-IPSEC-56"
elif imagecode == "jos56i":
subdirectory = "ENTERPRISE-FW-PLUS-IPSEC-56"
elif imagecode == "jk2sv":
subdirectory = "ENTERPRISE-IPSEC-3DES"
elif imagecode == "jk9s":
subdirectory = "ENTERPRISE-IPSEC-3DES"
elif imagecode == "jk9su2":
subdirectory = "ENTERPRISE-IPSEC-3DES-LAWFUL-INTERCEPT"
elif imagecode == "jk9su2v":
subdirectory = "ENTERPRISE-IPSEC-3DES-LAWFUL-INTERCEPT"
elif imagecode == "jk8s":
subdirectory = "ENTERPRISE-IPSEC-56"
elif imagecode == "jk8sv":
subdirectory = "ENTERPRISE-IPSEC-56"
elif imagecode == "jsv56i":
subdirectory = "ENTERPRISE-IPSEC-56"
elif imagecode == "jk9sv":
subdirectory = "ENTERPRISE-IPV6-SSH-3DES"
elif imagecode == "jsu2":
subdirectory = "ENTERPRISE-LAWFUL-INTERCEPT"
elif imagecode == "jx2":
subdirectory = "ENTERPRISE-MCM"
elif imagecode == "js":
subdirectory = "ENTERPRISE-PLUS"
elif imagecode == "js56":
subdirectory = "ENTERPRISE-PLUS-56"
elif imagecode == "a2jsv5x":
subdirectory = "ENTERPRISE-PLUS-H323-MCM"
elif imagecode == "jsx":
subdirectory = "ENTERPRISE-PLUS-H323-MCM"
elif imagecode == "js56i":
subdirectory = "ENTERPRISE-PLUS-IPSEC-56"
elif imagecode == "a2jsv5":
subdirectory = "ENTERPRISE-PLUS-VOIP-VOATM"
elif imagecode == "a2jk2sv5":
subdirectory = "ENTERPRISE-PLUS-VOIP-VOATM-IPSEC-3DES"
elif imagecode == "a2jk9sv5":
subdirectory = "ENTERPRISE-PLUS-VOIP-VOATM-IPSEC-3DES"
elif imagecode == "a2jk8sv5":
subdirectory = "ENTERPRISE-PLUS-VOIP-VOATM-IPSEC-56"
elif imagecode == "entservicesk9":
subdirectory = "ENTERPRISE-SERVICES"
elif imagecode == "entservicesk9_wan":
subdirectory = "ENTERPRISE-SERVICES"
elif imagecode == "entservices":
subdirectory = "ENTERPRISE-SERVICES-NO-CRYPTO"
elif imagecode == "entservices_wan":
subdirectory = "ENTERPRISE-SERVICES-NO-CRYPTO"
elif imagecode == "a3jsv":
subdirectory = "ENTERPRISE-SNASW"
elif imagecode == "a3jk2sv":
subdirectory = "ENTERPRISE-SNASW-IPSEC-3DES"
elif imagecode == "a3jk9s":
subdirectory = "ENTERPRISE-SNASW-IPSEC-3DES"
elif imagecode == "a3jk9sv":
subdirectory = "ENTERPRISE-SNASW-IPSEC-3DES"
elif imagecode == "a3jk8s":
subdirectory = "ENTERPRISE-SNASW-IPSEC-56"
elif imagecode == "a3jk8sv":
subdirectory = "ENTERPRISE-SNASW-IPSEC-56"
elif imagecode == "a3jsv56i":
subdirectory = "ENTERPRISE-SNASW-IPSEC-56"
elif imagecode == "a3js":
subdirectory = "ENTERPRISE-SNASW-PLUS"
elif imagecode == "a3jk91s":
subdirectory = "ENTERPRISE-SNASW-SSH-3DES"
elif imagecode == "g4js":
subdirectory = "ENTERPRISE-SSG"
elif imagecode == "jk2s":
subdirectory = "ENTERPRISE-SSH-3DES-LAN-ONLY"
elif imagecode == "g5js":
subdirectory = "ENTERPRISE-WIRELESS"
elif imagecode == "g5jk8s":
subdirectory = "ENTERPRISE-WIRELESS-IPSEC-56"
elif imagecode == "driversucse":
subdirectory = "E-SERIES/DRIVERS"
elif imagecode == "events":
subdirectory = "EVENTS"
elif imagecode == "fdiagsbflc":
subdirectory = "FIELD-DIAGNOSTICS-LINECARD-IMAGE"
elif imagecode == "fpd":
subdirectory = "FIELD-PROGRAMABLE-DEVICE"
elif imagecode == "fips":
subdirectory = "FIPS"
elif imagecode == "fpasamodule":
subdirectory = "FIREPOWER-ASA-MODE/ASA-MODULE"
elif imagecode == "fpasamode":
subdirectory = "FIREPOWER-ASA-MODE/FIREPOWER-MODULE"
elif imagecode == "fpasasystem":
subdirectory = "FIREPOWER-ASA-MODE/SYSTEM"
elif imagecode == "fmc":
subdirectory = "FIREPOWER-MANAGEMENT-CENTER"
elif imagecode == "firepower-mibs":
subdirectory = "FIREPOWER-MIBS"
elif imagecode == "fxos-mibs-fp9k-fp4k":
subdirectory = "FIREPOWER-MIBS-9K-4K"
elif imagecode == "firmware":
subdirectory = "FIRMWARE"
elif imagecode == "firmwareeseries":
subdirectory = "FIRMWARE"
elif imagecode == "fxos-k9-fpr4k-firmware":
subdirectory = "FIRMWARE-4K"
elif imagecode == "fxos-k9-fpr9k-firmware":
subdirectory = "FIRMWARE-9K"
elif imagecode == "epld":
subdirectory = "FIRMWARE-EPLD"
elif imagecode == "fpga":
subdirectory = "FPGA-UPGRADE"
elif imagecode == "f":
subdirectory = "FRAD"
elif imagecode == "fin":
subdirectory = "FRAD-EIGRP"
elif imagecode == "fwsmtoasasm":
subdirectory = "FWSM-TO-ASASM-CONVERSION"
elif imagecode == "fxos-k9":
subdirectory = "FXOS"
elif imagecode == "fxos-k9-kickstart":
subdirectory = "FXOS-RECOVERY/KICKSTART"
elif imagecode == "fxos-k9-manager":
subdirectory = "FXOS-RECOVERY/MANAGER"
elif imagecode == "fxos-k9-system":
subdirectory = "FXOS-RECOVERY/SYSTEM"
elif imagecode == "sfgeodb":
subdirectory = "GeoDB-SRU-VDB/Geodb"
elif imagecode == "csfgeodb":
subdirectory = "GeoDB-SRU-VDB/Geodb-6.4-AND-LATER"
elif imagecode == "sfrules":
subdirectory = "GeoDB-SRU-VDB/Rules"
elif imagecode == "csfrules":
subdirectory = "GeoDB-SRU-VDB/Rules-6.4-AND-LATER"
elif imagecode == "sfvdb":
subdirectory = "GeoDB-SRU-VDB/VDB"
elif imagecode == "csfvdb":
subdirectory = "GeoDB-SRU-VDB/VDB-6.4-AND-LATER"
elif imagecode == "lsprel":
subdirectory = "GeoDB-SRU-VDB/Lightweight-Security-Package"
elif imagecode == "g6ik9s":
subdirectory = "GGSN-4.0-3DES"
elif imagecode == "g6is":
subdirectory = "GGSN-4.0-BASE"
elif imagecode == "g6ik8s":
subdirectory = "GGSN-4.0-IPSEC"
elif imagecode == "entservices_mw":
subdirectory = "GGSN-RELEASE-6"
elif imagecode == "adventerprisek9_mw":
subdirectory = "GGSN-RELEASE-6-IPSEC"
elif imagecode == "g7is":
subdirectory = "GGSN-SERIES-4-BASE"
elif imagecode == "g8ik9s":
subdirectory = "GGSN-SERIES-6-3DES"
elif imagecode == "g8ik8s":
subdirectory = "GGSN-SERIES-6-IPSEC"
elif imagecode == "g8is":
subdirectory = "GGSN-SERIES-6-BASE"
elif imagecode == "gina":
subdirectory = "GINA-MODULE"
elif imagecode == "hardware":
subdirectory = "HARDWARE-PROGRAMMABLES"
elif imagecode == "k1v4y5":
subdirectory = "HOME-OFFICE-VOICE-(SGCP-and-H.323)"
elif imagecode == "hostscan":
subdirectory = "HOST-SCAN"
elif imagecode == "ins":
subdirectory = "IP-IPX-PLUS"
elif imagecode == "huu":
subdirectory = "HOST-UPGRADE-UTILITY"
elif imagecode == "html":
subdirectory = "HTML"
elif imagecode == "HWIC3GGSM":
subdirectory = "HWIC-3G-GSM"
elif imagecode == "HWICCABLE":
subdirectory = "HWIC-CABLE"
elif imagecode == "hyperv":
subdirectory = "HYPERv"
elif imagecode == "install":
subdirectory = "INSTALL"
elif imagecode == "installer":
subdirectory = "INSTALLER"
elif imagecode == "installer-ase":
subdirectory = "INSTALLER-ASE"
elif imagecode == "ipvoice_ivs":
subdirectory = "INT-VOICE-VIDEO,-IPIP-GW,-TDMIP-GW"
elif imagecode == "adventerprisek9_ivs":
subdirectory = "INT-VOICE-VIDEO-GK,-IPIP-GW,-TDMIP-GW-AES"
elif imagecode == "adventerprisek9_ivs_li":
subdirectory = "INT-VOICE-VIDEO-GK,-IPIP-GW,-TDMIP-GW-AES,-LI"
elif imagecode == "js_ivs":
subdirectory = "INT-VOICE-VIDEO-IPIP-GW,-TDMIP-GW"
elif imagecode == "jk9su2_ivs":
subdirectory = "INT-VOICE-VIDEO-IPIP-GW,-TDMIP-GW-LI"
elif imagecode == "ucmk9":
subdirectory = "IOS-XE-SD-WAN"
elif imagecode == "i":
subdirectory = "IP"
elif imagecode == "isv":
subdirectory = "IP"
elif imagecode == "y":
subdirectory = "IP"
elif imagecode == "y1":
subdirectory = "IP"
elif imagecode == "y6":
subdirectory = "IP"
elif imagecode == "y7":
subdirectory = "IP-ADSL"
elif imagecode == "k9o3sy7":
subdirectory = "IP-ADSL-FW-IDS-PLUS-IPSEC-3DES"
elif imagecode == "k8o3sy7":
subdirectory = "IP-ADSL-FW-IDS-PLUS-IPSEC-56"
elif imagecode == "bk9no3r2sy7":
subdirectory = "IP-ADSL-IPX-AT-IBM-FW-IDS-PLUS-IPSEC-3DES"
elif imagecode == "bk8no3r2sy7":
subdirectory = "IP-ADSL-IPX-AT-IBM-FW-IDS-PLUS-IPSEC-56"
elif imagecode == "bnr2sy7":
subdirectory = "IP-ADSL-IPX-AT-IBM-PLUS"
elif imagecode == "bk9no3r2sv3y7":
subdirectory = "IP-ADSL-IPX-AT-IBM-VOICE-FW-IDS-PLUS-IPSEC-3DES"
elif imagecode == "bk8no3r2sv3y7":
subdirectory = "IP-ADSL-IPX-AT-IBM-VOICE-FW-IDS-PLUS-IPSEC-56"
elif imagecode == "bk9no3r2sv8y7":
subdirectory = "IP-ADSL-IPX-AT-IBM-VOX-FW-IDS-PLUS-IPSEC-3DES"
elif imagecode == "bk8no3r2sv8y7":
subdirectory = "IP-ADSL-IPX-AT-IBM-VOX-FW-IDS-PLUS-IPSEC-56"
elif imagecode == "no3sy7":
subdirectory = "IP-ADSL-IPX-FW-IDS-PLUS"
elif imagecode == "no3sv3y7":
subdirectory = "IP-ADSL-IPX-VOICE-FW-IDS-PLUS"
elif imagecode == "no3sv8y7":
subdirectory = "IP-ADSL-IPX-VOX-FW-IDS-PLUS"
elif imagecode == "sy7":
subdirectory = "IP-ADSL-PLUS"
elif imagecode == "k9sy7":
subdirectory = "IP-ADSL-PLUS-IPSEC-3DES"
elif imagecode == "k8sy7":
subdirectory = "IP-ADSL-PLUS-IPSEC-56"
elif imagecode == "o3sv3y7":
subdirectory = "IP-ADSL-VOICE-FW-IDS-PLUS"
elif imagecode == "k9o3sv3y7":
subdirectory = "IP-ADSL-VOICE-FW-IDS-PLUS-IPSEC-3DES"
elif imagecode == "k8o3sv3y7":
subdirectory = "IP-ADSL-VOICE-FW-IDS-PLUS-IPSEC-56"
elif imagecode == "sv3y7":
subdirectory = "IP-ADSL-VOICE-PLUS"
elif imagecode == "k9sv3y7":
subdirectory = "IP-ADSL-VOICE-PLUS-IPSEC-3DES"
elif imagecode == "k8sv3y7":
subdirectory = "IP-ADSL-VOICE-PLUS-IPSEC-56"
elif imagecode == "o3sv8y7":
subdirectory = "IP-ADSL-VOX-FW-IDS-PLUS"
elif imagecode == "k9o3sv8y7":
subdirectory = "IP-ADSL-VOX-FW-IDS-PLUS-IPSEC-3DES"
elif imagecode == "k8o3sv8y7":
subdirectory = "IP-ADSL-VOX-FW-IDS-PLUS-IPSEC-56"
elif imagecode == "sv8y7":
subdirectory = "IP-ADSL-VOX-PLUS"
elif imagecode == "k9sv8y7":
subdirectory = "IP-ADSL-VOX-PLUS-IPSEC-3DES"
elif imagecode == "k8sv8y7":
subdirectory = "IP-ADSL-VOX-PLUS-IPSEC-56"
elif imagecode == "qy":
subdirectory = "IP-ASYNC"
elif imagecode == "by":
subdirectory = "IP-AT"
elif imagecode == "a2i5k8s":
subdirectory = "IP-ATM-PLUS-IPSEC-56-NO-ISDN"
elif imagecode == "a2i5s":
subdirectory = "IP-ATM-PLUS-NO-ISDN"
elif imagecode == "a2i8sv5":
subdirectory = "IP-ATM-VOIP-VOATM"
elif imagecode == "a2i8k8sv5":
subdirectory = "IP-ATM-VOIP-VOATM-PLUS-IPSEC-56"
elif imagecode == "i9k2":
subdirectory = "IP-BASE"
elif imagecode == "i9k2l2q3":
subdirectory = "IP-BASE"
elif imagecode == "i9k91":
subdirectory = "IP-BASE"
elif imagecode == "i9k91l2q3":
subdirectory = "IP-BASE"
elif imagecode == "ipbasek9":
subdirectory = "IP-BASE"
elif imagecode == "ipbasek9_wan":
subdirectory = "IP-BASE"
elif imagecode == "ipbasek9_access":
subdirectory = "IP-BASE-ACCESS-ONLY"
elif imagecode == "ipbase_access":
subdirectory = "IP-BASE-ACCESS-ONLY-NO-CRYPTO"
elif imagecode == "i9":
subdirectory = "IP-BASE-NO-CRYPTO"
elif imagecode == "i9q3l2":
subdirectory = "IP-BASE-NO-CRYPTO"
elif imagecode == "ipbase":
subdirectory = "IP-BASE-NO-CRYPTO"
elif imagecode == "ipbase_wan":
subdirectory = "IP-BASE-NO-CRYPTO"
elif imagecode == "ipbaselm":
subdirectory = "IP-BASE-NO-CRYPTO-WITH-EXPRESS-SETUP"
elif imagecode == "ipbasek9_npe":
subdirectory = "IP-BASE-NPE"
elif imagecode == "ipbasek9npe":
subdirectory = "IP-BASE-NPE"
elif imagecode == "ipbaselmk9":
subdirectory = "IP-BASE-WITH-EXPRESS-SETUP"
elif imagecode == "in":
subdirectory = "IP-BRIDGING"
elif imagecode == "broadband":
subdirectory = "IP-BROADBAND"
elif imagecode == "io":
subdirectory = "IP-FW"
elif imagecode == "oy":
subdirectory = "IP-FW"
elif imagecode == "oy1":
subdirectory = "IP-FW"
elif imagecode == "oy6":
subdirectory = "IP-FW"
elif imagecode == "k9o3y6":
subdirectory = "IP-FW-3DES"
elif imagecode == "k9oy1":
subdirectory = "IP-FW-3DES"
elif imagecode == "k9oy6":
subdirectory = "IP-FW-3DES"
elif imagecode == "io3":
subdirectory = "IP-FW-IDS"
elif imagecode == "io3s":
subdirectory = "IP-FW-IDS"
elif imagecode == "io3sv":
subdirectory = "IP-FW-IDS"
elif imagecode == "o3y":
subdirectory = "IP-FW-IDS"
elif imagecode == "ik2o3s":
subdirectory = "IP-FW-IDS-IPSEC-3DES"
elif imagecode == "ik2o3sv":
subdirectory = "IP-FW-IDS-IPSEC-3DES"
elif imagecode == "ik9o3s":
subdirectory = "IP-FW-IDS-IPSEC-3DES"
elif imagecode == "ik9o3sv":
subdirectory = "IP-FW-IDS-IPSEC-3DES"
elif imagecode == "ik8o3s":
subdirectory = "IP-FW-IDS-IPSEC-56"
elif imagecode == "ik8o3sv":
subdirectory = "IP-FW-IDS-IPSEC-56"
elif imagecode == "io3sv56i":
subdirectory = "IP-FW-IDS-IPSEC-56"
elif imagecode == "o3sy56i":
subdirectory = "IP-FW-IDS-PLUS-IPSEC-3DES"
elif imagecode == "ik9o3s3":
subdirectory = "IP-FW-IDS-PLUS-IPSEC-3DES-BASIC"
elif imagecode == "ik9o3s6":
subdirectory = "IP-FW-IDS-PLUS-IPSEC-3DES-BASIC-NO-ATM"
elif imagecode == "ik9o3s7":
subdirectory = "IP-FW-IDS-PLUS-IPSEC-3DES-BASIC-NO-VOICE"
elif imagecode == "k8o3sy":
subdirectory = "IP-FW-IDS-PLUS-IPSEC-56"
elif imagecode == "o3sy6":
subdirectory = "IP-FW-PLUS"
elif imagecode == "osy6":
subdirectory = "IP-FW-PLUS"
elif imagecode == "k9o3sy6":
subdirectory = "IP-FW-PLUS-3DES"
elif imagecode == "k2osy6":
subdirectory = "IP-FW-PLUS-IPSEC-3DES"
elif imagecode == "k9osy6":
subdirectory = "IP-FW-PLUS-IPSEC-3DES"
elif imagecode == "ik8os":
subdirectory = "IP-FW-PLUS-IPSEC-56"
elif imagecode == "ios56i":
subdirectory = "IP-FW-PLUS-IPSEC-56"
elif imagecode == "k8osy":
subdirectory = "IP-FW-PLUS-IPSEC-56"
elif imagecode == "k8osy6":
subdirectory = "IP-FW-PLUS-IPSEC-56"
elif imagecode == "osy56i":
subdirectory = "IP-FW-PLUS-IPSEC-56"
elif imagecode == "osy656i":
subdirectory = "IP-FW-PLUS-IPSEC-56"
elif imagecode == "k9o3s8y6":
subdirectory = "IP-FW-PLUS-ISDN-DIAL-BACKUP-3DES-VPN"
elif imagecode == "ov6y6":
subdirectory = "IP-FW-VOICE"
elif imagecode == "k9osv6y6":
subdirectory = "IP-FW-VOICE-PLUS-3DES"
elif imagecode == "k9o3sv3y":
subdirectory = "IP-FW-VOICE-PLUS-IPSEC-3DES"
elif imagecode == "ix":
subdirectory = "IP-H323"
elif imagecode == "is3x":
subdirectory = "IP-H323-PLUS-BASIC"
elif imagecode == "ai3r4":
subdirectory = "IP-IBM-APPN7"
elif imagecode == "a3i3r4":
subdirectory = "IP-IBM-SNASW"
elif imagecode == "ik2s":
subdirectory = "IP-PLUS-IPSEC-3DES"
elif imagecode == "ik9su2":
subdirectory = "IP-IPSEC-3DES-LAWFUL-INTERCEPT"
elif imagecode == "ik8sv":
subdirectory = "IP-IPSEC-56"
elif imagecode == "isv56i":
subdirectory = "IP-IPSEC-56"
elif imagecode == "ny":
subdirectory = "IP-IPX"
elif imagecode == "bin":
subdirectory = "IP-IPX-APPLETALK"
elif imagecode == "bins":
subdirectory = "IP-IPX-APPLETALK-PLUS"
elif imagecode == "bino3s":
subdirectory = "IP-IPX-APPLETALK-PLUS-FW-IDS"
elif imagecode == "nqy":
subdirectory = "IP-IPX-ASYNC"
elif imagecode == "bny":
subdirectory = "IP-IPX-AT"
elif imagecode == "d":
subdirectory = "IP-IPX-AT-DEC"
elif imagecode == "dos":
subdirectory = "IP-IPX-AT-DEC-FW-PLUS"
elif imagecode == "ds":
subdirectory = "IP-IPX-AT-DEC-PLUS"
elif imagecode == "ds40":
subdirectory = "IP-IPX-AT-DEC-PLUS-40"
elif imagecode == "bino3s3":
subdirectory = "IP-IPX-AT-FW-IDS-PLUS-BASIC"
elif imagecode == "bnr2y":
subdirectory = "IP-IPX-AT-IBM"
elif imagecode == "bk8no3r2sy":
subdirectory = "IP-IPX-AT-IBM-FW-IDS-PLUS-IPSEC-56"
elif imagecode == "bk8nor2sy":
subdirectory = "IP-IPX-AT-IBM-FW-PLUS-IPSEC-56"
elif imagecode == "bno3r2sy56i":
subdirectory = "IP-IPX-AT-IBM-FW-PLUS-IPSEC-56"
elif imagecode == "bnor2sy56i":
subdirectory = "IP-IPX-AT-IBM-FW-PLUS-IPSEC-56"
elif imagecode == "bk9no3r2sv3y":
subdirectory = "IP-IPX-AT-IBM-FW-VOICE-PLUS-IPSEC-3DES"
elif imagecode == "bk8no3r2sv3":
subdirectory = "IP-IPX-AT-IBM-FW-VOICE-PLUS-IPSEC-56"
elif imagecode == "bnr2sy":
subdirectory = "IP-IPX-AT-IBM-PLUS"
elif imagecode == "bk8no3r2sv3y":
subdirectory = "IP-IPX-AT-IBM-VOICE-FW-IDS-PLUS-IPSEC-56"
elif imagecode == "bnr2sv3y":
subdirectory = "IP-IPX-AT-IBM-VOICE-PLUS"
elif imagecode == "bnsy":
subdirectory = "IP-IPX-AT-PLUS"
elif imagecode | |
:
return _define_any_model(data, model_params, global_params, random_seed)
def optimize_imp_ama_model(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
random_seed: str,
hyper_params: Dict[str,str],
filt_pipeline: FilterPipeline,
) :
train_selection = True
return _optimize_any_model(data, model_params, global_params, active_run_id,
random_seed, hyper_params, filt_pipeline, train_selection)
def train_imp_ama_model(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
random_seed: str,
filt_pipeline : FilterPipeline,
) -> List[FilterPipeline]:
train_selection = True
return _train_any_model(data, model_params, global_params, active_run_id,
random_seed, filt_pipeline, train_selection)
##################
####### full
def define_imp_full_model(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
random_seed: str,
)-> FilterPipeline :
return _define_any_model(data, model_params, global_params, random_seed)
def optimize_imp_full_model(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
random_seed: str,
hyper_params: Dict[str,str],
filt_pipeline: FilterPipeline,
) :
train_selection = True
return _optimize_any_model(data, model_params, global_params, active_run_id,
random_seed, hyper_params, filt_pipeline, train_selection)
def train_imp_full_model(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
random_seed: str,
filt_pipeline : FilterPipeline,
) -> List[FilterPipeline]:
train_selection = True
return _train_any_model(data, model_params, global_params, active_run_id,
random_seed, filt_pipeline, train_selection)
####### ramp
def define_imp_ramp_model(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
random_seed: str,
)-> FilterPipeline :
return _define_any_model(data, model_params, global_params, random_seed)
def optimize_imp_ramp_model(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
random_seed: str,
hyper_params: Dict[str,str],
filt_pipeline: FilterPipeline,
) :
train_selection = True
return _optimize_any_model(data, model_params, global_params, active_run_id,
random_seed, hyper_params, filt_pipeline, train_selection)
def train_imp_ramp_model(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
random_seed: str,
filt_pipeline : FilterPipeline,
) -> List[FilterPipeline]:
train_selection = True
return _train_any_model(data, model_params, global_params, active_run_id,
random_seed, filt_pipeline, train_selection)
################################################################
################################ BASELINE MODELS ##############
################################################################
def _train_any_baseline(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
train_selection: Union[pd.Series, bool],
) -> FilterPipeline:
pip_steps = []
# Get also a non-nan default answer for baseline model
default_answer = np.nanmedian(data.loc[(data.group == 'train') & train_selection, model_params['target']])
# Better to follow the same basic filtering/wrapping as the full estimator
filt_pipeline = FilterPipeline(sklearn_Pipeline([('dummy',FunctionTransformer(validate=False))]), default_answer)
if not('baseline' in model_params) :
return filt_pipeline
missing_values = [np.nan, None, '']
for feature_name in model_params['features_core']:
feature_values = [
c for c in data.loc[(data.group == 'train') & (data[feature_name].notnull()), feature_name].unique()
if (feature_name not in global_params['category_exclusions']) or
(str(c) not in [str(v) for v in global_params['category_exclusions'][feature_name]])
]
filt_pipeline.add_include_rule(feature_name, feature_values + missing_values, 'Unknown ' + feature_name)
filt_pipeline.add_exclude_rule(feature_name, missing_values, 'Missing ' + feature_name)
filt_pipeline.add_exclude_rule_preds(lambda x: x < 0, 'Negative prediction')
# Orders feature columns : when you fit you look at the column order, transform will put
# column back in the same order. Why would column order be different ?
order_features = OrderFeatures()
pip_steps.append(('order_features', order_features))
# Replaces miscellaneous missing values with expected values (takes care of the Nan,
# only for not "features_core"
format_missing_data = FormatMissingData(model_params['features_core'])
pip_steps.append(('format_missing_data', format_missing_data))
# Get a value for the Terminal if terminal used
if ('terminal' in model_params['baseline']['group_by_features']) :
features_stand = ['departure_stand_actual']
terminal_encoder = TerminalEncoder(features_stand)
pip_steps.append(('terminal_encoder', terminal_encoder))
if 'baseline' in model_params:
baseline_model = GroupByModel(model_params['baseline'])
else:
baseline_model = DummyClassifier(strategy='most_frequent')
pip_steps.append(('baseline_model',baseline_model))
# Make pipeline
pipeline = sklearn_Pipeline(
steps=pip_steps
)
# Replace dummy pipeline with the real one :
filt_pipeline.core_pipeline = pipeline
tic = time.time()
filt_pipeline.fit(
data.loc[
train_selection & (data.group == 'train'),
model_params['features']
],
data.loc[
train_selection & (data.group == 'train'),
model_params['target']
],
)
toc = time.time()
log = logging.getLogger(__name__)
log.info('training unimpeded baseline for {} took {:.1f} minutes'.format(
model_params['target'], (toc - tic) / 60)
)
if (active_run_id != None) :
with mlflow.start_run(run_id=active_run_id):
# Log trained model
mlf_sklearn.log_model(
sk_model=baseline_model,
artifact_path='baseline',
conda_env=add_environment_specs_to_conda_file())
return filt_pipeline
#### Baseline unimpeded
def train_unimp_full_baseline(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
) -> FilterPipeline:
if ('unimpeded_AMA' in data) :
train_selection = data.unimpeded_AMA
else :
train_selection = True
return _train_any_baseline(data, model_params, global_params, active_run_id, train_selection)
def train_unimp_ama_baseline(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
) -> FilterPipeline:
if ('unimpeded_AMA' in data) :
train_selection = data.unimpeded_AMA
else :
train_selection = True
return _train_any_baseline(data, model_params, global_params, active_run_id, train_selection)
def train_unimp_ramp_baseline(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
) -> FilterPipeline:
train_selection = True
return _train_any_baseline(data, model_params, global_params, active_run_id, train_selection)
#### Baseline impeded
def train_imp_full_baseline(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
) -> FilterPipeline:
train_selection = True
return _train_any_baseline(data, model_params, global_params, active_run_id, train_selection)
def train_imp_ama_baseline(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
) -> FilterPipeline:
train_selection = True
return _train_any_baseline(data, model_params, global_params, active_run_id, train_selection)
def train_imp_ramp_baseline(
data: pd.DataFrame,
model_params: Dict[str, Any],
global_params: Dict[str, Any],
active_run_id: str,
) -> FilterPipeline:
train_selection = True
return _train_any_baseline(data, model_params, global_params, active_run_id, train_selection)
################################################################
################################ PREDICTION ###################
################################################################
def predict(
pipeline: Union[List[FilterPipeline], FilterPipeline],
data: pd.DataFrame,
model_params: Dict[str, Any],
) -> pd.DataFrame:
# Run model
log = logging.getLogger(__name__)
data_out = data.copy()
# Now it should be a list, but just in case I am checking
if isinstance(pipeline, list) :
pipeline_one = pipeline[0]
else :
pipeline_one = pipeline
if (('features' in model_params) & (model_params['model'] != 'Constant')) :
tic = time.time()
predictions = pipeline_one.predict(
data_out[model_params['features']]
)
toc = time.time()
log.info('predicting took {:.1f} minutes'.format(
(toc-tic)/60)
)
# Add predictions to dataframe for convenience
data_out['predicted_{}'.format(model_params['name'])] = predictions
# Flag predictions with missing core features
data_out['missing_core_features'] = pipeline_one.filter(data_out[model_params['features']])[0] == False
else:
log.warning('no features in model_params or model = Constant, skipping predictions')
# Add prediction from CV fitting
if isinstance(pipeline, list) :
for kk,pipeline_i in enumerate(pipeline[1:]) :
predictions = pipeline_i.predict(data_out[model_params['features']])
data_out['predictedCV{}_{}'.format(kk, model_params['name'])] = predictions
return data_out
def predict_baseline(
pipeline: sklearn_Pipeline,
data: pd.DataFrame,
model_params: Dict[str, Any]
) -> pd.DataFrame:
log = logging.getLogger(__name__)
data_out = data.copy()
if 'baseline' in model_params:
# Run model
tic = time.time()
predictions = pipeline.predict(
data_out[model_params['features']]
)
toc = time.time()
log.info('predicting baseline took {:.1f} minutes'.format(
(toc-tic)/60)
)
# Add predictions to dataframe for convenience
data_out['predicted_baseline'] = predictions
# Flag predictions with missing core features
data_out['missing_core_features_baseline'] = pipeline.filter(data_out)[0] == False
else :
log.warning('no baseline in model_params, skipping baseline predictions')
return data_out
################################################################
################################ METRICS ###################
################################################################
def report_performance_metrics(
data: pd.DataFrame,
model_params: Dict[str, Any],
active_run_id: str,
) -> None:
"""Node for reporting performance metrics. Notice that this function has no
outputs.
"""
log = logging.getLogger(__name__)
# Predictive model
if 'predicted_{}'.format(model_params['name']) in data :
report_model_metrics(data,
model_params,
'predicted_{}'.format(model_params['name']),
active_run_id)
else :
log.warning('no model predictions, skipping metrics calculation')
# Baseline
if 'predicted_baseline' in data.columns:
report_model_metrics(data,
model_params,
'predicted_baseline',
active_run_id,
'baseline_',
['train','test']) # I add 'train' to see how it does
else :
log.warning('no baseline predictions, skipping metrics calculation')
# STBO as truth data
if ('label' in model_params) :
if 'undelayed_departure_{}_transit_time'.format(model_params['label']) in data.columns:
report_model_metrics_STBO(data,
model_params,
'predicted_{}'.format(model_params['name']),
active_run_id,
'STBO_',
['train','test'])
else:
log.warning('no undelayed_departure transit time, skipping metrics calculation')
def report_model_metrics(
data: pd.DataFrame,
model_params: Dict[str, Any],
y_pred: str,
active_run_id: str,
name_prefix: str = '',
group_values : list = ['train','test']
) -> None:
"""Node for reporting the performance metrics of the predictions performed
by the previous node. Notice that this function has no outputs, except
logging.
"""
metrics_dict = {
metric_name: METRIC_NAME_TO_FUNCTION_DICT[metric_name]
for metric_name in model_params['metrics']
}
evaluation_df = evaluate_predictions(
data[(data.missing_core_features == False) &
(data['predicted_{}'.format(model_params['name'])].isna() == False) &
(data['predicted_baseline'].isna() == False) &
data.group.isin(group_values)],
y_true=model_params['target'],
y_pred=y_pred,
metrics_dict=metrics_dict,
)
# Log the accuracy of the model
log = logging.getLogger(__name__)
if (active_run_id != None) :
with mlflow.start_run(run_id=active_run_id):
# Set the metrics
# for metric_name in metrics_dict.keys():
# use evaluation_df to get the unimpeded_AMA metrics as well (if calculated)
for metric_name in evaluation_df.keys() :
log.info("metric {}:".format(name_prefix + metric_name))
for group in [v for v in data.group.unique() if v in group_values]:
log.info("{} group: {}".format(
group,
evaluation_df.loc[group, metric_name]
))
mlflow.log_metric(
name_prefix + metric_name + '_' + group,
evaluation_df.loc[group, metric_name]
)
def report_model_metrics_STBO(
data: pd.DataFrame,
model_params: Dict[str, Any],
y_pred: str,
active_run_id: str,
name_prefix: str = '',
group_values : list = ['train','test']
) -> None:
"""Node for reporting the performance metrics of the predictions performed
by the previous node. Notice that this function has no outputs, except
logging.
"""
metrics_dict = {
metric_name: METRIC_NAME_TO_FUNCTION_DICT[metric_name]
for metric_name in model_params['metrics']
}
if 'undelayed_departure_{}_transit_time'.format(model_params['label']) in data.columns:
data_filtered = data[(data.missing_core_features == False) &
(data['predicted_{}'.format(model_params['name'])].isna() == False) &
(data['predicted_baseline'].isna() == False) &
(data['undelayed_departure_{}_transit_time'.format(model_params['label'])].isna() == False) &
data.group.isin(group_values)]
evaluation_df_STBO = evaluate_predictions(
data_filtered,
y_true='undelayed_departure_{}_transit_time'.format(model_params['label']),
y_pred=y_pred,
metrics_dict=metrics_dict,
)
# Log the accuracy of the model
log = logging.getLogger(__name__)
if (active_run_id != None) :
with mlflow.start_run(run_id=active_run_id):
# Set the metrics
# for metric_name in metrics_dict.keys():
# use evaluation_df to get the unimpeded_AMA | |
<filename>py/shared/emails/plumbing.py<gh_stars>10-100
import asyncio
import base64
import datetime
import hashlib
import hmac
import json
import logging
import re
from binascii import hexlify
from email.message import EmailMessage
from email.policy import SMTP
from functools import reduce
from pathlib import Path
from textwrap import shorten
from typing import Any, Dict, List, NamedTuple, Optional
from urllib.parse import urlencode
import chevron
import sass
from aiohttp import ClientSession, ClientTimeout
from arq import concurrent
from buildpg import Values
from cryptography import fernet
from misaka import HtmlRenderer, Markdown
from pydantic.datetime_parse import parse_datetime
from ..actor import BaseActor
from ..utils import RequestError, format_dt, format_duration, unsubscribe_sig
from .defaults import EMAIL_DEFAULTS, Triggers
from .ical import ical_attachment
from .utils import Attachment
logger = logging.getLogger('nosht.emails')
THIS_DIR = Path(__file__).parent
DEFAULT_EMAIL_TEMPLATE = (THIS_DIR / 'default_template.html').read_text()
STYLES = (THIS_DIR / 'styles.scss').read_text()
STYLES = sass.compile(string=STYLES, output_style='compressed', precision=10).strip('\n')
_AWS_SERVICE = 'ses'
_AWS_AUTH_REQUEST = 'aws4_request'
_CONTENT_TYPE = 'application/x-www-form-urlencoded'
_SIGNED_HEADERS = 'content-type', 'host', 'x-amz-date'
_CANONICAL_REQUEST = """\
POST
/
{canonical_headers}
{signed_headers}
{payload_hash}"""
_AUTH_ALGORITHM = 'AWS4-HMAC-SHA256'
_CREDENTIAL_SCOPE = '{date_stamp}/{region}/{service}/{auth_request}'
_STRING_TO_SIGN = """\
{algorithm}
{x_amz_date}
{credential_scope}
{canonical_request_hash}"""
_AUTH_HEADER = (
'{algorithm} Credential={access_key}/{credential_scope},SignedHeaders={signed_headers},Signature={signature}'
)
flags = ('hard-wrap',)
extensions = ('no-intra-emphasis',)
safe_markdown = Markdown(HtmlRenderer(flags=flags), extensions=extensions) # maybe should use SaferHtmlRenderer
DEBUG_PRINT_REGEX = re.compile(r'{{ ?__debug_context__ ?}}')
class UserEmail(NamedTuple):
id: int
ctx: Dict[str, Any] = {}
ticket_id: int = None
class BaseEmailActor(BaseActor):
def __init__(self, *, http_client=None, **kwargs):
super().__init__(**kwargs)
self.client = http_client or ClientSession(timeout=ClientTimeout(total=10), loop=self.loop)
self._host = self.settings.aws_ses_host.format(region=self.settings.aws_region)
self._endpoint = self.settings.aws_ses_endpoint.format(host=self._host)
self.auth_fernet = fernet.Fernet(self.settings.auth_key)
self.send_via_aws = self.settings.aws_access_key and not self.settings.print_emails
def _aws_headers(self, data):
n = datetime.datetime.utcnow()
x_amz_date = n.strftime('%Y%m%dT%H%M%SZ')
date_stamp = n.strftime('%Y%m%d')
ctx = dict(
access_key=self.settings.aws_access_key,
algorithm=_AUTH_ALGORITHM,
x_amz_date=x_amz_date,
auth_request=_AWS_AUTH_REQUEST,
content_type=_CONTENT_TYPE,
date_stamp=date_stamp,
host=self._host,
payload_hash=hashlib.sha256(data).hexdigest(),
region=self.settings.aws_region,
service=_AWS_SERVICE,
signed_headers=';'.join(_SIGNED_HEADERS),
)
ctx.update(credential_scope=_CREDENTIAL_SCOPE.format(**ctx))
canonical_headers = ''.join('{}:{}\n'.format(h, ctx[h.replace('-', '_')]) for h in _SIGNED_HEADERS)
canonical_request = _CANONICAL_REQUEST.format(canonical_headers=canonical_headers, **ctx).encode()
s2s = _STRING_TO_SIGN.format(canonical_request_hash=hashlib.sha256(canonical_request).hexdigest(), **ctx)
key_parts = (
b'AWS4' + self.settings.aws_secret_key.encode(),
date_stamp,
self.settings.aws_region,
_AWS_SERVICE,
_AWS_AUTH_REQUEST,
s2s,
)
signature = reduce(lambda key, msg: hmac.new(key, msg.encode(), hashlib.sha256).digest(), key_parts)
authorization_header = _AUTH_HEADER.format(signature=hexlify(signature).decode(), **ctx)
return {'Content-Type': _CONTENT_TYPE, 'X-Amz-Date': x_amz_date, 'Authorization': authorization_header}
async def aws_send(self, *, e_from: str, email_msg: EmailMessage, to: List[str]):
data = {
'Action': 'SendRawEmail',
'Source': e_from,
'RawMessage.Data': base64.b64encode(email_msg.as_string().encode()),
}
data.update({f'Destination.ToAddresses.member.{i + 1}': t.encode() for i, t in enumerate(to)})
# data.update({f'Destination.BccAddresses.member.{i + 1}': t.encode() for i, t in enumerate(bcc)})
data = urlencode(data).encode()
headers = self._aws_headers(data)
async with self.client.post(self._endpoint, data=data, headers=headers, timeout=5) as r:
text = await r.text()
if r.status != 200:
raise RequestError(r.status, self._endpoint, text=text)
return re.search('<MessageId>(.+?)</MessageId>', text).group(1)
async def print_email(self, *, e_from: str, email_msg: EmailMessage, to: List[str]): # pragma: no cover
if self.settings.print_emails_verbose:
d = dict(email_msg)
d['AWS-Source'] = e_from
d['AWS-To'] = ', '.join(to)
print('=' * 80)
for f in ('AWS-Source', 'AWS-To', 'Subject', 'From', 'To', 'List-Unsubscribe'):
print(f'{f:>30}: {d[f]}')
for part in email_msg.walk():
payload = part.get_payload(decode=True)
if payload:
print('-' * 80)
print(f'{part.get_content_type()}:')
print(payload.decode().replace('\r\n', '\n').strip(' \n'))
print('=' * 80)
else:
logger.info('"%s" %s -> %s', email_msg["subject"], e_from, to)
return '-'
async def send_email(
self,
*,
user: Dict[str, Any],
user_ctx: Dict[str, Any],
subject: str,
title: str,
body: str,
template: str,
e_from: str,
reply_to: Optional[str],
global_ctx: Dict[str, Any],
attachment: Optional[Attachment],
tags: Dict[str, str],
company_id: int,
):
base_url = global_ctx['base_url']
full_name = '{first_name} {last_name}'.format(
first_name=user['first_name'] or '', last_name=user['last_name'] or '',
).strip(' ')
user_email = user['email']
extra_ctx = dict(
first_name=user['first_name'] or user['last_name'] or '',
full_name=full_name or 'user',
unsubscribe_link=f'/api/unsubscribe/{user["id"]}/?sig={unsubscribe_sig(user["id"], self.settings)}',
)
ctx = clean_ctx({**global_ctx, **extra_ctx, **user_ctx}, base_url)
markup_data = ctx.pop('markup_data', None)
e_msg = EmailMessage(policy=SMTP)
subject = chevron.render(subject, data=ctx)
e_msg['Subject'] = subject
e_msg['From'] = e_from
if reply_to:
e_msg['Reply-To'] = reply_to
e_msg['To'] = f'{full_name} <{user_email}>' if full_name else user_email
e_msg['List-Unsubscribe'] = '<{unsubscribe_link}>'.format(**ctx)
e_msg['X-SES-CONFIGURATION-SET'] = 'nosht'
e_msg['X-SES-MESSAGE-TAGS'] = ', '.join(f'{k}={v}' for k, v in tags.items())
if DEBUG_PRINT_REGEX.search(body):
ctx['__debug_context__'] = f'```{json.dumps(ctx, indent=2)}```'
body = apply_macros(body)
body = chevron.render(body, data=ctx)
raw_body = re.sub(r'\n{3,}', '\n\n', body).strip('\n')
e_msg.set_content(raw_body, cte='quoted-printable')
ctx.update(
styles=STYLES,
main_message=safe_markdown(raw_body),
message_preview=shorten(strip_markdown(raw_body), 60, placeholder='…'),
)
if markup_data:
ctx['markup_data'] = json.dumps(markup_data, separators=(',', ':'))
html_body = chevron.render(template, data=ctx, partials_dict={'title': title})
e_msg.add_alternative(html_body, subtype='html', cte='quoted-printable')
if attachment:
maintype, subtype = attachment.mime_type.split('/')
e_msg.add_attachment(
attachment.content.encode(), maintype=maintype, subtype=subtype, filename=attachment.filename,
)
if self.send_via_aws and user_email.endswith('example.com'):
logger.info('email not sent "%s" to "%s" because it ends "example.com"', subject, user_email)
return
send_method = self.aws_send if self.send_via_aws else self.print_email
msg_id = await send_method(e_from=e_from, to=[user_email], email_msg=e_msg)
await self.pg.execute(
"""
insert into emails (company, user_id, ext_id, trigger, subject, address)
values ($1, $2, $3, $4, $5, $6)
""",
company_id,
user['id'],
msg_id,
tags['trigger'],
subject,
user_email,
)
@concurrent
async def send_emails(
self, company_id: int, trigger: str, users_emails: List[UserEmail], *, force_send=False, attached_event_id=None
):
trigger = Triggers(trigger)
dft = EMAIL_DEFAULTS[trigger]
subject, title, body = dft['subject'], dft['title'], dft['body']
attachment = None
async with self.pg.acquire() as conn:
company_name, company_slug, e_from, reply_to, template, company_logo, company_domain = await conn.fetchrow(
'SELECT name, slug, email_from, email_reply_to, email_template, logo, domain '
'FROM companies WHERE id=$1',
company_id,
)
e_from = e_from or self.settings.default_email_address
template = template or DEFAULT_EMAIL_TEMPLATE
r = await conn.fetchrow(
"""
SELECT active, subject, title, body
FROM email_definitions
WHERE company=$1 AND trigger=$2
""",
company_id,
trigger.value,
)
if r:
if not r['active']:
logger.info('not sending email %s (%d), email definition inactive', trigger.value, company_id)
return
subject = r['subject'] or subject
title = r['title'] or title
body = r['body'] or body
sql = """
SELECT id, first_name, last_name, email
FROM users
WHERE
company=$1 AND
email IS NOT NULL AND
id=ANY($2) AND
status!='suspended'
"""
sql += '' if force_send else 'AND receive_emails=TRUE'
user_data = await conn.fetch(sql, company_id, [u[0] for u in users_emails])
ticket_name_lookup = {}
ticket_ids = [ue[2] for ue in users_emails if ue[2]]
if ticket_ids:
ticket_name_lookup = {
r['ticket_id']: r
for r in await conn.fetch(
'SELECT id AS ticket_id, first_name, last_name FROM tickets WHERE id=ANY($1)', ticket_ids
)
}
if attached_event_id:
attachment = await ical_attachment(attached_event_id, company_id, conn=conn, settings=self.settings)
global_ctx = dict(company_name=company_name, company_logo=company_logo, base_url=f'https://{company_domain}')
coros = []
tags = {
'company': company_slug,
'trigger': trigger.value,
}
user_data_lookup = {u['id']: u for u in user_data}
for user_id, ctx, ticket_id in users_emails:
try:
user_data_ = user_data_lookup[user_id]
except KeyError:
# this user has receive_emails = FALSE or status = 'suspended'
continue
ticket_data = ticket_id and ticket_name_lookup.get(ticket_id)
if ticket_data:
user_data_ = dict(user_data_)
user_data_['first_name'] = user_data_['first_name'] or ticket_data['first_name']
user_data_['last_name'] = user_data_['last_name'] or ticket_data['last_name']
coros.append(
self.send_email(
user=user_data_,
user_ctx=ctx,
subject=subject,
title=title,
body=body,
template=template,
e_from=e_from,
reply_to=reply_to,
global_ctx=global_ctx,
attachment=attachment,
tags=tags,
company_id=company_id,
)
)
await asyncio.gather(*coros)
logger.info(
'%d emails sent for trigger %s, company %s (%d)', len(user_data), trigger, company_domain, company_id
)
@concurrent('low') # noqa: C901 (ignore complexity)
async def record_email_event(self, raw_message: str): # noqa: C901
"""
record email events
"""
message = json.loads(raw_message)
msg_id = message['mail']['messageId']
r = await self.pg.fetchrow('select id, user_id, update_ts from emails where ext_id=$1', msg_id)
if not r:
return
email_id, user_id, last_updated = r
event_type = message.get('eventType')
extra = None
data = message.get(event_type.lower()) or {}
if event_type == 'Send':
data = message['mail']
elif event_type == 'Delivery':
extra = {
'delivery_time': data.get('processingTimeMillis'),
}
elif event_type == 'Open':
extra = {
'ip': data.get('ipAddress'),
'ua': data.get('userAgent'),
}
elif event_type == 'Click':
extra = {
'link': data.get('link'),
'ip': data.get('ipAddress'),
'ua': data.get('userAgent'),
}
elif event_type == 'Bounce':
extra = {
'bounceType': data.get('bounceType'),
'bounceSubType': data.get('bounceSubType'),
'reportingMTA': data.get('reportingMTA'),
'feedbackId': data.get('feedbackId'),
'unsubscribe': data.get('bounceType') == 'Permanent',
}
elif event_type == 'Complaint':
extra = {
'complaintFeedbackType': data.get('complaintFeedbackType'),
'feedbackId': data.get('feedbackId'),
'ua': data.get('userAgent'),
'unsubscribe': True,
}
else:
logger.warning('unknown aws webhooks %s', event_type, extra={'data': {'message': message}})
values = dict(email=email_id, status=event_type)
ts = None
if data.get('timestamp'):
ts = parse_datetime(data['timestamp'])
values['ts'] = ts
if extra:
values['extra'] = json.dumps({k: v for k, v in extra.items() if v})
async with self.pg.acquire() as conn:
await conn.execute_b('insert into email_events (:values__names) values :values', values=Values(**values))
if not ts:
await conn.execute(
'update emails set status=$1, update_ts=CURRENT_TIMESTAMP where id=$2', event_type, email_id
)
elif last_updated < ts:
await conn.execute('update emails set status=$1, update_ts=$2 where id=$3', event_type, ts, email_id)
if extra and extra.get('unsubscribe'):
await conn.execute('update users set receive_emails=false where id=$1', user_id)
return event_type
strip_markdown_re = [
(re.compile(r'\<.*?\>', flags=re.S), ''),
(re.compile(r'_(\S.*?\S)_'), r'\1'),
(re.compile(r'\[(.+?)\]\(.+?\)'), r'\1'),
(re.compile(r'\*\*'), ''),
(re.compile('^#+ ', flags=re.M), ''),
(re.compile('`'), ''),
(re.compile('\n+'), ' '),
]
def strip_markdown(s):
for regex, p in strip_markdown_re:
s = regex.sub(p, s)
return s
def clean_ctx(context, base_url):
context = context or {}
for key, value in context.items():
if key.endswith('link') and isinstance(value, str):
value = value or '/'
assert value.startswith('/'), f'link field found which doesn\'t start "/". {key}: {value}'
context[key] = base_url + value
elif isinstance(value, datetime.datetime) or isinstance(value, datetime.date):
context[key] = format_dt(value)
elif isinstance(value, datetime.timedelta):
context[key] = format_duration(value)
elif isinstance(value, dict):
context[key] = clean_ctx(value, base_url=base_url)
elif isinstance(value, list):
context[key] = [clean_ctx(v, base_url=base_url) for v in value]
return context
markdown_macros = [
{
'name': 'primary_button',
'args': ('text', 'link'),
'body': '<div class="button">\n <a href="{{ link }}"><span>{{ text }}</span></a>\n</div>\n',
},
{
'name': 'secondary_button',
| |
allnet=False,
modified_after=None, qc_constraints=None):
constraints = {}
if qc_constraints is not None:
constraints = qc_constraints
if sensortype is not None:
constraints['sensortype'] = sensortype
if permanent is not None:
if permanent:
constraints['permanent'] = 'true'
else:
constraints['permanent'] = 'false'
if restricted is not None:
if restricted:
constraints['restricted'] = 'true'
else:
constraints['restricted'] = 'false'
if latmin is not None:
constraints['latmin'] = str(latmin)
if latmax is not None:
constraints['latmax'] = str(latmax)
if lonmin is not None:
constraints['lonmin'] = str(lonmin)
if lonmax is not None:
constraints['lonmax'] = str(lonmax)
if start_time is None:
start_time = datetime.datetime(1980,1,1,0,0,0)
if end_time is None:
end_time = datetime.datetime(2030,12,31,0,0,0)
args = { 'compression': 'bzip2' }
if instr:
args['instruments'] = 'true'
else:
args['instruments'] = 'false'
if modified_after is not None:
args['modified_after'] = modified_after.isoformat()
req = self.new_request("INVENTORY", args)
req.add(start_time, end_time, network, station, stream, loc_id, constraints)
if allnet:
req.add(start_time, end_time, '*', '', '', '', constraints)
req.submit(self.__myaddr, self.__myuser, self.__mypasswd, self.__user_ip)
if req.error is not None:
raise ArclinkError, req.error
inv = _Inventory()
req.download_xml(inv, True)
return inv
def __estimate_size(self, strm, start_time, end_time):
if strm.sampleRateDenominator == 0:
return 0
tdiff = end_time - start_time
tdiff = tdiff.days * 86400 + tdiff.seconds
spfr = float(strm.sampleRateNumerator) / float(strm.sampleRateDenominator)
return max(int(tdiff * spfr * 1.5), 512)
def __spfr_diff(self, strm, spfr):
if strm.sampleRateDenominator == 0:
return 10000
return abs(spfr - float(strm.sampleRateNumerator) / float(strm.sampleRateDenominator))
def __expand_request(self, req, inv, spfr):
def _dot(s):
if not s:
return "."
return s
for i in req.content:
if i[0] in inv.stationGroup:
break
for j in i[:4]:
if j.find("*") >= 0 or j.find("?") >= 0:
break
else:
continue
break
else:
return
content = []
for rl in req.content:
expanded = {}
spfr_diff = 10000
for sgrp in inv.stationGroup.itervalues():
if not fnmatch.fnmatchcase(sgrp.code, rl.net):
continue
for sref in sgrp.stationReference.itervalues():
for net in sum([i.values() for i in inv.network.itervalues()], []):
try:
sta = net.object[sref.stationID]
break
except KeyError:
pass
else:
continue
for loc in sum([i.values() for i in sta.sensorLocation.itervalues()], []):
if not fnmatch.fnmatchcase(_dot(loc.code), _dot(rl.loc)):
continue
for strm in sum([i.values() for i in loc.stream.itervalues()], []):
if fnmatch.fnmatchcase(strm.code, rl.cha):
if spfr is not None:
if self.__spfr_diff(strm, spfr) < spfr_diff:
spfr_diff = self.__spfr_diff(strm, spfr)
expanded.clear()
elif self.__spfr_diff(strm, spfr) > spfr_diff:
continue
expanded[(rl.start_time, rl.end_time, net.code, sta.code, strm.code, _dot(loc.code))] = \
self.__estimate_size(strm, rl.start_time, rl.end_time)
for strm in sum([i.values() for i in loc.auxStream.itervalues()], []):
if fnmatch.fnmatchcase(strm.code, rl.cha):
if spfr is not None:
if self.__spfr_diff(strm, spfr) < spfr_diff:
spfr_diff = self.__spfr_diff(strm, spfr)
expanded.clear()
elif self.__spfr_diff(strm, spfr) > spfr_diff:
continue
expanded[(rl.start_time, rl.end_time, net.code, sta.code, strm.code, _dot(loc.code))] = 0
# auxStream doesn't have sample rate info, so this wouldn't work
# self.__estimate_size(strm, rl.start_time, rl.end_time)
for net in sum([i.values() for i in inv.network.itervalues()], []):
if not fnmatch.fnmatchcase(net.code, rl.net):
continue
for sta in sum([i.values() for i in net.station.itervalues()], []):
if not fnmatch.fnmatchcase(sta.code, rl.sta):
continue
for loc in sum([i.values() for i in sta.sensorLocation.itervalues()], []):
if not fnmatch.fnmatchcase(_dot(loc.code), _dot(rl.loc)):
continue
for strm in sum([i.values() for i in loc.stream.itervalues()], []):
if fnmatch.fnmatchcase(strm.code, rl.cha):
if spfr is not None:
if self.__spfr_diff(strm, spfr) < spfr_diff:
spfr_diff = self.__spfr_diff(strm, spfr)
expanded.clear()
elif self.__spfr_diff(strm, spfr) > spfr_diff:
continue
expanded[(rl.start_time, rl.end_time, net.code, sta.code, strm.code, _dot(loc.code))] = \
self.__estimate_size(strm, rl.start_time, rl.end_time)
for strm in sum([i.values() for i in loc.auxStream.itervalues()], []):
if fnmatch.fnmatchcase(strm.code, rl.cha):
if spfr is not None:
if self.__spfr_diff(strm, spfr) < spfr_diff:
spfr_diff = self.__spfr_diff(strm, spfr)
expanded.clear()
elif self.__spfr_diff(strm, spfr) > spfr_diff:
continue
expanded[(rl.start_time, rl.end_time, net.code, sta.code, strm.code, _dot(loc.code))] = 0
# auxStream doesn't have sample rate info, so this wouldn't work
# self.__estimate_size(strm, rl.start_time, rl.end_time)
if expanded:
for (x, estimated_size) in expanded.iteritems():
rlx = RequestLine(*x)
rlx.routes_tried = rl.routes_tried.copy()
rlx.estimated_size = estimated_size
content.append(rlx)
else:
logs.warning("no match for " + repr(rl))
req.content[:] = content
def __execute(self, inv, request, req_sent, req_noroute, req_nodata, dry_run):
def _cmptime(t1, t2):
if t1 is None and t2 is None:
return 0
elif t2 is None or (t1 is not None and t1 < t2):
return -1
elif t1 is None or (t2 is not None and t1 > t2):
return 1
return 0
req_retry = request.new()
req_route = {}
for rl in request.content:
for x in (15, 14, 13, 11, 7, 12, 10, 9, 6, 5, 3, 8, 4, 2, 1, 0):
net = (rl.net, "")[not (x & 8)]
sta = (rl.sta, "")[not (x & 4)]
cha = (rl.cha, "")[not (x & 2)]
loc = (rl.loc, "")[not (x & 1)]
try:
route = inv.route[net][sta][loc][cha]
break
except KeyError:
continue
else:
logs.warning("route to station %s %s not found" % (rl.net, rl.sta))
req_noroute.content.append(rl)
continue
server_list = sum([i.values() for i in route.arclink.itervalues()], [])
server_list.sort(key=lambda x: x.priority)
arclink_addrs = []
for server in server_list:
if _cmptime(server.start, rl.end_time) > 0 or \
_cmptime(server.end, rl.start_time) < 0:
continue
alias = self.__addr_alias.get(server.address)
if alias is None:
arclink_addrs.append(server.address)
else:
arclink_addrs.append(alias)
for addr in arclink_addrs:
if addr not in rl.routes_tried:
if addr not in req_route:
req_route[addr] = request.new()
req_route[addr].content.append(rl)
break
else:
if arclink_addrs:
req_nodata.content.append(rl)
else:
req_noroute.content.append(rl)
req_thr = []
for (addr, req) in req_route.items():
usr_pwd = self.__pwtable.get(addr)
if usr_pwd is None:
user = self.__default_user
passwd = <PASSWORD>
else:
(user, passwd) = usr_pwd
if not dry_run:
logs.info("launching request thread (%s)" % (addr,))
thr = RequestThread(req, addr, user, passwd, self.__user_ip, req_sent, req_retry,
self.__max_req_lines, self.__max_req_mb)
thr.start()
req_thr.append(thr)
else:
req_sent.append(req)
for thr in req_thr:
thr.join()
if req_retry.content:
return self.__execute(inv, req_retry, req_sent, req_noroute, req_nodata, dry_run)
def execute(self, request, use_inventory=True, use_routing=True, preferred_sample_rate=None, dry_run=False):
if len(request.content) == 0:
raise ArclinkError, "empty request"
inv = _Inventory()
rtn = _Routing()
req_sent = []
req_noroute = request.new()
req_nodata = request.new()
if use_inventory:
logs.debug("requesting inventory from %s" % (self.__myaddr))
startidx = 0
while startidx < len(request.content):
args = {'instruments': 'true', 'compression': 'bzip2'}
req = self.new_request("INVENTORY", args, request.label)
req.content = request.content[startidx:startidx+self.__max_req_lines]
req.submit(self.__myaddr, self.__myuser, self.__mypasswd, self.__user_ip)
if req.error is not None:
raise ArclinkError, "error getting inventory data from %s: %s" % \
(self.__myaddr, req.error)
try:
req.download_xml(inv, True)
except ArclinkError, e:
raise ArclinkError, "error getting inventory data from %s: %s" % \
(self.__myaddr, str(e))
startidx += len(req.content)
self.__expand_request(request, inv, preferred_sample_rate)
if len(request.content) == 0:
raise ArclinkError, "empty request after wildcard expansion"
if use_routing:
logs.debug("requesting routing from %s" % (self.__myaddr))
startidx = 0
while startidx < len(request.content):
args = { 'compression': 'bzip2' }
req = self.new_request("ROUTING", args, request.label)
req.content = request.content[startidx:startidx+self.__max_req_lines]
req.submit(self.__myaddr, self.__myuser, self.__mypasswd, self.__user_ip)
if req.error is not None:
raise ArclinkError, "error getting routing data from %s: %s" % \
(self.__myaddr, req.error)
try:
req.download_xml(rtn, True)
except ArclinkError, e:
raise ArclinkError, "error getting routing data from %s: %s" % \
(self.__myaddr, str(e))
startidx += len(req.content)
self.__execute(rtn, request, req_sent, req_noroute, req_nodata, dry_run)
else:
logs.debug("requesting %s data from %s" % (request.rtype.lower(), self.__myaddr))
startidx = 0
while startidx < len(request.content):
req = request.new()
req.content = request.content[startidx:startidx+self.__max_req_lines]
req.submit(self.__myaddr, self.__myuser, self.__mypasswd, self.__user_ip)
if req.error is not None:
raise ArclinkError, "error getting %s data from %s: %s" % \
(req.rtype.lower(), self.__myaddr, req.error)
try:
req.wait()
except ArclinkError, e:
sr = req.status()
if sr.error:
logs.warning("%s: request %s failed (%s)" % (req.address, req.id, str(e)))
else:
logs.warning("%s: request %s returned no data (%s)" % (req.address, req.id, str(e)))
req_sent.append(req)
startidx += len(req.content)
if not req_noroute.content:
req_noroute = None
if not req_nodata.content:
req_nodata = None
return (inv, req_sent, req_noroute, req_nodata)
def __route_request(self, inv, req_sent, request, dry_run):
def _cmptime(t1, t2):
if t1 is None and t2 is None:
return 0
elif t2 is None or (t1 is not None and t1 < t2):
return -1
elif t1 is None or (t2 is not None and t1 > t2):
return 1
return 0
req_fail = None
req_route = {}
for rl in request.content:
for x in (15, 14, 13, 11, 7, 12, 10, 9, 6, 5, 3, 8, 4, 2, 1, 0):
net = (rl.net, "")[not (x & 8)]
sta = (rl.sta, "")[not (x & 4)]
cha = (rl.cha, "")[not (x & 2)]
loc = (rl.loc, "")[not (x & 1)]
try:
route = inv.route[net][sta][loc][cha]
break
except KeyError:
continue
else:
logs.warning("route to station %s %s not found" % (rl.net, rl.sta))
if req_fail is None:
req_fail = request.new()
req_fail.content.append(rl)
continue
server_list = sum([i.values() for i in route.arclink.itervalues()], [])
server_list.sort(key=lambda x: x.priority)
arclink_addrs = | |
<gh_stars>1-10
import numpy as np
import torch
import random
import pandas as pd
import os
import cv2
import argparse
import math
import matplotlib.pyplot as plt
import pathlib
def load_sdd_raw(path):
data_path = os.path.join(path, "annotations")
scenes_main = os.listdir(data_path)
SDD_cols = ['trackId', 'xmin', 'ymin', 'xmax', 'ymax', 'frame', 'lost', 'occluded', 'generated', 'label']
data = []
for scene_main in sorted(scenes_main):
scene_main_path = os.path.join(data_path, scene_main)
for scene_sub in sorted(os.listdir(scene_main_path)):
scene_path = os.path.join(scene_main_path, scene_sub)
annot_path = os.path.join(scene_path, 'annotations.txt')
scene_df = pd.read_csv(annot_path, header=0, names=SDD_cols, delimiter=' ')
# Calculate center point of bounding box
scene_df['x'] = (scene_df['xmax'] + scene_df['xmin']) / 2
scene_df['y'] = (scene_df['ymax'] + scene_df['ymin']) / 2
scene_df = scene_df[scene_df['lost'] == 0] # drop lost samples
scene_df = scene_df.drop(columns=['xmin', 'xmax', 'ymin', 'ymax', 'occluded', 'generated', 'lost'])
scene_df['sceneId'] = f"{scene_main}_{scene_sub.split('video')[1]}"
# new unique id by combining scene_id and track_id
scene_df['rec&trackId'] = [recId + '_' + str(trackId).zfill(4) for recId, trackId in
zip(scene_df.sceneId, scene_df.trackId)]
data.append(scene_df)
data = pd.concat(data, ignore_index=True)
rec_trackId2metaId = {}
for i, j in enumerate(data['rec&trackId'].unique()):
rec_trackId2metaId[j] = i
data['metaId'] = [rec_trackId2metaId[i] for i in data['rec&trackId']]
data = data.drop(columns=['rec&trackId'])
return data
def mask_step(x, step):
"""
Create a mask to only contain the step-th element starting from the first element. Used to downsample
"""
mask = np.zeros_like(x)
mask[::step] = 1
return mask.astype(bool)
def downsample(df, step):
"""
Downsample data by the given step. Example, SDD is recorded in 30 fps, with step=30, the fps of the resulting
df will become 1 fps. With step=12 the result will be 2.5 fps. It will do so individually for each unique
pedestrian (metaId)
:param df: pandas DataFrame - necessary to have column 'metaId'
:param step: int - step size, similar to slicing-step param as in array[start:end:step]
:return: pd.df - downsampled
"""
mask = df.groupby(['metaId'])['metaId'].transform(mask_step, step=step)
return df[mask]
def filter_short_trajectories(df, threshold):
"""
Filter trajectories that are shorter in timesteps than the threshold
:param df: pandas df with columns=['x', 'y', 'frame', 'trackId', 'sceneId', 'metaId']
:param threshold: int - number of timesteps as threshold, only trajectories over threshold are kept
:return: pd.df with trajectory length over threshold
"""
len_per_id = df.groupby(by='metaId', as_index=False).count() # sequence-length for each unique pedestrian
idx_over_thres = len_per_id[len_per_id['frame'] >= threshold] # rows which are above threshold
idx_over_thres = idx_over_thres['metaId'].unique() # only get metaIdx with sequence-length longer than threshold
df = df[df['metaId'].isin(idx_over_thres)] # filter df to only contain long trajectories
return df
def groupby_sliding_window(x, window_size, stride):
x_len = len(x)
n_chunk = (x_len - window_size) // stride + 1
idx = []
metaId = []
for i in range(n_chunk):
idx += list(range(i * stride, i * stride + window_size))
metaId += ['{}_{}'.format(x.metaId.unique()[0], i)] * window_size
df = x.iloc()[idx]
df['newMetaId'] = metaId
return df
def sliding_window(df, window_size, stride):
"""
Assumes downsampled df, chunks trajectories into chunks of length window_size. When stride < window_size then
chunked trajectories are overlapping
:param df: df
:param window_size: sequence-length of one trajectory, mostly obs_len + pred_len
:param stride: timesteps to move from one trajectory to the next one
:return: df with chunked trajectories
"""
gb = df.groupby(['metaId'], as_index=False)
df = gb.apply(groupby_sliding_window, window_size=window_size, stride=stride)
df['metaId'] = pd.factorize(df['newMetaId'], sort=False)[0]
df = df.drop(columns='newMetaId')
df = df.reset_index(drop=True)
return df
def split_at_fragment_lambda(x, frag_idx, gb_frag):
""" Used only for split_fragmented() """
metaId = x.metaId.iloc()[0]
counter = 0
if metaId in frag_idx:
split_idx = gb_frag.groups[metaId]
for split_id in split_idx:
x.loc[split_id:, 'newMetaId'] = '{}_{}'.format(metaId, counter)
counter += 1
return x
def split_fragmented(df):
"""
Split trajectories when fragmented (defined as frame_{t+1} - frame_{t} > 1)
Formally, this is done by changing the metaId at the fragmented frame and below
:param df: DataFrame containing trajectories
:return: df: DataFrame containing trajectories without fragments
"""
gb = df.groupby('metaId', as_index=False)
# calculate frame_{t+1} - frame_{t} and fill NaN which occurs for the first frame of each track
df['frame_diff'] = gb['frame'].diff().fillna(value=1.0).to_numpy()
fragmented = df[df['frame_diff'] != 1.0] # df containing all the first frames of fragmentation
gb_frag = fragmented.groupby('metaId') # helper for gb.apply
frag_idx = fragmented.metaId.unique() # helper for gb.apply
df['newMetaId'] = df['metaId'] # temporary new metaId
df = gb.apply(split_at_fragment_lambda, frag_idx, gb_frag)
df['metaId'] = pd.factorize(df['newMetaId'], sort=False)[0]
df = df.drop(columns='newMetaId')
return df
def load_raw_dataset(path, step, window_size, stride):
df = load_sdd_raw(path=path)
df = split_fragmented(df) # split track if frame is not continuous
df = downsample(df, step=step)
df = filter_short_trajectories(df, threshold=window_size)
df = sliding_window(df, window_size=window_size, stride=stride)
return df
def rot(df, image, k=1):
'''
Rotates image and coordinates counter-clockwise by k * 90° within image origin
:param df: Pandas DataFrame with at least columns 'x' and 'y'
:param image: PIL Image
:param k: Number of times to rotate by 90°
:return: Rotated Dataframe and image
'''
xy = df.copy()
if image.ndim == 3:
y0, x0, channels = image.shape
else:
y0, x0= image.shape
xy.loc()[:, 'x'] = xy['x'] - x0 / 2
xy.loc()[:, 'y'] = xy['y'] - y0 / 2
c, s = np.cos(-k * np.pi / 2), np.sin(-k * np.pi / 2)
R = np.array([[c, s], [-s, c]])
xy.loc()[:, ['x', 'y']] = np.dot(xy[['x', 'y']], R)
for i in range(k):
image = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
if image.ndim == 3:
y0, x0, channels = image.shape
else:
y0, x0= image.shape
xy.loc()[:, 'x'] = xy['x'] + x0 / 2
xy.loc()[:, 'y'] = xy['y'] + y0 / 2
return xy, image
def fliplr(df, image):
'''
Flip image and coordinates horizontally
:param df: Pandas DataFrame with at least columns 'x' and 'y'
:param image: PIL Image
:return: Flipped Dataframe and image
'''
xy = df.copy()
if image.ndim == 3:
y0, x0, channels = image.shape
else:
y0, x0= image.shape
xy.loc()[:, 'x'] = xy['x'] - x0 / 2
xy.loc()[:, 'y'] = xy['y'] - y0 / 2
R = np.array([[-1, 0], [0, 1]])
xy.loc()[:, ['x', 'y']] = np.dot(xy[['x', 'y']], R)
image = cv2.flip(image, 1)
if image.ndim == 3:
y0, x0, channels = image.shape
else:
y0, x0= image.shape
xy.loc()[:, 'x'] = xy['x'] + x0 / 2
xy.loc()[:, 'y'] = xy['y'] + y0 / 2
return xy, image
def augment_data(data, image_path='data/SDD/train', images={}, image_file='reference.jpg', seg_mask=False, use_raw_data=False):
'''
Perform data augmentation
:param data: Pandas df, needs x,y,metaId,sceneId columns
:param image_path: example - 'data/SDD/val'
:param images: dict with key being sceneId, value being PIL image
:param image_file: str, image file name
:param seg_mask: whether it's a segmentation mask or an image file
:return:
'''
ks = [1, 2, 3]
for scene in data.sceneId.unique():
scene_name, scene_idx = scene.split("_")
if use_raw_data:
im_path = os.path.join(image_path, scene_name, f"video{scene_idx}", image_file)
else:
im_path = os.path.join(image_path, scene, image_file)
if seg_mask:
im = cv2.imread(im_path, 0)
else:
im = cv2.imread(im_path)
images[scene] = im
data_ = data.copy() # data without rotation, used so rotated data can be appended to original df
k2rot = {1: '_rot90', 2: '_rot180', 3: '_rot270'}
for k in ks:
metaId_max = data['metaId'].max()
for scene in data_.sceneId.unique():
if use_raw_data:
im_path = os.path.join(image_path, scene_name, f"video{scene_idx}", image_file)
else:
im_path = os.path.join(image_path, scene, image_file)
if seg_mask:
im = cv2.imread(im_path, 0)
else:
im = cv2.imread(im_path)
data_rot, im = rot(data_[data_.sceneId == scene], im, k)
# image
rot_angle = k2rot[k]
images[scene + rot_angle] = im
data_rot['sceneId'] = scene + rot_angle
data_rot['metaId'] = data_rot['metaId'] + metaId_max + 1
data = data.append(data_rot)
metaId_max = data['metaId'].max()
for scene in data.sceneId.unique():
im = images[scene]
data_flip, im_flip = fliplr(data[data.sceneId == scene], im)
data_flip['sceneId'] = data_flip['sceneId'] + '_fliplr'
data_flip['metaId'] = data_flip['metaId'] + metaId_max + 1
data = data.append(data_flip)
images[scene + '_fliplr'] = im_flip
return data, images
def resize_and_pad_image(images, size, pad=2019):
""" Resize image to desired size and pad image to make it square shaped and ratio of images still is the same, as
images all have different sizes.
"""
for key, im in images.items():
H, W, C = im.shape
im = cv2.copyMakeBorder(im, 0, pad - H, 0, pad - W, cv2.BORDER_CONSTANT)
im = cv2.resize(im, (size, size), interpolation=cv2.INTER_AREA)
images[key] = im
def create_images_dict(data, image_path, image_file='reference.jpg', use_raw_data=False):
images = {}
for scene in data.sceneId.unique():
if image_file == 'oracle.png':
im = cv2.imread(os.path.join(image_path, scene, image_file), 0)
else:
if use_raw_data:
scene_name, scene_idx = scene.split("_")
im_path = os.path.join(image_path, scene_name, f"video{scene_idx}", image_file)
else:
im_path = os.path.join(image_path, scene, image_file)
im = cv2.imread(im_path)
images[scene] = im
return images
def load_images(scenes, image_path, image_file='reference.jpg'):
images = {}
if type(scenes) is list:
scenes = set(scenes)
for scene in scenes:
if image_file == 'oracle.png':
im = cv2.imread(os.path.join(image_path, scene, image_file), 0)
else:
im = cv2.imread(os.path.join(image_path, scene, image_file))
images[scene] = im
return images
def compute_vel_labels(df):
vel_labels = {}
meta_ids = np.unique(df["metaId"].values)
for meta_id in meta_ids:
vel_mean, label = compute_vel_meta_id(df, meta_id)
if label not in vel_labels:
vel_labels[label] = []
vel_labels[label] += [vel_mean]
return vel_labels
def compute_vel_meta_id(df, meta_id):
df_meta = df[df["metaId"] == meta_id]
x = df_meta["x"].values
y = df_meta["y"].values
unique_labels = np.unique(df_meta["label"].values)
assert len(unique_labels) == 1
label = unique_labels[0]
frame_steps = []
for frame_idx, frame in enumerate(df_meta["frame"].values):
if frame_idx != len(df_meta["frame"].values) - 1:
frame_steps.append(df_meta["frame"].values[frame_idx + 1] - frame)
unique_frame_step = np.unique(frame_steps)
assert len(unique_frame_step) == 1
frame_step = unique_frame_step[0]
vel = []
for i in range(len(x)):
if i != len(x) - 1:
vel_i = math.sqrt(((x[i+1] - x[i])/frame_step)**2 + ((y[i+1] - y[i])/frame_step)**2)
vel.append(vel_i)
vel_mean = np.mean(vel)
return vel_mean, label
def create_vel_dataset(df, vel_ranges, labels, out_dir):
pathlib.Path(out_dir).mkdir(parents=True, exist_ok=True)
vel_meta_ids = {vel_range: {"metaId": [], "sceneId": [], "label": []} for vel_range in vel_ranges}
meta_ids = np.unique(df["metaId"].values)
for meta_id in meta_ids:
vel_mean, label = compute_vel_meta_id(df, meta_id)
if label not in labels:
continue
for vel_range in vel_meta_ids.keys():
vel_min, vel_max = vel_range
if vel_mean >= vel_min and vel_mean <= vel_max:
vel_meta_ids[vel_range]["metaId"].append(meta_id)
unique_scene_ids = np.unique(df[df["metaId"] == meta_id]["sceneId"].values)
assert len(unique_scene_ids) == 1
scene_id = unique_scene_ids[0]
vel_meta_ids[vel_range]["sceneId"].append(scene_id)
vel_meta_ids[vel_range]["label"].append(label)
num_metas = min([len(vel_range_meta_ids["metaId"]) for vel_range_meta_ids in vel_meta_ids.values()])
for vel_range, vel_range_meta_ids in vel_meta_ids.items():
scene_ids, scene_counts = np.unique(vel_range_meta_ids["sceneId"], return_counts=True)
sorted_unique_scene_counts = np.unique(np.sort(scene_counts))
total_count = 0
prev_count = 0
mask = np.zeros_like(scene_counts).astype(bool)
for scene_count in sorted_unique_scene_counts:
total_count += (scene_counts >= scene_count).sum() * (scene_count - prev_count)
if total_count >= num_metas:
break
mask[scene_counts == scene_count] = True
prev_count = scene_count
total_counts = np.zeros_like(scene_counts)
total_counts[mask] = scene_counts[mask]
total_counts[mask==False] = prev_count
less = True
while less:
for i in np.where(mask==False)[0]:
total_counts[i] += min(1, num_metas - total_counts.sum())
if num_metas == total_counts.sum():
less = False
break
vel_range_meta_ids["sceneId"] = np.array(vel_range_meta_ids["sceneId"])
vel_range_meta_ids["metaId"] = np.array(vel_range_meta_ids["metaId"])
vel_range_meta_ids["label"] = np.array(vel_range_meta_ids["label"])
meta_id_mask = np.zeros_like(vel_range_meta_ids["metaId"]).astype(bool)
for scene_idx, scene_id in enumerate(scene_ids):
scene_count = total_counts[scene_idx]
scene_mask = vel_range_meta_ids["sceneId"] == scene_id
scene_labels = vel_range_meta_ids["label"][scene_mask]
unique_scene_labels, scene_labels_count = np.unique(scene_labels, return_counts=True)
scene_labels_chosen = []
while len(scene_labels_chosen) | |
<reponame>theGreenJedi/neon
from builtins import str
from pycuda.tools import context_dependent_memoize
from neon.backends import cuda_templates
from neon.backends.cuda_templates import (_common_fp16_to_fp32,
_common_round, # for fp32_to_fp16 converter
_common_max_abs,
_common_kepler,
_ew_types)
from neon.backends.util.source_module import SourceModule
"""
CUDA kernels for pooling layers, with support for max pooling and average pooling.
For each pooling type, there is an fprop function, a bprop function, and a bprop
for overlapping kernels. Each of the six kernels uses templating to perform dtype
conversion so it works for all data types (currently fp32 and fp16 are supported).
Additionally, there are templates for statistics collection, currently supporting
a global max abs over the output tensor which is passed in as an additional kernel
argument.
"""
def map_string2func(funcname, clss, compute_capability):
"""
Helper function that converts string function names to function calls
"""
if "_get_" + funcname not in globals():
raise AttributeError("kernel type '" + funcname + "' not understood")
return globals()["_get_" + funcname](clss, compute_capability)
# this template is used to hide variables that are only defined conditionally.
atomic_max = r"""
atomicMax(maxabs, intermediate_max);
"""
_common_divmod = r"""
__device__ __forceinline__ int div16(int numerator, int magic, int shift)
{
int res;
asm("vmad.s32.u32.u32 %0, %1.h0, %2.h0, 0;" : "=r"(res) : "r"(numerator), "r"(magic));
return res >> shift;
}
__device__ __forceinline__ int mod16(int numerator, int div, int maxdiv)
{
int res;
asm("vmad.s32.u32.u32 %0, -%1.h0, %2.h0, %3;" : "=r"(res) : "r"(div), "r"(maxdiv), "r"(numerator));
return res;
}
__device__ __forceinline__ int mad16(int a, int b, int c)
{
int res;
asm("vmad.s32.u32.u32 %0, %1.h0, %2.h0, %3;" : "=r"(res) : "r"(a), "r"(b), "r"(c));
return res;
}
__device__ __forceinline__ int msub16(int a, int b, int c)
{
int res;
asm("vmad.s32.u32.u32 %0, %1.h0, %2.h0, -%3;" : "=r"(res) : "r"(a), "r"(b), "r"(c));
return res;
}
"""
def prepare_template_vals(dtype, compute_capability, rounding=False):
"""
Set up template code snippets that are reused across multiple kernels.
Most are data type conversion and statistics collection related.
"""
template_vals = dict()
for key in ("inits", "finish", "stats_args", "mul_by_scale", "atomic_max", "cvt_out"):
template_vals[key] = ""
template_vals["common"] = _common_divmod
if rounding:
template_vals["common"] += _common_urand_gen
template_vals["common"] += _common_round["nearest"].get(dtype, "")
template_vals["inits"] += _init_rand_func + _init_rand_round_func
template_vals["finish"] += _finish_rand_func
mode = "random"
else:
mode = "nearest"
template_vals["common"] += _common_round[mode].get(dtype, "")
template_vals["common"] += _common_max_abs
if (compute_capability[0] == 3 and compute_capability[1] < 5) or compute_capability[0] < 3:
template_vals["common"] += _common_kepler
template_vals["type"] = _ew_types[dtype]["type"]
template_vals["cvt"] = _ew_types[dtype]["cvt"]
if dtype == "f2":
template_vals["common"] += _common_fp16_to_fp32
template_vals["cvt_out"] = "fp32_to_fp16"
elif dtype == "x2":
template_vals["stats_args"] += ", int* maxabs, float scale0"
template_vals["cvt"] = "(float)"
template_vals["cvt_out"] = "fp32_to_int16"
template_vals["mul_by_scale"] += "1/scale0 *"
template_vals["atomic_max"] += atomic_max
elif dtype == "f4":
pass
else:
raise ValueError("Did not understand clss dtype " + str(dtype))
return template_vals
# This section of the code contains templated CUDA-C code for the kernels.
@context_dependent_memoize
def _get_fprop_max(clss, compute_capability):
code = r"""
#define FLT_MAX 3.402823466E+38F
%(common)s
__global__ void spool_fprop_max(
const %(type)s* I, %(type)s* O, unsigned char* A,
float alpha, float beta, int flags,
int N, int W, int H, int D, int C,
int WN, int HWN, int DHWN, int P, int Q,
int magic_P, int shift_P, int QN, int PQN, int MPQN,
int pad_c, int pad_d, int pad_h, int pad_w,
int str_c, int str_d, int str_h, int str_w,
int S, int RS, int RST, int JRST,
int magic_S, int shift_S,
int magic_RS, int shift_RS, int magic_RST, int shift_RST,
int supP, int supQ, int shlP, int maskP, int shrP,
int shlQ, int maskQ, int shrQ, int maskN, int shrN
%(stats_args)s
)
{
extern __shared__ int lut[];
int tid = threadIdx.x;
int q = blockIdx.x;
int mp = blockIdx.y;
int k = blockIdx.z;
int m = mp * magic_P; m >>= shift_P;
int p = mp - m*supP;
// zigzag q back and forth to improve L2 cache perf
if (p & 1)
q = supQ - q - 1;
// Superblock P and Q
p = (p << shlP) + ((tid & maskP) >> shrP);
q = (q << shlQ) + ((tid & maskQ) >> shrQ);
int n = tid & maskN;
int sb = tid >> shrN;
int offset = k*MPQN + m*PQN + p*QN + mad16(q, N, n);
I += n;
O += offset;
A += offset;
float O_val = beta != 0.0f && p < P && q < Q && n < N ? %(cvt)s(__ldg(O)) : 0.0f;
if (tid < 32)
{
int kj = k * str_c - pad_c;
int mt = m * str_d - pad_d;
int pr = p * str_h - pad_h;
int qs = q * str_w - pad_w;
int inc = min(maskN + 1, 32);
int jrst = n;
while (jrst < JRST)
{
int j = div16(jrst, magic_RST, shift_RST);
int rst = mod16(jrst, j, RST);
int t = div16(rst, magic_RS, shift_RS);
int rs = mod16(rst, t, RS);
int r = div16(rs, magic_S, shift_S);
int s = mod16(rs, r, S);
int x = qs + s;
int y = pr + r;
int z = mt + t;
int c = kj + j;
bool bounds_x = x >= 0 && x < W;
bool bounds_y = y >= 0 && y < H;
bool bounds_z = z >= 0 && z < D;
bool bounds_c = c >= 0 && c < C;
bool in_bounds = bounds_x && bounds_y && bounds_z && bounds_c;
int sliceI = c*DHWN + z*HWN + y*WN + x*N;
int lut_offset = mad16(sb, JRST, jrst);
lut[lut_offset] = in_bounds ? sliceI : -1;
jrst += inc;
}
}
__syncthreads();
int intermediate_max = 0;
if (p < P && q < Q && n < N)
{
int jrst = 0;
int argmax = 0;
float max = -FLT_MAX;
while (jrst < JRST)
{
int lut_offset = mad16(sb, JRST, jrst);
int slice0 = lut[lut_offset + 0];
int slice1 = lut[lut_offset + 1];
int slice2 = lut[lut_offset + 2];
int slice3 = lut[lut_offset + 3];
// val needs to stay in fp32 or can't be se to FLT_MAX
float val0 = jrst + 0 < JRST && slice0 >= 0 ? %(cvt)s(__ldg(I + slice0)) : -FLT_MAX;
float val1 = jrst + 1 < JRST && slice1 >= 0 ? %(cvt)s(__ldg(I + slice1)) : -FLT_MAX;
float val2 = jrst + 2 < JRST && slice2 >= 0 ? %(cvt)s(__ldg(I + slice2)) : -FLT_MAX;
float val3 = jrst + 3 < JRST && slice3 >= 0 ? %(cvt)s(__ldg(I + slice3)) : -FLT_MAX;
if (val0 > max) {
max = val0;
argmax = jrst + 0;
}
if (val1 > max) {
max = val1;
argmax = jrst + 1;
}
if (val2 > max) {
max = val2;
argmax = jrst + 2;
}
if (val3 > max) {
max = val3;
argmax = jrst + 3;
}
jrst += 4;
}
// convert back to fp to write out
%(type)s temp_out = %(cvt_out)s( %(mul_by_scale)s (max*alpha + O_val*beta));
if (!(flags & 1)) {
*O = temp_out;
*A = (unsigned char)argmax;
}
intermediate_max = max_abs(0, temp_out); // compute abs
}
intermediate_max += 0;
%(atomic_max)s
}
"""
template_vals = prepare_template_vals(clss, compute_capability)
code = code % template_vals
module = SourceModule(code)
kernel = module.get_function("spool_fprop_max")
sig = "3P 2f 44I" + ("Pf" if (clss[0] == "x") else "")
kernel.prepare(sig)
return kernel
@context_dependent_memoize
def _get_fprop_avg(clss, compute_capability):
code = r"""
%(common)s
__global__ void spool_fprop_avg(
const %(type)s* I, %(type)s* O, unsigned char* A,
float alpha, float beta, int flags,
int N, int W, int H, int D, int C,
int WN, int HWN, int DHWN, int P, int Q,
int magic_P, int shift_P, int QN, int PQN, int MPQN,
int pad_c, int pad_d, int pad_h, int pad_w,
int str_c, int str_d, int str_h, int str_w,
int S, int RS, int RST, int JRST,
int magic_S, int shift_S,
int magic_RS, int shift_RS, int magic_RST, int shift_RST,
int supP, int supQ, int shlP, int maskP, int shrP,
int shlQ, int maskQ, int shrQ, int maskN, int shrN
%(stats_args)s
)
{
__shared__ float rcpWindowSize[32];
extern __shared__ int lut[];
int tid = threadIdx.x;
int q = blockIdx.x;
int mp = blockIdx.y;
int k = blockIdx.z;
int m = mp * magic_P; m >>= shift_P;
int p = mp - m*supP;
// zigzag q back and forth to | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#############################################
# WARNING #
#############################################
#
# This file is auto generated by the resource
# module builder playbook.
#
# Do not edit this file manually.
#
# Changes to this file will be over written
# by the resource module builder.
#
# Changes should be made in the model used to
# generate this file or in the resource module
# builder template.
#
#############################################
"""
The module file for asa_ogs
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
module: asa_ogs
short_description: Object Group resource module
description: This module configures and manages Objects and Groups on ASA platforms.
version_added: 1.0.0
author: <NAME> (@justjais)
notes:
- Tested against Cisco ASA Version 9.10(1)11
- This module works with connection C(network_cli). See L(ASA Platform Options,../network/user_guide/platform_asa.html).
options:
config:
description: A list of Object Group options.
type: list
elements: dict
suboptions:
object_type:
description: The object group type.
type: str
required: true
choices:
- icmp-type
- network
- protocol
- security
- service
- user
object_groups:
description: The object groups.
type: list
elements: dict
suboptions:
name:
description: Specifies object-group ID
required: true
type: str
description:
description: The description for the object-group.
type: str
icmp_type:
description: Configure an ICMP-type object
type: dict
suboptions:
icmp_object:
description: Defines the ICMP types in the group.
type: list
elements: str
choices: [alternate-address, conversion-error, echo, echo-reply, information-reply,
information-request, mask-reply, mask-request, mobile-redirect,
parameter-problem, redirect, router-advertisement, router-solicitation,
source-quench, time-exceeded, timestamp-reply, timestamp-request,
traceroute, unreachable]
network_object:
description: Configure a network object
type: dict
suboptions:
host:
description: Set this to specify a single host object.
type: list
elements: str
address:
description: Enter an IPv4 network address with space seperated netmask.
type: list
elements: str
ipv6_address:
description: Enter an IPv6 prefix.
type: list
elements: str
object:
description: Enter this keyword to specify a network object
type: list
elements: str
protocol_object:
description: Configure a protocol object
type: dict
suboptions:
protocol:
description:
- Defines the protocols in the group.
- User can either specify protocols directly/protocol numbers(0-255)
type: list
elements: str
security_group:
description: Configure a security-group
type: dict
suboptions:
sec_name:
description: Enter this keyword to specify a security-group name.
type: list
elements: str
tag:
description: Enter this keyword to specify a security-group tag.
type: list
elements: str
service_object:
description:
- Configure a service object
- NEW 'services_object' param is introduced at object_group level, please
use the newer 'services_object' param defined at object_group level instead of
'service_object' param at object_group level, as 'service_object' option
will get deprecated and removed in a future release.
type: dict
suboptions:
protocol:
description: Defines the protocols in the group.
type: list
elements: str
choices: [ah, eigrp, esp, gre, icmp, icmp6, igmp, igrp, ip, ipinip,
ipsec, nos, ospf, pcp, pim, pptp, sctp, snp, tcp, tcp-udp, udp]
object:
description: Enter this keyword to specify a service object
type: str
services_object:
description:
- Configure list of service objects
- Newer OGs services_object param which will replace service_object param
- Relased with version 2.1.0
type: list
elements: dict
suboptions:
protocol:
description: Defines the protocols in the group.
type: str
object:
description: Enter this keyword to specify a service object
type: str
source_port:
description: Keyword to specify source port
type: dict
suboptions:
eq:
description: Match only packets on a given port number.
type: str
gt:
description: Match only packets with a greater port number.
type: str
lt:
description: Match only packets with a lower port number.
type: str
neq:
description: Match only packets not on a given port number.
type: str
range:
description: Port range operator
type: dict
suboptions:
start:
description: Specify the start of the port range.
type: int
end:
description: Specify the end of the port range.
type: int
destination_port:
description: Keyword to specify destination port
type: dict
suboptions:
eq:
description: Match only packets on a given port number.
type: str
gt:
description: Match only packets with a greater port number.
type: str
lt:
description: Match only packets with a lower port number.
type: str
neq:
description: Match only packets not on a given port number.
type: str
range:
description: Port range operator
type: dict
suboptions:
start:
description: Specify the start of the port range.
type: int
end:
description: Specify the end of the port range.
type: int
protocol:
description:
- Specifies that object-group is for only specified protocol only.
- Required when port-object need to be configured
type: str
choices: [tcp, tcp-udp, udp]
port_object:
description: Configure a port object
type: list
elements: dict
suboptions:
eq:
description: Enter this keyword to specify a port
type: str
range:
description: Enter this keyword to specify a range of ports
type: dict
suboptions:
start:
description: Specify the start of the port range.
type: int
end:
description: Specify the end of the port range.
type: int
user_object:
description: Configures single user, local or import user group
type: dict
suboptions:
user:
description: Configure a user objectUser name to configure a user
object.
type: list
elements: dict
suboptions:
name:
description: Enter the name of the user
type: str
required: true
domain:
description: User domain
type: str
required: true
user_group:
description: Configure a user group object.
type: list
elements: dict
suboptions:
name:
description: Enter the name of the group
type: str
required: true
domain:
description: Group domain
type: str
required: true
group_object:
description: Configure an object group as an object
type: list
elements: str
running_config:
description:
- The module, by default, will connect to the remote device and retrieve the current
running-config to use as a base for comparing against the contents of source.
There are times when it is not desirable to have the task get the current running-config
for every task in a playbook. The I(running_config) argument allows the implementer
to pass in the configuration to use as the base config for comparison. This
value of this option should be the output received from device by executing
command.
type: str
state:
description:
- The state the configuration should be left in
type: str
choices:
- merged
- replaced
- overridden
- deleted
- gathered
- rendered
- parsed
default: merged
"""
EXAMPLES = """
# Using merged
# Before state:
# -------------
#
# ciscoasa# sh running-config object-group
# object-group network test_og_network
# description test_network_og
# network-object host 192.168.3.11
- name: "Merge module attributes of given object-group"
cisco.asa.asa_ogs:
config:
- object_type: network
object_groups:
- name: group_network_obj
group_object:
- test_og_network
- name: test_og_network
description: test_og_network
network_object:
host:
- 192.0.2.1
- 192.0.2.2
address:
- 192.0.2.0 255.255.255.0
- 198.51.100.0 255.255.255.0
- name: test_network_og
description: test_network_og
network_object:
host:
- 192.168.3.11
- 192.168.3.11
ipv6_address:
- 2001:db8:3::/64
- object_type: security
object_groups:
- name: test_og_security
description: test_security
security_group:
sec_name:
- test_1
- test_2
tag:
- 10
- 20
- object_type: service
object_groups:
- name: O-Worker
services_object:
- protocol: tcp
destination_port:
range:
start: 100
end: 200
- protocol: tcp-udp
source_port:
eq: 1234
destination_port:
gt: nfs
- name: O-UNIX-TCP
protocol: tcp
port_object:
- eq: https
- range:
start: 100
end: 400
- object_type: user
object_groups:
- name: test_og_user
description: test_user
user_object:
user:
- name: new_user_1
domain: LOCAL
- name: new_user_2
domain: LOCAL
state: merged
# Commands fired:
# ---------------
#
# object-group security test_og_security
# description test_security
# security-group name test_1
# security-group name test_2
# security-group tag 10
# security-group tag 20
# object-group network group_network_obj
# group-object test_og_network
# object-group network test_og_network
# description test_og_network
# network-object 192.0.2.0 255.255.255.0
# network-object 198.51.100.0 255.255.255.0
# network-object host 192.0.2.1
# network-object host 192.0.2.2
# object-group network test_network_og
# network-object host 192.168.3.11
# network-object host 192.168.3.11
# network-object 2001:db8:3::/64
# object-group service O-Worker
# service-object tcp destination range 100 200
# service-object tcp source eq 1234 destination gt nfs
# object-group service O-UNIX-TCP tcp
# port-object eq https
# port-object range 100 400
# object-group user test_og_user
# description test_user
# user LOCAL\\new_user_1
# user LOCAL\\new_user_2
# After state:
# ------------
#
# ciscoasa# sh running-config object-group
# object-group network group_network_obj
# group-object test_og_network
# object-group network test_og_network
# description test_og_network
# network-object host 192.0.2.1
# network-object host 192.0.2.2
# network-object 192.0.2.0 255.255.255.0
# network-object 198.51.100.0 255.255.255.0
# network-object host 192.168.3.11
# object-group network test_network_og
# description test_network_og
# network-object host 192.168.3.11
# network-object host 192.168.3.11
# network-object 2001:db8:0:3::/64
# group-object test_og_network
# object-group security test_og_security
# security-group name test_1
# security-group name test_2
# security-group tag 10
# security-group tag 20
# object-group service O-Worker
# service-object | |
== 11:
if ftype == TType.STRING:
self.cld_in = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 12:
if ftype == TType.STRING:
self.cli_in = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 13:
if ftype == TType.STRING:
self.prefix = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 14:
if ftype == TType.DOUBLE:
self.price_1 = iprot.readDouble()
else:
iprot.skip(ftype)
elif fid == 15:
if ftype == TType.DOUBLE:
self.price_n = iprot.readDouble()
else:
iprot.skip(ftype)
elif fid == 16:
if ftype == TType.I32:
self.interval_1 = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 17:
if ftype == TType.I32:
self.interval_n = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 18:
if ftype == TType.DOUBLE:
self.post_call_surcharge = iprot.readDouble()
else:
iprot.skip(ftype)
elif fid == 19:
if ftype == TType.DOUBLE:
self.connect_fee = iprot.readDouble()
else:
iprot.skip(ftype)
elif fid == 20:
if ftype == TType.I64:
self.free_seconds = iprot.readI64()
else:
iprot.skip(ftype)
elif fid == 21:
if ftype == TType.STRING:
self.remote_ip = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 22:
if ftype == TType.I32:
self.grace_period = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 23:
if ftype == TType.STRING:
self.user_agent = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 24:
if ftype == TType.DOUBLE:
self.pdd1xx = iprot.readDouble()
else:
iprot.skip(ftype)
elif fid == 25:
if ftype == TType.I16:
self.i_protocol = iprot.readI16()
else:
iprot.skip(ftype)
elif fid == 26:
if ftype == TType.STRING:
self.release_source = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 27:
if ftype == TType.DOUBLE:
self.plan_duration = iprot.readDouble()
else:
iprot.skip(ftype)
elif fid == 28:
if ftype == TType.DOUBLE:
self.accessibility_cost = iprot.readDouble()
else:
iprot.skip(ftype)
elif fid == 29:
if ftype == TType.STRUCT:
self.lrn_cld = NullString()
self.lrn_cld.read(iprot)
else:
iprot.skip(ftype)
elif fid == 30:
if ftype == TType.STRUCT:
self.lrn_cld_in = NullString()
self.lrn_cld_in.read(iprot)
else:
iprot.skip(ftype)
elif fid == 31:
if ftype == TType.STRUCT:
self.area_name = NullString()
self.area_name.read(iprot)
else:
iprot.skip(ftype)
elif fid == 32:
if ftype == TType.STRUCT:
self.p_asserted_id = NullString()
self.p_asserted_id.read(iprot)
else:
iprot.skip(ftype)
elif fid == 33:
if ftype == TType.STRUCT:
self.remote_party_id = NullString()
self.remote_party_id.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('Cdrs')
if self.i_cdr is not None:
oprot.writeFieldBegin('i_cdr', TType.I64, 1)
oprot.writeI64(self.i_cdr)
oprot.writeFieldEnd()
if self.i_call is not None:
oprot.writeFieldBegin('i_call', TType.I64, 2)
oprot.writeI64(self.i_call)
oprot.writeFieldEnd()
if self.i_account is not None:
oprot.writeFieldBegin('i_account', TType.I64, 3)
oprot.writeI64(self.i_account)
oprot.writeFieldEnd()
if self.result is not None:
oprot.writeFieldBegin('result', TType.I64, 4)
oprot.writeI64(self.result)
oprot.writeFieldEnd()
if self.cost is not None:
oprot.writeFieldBegin('cost', TType.DOUBLE, 5)
oprot.writeDouble(self.cost)
oprot.writeFieldEnd()
if self.delay is not None:
oprot.writeFieldBegin('delay', TType.DOUBLE, 6)
oprot.writeDouble(self.delay)
oprot.writeFieldEnd()
if self.duration is not None:
oprot.writeFieldBegin('duration', TType.DOUBLE, 7)
oprot.writeDouble(self.duration)
oprot.writeFieldEnd()
if self.billed_duration is not None:
oprot.writeFieldBegin('billed_duration', TType.DOUBLE, 8)
oprot.writeDouble(self.billed_duration)
oprot.writeFieldEnd()
if self.connect_time is not None:
oprot.writeFieldBegin('connect_time', TType.I64, 9)
oprot.writeI64(self.connect_time)
oprot.writeFieldEnd()
if self.disconnect_time is not None:
oprot.writeFieldBegin('disconnect_time', TType.I64, 10)
oprot.writeI64(self.disconnect_time)
oprot.writeFieldEnd()
if self.cld_in is not None:
oprot.writeFieldBegin('cld_in', TType.STRING, 11)
oprot.writeString(self.cld_in.encode('utf-8') if sys.version_info[0] == 2 else self.cld_in)
oprot.writeFieldEnd()
if self.cli_in is not None:
oprot.writeFieldBegin('cli_in', TType.STRING, 12)
oprot.writeString(self.cli_in.encode('utf-8') if sys.version_info[0] == 2 else self.cli_in)
oprot.writeFieldEnd()
if self.prefix is not None:
oprot.writeFieldBegin('prefix', TType.STRING, 13)
oprot.writeString(self.prefix.encode('utf-8') if sys.version_info[0] == 2 else self.prefix)
oprot.writeFieldEnd()
if self.price_1 is not None:
oprot.writeFieldBegin('price_1', TType.DOUBLE, 14)
oprot.writeDouble(self.price_1)
oprot.writeFieldEnd()
if self.price_n is not None:
oprot.writeFieldBegin('price_n', TType.DOUBLE, 15)
oprot.writeDouble(self.price_n)
oprot.writeFieldEnd()
if self.interval_1 is not None:
oprot.writeFieldBegin('interval_1', TType.I32, 16)
oprot.writeI32(self.interval_1)
oprot.writeFieldEnd()
if self.interval_n is not None:
oprot.writeFieldBegin('interval_n', TType.I32, 17)
oprot.writeI32(self.interval_n)
oprot.writeFieldEnd()
if self.post_call_surcharge is not None:
oprot.writeFieldBegin('post_call_surcharge', TType.DOUBLE, 18)
oprot.writeDouble(self.post_call_surcharge)
oprot.writeFieldEnd()
if self.connect_fee is not None:
oprot.writeFieldBegin('connect_fee', TType.DOUBLE, 19)
oprot.writeDouble(self.connect_fee)
oprot.writeFieldEnd()
if self.free_seconds is not None:
oprot.writeFieldBegin('free_seconds', TType.I64, 20)
oprot.writeI64(self.free_seconds)
oprot.writeFieldEnd()
if self.remote_ip is not None:
oprot.writeFieldBegin('remote_ip', TType.STRING, 21)
oprot.writeString(self.remote_ip.encode('utf-8') if sys.version_info[0] == 2 else self.remote_ip)
oprot.writeFieldEnd()
if self.grace_period is not None:
oprot.writeFieldBegin('grace_period', TType.I32, 22)
oprot.writeI32(self.grace_period)
oprot.writeFieldEnd()
if self.user_agent is not None:
oprot.writeFieldBegin('user_agent', TType.STRING, 23)
oprot.writeString(self.user_agent.encode('utf-8') if sys.version_info[0] == 2 else self.user_agent)
oprot.writeFieldEnd()
if self.pdd1xx is not None:
oprot.writeFieldBegin('pdd1xx', TType.DOUBLE, 24)
oprot.writeDouble(self.pdd1xx)
oprot.writeFieldEnd()
if self.i_protocol is not None:
oprot.writeFieldBegin('i_protocol', TType.I16, 25)
oprot.writeI16(self.i_protocol)
oprot.writeFieldEnd()
if self.release_source is not None:
oprot.writeFieldBegin('release_source', TType.STRING, 26)
oprot.writeString(self.release_source.encode('utf-8') if sys.version_info[0] == 2 else self.release_source)
oprot.writeFieldEnd()
if self.plan_duration is not None:
oprot.writeFieldBegin('plan_duration', TType.DOUBLE, 27)
oprot.writeDouble(self.plan_duration)
oprot.writeFieldEnd()
if self.accessibility_cost is not None:
oprot.writeFieldBegin('accessibility_cost', TType.DOUBLE, 28)
oprot.writeDouble(self.accessibility_cost)
oprot.writeFieldEnd()
if self.lrn_cld is not None:
oprot.writeFieldBegin('lrn_cld', TType.STRUCT, 29)
self.lrn_cld.write(oprot)
oprot.writeFieldEnd()
if self.lrn_cld_in is not None:
oprot.writeFieldBegin('lrn_cld_in', TType.STRUCT, 30)
self.lrn_cld_in.write(oprot)
oprot.writeFieldEnd()
if self.area_name is not None:
oprot.writeFieldBegin('area_name', TType.STRUCT, 31)
self.area_name.write(oprot)
oprot.writeFieldEnd()
if self.p_asserted_id is not None:
oprot.writeFieldBegin('p_asserted_id', TType.STRUCT, 32)
self.p_asserted_id.write(oprot)
oprot.writeFieldEnd()
if self.remote_party_id is not None:
oprot.writeFieldBegin('remote_party_id', TType.STRUCT, 33)
self.remote_party_id.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class CdrsConnections(object):
"""
Attributes:
- i_cdrs_connection
- i_call
- i_connection
- result
- cost
- delay
- duration
- billed_duration
- setup_time
- connect_time
- disconnect_time
- cld_out
- cli_out
- prefix
- price_1
- price_n
- interval_1
- interval_n
- post_call_surcharge
- connect_fee
- free_seconds
- grace_period
- user_agent
- pdd100
- pdd1xx
- i_account_debug
- i_protocol
- release_source
- call_setup_time
- lrn_cld
- area_name
- i_media_relay
- remote_ip
- vendor_name
"""
thrift_spec = (
None, # 0
(1, TType.I64, 'i_cdrs_connection', None, None, ), # 1
(2, TType.I64, 'i_call', None, None, ), # 2
(3, TType.I64, 'i_connection', None, None, ), # 3
(4, TType.I32, 'result', None, None, ), # 4
(5, TType.DOUBLE, 'cost', None, None, ), # 5
(6, TType.DOUBLE, 'delay', None, None, ), # 6
(7, TType.DOUBLE, 'duration', None, None, ), # 7
(8, TType.DOUBLE, 'billed_duration', None, None, ), # 8
(9, TType.I64, 'setup_time', None, None, ), # 9
(10, TType.I64, 'connect_time', None, None, ), # 10
(11, TType.I64, 'disconnect_time', None, None, ), # 11
(12, TType.STRING, 'cld_out', 'UTF8', None, ), # 12
(13, TType.STRING, 'cli_out', 'UTF8', None, ), # 13
(14, TType.STRING, 'prefix', 'UTF8', None, ), # 14
(15, TType.DOUBLE, 'price_1', None, None, ), # 15
(16, TType.DOUBLE, 'price_n', None, None, ), # 16
(17, TType.I32, 'interval_1', None, None, ), # 17
(18, TType.I32, 'interval_n', None, None, ), # 18
(19, TType.DOUBLE, 'post_call_surcharge', None, None, ), # 19
(20, TType.DOUBLE, 'connect_fee', None, None, ), # 20
(21, TType.I32, 'free_seconds', None, None, ), # 21
(22, TType.I32, 'grace_period', None, None, ), # 22
(23, TType.STRING, 'user_agent', 'UTF8', None, ), # 23
(24, TType.DOUBLE, 'pdd100', None, None, ), # 24
(25, TType.DOUBLE, 'pdd1xx', None, None, ), # 25
(26, TType.I64, 'i_account_debug', None, None, ), # 26
(27, TType.I32, 'i_protocol', None, None, ), # 27
(28, TType.STRING, 'release_source', 'UTF8', None, ), # 28
(29, TType.I64, 'call_setup_time', None, None, ), # 29
(30, TType.STRUCT, 'lrn_cld', (NullString, NullString.thrift_spec), None, ), # 30
(31, TType.STRUCT, 'area_name', (NullString, NullString.thrift_spec), None, ), # 31
(32, TType.STRUCT, 'i_media_relay', (NullInt64, NullInt64.thrift_spec), None, ), # 32
(33, TType.STRUCT, 'remote_ip', (NullString, NullString.thrift_spec), None, ), # 33
(34, TType.STRUCT, 'vendor_name', (NullString, NullString.thrift_spec), None, ), # 34
)
def __init__(self, i_cdrs_connection=None, i_call=None, i_connection=None, result=None, cost=None, delay=None, duration=None, billed_duration=None, setup_time=None, connect_time=None, disconnect_time=None, cld_out=None, cli_out=None, prefix=None, price_1=None, price_n=None, interval_1=None, interval_n=None, post_call_surcharge=None, connect_fee=None, free_seconds=None, grace_period=None, user_agent=None, pdd100=None, pdd1xx=None, i_account_debug=None, i_protocol=None, release_source=None, call_setup_time=None, lrn_cld=None, area_name=None, i_media_relay=None, remote_ip=None, vendor_name=None,):
self.i_cdrs_connection = i_cdrs_connection
self.i_call = i_call
self.i_connection = i_connection
self.result = result
self.cost = cost
self.delay = delay
self.duration = duration
self.billed_duration = billed_duration
self.setup_time = setup_time
self.connect_time = connect_time
self.disconnect_time = disconnect_time
self.cld_out = cld_out
self.cli_out = cli_out
self.prefix = prefix
self.price_1 = price_1
self.price_n = price_n
self.interval_1 = interval_1
self.interval_n = interval_n
self.post_call_surcharge = post_call_surcharge
self.connect_fee = connect_fee
self.free_seconds = free_seconds
self.grace_period = grace_period
self.user_agent = user_agent
self.pdd100 = pdd100
self.pdd1xx = pdd1xx
self.i_account_debug = i_account_debug
self.i_protocol = i_protocol
self.release_source = release_source
self.call_setup_time = call_setup_time
self.lrn_cld = lrn_cld
self.area_name = area_name
self.i_media_relay = i_media_relay
self.remote_ip = remote_ip
self.vendor_name = vendor_name
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not | |
some commonly useful distributions,
`co2Qgates` can be a list of lists of lists of compatible 2-qubit gates ("nested" sampling).
In this case, a list of lists of compatible 2-qubit gates is picked according to the distribution
`co2Qgatesprob`, and then one of the sublists of compatible 2-qubit gates in the selected list is
then chosen uniformly at random. For example, this is useful for sampling a layer containing one
uniformly random 2-qubit gate with probability p and a layer of 1-qubit gates with probability
1-p. Here, we can specify `co2Qgates` as [[],[[the 1st 2Q-gate,],[the 2nd 2Q-gate,], ...]] and
set `twoQprob=1` and `co2Qgatesprob = [1-p,p].
Parameters
----------
pspec : ProcessorSpec
The ProcessorSpec for the device that the circuit layer is being sampled for. Unless
`qubit_labels` is not None, a circuit layer is sampled over all the qubits in `pspec`.
qubit_labels : list
If not None, a list of the qubits to sample the circuit layer for. This is a subset of
`pspec.qubit_labels`. If None, the circuit layer is sampled to act on all the qubits
in `pspec`.
co2Qgates : list
This is either:
1. A list of lists of 2-qubit gate Labels that can be applied in parallel.
2. A list of lists of lists of 2-qubit gate Labels that can be applied in parallel.
In case (1) each list in `co2Qgates` should contain 2-qubit gates, in the form of Labels,
that can be applied in parallel and act only on the qubits in `pspec` if `qubit_labels` is None,
or act only on the qubits in `qubit_labels` if `qubit_labels` is not None. The sampler then picks
one of these compatible sets of gates (with probability specified by `co2Qgatesprob`, and converts
this into a circuit layer by applying the 2-qubit gates it contains with the user-specified
probability `twoQprob`, and augmenting these 2-qubit gates with 1-qubit gates on all other qubits.
In case (2) a sublist of lists is sampled from `co2Qgates` according to `co2Qgatesprob` and then we
proceed as in case (1) but as though `co2Qgatesprob` is the uniform distribution.
co2Qgatesprob : str or list of floats
If a list, they are unnormalized probabilities to sample each of the elements of `co2Qgates`. So it
is a list of non-negative floats of the same length as `co2Qgates`. If 'uniform', then the uniform
distribution is used.
twoQprob : float, optional
The probability for each two-qubit gate to be applied to a pair of qubits, after a
set of compatible 2-qubit gates has been chosen. The expected number of 2-qubit
gates in a layer is `twoQprob` times the expected number of 2-qubit gates in a
set of compatible 2-qubit gates sampled according to `co2Qgatesprob`.
oneQgatenames : 'all' or list of strs, optional
If not 'all', a list of the names of the 1-qubit gates to be sampled from when applying
a 1-qubit gate to a qubit. If this is 'all', the full set of 1-qubit gate names is
extracted from the ProcessorSpec.
modelname : str, optional
Only used if oneQgatenames is 'all'. Specifies which of the `pspec.models` to use to
extract the model. The `clifford` default is suitable for Clifford or direct RB,
but will not use any non-Clifford gates in the model.
Returns
-------
list of gates
A list of gate Labels that defines a "complete" circuit layer (there is one and
only one gate acting on each qubit).
"""
assert(modelname == 'clifford'), "This function currently assumes sampling from a Clifford model!"
# Pick the sector.
if isinstance(co2Qgatesprob, str):
assert(co2Qgatesprob == 'uniform'), "If `co2Qgatesprob` is a string it must be 'uniform!'"
twoqubitgates_or_nestedco2Qgates = co2Qgates[_np.random.randint(0, len(co2Qgates))]
else:
co2Qgatesprob = _np.array(co2Qgatesprob) / _np.sum(co2Qgatesprob)
x = list(_np.random.multinomial(1, co2Qgatesprob))
twoqubitgates_or_nestedco2Qgates = co2Qgates[x.index(1)]
# The special case where the selected co2Qgates contains no gates or co2Qgates.
if len(twoqubitgates_or_nestedco2Qgates) == 0:
twoqubitgates = twoqubitgates_or_nestedco2Qgates
# If it's a nested sector, sample uniformly from the nested co2Qgates.
elif type(twoqubitgates_or_nestedco2Qgates[0]) == list:
twoqubitgates = twoqubitgates_or_nestedco2Qgates[_np.random.randint(0, len(twoqubitgates_or_nestedco2Qgates))]
# If it's not a list of "co2Qgates" (lists) then this is the list of gates to use.
else:
twoqubitgates = twoqubitgates_or_nestedco2Qgates
# Prep the sampling variables
sampled_layer = []
if qubit_labels is not None:
assert(isinstance(qubit_labels, list) or isinstance(qubit_labels, tuple)), "SubsetQs must be a list or a tuple!"
remaining_qubits = list(qubit_labels[:]) # copy this list
else:
remaining_qubits = pspec.qubit_labels[:] # copy this list
# Go through the 2-qubit gates in the sector, and apply each one with probability twoQprob
for i in range(0, len(twoqubitgates)):
if _np.random.binomial(1, twoQprob) == 1:
gate = twoqubitgates[i]
# If it's a nested co2Qgates:
sampled_layer.append(gate)
# Delete the qubits that have been assigned a gate.
del remaining_qubits[remaining_qubits.index(gate.qubits[0])]
del remaining_qubits[remaining_qubits.index(gate.qubits[1])]
# Go through the qubits which don't have a 2-qubit gate assigned to them, and pick a 1-qubit gate
for i in range(0, len(remaining_qubits)):
qubit = remaining_qubits[i]
# If the 1-qubit gate names are specified, use these.
if oneQgatenames != 'all':
possibleops = [_lbl.Label(name, (qubit,)) for name in oneQgatenames]
# If the 1-qubit gate names are not specified, find the available 1-qubit gates
else:
if modelname == 'clifford':
possibleops = pspec.clifford_ops_on_qubits[(qubit,)]
else:
possibleops = pspec.models[modelname].get_primitive_op_labels()
l = len(possibleops)
for j in range(0, l):
if possibleops[l - j].number_of_qubits != 1:
del possibleops[l - j]
else:
if possibleops[l - j].qubits[0] != qubit:
del possibleops[l - j]
gate = possibleops[_np.random.randint(0, len(possibleops))]
sampled_layer.append(gate)
return sampled_layer
def circuit_layer_of_oneQgates(pspec, qubit_labels=None, oneQgatenames='all', pdist='uniform',
modelname='clifford'):
"""
Samples a random circuit layer containing only 1-qubit gates. The allowed
1-qubit gates are specified by `oneQgatenames`, and the 1-qubit gates are
sampled independently and uniformly.
Parameters
----------
pspec : ProcessorSpec
The ProcessorSpec for the device that the circuit layer is being sampled for. Unless
`qubit_labels` is not None, a circuit layer is sampled over all the qubits in `pspec`.
qubit_labels : list, optional
If not None, a list of the qubits to sample the circuit layer for. This is a subset of
`pspec.qubit_labels`. If None, the circuit layer is sampled to acton all the qubits
in `pspec`.
oneQgatenames : 'all' or list of strs, optional
If not 'all', a list of the names of the 1-qubit gates to be sampled from when applying
a 1-qubit gate to a qubit. If this is 'all', the full set of 1-qubit gate names is
extracted from the ProcessorSpec.
pdist : 'uniform' or list of floats, optional
If a list, they are unnormalized probabilities to sample each of the 1-qubit gates
in the list `oneQgatenames`. If this is not 'uniform', then oneQgatename` must not
be 'all' (it must be a list so that it is unambigious which probability correpsonds
to which gate). So if not 'uniform', `pdist` is a list of non-negative floats of the
same length as `oneQgatenames`. If 'uniform', then the uniform distribution over
the gates is used.
modelname : str, optional
Only used if oneQgatenames is 'all'. Specifies which of the `pspec.models` to use to
extract the model. The `clifford` default is suitable for Clifford or direct RB,
but will not use any non-Clifford gates in the model.
Returns
-------
list of gates
A list of gate Labels that defines a "complete" circuit layer (there is one and
only one gate acting on each qubit).
"""
if qubit_labels is not None:
assert(isinstance(qubit_labels, list) or isinstance(qubit_labels, tuple)), "SubsetQs must be a list or a tuple!"
qubits = list(qubit_labels[:]) # copy this list
else:
qubits = list(pspec.qubit_labels[:]) # copy this list
sampled_layer = []
if isinstance(pdist, str): assert(pdist == 'uniform'), "If pdist is not a list or numpy.array it must be 'uniform'"
if oneQgatenames == 'all':
assert(pdist == 'uniform'), "If `oneQgatenames` = 'all', pdist must be 'uniform'"
if modelname == 'clifford':
for i in qubits:
try:
gate = pspec.clifford_ops_on_qubits[(i,)][_np.random.randint(
0, len(pspec.clifford_ops_on_qubits[(i,)]))]
sampled_layer.append(gate)
except:
raise ValueError("There are no 1Q Clifford gates on qubit {}!".format(i))
else: raise ValueError("Currently, 'modelname' must be 'clifford'")
else:
# A basic check for the validity of | |
<filename>neutron/plugins/ml2/drivers/ovn/mech_driver/ovsdb/ovn_client.py
# Copyright 2019 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import collections
import copy
import netaddr
from neutron_lib.api.definitions import l3
from neutron_lib.api.definitions import port_security as psec
from neutron_lib.api.definitions import portbindings
from neutron_lib.api.definitions import provider_net as pnet
from neutron_lib.api.definitions import segment as segment_def
from neutron_lib import constants as const
from neutron_lib import context as n_context
from neutron_lib import exceptions as n_exc
from neutron_lib.plugins import constants as plugin_constants
from neutron_lib.plugins import directory
from neutron_lib.plugins import utils as p_utils
from neutron_lib.utils import helpers
from neutron_lib.utils import net as n_net
from oslo_config import cfg
from oslo_log import log
from oslo_utils import excutils
from ovsdbapp.backend.ovs_idl import idlutils
from neutron.common.ovn import acl as ovn_acl
from neutron.common.ovn import constants as ovn_const
from neutron.common.ovn import utils
from neutron.conf.plugins.ml2.drivers.ovn import ovn_conf
from neutron.db import ovn_revision_numbers_db as db_rev
from neutron.db import segments_db
from neutron.plugins.ml2.drivers.ovn.mech_driver.ovsdb.extensions \
import qos as qos_extension
from neutron.scheduler import l3_ovn_scheduler
LOG = log.getLogger(__name__)
OvnPortInfo = collections.namedtuple(
'OvnPortInfo', ['type', 'options', 'addresses', 'port_security',
'parent_name', 'tag', 'dhcpv4_options', 'dhcpv6_options',
'cidrs', 'device_owner', 'security_group_ids'])
GW_INFO = collections.namedtuple('GatewayInfo', ['network_id', 'subnet_id',
'router_ip', 'gateway_ip',
'ip_version', 'ip_prefix'])
class OVNClient(object):
def __init__(self, nb_idl, sb_idl):
self._nb_idl = nb_idl
self._sb_idl = sb_idl
self._plugin_property = None
self._l3_plugin_property = None
# TODO(ralonsoh): handle the OVN client extensions with an ext. manager
self._qos_driver = qos_extension.OVNClientQosExtension(self)
self._ovn_scheduler = l3_ovn_scheduler.get_scheduler()
@property
def _plugin(self):
if self._plugin_property is None:
self._plugin_property = directory.get_plugin()
return self._plugin_property
@property
def _l3_plugin(self):
if self._l3_plugin_property is None:
self._l3_plugin_property = directory.get_plugin(
plugin_constants.L3)
return self._l3_plugin_property
def _transaction(self, commands, txn=None):
"""Create a new transaction or add the commands to an existing one."""
if txn is None:
with self._nb_idl.transaction(check_error=True) as new_txn:
for cmd in commands:
new_txn.add(cmd)
else:
for cmd in commands:
txn.add(cmd)
def _is_virtual_port_supported(self):
# TODO(lucasagomes): Remove this method in the future. The
# "virtual" port type was added in the version 2.12 of OVN
return self._sb_idl.is_col_present('Port_Binding', 'virtual_parent')
def is_external_ports_supported(self):
return self._nb_idl.is_col_present(
'Logical_Switch_Port', 'ha_chassis_group')
def _get_allowed_addresses_from_port(self, port):
if not port.get(psec.PORTSECURITY):
return [], []
if utils.is_lsp_trusted(port):
return [], []
allowed_addresses = set()
new_macs = set()
addresses = port['mac_address']
for ip in port.get('fixed_ips', []):
addresses += ' ' + ip['ip_address']
for allowed_address in port.get('allowed_address_pairs', []):
# If allowed address pair has same mac as the port mac,
# append the allowed ip address to the 'addresses'.
# Else we will have multiple entries for the same mac in
# 'Logical_Switch_Port.port_security'.
if allowed_address['mac_address'] == port['mac_address']:
addresses += ' ' + allowed_address['ip_address']
else:
allowed_addresses.add(allowed_address['mac_address'] + ' ' +
allowed_address['ip_address'])
new_macs.add(allowed_address['mac_address'])
allowed_addresses.add(addresses)
return list(allowed_addresses), list(new_macs)
def _get_subnet_dhcp_options_for_port(self, port, ip_version):
"""Returns the subnet dhcp options for the port.
Return the first found DHCP options belong for the port.
"""
subnets = [
fixed_ip['subnet_id']
for fixed_ip in port['fixed_ips']
if netaddr.IPAddress(fixed_ip['ip_address']).version == ip_version]
get_opts = self._nb_idl.get_subnets_dhcp_options(subnets)
if get_opts:
if ip_version == const.IP_VERSION_6:
# Always try to find a dhcpv6 stateful v6 subnet to return.
# This ensures port can get one stateful v6 address when port
# has multiple dhcpv6 stateful and stateless subnets.
for opts in get_opts:
# We are setting ovn_const.DHCPV6_STATELESS_OPT to "true"
# in _get_ovn_dhcpv6_opts, so entries in DHCP_Options table
# should have unicode type 'true' if they were defined as
# dhcpv6 stateless.
if opts['options'].get(
ovn_const.DHCPV6_STATELESS_OPT) != 'true':
return opts
return get_opts[0]
def _get_port_dhcp_options(self, port, ip_version):
"""Return dhcp options for port.
In case the port is dhcp disabled, or IP addresses it has belong
to dhcp disabled subnets, returns None.
Otherwise, returns a dict:
- with content from a existing DHCP_Options row for subnet, if the
port has no extra dhcp options.
- with only one item ('cmd', AddDHCPOptionsCommand(..)), if the port
has extra dhcp options. The command should be processed in the same
transaction with port creating or updating command to avoid orphan
row issue happen.
"""
lsp_dhcp_disabled, lsp_dhcp_opts = utils.get_lsp_dhcp_opts(
port, ip_version)
if lsp_dhcp_disabled:
return
subnet_dhcp_options = self._get_subnet_dhcp_options_for_port(
port, ip_version)
if not subnet_dhcp_options:
# NOTE(lizk): It's possible for Neutron to configure a port with IP
# address belongs to subnet disabled dhcp. And no DHCP_Options row
# will be inserted for such a subnet. So in that case, the subnet
# dhcp options here will be None.
return
if not lsp_dhcp_opts:
return subnet_dhcp_options
# This port has extra DHCP options defined, so we will create a new
# row in DHCP_Options table for it.
subnet_dhcp_options['options'].update(lsp_dhcp_opts)
subnet_dhcp_options['external_ids'].update(
{'port_id': port['id']})
subnet_id = subnet_dhcp_options['external_ids']['subnet_id']
add_dhcp_opts_cmd = self._nb_idl.add_dhcp_options(
subnet_id, port_id=port['id'],
cidr=subnet_dhcp_options['cidr'],
options=subnet_dhcp_options['options'],
external_ids=subnet_dhcp_options['external_ids'])
return {'cmd': add_dhcp_opts_cmd}
def get_virtual_port_parents(self, virtual_ip, port):
ls = self._nb_idl.ls_get(utils.ovn_name(port['network_id'])).execute(
check_error=True)
return [lsp.name for lsp in ls.ports
if lsp.name != port['id'] and
virtual_ip in utils.get_ovn_port_addresses(lsp)]
def _get_port_options(self, port):
context = n_context.get_admin_context()
binding_prof = utils.validate_and_get_data_from_binding_profile(port)
vtep_physical_switch = binding_prof.get('vtep-physical-switch')
port_type = ''
cidrs = ''
if vtep_physical_switch:
vtep_logical_switch = binding_prof.get('vtep-logical-switch')
port_type = 'vtep'
options = {'vtep-physical-switch': vtep_physical_switch,
'vtep-logical-switch': vtep_logical_switch}
addresses = [ovn_const.UNKNOWN_ADDR]
parent_name = []
tag = []
port_security = []
else:
options = {}
parent_name = binding_prof.get('parent_name', [])
tag = binding_prof.get('tag', [])
address = port['mac_address']
for ip in port.get('fixed_ips', []):
try:
subnet = self._plugin.get_subnet(context, ip['subnet_id'])
except n_exc.SubnetNotFound:
continue
ip_addr = ip['ip_address']
address += ' ' + ip_addr
cidrs += ' {}/{}'.format(ip['ip_address'],
subnet['cidr'].split('/')[1])
# Check if the port being created is a virtual port
if (self._is_virtual_port_supported() and
not port['device_owner']):
parents = self.get_virtual_port_parents(ip_addr, port)
if parents:
port_type = ovn_const.LSP_TYPE_VIRTUAL
options[ovn_const.LSP_OPTIONS_VIRTUAL_IP_KEY] = ip_addr
options[ovn_const.LSP_OPTIONS_VIRTUAL_PARENTS_KEY] = (
','.join(parents))
port_security, new_macs = (
self._get_allowed_addresses_from_port(port))
addresses = [address]
addresses.extend(new_macs)
# Only adjust the OVN type if the port is not owned by Neutron
# DHCP agents.
# TODO(mjozefcz): Remove const.DEVICE_OWNER_DHCP
# from get_ports in W-release.
if (port['device_owner'] in [
const.DEVICE_OWNER_DISTRIBUTED,
const.DEVICE_OWNER_DHCP] and
not utils.is_neutron_dhcp_agent_port(port)):
port_type = 'localport'
capabilities = utils.get_port_capabilities(port)
vnic_type = port.get(portbindings.VNIC_TYPE,
portbindings.VNIC_NORMAL)
if (vnic_type in ovn_const.EXTERNAL_PORT_TYPES and
ovn_const.PORT_CAP_SWITCHDEV not in capabilities):
if self.is_external_ports_supported():
port_type = ovn_const.LSP_TYPE_EXTERNAL
else:
LOG.warning('The version of OVN used does not support '
'the "external ports" feature used for '
'SR-IOV ports with OVN native DHCP')
# The "unknown" address should only be set for the normal LSP
# ports (the ones which type is empty)
if not port_security and not port_type:
# Port security is disabled for this port.
# So this port can send traffic with any mac address.
# OVN allows any mac address from a port if "unknown"
# is added to the Logical_Switch_Port.addresses column.
# So add it.
addresses.append(ovn_const.UNKNOWN_ADDR)
dhcpv4_options = self._get_port_dhcp_options(port, const.IP_VERSION_4)
dhcpv6_options = self._get_port_dhcp_options(port, const.IP_VERSION_6)
# HA Chassis Group will bind the port to the highest
# priority Chassis
if port_type != ovn_const.LSP_TYPE_EXTERNAL:
options.update({'requested-chassis':
port.get(portbindings.HOST_ID, '')})
device_owner = port.get('device_owner', '')
sg_ids = ' '.join(utils.get_lsp_security_groups(port))
return OvnPortInfo(port_type, options, addresses, port_security,
parent_name, tag, dhcpv4_options, dhcpv6_options,
cidrs.strip(), device_owner, sg_ids)
def _get_default_ha_chassis_group(self):
return self._nb_idl.ha_chassis_group_get(
ovn_const.HA_CHASSIS_GROUP_DEFAULT_NAME).execute(
check_error=True).uuid
def create_port(self, context, port):
if utils.is_lsp_ignored(port):
return
port_info = self._get_port_options(port)
external_ids = {ovn_const.OVN_PORT_NAME_EXT_ID_KEY: port['name'],
ovn_const.OVN_DEVID_EXT_ID_KEY: port['device_id'],
ovn_const.OVN_PROJID_EXT_ID_KEY: port['project_id'],
ovn_const.OVN_CIDRS_EXT_ID_KEY: port_info.cidrs,
ovn_const.OVN_DEVICE_OWNER_EXT_ID_KEY:
port_info.device_owner,
ovn_const.OVN_NETWORK_NAME_EXT_ID_KEY:
utils.ovn_name(port['network_id']),
ovn_const.OVN_SG_IDS_EXT_ID_KEY:
port_info.security_group_ids,
ovn_const.OVN_REV_NUM_EXT_ID_KEY: str(
utils.get_revision_number(
port, ovn_const.TYPE_PORTS))}
lswitch_name = utils.ovn_name(port['network_id'])
# It's possible to have a network created on one controller and then a
# port created on a different controller quickly enough that the second
# controller does not yet see that network in its local cache of the
# OVN northbound database. Check if the logical switch is present
# or not in the idl's local copy of the database before creating
# the lswitch port.
self._nb_idl.check_for_row_by_value_and_retry(
'Logical_Switch', 'name', lswitch_name)
with self._nb_idl.transaction(check_error=True) as txn:
if not port_info.dhcpv4_options:
dhcpv4_options = []
elif 'cmd' in port_info.dhcpv4_options:
dhcpv4_options = txn.add(port_info.dhcpv4_options['cmd'])
else:
dhcpv4_options = [port_info.dhcpv4_options['uuid']]
if not port_info.dhcpv6_options:
dhcpv6_options = []
elif 'cmd' in port_info.dhcpv6_options:
dhcpv6_options = txn.add(port_info.dhcpv6_options['cmd'])
else:
dhcpv6_options = [port_info.dhcpv6_options['uuid']]
# The lport_name *must* be neutron port['id']. It must match the
# iface-id set in the Interfaces table of the Open_vSwitch
# database which nova sets to be the port ID.
kwargs = {
| |
<filename>optical_rl_gym/envs/rmcsa_env.py
import gym
import copy
import math
import heapq
import logging
import functools
import numpy as np
from collections import defaultdict
from optical_rl_gym.utils import Service, Path
from .optical_network_env import OpticalNetworkEnv
class RMCSAEnv(OpticalNetworkEnv):
metadata = {
'metrics': ['service_blocking_rate', 'episode_service_blocking_rate',
'bit_rate_blocking_rate', 'episode_bit_rate_blocking_rate']
}
def __init__(self, topology=None,
episode_length=1000,
load=10,
mean_service_holding_time=10800.0,
num_spectrum_resources=100,
num_spatial_resources=3, # number of cores - 3, 7, 11, 22
node_request_probabilities=None,
bit_rate_lower_bound=25,
bit_rate_higher_bound=100,
seed=None,
k_paths=5,
allow_rejection=False,
reset=True):
super().__init__(topology,
episode_length=episode_length,
load=load,
mean_service_holding_time=mean_service_holding_time,
num_spectrum_resources=num_spectrum_resources,
node_request_probabilities=node_request_probabilities,
seed=seed, allow_rejection=allow_rejection,
k_paths=k_paths)
assert 'modulations' in self.topology.graph
# specific attributes for elastic optical networks
self.bit_rate_requested = 0
self.bit_rate_provisioned = 0
self.episode_bit_rate_requested = 0
self.episode_bit_rate_provisioned = 0
self.utilization = []
self.core_utilization = defaultdict(list)
self.bit_rate_lower_bound = bit_rate_lower_bound
self.bit_rate_higher_bound = bit_rate_higher_bound
self.num_spatial_resources = num_spatial_resources # number of cores
self.spectrum_slots_allocation = np.full((self.num_spatial_resources, self.topology.number_of_edges(),
self.num_spectrum_resources),
fill_value=-1, dtype=np.int)
# do we allow proactive rejection or not?
self.reject_action = 1 if allow_rejection else 0
# defining the observation and action spaces
self.actions_output = np.zeros((self.num_spatial_resources + 1,
self.k_paths + 1,
self.num_spectrum_resources + 1),
dtype=int)
self.episode_actions_output = np.zeros((self.num_spatial_resources + 1,
self.k_paths + 1,
self.num_spectrum_resources + 1),
dtype=int)
self.actions_taken = np.zeros((self.num_spatial_resources + 1,
self.k_paths + 1,
self.num_spectrum_resources + 1),
dtype=int)
self.episode_actions_taken = np.zeros((self.num_spatial_resources + 1,
self.k_paths + 1,
self.num_spectrum_resources + 1),
dtype=int)
self.action_space = gym.spaces.MultiDiscrete((self.num_spatial_resources + self.reject_action,
self.k_paths + self.reject_action,
self.num_spectrum_resources + self.reject_action))
self.observation_space = gym.spaces.Dict(
{'topology': gym.spaces.Discrete(10),
'current_service': gym.spaces.Discrete(10)}
)
self.action_space.seed(self.rand_seed)
self.observation_space.seed(self.rand_seed)
self.logger = logging.getLogger('rmcsaenv')
if self.logger.isEnabledFor(logging.DEBUG):
self.logger.warning(
'Logging is enabled for DEBUG which generates a large number of messages. '
'Set it to INFO if DEBUG is not necessary.')
self._new_service = False
if reset:
self.reset(only_counters=False)
def step(self, action: [int]):
core, path, initial_slot = action[0], action[1], action[2]
self.actions_output[core, path, initial_slot] += 1
if core < self.num_spatial_resources and path < self.k_paths and initial_slot < self.num_spectrum_resources:
slots = self.get_number_slots(self.k_shortest_paths[self.service.source, self.service.destination][path])
self.logger.debug('{} processing action {} path {} and initial slot {} for {} slots'.format(self.service.service_id, action, path, initial_slot, slots))
if self.is_path_free(core, self.k_shortest_paths[self.service.source, self.service.destination][path],
initial_slot, slots):
self._provision_path(core, self.k_shortest_paths[self.service.source, self.service.destination][path],
initial_slot, slots)
self.service.accepted = True
self.actions_taken[core, path, initial_slot] += 1
self._add_release(self.service)
else:
self.service.accepted = False
else:
self.service.accepted = False
if not self.service.accepted:
self.actions_taken[self.num_spatial_resources, self.k_paths, self.num_spectrum_resources] += 1
self.services_processed += 1
self.episode_services_processed += 1
self.bit_rate_requested += self.service.bit_rate
self.episode_bit_rate_requested += self.service.bit_rate
self.topology.graph['services'].append(self.service)
reward = self.reward()
info = {
'service_blocking_rate': (self.services_processed - self.services_accepted) / self.services_processed,
'episode_service_blocking_rate': (self.episode_services_processed - self.episode_services_accepted) / self.episode_services_processed,
'bit_rate_blocking_rate': (self.bit_rate_requested - self.bit_rate_provisioned) / self.bit_rate_requested,
'episode_bit_rate_blocking_rate': (self.episode_bit_rate_requested - self.episode_bit_rate_provisioned) / self.episode_bit_rate_requested
}
self._new_service = False
self._next_service()
return self.observation(), reward, self.episode_services_processed == self.episode_length, info
def reset(self, only_counters=True):
self.episode_bit_rate_requested = 0
self.episode_bit_rate_provisioned = 0
self.episode_services_processed = 0
self.episode_services_accepted = 0
self.episode_actions_output = np.zeros((self.k_paths + self.reject_action,
self.num_spectrum_resources + self.reject_action),
dtype=int)
self.episode_actions_taken = np.zeros((self.k_paths + self.reject_action,
self.num_spectrum_resources + self.reject_action),
dtype=int)
if only_counters:
return self.observation()
super().reset()
self.bit_rate_requested = 0
self.bit_rate_provisioned = 0
self.topology.graph["available_slots"] = np.ones((self.num_spatial_resources, self.topology.number_of_edges(),
self.num_spectrum_resources), dtype=int)
self.spectrum_slots_allocation = np.full((self.num_spatial_resources, self.topology.number_of_edges(),
self.num_spectrum_resources),
fill_value=-1, dtype=np.int)
self.topology.graph["compactness"] = 0.
self.topology.graph["throughput"] = 0.
for idx, lnk in enumerate(self.topology.edges()):
self.topology[lnk[0]][lnk[1]]['external_fragmentation'] = 0.
self.topology[lnk[0]][lnk[1]]['compactness'] = 0.
self._new_service = False
self._next_service()
return self.observation()
def render(self, mode='human'):
return
def _provision_path(self, core: int, path: Path, initial_slot, number_slots):
if not self.is_path_free(core, path, initial_slot, number_slots):
raise ValueError("Path {} has not enough capacity on slots {}-{}".format(path.node_list, path, initial_slot,
initial_slot + number_slots))
self.logger.debug('{} assigning path {} on initial slot {} for {} slots'.format(self.service.service_id, path.node_list, initial_slot, number_slots))
for i in range(len(path.node_list) - 1):
self.topology.graph['available_slots'][core, self.topology[path.node_list[i]][path.node_list[i + 1]]['index'],
initial_slot:initial_slot + number_slots] = 0
self.spectrum_slots_allocation[core, self.topology[path.node_list[i]][path.node_list[i + 1]]['index'],
initial_slot:initial_slot + number_slots] = self.service.service_id
self.topology[path.node_list[i]][path.node_list[i + 1]]['services'].append(self.service)
self.topology[path.node_list[i]][path.node_list[i + 1]]['running_services'].append(self.service)
self._update_link_stats(core, path.node_list[i], path.node_list[i + 1])
self.topology.graph['running_services'].append(self.service)
self.service.route = path
self.service.initial_slot = initial_slot
self.service.number_slots = number_slots
self.service.core = core
self._update_network_stats(core)
self.services_accepted += 1
self.episode_services_accepted += 1
self.bit_rate_provisioned += self.service.bit_rate
self.episode_bit_rate_provisioned += self.service.bit_rate
def _release_path(self, service: Service):
for i in range(len(service.route.node_list) - 1):
self.topology.graph['available_slots'][service.core,
self.topology[service.route.node_list[i]][service.route.node_list[i + 1]]['index'],
service.initial_slot:service.initial_slot + service.number_slots] = 1
self.spectrum_slots_allocation[service.core,
self.topology[service.route.node_list[i]][service.route.node_list[i + 1]]['index'],
service.initial_slot:service.initial_slot + service.number_slots] = -1
self.topology[service.route.node_list[i]][service.route.node_list[i + 1]]['running_services'].remove(service)
self._update_link_stats(service.core, service.route.node_list[i], service.route.node_list[i + 1])
self.topology.graph['running_services'].remove(service)
def _update_network_stats(self, core: int):
"""
Update network stats is used to create metrics for "throughput" & "compactness".
:param core: number of cores
"""
last_update = self.topology.graph['last_update']
time_diff = self.current_time - last_update
if self.current_time > 0:
last_throughput = self.topology.graph['throughput']
last_compactness = self.topology.graph['compactness']
cur_throughput = 0.
for service in self.topology.graph["running_services"]:
cur_throughput += service.bit_rate
throughput = ((last_throughput * last_update) + (cur_throughput * time_diff)) / self.current_time
self.topology.graph['throughput'] = throughput
compactness = ((last_compactness * last_update) + (self._get_network_compactness(core) * time_diff)) / \
self.current_time
self.topology.graph['compactness'] = compactness
self.topology.graph['last_update'] = self.current_time
def _update_link_stats(self, core: int, node1: str, node2: str):
""" Creates metrics for:
Individual node "utilization", overall "core_utilization", "external fragmentation", and "link_compactness".
:param core : number of cores,
:param node1: number of node1 within the node_list
:param node2: number of node2 within the node_list
"""
last_update = self.topology[node1][node2]['last_update']
time_diff = self.current_time - self.topology[node1][node2]['last_update']
if self.current_time > 0:
last_util = self.topology[node1][node2]['utilization']
cur_util = (self.num_spectrum_resources - np.sum(
self.topology.graph['available_slots'][core, self.topology[node1][node2]['index'], :])) / \
self.num_spectrum_resources
utilization = ((last_util * last_update) + (cur_util * time_diff)) / self.current_time
self.topology[node1][node2]['utilization'] = utilization
# Adds each node utilization value to an array
self.utilization.append(utilization)
# Adds each node utilization value to the core key within a dictionary
self.core_utilization[core].append(utilization)
slot_allocation = self.topology.graph['available_slots'][core, self.topology[node1][node2]['index'], :]
# implementing fragmentation from https://ieeexplore.ieee.org/abstract/document/6421472
last_external_fragmentation = self.topology[node1][node2]['external_fragmentation']
last_compactness = self.topology[node1][node2]['compactness']
cur_external_fragmentation = 0.
cur_link_compactness = 0.
if np.sum(slot_allocation) > 0:
initial_indices, values, lengths = RMCSAEnv.rle(slot_allocation)
# computing external fragmentation from https://ieeexplore.ieee.org/abstract/document/6421472
unused_blocks = [i for i, x in enumerate(values) if x == 1]
max_empty = 0
if len(unused_blocks) > 1 and unused_blocks != [0, len(values) - 1]:
max_empty = max(lengths[unused_blocks])
cur_external_fragmentation = 1. - (float(max_empty) / float(np.sum(slot_allocation)))
# computing link spectrum compactness from https://ieeexplore.ieee.org/abstract/document/6421472
used_blocks = [i for i, x in enumerate(values) if x == 0]
if len(used_blocks) > 1:
lambda_min = initial_indices[used_blocks[0]]
lambda_max = initial_indices[used_blocks[-1]] + lengths[used_blocks[-1]]
# evaluate again only the "used part" of the spectrum
internal_idx, internal_values, internal_lengths = RMCSAEnv.rle(
slot_allocation[lambda_min:lambda_max])
unused_spectrum_slots = np.sum(1 - internal_values)
if unused_spectrum_slots > 0:
cur_link_compactness = ((lambda_max - lambda_min) / np.sum(1 - slot_allocation)) * (
1 / unused_spectrum_slots)
else:
cur_link_compactness = 1.
else:
cur_link_compactness = 1.
external_fragmentation = ((last_external_fragmentation * last_update) + (cur_external_fragmentation * time_diff)) / self.current_time
self.topology[node1][node2]['external_fragmentation'] = external_fragmentation
link_compactness = ((last_compactness * last_update) + (cur_link_compactness * time_diff)) / self.current_time
self.topology[node1][node2]['compactness'] = link_compactness
self.topology[node1][node2]['last_update'] = self.current_time
def _next_service(self):
if self._new_service:
return
at = self.current_time + self.rng.expovariate(1 / self.mean_service_inter_arrival_time)
self.current_time = at
ht = self.rng.expovariate(1 / self.mean_service_holding_time)
src, src_id, dst, dst_id = self._get_node_pair()
bit_rate = self.rng.randint(self.bit_rate_lower_bound, self.bit_rate_higher_bound)
# release connections up to this point
while len(self._events) > 0:
(time, service_to_release) = heapq.heappop(self._events)
if time <= self.current_time:
self._release_path(service_to_release)
else: # release is not to be processed yet
self._add_release(service_to_release) # puts service back in the queue
break # breaks the loop
self.service = Service(self.episode_services_processed, src, src_id,
destination=dst, destination_id=dst_id,
arrival_time=at, holding_time=ht, bit_rate=bit_rate)
self._new_service = True
def _get_path_slot_id(self, action: int) -> (int, int):
"""
Decodes the single action index into the path index and the slot index to be used.
:param action: the single action index
:return: path index and initial slot index encoded in the action
"""
path = int(action / self.num_spectrum_resources)
initial_slot = action % self.num_spectrum_resources
return path, initial_slot
def get_number_slots(self, path: Path) -> int:
"""
Method that computes the number of spectrum slots necessary to accommodate the service request into the path.
The method already adds the guardband.
"""
return math.ceil(self.service.bit_rate / path.best_modulation['capacity']) + 1
def is_path_free(self, core: int, path: Path, initial_slot: int, number_slots: int) -> bool:
"""
Method that determines if the path is free for the core, path, and initial_slot.
:param core: Number of cores currently being used
:param path: Index of K shortest paths
:param initial_slot: The current frequency slot being used <-carlos pls double check
:param number_slots: The total number of slots
:return: True/False
:rtype: bool
"""
if initial_slot + number_slots > self.num_spectrum_resources:
# logging.debug('error index' + env.parameters.rsa_algorithm)
return False
for i in range(len(path.node_list) - 1):
if np.any(self.topology.graph['available_slots'][
core,
self.topology[path.node_list[i]][path.node_list[i + 1]]['index'],
initial_slot:initial_slot + number_slots] == 0):
return False
return True
def get_available_slots(self, path: Path):
available_slots = functools.reduce(np.multiply,
self.topology.graph["available_slots"][[self.topology[path.node_list[i]][path.node_list[i + 1]]['id']
for i in range(len(path.node_list) - 1)], :])
return available_slots
def rle(inarray):
""" run length encoding. Partial credit to | |
values are environment variable values for those names.
serving_container_ports: Optional[Sequence[int]]=None,
Declaration of ports that are exposed by the container. This field is
primarily informational, it gives Vertex AI information about the
network connections the container uses. Listing or not a port here has
no impact on whether the port is actually exposed, any port listening on
the default "0.0.0.0" address inside a container will be accessible from
the network.
instance_schema_uri (str):
Optional. Points to a YAML file stored on Google Cloud
Storage describing the format of a single instance, which
are used in
``PredictRequest.instances``,
``ExplainRequest.instances``
and
``BatchPredictionJob.input_config``.
The schema is defined as an OpenAPI 3.0.2 `Schema
Object <https://tinyurl.com/y538mdwt#schema-object>`__.
AutoML Models always have this field populated by AI
Platform. Note: The URI given on output will be immutable
and probably different, including the URI scheme, than the
one given on input. The output URI will point to a location
where the user only has a read access.
parameters_schema_uri (str):
Optional. Points to a YAML file stored on Google Cloud
Storage describing the parameters of prediction and
explanation via
``PredictRequest.parameters``,
``ExplainRequest.parameters``
and
``BatchPredictionJob.model_parameters``.
The schema is defined as an OpenAPI 3.0.2 `Schema
Object <https://tinyurl.com/y538mdwt#schema-object>`__.
AutoML Models always have this field populated by AI
Platform, if no parameters are supported it is set to an
empty string. Note: The URI given on output will be
immutable and probably different, including the URI scheme,
than the one given on input. The output URI will point to a
location where the user only has a read access.
prediction_schema_uri (str):
Optional. Points to a YAML file stored on Google Cloud
Storage describing the format of a single prediction
produced by this Model, which are returned via
``PredictResponse.predictions``,
``ExplainResponse.explanations``,
and
``BatchPredictionJob.output_config``.
The schema is defined as an OpenAPI 3.0.2 `Schema
Object <https://tinyurl.com/y538mdwt#schema-object>`__.
AutoML Models always have this field populated by AI
Platform. Note: The URI given on output will be immutable
and probably different, including the URI scheme, than the
one given on input. The output URI will point to a location
where the user only has a read access.
explanation_metadata (explain.ExplanationMetadata):
Optional. Metadata describing the Model's input and output for explanation.
Both `explanation_metadata` and `explanation_parameters` must be
passed together when used. For more details, see
`Ref docs <http://tinyurl.com/1igh60kt>`
explanation_parameters (explain.ExplanationParameters):
Optional. Parameters to configure explaining for Model's predictions.
For more details, see `Ref docs <http://tinyurl.com/1an4zake>`
project: Optional[str]=None,
Project to upload this model to. Overrides project set in
aiplatform.init.
location: Optional[str]=None,
Location to upload this model to. Overrides location set in
aiplatform.init.
credentials: Optional[auth_credentials.Credentials]=None,
Custom credentials to use to upload this model. Overrides credentials
set in aiplatform.init.
labels (Dict[str, str]):
Optional. The labels with user-defined metadata to
organize your Models.
Label keys and values can be no longer than 64
characters (Unicode codepoints), can only
contain lowercase letters, numeric characters,
underscores and dashes. International characters
are allowed.
See https://goo.gl/xmQnxf for more information
and examples of labels.
encryption_spec_key_name (Optional[str]):
Optional. The Cloud KMS resource identifier of the customer
managed encryption key used to protect the model. Has the
form:
``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``.
The key needs to be in the same region as where the compute
resource is created.
If set, this Model and all sub-resources of this Model will be secured by this key.
Overrides encryption_spec_key_name set in aiplatform.init.
staging_bucket (str):
Optional. Bucket to stage local model artifacts. Overrides
staging_bucket set in aiplatform.init.
Returns:
model: Instantiated representation of the uploaded model resource.
Raises:
ValueError: If only `explanation_metadata` or `explanation_parameters`
is specified.
Also if model directory does not contain a supported model file.
"""
utils.validate_display_name(display_name)
if labels:
utils.validate_labels(labels)
if bool(explanation_metadata) != bool(explanation_parameters):
raise ValueError(
"Both `explanation_metadata` and `explanation_parameters` should be specified or None."
)
api_client = cls._instantiate_client(location, credentials)
env = None
ports = None
if serving_container_environment_variables:
env = [
gca_env_var_compat.EnvVar(name=str(key), value=str(value))
for key, value in serving_container_environment_variables.items()
]
if serving_container_ports:
ports = [
gca_model_compat.Port(container_port=port)
for port in serving_container_ports
]
container_spec = gca_model_compat.ModelContainerSpec(
image_uri=serving_container_image_uri,
command=serving_container_command,
args=serving_container_args,
env=env,
ports=ports,
predict_route=serving_container_predict_route,
health_route=serving_container_health_route,
)
model_predict_schemata = None
if any([instance_schema_uri, parameters_schema_uri, prediction_schema_uri]):
model_predict_schemata = gca_model_compat.PredictSchemata(
instance_schema_uri=instance_schema_uri,
parameters_schema_uri=parameters_schema_uri,
prediction_schema_uri=prediction_schema_uri,
)
# TODO(b/182388545) initializer.global_config.get_encryption_spec from a sync function
encryption_spec = initializer.global_config.get_encryption_spec(
encryption_spec_key_name=encryption_spec_key_name,
)
managed_model = gca_model_compat.Model(
display_name=display_name,
description=description,
container_spec=container_spec,
predict_schemata=model_predict_schemata,
labels=labels,
encryption_spec=encryption_spec,
)
if artifact_uri and not artifact_uri.startswith("gs://"):
model_dir = pathlib.Path(artifact_uri)
# Validating the model directory
if not model_dir.exists():
raise ValueError(f"artifact_uri path does not exist: '{artifact_uri}'")
PREBUILT_IMAGE_RE = "(us|europe|asia)-docker.pkg.dev/vertex-ai/prediction/"
if re.match(PREBUILT_IMAGE_RE, serving_container_image_uri):
if not model_dir.is_dir():
raise ValueError(
f"artifact_uri path must be a directory: '{artifact_uri}' when using prebuilt image '{serving_container_image_uri}'"
)
if not any(
(model_dir / file_name).exists()
for file_name in _SUPPORTED_MODEL_FILE_NAMES
):
raise ValueError(
"artifact_uri directory does not contain any supported model files. "
f"When using a prebuilt serving image, the upload method only supports the following model files: '{_SUPPORTED_MODEL_FILE_NAMES}'"
)
# Uploading the model
staged_data_uri = gcs_utils.stage_local_data_in_gcs(
data_path=str(model_dir),
staging_gcs_dir=staging_bucket,
project=project,
location=location,
credentials=credentials,
)
artifact_uri = staged_data_uri
if artifact_uri:
managed_model.artifact_uri = artifact_uri
# Override explanation_spec if both required fields are provided
if explanation_metadata and explanation_parameters:
explanation_spec = gca_endpoint_compat.explanation.ExplanationSpec()
explanation_spec.metadata = explanation_metadata
explanation_spec.parameters = explanation_parameters
managed_model.explanation_spec = explanation_spec
lro = api_client.upload_model(
parent=initializer.global_config.common_location_path(project, location),
model=managed_model,
)
_LOGGER.log_create_with_lro(cls, lro)
model_upload_response = lro.result()
this_model = cls(model_upload_response.model)
_LOGGER.log_create_complete(cls, this_model._gca_resource, "model")
return this_model
# TODO(b/172502059) support deploying with endpoint resource name
def deploy(
self,
endpoint: Optional["Endpoint"] = None,
deployed_model_display_name: Optional[str] = None,
traffic_percentage: Optional[int] = 0,
traffic_split: Optional[Dict[str, int]] = None,
machine_type: Optional[str] = None,
min_replica_count: int = 1,
max_replica_count: int = 1,
accelerator_type: Optional[str] = None,
accelerator_count: Optional[int] = None,
service_account: Optional[str] = None,
explanation_metadata: Optional[explain.ExplanationMetadata] = None,
explanation_parameters: Optional[explain.ExplanationParameters] = None,
metadata: Optional[Sequence[Tuple[str, str]]] = (),
encryption_spec_key_name: Optional[str] = None,
sync=True,
) -> Endpoint:
"""Deploys model to endpoint. Endpoint will be created if unspecified.
Args:
endpoint ("Endpoint"):
Optional. Endpoint to deploy model to. If not specified, endpoint
display name will be model display name+'_endpoint'.
deployed_model_display_name (str):
Optional. The display name of the DeployedModel. If not provided
upon creation, the Model's display_name is used.
traffic_percentage (int):
Optional. Desired traffic to newly deployed model. Defaults to
0 if there are pre-existing deployed models. Defaults to 100 if
there are no pre-existing deployed models. Negative values should
not be provided. Traffic of previously deployed models at the endpoint
will be scaled down to accommodate new deployed model's traffic.
Should not be provided if traffic_split is provided.
traffic_split (Dict[str, int]):
Optional. A map from a DeployedModel's ID to the percentage of
this Endpoint's traffic that should be forwarded to that DeployedModel.
If a DeployedModel's ID is not listed in this map, then it receives
no traffic. The traffic percentage values must add up to 100, or
map must be empty if the Endpoint is to not accept any traffic at
the moment. Key for model being deployed is "0". Should not be
provided if traffic_percentage is provided.
machine_type (str):
Optional. The type of machine. Not specifying machine type will
result in model to be deployed with automatic resources.
min_replica_count (int):
Optional. The minimum number of machine replicas this deployed
model will be always deployed on. If traffic against it increases,
it may dynamically be deployed onto more replicas, and as traffic
decreases, some of these extra replicas may be freed.
max_replica_count (int):
Optional. The maximum number of replicas this deployed model may
be deployed on when the traffic against it increases. If requested
value is too large, the deployment will error, but if deployment
succeeds then the ability to scale the model to that many replicas
is guaranteed (barring service outages). If traffic against the
deployed model increases beyond what its replicas at maximum may
handle, a portion of the traffic will be dropped. If this value
is not provided, the smaller value of min_replica_count or 1 will
be used.
accelerator_type (str):
Optional. Hardware accelerator type. Must also set accelerator_count if used.
One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100,
NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4
accelerator_count (int):
Optional. The number of accelerators to | |
<reponame>pulumi/pulumi-kubernetes-crds<gh_stars>0
# coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'NexusSpec',
'NexusSpecAutomaticUpdate',
'NexusSpecLivenessProbe',
'NexusSpecNetworking',
'NexusSpecNetworkingTls',
'NexusSpecPersistence',
'NexusSpecReadinessProbe',
'NexusSpecResources',
'NexusSpecResourcesLimits',
'NexusSpecResourcesRequests',
'NexusSpecServerOperations',
'NexusStatus',
'NexusStatusDeploymentStatus',
'NexusStatusDeploymentStatusConditions',
'NexusStatusServerOperationsStatus',
]
@pulumi.output_type
class NexusSpec(dict):
"""
NexusSpec defines the desired state of Nexus
"""
def __init__(__self__, *,
persistence: 'outputs.NexusSpecPersistence',
replicas: int,
use_red_hat_image: bool,
automatic_update: Optional['outputs.NexusSpecAutomaticUpdate'] = None,
generate_random_admin_password: Optional[bool] = None,
image: Optional[str] = None,
image_pull_policy: Optional[str] = None,
liveness_probe: Optional['outputs.NexusSpecLivenessProbe'] = None,
networking: Optional['outputs.NexusSpecNetworking'] = None,
readiness_probe: Optional['outputs.NexusSpecReadinessProbe'] = None,
resources: Optional['outputs.NexusSpecResources'] = None,
server_operations: Optional['outputs.NexusSpecServerOperations'] = None,
service_account_name: Optional[str] = None):
"""
NexusSpec defines the desired state of Nexus
:param 'NexusSpecPersistenceArgs' persistence: Persistence definition
:param int replicas: Number of pod replicas desired. Defaults to 0.
:param bool use_red_hat_image: If you have access to Red Hat Container Catalog, set this to `true` to use the certified image provided by Sonatype Defaults to `false`
:param 'NexusSpecAutomaticUpdateArgs' automatic_update: Automatic updates configuration
:param bool generate_random_admin_password: GenerateRandomAdminPassword enables the random password generation. Defaults to `false`: the default password for a newly created instance is '<PASSWORD>', which should be changed in the first login. If set to `true`, you must use the automatically generated 'admin' password, stored in the container's file system at `/nexus-data/admin.password`. The operator uses the default credentials to create a user for itself to create default repositories. If set to `true`, the repositories won't be created since the operator won't fetch for the random password.
:param str image: Full image tag name for this specific deployment. Will be ignored if `spec.useRedHatImage` is set to `true`. Default: docker.io/sonatype/nexus3:latest
:param str image_pull_policy: The image pull policy for the Nexus image. If left blank behavior will be determined by the image tag (`Always` if "latest" and `IfNotPresent` otherwise). Possible values: `Always`, `IfNotPresent` or `Never`.
:param 'NexusSpecLivenessProbeArgs' liveness_probe: LivenessProbe describes how the Nexus container liveness probe should work
:param 'NexusSpecNetworkingArgs' networking: Networking definition
:param 'NexusSpecReadinessProbeArgs' readiness_probe: ReadinessProbe describes how the Nexus container readiness probe should work
:param 'NexusSpecResourcesArgs' resources: Defined Resources for the Nexus instance
:param 'NexusSpecServerOperationsArgs' server_operations: ServerOperations describes the options for the operations performed on the deployed server instance
:param str service_account_name: ServiceAccountName is the name of the ServiceAccount used to run the Pods. If left blank, a default ServiceAccount is created with the same name as the Nexus CR (`metadata.name`).
"""
pulumi.set(__self__, "persistence", persistence)
pulumi.set(__self__, "replicas", replicas)
pulumi.set(__self__, "use_red_hat_image", use_red_hat_image)
if automatic_update is not None:
pulumi.set(__self__, "automatic_update", automatic_update)
if generate_random_admin_password is not None:
pulumi.set(__self__, "generate_random_admin_password", generate_random_admin_password)
if image is not None:
pulumi.set(__self__, "image", image)
if image_pull_policy is not None:
pulumi.set(__self__, "image_pull_policy", image_pull_policy)
if liveness_probe is not None:
pulumi.set(__self__, "liveness_probe", liveness_probe)
if networking is not None:
pulumi.set(__self__, "networking", networking)
if readiness_probe is not None:
pulumi.set(__self__, "readiness_probe", readiness_probe)
if resources is not None:
pulumi.set(__self__, "resources", resources)
if server_operations is not None:
pulumi.set(__self__, "server_operations", server_operations)
if service_account_name is not None:
pulumi.set(__self__, "service_account_name", service_account_name)
@property
@pulumi.getter
def persistence(self) -> 'outputs.NexusSpecPersistence':
"""
Persistence definition
"""
return pulumi.get(self, "persistence")
@property
@pulumi.getter
def replicas(self) -> int:
"""
Number of pod replicas desired. Defaults to 0.
"""
return pulumi.get(self, "replicas")
@property
@pulumi.getter(name="useRedHatImage")
def use_red_hat_image(self) -> bool:
"""
If you have access to Red Hat Container Catalog, set this to `true` to use the certified image provided by Sonatype Defaults to `false`
"""
return pulumi.get(self, "use_red_hat_image")
@property
@pulumi.getter(name="automaticUpdate")
def automatic_update(self) -> Optional['outputs.NexusSpecAutomaticUpdate']:
"""
Automatic updates configuration
"""
return pulumi.get(self, "automatic_update")
@property
@pulumi.getter(name="generateRandomAdminPassword")
def generate_random_admin_password(self) -> Optional[bool]:
"""
GenerateRandomAdminPassword enables the random password generation. Defaults to `false`: the default password for a newly created instance is '<PASSWORD>', which should be changed in the first login. If set to `true`, you must use the automatically generated 'admin' password, stored in the container's file system at `/nexus-data/admin.password`. The operator uses the default credentials to create a user for itself to create default repositories. If set to `true`, the repositories won't be created since the operator won't fetch for the random password.
"""
return pulumi.get(self, "generate_random_admin_password")
@property
@pulumi.getter
def image(self) -> Optional[str]:
"""
Full image tag name for this specific deployment. Will be ignored if `spec.useRedHatImage` is set to `true`. Default: docker.io/sonatype/nexus3:latest
"""
return pulumi.get(self, "image")
@property
@pulumi.getter(name="imagePullPolicy")
def image_pull_policy(self) -> Optional[str]:
"""
The image pull policy for the Nexus image. If left blank behavior will be determined by the image tag (`Always` if "latest" and `IfNotPresent` otherwise). Possible values: `Always`, `IfNotPresent` or `Never`.
"""
return pulumi.get(self, "image_pull_policy")
@property
@pulumi.getter(name="livenessProbe")
def liveness_probe(self) -> Optional['outputs.NexusSpecLivenessProbe']:
"""
LivenessProbe describes how the Nexus container liveness probe should work
"""
return pulumi.get(self, "liveness_probe")
@property
@pulumi.getter
def networking(self) -> Optional['outputs.NexusSpecNetworking']:
"""
Networking definition
"""
return pulumi.get(self, "networking")
@property
@pulumi.getter(name="readinessProbe")
def readiness_probe(self) -> Optional['outputs.NexusSpecReadinessProbe']:
"""
ReadinessProbe describes how the Nexus container readiness probe should work
"""
return pulumi.get(self, "readiness_probe")
@property
@pulumi.getter
def resources(self) -> Optional['outputs.NexusSpecResources']:
"""
Defined Resources for the Nexus instance
"""
return pulumi.get(self, "resources")
@property
@pulumi.getter(name="serverOperations")
def server_operations(self) -> Optional['outputs.NexusSpecServerOperations']:
"""
ServerOperations describes the options for the operations performed on the deployed server instance
"""
return pulumi.get(self, "server_operations")
@property
@pulumi.getter(name="serviceAccountName")
def service_account_name(self) -> Optional[str]:
"""
ServiceAccountName is the name of the ServiceAccount used to run the Pods. If left blank, a default ServiceAccount is created with the same name as the Nexus CR (`metadata.name`).
"""
return pulumi.get(self, "service_account_name")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class NexusSpecAutomaticUpdate(dict):
"""
Automatic updates configuration
"""
def __init__(__self__, *,
disabled: Optional[bool] = None,
minor_version: Optional[int] = None):
"""
Automatic updates configuration
:param bool disabled: Whether or not the Operator should perform automatic updates. Defaults to `false` (auto updates are enabled). Is set to `false` if `spec.image` is not empty and is different from the default community image.
:param int minor_version: The Nexus image minor version the deployment should stay in. If left blank and automatic updates are enabled the latest minor is set.
"""
if disabled is not None:
pulumi.set(__self__, "disabled", disabled)
if minor_version is not None:
pulumi.set(__self__, "minor_version", minor_version)
@property
@pulumi.getter
def disabled(self) -> Optional[bool]:
"""
Whether or not the Operator should perform automatic updates. Defaults to `false` (auto updates are enabled). Is set to `false` if `spec.image` is not empty and is different from the default community image.
"""
return pulumi.get(self, "disabled")
@property
@pulumi.getter(name="minorVersion")
def minor_version(self) -> Optional[int]:
"""
The Nexus image minor version the deployment should stay in. If left blank and automatic updates are enabled the latest minor is set.
"""
return pulumi.get(self, "minor_version")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class NexusSpecLivenessProbe(dict):
"""
LivenessProbe describes how the Nexus container liveness probe should work
"""
def __init__(__self__, *,
failure_threshold: Optional[int] = None,
initial_delay_seconds: Optional[int] = None,
period_seconds: Optional[int] = None,
success_threshold: Optional[int] = None,
timeout_seconds: Optional[int] = None):
"""
LivenessProbe describes how the Nexus container liveness probe should work
:param int failure_threshold: Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.
:param int initial_delay_seconds: Number of seconds after the container has started before probes are initiated. Defaults to 240 seconds. Minimum value is 0.
:param int period_seconds: How often (in seconds) to perform the probe. Defaults to 10 seconds. Minimum value is 1.
:param int success_threshold: Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness and startup. Minimum value is 1.
:param int timeout_seconds: Number of seconds after which the probe times out. Defaults to 15 seconds. Minimum value is 1.
"""
if failure_threshold is not None:
pulumi.set(__self__, "failure_threshold", failure_threshold)
if initial_delay_seconds is not None:
pulumi.set(__self__, "initial_delay_seconds", initial_delay_seconds)
if period_seconds is not None:
pulumi.set(__self__, "period_seconds", period_seconds)
if success_threshold is not None:
pulumi.set(__self__, "success_threshold", success_threshold)
if timeout_seconds is not None:
pulumi.set(__self__, "timeout_seconds", timeout_seconds)
@property
@pulumi.getter(name="failureThreshold")
def failure_threshold(self) -> Optional[int]:
"""
Minimum consecutive | |
import pandas as pd
from pandas import DatetimeIndex
from pandas.plotting import table
import datetime
from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as pltimport
import seaborn as sb
sb.set()
import os
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
from alpha_vantage.timeseries import TimeSeries
import pickle
from joblib import dump, load
import time
import six
def get_raw(sym='V'):
'''
download data and return data dictionary
'''
# download historical prices
ts = TimeSeries(key='enter your access key')
# Get json object with the intraday data and another with the call's metadata
data, meta_data = ts.get_daily_adjusted(sym, outputsize='compact')
return data
def format_raw(raw_dict):
'''
import raw dictionary
format column names and sort date ascending
return dataframe
'''
# reformat
data = raw_dict.copy()
df_raw = pd.DataFrame.from_dict(data).T
df_raw.reset_index(level=0, inplace=True)
df_raw = df_raw.rename(index=str, columns={'index':'date',
'1. open': 'open',
'2. high': 'high',
'3. low': 'low',
'4. close':'close',
'5. adjusted close':'adj_close',
'6. volume':'volume',
'7. dividend amount':'dividend',
'8. split coefficient':'split',
})
df_raw = df_raw.sort_values(by='date', ascending=True)
df_raw = df_raw.reset_index(drop=True)
df_raw.date = pd.to_datetime(df_raw.date)
return df_raw
def scale_adjusted(df_raw):
'''
import raw dataframe
scale open,high,low, close to adjusted close
return updated dataframe
'''
df = df_raw.copy()
df_scale = pd.DataFrame()
close = df.close.to_numpy().astype(float)
adj = df.adj_close.to_numpy().astype(float)
scale = adj / close
df_scale['date'] = df['date'].copy()
df_scale['open']=df.open.to_numpy().astype(float)*scale
df_scale['high']=df.high.to_numpy().astype(float)*scale
df_scale['low']=df.low.to_numpy().astype(float)*scale
df_scale['close']=df.close.to_numpy().astype(float)*scale
return df_scale
def compute_day_shape(prices, sigmas, dayspan):
'''
compute one day shape
'''
abs_deltas = (prices) - (prices.shift(dayspan))
s_ratios = abs_deltas / sigmas
ups = 3*(s_ratios>1)
downs = 1*(s_ratios<-1)
neuts = 2*((s_ratios>=-1)&(s_ratios<=1))
return (ups+downs+neuts)
def compute_shape(dayshape, dayspan):
'''
compute 5 day shape ordinals
'''
ago5s = 10000*(dayshape.shift(4*dayspan))
ago4s = 1000*(dayshape.shift(3*dayspan))
ago3s = 100*(dayshape.shift(2*dayspan))
ago2s = 10*(dayshape.shift(1*dayspan))
return (ago5s+ago4s+ago3s+ago2s+dayshape)
def preprocess(df):
'''
compute statistics
use day shape spans of 1, 3 and 5 days
build shape ordinals for day data
'''
df_for = df.copy()
# raw data overlaps
shifts = [['o1','h1','l1','c1'],
['o2','h2','l2','c2'],
['o3','h3','l3','c3'],
['o4','h4','l4','c4'],
]
# format df to calculate price estimates and standard deviations
for j, shift in zip(range(1,6),shifts):
df_for[shift[0]] = df_for.open.shift(-j)
df_for[shift[1]] = df_for.high.shift(-j)
df_for[shift[2]] = df_for.low.shift(-j)
df_for[shift[3]] = df_for.close.shift(-j)
# define price estimate columns for 1,3,5 day spans
p1_col = df_for.loc[:,"open":"close"].astype(float)
p3_col = df_for.loc[:,"open":"c2"].astype(float)
p5_col = df_for.loc[:,"open":"c4"].astype(float)
p_cols = [p1_col, p3_col, p5_col]
# compute price estimates and standard deviations for spans
stats = [['pe1','sd1'],['pe3','sd3'],['pe5','sd5']]
for stat, p_col in zip(stats, p_cols):
df_for[stat[0]] = p_col.mean(axis=1)
df_for[stat[1]] = p_col.std(axis=1)
# keep date but leave raw data behind
df_prep = df_for[['date','pe1','sd1','pe3','sd3','pe5','sd5']].copy()
# add day shapes to df
dayshapes = ['ds1','ds3','ds5']
dayspans = [1,3,5]
for shape, stat, span in zip(dayshapes, stats, dayspans):
df_prep[shape] = compute_day_shape(df_prep[stat[0]], df_prep[stat[1]], span)
# add shapes to df
shapes = ['shp1','shp3','shp5']
for shape, dayshape, span in zip(shapes, dayshapes, dayspans):
df_prep[shape] = compute_shape(df_prep[dayshape], span)
#trim the head then format
df_trim = df_prep[25:].copy()
df_trim[['shp1','shp3','shp5']] = df_trim[['shp1','shp3','shp5']].astype(int)
return df_trim
def assign_hsi(df, df_shape):
'''
for daily market data
lookup the HSI figures given shape ordinals
return updated dataframe with daily HSC assignment
'''
df_mkt = df.copy()
# HSI lookups
shapenames = ['shp1','shp3','shp5']
hsi_names = ['hsi1','hsi3','hsi5']
for sname, hsi_name in zip(shapenames, hsi_names):
lookups = []
s_list = df_shape[sname]['shape'].tolist()
for i,nrows in df_mkt.iterrows():
shp = nrows[sname]
# assign last known(or 0.5) for unknown shapes
if shp in s_list:
lookups.append(np.asscalar(df_shape[sname]\
[df_shape[sname]['shape']==shp]['HSI'].values))
else:
try:
lookups.append(lookups[-1])
except:
lookups.append(0.5)
df_mkt[hsi_name] = lookups
# compile three into the average of the two closest
nearest_two = []
for i,nrows in df_mkt.iterrows():
v1 = nrows['hsi1']
v2 = nrows['hsi3']
v3 = nrows['hsi5']
diffs = np.abs([v1-v2, v2-v3, v1-v3])
sums = [v1+v2, v2+v3, v1+v3]
nearest_two.append(np.max((diffs==np.amin(diffs))*sums)/2)
df_mkt['HSC'] = nearest_two
return df_mkt
def compute_trades(indicator, highT, lowT):
'''
compare HSC to thresholds
return binaries of in/out days
'''
trades = []
inout = 0
for ind in indicator:
# from out to enter
if inout == 0:
if ind > highT:
trades.append(1)
inout = 1
else:
trades.append(0)
# from in to exit
else:
if ind < lowT:
trades.append(0)
inout = 0
else:
trades.append(1)
return trades
def find_trade_masks(trade_array):
'''
Import optimal trade in/out boolean array
Export buy and sell day masks
'''
trades = trade_array.copy()
num_days = len(trades)
# number of days after threshold crossing
late = 5
# trade changes as threshold crossings
difference = np.diff(trades)
# optimal threshold day indices
buys = np.where(difference==1)
sells = np.where(difference==-1)
# optimals + late day indices using heavy numpy
late_days = np.arange(late)
buy_index_array = np.unique(np.sort(np.add(np.tile(
late_days,[len(buys[0]),1]).T,buys[0]).flatten()))
sell_index_array = np.unique(np.sort(np.add(np.tile(
late_days,[len(sells[0]),1]).T,sells[0]).flatten()))
# truncate those out of range
buy_index_array = buy_index_array[buy_index_array<num_days]
sell_index_array = sell_index_array[sell_index_array<num_days]
# build mask arrays from indices
buy_mask_array = np.zeros(num_days, dtype=int)
buy_mask_array[buy_index_array] = 1
sell_mask_array = np.zeros(num_days, dtype=int)
sell_mask_array[sell_index_array] = 1
return buy_mask_array, sell_mask_array
def add_class_fields(df_trades):
'''
import consolidated summaries
add symbol category and year fields
return updated dataframe
'''
df = df_trades.copy()
# Add symbol ordinals
with open('dict_symbolcat.pkl', 'rb') as handle:
d_symcat = pickle.load(handle)
symcat = list(map(lambda x: d_symcat[x], df.symbol.tolist()))
df['sym'] = symcat
# Add year column
df.date = pd.to_datetime(df.date)
df['year'] = df['date'].map(lambda x: x.year)
return df
def class_trades(df_trade):
'''
Import trade dataframe
Load trained classifier
Predict high return trade classification
Return updated dataframe
'''
df = df_trade.copy()
if len(df) > 0:
# load models
logreg = load('logreg_model.joblib')
# specify the same features as model trainings
class_cols = ['HSC',
'ds1', 'ds3', 'ds5',
'hsi1', 'hsi3', 'hsi5',
'pe1', 'pe3', 'pe5',
'sd1', 'sd3', 'sd5',
'shp1', 'shp3', 'shp5',
'sym','year']
# model predictions
df_class = df[class_cols].copy()
df['year'] = df['year'].astype(float)
df['pred'] = logreg.predict(df_class)
df['prob'] = logreg.predict_proba(df_class).T[1]
return df
def assign_actions(df_trade, lowT, highT):
'''
identify buy and sell day possibilities
return dataframe with buy sell boolean fields
'''
df = df_trade.copy()
# get trade mask possibilities
trades = df['trade'].to_numpy()
buys, sells = find_trade_masks(trades)
# mask for those above or below thresholds
HSC = df['HSC'].to_numpy()
b_ok = (HSC>highT)*1
s_ok = (HSC<lowT)*1
# check that the classifier is agreeable
pred = df['pred'].to_numpy()
c_ok = (pred==1)*1
# assign buy and sell boolean flags
df['buyday'] = (buys*b_ok)*c_ok
df['sellday'] = (sells*s_ok)*c_ok
return df
def summarize(df_actions):
'''
import action dataframe
check for buy sell opportunities in last five days
return slices where true
'''
df = df_actions.tail()
dates = df.date.unique()
df_sum = pd.DataFrame()
for date in dates:
#buy days
df_slice = df[(df['date']==date)&(df['buyday']==1.)]
if len(df_slice)>0:
df_sum = df_sum.append(df_slice.iloc[0])
#sell days
df_slice = df[(df['date']==date)&(df['sellday']==1.)]
if len(df_slice)>0:
df_sum = df_sum.append(df_slice.iloc[0])
return df_sum
def rank_score(df_trades):
'''
import trade opportunity dataframe
rank sort by assigned high return probabilities
return ranked dataframe
'''
df = df_trades.copy()
# sort descending
df = df.sort_values(by='prob', ascending=False)
return df
def build_image(data, col_width=3.0, row_height=0.625, font_size=14,
header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
bbox=[0, 0, 1, 1], header_columns=0,
ax=None, **kwargs):
'''
import dataframe
write dataframe to image file
return image
'''
if ax is None:
size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])
fig, ax = plt.subplots(figsize=size)
ax.axis('off')
mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)
mpl_table.auto_set_font_size(False)
mpl_table.set_fontsize(font_size)
for k, cell in six.iteritems(mpl_table._cells):
cell.set_edgecolor(edge_color)
if k[0] == 0 or k[1] < header_columns:
cell.set_text_props(weight='bold', color='w')
cell.set_facecolor(header_color)
else:
cell.set_facecolor(row_colors[k[0]%len(row_colors) ])
# add image file export
folder = 'images/'
plt.savefig(folder+'report.png')
return ax
def pipe_etl_pre(ticker, df_threshold):
'''
run ETL pre-processing pipeline
'''
print('Runnning ETL for '+ ticker)
dict_raw = get_raw(ticker)
print('formatting')
df_for = format_raw(dict_raw)
df_scale = scale_adjusted(df_for)
print('preprocessing')
df_pre = preprocess(df_scale)
df_pre['symbol'] = ticker
print('assigning shapes')
df_shape = pd.read_csv('hsi_data/{}_hsi.csv'.format(ticker),
header=[0, 1], skipinitialspace=True,
tupleize_cols=True)
df_shape.columns = pd.MultiIndex.from_tuples(df_shape.columns)
df_ind = assign_hsi(df_pre, df_shape)
print('loading trade thresholds')
lowT = df_threshold[df_threshold['ticker']==ticker]['lowT'].values[0]
highT = df_threshold[df_threshold['ticker']==ticker]['highT'].values[0]
print('computing indicated trades')
trades = compute_trades(df_ind['HSC'].tolist(), highT, lowT)
df_ind['trade'] = trades
print('classifying trades')
df_class = add_class_fields(df_ind)
df_class = class_trades(df_class)
print('finding trade opportunities')
df_act = assign_actions(df_class, lowT, highT)
print('sumarizing latest trade days')
df_sum = summarize(df_act)
return df_sum
def pipe_etl_post(df_trades):
'''
run ETL post-processing pipeline
rank sorts, formats, exports image
'''
df = df_trades.copy()
print('ranking trades')
df_out = rank_score(df)
print('formatting dataframe')
act_bool = df_out['sellday'].to_numpy()
act_strings = np.where(act_bool==1., 'SELL', 'BUY')
df_out['action'] = act_strings
out_cols = ['date','symbol','action','pe1','prob','pred']
df_form = df_out[out_cols]
df_form = df_form.rename(columns={"pe1": "price",
"prob": "score",
"pred": "class"})
df_form = df_form.sort_values(['date','score'], ascending=[False, False])
df_form['price'] = df_form['price'].round(decimals=2)
df_form['score'] = df_form['score'].round(decimals=2)
df_form['date'] = df_form['date'].dt.strftime('%Y-%m-%d')
print('exporting | |
'int'},
'component_separator': {'key': 'componentSeparator', 'type': 'int'},
'segment_terminator': {'key': 'segmentTerminator', 'type': 'int'},
'repetition_separator': {'key': 'repetitionSeparator', 'type': 'int'},
'segment_terminator_suffix': {'key': 'segmentTerminatorSuffix', 'type': 'str'},
'decimal_point_indicator': {'key': 'decimalPointIndicator', 'type': 'str'},
'release_indicator': {'key': 'releaseIndicator', 'type': 'int'},
'message_association_assigned_code': {'key': 'messageAssociationAssignedCode', 'type': 'str'},
'target_namespace': {'key': 'targetNamespace', 'type': 'str'},
}
def __init__(
self,
*,
data_element_separator: int,
component_separator: int,
segment_terminator: int,
repetition_separator: int,
segment_terminator_suffix: Union[str, "SegmentTerminatorSuffix"],
decimal_point_indicator: Union[str, "EdifactDecimalIndicator"],
release_indicator: int,
message_id: Optional[str] = None,
message_version: Optional[str] = None,
message_release: Optional[str] = None,
message_association_assigned_code: Optional[str] = None,
target_namespace: Optional[str] = None,
**kwargs
):
super(EdifactDelimiterOverride, self).__init__(**kwargs)
self.message_id = message_id
self.message_version = message_version
self.message_release = message_release
self.data_element_separator = data_element_separator
self.component_separator = component_separator
self.segment_terminator = segment_terminator
self.repetition_separator = repetition_separator
self.segment_terminator_suffix = segment_terminator_suffix
self.decimal_point_indicator = decimal_point_indicator
self.release_indicator = release_indicator
self.message_association_assigned_code = message_association_assigned_code
self.target_namespace = target_namespace
class EdifactEnvelopeOverride(msrest.serialization.Model):
"""The Edifact envelope override settings.
:param message_id: The message id on which this envelope settings has to be applied.
:type message_id: str
:param message_version: The message version on which this envelope settings has to be applied.
:type message_version: str
:param message_release: The message release version on which this envelope settings has to be
applied.
:type message_release: str
:param message_association_assigned_code: The message association assigned code.
:type message_association_assigned_code: str
:param target_namespace: The target namespace on which this envelope settings has to be
applied.
:type target_namespace: str
:param functional_group_id: The functional group id.
:type functional_group_id: str
:param sender_application_qualifier: The sender application qualifier.
:type sender_application_qualifier: str
:param sender_application_id: The sender application id.
:type sender_application_id: str
:param receiver_application_qualifier: The receiver application qualifier.
:type receiver_application_qualifier: str
:param receiver_application_id: The receiver application id.
:type receiver_application_id: str
:param controlling_agency_code: The controlling agency code.
:type controlling_agency_code: str
:param group_header_message_version: The group header message version.
:type group_header_message_version: str
:param group_header_message_release: The group header message release.
:type group_header_message_release: str
:param association_assigned_code: The association assigned code.
:type association_assigned_code: str
:param application_password: The application password.
:type application_password: str
"""
_attribute_map = {
'message_id': {'key': 'messageId', 'type': 'str'},
'message_version': {'key': 'messageVersion', 'type': 'str'},
'message_release': {'key': 'messageRelease', 'type': 'str'},
'message_association_assigned_code': {'key': 'messageAssociationAssignedCode', 'type': 'str'},
'target_namespace': {'key': 'targetNamespace', 'type': 'str'},
'functional_group_id': {'key': 'functionalGroupId', 'type': 'str'},
'sender_application_qualifier': {'key': 'senderApplicationQualifier', 'type': 'str'},
'sender_application_id': {'key': 'senderApplicationId', 'type': 'str'},
'receiver_application_qualifier': {'key': 'receiverApplicationQualifier', 'type': 'str'},
'receiver_application_id': {'key': 'receiverApplicationId', 'type': 'str'},
'controlling_agency_code': {'key': 'controllingAgencyCode', 'type': 'str'},
'group_header_message_version': {'key': 'groupHeaderMessageVersion', 'type': 'str'},
'group_header_message_release': {'key': 'groupHeaderMessageRelease', 'type': 'str'},
'association_assigned_code': {'key': 'associationAssignedCode', 'type': 'str'},
'application_password': {'key': 'applicationPassword', 'type': 'str'},
}
def __init__(
self,
*,
message_id: Optional[str] = None,
message_version: Optional[str] = None,
message_release: Optional[str] = None,
message_association_assigned_code: Optional[str] = None,
target_namespace: Optional[str] = None,
functional_group_id: Optional[str] = None,
sender_application_qualifier: Optional[str] = None,
sender_application_id: Optional[str] = None,
receiver_application_qualifier: Optional[str] = None,
receiver_application_id: Optional[str] = None,
controlling_agency_code: Optional[str] = None,
group_header_message_version: Optional[str] = None,
group_header_message_release: Optional[str] = None,
association_assigned_code: Optional[str] = None,
application_password: Optional[str] = None,
**kwargs
):
super(EdifactEnvelopeOverride, self).__init__(**kwargs)
self.message_id = message_id
self.message_version = message_version
self.message_release = message_release
self.message_association_assigned_code = message_association_assigned_code
self.target_namespace = target_namespace
self.functional_group_id = functional_group_id
self.sender_application_qualifier = sender_application_qualifier
self.sender_application_id = sender_application_id
self.receiver_application_qualifier = receiver_application_qualifier
self.receiver_application_id = receiver_application_id
self.controlling_agency_code = controlling_agency_code
self.group_header_message_version = group_header_message_version
self.group_header_message_release = group_header_message_release
self.association_assigned_code = association_assigned_code
self.application_password = <PASSWORD>
class EdifactEnvelopeSettings(msrest.serialization.Model):
"""The Edifact agreement envelope settings.
All required parameters must be populated in order to send to Azure.
:param group_association_assigned_code: The group association assigned code.
:type group_association_assigned_code: str
:param communication_agreement_id: The communication agreement id.
:type communication_agreement_id: str
:param apply_delimiter_string_advice: Required. The value indicating whether to apply delimiter
string advice.
:type apply_delimiter_string_advice: bool
:param create_grouping_segments: Required. The value indicating whether to create grouping
segments.
:type create_grouping_segments: bool
:param enable_default_group_headers: Required. The value indicating whether to enable default
group headers.
:type enable_default_group_headers: bool
:param recipient_reference_password_value: The recipient reference password value.
:type recipient_reference_password_value: str
:param recipient_reference_password_qualifier: The recipient reference password qualifier.
:type recipient_reference_password_qualifier: str
:param application_reference_id: The application reference id.
:type application_reference_id: str
:param processing_priority_code: The processing priority code.
:type processing_priority_code: str
:param interchange_control_number_lower_bound: Required. The interchange control number lower
bound.
:type interchange_control_number_lower_bound: long
:param interchange_control_number_upper_bound: Required. The interchange control number upper
bound.
:type interchange_control_number_upper_bound: long
:param rollover_interchange_control_number: Required. The value indicating whether to rollover
interchange control number.
:type rollover_interchange_control_number: bool
:param interchange_control_number_prefix: The interchange control number prefix.
:type interchange_control_number_prefix: str
:param interchange_control_number_suffix: The interchange control number suffix.
:type interchange_control_number_suffix: str
:param sender_reverse_routing_address: The sender reverse routing address.
:type sender_reverse_routing_address: str
:param receiver_reverse_routing_address: The receiver reverse routing address.
:type receiver_reverse_routing_address: str
:param functional_group_id: The functional group id.
:type functional_group_id: str
:param group_controlling_agency_code: The group controlling agency code.
:type group_controlling_agency_code: str
:param group_message_version: The group message version.
:type group_message_version: str
:param group_message_release: The group message release.
:type group_message_release: str
:param group_control_number_lower_bound: Required. The group control number lower bound.
:type group_control_number_lower_bound: long
:param group_control_number_upper_bound: Required. The group control number upper bound.
:type group_control_number_upper_bound: long
:param rollover_group_control_number: Required. The value indicating whether to rollover group
control number.
:type rollover_group_control_number: bool
:param group_control_number_prefix: The group control number prefix.
:type group_control_number_prefix: str
:param group_control_number_suffix: The group control number suffix.
:type group_control_number_suffix: str
:param group_application_receiver_qualifier: The group application receiver qualifier.
:type group_application_receiver_qualifier: str
:param group_application_receiver_id: The group application receiver id.
:type group_application_receiver_id: str
:param group_application_sender_qualifier: The group application sender qualifier.
:type group_application_sender_qualifier: str
:param group_application_sender_id: The group application sender id.
:type group_application_sender_id: str
:param group_application_password: The group application password.
:type group_application_password: str
:param overwrite_existing_transaction_set_control_number: Required. The value indicating
whether to overwrite existing transaction set control number.
:type overwrite_existing_transaction_set_control_number: bool
:param transaction_set_control_number_prefix: The transaction set control number prefix.
:type transaction_set_control_number_prefix: str
:param transaction_set_control_number_suffix: The transaction set control number suffix.
:type transaction_set_control_number_suffix: str
:param transaction_set_control_number_lower_bound: Required. The transaction set control number
lower bound.
:type transaction_set_control_number_lower_bound: long
:param transaction_set_control_number_upper_bound: Required. The transaction set control number
upper bound.
:type transaction_set_control_number_upper_bound: long
:param rollover_transaction_set_control_number: Required. The value indicating whether to
rollover transaction set control number.
:type rollover_transaction_set_control_number: bool
:param is_test_interchange: Required. The value indicating whether the message is a test
interchange.
:type is_test_interchange: bool
:param sender_internal_identification: The sender internal identification.
:type sender_internal_identification: str
:param sender_internal_sub_identification: The sender internal sub identification.
:type sender_internal_sub_identification: str
:param receiver_internal_identification: The receiver internal identification.
:type receiver_internal_identification: str
:param receiver_internal_sub_identification: The receiver internal sub identification.
:type receiver_internal_sub_identification: str
"""
_validation = {
'apply_delimiter_string_advice': {'required': True},
'create_grouping_segments': {'required': True},
'enable_default_group_headers': {'required': True},
'interchange_control_number_lower_bound': {'required': True},
'interchange_control_number_upper_bound': {'required': True},
'rollover_interchange_control_number': {'required': True},
'group_control_number_lower_bound': {'required': True},
'group_control_number_upper_bound': {'required': True},
'rollover_group_control_number': {'required': True},
'overwrite_existing_transaction_set_control_number': {'required': True},
'transaction_set_control_number_lower_bound': {'required': True},
'transaction_set_control_number_upper_bound': {'required': True},
'rollover_transaction_set_control_number': {'required': True},
'is_test_interchange': {'required': True},
}
_attribute_map = {
'group_association_assigned_code': {'key': 'groupAssociationAssignedCode', 'type': 'str'},
'communication_agreement_id': {'key': 'communicationAgreementId', 'type': 'str'},
'apply_delimiter_string_advice': {'key': 'applyDelimiterStringAdvice', 'type': 'bool'},
'create_grouping_segments': {'key': 'createGroupingSegments', 'type': 'bool'},
'enable_default_group_headers': {'key': 'enableDefaultGroupHeaders', 'type': 'bool'},
'recipient_reference_password_value': {'key': 'recipientReferencePasswordValue', 'type': 'str'},
'recipient_reference_password_qualifier': {'key': 'recipientReferencePasswordQualifier', 'type': 'str'},
'application_reference_id': {'key': 'applicationReferenceId', 'type': 'str'},
'processing_priority_code': {'key': 'processingPriorityCode', 'type': 'str'},
'interchange_control_number_lower_bound': {'key': 'interchangeControlNumberLowerBound', 'type': 'long'},
'interchange_control_number_upper_bound': {'key': 'interchangeControlNumberUpperBound', 'type': 'long'},
'rollover_interchange_control_number': {'key': 'rolloverInterchangeControlNumber', 'type': 'bool'},
'interchange_control_number_prefix': {'key': 'interchangeControlNumberPrefix', 'type': 'str'},
'interchange_control_number_suffix': {'key': 'interchangeControlNumberSuffix', 'type': 'str'},
'sender_reverse_routing_address': {'key': 'senderReverseRoutingAddress', 'type': 'str'},
'receiver_reverse_routing_address': {'key': 'receiverReverseRoutingAddress', 'type': 'str'},
'functional_group_id': {'key': 'functionalGroupId', 'type': 'str'},
'group_controlling_agency_code': {'key': 'groupControllingAgencyCode', 'type': 'str'},
'group_message_version': {'key': 'groupMessageVersion', 'type': 'str'},
'group_message_release': {'key': 'groupMessageRelease', 'type': 'str'},
'group_control_number_lower_bound': {'key': 'groupControlNumberLowerBound', 'type': 'long'},
'group_control_number_upper_bound': {'key': 'groupControlNumberUpperBound', 'type': 'long'},
'rollover_group_control_number': {'key': 'rolloverGroupControlNumber', 'type': 'bool'},
'group_control_number_prefix': {'key': 'groupControlNumberPrefix', 'type': 'str'},
'group_control_number_suffix': {'key': 'groupControlNumberSuffix', 'type': 'str'},
'group_application_receiver_qualifier': {'key': 'groupApplicationReceiverQualifier', 'type': 'str'},
'group_application_receiver_id': {'key': 'groupApplicationReceiverId', 'type': 'str'},
'group_application_sender_qualifier': {'key': 'groupApplicationSenderQualifier', 'type': 'str'},
'group_application_sender_id': {'key': 'groupApplicationSenderId', 'type': 'str'},
'group_application_password': {'key': 'groupApplicationPassword', 'type': 'str'},
'overwrite_existing_transaction_set_control_number': {'key': 'overwriteExistingTransactionSetControlNumber', 'type': 'bool'},
'transaction_set_control_number_prefix': {'key': 'transactionSetControlNumberPrefix', 'type': 'str'},
'transaction_set_control_number_suffix': {'key': 'transactionSetControlNumberSuffix', 'type': 'str'},
'transaction_set_control_number_lower_bound': {'key': 'transactionSetControlNumberLowerBound', 'type': 'long'},
'transaction_set_control_number_upper_bound': {'key': 'transactionSetControlNumberUpperBound', 'type': 'long'},
'rollover_transaction_set_control_number': {'key': 'rolloverTransactionSetControlNumber', 'type': 'bool'},
'is_test_interchange': {'key': 'isTestInterchange', 'type': 'bool'},
'sender_internal_identification': {'key': 'senderInternalIdentification', 'type': 'str'},
'sender_internal_sub_identification': {'key': 'senderInternalSubIdentification', 'type': 'str'},
'receiver_internal_identification': {'key': 'receiverInternalIdentification', 'type': 'str'},
'receiver_internal_sub_identification': {'key': 'receiverInternalSubIdentification', 'type': 'str'},
}
def __init__(
self,
*,
apply_delimiter_string_advice: bool,
create_grouping_segments: bool,
enable_default_group_headers: bool,
interchange_control_number_lower_bound: int,
interchange_control_number_upper_bound: int,
rollover_interchange_control_number: bool,
group_control_number_lower_bound: int,
group_control_number_upper_bound: int,
rollover_group_control_number: bool,
overwrite_existing_transaction_set_control_number: bool,
transaction_set_control_number_lower_bound: int,
transaction_set_control_number_upper_bound: int,
rollover_transaction_set_control_number: bool,
is_test_interchange: bool,
group_association_assigned_code: Optional[str] = None,
communication_agreement_id: Optional[str] = None,
recipient_reference_password_value: Optional[str] = None,
recipient_reference_password_qualifier: Optional[str] = None,
application_reference_id: Optional[str] = None,
processing_priority_code: Optional[str] = | |
if in_samples and out_samples:
y10 = [each[0] for each in out_samples]
y20 = [each[0] for each in in_samples]
miny = min(min(y10), min(y20))
maxy = max(max(y10), max(y20))
y0 = [m for m in range(miny, maxy + 1)]
miss1 = list(set(y10) ^ set(y0))
miss2 = list(set(y20) ^ set(y0))
for each in miss1:
out_samples.append((each, 0))
for each in miss2:
in_samples.append((each, 0))
out_samples.sort()
in_samples.sort()
y1 = [dist_ind[1] for dist_ind in out_samples]
y2 = [dist_ind[1] for dist_ind in in_samples]
x1 = [dist_ind[0] for dist_ind in out_samples]
x2 = [dist_ind[0] for dist_ind in in_samples]
x0 = list(set(x1).union(set(x2)))
x0.sort()
x = np.arange(len(x0))
width = 0.25
fig, ax = plt.subplots()
ax.bar(x-width/2, y1, width, label='outdegree')
ax.bar(x+width/2, y2, width, label='indegree')
ax.set_xlabel("Edge Degree")
ax.set_ylabel("Number of Nodes")
ax.set_xticks(x)
ax.set_xticklabels(x0)
ax.legend()
plt.savefig(os.path.join(output_dir, group_name, 'dist_figs', group_name + '_' + str(i) + '_out_in'
+ '.png'))
plt.close()
if joint_samples:
x = [dist_ind[0] for dist_ind in joint_samples]
y = [dist_ind[1] for dist_ind in joint_samples]
z = [0 for _ in joint_samples]
dx = np.ones(len(joint_samples))
dy = np.ones(len(joint_samples))
dz = [dist_ind[2] for dist_ind in joint_samples]
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
ax1.bar3d(x, y, z, dx, dy, dz)
ax1.set_xlabel("Out-Edge Degree")
ax1.set_ylabel("In-Edge Degree")
ax1.set_zlabel("Number of Nodes")
plt.savefig(os.path.join(output_dir, group_name, 'dist_figs', group_name + '_' + str(i) + '_joint'
+ '.png'))
plt.close()
sbml_dir = os.path.join(output_dir, group_name, 'sbml', group_name + '_' + str(i) + '.sbml')
antimony.loadAntimonyString(ant_str)
sbml = antimony.getSBMLString()
with open(sbml_dir, 'w') as f:
f.write(sbml)
antimony.clearPreviousLoads()
output_str = None
if str_format == 'ant':
output_str = ant_str
if str_format == 'sbml':
output_str = sbml
return output_str
def models(verbose_exceptions=False, output_dir='models', group_name='test', overwrite=True, n_models=1, n_species=10,
n_reactions=None, in_dist='random', out_dist='random', joint_dist=None, in_range=None, out_range=None,
joint_range=None, min_freq=1.0, mass_violating_reactions=True, edge_type='generic', kinetics=None,
add_enzyme=False, mod_reg=None, rxn_prob=None, rev_prob=0, ic_params=None, dist_plots=False,
net_plots=False):
"""
Generates a collection of models. This function runs the complete workflow for model generation including
truncation and re-normalization of the distributions, reaction selection and construction of the network, and the
imposition of rate-laws. Outputs include distribution data and figures, network data and figures, and the
final models in Antimony and SBML formats.
:param verbose_exceptions: Traceback for input errors are suppressed.
:param output_dir: Output directory.
:param group_name: Name of the group the models belong too and the directory they will be placed in.
:param overwrite: Overwrite the models in output_dir/models/group_name.
:param n_models: Number of models to produce.
:param n_species: Number of species per model.
:param n_reactions: Specifies the minimum number of reactions per model. Only valid in the completely random case.
:param out_dist: Describes the out-edge distribution function, the discrete distribution,
or the frequency distribution.
:param in_dist: Describes the in-edge distribution function, discrete distribution,
or frequency distribution.
:param joint_dist: Describes the joint distribution function, discrete distribution,
or frequency distribution.
:param in_range: The degree range for the in-edge distribution.
:param out_range: The degree range for the out-edge distribution.
:param joint_range: The degree range for the joint distribution (must be symmetrical, see examples).
:param min_freq: Sets the minimum number (expected value) of nodes (species) that must be in each degree bin.
:param mass_violating_reactions: Allow apparent mass violating reactions such as A + B -> A.
:param edge_type: Determines how the edges are counted against the frequency distributions.
Current options are 'generic' and 'metabolic'.
:param kinetics: Describes the desired rate-laws and parameter ranges. Ultimately defaults to
['mass_action', 'loguniform', ['kf', 'kr', 'kc'], [[0.01, 100], [0.01, 100], [0.01, 100]]]
:param add_enzyme: Add a multiplicative parameter to the rate-law that may be used for perturbation
analysis.
:param mod_reg: Describes the modifiers. Only valid for modular rate-laws.
:param rxn_prob: Describes the reaction probabilities. Ultimately defaults to
[UniUni, BiUni, UniBi, BiBI] = [0.35, 0.3, 0.3, 0.05]
:param rev_prob: Describes the probability that a reaction is reversible.
:param ic_params: Describes the initial condition sampling distributions. Ultimately defaults to ['uniform', 0, 10]
:param dist_plots: Generate distribution charts.
:param net_plots: Generate network plots.
"""
if net_plots and not found_pydot:
print('The pydot package was not found and network figures will not be produced.')
if kinetics is None:
kinetics = ['mass_action', 'loguniform', ['kf', 'kr', 'kc'], [[0.01, 100], [0.01, 100], [0.01, 100]]]
if 'modular' not in kinetics[0] and mod_reg is not None:
if not verbose_exceptions:
sys.tracebacklimit = 0
raise Exception('Regulators are relevant only to modular kinetics.\n'
'Please reset the run with appropriate parameters.')
if ic_params is None:
ic_params = ['uniform', 0, 10]
if joint_dist and (in_dist != 'random' or out_dist != 'random'):
if not verbose_exceptions:
sys.tracebacklimit = 0
raise Exception("You have provided both a joint distribution "
"and one or both of the input and output distributions")
if rxn_prob:
if round(sum(rxn_prob), 10) != 1:
if not verbose_exceptions:
sys.tracebacklimit = 0
raise Exception(f"Your stated reaction probabilities are {rxn_prob} and they do not add to 1.")
if mod_reg:
if round(sum(mod_reg[0]), 10) != 1:
if not verbose_exceptions:
sys.tracebacklimit = 0
raise Exception(f"Your stated modular regulator probabilities are {mod_reg[0]} and they do not add to 1.")
if mod_reg[1] < 0 or mod_reg[1] > 1:
if not verbose_exceptions:
sys.tracebacklimit = 0
raise Exception(f"Your positive (vs negative) probability is {mod_reg[1]} is not between 0 and 1.")
if rev_prob < 0 or rev_prob > 1:
if not verbose_exceptions:
sys.tracebacklimit = 0
raise Exception('Your reversibility probability is not between 0 and 1')
if isinstance(joint_range, list) and joint_range[0] < 1:
if not verbose_exceptions:
sys.tracebacklimit = 0
raise Exception("Node degree cannot be less than 1.")
if isinstance(in_range, list) and in_range[0] < 1:
if not verbose_exceptions:
sys.tracebacklimit = 0
raise Exception("Node degree cannot be less than 1.")
if isinstance(out_range, list) and out_range[0] < 1:
if not verbose_exceptions:
sys.tracebacklimit = 0
raise Exception("Node degree cannot be less than 1.")
if isinstance(in_dist, list) and all(isinstance(x[1], int) for x in in_dist) \
and isinstance(out_dist, list) and all(isinstance(x[1], int) for x in out_dist) \
and sum(int(x[0])*int(x[1]) for x in in_dist) != sum(int(x[0])*int(x[1]) for x in out_dist):
if not verbose_exceptions:
sys.tracebacklimit = 0
raise Exception("The total in-edges do not match the total out-edges. "
"Please revise these frequency distributions.")
num_existing_models = 0
path = os.path.join(output_dir, group_name, '')
if overwrite:
if os.path.exists(path):
shutil.rmtree(path)
os.makedirs(os.path.join(path, 'antimony'))
os.makedirs(os.path.join(path, 'networks'))
os.makedirs(os.path.join(path, 'net_figs'))
os.makedirs(os.path.join(path, 'dot_files'))
os.makedirs(os.path.join(path, 'distributions'))
os.makedirs(os.path.join(path, 'sbml'))
os.makedirs(os.path.join(path, 'dist_figs'))
else:
os.makedirs(os.path.join(path, 'antimony'))
os.makedirs(os.path.join(path, 'networks'))
os.makedirs(os.path.join(path, 'net_figs'))
os.makedirs(os.path.join(path, 'dot_files'))
os.makedirs(os.path.join(path, 'distributions'))
os.makedirs(os.path.join(path, 'sbml'))
os.makedirs(os.path.join(path, 'dist_figs'))
else:
if os.path.exists(os.path.join(path)):
gd = glob.glob(os.path.join(path, 'antimony', '*'))
num_existing_models = len(gd)
else:
os.makedirs(os.path.join(path, 'antimony'))
os.makedirs(os.path.join(path, 'networks'))
os.makedirs(os.path.join(path, 'net_figs'))
os.makedirs(os.path.join(path, 'dot_files'))
os.makedirs(os.path.join(path, 'distributions'))
os.makedirs(os.path.join(path, 'sbml'))
os.makedirs(os.path.join(path, 'dist_figs'))
i = num_existing_models
while i < num_existing_models + n_models:
in_samples = []
out_samples = []
joint_samples = []
rl = [None]
el = [[]]
rl_failed_count = -1
while not rl[0]:
rl_failed_count += 1
if rl_failed_count == 100:
print(i, 'failed')
ant_str = "Network construction failed on this attempt, consider revising your settings."
anti_dir = os.path.join(output_dir, group_name, 'antimony', group_name + '_' + str(i) + '.txt')
with open(anti_dir, 'w') as f:
f.write(ant_str)
break
in_samples, out_samples, joint_samples = \
buildNetworks.generate_samples(n_species, in_dist, out_dist, joint_dist, min_freq, in_range,
out_range, joint_range)
rl, el = buildNetworks.generate_reactions(in_samples, out_samples, joint_samples, n_species, n_reactions,
rxn_prob, mod_reg, mass_violating_reactions, edge_type)
if not rl[0]:
i += 1
continue
net_dir = os.path.join(output_dir, group_name, 'networks', group_name + '_' + str(i) + '.csv')
with open(net_dir, 'w') as f:
for j, each in enumerate(rl):
if j == 0:
f.write(str(each))
else:
for k, item in enumerate(each):
if k == 0:
f.write(str(item))
else:
f.write(',[')
for m, every in enumerate(item):
if m == 0:
f.write(str(every))
else:
f.write(',' + str(every))
f.write(']')
f.write('\n')
if net_plots and found_pydot:
edges = []
for each in el:
edges.append(('S' + str(each[0]), 'S' + str(each[1])))
graph = pydot.Dot(graph_type="digraph")
graph.set_node_defaults(color='black', style='filled', fillcolor='#4472C4')
# node_ids = set()
# for each in edges:
# node_ids.add(each[0])
# node_ids.add(each[1])
# for each in node_ids:
# graph.add_node(pydot.Node(each))
for each in edges:
graph.add_edge(pydot.Edge(each[0], each[1]))
graph.write_png(os.path.join(output_dir, group_name, 'net_figs', group_name + '_' + str(i) + '.png'))
graph.write(os.path.join(output_dir, group_name, 'dot_files', group_name + '_' + str(i) + '.dot'),
format='dot')
# KEEP THIS FOR NOW
# output graph to Dot object
# graph_file = graph.create_dot(prog='dot')
# graph_file = graph_file.decode('ascii')
# graph_file = pydot.graph_from_dot_data(graph_file)[0]
ant_str = buildNetworks.get_antimony_script(rl, ic_params, kinetics, rev_prob, add_enzyme)
anti_dir = os.path.join(output_dir, group_name, | |
"""Probes are pipeline operators to instrument state that passes through the
pipeline such as populations or individuals. """
import csv
import sys
from typing import Dict, Iterator
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from toolz import curry
from leap_ec.global_vars import context
from leap_ec import ops as op
from leap_ec.ops import iteriter_op
##############################
# print_probe
##############################
@curry
def print_probe(population, probe, stream=sys.stdout, prefix=''):
""" pipeline operator for printing the given population
:param population:
:param probe:
:param stream:
:param prefix:
:return: population
"""
val = prefix + str(probe(population))
stream.write(val)
return population
##############################
# print_individual
##############################
@curry
@iteriter_op
def print_individual(next_individual: Iterator, prefix='',
stream=sys.stdout) -> Iterator:
""" Just echoes the individual from within the pipeline
Uses next_individual.__str__
:param next_individual: iterator for next individual to be printed
:return: the same individual, unchanged
"""
while True:
individual = next(next_individual)
print(f'{prefix}{individual!s}', file=stream)
yield individual
##############################
# BestSoFar probe
##############################
class BestSoFarProbe(op.Operator):
def __init__(self, stream=sys.stdout, header=True, context=context):
self.bsf = None
self.context = context
self.writer = csv.DictWriter(stream, fieldnames=['step', 'bsf'])
def __call__(self, next_individual):
assert (next_individual is not None)
assert ('leap' in self.context)
assert ('generation' in self.context['leap'])
ind = next(next_individual)
if self.bsf is None or (ind > self.bsf):
self.bsf = ind
self.writer.writerow({'step': self.context['leap']['generation'],
'bsf' : self.bsf.fitness
})
yield ind
##############################
# Class FitnessStatsCSVProbe
##############################
class FitnessStatsCSVProbe(op.Operator):
"""A probe that records basic fitness statistics for a population
to a text stream in CSV format.
This is meant to capture the "bread and butter" values you'll typically
want to see in any population-based optimization experiment. If you
want additional columns with custom values, you can pass in a dict of
`notes` with constant values or `extra_metrics` with functions to
compute them.
:param stream: the file object to write to (defaults to sys.stdout)
:param header: whether to print column names in the first line
:param extra_metrics: a dict of `'column_name': function` pairs, to compute
optional extra columns. The functions take a the population as input
as a list of individuals, and their return value is printed in the column.
:param job: optional constant job ID, which will be printed as the
first column
:param str notes: a dict of optional constant-value columns to include in
all rows (ex. to identify and experiment or parameters)
:param context: a LEAP context object, used to retrieve the current generation
from the EA state (i.e. from `context['leap']['generation']`)
In this example, we'll set up two three inputs for the probe: an output stream,
the generation number, and a population.
We use a `StringIO` stream to print the results here, but in practice you
often want to use `sys.stdout` (the default) or a file object:
>>> import io
>>> stream = io.StringIO()
The probe also relies on LEAP's algorithm `context` to determine the generation number:
>>> from leap_ec.global_vars import context
>>> context['leap']['generation'] = 100
Here's how we'd compute fitness statistics for a test population. The population
is unmodified:
>>> from leap_ec.data import test_population
>>> probe = FitnessStatsCSVProbe(stream=stream, job=15, notes={'description': 'just a test'})
>>> probe(test_population) == test_population
True
and the output has the following columns:
>>> print(stream.getvalue())
job, description, step, bsf, mean_fitness, std_fitness, min_fitness, max_fitness
15, just a test, 100, 4, 2.5, 1.11803..., 1, 4
<BLANKLINE>
To add custom columns, use the `extra_metrics` dict. For example, here's a function
that computes the median fitness value of a population:
>>> import numpy as np
>>> median = lambda p: np.median([ ind.fitness for ind in p ])
We can include it in the fitness stats report like so:
>>> stream = io.StringIO()
>>> extras_probe = FitnessStatsCSVProbe(stream=stream, job="15", extra_metrics={'median_fitness': median})
>>> extras_probe(test_population) == test_population
True
>>> print(stream.getvalue())
job, step, bsf, mean_fitness, std_fitness, min_fitness, max_fitness, median_fitness
15, 100, 4, 2.5, 1.11803..., 1, 4, 2.5
<BLANKLINE>
"""
comment_character = '#'
time_col='step'
default_metric_cols=('bsf', 'mean_fitness', 'std_fitness', 'min_fitness', 'max_fitness')
def __init__(self, stream=sys.stdout,
header=True,
extra_metrics=None,
comment=None,
job: str = None,
notes: Dict = None,
modulo: int = 1,
context: Dict = context):
assert (stream is not None)
assert (hasattr(stream, 'write'))
assert (context is not None)
self.stream = stream
self.context = context
self.bsf_ind = None
self.modulo = modulo
self.notes = notes if notes else {}
self.extra_metrics = extra_metrics if extra_metrics else {}
self.job = job
self.comment = comment
if header:
self.write_comment(stream)
self.write_header(stream)
def write_header(self, stream):
job_header = 'job, ' if self.job is not None else ''
note_extras = '' if not self.notes else ', '.join(self.notes.keys()) + ', '
extras = '' if not self.extra_metrics else ', ' + ', '.join(
self.extra_metrics.keys())
stream.write(
job_header + note_extras + 'step, bsf, mean_fitness, std_fitness, min_fitness, max_fitness'
+ extras + '\n')
def write_comment(self, stream):
if self.comment:
commented_lines = []
for line in self.comment.split('\n'):
commented_lines.append(f"{self.comment_character} {line}")
stream.write('\n'.join(commented_lines) + '\n')
def __call__(self, population):
assert (population is not None)
assert ('leap' in self.context)
assert ('generation' in self.context['leap'])
generation = self.context['leap']['generation']
if generation % self.modulo != 0:
return population
if self.job is not None:
self.stream.write(str(self.job) + ', ')
for _, v in self.notes.items():
self.stream.write(str(v) + ', ')
self.stream.write(str(generation) + ', ')
best_ind = best_of_gen(population)
if self.bsf_ind is None or (best_ind > self.bsf_ind):
self.bsf_ind = best_ind
self.stream.write(str(self.bsf_ind.fitness) + ', ')
fitnesses = [x.fitness for x in population]
self.stream.write(str(np.mean(fitnesses)) + ', ')
self.stream.write(str(np.std(fitnesses)) + ', ')
self.stream.write(str(np.min(fitnesses)) + ', ')
self.stream.write(str(np.max(fitnesses)))
for _, f in self.extra_metrics.items():
self.stream.write(', ' + str(f(population)))
self.stream.write('\n')
return population
##############################
# Class AttributesCSVProbe
##############################
class AttributesCSVProbe(op.Operator):
"""
An operator that records the specified attributes for all the individuals
(or just the best individual) in `population` in CSV-format to the
specified stream and/or to a DataFrame.
:param attributes: list of attribute names to record, as found in the
individuals' `attributes` field
:param stream: a file object to write the CSV rows to (defaults to sys.stdout).
Can be `None` if you only want a DataFrame
:param bool do_dataframe: if True, data will be collected in memory as a
Pandas DataFrame, which can be retrieved by calling the `dataframe` property
after (or during) the algorithm run. Defaults to False, since this can
consume a lot of memory for long-running algorithms.
:param bool best_only: if True, attributes will only be recorded
for the best-fitness individual; otherwise a row is recorded for every
individual in the population
:param bool header: if True (the default), a CSV header is printed as the
first row with the column names
:param bool do_fitness: if True, the individuals' fitness is
included as one of the columns
:param bool do_genomes: if True, the individuals' genome is
included as one of the columns
:param str notes: a dict of optional constant-value columns to include in
all rows (ex. to identify and experiment or parameters)
:param extra_metrics: a dict of `'column_name': function` pairs, to compute
optional extra columns. The functions take a the population as input
as a list of individuals, and their return value is printed in the column.
:param int job: a job ID that will be included as a constant-value column in
all rows (ex. typically an integer, indicating the ith run out of many)
:param context: the algorithm context we use to read the current generation
from (so we can write it to a column)
Individuals contain some build-in attributes (namely fitness, genome),
and also a `dict` of additional custom attributes called, well,
`attributes`. This class allows you to log all of the above.
Most often, you will want to record only the best individual in the
population at each step, and you'll just want to know its fitness and
genome. You can do this with this class's boolean flags. For example,
here's how you'd record the best individual's fitness and genome to a
dataframe:
>>> from leap_ec.global_vars import context
>>> from leap_ec.data import test_population
>>> probe = AttributesCSVProbe(do_dataframe=True, best_only=True,
... do_fitness=True, do_genome=True)
>>> context['leap']['generation'] = 100
>>> probe(test_population) == test_population
True
You can retrieve the result programatically from the `dataframe` property:
>>> probe.dataframe
step fitness genome
0 100 4 [0 1 1 1 1]
By default, the results are also written to `sys.stdout`. You can pass
any file object you like into the `stream` parameter.
Another common use of this task | |
"""
label_list = set()
for entry in entrylist:
object_type = entry['object']['type']
object_value = entry['object']['value']
if not object_value:
break
if object_type == 'label':
label_list.add(object_value)
rdfobject = {}
rdfobject['type'] = object_type
rdfobject['value'] = object_value
pred_type = entry['predicate']['type']
pred_value = entry['predicate']['value']
if not pred_value:
break
if pred_type == 'label':
label_list.add(pred_value)
rdf_pred = {}
rdf_pred['type'] = pred_type
rdf_pred['value'] = [rdfobject]
predicate = {pred_value: rdf_pred}
subject_type = entry['subject']['type']
subject_value = entry['subject']['value']
if not subject_value:
break
if subject_type == 'label':
label_list.add(subject_value)
rdf_subject = {}
rdf_subject['type'] = subject_type
rdf_subject['value'] = predicate
subject = {subject_value: rdf_subject}
self.add_constraints(subjectlist=subject)
self.add_constraints(labellist=label_list)
self._set_label_constraints()
return self.submit_query()['results']['bindings']
def add_resource(self, category, label, desc, lang = ''):
"""INSERT entries with one skmf:Resource as the subject.
Resources are assumed to have certain attributes to give them a
consistent view in the user interface. They must specify a category to
distinguish if they are to be treated primarily as subjects
(skmf:Resource) or predicates (rdf:Property). They must have rdfs:label
and rdfs:comment defined to make them understandable to human users.
They may optionally specify the language for string literals as an ISO
language code.
Args:
category (str): One of skmf:Resource, rdf:property.
desc (str): Detailed description of the new resource.
label (str): Readable name from which the id is derived.
lang (str): ISO language code to associate with 'label' and 'desc'.
"""
new_id = ''.join(c for c in label if c.isalnum()).rstrip().lower()
id_uri = '{}#{}'.format(app.config['NAMESPACE'], new_id)
subject = Subject(id_uri, type='uri')
if not subject.preds:
cat_objects = []
cat_object = {}
cat_object['type'] = 'pfx'
cat_object['value'] = category
cat_objects.append(cat_object)
if category == 'skmf:Resource':
new_object = {}
new_object['type'] = 'pfx'
new_object['value'] = 'rdfs:Class'
cat_objects.append(new_object)
label_object = {}
label_object['type'] = 'literal'
label_object['value'] = label
desc_object = {}
desc_object['type'] = 'literal'
desc_object['value'] = desc
if lang:
label_object['xml:lang'] = lang
desc_object['xml:lang'] = lang
pred_value = {}
pred_value['type'] = 'pfx'
pred_value['value'] = cat_objects
new_preds = {'a': pred_value}
label_value = {}
label_value['type'] = 'pfx'
label_value['value'] = [label_object]
new_preds['rdfs:label'] = label_value
desc_value = {}
desc_value['type'] = 'pfx'
desc_value['value'] = [desc_object]
new_preds['rdfs:comment'] = desc_value
return subject.add_data(graphlist={''}, predlist=new_preds)
class Subject(object):
"""JSON/TTL-like serialization of a subject described in RDF.
An instance of a Subject typically encompasses all of the predicates and
associated RDF objects that describe one RDF subject in a triplestore. It
may also store just a subset of that information or the elements of a query
that pertain to a single subject, either by URI or through a placeholder
label. The 'type' attribute is used to specify which and the 'id' attribute
holds the actual URI or label string. A list of graphs may also be
maintained to specify which graphs are part of any query that is performed
on the Subject.
Attributes:
id (str): URI or label that identifies this Subject in a query.
graphs (list): Graphs in which to scope queries for this Subject.
preds (dict): Predicates and objects that describe this Subject. The
format should match that of the second inner dict in Query, with
the predicate id as the key:
{<predicate_uri>|<predicate_label>:
{'type': 'uri'|'pfx'|'label',
'value':
[{'type': 'uri'|'pfx'|'label'|'literal',
'value': <ojbect_uri>|<object_label>|<literal>,
'xml:lang': <lang_string>
}]
}
}
type (str): How to interpret the id, one of 'uri', 'pfx', or 'label'.
"""
def __init__(self, id, type = 'uri', graphlist = set(), predlist = {}):
"""Setup using defaults, provided values, or from the triplestore.
If no predicate list is provided and 'type' is set to 'uri' - the
default - then it is assumed that this Subject should be retrieved from
the provided list of graphs based on the 'id' argument. This assumption
is made to prevent the formation of a Subject that already exists in
the triplestore but is treated as a new RDF subject. The only way to
override this behavior is to set 'type' to something other than 'uri',
although it is not recommended to use 'label' since that already has
another meaning.
Args:
graphlist (set): Named graphs to which a subject may belong.
id (str): Unique value to assign to this subject for queries.
predlist (dict): Predicates and their associated objects.
type (str): 'uri' for SPARQL URI or 'label' for a placeholder.
"""
self.id = id
self.type = type
self.graphs = {''}
self.graphs.update(graphlist)
self.preds = predlist
if self.type != 'label' and not self.preds:
results = g.sparql.query_subject(id, type, graphlist)
self.preds = self._init_values(results)
def _init_values(self, results):
"""Returns all triples about this subject retrieved from a triplestore.
The input is expected to follow the JSON syntax for SPARQL query
responses. Moreover, it is exptected to contain 'p' and 'o' labels,
representing the predicates and objects, respectively, that make up RDF
triples that contain this Subject as their subject. If the wrong
information is passed in, then an invalid Subject may be formed.
Args:
results (dict): JSON format results of SPARQL query for a subject.
Returns:
A graph containing descriptive predicates and associated objects.
"""
predlist = {}
if 'results' in results:
try:
bindings = results['results']['bindings']
for binding in bindings:
predicate = binding['p']['value']
rdfobject = binding['o']
type = binding['p']['type']
value = {'type': type, 'value': [rdfobject]}
if predicate not in predlist:
predlist[predicate] = value
elif rdfobject not in predlist[predicate]['value']:
predlist[predicate]['value'].append(rdfobject)
except KeyError as e:
print(__name__, str(e))
return None
return predlist
def add_graphs(self, graphlist):
"""Append new graphs to the list of graphs to query for this subject.
If a graph in the provided list is not present in the local graph list,
then it is ignored.
Args:
graphlist (set): Short names of named graphs in the triplestore.
"""
self.graphs.update(graphlist)
def remove_graphs(self, graphlist):
"""Remove a graph from the list of graphs to query for this subject.
If a graph in the provided list is not present in the local graph list,
then it is ignored.
Args:
graphlist (set): Short names of named graphs in the triplestore.
"""
self.graphs.difference_update(graphlist)
def add_data(self, graphlist, predlist = {}):
"""Add new triples that describe this subject to the triplestore.
The provided graph list is used to determine to which graphs triples
are added, but any graphs that are not attributed to this Subject are
ignored in order to support access control mechanisms. No default graph
is provided for INSERTs, so this list must not be empty.
Params:
graphlist (set): Named graphs that should hold the new triples.
predlist (dict): New data to add, in the same format at self.preds.
Returns:
The list of graphs that were available for adding triples.
The dictionary of predicates that were actually added.
"""
new_preds = {}
new_graphs = self.graphs.intersection(graphlist)
for predicate in predlist:
if predlist[predicate]['value'] and predlist[predicate]['type']:
new_type = predlist[predicate]['type']
rdfobjects = predlist[predicate]['value']
temp = {}
temp['type'] = new_type
temp['value'] = []
# to avoid KeyError during iteration
if predicate not in self.preds:
self.preds[predicate] = temp
for rdfobject in rdfobjects:
if rdfobject['value'] and rdfobject['type']:
if rdfobject not in self.preds[predicate]['value']:
self.preds[predicate]['value'].append(rdfobject)
if temp['value']:
new_preds[predicate] = temp
else:
del self.preds[predicate]
if new_preds:
rec_value = {}
rec_value['type'] = self.type
rec_value['value'] = new_preds
record = {self.id: rec_value}
g.sparql.insert(new_graphs, record)
return new_graphs, new_preds
def remove_data(self, graphlist, predlist = {}):
"""Delete triples for this subject from some graphs in the triplestore.
The provided graph list is used to determine from which graphs triples
are deleted, but any graphs that are not attributed to this Subject are
ignored in order to support access control mechanisms. No default graph
is provided for DELETEs, so this list must not be empty.
Params:
graphlist (set): Named graphs from which to delete triples.
predlist (graph): Data to delete, in the same format as self.preds.
Returns:
The list of graphs that were available for removing triples.
The dictionary of predicates that were actually deleted.
"""
old_preds = {}
old_graphs = self.graphs.intersection(graphlist)
for predicate in predlist:
if predlist[predicate]['value'] and predlist[predicate]['type']:
if predicate in self.preds:
old_type = predlist[predicate]['type']
rdfobjects = predlist[predicate]['value']
temp = {'type': old_type, 'value': []}
for rdfobject in rdfobjects:
if rdfobject | |
kwargs=network_params \
);
elif(network_class_name == 'MultiplexAutoencoderFixedStainsArch3Next3Adverserial'):
from ..sa_networks.multiplex_autoencoder_fixed_stains_arch3_next3_adverserial import MultiplexAutoencoderFixedStainsArch3Next3Adverserial;
cnn_arch = MultiplexAutoencoderFixedStainsArch3Next3Adverserial(n_channels = n_channels, n_classes = n_classes, model_out_path = model_path, model_base_filename = model_base_filename, model_restore_filename = model_restore_filename, cost_func = cost_func \
, device=device, kwargs=network_params \
);
elif(network_class_name == 'MultiplexAutoencoderFixedStainsArch3Next3AdverserialInv'):
from ..sa_networks.multiplex_autoencoder_fixed_stains_arch3_next3_adverserial_inv import MultiplexAutoencoderFixedStainsArch3Next3AdverserialInv;
cnn_arch = MultiplexAutoencoderFixedStainsArch3Next3AdverserialInv(n_channels = n_channels, n_classes = n_classes, model_out_path = model_path, model_base_filename = model_base_filename, model_restore_filename = model_restore_filename, cost_func = cost_func \
, device=device, kwargs=network_params \
);
elif(network_class_name == 'MultiplexAutoencoderFixedStainsArch3Next3InputStain'):
from ..sa_networks.multiplex_autoencoder_fixed_stains_arch3_next3_input_stain import MultiplexAutoencoderFixedStainsArch3Next3InputStain;
cnn_arch = MultiplexAutoencoderFixedStainsArch3Next3InputStain(n_channels = n_channels, n_classes = n_classes, model_out_path = model_path, model_base_filename = model_base_filename, model_restore_filename = model_restore_filename, cost_func = cost_func \
, device=device, kwargs=network_params \
);
else:
print('error: network class name \'{}\' is not supported by runner'.format(network_class_name));
sys.exit();
print("distribute arch over gpus ")
# distribute arch over gpus
params = list(cnn_arch.parameters()); # The learnable parameters of a model are returned by net.parameters()
print(len(params)); # each conv or linear (fc) consists of main weights and bias
print(params[0].size());
if (torch.cuda.device_count() > 1 and len(device_ids) > 1):
cnn_arch = torch.nn.DataParallel(cnn_arch, device_ids);
print("before move to device ", device)
cnn_arch.to(device);
print("after move to device")
try:
if(cnn_arch.module is None):
cnn_arch_module = cnn_arch;
else:
cnn_arch_module = cnn_arch.module;
except:
cnn_arch_module = cnn_arch;
print("get dataprovider ")
if(is_test == False):
if(train_dataprovider_class_name == 'MultiplexAutoencoderDataProvider'):
from sa_data_providers.multiplex_autoencoder_data_provider import MultiplexAutoencoderDataProvider;
train_data_provider = MultiplexAutoencoderDataProvider( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = None \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
elif(train_dataprovider_class_name == 'MultiplexAutoencoderDataProviderFromPkl'):
from sa_data_providers.multiplex_autoencoder_data_provider_from_pkl import MultiplexAutoencoderDataProviderFromPkl;
train_data_provider = MultiplexAutoencoderDataProviderFromPkl( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = train_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
elif(train_dataprovider_class_name == 'MultiplexAutoencoderDataProviderFromPklRGB'):
from sa_data_providers.multiplex_autoencoder_data_provider_from_pkl_rgb import MultiplexAutoencoderDataProviderFromPklRGB;
train_data_provider = MultiplexAutoencoderDataProviderFromPklRGB( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = train_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
elif(train_dataprovider_class_name == 'MultiplexAutoencoderDataProviderFromPklRGBLbl'):
from sa_data_providers.multiplex_autoencoder_data_provider_from_pkl_rgb_lbl import MultiplexAutoencoderDataProviderFromPklRGBLbl;
train_data_provider = MultiplexAutoencoderDataProviderFromPklRGBLbl( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = train_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
elif(train_dataprovider_class_name == 'MultiplexAutoencoderDataProviderFromPklHSL'):
from sa_data_providers.multiplex_autoencoder_data_provider_from_pkl_hsl import MultiplexAutoencoderDataProviderFromPklHSL;
train_data_provider = MultiplexAutoencoderDataProviderFromPklHSL( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = train_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
elif(train_dataprovider_class_name == 'MnistAutoencoderDataProviderRGB'):
from sa_data_providers.mnist_autoencoder_data_provider_rgb import MnistAutoencoderDataProviderRGB;
train_data_provider = MnistAutoencoderDataProviderRGB( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = train_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
elif(train_dataprovider_class_name == 'MultiplexAutoencoderDataProviderFromNumpyRGBDots'):
from sa_data_providers.multiplex_autoencoder_data_provider_from_npy_rgb_dots import MultiplexAutoencoderDataProviderFromNumpyRGBDots;
train_data_provider = MultiplexAutoencoderDataProviderFromNumpyRGBDots( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = train_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
elif(train_dataprovider_class_name == 'MultiplexAutoencoderDataProviderRGB'):
from sa_data_providers.multiplex_autoencoder_data_provider_rgb import MultiplexAutoencoderDataProviderRGB;
train_data_provider = MultiplexAutoencoderDataProviderRGB( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = train_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
elif(train_dataprovider_class_name == 'MultiplexAutoencoderDataProviderCMYK'):
from sa_data_providers.multiplex_autoencoder_data_provider_cmyk import MultiplexAutoencoderDataProviderCMYK;
train_data_provider = MultiplexAutoencoderDataProviderCMYK( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = train_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
elif(train_dataprovider_class_name == 'MultiplexAutoencoderDataProviderLum'):
from sa_data_providers.multiplex_autoencoder_data_provider_lum import MultiplexAutoencoderDataProviderLum;
train_data_provider = MultiplexAutoencoderDataProviderLum( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = train_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
elif(train_dataprovider_class_name == 'MultiplexAutoencoderDataProviderRGBwithLoss'):
from sa_data_providers.multiplex_autoencoder_data_provider_rgb_wloss import MultiplexAutoencoderDataProviderRGBwithLoss;
train_data_provider = MultiplexAutoencoderDataProviderRGBwithLoss( \
is_test=is_test \
, filepath_data = train_filepath_data \
, filepath_label = train_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = train_preprocess \
, do_augment = train_augment \
, data_var_name = None \
, label_var_name = None \
, permute = train_permute \
, repeat = True \
, kwargs = train_params\
);
else:
print('error: train data provider class name \'{}\' is not supported by runner'.format(train_dataprovider_class_name));
sys.exit();
if(has_validation):
if(validate_dataprovider_class_name == 'MultiplexAutoencoderDataProvider'):
from sa_data_providers.multiplex_autoencoder_data_provider import MultiplexAutoencoderDataProvider;
validate_data_provider = MultiplexAutoencoderDataProvider( \
is_test=is_test \
, filepath_data = validate_filepath_data \
, filepath_label = None \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = validate_preprocess \
, do_augment = validate_augment \
, data_var_name = None \
, label_var_name = None \
, permute = validate_permute \
, repeat = False \
, kwargs = validate_params\
);
elif(validate_dataprovider_class_name == 'MultiplexAutoencoderDataProviderFromPkl'):
from sa_data_providers.multiplex_autoencoder_data_provider_from_pkl import MultiplexAutoencoderDataProviderFromPkl;
validate_data_provider = MultiplexAutoencoderDataProviderFromPkl( \
is_test=is_test \
, filepath_data = validate_filepath_data \
, filepath_label = validate_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = validate_preprocess \
, do_augment = validate_augment \
, data_var_name = None \
, label_var_name = None \
, permute = validate_permute \
, repeat = False \
, kwargs = validate_params\
);
elif(validate_dataprovider_class_name == 'MultiplexAutoencoderDataProviderFromPklRGB'):
from sa_data_providers.multiplex_autoencoder_data_provider_from_pkl_rgb import MultiplexAutoencoderDataProviderFromPklRGB;
validate_data_provider = MultiplexAutoencoderDataProviderFromPklRGB( \
is_test=is_test \
, filepath_data = validate_filepath_data \
, filepath_label = validate_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = validate_preprocess \
, do_augment = validate_augment \
, data_var_name = None \
, label_var_name = None \
, permute = validate_permute \
, repeat = False \
, kwargs = validate_params\
);
elif(validate_dataprovider_class_name == 'MultiplexAutoencoderDataProviderFromPklRGBLbl'):
from sa_data_providers.multiplex_autoencoder_data_provider_from_pkl_rgb_lbl import MultiplexAutoencoderDataProviderFromPklRGBLbl;
validate_data_provider = MultiplexAutoencoderDataProviderFromPklRGBLbl( \
is_test=is_test \
, filepath_data = validate_filepath_data \
, filepath_label = validate_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = validate_preprocess \
, do_augment = validate_augment \
, data_var_name = None \
, label_var_name = None \
, permute = validate_permute \
, repeat = False \
, kwargs = validate_params\
);
elif(validate_dataprovider_class_name == 'MultiplexAutoencoderDataProviderFromPklHSL'):
from sa_data_providers.multiplex_autoencoder_data_provider_from_pkl_hsl import MultiplexAutoencoderDataProviderFromPklHSL;
validate_data_provider = MultiplexAutoencoderDataProviderFromPklHSL( \
is_test=is_test \
, filepath_data = validate_filepath_data \
, filepath_label = validate_filepath_label \
, n_channels = n_channels \
, n_classes = n_classes \
, do_preprocess = validate_preprocess \
, do_augment = validate_augment \
, data_var_name | |
normalized best-fit
# values, or 1 if any of them deviates more than limdev
mask_deviant = (np.abs(factor_temp_norm - 1) > limdev)
if np.any(mask_deviant):
log.warning ('factor deviation for channel(s) {} larger than {}: '
'{}; setting all channel factors to 1'
.format(list(np.nonzero(mask_deviant)[0]+1), limdev,
factor_temp_norm[mask_deviant]))
factor_temp_norm[:] = 1
# easier to create new set of fit parameters rather than adjusting them
params = Parameters()
for i_chan in range(nchans):
params.add('factor{}'.format(i_chan+1), value=factor_temp_norm[i_chan],
vary=False)
for i_coeff in range(ncoeffs):
params.add('coeff{}'.format(i_coeff), value=coeff_temp_norm[i_coeff],
vary=mask_cfit[i_coeff])
# fit
result = minimize (mini2min, params, method='Leastsq', max_nfev=100,
args=(mini_median, mini_std, mini_sec, order,
mask_reject_temp, f_norm,))
params = result.params
chi2red = result.redchi
log.info ('order: {}, chi2red: {}'.format(order, chi2red))
log.info ('normalized factors for this intermediate fit: {}'
.format(factor_temp_norm))
# check formal criterium to use
if (chi2red_old / chi2red) > 2:
chi2red_old = chi2red
order_bf = order
chi2red_bf = chi2red
params_bf = params
mask_reject_bf = mask_reject_temp
result_bf = result
resid_bf = resid_temp
if log is not None:
mem_use (label='at end of order loop in bkg_corr_MLBG', log=log)
log.info (fit_report(result_bf))
log.info ('order used: {}, reduced chi-square: {}'.format(order_bf,
chi2red_bf))
p = params_bf
# save fit factors and coefficients in numpy arrays; N.B.: error
# estimate is unreliable because factor and coefficients fit
# parameters are typically correlated, so not considering the
# errors
factor = np.zeros(nchans)
for i_chan in range(nchans):
factor[i_chan] = p['factor{}'.format(i_chan+1)].value
ncoeffs = (order_bf+1)**2
coeff = np.zeros(ncoeffs)
for i_coeff in range(ncoeffs):
coeff[i_coeff] = p['coeff{}'.format(i_coeff)].value
# one more call to mini2min with final fit parameters
mini_median_corr, mini_std_corr, mini_median_2Dfit, __ = \
mini2min(p, mini_median, mini_std, mini_sec, order_bf,
mask_reject_bf, f_norm, return_resid=False)
if False:
ds9_arrays (mini_median=mini_median,
mini_std=mini_std,
mini_median_corr=mini_median_corr,
mini_std_corr=mini_std_corr,
mini_median_2Dfit=mini_median_2Dfit,
resid_bf=resid_bf,
mask_reject_bf=mask_reject_bf,
bkg_mini=np.amin([mini_median_corr,mini_median_2Dfit],
axis=0)
)
if log is not None:
mem_use (label='just before correcting data in bkg_corr_MLBG', log=log)
if correct_data and not np.all(factor==1):
bkg_corr = True
# mini median and std
mini_median[:] = mini_median_corr
mini_std[:] = mini_std_corr
# full image data
for i_chan in range(nchans):
data[data_sec[i_chan]] *= factor[i_chan]
if log is not None:
log.info ('image channels modified with correction factors: {}'
.format(factor))
else:
bkg_corr = False
# add boolean to header
header['BKG-CORR'] = (bkg_corr, 'channels corrected for background ratios?')
header['BKG-CHI2'] = (chi2red_bf, 'reduced chi2 of background factor/poly fit')
# add correction factors to header
for i_chan in range(nchans):
header['BKG-CF{}'.format(i_chan+1)] = (
factor[i_chan],
'channel {} correction factor'.format(i_chan+1))
# N.B.: polynomials were fit with normalized x and y pixel indices
# (using [f_norm]) of the mini image, so coeffients should be
# scaled accordingly if original image pixel indices are used to
# infer the polynomial fit (most natural)
bkg_boxsize = get_par(set_zogy.bkg_boxsize,tel)
xy = np.arange(order_bf+1)
coeff_power = np.sum(np.meshgrid(xy,xy), axis=0).ravel()
coeff_scaled = coeff / (float(f_norm * bkg_boxsize)**coeff_power)
header['BKG-FDEG'] = (order_bf, 'degree background 2D polynomial fit')
# add coefficients to header
for i_coeff in range((order_bf+1)**2):
header['BKG-FC{}'.format(i_coeff)] = (
coeff_scaled[i_coeff],
'background 2D poly fit coefficient {}'.format(i_coeff))
if log is not None and get_par(set_zogy.timing,tel):
log_timing_memory (t0=t, label='bkg_corr_MLBG', log=log)
return bkg_corr, mini_median_2Dfit
################################################################################
def mini2min (params, data, data_std, data_sec, order, mask_reject,
f_norm, return_resid=True):
# fit parameters
p = params
# define x, y grid to fit
x = np.arange(data.shape[1])
y = np.arange(data.shape[0])
# make copy of input data
data_corr = np.copy(data)
data_std_corr = np.copy(data_std)
# modify channel sections with fit parameters
nchans = np.shape(data_sec)[0]
for i_chan in range(nchans):
factor_chan = p['factor{}'.format(i_chan+1)].value
data_corr[data_sec[i_chan]] *= factor_chan
data_std_corr[data_sec[i_chan]] *= factor_chan
# exclude pixels where data_std_corr is zero
mask_fit = (data_std_corr != 0)
# add input mask_reject
if mask_reject is not None:
mask_fit &= ~mask_reject
# create model 2D polynomial fit from coefficients
coeff = [p['coeff{}'.format(i)].value for i in range((order+1)**2)]
coeff = np.array(coeff).reshape((order+1, order+1))
fit = polygrid2d(x/f_norm, y/f_norm, coeff).T
# residuals
resid = np.zeros(data_corr.shape)
resid[mask_fit] = ((data_corr[mask_fit] - fit[mask_fit]) /
data_std_corr[mask_fit])
# return flattened residuals
if return_resid:
return resid[mask_fit].ravel()
else:
return data_corr, data_std_corr, fit, resid
################################################################################
def polyfcn2d (params, x, y, z, z_err, deg):
# extract coefficients from params
p = params.valuesdict()
coeffs = [p['c{}'.format(i)] for i in range((deg+1)**2)]
coeffs = np.array(coeffs).reshape(deg+1,deg+1)
# determine z_model at x,y with coefficients
z_model = polyval2d(x, y, coeffs)
# determine residuals
resid = (z - z_model) / z_err
# return residuals
return resid.ravel()
################################################################################
def polyfit2d (x, y, z, z_err=None, order=2, fit_higher_Xterms=False,
verbose=False):
# exclude higher cross-terms if input parameter
# [fit_higher_Xterms] is False
if not fit_higher_Xterms:
xy = np.arange(order+1)
xx, yy = np.meshgrid(xy, xy)
mask_fit = (xx+yy <= order).ravel()
else:
mask_fit = np.ones((order+1)**2, dtype=bool)
# polynomial fit without considering z_err
deg = [order, order]
deg = np.asarray(deg)
vander = polyvander2d(x, y, deg)
vander = vander.reshape((-1,vander.shape[-1]))
vander[:,~mask_fit] = 0
z_temp = z.reshape((vander.shape[0],))
coeffs, resid, rank, s = np.linalg.lstsq(vander, z_temp, rcond=None)
if verbose:
#print ('vander: {}'.format(vander))
print ('resid : {}'.format(resid))
print ('rank : {}'.format(rank))
print ('s : {}'.format(s))
print ('coeffs: {}'.format(coeffs))
if z_err is not None:
# put coeffients in parameters
coeffs[~mask_fit] = 0
params = Parameters()
nc = coeffs.size
for i in range(nc):
params.add('c{}'.format(i), value=coeffs[i], vary=mask_fit[i])
# do leastsq polynomial fit including z_err
result = minimize (polyfcn2d, params, method='Leastsq',
args=(x, y, z, z_err, order,))
p = result.params.valuesdict()
coeffs = np.array([p['c{}'.format(i)] for i in range(nc)])
if verbose:
print (fit_report(result))
# return fit coefficients
return coeffs.reshape(deg+1)
################################################################################
def polyfit2d_orig (x, y, f, deg):
"""see 2nd most popular answer at
https://stackoverflow.com/questions/7997152/python-3d-polynomial-surface-fit-order-dependent
"""
deg = [deg, deg]
deg = np.asarray(deg)
vander = polyvander2d(x, y, deg)
vander = vander.reshape((-1,vander.shape[-1]))
f = f.reshape((vander.shape[0],))
c = np.linalg.lstsq(vander, f, rcond=None)[0]
return c.reshape(deg+1)
################################################################################
# helper function to return median filter, with size
# [filter_size], of array with mask (True=valid pixels)
def median_filter (array, mask, filter_size=3):
# array shape
ysize, xsize = array.shape
# pad array with (filter_size-1)//2 pixels with value 0
dpix = int(filter_size-1)//2
array_pad = np.pad(array, (dpix,dpix), 'constant')
# and mask with value False
mask_pad = np.pad(mask, (dpix,dpix), 'constant')
# using skimage.util.shape.view_as_windows to construct cubes
window_shape = (filter_size, filter_size)
array_cube = view_as_windows (array_pad, window_shape).reshape(
array.shape[0], array.shape[1], -1)
mask_cube = view_as_windows (mask_pad, window_shape).reshape(
mask.shape[0], mask.shape[1], -1)
# create masked array
array_masked = np.ma.masked_array(array_cube, mask=~mask_cube)
# return median filtered array
return np.ma.median(array_masked, axis=2)
################################################################################
def get_rand_indices (shape, fraction=0.2):
"""Given an input shape, this function returns a tuple of random
integer arrays (with the ranges determined by shape), one for each
axis/dimension. The total number of indices returned is the total
size defined by [shape] times [fraction].
"""
# determine size
size = np.empty(shape).size
# number of dimensions
ndim = len(shape)
# create list of integer arrays
# N.B.: size needs to be the same for each axis
index = [np.random.randint(shape[i],size=int(size*fraction))
for i in range(ndim)]
if ndim==1:
index = index[0]
# return tuple
return tuple(index)
################################################################################
def mini2back (data_mini, output_shape, order_interp=3, bkg_boxsize=None,
interp_Xchan=True, timing=True, log=None):
if log is not None:
if timing: t = time.time()
log.info('executing mini2back ...')
def help_mini2back (data_mini, output_shape):
# resize low-resolution meshes, with order [order_interp], where
# order=0: nearest
# order=1: bilinear spline interpolation
# order=2: quadratic spline interpolation
# order=3: cubic spline interpolation
background = ndimage.zoom(data_mini, bkg_boxsize, order=order_interp,
mode='nearest')
# if shape of the background is not equal to input
# [output_data], then pad the background image
if output_shape != background.shape:
t1 = time.time()
ysize, xsize = output_shape
ypad = ysize - background.shape[0]
xpad = xsize - background.shape[1]
background = np.pad(background, ((0,ypad),(0,xpad)), 'edge')
if log is not None:
log.info('time to pad: {:.4f}'.format(time.time()-t1))
#np.pad seems quite slow; alternative:
#centers, cuts_ima, cuts_ima_fft, cuts_fft, sizes = centers_cutouts(
# get_par(set_zogy.bkg_boxsize,tel), ysize, xsize, log,
# get_remainder=True)
# these now include the remaining patches
return background
# if interp_Xchan is True, then expand the mini image to the full
# image allowing the interpolation to cross the different channels
if interp_Xchan:
data_full = help_mini2back (data_mini, output_shape)
else:
# for ML/BG, determine the full image for each channel
# separately and insert them into the output image
data_sec = get_section_MLBG (output_shape)
mini_shape = data_mini.shape
mini_sec = get_section_MLBG (mini_shape)
nchans = np.shape(mini_sec)[0]
# prepare output array and loop channels
data_full = np.zeros(output_shape, dtype='float32')
channel_shape | |
dataset as argument. Therefore, in this case setting the dataset
property within the exporter object is not necessary.
The actual export is implemented within the non-public method
:meth:`_export` that gets automatically called.
Parameters
----------
dataset : :class:`aspecd.dataset.Dataset`
Dataset to export data and metadata from
Raises
------
aspecd.io.MissingDatasetError
Raised if no dataset is provided.
"""
if not dataset:
if self.dataset:
self.dataset.export_to(self)
else:
raise aspecd.exceptions.MissingDatasetError(
"No dataset provided")
else:
self.dataset = dataset
self._export()
def _export(self):
"""Perform the actual export of data and metadata from the dataset.
The implementation of the actual export goes in here in all
classes inheriting from DatasetExporter. This method is automatically
called by :meth:`export_from`.
Usually, this method will successively call other private/protected
methods of the exporter to perform the required tasks that are
specific for each target format.
"""
class RecipeImporter:
"""Base class for recipe importer.
Each class actually importing recipes into a :obj:`aspecd.tasks.Recipe`
object should inherit from this class.
To perform the import, call the
:meth:`~aspecd.tasks.Recipe.import_from` method of the recipe the
import should be performed for, and provide a reference to the
actual importer object to it.
The actual implementation of the importing is done in the non-public
method :meth:`_import` that in turn gets called by :meth:`import_into`
which is called by the :meth:`aspecd.tasks.Recipe.import_from` method
of the recipe object.
One question arising when actually implementing an importer for a
specific file format: How does the information get into the recipe? The
simple answer: The :meth:`_import` method of the importer knows about the
recipe and its structure (see :class:`aspecd.tasks.Recipe` for
details) and creates a dictionary with keys corresponding to the
respective attributes of the recipe. In turn, it can then call the
:meth:`aspecd.tasks.Recipe.from_dict` method. In terms of a broader
software architecture point of view: The recipe knows nothing about the
importer besides its bare existence and interface, whereas the importer
knows about the recipe and how to map the information obtained to it.
Attributes
----------
recipe : :obj:`aspecd.tasks.Recipe`
recipe to import into
source : :class:`str`
specifier of the source the information will be read from
Raises
------
aspecd.io.MissingRecipeError
Raised when no dataset exists to act upon
"""
def __init__(self, source=''):
self.source = source
self.recipe = None
def import_into(self, recipe=None):
"""Perform the actual import into the given recipe.
If no recipe is provided at method call, but is set as property in
the importer object, the :meth:`aspecd.tasks.Recipe.import_from`
method of the recipe will be called.
If no recipe is provided at method call nor as property in the
object, the method will raise a respective exception.
The recipe object always calls this method with the respective
recipe as argument. Therefore, in this case setting the recipe
property within the importer object is not necessary.
The actual import should be implemented within the non-public method
:meth:`_import`.
Parameters
----------
recipe : :obj:`aspecd.tasks.Recipe`
recipe to import into
Raises
------
aspecd.io.MissingRecipeError
Raised if no recipe is provided.
"""
if not recipe:
if self.recipe:
self.recipe.import_from(self)
else:
raise aspecd.exceptions.MissingRecipeError("No recipe provided")
else:
self.recipe = recipe
self.recipe.filename = self.source
self._import()
def _import(self):
"""Perform the actual import into the recipe.
The implementation of the actual import goes in here in all
classes inheriting from RecipeImporter. This method is automatically
called by :meth:`import_into`.
Importing metadata includes assigning it to the respective fields
of the :obj:`aspecd.tasks.Recipe` object. For details of
its structure, see there. To do this, the method should create a
dictionary that can afterwards be supplied as an argument to a call
to :meth:`aspecd.tasks.Recipe.from_dict`.
"""
class RecipeExporter:
"""Base class for recipe exporter.
Each class actually exporting recipes from :obj:`aspecd.tasks.Recipe`
objects should inherit from this class.
To perform the export, call the
:meth:`aspecd.tasks.Recipe.export_to` method of the recipe the export
should be performed for, and provide a reference to the actual exporter
object to it.
The actual implementation of the exporting is done in the non-public
method :meth:`_export` that in turn gets called by :meth:`export_from`
which is called by the :meth:`aspecd.tasks.Recipe.export_to` method
of the recipe object.
Attributes
----------
recipe : :obj:`aspecd.tasks.Recipe`
recipe to export information from
target : string
specifier of the target the information will be written to
Raises
------
aspecd.io.MissingRecipeError
Raised when no dataset exists to act upon
"""
def __init__(self, target=''):
self.target = target
self.recipe = None
def export_from(self, recipe=None):
"""Perform the actual export from the given recipe.
If no recipe is provided at method call, but is set as property in
the exporter object, the :meth:`aspecd.tasks.Recipe.export_to`
method of the recipe will be called.
If no recipe is provided at method call nor as property in the
object, the method will raise a respective exception.
The recipe object always calls this method with the respective
recipe as argument. Therefore, in this case setting the recipe
property within the exporter object is not necessary.
The actual export should be implemented within the non-public method
:meth:`_export`.
Parameters
----------
recipe : :class:`aspecd.tasks.Recipe`
Recipe to export from
Raises
------
aspecd.io.MissingRecipeError
Raised if no recipe is provided.
"""
if not recipe:
if self.recipe:
self.recipe.export_to(self)
else:
raise aspecd.exceptions.MissingRecipeError("No recipe provided")
else:
self.recipe = recipe
self._export()
def _export(self):
"""Perform the actual export from the recipe.
The implementation of the actual export goes in here in all
classes inheriting from RecipeExporter. This method is automatically
called by :meth:`export_from`.
Usually, this method will first create a dictionary from the recipe
using the :meth:`aspecd.tasks.Recipe.to_dict` method. This
dictionary can afterwards be further processed and written to some
file.
"""
class RecipeYamlImporter(RecipeImporter):
"""
Recipe importer for importing from YAML files.
The YAML file needs to have a structure compatible to the actual
recipe, such that the dict created from reading the YAML file can be
directly fed into the :meth:`aspecd.tasks.Recipe.from_dict` method.
The order of entries of the YAML file is preserved due to using ordered
dictionaries (:class:`collections.OrderedDict`) internally.
Parameters
----------
source : :class:`str`
filename of a YAML file to read from
"""
def __init__(self, source=''):
self.recipe_version = ''
self._recipe_dict = None
super().__init__(source=source)
def _import(self):
self._load_from_yaml()
self._convert()
self.recipe.from_dict(self._recipe_dict)
def _load_from_yaml(self):
yaml = aspecd.utils.Yaml()
yaml.read_from(filename=self.source)
yaml.deserialise_numpy_arrays()
self._recipe_dict = yaml.dict
def _convert(self):
self._get_recipe_version()
self._map_recipe_structure()
def _get_recipe_version(self):
self.recipe_version = self.recipe.format['version']
if 'format' in self._recipe_dict \
and 'version' in self._recipe_dict['format']:
self.recipe_version = self._recipe_dict['format']['version']
deprecated_keys = ['default_package', 'autosave_plots',
'output_directory', 'datasets_source_directory']
if any([key in self._recipe_dict for key in deprecated_keys]):
self.recipe_version = '0.1'
def _map_recipe_structure(self):
mapper = aspecd.metadata.MetadataMapper()
mapper.version = self.recipe_version
mapper.metadata = self._recipe_dict
mapper.recipe_filename = 'recipe_mapper.yaml'
mapper.map()
self._recipe_dict = mapper.metadata
class RecipeYamlExporter(RecipeExporter):
"""
Recipe exporter for exporting to YAML files.
The YAML file will have a structure corresponding to the output of the
:meth:`aspecd.tasks.Recipe.to_dict` method of the recipe object.
Parameters
----------
target : :class:`str`
filename of a YAML file to write to
"""
def __init__(self, target=''):
super().__init__(target=target)
def _export(self):
yaml = aspecd.utils.Yaml()
yaml.dict = self.recipe.to_dict()
yaml.numpy_array_to_list = True
yaml.serialise_numpy_arrays()
yaml.write_to(filename=self.target)
class AdfExporter(DatasetExporter):
"""
Dataset exporter for exporting to ASpecD dataset format.
The ASpecD dataset format is vaguely reminiscent of the Open Document
Format, *i.e.* a zipped directory containing structured data (in this
case in form of a YAML file) and binary data in a corresponding
subdirectory.
As PyYAML is not capable of dealing with NumPy arrays out of the box,
those are dealt with separately. Small arrays are stored inline as
lists, larger arrays in separate files. For details, see the
:class:`aspecd.utils.Yaml` class.
The data format tries to be as self-contained as possible,
using standard file formats and a brief description of its layout
contained within the archive. Collecting the contents in a single ZIP
archive allows the user to deal with a single file for a dataset,
while more advanced users can easily dig into the details and write
importers for other platforms and programming languages, making the
format rather platform-independent and future-safe. Due to using binary
representation for larger numerical arrays, the format should be more
memory-efficient than other formats.
"""
def __init__(self, target=None):
super().__init__(target=target)
self.extension = '.adf'
self._filenames = {
'dataset': 'dataset.yaml',
'version': 'VERSION',
'readme': 'README',
}
self._bin_dir = | |
#
# To run tests, you can do 'python -m testtools.run tests'. To run specific tests,
# You can do 'python -m testtools.run -l tests'
# Set the env variable PARAMS_FILE to point to your ini file. Else it will try to pick params.ini in PWD
#
import os
import copy
import traceback
from novaclient import client as mynovaclient
from novaclient import exceptions as novaException
import unittest
import fixtures
import testtools
from contrail_test_init import *
from vn_test import *
from quantum_test import *
from vnc_api_test import *
from nova_test import *
from vm_test import *
from connections import ContrailConnections
from floating_ip import *
from policy_test import *
from contrail_fixtures import *
from vna_introspect_utils import *
from random import choice
from topo_helper import *
import policy_test_utils
import project_test_utils
from tcutils.wrappers import preposttest_wrapper
from tcutils.commands import ssh, execute_cmd, execute_cmd_out
from sdn_topo_setup import *
from get_version import *
from system_verification import *
import sdn_flow_test_topo
import traffic_tests
import time
import datetime
import threading
import socket
import flow_test_utils
class sdnFlowTest(testtools.TestCase, fixtures.TestWithFixtures):
def setUp(self):
super(sdnFlowTest, self).setUp()
if 'PARAMS_FILE' in os.environ:
self.ini_file = os.environ.get('PARAMS_FILE')
else:
self.ini_file = 'params.ini'
self.inputs = self.useFixture(ContrailTestInit(self.ini_file))
self.connections = ContrailConnections(self.inputs)
self.agent_inspect = self.connections.agent_inspect
self.quantum_fixture = self.connections.quantum_fixture
self.nova_fixture = self.connections.nova_fixture
self.vnc_lib = self.connections.vnc_lib
self.logger = self.inputs.logger
self.analytics_obj = self.connections.analytics_obj
self.agent_inspect = self.connections.agent_inspect
self.cn_inspect = self.connections.cn_inspect
self.ops_inspect = self.connections.ops_inspect
# end setUpClass
def cleanUp(self):
super(sdnFlowTest, self).cleanUp()
# end cleanUp
def runTest(self):
pass
# end runTest
# get source min, max ip's and destination max port.
def src_min_max_ip_and_dst_max_port(self, ips, no_of_ip, dst_min_port, flows):
""" Called by test_flow_single_project or test_flow_multi_project to get the min source ip, max source ip and
Max port number of the destination. This helps to create certain no of flows as expected by test_flow_single_project
or test_flow_multi_project routines, from where it is called.
"""
ip_list = list()
for index in range(no_of_ip):
ip_list.append(ips[index])
src_min_ip = ip_list[0]
src_max_ip = ip_list[-1]
dst_max_port = dst_min_port + (flows / no_of_ip)
result_dict = {'src_min_ip': src_min_ip, 'src_max_ip':
src_max_ip, 'dst_max_port': dst_max_port}
return result_dict
# end src_min_max_ip_and_dst_max_port
def start_traffic(self, vm, src_min_ip='', src_max_ip='', dest_ip='', dest_min_port='', dest_max_port='', pkt_cnt=''):
""" This routine is for generation of UDP flows using pktgen. Only UDP packets are generated using this routine.
"""
self.logger.info("Sending traffic...")
try:
cmd = '~/flow_test_pktgen.sh %s %s %s %s %s %s' % (src_min_ip,
src_max_ip, dest_ip, dest_min_port, dest_max_port, pkt_cnt)
vm.run_cmd_on_vm(cmds=[cmd], as_sudo=True)
except Exception as e:
self.logger.exception("Got exception at start_traffic as %s" % (e))
# end start_traffic
def generate_udp_flows_and_do_verification(self, traffic_profile, verification_obj, build_version):
""" Routine to generate UDP flows by calling the start_traffic routine in a thread and do parallel verification of
flow setup rate and system level verifications like vm-state, vn-state, policies etc.
@inputs :
traffic_profile - a list of traffic generation parameters as explained in test_flow_single_project and test_flow_multi_project
routines.
verification_obj - topology objects to call verification methods on them.
build_version - os_version, release_version and build_version for logging purposes.
"""
Shost = socket.gethostbyaddr(traffic_profile[0].vm_node_ip)
Dhost = socket.gethostbyaddr(traffic_profile[7].vm_node_ip)
self.logger.info("Src_VM = %s, Src_IP_Range = %s to %s, Dest_VM = %s, Dest_IP = %s, Src_VN = %s, Dest_VN = %s,"
" Port_Range = %s to %s, Src_Node = %s, Dst_Node = %s." % (traffic_profile[0].vm_name,
traffic_profile[1], traffic_profile[
2], traffic_profile[
7].vm_name, traffic_profile[
3],
traffic_profile[0].vn_name, traffic_profile[
7].vn_name, traffic_profile[
4], traffic_profile[
5],
Shost[0], Dhost[0]))
th = threading.Thread(
target=self.start_traffic, args=(
traffic_profile[0], traffic_profile[1], traffic_profile[2],
traffic_profile[3], traffic_profile[
4], traffic_profile[
5],
traffic_profile[6]))
th.start()
#
# Flow setup rate calculation.
NoOfFlows = []
FlowRatePerInterval = []
AverageFlowSetupRate = 0
default_setup_rate = 7000 # A default value of 7K flows per second.
src_vm_obj = traffic_profile[0]
dst_vm_obj = traffic_profile[7]
#
# Decide the test is for NAT Flow or Policy Flow.
PolNatSI = 'NONE'
srcFIP = src_vm_obj.chk_vmi_for_fip(src_vm_obj.vn_fq_name)
dstFIP = dst_vm_obj.chk_vmi_for_fip(dst_vm_obj.vn_fq_name)
if srcFIP is None:
if dstFIP is None:
PolNatSI = 'Policy Flow'
else:
PolNatSI = 'NAT Flow'
#
# Get or calculate the sleep_interval/wait time before getting the no of flows in vrouter for each release based
# on a file defining a release to average flow setup rate mapping. The threshold defined in the file is for Policy Flows,
# so NAT flow is calculated at 70% of the average flow setup rate
# defined.
RelVer = str(get_VrouterReleaseVersion(self))
from ReleaseToFlowSetupRateMapping import *
try:
DefinedSetupRate = my_rel_flow_setup_rate_mapping[RelVer]
except KeyError:
# A default value of 7K flows per second is set.
DefinedSetupRate = default_setup_rate
#
# if we are creating NAT Flows then our expected flow setup rate should be 70% of the defined flow setup
# rate defined for that release in ReleaseToFlowSetupRateMapping file.
if PolNatSI == 'NAT Flow':
DefinedSetupRate = 0.7 * DefinedSetupRate
#
# The flow setup rate is calculated based on setup time required for first 100K flows. So TotalFlows is set to 100K and 5
# samples (NoOfIterations) are taken within the time required to setup 100K flows. The time interval (sleep_interval) is
# calculated based on DefinedSetupRate for the particular release
# version.
TotalFlows = 100000
NoOfIterations = 5
sleep_interval = (float(TotalFlows) / float(DefinedSetupRate)) / \
float(NoOfIterations)
#
# After each sleep_interval we get the number of active forward or nat flows setup on the vrouter which is repeated for
# NoOfIterations times. and the average is calculated in each
# iteration.
for ind in range(NoOfIterations):
time.sleep(sleep_interval)
NoOfFlows.append(flow_test_utils.vm_vrouter_flow_count(src_vm_obj))
if ind == 0:
FlowRatePerInterval.append(NoOfFlows[ind])
AverageFlowSetupRate = FlowRatePerInterval[ind]
elif ind > 0:
FlowRatePerInterval.append(NoOfFlows[ind] - NoOfFlows[ind - 1])
AverageFlowSetupRate = (
AverageFlowSetupRate + FlowRatePerInterval[ind]) / 2
self.logger.info("Flows setup in last %s sec = %s" %
(sleep_interval, FlowRatePerInterval[ind]))
self.logger.info(
"Average flow setup rate per %s sec till this iteration = %s" %
(sleep_interval, AverageFlowSetupRate))
self.logger.info(" ")
self.logger.info("Sleeping for 60 sec, for all the flows to be setup.")
time.sleep(60)
# Calculate the flow setup rate per second = average flow setup in
# sleep interval over the above iterations / sleep interval.
AverageFlowSetupRate = int(AverageFlowSetupRate / sleep_interval)
self.logger.info("Flow setup rate seen in this test is = %s" %
(AverageFlowSetupRate))
if (AverageFlowSetupRate < (0.9 * DefinedSetupRate)):
self.logger.warn(
"Flow setup rate seen in this test fell below 90 percent of the defined flow setup rate for this release - %s." %
(DefinedSetupRate))
else:
self.logger.info(
"Flow setup rate seen in this test is close to or above the defined flow setup rate for this release - %s." %
(DefinedSetupRate))
# write to a file to do record keeping of the flow rate on a particular
# node.
ts = time.time()
mtime = datetime.datetime.fromtimestamp(
ts).strftime('%Y-%m-%d %H:%M:%S')
fh = open("Flow_Test_Data.xls", "a")
localflow = 'Remote Flow'
# Check if it's a remote or local flow to log the data accordingly.
if Shost[0] == Dhost[0]:
localflow = 'Local Flow'
# if source and destination VN are same then it's not a NAT/Policy flow else it is a NAT/Policy flow and needs to be logged
# accordingly.
if src_vm_obj.vn_name == dst_vm_obj.vn_name:
mystr = "%s\t%s\t%s\t%s\t%s\n" % (
build_version, mtime, Shost[0], AverageFlowSetupRate, localflow)
else:
mystr = "%s\t%s\t%s\t%s\t%s\t%s\n" % (
build_version, mtime, Shost[0], AverageFlowSetupRate, localflow, PolNatSI)
fh.write(mystr)
fh.close()
#
# Do system verification.
verify_system_parameters(self, verification_obj)
self.logger.info("Joining thread")
th.join()
#
# Fail the test if the actual flow setup rate is < 70% of the defined
# flow setup rate for the release.
if (AverageFlowSetupRate < (0.7 * DefinedSetupRate)):
self.logger.error(
"The Flow setup rate seen in this test is below 70% of the defined (expected) flow setup rate for this release.")
self.logger.error(
"The Actual Flow setup rate = %s and the Defined Flow setup rate = %s." %
(AverageFlowSetupRate, DefinedSetupRate))
self.logger.error(
"This clearly indicates there is something wrong here and thus the test will execute no further test cases.")
self.logger.error("Exiting Now!!!")
return False
return True
# end generate_udp_flows_and_do_verification
@preposttest_wrapper
def test_flow_single_project(self):
"""Tests related to flow setup rate and flow table stability accross various triggers for verification
accross VN's within a single project"""
result = True
topology_class_name = None
#
# Check if there are enough nodes i.e. atleast 2 compute nodes to run this test.
# else report that minimum 2 compute nodes are needed for this test and
# exit.
if len(self.inputs.compute_ips) < 2:
self.logger.warn(
"Minimum 2 compute nodes are needed for this test to run")
self.logger.warn(
"Exiting since this test can't be run on single compute node")
return True
#
# | |
<filename>bazel/repositories.bzl
load(":dev_binding.bzl", "envoy_dev_binding")
load(":genrule_repository.bzl", "genrule_repository")
load("@envoy_api//bazel:envoy_http_archive.bzl", "envoy_http_archive")
load("@envoy_api//bazel:external_deps.bzl", "load_repository_locations")
load(":repository_locations.bzl", "REPOSITORY_LOCATIONS_SPEC")
load("@com_google_googleapis//:repository_rules.bzl", "switched_rules_by_language")
# maistra/envoy uses luajit2 on ppc64le so http.lua can be built
PPC_SKIP_TARGETS = []
WINDOWS_SKIP_TARGETS = [
"envoy.filters.http.sxg",
"envoy.tracers.dynamic_ot",
"envoy.tracers.lightstep",
"envoy.tracers.datadog",
"envoy.tracers.opencensus",
]
# Make all contents of an external repository accessible under a filegroup. Used for external HTTP
# archives, e.g. cares.
def _build_all_content(exclude = []):
return """filegroup(name = "all", srcs = glob(["**"], exclude={}), visibility = ["//visibility:public"])""".format(repr(exclude))
BUILD_ALL_CONTENT = _build_all_content()
REPOSITORY_LOCATIONS = load_repository_locations(REPOSITORY_LOCATIONS_SPEC)
# Use this macro to reference any HTTP archive from bazel/repository_locations.bzl.
def external_http_archive(name, **kwargs):
envoy_http_archive(
name,
locations = REPOSITORY_LOCATIONS,
**kwargs
)
# Use this macro to reference any genrule_repository sourced from bazel/repository_locations.bzl.
def external_genrule_repository(name, **kwargs):
location = REPOSITORY_LOCATIONS[name]
genrule_repository(
name = name,
**dict(location, **kwargs)
)
def _default_envoy_build_config_impl(ctx):
ctx.file("WORKSPACE", "")
ctx.file("BUILD.bazel", "")
ctx.symlink(ctx.attr.config, "extensions_build_config.bzl")
_default_envoy_build_config = repository_rule(
implementation = _default_envoy_build_config_impl,
attrs = {
"config": attr.label(default = "@envoy//source/extensions:extensions_build_config.bzl"),
},
)
def _envoy_repo_impl(repository_ctx):
"""This provides information about the Envoy repository
You can access the current version and path to the repository in .bzl/BUILD
files as follows:
```starlark
load("@envoy_repo//:version.bzl", "VERSION")
```
`VERSION` can be used to derive version-specific rules and can be passed
to the rules.
The `VERSION` and also the local `PATH` to the repo can be accessed in
python libraries/binaries. By adding `@envoy_repo` to `deps` they become
importable through the `envoy_repo` namespace.
As the `PATH` is local to the machine, it is generally only useful for
jobs that will run locally.
This can be useful for example, for tooling that needs to check the
repository, or to run bazel queries that cannot be run within the
constraints of a `genquery`.
"""
repo_path = repository_ctx.path(repository_ctx.attr.envoy_root).dirname
version = repository_ctx.read(repo_path.get_child("VERSION")).strip()
repository_ctx.file("version.bzl", "VERSION = '%s'" % version)
repository_ctx.file("__init__.py", "PATH = '%s'\nVERSION = '%s'" % (repo_path, version))
repository_ctx.file("WORKSPACE", "")
repository_ctx.file("BUILD", """
load("@rules_python//python:defs.bzl", "py_library")
py_library(name = "envoy_repo", srcs = ["__init__.py"], visibility = ["//visibility:public"])
""")
_envoy_repo = repository_rule(
implementation = _envoy_repo_impl,
attrs = {
"envoy_root": attr.label(default = "@envoy//:BUILD"),
},
)
def envoy_repo():
if "envoy_repo" not in native.existing_rules().keys():
_envoy_repo(name = "envoy_repo")
# Python dependencies.
def _python_deps():
# TODO(htuch): convert these to pip3_import.
external_http_archive(
name = "com_github_twitter_common_lang",
build_file = "@envoy//bazel/external:twitter_common_lang.BUILD",
)
external_http_archive(
name = "com_github_twitter_common_rpc",
build_file = "@envoy//bazel/external:twitter_common_rpc.BUILD",
)
external_http_archive(
name = "com_github_twitter_common_finagle_thrift",
build_file = "@envoy//bazel/external:twitter_common_finagle_thrift.BUILD",
)
external_http_archive(
name = "six",
build_file = "@com_google_protobuf//third_party:six.BUILD",
)
# Bazel native C++ dependencies. For the dependencies that doesn't provide autoconf/automake builds.
def _cc_deps():
external_http_archive("grpc_httpjson_transcoding")
native.bind(
name = "path_matcher",
actual = "@grpc_httpjson_transcoding//src:path_matcher",
)
native.bind(
name = "grpc_transcoding",
actual = "@grpc_httpjson_transcoding//src:transcoding",
)
def _go_deps(skip_targets):
# Keep the skip_targets check around until Istio Proxy has stopped using
# it to exclude the Go rules.
if "io_bazel_rules_go" not in skip_targets:
external_http_archive(
name = "io_bazel_rules_go",
# TODO(wrowe, sunjayBhatia): remove when Windows RBE supports batch file invocation
patch_args = ["-p1"],
patches = ["@envoy//bazel:rules_go.patch"],
)
external_http_archive("bazel_gazelle")
def _rust_deps():
external_http_archive("rules_rust")
def envoy_dependencies(skip_targets = []):
# Add a binding for repository variables.
envoy_repo()
# Setup Envoy developer tools.
envoy_dev_binding()
# Treat Envoy's overall build config as an external repo, so projects that
# build Envoy as a subcomponent can easily override the config.
if "envoy_build_config" not in native.existing_rules().keys():
_default_envoy_build_config(name = "envoy_build_config")
# Setup external Bazel rules
_foreign_cc_dependencies()
# Binding to an alias pointing to the selected version of BoringSSL:
# - BoringSSL FIPS from @boringssl_fips//:ssl,
# - non-FIPS BoringSSL from @boringssl//:ssl.
# EXTERNAL OPENSSL
_openssl()
_openssl_includes()
_com_github_maistra_bssl_wrapper()
# The long repo names (`com_github_fmtlib_fmt` instead of `fmtlib`) are
# semi-standard in the Bazel community, intended to avoid both duplicate
# dependencies and name conflicts.
_com_github_c_ares_c_ares()
_com_github_circonus_labs_libcircllhist()
_com_github_cyan4973_xxhash()
_com_github_datadog_dd_opentracing_cpp()
_com_github_mirror_tclap()
_com_github_envoyproxy_sqlparser()
_com_github_fmtlib_fmt()
_com_github_gabime_spdlog()
_com_github_google_benchmark()
_com_github_google_jwt_verify()
_com_github_google_libprotobuf_mutator()
_com_github_google_libsxg()
_com_github_google_tcmalloc()
_com_github_gperftools_gperftools()
_com_github_grpc_grpc()
_com_github_intel_ipp_crypto_crypto_mb()
_com_github_jbeder_yaml_cpp()
_com_github_libevent_libevent()
_com_github_luajit_luajit()
_com_github_moonjit_moonjit()
_com_github_luajit2_luajit2()
_com_github_nghttp2_nghttp2()
_com_github_skyapm_cpp2sky()
_com_github_nodejs_http_parser()
_com_github_alibaba_hessian2_codec()
_com_github_tencent_rapidjson()
_com_github_nlohmann_json()
_com_github_ncopa_suexec()
_com_google_absl()
_com_google_googletest()
_com_google_protobuf()
_io_opencensus_cpp()
_com_github_curl()
_com_github_envoyproxy_sqlparser()
_com_googlesource_chromium_v8()
_com_github_google_quiche()
_com_googlesource_googleurl()
_com_lightstep_tracer_cpp()
_io_opentracing_cpp()
_net_zlib()
_com_github_zlib_ng_zlib_ng()
_org_brotli()
_upb()
_proxy_wasm_cpp_sdk()
_proxy_wasm_cpp_host()
_rules_fuzzing()
external_http_archive("proxy_wasm_rust_sdk")
external_http_archive("com_googlesource_code_re2")
_com_google_cel_cpp()
external_http_archive("com_github_google_flatbuffers")
external_http_archive("bazel_toolchains")
external_http_archive("bazel_compdb")
external_http_archive(
name = "envoy_build_tools",
patch_args = ["-p1"],
patches = ["@envoy//bazel/external:envoy_build_tools.patch"],
)
external_http_archive(
"rules_cc",
patch_args = ["-p1"],
patches = ["@envoy//bazel/external:rules_cc.patch"],
)
external_http_archive("rules_pkg")
# Unconditional, since we use this only for compiler-agnostic fuzzing utils.
_org_llvm_releases_compiler_rt()
_python_deps()
_cc_deps()
_go_deps(skip_targets)
_rust_deps()
_kafka_deps()
_com_github_wamr()
_com_github_wavm_wavm()
_com_github_wasmtime()
_com_github_wasm_c_api()
switched_rules_by_language(
name = "com_google_googleapis_imports",
cc = True,
go = True,
grpc = True,
rules_override = {
"py_proto_library": "@envoy_api//bazel:api_build_system.bzl",
},
)
native.bind(
name = "bazel_runfiles",
actual = "@bazel_tools//tools/cpp/runfiles",
)
def _openssl():
native.bind(
name = "ssl",
actual = "@openssl//:openssl-lib",
)
def _openssl_includes():
external_http_archive(
name = "com_github_openssl_openssl",
build_file = "@envoy//bazel/external:openssl_includes.BUILD",
patches = [
"@envoy//bazel/external:openssl_includes-1.patch",
],
patch_args = ["-p1"],
)
native.bind(
name = "openssl_includes_lib",
actual = "@com_github_openssl_openssl//:openssl_includes_lib",
)
def _com_github_maistra_bssl_wrapper():
external_http_archive(
name = "com_github_maistra_bssl_wrapper",
)
native.bind(
name = "bssl_wrapper_lib",
actual = "@com_github_maistra_bssl_wrapper//:bssl_wrapper",
)
def _com_github_circonus_labs_libcircllhist():
external_http_archive(
name = "com_github_circonus_labs_libcircllhist",
build_file = "@envoy//bazel/external:libcircllhist.BUILD",
)
native.bind(
name = "libcircllhist",
actual = "@com_github_circonus_labs_libcircllhist//:libcircllhist",
)
def _com_github_c_ares_c_ares():
external_http_archive(
name = "com_github_c_ares_c_ares",
build_file_content = BUILD_ALL_CONTENT,
)
native.bind(
name = "ares",
actual = "@envoy//bazel/foreign_cc:ares",
)
def _com_github_cyan4973_xxhash():
external_http_archive(
name = "com_github_cyan4973_xxhash",
build_file = "@envoy//bazel/external:xxhash.BUILD",
)
native.bind(
name = "xxhash",
actual = "@com_github_cyan4973_xxhash//:xxhash",
)
def _com_github_envoyproxy_sqlparser():
external_http_archive(
name = "com_github_envoyproxy_sqlparser",
build_file = "@envoy//bazel/external:sqlparser.BUILD",
)
native.bind(
name = "sqlparser",
actual = "@com_github_envoyproxy_sqlparser//:sqlparser",
)
def _com_github_mirror_tclap():
external_http_archive(
name = "com_github_mirror_tclap",
build_file = "@envoy//bazel/external:tclap.BUILD",
patch_args = ["-p1"],
# If and when we pick up tclap 1.4 or later release,
# this entire issue was refactored away 6 years ago;
# https://sourceforge.net/p/tclap/code/ci/5d4ffbf2db794af799b8c5727fb6c65c079195ac/
# https://github.com/envoyproxy/envoy/pull/8572#discussion_r337554195
patches = ["@envoy//bazel:tclap-win64-ull-sizet.patch"],
)
native.bind(
name = "tclap",
actual = "@com_github_mirror_tclap//:tclap",
)
def _com_github_fmtlib_fmt():
external_http_archive(
name = "com_github_fmtlib_fmt",
build_file = "@envoy//bazel/external:fmtlib.BUILD",
)
native.bind(
name = "fmtlib",
actual = "@com_github_fmtlib_fmt//:fmtlib",
)
def _com_github_gabime_spdlog():
external_http_archive(
name = "com_github_gabime_spdlog",
build_file = "@envoy//bazel/external:spdlog.BUILD",
)
native.bind(
name = "spdlog",
actual = "@com_github_gabime_spdlog//:spdlog",
)
def _com_github_google_benchmark():
external_http_archive(
name = "com_github_google_benchmark",
)
native.bind(
name = "benchmark",
actual = "@com_github_google_benchmark//:benchmark",
)
def _com_github_google_libprotobuf_mutator():
external_http_archive(
name = "com_github_google_libprotobuf_mutator",
build_file = "@envoy//bazel/external:libprotobuf_mutator.BUILD",
)
def _com_github_google_libsxg():
external_http_archive(
name = "com_github_google_libsxg",
build_file_content = BUILD_ALL_CONTENT,
)
native.bind(
name = "libsxg",
actual = "@envoy//bazel/foreign_cc:libsxg",
)
def _com_github_intel_ipp_crypto_crypto_mb():
external_http_archive(
name = "com_github_intel_ipp_crypto_crypto_mb",
build_file_content = BUILD_ALL_CONTENT,
)
def _com_github_jbeder_yaml_cpp():
external_http_archive(
name = "com_github_jbeder_yaml_cpp",
)
native.bind(
name = "yaml_cpp",
actual = "@com_github_jbeder_yaml_cpp//:yaml-cpp",
)
def _com_github_libevent_libevent():
external_http_archive(
name = "com_github_libevent_libevent",
build_file_content = BUILD_ALL_CONTENT,
)
native.bind(
name = "event",
actual = "@envoy//bazel/foreign_cc:event",
)
def _net_zlib():
external_http_archive(
name = "net_zlib",
build_file_content = BUILD_ALL_CONTENT,
patch_args = ["-p1"],
patches = ["@envoy//bazel/foreign_cc:zlib.patch"],
)
native.bind(
name = "zlib",
actual = "@envoy//bazel/foreign_cc:zlib",
)
# Bind for grpc.
native.bind(
name = "madler_zlib",
actual = "@envoy//bazel/foreign_cc:zlib",
)
def _com_github_zlib_ng_zlib_ng():
external_http_archive(
name = "com_github_zlib_ng_zlib_ng",
build_file_content = BUILD_ALL_CONTENT,
patch_args = ["-p1"],
patches = ["@envoy//bazel/foreign_cc:zlib_ng.patch"],
)
# If you're looking for envoy-filter-example / envoy_filter_example
# the hash is in ci/filter_example_setup.sh
def _org_brotli():
external_http_archive(
name = "org_brotli",
)
native.bind(
name = "brotlienc",
actual = "@org_brotli//:brotlienc",
)
native.bind(
name = "brotlidec",
actual = "@org_brotli//:brotlidec",
)
def _com_google_cel_cpp():
external_http_archive("com_google_cel_cpp")
external_http_archive("rules_antlr")
# Parser dependencies
# TODO: upgrade this when cel is upgraded to use the latest version
external_http_archive(name = "rules_antlr")
external_http_archive(
name = "antlr4_runtimes",
build_file_content = """
package(default_visibility = ["//visibility:public"])
cc_library(
name = "cpp",
srcs = glob(["runtime/Cpp/runtime/src/**/*.cpp"]),
hdrs = glob(["runtime/Cpp/runtime/src/**/*.h"]),
includes = ["runtime/Cpp/runtime/src"],
)
""",
patch_args = ["-p1"],
# Patches ASAN violation of initialization fiasco
patches = [
"@envoy//bazel:antlr.patch",
# antlr_s390x_ossm_1526.patch is a temporary workaround for antlr4 crash problem on s390x
# https://issues.redhat.com/browse/OSSM-1526
# https://github.com/antlr/antlr4/issues/3728
"@envoy//bazel:antlr_s390x_ossm_1526.patch"
],
)
def _com_github_nghttp2_nghttp2():
external_http_archive(
name = "com_github_nghttp2_nghttp2",
build_file_content = BUILD_ALL_CONTENT,
patch_args = ["-p1"],
# This patch cannot be picked up due to ABI rules. Discussion at;
# https://github.com/nghttp2/nghttp2/pull/1395
# https://github.com/envoyproxy/envoy/pull/8572#discussion_r334067786
patches = ["@envoy//bazel/foreign_cc:nghttp2.patch"],
)
native.bind(
name = "nghttp2",
actual = "@envoy//bazel/foreign_cc:nghttp2",
)
def _io_opentracing_cpp():
external_http_archive(
name = "io_opentracing_cpp",
patch_args = ["-p1"],
# Workaround for LSAN false positive in https://github.com/envoyproxy/envoy/issues/7647
patches = ["@envoy//bazel:io_opentracing_cpp.patch"],
)
native.bind(
name = "opentracing",
actual = "@io_opentracing_cpp//:opentracing",
)
def _com_lightstep_tracer_cpp():
external_http_archive("com_lightstep_tracer_cpp")
native.bind(
name = "lightstep",
actual = "@com_lightstep_tracer_cpp//:manual_tracer_lib",
)
def _com_github_datadog_dd_opentracing_cpp():
external_http_archive("com_github_datadog_dd_opentracing_cpp")
external_http_archive(
name = "com_github_msgpack_msgpack_c",
build_file = "@com_github_datadog_dd_opentracing_cpp//:bazel/external/msgpack.BUILD",
)
native.bind(
name = "dd_opentracing_cpp",
actual = "@com_github_datadog_dd_opentracing_cpp//:dd_opentracing_cpp",
)
def _com_github_skyapm_cpp2sky():
external_http_archive(
name = "com_github_skyapm_cpp2sky",
)
external_http_archive(
name = "skywalking_data_collect_protocol",
)
native.bind(
name = "cpp2sky",
actual = "@com_github_skyapm_cpp2sky//source:cpp2sky_data_lib",
)
def _com_github_tencent_rapidjson():
external_http_archive(
name = "com_github_tencent_rapidjson",
build_file = "@envoy//bazel/external:rapidjson.BUILD",
)
native.bind(
name = "rapidjson",
actual = "@com_github_tencent_rapidjson//:rapidjson",
)
def _com_github_nlohmann_json():
external_http_archive(
name = "com_github_nlohmann_json",
build_file = "@envoy//bazel/external:json.BUILD",
)
native.bind(
name = "json",
actual = "@com_github_nlohmann_json//:json",
)
def _com_github_nodejs_http_parser():
external_http_archive(
name = "com_github_nodejs_http_parser",
build_file = "@envoy//bazel/external:http-parser.BUILD",
)
native.bind(
name = "http_parser",
actual = "@com_github_nodejs_http_parser//:http_parser",
)
def _com_github_alibaba_hessian2_codec():
external_http_archive("com_github_alibaba_hessian2_codec")
native.bind(
name = "hessian2_codec_object_codec_lib",
actual = "@com_github_alibaba_hessian2_codec//hessian2/basic_codec:object_codec_lib",
)
native.bind(
name = "hessian2_codec_codec_impl",
actual = "@com_github_alibaba_hessian2_codec//hessian2:codec_impl_lib",
)
def _com_github_ncopa_suexec():
external_http_archive(
name = | |
% uid
else:
tag_info = ''
tag_call = '(no tags)'
items.append({
'uid': uid,
'since_when': since_when,
'creator': creator,
'loaded': loaded,
'feed_uid': feed_uid,
'title': title,
'feed_html': feed_html,
'content': content,
'tag_info': tag_info,
'tag_call': tag_call,
'redirect': redirect,
'feed_title': feed_title,
'feed_snr': feed_snr,
'updated_ts': updated_ts,
'rating': rating,
'feed_exempt': str(bool(feed_exempt)).lower()
})
return {
'show': show,
'item_desc': item_desc,
'feed_uid': feed_uid,
'ratings_list': ratings_list,
'sort_desc': sort_desc,
'sort_list': sort_list,
'items': items,
'overload_threshold': param.overload_threshold
}
@app.route("/")
@app.route("/view")
def view():
pvars = view_common()
return flask.render_template('view.html', **pvars)
@app.route("/xmlfeedback/<op>/<rand>/<arg>")
def ajax(op, rand, arg):
item_uid = arg.split('.')[0]
# for safety, these operations should be idempotent
if op in ['promote', 'demote', 'basic', 'yappi']:
if op != 'yappi':
update.set_rating(int(item_uid), {
'demote': -1,
'basic': 0,
'promote': 1
}[op])
return '<?xml version="1.0"?><nothing />'
else:
import yappi
assert arg in ['start', 'stop', 'clear_stats']
getattr(yappi, arg)()
return '<?xml version="1.0"?><nothing />'
@app.route("/robots.txt")
def robots():
return ('User-agent: *\nDisallow: /\n', 200, {'Content-Type': 'text/plain'})
@app.route("/favicon.ico")
@app.route("/api/favicon.ico")
@app.route("/apple-touch-icon.png")
@app.route("/api/apple-touch-icon.png")
def favicon():
return ('No favicon\n', 404, {'Content-Type': 'text/plain'})
def rule_tabset(feed_uid=None):
return flask.render_template(
'feed.html', filters=filters,
len=len, max=max, **locals()
)
@app.template_filter('rule_lines')
def rule_lines(text):
return max(4, filters.rule_lines(text))
@app.route("/feed/<int:feed_uid>", methods=['GET', 'POST'])
@app.route("/feed/<int:feed_uid>/<op>", methods=['GET', 'POST'])
def feed_info(feed_uid, op=None):
notices = []
# operations
if op:
if op == 'activate':
status = 0
update.set_status(feed_uid, status)
elif op == 'suspend':
status = 1
update.set_status(feed_uid, status)
elif op == 'private':
private = 1
update.update_feed_private(feed_uid, private)
elif op == 'public':
private = 0
update.update_feed_private(feed_uid, private)
elif op == 'Dupcheck':
dupcheck = 1
update.update_feed_dupcheck(feed_uid, dupcheck)
elif op == 'NoDupcheck':
dupcheck = 0
update.update_feed_dupcheck(feed_uid, dupcheck)
elif op == 'exempt':
exempt = 1
update.update_feed_exempt(feed_uid, exempt)
elif op == 'reinstate':
exempt = 0
update.update_feed_exempt(feed_uid, exempt)
elif op == 'catchup' and flask.request.form.get('confirm') == 'yes':
update.catch_up(feed_uid)
back = flask.request.args.get('back', '')
if back == '/feeds':
return flask.redirect(back)
notices.append('<p>Caught up successfully.</p>')
elif op == 'reload' and flask.request.form.get('confirm') == 'yes':
update.purge_reload(feed_uid)
back = flask.request.args.get('back', '')
if back == '/feeds':
return flask.redirect(back)
notices.append('<p>Purged and reloaded successfully.</p>')
with dbop.db() as c:
# Get feed statistics
row = dbop.feed_info_sql(c, feed_uid).fetchone()
(feed_title, feed_desc, feed_filter, feed_html, feed_xml, feed_pubxml,
delta_t, interesting, unread, uninteresting, filtered, total, status,
private, exempt, dupcheck, feed_errors) = row
feed_pubxml = feed_pubxml or ''
feed_filter = feed_filter or ''
since_when = since(delta_t)
unread = int(unread)
interesting = int(interesting)
uninteresting = int(uninteresting)
filtered = int(filtered)
total = int(total)
if interesting + uninteresting > 0:
ratio = interesting * 100 // (interesting + uninteresting)
else:
ratio = 0
assert interesting + uninteresting + unread + filtered == total, \
feed_title
uninteresting = total - unread - filtered - interesting
if feed_filter is None:
feed_filter = ''
# hard purge confirmation
if op == 'hardpurge' and flask.request.form.get('confirm') == 'yes':
status = update.hard_purge(feed_uid)
if status:
notices.append('<p>Error: %r</p>' % status)
else:
notices.append('<p>Deleted <a href="%s">%s</a></p>'
% (feed_html, feed_title))
# Change feed title/html/desc/filter if requested
f = flask.request.form
if flask.request.method == 'POST':
if f.get('feed_title') and f.get('feed_title') != feed_title:
feed_title = f.get('feed_title')
update.update_feed_title(feed_uid, feed_title)
notices.append('<p>Feed title updated successfully.</p>')
if f.get('feed_html') and f.get('feed_html') != feed_html:
feed_html = f.get('feed_html')
update.update_feed_html(feed_uid, feed_html)
notices.append('<p>Feed HTML link updated successfully.</p>')
if f.get('feed_desc') and f.get('feed_desc') != feed_desc:
feed_desc = f.get('feed_desc')
update.update_feed_desc(feed_uid, feed_desc)
notices.append('<p>Feed description updated successfully.</p>')
if f.get('feed_filter') and f.get('feed_filter') != feed_filter:
feed_filter = f.get('feed_filter')
update.update_feed_filter(feed_uid, feed_filter)
notices.append('<p>Feed filter updated successfully.</p>')
if f.get('feed_pubxml') and f.get('feed_pubxml') != feed_pubxml:
feed_pubxml = f.get('feed_pubxml')
update.update_feed_pubxml(feed_uid, feed_pubxml)
notices.append('<p>Feed public XML link updated successfully.</p>')
# Change feed URL if requested
if op == 'refresh' or (
flask.request.method == 'POST'
and flask.request.form.get('feed_xml')
and flask.request.form.get('feed_xml') != feed_xml
):
try:
num_added, num_filtered = update.update_feed_xml(
feed_uid, flask.request.form.get('feed_xml', feed_xml))
unread += num_added
filtered += num_filtered
feed_errors = 0
notices.append('<p>Feed refreshed successfully.</p>')
if status == 1:
status = 0
update.set_status(feed_uid, status)
notices.append('<p>Feed reactivated</p>')
if num_added > 0:
notices.append("""<p>%d new unread articles.
<a href="/view?feed_uid=%d">view articles now</a>
<a href="/feed/%d/catchup">catch up</a></p>"""
% (unread, feed_uid, feed_uid))
except update.ParseError:
notices.append('<p><b>Connection or parse error in attempting to'
+ 'subscribe to</b> %s, check URL</p>' % feed_xml)
except update.FeedAlreadyExists:
notices.append('<p>The feed %s ' % feed_xml
+ 'is already assigned to another feed,'
+ 'check for duplicates.</p>')
except update.UnknownError as e:
notices.append('<p>Unknown error:<p>\n<pre>%s</pre>\n' % e.args[0])
feed_public = None
hidden = regurgitate_except()
# Display feed flags with option to change it
if status == 0:
status_text = 'Active'
status_change_op = 'suspend'
elif status == 1:
status_text = 'Suspended'
status_change_op = 'activate'
else:
status_text = 'Unknown'
status_change_op = 'activate'
if private == 0:
private_text = 'Public'
private_change_op = 'private'
elif private == 1:
private_text = 'Private'
private_change_op = 'public'
else:
private_text = 'Unknown'
private_change_op = 'private'
if exempt == 0:
exempt_text = 'Not exempt'
exempt_change_op = 'exempt'
elif exempt == 1:
exempt_text = 'Exempt'
exempt_change_op = 'reinstate'
else:
exempt_text = 'Unknown'
exempt_change_op = 'exempt'
# Get top rules
top_rules = dbop.top_rules(c, feed_uid)
feed_rules = dbop.rules(c, feed_uid)
return flask.render_template(
'feed.html', filters=filters,
len=len, max=max, **locals()
)
@app.route("/feed_debug/<int:feed_uid>", methods=['GET'])
def feed_debug(feed_uid):
with dbop.db() as c:
row = dbop.feed_info_sql(c, feed_uid).fetchone()
(feed_title, feed_desc, feed_filter, feed_html, feed_xml, feed_pubxml,
delta_t, interesting, unread, uninteresting, filtered, total, status,
private, exempt, dupcheck, feed_errors) = row
f = feedparser.parse(feed_xml)
normalize.normalize_all(f)
pprinted = pprint.pformat(f)
return flask.render_template(
'feed_debug.html',
len=len, max=max, **locals()
)
@app.route("/feeds")
def feeds():
sort_key = flask.request.args.get('sort', '(unread > 0) DESC, snr')
if sort_key == 'feed_title':
sort_key = 'lower(feed_title)'
order = flask.request.args.get('order', 'DESC')
with dbop.db() as db:
rows = dbop.feeds(db, sort_key, order)
sum_unread = sum(int(row['unread']) for row in rows)
sum_filtered = sum(int(row['filtered']) for row in rows)
sum_interesting = sum(int(row['interesting']) for row in rows)
sum_total = sum(int(row['total']) for row in rows)
return flask.render_template('feeds.html',
since=since, int=int, repr=repr,
**locals())
@app.route("/rules")
def rules():
with dbop.db() as db:
c = db.cursor()
feed_rules = dbop.rules(c, None)
return flask.render_template(
'rules.html', filters=filters,
len=len, max=max, **locals()
)
@app.route("/rule/<int:rule_uid>/<op>")
def rule_op(rule_uid, op):
with dbop.db() as db:
c = db.cursor()
if op == 'del':
filters.del_kw_rule(db, c, rule_uid)
return '<?xml version="1.0"?><nothing />'
@app.route("/rule/add", methods=['POST'])
def rule_add():
with dbop.db() as db:
c = db.cursor()
filters.add_kw_rule(db, c, **(flask.request.form.to_dict()))
db.commit()
return '<?xml version="1.0"?><nothing />'
@app.route("/add", methods=['GET', 'POST'])
def add_feed():
if flask.request.method == 'POST':
feed_xml = flask.request.form.get('feed_xml', '').strip()
if feed_xml:
with dbop.db() as db:
c = db.cursor()
try:
feed_uid, feed_title, num_added, num_filtered \
= update.add_feed(feed_xml)
except update.ParseError:
feed_err = 'Connection or parse error in subcription attempt.'
resolution= 'check URL'
except update.AutoDiscoveryError:
feed_err = 'Autodiscovery failed.'
resolution = 'you need to find a valid feed URL'
except update.FeedAlreadyExists:
feed_err = 'The feed URL is already assigned to another feed.'
resolution = 'check for duplicates'
except requests.exceptions.RequestException as e:
feed_err = 'Error loading URL during autodiscovery attempt: %r' % e
except update.UnknownError as e:
feed_err = 'Unknown error: %r' % e.args[0]
return flask.render_template(
'add.html', filters=filters,
len=len, max=max, **locals()
)
@app.route("/settings", methods=['GET', 'POST'])
def settings(status=''):
op = flask.request.form.get('op', '') or flask.request.args.get('op', '')
with dbop.db() as db:
c = db.cursor()
if op == 'refresh':
__main__.updater.event.set()
status = 'Manual refresh of all feeds requested.'
elif op == 'debug':
if flask.request.form.get('debug', '') == 'Disable verbose logging':
setattr(param, 'debug', False)
else:
setattr(param, 'debug', True)
elif op == 'facebook':
api_key = flask.request.form.get('api_key', '').strip()
if api_key:
dbop.setting(db, c, fb_api_key=api_key)
app_id = flask.request.form.get('app_id', '').strip()
if app_id:
dbop.setting(db, c, fb_app_id=app_id)
fb_secret = flask.request.form.get('fb_secret', '').strip()
if fb_secret:
dbop.setting(db, c, fb_secret=fb_secret)
elif op == 'del_token':
dbop.setting(db, c, fb_token='')
elif op == 'maint':
dbop.snr_mv(db, c)
db.commit()
stats = filters.stats(c)
return flask.render_template(
'settings.html', filters=filters,
executable=sys.argv[0], py_version=sys.version,
param_debug=param.debug, param_settings=param.settings,
started=__main__.started,
uptime=datetime.datetime.now()-__main__.started,
fts5_enabled=getattr(dbop, 'fts_enabled'),
len=len, max=max, **locals()
)
@app.route("/stats")
def stats():
with dbop.db() as db:
c = db.cursor()
rows = dbop.stats(c)
csvfile = io.StringIO()
out = csv.writer(csvfile, dialect='excel', delimiter=',')
out.writerow([col[0].capitalize() for col in c.description])
for row in c:
out.writerow(row)
try:
return (csvfile.getvalue(), 200, {'Content-Type': 'text/csv'})
finally:
csvfile.close()
@app.route("/_share")
def mylos():
with dbop.db() as db:
c = db.cursor()
last = dbop.share(c)
return flask.render_template(
'_share.atom', time=time, normalize=normalize,
atom_content=atom_content, **locals()
)
@app.route("/threads")
def threads():
frames = sys._current_frames()
try:
return flask.render_template(
'threads.html', sys=sys, pprint=pprint, traceback=traceback,
sorted=sorted, **locals()
)
finally:
del frames
@app.route("/stem")
def stem():
term = flask.request.args.get('q', '')
stem = ' '.join(normalize.stem(normalize.get_words(term)))
return (stem, 200, {'Content-Type': 'text/plain'})
@app.route("/opml")
def opml():
sort_key = flask.request.args.get('sort', '(unread > 0) DESC, snr')
if sort_key == 'feed_title':
sort_key = 'lower(feed_title)'
order = flask.request.args.get('order', 'DESC')
with dbop.db() as db:
rows = dbop.opml(db)
return (flask.render_template('opml.opml',
atom_content=atom_content, rows=rows),
200 , {'Content-Type': 'text/plain'})
@app.route("/item/<int:uid>/<op>", methods=['GET', 'POST'])
def item(uid, op):
assert op == 'edit'
status = None
if flask.request.method == 'POST':
assert check_nonce('edit%d' % uid, flask.request.form.get('nonce'))
| |
<gh_stars>0
import os
import numpy as np
import skimage
from PIL import Image
import matplotlib.pyplot as plt
import time
import zipfile
import urllib.request
import shutil
import json
import shutil
from IPython.display import clear_output
import datetime
from enum import Enum
# COCO tools
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from pycocotools import mask as maskUtils
from pycococreatortools import pycococreatortools
# Other .py
import utils
from config import Config
import model as modellib
import mail
# DIRECTORIES
ROOT_DIR = os.getcwd() # Root directory of the project
XAVI_DIR = os.path.join(os.getcwd(), "XAVI_Dataset") # Xavi Dataset directory
MODEL_DIR = os.path.join(XAVI_DIR, "model") # Directory to save trained model
DEFAULT_LOGS_DIR = os.path.join(MODEL_DIR, "logs") # Directory to save logs
MODEL_FILE = os.path.join(MODEL_DIR, "mask_rcnn_xavi.h5") # Local path to trained weights file
DEFAULT_TRAINING_SUBSET = "train512"
DEFAULT_VALIDATION_SUBSET = "val512"
class MasksType(Enum):
ON_THE_FLY = 1
PNG = 2
ANNOTATIONS = 3
class XaviConfig(Config):
NAME = "xavi512"
BACKBONE = "resnet101"
IMAGES_PER_GPU = 1
STEPS_PER_EPOCH = 5000
TRAIN_ROIS_PER_IMAGE = 200
RPN_ANCHOR_SCALES = (16, 32, 64, 128, 256)
IMAGE_MIN_DIM = 512
IMAGE_MAX_DIM = 512
DETECTION_MIN_CONFIDENCE = 0.8 # Skip detections with < 80% confidence
def __init__(self, json_categories):
XaviConfig.NUM_CLASSES = 1 + len(json_categories) # Background + json classes
super(XaviConfig, self).__init__()
class XaviDataset(utils.Dataset):
# --------------------- Load Dataset ---------------------------
def load_xavi(self, dataset_dir, subset, type_masks=MasksType.PNG, json_categories = None, size_image = None, class_ids = None):
self.main_dir = dataset_dir
self.subset = subset
self.dataset_dir = os.path.join(dataset_dir, subset)
self.type_masks = type_masks
# Subdirs
self.rgb_dir = os.path.join(self.dataset_dir, "RGB")
self.cat_dir = os.path.join(self.dataset_dir, "Categories")
self.seg_dir = os.path.join(self.dataset_dir, "Segmentation")
self.msk_dir = os.path.join(self.dataset_dir, "Masks")
if type_masks == MasksType.PNG or type_masks == MasksType.ON_THE_FLY:
assert(json_categories != None and size_image != None)
self.load_categories(json_categories, size_image)
elif type_masks == MasksType.ANNOTATIONS:
self.load_annotations(class_ids)
# Load classes from categories.json
def load_categories(self, json_categories, size_image):
self.json_categories = json_categories
for i, cat in enumerate(self.json_categories):
self.add_class("xavi", i + 1, cat['name'])
# Add rgb images from RGB folder
self.size_image = size_image
width, height = size_image
for i, filename in enumerate(os.listdir(self.rgb_dir)):
image_path = os.path.join(self.rgb_dir, filename)
self.add_image(
"xavi",
image_id = i + 1,
path = image_path,
width = width,
height = height)
# Load classes from annotations.json
# Select subset of classes
def load_annotations(self, class_ids):
# Load json of annotations
coco = COCO(os.path.join(self.dataset_dir, "annotations.json"))
# All images or a subset?
if class_ids:
image_ids = []
for id in class_ids:
image_ids.extend(list(coco.getImgIds(catIds=[id])))
# Remove duplicates
image_ids = list(set(image_ids))
else:
# All images
class_ids = sorted(coco.getCatIds())
image_ids = list(coco.imgs.keys())
# Add classes
for i in class_ids:
self.add_class("xavi", i, coco.loadCats(i)[0]["name"])
# Add images
for i in image_ids:
self.add_image(
"xavi", image_id=i,
path=os.path.join(self.rgb_dir, coco.imgs[i]['file_name']),
width=coco.imgs[i]["width"],
height=coco.imgs[i]["height"],
annotations=coco.loadAnns(coco.getAnnIds(
imgIds=[i], catIds=class_ids, iscrowd=None)))
# --------------------- Get Masks ---------------------------
def load_mask(self, image_id):
if self.type_masks == MasksType.ON_THE_FLY:
return self.load_mask_on_the_fly(image_id)
elif self.type_masks == MasksType.PNG:
return self.load_mask_png(image_id)
elif self.type_masks == MasksType.ANNOTATIONS:
return self.load_mask_annotations(image_id)
else:
raise Exception("Invalid value for type of masks:" + str(self.type_masks))
def load_mask_on_the_fly(self, image_id):
masks, class_ids = self.generate_mask(image_id)
if masks.size == 0:
return super(XaviDataset, self).load_mask(image_id)
else:
return masks, class_ids
def load_mask_png(self, image_id):
image_dir = os.path.join(self.msk_dir, os.path.splitext(os.path.basename(self.image_info[image_id]['path']))[0])
class_ids = []
masks = []
for i, filename in enumerate(os.listdir(image_dir)):
# Mask
mask = np.array(Image.open(os.path.join(image_dir, filename)), dtype=np.uint8) // 255
masks.append(mask)
# Class
image_class = filename[0:filename.rfind('_')]
class_ids.append(self.class_names.index(image_class))
if len(masks) == 0:
return super(XaviDataset, self).load_mask(image_id)
else:
return np.stack(masks, axis=2), np.array(class_ids, dtype=np.int32)
def load_mask_annotations(self, image_id):
image_info = self.image_info[image_id]
instance_masks = []
class_ids = []
annotations = self.image_info[image_id]["annotations"]
# Build mask of shape [height, width, instance_count] and list
# of class IDs that correspond to each channel of the mask.
for annotation in annotations:
class_id = self.map_source_class_id(
"xavi.{}".format(annotation['category_id']))
if class_id:
m = self.annToMask(annotation, image_info["height"],
image_info["width"])
# Some objects are so small that they're less than 1 pixel area
# and end up rounded out. Skip those objects.
if m.max() < 1:
continue
# Is it a crowd? If so, use a negative class ID.
if annotation['iscrowd']:
# Use negative class ID for crowds
class_id *= -1
# For crowd masks, annToMask() sometimes returns a mask
# smaller than the given dimensions. If so, resize it.
if m.shape[0] != image_info["height"] or m.shape[1] != image_info["width"]:
m = np.ones([image_info["height"], image_info["width"]], dtype=bool)
instance_masks.append(m)
class_ids.append(class_id)
# Pack instance masks into an array
if class_ids:
mask = np.stack(instance_masks, axis=2)
class_ids = np.array(class_ids, dtype=np.int32)
return mask, class_ids
else:
# Call super class to return an empty mask
return super(XaviDataset, self).load_mask(image_id)
# Compute BW individual masks from Category and Segmentation images
def generate_mask(self, image_id):
def only_color(color, image):
r = color[0]
g = color[1]
b = color[2]
RESULT = np.where(image[:,:,0] == r, 1, 0) * np.where(image[:,:,1] == g, 1, 0) * np.where(image[:,:,2] == b, 1, 0)
return np.array(RESULT, dtype=np.uint8)
image_name = os.path.splitext(os.path.basename(self.image_info[image_id]['path']))[0] + ".png"
CAT_IMAGE = np.array(Image.open(os.path.join(self.cat_dir, image_name)), dtype=np.uint8)
SEG_IMAGE = np.array(Image.open(os.path.join(self.seg_dir, image_name)), dtype=np.uint8)
categories = self.json_categories
class_ids = []
masks = []
i = 1
for cat in categories:
# Get category mask
MASK_CATEGORY = only_color(cat['color'], CAT_IMAGE)
# Leave only one category in segmentation image
SEG_IMAGE2 = np.copy(SEG_IMAGE)
SEG_IMAGE2[:,:,0] *= MASK_CATEGORY
SEG_IMAGE2[:,:,1] *= MASK_CATEGORY
SEG_IMAGE2[:,:,2] *= MASK_CATEGORY
# Compute colors left
diff_colors = np.unique(SEG_IMAGE2.reshape(-1, SEG_IMAGE2.shape[2]), axis=0)
for color in diff_colors:
# if color is not black
if color[0] != 0 or color[1] != 0 or color[2] != 0:
MASK_SEGMENTATION = only_color(color, SEG_IMAGE2)
masks.append(MASK_SEGMENTATION)
# Since classes are loaded from the same json, they are in the same order
class_ids.append(i)
i += 1
return np.stack(masks, axis=2), np.array(class_ids, dtype=np.int32)
# Convert annotation which can be polygons, uncompressed RLE to RLE
# From pycocotools with a few changes.
def annToRLE(self, ann, height, width):
segm = ann['segmentation']
if isinstance(segm, list):
# polygon -- a single object might consist of multiple parts
# we merge all parts into one mask rle code
rles = maskUtils.frPyObjects(segm, height, width)
rle = maskUtils.merge(rles)
elif isinstance(segm['counts'], list):
# uncompressed RLE
rle = maskUtils.frPyObjects(segm, height, width)
else:
# rle
rle = ann['segmentation']
return rle
# Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask
# From pycocotools with a few changes.
def annToMask(self, ann, height, width):
rle = self.annToRLE(ann, height, width)
m = maskUtils.decode(rle)
return m
# --------------------- Clean Dataset ---------------------------
# Removes images with no classes from the dataset
def remove_black_images(self, target_path):
# Find black images
black_images = self.get_no_class()
# Subfolders
t_rgb_folder = os.path.join(target_path, "RGB")
t_cat_folder = os.path.join(target_path, "Categories")
t_seg_folder = os.path.join(target_path, "Segmentation")
# Create folders
if not os.path.exists(t_rgb_folder):
os.makedirs(t_rgb_folder)
if not os.path.exists(t_cat_folder):
os.makedirs(t_cat_folder)
if not os.path.exists(t_seg_folder):
os.makedirs(t_seg_folder)
# Move black images
for image in black_images:
shutil.move(os.path.join(self.rgb_dir, image + ".jpg"), os.path.join(t_rgb_folder, image + ".jpg"))
shutil.move(os.path.join(self.cat_dir, image + ".png"), os.path.join(t_cat_folder, image + ".png"))
shutil.move(os.path.join(self.seg_dir, image + ".png"), os.path.join(t_seg_folder, image + ".png"))
print("Number of Images removed from dataset: " + str(len(black_images)))
# Returns list of images with no classes
def get_no_class(self):
no_class = []
for i, filename in enumerate(os.listdir(self.cat_dir)):
image = Image.open(os.path.join(self.cat_dir, filename))
if not image.getbbox():
no_class.append(os.path.splitext(os.path.basename(filename))[0])
return no_class
# Generate Masks as PNGs
def GeneratePngMasks(self):
# Create folder
if not os.path.exists(self.msk_dir):
os.makedirs(self.msk_dir)
start = time.time()
# for each image
for i, image_id in enumerate(self.image_ids):
image_masks, image_classes = self.generate_mask(image_id)
image_dir = os.path.join(self.msk_dir, os.path.splitext(os.path.basename(self.image_info[image_id]['path']))[0])
# Create folder
if not os.path.exists(image_dir):
os.makedirs(image_dir)
# for each mask
for j, image_class in enumerate(image_classes):
Image.fromarray(image_masks[:,:,j] * 255).save(os.path.join(image_dir, self.class_names[image_class] + "_" + str(j) + ".png"), "PNG")
if(i % 100 == 0):
print("Count: {:7} / {:7} \t || Time from start: {:7}".format(i, self.num_images, str(round( time.time() - start, 2))))
clear_output(wait=True)
print("Finished generating masks. Time elapsed: " + str(round( time.time() - start, 2)))
# Convert PNG generated masks to annotations.json
def PngMasksToAnnotations(self, description = "Xavi Dataset"):
coco_output = {}
# info
coco_output['info'] = {
"description": description,
"url": "",
"version": "1.0",
"year": 2021,
"contributor": "Xavi",
"date_created": datetime.datetime.utcnow().isoformat(' ')
}
# licenses
coco_output['licenses'] = []
coco_output['licenses'].append({
"id": 1,
"name": "Attribution-NonCommercial-ShareAlike License",
"url": "http://creativecommons.org/licenses/by-nc-sa/2.0/"
})
# categories
coco_output['categories'] = []
class_ids = {}
for i, category in enumerate(self.json_categories):
coco_output['categories'].append({
'id': (i + 1),
'name': category['name'],
})
class_ids[category['name']] = (i + 1)
# images and annotations
rgb_images = os.listdir(self.rgb_dir)
n_images = len(rgb_images)
segmentation_id = 1
start = time.time()
coco_output["images"] = []
coco_output["annotations"] = []
# go through each RGB image
for i, rgb_image in enumerate(rgb_images):
# Image info
image_id = i + 1
image_info = pycococreatortools.create_image_info(
image_id, # | |
E501
# verify the required parameter 'uuid' is set
if self.api_client.client_side_validation and ('uuid' not in local_var_params or # noqa: E501
local_var_params['uuid'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `uuid` when calling `get_run_clones_lineage`") # noqa: E501
collection_formats = {}
path_params = {}
if 'owner' in local_var_params:
path_params['owner'] = local_var_params['owner'] # noqa: E501
if 'entity' in local_var_params:
path_params['entity'] = local_var_params['entity'] # noqa: E501
if 'uuid' in local_var_params:
path_params['uuid'] = local_var_params['uuid'] # noqa: E501
query_params = []
if 'offset' in local_var_params and local_var_params['offset'] is not None: # noqa: E501
query_params.append(('offset', local_var_params['offset'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'sort' in local_var_params and local_var_params['sort'] is not None: # noqa: E501
query_params.append(('sort', local_var_params['sort'])) # noqa: E501
if 'query' in local_var_params and local_var_params['query'] is not None: # noqa: E501
query_params.append(('query', local_var_params['query'])) # noqa: E501
if 'no_page' in local_var_params and local_var_params['no_page'] is not None: # noqa: E501
query_params.append(('no_page', local_var_params['no_page'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['ApiKey'] # noqa: E501
return self.api_client.call_api(
'/api/v1/{owner}/{entity}/runs/{uuid}/lineage/clones', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ListRunsResponse', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def get_run_connections_lineage(self, owner, entity, uuid, **kwargs): # noqa: E501
"""Get run connections lineage # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_run_connections_lineage(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str entity: Entity name under namesapce (required)
:param str uuid: SubEntity uuid (required)
:param int offset: Pagination offset.
:param int limit: Limit size.
:param str sort: Sort to order the search.
:param str query: Query filter the search.
:param bool no_page: No pagination.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ListRunConnectionsResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.get_run_connections_lineage_with_http_info(owner, entity, uuid, **kwargs) # noqa: E501
def get_run_connections_lineage_with_http_info(self, owner, entity, uuid, **kwargs): # noqa: E501
"""Get run connections lineage # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_run_connections_lineage_with_http_info(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str entity: Entity name under namesapce (required)
:param str uuid: SubEntity uuid (required)
:param int offset: Pagination offset.
:param int limit: Limit size.
:param str sort: Sort to order the search.
:param str query: Query filter the search.
:param bool no_page: No pagination.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ListRunConnectionsResponse, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'owner',
'entity',
'uuid',
'offset',
'limit',
'sort',
'query',
'no_page'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method get_run_connections_lineage" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'owner' is set
if self.api_client.client_side_validation and ('owner' not in local_var_params or # noqa: E501
local_var_params['owner'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `owner` when calling `get_run_connections_lineage`") # noqa: E501
# verify the required parameter 'entity' is set
if self.api_client.client_side_validation and ('entity' not in local_var_params or # noqa: E501
local_var_params['entity'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `entity` when calling `get_run_connections_lineage`") # noqa: E501
# verify the required parameter 'uuid' is set
if self.api_client.client_side_validation and ('uuid' not in local_var_params or # noqa: E501
local_var_params['uuid'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `uuid` when calling `get_run_connections_lineage`") # noqa: E501
collection_formats = {}
path_params = {}
if 'owner' in local_var_params:
path_params['owner'] = local_var_params['owner'] # noqa: E501
if 'entity' in local_var_params:
path_params['entity'] = local_var_params['entity'] # noqa: E501
if 'uuid' in local_var_params:
path_params['uuid'] = local_var_params['uuid'] # noqa: E501
query_params = []
if 'offset' in local_var_params and local_var_params['offset'] is not None: # noqa: E501
query_params.append(('offset', local_var_params['offset'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'sort' in local_var_params and local_var_params['sort'] is not None: # noqa: E501
query_params.append(('sort', local_var_params['sort'])) # noqa: E501
if 'query' in local_var_params and local_var_params['query'] is not None: # noqa: E501
query_params.append(('query', local_var_params['query'])) # noqa: E501
if 'no_page' in local_var_params and local_var_params['no_page'] is not None: # noqa: E501
query_params.append(('no_page', local_var_params['no_page'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['ApiKey'] # noqa: E501
return self.api_client.call_api(
'/api/v1/{owner}/{entity}/runs/{uuid}/lineage/connections', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ListRunConnectionsResponse', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def get_run_downstream_lineage(self, owner, entity, uuid, **kwargs): # noqa: E501
"""Get run downstream lineage # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_run_downstream_lineage(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str entity: Entity name under namesapce (required)
:param str uuid: SubEntity uuid (required)
:param int offset: Pagination offset.
:param int limit: Limit size.
:param str sort: Sort to order the search.
:param str query: Query filter the search.
:param bool no_page: No pagination.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ListRunEdgesResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.get_run_downstream_lineage_with_http_info(owner, entity, uuid, **kwargs) # noqa: E501
def get_run_downstream_lineage_with_http_info(self, owner, entity, uuid, **kwargs): # noqa: E501
"""Get run downstream lineage # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_run_downstream_lineage_with_http_info(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str entity: Entity name under namesapce (required)
:param str uuid: SubEntity uuid (required)
:param int offset: Pagination offset.
:param int limit: Limit size.
:param str sort: Sort to order the search.
:param str query: Query filter the search.
:param bool no_page: No pagination.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ListRunEdgesResponse, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'owner',
'entity',
'uuid',
'offset',
'limit',
'sort',
'query',
'no_page'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
| |
<gh_stars>1-10
import argparse
import csv
import itertools
import os
import re
import sys
import time
from collections import defaultdict
from io import StringIO, BytesIO
from logging import FileHandler
from urllib import parse as urlparse
from cached_property import cached_property
from egcg_core import rest_communication, app_logging
from egcg_core.config import cfg
from egcg_core.notifications import email
from pyclarity_lims.entities import Process, Artifact, Protocol
from pyclarity_lims.lims import Lims
from requests import HTTPError
from requests.exceptions import ConnectionError
import EPPs
from EPPs.config import load_config
class InvalidStepError(Exception):
"""Exception raised when error occurred during the script due to the step being Invalid"""
def __init__(self, message):
super().__init__(message)
self.message = message
class StepEPP(app_logging.AppLogger):
_etc_path = os.path.join(os.path.dirname(os.path.abspath(EPPs.__file__)), 'etc')
_lims = None
_process = None
_use_load_config = True
# Step Validation parameters
_max_nb_input_containers = None
_max_nb_output_containers = None
_max_nb_inputs = None
_nb_analytes_per_input = None
_nb_resfiles_per_input = None
_max_nb_projects = None
_max_nb_input_container_types = None
def __init__(self, argv=None):
self.argv = argv
args = self.cmd_args
split_url = urlparse.urlsplit(args.step_uri)
self.baseuri = '%s://%s' % (split_url.scheme, split_url.netloc)
self.username = args.username
self.password = <PASSWORD>
self.step_id = split_url.path.split('/')[-1]
self.open_files = []
if args.log_file:
app_logging.logging_default.add_handler(FileHandler(args.log_file))
if self._use_load_config:
load_config()
@cached_property
def cmd_args(self):
a = argparse.ArgumentParser()
a.add_argument('-u', '--username', type=str, help='The username of the person logged in')
a.add_argument('-p', '--password', type=str, help='The password used by the person logged in')
a.add_argument('-s', '--step_uri', type=str, help='The URI of the step this EPP is attached to')
a.add_argument('-l', '--log_file', type=str, help='Optional log file to append to', default=None)
self.add_args(a)
return a.parse_args(self.argv)
@staticmethod
def add_args(argparser):
"""
:param argparse.ArgumentParser argparser:
"""
pass
@cached_property
def lims(self):
return Lims(self.baseuri, self.username, self.password)
@cached_property
def process(self):
return Process(self.lims, id=self.step_id)
def step(self):
return self.process.step
@cached_property
def artifacts(self):
"""This is the input artifacts of that step"""
return self.process.all_inputs(unique=True, resolve=True)
@cached_property
def output_artifacts(self):
"""This is the output artifacts of that step"""
return self.process.all_outputs(unique=True, resolve=True)
@cached_property
def samples(self):
"""This is the samples associated with the input artifacts of that step"""
samples = [a.samples[0] for a in self.artifacts]
self.lims.get_batch(samples)
return samples
@cached_property
def projects(self):
"""This is the projects associated with the input artifacts of that step"""
return list(set([s.project for s in self.samples]))
def open_or_download_file(self, file_or_uid, encoding=None, crlf=False, binary=False):
if os.path.isfile(file_or_uid):
if binary:
f = open(file_or_uid, mode='rb')
else:
f = open(file_or_uid)
else:
a = Artifact(self.lims, id=file_or_uid)
if a.files:
if binary:
f = BytesIO(
self.lims.get_file_contents(uri=a.files[0].uri, encoding=encoding, crlf=crlf, binary=True))
else:
f = StringIO(self.lims.get_file_contents(uri=a.files[0].uri, encoding=encoding, crlf=crlf))
else:
f = None
if f:
self.open_files.append(f)
return f
def find_available_container(self, project, container_type=None, container_limit=99):
"""
Check to see if a container name is available, and recurse with incremented container numbers until an available
container name is found.
:param str project:
:param str container_type:
:param int container_limit:
"""
name_template = project + 'P%03d'
if container_type == '96 well plate':
container_limit = 999
if container_type in ['rack 96 positions', 'SGP rack 96 positions']:
name_template = project + 'R%02d'
container_limit = 99
for container_count in range(1, container_limit + 1):
new_name = name_template % container_count
if not self.lims.get_containers(name=new_name):
return new_name
raise ValueError('Cannot allocate more than %s containers of type %s ' % (container_limit, container_type))
def next_step_or_complete(self, next_actions):
"""
Assigns the next action to all artifacts as either workflow complete or the next available step.
:param next_actions:
:return: next_actions
"""
current_step = self.process.step.configuration # configuration gives the ProtocolStep entity.
protocol = Protocol(self.process.lims, uri='/'.join(self.process.step.configuration.uri.split('/')[:-2]))
steps = protocol.steps # a list of all the ProtocolSteps in protocol
# If the step is the last step in the protocol then set the next action to complete
if current_step == steps[-1]:
# for all artifacts in next_actions update the action to "complete"
for next_action in next_actions:
next_action['action'] = 'complete'
# If the step is not the last step in the protocol then set the next action to the next step
# and assign the identity of that step with the step_object
else:
step_object = steps[steps.index(current_step) + 1]
# for all artifacts in next_actions update the action to "next step" with the step
# as the next step in the protocol
for next_action in next_actions:
next_action['action'] = 'nextstep'
next_action['step'] = step_object
return next_actions
def _run(self):
raise NotImplementedError
def run(self):
try:
self._validate_step()
return self._run()
except InvalidStepError as e:
print(e.message)
sys.exit(1)
except Exception as e:
self.critical('Encountered a %s exception: %s', e.__class__.__name__, str(e))
import traceback
stacktrace = traceback.format_exc()
self.error('Stack trace below:\n' + stacktrace)
raise e
@cached_property
def input_container_names(self):
"""The name of containers from input artifacts. """
containers = set()
for art in self.artifacts:
# Check to see if artifact has a container before retrieving the container.
# Artifacts that are not samples will not have containers.
if art.container:
containers.add(art.container.name)
return sorted(containers)
@cached_property
def input_container_name_types(self):
"""The name of containers from input artifacts. """
container_types = set()
for art in self.artifacts:
# Check to see if artifact has a container before retrieving the container.
# Artifacts that are not samples will not have containers.
if art.container:
container_types.add(art.container.type.name)
return sorted(container_types)
@cached_property
def output_container_names(self):
"""The name of containers from output artifacts"""
containers = set()
for art in self.output_artifacts:
# Check to see if artifact has a container before retrieving the container.
# Artifacts that are not samples will not have containers.
if art.container:
containers.add(art.container.name)
return sorted(containers)
def _validate_step(self):
"""Perform the Step EPP's validations when required.
All validations are optionals and will require sub classes to set the corresponding varaibles:
- _max_nb_input_containers: set the maximum number of input container of the step.
- _max_nb_input_container_types: set the maximum number of input container types of the step
- _max_nb_output_containers: set the maximum number of output container of the step.
- _max_nb_input: set the maximum number of input of the step.
- _nb_analyte_per_input: set the number of replicates (Analytes) required for the step.
- _nb_resfile_per_input: set the number of replicates (ResultFiles) required for the step.
- _max_nb_project: set the maximum number of project in the step.
"""
if self._max_nb_input_containers is not None:
# check the number of input containers
if len(self.input_container_names) > self._max_nb_input_containers:
raise InvalidStepError(
'Maximum number of input container is %s. There are %s input container in the step.' % (
self._max_nb_input_containers, len(self.input_container_names)
)
)
if self._max_nb_input_container_types is not None:
# check the number of input containers
if len(self.input_container_name_types) > self._max_nb_input_container_types:
raise InvalidStepError(
'Maximum number of input container types is %s. There are %s input container types in the step.' % (
self._max_nb_input_container_types, len(self.input_container_name_types)
)
)
if self._max_nb_output_containers is not None:
# check the number of output containers
if len(self.output_container_names) > self._max_nb_output_containers:
raise InvalidStepError(
'Maximum number of output plates is %s. There are %s output plates in the step.' % (
self._max_nb_output_containers, len(self.output_container_names)
)
)
if self._max_nb_inputs is not None:
if len(self.artifacts) > self._max_nb_inputs:
raise InvalidStepError(
"Maximum number of inputs is %s. %s inputs present in step." % (
self._max_nb_inputs, len(self.artifacts)
)
)
if self._nb_analytes_per_input is not None:
for artifact in self.artifacts:
outputs = self.process.outputs_per_input(artifact.id, Analyte=True)
if len(outputs) != self._nb_analytes_per_input:
raise InvalidStepError(
"%s replicates required for each input. "
"%s replicates found for %s." % (self._nb_analytes_per_input, len(outputs), artifact.id)
)
if self._nb_resfiles_per_input is not None:
for artifact in self.artifacts:
outputs = self.process.outputs_per_input(artifact.id, ResultFile=True)
if len(outputs) != self._nb_resfiles_per_input:
raise InvalidStepError(
"%s replicates required for each input. "
"%s replicates found for %s." % (self._nb_analytes_per_input, len(outputs), artifact.id)
)
if self._max_nb_projects is not None:
if len(self.projects) > self._max_nb_projects:
raise InvalidStepError(
'Maximum number of projet in step is %s. %s projects found.' % (
self._max_nb_projects, len(self.projects)
)
)
def __del__(self):
try:
for f in self.open_files:
f.close()
except Exception:
pass
class SendMailEPP(StepEPP):
def get_email_template(self, name=None):
return os.path.join(self._etc_path, name)
def get_config(self, config_heading_1=None, config_heading_2=None, config_heading_3=None, template_name=None):
if config_heading_1 == None or config_heading_1 == 'email_notify':
if config_heading_2:
config = cfg.query('email_notify', 'default')
config.update(cfg.query('email_notify', config_heading_2))
elif not config_heading_2:
config = cfg.query(config_heading_1, 'default')
if 'email_template' not in config and template_name:
config['email_template'] = self.get_email_template(template_name)
if config_heading_1 == 'file_templates':
if config_heading_3:
config = cfg.query(config_heading_1, config_heading_2, config_heading_3)
else:
config = cfg.query(config_heading_1, config_heading_2)
return config
def send_mail(self, subject, msg, config_name=None, template_name=None, attachments=None, **kwargs):
tmp_dict = {}
tmp_dict.update(self.get_config(config_heading_2=config_name, template_name=template_name))
tmp_dict.update(kwargs)
email.send_email(msg=msg, subject=subject, strict=True, attachments=attachments, **tmp_dict)
def _run(self):
raise NotImplementedError
class RestCommunicationEPP:
@staticmethod
def _rest_interaction(func, *args, **kwargs):
try:
return func(*args, **kwargs)
except ConnectionError as ce:
print('%s: %s' % (ce.__class__.__name__, ce))
sys.exit(127)
@classmethod
def get_documents(cls, *args, **kwargs):
return cls._rest_interaction(rest_communication.get_documents, *args, **kwargs)
@classmethod
def patch_entry(cls, *args, **kwargs):
return | |
with pytest.raises(InvalidTimeDeclarationError):
chef_parser.parse_refrigerate('for 1 hours.')
with pytest.raises(InvalidTimeDeclarationError):
chef_parser.parse_refrigerate('for 2 hour.')
class TestParseLoopStart(object):
def test_valid(self):
d = chef_parser.parse_loop_start('Eat', 'the burger.')
assert d == {
'command': 'loop_start', 'verb': 'Eat', 'ingredient': 'burger'}
def test_invalid(self):
with pytest.raises(InvalidCommandError):
chef_parser.parse_loop_start('Shake', 'it.')
class TestParseLoopEnd(object):
def test_without_ingredient(self):
d = chef_parser.parse_loop_end('Bake', 'until heated.')
assert d == {
'command': 'loop_end', 'verb': 'heated', 'ingredient': None}
def test_with_ingredient(self):
# I apologize in advance to all vegetarians who are insulted by the
# following lines
d = chef_parser.parse_loop_end('Punch', 'the broccoli until killed.')
assert d == {
'command': 'loop_end', 'verb': 'killed', 'ingredient': 'broccoli'}
def test_invalid(self):
with pytest.raises(InvalidCommandError):
chef_parser.parse_loop_end('Throw', 'meat balls until gone.')
class TestParseMethod(object):
def test_single_instruction(self):
parsed_instructions, lineno = chef_parser.parse_method(
'Method.\nAdd flour to 3rd mixing bowl.', 1)
assert lineno == 2
assert len(parsed_instructions) == 1
assert parsed_instructions == [{
'command': 'add',
'ingredient': 'flour',
'mixing_bowl_id': 3,
'lineno': 2}]
def test_multiple_instructions(self):
parsed_instructions, lineno = chef_parser.parse_method(
'Method.\n'
'Add flour to 3rd mixing bowl.\n'
'Take sugar from refrigerator.', 1)
assert lineno == 3
assert len(parsed_instructions) == 2
assert parsed_instructions == [
{
'command': 'add',
'ingredient': 'flour',
'mixing_bowl_id': 3,
'lineno': 2},
{
'command': 'take',
'ingredient': 'sugar',
'lineno': 3}]
def test_parse_serves():
num_of_diners = chef_parser.parse_serves('Serves 7.', 12)
assert num_of_diners == 7
class TestParseRecipe(object):
def test_missing_first_blank_line(self):
with pytest.raises(MissingEmptyLineError) as e:
chef_parser.parse_recipe(
StringIO('The title.\nno line break here.'))
assert e.value.lineno == 2
def test_without_method(self, missing_method_recipe):
with pytest.raises(ChefSyntaxError) as e:
chef_parser.parse_recipe(missing_method_recipe)
assert e.value.msg == 'missing syntax element: method'
assert e.value.lineno == 5
def test_multiple_instructions(self, multiple_instr):
recipe = chef_parser.parse_recipe(multiple_instr)
assert recipe.ingredients == []
assert recipe.cooking_time is undefined
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{
'command': 'put',
'ingredient': 'sugar',
'mixing_bowl_id': None,
'lineno': 4},
{
'command': 'liquefy_ingredient',
'ingredient': 'sugar',
'lineno': 5},
{
'command': 'pour',
'mixing_bowl_id': None,
'baking_dish_id': None,
'lineno': 6}]
assert recipe.serves is undefined
def test_only_required_elements(self, only_title_and_method):
recipe = chef_parser.parse_recipe(only_title_and_method)
assert recipe.ingredients == []
assert recipe.cooking_time is undefined
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 4}]
assert recipe.serves is undefined
def test_description_only(self, description_only):
recipe = chef_parser.parse_recipe(description_only)
assert recipe.ingredients == []
assert recipe.cooking_time is undefined
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 10}]
assert recipe.serves is undefined
def test_ingredients_only(self, ingredients_only):
recipe = chef_parser.parse_recipe(ingredients_only)
assert recipe.ingredients == [
Ingredient('lard', IngredientProperties(108, True, False)),
Ingredient('oil', IngredientProperties(111, unknown, unknown))]
assert recipe.cooking_time is undefined
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 8}]
assert recipe.serves is undefined
def test_cooking_time_only(self, cooking_time_only):
recipe = chef_parser.parse_recipe(cooking_time_only)
assert recipe.ingredients == []
assert recipe.cooking_time == (20, 'minutes')
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 6}]
assert recipe.serves is undefined
def test_oven_temp_only(self, oven_temp_only):
recipe = chef_parser.parse_recipe(oven_temp_only)
assert recipe.ingredients == []
assert recipe.cooking_time is undefined
assert recipe.oven_temperature == (200, 5)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 6}]
assert recipe.serves is undefined
def test_serves_only(self, serves_only):
recipe = chef_parser.parse_recipe(serves_only)
assert recipe.ingredients == []
assert recipe.cooking_time is undefined
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 4}]
assert recipe.serves == 4
def test_description_and_ingredients(self, description_and_ingredients):
recipe = chef_parser.parse_recipe(description_and_ingredients)
assert recipe.ingredients == [
Ingredient('gnocchi', IngredientProperties(1, True, False)),
Ingredient('butter', IngredientProperties(2, unknown, unknown)),
Ingredient('flour', IngredientProperties(1, unknown, unknown)),
Ingredient('milk', IngredientProperties(1, unknown, unknown)),
Ingredient('cheese', IngredientProperties(4, unknown, unknown))]
assert recipe.cooking_time is undefined
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 14}]
assert recipe.serves is undefined
def test_description_and_cooking_time(self, description_and_cooking_time):
recipe = chef_parser.parse_recipe(description_and_cooking_time)
assert recipe.ingredients == []
assert recipe.cooking_time == (2, 'hours')
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 9}]
assert recipe.serves is undefined
def test_description_and_oven_temp(self, description_and_oven_temp):
recipe = chef_parser.parse_recipe(description_and_oven_temp)
assert recipe.ingredients == []
assert recipe.cooking_time is undefined
assert recipe.oven_temperature == (250, 7)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 9}]
assert recipe.serves is undefined
def test_description_and_serves_recipe(self, description_and_serves):
recipe = chef_parser.parse_recipe(description_and_serves)
assert recipe.ingredients == []
assert recipe.cooking_time is undefined
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 7}]
assert recipe.serves == 5
def test_ingredients_and_cooking_time(self, ingredients_and_cooking_time):
recipe = chef_parser.parse_recipe(ingredients_and_cooking_time)
assert recipe.ingredients == [
Ingredient('tuna', IngredientProperties(72, True, False)),
Ingredient('lettuce', IngredientProperties(2300, True, False)),
Ingredient(
'olive oil', IngredientProperties(37, unknown, unknown)),
Ingredient('peppers', IngredientProperties(18, False, False))]
assert recipe.cooking_time == (10, 'minutes')
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 12}]
assert recipe.serves is undefined
def test_ingredients_and_oven_temp(self, ingredients_and_oven_temp):
recipe = chef_parser.parse_recipe(ingredients_and_oven_temp)
assert recipe.ingredients == [
Ingredient('marshmallows', IngredientProperties(1, True, False)),
Ingredient('bananas', IngredientProperties(5, False, False)),
Ingredient('hazelnuts', IngredientProperties(3, unknown, unknown)),
Ingredient('chocolate', IngredientProperties(500, True, False))]
assert recipe.cooking_time is undefined
assert recipe.oven_temperature == (220, None)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 12}]
assert recipe.serves is undefined
def test_ingredients_and_serves(self, ingredients_and_serves):
recipe = chef_parser.parse_recipe(ingredients_and_serves)
assert recipe.ingredients == [
Ingredient('water', IngredientProperties(2, False, True)),
Ingredient('raisins', IngredientProperties(13, False, False)),
Ingredient('rum', IngredientProperties(6, False, True))]
assert recipe.cooking_time is undefined
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 9}]
assert recipe.serves == 23
def test_cooking_time_and_oven_temp(self, cooking_time_and_oven_temp):
recipe = chef_parser.parse_recipe(cooking_time_and_oven_temp)
assert recipe.ingredients == []
assert recipe.cooking_time == (45, 'minutes')
assert recipe.oven_temperature == (250, 5)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 8}]
assert recipe.serves is undefined
def test_cooking_time_and_serves(self, cooking_time_and_serves):
recipe = chef_parser.parse_recipe(cooking_time_and_serves)
assert recipe.ingredients == []
assert recipe.cooking_time == (15, 'minutes')
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 6}]
assert recipe.serves == 1
def test_oven_temp_and_serves(self, oven_temp_and_serves):
recipe = chef_parser.parse_recipe(oven_temp_and_serves)
assert recipe.ingredients == []
assert recipe.cooking_time is undefined
assert recipe.oven_temperature == (175, None)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 6}]
assert recipe.serves == 8
def test_descr_ingredients_and_cooking_time(self, descr_ingr_cooking_time):
recipe = chef_parser.parse_recipe(descr_ingr_cooking_time)
assert recipe.ingredients == [
Ingredient('apple', IngredientProperties(None, False, False)),
Ingredient('cinnamon', IngredientProperties(2, unknown, unknown)),
Ingredient(
'brown sugar', IngredientProperties(1, unknown, unknown))]
assert recipe.cooking_time == (20, 'minutes')
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 13}]
assert recipe.serves is undefined
def test_descr_ingredients_and_oven_temp(self, descr_ingr_oven_temp):
recipe = chef_parser.parse_recipe(descr_ingr_oven_temp)
assert recipe.ingredients == [
Ingredient('water', IngredientProperties(100, False, True)),
Ingredient('oranges', IngredientProperties(3, False, False)),
Ingredient('lemon juice', IngredientProperties(2, False, True)),
Ingredient(
'vanilla ice cream', IngredientProperties(250, False, True))]
assert recipe.cooking_time is undefined
assert recipe.oven_temperature == (250, None)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 16}]
assert recipe.serves is undefined
def test_descr_ingredients_and_serves(self, descr_ingr_serves):
recipe = chef_parser.parse_recipe(descr_ingr_serves)
assert recipe.ingredients == [
Ingredient('frog legs', IngredientProperties(7, False, False)),
Ingredient('spiders', IngredientProperties(23, True, False)),
Ingredient(
'zombie brains', IngredientProperties(13, False, False)),
Ingredient(
'werewolf blood', IngredientProperties(200, False, True))]
assert recipe.cooking_time is undefined
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 12}]
assert recipe.serves == 12
def test_descr_cooking_time_oven_temp(self, descr_cooking_time_oven_temp):
recipe = chef_parser.parse_recipe(descr_cooking_time_oven_temp)
assert recipe.ingredients == []
assert recipe.cooking_time == (15, 'minutes')
assert recipe.oven_temperature == (200, None)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 10}]
assert recipe.serves is undefined
def test_descr_cooking_time_and_serves(self, descr_cooking_time_serves):
recipe = chef_parser.parse_recipe(descr_cooking_time_serves)
assert recipe.ingredients == []
assert recipe.cooking_time == (7, 'hours')
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 8}]
assert recipe.serves == 5
def test_descr_oven_temp_and_serves(self, descr_oven_temp_serves):
recipe = chef_parser.parse_recipe(descr_oven_temp_serves)
assert recipe.ingredients == []
assert recipe.cooking_time is undefined
assert recipe.oven_temperature == (80, 2)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 9}]
assert recipe.serves == 1
def test_ingr_cooking_time_oven_temp(self, ingr_cooking_time_oven_temp):
recipe = chef_parser.parse_recipe(ingr_cooking_time_oven_temp)
assert recipe.ingredients == [
Ingredient('pickles', IngredientProperties(5, False, False)),
Ingredient('wheat', IngredientProperties(200, True, False))]
assert recipe.cooking_time == (25, 'minutes')
assert recipe.oven_temperature == (220, None)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 12}]
assert recipe.serves is undefined
def test_ingr_cooking_time_serves(self, ingr_cooking_time_serves):
recipe = chef_parser.parse_recipe(ingr_cooking_time_serves)
assert recipe.ingredients == [
Ingredient('girls', IngredientProperties(2, False, False)),
Ingredient('chocolate', IngredientProperties(1, unknown, unknown))]
assert recipe.cooking_time == (1, 'minute')
assert recipe.oven_temperature is undefined
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 10}]
assert recipe.serves == 2
def test_cooking_time_oven_temp_serves(self,
cooking_time_oven_temp_serves):
recipe = chef_parser.parse_recipe(cooking_time_oven_temp_serves)
assert recipe.ingredients == []
assert recipe.cooking_time == (2, 'hours')
assert recipe.oven_temperature == (130, None)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 8}]
assert recipe.serves == 7
def test_descr_ingr_cooking_time_oven_temp(self,
descr_ingr_cooking_time_oven_temp):
recipe = chef_parser.parse_recipe(descr_ingr_cooking_time_oven_temp)
assert recipe.ingredients == [
Ingredient('beer', IngredientProperties(25, False, True)),
Ingredient('mustard', IngredientProperties(5, True, False))]
assert recipe.cooking_time == (34, 'minutes')
assert recipe.oven_temperature == (85, None)
assert recipe.instructions == [
{'command': 'take', 'ingredient': 'apple', 'lineno': 14}]
assert recipe.serves is | |
<filename>unittest/scripts/auto/py_adminapi/validation/dba_cluster_help.py<gh_stars>0
#@ __global__
||
#@<OUT> cluster
NAME
Cluster - Represents an InnoDB cluster.
DESCRIPTION
The cluster object is the entry point to manage and monitor a MySQL
InnoDB cluster.
A cluster is a set of MySQLd Instances which holds the user's data.
It provides high-availability and scalability for the user's data.
PROPERTIES
name
Retrieves the name of the cluster.
FUNCTIONS
add_instance(instance[, options])
Adds an Instance to the cluster.
check_instance_state(instance)
Verifies the instance gtid state in relation to the cluster.
describe()
Describe the structure of the cluster.
disconnect()
Disconnects all internal sessions used by the cluster object.
dissolve([options])
Dissolves the cluster.
force_quorum_using_partition_of(instance[, password])
Restores the cluster from quorum loss.
get_name()
Retrieves the name of the cluster.
help([member])
Provides help about this class and it's members
list_routers([options])
Lists the Router instances.
options([options])
Lists the cluster configuration options.
rejoin_instance(instance[, options])
Rejoins an Instance to the cluster.
remove_instance(instance[, options])
Removes an Instance from the cluster.
remove_router_metadata(routerDef)
Removes metadata for a router instance.
rescan([options])
Rescans the cluster.
reset_recovery_accounts_password(options)
Reset the password of the recovery accounts of the cluster.
set_instance_option(instance, option, value)
Changes the value of an option in a Cluster member.
set_option(option, value)
Changes the value of an option for the whole Cluster.
set_primary_instance(instance)
Elects a specific cluster member as the new primary.
setup_admin_account(user, options)
Create or upgrade an InnoDB Cluster admin account.
setup_router_account(user, options)
Create or upgrade a MySQL account to use with MySQL Router.
status([options])
Describe the status of the cluster.
switch_to_multi_primary_mode()
Switches the cluster to multi-primary mode.
switch_to_single_primary_mode([instance])
Switches the cluster to single-primary mode.
For more help on a specific function use: cluster.help('<functionName>')
e.g. cluster.help('addInstance')
#@<OUT> cluster.add_instance
NAME
add_instance - Adds an Instance to the cluster.
SYNTAX
<Cluster>.add_instance(instance[, options])
WHERE
instance: Connection options for the target instance to be added.
options: Dictionary with options for the operation.
RETURNS
nothing
DESCRIPTION
This function adds an Instance to a InnoDB cluster.
For additional information on connection data use \? connection.
The options dictionary may contain the following attributes:
- label: an identifier for the instance being added
- recoveryMethod: Preferred method of state recovery. May be auto, clone
or incremental. Default is auto.
- waitRecovery: Integer value to indicate if the command shall wait for
the recovery process to finish and its verbosity level.
- password: <PASSWORD>
- memberSslMode: SSL mode used on the instance
- ipWhitelist: The list of hosts allowed to connect to the instance for
group replication. Deprecated.
- ipAllowlist: The list of hosts allowed to connect to the instance for
group replication.
- localAddress: string value with the Group Replication local address to
be used instead of the automatically generated one.
- groupSeeds: string value with a comma-separated list of the Group
Replication peer addresses to be used instead of the automatically
generated one.
- interactive: boolean value used to disable/enable the wizards in the
command execution, i.e. prompts and confirmations will be provided or
not according to the value set. The default value is equal to MySQL
Shell wizard mode.
- exitStateAction: string value indicating the group replication exit
state action.
- memberWeight: integer value with a percentage weight for automatic
primary election on failover.
- autoRejoinTries: integer value to define the number of times an
instance will attempt to rejoin the cluster after being expelled.
The password may be contained on the instance definition, however, it can
be overwritten if it is specified on the options.
The recoveryMethod option supports the following values:
- incremental: uses distributed state recovery, which applies missing
transactions copied from another cluster member. Clone will be
disabled.
- clone: clone: uses built-in MySQL clone support, which completely
replaces the state of the target instance with a full snapshot of
another cluster member before distributed recovery starts. Requires
MySQL 8.0.17 or newer.
- auto: let Group Replication choose whether or not a full snapshot has
to be taken, based on what the target server supports and the
group_replication_clone_threshold sysvar. This is the default value. A
prompt will be shown if not possible to safely determine a safe way
forward. If interaction is disabled, the operation will be canceled
instead.
ATTENTION: The memberSslMode option will be removed in a future release.
The memberSslMode option supports the following values:
- REQUIRED: if used, SSL (encryption) will be enabled for the instance to
communicate with other members of the cluster
- VERIFY_CA: Like REQUIRED, but additionally verify the server TLS
certificate against the configured Certificate Authority (CA)
certificates.
- VERIFY_IDENTITY: Like VERIFY_CA, but additionally verify that the
server certificate matches the host to which the connection is
attempted.
- DISABLED: if used, SSL (encryption) will be disabled
- AUTO: if used, SSL (encryption) will be automatically enabled or
disabled based on the cluster configuration
If memberSslMode is not specified AUTO will be used by default.
The waitRecovery option supports the following values:
- 0: do not wait and let the recovery process to finish in the
background.
- 1: block until the recovery process to finishes.
- 2: block until the recovery process finishes and show progress
information.
- 3: block until the recovery process finishes and show progress using
progress bars.
By default, if the standard output on which the Shell is running refers
to a terminal, the waitRecovery option has the value of 3. Otherwise, it
has the value of 2.
The exitStateAction option supports the following values:
- ABORT_SERVER: if used, the instance shuts itself down if it leaves the
cluster unintentionally or exhausts its auto-rejoin attempts.
- READ_ONLY: if used, the instance switches itself to super-read-only
mode if it leaves the cluster unintentionally or exhausts its
auto-rejoin attempts.
- OFFLINE_MODE: if used, the instance switches itself to offline mode if
it leaves the cluster unintentionally or exhausts its auto-rejoin
attempts. Requires MySQL 8.0.18 or newer.
If exitStateAction is not specified READ_ONLY will be used by default.
The ipAllowlist format is a comma separated list of IP addresses or
subnet CIDR notation, for example: 192.168.1.0/24,10.0.0.1. By default
the value is set to AUTOMATIC, allowing addresses from the instance
private network to be automatically set for the allowlist.
The localAddress and groupSeeds are advanced options and their usage is
discouraged since incorrect values can lead to Group Replication errors.
The value for localAddress is used to set the Group Replication system
variable 'group_replication_local_address'. The localAddress option
accepts values in the format: 'host:port' or 'host:' or ':port'. If the
specified value does not include a colon (:) and it is numeric, then it
is assumed to be the port, otherwise it is considered to be the host.
When the host is not specified, the default value is the value of the
system variable 'report_host' if defined (i.e., not 'NULL'), otherwise it
is the hostname value. When the port is not specified, the default value
is the port of the target instance * 10 + 1. In case the automatically
determined default port value is invalid (> 65535) then an error is
thrown.
The value for groupSeeds is used to set the Group Replication system
variable 'group_replication_group_seeds'. The groupSeeds option accepts a
comma-separated list of addresses in the format:
'host1:port1,...,hostN:portN'.
The value for exitStateAction is used to configure how Group Replication
behaves when a server instance leaves the group unintentionally (for
example after encountering an applier error) or exhausts its auto-rejoin
attempts. When set to ABORT_SERVER, the instance shuts itself down. When
set to READ_ONLY the server switches itself to super-read-only mode. When
set to OFFLINE_MODE it switches itself to offline mode. In this mode,
connected client users are disconnected on their next request and
connections are no longer accepted, with the exception of client users
that have the CONNECTION_ADMIN or SUPER privilege. The exitStateAction
option accepts case-insensitive string values, being the accepted values:
OFFLINE_MODE (or 2), ABORT_SERVER (or 1) and READ_ONLY (or 0).
The default value is READ_ONLY.
The | |
<reponame>xochilt/cousebuilder
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Functional tests for modules/i18n_dashboard/jobs.py."""
__author__ = [
'<EMAIL> (<NAME>)',
]
import os
import zipfile
from common import utils as common_utils
from models import courses
from modules.i18n_dashboard import jobs
from modules.i18n_dashboard import i18n_dashboard
from modules.i18n_dashboard import i18n_dashboard_tests
from tests.functional import actions
from tools.etl import etl
from tools.etl import testing
# Allow access to code under test. pylint: disable=protected-access
class _JobTestBase(
testing.EtlTestBase, i18n_dashboard_tests.CourseLocalizationTestBase):
def setUp(self):
super(_JobTestBase, self).setUp()
self.filename = os.path.join(self.test_tempdir, 'filename')
self.zipfile_name = self.filename + '.zip'
def assert_dies_if_cannot_get_app_context_for_course_url_prefix(
self, job_name, job_args=None):
bad_course_url_prefix = '/bad' + self.url_prefix
args = [
'run', 'modules.i18n_dashboard.jobs.' + job_name,
bad_course_url_prefix, 'localhost']
if job_args:
args.append(job_args)
with self.assertRaises(SystemExit):
etl.main(etl.create_args_parser().parse_args(args), testing=True)
self.assertIn(
'Unable to find course with url prefix ' + bad_course_url_prefix,
self.get_log())
def assert_ln_locale_in_course(self, response):
self.assertEqual(200, response.status_int)
self.assertIn('>ln</th>', response.body)
def assert_ln_locale_not_in_course(self, response):
self.assertEqual(200, response.status_int)
self.assertNotIn('>ln</th>', response.body)
def assert_zipfile_contains_only_ln_locale(self, filename):
with zipfile.ZipFile(filename) as zf:
files = zf.infolist()
self.assertEqual(
['locale/ln/LC_MESSAGES/messages.po'],
[f.filename for f in files])
def create_file(self, contents):
with open(self.filename, 'w') as f:
f.write(contents)
def run_job(self, name, job_args=None):
# Requires course at /first; use self._import_course().
args = ['run', name, '/first', 'localhost']
if job_args:
args.append(job_args)
etl.main(etl.create_args_parser().parse_args(args), testing=True)
def run_delete_job(self, job_args=None):
self.run_job(
'modules.i18n_dashboard.jobs.DeleteTranslations', job_args=job_args)
def run_download_job(self, job_args=None):
if not job_args:
job_args = '--job_args=' + self.zipfile_name
self.run_job(
'modules.i18n_dashboard.jobs.DownloadTranslations',
job_args=job_args)
def run_translate_job(self, job_args=None):
self.run_job(
'modules.i18n_dashboard.jobs.TranslateToReversedCase',
job_args=job_args)
def run_upload_job(self, job_args=None):
if not job_args:
job_args = '--job_args=' + self.zipfile_name
self.run_job(
'modules.i18n_dashboard.jobs.UploadTranslations', job_args=job_args)
def extract_zipfile(self):
extracted = []
with zipfile.ZipFile(self.zipfile_name) as zf:
for zipinfo in zf.infolist():
path = os.path.join(self.test_tempdir, zipinfo.filename)
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(path, 'w') as f:
fromzip = zf.open(zipinfo.filename)
f.write(fromzip.read())
extracted.append(path)
return extracted
class BaseJobTest(_JobTestBase):
def test_file_does_not_exist_when_file_does_not_exist(self):
jobs._BaseJob._check_file_does_not_exist(self.filename)
def test_file_does_not_exist_dies_when_file_exists(self):
with open(self.filename, 'w') as f:
f.write('contents')
with self.assertRaises(SystemExit):
jobs._BaseJob._check_file_does_not_exist(self.filename)
self.assertIn('File already exists', self.get_log())
def test_file_exists_when_file_exists(self):
self.create_file('contents')
jobs._BaseJob._check_file_exists(self.filename)
def test_file_exists_dies_when_file_does_not_exist(self):
with self.assertRaises(SystemExit):
jobs._BaseJob._check_file_exists(self.filename)
self.assertIn('File does not exist', self.get_log())
def test_get_app_context_or_die_gets_existing_app_context(self):
self.assertEqual(
self.url_prefix,
jobs._BaseJob._get_app_context_or_die(self.url_prefix).slug)
def test_get_app_context_or_die_dies_if_context_missing(self):
with self.assertRaises(SystemExit):
jobs._BaseJob._get_app_context_or_die('missing')
self.assertIn(
'Unable to find course with url prefix missing', self.get_log())
def get_get_locales_returns_all_locales_if_no_requested_locales(self):
self.assertEqual(
['all'],
jobs._BaseJob._get_locales([], ['requested'], 'strip', 'prefix'))
def test_get_locales_strips_default_locale(self):
self.assertEqual(
['keep'],
jobs._BaseJob._get_locales(
[], ['strip', 'keep'], 'strip', 'prefix'))
def test_get_locales_returns_sorted_locales_when_no_locales_missing(self):
self.assertEqual(
['a', 'b'],
jobs._BaseJob._get_locales(
['b', 'a'], ['b', 'a', 'strip'], 'strip', 'prefix'))
def test_get_locales_dies_if_requested_locales_missing(self):
with self.assertRaises(SystemExit):
jobs._BaseJob._get_locales(
['missing'], ['first', 'second', 'strip'], 'strip', 'prefix')
self.assertIn(
'Requested locale missing not found for course at prefix. Choices '
'are: first, second', self.get_log())
class DeleteTranslationsTest(_JobTestBase):
def test_dies_if_cannot_get_app_context_for_course_url_prefix(self):
self.assert_dies_if_cannot_get_app_context_for_course_url_prefix(
'DeleteTranslations')
def test_delete_all_locales(self):
self._import_course()
self.run_translate_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_in_course(response)
self.run_delete_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_not_in_course(response)
def test_delete_specific_locales(self):
self._import_course()
self.run_translate_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_in_course(response)
self.run_delete_job(job_args='--job_args=--locales=ln')
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_not_in_course(response)
class DownloadTranslationsTest(_JobTestBase):
def test_dies_if_cannot_get_app_context_for_course_url_prefix(self):
self.assert_dies_if_cannot_get_app_context_for_course_url_prefix(
'DownloadTranslations', '--job_args=path')
def test_dies_if_path_already_exists(self):
self.create_file('contents')
args = [
'run', 'modules.i18n_dashboard.jobs.DownloadTranslations',
self.url_prefix, 'localhost', '--job_args=%s' % self.filename]
with self.assertRaises(SystemExit):
etl.main(etl.create_args_parser().parse_args(args), testing=True)
self.assertIn('File already exists', self.get_log())
def test_download_of_course_with_no_translations_dies(self):
args = [
'run', 'modules.i18n_dashboard.jobs.DownloadTranslations',
self.url_prefix, 'localhost', '--job_args=%s' % self.zipfile_name]
with self.assertRaises(SystemExit):
etl.main(etl.create_args_parser().parse_args(args), testing=True)
self.assertIn(
'No translations found for course at %s; exiting' % self.url_prefix,
self.get_log())
def test_download_all_locales(self):
self._import_course()
self.run_translate_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_in_course(response)
self.run_download_job()
self.assert_zipfile_contains_only_ln_locale(self.zipfile_name)
def test_download_specific_locales(self):
self._import_course()
self.run_translate_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_in_course(response)
self.run_download_job('--job_args=%s --locales=ln' % self.zipfile_name)
self.assert_zipfile_contains_only_ln_locale(self.zipfile_name)
class TranslateToReversedCaseTest(_JobTestBase):
def test_dies_if_cannot_get_app_context_for_course_url_prefix(self):
self.assert_dies_if_cannot_get_app_context_for_course_url_prefix(
'TranslateToReversedCase')
class UploadTranslationsTest(_JobTestBase):
def create_zip_file(self, contents):
with zipfile.ZipFile(self.zipfile_name, 'w') as zf:
zf.writestr('filename', contents)
def test_dies_if_path_does_not_exist(self):
args = [
'run', 'modules.i18n_dashboard.jobs.UploadTranslations',
self.url_prefix, 'localhost', '--job_args=%s' % self.zipfile_name]
with self.assertRaises(IOError):
etl.main(etl.create_args_parser().parse_args(args), testing=True)
def test_dies_if_path_has_bad_file_extension(self):
args = [
'run', 'modules.i18n_dashboard.jobs.UploadTranslations',
self.url_prefix, 'localhost',
'--job_args=%s' % self.zipfile_name + '.bad']
with self.assertRaises(IOError):
etl.main(etl.create_args_parser().parse_args(args), testing=True)
def test_dies_if_cannot_get_app_context_for_course_url_prefix(self):
self.create_zip_file('contents')
args = [
'run', 'modules.i18n_dashboard.jobs.UploadTranslations',
'/bad' + self.url_prefix, 'localhost',
'--job_args=%s' % self.zipfile_name]
with self.assertRaises(SystemExit):
etl.main(etl.create_args_parser().parse_args(args), testing=True)
self.assertIn(
'Unable to find course with url prefix', self.get_log())
def test_processes_pofile(self):
self._import_course()
self.run_translate_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_in_course(response)
self.run_download_job()
self.assert_zipfile_contains_only_ln_locale(self.zipfile_name)
self.run_delete_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_not_in_course(response)
for po_file in self.extract_zipfile():
self.run_upload_job('--job_args=' + po_file)
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_in_course(response)
def test_processes_zipfile(self):
self._import_course()
self.run_translate_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_in_course(response)
self.run_download_job()
self.assert_zipfile_contains_only_ln_locale(self.zipfile_name)
self.run_delete_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_not_in_course(response)
self.run_upload_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_in_course(response)
class RoundTripTest(_JobTestBase):
"""Tests translate -> download -> delete -> upload."""
def test_round_trip(self):
self._import_course()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_not_in_course(response)
self.run_translate_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_in_course(response)
self.run_download_job()
self.assert_zipfile_contains_only_ln_locale(self.zipfile_name)
self.run_delete_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_not_in_course(response)
self.run_upload_job()
response = self.get('first/dashboard?action=i18n_dashboard')
self.assert_ln_locale_in_course(response)
def test_separate_files(self):
app_context = self._import_course()
course = courses.Course(None, app_context=app_context)
unit = course.add_unit()
lesson = course.add_lesson(unit)
lesson.objectives = 'some text'
course.save()
self.run_translate_job()
self.run_download_job('--job_args=%s --separate_files_by_type' %
self.zipfile_name)
paths = self.extract_zipfile()
actual = sorted([os.path.basename(path) for path in paths])
expected = [
'course_settings.po',
'html_hook.po',
'lesson_2.po',
'unit_1.po'
]
self.assertEquals(expected, actual)
def test_max_entries(self):
app_context = self._import_course()
course = courses.Course(None, app_context=app_context)
unit = course.add_unit()
lesson = course.add_lesson(unit)
lesson.objectives = 'some text'
course.save()
self.run_translate_job()
self.run_download_job('--job_args=%s --max_entries_per_file=6' %
self.zipfile_name)
paths = self.extract_zipfile()
actual = sorted([os.path.basename(path) for path in paths])
expected = [
'messages_001.po',
'messages_002.po',
]
self.assertEquals(expected, actual)
def test_max_entries_and_separate_files(self):
app_context = self._import_course()
course = courses.Course(None, app_context=app_context)
unit = course.add_unit()
lesson = course.add_lesson(unit)
lesson.objectives = 'some text'
course.save()
self.run_translate_job()
self.run_download_job(
'--job_args=%s --separate_files_by_type --max_entries_per_file=2' %
self.zipfile_name)
paths = self.extract_zipfile()
actual = sorted([os.path.basename(path) for path in paths])
expected = [
'course_settings_001.po',
'course_settings_002.po',
'html_hook_001.po',
'lesson_2_001.po',
'unit_1_001.po']
self.assertEquals(expected, actual)
def test_square_brackets(self):
app_context = self._import_course()
course = courses.Course(None, app_context=app_context)
assessment = course.add_assessment()
assessment.html_content = '<b>[in [square] brackets]</b>'
course.save()
self.run_translate_job()
self.run_download_job('--job_args=%s --encoded_angle_brackets' %
self.zipfile_name)
# Open the downloaded .zip file; check the contents of the .po file
# to ensure we have an HTML tag converted to square brackets, and
# that the literal square brackets in the text were escaped.
with zipfile.ZipFile(self.zipfile_name) as zf:
data = zf.read('locale/ln/LC_MESSAGES/messages.po')
lines = data.split('\n')
index = lines.index(
'msgid "[b#1]\\\\[in \\\\[square\\\\] brackets\\\\][/b#1]"')
self.assertGreater(index, -1)
# Overwrite the .zip file with a new .po file that contains a
# translated version of the text w/ square brackets, and upload.
lines[index + 1] = (
'msgstr "[b#1]\\\\[IN \\\\[ROUND\\\\] BRACKETS\\\\][/b#1]"')
data = '\n'.join(lines)
with zipfile.ZipFile(self.zipfile_name, 'w') as zf:
zf.writestr('locale/ln/LC_MESSAGES/messages.po', data)
zf.close()
self.run_upload_job('--job_args=%s --encoded_angle_brackets' %
self.zipfile_name)
# Verify that the translated version is visible in the page.
actions.login('<EMAIL>', is_admin=True)
response = self.get('first/assessment?name=%s&hl=ln' %
assessment.unit_id)
self.assertIn('<b>[IN [ROUND] BRACKETS]</b>', response.body)
def test_locale_agnostic_lifecycle(self):
app_context = self._import_course()
course = courses.Course(None, app_context=app_context)
unit = course.add_unit()
unit.title = 'Title in base language'
course.save()
extra_env = {
'extra_locales': [
{'locale': 'de', 'availability': 'available'},
{'locale': 'fr', 'availability': 'available'},
]
}
bundle_key_de = str(i18n_dashboard.ResourceBundleKey(
'unit', str(unit.unit_id), 'de'))
bundle_key_fr = str(i18n_dashboard.ResourceBundleKey(
'unit', str(unit.unit_id), 'fr'))
# Do language-agnostic export; should get locale 'gv'.
with actions.OverriddenEnvironment(extra_env):
self.run_download_job(
'--job_args=%s '
'--locale_agnostic '
'--export=all' %
self.zipfile_name)
with zipfile.ZipFile(self.zipfile_name) as zf:
data = zf.read('locale/%s/LC_MESSAGES/messages.po' %
jobs.AGNOSTIC_EXPORT_LOCALE)
lines = data.split('\n')
index = lines.index('msgid "Title in base language"')
self.assertGreater(index, -1)
# Provide 'translation' for unit title to 'German'.
lines[index + 1] = 'msgstr "Title in German"'
data = '\n'.join(lines)
with zipfile.ZipFile(self.zipfile_name, 'w') as zf:
zf.writestr('locale/%s/LC_MESSAGES/messages.po' %
jobs.AGNOSTIC_EXPORT_LOCALE, data)
zf.close()
# Run upload, forcing locale to German.
self.run_upload_job('--job_args=%s --force_locale=de' %
self.zipfile_name)
# Verify that we now have DE translation bundle.
with common_utils.Namespace(self.NAMESPACE):
bundle = i18n_dashboard.ResourceBundleDAO.load(bundle_key_de)
self.assertEquals(
'Title in German',
bundle.dict['title']['data'][0]['target_value'])
# Also upload to 'fr', which will give us the wrong content, but
# the user said "--force", so we force it.
self.run_upload_job('--job_args=%s --force_locale=fr' %
self.zipfile_name)
# Verify that we now have FR translation bundle.
with common_utils.Namespace(self.NAMESPACE):
bundle = i18n_dashboard.ResourceBundleDAO.load(bundle_key_fr)
self.assertEquals(
'Title in German',
bundle.dict['title']['data'][0]['target_value'])
# Do a locale-agnostic download, specifying all content.
# Since it's --export=all, we should get the unit title, but
# since it's locale agnostic, we should get no translated text.
os.unlink(self.zipfile_name)
with actions.OverriddenEnvironment(extra_env):
self.run_download_job(
'--job_args=%s '
'--locale_agnostic '
'--export=all' %
self.zipfile_name)
with zipfile.ZipFile(self.zipfile_name) as zf:
data = zf.read('locale/%s/LC_MESSAGES/messages.po' %
jobs.AGNOSTIC_EXPORT_LOCALE)
lines = data.split('\n')
index = lines.index('msgid "Title in base language"')
self.assertGreater(index, -1)
self.assertEquals('msgstr ""', lines[index + 1])
# Do locale-agnostic download, specifying only new content.
# We don't specificy locale, which means we should consider
# 'de' and 'fr'. But since both of those are up-to-date,
# we shouldn't see the translation for the unit title even
# appear in | |
+ m.b224 + m.b225 + m.b226 + m.b227 + m.b228 + m.b229 + m.b230 + m.b231 + m.b232
+ m.b233 + m.b234 == 1)
m.c19 = Constraint(expr= m.b235 + m.b236 + m.b237 + m.b238 + m.b239 + m.b240 + m.b241 + m.b242 + m.b243 + m.b244
+ m.b245 + m.b246 == 1)
m.c20 = Constraint(expr= m.b247 + m.b248 + m.b249 + m.b250 + m.b251 + m.b252 + m.b253 + m.b254 + m.b255 + m.b256
+ m.b257 + m.b258 == 1)
m.c21 = Constraint(expr= m.b259 + m.b260 + m.b261 + m.b262 + m.b263 + m.b264 + m.b265 + m.b266 + m.b267 + m.b268
+ m.b269 + m.b270 == 1)
m.c22 = Constraint(expr= m.b271 + m.b272 + m.b273 + m.b274 + m.b275 + m.b276 + m.b277 + m.b278 + m.b279 + m.b280
+ m.b281 + m.b282 == 1)
m.c23 = Constraint(expr= m.b283 + m.b284 + m.b285 + m.b286 + m.b287 + m.b288 + m.b289 + m.b290 + m.b291 + m.b292
+ m.b293 + m.b294 == 1)
m.c24 = Constraint(expr= m.b295 + m.b296 + m.b297 + m.b298 + m.b299 + m.b300 + m.b301 + m.b302 + m.b303 + m.b304
+ m.b305 + m.b306 == 1)
m.c25 = Constraint(expr= m.b307 + m.b308 + m.b309 + m.b310 + m.b311 + m.b312 + m.b313 + m.b314 + m.b315 + m.b316
+ m.b317 + m.b318 == 1)
m.c26 = Constraint(expr= m.b319 + m.b320 + m.b321 + m.b322 + m.b323 + m.b324 + m.b325 + m.b326 + m.b327 + m.b328
+ m.b329 + m.b330 == 1)
m.c27 = Constraint(expr= m.b331 + m.b332 + m.b333 + m.b334 + m.b335 + m.b336 + m.b337 + m.b338 + m.b339 + m.b340
+ m.b341 + m.b342 == 1)
m.c28 = Constraint(expr=-(m.b178*m.x344 + m.b179*m.x345 + m.b180*m.x346 + m.b181*m.x347 + m.b182*m.x348 + m.b183*m.x349
+ m.b184*m.x350 + m.b185*m.x351 + m.b186*m.x352) + m.x85 - 1.25*m.b175 - 1.25*m.b176
- 1.25*m.b177 == 0)
m.c29 = Constraint(expr=-(m.b190*m.x344 + m.b191*m.x345 + m.b192*m.x346 + m.b193*m.x347 + m.b194*m.x348 + m.b195*m.x349
+ m.b196*m.x350 + m.b197*m.x351 + m.b198*m.x352) + m.x91 - 1.25*m.b187 - 1.25*m.b188
- 1.25*m.b189 == 0)
m.c30 = Constraint(expr=-(m.b202*m.x344 + m.b203*m.x345 + m.b204*m.x346 + m.b205*m.x347 + m.b206*m.x348 + m.b207*m.x349
+ m.b208*m.x350 + m.b209*m.x351 + m.b210*m.x352) + m.x97 - 1.25*m.b199 - 1.25*m.b200
- 1.25*m.b201 == 0)
m.c31 = Constraint(expr=-(m.b214*m.x344 + m.b215*m.x345 + m.b216*m.x346 + m.b217*m.x347 + m.b218*m.x348 + m.b219*m.x349
+ m.b220*m.x350 + m.b221*m.x351 + m.b222*m.x352) + m.x103 - 1.25*m.b211 - 1.25*m.b212
- 1.25*m.b213 == 0)
m.c32 = Constraint(expr=-(m.b226*m.x344 + m.b227*m.x345 + m.b228*m.x346 + m.b229*m.x347 + m.b230*m.x348 + m.b231*m.x349
+ m.b232*m.x350 + m.b233*m.x351 + m.b234*m.x352) + m.x109 - 1.25*m.b223 - 1.25*m.b224
- 1.25*m.b225 == 0)
m.c33 = Constraint(expr=-(m.b238*m.x344 + m.b239*m.x345 + m.b240*m.x346 + m.b241*m.x347 + m.b242*m.x348 + m.b243*m.x349
+ m.b244*m.x350 + m.b245*m.x351 + m.b246*m.x352) + m.x115 - 1.25*m.b235 - 1.25*m.b236
- 1.25*m.b237 == 0)
m.c34 = Constraint(expr=-(m.b250*m.x344 + m.b251*m.x345 + m.b252*m.x346 + m.b253*m.x347 + m.b254*m.x348 + m.b255*m.x349
+ m.b256*m.x350 + m.b257*m.x351 + m.b258*m.x352) + m.x121 - 1.25*m.b247 - 1.25*m.b248
- 1.25*m.b249 == 0)
m.c35 = Constraint(expr=-(m.b262*m.x344 + m.b263*m.x345 + m.b264*m.x346 + m.b265*m.x347 + m.b266*m.x348 + m.b267*m.x349
+ m.b268*m.x350 + m.b269*m.x351 + m.b270*m.x352) + m.x127 - 1.25*m.b259 - 1.25*m.b260
- 1.25*m.b261 == 0)
m.c36 = Constraint(expr=-(m.b274*m.x344 + m.b275*m.x345 + m.b276*m.x346 + m.b277*m.x347 + m.b278*m.x348 + m.b279*m.x349
+ m.b280*m.x350 + m.b281*m.x351 + m.b282*m.x352) + m.x133 - 1.25*m.b271 - 1.25*m.b272
- 1.25*m.b273 == 0)
m.c37 = Constraint(expr=-(m.b286*m.x344 + m.b287*m.x345 + m.b288*m.x346 + m.b289*m.x347 + m.b290*m.x348 + m.b291*m.x349
+ m.b292*m.x350 + m.b293*m.x351 + m.b294*m.x352) + m.x139 - 1.25*m.b283 - 1.25*m.b284
- 1.25*m.b285 == 0)
m.c38 = Constraint(expr=-(m.b298*m.x344 + m.b299*m.x345 + m.b300*m.x346 + m.b301*m.x347 + m.b302*m.x348 + m.b303*m.x349
+ m.b304*m.x350 + m.b305*m.x351 + m.b306*m.x352) + m.x145 - 1.25*m.b295 - 1.25*m.b296
- 1.25*m.b297 == 0)
m.c39 = Constraint(expr=-(m.b310*m.x344 + m.b311*m.x345 + m.b312*m.x346 + m.b313*m.x347 + m.b314*m.x348 + m.b315*m.x349
+ m.b316*m.x350 + m.b317*m.x351 + m.b318*m.x352) + m.x151 - 1.25*m.b307 - 1.25*m.b308
- 1.25*m.b309 == 0)
m.c40 = Constraint(expr=-(m.b322*m.x344 + m.b323*m.x345 + m.b324*m.x346 + m.b325*m.x347 + m.b326*m.x348 + m.b327*m.x349
+ m.b328*m.x350 + m.b329*m.x351 + m.b330*m.x352) + m.x157 - 1.25*m.b319 - 1.25*m.b320
- 1.25*m.b321 == 0)
m.c41 = Constraint(expr=-(m.b334*m.x344 + m.b335*m.x345 + m.b336*m.x346 + m.b337*m.x347 + m.b338*m.x348 + m.b339*m.x349
+ m.b340*m.x350 + m.b341*m.x351 + m.b342*m.x352) + m.x163 - 1.25*m.b331 - 1.25*m.b332
- 1.25*m.b333 == 0)
m.c42 = Constraint(expr=0.705*m.x85*m.x1 + 0.25*m.x91*m.x7 - m.x1*m.x169 == 0)
m.c43 = Constraint(expr=0.705*m.x86*m.x2 + 0.25*m.x92*m.x8 - m.x2*m.x170 == 0)
m.c44 = Constraint(expr=0.705*m.x87*m.x3 + 0.25*m.x93*m.x9 - m.x3*m.x171 == 0)
m.c45 = Constraint(expr=0.705*m.x88*m.x4 + 0.25*m.x94*m.x10 - m.x4*m.x172 == 0)
m.c46 = Constraint(expr=0.705*m.x89*m.x5 + 0.25*m.x95*m.x11 - m.x5*m.x173 == 0)
m.c47 = Constraint(expr=0.705*m.x90*m.x6 + 0.25*m.x96*m.x12 - m.x6*m.x174 == 0)
m.c48 = Constraint(expr=0.125*m.x85*m.x1 + 0.625*m.x91*m.x7 + 0.125*m.x97*m.x13 + 0.08*m.x121*m.x37 + 0.045*m.x127*m.x43
- m.x7*m.x169 == 0)
m.c49 = Constraint(expr=0.125*m.x86*m.x2 + 0.625*m.x92*m.x8 + 0.125*m.x98*m.x14 + 0.08*m.x122*m.x38 + 0.045*m.x128*m.x44
- m.x8*m.x170 == 0)
m.c50 = Constraint(expr=0.125*m.x87*m.x3 + 0.625*m.x93*m.x9 + 0.125*m.x99*m.x15 + 0.08*m.x123*m.x39 + 0.045*m.x129*m.x45
- m.x9*m.x171 == 0)
m.c51 = Constraint(expr=0.125*m.x88*m.x4 + 0.625*m.x94*m.x10 + 0.125*m.x100*m.x16 + 0.08*m.x124*m.x40 + 0.045*m.x130*
m.x46 - m.x10*m.x172 == 0)
m.c52 = Constraint(expr=0.125*m.x89*m.x5 + 0.625*m.x95*m.x11 + 0.125*m.x101*m.x17 + 0.08*m.x125*m.x41 + 0.045*m.x131*
m.x47 - m.x11*m.x173 == 0)
m.c53 = Constraint(expr=0.125*m.x90*m.x6 + 0.625*m.x96*m.x12 + 0.125*m.x102*m.x18 + 0.08*m.x126*m.x42 + 0.045*m.x132*
m.x48 - m.x12*m.x174 == 0)
m.c54 = Constraint(expr=0.125*m.x91*m.x7 + 0.58*m.x97*m.x13 + 0.125*m.x103*m.x19 + 0.045*m.x121*m.x37 + 0.08*m.x127*
m.x43 + 0.045*m.x133*m.x49 - m.x13*m.x169 == 0)
m.c55 = Constraint(expr=0.125*m.x92*m.x8 + 0.58*m.x98*m.x14 + 0.125*m.x104*m.x20 + 0.045*m.x122*m.x38 + 0.08*m.x128*
m.x44 + 0.045*m.x134*m.x50 - m.x14*m.x170 == 0)
m.c56 = Constraint(expr=0.125*m.x93*m.x9 + 0.58*m.x99*m.x15 + 0.125*m.x105*m.x21 + 0.045*m.x123*m.x39 + 0.08*m.x129*
m.x45 + 0.045*m.x135*m.x51 - m.x15*m.x171 == 0)
m.c57 = Constraint(expr=0.125*m.x94*m.x10 + 0.58*m.x100*m.x16 + 0.125*m.x106*m.x22 + 0.045*m.x124*m.x40 + 0.08*m.x130*
m.x46 + 0.045*m.x136*m.x52 - m.x16*m.x172 == 0)
m.c58 = Constraint(expr=0.125*m.x95*m.x11 + 0.58*m.x101*m.x17 + 0.125*m.x107*m.x23 + 0.045*m.x125*m.x41 + 0.08*m.x131*
m.x47 + 0.045*m.x137*m.x53 - m.x17*m.x173 == 0)
m.c59 = Constraint(expr=0.125*m.x96*m.x12 + 0.58*m.x102*m.x18 + 0.125*m.x108*m.x24 + 0.045*m.x126*m.x42 + 0.08*m.x132*
m.x48 + 0.045*m.x138*m.x54 - m.x18*m.x174 == 0)
m.c60 = Constraint(expr=0.125*m.x97*m.x13 + 0.58*m.x103*m.x19 + 0.125*m.x109*m.x25 + 0.045*m.x127*m.x43 + 0.08*m.x133*
m.x49 + 0.045*m.x139*m.x55 - m.x19*m.x169 == 0)
m.c61 = Constraint(expr=0.125*m.x98*m.x14 + 0.58*m.x104*m.x20 + 0.125*m.x110*m.x26 + 0.045*m.x128*m.x44 + 0.08*m.x134*
m.x50 + 0.045*m.x140*m.x56 - m.x20*m.x170 == 0)
m.c62 = Constraint(expr=0.125*m.x99*m.x15 + 0.58*m.x105*m.x21 + 0.125*m.x111*m.x27 + 0.045*m.x129*m.x45 + 0.08*m.x135*
m.x51 + 0.045*m.x141*m.x57 - m.x21*m.x171 == 0)
m.c63 = Constraint(expr=0.125*m.x100*m.x16 + 0.58*m.x106*m.x22 + 0.125*m.x112*m.x28 + 0.045*m.x130*m.x46 + 0.08*m.x136*
m.x52 + 0.045*m.x142*m.x58 - m.x22*m.x172 == 0)
m.c64 = Constraint(expr=0.125*m.x101*m.x17 + 0.58*m.x107*m.x23 + 0.125*m.x113*m.x29 + 0.045*m.x131*m.x47 + 0.08*m.x137*
m.x53 + 0.045*m.x143*m.x59 - m.x23*m.x173 == 0)
m.c65 = Constraint(expr=0.125*m.x102*m.x18 + 0.58*m.x108*m.x24 + 0.125*m.x114*m.x30 + 0.045*m.x132*m.x48 + 0.08*m.x138*
m.x54 + 0.045*m.x144*m.x60 - m.x24*m.x174 == 0)
m.c66 = Constraint(expr=0.125*m.x103*m.x19 + 0.58*m.x109*m.x25 + 0.125*m.x115*m.x31 + 0.045*m.x133*m.x49 + 0.08*m.x139*
m.x55 - m.x25*m.x169 == 0)
m.c67 = Constraint(expr=0.125*m.x104*m.x20 + 0.58*m.x110*m.x26 + 0.125*m.x116*m.x32 + 0.045*m.x134*m.x50 + 0.08*m.x140*
m.x56 - m.x26*m.x170 == 0)
m.c68 = Constraint(expr=0.125*m.x105*m.x21 + 0.58*m.x111*m.x27 + 0.125*m.x117*m.x33 + 0.045*m.x135*m.x51 + 0.08*m.x141*
m.x57 - m.x27*m.x171 == 0)
m.c69 = Constraint(expr=0.125*m.x106*m.x22 + 0.58*m.x112*m.x28 + 0.125*m.x118*m.x34 + 0.045*m.x136*m.x52 + 0.08*m.x142*
m.x58 - m.x28*m.x172 == 0)
m.c70 = Constraint(expr=0.125*m.x107*m.x23 + 0.58*m.x113*m.x29 + 0.125*m.x119*m.x35 + 0.045*m.x137*m.x53 + 0.08*m.x143*
m.x59 - m.x29*m.x173 == 0)
m.c71 = Constraint(expr=0.125*m.x108*m.x24 + 0.58*m.x114*m.x30 + 0.125*m.x120*m.x36 + 0.045*m.x138*m.x54 + 0.08*m.x144*
m.x60 - m.x30*m.x174 == 0)
m.c72 = Constraint(expr=0.125*m.x109*m.x25 + 0.58*m.x115*m.x31 + 0.045*m.x139*m.x55 - m.x31*m.x169 == 0)
m.c73 = Constraint(expr=0.125*m.x110*m.x26 + 0.58*m.x116*m.x32 + 0.045*m.x140*m.x56 - m.x32*m.x170 == 0)
m.c74 = Constraint(expr=0.125*m.x111*m.x27 + 0.58*m.x117*m.x33 + 0.045*m.x141*m.x57 - m.x33*m.x171 == 0)
m.c75 = Constraint(expr=0.125*m.x112*m.x28 + 0.58*m.x118*m.x34 + 0.045*m.x142*m.x58 - m.x34*m.x172 == 0)
m.c76 = Constraint(expr=0.125*m.x113*m.x29 + 0.58*m.x119*m.x35 + 0.045*m.x143*m.x59 - m.x35*m.x173 == 0)
m.c77 = Constraint(expr=0.125*m.x114*m.x30 + 0.58*m.x120*m.x36 + 0.045*m.x144*m.x60 - m.x36*m.x174 == 0)
m.c78 = Constraint(expr=0.045*m.x85*m.x1 + 0.16*m.x91*m.x7 + 0.5*m.x121*m.x37 + 0.16*m.x127*m.x43 + 0.045*m.x145*m.x61
- m.x37*m.x169 == 0)
m.c79 = Constraint(expr=0.045*m.x86*m.x2 + 0.16*m.x92*m.x8 + 0.5*m.x122*m.x38 + 0.16*m.x128*m.x44 + 0.045*m.x146*m.x62
- m.x38*m.x170 == 0)
m.c80 = Constraint(expr=0.045*m.x87*m.x3 + 0.16*m.x93*m.x9 + 0.5*m.x123*m.x39 + 0.16*m.x129*m.x45 + 0.045*m.x147*m.x63
- m.x39*m.x171 == 0)
m.c81 = Constraint(expr=0.045*m.x88*m.x4 + 0.16*m.x94*m.x10 + 0.5*m.x124*m.x40 + 0.16*m.x130*m.x46 + 0.045*m.x148*m.x64
- m.x40*m.x172 == 0)
m.c82 = Constraint(expr=0.045*m.x89*m.x5 + 0.16*m.x95*m.x11 + 0.5*m.x125*m.x41 + 0.16*m.x131*m.x47 + 0.045*m.x149*m.x65
- m.x41*m.x173 == 0)
m.c83 = Constraint(expr=0.045*m.x90*m.x6 + 0.16*m.x96*m.x12 + 0.5*m.x126*m.x42 + 0.16*m.x132*m.x48 + 0.045*m.x150*m.x66
- m.x42*m.x174 == 0)
m.c84 = Constraint(expr=0.045*m.x91*m.x7 + 0.08*m.x97*m.x13 + 0.045*m.x103*m.x19 + 0.08*m.x121*m.x37 + 0.545*m.x127*
m.x43 + 0.08*m.x133*m.x49 + 0.08*m.x145*m.x61 + 0.045*m.x151*m.x67 - m.x43*m.x169 == 0)
m.c85 = Constraint(expr=0.045*m.x92*m.x8 + 0.08*m.x98*m.x14 + 0.045*m.x104*m.x20 + 0.08*m.x122*m.x38 + 0.545*m.x128*
m.x44 + 0.08*m.x134*m.x50 + 0.08*m.x146*m.x62 + 0.045*m.x152*m.x68 - m.x44*m.x170 == 0)
m.c86 = Constraint(expr=0.045*m.x93*m.x9 + 0.08*m.x99*m.x15 + 0.045*m.x105*m.x21 | |
# -*- coding: utf-8 -*-
from __future__ import annotations
import llvmlite.ir as ir
import numpy as np
from ctypes import c_float, POINTER, pointer, byref, addressof, c_double, c_int32
from .utils import LRValue, uuname, BinaryOpr, UnaryOpr, biopr_map, LoopCtx, unopr_map
from . import global_records as gr
from .typing import DType, type_map_llvm, type_cast_llvm, build_type_cast
from typing import Optional, Set, Iterable, Tuple, List, Union
from math import ceil
int_type = ir.IntType(32)
class Node():
"""Base class for all kinds of nodes
"""
size: int
name: str
label: str
dtype: DType
vtype: LRValue
dependence: Set[Node]
iter_ind: int
def __init__(
self,
size: int,
name: str,
dtype: DType,
vtype: LRValue = LRValue.RIGHT
) -> None:
super().__init__()
self.size = size
self.name = uuname(name)
self.label = name
self.dtype = dtype
self.vtype = vtype
self.gened = False
self.dependence: Set[Node] = set()
# leave a record of initilizing itself
gr._append({"type": "make", "target": self})
# -------------------------------------------
# Basic operations
# -------------------------------------------
def allocate(self, builder: ir.IRBuilder) -> None:
"""Use IRBuilder to allocate memory of 'size' and use self.alloc as the pointer,
Need twice of space for complex data.
Should be called at the graph level.
"""
if self.dtype in (DType.Int, DType.Float, DType.Double):
self.alloc = builder.alloca(
type_map_llvm[self.dtype],
self.size,
self.name+"-data"
)
else: # Complx or DComplx
self.alloc = builder.alloca(
type_map_llvm[self.dtype],
self.size * 2,
self.name+"-data"
)
def set_alloc_from(self, mem_ptr) -> None:
"""Use existing mem_ptr as the alloca memory
"""
self.alloc = mem_ptr
def code_gen(self, bd: ir.IRBuilder) -> None:
"""Wrapper of the code_gen function,
Rcursively generates it's dependences and call itselves _code_gen core
Note that only Lvalue node need generate llvm ir
"""
if self.gened:
return
for dep in self.dependence:
dep.code_gen(bd)
self.gened = True
if self.vtype == LRValue.LEFT:
self._code_gen(bd)
def _code_gen(self, bd: ir.IRBuilder) -> None:
raise NotImplementedError
def get_ele(
self,
ind: Union[ir.Constant, ir.instructions.Instruction, int],
builder: ir.IRBuilder
) -> List[ir.instructions.Instruction]:
"""Generate the llvm ir to get cirtain element,
ind can be a integer in python or int_type in llvm ir,
but its type must be ir.IntType(32).
It may contains two elements for complex number.
"""
if type(ind) == int:
ind = ir.Constant(int_type, ind)
assert(ind.type == int_type)
if not self.gened:
print("Error: try to access ungenerated array")
raise NameError
if self.size == 1:
ind = ir.Constant(int_type, 0)
if self.vtype == LRValue.LEFT:
return self._load_from_alloc(ind, builder)
else:
# print(self._load_from_src(ind, builder))
return self._load_from_src(ind, builder)
def _load_from_src(self, ind, builder) -> List[ir.LoadInstr]:
raise NotImplementedError
def _store_to_alloc(
self,
index: Union[ir.Constant, ir.Instruction],
src_nums: List[ir.LoadInstr],
builder: ir.IRBuilder
) -> None:
if not self.dtype in (DType.Complx, DType.DComplx):
dest_ptr = builder.gep(self.alloc, [index])
builder.store(src_nums[0], dest_ptr)
else:
cmplx_dest_index = builder.mul(index, ir.Constant(int_type, 2))
dest_ptr_r = builder.gep(self.alloc, [cmplx_dest_index])
builder.store(src_nums[0], dest_ptr_r)
cmplx_dest_index = builder.add(
cmplx_dest_index, ir.Constant(int_type, 1))
dest_ptr_i = builder.gep(self.alloc, [cmplx_dest_index])
builder.store(src_nums[1], dest_ptr_i)
def _load_from_alloc(
self,
index: Union[ir.Constant, ir.Instruction],
builder: ir.IRBuilder
) -> List[ir.LoadInstr]:
if not self.dtype in (DType.Complx, DType.DComplx):
self_ptr = builder.gep(self.alloc, [index])
products = [builder.load(self_ptr)]
else:
cmplx_index = builder.mul(index, ir.Constant(int_type, 2))
self_ptr_real = builder.gep(self.alloc, [cmplx_index])
product_real = builder.load(self_ptr_real)
cmplx_index = builder.add(cmplx_index, ir.Constant(int_type, 1))
self_ptr_imag = builder.gep(self.alloc, [cmplx_index])
product_imag = builder.load(self_ptr_imag)
products = [product_real, product_imag]
return products
# -------------------------------------------
# Mathematical operations
# -------------------------------------------
def __add__(
self,
other: Union[Node, int, float, complex]
) -> Node:
if isinstance(other, (int, float, complex)):
other = make_const_node(other, type(other))
return BinOpNode(BinaryOpr.ADD, self, other)
def __radd__(
self,
other: Union[Node, int, float, complex]
) -> Node:
if isinstance(other, (int, float, complex)):
other = make_const_node(other, type(other))
return BinOpNode(BinaryOpr.ADD, self, other)
def __sub__(
self,
other: Union[Node, int, float, complex]
) -> Node:
if isinstance(other, (int, float, complex)):
other = make_const_node(other, type(other))
return BinOpNode(BinaryOpr.SUB, self, other)
def __rsub__(
self,
other: Union[Node, int, float, complex]
) -> Node:
if isinstance(other, (int, float, complex)):
other = make_const_node(other, type(other))
return BinOpNode(BinaryOpr.SUB, other, self)
def __mul__(
self,
other: Union[Node, int, float, complex]
) -> Node:
if isinstance(other, (int, float, complex)):
other = make_const_node(other, type(other))
return BinOpNode(BinaryOpr.MUL, self, other)
def __rmul__(
self,
other: Union[Node, int, float, complex]
) -> Node:
if isinstance(other, (int, float, complex)):
other = make_const_node(other, type(other))
return BinOpNode(BinaryOpr.MUL, self, other)
def __floordiv__(
self,
other: Union[Node, int, float, complex]
) -> Node:
if isinstance(other, (int, float, complex)):
other = make_const_node(other, type(other))
return BinOpNode(BinaryOpr.IDIV, self, other)
def __rfloordiv__(
self,
other: Union[Node, int, float, complex]
) -> Node:
if isinstance(other, (int, float, complex)):
other = make_const_node(other, type(other))
return BinOpNode(BinaryOpr.IDIV, other, self)
def __truediv__(
self,
other: Union[Node, int, float, complex]
) -> Node:
if isinstance(other, (int, float, complex)):
other = make_const_node(other, type(other))
return BinOpNode(BinaryOpr.FDIV, self, other)
def __rtruediv__(
self,
other: Union[Node, int, float, complex]
) -> Node:
if isinstance(other, (int, float, complex)):
other = make_const_node(other, type(other))
return BinOpNode(BinaryOpr.FDIV, other, self)
def __neg__(self):
return UnaOpNode(UnaryOpr.NEG, self)
# -------------------------------------------
# Indexing operations
# -------------------------------------------
def __getitem__(
self,
index: Union[int, ir.Constant, ir.Instruction,
list, tuple, Node, slice, np.ndarray]
) -> Node:
if isinstance(index, int):
index = ConstNode(index, DType.Int)
return GetSliceNode(index, self)
def __setitem__(
self,
index: Union[int, Node, slice, list, tuple, np.ndarray],
val: Union[float, int, complex, Node]
) -> None:
"""Setting index,
Do not recommend to use numpy array for index
Do not recommend to use numpy array, list or tuple for val
"""
if isinstance(val, (float, int, complex)):
val = make_const_node(val, type(val))
length = compute_size(index, self.size)
if isinstance(index, Node):
assert(index.dtype == DType.Int)
assert((length == val.size) or len(val) == 1)
gr._append({"type": "set", "target": self, "src": (index, val)})
def _gen_setitem(
self,
builder: ir.IRBuilder,
index: Union[int, Node, slice, list, tuple, np.ndarray],
val: Node) -> None:
"""When set index to one node, it must be LValue node,
if not, the graph maintainer should modify its vtype to LEFT.
Also, only when the array is required, will it be generated.
"""
if isinstance(index, int):
const0 = ir.Constant(int_type, 0)
src_nums = val.get_ele(const0, builder)
if val.dtype != self.dtype:
src_nums = build_type_cast(
builder, src_nums, val.dtype, self.dtype)
index = ir.Constant(int_type, index)
self._store_to_alloc(index, src_nums, builder)
elif isinstance(index, slice):
size = compute_size(index, self.size)
start, _, step = index.indices(val.size)
v_start = ir.Constant(int_type, start)
v_step = ir.Constant(int_type, step)
dest_index_ptr = builder.alloca(int_type, 1)
builder.store(v_start, dest_index_ptr)
with LoopCtx(self.name+"_set_slice", builder, size) as loop:
loop_inc = builder.load(loop.inc)
dest_index = builder.load(dest_index_ptr)
src_nums = val.get_ele(loop_inc, builder)
self._store_to_alloc(dest_index, src_nums, builder)
builder.store(builder.add(
dest_index, v_step), dest_index_ptr)
elif isinstance(index, Node):
with LoopCtx(self.name+"_set_slice", builder, index.size) as loop:
loop_inc = builder.load(loop.inc)
dest_index = index.get_ele(loop_inc)[0]
src_nums = val.get_ele(loop_inc, builder)
self._store_to_alloc(dest_index, src_nums, builder)
else:
all_inds = builder.alloca(int_type, len(index))
# TODO: change this to malloc function
for i in range(len(index)):
ind_ptr = builder.gep(all_inds, [ir.Constant(int_type, i)])
builder.store(ir.Constant(int_type, index[i]), ind_ptr)
with LoopCtx(self.name+"_set_slice", builder, len(index)) as loop:
loop_inc = builder.load(loop.inc)
dest_index_ptr = builder.gep(all_inds, [loop_inc])
dest_index = builder.load(dest_index_ptr)
src_nums = val.get_ele(loop_inc)
self._store_to_alloc(dest_index, src_nums, builder)
# -------------------------------------------
# Iteration methods
# -------------------------------------------
def __iter__(self):
self.iter_ind = 0
return self
def __next__(self) -> Optional[GetSliceNode]:
self.iter_ind += 1
if self.iter_ind >= self.size:
raise StopIteration
else:
return self[self.iter_ind]
def __len__(self) -> int:
return self.size
# #-------------------------------------------
# # Moving methods
# #-------------------------------------------
# def mov_from(self, other):
# pass
# def _gen_mov(self,builder: ir.IRBuilder):
# pass
#
# -------------------------------------------
# Other methods
# -------------------------------------------
def rename(self, new_name: str) -> None:
self.name = uuname(new_name)
self.label = new_name
def __str__(self) -> str:
return f"{self.label}:{self.name}"
class InputNode(Node):
"""Input Node for the whole graph, cannot generated by other node.
"""
def __init__(
self,
size: int,
name: str,
dtype: DType
):
if not name:
name = "input"
super().__init__(size, name, dtype, LRValue.LEFT)
def fill(self, builder: ir.IRBuilder) -> None:
pass
def _code_gen(self, builder: ir.IRBuilder) -> None:
self.fill(builder)
class BinOpNode(Node):
"""Generated node from binary operator
"""
def __init__(self, opr: BinaryOpr, LHS: Node, RHS: Node) -> None:
size = det_size(LHS, RHS)
dtype = det_dtype(opr, LHS.dtype, RHS.dtype)
super().__init__(size, biopr_map[opr][dtype], dtype)
self.opr = opr
self.dependence = {LHS, RHS}
self.LHS = LHS
self.RHS = RHS
def _code_gen(self, builder: ir.IRBuilder) -> None:
# instr = getattr(builder, biopr_map[self.opr][self.dtype])
with LoopCtx(self.name, builder, self.size) as loop:
loop_inc = builder.load(loop.inc)
products = self._build_opr(loop_inc, builder)
self._store_to_alloc(loop_inc, products, builder)
def _build_opr(
self,
loop_inc: Union[ir.instructions.Instruction, ir.Constant],
builder: ir.IRBuilder
) -> List[ir.instructions.Instruction]:
"""Build llvm ir for binary operator
If the type of any operand is different from the output type, a type cast from type_cast_llvm dict
should be performed.
Special calculations on Complx and DComplx output
"""
assert(loop_inc.type == int_type)
if not self.dtype in (DType.Complx, DType.DComplx):
left_nums = | |
X
to train each base estimator.
- If None (default), then draw `X.shape[0]` samples.
- If int, then draw `max_samples` samples.
- If float, then draw `max_samples * X.shape[0]` samples. Thus,
`max_samples` should be in the interval `(0.0, 1.0]`.
Attributes
----------
base_estimator_ : DecisionTreeRegressor
The child estimator template used to create the collection of fitted
sub-estimators.
estimators_ : list of DecisionTreeRegressor
The collection of fitted sub-estimators.
feature_importances_ : ndarray of shape (n_features,)
The impurity-based feature importances.
The higher, the more important the feature.
The importance of a feature is computed as the (normalized)
total reduction of the criterion brought by that feature. It is also
known as the Gini importance.
Warning: impurity-based feature importances can be misleading for
high cardinality features (many unique values).
n_features_in_ : int
Number of features seen during :term:`fit`.
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
n_outputs_ : int
The number of outputs when ``fit`` is performed.
oob_score_ : float
Score of the training dataset obtained using an out-of-bag estimate.
This attribute exists only when ``oob_score`` is True.
oob_prediction_ : ndarray of shape (n_samples,) or (n_samples, n_outputs)
Prediction computed with out-of-bag estimate on the training set.
This attribute exists only when ``oob_score`` is True.
See Also
--------
ExtraTreesQuantileRegressor : Quantile ensemble of extremely randomized
tree regressors.
References
----------
.. [1] <NAME>, "Quantile Regression Forests", Journal of Machine
Learning Research, 7(Jun), 983-999, 2006.
http://www.jmlr.org/papers/volume7/meinshausen06a/meinshausen06a.pdf
Examples
--------
>>> from quantile_forest import RandomForestQuantileRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(
... n_features=4, n_informative=2, random_state=0, shuffle=False)
>>> regr = RandomForestQuantileRegressor(max_depth=2, random_state=0)
>>> regr.fit(X, y)
RandomForestQuantileRegressor(...)
>>> print(regr.predict([[0, 0, 0, 0]], quantiles=0.5))
[-4.68693299]
"""
def __init__(
self,
n_estimators=100,
*,
criterion="squared_error",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
max_samples_leaf=None,
min_weight_fraction_leaf=0.0,
max_features=1.0,
max_leaf_nodes=None,
min_impurity_decrease=0.0,
bootstrap=True,
oob_score=False,
n_jobs=None,
random_state=None,
verbose=0,
warm_start=False,
ccp_alpha=0.0,
max_samples=None,
):
super(RandomForestQuantileRegressor, self).__init__(
base_estimator=DecisionTreeRegressor(),
n_estimators=n_estimators,
estimator_params=(
"criterion",
"max_depth",
"min_samples_split",
"min_samples_leaf",
"min_weight_fraction_leaf",
"max_features",
"max_leaf_nodes",
"min_impurity_decrease",
"random_state",
"ccp_alpha",
),
bootstrap=bootstrap,
oob_score=oob_score,
n_jobs=n_jobs,
random_state=random_state,
verbose=verbose,
warm_start=warm_start,
max_samples=max_samples,
)
self.criterion = criterion
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.max_samples_leaf = max_samples_leaf
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.max_features = max_features
self.max_leaf_nodes = max_leaf_nodes
self.min_impurity_decrease = min_impurity_decrease
self.ccp_alpha = ccp_alpha
def _more_tags(self):
"""TODO: Add support for multioutput."""
return {
"multioutput": False,
"_xfail_checks": {
"check_dataframe_column_names_consistency": "Internal calls.",
},
}
class ExtraTreesQuantileRegressor(BaseForestQuantileRegressor):
"""An extra-trees regressor that provides quantile estimates.
This class implements a meta estimator that fits a number of randomized
decision trees (a.k.a. extra-trees) on various sub-samples of the dataset
and use averaging to improve the predictive accuracy and control
over-fitting.
Parameters
----------
n_estimators : int, default=100
The number of trees in the forest.
criterion : {"squared_error", "absolute_error"}, default="squared_error"
The function to measure the quality of a split. Supported criteria
are "squared_error" for the mean squared error, which is equal to
variance reduction as feature selection criterion, and "absolute_error"
for the mean absolute error.
max_depth : int, default=None
The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split : int or float, default=2
The minimum number of samples required to split an internal node:
- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a fraction and
`ceil(min_samples_split * n_samples)` are the minimum
number of samples for each split.
min_samples_leaf : int or float, default=1
The minimum number of samples required to be at a leaf node.
A split point at any depth will only be considered if it leaves at
least ``min_samples_leaf`` training samples in each of the left and
right branches. This may have the effect of smoothing the model,
especially in regression.
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a fraction and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
max_samples_leaf : int or float, default=None
The maximum number of samples permitted to be at a leaf node.
- If int, then consider `max_samples_leaf` as the maximum number.
- If float, then `max_samples_leaf` is a fraction and
`ceil(max_samples_leaf * n_samples)` are the maximum
number of samples for each node.
min_weight_fraction_leaf : float, default=0.0
The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
max_features : {"sqrt", "log2", None}, int or float, default=1.0
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a fraction and
`round(max_features * n_features)` features are considered at each
split.
- If "auto", then `max_features=n_features`.
- If "sqrt", then `max_features=sqrt(n_features)`.
- If "log2", then `max_features=log2(n_features)`.
- If None or 1.0, then `max_features=n_features`.
.. note::
The default of 1.0 is equivalent to bagged trees and more
randomness can be achieved by setting smaller values, e.g. 0.3.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than ``max_features`` features.
max_leaf_nodes : int, default=None
Grow trees with ``max_leaf_nodes`` in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
min_impurity_decrease : float, default=0.0
A node will be split if this split induces a decrease of the impurity
greater than or equal to this value.
The weighted impurity decrease equation is the following::
N_t / N * (impurity - N_t_R / N_t * right_impurity
- N_t_L / N_t * left_impurity)
where ``N`` is the total number of samples, ``N_t`` is the number of
samples at the current node, ``N_t_L`` is the number of samples in the
left child, and ``N_t_R`` is the number of samples in the right child.
``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
if ``sample_weight`` is passed.
bootstrap : bool, default=False
Whether bootstrap samples are used when building trees. If False, the
whole dataset is used to build each tree.
oob_score : bool, default=False
Whether to use out-of-bag samples to estimate the generalization score.
Only available if bootstrap=True.
n_jobs : int, default=None
The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,
:meth:`decision_path` and :meth:`apply` are all parallelized over the
trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`
context. ``-1`` means using all processors.
random_state : int, RandomState instance or None, default=None
Controls 3 sources of randomness:
- the bootstrapping of the samples used when building trees
(if ``bootstrap=True``)
- the sampling of the features to consider when looking for the best
split at each node (if ``max_features < n_features``)
- the draw of the splits for each of the `max_features`
verbose : int, default=0
Controls the verbosity when fitting and predicting.
warm_start : bool, default=False
When set to ``True``, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just fit a whole
new forest.
ccp_alpha : non-negative float, default=0.0
Complexity parameter used for Minimal Cost-Complexity Pruning. The
subtree with the largest cost complexity that is smaller than
``ccp_alpha`` will be chosen. By default, no pruning is performed.
max_samples : int or float, default=None
If bootstrap is True, the number of samples to draw from X
to train each base estimator.
- If None (default), then draw `X.shape[0]` samples.
- If int, then draw `max_samples` samples.
- If float, then draw `max_samples * X.shape[0]` samples. Thus,
`max_samples` should be in the interval `(0.0, 1.0]`.
Attributes
----------
base_estimator_ : ExtraTreeQuantileRegressor
The child estimator template used to create the collection of fitted
sub-estimators.
estimators_ : list of ForestRegressor
The collection of fitted sub-estimators.
feature_importances_ : ndarray of shape (n_features,)
The impurity-based feature importances.
| |
`layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
z
Sets the points' weight. For example, a value of 10
would be equivalent to having 10 points of weight 1 in
the same spot
zauto
Determines whether or not the color domain is computed
with respect to the input data (here in `z`) or the
bounds set in `zmin` and `zmax` Defaults to `false`
when `zmin` and `zmax` are set by the user.
zmax
Sets the upper bound of the color domain. Value should
have the same units as in `z` and if set, `zmin` must
be set as well.
zmid
Sets the mid-point of the color domain by scaling
`zmin` and/or `zmax` to be equidistant to this point.
Value should have the same units as in `z`. Has no
effect when `zauto` is `false`.
zmin
Sets the lower bound of the color domain. Value should
have the same units as in `z` and if set, `zmax` must
be set as well.
zsrc
Sets the source reference on Chart Studio Cloud for z
.
row : 'all', int or None (default)
Subplot row index (starting from 1) for the trace to be
added. Only valid if figure was created using
`plotly.tools.make_subplots`.If 'all', addresses all
rows in the specified column(s).
col : 'all', int or None (default)
Subplot col index (starting from 1) for the trace to be
added. Only valid if figure was created using
`plotly.tools.make_subplots`.If 'all', addresses all
columns in the specified row(s).
Returns
-------
Figure
"""
from plotly.graph_objs import Densitymapbox
new_trace = Densitymapbox(
autocolorscale=autocolorscale,
below=below,
coloraxis=coloraxis,
colorbar=colorbar,
colorscale=colorscale,
customdata=customdata,
customdatasrc=customdatasrc,
hoverinfo=hoverinfo,
hoverinfosrc=hoverinfosrc,
hoverlabel=hoverlabel,
hovertemplate=hovertemplate,
hovertemplatesrc=hovertemplatesrc,
hovertext=hovertext,
hovertextsrc=hovertextsrc,
ids=ids,
idssrc=idssrc,
lat=lat,
latsrc=latsrc,
legendgroup=legendgroup,
lon=lon,
lonsrc=lonsrc,
meta=meta,
metasrc=metasrc,
name=name,
opacity=opacity,
radius=radius,
radiussrc=radiussrc,
reversescale=reversescale,
showlegend=showlegend,
showscale=showscale,
stream=stream,
subplot=subplot,
text=text,
textsrc=textsrc,
uid=uid,
uirevision=uirevision,
visible=visible,
z=z,
zauto=zauto,
zmax=zmax,
zmid=zmid,
zmin=zmin,
zsrc=zsrc,
**kwargs
)
return self.add_trace(new_trace, row=row, col=col)
def add_funnel(
self,
alignmentgroup=None,
cliponaxis=None,
connector=None,
constraintext=None,
customdata=None,
customdatasrc=None,
dx=None,
dy=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
insidetextanchor=None,
insidetextfont=None,
legendgroup=None,
marker=None,
meta=None,
metasrc=None,
name=None,
offset=None,
offsetgroup=None,
opacity=None,
orientation=None,
outsidetextfont=None,
selectedpoints=None,
showlegend=None,
stream=None,
text=None,
textangle=None,
textfont=None,
textinfo=None,
textposition=None,
textpositionsrc=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
uid=None,
uirevision=None,
visible=None,
width=None,
x=None,
x0=None,
xaxis=None,
xperiod=None,
xperiod0=None,
xperiodalignment=None,
xsrc=None,
y=None,
y0=None,
yaxis=None,
yperiod=None,
yperiod0=None,
yperiodalignment=None,
ysrc=None,
row=None,
col=None,
secondary_y=None,
**kwargs
):
"""
Add a new Funnel trace
Visualize stages in a process using length-encoded bars. This
trace can be used to show data in either a part-to-whole
representation wherein each item appears in a single stage, or
in a "drop-off" representation wherein each item appears in
each stage it traversed. See also the "funnelarea" trace type
for a different approach to visualizing funnel data.
Parameters
----------
alignmentgroup
Set several traces linked to the same position axis or
matching axes to the same alignmentgroup. This controls
whether bars compute their positional range dependently
or independently.
cliponaxis
Determines whether the text nodes are clipped about the
subplot axes. To show the text nodes above axis lines
and tick labels, make sure to set `xaxis.layer` and
`yaxis.layer` to *below traces*.
connector
:class:`plotly.graph_objects.funnel.Connector` instance
or dict with compatible properties
constraintext
Constrain the size of text inside or outside a bar to
be no larger than the bar itself.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
customdata .
dx
Sets the x coordinate step. See `x0` for more info.
dy
Sets the y coordinate step. See `y0` for more info.
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
hoverinfo .
hoverlabel
:class:`plotly.graph_objects.funnel.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api-
reference/blob/master/Formatting.md#d3_format for
details on the formatting syntax. Dates are formatted
using d3-time-format's syntax %{variable|d3-time-
format}, for example "Day: %{2019-01-01|%A}".
https://github.com/d3/d3-time-format#locale_format for
details on the date formatting syntax. The variables
available in `hovertemplate` are the ones emitted as
event data described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. variables `percentInitial`,
`percentPrevious` and `percentTotal`. Anything
contained in tag `<extra>` is displayed in the
secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
hovertemplate .
hovertext
Sets hover text elements associated with each (x,y)
pair. If a single string, the same string appears over
all the data points. If an array of string, the items
are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace `hoverinfo` must contain
a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
hovertext .
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
ids .
insidetextanchor
Determines if texts are kept at center or start/end
points in `textposition` "inside" mode.
insidetextfont
Sets the font used for `text` lying inside the bar.
legendgroup
Sets the legend group for this trace. Traces part of
the same legend group hide/show at the same time when
toggling legend items.
marker
:class:`plotly.graph_objects.funnel.Marker` instance or
dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
meta .
name
Sets the trace name. The trace name appear as the
legend item and on hover.
offset
Shifts the position where the bar is drawn (in position
axis units). In "group" barmode, traces that set
"offset" will be excluded and drawn in "overlay" mode
instead.
offsetgroup
Set several traces linked to the same position axis or
matching axes to the same offsetgroup where bars of the
same position coordinate will line up.
opacity
Sets the opacity of the trace.
orientation
Sets the orientation of the funnels. With "v" ("h"),
the value of the each bar spans along the vertical
(horizontal). By default funnels are tend to be
oriented horizontally; unless only "y" array is
presented or orientation is set to "v". Also regarding
graphs including only 'horizontal' funnels, "autorange"
on the | |
<reponame>OttoJursch/DRL_robot_exploration<gh_stars>0
from copy import deepcopy
from scipy import spatial
from skimage import io
from skimage.transform import resize
from scipy import ndimage
from random import shuffle
import numpy as np
import numpy.ma as ma
import time
import copy
import sys
import os
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchsummary
import matplotlib.pyplot as plt
#OTTO UNCOMMENT THESE TO RUN ON COLAB
# sys.path.append('DRL_robot_exploration')
# from DRL_robot_exploration.build.inverse_sensor_model import *
# from DRL_robot_exploration.build.astar import *
#AND COMMENT THESE
from build.inverse_sensor_model import *
from build.astar import *
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class PaperRewardFunction:
'''
Reward function from the paper
'''
def __init__(self):
pass
def get_reward(self, robot_position, old_op_map, op_map, coll_index):
'''
Takes in map before step and map after step. Measures effect of sensor
input from last step
'''
if not coll_index:
reward = float(
np.size(np.where(op_map == 255)) -
np.size(np.where(old_op_map == 255))) / 14000
if reward > 1:
reward = 1
else:
reward = -1
return reward
class FrontierRewardFunction:
def __init__(self, reward_scale):
self.reward_scale = reward_scale
self.paper_reward = PaperRewardFunction()
def frontiers(self, op_map, map_size, points):
y_len = map_size[0]
x_len = map_size[1]
mapping = op_map.copy()
# 0-1 unknown area map
mapping = (mapping == 127) * 1
mapping = np.lib.pad(mapping, ((1, 1), (1, 1)),
'constant',
constant_values=0)
fro_map = mapping[2:][:, 1:x_len + 1] + mapping[:y_len][:, 1:x_len + 1] + mapping[1:y_len + 1][:, 2:] + \
mapping[1:y_len + 1][:, :x_len] + mapping[:y_len][:, 2:] + mapping[2:][:, :x_len] + mapping[2:][:,
2:] + \
mapping[:y_len][:, :x_len]
ind_free = np.where(op_map.ravel(order='F') == 255)[0]
ind_fron_1 = np.where(1 < fro_map.ravel(order='F'))[0]
ind_fron_2 = np.where(fro_map.ravel(order='F') < 8)[0]
ind_fron = np.intersect1d(ind_fron_1, ind_fron_2)
ind_to = np.intersect1d(ind_free, ind_fron)
f = points[ind_to]
f = f.astype(int)
return f
def map_points(self, map_glo):
map_x = map_glo.shape[1]
map_y = map_glo.shape[0]
x = np.linspace(0, map_x - 1, map_x)
y = np.linspace(0, map_y - 1, map_y)
t1, t2 = np.meshgrid(x, y)
points = np.vstack([t1.T.ravel(), t2.T.ravel()]).T
return points
def get_reward(self, robot_pos, old_op_map, op_map, coll_index):
paper_reward = self.paper_reward.get_reward(robot_pos, old_op_map,
op_map, coll_index)
#If there was a collision return the collision reward
if coll_index:
print('collided??')
return paper_reward
frontiers = np.array(
self.frontiers(op_map, op_map.shape, self.map_points(op_map)))
min_frontier_dist = -np.min(np.linalg.norm(robot_pos - frontiers, axis=1))
return self.reward_scale * min_frontier_dist + paper_reward
class PolarActionSpace:
'''
Action space is polar representation of vector robot should take from its
current position
This class will take that and add it to the current robot position to get
'''
def __init__(self, max_travel):
self.max_distance = max_travel
def get_action(self, action_polar_coords, robot_position):
angle = action_polar_coords[0] * (2 * np.pi)
dist = action_polar_coords[1] * self.max_distance
dx = dist * np.sin(angle)
dy = dist * np.cos(angle)
return np.array([dx, dy])
class Robot:
def __init__(self,
index_map,
train,
plot,
root_dir,
action_space,
reward_function,
do_rescue,
shuffle=True):
self.mode = train
self.action_space = action_space
self.plot = plot
self.root_dir = root_dir
self.index_map = index_map
self.do_rescue = do_rescue
self.reward_function = reward_function
self.reset(index_map, shuffle)
def reset(self, index_map=None, do_shuffle=True):
if self.mode:
self.map_dir = os.path.join(self.root_dir, 'train')
else:
self.map_dir = os.path.join(self.root_dir, 'test')
self.map_list = os.listdir(self.map_dir)
self.map_number = np.size(self.map_list)
if self.mode and do_shuffle:
shuffle(self.map_list)
if index_map is None:
index_map = random.choice(range(len(self.map_list)))
self.li_map = index_map
self.global_map, self.robot_position = self.map_setup(
self.map_dir + '/' + self.map_list[self.li_map])
print('robot after map load', self.robot_position)
self.op_map = np.ones(self.global_map.shape) * 127
self.map_size = np.shape(self.global_map)
self.finish_percent = 0.985
self.resolution = 1
self.sensor_range = 80
self.old_position = np.zeros([2])
self.old_op_map = np.empty([0])
#current_dir = os.path.dirname(os.path.realpath(__file__))
self.t = self.map_points(self.global_map)
self.free_tree = spatial.KDTree(
self.free_points(self.global_map).tolist())
self.robot_size = 6
self.local_size = 40
if self.plot:
self.xPoint = np.array([self.robot_position[0]])
self.yPoint = np.array([self.robot_position[1]])
self.x2frontier = np.empty([0])
self.y2frontier = np.empty([0])
print('robot pos returned', self.robot_position)
return self.begin(), self.robot_position
def begin(self):
self.op_map = self.inverse_sensor(self.robot_position,
self.sensor_range, self.op_map,
self.global_map)
step_map = self.robot_model(self.robot_position, self.robot_size,
self.t, self.op_map)
map_local = self.local_map(self.robot_position, step_map,
self.map_size,
self.sensor_range + self.local_size)
if self.plot:
self.plot_env()
return self.op_map
def step(self, action_index):
terminal = False
complete = False
new_location = False
all_map = False
self.old_position = self.robot_position.copy()
self.old_op_map = self.op_map.copy()
# take action
self.take_action(action_index, self.robot_position)
# collision check
collision_points, collision_index = self.collision_check(
self.old_position, self.robot_position, self.map_size,
self.global_map)
if collision_index:
self.robot_position = self.nearest_free(self.free_tree,
collision_points)
self.op_map = self.inverse_sensor(self.robot_position,
self.sensor_range, self.op_map,
self.global_map)
step_map = self.robot_model(self.robot_position, self.robot_size,
self.t, self.op_map)
else:
self.op_map = self.inverse_sensor(self.robot_position,
self.sensor_range, self.op_map,
self.global_map)
step_map = self.robot_model(self.robot_position, self.robot_size,
self.t, self.op_map)
map_local = self.local_map(self.robot_position, step_map,
self.map_size,
self.sensor_range + self.local_size)
reward = self.reward_function.get_reward(self.robot_position,
self.old_op_map, self.op_map,
collision_index)
if reward <= 0.02 and not collision_index:
reward = -0.8
new_location = True
#terminal = True
# during training, the robot is relocated if it has a collision
# during testing, the robot will use collision check to avoid the collision
if collision_index:
if not self.mode:
new_location = False
terminal = False
else:
new_location = True
terminal = True
if self.plot and self.mode:
self.xPoint = ma.append(self.xPoint, self.robot_position[0])
self.yPoint = ma.append(self.yPoint, self.robot_position[1])
self.plot_env()
self.robot_position = self.old_position.copy()
self.op_map = self.old_op_map.copy()
if self.plot and self.mode:
self.xPoint[self.xPoint.size - 1] = ma.masked
self.yPoint[self.yPoint.size - 1] = ma.masked
else:
if self.plot:
self.xPoint = ma.append(self.xPoint, self.robot_position[0])
self.yPoint = ma.append(self.yPoint, self.robot_position[1])
self.plot_env()
# check if exploration is finished
if np.size(np.where(self.op_map == 255)) / np.size(
np.where(self.global_map == 255)) > self.finish_percent:
self.li_map += 1
if self.li_map == self.map_number:
self.li_map = 0
all_map = True
self.__init__(self.li_map, self.mode, self.plot)
complete = True
new_location = False
terminal = True
return (
self.op_map, self.robot_position
), reward, terminal, complete, new_location, collision_index, all_map
def rescuer(self):
complete = False
all_map = False
pre_position = self.robot_position.copy()
self.robot_position = self.frontier(self.op_map, self.map_size, self.t)
self.op_map = self.inverse_sensor(self.robot_position,
self.sensor_range, self.op_map,
self.global_map)
step_map = self.robot_model(self.robot_position, self.robot_size,
self.t, self.op_map)
map_local = self.local_map(self.robot_position, step_map,
self.map_size,
self.sensor_range + self.local_size)
if self.plot:
path = self.astar_path(self.op_map, pre_position.tolist(),
self.robot_position.tolist())
self.x2frontier = ma.append(self.x2frontier, ma.masked)
self.y2frontier = ma.append(self.y2frontier, ma.masked)
self.x2frontier = ma.append(self.x2frontier, path[1, :])
self.y2frontier = ma.append(self.y2frontier, path[0, :])
self.xPoint = ma.append(self.xPoint, ma.masked)
self.yPoint = ma.append(self.yPoint, ma.masked)
self.xPoint = ma.append(self.xPoint, self.robot_position[0])
self.yPoint = ma.append(self.yPoint, self.robot_position[1])
self.plot_env()
if np.size(np.where(self.op_map == 255)) / np.size(
np.where(self.global_map == 255)) > self.finish_percent:
self.li_map += 1
if self.li_map == self.map_number:
self.li_map = 0
all_map = True
self.__init__(self.li_map, self.mode, self.plot)
complete = True
new_location = False
terminal = True
return map_local, complete, all_map
def take_action(self, action_index, robot_position):
move_action = self.action_space.get_action(action_index,
robot_position)
print('move action', move_action)
print('robot position', robot_position)
robot_position[0] = np.round(robot_position[0] + move_action[0])
robot_position[1] = np.round(robot_position[1] + move_action[1])
def map_setup(self, location):
global_map = (io.imread(location, 1) * 255).astype(int)
robot_location = np.nonzero(global_map == 208)
robot_location = np.array([
np.array(robot_location)[1, 127],
np.array(robot_location)[0, 127]
])
global_map = (global_map > 150)
global_map = global_map * 254 + 1
return global_map, robot_location
def map_points(self, map_glo):
map_x = map_glo.shape[1]
map_y = map_glo.shape[0]
x = np.linspace(0, map_x - 1, map_x)
y = np.linspace(0, map_y - 1, map_y)
t1, t2 = np.meshgrid(x, y)
points = np.vstack([t1.T.ravel(), t2.T.ravel()]).T
return points
def local_map(self, robot_location, map_glo, map_size, local_size):
minX = robot_location[0] - local_size
maxX = robot_location[0] + local_size
minY = robot_location[1] - local_size
maxY = robot_location[1] + local_size
if minX < 0:
maxX = abs(minX) + maxX
minX = 0
if maxX > map_size[1]:
minX = minX - (maxX - map_size[1])
maxX = map_size[1]
if minY < 0:
maxY = abs(minY) + maxY
minY = 0
if maxY > map_size[0]:
minY = minY - (maxY - map_size[0])
maxY = map_size[0]
map_loc = map_glo[minY:maxY][:, minX:maxX]
return map_loc
def free_points(self, op_map):
index = np.where(op_map == 255)
free = np.asarray([index[1], index[0]]).T
return free
def nearest_free(self, tree, point):
pts = np.atleast_2d(point)
index = tuple(tree.query(pts)[1])
nearest = tree.data[index]
return nearest
def robot_model(self, position, robot_size, points, map_glo):
map_copy = map_glo.copy()
robot_points = self.range_search(position, robot_size, points)
for i in range(0, robot_points.shape[0]):
rob_loc = np.int32(robot_points[i, :])
rob_loc = np.flipud(rob_loc)
map_copy[tuple(rob_loc)] = 76
map_with_robot = map_copy
return map_with_robot
def range_search(self, position, r, points):
nvar = position.shape[0]
r2 = r**2
s = 0
for d in range(0, nvar):
s += (points[:, d] - position[d])**2
idx = np.nonzero(s <= r2)
idx = np.asarray(idx).ravel()
inrange_points = points[idx, :]
return inrange_points
def collision_check(self, start_point, end_point, map_size, map_glo):
x0, y0 = start_point.round()
x1, y1 = end_point.round()
dx, dy = abs(x1 - x0), abs(y1 - y0)
x, y = x0, y0
error = dx - dy
print('coll dx', dx)
print('coll dy', dy)
x_inc = 1 if x1 > x0 else -1
y_inc = 1 if y1 > y0 else -1
dx *= 2
dy *= 2
coll_points = np.ones((1, 2), np.uint8) * -1
while 0 <= x < map_size[1] and | |
"""
Levenberg Marquart fitting class and helper tools
https://github.com/jaimedelacruz/LevMar
Coded by <NAME> (ISP-SU 2021)
References:
This implementation follows the notation presented in:
<NAME>, Leenaarts, Danilovic & Uitenbroek (2019):
https://ui.adsabs.harvard.edu/abs/2019A%26A...623A..74D/abstract
but without l-2 regularization for the time being.
Original Levenberg-Marquardt algorithm references:
Levenberg (1944)
Marquardt (1963)
Dependences: NumPy
Modifications history:
2021-07-8, JdlCR: added SVD_thres to reject small singular values.
Bugfix in autoderivatives scaling
TODO:
1) Implement handling of cyclic variables.
"""
import numpy as np
# *******************************************************
class Pinfo:
"""
Helper class to store parameter scaling norms and limits
Methods: checkLimits, scale, normalize
"""
def __init__(self, scale = 1.0, min = None, max = None, is_cyclic = 0):
self.scl = scale
self.min = min
self.max = max
self.is_cyclic = is_cyclic
# --------------------------------------------------
def checkLimits(self, value):
"""
This function gets a parameter value and
checks whether it is within the specified
limits. If it isn't, the value will saturate
at the limit value.
"""
if(self.min is not None):
value = np.maximum(value, self.min)
if(self.max is not None):
value = np.minimum(value, self.max)
return value
# --------------------------------------------------
def scale(self, value):
"""
This function scales a paramter value that
has been normalized with the scaling norm
"""
return value*self.scl
# --------------------------------------------------
def normalize(self, value):
"""
This function normalizes a parameter value
with a scaling norm
"""
return value / self.scl
# *******************************************************
def ScalePars(pars, Pinfo):
"""
Helper function that scales an array of parameters inplace
pars: 1D numpy array of length Npar
Pinfo: tuple/list of Pinfo objects of length Npar
"""
pLen = pars.size
piLen = len(Pinfo)
if(piLen != pLen):
print("[error] ScalePars: Error, parameter array has different length than Parameter info array: {0} != {1}".format(pLen, piLen))
return 0
for ii in range(pLen):
pars[ii] = Pinfo[ii].scale(pars[ii])
return 1
# *******************************************************
def NormalizePars(pars, Pinfo):
"""
Helper function that normalizes an array of parameters inplace
pars: 1D numpy array of length Npar
Pinfo: tuple/list of Pinfo objects of length Npar
"""
pLen = pars.size
piLen = len(Pinfo)
if(piLen != pLen):
print("[error] NormalizePars: Error, parameter array has different length than Parameter info array: {0} != {1}".format(pLen, piLen))
return 0
for ii in range(pLen):
pars[ii] = Pinfo[ii].normalize(pars[ii])
return 1
# *******************************************************
def CheckPars(pars, Pinfo):
"""
Helper function that checks an array of parameters inplace
pars: 1D numpy array of length Npar
Pinfo: tuple/list of Pinfo objects of length Npar
"""
pLen = pars.size
piLen = len(Pinfo)
if(piLen != pLen):
print("[error] CheckPars: Error, parameter array has different length than Parameter info array: {0} != {1}".format(pLen, piLen))
return 0
for ii in range(pLen):
pars[ii] = Pinfo[ii].checkLimits(pars[ii])
return 1
# *******************************************************
def _eval_fx(fx, x, pinfo, udat, auto_derivatives = False, get_J = False):
"""
Internal helper function that evaluates the user provided function fx,
and computes the Jacobian if needed. If the analytical form
of the Jacobian is unknown, this routine can do if by finite
diferences
"""
nPar = x.size
xtmp = np.copy(x)
status = ScalePars(xtmp, pinfo)
#print("kk", xtmp.size)
#print(xtmp)
if(get_J):
#
# The user does not provide a drivatives engine, compute them
# automatically. Keep your fingers crossed
#
if(auto_derivatives):
dpar = 0.001
syn = fx(xtmp, udat)
nObs = syn.size
J = np.zeros((nPar, nObs), dtype='float64')
for ii in range(nPar):
xtmp = np.copy(x)
xtmp[ii] += dpar
status = ScalePars(xtmp, pinfo)
left = fx(xtmp, udat)
xtmp = np.copy(x)
xtmp[ii] -= dpar
status = ScalePars(xtmp, pinfo)
right = fx(xtmp, udat)
J[ii] = (left - right) / (2*dpar*pinfo[ii].scl)
else: # The user provides derivatives
syn, J = fx(xtmp, udat, get_J=get_J)
return syn, J
else:
#
# No derivatives are requested
#
return fx(xtmp, udat)
# *******************************************************
def _getResidue(syn, o, s, pinfo, J = None):
"""
Internal helper function that computes the
residue and scales the Jacobian with sigma and
the sqrt of scaling factors
"""
nPar = len(pinfo)
nDat = o.size
scl = np.sqrt(1.0/nDat) / s # Includes the noise estimate!
res = scl * (o-syn)
if(J is not None):
for pp in range(nPar):
J[pp] *= scl * pinfo[pp].scl
return res
# *******************************************************
def _getChi2(res):
"""
Helper function that computes Chi2 from the residue array
"""
return (res*res).sum()
# *******************************************************
def _checkLambda(lamb, lmin, lmax, lstep):
"""
Helper function that check the lambda parameter limits
"""
if(lamb > lmax):
return lmax
elif(lamb < lmin):
return lamb*lstep*lstep
else:
return lamb
# *******************************************************
def _solveLinearSVD(A,b, svd_thres = None):
"""
Resolution of a linear system of equation using SVD
TODO: Singular value filtering for small values below
svd_thres
"""
U,s,Vh = np.linalg.svd(A)
if(svd_thres is not None):
ithr = np.abs(s).max() * svd_thres
for ii in range(len(s)):
if(s[ii] >= ithr):
s[ii] = 1.0 / s[ii]
else:
s[ii] = 0.0
else:
s = 1.0 / s
c = np.dot(U.T,np.transpose(b))
w = np.dot(np.diag(s),c)
x = np.dot(Vh.conj().T,w)
return x
# *******************************************************
def _computeNew(J, res, x, lamb, pinfo, svd_thres=None):
"""
Helper function that computes the correction
to the current estimate of the model for a given
Jacobian matrix, residues array and lambda parameter
"""
# Allocate linear system terms
# A = J.T * J, where A is a symmetric matrix
# b = J.T * res, where b is a vector
nPar, nDat = J.shape
A = np.zeros((nPar,nPar), dtype='float64')
b = np.zeros((nPar), dtype='float64')
for jj in range(nPar):
# Evaluate b = J.T * res
b[jj] = (J[jj] * res).sum()
for ii in range(jj,nPar): # Remember, it is sym!
# Evaluate A = J.T * J
tmp = (J[jj]*J[ii]).sum()
A[jj,ii] = tmp
A[ii,jj] = tmp
# Apply diagonal damping to A matrix
A[jj,jj] *= (1.0 + lamb)
# Solve linear system for correction
dx = _solveLinearSVD(A, b, svd_thres=svd_thres)
# Add correction to the current estimate of the model
xnew = x + dx
# Check parameter limits
status = ScalePars(xnew, pinfo)
status = CheckPars(xnew, pinfo)
status = NormalizePars(xnew, pinfo)
return xnew
# *******************************************************
def _getNewEstimate(fx, x, o, s, res, pinfo, udat, lamb, J, lmin, lmax, \
lstep, auto_derivatives = False, svd_thres = None):
"""
Wrapper helper function that computes a new estimate of the model
and evaluates Chi2 for this estimate for a given J, res and lambda
parameter
"""
# get nde estimate of the model for lambda parameter
xnew = _computeNew(J, res, np.copy(x), lamb, pinfo, svd_thres=svd_thres)
# get model prediction
synnew = _eval_fx(fx, xnew, pinfo, udat, auto_derivatives=auto_derivatives, get_J = False)
# residue, no J scaling this time as it is already done
res_new = _getResidue(synnew, o, s, pinfo)
new_chi2 = _getChi2(res_new)
return new_chi2, xnew, lamb
# *******************************************************
def LevMar(fx, par_in, obs_in, sig_in, pinfo, udat, Niter = 20, init_lambda=10.0, \
lmin = 1.e-4, lmax=1.e4, lstep = 10**0.5, chi2_thres=1.0, \
fx_thres=0.001, auto_derivatives = False, verbose = True, n_reject_max = 6,
svd_thres = 1.e-14):
"""
Levenberg-Marquard based fitting routine for non-linear models
Coded by <NAME> (ISP-SU 2021)
Input:
fx: a user provided function that taxes as input fx(pars, user_data, get_J = True/False)
par_in: a numpy array with the initial estimate of the model parameters (length=Npar). It will be flattened.
obs_in: a numpy array with the data to be fitted of length (Ndat). It will be flattened internally.
sig_in: a numpy array with the noise estimate for each data point (length Ndat).
pinfo: a list of Pinfo objects of length (Npar), containing the scaling norm and the parameter limits (if any).
udat: User provided data. This variable can be anyhing (a struct?) with data that will be passed to fx as an argument. The user can pack here as much info as needed.
Optional:
Niter: Maximum number of iterations (typically Niter=20)
init_lambda: Initial value of the lambda parameter that scales the diagonal of the Hessian. Typically > 1.0 when starting the fitting process.
lmin: Minimum value of lambda allowed (default 1.e-4)
lmax: Maximum value of lambda allowed (default 1.e+4)
lstep: step in lambda between iterations (lambda is divided by this number, default sqrt(10))
chi2_thres: stop the iterations if Chi2 goes below this value. | |
`{}`\nMember will be muted for: `{}`\nCustom Text for Unmute button: `{}`".format(getcur, cur_value, cust_text)
update.effective_message.reply_text(text, parse_mode="markdown")
@run_async
@user_admin
def security_mute(bot: Bot, update: Update, args: List[str]) -> str:
chat = update.effective_chat # type: Optional[Chat]
message = update.effective_message # type: Optional[Message]
getcur, cur_value, cust_text = sql.welcome_security(chat.id)
if len(args) >= 1:
var = args[0]
if var[:1] == "0":
mutetime = "0"
sql.set_welcome_security(chat.id, getcur, "0", cust_text)
text = "Every new member will be mute forever until they press the welcome button!"
else:
mutetime = extract_time(message, var)
if mutetime == "":
return
sql.set_welcome_security(chat.id, getcur, str(var), cust_text)
text = "Every new member will be muted for {} until they press the welcome button!".format(var)
update.effective_message.reply_text(text)
else:
if str(cur_value) == "0":
update.effective_message.reply_text("Current settings: New members will be mute forever until they press the button!")
else:
update.effective_message.reply_text("Current settings: New members will be mute for {} until they press the button!".format(cur_value))
@run_async
@user_admin
def security_text(bot: Bot, update: Update, args: List[str]) -> str:
chat = update.effective_chat # type: Optional[Chat]
message = update.effective_message # type: Optional[Message]
getcur, cur_value, cust_text = sql.welcome_security(chat.id)
if len(args) >= 1:
text = " ".join(args)
sql.set_welcome_security(chat.id, getcur, cur_value, text)
text = "The text of button have been changed to: `{}`".format(text)
update.effective_message.reply_text(text, parse_mode="markdown")
else:
update.effective_message.reply_text("The current security button text is: `{}`".format(cust_text), parse_mode="markdown")
@run_async
@user_admin
def security_text_reset(bot: Bot, update: Update):
chat = update.effective_chat # type: Optional[Chat]
message = update.effective_message # type: Optional[Message]
getcur, cur_value, cust_text = sql.welcome_security(chat.id)
sql.set_welcome_security(chat.id, getcur, cur_value, "Click here to prove you're human!")
update.effective_message.reply_text(" The text of security button has been reset to: `Click here to prove you're human!`", parse_mode="markdown")
@run_async
@user_admin
def cleanservice(bot: Bot, update: Update, args: List[str]) -> str:
chat = update.effective_chat # type: Optional[Chat]
if chat.type != chat.PRIVATE:
if len(args) >= 1:
var = args[0]
if (var == "no" or var == "off"):
sql.set_clean_service(chat.id, False)
update.effective_message.reply_text("I'll leave service messages")
elif(var == "yes" or var == "on"):
sql.set_clean_service(chat.id, True)
update.effective_message.reply_text("I will clean service messages")
else:
update.effective_message.reply_text("Please enter yes or no!", parse_mode=ParseMode.MARKDOWN)
else:
update.effective_message.reply_text("Please enter yes or no!", parse_mode=ParseMode.MARKDOWN)
else:
curr = sql.clean_service(chat.id)
if curr:
update.effective_message.reply_text("I will now clean `x joined the group` message!", parse_mode=ParseMode.MARKDOWN)
else:
update.effective_message.reply_text("I will no longer clean `x joined the group` message!", parse_mode=ParseMode.MARKDOWN)
@run_async
@user_admin
def welcome(bot: Bot, update: Update, args: List[str]):
chat = update.effective_chat # type: Optional[Chat]
# if no args, show current replies.
if len(args) == 0 or args[0].lower() == "noformat":
noformat = args and args[0].lower() == "noformat"
pref, welcome_m, cust_content, welcome_type = sql.get_welc_pref(chat.id)
prev_welc = sql.get_clean_pref(chat.id)
if prev_welc:
prev_welc = True
else:
prev_welc = False
cleanserv = sql.clean_service(chat.id)
getcur, cur_value, cust_text = sql.welcome_security(chat.id)
if getcur:
welcsec = "True "
else:
welcsec = "False "
if cur_value[:1] == "0":
welcsec += "(Muted forever until user clicked the button)"
else:
welcsec += "(Muting user for {})".format(cur_value)
text = "This chat has it's welcome setting set to: `{}`\n".format(pref)
text += "Deleting old welcome message: `{}`\n".format(prev_welc)
text += "Deleting service message: `{}`\n".format(cleanserv)
text += "Muting users when they joined: `{}`\n".format(welcsec)
text += "Mute button text: `{}`\n".format(cust_text)
text += "\n*The welcome message (not filling the {}) is:*"
update.effective_message.reply_text(text,
parse_mode=ParseMode.MARKDOWN)
if welcome_type == sql.Types.BUTTON_TEXT or welcome_type == sql.Types.TEXT:
buttons = sql.get_welc_buttons(chat.id)
if noformat:
welcome_m += revert_buttons(buttons)
update.effective_message.reply_text(welcome_m)
else:
keyb = build_keyboard(buttons)
keyboard = InlineKeyboardMarkup(keyb)
send(update, welcome_m, keyboard, sql.DEFAULT_WELCOME)
else:
buttons = sql.get_welc_buttons(chat.id)
if noformat:
welcome_m += revert_buttons(buttons)
ENUM_FUNC_MAP[welcome_type](chat.id, cust_content, caption=welcome_m)
else:
keyb = build_keyboard(buttons)
keyboard = InlineKeyboardMarkup(keyb)
ENUM_FUNC_MAP[welcome_type](chat.id, cust_content, caption=welcome_m, reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
elif len(args) >= 1:
if args[0].lower() in ("on", "yes"):
sql.set_welc_preference(str(chat.id), True)
update.effective_message.reply_text("New member will be greeted with warm welcome message now!")
elif args[0].lower() in ("off", "no"):
sql.set_welc_preference(str(chat.id), False)
update.effective_message.reply_text("I'm sulking, Not saying hello anymore :V")
else:
# idek what you're writing, say yes or no
update.effective_message.reply_text("Please choose 'on/yes' or 'off/no' only!")
@run_async
@user_admin
def goodbye(bot: Bot, update: Update, args: List[str]):
chat = update.effective_chat # type: Optional[Chat]
if len(args) == 0 or args[0] == "noformat":
noformat = args and args[0] == "noformat"
pref, goodbye_m, cust_content, goodbye_type = sql.get_gdbye_pref(chat.id)
update.effective_message.reply_text(
"This chat has it's goodbye setting set to: `{}`.\n*The goodbye message "
"(not filling the {{}}) is:*".format(pref),
parse_mode=ParseMode.MARKDOWN)
if goodbye_type == sql.Types.BUTTON_TEXT:
buttons = sql.get_gdbye_buttons(chat.id)
if noformat:
goodbye_m += revert_buttons(buttons)
update.effective_message.reply_text(goodbye_m)
else:
keyb = build_keyboard(buttons)
keyboard = InlineKeyboardMarkup(keyb)
send(update, goodbye_m, keyboard, sql.DEFAULT_GOODBYE)
else:
buttons = sql.get_gdbye_buttons(chat.id)
if noformat:
goodbye_m += revert_buttons(buttons)
ENUM_FUNC_MAP[goodbye_type](chat.id, cust_content, caption=goodbye_m)
else:
keyb = build_keyboard(buttons)
keyboard = InlineKeyboardMarkup(keyb)
ENUM_FUNC_MAP[goodbye_type](chat.id, cust_content, caption=goodbye_m, reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
elif len(args) >= 1:
if args[0].lower() in ("on", "yes"):
sql.set_gdbye_preference(str(chat.id), True)
try:
update.effective_message.reply_text("I'll be sorry when people leave!")
except:
print("Nut")
elif args[0].lower() in ("off", "no"):
sql.set_gdbye_preference(str(chat.id), False)
update.effective_message.reply_text("They leave, they're dead to me.")
else:
# idek what you're writing, say yes or no
update.effective_message.reply_text("I understand 'on/yes' or 'off/no' only!")
@run_async
@user_admin
@loggable
def set_welcome(bot: Bot, update: Update) -> str:
chat = update.effective_chat # type: Optional[Chat]
user = update.effective_user # type: Optional[User]
msg = update.effective_message # type: Optional[Message]
# If user is not set text and not reply a message
if not msg.reply_to_message:
if len(msg.text.split()) == 1:
msg.reply_text("You must provide the contents in a welcome message!/n Type `/welcomehelp` for some help at welcome!", parse_mode="markdown")
return ""
text, data_type, content, buttons = get_welcome_type(msg)
if data_type is None:
msg.reply_text("You didn't specify what to reply with!")
return ""
sql.set_custom_welcome(chat.id, content, text, data_type, buttons)
msg.reply_text("Successfully set custom welcome message!")
return "<b>{}:</b>" \
"\n#SET_WELCOME" \
"\n<b>Admin:</b> {}" \
"\nSet the welcome message.".format(escape(chat.title),
mention_html(user.id, user.first_name))
@run_async
@user_admin
@loggable
def reset_welcome(bot: Bot, update: Update) -> str:
chat = update.effective_chat # type: Optional[Chat]
user = update.effective_user # type: Optional[User]
sql.set_custom_welcome(chat.id, None, sql.DEFAULT_WELCOME, sql.Types.TEXT)
update.effective_message.reply_text("Successfully reset welcome message to default!")
return "<b>{}:</b>" \
"\n#RESET_WELCOME" \
"\n<b>Admin:</b> {}" \
"\nReset the welcome message to default.".format(escape(chat.title),
mention_html(user.id, user.first_name))
@run_async
@user_admin
@loggable
def set_goodbye(bot: Bot, update: Update) -> str:
chat = update.effective_chat # type: Optional[Chat]
user = update.effective_user # type: Optional[User]
msg = update.effective_message # type: Optional[Message]
text, data_type, content, buttons = get_welcome_type(msg)
# If user is not set text and not reply a message
if not msg.reply_to_message:
if len(msg.text.split()) == 1:
msg.reply_text("You must provide the contents in a welcome message!/n Type `/welcomehelp` for some help at welcome!", parse_mode="markdown")
return ""
if data_type is None:
msg.reply_text("You didn't specify what to reply with!")
return ""
sql.set_custom_gdbye(chat.id, content, text, data_type, buttons)
msg.reply_text("Successfully set custom goodbye message!")
return "<b>{}:</b>" \
"\n#SET_GOODBYE" \
"\n<b>Admin:</b> {}" \
"\nSet the goodbye message.".format(escape(chat.title),
mention_html(user.id, user.first_name))
@run_async
@user_admin
@loggable
def reset_goodbye(bot: Bot, update: Update) -> str:
chat = update.effective_chat # type: Optional[Chat]
user = update.effective_user # type: Optional[User]
sql.set_custom_gdbye(chat.id, None, sql.DEFAULT_GOODBYE, sql.Types.TEXT)
update.effective_message.reply_text("Successfully reset goodbye message to default!")
return "<b>{}:</b>" \
"\n#RESET_GOODBYE" \
"\n<b>Admin:</b> {}" \
"\nReset the goodbye message.".format(escape(chat.title),
mention_html(user.id, user.first_name))
@run_async
@user_admin
@loggable
def clean_welcome(bot: Bot, update: Update, args: List[str]) -> str:
chat = update.effective_chat # type: Optional[Chat]
user = update.effective_user # type: Optional[User]
if not args:
clean_pref = sql.get_clean_pref(chat.id)
if clean_pref:
update.effective_message.reply_text("I should be deleting welcome messages up to two days old.")
else:
update.effective_message.reply_text("I'm currently not deleting old welcome messages!")
return ""
if args[0].lower() in ("on", "yes"):
sql.set_clean_welcome(str(chat.id), True)
update.effective_message.reply_text("I'll try to delete old welcome messages!")
return "<b>{}:</b>" \
"\n#CLEAN_WELCOME" \
"\n<b>Admin:</b> {}" \
"\nHas toggled clean welcomes to <code>ON</code>.".format(escape(chat.title),
mention_html(user.id, user.first_name))
elif args[0].lower() in ("off", "no"):
sql.set_clean_welcome(str(chat.id), False)
update.effective_message.reply_text("I won't delete old welcome messages.")
return "<b>{}:</b>" \
"\n#CLEAN_WELCOME" \
"\n<b>Admin:</b> {}" \
"\nHas toggled clean welcomes to <code>OFF</code>.".format(escape(chat.title),
mention_html(user.id, user.first_name))
else:
# idek what you're writing, say yes or no
update.effective_message.reply_text("I understand 'on/yes' or 'off/no' only!")
return ""
# TODO: get welcome data from group butler snap
# def __import_data__(chat_id, data):
# welcome = data.get('info', {}).get('rules')
# welcome = welcome.replace('$username', '{username}')
# welcome = welcome.replace('$name', '{fullname}')
# welcome = welcome.replace('$id', '{id}')
# welcome = welcome.replace('$title', '{chatname}')
# welcome = welcome.replace('$surname', '{lastname}')
# welcome = welcome.replace('$rules', '{rules}')
# sql.set_custom_welcome(chat_id, welcome, sql.Types.TEXT)
def __migrate__(old_chat_id, new_chat_id):
sql.migrate_chat(old_chat_id, new_chat_id)
def __chat_settings__(chat_id, user_id):
welcome_pref, _, _, _ = sql.get_welc_pref(chat_id)
goodbye_pref, _, _, _ = sql.get_gdbye_pref(chat_id)
cleanserv = sql.clean_service(chat_id)
def __migrate__(old_chat_id, new_chat_id):
sql.migrate_chat(old_chat_id, new_chat_id)
def __chat_settings__(bot, update, chat, chatP, user):
chat_id = chat.id
welcome_pref, _, _, _ = sql.get_welc_pref(chat_id)
goodbye_pref, _, _, _ = sql.get_gdbye_pref(chat_id)
return "This chat has it's welcome preference set to `{}`.\n" \
"It's goodbye preference is `{}`.".format(welcome_pref, goodbye_pref)
__help__ = """
Give your members a warm welcome with the greetings module! Or a sad goodbye... Depends!
Available commands are:
- /welcome <on/off/yes/no>: | |
= 'an' if txt[0] in ['a', 'e', 'i', 'o', 'u'] else 'a'
return txt
return pre
# -- Messaging commands -- #
def send_action(self, agent_id, action):
"""
Parse the action and send it to the agent with send_msg.
"""
if action['caller'] is None:
val = self.extract_classed_from_dict(action['txt'], agent_id, '')
if type(val) is dict and 'iter' in val:
i = val['iter']
val['iter'] = (i + 1) % len(val['data'])
extracted_text = val['data'][i]
else:
extracted_text = val
self.send_msg(agent_id, extracted_text, action)
return
try:
func_wrap = GRAPH_FUNCTIONS[action['caller']]
except BaseException:
func_wrap = CONSTRAINTS[action['caller']]
try:
t = func_wrap.format_observation(self, agent_id, action).rstrip()
except Exception:
return # the agent doesn't accept observations
t += ' '
self.send_msg(agent_id, t, action)
def send_msg(self, agent_id, txt, action=None):
"""
Send an agent an action and a message.
"""
if agent_id in self._node_to_text_buffer:
if action is None:
action = {
'caller': None,
'room_id': self.location(agent_id),
'txt': txt,
}
if not hasattr(self, '_node_to_observations'):
# TODO remove when all the samples are converted
self._node_to_observations = {}
if agent_id not in self._node_to_observations:
self._node_to_observations[agent_id] = []
self._node_to_observations[agent_id].append(action)
self._node_to_text_buffer[agent_id] += txt
if agent_id in self.__message_callbacks:
self.__message_callbacks[agent_id](self, action)
def broadcast_to_room(self, action, exclude_agents=None, told_by=None):
"""
send a message to everyone in a room.
"""
if exclude_agents is None:
exclude_agents = []
else:
exclude_agents = list(exclude_agents)
agents_list, _descs = self.get_room_agents(action['room_id'])
agents = set(agents_list)
if 'actors' in action:
# send message to the actor first
actor = action['actors'][0]
if actor in agents and actor not in exclude_agents:
self.send_action(actor, action)
exclude_agents.append(actor)
action['present_agent_ids'] = agents
for a in agents:
if a in exclude_agents:
continue
self.send_action(a, action)
# ----------------------------------------------------------------
# TODO: Ideally, all functions below do not use the graph structure
# directly but only the accessor functions (should not use self._node_* ).
# -- Helpers -- #
def clean_props(self, object_id):
"""
ensures all necessary props are set on items that might not have been on earlier
versions of graphworld.
"""
# TODO remove when all samples are converted
size = self.get_prop(object_id, 'size')
if size is None or type(size) == bool:
self.set_prop(object_id, 'size', 1)
contain_size = self.get_prop(object_id, 'contain_size')
if contain_size is None or type(contain_size) == bool:
self.set_prop(object_id, 'contain_size', 3)
classes = self.get_prop(object_id, 'classes')
if type(classes) == str:
self.set_prop(object_id, 'classes', [classes])
elif type(classes) != list:
self.set_prop(object_id, 'classes', [])
# -- Commands -- #
def create(self, agent_id, params):
# -- create commands: --
# *create room kitchen -> creates room with path from this room
# *create path kitchen -> create path to that room from this one
# *create agent orc
# *create object ring
# *create key golden key
# create lockable tower with golden key
# create container box
# create [un]freeze
# create reset/load/save [fname]
# create rename <node> <value> <-- **crashes*
# create delete <node>
# create set_prop orc to health=5
from parlai_internal.tasks.graph_world3.class_nodes import (
create_thing,
CLASS_NAMES,
)
if not self.has_prop(agent_id, 'agent'):
return False, 'create'
if params is None:
return False, 'create'
room_id = self.room(agent_id)
all_params = ' '.join(params)
txt = ' '.join(params[1:])
resp = 'create ' + ' '.join(params)
if not (all_params in ['save', 'load', 'freeze', 'unfreeze']):
if txt == '':
return False, resp
if params[0] == 'print':
ids = self.desc_to_nodes(txt, nearbyid=agent_id, nearbytype='all')
if len(ids) == 0:
self.send_msg(agent_id, "Not found.\n ")
return False, resp
id = ids[0]
self.send_msg(agent_id, id + " has:\n{}".format(self._node_to_prop[id]))
return True, resp
if params[0] == 'save':
self.save_graph(txt)
self.send_msg(agent_id, "[ saved: " + self._save_fname + ' ]\n')
return True, resp
if params[0] == 'load' or params[0] == 'reset':
self.load_graph(txt)
self.send_msg(agent_id, "[ loaded: " + self._save_fname + ' ]\n')
return True, resp
if params[0] == 'freeze':
self.freeze(True)
self.send_msg(agent_id, "Frozen.\n")
return True, resp
if params[0] == 'unfreeze':
self.freeze(False)
self.send_msg(agent_id, "Unfrozen.\n")
return True, resp
if params[0] in ['delete', 'del', 'rm']:
ids = self.desc_to_nodes(txt, nearbyid=agent_id, nearbytype='all')
if len(ids) == 0:
self.send_msg("Not found.\n ")
return False, resp
id = ids[0]
self.delete_node(id)
self.send_msg(agent_id, "Deleted.\n")
return True, resp
if params[0] == 'rename':
params = self.split_params(params[1:], 'to')
to_ids = self.desc_to_nodes(params[0], nearbyid=agent_id, nearbytype='all')
if len(to_ids) == 0:
self.send_msg("Not found.\n ")
return False, resp
to_id = to_ids[0]
self.set_desc(to_id, params[1])
self.send_msg(agent_id, "Done.\n")
return True, resp
if params[0] == 'agent':
create_thing(self, room_id, params[0], force=True, use_name=txt)
self.send_msg(agent_id, "Done.\n")
return True, resp
if params[0] == 'room':
new_id = self.add_node(txt, params[0])
self.add_path_to(new_id, room_id)
self.set_prop(new_id, 'contain_size', 2000)
self.send_msg(agent_id, "Done.\n")
return True, resp
if params[0] == 'set_prop':
params = self.split_params(params[1:], 'to')
to_ids = self.desc_to_nodes(params[0], nearbyid=agent_id, nearbytype='all')
if len(to_ids) == 0:
self.send_msg("Not found.\n ")
return False, resp
to_id = to_ids[0]
key = params[1]
value = True
if '=' in key:
sp = key.split('=')
if len(sp) != 2:
return False, resp
key = sp[0]
value = sp[1]
if value == 'True':
value = True
try:
value = int(value)
except ValueError:
pass
self.set_prop(to_id, key, value)
self.send_msg(agent_id, "Done.\n")
return True, resp
if params[0] in CLASS_NAMES:
if params[0] == 'key' and txt.find('key') == -1:
self.send_msg(agent_id, "Keys must be called keys!\n")
return False, resp
create_thing(self, room_id, params[0], force=True, use_name=txt)
self.send_msg(agent_id, "Done.\n")
return True, resp
if params[0] == 'lockable':
ps = self.split_params(params[1:], 'with')
if len(ps) != 2:
return False, resp
to_ids = self.desc_to_nodes(ps[0], nearbyid=agent_id, nearbytype='all')
with_ids = self.desc_to_nodes(ps[1], nearbyid=agent_id, nearbytype='all')
if len(to_ids) == 0 or len(with_ids) == 0:
self.send_msg("Something was not found.\n ")
return False, resp
to_id = to_ids[0]
with_id = with_ids[0]
if not self.get_prop(with_id, 'key'):
self.send_msg(agent_id, "You need to use a key!\n")
return False, resp
self.set_prop(to_id, 'locked_with', with_id)
self.set_prop(to_id, 'locked', True)
self.send_msg(agent_id, "Done.\n")
return True, resp
if params[0] == 'path':
to_id = self.desc_to_nodes(txt)
if to_id is False:
return False, resp
self.add_path_to(to_id, room_id)
self.send_msg(agent_id, "Done.\n")
return True, resp
self.send_msg(agent_id, 'Create is not supported for: ' + resp)
return False, resp
# -- Create helpers -- #
def split_params(self, params, word):
if type(word) is str:
word = {word}
for w in word:
search = ' {} '.format(w)
phrase = ' '.join(params)
if phrase.find(w) != -1:
return phrase.split(search)
return None
# -- GraphFunction Helpers -- #
def obj_fits(self, object_id, container_id):
"""
Return if one object will fit into another.
"""
size = self.get_prop(object_id, 'size')
max_size = self.get_prop(container_id, 'contain_size')
if size is None or max_size is None:
# TODO log these kinds of things
print(
'None compare between {} and {}'.format(object_id, container_id),
self._node_to_prop,
)
return size <= max_size
def move_object(self, object_id, container_id):
"""
Move an object from wherever it is into somewhere else.
"""
size = self.get_prop(object_id, 'size')
# Remove from the old container
old_id = self.node_contained_in(object_id)
if old_id is not None:
contain_size = self.get_prop(old_id, 'contain_size')
contain_size += size
self.set_prop(old_id, 'contain_size', contain_size)
# Put in the new container
contain_size = self.get_prop(container_id, 'contain_size')
contain_size -= size
self.set_prop(container_id, 'contain_size', contain_size)
self.add_contained_in(object_id, container_id)
def die(self, id):
"""
Update an agent into a dead state.
"""
if not self.has_prop(id, 'agent'):
return False
if self.get_prop(id, 'is_player', False) is True:
self.set_follow(id, None)
room = self.location(id)
add_text = ''
contents = self.node_contains(id)
if len(contents) > 0:
add_text += '[*SPLIT*] Your travel companion leaves behind {}.'.format(
self.display_node_list(contents)
)
for content in contents:
self.move_object(content, room)
text = {
'elf': "Josephine collapses to the ground! "
"She looks like she's asleep except for an awful "
"stillness about her. Although her home is in the "
"mountains, she seems a part of the woods as well. You "
"hope to meet her again in the next life. And as you "
"think this, a bright white light filters through the "
"trees, engulfing the troll's peaceful form. You stare in "
"wonder: when the light fades away, so does Josephine!" + add_text,
'troll': "You watch in horror as the elf drops lifelessly to the "
"ground. Lying there, Alixlior looks strangely peaceful "
"and as much a part of the woods as when alive. You know "
"that were your friend alive, you would be told not to "
"mourn and that all of this is a journey that will repeat "
"itself - where you will undoubtedly meet again. But for "
"now, this kind of blows. Before you can wonder if you "
"should conduct a burial ceremony, | |
3.2, 2.8, 2.5, 2.8, 2.9, 3, 2.8, 3, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3, 3.4, 3.1, 2.3, 3, 2.5, 2.6, 3, 2.6, 2.3, 2.7, 3, 2.9, 2.9, 2.5, 2.8],
"y": [4.7, 4.5, 4.9, 4, 4.6, 4.5, 4.7, 3.3, 4.6, 3.9, 3.5, 4.2, 4, 4.7, 3.6, 4.4, 4.5, 4.1, 4.5, 3.9, 4.8, 4, 4.9, 4.7, 4.3, 4.4, 4.8, 5, 4.5, 3.5, 3.8, 3.7, 3.9, 5.1, 4.5, 4.5, 4.7, 4.4, 4.1, 4, 4.4, 4.6, 4, 3.3, 4.2, 4.2, 4.2, 4.3, 3, 4.1],
# "marker": {
# "color": "rgb(255, 127, 14)",
# "line": {
# "color": "rgb(255, 255, 255)",
# "width": 0.5
# },
# "opacity": 0.74,
# "size": 8
# },
# "mode": "markers",
# "name": "versicolor",
# "type": "scatter",
# "uid": "b68390",
"xaxis": "x2",
"yaxis": "y"
}
trace27 = {
"x": [3.3, 2.7, 3, 2.9, 3, 3, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3, 2.5, 2.8, 3.2, 3, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3, 2.8, 3, 2.8, 3.8, 2.8, 2.8, 2.6, 3, 3.4, 3.1, 3, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3, 2.5, 3, 3.4, 3],
"y": [6, 5.1, 5.9, 5.6, 5.8, 6.6, 4.5, 6.3, 5.8, 6.1, 5.1, 5.3, 5.5, 5, 5.1, 5.3, 5.5, 6.7, 6.9, 5, 5.7, 4.9, 6.7, 4.9, 5.7, 6, 4.8, 4.9, 5.6, 5.8, 6.1, 6.4, 5.6, 5.1, 5.6, 6.1, 5.6, 5.5, 4.8, 5.4, 5.6, 5.1, 5.1, 5.9, 5.7, 5.2, 5, 5.2, 5.4, 5.1],
# "marker": {
# "color": "rgb(44, 160, 44)",
# "line": {
# "color": "rgb(255, 255, 255)",
# "width": 0.5
# },
# "opacity": 0.74,
# "size": 8
# },
# "mode": "markers",
# "name": "virginica",
# "type": "scatter",
# "uid": "008418",
"xaxis": "x2",
"yaxis": "y"
}
trace28 = {
"x": [3.5, 3, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3, 3, 4, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3.6, 3, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3, 3.8, 3.2, 3.7, 3.3],
"y": [0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1, 0.2, 0.2, 0.3, 0.3, 0.2, 0.6, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2],
# "marker": {
# "color": "rgb(31, 119, 180)",
# "line": {
# "color": "rgb(255, 255, 255)",
# "width": 0.5
# },
# "opacity": 0.74,
# "size": 8
# },
# "mode": "markers",
# "name": "setosa",
# "type": "scatter",
# "uid": "4332db",
"xaxis": "x2",
"yaxis": "y"
}
trace29 = {
"x": [3.2, 3.2, 3.1, 2.3, 2.8, 2.8, 3.3, 2.4, 2.9, 2.7, 2, 3, 2.2, 2.9, 2.9, 3.1, 3, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8, 2.9, 3, 2.8, 3, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3, 3.4, 3.1, 2.3, 3, 2.5, 2.6, 3, 2.6, 2.3, 2.7, 3, 2.9, 2.9, 2.5, 2.8],
"y": [1.4, 1.5, 1.5, 1.3, 1.5, 1.3, 1.6, 1, 1.3, 1.4, 1, 1.5, 1, 1.4, 1.3, 1.4, 1.5, 1, 1.5, 1.1, 1.8, 1.3, 1.5, 1.2, 1.3, 1.4, 1.4, 1.7, 1.5, 1, 1.1, 1, 1.2, 1.6, 1.5, 1.6, 1.5, 1.3, 1.3, 1.3, 1.2, 1.4, 1.2, 1, 1.3, 1.2, 1.3, 1.3, 1.1, 1.3],
# "marker": {
# "color": "rgb(255, 127, 14)",
# "line": {
# "color": "rgb(255, 255, 255)",
# "width": 0.5
# },
# "opacity": 0.74,
# "size": 8
# },
# "mode": "markers",
# "name": "versicolor",
# "type": "scatter",
# "uid": "bd5eb9",
"xaxis": "x2",
"yaxis": "y"
}
trace30 = {
"x": [3.3, 2.7, 3, 2.9, 3, 3, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3, 2.5, 2.8, 3.2, 3, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3, 2.8, 3, 2.8, 3.8, 2.8, 2.8, 2.6, 3, 3.4, 3.1, 3, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3, 2.5, 3, 3.4, 3],
"y": [2.5, 1.9, 2.1, 1.8, 2.2, 2.1, 1.7, 1.8, 1.8, 2.5, 2, 1.9, 2.1, 2, 2.4, 2.3, 1.8, 2.2, 2.3, 1.5, 2.3, 2, 2, 1.8, 2.1, 1.8, 1.8, 1.8, 2.1, 1.6, 1.9, 2, 2.2, 1.5, 1.4, 2.3, 2.4, 1.8, 1.8, 2.1, 2.4, 2.3, 1.9, 2.3, 2.5, 2.3, 1.9, 2, 2.3, 1.8],
# "marker": {
# "color": "rgb(44, 160, 44)",
# "line": {
# "color": "rgb(255, 255, 255)",
# "width": 0.5
# },
# "opacity": 0.74,
# "size": 8
# },
# "mode": "markers",
# "name": "virginica",
# "type": "scatter",
# "uid": "a0f680",
"xaxis": "x2",
"yaxis": "y"
}
trace31 = {
"x": [3.5, 3, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3, 3, 4, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3.6, 3, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3, 3.8, 3.2, 3.7, 3.3],
"y": [3.5, 3, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3, 3, 4, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3.6, 3, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3, 3.8, 3.2, 3.7, 3.3],
# "marker": {
# "color": "rgb(31, 119, 180)",
# "line": {
# "color": "rgb(255, 255, 255)",
# "width": 0.5
# },
# "opacity": 0.74,
# "size": 8
# },
# "mode": "markers",
# "name": "setosa",
# "type": "scatter",
# "uid": "7b50ba",
"xaxis": "x2",
"yaxis": "y2"
}
trace32 = {
"x": [3.2, 3.2, 3.1, 2.3, 2.8, 2.8, 3.3, 2.4, 2.9, 2.7, 2, 3, 2.2, 2.9, 2.9, 3.1, 3, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8, 2.9, 3, 2.8, 3, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3, 3.4, 3.1, 2.3, 3, 2.5, 2.6, 3, 2.6, 2.3, 2.7, 3, 2.9, 2.9, 2.5, 2.8],
"y": [3.2, 3.2, 3.1, 2.3, 2.8, 2.8, 3.3, 2.4, 2.9, 2.7, 2, 3, 2.2, 2.9, 2.9, 3.1, 3, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8, 2.9, 3, 2.8, 3, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3, 3.4, 3.1, 2.3, 3, 2.5, 2.6, 3, 2.6, 2.3, 2.7, 3, 2.9, 2.9, 2.5, 2.8],
# "marker": {
# "color": "rgb(255, 127, 14)",
# "line": {
# "color": "rgb(255, 255, 255)",
# "width": 0.5
# },
# "opacity": 0.74,
# "size": 8
# },
# "mode": "markers",
# "name": "versicolor",
# "type": "scatter",
# "uid": "851d88",
"xaxis": "x2",
"yaxis": "y2"
}
trace33 = {
"x": [3.3, 2.7, 3, 2.9, 3, 3, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3, 2.5, 2.8, 3.2, 3, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3, 2.8, 3, 2.8, 3.8, 2.8, 2.8, 2.6, 3, 3.4, 3.1, 3, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3, 2.5, 3, 3.4, 3],
"y": [3.3, 2.7, 3, 2.9, 3, 3, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3, 2.5, 2.8, 3.2, 3, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3, 2.8, 3, 2.8, 3.8, 2.8, 2.8, 2.6, 3, 3.4, 3.1, 3, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3, 2.5, 3, 3.4, 3],
# "marker": {
# "color": "rgb(44, 160, 44)",
# "line": {
# "color": "rgb(255, 255, 255)",
# "width": 0.5
# },
# "opacity": 0.74,
# "size": 8
# },
# "mode": "markers",
# "name": "virginica",
# "type": "scatter",
# "uid": "f59103",
"xaxis": "x2",
"yaxis": "y2"
}
trace34 = {
"x": [3.5, 3, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3, 3, 4, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3.6, 3, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3, 3.8, 3.2, 3.7, 3.3],
"y": [5.1, 4.9, 4.7, 4.6, 5, 5.4, 4.6, 5, 4.4, 4.9, 5.4, 4.8, 4.8, 4.3, 5.8, 5.7, 5.4, 5.1, 5.7, 5.1, 5.4, 5.1, 4.6, 5.1, 4.8, 5, 5, 5.2, 5.2, 4.7, 4.8, 5.4, 5.2, 5.5, 4.9, 5, 5.5, 4.9, 4.4, 5.1, 5, 4.5, 4.4, 5, 5.1, 4.8, 5.1, 4.6, 5.3, 5],
# "marker": {
# "color": "rgb(31, 119, | |
<reponame>RoyaFiroozi/barc<filename>barc_ros_packages/barc_general/src/state_estimation_bm/main.py
#!/usr/bin/env python
# ---------------------------------------------------------------------------
# Licensing Information: You are free to use or extend these projects for
# education or reserach purposes provided that (1) you retain this notice
# and (2) you provide clear attribution to UC Berkeley, including a link
# to http://barc-project.com
#
# Attibution Information: The barc project ROS code-base was developed
# at UC Berkeley in the Model Predictive Control (MPC) lab by <NAME>
# (<EMAIL>). The cloud services integation with ROS was developed
# by <NAME> (<EMAIL>). The web-server app Dator was
# based on an open source project by <NAME>
# ---------------------------------------------------------------------------
import rospy
import time
import os
import math
from sensor_msgs.msg import Imu, NavSatFix
from barc.msg import ECU, Encoder, Z_KinBkMdl, pos_info
from numpy import pi, cos, sin, eye, array, zeros, unwrap, tan, diag
from observers import ekf, ukf
from system_models import f_KinBkMdl, h_KinBkMdl
from tf import transformations
from lla2flat import lla2flat
from Localization_helpers import Localization
from std_msgs.msg import Header
from SteeringMap import servo2df
# from numpy import unwrap
# input variables [default values]
d_f = 0 # steering angle [rad]
acc = 0 # velocity from encoders [m/s] - if state estimator model is changed, this will most likely become acceleration
# desired input variables from MPC [default values]
d_f_cmd = 0 # steering angle [rad]
acc_cmd = 0 # acceleration [m**2/s]
# initial (servo_pwm,curve,bm) (see SteeringMap.py)
# servo_pwm_init = 1500
# args_servo2df = (servo_pwm_init,0,0.0772518905741900-(-0.000371249151551210)*servo_pwm_init)
# raw measurement variables for IMU
yaw_prev = 0
(roll, pitch, yaw, a_x, a_y, a_z, w_x, w_y, w_z) = zeros(9)
yaw_prev = 0
yaw_local = 0
read_yaw0 = False
psi = 0
psi_meas = 0
new_imu_meas = False
# from encoder
v_meas = 0.0
t0 = time.time()
ang_km1 = 0.0
ang_km2 = 0.0
n_FL = 0.0
n_FR = 0.0
n_BL = 0.0
n_BR = 0.0
r_tire = rospy.get_param("r_tire") # radius of the tire
new_enc_meas = False
# for vel_est additionally:
v_est_FL = 0.0
v_est_FR = 0.0
v_est_BL = 0.0
v_est_BR = 0.0
# from gps
x_local = 0.0
y_local = 0.0
z_local = 0.0
gps_first_call = True
new_gps_meas = False
psio_gps = rospy.get_param("psio_gps") # initial heading angle GPS
sim_mode = rospy.get_param("sim_mode") # indicates whether we are in simulation without /ecu topic
# ecu command update
def ecu_callback(data):
global acc_cmd, d_f_cmd
acc_cmd = data.motor # input acceleration
d_f_cmd = data.servo # input steering angle
# ecu_pwm command update
def ecu_pwm_callback(data):
# read only steering angle from ecu_pwm (acceleration map not really good)
global d_f, acc, args_servo2df
motor_pwm = data.motor
servo_pwm = data.servo
# use steering command map to get d_f
# (d_f,args_servo2df) = servo2df(servo_pwm,args_servo2df)
# d_f = -0.000527833480631484*servo_pwm+0.836616066800903#0.842150600118722
d_f = -0.000525151156156895*servo_pwm+0.834465187133306 #0.832364582508679#0.838026451730028
#d_f = -0.000479973711852115*servo_pwm+0.758358464726342
#d_f = -4.838020766400743*10**(-4)*servo_pwm+0.775758994667799 #5/9.0*(-0.000935851818915458*servo_pwm + 1.48382531174335) #5/12.0*(-0.0012*servo_pwm + 1.8962) #
# assign the acc input the last measurement from the IMU (noisy!) in direction of the v for KinBkMdl
# L_a = vhMdl[0]
# L_b = vhMdl[1]
# bta = math.atan2( L_b * tan(d_f),(L_a + L_b) )
# v_x_meas = v_meas*cos(d_f)
# acc = (a_x+w_z*v_x_meas*tan(bta))*cos(bta)+(a_y-w_z*v_x_meas)*sin(bta)
# acc = a_x
acc = v_meas
# GPS measurement update
def gps_callback(data):
global x_local, y_local, z_local, gps_first_call, gps_lat_init, gps_lng_init, gps_alt_init, new_gps_meas
gps_latitude = data.latitude
gps_longitude = data.longitude
gps_altitude = data.altitude
# save the initial measurement (after MPC has been solved the first time)
if gps_first_call:
gps_lat_init = gps_latitude
gps_lng_init = gps_longitude
gps_alt_init = gps_altitude
if acc_cmd!=0 or sim_mode:
gps_first_call = False
# compute x,y,z coordinates respectively
(x_gps, y_gps, z_gps) = lla2flat((gps_latitude, gps_longitude, gps_altitude),(gps_lat_init, gps_lng_init), psio_gps, gps_alt_init) # 115: FifteenThreePihalf.bag -yaw0*180/pi+115
x_local = x_gps
y_local = y_gps
z_gps = z_gps
# indicate that a new measurement has been received
new_gps_meas = True
# imu measurement update
def imu_callback(data):
# units: [rad] and [rad/s]
global roll, pitch, yaw, a_x, a_y, a_z, w_x, w_y, w_z
global yaw_prev, yaw0, read_yaw0, yaw_local, psi_meas
global new_imu_meas
# get orientation from quaternion data, and convert to roll, pitch, yaw
# extract angular velocity and linear acceleration data
ori = data.orientation
quaternion = (ori.x, ori.y, ori.z, ori.w)
(roll, pitch, yaw) = transformations.euler_from_quaternion(quaternion)
# save initial measurements (after MPC has been solved the first time)
if not read_yaw0:
if acc_cmd!=0 or sim_mode:
read_yaw0 = True
yaw_prev = yaw
yaw0 = yaw
# unwrap measurement
yaw = unwrap(array([yaw_prev, yaw]), discont = pi)[1]
yaw_prev = yaw
yaw_local = yaw - yaw0
psi_meas = yaw_local
# extract angular velocity and linear acceleration data
w_x = data.angular_velocity.x
w_y = data.angular_velocity.y
w_z = data.angular_velocity.z
a_x = data.linear_acceleration.x
a_y = data.linear_acceleration.y
a_z = data.linear_acceleration.z
# indicate that a new measurement has been received
new_imu_meas = True
# encoder measurement update
def enc_callback(data):
global t0, v_meas, new_enc_meas
global n_FL, n_FR, n_BL, n_BR
global ang_km1, ang_km2
n_FL = data.FL
n_FR = data.FR
n_BL = data.BL
n_BR = data.BR
# compute the average encoder measurement (no slip at front wheels)
n_mean = (n_FL + n_FR)/2.0
# transfer the encoder measurement to angular displacement
ang_mean = n_mean*2*pi/8.0
# compute time elapsed
tf = time.time()
dt = tf - t0
# compute speed with second-order, backwards-finite-difference estimate
v_meas = r_tire*(3*ang_mean - 4*ang_km1 + ang_km2)/(2*dt)
# update old data
ang_km2 = ang_km1
ang_km1 = ang_mean
t0 = time.time()
# indicate that a new measurement has been received
# Uncomment this if the encoder measurements are used to correct the estimates
# new_enc_meas = True
# velocity estimation callback
def vel_est_callback(data):
# This relies on the published information to the topic vel_est (estimate
# produced in Arduino) and is not used for now since the second order
# finite backwards difference is more accurate (see enc_callback)
global v_meas, new_enc_meas
v_est_FL = data.FL
v_est_FR = data.FR
v_est_BL = data.BL
v_est_BR = data.BR
# (once it comes to wheels taking off or wrong enc meas. from one wheel, think about what makes sense)
# idea: Get an estimate also from the integration of acceleration from the IMU and compare to vel_est (drifting?)
v_meas = (v_est_FL + v_est_FR)/2.0
# indicate that a new measurement has been received
# Uncomment this if the encoder measurements are used to correct the estimates
# new_enc_meas = True
# state estimation node
def state_estimation():
global dt_v_enc
global v_meas, psi_meas
global x_local, y_local
global new_enc_meas, new_gps_meas, new_imu_meas
global vhMdl
# initialize node
rospy.init_node('state_estimation_bm', anonymous=True)
# topic subscriptions / publications
rospy.Subscriber('imu/data', Imu, imu_callback)
rospy.Subscriber('encoder', Encoder, enc_callback)
# rospy.Subscriber('vel_est', Encoder, vel_est_callback)
rospy.Subscriber('ecu', ECU, ecu_callback)
rospy.Subscriber('ecu_pwm', ECU, ecu_pwm_callback)
rospy.Subscriber('fix', NavSatFix, gps_callback)
state_pub = rospy.Publisher('state_estimate', Z_KinBkMdl, queue_size = 10)
state_pub_pos = rospy.Publisher('pos_info', pos_info, queue_size = 10)
# for debugging
meas_pub = rospy.Publisher('meas', Z_KinBkMdl, queue_size = 10)
u_pub = rospy.Publisher('u', ECU, queue_size = 10)
# get vehicle dimension parameters
L_a = rospy.get_param("L_a") # distance from CoG to front axel
L_b = rospy.get_param("L_b") # distance from CoG to rear axel
vhMdl = (L_a, L_b)
# get encoder parameters
dt_v_enc = rospy.get_param("state_estimation/dt_v_enc") # time interval to compute v_x from encoders
# get EKF observer properties
q_std = rospy.get_param("state_estimation/q_std") # std of process noise
r_std = rospy.get_param("state_estimation/r_std") # std of measurementnoise
# get measurement model type according to incorporated sensors
est_mode = rospy.get_param("state_estimation/est_mode")
##################################################################################################################################
# Set up track parameters (for simulation, this needs to be changed according to the track the sensor data was recorded for)
l = Localization()
l.create_track()
est_counter = 0
##################################################################################################################################
# set node rate
loop_rate = 50
dt = 1.0 / loop_rate
rate = rospy.Rate(loop_rate)
t0 = time.time()
# initial state vector (mean)
x_EKF = zeros(4)
# estimation variables for the filter (covariances)
# make the uncertainty in the initial psi and/or psi_drift bigger the less we know about the relationship between the relationship
# between the GPS coordinate system (namely NESW) and the IMU coordinate system
# Precisely: where is the car heading initially w.r.t. NESW?
P = diag([0.1,0.1,50*q_std**2,0.01]) # initial state covariance matrix
Q = diag([q_std**2,q_std**2,10*q_std**2,2*q_std**2]) # process noise covariance matrix (drift: 5)
R = diag([r_std**2,r_std**2,2*r_std**2,r_std**2]) # measurement noise covariance matrix
# publish initial state estimate
(x, y, psi, psi_drift) = x_EKF
# print x,y,psi,v
v = acc
state_pub.publish( Z_KinBkMdl(x, y, psi, v) )
# collect input
u = [ d_f, acc ]
# u_pub.publish( ECU(u[1],u[0]) )
# wait
rate.sleep()
while not rospy.is_shutdown():
# collect measurements
z = array([x_local, y_local, psi_meas, v_meas])
# print
# print z
z_new = array([new_gps_meas, new_gps_meas, new_imu_meas, new_enc_meas])
meas_pub.publish(Z_KinBkMdl(x_local,y_local,psi_meas,v_meas))
z = z[z_new]
# Reset booleans for new measurements for the next iteration
new_enc_meas = False
new_gps_meas = | |
"""module for checking if source needs to be updated in Knowledge Network (KN).
Contains the class SrcClass which serves as the base class for each supported
source in the KN.
Contains module functions::
get_SrcClass(args)
compare_versions(SrcClass)
check(module, args=None)
main_parse_args()
Examples:
To run check on a single source (e.g. dip)::
$ python3 code/check_utilities.py dip
To view all optional arguments that can be specified::
$ python3 code/check_utilities.py -h
"""
import urllib.request
import urllib.error
import os
import time
import json
import csv
import sys
from argparse import ArgumentParser
import config_utilities as cf
import table_utilities as tu
import mysql_utilities as mu
import import_utilities as iu
class SrcClass(object):
"""Base class to be extended by each supported source in KnowEnG.
This SrcClass provides default functions that should be extended
or overridden by any source which is added to the Knowledge Network (KN).
Attributes:
name (str): The name of the remote source to be included in the KN.
url_base (str): The base url of the remote source, which may need
additional processing to provide an actual download link (see
get_remote_url).
aliases (dict): A dictionary with subsets of the source which will be
included in the KN as the keys (e.g. different species, data
types, or interaction types), and a short string with information
about the alias as the value.
remote_file (str): The name of the file to extract if the remote source
is a directory
version (dict): The release version of each alias in the source.
source_url (str): The website for the source.
reference (str): The citation for the source.
pmid (str): The pubmed ID for the source.
license (str): The license for the source.
"""
def __init__(self, src_name, base_url, aliases, args=None):
"""Init a SrcClass object with the provided parameters.
Constructs a SrcClass object with the provided parameters, which should
be provided by any class extending SrcClass.
Args:
src_name (str): The name of the remote source to be included in
the KN. Must be provided by the extending class.
url_base (str): The base url of the remote source, which may need
additional processing to provide an actual download link (see
get_remote_url). Must be provided by the extending class.
aliases (dict): A dictionary with subsets of the source which will
be included in the KN as the keys (e.g. different species,
data types, or interaction types), and a short string with
information about the alias as the value.
args (Namespace): args as populated namespace or 'None' for defaults
"""
if args is None:
args = cf.config_args()
self.name = src_name
self.url_base = base_url
self.aliases = aliases
self.remote_file = ''
self.version = dict()
self.args = args
self.chunk_size = 500000
def get_aliases(self, args=cf.config_args()):
"""Helper function for producing the alias dictionary.
This returns a dictionary where alias names are keys and alias info
are the values. This helper function uses the species
specific information for the build of the Knowledge Network, which is
produced by ensembl.py during setup utilities and is located at
cf.DEFAULT_MAP_PATH/species/species.json, in order to fetch all matching
species specific aliases from the source.
Args:
args (Namespace): args as populated namespace or 'None' for defaults
Returns:
dict: A dictionary of species:(taxid, division) values
"""
return dict()
def get_source_version(self, alias):
"""Return the release version of the remote source:alias.
This returns the release version of the remote source for a specific
alias. This value will be the same for every alias unless the
the alias can have a different release version than the source
(this will be source dependent). This value is stored in the
self.version dictionary object. If the value does not already exist,
all aliases versions are initialized to 'unknown'.
Args:
alias (str): An alias defined in self.aliases.
Returns:
str: The remote version of the source.
"""
if alias not in self.version:
for alias_name in self.aliases:
self.version[alias_name] = 'unknown'
return self.version[alias]
def get_local_file_info(self, alias):
"""Return a dictionary with the local file information for the alias.
This returns the local file information for a given source alias, which
will always contain the following keys::
'local_file_name' (str): name of the file locally
'local_file_exists' (bool): boolean if file exists at path
indicated by 'local_file_name'
and will also contain the following if 'local_file_exists' is True::
'local_size' (int): size of local file in bytes
'local_date' (float): time of last modification time of local
file in seconds since the epoch
Args:
alias (str): An alias defined in self.aliases.
Returns:
dict: The local file information for a given source alias.
"""
f_dir = os.path.join(self.args.working_dir, self.args.data_path, self.name)
f_dir = os.path.join(f_dir, alias)
url = self.get_remote_url(alias)
filename = os.path.basename(url).replace('%20', '_')
file = os.path.join(f_dir, filename)
local_dict = dict()
local_dict['local_file_name'] = filename
local_dict['local_file_exists'] = os.path.isfile(file)
if not local_dict['local_file_exists']:
return local_dict
local_dict['local_size'] = os.path.getsize(file)
local_dict['local_date'] = os.path.getmtime(file)
return local_dict
def get_local_version_info(self, alias, args):
"""Return a dictionary with the local information for the alias.
This returns the local information for a given source alias, as
retrieved from the msyql database and formated as a dicitonary object.
(see mysql_utilities.get_file_meta). It adds the local_file_name and
local_file_exists to the fields retrieved from the database, which
are the name of the file locally and a boolean indicating if it already
exists on disk, respectively.
Args:
alias (str): An alias defined in self.aliases.
Returns:
dict: The local file information for a given source alias.
"""
file_id = '.'.join([self.name, alias])
file_meta = mu.get_file_meta(file_id, args)
f_dir = os.path.join(self.args.working_dir, self.args.data_path, self.name)
f_dir = os.path.join(f_dir, alias)
url = self.get_remote_url(alias)
filename = os.path.basename(url).replace('%20', '_')
file = os.path.join(f_dir, filename)
file_meta['local_file_name'] = filename
file_meta['local_file_exists'] = os.path.isfile(file)
return file_meta
def get_remote_file_size(self, alias):
"""Return the remote file size.
This returns the remote file size as specificied by the
'content-length' page header. If the remote file size is unknown, this
value should be -1.
Args:
remote_url (str): The url of the remote file to get the size of.
Returns:
int: The remote file size in bytes.
"""
remote_url = self.get_remote_url(alias)
try:
response = urllib.request.urlopen(remote_url)
print(response.headers)
return int(response.headers['content-length'])
except (TypeError, ValueError, urllib.error.URLError):
return -1
def get_remote_file_modified(self, alias):
"""Return the remote file date modified.
This returns the remote file date modifed as specificied by the
'last-modified' page header.
Args:
remote_url (str): The url of the remote file to get the date
modified of.
Returns:
float: time of last modification time of remote file in seconds
since the epoch
"""
remote_url = self.get_remote_url(alias)
try:
response = urllib.request.urlopen(remote_url)
time_str = response.headers['last-modified']
time_format = "%a, %d %b %Y %H:%M:%S %Z"
return time.mktime(time.strptime(time_str, time_format))
except (urllib.error.URLError, ValueError, TypeError, ConnectionResetError):
return float(0)
def get_remote_url(self, alias):
"""Return the remote url needed to fetch the file corresponding to the
alias.
This returns the url needed to fetch the file corresponding to the
alias. By default this returns self.base_url.
Args:
alias (str): An alias defined in self.aliases.
Returns:
str: The url needed to fetch the file corresponding to the alias.
"""
return self.url_base
def is_map(self, alias):
"""Return a boolean representing if the provided alias is used for
source specific mapping of nodes or edges.
This returns a boolean representing if the alias corresponds to a file
used for mapping. By default this returns True if the alias ends in
'_map' and False otherwise.
Args:
alias (str): An alias defined in self.aliases.
Returns:
bool: Whether or not the alias is used for mapping.
"""
return alias[-4:] == '_map'
def get_dependencies(self, alias):
"""Return a list of other aliases that the provided alias depends on.
This returns a list of other aliases that must be processed before
full processing of the provided alias can be completed. By default,
returns a list of all aliases which are considered mapping files (see
is_map)
Args:
alias(str): An alias defined in self.aliases.
Returns:
list: The other aliases defined in self.aliases that the provided
alias depends on.
"""
depends = list()
if self.is_map(alias):
return depends
for alias_name in self.aliases:
if alias_name == alias:
continue
elif self.is_map(alias_name):
depends.append(alias_name)
return depends
def create_mapping_dict(self, filename, key_col=3, value_col=4):
"""Return a mapping dictionary for the provided file.
This returns a dictionary for use in mapping nodes or edge types from
the | |
<gh_stars>0
# File created for Yale research
# by <NAME>, <NAME>
# This python3 code has two functions
# 1) communicating with the credential issuer UI
# 2) acting as the msp server
import argparse
import asyncio
import json
import random
import logging
import base64
import os
import sys
from uuid import uuid4
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # noqa
from aiohttp import web, ClientSession, DummyCookieJar
from aiohttp_apispec import docs, response_schema, setup_aiohttp_apispec
import aiohttp_cors
from runners.support.agent import DemoAgent, default_genesis_txns
from runners.support.utils import (
log_json,
log_msg,
log_status,
log_timer,
require_indy,
)
LOGGER = logging.getLogger(__name__)
#This global variable is common for issuer and verifier
agent = None
#These are the global variables of the issuer
issue_message = None
temp_conn_id = None
credDefIdList = []
connection_list = []
#These are the global variables of the verifier
proof_message = None
class CI_MSPAgent(DemoAgent):
def __init__(self, http_port: int, admin_port: int, **kwargs):
super().__init__(
"Issuer and Verfier Agent",
http_port,
admin_port,
prefix="CI_MSP",
extra_args=["--auto-accept-invites", "--auto-accept-requests"],
**kwargs,
)
self.connection_id = None
self._connection_ready=None
self.cred_state = {}
self.cred_attrs = {}
async def detect_connection(self):
await self._connection_ready
@property
def connection_ready(self):
return self._connection_ready.done() and self._connection_ready.result()
async def handle_connections(self, message):
global connection_list
if message["connection_id"] == self.connection_id:
if message["state"] == "active" and not self._connection_ready.done():
self.log("Connected")
self.log(message)
connection_list.append({
"their_label" : message['their_label'],
"connection_id" : message['connection_id']
})
self._connection_ready.set_result(True)
# Sending a message requesting the verkey and did
# Start here
msg= {
"status" : "Requesting verkey and did"
}
log_status("Putting did and verkey into the ledger")
await agent.admin_POST(
f"/connections/{self.connection_id}/send-message",
{"content": json.dumps(msg)},
)
# Sending a message requesting the verkey and did
# Ends here
async def handle_issue_credential(self, message):
global issue_message
issue_message = message
async def handle_present_proof(self, message):
global proof_message
global proof_event
if message["state"] == "presentation_received":
log_status("Proof has been got")
proof_message=message
proof_event.set()
async def handle_basicmessages(self, message):
try:
# Putting the verkey using did into the ledger
# Start here
msg=json.loads(message["content"])
if "status" in msg:
if msg['status'] == "Sending verkey and did":
await putKeyToLedger(msg['signing_did'], msg['signing_vk'])
except:
self.log("Received message:", message["content"])
# Putting the verkey using did into the ledger
# Ends here
# ======================================================================
# ======================================================================
# ======================================================================
# This is the section dedicated to the api functions of issuer and verfier
# ======================================================================
# ======================================================================
# ======================================================================
async def handle_create_invitation(request):
global agent
connection = await agent.admin_POST("/connections/create-invitation")
agent._connection_ready=asyncio.Future()
agent.connection_id = connection["connection_id"]
log_status("Invitation has been created !!")
return web.json_response(connection["invitation"])
# ======================================================================
# ======================================================================
# ======================================================================
# This is the section dedicated to the api functions of issuer
# ======================================================================
# ======================================================================
# ======================================================================
async def handle_create_schema_credential_definition(request):
global agent
global credDefIdList
data = await request.json()
# Check if data is empty or has the values
if "schema_name" not in data:
return web.json_response({"status" : "Schema name needed"})
if "attributes" not in data:
return web.json_response({"status" : "Attributes needed"})
# Schema name and attributes input validation
if data['schema_name']=='' or data['schema_name']==None:
return web.json_response({"status" : "Enter a valid schema name"})
if data['attributes']=='' or data['attributes']==None:
return web.json_response({"status" : "Enter valid attibutes"})
schema_name = data['schema_name']
attr_list = [element.strip(' ') for element in data['attributes'].split(",")]
version = format(
"%d.%d.%d"
% (
random.randint(1, 101),
random.randint(1, 101),
random.randint(1, 101),
)
)
(schema_id, credential_definition_id) = await agent.register_schema_and_creddef(
schema_name, version, attr_list
)
log_msg("schema has been created !!")
log_msg("Schema and Credential definition has been created !!")
log_msg("Schema id : ", schema_id)
log_msg("Credential definition id : ", credential_definition_id)
credDefIdList.append({
"schema_name" : schema_name,
"credential_definition_id" : credential_definition_id,
"attr_list" : attr_list,
})
return web.json_response({
"schema_id" : schema_id,
"credential_definition_id" : credential_definition_id
})
async def handle_send_credential_offer(request):
global agent
global temp_conn_id
CRED_PREVIEW_TYPE = ("did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/credential-preview")
data = await request.json()
# Check if data is empty
if 'credential_definition_id' not in data:
return web.json_response({"status" : "Credential definition id needed"})
if 'attr_data' not in data:
return web.json_response({"status" : "Attribute data needed"})
if 'connection_id' not in data:
return web.json_response({"status" : "Connection id needed"})
# Credential definition id, Attributes, Connection id input validation
if data['credential_definition_id']=='' or data['credential_definition_id']==None:
return web.json_response({"status" : "Enter a valid credential definition id"})
if data['attr_data']=='' or data['attr_data']==None:
return web.json_response({"status" : "Enter valid attibutes"})
if data['connection_id']=='' or data['connection_id']==None:
return web.json_response({"status" : "Enter a valid connection id"})
credential_definition_id = data['credential_definition_id']
attr_data = data['attr_data']
agent.cred_attrs[credential_definition_id] = attr_data
agent.connection_id = data["connection_id"]
temp_conn_id = agent.connection_id
cred_preview = {
"@type": CRED_PREVIEW_TYPE,
"attributes": [
{"name": n, "value": v}
for (n, v) in agent.cred_attrs[credential_definition_id].items()
],
}
offer_request = {
"connection_id": agent.connection_id,
"cred_def_id": credential_definition_id,
"comment": f"Offer on cred def id {credential_definition_id}",
"credential_preview": cred_preview,
}
await agent.admin_POST("/issue-credential/send-offer", offer_request)
return web.json_response({"status" : True})
async def handle_issue_credential(request):
global agent
global issue_message
global temp_conn_id
CRED_PREVIEW_TYPE = ("did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/credential-preview")
state = issue_message["state"]
credential_exchange_id = issue_message["credential_exchange_id"]
prev_state = agent.cred_state.get(credential_exchange_id)
if prev_state == state:
return # ignore
agent.cred_state[credential_exchange_id] = state
if state == "request_received":
cred_attrs = agent.cred_attrs[issue_message["credential_definition_id"]]
cred_preview = {
"@type": CRED_PREVIEW_TYPE,
"attributes": [
{"name": n, "value": v} for (n, v) in cred_attrs.items()
],
}
res = await agent.admin_POST(
f"/issue-credential/records/{credential_exchange_id}/issue",
{
"comment": f"Issuing credential, exchange {credential_exchange_id}",
"credential_preview": cred_preview,
},
)
log_status("Credential has been issued!!")
log_msg(res['credential'])
return web.json_response({
"status" : True
}
)
async def handle_get_connection_list(request):
global connection_list
return web.json_response({"connectionList" : connection_list})
async def handle_get_cred_def_list(request):
global credDefIdList
return web.json_response({"credDefIdList" : credDefIdList})
async def putKeyToLedger(signing_did:str=None, signing_vk:str=None):
global agent
res=await agent.admin_POST("/connections/put-key-ledger", {
"did" : agent.did,
"signing_did" : signing_did,
"signing_vk" : signing_vk
})
if res['status']=="true":
return web.json_response({"status" : True})
else:
return web.json_response({"status" : False})
# ======================================================================
# ======================================================================
# ======================================================================
# This is the section dedicated to the api functions of verfier
# ======================================================================
# ======================================================================
# ======================================================================
async def handle_verify_proof(request):
global agent
global proof_event
global proof_message
log_status("Send proof request has been called !!")
req_attrs = []
temp_req = None
req_preds = []
attributes_asked = {}
data = await request.json()
#Check if any proof_attr not there.
if 'proof_attr' not in data:
return web.json_response({"status" : "Attribute missing"})
if data['proof_attr']==None or data['proof_attr']=='':
return web.json_response({"status" : "Enter valid proof_attr"})
#Check if connection id or their_did is available or not -- starts here
if 'connection_id' in data:
log_status("Connection id available!!")
if (data['connection_id']!=None and data['connection_id']!=''):
connection_id = data['connection_id']
elif 'their_did' in data:
log_status("Their did available!!")
if (data['their_did']!=None and data['their_did']!=''):
print("##################################")
print("##################################")
res = await agent.admin_GET(f"/connections",
params = {
"their_did" : data['their_did']
})
if res!=[]:
connection_id = res[0]['connection_id']
else:
return web.json_response({"status" : "Invalid their did"})
else:
log_status("Both not available!!")
return web.json_response({"status" : "Enter valid did or connection id"})
#Check if connection id or their_did is available or not -- ends here
proof_attr = [element.strip(' ') for element in data['proof_attr'].split(",")]
for item in proof_attr:
req_attrs.append(
{
"name": item.strip(),
}
)
# Checking if prdicate is given or not
if ('req_predicate' not in data)==True:
temp_req = {}
elif data['req_predicate']==None or data['req_predicate']=='' or (not data['req_predicate']):
temp_req = {}
else:
temp_req = { 'predicate1_referent' : data['req_predicate'] }
# Cheching if issuer did given or not
if ('issuer_did_list' in data)==True:
log_msg("Issuer did has been given as input!!")
issuer_did_list = data['issuer_did_list']
if not issuer_did_list:
pass
else:
for inc in range(0, len(req_attrs)):
did_list = []
for did_value in issuer_did_list:
did_list.append({
"issuer_did" : did_value
})
req_attrs[inc]['restrictions'] = did_list
indy_proof_request = {
"name": "simple_proof",
"version": "1.0",
"nonce": str(uuid4().int),
"requested_attributes": {
f"0_{req_attr['name']}_uuid": req_attr
for req_attr in req_attrs
},
"requested_predicates" : temp_req
}
log_msg("++++++++++++++++++++++++++++++++++++++++++")
log_msg("++++++++++++++++++++++++++++++++++++++++++")
log_msg("++++++++++++++++++++++++++++++++++++++++++")
log_msg(indy_proof_request)
log_msg("++++++++++++++++++++++++++++++++++++++++++")
log_msg("++++++++++++++++++++++++++++++++++++++++++")
log_msg("++++++++++++++++++++++++++++++++++++++++++")
proof_request_web_request = {
"connection_id": connection_id,
"proof_request": indy_proof_request
}
try:
await agent.admin_POST(
"/present-proof/send-request",
proof_request_web_request
)
except:
return web.json_response({
"status" : "Error while sending proof request",
})
proof_event = asyncio.Event()
await proof_event.wait()
log_status("Verification of proof has been called !!")
presentation_exchange_id = proof_message["presentation_exchange_id"]
try:
proof = await agent.admin_POST(
f"/present-proof/records/{presentation_exchange_id}/"
"verify-presentation"
)
except:
return web.json_response({
"status" : "Error while verifing proof",
})
if proof["verified"]=='true':
try:
pres_req = proof_message["presentation_request"]
pres = proof_message["presentation"]
for (referent, attr_spec) in pres_req["requested_attributes"].items():
attributes_asked[str(attr_spec['name'])] = pres['requested_proof']['revealed_attrs'][referent]['raw']
print(attr_spec['name'])
print(pres['requested_proof']['revealed_attrs'][referent]['raw'])
for id_spec in pres["identifiers"]:
agent.log(id_spec['schema_id'])
agent.log(id_spec['cred_def_id'])
return web.json_response({
"status" : proof["verified"],
"attributes" : attributes_asked,
})
except:
return web.json_response({
"status" : 'False',
})
else:
return web.json_response({
"status" : proof["verified"],
})
async def handle_verify_signature(request):
global agent
data = await request.json()
resp = {}
#Check if any attribute not there.
for element in ['message','their_did','signature']:
if element not in data:
return web.json_response({"status" : "Attribute missing"})
#Check if any attribute has not value.
if (data['message']==None or data['message']=='') or (data['their_did']==None or data['their_did']=='') or (data['signature']==None or data['signature']==''):
return web.json_response({"status" : "Enter valid details"})
message = data['message']
their_did = data['their_did']
signature = data['signature']
log_msg("message : "+message)
log_msg("their_did : "+their_did)
log_msg("signature : "+signature)
try:
temp=signature.encode('iso-8859-15')
temp1=base64.b64decode(temp)
signature=temp1.decode('utf-8')
except:
return web.json_response({"status" : "Invalid signature"})
while True:
verify = await agent.admin_POST("/connections/verify-transaction", {
"message" : message,
| |
<reponame>wlongxiang/KRR-course
###
### Propagation function to be used in the recursive sudoku solver
###
import time
from itertools import chain
import clingo
from pysat.formula import CNF
from pysat.solvers import MinisatGH
def deep_copy(sudoku_possible_values):
copy = []
for row in sudoku_possible_values:
row_copy = []
for element in row:
element_copy = element.copy()
row_copy.append(element_copy)
copy.append(row_copy)
return copy
### Pretty printing representation
def pretty_repr(sudoku, k):
repr = ""
numwidth = len(str(k ** 2))
def pretty_line(k):
return "+" + "+".join(["-" * ((numwidth + 1) * k + 1)] * k) + "+\n"
# Add a line separator at the beginning
repr += pretty_line(k)
rownum = 0
# Go through all rows of the sudoku
for i in range(0, k):
for j in range(0, k):
# Add a row of the sudoku
repr += "| "
for u in range(0, k):
for v in range(0, k):
if sudoku[rownum][u * k + v] != 0:
repr += str(sudoku[rownum][u * k + v]).zfill(numwidth) + " "
else:
repr += " " * numwidth + " "
repr += "| "
repr += "\n"
rownum += 1
# Add a line separator after every k'th row
repr += pretty_line(k)
# Return the constructed string (without trailing '\n')
return repr[:-1]
def propagate(sudoku_possible_values, k):
"""
In the propogate function, we try to prune values to narrow down the search space.
:param sudoku_possible_values: the original search space
:param k: the size of the sudoku
:return: the pruned search space
"""
# 1. let's first scan once to find out indice for all single values
# 2. we loop over all those indices, then eliminating across rows, cols, and blocks for each one
all_single_vals_positions = {} # key is (i,j), value is value
for i in range(k ** 2):
for j in range(k ** 2):
possibilities = sudoku_possible_values[i][j]
if len(possibilities) == 1:
all_single_vals_positions[(i, j)] = possibilities[0]
for (i, j), value in all_single_vals_positions.items():
# remove duplicate values row-wise
# skip the row that contains the value
for row_i in chain(range(0, i), range(i + 1, k ** 2)):
if value in sudoku_possible_values[row_i][j]:
sudoku_possible_values[row_i][j].remove(value)
# remove duplicate values col-wise
for col_j in chain(range(0, j), range(j + 1, k ** 2)):
if value in sudoku_possible_values[i][col_j]:
sudoku_possible_values[i][col_j].remove(value)
# pruning block-wise cells
# find out which block is it in
block_i = (i // k) * k
block_j = (j // k) * k
# loop over all cells in the block
for i2 in range(k):
for j2 in range(k):
i_b = block_i + i2
j_b = block_j + j2
if i != i_b and j != j_b:
if value in sudoku_possible_values[i_b][j_b]:
sudoku_possible_values[i_b][j_b].remove(value)
return sudoku_possible_values
###
### Solver that uses SAT encoding
###
# some uti functions first
def var_number(i, j, d, k):
"""
Convert possible values into propositional vars
:param i: row number 1 - 9
:param j: col number 1 - 9
:param d: digit 1 - 9
:param k: size of suduko
:return: variable number 1- 729
"""
return (k ** 2 * k ** 2) * (i - 1) + (k ** 2) * (j - 1) + d
def extract_digit_from_solution(i, j, solution, k):
# return the digit of cell i, j according to the solution
for d in range(1, k ** 2 + 1):
if var_number(i, j, d, k) in solution:
return d
def create_clauses(sudoku, k):
clauses = []
for i in range(1, k ** 2 + 1):
for j in range(1, k ** 2 + 1):
# 1. make sure all cells have at least one one digit
clauses.append([var_number(i, j, d, k) for d in range(1, k ** 2 + 1)])
# 2. make sure all cells have only one digit
for d in range(1, k ** 2 + 1):
for d2 in range(d + 1, k ** 2 + 1):
clauses.append([-var_number(i, j, d, k), -var_number(i, j, d2, k)])
def add_distinct_clauses(cells):
"""
Given a list of positions, such as indices for first row, [(1,1), (1,2)... (1,9)]
we create clauses that make sure each digit is distinct
"""
for i in range(len(cells)):
for j in range(i + 1, len(cells)):
for d in range(1, k ** 2 + 1):
clauses.append([-var_number(cells[i][0], cells[i][1], d, k),
-var_number(cells[j][0], cells[j][1], d, k)])
# make sure each row has distinct value
for i in range(1, k ** 2 + 1):
rowwise_cells = [(i, j) for j in range(1, k ** 2 + 1)]
add_distinct_clauses(rowwise_cells)
# make sure each col has distinct value
for j in range(1, k ** 2 + 1):
colwise_cells = [(i, j) for i in range(1, k ** 2 + 1)]
add_distinct_clauses(colwise_cells)
# make sure each block has distinct value
for i in [1 + n * k for n in range(k - 1)]: # 1,4,7 when k=3; 1 ,5, 9, 13 when k=4
for j in [1 + n * k for n in range(k - 1)]:
add_distinct_clauses([(i + m % k, j + m // k) for m in range(k ** 2)])
# make sure the prefilled values are honored by a unit clause
for i in range(1, k ** 2 + 1):
for j in range(1, k ** 2 + 1):
d = sudoku[i - 1][j - 1]
if d > 0:
clauses.append([var_number(i, j, d, k)])
return clauses
def solve_sudoku_SAT(sudoku, k):
#############
# this solution is adjusted from https://github.com/taufanardi/sudoku-sat-solver/blob/master/Sudoku.py
# what I have done differently:
# 1. Adjusted so that it can generate to k-sized problem, not just hardcoded k=3 in the original post
# 2. Refactored the code to make it more readable and splitted into smaller functions instead of chunk of code
# 3. Rewrited the `add_distinct_clauses` code to make it more robust and easy to understand
#############
# make clauses
clauses = create_clauses(sudoku, k)
# append clauses to formula
formula = CNF()
for c in clauses:
formula.append(c)
# solve the SAT problem
solver = MinisatGH()
solver.append_formula(formula)
answer = solver.solve()
if not answer:
return None
# get the solution
solution = solver.get_model()
# reformat the solution into a suduko representation
for i in range(1, k ** 2 + 1):
for j in range(1, k ** 2 + 1):
sudoku[i - 1][j - 1] = extract_digit_from_solution(i, j, solution, k)
return sudoku
###
### Solver that uses CSP encoding
###
from ortools.sat.python import cp_model
def solve_sudoku_CSP(sudoku, k):
###########################
# this solution only references the or-tool documentation and the provided example
# it follows the same structure of the SAT solver, which is inspired by a existing solution as shown above
model = cp_model.CpModel()
# create variables with domain contrstrain, x1_1... x9_9 all in (1 to 9)
vars = dict()
for i in range(1, k ** 2 + 1):
for j in range(1, k ** 2 + 1):
vars[(i, j)] = model.NewIntVar(1, k ** 2, "x{}_{}".format(i, j))
# make sure all row values are distinct
def add_distinct_constrain(cells):
"""
Given a list of positions, such as indices for first row, [(1,1), (1,2)... (1,9)]
we create clauses that make sure each digit is distinct
"""
all_vars = [vars[i] for i in cells]
model.AddAllDifferent(all_vars)
# make sure each row has distinct value
for i in range(1, k ** 2 + 1):
rowwise_cells = [(i, j) for j in range(1, k ** 2 + 1)]
add_distinct_constrain(rowwise_cells)
# make sure each col has distinct value
for j in range(1, k ** 2 + 1):
colwise_cells = [(i, j) for i in range(1, k ** 2 + 1)]
add_distinct_constrain(colwise_cells)
# make sure each block has distinct value
for i in [1 + n * k for n in range(k - 1)]: # 1,4,7 when k=3; 1 ,5, 9, 13 when k=4
for j in [1 + n * k for n in range(k - 1)]:
add_distinct_constrain([(i + m % k, j + m // k) for m in range(k ** 2)])
# make sure the prefilled values are honored by a unit clause
for i in range(1, k ** 2 + 1):
for j in range(1, k ** 2 + 1):
d = sudoku[i - 1][j - 1]
| |
there is a new version being worked on"
return bool(self.activeprojects.filter())
def get_published_versions(self):
"""
Return a queryset of PublishedProjects, sorted by version.
"""
return self.publishedprojects.filter().order_by('version_order')
@property
def total_published_size(self):
"""
Total storage size of the published projects.
This is the sum of the PublishedProjects'
incremental_storage_size values (which will be less than the
sum of the main_storage_size values if there are files that
are shared between versions) and reflects the actual size of
the data on disk.
"""
result = self.publishedprojects \
.aggregate(total=models.Sum('incremental_storage_size'))
# The sum will be None if there are no publishedprojects. It will
# also be None if any projects have incremental_storage_size=None.
return result['total'] or 0
class ProjectType(models.Model):
"""
The project types available on the platform
"""
id = models.PositiveSmallIntegerField(primary_key=True)
name = models.CharField(max_length=20)
description = models.TextField()
class Metadata(models.Model):
"""
Visible content of a published or unpublished project.
Every project (ActiveProject, PublishedProject, and
ArchivedProject) inherits from this class as well as
SubmissionInfo. The difference is that the fields of this class
contain public information that will be shown on the published
project pages; SubmissionInfo contains internal information about
the publication process.
In particular, the UnpublishedProject modified_datetime will be
updated when any field of Metadata is altered (see
UnpublishedProject.save), but not when a field of SubmissionInfo
is modified.
New fields should be added to this class only if they affect the
content of the project as it will be shown when published.
"""
ACCESS_POLICIES = (
(0, 'Open'),
(1, 'Restricted'),
(2, 'Credentialed'),
)
resource_type = models.ForeignKey('project.ProjectType',
db_column='resource_type',
related_name='%(class)ss',
on_delete=models.PROTECT)
# Main body descriptive metadata
title = models.CharField(max_length=200, validators=[validate_title])
abstract = SafeHTMLField(max_length=10000, blank=True)
background = SafeHTMLField(blank=True)
methods = SafeHTMLField(blank=True)
content_description = SafeHTMLField(blank=True)
usage_notes = SafeHTMLField(blank=True)
installation = SafeHTMLField(blank=True)
acknowledgements = SafeHTMLField(blank=True)
conflicts_of_interest = SafeHTMLField(blank=True)
version = models.CharField(max_length=15, default='', blank=True,
validators=[validate_version])
release_notes = SafeHTMLField(blank=True)
# Short description used for search results, social media, etc
short_description = models.CharField(max_length=250, blank=True)
# Access information
access_policy = models.SmallIntegerField(choices=ACCESS_POLICIES,
default=0)
is_self_managed_access = models.BooleanField(default=False)
self_managed_dua = SafeHTMLField(blank=True, default='')
self_managed_request_template = SafeHTMLField(blank=True, default='')
license = models.ForeignKey('project.License', null=True,
on_delete=models.SET_NULL)
project_home_page = models.URLField(default='', blank=True)
parent_projects = models.ManyToManyField('project.PublishedProject',
blank=True, related_name='derived_%(class)ss')
programming_languages = models.ManyToManyField(
'project.ProgrammingLanguage', related_name='%(class)ss', blank=True)
core_project = models.ForeignKey('project.CoreProject',
related_name='%(class)ss',
on_delete=models.CASCADE)
class Meta:
abstract = True
def is_published(self):
if isinstance(self, PublishedProject):
return True
else:
return False
def author_contact_info(self, only_submitting=False):
"""
Get the names and emails of the project's authors.
"""
if only_submitting:
user = self.authors.get(is_submitting=True).user
return user.email, user.get_full_name
else:
authors = self.authors.all().order_by('display_order')
users = [a.user for a in authors]
return ((u.email, u.get_full_name()) for u in users)
def corresponding_author(self):
return self.authors.get(is_corresponding=True)
def submitting_author(self):
return self.authors.get(is_submitting=True)
def author_list(self):
"""
Get the project's authors in the correct display order.
"""
return self.authors.all().order_by('display_order')
def get_author_info(self, separate_submitting=False, include_emails=False):
"""
Get the project's authors, setting information needed to display
their attributes.
"""
authors = self.authors.all().order_by('display_order')
author_emails = ';'.join(a.user.email for a in authors)
if separate_submitting:
submitting_author = authors.get(is_submitting=True)
coauthors = authors.filter(is_submitting=False)
submitting_author.set_display_info()
for a in coauthors:
a.set_display_info()
if include_emails:
return submitting_author, coauthors, author_emails
else:
return submitting_author, coauthors
else:
for a in authors:
a.set_display_info()
if include_emails:
return authors, author_emails
else:
return authors
def get_platform_citation(self):
"""
Returns the information needed to generate the standard platform
citation in multiple formats (MLA, APA, Chicago, Harvard, and
Vancouver).
1. MLA (8th edition) [https://owl.purdue.edu/owl/research_and_citation/
mla_style/mla_formatting_and_style_guide/
mla_formatting_and_style_guide.html]
2. APA (7th edition) [https://owl.purdue.edu/owl/research_and_citation/
apa_style/apa_style_introduction.html]
3. Chicago (17th edition) [https://owl.purdue.edu/owl/
research_and_citation/
chicago_manual_17th_edition/
cmos_formatting_and_style_guide/
chicago_manual_of_style_17th_edition.html]
4. Harvard [https://www.mendeley.com/guides/harvard-citation-guide]
5. Vancouver [https://guides.lib.monash.edu/ld.php?content_id=14570618]
Parameters
----------
N/A
Returns
-------
citation_styles [dict]:
dictionary containing the desired citation style
"""
citation_styles = {
'MLA': ('<NAME>., et al. "PhysioBank, '
'PhysioToolkit, and PhysioNet: Components of a '
'new research resource for complex physiologic '
'signals. Circulation [Online]. 101 (23), pp. '
'e215–e220." (2000).'),
'APA': ('<NAME>., <NAME>., <NAME>., '
'<NAME>., <NAME>., <NAME>., ... & '
'Stanley, <NAME>. (2000). PhysioBank, '
'PhysioToolkit, and PhysioNet: Components of a '
'new research resource for complex physiologic '
'signals. Circulation [Online]. 101 (23), pp. '
'e215–e220.'),
'Chicago': ('<NAME>., <NAME>, <NAME>. '
'Hausdorff, <NAME>. <NAME>, <NAME>. '
'<NAME>, <NAME>, and <NAME>. '
'Stanley. "PhysioBank, PhysioToolkit, and '
'PhysioNet: Components of a new research '
'resource for complex physiologic signals. '
'Circulation [Online]. 101 (23), pp. '
'e215–e220." (2000).'),
'Harvard': ('<NAME>., <NAME>., <NAME>., '
'<NAME>., <NAME>., <NAME>., '
'<NAME>., <NAME>., <NAME>. and '
'Stanley, H.E., 2000. PhysioBank, '
'PhysioToolkit, and PhysioNet: Components of a '
'new research resource for complex physiologic '
'signals. Circulation [Online]. 101 (23), pp. '
'e215–e220.'),
'Vancouver': ('<NAME>, <NAME>, <NAME>, <NAME>, '
'<NAME>, <NAME>, <NAME>, <NAME>, Peng '
'CK, Stanley HE. PhysioBank, PhysioToolkit, '
'and PhysioNet: Components of a new research '
'resource for complex physiologic signals. '
'Circulation [Online]. 101 (23), pp. '
'e215–e220.')
}
return citation_styles
def abstract_text_content(self):
"""
Returns abstract as plain text.
"""
return html2text(self.abstract)
def edit_log_history(self):
"""
Get a list of EditLog objects in submission order.
Every object corresponds to a single submission from the
author (and objects are listed in that order), but also
includes the details of the editor's response (if any) to that
particular submission.
"""
return self.edit_logs.order_by('submission_datetime').all()
def copyedit_log_history(self):
"""
Get a list of CopyeditLog objects in creation order.
Every object represents a point in time when the project was
"opened for copyediting" (which happens once when the project
is "accepted", and may happen again if the authors
subsequently request further changes.)
"""
return self.copyedit_logs.order_by('start_datetime').all()
def info_card(self, include_emails=True, force_calculate=False):
"""
Get all the information needed for the project info card
seen by an admin
"""
authors, author_emails = self.get_author_info(include_emails=include_emails)
storage_info = self.get_storage_info(force_calculate=force_calculate)
edit_logs = self.edit_log_history()
for e in edit_logs:
e.set_quality_assurance_results()
copyedit_logs = self.copyedit_log_history()
# The last published version. May be None.
latest_version = self.core_project.publishedprojects.all().last()
return authors, author_emails, storage_info, edit_logs, copyedit_logs, latest_version
def license_content(self, fmt):
"""
Get the license content of the project's license in text or html
content. Takes the selected license and fills in the year and
copyright holder.
"""
authors = self.authors.all().order_by('display_order')
author_names = ', '.join(a.get_full_name() for a in authors) + '.'
if fmt == 'text':
content = self.license.text_content
content = content.replace('<COPYRIGHT HOLDER>', author_names, 1)
content = content.replace('<YEAR>', str(timezone.now().year), 1)
elif fmt == 'html':
content = self.license.html_content
content = content.replace('<COPYRIGHT HOLDER>', author_names, 1)
content = content.replace('<YEAR>', str(timezone.now().year), 1)
return content
def create_license_file(self):
"""
Create a file containing the text of the project license.
A file 'LICENSE.txt' is created at the top level of the
project directory, replacing any existing file with that name.
"""
fname = os.path.join(self.file_root(), 'LICENSE.txt')
if os.path.isfile(fname):
os.remove(fname)
with open(fname, 'x') as outfile:
outfile.write(self.license_content(fmt='text'))
def get_directory_content(self, subdir=''):
"""
Return information for displaying files and directories from
the project's file root.
"""
# Get folder to inspect if valid
inspect_dir = self.get_inspect_dir(subdir)
file_names, dir_names = list_items(inspect_dir)
display_files, display_dirs = [], []
# Files require desciptive info and download links
for file in file_names:
file_info = get_file_info(os.path.join(inspect_dir, file))
file_info.url = self.file_display_url(subdir=subdir, file=file)
file_info.raw_url = self.file_url(subdir=subdir, file=file)
file_info.download_url = file_info.raw_url + '?download'
display_files.append(file_info)
# Directories require links
for dir_name in dir_names:
dir_info = get_directory_info(os.path.join(inspect_dir, dir_name))
dir_info.full_subdir = os.path.join(subdir, dir_name)
display_dirs.append(dir_info)
return display_files, display_dirs
def schema_org_resource_type(self):
"""
Return a valid https://schema.org resource type.
"""
type_map = {0: 'Dataset', # database
1: 'SoftwareSourceCode', # software
2: 'Dataset', # challenge
3: 'Dataset' # model
}
try:
return type_map[self.resource_type]
except KeyError:
return 'Dataset'
def is_valid_passphrase(self, raw_passphrase):
"""
Checks if passphrase is valid for project
"""
anonymous = self.anonymous.first()
if not anonymous:
return False
return anonymous.check_passphrase(raw_passphrase)
def generate_anonymous_access(self):
"""
Checks if passphrase is valid for project
"""
if not self.anonymous.first():
anonymous = AnonymousAccess(project=self)
else:
anonymous = self.anonymous.first()
return anonymous.generate_access()
def get_anonymous_url(self):
"""
Returns current url for anonymous access
"""
anonymous = self.anonymous.first()
if not anonymous:
return False
return anonymous.url
def citation_text(self, style):
"""
Citation information in multiple formats (MLA, APA, Chicago,
Harvard, and Vancouver).
1. MLA (8th edition) [https://owl.purdue.edu/owl/research_and_citation/
mla_style/mla_formatting_and_style_guide/
mla_formatting_and_style_guide.html]
2. APA (7th edition) [https://owl.purdue.edu/owl/research_and_citation/
apa_style/apa_style_introduction.html]
3. Chicago (17th edition) [https://owl.purdue.edu/owl/
research_and_citation/
chicago_manual_17th_edition/
cmos_formatting_and_style_guide/
chicago_manual_of_style_17th_edition.html]
4. Harvard [https://www.mendeley.com/guides/harvard-citation-guide]
5. Vancouver [https://guides.lib.monash.edu/ld.php?content_id=14570618]
Parameters
----------
style [string]:
['MLA', 'APA', 'Chicago', 'Harvard', 'Vancouver']
Returns
-------
citation_format [string]:
string | |
Changing configuration.")
self.change_config('FAIL')
self.agentMgr.status_set("HealthStatus:", "FAIL")
self.CURRENTSTATUS = 0
else:
# We get here if we had some weird exception
syslog.syslog("TCPCheck - An exception occurred. Skipping to next interval")
# Wait for CHECKINTERVAL
if self.agentMgr.agent_option("CHECKINTERVAL"):
self.timeout_time_is(eossdk.now() + int(self.agentMgr.agent_option("CHECKINTERVAL")))
else:
self.timeout_time_is(eossdk.now() + int(self.CHECKINTERVAL))
def on_agent_option(self, optionName, value):
# options are a key/value pair
# Here we set the status output when user does a show agent command
if optionName == "IPv4":
if not value:
self.tracer.trace3("IPv4 List Deleted")
self.agentMgr.status_set("IPv4 Address List:", "None")
else:
self.tracer.trace3("Adding IPv4 Address list to %s" % value)
self.agentMgr.status_set("IPv4 Address List:", "%s" % value)
if optionName == "PROTOCOL":
if not value:
self.tracer.trace3("Protocol Deleted")
self.agentMgr.status_set("PROTOCOL:", "None")
else:
self.tracer.trace3("Adding Protocol %s" % value)
self.agentMgr.status_set("PROTOCOL:", "%s" % value)
if optionName == "TCPPORT":
if not value:
self.tracer.trace3("TCPPORT Deleted")
self.agentMgr.status_set("TCPPORT:", "None")
else:
self.tracer.trace3("Adding TCPPORT %s" % value)
self.agentMgr.status_set("TCPPORT:", "%s" % value)
if optionName == "USERNAME":
if not value:
self.tracer.trace3("USERNAME Deleted")
self.agentMgr.status_set("USERNAME:", "None")
else:
self.tracer.trace3("Adding USERNAME %s" % value)
self.agentMgr.status_set("USERNAME:", "%s" % value)
if optionName == "PASSWORD":
if not value:
self.tracer.trace3("PASSWORD Deleted")
self.agentMgr.status_set("PASSWORD:", "None")
else:
self.tracer.trace3("Adding PASSWORD %s" % value)
self.agentMgr.status_set("PASSWORD:", "%s" % value)
if optionName == "CONF_FAIL":
if not value:
self.tracer.trace3("CONF_FAIL Deleted")
self.agentMgr.status_set("CONF_FAIL:", "None")
else:
self.tracer.trace3("Adding CONF_FAIL %s" % value)
self.agentMgr.status_set("CONF_FAIL:", "%s" % value)
if optionName == "CONF_RECOVER":
if not value:
self.tracer.trace3("CONF_RECOVER Deleted")
self.agentMgr.status_set("CONF_RECOVER:", "None")
else:
self.tracer.trace3("Adding CONF_RECOVER %s" % value)
self.agentMgr.status_set("CONF_RECOVER:", "%s" % value)
if optionName == "REGEX":
if not value:
self.tracer.trace3("REGEX Deleted")
self.agentMgr.status_set("REGEX:", "None")
else:
self.tracer.trace3("Adding REGEX %s" % value)
self.agentMgr.status_set("REGEX:", "%s" % value)
if optionName == "HTTPTIMEOUT":
if not value:
self.tracer.trace3("HTTPTIMEOUT Deleted")
self.agentMgr.status_set("HTTPTIMEOUT:", self.HTTPTIMEOUT)
else:
self.tracer.trace3("Adding HTTPTIMEOUT %s" % value)
self.agentMgr.status_set("HTTPTIMEOUT:", "%s" % value)
if optionName == "FAILCOUNT":
if not value:
self.tracer.trace3("FAILCOUNT Deleted")
self.agentMgr.status_set("FAILCOUNT:", self.FAILCOUNT)
else:
self.tracer.trace3("Adding FAILCOUNT %s" % value)
self.agentMgr.status_set("FAILCOUNT:", "%s" % value)
if optionName == "CHECKINTERVAL":
if not value:
self.tracer.trace3("CHECKINTERVAL Deleted")
self.agentMgr.status_set("CHECKINTERVAL:", self.CHECKINTERVAL)
else:
self.tracer.trace3("Adding CHECKINTERVAL %s" % value)
self.agentMgr.status_set("CHECKINTERVAL:", "%s" % value)
if optionName == "URLPATH":
if not value:
self.tracer.trace3("URLPATH Deleted")
self.agentMgr.status_set("URLPATH:", "%s" % "/")
else:
self.tracer.trace3("Adding URLPATH %s" % value)
self.agentMgr.status_set("URLPATH:", "%s" % value)
if optionName == "VRF":
if not value:
self.tracer.trace3("VRF Deleted")
self.agentMgr.status_set("VRF:", "%s" % "Default")
else:
self.tracer.trace3("Adding VRF %s" % value)
self.agentMgr.status_set("VRF:", "%s" % value)
def on_agent_enabled(self, enabled,reason=None):
# When shutdown set status and then shutdown
if not enabled:
self.tracer.trace0("Shutting down")
self.agentMgr.status_del("Status:")
if reason is not None:
self.agentMgr.status_set("Status:", "Administratively Down - %s" % reason)
else:
self.agentMgr.status_set("Status:", "Administratively Down")
self.agentMgr.agent_shutdown_complete_is(True)
def check_vars(self):
'''
Do some basic config checking. Return 1 if all is good. Else return
0 if config is missing a key parameter and send a syslog message so user
knows what is wrong.
Very basic existance testing here. Maybe add later some greater syntax testing...
'''
if not self.agentMgr.agent_option("TCPPORT"):
syslog.syslog("TCPPORT Parameter is not set. This is a mandatory parameter")
self.on_agent_enabled(enabled=False, reason='TCPPORT Parameter is not set')
return 0
if not self.agentMgr.agent_option("PROTOCOL"):
syslog.syslog("PROTOCOL parameter is not set. This is a mandatory parameter")
self.on_agent_enabled(enabled=False, reason='PROTOCOL Parameter is not set')
return 0
if self.agentMgr.agent_option("PROTOCOL") not in ('http', 'https'):
syslog.syslog("PROTOCOL parameter is not valid. Parameter must be http or https")
self.on_agent_enabled(enabled=False, reason='PROTOCOL parameter is not valid')
return 0
if not self.agentMgr.agent_option("IPv4"):
syslog.syslog("IPv4 parameter is not set. This is a mandatory parameter")
self.on_agent_enabled(enabled=False, reason='IPv4 parameter is not set')
return 0
if not self.agentMgr.agent_option("REGEX"):
syslog.syslog("REGEX parameter is not set. This is a mandatory parameter")
self.on_agent_enabled(enabled=False, reason='REGEX parameter is not set')
return 0
# Should add some basic file checking here...i.e. make sure the following files
# actually exist.
if not self.agentMgr.agent_option("CONF_FAIL"):
syslog.syslog("CONF_FAIL parameter is not set. This is a mandatory parameter")
self.on_agent_enabled(enabled=False, reason='CONF_FAIL parameter is not set')
return 0
if not self.agentMgr.agent_option("CONF_RECOVER"):
syslog.syslog("CONF_RECOVER parameter is not set. This is a mandatory parameter")
self.on_agent_enabled(enabled=False, reason='CONF_RECOVER parameter is not set')
return 0
# Check to see if files exist
if self.agentMgr.agent_option("CONF_FAIL"):
CONFFAILFILE = os.path.isfile(self.agentMgr.agent_option("CONF_FAIL"))
if not CONFFAILFILE:
syslog.syslog("CONF_FAIL file does NOT exist")
self.on_agent_enabled(enabled=False, reason='CONF_FAIL file missing')
return 0
if self.agentMgr.agent_option("CONF_RECOVER"):
CONFRECOVERFILE = os.path.isfile(self.agentMgr.agent_option("CONF_RECOVER"))
if not CONFRECOVERFILE:
syslog.syslog("CONF_RECOVER file does NOT exist")
self.on_agent_enabled(enabled=False, reason='CONF_RECOVER file missing')
return 0
# If VRF option set, check to make sure it really exists.
if self.agentMgr.agent_option("VRF"):
if not self.VrfMgr.exists(self.agentMgr.agent_option("VRF")):
# This means the VRF does not exist
syslog.syslog("VRF %s does not exist." % self.agentMgr.agent_option("VRF"))
self.on_agent_enabled(enabled=False, reason='VRF does not exist')
return 0
# If we get here, then we're good!
return 1
def web_check(self):
'''
This function will do HTTP/HTTPS Request and will return 1 if REGEX is found
or 0 if not found or there are issues.
'''
# Let's build the correct URL
if self.agentMgr.agent_option("URLPATH"):
# We have a URLPATH we need to deal with.
# Let's see if we have a leading / or not.
if re.findall('^/', self.agentMgr.agent_option("URLPATH")):
# This means we have a preceeding /
FINALPATH="%s" % self.agentMgr.agent_option("URLPATH")
else:
FINALPATH="/%s" % self.agentMgr.agent_option("URLPATH")
else:
# If we get here, it means that URLPATH is not set, so lets just add a trailing / for consistency.
FINALPATH="/"
CRLF="\r\n"
# Now lets build the request
request = 'GET %s HTTP/1.1%s' % (FINALPATH, CRLF)
request += 'HOST: %s%s' % (self.agentMgr.agent_option("IPv4"), CRLF)
if self.agentMgr.agent_option("USERNAME"):
token=base64.b64encode('%s:%s' % (self.agentMgr.agent_option("USERNAME"), self.agentMgr.agent_option("PASSWORD"))).decode("ascii")
request += 'Authorization: Basic %s%s' % (token, CRLF)
request += 'Connection: close%s' % CRLF
if self.VrfMgr.exists(self.agentMgr.agent_option("VRF")):
try:
sock_fd=self.VrfMgr.socket_at(socket.AF_INET,socket.SOCK_STREAM,0,self.agentMgr.agent_option("VRF"))
s = socket.fromfd( sock_fd, socket.AF_INET, socket.SOCK_STREAM, 0 )
# Convert socket from type _socket.socket to socket._socketobject
s = socket.socket ( _sock=s )
except Exception as e:
# If we get an issue, lets log this because we have an issue.
s.close()
syslog.syslog("Unable to create socket. Closing sock_fd")
os.close(sock_fd)
syslog.syslog("%s" % e)
return 255
else:
try:
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM, 0 )
except Exception as e:
# If we get an issue, lets log this because we have an issue.
syslog.syslog("Unable to create socket. Closing socket.")
syslog.syslog("%s" % e)
s.close()
return 255
if self.agentMgr.agent_option("PROTOCOL") == 'https':
# Wrap in SSL
try:
thesocket = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1)
except Exception as e:
# If we get an issue, lets log this.
s.close()
if self.VrfMgr.exists(self.agentMgr.agent_option("VRF")):
# Because eossdk.VrfMgr.socket_at() provides a fileno, we'll just
# use os.close.
os.close(sock_fd)
syslog.syslog("%s" % e)
return 255
else:
# Whether we use s or thesocket, lets make thesocket be used moving forward for
# http connection so I'm only using one object name here for crafting HTTP or HTTPS request...
thesocket=s
# Define server address and port
serverAddress = ( self.agentMgr.agent_option("IPv4"), int(self.agentMgr.agent_option("TCPPORT")) )
# Set timeout.
if self.agentMgr.agent_option("HTTPTIMEOUT"):
thesocket.settimeout(int(self.agentMgr.agent_option("HTTPTIMEOUT")))
else:
thesocket.settimeout(int(self.HTTPTIMEOUT))
try:
thesocket.connect( serverAddress )
except:
syslog.syslog("Connection Timeout")
thesocket.close()
if self.VrfMgr.exists(self.agentMgr.agent_option("VRF")):
# Because eossdk.VrfMgr.socket_at() provides a fileno, we'll just
# use os.close.
os.close(sock_fd)
# We get here if we can not establish connection to server. Return 0 same as
# remote host down event.
return 0
thesocket.send(CRLF+request+CRLF+CRLF)
pagecontent = thesocket.recv(self.PACKETSIZE)
# pagecontent is a string, so I should be able to clean up sockets now.
# and get that out of the way.
# Cleanup
thesocket.shutdown(socket.SHUT_RD)
thesocket.close()
if self.agentMgr.agent_option("PROTOCOL") == 'https':
# Need to close the TCP socket too. Closing ssl socket doesn't always do this
# If we get here, we had a legit SSL & TCP socket.
s.shutdown(socket.SHUT_RD)
s.close()
if self.VrfMgr.exists(self.agentMgr.agent_option("VRF")):
# Because eossdk.VrfMgr.socket_at() provides a fileno, we'll just
# use os.close.
os.close(sock_fd)
# We could just return here because we got a page. But it would be more accurate
# to do a Regex on the content so we know that things are legitimate.
REGEX = self.agentMgr.agent_option("REGEX")
# Now lets do regex match to make sure we got what was expected.
if pagecontent:
if re.findall(REGEX, pagecontent):
self.tracer.trace0("REGEX %s found" % REGEX)
return 1
else:
self.tracer.trace0("REGEX %s NOT found" % REGEX)
return 0
else:
self.tracer.trace0("WEB Content is blank")
return 0
def change_config(self, STATUS):
'''
Method to change configuration of switch.
If STATUS is FAIL, then run CONF_FAIL via eAPI API
If STATUS RECOVER (or else) then run CONF_RECOVER via eAPI API
'''
CONF_FAIL = self.agentMgr.agent_option("CONF_FAIL")
CONF_RECOVER = self.agentMgr.agent_option("CONF_RECOVER")
if STATUS == 'FAIL':
self.tracer.trace0("Status FAIL. Applying config changes")
with open(CONF_FAIL) as fh:
| |
'tellurium-116', 52, 116, 115.908460, False),
'Te-117': Iso('Te-117', 'tellurium-117', 52, 117, 116.908646, False),
'Te-118': Iso('Te-118', 'tellurium-118', 52, 118, 117.905854, False),
'Te-119': Iso('Te-119', 'tellurium-119', 52, 119, 118.9064071, False),
'Te-120': Iso('Te-120', 'tellurium-120', 52, 120, 119.9040593, True,
isotopic_abundance=0.0009),
'Te-121': Iso('Te-121', 'tellurium-121', 52, 121, 120.904944, False),
'Te-122': Iso('Te-122', 'tellurium-122', 52, 122, 121.9030435, True,
isotopic_abundance=0.0255),
'Te-123': Iso('Te-123', 'tellurium-123', 52, 123, 122.9042698, True,
isotopic_abundance=0.0089),
'Te-124': Iso('Te-124', 'tellurium-124', 52, 124, 123.9028171, True,
isotopic_abundance=0.0474),
'Te-125': Iso('Te-125', 'tellurium-125', 52, 125, 124.9044299, True,
isotopic_abundance=0.0707),
'Te-126': Iso('Te-126', 'tellurium-126', 52, 126, 125.9033109, True,
isotopic_abundance=0.1884),
'Te-127': Iso('Te-127', 'tellurium-127', 52, 127, 126.9052257, False),
'Te-128': Iso('Te-128', 'tellurium-128', 52, 128, 127.90446128, False,
isotopic_abundance=0.3174),
'Te-129': Iso('Te-129', 'tellurium-129', 52, 129, 128.90659646, False),
'Te-130': Iso('Te-130', 'tellurium-130', 52, 130, 129.906222748, False,
isotopic_abundance=0.3408),
'Te-131': Iso('Te-131', 'tellurium-131', 52, 131, 130.908522213, False),
'Te-132': Iso('Te-132', 'tellurium-132', 52, 132, 131.9085467, False),
'Te-133': Iso('Te-133', 'tellurium-133', 52, 133, 132.9109688, False),
'Te-134': Iso('Te-134', 'tellurium-134', 52, 134, 133.9113940, False),
'Te-135': Iso('Te-135', 'tellurium-135', 52, 135, 134.9165557, False),
'Te-136': Iso('Te-136', 'tellurium-136', 52, 136, 135.9201006, False),
'Te-137': Iso('Te-137', 'tellurium-137', 52, 137, 136.9255989, False),
'Te-138': Iso('Te-138', 'tellurium-138', 52, 138, 137.9294722, False),
'Te-139': Iso('Te-139', 'tellurium-139', 52, 139, 138.9353672, False),
'Te-140': Iso('Te-140', 'tellurium-140', 52, 140, 139.939499, False),
'Te-141': Iso('Te-141', 'tellurium-141', 52, 141, 140.94580, False),
'Te-142': Iso('Te-142', 'tellurium-142', 52, 142, 141.95022, False),
'Te-143': Iso('Te-143', 'tellurium-143', 52, 143, 142.95676, False),
'I-107': Iso('I-107', 'iodine-107', 53, 107, 106.94678, False),
'I-108': Iso('I-108', 'iodine-108', 53, 108, 107.94348, False),
'I-109': Iso('I-109', 'iodine-109', 53, 109, 108.9380853, False),
'I-110': Iso('I-110', 'iodine-110', 53, 110, 109.935089, False),
'I-111': Iso('I-111', 'iodine-111', 53, 111, 110.9302692, False),
'I-112': Iso('I-112', 'iodine-112', 53, 112, 111.928005, False),
'I-113': Iso('I-113', 'iodine-113', 53, 113, 112.9236501, False),
'I-114': Iso('I-114', 'iodine-114', 53, 114, 113.92185, False),
'I-115': Iso('I-115', 'iodine-115', 53, 115, 114.918048, False),
'I-116': Iso('I-116', 'iodine-116', 53, 116, 115.91681, False),
'I-117': Iso('I-117', 'iodine-117', 53, 117, 116.913648, False),
'I-118': Iso('I-118', 'iodine-118', 53, 118, 117.913074, False),
'I-119': Iso('I-119', 'iodine-119', 53, 119, 118.910074, False),
'I-120': Iso('I-120', 'iodine-120', 53, 120, 119.910087, False),
'I-121': Iso('I-121', 'iodine-121', 53, 121, 120.9074051, False),
'I-122': Iso('I-122', 'iodine-122', 53, 122, 121.9075888, False),
'I-123': Iso('I-123', 'iodine-123', 53, 123, 122.9055885, False,
half_life=47604.6),
'I-124': Iso('I-124', 'iodine-124', 53, 124, 123.9062090, False),
'I-125': Iso('I-125', 'iodine-125', 53, 125, 124.9046294, False,
half_life=5139936.0),
'I-126': Iso('I-126', 'iodine-126', 53, 126, 125.9056233, False),
'I-127': Iso('I-127', 'iodine-127', 53, 127, 126.9044719, True,
isotopic_abundance=1),
'I-128': Iso('I-128', 'iodine-128', 53, 128, 127.9058086, False),
'I-129': Iso('I-129', 'iodine-129', 53, 129, 128.9049837, False),
'I-130': Iso('I-130', 'iodine-130', 53, 130, 129.9066702, False),
'I-131': Iso('I-131', 'iodine-131', 53, 131, 130.90612630, False,
half_life=692902.0800000001),
'I-132': Iso('I-132', 'iodine-132', 53, 132, 131.9079935, False),
'I-133': Iso('I-133', 'iodine-133', 53, 133, 132.9077970, False),
'I-134': Iso('I-134', 'iodine-134', 53, 134, 133.9097588, False),
'I-135': Iso('I-135', 'iodine-135', 53, 135, 134.9100488, False),
'I-136': Iso('I-136', 'iodine-136', 53, 136, 135.914604, False),
'I-137': Iso('I-137', 'iodine-137', 53, 137, 136.9180282, False),
'I-138': Iso('I-138', 'iodine-138', 53, 138, 137.9227264, False),
'I-139': Iso('I-139', 'iodine-139', 53, 139, 138.926506, False),
'I-140': Iso('I-140', 'iodine-140', 53, 140, 139.93173, False),
'I-141': Iso('I-141', 'iodine-141', 53, 141, 140.93569, False),
'I-142': Iso('I-142', 'iodine-142', 53, 142, 141.94120, False),
'I-143': Iso('I-143', 'iodine-143', 53, 143, 142.94565, False),
'I-144': Iso('I-144', 'iodine-144', 53, 144, 143.95139, False),
'I-145': Iso('I-145', 'iodine-145', 53, 145, 144.95605, False),
'Xe-109': Iso('Xe-109', 'xenon-109', 54, 109, 108.95043, False),
'Xe-110': Iso('Xe-110', 'xenon-110', 54, 110, 109.94426, False),
'Xe-111': Iso('Xe-111', 'xenon-111', 54, 111, 110.941607, False),
'Xe-112': Iso('Xe-112', 'xenon-112', 54, 112, 111.9355590, False),
'Xe-113': Iso('Xe-113', 'xenon-113', 54, 113, 112.9332217, False),
'Xe-114': Iso('Xe-114', 'xenon-114', 54, 114, 113.927980, False),
'Xe-115': Iso('Xe-115', 'xenon-115', 54, 115, 114.926294, False),
'Xe-116': Iso('Xe-116', 'xenon-116', 54, 116, 115.921581, False),
'Xe-117': Iso('Xe-117', 'xenon-117', 54, 117, 116.920359, False),
'Xe-118': Iso('Xe-118', 'xenon-118', 54, 118, 117.916179, False),
'Xe-119': Iso('Xe-119', 'xenon-119', 54, 119, 118.915411, False),
'Xe-120': Iso('Xe-120', 'xenon-120', 54, 120, 119.911784, False),
'Xe-121': Iso('Xe-121', 'xenon-121', 54, 121, 120.911453, False),
'Xe-122': Iso('Xe-122', 'xenon-122', 54, 122, 121.908368, False),
'Xe-123': Iso('Xe-123', 'xenon-123', 54, 123, 122.908482, False),
'Xe-124': Iso('Xe-124', 'xenon-124', 54, 124, 123.9058920, True,
isotopic_abundance=0.000952),
'Xe-125': Iso('Xe-125', 'xenon-125', 54, 125, 124.9063944, False),
'Xe-126': Iso('Xe-126', 'xenon-126', 54, 126, 125.9042983, True,
isotopic_abundance=0.000890),
'Xe-127': Iso('Xe-127', 'xenon-127', 54, 127, 126.9051829, False,
half_life=3140173.44),
'Xe-128': Iso('Xe-128', 'xenon-128', 54, 128, 127.9035310, True,
isotopic_abundance=0.019102),
'Xe-129': Iso('Xe-129', 'xenon-129', 54, 129, 128.9047808611, True,
isotopic_abundance=0.264006),
'Xe-130': Iso('Xe-130', 'xenon-130', 54, 130, 129.903509349, True,
isotopic_abundance=0.040710),
'Xe-131': Iso('Xe-131', 'xenon-131', 54, 131, 130.90508406, True,
isotopic_abundance=0.212324),
'Xe-132': Iso('Xe-132', 'xenon-132', 54, 132, 131.9041550856, True,
isotopic_abundance=0.269086),
'Xe-133': Iso('Xe-133', 'xenon-133', 54, 133, 132.9059108, False,
half_life=453381.408),
'Xe-134': Iso('Xe-134', 'xenon-134', 54, 134, 133.90539466, True,
isotopic_abundance=0.104357),
'Xe-135': Iso('Xe-135', 'xenon-135', 54, 135, 134.9072278, False),
'Xe-136': Iso('Xe-136', 'xenon-136', 54, 136, 135.907214484, False,
isotopic_abundance=0.088573),
'Xe-137': Iso('Xe-137', 'xenon-137', 54, 137, 136.91155778, False),
'Xe-138': Iso('Xe-138', 'xenon-138', 54, 138, 137.9141463, False),
'Xe-139': Iso('Xe-139', 'xenon-139', 54, 139, 138.9187922, False),
'Xe-140': Iso('Xe-140', 'xenon-140', 54, 140, 139.9216458, False),
'Xe-141': Iso('Xe-141', 'xenon-141', 54, 141, 140.9267872, False),
'Xe-142': Iso('Xe-142', 'xenon-142', 54, 142, 141.9299731, False),
'Xe-143': Iso('Xe-143', 'xenon-143', 54, 143, 142.9353696, False),
'Xe-144': Iso('Xe-144', 'xenon-144', 54, 144, 143.9389451, False),
'Xe-145': Iso('Xe-145', 'xenon-145', 54, 145, 144.944720, False),
'Xe-146': Iso('Xe-146', 'xenon-146', 54, 146, 145.948518, False),
'Xe-147': Iso('Xe-147', 'xenon-147', 54, 147, 146.95426, False),
'Xe-148': Iso('Xe-148', 'xenon-148', 54, 148, 147.95813, False),
'Cs-112': Iso('Cs-112', 'caesium-112', 55, 112, 111.950309, False),
'Cs-113': Iso('Cs-113', 'caesium-113', 55, 113, 112.9444291, False),
'Cs-114': Iso('Cs-114', 'caesium-114', 55, 114, 113.941296, False),
'Cs-115': Iso('Cs-115', 'caesium-115', 55, 115, 114.93591, False),
'Cs-116': Iso('Cs-116', 'caesium-116', 55, 116, 115.93337, False),
'Cs-117': Iso('Cs-117', 'caesium-117', 55, 117, 116.928617, False),
'Cs-118': Iso('Cs-118', 'caesium-118', 55, 118, 117.926560, False),
'Cs-119': Iso('Cs-119', 'caesium-119', 55, 119, 118.922377, False),
'Cs-120': Iso('Cs-120', 'caesium-120', 55, 120, 119.920677, False),
'Cs-121': Iso('Cs-121', 'caesium-121', 55, 121, 120.917227, False),
'Cs-122': Iso('Cs-122', 'caesium-122', 55, 122, 121.916108, False),
'Cs-123': Iso('Cs-123', 'caesium-123', 55, 123, 122.912996, False),
'Cs-124': Iso('Cs-124', 'caesium-124', 55, 124, 123.9122578, False),
'Cs-125': Iso('Cs-125', 'caesium-125', 55, 125, 124.9097280, False),
'Cs-126': Iso('Cs-126', 'caesium-126', 55, 126, 125.909446, False),
'Cs-127': Iso('Cs-127', 'caesium-127', 55, 127, 126.9074174, False),
'Cs-128': Iso('Cs-128', 'caesium-128', 55, 128, 127.9077487, False),
'Cs-129': Iso('Cs-129', 'caesium-129', 55, 129, 128.9060657, False),
'Cs-130': Iso('Cs-130', 'caesium-130', 55, 130, 129.9067093, False),
'Cs-131': Iso('Cs-131', 'caesium-131', 55, 131, 130.9054649, False),
'Cs-132': Iso('Cs-132', 'caesium-132', 55, 132, 131.9064339, False),
'Cs-133': Iso('Cs-133', 'caesium-133', 55, 133, 132.9054519610, True,
isotopic_abundance=1),
'Cs-134': Iso('Cs-134', 'caesium-134', 55, 134, 133.906718503, False,
half_life=65135232.0),
'Cs-135': Iso('Cs-135', 'caesium-135', 55, 135, 134.9059770, False),
'Cs-136': Iso('Cs-136', 'caesium-136', 55, 136, 135.9073114, False),
'Cs-137': Iso('Cs-137', 'caesium-137', 55, 137, 136.90708923, False,
half_life=951981119.9999999),
'Cs-138': Iso('Cs-138', 'caesium-138', 55, 138, 137.9110171, False),
'Cs-139': Iso('Cs-139', 'caesium-139', 55, 139, 138.9133638, False),
'Cs-140': Iso('Cs-140', 'caesium-140', 55, 140, 139.9172831, False),
'Cs-141': Iso('Cs-141', 'caesium-141', 55, 141, 140.9200455, False),
'Cs-142': Iso('Cs-142', 'caesium-142', 55, 142, 141.9242960, False),
'Cs-143': Iso('Cs-143', 'caesium-143', 55, 143, 142.927349, False),
'Cs-144': Iso('Cs-144', 'caesium-144', 55, 144, 143.932076, False),
'Cs-145': Iso('Cs-145', 'caesium-145', 55, 145, 144.935527, False),
'Cs-146': Iso('Cs-146', 'caesium-146', 55, 146, 145.940344, False),
'Cs-147': Iso('Cs-147', 'caesium-147', 55, 147, 146.944156, False),
'Cs-148': Iso('Cs-148', 'caesium-148', 55, 148, 147.94923, False),
'Cs-149': Iso('Cs-149', 'caesium-149', 55, 149, 148.95302, False),
'Cs-150': Iso('Cs-150', 'caesium-150', 55, 150, 149.95833, False),
'Cs-151': Iso('Cs-151', 'caesium-151', 55, 151, 150.96258, False),
'Ba-114': Iso('Ba-114', 'barium-114', 56, 114, 113.95066, False),
'Ba-115': Iso('Ba-115', 'barium-115', 56, 115, 114.94737, False),
'Ba-116': Iso('Ba-116', 'barium-116', 56, 116, 115.94128, False),
'Ba-117': Iso('Ba-117', 'barium-117', 56, 117, 116.93814, False),
'Ba-118': Iso('Ba-118', 'barium-118', 56, 118, 117.93306, False),
'Ba-119': Iso('Ba-119', 'barium-119', 56, 119, 118.93066, False),
'Ba-120': Iso('Ba-120', 'barium-120', 56, 120, 119.92605, False),
'Ba-121': Iso('Ba-121', 'barium-121', 56, 121, 120.92405, False),
'Ba-122': Iso('Ba-122', 'barium-122', 56, 122, 121.919904, False),
'Ba-123': Iso('Ba-123', 'barium-123', 56, 123, 122.918781, False),
'Ba-124': Iso('Ba-124', 'barium-124', 56, 124, 123.915094, False),
'Ba-125': Iso('Ba-125', 'barium-125', 56, 125, 124.914472, False),
'Ba-126': Iso('Ba-126', 'barium-126', 56, 126, 125.911250, False),
'Ba-127': Iso('Ba-127', 'barium-127', 56, 127, 126.911091, False),
'Ba-128': Iso('Ba-128', 'barium-128', 56, 128, 127.9083420, False),
'Ba-129': Iso('Ba-129', 'barium-129', 56, 129, 128.908681, False),
'Ba-130': Iso('Ba-130', 'barium-130', 56, 130, 129.9063207, False,
isotopic_abundance=0.00106),
'Ba-131': Iso('Ba-131', 'barium-131', 56, 131, 130.9069410, False),
'Ba-132': Iso('Ba-132', 'barium-132', 56, 132, 131.9050611, True,
isotopic_abundance=0.00101),
'Ba-133': Iso('Ba-133', 'barium-133', 56, 133, 132.9060074, False,
half_life=333046080.0),
'Ba-134': Iso('Ba-134', 'barium-134', 56, 134, 133.90450818, True,
isotopic_abundance=0.02417),
'Ba-135': Iso('Ba-135', 'barium-135', 56, 135, 134.90568838, True,
isotopic_abundance=0.06592),
'Ba-136': Iso('Ba-136', 'barium-136', 56, 136, 135.90457573, True,
isotopic_abundance=0.07854),
'Ba-137': Iso('Ba-137', 'barium-137', 56, 137, 136.90582714, True,
isotopic_abundance=0.11232),
'Ba-138': Iso('Ba-138', 'barium-138', 56, 138, 137.90524700, True,
isotopic_abundance=0.71698),
'Ba-139': Iso('Ba-139', 'barium-139', 56, 139, 138.90884110, False),
'Ba-140': Iso('Ba-140', 'barium-140', 56, 140, 139.9106057, False,
half_life=1101833.28),
'Ba-141': Iso('Ba-141', 'barium-141', 56, 141, 140.9144033, False),
'Ba-142': Iso('Ba-142', 'barium-142', 56, 142, 141.9164324, False),
'Ba-143': Iso('Ba-143', 'barium-143', 56, 143, 142.9206253, False),
'Ba-144': Iso('Ba-144', 'barium-144', 56, 144, 143.9229549, False),
'Ba-145': | |
1]
# risingdeltas[-1][0] >= len(self.bcdeltas)
return risingdeltas
def inflectionPoints(self) -> Tuple[List[int], List[float]]:
"""
adjusted approximation of the inflection points at rising edges of the smoothed bcd.
The approximation is that we are using the maximum delta of the unsmoothed bcd
in scope of the rising part of the graph.
:return: The indices and values of the approximated inflections.
"""
inflpt = [ offset + int(numpy.nanargmax(wd)) for offset, wd in self.risingDeltas() ]
inflvl = [ self.bcdeltas[pkt] for pkt in inflpt ]
return inflpt, inflvl
def bcHighPlateaus(self):
"""
:return: Plateaus in the bit congruence at high level (> 0.8)
"""
plateauElevation = 0.8
plat = MessageAnalyzer.plateouStart(self.bitcongruences)
# filter for plateaus of high bit congruence
hiPlat = ([], [])
for ix, vl in zip(plat[0], plat[1]):
if vl > plateauElevation:
hiPlat[0].append(ix)
hiPlat[1].append(vl)
return hiPlat
class BitCongruence2ndDelta(BitCongruenceDelta):
def analyze(self):
"""
2nd order delta of bitwise congruence. see :func:`MessageAnalyzer.bitCongruence()`
not unit-dependant, always byte-wise
:return: list of amplitudes of bit congruences from index i = 1 to n between bits of i-1 and i
"""
super().analyze()
self._values = MessageAnalyzer.tokenDelta(self._values)
self._startskip += 1
class BitCongruenceBetweenNgrams(BitCongruence):
"""
Bit congruence for all bits within consecutive ngrams.
"""
_n = None
def setAnalysisParams(self, n: Union[int, Tuple[int]]):
self._n = n if not isinstance(n, tuple) else n[0]
self._startskip = self._n
def analyze(self):
"""
not unit-dependant
bit congruence directly between ngrams
"""
if not self._n:
raise ParametersNotSet('Analysis parameter missing: N-gram size ("n").')
tokenlist = list(self.ngrams(self._n))
self._values = BitCongruence.bitCongruenceBetweenTokens(tokenlist)
MessageAnalyzer.analyze(self)
class BitCongruenceNgramMean(BitCongruence):
"""
Cumulated bit congruences within each ngram of the message,
"""
_n = None
_ngramMean = list()
def setAnalysisParams(self, n: Union[int, Tuple[int]]):
self._n = int(n) if not isinstance(n, tuple) else int(n[0])
self._startskip = self._n
def analyze(self):
"""
not unit-dependant
mean of byte-wise bit congruences of each ngram
:return:
"""
if not self._n:
raise ParametersNotSet('Analysis parameter missing: N-gram size ("n").')
from utils.baseAlgorithms import ngrams
super().analyze()
self._ngramMean = [float(numpy.mean(bcn)) for bcn in ngrams(self._values, self._n)]
@property
def values(self):
if self._values is None:
return None
return [0.0] * self.startskip + self._ngramMean
class PivotBitCongruence(BitCongruence):
"""
Repeatedly cut the message(segments) in half, calculate the mean/variance of bit congruence for each half,
until the difference between the segments is below a™ threshold.
Fixed Pivot Results:
====================
Thresholds .1, .05, .02 show (pivotedbitvariancesParent.*_ntp_SMIA-20111010_deduped-100)
that some messages get segmented arbitrarily deep, while others with clearly visible structure are
not segmented at all. In this design the analysis is unsuitable.
Alternative:
============
Slide the pivot positions over the whole message (-segment)
and use the one maximizing difference in the segments' congruence to recurse.
Results:
========
Works comparatively well for DNS, is awful for ntp and dhcp.
With the same parameters (different fixed and weighted threshold calculation strategies, fixed and weighted pivot
selection condition), there is no correlation between fields and segment splits. Some areas of the message are too
similar in mean and deviation to be splitted altough they should be, while others are to diverse within a field,
so they get fragmented way to much.
"""
_meanThreshold = .02
def setAnalysisParams(self, args):
if isinstance(args, tuple):
self._meanThreshold = args[0]
else:
self._meanThreshold = args
@property
def analysisParams(self):
return self._meanThreshold,
def _recursivePivotMean(self, segment: MessageSegment):
"""
Recursively split the segment in half, calculate the mean for the values of each of the two resulting
sub-segments, and compare each of them to the original segments mean. If a sub-segment is sufficiently
different from its parent (meanThreshold = .02) further split the sub-segment.
:param segment: One message segment that should be segmented.
:return: List of segments after the splitting.
"""
if not segment.values:
segment.analyzer.analyze()
mymean = segment.mean()
if segment.length >= 4: # we need two bytes for each segment to get a bit congruence of them
pivot = segment.length//2
leftSegment = MessageSegment(segment.analyzer, segment.offset, pivot)
rightSegment = MessageSegment(segment.analyzer, segment.offset + pivot, segment.length - pivot)
# test for recursion conditions
returnSegments = list()
if abs(leftSegment.mean() - mymean) > self._meanThreshold: # still different
returnSegments.extend(self._recursivePivotMean(leftSegment))
else:
returnSegments.append(leftSegment)
if abs(rightSegment.mean() - mymean) > self._meanThreshold: # still different
returnSegments.extend(self._recursivePivotMean(rightSegment))
else:
returnSegments.append(rightSegment)
# if abs(lsm - rsm) > .1: # still different
return returnSegments
else:
return [segment]
def messageSegmentation(self) -> List[MessageSegment]:
segments = self._recursivePivotVar(MessageSegment(BitCongruence(self.message), 0, len(self._message.data)))
sortedSegments = sorted(segments, key=lambda x: x.offset)
# varPerSeg = list()
# for segment in sortedSegments:
# if segment.offset > len(varPerSeg):
# raise ValueError('Segment before offset {} missing for message with data ...{}...'.format(
# segment.offset, hex(self._message.data[len(varPerSeg):segment.offset])))
# # # instead of failing we could also add placeholders if something is missing.
# # # But is shouldn't happen: We do not have overlapping or omitted segments.
# # meanVarPerSeg.extend( [-1]*(segment.offset-len(meanVarPerSeg)) )
# # add mean value for all byte positions of one segment.
# varPerSeg.extend( [ segment.stdev() ]*segment.length )
# self._values = varPerSeg
if self.__debug:
input('next message: ')
return sortedSegments
__debug = False
def _recursivePivotVar(self, segment: MessageSegment):
"""
Recursively split the segment at positions shifting from 2 to n-2, calculate the standard deviation for the
values of each of the two resulting sub-segments, and compare each of them to the original segments deviation.
If a sub-segment is sufficiently different from its parent
(varThreshold = 0.5 parentvar * min(len(vl), len(vr))/(len(vl) + len(vr))) further split the sub-segment.
:param segment: One message segment that should be segmented.
:return: List of segments after the splitting.
"""
if not segment.values:
segment.analyzer.analyze()
myvar = segment.stdev()
if segment.length >= 4: # we need two bytes for each segment to get a bit congruence of them
# select a suitable pivot: find the one yielding the highest deviation-difference from parent
segmentSplit = dict()
for pivot in range(2, segment.length-1):
leftSegment = MessageSegment(segment.analyzer, segment.offset, pivot)
rightSegment = MessageSegment(segment.analyzer, segment.offset + pivot, segment.length - pivot)
# deviation needs to be higher towards the edges to be a probable splitting point
lenweight = 2 * min(leftSegment.length, rightSegment.length) / segment.length
# add splits: varDiff: (leftSegment, rightSegment)
segmentSplit[abs(leftSegment.stdev() - rightSegment.stdev()) * lenweight] \
= (leftSegment, rightSegment)
if self.__debug:
from tabulate import tabulate
print(tabulate(sorted([(wlrdiff, ls.offset, ls.stdev(), rs.offset, rs.stdev(), rs.offset + rs.length)
for wlrdiff, (ls, rs) in segmentSplit.items()], key=lambda x: x[0]), headers=[
'wlrdiff', 'l.o', 'lvar', 'r.o', 'rvar', 'r.b'])) #abs(x[3] - x[4])
# use the segments splitted at selected pivot: search max varDiff in splits
splitdiffmax = max(segmentSplit.keys())
leftSegment, rightSegment = segmentSplit[splitdiffmax]
# weightedThresh = 0.5 * myvar * min(leftSegment.length, rightSegment.length) / segment.length
weightedThresh = 0.1 * myvar
if self.__debug:
print('parent segment stdev:', myvar)
print('weighted threshold:', weightedThresh)
# test for recursion conditions: recurse if above weightedThresh
returnSegments = list()
if abs(leftSegment.stdev() - myvar) > weightedThresh: # still different
if self.__debug:
print('split left', leftSegment.offset)
returnSegments.extend(self._recursivePivotVar(leftSegment))
else:
if self.__debug:
print('left finished', abs(rightSegment.stdev() - myvar))
returnSegments.append(leftSegment)
if abs(rightSegment.stdev() - myvar) > weightedThresh: # still different
if self.__debug:
print('split right', rightSegment.offset)
returnSegments.extend(self._recursivePivotVar(rightSegment))
else:
if self.__debug:
print('right finished', abs(rightSegment.stdev() - myvar))
returnSegments.append(rightSegment)
# if abs(lsm - rsm) > .1: # still different
return returnSegments
else:
return [segment]
class SlidingNmeanBitCongruence(BitCongruence):
"""
Slide a window of given size over the message and calculate means of the bit congruences of the windows.
"""
def setAnalysisParams(self, halfWindow = (2,)):
if isinstance(halfWindow, int):
self._analysisArgs = (halfWindow,)
else:
self._analysisArgs = halfWindow
self._startskip = halfWindow - 1
def analyze(self):
if not self._analysisArgs:
raise ParametersNotSet('Analysis parameter missing: halfWindow.')
halfWindow = self._analysisArgs[0]
super().analyze()
rollmean = pandas.Series(self._values).rolling(window=halfWindow).mean() # type: pandas.Series
self._values = rollmean.tolist()
class SlidingNbcGradient(SlidingNmeanBitCongruence):
"""
Gradient (centered finite difference, h=1) with numpy method.
"""
def analyze(self):
super().analyze()
self._values = numpy.gradient(self._values).tolist()
class SlidingNbcDelta(SlidingNmeanBitCongruence):
"""
Slide a window of given size over the message and calculate means of the bit congruences in (two equally long)
halfs of the window. Compare each two means by calculating its difference.
Delta (difference quotient with forward finite difference, h=1) for all values.
Alternative Idea
====
A difference quotient of n > 1 (8, 6, 4) may show regularly recurring 0s for consecutive fields
of equal length ant type.
"""
def analyze(self):
super().analyze()
halfWindow = self._analysisArgs[0]
self._startskip += 1
self._values = [r-l for l,r in zip(self._values[:-halfWindow], self._values[halfWindow:])] + [numpy.nan]
# self._values = numpy.ediff1d(self._values).tolist() + [numpy.nan]
| |
)) ",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#$task = open the (entrance | exit | corridor) door
#$task = close the (entrance | exit | corridor) door
{"params": ["Action", "Pos", "Door"],
"Action": [["open", "close"], [], [], []],
"Pos":[["entrance", "exit", "corridor"],[],[],[]],
"Door": [["door"], [], [], []],
"conceptual_dependency": "(task (plan user_speech) (action_type interact_with_door) (params door -Pos- -Action-) (step )) ",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#$pour = $vbdeliver me some $pourable in a $canpourin
{"params": ["Action_deliver", "Person", "Pourable", "Canpourin"],
"Action_deliver": [["deliver", "bring", "give"], [], [], []],
"Person":[["me"],[],[],[]],
"Pourable": [[], [], ["item"], []],
"Canpourin": [[], [], ["item"], []],
"conceptual_dependency":"(task (plan user_speech) (action_type pourin_object) (param -Pourable- -Canpourin- -Person-) (step )) ",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#$pour = $vbpour some $pourable in a $canpourin
{"params": ["Action_pour", "Pourable", "Canpourin"],
"Action_pour": [["pour", "serve"], [], [], []],
"Pourable": [[], [], ["item"], []],
"Canpourin": [[], [], ["item"], []],
"conceptual_dependency":"(task (plan user_speech) (action_type pourin_object) (param -Pourable- -Canpourin- nil) (step )) ",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#$serve = $vbplace a $tableware on the {placement} and a $cutlery $servewhere
{"params": ["Action_place", "Tableware", "Place"],
"Action_place": [["place", "set", "put", "leave"], [], [], []],
"Tableware": [[], [], ["item"], []],
"Place": [[], [], ["place"], []],
"conceptual_dependency":"(task (plan user_speech) (action_type set_tableware) (params -Tableware- -Place-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
{"params": ["Cutlery", "On", "Pos"],
"Cutlery": [[], [], ["item"], []],
"On": [["on"], [], [], []],
"Pos": [["it", "right", "left"], [], [], []],
"conceptual_dependency":"(task (plan user_speech) (action_type set_cutlery) (params -Cutlery- -Pos-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
####
### OFFER objects
####
{"params": ["Person_name"],
"Person_name": [[], [], ["person"], []],
"conceptual_dependency": "-Person_name-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
{"params": ["My", "Person_name"],
"My": [["My", "name"], [], [], []],
"Person_name": [[], [], ["person"], []],
"conceptual_dependency": "-Person_name-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#I am
{"params": ["I", "Person_name"],
"I": [["i"], [], ["person"], []],
"Person_name": [[], [], ["person"], []],
"conceptual_dependency": "-Person_name-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#I want drink
{"params": ["Person", "Want", "Favorite_drink"],
"Person": [["i"], [], [], []],
"Want": [["want"], [], [], []],
"Favorite_drink": [[], [], ["item"], []],
"conceptual_dependency": "-Favorite_drink-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
####
### GET LOCATION NAMES
###
{"params": ["At", "Place"],
"At": [["at", "in"], [], [], []],
"Place": [[], [], ["place", "room"], []],
"conceptual_dependency": "-Place-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
{"params": ["Question"],
"Question": [[], [], ["question"], []],
"conceptual_dependency": "-Question-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
{"params": ["Question", "You" , "Dream", "Sheep"],
"Question": [[], [], ["question"], []],
"You": [["you"], [], [], []],
"Dream": [["dream"], [], [], []],
"Sheep": [["sheep"], [], [], []],
"conceptual_dependency": "-Question-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''}
]
meaning_mapping_patterns_restaurant = [
# patrones para el restaurant 2018 montreal
############################################# GetNDeliver
# param: [["palabras", "clave"], ["noun", "vrb", "prep_phrase"], ["categoria", "item", "place", "person"], []]
# take from and deliver to person
#{"params": ["Action_get", "Get_object", "Source_get", "Action_deliver", "Destination_person", "Destination_location"],
#"Action_get": [["get", "grasp", "take"], ["vrb"], [], []],
#"Get_object": [[], ["noun"], ["item"], []],
#"Source_get": [[], ["noun"], ["place"], []],
#"Action_deliver": [["bring", "carry", "deliver", "take"], ["vrb"], [], []],
#"Destination_person": [[], ["noun", "prep_phrase"], ["person"], []],
#"Destination_location": [[], ["noun"], ["place"], []],
#"conceptual_dependency": "(task (plan user_speech) (action_type update_object_location) (params -Get_object- -Source_get- ) (step 1)) " +
# "(task (plan user_speech) (action_type get_object) (params -Get_object- -Source_get-) (step 2)) " +
# "(task (plan user_speech) (action_type find_person_in_room) (params -Destination_person- -Destination_location-) (step 3))" +
# "(task (plan user_speech) (action_type handover_object) (params -Get_object-) (step 4))",
#"verbal_confirmation": '',
#"planner_confirmed": '',
#"planner_not_confirmed": ''},
#Beverage
#a drink
#I want a drink
#drink
{"params": ["Action_order", "Object_find"],
"Action_order": [["a", "want"], [], [], []],
"Object_find": [["beer", "chocolate_milk", "coke", "juice", "lemonade", "tea_bag", "water"], [], [], []],
"conceptual_dependency": "(task (plan user_speech) (action_type take_order_beverage) (params drink -Object_find-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
{"params": ["Object_find"],
"Object_find": [["beer", "chocolate_milk", "coke", "juice", "lemonade", "tea_bag", "water"], [], [], []],
"conceptual_dependency": "(task (plan user_speech) (action_type take_order_beverage) (params drink -Object_find-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#Combos
#food
{"params": ["Action_order", "Object_find1", "Object_find2"],
"Action_order": [["a", "want"], [], [], []],
"Object_find1": [["biscuite", "frosty_fruits", "snakes", "carrot", "cereals", "noodles", "onion", "vegemite", "kiwi", "pear", "cheetos", "doritos", "shapes_chicken", "shapes_pizza", "twisties", "apple", "orange", "lemon"], [], [], []],
"Object_find2": [["biscuite", "frosty_fruits", "snakes", "carrot", "cereals", "noodles", "onion", "vegemite", "kiwi", "pear", "cheetos", "doritos", "shapes_chicken", "shapes_pizza", "twisties", "apple", "orange", "lemon"], [], [], []],
"conceptual_dependency": "(task (plan user_speech) (action_type take_order_combo) (params obj1 -Object_find1- obj2 -Object_find2-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
{"params": ["Object_find1", "Object_find2"],
"Object_find1": [["biscuite", "frosty_fruits", "snakes", "carrot", "cereals", "noodles", "onion", "vegemite", "kiwi", "pear", "cheetos", "doritos", "shapes_chicken", "shapes_pizza", "twisties", "apple", "orange", "lemon"], [], [], []],
"Object_find2": [["biscuite", "frosty_fruits", "snakes", "carrot", "cereals", "noodles", "onion", "vegemite", "kiwi", "pear", "cheetos", "doritos", "shapes_chicken", "shapes_pizza", "twisties", "apple", "orange", "lemon"], [], [], []],
"conceptual_dependency": "(task (plan user_speech) (action_type take_order_combo) (params obj1 -Object_find1- obj2 -Object_find2-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''}
]
meaning_mapping_patterns_receptionist = [
# patrones para el receptionist Robocup 2018
############################################# GetNDeliver
# param: [["palabras", "clave"], ["noun", "vrb", "prep_phrase"], ["categoria", "item", "place", "person"], []]
# take from and deliver to person
#{"params": ["Action_get", "Get_object", "Source_get", "Action_deliver", "Destination_person", "Destination_location"],
#"Action_get": [["get", "grasp", "take"], ["vrb"], [], []],
#"Get_object": [[], ["noun"], ["item"], []],
#"Source_get": [[], ["noun"], ["place"], []],
#"Action_deliver": [["bring", "carry", "deliver", "take"], ["vrb"], [], []],
#"Destination_person": [[], ["noun", "prep_phrase"], ["person"], []],
#"Destination_location": [[], ["noun"], ["place"], []],
#"conceptual_dependency": "(task (plan user_speech) (action_type update_object_location) (params -Get_object- -Source_get- ) (step 1)) " +
# "(task (plan user_speech) (action_type get_object) (params -Get_object- -Source_get-) (step 2)) " +
# "(task (plan user_speech) (action_type find_person_in_room) (params -Destination_person- -Destination_location-) (step 3))" +
# "(task (plan user_speech) (action_type handover_object) (params -Get_object-) (step 4))",
#"verbal_confirmation": '',
#"planner_confirmed": '',
#"planner_not_confirmed": ''},
#Recognize guest name
#My name is
{"params": ["Receptionist_name", "Person_name"],
"Receptionist_name": [["My", "name", "is"], [], [], []],
"Person_name": [[], [], ["person"], []],
"conceptual_dependency": "(task (plan user_speech) (action_type receptionist_guest_name) (params name -Person_name-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#I am
{"params": ["Receptionist_name", "Person_name"],
"Receptionist_name": [["i"], [], ["person"], []],
"Person_name": [[], [], ["person"], []],
"conceptual_dependency": "(task (plan user_speech) (action_type receptionist_guest_name) (params name -Person_name-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#Only the name
{"params": ["Person_name"],
"Person_name": [[], [], ["person"], []],
"conceptual_dependency": "(task (plan user_speech) (action_type receptionist_guest_name) (params name -Person_name-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#My favorite drink is
#is
{"params": ["Receptionist_drink", "Favorite_drink"],
"Receptionist_drink": [["My", "favorite", "drink", "is"], [], [], []],
"Favorite_drink": [[], [], ["item"], []],
"conceptual_dependency": "(task (plan user_speech) (action_type receptionist_favorite_drink) (params drink -Favorite_drink-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#Only the drink
{"params": ["Favorite_drink"],
"Favorite_drink": [[], [], ["item"], []],
"conceptual_dependency": "(task (plan user_speech) (action_type receptionist_favorite_drink) (params drink -Favorite_drink-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
]
meaning_mapping_patterns_servingdrinks = [
# patrones para serving Drinks Robocup 2019
############################################# GetNDeliver
{"params": ["My", "Person_name"],
"My": [["My", "name"], [], [], []],
"Person_name": [[], [], ["person"], []],
"conceptual_dependency": "-Person_name-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#I am
{"params": ["I", "Person_name"],
"I": [["i"], [], ["person"], []],
"Person_name": [[], [], ["person"], []],
"conceptual_dependency": "-Person_name-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#Only the name
{"params": ["Person_name"],
"Person_name": [[], [], ["person"], []],
"conceptual_dependency": "-Person_name-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#I want drink
{"params": ["Person", "Want", "Favorite_drink"],
"Person": [["i"], [], [], []],
"Want": [["want"], [], [], []],
"Favorite_drink": [[], [], ["item"], []],
"conceptual_dependency": "-Favorite_drink-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#Only drink
{"params": ["Favorite_drink"],
"Favorite_drink": [[], [], ["item"], []],
"conceptual_dependency": "-Favorite_drink-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''}
]
meaning_mapping_patterns_where_is_this = [
##patron where is this SYDNEY 2019
#Only drink
{"params": ["Where", "Is", "Place"],
"Where": [["where"], [], [], []],
"Is": [["Is"], [], [], []],
"Place": [[], [], ["place", "room"], []],
"conceptual_dependency": "-Place-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#Only drink
{"params": ["Where", "Is", "Object"],
"Where": [["where"], [], [], []],
"Is": [["Is"], [], [], []],
"Object": [[], [], ["item"], []],
"conceptual_dependency": "-Object-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
####
### GET LOCATION NAMES
###
{"params": ["At", "Place"],
"At": [["at", "in"], [], [], []],
"Place": [[], [], ["place", "room"], []],
"conceptual_dependency": "-Place-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
{"params": ["Give", "Me", "Object"],
"Give":[["give", "bring"],[],[],[]],
"Me":[["me"],[],[],[]],
"Object":[[],[],["item"],[]],
"conceptual_dependency": "give -Object-",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''
}
]
meaning_mapping_patterns_catering_comfort = [
###Patrones para IROS catering granny Annie's comfort
## find a person 1 parametro
{"params": ["Action_find","Find_person"],
"Action_find": [["find", "look_for", "search_for", "pinpoint", "spot"], [], [], []],
"Find_person": [[], [], ["person"], []],
"conceptual_dependency": "(task (plan user_speech) (action_type find_person_in_many_rooms) (params -Find_person-) (step ))" +
"(task (plan user_speech) (action_type update_location_coords) (params current_person) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#grasp object 1 parametro
{"params": ["Action_get", "Get_object"],
"Action_get": [[ "find", "locate", "search_for", "spot", "get", "grasp", "take", "retrieve", "pickup", "look_for", "pinpoint"], [], [], []],
"Get_object": [[], [], ["item"], []],
"conceptual_dependency": "(task (plan user_speech) (action_type get_object_many_rooms) (params -Get_object-) (step )) ",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
#bring me an object
# deliver to me
{"params": ["Action_get", "Person", "Get_object", "Location"],
"Action_get": [["give", "bring", "deliver", "hand"], [], [], []],
"Person": [["me"], [], [], []],
"Get_object":[[],[],["item"],[]],
"Location":[[],[],["place"],[]],
"conceptual_dependency":"(task (plan user_speech) (action_type get_object) (params -Get_object- -Location-) (step ))" +
"(task (plan user_speech) (action_type update_object_location) (params location current_loc) (step ))" +
"(task (plan user_speech) (action_type handover_object) (params ) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
##deliver to me know object
{"params": ["Action_get", "Pron", "Person"],
"Action_get": [["give", "bring", "deliver", "hand"], [], [], []],
"Pron": [["it"], [], [], []],
"Person": [["me"], [], [], []],
"conceptual_dependency":"(task (plan user_speech) (action_type update_object_location) (params location current_loc) (step ))" +
"(task (plan user_speech) (action_type handover_object) (params ) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
##deliver in place
{"params": ["Action_place", "Destination_place"],
"Action_place": [["place", "leave", "put", "set", "deliver"], [], [], []],
"Destination_place": [[], [], ["place"], []],
"conceptual_dependency": "(task (plan user_speech) (action_type deliver_in_position) (params -Destination_place-) (step ))",
"verbal_confirmation": '',
"planner_confirmed": '',
"planner_not_confirmed": ''},
##deliver to person
{"params": ["Action_give", "Person", "Destination_place"],
"Action_give": [["give", "bring", "deliver", "hand", "take"], [], [], []],
"Person": [[], [], ["person"], []],
"Destination_place": [[], [], ["place"], []],
"conceptual_dependency": "(task (plan user_speech) (action_type find_person_in_room) (params -Person- | |
key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/x-www-form-urlencoded']) # noqa: E501
# Authentication setting
auth_settings = ['BBOAuth2'] # noqa: E501
return self.api_client.call_api(
'/emails/quicksend/templates', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_template_html_for_template_id(self, template_id, **kwargs): # noqa: E501
"""Get the HTML for a given template # noqa: E501
Get the HTML for a given template, with or without rendered variables # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_template_html_for_template_id(template_id, async=True)
>>> result = thread.get()
:param async bool
:param str template_id: The id of the template. (required)
:param str render_variables: Whether to render profile variables in the returned HTML.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_template_html_for_template_id_with_http_info(template_id, **kwargs) # noqa: E501
else:
(data) = self.get_template_html_for_template_id_with_http_info(template_id, **kwargs) # noqa: E501
return data
def get_template_html_for_template_id_with_http_info(self, template_id, **kwargs): # noqa: E501
"""Get the HTML for a given template # noqa: E501
Get the HTML for a given template, with or without rendered variables # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_template_html_for_template_id_with_http_info(template_id, async=True)
>>> result = thread.get()
:param async bool
:param str template_id: The id of the template. (required)
:param str render_variables: Whether to render profile variables in the returned HTML.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['template_id', 'render_variables'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_template_html_for_template_id" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'template_id' is set
if ('template_id' not in params or
params['template_id'] is None):
raise ValueError("Missing the required parameter `template_id` when calling `get_template_html_for_template_id`") # noqa: E501
collection_formats = {}
path_params = {}
if 'template_id' in params:
path_params['templateId'] = params['template_id'] # noqa: E501
query_params = []
if 'render_variables' in params:
query_params.append(('renderVariables', params['render_variables'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/x-www-form-urlencoded']) # noqa: E501
# Authentication setting
auth_settings = ['BBOAuth2'] # noqa: E501
return self.api_client.call_api(
'/emails/templates/{templateId}/html', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_video_quick_sender_data(self, **kwargs): # noqa: E501
"""Get quicksend data # noqa: E501
Get the user data for quicksender, including templates and lists. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_video_quick_sender_data(async=True)
>>> result = thread.get()
:param async bool
:param str message: A message for the video content.
:param str subject: A subject for the video content.
:param str video_id: A video ID.
:param str template_id: A template ID.
:param str comma_delim_emails: Comma delimited emails
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_video_quick_sender_data_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_video_quick_sender_data_with_http_info(**kwargs) # noqa: E501
return data
def get_video_quick_sender_data_with_http_info(self, **kwargs): # noqa: E501
"""Get quicksend data # noqa: E501
Get the user data for quicksender, including templates and lists. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_video_quick_sender_data_with_http_info(async=True)
>>> result = thread.get()
:param async bool
:param str message: A message for the video content.
:param str subject: A subject for the video content.
:param str video_id: A video ID.
:param str template_id: A template ID.
:param str comma_delim_emails: Comma delimited emails
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['message', 'subject', 'video_id', 'template_id', 'comma_delim_emails'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_video_quick_sender_data" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'message' in params:
query_params.append(('message', params['message'])) # noqa: E501
if 'subject' in params:
query_params.append(('subject', params['subject'])) # noqa: E501
if 'video_id' in params:
query_params.append(('videoId', params['video_id'])) # noqa: E501
if 'template_id' in params:
query_params.append(('templateId', params['template_id'])) # noqa: E501
if 'comma_delim_emails' in params:
query_params.append(('commaDelimEmails', params['comma_delim_emails'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/x-www-form-urlencoded']) # noqa: E501
# Authentication setting
auth_settings = ['BBOAuth2'] # noqa: E501
return self.api_client.call_api(
'/emails/quicksend', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def save_quick_sender_settings(self, **kwargs): # noqa: E501
"""Save quicksender settings # noqa: E501
Save the quicksender notification and default template settings # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.save_quick_sender_settings(async=True)
>>> result = thread.get()
:param async bool
:param str alert_on_play: A preference setting for whether or not to notify user on quicksend email video plays.
:param str alert_on_open: A preference setting for whether or not to notify user on quicksend email opens.
:param str template_id: Id of a template to use for this send. A null value means use the default for this user.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.save_quick_sender_settings_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.save_quick_sender_settings_with_http_info(**kwargs) # noqa: E501
return data
def save_quick_sender_settings_with_http_info(self, **kwargs): # noqa: E501
"""Save quicksender settings # noqa: E501
Save the quicksender notification and default template settings # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.save_quick_sender_settings_with_http_info(async=True)
>>> result = thread.get()
:param async bool
:param str alert_on_play: A preference setting for whether or not to notify user on quicksend email video plays.
:param str alert_on_open: A preference setting for whether or not to notify user on quicksend email opens.
:param str template_id: Id of a template to use for this send. A null value means use the default for this user.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['alert_on_play', 'alert_on_open', 'template_id'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method save_quick_sender_settings" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
if 'alert_on_play' in params:
form_params.append(('alertOnPlay', params['alert_on_play'])) # noqa: E501
if 'alert_on_open' in params:
form_params.append(('alertOnOpen', params['alert_on_open'])) # noqa: E501
if 'template_id' in params:
form_params.append(('templateId', params['template_id'])) # noqa: E501
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/x-www-form-urlencoded']) # noqa: E501
# Authentication setting
auth_settings = ['BBOAuth2'] # noqa: E501
return self.api_client.call_api(
'/emails/quicksend/settings', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def video_quick_sender(self, **kwargs): # noqa: E501
"""Send a quicksend email # noqa: | |
invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.portals_id_members_rel_fk_delete(id, fk, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Portal id (required)
:param str fk: Foreign key for members (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.portals_id_members_rel_fk_delete_with_http_info(id, fk, **kwargs)
else:
(data) = self.portals_id_members_rel_fk_delete_with_http_info(id, fk, **kwargs)
return data
def portals_id_members_rel_fk_delete_with_http_info(self, id, fk, **kwargs):
"""
Remove the members relation to an item by id.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.portals_id_members_rel_fk_delete_with_http_info(id, fk, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Portal id (required)
:param str fk: Foreign key for members (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id', 'fk']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method portals_id_members_rel_fk_delete" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params) or (params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `portals_id_members_rel_fk_delete`")
# verify the required parameter 'fk' is set
if ('fk' not in params) or (params['fk'] is None):
raise ValueError("Missing the required parameter `fk` when calling `portals_id_members_rel_fk_delete`")
collection_formats = {}
resource_path = '/Portals/{id}/members/rel/{fk}'.replace('{format}', 'json')
path_params = {}
if 'id' in params:
path_params['id'] = params['id']
if 'fk' in params:
path_params['fk'] = params['fk']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'])
# Authentication setting
auth_settings = ['access_token']
return self.api_client.call_api(resource_path, 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
collection_formats=collection_formats)
def portals_id_members_rel_fk_head(self, id, fk, **kwargs):
"""
Check the existence of members relation to an item by id.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.portals_id_members_rel_fk_head(id, fk, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Portal id (required)
:param str fk: Foreign key for members (required)
:return: bool
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.portals_id_members_rel_fk_head_with_http_info(id, fk, **kwargs)
else:
(data) = self.portals_id_members_rel_fk_head_with_http_info(id, fk, **kwargs)
return data
def portals_id_members_rel_fk_head_with_http_info(self, id, fk, **kwargs):
"""
Check the existence of members relation to an item by id.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.portals_id_members_rel_fk_head_with_http_info(id, fk, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Portal id (required)
:param str fk: Foreign key for members (required)
:return: bool
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id', 'fk']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method portals_id_members_rel_fk_head" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params) or (params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `portals_id_members_rel_fk_head`")
# verify the required parameter 'fk' is set
if ('fk' not in params) or (params['fk'] is None):
raise ValueError("Missing the required parameter `fk` when calling `portals_id_members_rel_fk_head`")
collection_formats = {}
resource_path = '/Portals/{id}/members/rel/{fk}'.replace('{format}', 'json')
path_params = {}
if 'id' in params:
path_params['id'] = params['id']
if 'fk' in params:
path_params['fk'] = params['fk']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'])
# Authentication setting
auth_settings = ['access_token']
return self.api_client.call_api(resource_path, 'HEAD',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='bool',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
collection_formats=collection_formats)
def portals_id_members_rel_fk_put(self, id, fk, **kwargs):
"""
Add a related item by id for members.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.portals_id_members_rel_fk_put(id, fk, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Portal id (required)
:param str fk: Foreign key for members (required)
:param PortalMember data:
:return: PortalMember
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.portals_id_members_rel_fk_put_with_http_info(id, fk, **kwargs)
else:
(data) = self.portals_id_members_rel_fk_put_with_http_info(id, fk, **kwargs)
return data
def portals_id_members_rel_fk_put_with_http_info(self, id, fk, **kwargs):
"""
Add a related item by id for members.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.portals_id_members_rel_fk_put_with_http_info(id, fk, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Portal id (required)
:param str fk: Foreign key for members (required)
:param PortalMember data:
:return: PortalMember
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id', 'fk', 'data']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method portals_id_members_rel_fk_put" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params) or (params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `portals_id_members_rel_fk_put`")
# verify the required parameter 'fk' is set
if ('fk' not in params) or (params['fk'] is None):
raise ValueError("Missing the required parameter `fk` when calling `portals_id_members_rel_fk_put`")
collection_formats = {}
resource_path = '/Portals/{id}/members/rel/{fk}'.replace('{format}', 'json')
path_params = {}
if 'id' in params:
path_params['id'] = params['id']
if 'fk' in params:
path_params['fk'] = params['fk']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'data' in params:
body_params = params['data']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'])
# Authentication setting
auth_settings = ['access_token']
return self.api_client.call_api(resource_path, 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PortalMember',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
collection_formats=collection_formats)
def portals_id_patch(self, id, **kwargs):
"""
Patch attributes for a model instance and persist it into the data source.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.portals_id_patch(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Portal id (required)
:param Portal data: An object of model property name/value pairs
:return: Portal
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.portals_id_patch_with_http_info(id, **kwargs)
else:
(data) = self.portals_id_patch_with_http_info(id, **kwargs)
return data
def portals_id_patch_with_http_info(self, id, **kwargs):
"""
Patch attributes for a model instance and persist it into the data source.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
| |
1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0
Element: 81
Faces:
-1 -1 -1 -1 -1 -1
Nodes:
88 96 81 89 184 192 177 185
Scale factors:
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0
Element: 82
Faces:
-1 -1 -1 -1 -1 -1
Nodes:
81 89 82 90 177 185 178 186
Scale factors:
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0
Element: 83
Faces:
-1 -1 -1 -1 -1 -1
Nodes:
82 90 83 91 178 186 179 187
Scale factors:
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0
Element: 84
Faces:
-1 -1 -1 -1 -1 -1
Nodes:
83 91 84 92 179 187 180 188
Scale factors:
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0
Element: 85
Faces:
-1 -1 -1 -1 -1 -1
Nodes:
84 92 85 93 180 188 181 189
Scale factors:
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0
Element: 86
Faces:
-1 -1 -1 -1 -1 -1
Nodes:
85 93 86 94 181 189 182 190
Scale factors:
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0
Element: 87
Faces:
-1 -1 -1 -1 -1 -1
Nodes:
86 94 87 95 182 190 183 191
Scale factors:
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0
Element: 88
Faces:
-1 -1 -1 -1 -1 -1
Nodes:
87 95 88 96 183 191 184 192
Scale factors:
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0
#Scale factor sets=3
scaling1, #Scale factors=64, identifiers="element_patch(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)"
scaling2, #Scale factors=8, identifiers="element_patch(0,0,0,0,0,0,0,0)"
scaling3, #Scale factors=8, identifiers="element_patch(0,0,0,0,0,0,0,0)"
#Nodes=8
#Fields=2
1) coordinates, coordinate, rectangular cartesian, real, #Components=3
x. c.Hermite*c.Hermite*c.Hermite, no modify, standard node based. scale factor set=scaling1
#Nodes=8
1. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 1 2 3 4 5 6 7 8
2. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 9 10 11 12 13 14 15 16
3. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 17 18 19 20 21 22 23 24
4. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 25 26 27 28 29 30 31 32
5. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 33 34 35 36 37 38 39 40
6. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 41 42 43 44 45 46 47 48
7. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 49 50 51 52 53 54 55 56
8. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 57 58 59 60 61 62 63 64
y. c.Hermite*c.Hermite*c.Hermite, no modify, standard node based. scale factor set=scaling1
#Nodes=8
1. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 1 2 3 4 5 6 7 8
2. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 9 10 11 12 13 14 15 16
3. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 17 18 19 20 21 22 23 24
4. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 25 26 27 28 29 30 31 32
5. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 33 34 35 36 37 38 39 40
6. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 41 42 43 44 45 46 47 48
7. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 49 50 51 52 53 54 55 56
8. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 57 58 59 60 61 62 63 64
z. c.Hermite*c.Hermite*c.Hermite, no modify, standard node based. scale factor set=scaling1
#Nodes=8
1. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 1 2 3 4 5 6 7 8
2. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: 9 10 11 12 13 14 15 16
3. #Values=8
Value labels: value d/ds1 d/ds2 d2/ds1ds2 d/ds3 d2/ds1ds3 d2/ds2ds3 d3/ds1ds2ds3
Scale factor indices: | |
import matplotlib.pyplot as plt
import numpy as np
import os,glob,sys,importlib,pickle#,scipy,coolbox,pybedtools,
# from tqdm import tqdm
from scipy.stats import rankdata
import pandas as pd
import networkx as nx
import seaborn as sns
from joblib import delayed, wrap_non_picklable_objects
from pathlib import Path
import plotly
from numba import jit
from joblib import Parallel
import sklearn.utils as sku
import plotly.graph_objects as go
import plotly.express as px
# j=sys.argv[1]
from urllib import request
import xml.etree.ElementTree as ET
import urllib
sys.path.insert(1, './nestedness_analysis/')
import nestedness_metrics_other_functions
from nestedness_metrics_other_functions import from_edges_to_matrix
# importlib.reload(sys.modules['EO_functions_bipartite'])
import extremal_bi
@delayed
@wrap_non_picklable_objects
def bip(cc,net,ff,C,patt):
# print(net)
# dd=cc[['spec','gene',net]]
dd=pd.read_csv('data/gcn/cc_'+patt+'.txt',index_col=False,sep='\t',usecols=['spec','gene',net])
# try:
dd=dd[dd[net]!=0]
# except:
# pass
# ee=nx.from_pandas_edgelist(dd,source='spec',target='gene')
# remove = [node for node,degree in dict(ee.degree()).items() if degree <5]
# ee.remove_nodes_from(remove)
# ff.append(ee)
B = nx.Graph()
B.add_nodes_from(dd['spec'], bipartite=0)
B.add_nodes_from(dd['gene'], bipartite=1)
B.add_weighted_edges_from(tuple(dd[['spec','gene',net]].itertuples(index=False, name=None)))
remove = [node for node,degree in dict(B.degree()).items() if degree <5]
B.remove_nodes_from(remove)
# C.append(B)
xx=nx.from_pandas_edgelist(dd,source='spec',target='gene',edge_attr=net)
remove = [node for node,degree in dict(xx.degree()).items() if degree <5]
xx.remove_nodes_from(remove)
# with open('data/gcn/NX_'+str(patt)+'_hypert.pkl', 'ab+') as f:
# pickle.dump(ff, f)
# with open('data/gcn/BX_'+str(patt)+'_hypert.pkl', 'ab+') as f:
# pickle.dump(C, f)
return xx,B
def load_list_of_dicts(filename, create_using=nx.Graph):
with open(filename, 'rb') as f:
list_of_dicts = pickle.load(f)
graphs = [create_using(graph) for graph in list_of_dicts]
return graphs
# @delayed
# @wrap_non_picklable_objects
def meas(measur,uni_bact,relgene,graphs,patt):
HTXX=uni_bact[uni_bact.index.isin(relgene.columns[1:-2].str.split('-').str[0])]
HTXX['index']=np.arange(len(HTXX))
# measur=eval(measur)
S = [eval(measur)(graphs[i]) for i in HTXX[HTXX['HT']==0]['index'].values]
T = [eval(measur)(graphs[i]) for i in HTXX[HTXX['HT']!=0]['index'].values]
if measur!='nx.degree':
non=pd.DataFrame(S).melt()
yes=pd.DataFrame(T).melt()
elif measur=='nx.degree':
non=pd.DataFrame(S.pop())
non=non.rename(columns={0:'variable',1:'value'})
yes=pd.DataFrame(T.pop())
yes=yes.rename(columns={0:'variable',1:'value'})
non['type']='NoHT'
non.dropna(inplace=True)
non=non[non.value!=0]
non=non[~non['variable'].str.contains('UniRef90')]
non.value=non.value/np.sum(non.value)
yes['type']='HT'
yes.dropna(inplace=True)
yes=yes[yes.value!=0]
yes=yes[~yes['variable'].str.contains('UniRef90')]
yes.value=yes.value/np.sum(yes.value)
df=non.append(yes)
# df=df.dropna()
df['gen']=df.variable.str.split('_').str[2]
df.to_csv("data/gcn/"+patt+"_"+str(measur)+".txt",sep='\t')
plt.figure(figsize=(10,30))
sns.set_theme(style="whitegrid")
sns.violinplot(data=df, y="gen", x="value",hue="type",
split=True, inner="quart", linewidth=1,
orient="h")
sns.despine(left=True)
plt.savefig("data/gcn/"+patt+"_"+str(measur)+"_violin.png",dpi=300,bbox_inches = "tight")
return df
def time_bar(data,XX,rank='rank',species='all'):
if rank=='rank':
data['rank']=rankdata(data.value,method='min')
elif rank=='rank_diff' or rank=='diff':
data['vx']=rankdata(data.value_x,method='min')
data['vy']=rankdata(data.value_y,method='min')
data['rank_diff']=data['vx'].astype('int')-data['vy'].astype('int')
data['diff']=data['value_x']-data['value_y']
# elif rank=='value':
# rank=data.value
if species!='all':
data=data[data['species']==species]
# clust = ll.groupby(['species','target','time'], as_index=False)['diff'].sum()
df = data[['species','target','time',rank]]#.sort_values(['time'], ascending=[True]).groupby(['species','time']).max(5)
jeff=pd.DataFrame(df.groupby(['species','time'])[rank].nlargest(XX))
jeff.reset_index(inplace=True)
for cc in np.unique(jeff.species):
jeff2=jeff[jeff['species']==cc]
if species!='all':
jeff2=df.loc[jeff2['level_2']]
else:
jeff2=df.iloc[jeff2['level_2']]
plt.figure(figsize=(15,5))
ax = sns.histplot(jeff2, x='time', hue='target', weights=rank,
multiple='stack', palette='icefire', shrink=0.6,bins=len(pd.unique(jeff2.time))+5)
ax.set_ylabel(str(rank)+'_HT')
ax.set_title(cc)
# Fix the legend so it's not on top of the bars.
# legend = ax.get_legend()
plt.legend([],[], frameon=False)
Path("data/gcn/img/"+cc).mkdir(parents=True, exist_ok=True)
plt.savefig("data/gcn/img/"+cc+"/"+str(data)+"_"+cc+"_"+str(rank)+".png",dpi=300,bbox_inches = "tight")
def proc_dat(noHT):
# noHT=jj.filter(regex=str(focus)).dropna(how='all')
noHT.columns=noHT.columns.str.split('_').str[0]
noHT=noHT.groupby(by=noHT.columns, axis=1).mean()
noHT=noHT.dropna(how='any')
noHT.reset_index(inplace=True)
jj=noHT.melt(['source','target'])
jj.rename(columns={'variable':'time'},inplace=True)
jj['t']=jj['time']
# jj['time']=jj['time'].astype('int')+2000
# jj['time'] = pd.to_datetime(jj['time'], format='%Y')
# jj=jj[jj['value']>5]
jj['species']=jj['source'].str.split('_').str[2]
jj=jj.dropna(how='any')
return jj
# @delayed
# @wrap_non_picklable_objects
def rev_tbar(jj,XX,gg,species='all'):
data=jj[['species','target','time','t','value']]
# df=data.copy()
# data.reset_index(inplace=True)
data['sum']=pd.DataFrame(data.groupby(['species','t','target'])['value'].transform('sum'))
# jeff.reset_index(inplace=True)
del data['value']
data.drop_duplicates(inplace=True)
data.reset_index(inplace=True)
del data['index'],data['time']
jeff=pd.DataFrame(data.groupby(['species','t'])['sum'].nlargest(XX))
jeff.reset_index(inplace=True)
jeffA=data.iloc[jeff['level_2']]
tim_len=len(np.unique(jeffA['t']))
if species!='all':
jeff=jeff[jeff['species']==species]
JJ=pd.DataFrame()
rr=[]
for q,ee in enumerate((np.unique(jeff.species))):
jeff2=jeffA[jeffA['species']==ee]#.explode('target')
dd=pd.DataFrame(jeff2['target'].to_numpy().reshape(int(len(jeff2)/tim_len),tim_len,order='F'))
if len(dd.melt())==(tim_len*XX):
JJ=JJ.append(dd)
rr=np.append(rr, ee)
jeffA=jeffA.sort_values(['species', 't'], ascending=[True, True])
labels,levels=pd.factorize(sku.shuffle(JJ.melt()['value']))
cc=pd.DataFrame(np.array(labels).reshape((XX)*len(rr),tim_len,order='F'))
for i in np.arange(0,len(cc),XX+1):
for col in cc:
cc.iloc[i:i+XX,col] = cc.iloc[i:i+XX,col].sort_values(ignore_index=True)
cc.loc[i+XX]=0
plt.figure(figsize=(10,30))
ax=sns.heatmap(cc,cmap='rocket_r',annot=True, fmt="d",cbar=False,xticklabels=False,
yticklabels=False).set(ylabel=' - '.join(rr))
# plt.show()
data.to_csv('data/gcn/'+str(gg)+'.csv',sep='\t')
# Path("data/gcn/img/"+cc).mkdir(parents=True, exist_ok=True)
plt.savefig("data/gcn/img/full_"+str(gg)+"_10.png",dpi=300,bbox_inches = "tight")
def group_time_plot(noHT,steps,XX,spec_spec):
noHT.columns=noHT.columns.str.split('_').str[0]
noHT.columns=pd.qcut((noHT.columns).astype('int'), steps, labels=False)
noHT=noHT.groupby(by=noHT.columns, axis=1).mean()
noHT=noHT.dropna(how='all')
noHT.reset_index(inplace=True)
jj=noHT.melt(['source','target'])
jj.rename(columns={'variable':'time'},inplace=True)
jj['t']=jj['time']
# jj['time']=jj['time'].astype('int')+2000
# jj['time'] = pd.to_datetime(jj['time'], format='%Y')
# jj=jj[jj['value']>5]
jj['species']=jj['source'].str.split('_').str[2]
jj=jj.dropna(how='any')
jj['rank']=rankdata(jj.value,method='min')
XX=50 #10
# df = noHT[['species','target','time','rank']]
del jj['value'], jj['t'], jj['source']
if spec_spec=='1':
jeff=pd.DataFrame(jj.groupby(['species','time'])['rank_diff'].nlargest(XX))
jeff=jeff.dropna(how='any')
jeff.reset_index(inplace=True)
jeff2=jj.loc[jeff['level_2']]
else:
jeff=pd.DataFrame(jj.groupby(['time'])['rank'].nlargest(XX))
jeff=jeff.dropna(how='any')
jeff.reset_index(inplace=True)
jeff2=jj.loc[jeff['level_1']]
plt.figure(figsize=(15,5))
ax = sns.histplot(jeff2, x='time', hue='target', weights='rank',
multiple='stack', palette='icefire', shrink=0.6,bins=len(pd.unique(jeff2['time']))+5)
ax.set_ylabel('rank_noHT')
# ax.set_title(cc)
# Fix the legend so it's not on top of the bars.
# legend = ax.get_legend()
plt.legend([],[], frameon=False)
def time_order_net(control,case,thresh=10**-6,group='source',groups=6,rounder=1,math='mean'):
def preproc(data):
data.columns=data.columns.str.split('_').str[0]
data.columns=pd.qcut((data.columns).astype('int'), groups, labels=False)
noHTm=data.groupby(by=data.columns, axis=1).mean()
noHTm=noHTm.dropna(how='all')
noHTm.reset_index(inplace=True)
noHTv=data.groupby(by=data.columns, axis=1).var()
noHTv=noHTv.dropna(how='all')
noHTv.reset_index(inplace=True)
return noHTm,noHTv
noHTm,noHTv=preproc(control)
HTm,HTv=preproc(case)
if math=='mean':
BB=noHTm[noHTm[0]>thresh].dropna().groupby(group).mean()-HTm[HTm[0]>thresh].dropna().groupby(group).mean()
elif math=='median':
BB=noHTm[noHTm[0]>thresh].dropna().groupby(group).median()-HTm[HTm[0]>thresh].dropna().groupby(group).median()
BB=np.round(BB,rounder)
aa='(BB[0]>='
bb='(BB[0]<='
for i in np.arange(groups)[1:]:
cc='BB['+str(i)+'])&(BB['+str(i)+']>='
aa=aa+str(cc)
dd='BB['+str(i)+'])&(BB['+str(i)+']<='
bb=bb+str(dd)
grow=BB[eval(bb[:-9])]
die=BB[eval(aa[:-9])]
def proc_run(BBgrow,grow):
if len(BBgrow)>0:
BBgrow[groups]=BBgrow[0]-BBgrow[groups-1]
BBgrow=BBgrow[BBgrow[groups]!=0]
BBgrow.sort_values(by=groups,inplace=True)
del BBgrow[groups]
BBgrow.to_csv('data/gcn/comp_net/'+str(group)+'_'+str(thresh)+'_'+str(math)+'_'+str(groups)+'_'+grow+'.txt',sep='\t')
else:
BBgrow=0
return BBgrow
BBgrow=proc_run(grow,'grow')
BBdie=proc_run(die,'die')
return BBgrow,BBdie,noHTm,HTm
def build_gcn(i,net,cc,min_deg=5):
# relgene=pd.read_csv(path,sep='\t')
# # relgene=pd.read_csv('50_genefamilies-cpm.tsv')
# # relgene=pd.read_csv('hmp_subset_genefamilies-cpm.tsv',sep='\t',nrows=100)
# relgene['gene']=relgene['# Gene Family'].str.split('|').str[0]
# relgene=relgene[relgene['gene']!='UniRef90_unknown']
# relgene=relgene[relgene['gene']!='UNMAPPED']
# relgene.index=relgene['# Gene Family']
# del relgene['gene'], relgene['# Gene Family']
# # relgene=relgene/relgene.sum(axis=0)
# # relgene=relgene/relgene.sum(axis=0)
# relgene['gen']=relgene.index.str.split('|').str[1].str.split('.').str[0].tolist()
# relgene['spec']=relgene.index.str.split('.').str[1]#.str.split('.').str[0].tolist()
# relgene['spec'].replace('_',' ')
# relgene.index=relgene.index.str.split('|').str[0]
# relgene=relgene.dropna()
# cc=relgene.groupby(['# Gene Family','spec']).sum()
# cc=cc.reset_index()
# cc=cc.rename(columns={'# Gene Family':'gene'})
# ff=[]
# C=[]
# for i,net in enumerate(relgene.columns[1:-2]):
# pd.read_csv()
dd=cc[['spec','gene',net]]
dd=dd[dd[net]!=0]
ee=nx.from_pandas_edgelist(dd,source='spec',target='gene',edge_attr=net)
remove = [node for node,degree in dict(ee.degree()).items() if degree <min_deg]
ee.remove_nodes_from(remove)
# ff.append(ee)
B = nx.Graph()
B.add_nodes_from(dd['spec'], bipartite=0)
B.add_nodes_from(dd['gene'], bipartite=1)
B.add_edges_from(tuple(dd[['spec','gene']].itertuples(index=False, name=None)))
remove = [node for node,degree in dict(B.degree()).items() if degree <min_deg]
B.remove_nodes_from(remove)
# C.append(B)
return ee,B
# with open('data/gcn/NX_Emore_'+name+'.pkl', 'wb') as f:
# pickle.dump(ff, f)
# with open('data/gcn/BX_Emore_'+name+'.pkl', 'wb') as f:
# pickle.dump(C, f)
def buildSYNCSA(dd):
names=pd.unique(dd.columns.str.split('_').str[1]+'_'+dd.columns.str.split('_').str[2])[1:]
for i in names:
# ff.columns = ff.columns.str.strip('_x')
# ff.columns = ff.columns.str.strip('_y')
# i=i.split('_')[1]+'_'+i.split('_')[2]
ff=dd.loc[:,dd.columns.str.contains(i)]
ff[['source','target']]=dd[['source','target']]
ff=ff[ff['source'].str.contains('s__')]
ff=ff[ff['target'].str.contains('UniRef')]
ff.groupby('source').sum().transpose().to_csv('comm_'+i+'.csv')
ff.reset_index(inplace=True)
ff.set_index(['source', 'target'], inplace=True)
del ff['index']
ff.columns=(ff.columns.str.split('_').str[1]+'_'+ff.columns.str.split('_').str[2])
gg=ff.groupby(by=ff.columns, axis=1).sum()
traits=gg[[i]].reset_index().pivot('source','target',i).dropna(how='all',axis=1).replace(np.nan,0)
traits.to_csv('trait_'+i+'.csv')
def buildNestedNess():
C=pd.DataFrame(columns=['N','Q','I','type'])
D=[]
files=glob.glob('*.npz')
for i,j in enumerate(files):
d=np.load(j)
C.loc[i]=[float(d['N']),float(d['Q']),float(d['I']),j.split('_')[1]+'_'+j.split('_')[2]+'_'+j.split('_')[3].split('.')[0]]
def structural_analysis(ii,i,graphs,ARG_meta,rand,deg_rand):
# aa= rrr[['from','to','value']].values
ccc=nx.convert_matrix.to_pandas_edgelist(graphs[ii])
ee=nx.convert_matrix.to_pandas_edgelist(graphs[ii])
# cc['weight']=np.random.randn(len(cc))
pww=i
j=(i.split('-')[1])
i=(i.split('-')[0])
rrr=str(ARG_meta[ARG_meta['id']==i].index.item())+'_'+str(ARG_meta[ARG_meta['id']==i]['group'].item())+'_'+str(j)
ccc.rename(columns={ccc.columns[2]:rrr},inplace=True)
a,b=pd.factorize(ccc['source'])
c,d=pd.factorize(ccc['target'])
rrr=pd.DataFrame()
rrr['from']=a
rrr['to']=c
rrr['value']=1
sss=str(ARG_meta[ARG_meta['id']==i]['group'].item())+'_'+str(j)
Path('nest/'+sss).mkdir(parents=True, exist_ok=True)
# rrr[['from','to','value']].to_csv('~/nest/'+sss+'/'+str(ccc.columns[2])+'.csv',sep=' ',index=False,header=False)
aa= rrr[['from','to','value']].values
if rand==True: ## to randomize
aa=pd.DataFrame(aa)
ddd=aa.sample(frac=np.float(deg_rand), replace=False, random_state=1) ##degree randomized
rrr=aa[~aa.isin(ddd)].dropna(how='all')
ddd.reset_index(inplace=True)
del ddd['index']
sss=shuffle(ddd)
aa=pd.concat([rrr,sss])
aa=np.array(aa).astype(int)
nodes_cols = int(max(aa[j,1] for j in range(aa.shape[0]))+1)
nodes_rows= int(max(aa[j,0] for j in range(aa.shape[0]))+1)
matrix=np.zeros((nodes_rows,nodes_cols),dtype='int')
for j in range(aa.shape[0]):
matrix[aa[j,0],aa[j,1]] = 1
M=matrix
cols_degr=M.sum(axis=0)
row_degr=M.sum(axis=1)
R,C=M.shape #rows and cols
#Nestednes
# In-block nestedness with B=1
Cn_=[np.repeat(1, R),np.repeat(1, C)]
max_blockN=max(max(Cn_[0]),max(Cn_[1]))+1
lambdasN=extremal_bi.call_lambda_i(M,cols_degr,row_degr,Cn_[1],Cn_[0],max_blockN,True)
N=extremal_bi.calculate_Fitness(M,cols_degr,row_degr,lambdasN[0],lambdasN[1],True)
#Modularity Extremal
C_=extremal_bi.recursive_step(M,cols_degr,row_degr,.7,3,False)
max_blockQ=max(max(C_[0]),max(C_[1]))+1
lambdasQ=extremal_bi.call_lambda_i(M,cols_degr,row_degr,C_[1],C_[0],max_blockQ,False)
Q=extremal_bi.calculate_Fitness(M,cols_degr,row_degr,lambdasQ[0],lambdasQ[1],False)
# Inblock nestedness extremal
Ci_=extremal_bi.recursive_step(M,cols_degr,row_degr,.7,3,True)
max_blockI=max(max(Ci_[0]),max(Ci_[1]))+1
lambdasI=extremal_bi.call_lambda_i(M,cols_degr,row_degr,Ci_[1],Ci_[0],max_blockI,True)
I=extremal_bi.calculate_Fitness(M,cols_degr,row_degr,lambdasI[0],lambdasI[1],True)
zzz=[str(N),str(Q),str(I),sss]
print(zzz)
# np.savetxt('ARG_nest_test.txt', zzz, delimiter = '\t', fmt='%s')
with open("randB_ARG_nest.txt", "ab") as f:
np.savetxt(f,np.column_stack([str(N),str(Q),str(I),sss,pww]),delimiter = '\t', fmt='%s')
return N,Q,I,sss,pww
def shuffle_net(df, n=1, axis=0):
df = df.copy()
for _ in range(n):
df.apply(np.random.shuffle, axis=axis)
return df
#https://stackoverflow.com/questions/15772009/shuffling-permutating-a-dataframe-in-pandas
def create_data(path,rand):
C=pd.read_csv(path,header=0)#,'type','init'],sep='\t')
#### for randomized samples
C=C[C['name']!='name']
C['R']=C['R'].str.replace("False", "0")
# pd.unique(C['name'])
C=C[C['R']==rand]
del C['R']
# ####
C['type']=C['name'].str.split('_').str[1]+'_'+C['name'].str.split('_').str[2]
C['type']=C['type'].str.replace("_00", "_00ST")
# # C=C[~C['type'].str.contains("03")]
C['type']=C['type'].str.replace("_03ST", "_02ST")
C['type']=C['type'].str.replace("_00STST", "_00ST")
C['sample']=C['name'].str.split('_').str[0]
C=C[C['N']!='0.0']
# C=C[~C['name'].duplicated(keep='last')]
C=C[~C[['type','sample']].duplicated(keep='last')]
del C['name']
C.reset_index(inplace=True)
del C['index']
D=C.pivot(index='sample', columns='type', values=['N','I','Q'])
D=D.astype('float')
return D
def form_tests(data,var,level):
E0=data[var].reset_index()
E0=E0[['sample',level+'_00ST',level+'_01ST',level+'_02ST']]
E0['var']=var
return E0
def merge_form(data,level):
E0=form_tests(data,'N',level)
E1=form_tests(data,'I',level)
E2=form_tests(data,'Q',level)
E=E0.append(E1)
E=E.append(E2)
return E
def output_data(D):
E=merge_form(D,'CLA')
G=merge_form(D,'LEVO')
F=merge_form(D,'OTHER')
H=E.merge(G,on=['sample','var'])
H=H.merge(F,on=['sample','var'])
# H.set_index(['var','sample'],inplace=True)
# del H['var_x'],H['var_y']#,H0['type']
return H
def makeSYNCSAnet(relgene,graphs,JEFF,META,deg_rand):
# for i,net in tqdm.tqdm(enumerate(BX_graphs)):
# for ii,i in tqdm():
for ii,i in (enumerate(relgene.columns[1:])):
ccc=nx.convert_matrix.to_pandas_edgelist(graphs[ii])
ee=nx.convert_matrix.to_pandas_edgelist(graphs[ii])
# cc['weight']=np.random.randn(len(cc))
pww=i
j=(i.split('-')[1])
i=(i.split('-')[0])
try:
rrr=str(META[META['id']==i].index.item())+'_'+str(META[META['id']==i]['group'].item())+'_'+str(j)
ccc.rename(columns={ccc.columns[2]:rrr},inplace=True)
ddd=ccc[ccc['source'].str.contains('UniRef')]
ddd[['source','target']] = ddd[['target','source']]
ccc=ccc[~ccc['source'].str.contains('UniRef')].append(ddd)
if deg_rand!=0:
aa=pd.DataFrame(ccc)
pcc=aa.sample(frac=np.float(deg_rand), replace=False, random_state=1) ##degree randomized
pol=aa[~aa.isin(pcc)].dropna(how='all')
pcc.reset_index(inplace=True)
del pcc['index']
lll=shuffle_net(pcc)
ccc=pd.concat([pol,lll])
del aa,pol,pcc,lll
# a,b=pd.factorize(ccc['source'])
# c,d=pd.factorize(ccc['target'])
# rrr=pd.DataFrame()
# rrr['from']=a
# rrr['to']=c
# rrr['value']=1
# sss=str(META[META['id']==i]['group'].item())+'_'+str(j)
# Path('~/nest/'+sss).mkdir(parents=True, exist_ok=True)
# rrr[['from','to','value']].to_csv('~/nest/'+sss+'/'+str(ccc.columns[2])+'.csv',sep=' ',index=False,header=False)
# ee.rename(columns={ee.columns[2]:sss},inplace=True)
print(ii)
if ii==0:
dd=ccc
# ff=ee
else:
dd=dd.merge(ccc,on=['source','target'],how='outer')
# ff=ff.merge(ee,on=['source','target'],how='outer')
del ddd,rrr,ee,ccc
except:
print('no match for '+str(i))
return dd
# names=pd.unique(dd.columns.str.split('_').str[1]+'_'+dd.columns.str.split('_').str[2])[1:]
# for i in tqdm(names):
def group4SYNCSA(i,dd,DR):
# ff.columns = ff.columns.str.strip('_x')
# ff.columns = ff.columns.str.strip('_y')
# i=i.split('_')[1]+'_'+i.split('_')[2]
ff=dd.loc[:,dd.columns.str.contains(i)]
ff[['source','target']]=dd[['source','target']]
ff=ff[ff['source'].str.contains('s__')]
ff=ff[ff['target'].str.contains('UniRef')]
comm=ff.groupby('source').sum().transpose()
comm.to_csv('~/SYNCSA_eval/'+str(DR)+'_rand_comm_'+i+'.csv')
ff.reset_index(inplace=True)
ff.set_index(['source', 'target'], inplace=True)
del ff['index']
ff.columns=(ff.columns.str.split('_').str[1]+'_'+ff.columns.str.split('_').str[2])
gg=ff.groupby(by=ff.columns, axis=1).sum()
# traits=gg[[i]].reset_index().pivot('source','target',i).dropna(how='all',axis=1).replace(np.nan,0)
traits=gg[[i]].reset_index().groupby(['source','target']).mean().reset_index().pivot('source','target',i).dropna(how='all',axis=1).replace(np.nan,0)
traits.to_csv('~/SYNCSA_eval/'+str(DR)+'_rand_trait_'+i+'.csv')
def research_orthologs(uniID, species):
'''
research orthologs of a specific UniProtID in the inparanoid database available on the web
save the info in the neo4j database
'''
# import urllib
url="http://inparanoid.sbc.su.se/cgi-bin/gene_search.cgi?idtype=all;all_or_selection=all;scorelimit=0.05;rettype=xml;id=" + uniID
# request = request(url)
# for n in range(10):
response = request.urlopen(url)
txml = response.read()
root = ET.fromstring(txml)
for cluster in root.iter('cluster'):
# print(cluster)
c = cluster.attrib['nr'] #Cluster ID
for p in cluster.iter('protein'):
pid = p.attrib['prot_id']
spec = p.attrib['speclong']
if spec in species:
P=pid
S=spec
return P,S
def dgtz(A):
bis=np.round(np.sqrt(len(A))).astype(int)
# bisA=np.abs(np.round((np.round(np.min(A),-1)-np.round(np.max(A),-1))/bis))
# binA=np.arange(np.round(np.min(A),-1),np.round(np.max(A),-1),bisA)
bisA=np.abs(np.round(np.min(A))-(np.max(A))/bis)
binA=np.arange((np.min(A)),(np.max(A)),bisA)
tmpA=np.digitize(A,bins=binA)
return tmpA,bis
def shan_entropy(c):
c_normalized = c / (np.sum(c))
c_normalized = c_normalized[np.nonzero(c_normalized)]
H = -sum(c_normalized* np.log2(c_normalized))
return H
def get_red(c_X,c_Y,c_Z,c_XZ,c_YZ):
SI0=np.sum(np.nan_to_num(np.divide(c_XZ,c_Z)*(np.log10(np.divide(c_XZ,(np.matmul(c_X,c_Z))))), posinf=0, neginf=0),axis=0)
SI1=np.sum(np.nan_to_num(np.divide(c_YZ,c_Z)*(np.log10(np.divide(c_YZ,(np.matmul(c_Y,c_Z))))), posinf=0, neginf=0),axis=0) ##maybe along axis=1
minSI=np.min([SI0,SI1])
red=np.sum((c_Z)*minSI)
return red,SI0,SI1
def calc_MI(H_X,H_Y,H_XY):
return H_X + H_Y - H_XY
def calc_CMI(H_XZ,H_YZ,H_XYZ,H_Z):
return H_XZ+H_YZ+H_XYZ-H_Z
def calc_II(CMI_XY,MI_XY):
return CMI_XY-MI_XY
# cdf=[]
# pucN=[]
# data=pd.read_csv('data/Pipeline_consolidate_220301/UP_gene_sum_Lx.txt',sep='\t',header=None,index_col=0)
# data=data[1:12]
# for i in np.arange(1,len(data)):
# @jit(nopython=True)
def puc_cal(data,i,genes,cdf,puc_genes):
if cdf!=[]:
tiss=str(cdf)
cdf=[]
if puc_genes!=[]:
omic=str(puc_genes)
puc_genes=[]
for j in (np.arange(1,len(data))):#,position=1, desc="j", leave=False, colour='magenta'):
pucN=[];
for k in (np.arange(1,len(data))):#,position=2, desc="k", leave=False, colour='cyan'):
# try:
# time.sleep(0.5)
puc=0
if (i!=j)&(i!=k)&(j!=k):
# print(i,j,k)
A=np.array(data.iloc[i]).tolist()
B=np.array(data.iloc[j]).tolist()
C=np.array(data.iloc[k]).tolist()
# print(A)
# A=np.array(data[1]).tolist()
# B=np.array(data[2]).tolist()
# C=np.array(data[3]).tolist()
tmpA,ba=dgtz(A);
tmpB,bb=dgtz(B);
tmpC,cc=dgtz(C)
A=tmpA/np.sum(tmpA);B=tmpB/np.sum(tmpB);C=tmpC/np.sum(tmpC);
b=np.round(np.sqrt(len(A))).astype(int)
c_XY = np.histogramdd([A,B],bins=(b,b))[0]
c_XZ = np.histogramdd([A,C],bins=(b,b))[0]
c_YZ = np.histogramdd([B,C],bins=(b,b))[0]
c_XYZ = np.histogramdd([A,B,C],bins=(b,b,b))[0]
c_Z = np.histogramdd([C],bins=(b))[0]
c_Y = np.histogramdd([B],bins=(b))[0]
c_X = np.histogramdd([A],bins=(b))[0]
# H=[]
# for ii,i in enumerate([c_X,c_Y,c_Z,c_XY,c_XZ,c_YZ,c_XYZ]):
# i.split('_')[1]
H_X= shan_entropy(c_X)
H_Y = shan_entropy(c_Y)
H_Z = shan_entropy(c_Z)
H_XY = shan_entropy(c_XY)
H_XZ = shan_entropy(c_XZ)
H_YZ = shan_entropy(c_YZ)
H_XYZ = shan_entropy(c_XYZ)
MIxy=calc_MI(H_X,H_Y,H_XY)
MIxz=calc_MI(H_X,H_Z,H_XZ)
MIyz=calc_MI(H_Z,H_Y,H_YZ)
CMIx=calc_CMI(H_XZ,H_XY,H_XYZ,H_X)
CMIy=calc_CMI(H_XY,H_YZ,H_XYZ,H_Y)
CMIz=calc_CMI(H_XZ,H_YZ,H_XYZ,H_Z)
[calc_II(CMIz,MIxy),
calc_II(CMIy,MIxz),
calc_II(CMIx,MIyz)]
rX=get_red(c_X,c_Z,c_Y,c_XY,c_XZ)
rY=get_red(c_X,c_Y,c_Z,c_XZ,c_YZ)
rZ=get_red(c_Y,c_X,c_Z,c_YZ,c_XY)
# # [rX[0],rY[0],rZ[0]]
| |
<reponame>janssenhenning/pymatgen
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License
"""
Module for reading Lobster output files. For more information
on LOBSTER see www.cohp.de.
"""
import collections
import fnmatch
import os
import re
import warnings
from collections import defaultdict
from typing import Any, Dict, List, Optional
import numpy as np
from monty.io import zopen
from pymatgen.core.structure import Structure
from pymatgen.electronic_structure.bandstructure import LobsterBandStructureSymmLine
from pymatgen.electronic_structure.core import Orbital, Spin
from pymatgen.electronic_structure.dos import Dos, LobsterCompleteDos
from pymatgen.io.vasp.inputs import Kpoints
from pymatgen.io.vasp.outputs import Vasprun, VolumetricData
__author__ = "<NAME>, <NAME>"
__copyright__ = "Copyright 2017, The Materials Project"
__version__ = "0.2"
__maintainer__ = "<NAME>, <NAME> "
__email__ = "<EMAIL>, <EMAIL>"
__date__ = "Dec 13, 2017"
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
class Cohpcar:
"""
Class to read COHPCAR/COOPCAR files generated by LOBSTER.
.. attribute: cohp_data
Dict that contains the COHP data of the form:
{bond: {"COHP": {Spin.up: cohps, Spin.down:cohps},
"ICOHP": {Spin.up: icohps, Spin.down: icohps},
"length": bond length,
"sites": sites corresponding to the bond}
Also contains an entry for the average, which does not have
a "length" key.
.. attribute: efermi
The Fermi energy in eV.
.. attribute: energies
Sequence of energies in eV. Note that LOBSTER shifts the energies
so that the Fermi energy is at zero.
.. attribute: is_spin_polarized
Boolean to indicate if the calculation is spin polarized.
.. attribute: orb_res_cohp
orb_cohp[label] = {bond_data["orb_label"]: {"COHP": {Spin.up: cohps, Spin.down:cohps},
"ICOHP": {Spin.up: icohps, Spin.down: icohps},
"orbitals": orbitals,
"length": bond lengths,
"sites": sites corresponding to the bond}}
"""
def __init__(self, are_coops: bool = False, are_cobis: bool = False, filename: str = None):
"""
Args:
are_coops: Determines if the file is a list of COHPs or COOPs.
Default is False for COHPs.
are_cobis: Determines if the file is a list of COHPs or COOPs.
Default is False for COHPs.
filename: Name of the COHPCAR file. If it is None, the default
file name will be chosen, depending on the value of are_coops.
"""
if are_coops and are_cobis:
raise ValueError("You cannot have info about COOPs and COBIs in the same file.")
self.are_coops = are_coops
self.are_cobis = are_cobis
if filename is None:
if are_coops:
filename = "COOPCAR.lobster"
elif are_cobis:
filename = "COBICAR.lobster"
else:
filename = "COHPCAR.lobster"
with zopen(filename, "rt") as f:
contents = f.read().split("\n")
# The parameters line is the second line in a COHPCAR file. It
# contains all parameters that are needed to map the file.
parameters = contents[1].split()
# Subtract 1 to skip the average
num_bonds = int(parameters[0]) - 1
self.efermi = float(parameters[-1])
if int(parameters[1]) == 2:
spins = [Spin.up, Spin.down]
self.is_spin_polarized = True
else:
spins = [Spin.up]
self.is_spin_polarized = False
# The COHP data start in row num_bonds + 3
data = np.array([np.array(row.split(), dtype=float) for row in contents[num_bonds + 3 :]]).transpose()
data = np.array([np.array(row.split(), dtype=float) for row in contents[num_bonds + 3 :]]).transpose()
self.energies = data[0]
cohp_data = {
"average": {
"COHP": {spin: data[1 + 2 * s * (num_bonds + 1)] for s, spin in enumerate(spins)},
"ICOHP": {spin: data[2 + 2 * s * (num_bonds + 1)] for s, spin in enumerate(spins)},
}
} # type: Dict[Any, Any]
orb_cohp = {} # type: Dict[str, Any]
# present for Lobster versions older than Lobster 2.2.0
veryold = False
# the labeling had to be changed: there are more than one COHP for each atom combination
# this is done to make the labeling consistent with ICOHPLIST.lobster
bondnumber = 0
for bond in range(num_bonds):
bond_data = self._get_bond_data(contents[3 + bond])
label = str(bondnumber)
orbs = bond_data["orbitals"]
cohp = {spin: data[2 * (bond + s * (num_bonds + 1)) + 3] for s, spin in enumerate(spins)}
icohp = {spin: data[2 * (bond + s * (num_bonds + 1)) + 4] for s, spin in enumerate(spins)}
if orbs is None:
bondnumber = bondnumber + 1
label = str(bondnumber)
cohp_data[label] = {
"COHP": cohp,
"ICOHP": icohp,
"length": bond_data["length"],
"sites": bond_data["sites"],
}
elif label in orb_cohp:
orb_cohp[label].update(
{
bond_data["orb_label"]: {
"COHP": cohp,
"ICOHP": icohp,
"orbitals": orbs,
"length": bond_data["length"],
"sites": bond_data["sites"],
}
}
)
else:
# present for Lobster versions older than Lobster 2.2.0
if bondnumber == 0:
veryold = True
if veryold:
bondnumber += 1
label = str(bondnumber)
orb_cohp[label] = {
bond_data["orb_label"]: {
"COHP": cohp,
"ICOHP": icohp,
"orbitals": orbs,
"length": bond_data["length"],
"sites": bond_data["sites"],
}
}
# present for lobster older than 2.2.0
if veryold:
for bond_str in orb_cohp:
cohp_data[bond_str] = {
"COHP": None,
"ICOHP": None,
"length": bond_data["length"],
"sites": bond_data["sites"],
}
self.orb_res_cohp = orb_cohp if orb_cohp else None
self.cohp_data = cohp_data
@staticmethod
def _get_bond_data(line: str) -> dict:
"""
Subroutine to extract bond label, site indices, and length from
a LOBSTER header line. The site indices are zero-based, so they
can be easily used with a Structure object.
Example header line: No.4:Fe1->Fe9(2.4524893531900283)
Example header line for orbtial-resolved COHP:
No.1:Fe1[3p_x]->Fe2[3d_x^2-y^2](2.456180552772262)
Args:
line: line in the COHPCAR header describing the bond.
Returns:
Dict with the bond label, the bond length, a tuple of the site
indices, a tuple containing the orbitals (if orbital-resolved),
and a label for the orbitals (if orbital-resolved).
"""
orb_labs = [
"s",
"p_y",
"p_z",
"p_x",
"d_xy",
"d_yz",
"d_z^2",
"d_xz",
"d_x^2-y^2",
"f_y(3x^2-y^2)",
"f_xyz",
"f_yz^2",
"f_z^3",
"f_xz^2",
"f_z(x^2-y^2)",
"f_x(x^2-3y^2)",
]
line_new = line.rsplit("(", 1)
# bondnumber = line[0].replace("->", ":").replace(".", ":").split(':')[1]
length = float(line_new[-1][:-1])
sites = line_new[0].replace("->", ":").split(":")[1:3]
site_indices = tuple(int(re.split(r"\D+", site)[1]) - 1 for site in sites)
# species = tuple(re.split(r"\d+", site)[0] for site in sites)
if "[" in sites[0]:
orbs = [re.findall(r"\[(.*)\]", site)[0] for site in sites]
orbitals = [tuple((int(orb[0]), Orbital(orb_labs.index(orb[1:])))) for orb in orbs] # type: Any
orb_label = "%d%s-%d%s" % (
orbitals[0][0],
orbitals[0][1].name,
orbitals[1][0],
orbitals[1][1].name,
) # type: Any
else:
orbitals = None
orb_label = None
# a label based on the species alone is not feasible, there can be more than one bond for each atom combination
# label = "%s" % (bondnumber)
bond_data = {
"length": length,
"sites": site_indices,
"orbitals": orbitals,
"orb_label": orb_label,
}
return bond_data
class Icohplist:
"""
Class to read ICOHPLIST/ICOOPLIST files generated by LOBSTER.
.. attribute: are_coops
Boolean to indicate if the populations are COOPs or COHPs.
.. attribute: is_spin_polarized
Boolean to indicate if the calculation is spin polarized.
.. attribute: Icohplist
Dict containing the listfile data of the form:
{bond: "length": bond length,
"number_of_bonds": number of bonds
"icohp": {Spin.up: ICOHP(Ef) spin up, Spin.down: ...}}
.. attribute: IcohpCollection
IcohpCollection Object
"""
def __init__(self, are_coops: bool = False, are_cobis: bool = False, filename: str = None):
"""
Args:
are_coops: Determines if the file is a list of ICOOPs.
Defaults to False for ICOHPs.
are_cobis: Determines if the file is a list of ICOBIs.
Defaults to False for ICOHPs.
filename: Name of the ICOHPLIST file. If it is None, the default
file name will be chosen, depending on the value of are_coops.
"""
if are_coops and are_cobis:
raise ValueError("You cannot have info about COOPs and COBIs in the same file.")
self.are_coops = are_coops
self.are_cobis = are_cobis
if filename is None:
if are_coops:
filename = "ICOOPLIST.lobster"
elif are_cobis:
filename = "ICOBILIST.lobster"
else:
filename = "ICOHPLIST.lobster"
# LOBSTER list files have an extra trailing blank line
# and we don't need the header.
with zopen(filename, "rt") as f:
data = f.read().split("\n")[1:-1]
if len(data) == 0:
raise IOError("ICOHPLIST file contains no data.")
# Which Lobster version?
if len(data[0].split()) == 8:
version = "3.1.1"
elif len(data[0].split()) == 6:
version = "2.2.1"
warnings.warn("Please consider using the new Lobster version. See www.cohp.de.")
else:
raise ValueError
# If the calculation is spin polarized, the line in the middle
# of the file will be another header line.
if "distance" in data[len(data) // 2]:
# TODO: adapt this for orbitalwise stuff
self.is_spin_polarized = True
else:
self.is_spin_polarized = False
# check if orbitalwise ICOHPLIST
# include case when there is only one ICOHP!!!
if len(data) > 2 and "_" in data[2].split()[1]:
self.orbitalwise = True
warnings.warn("This is an orbitalwise IC**LIST.lobter. Currently, the orbitalwise information is not read!")
else:
self.orbitalwise = False
if self.orbitalwise:
data_without_orbitals = []
for line in data:
if "_" not in line.split()[1]:
data_without_orbitals.append(line)
else:
data_without_orbitals = data
if "distance" in data_without_orbitals[len(data_without_orbitals) // | |
<reponame>gvashchenkolineate/gvashchenkolineate_infra_trytravis<filename>ansible/venv/lib/python2.7/site-packages/ansible/module_utils/network/ftd/configuration.py
# Copyright (c) 2018 Cisco and/or its affiliates.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
import copy
from functools import partial
from ansible.module_utils.network.ftd.common import HTTPMethod, equal_objects, FtdConfigurationError, \
FtdServerError, ResponseParams, copy_identity_properties, FtdUnexpectedResponse
from ansible.module_utils.network.ftd.fdm_swagger_client import OperationField, ValidationError
from ansible.module_utils.six import iteritems
DEFAULT_PAGE_SIZE = 10
DEFAULT_OFFSET = 0
UNPROCESSABLE_ENTITY_STATUS = 422
INVALID_UUID_ERROR_MESSAGE = "Validation failed due to an invalid UUID"
DUPLICATE_NAME_ERROR_MESSAGE = "Validation failed due to a duplicate name"
MULTIPLE_DUPLICATES_FOUND_ERROR = (
"Multiple objects matching specified filters are found. "
"Please, define filters more precisely to match one object exactly."
)
DUPLICATE_ERROR = (
"Cannot add a new object. "
"An object with the same name but different parameters already exists."
)
ADD_OPERATION_NOT_SUPPORTED_ERROR = (
"Cannot add a new object while executing an upsert request. "
"Creation of objects with this type is not supported."
)
PATH_PARAMS_FOR_DEFAULT_OBJ = {'objId': 'default'}
class OperationNamePrefix:
ADD = 'add'
EDIT = 'edit'
GET = 'get'
DELETE = 'delete'
UPSERT = 'upsert'
class QueryParams:
FILTER = 'filter'
class ParamName:
QUERY_PARAMS = 'query_params'
PATH_PARAMS = 'path_params'
DATA = 'data'
FILTERS = 'filters'
class CheckModeException(Exception):
pass
class FtdInvalidOperationNameError(Exception):
def __init__(self, operation_name):
super(FtdInvalidOperationNameError, self).__init__(operation_name)
self.operation_name = operation_name
class OperationChecker(object):
@classmethod
def is_add_operation(cls, operation_name, operation_spec):
"""
Check if operation defined with 'operation_name' is add object operation according to 'operation_spec'.
:param operation_name: name of the operation being called by the user
:type operation_name: str
:param operation_spec: specification of the operation being called by the user
:type operation_spec: dict
:return: True if the called operation is add object operation, otherwise False
:rtype: bool
"""
# Some endpoints have non-CRUD operations, so checking operation name is required in addition to the HTTP method
return operation_name.startswith(OperationNamePrefix.ADD) and is_post_request(operation_spec)
@classmethod
def is_edit_operation(cls, operation_name, operation_spec):
"""
Check if operation defined with 'operation_name' is edit object operation according to 'operation_spec'.
:param operation_name: name of the operation being called by the user
:type operation_name: str
:param operation_spec: specification of the operation being called by the user
:type operation_spec: dict
:return: True if the called operation is edit object operation, otherwise False
:rtype: bool
"""
# Some endpoints have non-CRUD operations, so checking operation name is required in addition to the HTTP method
return operation_name.startswith(OperationNamePrefix.EDIT) and is_put_request(operation_spec)
@classmethod
def is_delete_operation(cls, operation_name, operation_spec):
"""
Check if operation defined with 'operation_name' is delete object operation according to 'operation_spec'.
:param operation_name: name of the operation being called by the user
:type operation_name: str
:param operation_spec: specification of the operation being called by the user
:type operation_spec: dict
:return: True if the called operation is delete object operation, otherwise False
:rtype: bool
"""
# Some endpoints have non-CRUD operations, so checking operation name is required in addition to the HTTP method
return operation_name.startswith(OperationNamePrefix.DELETE) \
and operation_spec[OperationField.METHOD] == HTTPMethod.DELETE
@classmethod
def is_get_list_operation(cls, operation_name, operation_spec):
"""
Check if operation defined with 'operation_name' is get list of objects operation according to 'operation_spec'.
:param operation_name: name of the operation being called by the user
:type operation_name: str
:param operation_spec: specification of the operation being called by the user
:type operation_spec: dict
:return: True if the called operation is get a list of objects operation, otherwise False
:rtype: bool
"""
return operation_spec[OperationField.METHOD] == HTTPMethod.GET \
and operation_spec[OperationField.RETURN_MULTIPLE_ITEMS]
@classmethod
def is_get_operation(cls, operation_name, operation_spec):
"""
Check if operation defined with 'operation_name' is get objects operation according to 'operation_spec'.
:param operation_name: name of the operation being called by the user
:type operation_name: str
:param operation_spec: specification of the operation being called by the user
:type operation_spec: dict
:return: True if the called operation is get object operation, otherwise False
:rtype: bool
"""
return operation_spec[OperationField.METHOD] == HTTPMethod.GET \
and not operation_spec[OperationField.RETURN_MULTIPLE_ITEMS]
@classmethod
def is_upsert_operation(cls, operation_name):
"""
Check if operation defined with 'operation_name' is upsert objects operation according to 'operation_name'.
:param operation_name: name of the operation being called by the user
:type operation_name: str
:return: True if the called operation is upsert object operation, otherwise False
:rtype: bool
"""
return operation_name.startswith(OperationNamePrefix.UPSERT)
@classmethod
def is_find_by_filter_operation(cls, operation_name, params, operation_spec):
"""
Checks whether the called operation is 'find by filter'. This operation fetches all objects and finds
the matching ones by the given filter. As filtering is done on the client side, this operation should be used
only when selected filters are not implemented on the server side.
:param operation_name: name of the operation being called by the user
:type operation_name: str
:param operation_spec: specification of the operation being called by the user
:type operation_spec: dict
:param params: params - params should contain 'filters'
:return: True if the called operation is find by filter, otherwise False
:rtype: bool
"""
is_get_list = cls.is_get_list_operation(operation_name, operation_spec)
return is_get_list and ParamName.FILTERS in params and params[ParamName.FILTERS]
@classmethod
def is_upsert_operation_supported(cls, operations):
"""
Checks if all operations required for upsert object operation are defined in 'operations'.
:param operations: specification of the operations supported by model
:type operations: dict
:return: True if all criteria required to provide requested called operation are satisfied, otherwise False
:rtype: bool
"""
has_edit_op = next((name for name, spec in iteritems(operations) if cls.is_edit_operation(name, spec)), None)
has_get_list_op = next((name for name, spec in iteritems(operations)
if cls.is_get_list_operation(name, spec)), None)
return has_edit_op and has_get_list_op
class BaseConfigurationResource(object):
def __init__(self, conn, check_mode=False):
self._conn = conn
self.config_changed = False
self._operation_spec_cache = {}
self._models_operations_specs_cache = {}
self._check_mode = check_mode
self._operation_checker = OperationChecker
def execute_operation(self, op_name, params):
"""
Allow user request execution of simple operations(natively supported by API provider) as well as complex
operations(operations that are implemented as a set of simple operations).
:param op_name: name of the operation being called by the user
:type op_name: str
:param params: definition of the params that operation should be executed with
:type params: dict
:return: Result of the operation being executed
:rtype: dict
"""
if self._operation_checker.is_upsert_operation(op_name):
return self.upsert_object(op_name, params)
else:
return self.crud_operation(op_name, params)
def crud_operation(self, op_name, params):
"""
Allow user request execution of simple operations(natively supported by API provider) only.
:param op_name: name of the operation being called by the user
:type op_name: str
:param params: definition of the params that operation should be executed with
:type params: dict
:return: Result of the operation being executed
:rtype: dict
"""
op_spec = self.get_operation_spec(op_name)
if op_spec is None:
raise FtdInvalidOperationNameError(op_name)
if self._operation_checker.is_add_operation(op_name, op_spec):
resp = self.add_object(op_name, params)
elif self._operation_checker.is_edit_operation(op_name, op_spec):
resp = self.edit_object(op_name, params)
elif self._operation_checker.is_delete_operation(op_name, op_spec):
resp = self.delete_object(op_name, params)
elif self._operation_checker.is_find_by_filter_operation(op_name, params, op_spec):
resp = list(self.get_objects_by_filter(op_name, params))
else:
resp = self.send_general_request(op_name, params)
return resp
def get_operation_spec(self, operation_name):
if operation_name not in self._operation_spec_cache:
self._operation_spec_cache[operation_name] = self._conn.get_operation_spec(operation_name)
return self._operation_spec_cache[operation_name]
def get_operation_specs_by_model_name(self, model_name):
if model_name not in self._models_operations_specs_cache:
model_op_specs = self._conn.get_operation_specs_by_model_name(model_name)
self._models_operations_specs_cache[model_name] = model_op_specs
for op_name, op_spec in iteritems(model_op_specs):
self._operation_spec_cache.setdefault(op_name, op_spec)
return self._models_operations_specs_cache[model_name]
def get_objects_by_filter(self, operation_name, params):
def match_filters(filter_params, obj):
for k, v in iteritems(filter_params):
if k not in obj or obj[k] != v:
return False
return True
dummy, query_params, path_params = _get_user_params(params)
# copy required params to avoid mutation of passed `params` dict
url_params = {ParamName.QUERY_PARAMS: dict(query_params), ParamName.PATH_PARAMS: dict(path_params)}
filters = params.get(ParamName.FILTERS) or {}
if QueryParams.FILTER not in url_params[ParamName.QUERY_PARAMS] and 'name' in filters:
# most endpoints only support filtering by name, so remaining `filters` are applied on returned objects
url_params[ParamName.QUERY_PARAMS][QueryParams.FILTER] = 'name:%s' % filters['name']
item_generator = iterate_over_pageable_resource(
partial(self.send_general_request, operation_name=operation_name), url_params
)
return (i for i in item_generator if match_filters(filters, i))
def add_object(self, operation_name, params):
def is_duplicate_name_error(err):
return err.code == UNPROCESSABLE_ENTITY_STATUS and DUPLICATE_NAME_ERROR_MESSAGE in str(err)
try:
return self.send_general_request(operation_name, params)
except FtdServerError as e:
if is_duplicate_name_error(e):
return self._check_equality_with_existing_object(operation_name, params, e)
else:
raise e
def _check_equality_with_existing_object(self, operation_name, params, e):
"""
Looks for an existing | |
#!/usr/bin/python3
#import threading
from time import sleep
#import urllib.request
import subprocess
import re
import sys
import os
import cgi
import datetime
#from pushover import Client
#client = Client("ucGDF9dXuEPgUmNFWoGvGxKj9KVEgx", api_token="<KEY>")
# NEED BETTER LOGGING
topPoints = {}
magdic = {}
def log(logFile, msg):
ts = datetime.datetime.now().strftime('%d-%m-%y %H:%M:%S')
logFile.write('{}~# {}\n'.format(ts, msg))
def setsize(size, points, show, season, episode, tpe, logFile):
if tpe == 'film':
p1min = 699
p1max = 800
p2min = 801
p2max = 1000
p3min = 1001
p3max = 1200
p4min = 1201
p4max = 1400
p5min = 1401
p5max = 2000
pmin = 2001
pmax = 5000
elif tpe == 'season':
if season == 'complete':
p1min = 400
p1max = 50000
p2min = 50001
p2max = 10000
p3min = 10001
p3max = 20000
p4min = 20001
p4max = 40000
p5min = 40001
p5max = 60000
pmin = 60001
pmax = 150000
if re.findall(r'season \d{1,2}', season):
if episode == 'complete':
p1min = 400
p1max = 1000
p2min = 1001
p2max = 2000
p3min = 2001
p3max = 3000
p4min = 3001
p4max = 4000
p5min = 4001
p5max = 5000
pmin = 5001
pmax = 10000
if re.findall(r'S\d{1,2}', season):
if episode == 'complete':
p1min = 400
p1max = 1000
p2min = 1001
p2max = 2000
p3min = 2001
p3max = 3000
p4min = 3001
p4max = 4000
p5min = 4001
p5max = 5000
pmin = 5001
pmax = 10000
elif re.findall(r'E\d{1,2}', episode):
p1min = 80
p1max = 100
p2min = 101
p2max = 140
p3min = 141
p3max = 180
p4min = 181
p4max = 220
p5min = 221
p5max = 500
pmin = 501
pmax = 1500
if size < p1max > p1min:
points = points + 1
elif size < p2max > p2min:
points = points + 2
elif size < p3max > p3min:
points = points + 3
elif size < p4max > p4min:
points = points + 4
elif size < p5max > p5min:
points = points + 5
elif size < pmax > pmin:
points = points + 3
warning = 'Warning, file size = {}mb for show {}'.format(size, show)
if size >= pmax:
points = points - 100
warning = 'Warning, maximum file size exceded, size = {}mb for show {}'.format(size, show)
return points
def parse_query(show, getseason, getepisode, getseason3, getepisode3, logFile):
log(logFile, 'Parsing query...')
if getseason == None: #if season chkbox has not been clicked
try:
season = int(getseason3) # check for a number in season txtbox
tpe = 'season'
log(logFile, 'Found season {}'.format(season))
except:
log(logFile, 'int error')
try:
if len(str(season)) == 1:
log(logFile, 'len season == 1 prepending a 0')
season = 'S0{}'.format(season)
else:
log(logFile, 'Season len == 2. OK')
season = 'S{}'.format(season)
except:
pass
elif getseason == 'sall': #if season chkbox is selected
log(logFile, 'Getting all seasons!')
season = 'complete'
episode = ''
tpe = 'season'
if getseason == None: #if both chkbox and txtbox are blank look for movie
if getseason3 == None:
log(logFile, 'Movie found?')
tpe = 'film'
season = 'Movie'
if getseason == 'sall': #if season all chkbox seleted all eps presumed so pass
pass
else:
if getepisode == None: #if eps chkbox has not been selected
try:
episode = int(getepisode3) #test for number in txtbox
tpe = 'season'
log(logFile, 'Found episode {}'.format(episode))
except:
pass # pass if not number in txtbox
try:
if len(str(episode)) == 1:
episode = 'E0{}'.format(episode)
log(logFile, 'Episode len == 1 prepending 0')
else:
episode = 'E{}'.format(episode)
log(logFile, 'Episode len == 2. OK ')
except:
pass
if getepisode == 'eall': #if eps chkbox selected
episode = 'complete'
season = 'season {}'.format(getseason3)
tpe = 'season'
log(logFile, 'Found episodes all. Getting all episodes from season {}'.format(season))
# if getepisode == None: # if nether chkbox or txt box used look for movie
# if getepisode3 == None:
# tpe = 'film'
# episode = 'Movie'
if tpe == 'season':
if season == 'complete':
query = '{} {}'.format(show, season)
else:
if episode == 'complete':
query = '{} {} {}'.format(show, season, episode)
else:
query = '{} {}{}'.format(show, season, episode)
elif tpe == 'film':
query = show
squery = query.replace(' ', '%20')
return query, squery, tpe, season, episode
def getlinks(query, tpe, show, season, episode, url, input_source, logFile):
mags = re.findall(r"magnet:\?.+\n?.+\n?.+\n?.+\n?right\">\d{1,5}</td>\n?.+right\">\d{1,5}</td>", str(url))
if len(mags) > 0:
for mag in mags:
points = 0
link = re.findall(r"magnet:\?\S+(?=\")", mag)[0]
seeds = int(re.findall(r"(?<=right\">)\d{1,5}(?=<\/td>\n.{1,100}\d{1,5}<\/td>)", mag)[0])
# seeds = int(re.findall(r"(?<=right\">)\d{1,5}(?=<\/td>\n.{1,100}<td align=\"right\">\d{1,5}<\/td>)", mag)[0])
name = re.findall(r"(?<=dn=).{5,105}(?=tr=)", mag)[0]
size = float(re.findall(r"(?<=Size )\d{1,4}\.?\d{1,2}?(?= )", mag)[0])
if "MiB" in mag:
pass
elif "GiB" in mag:
size = size * 1024
else:
size = 0
points = setsize(size, points, show, season, episode, tpe, logFile)
if seeds == 0:
points = points - points - 10
if seeds >= 1 <= 5:
points = points + 1
if seeds >= 6 <= 10:
points = points + 2
if seeds >= 11 <= 20:
points = points + 3
if seeds >= 20:
points = points + 5
if '720p' in name:
points = points + 3
quality = '720p'
elif '1080p' in name:
quality = '1080p'
points = points + 5
else:
quality = 'Unknown'
if any(word in name for word in ['WEB-DL', 'WEBDL', 'Web-DL', 'webdl', 'web-dl', 'Web-dl', 'Web-Dl', 'Web-Dl', 'WEBRip']):
source = 'web download'
points = points - 1
if any(word in name for word in ['HDRIP', 'HDRip', 'HD-RIP', 'HD-Rip', 'hdrip', 'hd-rip', 'HDTV', 'hdtv', 'blueray', 'BLUERAY', 'Blueray', 'BrRip', 'HD']):
source = 'HD Rip'
points = points + 3
if any(word in name for word in ['DVDRIP', 'DVD-RIP', 'DVDRip', 'dvdrip', 'dvd-rip', 'DVD-Rip']):
source = 'DVD Rip'
points = points + 2
if any(word in name for word in ['[ettv]', '[eztv]']):
points = points + 2
else:
source = 'Unknown'
procpoints(tpe, name, points, link, input_source, query, logFile)
procpoints('end', 'end', 0, 0, input_source, query, logFile, show=show, season=season, episode=episode)
else:
logFile.write('No magnet links found')
print('No magnet links found!')
def procpoints(tpe, name, points, magnet, input_source, query, logFile, **kwargs):
if len(name) >= 4:
topPoints[name] = points
magdic[name] = magnet
elif len(name) == 3:
# try:
maxPoints = max(topPoints.values())
top = list(topPoints.keys())[list(topPoints.values()).index(maxPoints)]
topMagnet = magdic[top]
# os.popen('transmission-remote -a \"{}\"'.format(topMagnet))
transAdd = os.system('transmission-remote localhost -a \"{}\"'.format(topMagnet))
if not transAdd == 0:
print('SOME FAILURE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! {}'.format(transAdd))
print(topMagnet)
sys.exit()
print('Successefully added to Transmission Daemon. ({})'.format(topMagnet))
log(logFile, '{} added to download queue'.format(top))
# client.send_message('{} added to download queue'.format(top), title='Torrent Added')
cron_tweak('delete', kwargs.get('show'), kwargs.get('season'), kwargs.get('episode'), logFile)
# except:
# log(logFile, "Failed to add {} to download queue".format(name))
# client.send_message("Failed to add {} to download queue".format(name), title="Error!")
if input_source == 'web':
print('<head><h1>Redirecting</h1><body bgcolor="#F0F8FF"><meta http-equiv="refresh" content="5;url=download.py" /></head>')
print('<html><body><p>Please wait you are being redirected...</p>')
print('{} has been added to download queue</body></html>'.format(query))
log(logFile, '{} has been added to download queue'.format(query))
#os.system("echo 00 06 {} {} \* root /mnt/data/homes/scott/Backups/Pi2/pi/scripts/tvdb/monty.py download \\\"{}\\\" {} {} >> /etc/crontab".format(day+1, month, show, season, episode))
class cron_tweak:
def __init__(self, func, show, season, episode, logFile):
log(logFile, 'Cron_Tweak __init__')
exists = False
check_for_cron = open('/etc/crontab', 'r')
for line in check_for_cron.readlines():
# if '00 06 16 10 * root /mnt/data/homes/scott/Backups/Pi2/pi/scripts/tvdb/monty.py download "{}" {} {}'.format(datetime.datetime.today().strftime('%d'), datetime.datetime.today().strftime('%m'), show, season[1:], episode[1:]) in line:
if '"{}" {} {}'.format(show, season[1:], episode[1:]) in line:
exists = True
check_for_cron.close()
if exists and func == 'reshed':
self.reshed(show, season, episode, logFile)
elif exists:
log(logFile, 'Exists + func = '.format(func))
self.delete(show, season, episode, logFile)
else:
log(logFile, 'Cron does not exist func = {}'.format(func))
#input('Create cron for tomorrow?')
#if auto create cron flag is set then create cron
def reshed(self, show, season, episode, logFile):
os.rename('/etc/crontab', '/etc/crontab.BAK')
crontab_write = open('/etc/crontab', 'w')
crontab = open('/etc/crontab.BAK', 'r')
day = datetime.datetime.today().strftime('%d')
month = datetime.datetime.today().strftime('%m')
for tab in crontab.readlines():
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
tday = tomorrow.strftime('%d')
tmonth = tomorrow.strftime('%m')
if tap == '"{}" {} {}'.format(day, month, show, season, episode):
crontab.write('00 06 {} {} * root /mnt/data/homes/scott/Backups/Pi2/pi/scripts/tvdb/monty.py download "{}" {} {}'.format(tday, tmonth, show, season, episode))
else:
crontab.write(tab)
crontab.write()
def create(self, show, season, episode, logFile):
pass
def delete(self, show, season, episode, logFile):
os.rename('/etc/crontab', '/etc/crontab.BAK')
log(logFile, 'crontab backed up')
crontab_write = open('/etc/crontab', 'w')
log(logFile, 'crontab opened for writing')
crontab = open('/etc/crontab.BAK', 'r')
log(logFile, 'crontab.BAK opened for reading')
day = datetime.datetime.today().strftime('%d')
month = datetime.datetime.today().strftime('%m')
for tab in crontab.readlines():
tomorrow = | |
<reponame>AdnanKhan27/nicstestbed
"""
MIT License
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import re
from itertools import zip_longest
from collections import OrderedDict
class FileNotOpenException(Exception):
pass
class MissingHeaderException(Exception):
pass
class FieldNotFoundException(Exception):
pass
DEFAULT_FIELD_SEP = r'\s+'
def _DEFAULT_FIELD_FUNC(field_key, field):
return field
def _DEFAULT_FIELD_FILTER(field_key, field):
return True
def _DEFAULT_RECORD_FUNC(NR, record):
return record
def _DEFAULT_RECORD_FILTER(NR, record):
return True
class Record(object):
def __init__(self):
"""Initialises a Record object"""
self._field_dict = {}
self._field_list = []
self._key_list = []
self._iterator = None
def __getitem__(self, key):
"""Allows access to fields in the following forms:
- record[2] # column indices start from 0
- record[4:7:2] # same as above
- record['$4'] # same as record[3]
- record['mykey'] # columns are indexed based on header, if present
"""
try:
try:
return self._field_dict[key]
except (KeyError, TypeError): # nonexisting key or slice, respectively
return self._field_list[key]
except IndexError:
raise FieldNotFoundException('No field {} in record'.format(key))
def __setitem__(self, key, val):
"""should never be done manually, better create a new record than modifying an existing one"""
self._field_dict[key] = val
self._key_list.append(key)
self._field_list.append(val)
def add(self, val):
"""should never be done manually, better create a new record than modifying an existing one"""
self['${}'.format(len(self._field_list) + 1)] = val
def fields(self):
"""returns a generator of the record's fields"""
yield from self._field_list
def keys(self):
"""returns a generator of the record's keys"""
yield from self._key_list
def __iter__(self):
"""returns an iterator over the record's keys"""
self._iterator = iter(self._key_list)
return self
def __next__(self):
"""returns the next (key, field) pair. If a header was provided, the key corresponds to the header
otherwise it is of the form $1, $2, ..., $NF"""
try:
next_key = next(self._iterator)
return next_key, self._field_dict[next_key]
except StopIteration:
self._iterator = None
raise StopIteration
def __len__(self):
return len(self._field_list)
@property
def NF(self):
"""same as awk's NF variable"""
return len(self)
def __bool__(self):
return bool(len(self))
def __str__(self):
return 'Record({})'.format(', '.join(['{}: {}'.format(key, self._field_dict[key]) for key in self._key_list]))
class Reader(object):
# TODO: add field type
def __init__(self,
filename,
fs=DEFAULT_FIELD_SEP,
header=False,
max_lines=None,
field_filter=_DEFAULT_FIELD_FILTER,
record_filter=_DEFAULT_RECORD_FILTER):
"""Initialises a Reader
Arguments:
filename -- the name of the file to parse
Keyword arguments:
fs -- regex that separates the fields
header -- if set to True, the reader interprets the first line of the file as a header.
In this case every record is returned as a dictionary and every field in the header
is used as the key of the corresponding field in the following lines
max_lines -- the maximum number of lines to read
field_filter -- a function f(key, field) which is applied to the field.
If it returns a falsy value, the field is not included in the record.
default: lambda *args: True
record_filter -- a function f(NR, field) which is applied to the record.
If it returns a falsy value, the record is not returned.
default: lambda *args: True
"""
self.filename = filename
self.header = header
self.fs = fs
self.max_lines = max_lines
self.field_filter = field_filter
self.record_filter = record_filter
self._compiled_fs = re.compile(fs)
self._openfile = None
self._keys = None
@property
def keys(self):
"""returns the keys of the header if present, otherwise None"""
return self._keys
def __enter__(self):
self._openfile = open(self.filename)
self.lines = 0
if self.header:
first_line = next(self._openfile).rstrip()
self._keys = tuple(self._compiled_fs.split(first_line))
return self
def __exit__(self, *args):
self._openfile.close()
self.lines = 0
self._openfile = None
def __iter__(self):
return self
def _get_record(self, fields):
record = Record()
if self.header:
if len(fields) > len(self._keys):
zip_func = zip
else:
zip_func = zip_longest
for key, value in zip_func(self._keys, fields):
if self.field_filter(key, value):
record[key] = value
else:
# indexes start from 0
for key, value in enumerate(fields):
if self.field_filter(key, value):
record.add(value)
return record
def _get_next(self):
if self._openfile is None:
raise FileNotOpenException
if self.max_lines is not None and self.lines >= self.max_lines:
raise StopIteration
line = next(self._openfile).rstrip()
fields = self._compiled_fs.split(line)
record = self._get_record(fields)
self.lines += 1
if not self.record_filter(self.lines, record):
return None
return record
def __next__(self):
record = self._get_next()
while record is None:
# skip filtered out lines
record = self._get_next()
return record
class Parser(object):
def __init__(self,
filename,
fs=DEFAULT_FIELD_SEP,
header=False,
max_lines=None,
field_func=_DEFAULT_FIELD_FUNC,
record_func=_DEFAULT_RECORD_FUNC,
field_pre_filter=_DEFAULT_FIELD_FILTER,
record_pre_filter=_DEFAULT_RECORD_FILTER,
field_post_filter=_DEFAULT_FIELD_FILTER,
record_post_filter=_DEFAULT_RECORD_FILTER):
"""Initialise a Parser
Arguments:
filename -- the name of the file to parse
Keyword arguments:
fs -- a regex that separates the fields
header -- if set to True, the parser interprets the first line of the file as a header.
In this case every record is returned as a dictionary and every field in the header
is used as the key of the corresponding field in the following lines
max_lines -- the maximum number of lines to parse
field_func -- a function f(field_key, field) which is applied to every field, field_key is
the number of the field if there is no header, the corresponding header key otherwise.
default: a function that returns the field
record_func -- a function f(NR, NF, field) which is applied to every record, NR is the record number
NF is the total number of fields in the record.
default: a function that returns the record
field_pre_filter -- a function f(field_key, field) which is applied to the field before `field_func`.
If it returns a falsy value, the field is not returned.
default: lambda *args: True
record_pre_filter -- a function f(NR, field) which is applied to the record before `record_func`.
If it returns a falsy value, the record is not returned
default: lambda *args: True
field_post_filter -- a function f(field_key, field) which is applied to the field after `field_func`.
If it returns a falsy value, the field is not returned.
default: lambda *args: True
record_post_filter -- a function f(NR, field) which is applied to the record after `record_func`.
If it returns a falsy value, the record is not returned
default: lambda *args: True
"""
self.filename = filename
self.header = header
self.fs = fs
self.max_lines = max_lines
self.field_func = field_func
self.record_func = record_func
self.field_pre_filter = field_pre_filter
self.record_pre_filter = record_pre_filter
self.field_post_filter = field_post_filter
self.record_post_filter = record_post_filter
def _parse_fields(self, record):
new_record = Record()
for key, field in record:
new_field = self.field_func(key, field)
if self.field_post_filter(key, new_field):
new_record[key] = new_field
return new_record
def parse(self):
"""Parse the file provided at initialisation time returns a generator of `Record`s.
The records returned and the fields in them are the result of the application of
record_func and field_func respectively.
Only records respecting the pre and post filters are present, same applies for the fields in each record
"""
reader_args = (self.filename,
self.fs,
self.header,
self.max_lines,
self.field_pre_filter,
self.record_pre_filter)
with Reader(*reader_args) as reader:
for nr, record in enumerate(reader, 1): # line numbers start from 1
record = self.record_func(nr, self._parse_fields(record))
if self.record_post_filter(nr, record):
yield record
class Column(object):
def __init__(self,
filename,
fs=DEFAULT_FIELD_SEP,
header=False,
max_lines=None,
field_func=lambda x: x,
column_func=lambda x: x):
"""
Initialise a Column object.
Arguments:
filename -- the name of the file to parse
Keyword arguments:
fs -- a regex that separates the fields
header -- if set to True, the parser interprets the first line of the file as a header.
In this case the columns can be indexed as the key specified in the header and the first
element of the column is the header
max_lines -- the maximum number of lines to parse
field_func -- a function f(field) which is applied to every field. Default: a function that returns the | |
to which connections will be grown)
:param num_potential: list of counts of potential synapses for every segment
:return:
"""
for segment in learning_segments:
connections.adaptSegment(segment, active_cells, permanence_increment, permanence_decrement,
self.prune_zero_synapses, segmentThreshold)
if sample_size == -1:
max_new = len(winner_cells)
else:
max_new = sample_size - num_potential[segment]
if max_synapses_per_segment != -1:
synapse_counts = connections.numSynapses(segment)
num_synapses_to_reach_max = max_synapses_per_segment - synapse_counts
max_new = min(max_new, num_synapses_to_reach_max)
if max_new > 0:
connections.growSynapses(segment, winner_cells, initial_permanence, self.rng, max_new)
def _learn_on_new_segments(self, connections: Connections, new_segment_cells, growth_candidates, sample_size,
max_synapses_per_segment,
initial_permanence, max_segments_per_cell):
"""
Grows new segments and learn on them
:param connections:
:param new_segment_cells: cells' id to grow new segments on
:param growth_candidates: cells' id to grow synapses to
:return:
"""
num_new_synapses = len(growth_candidates)
if sample_size != -1:
num_new_synapses = min(num_new_synapses, sample_size)
if max_synapses_per_segment != -1:
num_new_synapses = min(num_new_synapses, max_synapses_per_segment)
for cell in new_segment_cells:
new_segment = connections.createSegment(cell, max_segments_per_cell)
connections.growSynapses(new_segment, growth_candidates, initial_permanence, self.rng,
maxNew=num_new_synapses)
def _calculate_basal_learning(self, bursting_columns, correct_predicted_cells):
"""
Calculates which segments to train and where to grow new segments
:param bursting_columns: numpy array of columns' id
:param correct_predicted_cells: numpy array of cells' id
:return:
"""
# Correctly predicted columns
# choose active segments for correctly predicted cells
learning_active_basal_segments = self.basal_connections.filterSegmentsByCell(self.active_segments_basal,
correct_predicted_cells)
# all cells with matching segments
cells_for_matching_basal = self.basal_connections.mapSegmentsToCells(self.matching_segments_basal)
matching_cells = np.unique(cells_for_matching_basal)
matching_cells_in_bursting_columns, bursting_columns_with_no_match = setCompare(matching_cells,
bursting_columns,
aKey=self._columns_for_cells(
matching_cells),
rightMinusLeft=True)
# choose the best segment per cell
if matching_cells_in_bursting_columns.size > 0:
(learning_matching_basal_segments,
cells_to_grow_apical_segments
) = self._choose_best_segment_per_column(
matching_cells_in_bursting_columns)
else:
learning_matching_basal_segments = np.empty(0, dtype=np.int32)
cells_to_grow_apical_segments = np.empty(0, dtype=np.int32)
# cells on which new apical and basal segments will be grown
if bursting_columns_with_no_match.size > 0:
cells_to_grow_apical_and_basal_segments = self._get_cells_with_fewest_segments(self.basal_connections,
self.apical_connections,
bursting_columns_with_no_match)
else:
cells_to_grow_apical_and_basal_segments = np.empty(0, dtype=UINT_DTYPE)
winner_cells = np.concatenate(
(correct_predicted_cells,
self.basal_connections.mapSegmentsToCells(learning_matching_basal_segments),
cells_to_grow_apical_and_basal_segments)
)
# Incorrectly predicted columns
incorrect_matching_basal_mask = np.isin(self._columns_for_cells(cells_for_matching_basal),
self.active_columns.sparse, invert=True)
basal_segments_to_punish = self.matching_segments_basal[incorrect_matching_basal_mask]
return (learning_active_basal_segments.astype('uint32'),
learning_matching_basal_segments.astype('uint32'),
basal_segments_to_punish.astype('uint32'),
cells_to_grow_apical_and_basal_segments.astype('uint32'),
cells_to_grow_apical_segments.astype('uint32'),
winner_cells.astype('uint32'))
def _calculate_apical_learning(self, candidate_cells):
learning_matching_apical_segments, apical_segments_to_punish, cells_to_grow_apical_segments = setCompare(
self.matching_segments_apical,
candidate_cells,
aKey=self.apical_connections.mapSegmentsToCells(
self.matching_segments_apical),
leftMinusRight=True,
rightMinusLeft=True
)
learning_matching_apical_segments = self._choose_best_segment_per_cell(self.apical_connections,
candidate_cells,
learning_matching_apical_segments,
self.num_potential_apical)
return learning_matching_apical_segments, cells_to_grow_apical_segments, apical_segments_to_punish
def _choose_best_segment_per_column(self, cells):
"""
Chooses best matching segment per column among the cells, using apical tie breaking.
:param cells: numpy array of cells' id
:return:
"""
candidate_basal_segments = self.basal_connections.filterSegmentsByCell(self.matching_segments_basal, cells)
tiebreaker = np.empty_like(candidate_basal_segments)
self.rng.initializeReal64Array(tiebreaker)
one_per_column_filter = argmaxMulti(
self.num_potential_basal[candidate_basal_segments] + tiebreaker * 0.1,
groupKeys=self._columns_for_cells(
self.basal_connections.mapSegmentsToCells(candidate_basal_segments)))
learning_basal_segments = candidate_basal_segments[one_per_column_filter]
cells_for_learning_basal_segments = self.basal_connections.mapSegmentsToCells(learning_basal_segments)
return learning_basal_segments.astype(UINT_DTYPE), cells_for_learning_basal_segments.astype(UINT_DTYPE)
@staticmethod
def _choose_best_segment_per_cell(connections, cells, segments, num_potential):
"""
Calculates best matching segment per cell.
:param connections:
:param cells: numpy array of cells' id
:param segments: numpy array of segments' id
:param num_potential:
:return:
"""
candidate_segments = connections.filterSegmentsByCell(segments, cells)
# Narrow it down to one pair per cell.
if candidate_segments.size > 0:
one_per_cell_filter = argmaxMulti(num_potential[candidate_segments],
groupKeys=connections.mapSegmentsToCells(candidate_segments))
learning_segments = candidate_segments[one_per_cell_filter]
else:
learning_segments = np.empty(0)
return learning_segments.astype('uint32')
def _get_cells_with_fewest_segments(self, basal_connections, apical_connections, columns):
"""
Calculates cells with fewest segments per column.
:param basal_connections:
:param apical_connections:
:param columns:
:return:
"""
candidate_cells = getAllCellsInColumns(columns, self.cells_per_column) + self.local_range[0]
# Arrange the segment counts into one row per minicolumn.
# count apical and basal segments per cell
segment_counts = np.reshape(
basal_connections.getSegmentCounts(candidate_cells) + apical_connections.getSegmentCounts(candidate_cells),
newshape=(len(columns), self.cells_per_column))
# Filter to just the cells that are tied for fewest in their minicolumn.
tiebreaker = np.empty_like(segment_counts, dtype='float64')
self.rng.initializeReal64Array(tiebreaker)
segment_counts = segment_counts + tiebreaker * 0.1
min_segment_counts = np.amin(segment_counts, axis=1, keepdims=True)
candidate_cells = candidate_cells[np.flatnonzero(segment_counts == min_segment_counts)]
return candidate_cells.astype('uint32')
@staticmethod
def _activate_dendrites(connections, presynaptic_cells, activation_threshold, learning_threshold, learn):
"""
Calculates active and matching segments and predictive cells.
:param connections:
:param presynaptic_cells:
:param activation_threshold:
:param learning_threshold:
:return:
"""
# Active
num_connected, num_potential = connections.computeActivityFull(presynaptic_cells,
learn) # The role of "learn" parameter isn't clear
active_segments = np.flatnonzero(num_connected >= activation_threshold)
predictive_cells = connections.mapSegmentsToCells(active_segments) # with duplicates
# Matching
matching_segments = np.flatnonzero(num_potential >= learning_threshold)
return active_segments, matching_segments, predictive_cells, num_potential
def _columns_for_cells(self, cells):
"""
Calculates column numbers for basal cells
:param cells: numpy array of cells id
:return: numpy array of columns id for every cell
"""
if np.any(cells < self.local_range[0]) or np.any(cells >= self.local_range[1]):
raise ValueError('cells are not in bounds')
local_cells = cells - self.local_range[0]
columns = local_cells // self.cells_per_column
return columns.astype('int32')
def _filter_by_columns(self, cells, columns, invert=False):
"""
Filters cells by specified columns
:param cells: numpy array of cells id
:param columns: numpy array of columns id
:param invert: if true then return cells that not in columns
:return: numpy array of cells id
"""
columns_for_cells = self._columns_for_cells(cells)
return cells[np.in1d(columns_for_cells, columns, invert=invert)]
class ApicalBasalFeedbackTM:
def __init__(self,
apical_columns, apical_cells_per_column,
basal_columns, basal_cells_per_column,
feedback_columns,
activation_threshold,
learning_threshold,
activation_apical_threshold,
learning_apical_threshold,
activation_inhib_basal_threshold,
learning_inhib_basal_threshold,
activation_inhib_feedback_threshold,
learning_inhib_feedback_threshold,
learning_exec_threshold,
activation_exec_threshold,
connected_threshold=0.5,
seed=None,
permanence_increment=0.1,
permanence_decrement=0.01,
initial_permanence=0.4,
predicted_segment_decrement=0.001,
sample_size=-1,
sample_apical_size=-1,
sample_inhib_basal_size=-1,
sample_inhib_feedback_size=-1,
sample_exec_size=-1,
max_synapses_per_segment=-1,
max_apical_synapses_per_segment=-1,
max_inhib_synapses_per_segment=-1,
max_exec_synapses_per_segment=-1,
max_segments_per_cell=255,
anomaly_window=1000,
confidence_window=1000,
noise_tolerance=0.0,
connected_threshold_apical=0.5,
permanence_increment_apical=0.1,
permanence_decrement_apical=0.01,
predicted_segment_decrement_apical=0.001,
initial_permanence_apical=0.4,
predicted_segment_decrement_exec=0.001,
initial_permanence_exec=0.4,
permanence_decrement_exec=0.01,
permanence_increment_exec=0.1,
connected_threshold_exec=0.5,
predicted_segment_decrement_inhib=0.001,
initial_permanence_inhib=0.4,
permanence_decrement_inhib=0.01,
permanence_increment_inhib=0.1,
connected_threshold_inhib=0.5,
enable_pruning_basal=True,
enable_pruning_apical=True,
enable_pruning_exec=True,
enable_pruning_inhib=True,
pruning_period_basal=1000,
pruning_period_apical=1000,
pruning_period_exec=1000,
pruning_period_inhib=1000,
prune_zero_synapses=True,
max_segments_per_cell_apical=255,
max_segments_per_cell_exec=255,
max_segments_per_cell_inhib=255,
timeseries=False):
self.step = 0
self.apical_columns = apical_columns
self.apical_cells_per_column = apical_cells_per_column
self.apical_total_cells = apical_columns * apical_cells_per_column
self.basal_columns = basal_columns
self.basal_cells_per_column = basal_cells_per_column
self.basal_total_cells = basal_columns * basal_cells_per_column
self.feedback_columns = feedback_columns
self.activation_threshold = activation_threshold
self.learning_threshold = learning_threshold
self.activation_inhib_basal_threshold = activation_inhib_basal_threshold
self.learning_inhib_basal_threshold = learning_inhib_basal_threshold
self.activation_inhib_feedback_threshold = activation_inhib_feedback_threshold
self.learning_inhib_feedback_threshold = learning_inhib_feedback_threshold
self.activation_apical_threshold = activation_apical_threshold
self.learning_apical_threshold = learning_apical_threshold
self.activation_exec_threshold = activation_exec_threshold
self.learning_exec_threshold = learning_exec_threshold
self.connected_threshold = connected_threshold
self.permanence_increment = permanence_increment
self.permanence_increment_init = permanence_increment
self.permanence_decrement = permanence_decrement
self.permanence_decrement_init = permanence_decrement
self.initial_permanence = initial_permanence
self.predicted_segment_decrement = predicted_segment_decrement
self.predicted_segment_decrement_init = predicted_segment_decrement
self.connected_threshold_apical = connected_threshold_apical
self.permanence_increment_apical = permanence_increment_apical
self.permanence_increment_apical_init = permanence_increment_apical
self.permanence_decrement_apical = permanence_decrement_apical
self.permanence_decrement_apical_init = permanence_decrement_apical
self.initial_permanence_apical = initial_permanence_apical
self.predicted_segment_decrement_apical = predicted_segment_decrement_apical
self.predicted_segment_decrement_apical_init = predicted_segment_decrement_apical
self.connected_threshold_inhib = connected_threshold_inhib
self.permanence_increment_inhib = permanence_increment_inhib
self.permanence_increment_inhib_init = permanence_increment_inhib
self.permanence_decrement_inhib = permanence_decrement_inhib
self.permanence_decrement_inhib_init = permanence_decrement_inhib
self.initial_permanence_inhib = initial_permanence_inhib
self.predicted_segment_decrement_inhib = predicted_segment_decrement_inhib
self.predicted_segment_decrement_inhib_init = predicted_segment_decrement_inhib
self.connected_threshold_exec = connected_threshold_exec
self.permanence_increment_exec = permanence_increment_exec
self.permanence_increment_exec_init = permanence_increment_exec
self.permanence_decrement_exec = permanence_decrement_exec
self.permanence_decrement_exec_init = permanence_decrement_exec
self.initial_permanence_exec = initial_permanence_exec
self.predicted_segment_decrement_exec = predicted_segment_decrement_exec
self.predicted_segment_decrement_exec_init = predicted_segment_decrement_exec
self.sample_size = sample_size
self.sample_inhib_basal_size = sample_inhib_basal_size
self.sample_inhib_feedback_size = sample_inhib_feedback_size
self.sample_exec_size = sample_exec_size
self.sample_apical_size = sample_apical_size
self.max_synapses_per_segment = max_synapses_per_segment
self.max_inhib_synapses_per_segment = max_inhib_synapses_per_segment
self.max_exec_synapses_per_segment = max_exec_synapses_per_segment
self.max_apical_synapses_per_segment = max_apical_synapses_per_segment
self.max_segments_per_cell = max_segments_per_cell
self.max_segments_per_cell_apical = max_segments_per_cell_apical
self.max_segments_per_cell_exec = max_segments_per_cell_exec
self.max_segments_per_cell_inhib = max_segments_per_cell_inhib
self.total_cells = (self.apical_total_cells +
self.basal_total_cells +
self.feedback_columns)
self.apical_range = (0, self.apical_total_cells)
self.basal_range = (self.apical_range[1], self.apical_range[1] + self.basal_total_cells)
self.feedback_range = (self.basal_range[1], self.basal_range[1] + self.feedback_columns)
self.timeseries = timeseries
self.apical_connections = Connections(numCells=self.total_cells,
connectedThreshold=self.connected_threshold_apical,
timeseries=self.timeseries)
self.basal_connections = Connections(numCells=self.total_cells,
connectedThreshold=self.connected_threshold,
timeseries=self.timeseries)
self.exec_feedback_connections = Connections(numCells=self.total_cells,
connectedThreshold=self.connected_threshold_exec,
timeseries=self.timeseries)
self.inhib_connections = Connections(numCells=self.total_cells,
connectedThreshold=self.connected_threshold_inhib,
timeseries=self.timeseries)
self.active_basal_cells = SDR(self.total_cells)
self.winner_basal_cells = SDR(self.total_cells)
self.active_basal_segments = np.empty(0)
self.matching_basal_segments = np.empty(0)
self.basal_predictive_cells = np.empty(0)
self.num_basal_potential = np.empty(0)
self.active_apical_cells = SDR(self.total_cells)
self.winner_apical_cells = SDR(self.total_cells)
self.active_apical_segments = np.empty(0)
self.matching_apical_segments = np.empty(0)
self.apical_predictive_cells = np.empty(0)
self.num_apical_potential = np.empty(0)
self.active_inhib_basal_segments = np.empty(0)
self.matching_inhib_basal_segments = np.empty(0)
self.inhibited_basal_cells = np.empty(0)
self.num_inhib_basal_potential = np.empty(0)
self.active_inhib_feedback_segments = np.empty(0)
self.matching_inhib_feedback_segments = np.empty(0)
self.inhibited_feedback_cells = np.empty(0)
self.num_inhib_feedback_potential = np.empty(0)
self.inhib_presynaptic_cells = SDR(self.total_cells)
self.inhib_receptive_field = SDR(self.total_cells)
self.active_inhib_segments = np.empty(0)
self.matching_inhib_segments = np.empty(0)
self.inhibited_cells = np.empty(0)
self.active_exec_segments = np.empty(0)
self.matching_exec_segments = np.empty(0)
self.exec_predictive_cells = np.empty(0)
self.num_exec_potential = np.empty(0)
self.active_columns = SDR(self.basal_columns)
self.predicted_cells = SDR(self.total_cells)
self.predicted_columns = SDR(self.basal_columns)
self.active_feedback_columns = SDR(self.total_cells)
self.anomaly_window = anomaly_window
self.confidence_window = confidence_window
self.anomaly = [0 for _ in range(self.anomaly_window)]
self.confidence = [0 for _ in range(self.confidence_window)]
self.anomaly_threshold = 0
self.confidence_threshold = 0
self.noise_tolerance = noise_tolerance
self.enable_pruning_basal = enable_pruning_basal
self.enable_pruning_apical = enable_pruning_apical
self.enable_pruning_exec = enable_pruning_exec
self.enable_pruning_inhib = enable_pruning_inhib
self.pruning_period_basal = pruning_period_basal
self.pruning_period_apical = pruning_period_apical
self.pruning_period_exec = pruning_period_exec
self.pruning_period_inhib = pruning_period_inhib
self.segments_activity_basal = np.empty(0)
self.segments_activity_apical = np.empty(0)
self.segments_activity_exec = np.empty(0)
self.segments_activity_inhib = np.empty(0)
self.prune_zero_synapses = prune_zero_synapses
if seed:
self.rng = Random(seed)
else:
self.rng = Random()
def reset(self):
self.active_basal_cells = SDR(self.total_cells)
self.winner_basal_cells = SDR(self.total_cells)
self.active_basal_segments = np.empty(0)
self.matching_basal_segments = np.empty(0)
self.basal_predictive_cells = np.empty(0)
self.num_basal_potential = np.empty(0)
self.active_apical_cells = SDR(self.total_cells)
self.winner_apical_cells = SDR(self.total_cells)
self.active_apical_segments = np.empty(0)
self.matching_apical_segments = np.empty(0)
self.apical_predictive_cells = np.empty(0)
self.num_apical_potential = np.empty(0)
self.active_inhib_basal_segments = np.empty(0)
self.matching_inhib_basal_segments = np.empty(0)
self.inhibited_basal_cells = np.empty(0)
self.num_inhib_basal_potential = np.empty(0)
self.active_inhib_feedback_segments = np.empty(0)
self.matching_inhib_feedback_segments = np.empty(0)
self.inhibited_feedback_cells = np.empty(0)
self.num_inhib_feedback_potential = np.empty(0)
self.inhib_presynaptic_cells = SDR(self.total_cells)
self.inhib_receptive_field = SDR(self.total_cells)
self.active_inhib_segments = np.empty(0)
self.matching_inhib_segments = np.empty(0)
self.inhibited_cells = np.empty(0)
self.active_exec_segments = np.empty(0)
self.matching_exec_segments = np.empty(0)
self.exec_predictive_cells = np.empty(0)
self.num_exec_potential = np.empty(0)
self.active_columns = SDR(self.basal_columns)
self.predicted_cells = SDR(self.total_cells)
self.predicted_columns = SDR(self.basal_columns)
self.active_feedback_columns = SDR(self.total_cells)
# input
def set_active_columns(self, columns_id):
self.active_columns.sparse = np.array(columns_id)
def set_active_feedback_columns(self, columns_id):
self.active_feedback_columns.sparse = np.array(columns_id) + self.feedback_range[0]
| |
<reponame>asch99/QDarkStyleSheet
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dw_buttons.ui',
# licensing of 'dw_buttons.ui' applies.
#
# Created: Fri May 31 23:17:03 2019
# by: pyside2-uic running on PySide2 5.12.3
#
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_DockWidget(object):
def setupUi(self, DockWidget):
DockWidget.setObjectName("DockWidget")
DockWidget.resize(562, 497)
self.dockWidgetContents = QtWidgets.QWidget()
self.dockWidgetContents.setObjectName("dockWidgetContents")
self.gridLayout = QtWidgets.QGridLayout(self.dockWidgetContents)
self.gridLayout.setObjectName("gridLayout")
self.pushButtonChecked = QtWidgets.QPushButton(self.dockWidgetContents)
self.pushButtonChecked.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.pushButtonChecked.setCheckable(True)
self.pushButtonChecked.setChecked(True)
self.pushButtonChecked.setObjectName("pushButtonChecked")
self.gridLayout.addWidget(self.pushButtonChecked, 2, 1, 1, 6)
self.label_2 = QtWidgets.QLabel(self.dockWidgetContents)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 6, 0, 1, 1)
self.toolButtonChecked = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonChecked.setCheckable(True)
self.toolButtonChecked.setChecked(True)
self.toolButtonChecked.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.toolButtonChecked.setObjectName("toolButtonChecked")
self.gridLayout.addWidget(self.toolButtonChecked, 6, 1, 1, 4)
self.toolButtonCheckedDis = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonCheckedDis.setEnabled(False)
self.toolButtonCheckedDis.setCheckable(True)
self.toolButtonCheckedDis.setChecked(True)
self.toolButtonCheckedDis.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.toolButtonCheckedDis.setObjectName("toolButtonCheckedDis")
self.gridLayout.addWidget(self.toolButtonCheckedDis, 6, 7, 1, 4)
self.label_3 = QtWidgets.QLabel(self.dockWidgetContents)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 7, 0, 1, 1)
self.toolButtonArrowDown = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonArrowDown.setArrowType(QtCore.Qt.DownArrow)
self.toolButtonArrowDown.setObjectName("toolButtonArrowDown")
self.gridLayout.addWidget(self.toolButtonArrowDown, 7, 1, 1, 1)
self.toolButtonArrowUp = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonArrowUp.setArrowType(QtCore.Qt.UpArrow)
self.toolButtonArrowUp.setObjectName("toolButtonArrowUp")
self.gridLayout.addWidget(self.toolButtonArrowUp, 7, 2, 1, 1)
self.toolButtonArrowRight = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonArrowRight.setArrowType(QtCore.Qt.RightArrow)
self.toolButtonArrowRight.setObjectName("toolButtonArrowRight")
self.gridLayout.addWidget(self.toolButtonArrowRight, 7, 3, 1, 1)
self.toolButtonArrowLeft = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonArrowLeft.setArrowType(QtCore.Qt.LeftArrow)
self.toolButtonArrowLeft.setObjectName("toolButtonArrowLeft")
self.gridLayout.addWidget(self.toolButtonArrowLeft, 7, 4, 1, 2)
self.toolButtonArrowDownDis = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonArrowDownDis.setEnabled(False)
self.toolButtonArrowDownDis.setArrowType(QtCore.Qt.DownArrow)
self.toolButtonArrowDownDis.setObjectName("toolButtonArrowDownDis")
self.gridLayout.addWidget(self.toolButtonArrowDownDis, 7, 7, 1, 1)
self.toolButtonArrowUpDis = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonArrowUpDis.setEnabled(False)
self.toolButtonArrowUpDis.setArrowType(QtCore.Qt.UpArrow)
self.toolButtonArrowUpDis.setObjectName("toolButtonArrowUpDis")
self.gridLayout.addWidget(self.toolButtonArrowUpDis, 7, 8, 1, 1)
self.toolButtonArrowRightDis = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonArrowRightDis.setEnabled(False)
self.toolButtonArrowRightDis.setArrowType(QtCore.Qt.RightArrow)
self.toolButtonArrowRightDis.setObjectName("toolButtonArrowRightDis")
self.gridLayout.addWidget(self.toolButtonArrowRightDis, 7, 9, 1, 1)
self.toolButtonArrowLeftDis = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonArrowLeftDis.setEnabled(False)
self.toolButtonArrowLeftDis.setArrowType(QtCore.Qt.LeftArrow)
self.toolButtonArrowLeftDis.setObjectName("toolButtonArrowLeftDis")
self.gridLayout.addWidget(self.toolButtonArrowLeftDis, 7, 10, 1, 2)
self.radioButtonChecked = QtWidgets.QRadioButton(self.dockWidgetContents)
self.radioButtonChecked.setChecked(True)
self.radioButtonChecked.setAutoExclusive(False)
self.radioButtonChecked.setObjectName("radioButtonChecked")
self.gridLayout.addWidget(self.radioButtonChecked, 8, 1, 1, 3)
self.radioButtonCheckedDis = QtWidgets.QRadioButton(self.dockWidgetContents)
self.radioButtonCheckedDis.setEnabled(False)
self.radioButtonCheckedDis.setChecked(True)
self.radioButtonCheckedDis.setAutoExclusive(False)
self.radioButtonCheckedDis.setObjectName("radioButtonCheckedDis")
self.gridLayout.addWidget(self.radioButtonCheckedDis, 8, 7, 1, 3)
self.label_29 = QtWidgets.QLabel(self.dockWidgetContents)
self.label_29.setMinimumSize(QtCore.QSize(0, 0))
self.label_29.setMaximumSize(QtCore.QSize(16777215, 16777215))
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_29.setFont(font)
self.label_29.setObjectName("label_29")
self.gridLayout.addWidget(self.label_29, 9, 0, 1, 1)
self.radioButtonUnchecked = QtWidgets.QRadioButton(self.dockWidgetContents)
self.radioButtonUnchecked.setMinimumSize(QtCore.QSize(0, 0))
self.radioButtonUnchecked.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.radioButtonUnchecked.setAutoExclusive(False)
self.radioButtonUnchecked.setObjectName("radioButtonUnchecked")
self.gridLayout.addWidget(self.radioButtonUnchecked, 9, 1, 1, 4)
self.radioButtonUncheckedDis = QtWidgets.QRadioButton(self.dockWidgetContents)
self.radioButtonUncheckedDis.setEnabled(False)
self.radioButtonUncheckedDis.setMinimumSize(QtCore.QSize(0, 0))
self.radioButtonUncheckedDis.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.radioButtonUncheckedDis.setChecked(False)
self.radioButtonUncheckedDis.setAutoExclusive(False)
self.radioButtonUncheckedDis.setObjectName("radioButtonUncheckedDis")
self.gridLayout.addWidget(self.radioButtonUncheckedDis, 9, 7, 1, 4)
self.label_53 = QtWidgets.QLabel(self.dockWidgetContents)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_53.setFont(font)
self.label_53.setObjectName("label_53")
self.gridLayout.addWidget(self.label_53, 10, 0, 1, 1)
self.checkBoxChecked = QtWidgets.QCheckBox(self.dockWidgetContents)
self.checkBoxChecked.setChecked(True)
self.checkBoxChecked.setObjectName("checkBoxChecked")
self.gridLayout.addWidget(self.checkBoxChecked, 10, 1, 1, 3)
self.checkBoxCheckedDis = QtWidgets.QCheckBox(self.dockWidgetContents)
self.checkBoxCheckedDis.setEnabled(False)
self.checkBoxCheckedDis.setChecked(True)
self.checkBoxCheckedDis.setObjectName("checkBoxCheckedDis")
self.gridLayout.addWidget(self.checkBoxCheckedDis, 10, 7, 1, 3)
self.label_30 = QtWidgets.QLabel(self.dockWidgetContents)
self.label_30.setMinimumSize(QtCore.QSize(0, 0))
self.label_30.setMaximumSize(QtCore.QSize(16777215, 16777215))
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_30.setFont(font)
self.label_30.setObjectName("label_30")
self.gridLayout.addWidget(self.label_30, 11, 0, 1, 1)
self.checkBoxEnabled = QtWidgets.QCheckBox(self.dockWidgetContents)
self.checkBoxEnabled.setMinimumSize(QtCore.QSize(0, 0))
self.checkBoxEnabled.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.checkBoxEnabled.setTristate(False)
self.checkBoxEnabled.setObjectName("checkBoxEnabled")
self.gridLayout.addWidget(self.checkBoxEnabled, 11, 1, 1, 4)
self.checkBoxUncheckedDis = QtWidgets.QCheckBox(self.dockWidgetContents)
self.checkBoxUncheckedDis.setEnabled(False)
self.checkBoxUncheckedDis.setMinimumSize(QtCore.QSize(0, 0))
self.checkBoxUncheckedDis.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.checkBoxUncheckedDis.setChecked(False)
self.checkBoxUncheckedDis.setObjectName("checkBoxUncheckedDis")
self.gridLayout.addWidget(self.checkBoxUncheckedDis, 11, 7, 1, 4)
self.label = QtWidgets.QLabel(self.dockWidgetContents)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 12, 0, 1, 1)
self.checkBoxTristate = QtWidgets.QCheckBox(self.dockWidgetContents)
self.checkBoxTristate.setChecked(False)
self.checkBoxTristate.setTristate(True)
self.checkBoxTristate.setObjectName("checkBoxTristate")
self.gridLayout.addWidget(self.checkBoxTristate, 12, 1, 1, 3)
self.checkBoxTristateDis = QtWidgets.QCheckBox(self.dockWidgetContents)
self.checkBoxTristateDis.setEnabled(False)
self.checkBoxTristateDis.setChecked(False)
self.checkBoxTristateDis.setTristate(True)
self.checkBoxTristateDis.setObjectName("checkBoxTristateDis")
self.gridLayout.addWidget(self.checkBoxTristateDis, 12, 7, 1, 3)
self.label_31 = QtWidgets.QLabel(self.dockWidgetContents)
self.label_31.setMinimumSize(QtCore.QSize(0, 0))
self.label_31.setMaximumSize(QtCore.QSize(16777215, 16777215))
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_31.setFont(font)
self.label_31.setObjectName("label_31")
self.gridLayout.addWidget(self.label_31, 13, 0, 1, 1)
self.commandLinkButton = QtWidgets.QCommandLinkButton(self.dockWidgetContents)
self.commandLinkButton.setMinimumSize(QtCore.QSize(0, 0))
self.commandLinkButton.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.commandLinkButton.setObjectName("commandLinkButton")
self.gridLayout.addWidget(self.commandLinkButton, 13, 1, 1, 6)
self.commandLinkButtonDIs = QtWidgets.QCommandLinkButton(self.dockWidgetContents)
self.commandLinkButtonDIs.setEnabled(False)
self.commandLinkButtonDIs.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.commandLinkButtonDIs.setObjectName("commandLinkButtonDIs")
self.gridLayout.addWidget(self.commandLinkButtonDIs, 13, 7, 1, 6)
self.label_32 = QtWidgets.QLabel(self.dockWidgetContents)
self.label_32.setMinimumSize(QtCore.QSize(0, 0))
self.label_32.setMaximumSize(QtCore.QSize(16777215, 16777215))
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_32.setFont(font)
self.label_32.setObjectName("label_32")
self.gridLayout.addWidget(self.label_32, 14, 0, 1, 1)
self.buttonBox = QtWidgets.QDialogButtonBox(self.dockWidgetContents)
self.buttonBox.setMinimumSize(QtCore.QSize(0, 0))
self.buttonBox.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.gridLayout.addWidget(self.buttonBox, 14, 1, 1, 6)
self.buttonBoxDis = QtWidgets.QDialogButtonBox(self.dockWidgetContents)
self.buttonBoxDis.setEnabled(False)
self.buttonBoxDis.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBoxDis.setObjectName("buttonBoxDis")
self.gridLayout.addWidget(self.buttonBoxDis, 14, 7, 1, 6)
spacerItem = QtWidgets.QSpacerItem(20, 4, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.gridLayout.addItem(spacerItem, 15, 0, 1, 1)
self.label_36 = QtWidgets.QLabel(self.dockWidgetContents)
self.label_36.setAlignment(QtCore.Qt.AlignCenter)
self.label_36.setObjectName("label_36")
self.gridLayout.addWidget(self.label_36, 16, 0, 1, 1)
self.label_76 = QtWidgets.QLabel(self.dockWidgetContents)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_76.setFont(font)
self.label_76.setObjectName("label_76")
self.gridLayout.addWidget(self.label_76, 3, 0, 1, 1)
self.label_33 = QtWidgets.QLabel(self.dockWidgetContents)
self.label_33.setMinimumSize(QtCore.QSize(0, 0))
self.label_33.setMaximumSize(QtCore.QSize(16777215, 16777215))
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_33.setFont(font)
self.label_33.setObjectName("label_33")
self.gridLayout.addWidget(self.label_33, 4, 0, 1, 1)
self.toolButton = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButton.setMinimumSize(QtCore.QSize(0, 0))
self.toolButton.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.toolButton.setObjectName("toolButton")
self.gridLayout.addWidget(self.toolButton, 4, 1, 1, 2)
self.toolButtonDis = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonDis.setEnabled(False)
self.toolButtonDis.setMinimumSize(QtCore.QSize(0, 0))
self.toolButtonDis.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.toolButtonDis.setObjectName("toolButtonDis")
self.gridLayout.addWidget(self.toolButtonDis, 4, 7, 1, 2)
self.label_75 = QtWidgets.QLabel(self.dockWidgetContents)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_75.setFont(font)
self.label_75.setObjectName("label_75")
self.gridLayout.addWidget(self.label_75, 8, 0, 1, 1)
self.pushButton = QtWidgets.QPushButton(self.dockWidgetContents)
self.pushButton.setMinimumSize(QtCore.QSize(0, 0))
self.pushButton.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 1, 1, 1, 6)
self.pushButtonDis = QtWidgets.QPushButton(self.dockWidgetContents)
self.pushButtonDis.setEnabled(False)
self.pushButtonDis.setMinimumSize(QtCore.QSize(0, 0))
self.pushButtonDis.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.pushButtonDis.setDefault(False)
self.pushButtonDis.setObjectName("pushButtonDis")
self.gridLayout.addWidget(self.pushButtonDis, 1, 7, 1, 6)
self.label_73 = QtWidgets.QLabel(self.dockWidgetContents)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_73.setFont(font)
self.label_73.setObjectName("label_73")
self.gridLayout.addWidget(self.label_73, 0, 7, 1, 3)
self.pushButtonCheckedDis = QtWidgets.QPushButton(self.dockWidgetContents)
self.pushButtonCheckedDis.setEnabled(False)
self.pushButtonCheckedDis.setCheckable(True)
self.pushButtonCheckedDis.setChecked(True)
self.pushButtonCheckedDis.setObjectName("pushButtonCheckedDis")
self.gridLayout.addWidget(self.pushButtonCheckedDis, 2, 7, 1, 6)
self.label_26 = QtWidgets.QLabel(self.dockWidgetContents)
self.label_26.setMinimumSize(QtCore.QSize(0, 0))
self.label_26.setMaximumSize(QtCore.QSize(16777215, 16777215))
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_26.setFont(font)
self.label_26.setObjectName("label_26")
self.gridLayout.addWidget(self.label_26, 1, 0, 1, 1)
self.pushButtonUncheckedDis = QtWidgets.QPushButton(self.dockWidgetContents)
self.pushButtonUncheckedDis.setEnabled(False)
self.pushButtonUncheckedDis.setCheckable(True)
self.pushButtonUncheckedDis.setObjectName("pushButtonUncheckedDis")
self.gridLayout.addWidget(self.pushButtonUncheckedDis, 3, 7, 1, 6)
self.toolButtonDots = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonDots.setObjectName("toolButtonDots")
self.gridLayout.addWidget(self.toolButtonDots, 7, 6, 1, 1)
self.label_74 = QtWidgets.QLabel(self.dockWidgetContents)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_74.setFont(font)
self.label_74.setObjectName("label_74")
self.gridLayout.addWidget(self.label_74, 2, 0, 1, 1)
self.pushButtonUnchecked = QtWidgets.QPushButton(self.dockWidgetContents)
self.pushButtonUnchecked.setCheckable(True)
self.pushButtonUnchecked.setObjectName("pushButtonUnchecked")
self.gridLayout.addWidget(self.pushButtonUnchecked, 3, 1, 1, 6)
self.label_72 = QtWidgets.QLabel(self.dockWidgetContents)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(True)
self.label_72.setFont(font)
self.label_72.setObjectName("label_72")
self.gridLayout.addWidget(self.label_72, 0, 1, 1, 2)
self.toolButtonCheckedIcon = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonCheckedIcon.setCheckable(True)
self.toolButtonCheckedIcon.setChecked(True)
self.toolButtonCheckedIcon.setObjectName("toolButtonCheckedIcon")
self.gridLayout.addWidget(self.toolButtonCheckedIcon, 6, 6, 1, 1)
self.toolButtonIcon = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonIcon.setObjectName("toolButtonIcon")
self.gridLayout.addWidget(self.toolButtonIcon, 4, 6, 1, 1)
self.toolButtonDotsDis = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonDotsDis.setEnabled(False)
self.toolButtonDotsDis.setObjectName("toolButtonDotsDis")
self.gridLayout.addWidget(self.toolButtonDotsDis, 7, 12, 1, 1)
self.toolButtonCheckedIconDis = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonCheckedIconDis.setEnabled(False)
self.toolButtonCheckedIconDis.setCheckable(True)
self.toolButtonCheckedIconDis.setChecked(True)
self.toolButtonCheckedIconDis.setObjectName("toolButtonCheckedIconDis")
self.gridLayout.addWidget(self.toolButtonCheckedIconDis, 6, 12, 1, 1)
self.toolButtonIconDis = QtWidgets.QToolButton(self.dockWidgetContents)
self.toolButtonIconDis.setEnabled(False)
self.toolButtonIconDis.setObjectName("toolButtonIconDis")
self.gridLayout.addWidget(self.toolButtonIconDis, 4, 12, 1, 1)
DockWidget.setWidget(self.dockWidgetContents)
self.retranslateUi(DockWidget)
QtCore.QObject.connect(self.radioButtonChecked, QtCore.SIGNAL("clicked(bool)"), self.radioButtonCheckedDis.setChecked)
QtCore.QObject.connect(self.radioButtonUnchecked, QtCore.SIGNAL("clicked(bool)"), self.radioButtonUncheckedDis.setChecked)
QtCore.QObject.connect(self.checkBoxChecked, QtCore.SIGNAL("clicked(bool)"), self.checkBoxCheckedDis.setChecked)
QtCore.QObject.connect(self.checkBoxEnabled, QtCore.SIGNAL("clicked(bool)"), self.checkBoxUncheckedDis.setChecked)
QtCore.QObject.connect(self.checkBoxTristate, QtCore.SIGNAL("clicked(bool)"), self.checkBoxTristateDis.setChecked)
QtCore.QObject.connect(self.commandLinkButton, QtCore.SIGNAL("clicked(bool)"), self.commandLinkButtonDIs.setChecked)
QtCore.QObject.connect(self.toolButton, QtCore.SIGNAL("clicked(bool)"), self.toolButtonDis.setChecked)
QtCore.QObject.connect(self.pushButtonChecked, QtCore.SIGNAL("clicked(bool)"), self.pushButtonCheckedDis.setChecked)
QtCore.QObject.connect(self.pushButtonUnchecked, QtCore.SIGNAL("clicked(bool)"), self.pushButtonUncheckedDis.setChecked)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked(bool)"), self.pushButtonDis.click)
QtCore.QMetaObject.connectSlotsByName(DockWidget)
def retranslateUi(self, DockWidget):
DockWidget.setWindowTitle(QtWidgets.QApplication.translate("DockWidget", "Buttons", None, -1))
self.pushButtonChecked.setText(QtWidgets.QApplication.translate("DockWidget", "Checked", None, -1))
self.label_2.setText(QtWidgets.QApplication.translate("DockWidget", "<html><head/><body><p><span style=\" font-weight:600;\">ToolButton</span></p></body></html>", None, -1))
self.toolButtonChecked.setText(QtWidgets.QApplication.translate("DockWidget", "Tool Checked", None, -1))
self.toolButtonCheckedDis.setText(QtWidgets.QApplication.translate("DockWidget", "Tool Checked", None, -1))
self.label_3.setText(QtWidgets.QApplication.translate("DockWidget", "<html><head/><body><p><span style=\" font-weight:600;\">ToolButton</span></p></body></html>", None, -1))
self.toolButtonArrowDown.setText(QtWidgets.QApplication.translate("DockWidget", "...", None, -1))
self.toolButtonArrowUp.setText(QtWidgets.QApplication.translate("DockWidget", "...", None, -1))
self.toolButtonArrowRight.setText(QtWidgets.QApplication.translate("DockWidget", "...", None, -1))
self.toolButtonArrowLeft.setText(QtWidgets.QApplication.translate("DockWidget", "...", None, -1))
self.toolButtonArrowDownDis.setText(QtWidgets.QApplication.translate("DockWidget", "...", None, -1))
self.toolButtonArrowUpDis.setText(QtWidgets.QApplication.translate("DockWidget", "...", None, -1))
self.toolButtonArrowRightDis.setText(QtWidgets.QApplication.translate("DockWidget", "...", None, -1))
self.toolButtonArrowLeftDis.setText(QtWidgets.QApplication.translate("DockWidget", "...", None, -1))
self.radioButtonChecked.setText(QtWidgets.QApplication.translate("DockWidget", "Checked", None, -1))
self.radioButtonCheckedDis.setText(QtWidgets.QApplication.translate("DockWidget", "Checked", None, -1))
self.label_29.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.label_29.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.label_29.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.label_29.setText(QtWidgets.QApplication.translate("DockWidget", "RadioButton", None, -1))
self.radioButtonUnchecked.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.radioButtonUnchecked.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.radioButtonUnchecked.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.radioButtonUnchecked.setText(QtWidgets.QApplication.translate("DockWidget", "Unchecked", None, -1))
self.radioButtonUncheckedDis.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.radioButtonUncheckedDis.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.radioButtonUncheckedDis.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.radioButtonUncheckedDis.setText(QtWidgets.QApplication.translate("DockWidget", "Unchecked", None, -1))
self.label_53.setText(QtWidgets.QApplication.translate("DockWidget", "CheckBox", None, -1))
self.checkBoxChecked.setText(QtWidgets.QApplication.translate("DockWidget", "Checked", None, -1))
self.checkBoxCheckedDis.setText(QtWidgets.QApplication.translate("DockWidget", "Checked", None, -1))
self.label_30.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.label_30.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.label_30.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.label_30.setText(QtWidgets.QApplication.translate("DockWidget", "CheckBox", None, -1))
self.checkBoxEnabled.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.checkBoxEnabled.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.checkBoxEnabled.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.checkBoxEnabled.setText(QtWidgets.QApplication.translate("DockWidget", "Unchecked", None, -1))
self.checkBoxUncheckedDis.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.checkBoxUncheckedDis.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.checkBoxUncheckedDis.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.checkBoxUncheckedDis.setText(QtWidgets.QApplication.translate("DockWidget", "Unchecked", None, -1))
self.label.setText(QtWidgets.QApplication.translate("DockWidget", "CheckBox", None, -1))
self.checkBoxTristate.setText(QtWidgets.QApplication.translate("DockWidget", "Tristate", None, -1))
self.checkBoxTristateDis.setText(QtWidgets.QApplication.translate("DockWidget", "Tristate", None, -1))
self.label_31.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.label_31.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.label_31.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.label_31.setText(QtWidgets.QApplication.translate("DockWidget", "CommandLinkButton", None, -1))
self.commandLinkButton.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.commandLinkButton.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.commandLinkButton.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.commandLinkButton.setText(QtWidgets.QApplication.translate("DockWidget", "Command", None, -1))
self.commandLinkButtonDIs.setText(QtWidgets.QApplication.translate("DockWidget", "Command", None, -1))
self.label_32.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.label_32.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.label_32.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.label_32.setText(QtWidgets.QApplication.translate("DockWidget", "ButtonBox", None, -1))
self.buttonBox.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.buttonBox.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.buttonBox.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.label_36.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.label_36.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.label_36.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.label_36.setText(QtWidgets.QApplication.translate("DockWidget", "Inside DockWidget", None, -1))
self.label_76.setText(QtWidgets.QApplication.translate("DockWidget", "PushButton", None, -1))
self.label_33.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.label_33.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.label_33.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.label_33.setText(QtWidgets.QApplication.translate("DockWidget", "ToolButton", None, -1))
self.toolButton.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.toolButton.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.toolButton.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, -1))
self.toolButton.setText(QtWidgets.QApplication.translate("DockWidget", "Tool", None, -1))
self.toolButtonDis.setToolTip(QtWidgets.QApplication.translate("DockWidget", "This is a tool tip", None, -1))
self.toolButtonDis.setStatusTip(QtWidgets.QApplication.translate("DockWidget", "This is a status tip", None, -1))
self.toolButtonDis.setWhatsThis(QtWidgets.QApplication.translate("DockWidget", "This is \"what is this\"", None, | |
"trust_with_sets": [set(), set(), set()]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set()],
"trust_with_sets": [set()]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [{1, 2}],
"trust_with_sets": [{1, 2}]
}
]
}
),
(
[
{
"col_names": ["a", "b"],
"stored_with": {1},
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1, 2}, {1}]
},
{
"col_names": ["c", "d"],
"stored_with": {2},
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}]
}
],
{
"node_order": [
Create,
Create,
AggregateSumSquaresAndCount,
AggregateSumSquaresAndCount,
Concat,
AggregateStdDev,
Collect
],
"requires_mpc": [False, False, False, False, True, True, False],
"ownership_data": [
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1, 2}, {1}]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}]
},
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}, {1}],
"trust_with_sets": [{1, 2}, {1, 2}, {1}]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}, {2}],
"trust_with_sets": [{2}, {2}, {2}]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set(), set()],
"trust_with_sets": [{2}, {2}, set()]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set()],
"trust_with_sets": [{2}]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [{1, 2}],
"trust_with_sets": [{1, 2}]
}
]
}
),
(
[
{
"col_names": ["a", "b"],
"stored_with": {1, 2},
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"col_names": ["c", "d"],
"stored_with": {1, 2},
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
}
],
{
"node_order": [Create, Create, Concat, AggregateStdDev, Collect],
"requires_mpc": [True, True, True, True, False],
"ownership_data": [
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"stored_with": [{1, 2}],
"plaintext_sets": [set()],
"trust_with_sets": [set()]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [{1, 2}],
"trust_with_sets": [{1, 2}]
}
]
}
)
])
def test_std_dev_no_key_cols(party_data, expected):
cols_in_one = create_cols(party_data[0])
cols_in_two = create_cols(party_data[1])
rel_one = create("in1", cols_in_one, party_data[0]["stored_with"])
rel_two = create("in2", cols_in_two, party_data[1]["stored_with"])
cc = concat([rel_one, rel_two], "concat", party_data[0]["col_names"])
std_dev = aggregate(cc, "std_dev", [], party_data[0]["col_names"][0], "std_dev")
collect(std_dev, {1, 2})
d = Dag({rel_one, rel_two})
pd = PushDown()
pd.rewrite(d)
compare_to_expected(d, expected)
@pytest.mark.parametrize("party_data, expected", [
(
[
{
"col_names": ["a", "b"],
"stored_with": {1},
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1}, {1}]
},
{
"col_names": ["c", "d"],
"stored_with": {2},
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}]
}
],
{
"node_order": [
Create,
Create,
AggregateSumSquaresAndCount,
AggregateSumSquaresAndCount,
Concat,
AggregateVariance,
Collect
],
"requires_mpc": [False, False, False, False, True, True, False],
"ownership_data":[
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1}, {1}]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}]
},
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}, {1}, {1}],
"trust_with_sets": [{1}, {1}, {1}, {1}]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}, {2}, {2}],
"trust_with_sets": [{2}, {2}, {2}, {2}]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set(), set(), set()],
"trust_with_sets": [set(), set(), set(), set()]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [{1, 2}, {1, 2}],
"trust_with_sets": [{1, 2}, {1, 2}]
}
]
}
),
(
[
{
"col_names": ["a", "b"],
"stored_with": {1},
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"col_names": ["c", "d"],
"stored_with": {2},
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
}
],
{
"node_order": [
Create,
Create,
AggregateSumSquaresAndCount,
AggregateSumSquaresAndCount,
Concat,
AggregateVariance,
Collect
],
"requires_mpc": [False, False, False, False, True, True, False],
"ownership_data": [
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1}, {1}]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}]
},
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}, {1}, {1}],
"trust_with_sets": [{1}, {1}, {1}, {1}]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}, {2}, {2}],
"trust_with_sets": [{2}, {2}, {2}, {2}]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set(), set(), set()],
"trust_with_sets": [set(), set(), set(), set()]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [{1, 2}, {1, 2}],
"trust_with_sets": [{1, 2}, {1, 2}]
}
]
}
),
(
[
{
"col_names": ["a", "b"],
"stored_with": {1},
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1, 2}, {1}]
},
{
"col_names": ["c", "d"],
"stored_with": {2},
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}]
}
],
{
"node_order": [
Create,
Create,
AggregateSumSquaresAndCount,
AggregateSumSquaresAndCount,
Concat,
AggregateVariance,
Collect
],
"requires_mpc": [False, False, False, False, True, True, False],
"ownership_data": [
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1, 2}, {1}]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}]
},
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}, {1}, {1}],
"trust_with_sets": [{1, 2}, {1}, {1}, {1, 2}]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}, {2}, {2}],
"trust_with_sets": [{2}, {2}, {2}, {2}]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set(), set(), set()],
"trust_with_sets": [{2}, set(), set(), {2}]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [{2}, set()]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [{1, 2}, {1, 2}],
"trust_with_sets": [{1, 2}, {1, 2}]
}
]
}
),
(
[
{
"col_names": ["a", "b"],
"stored_with": {1, 2},
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"col_names": ["c", "d"],
"stored_with": {1, 2},
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
}
],
{
"node_order": [Create, Create, Concat, AggregateVariance, Collect],
"requires_mpc": [True, True, True, True, False],
"ownership_data": [
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [{1, 2}, {1, 2}],
"trust_with_sets": [{1, 2}, {1, 2}]
}
]
}
)
])
def test_variance(party_data, expected):
cols_in_one = create_cols(party_data[0])
cols_in_two = create_cols(party_data[1])
rel_one = create("in1", cols_in_one, party_data[0]["stored_with"])
rel_two = create("in2", cols_in_two, party_data[1]["stored_with"])
cc = concat([rel_one, rel_two], "concat", party_data[0]["col_names"])
variance = aggregate(cc, "variance", [party_data[0]["col_names"][0]], party_data[0]["col_names"][1], "variance")
collect(variance, {1, 2})
d = Dag({rel_one, rel_two})
pd = PushDown()
pd.rewrite(d)
compare_to_expected(d, expected)
@pytest.mark.parametrize("party_data, expected", [
(
[
{
"col_names": ["a", "b"],
"stored_with": {1},
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1}, {1}]
},
{
"col_names": ["c", "d"],
"stored_with": {2},
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}]
}
],
{
"node_order": [
Create,
Create,
AggregateSumSquaresAndCount,
AggregateSumSquaresAndCount,
Concat,
AggregateVariance,
Collect
],
"requires_mpc": [False, False, False, False, True, True, False],
"ownership_data":[
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1}, {1}],
"col_names": ["a", "b"]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}],
"col_names": ["c", "d"]
},
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}, {1}, {1}],
"trust_with_sets": [{1}, {1}, {1}, {1}],
"col_names": ["b", "a", "__SQUARES__", "__COUNT__"]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}, {2}, {2}],
"trust_with_sets": [{2}, {2}, {2}, {2}],
"col_names": ["d", "c", "__SQUARES__", "__COUNT__"]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set(), set(), set()],
"trust_with_sets": [set(), set(), set(), set()],
"col_names": ["b", "a", "__SQUARES__", "__COUNT__"]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()],
"col_names": ["b", "a"]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [{1, 2}, {1, 2}],
"trust_with_sets": [{1, 2}, {1, 2}],
"col_names": ["b", "a"]
}
]
}
),
(
[
{
"col_names": ["a", "b"],
"stored_with": {1},
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1, 2}, {1, 2}]
},
{
"col_names": ["c", "d"],
"stored_with": {2},
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}]
}
],
{
"node_order": [Create, Create, Concat, AggregateVariance, Collect],
"requires_mpc": [False, False, False, False, False],
"ownership_data": [
{
"stored_with": [{1}],
"plaintext_sets": [{1}, {1}],
"trust_with_sets": [{1, 2}, {1, 2}],
"col_names": ["a", "b"]
},
{
"stored_with": [{2}],
"plaintext_sets": [{2}, {2}],
"trust_with_sets": [{2}, {2}],
"col_names": ["c", "d"]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [{2}, {2}],
"col_names": ["a", "b"]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [{2}, {2}],
"col_names": ["b", "a"]
},
{
"stored_with": [{1}, {2}],
"plaintext_sets": [{1, 2}, {1, 2}],
"trust_with_sets": [{1, 2}, {1, 2}],
"col_names": ["b", "a"]
}
]
}
),
(
[
{
"col_names": ["a", "b"],
"stored_with": {1, 2},
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
},
{
"col_names": ["c", "d"],
"stored_with": {1, 2},
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()]
}
],
{
"node_order": [Create, Create, Concat, AggregateVariance, Collect],
"requires_mpc": [True, True, True, True, False],
"ownership_data": [
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()],
"col_names": ["a", "b"]
},
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()],
"col_names": ["c", "d"]
},
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": [set(), set()],
"col_names": ["a", "b"]
},
{
"stored_with": [{1, 2}],
"plaintext_sets": [set(), set()],
"trust_with_sets": |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.