code
stringlengths 22
1.05M
| apis
listlengths 1
3.31k
| extract_api
stringlengths 75
3.25M
|
|---|---|---|
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import pickle
import argparse
import torch
from kobert.pytorch_kobert import get_pytorch_kobert_model
from kobert.utils import get_tokenizer
from model.net import KobertSequenceFeatureExtractor, KobertCRF, KobertBiLSTMCRF, KobertBiGRUCRF
from gluonnlp.data import SentencepieceTokenizer
from data_utils.utils import Config
from data_utils.vocab_tokenizer import Tokenizer
from data_utils.pad_sequence import keras_pad_fn
from pathlib import Path
def main(parser):
args = parser.parse_args()
model_dir = Path(args.model_dir)
model_config = Config(json_path=model_dir / 'config.json')
# Vocab & Tokenizer
# tok_path = get_tokenizer() # ./tokenizer_78b3253a26.model
tok_path = "./tokenizer_78b3253a26.model"
ptr_tokenizer = SentencepieceTokenizer(tok_path)
# load vocab & tokenizer
with open(model_dir / "vocab.pkl", 'rb') as f:
vocab = pickle.load(f)
tokenizer = Tokenizer(vocab=vocab, split_fn=ptr_tokenizer, pad_fn=keras_pad_fn, maxlen=model_config.maxlen)
# load ner_to_index.json
with open(model_dir / "ner_to_index.json", 'rb') as f:
ner_to_index = json.load(f)
index_to_ner = {v: k for k, v in ner_to_index.items()}
# Model
# model = KobertSequenceFeatureExtractor(config=model_config, num_classes=len(ner_to_index))
model = KobertCRF(config=model_config, num_classes=len(ner_to_index), vocab=vocab)
# model = KobertBiLSTMCRF(config=model_config, num_classes=len(ner_to_index), vocab=vocab)
# model = KobertBiGRUCRF(config=model_config, num_classes=len(ner_to_index), vocab=vocab)
# load
model_dict = model.state_dict()
# checkpoint = torch.load("./experiments/base_model/best-epoch-9-step-600-acc-0.845.bin", map_location=torch.device('cpu'))
# checkpoint = torch.load("./experiments/base_model_with_crf/best-epoch-16-step-1500-acc-0.993.bin", map_location=torch.device('cpu'))
checkpoint = torch.load("./experiments/base_model_with_crf_val/best-epoch-12-step-1000-acc-0.960.bin", map_location=torch.device('cpu'))
# checkpoint = torch.load("./experiments/base_model_with_bilstm_crf/best-epoch-15-step-2750-acc-0.992.bin", map_location=torch.device('cpu'))
# checkpoint = torch.load("./experiments/base_model_with_bigru_crf/model-epoch-18-step-3250-acc-0.997.bin", map_location=torch.device('cpu'))
convert_keys = {}
for k, v in checkpoint['model_state_dict'].items():
new_key_name = k.replace("module.", '')
if new_key_name not in model_dict:
print("{} is not int model_dict".format(new_key_name))
continue
convert_keys[new_key_name] = v
model.load_state_dict(convert_keys)
model.eval()
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
# n_gpu = torch.cuda.device_count()
# if n_gpu > 1:
# model = torch.nn.DataParallel(model)
model.to(device)
decoder_from_res = DecoderFromNamedEntitySequence(tokenizer=tokenizer, index_to_ner=index_to_ner)
while(True):
input_text = input("문장을 입력하세요: ")
list_of_input_ids = tokenizer.list_of_string_to_list_of_cls_sep_token_ids([input_text])
x_input = torch.tensor(list_of_input_ids).long()
## for bert alone
# y_pred = model(x_input)
# list_of_pred_ids = y_pred.max(dim=-1)[1].tolist()
## for bert crf
list_of_pred_ids = model(x_input)
## for bert bilstm crf & bert bigru crf
# list_of_pred_ids = model(x_input, using_pack_sequence=False)
list_of_ner_word, decoding_ner_sentence = decoder_from_res(list_of_input_ids=list_of_input_ids, list_of_pred_ids=list_of_pred_ids)
print("list_of_ner_word:", list_of_ner_word)
print("decoding_ner_sentence:", decoding_ner_sentence)
class DecoderFromNamedEntitySequence():
def __init__(self, tokenizer, index_to_ner):
self.tokenizer = tokenizer
self.index_to_ner = index_to_ner
def __call__(self, list_of_input_ids, list_of_pred_ids):
input_token = self.tokenizer.decode_token_ids(list_of_input_ids)[0]
pred_ner_tag = [self.index_to_ner[pred_id] for pred_id in list_of_pred_ids[0]]
print("len: {}, input_token:{}".format(len(input_token), input_token))
print("len: {}, pred_ner_tag:{}".format(len(pred_ner_tag), pred_ner_tag))
# ----------------------------- parsing list_of_ner_word ----------------------------- #
list_of_ner_word = []
entity_word, entity_tag, prev_entity_tag = "", "", ""
for i, pred_ner_tag_str in enumerate(pred_ner_tag):
if "B-" in pred_ner_tag_str:
entity_tag = pred_ner_tag_str[-3:]
if prev_entity_tag != entity_tag and prev_entity_tag != "":
list_of_ner_word.append({"word": entity_word.replace("▁", " "), "tag": prev_entity_tag, "prob": None})
entity_word = input_token[i]
prev_entity_tag = entity_tag
elif "I-"+entity_tag in pred_ner_tag_str:
entity_word += input_token[i]
else:
if entity_word != "" and entity_tag != "":
list_of_ner_word.append({"word":entity_word.replace("▁", " "), "tag":entity_tag, "prob":None})
entity_word, entity_tag, prev_entity_tag = "", "", ""
# ----------------------------- parsing decoding_ner_sentence ----------------------------- #
decoding_ner_sentence = ""
is_prev_entity = False
prev_entity_tag = ""
is_there_B_before_I = False
for token_str, pred_ner_tag_str in zip(input_token, pred_ner_tag):
token_str = token_str.replace('▁', ' ') # '▁' 토큰을 띄어쓰기로 교체
if 'B-' in pred_ner_tag_str:
if is_prev_entity is True:
decoding_ner_sentence += ':' + prev_entity_tag+ '>'
if token_str[0] == ' ':
token_str = list(token_str)
token_str[0] = ' <'
token_str = ''.join(token_str)
decoding_ner_sentence += token_str
else:
decoding_ner_sentence += '<' + token_str
is_prev_entity = True
prev_entity_tag = pred_ner_tag_str[-3:] # 첫번째 예측을 기준으로 하겠음
is_there_B_before_I = True
elif 'I-' in pred_ner_tag_str:
decoding_ner_sentence += token_str
if is_there_B_before_I is True: # I가 나오기전에 B가 있어야하도록 체크
is_prev_entity = True
else:
if is_prev_entity is True:
decoding_ner_sentence += ':' + prev_entity_tag+ '>' + token_str
is_prev_entity = False
is_there_B_before_I = False
else:
decoding_ner_sentence += token_str
return list_of_ner_word, decoding_ner_sentence
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', default='./data_in', help="Directory containing config.json of data")
# parser.add_argument('--model_dir', default='./experiments/base_model', help="Directory containing config.json of model")
parser.add_argument('--model_dir', default='./experiments/base_model_with_crf_val', help="Directory containing config.json of model")
# parser.add_argument('--model_dir', default='./experiments/base_model_with_crf', help="Directory containing config.json of model")
# parser.add_argument('--model_dir', default='./experiments/base_model_with_bilstm_crf', help="Directory containing config.json of model")
# parser.add_argument('--model_dir', default='./experiments/base_model_with_bigru_crf', help="Directory containing config.json of model")
main(parser)
|
[
"json.load",
"argparse.ArgumentParser",
"data_utils.vocab_tokenizer.Tokenizer",
"pathlib.Path",
"pickle.load",
"torch.cuda.is_available",
"torch.device",
"gluonnlp.data.SentencepieceTokenizer",
"data_utils.utils.Config",
"torch.tensor"
] |
[((608, 628), 'pathlib.Path', 'Path', (['args.model_dir'], {}), '(args.model_dir)\n', (612, 628), False, 'from pathlib import Path\n'), ((648, 691), 'data_utils.utils.Config', 'Config', ([], {'json_path': "(model_dir / 'config.json')"}), "(json_path=model_dir / 'config.json')\n", (654, 691), False, 'from data_utils.utils import Config\n'), ((847, 879), 'gluonnlp.data.SentencepieceTokenizer', 'SentencepieceTokenizer', (['tok_path'], {}), '(tok_path)\n', (869, 879), False, 'from gluonnlp.data import SentencepieceTokenizer\n'), ((1009, 1109), 'data_utils.vocab_tokenizer.Tokenizer', 'Tokenizer', ([], {'vocab': 'vocab', 'split_fn': 'ptr_tokenizer', 'pad_fn': 'keras_pad_fn', 'maxlen': 'model_config.maxlen'}), '(vocab=vocab, split_fn=ptr_tokenizer, pad_fn=keras_pad_fn, maxlen=\n model_config.maxlen)\n', (1018, 1109), False, 'from data_utils.vocab_tokenizer import Tokenizer\n'), ((7065, 7090), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (7088, 7090), False, 'import argparse\n'), ((977, 991), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (988, 991), False, 'import pickle\n'), ((1217, 1229), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1226, 1229), False, 'import json\n'), ((2820, 2845), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2843, 2845), False, 'import torch\n'), ((2796, 2816), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (2808, 2816), False, 'import torch\n'), ((2851, 2870), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2863, 2870), False, 'import torch\n'), ((2115, 2134), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2127, 2134), False, 'import torch\n'), ((3277, 3308), 'torch.tensor', 'torch.tensor', (['list_of_input_ids'], {}), '(list_of_input_ids)\n', (3289, 3308), False, 'import torch\n')]
|
'''
Model definition
'''
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from settings import *
from data_prep import calc_iou
def SSDHook(feature_map, hook_id):
"""
Takes input feature map, output the predictions tensor
hook_id is for variable_scope unqie string ID
"""
with tf.variable_scope('ssd_hook_' + hook_id):
# Note we have linear activation (i.e. no activation function)
net_conf = slim.conv2d(feature_map, NUM_PRED_CONF, [3, 3], activation_fn=None, scope='conv_conf')
net_conf = tf.contrib.layers.flatten(net_conf)
net_loc = slim.conv2d(feature_map, NUM_PRED_LOC, [3, 3], activation_fn=None, scope='conv_loc')
net_loc = tf.contrib.layers.flatten(net_loc)
return net_conf, net_loc
def ModelHelper(y_pred_conf, y_pred_loc):
"""
Define loss function, optimizer, predictions, and accuracy metric
Loss includes confidence loss and localization loss
conf_loss_mask is created at batch generation time, to mask the confidence losses
It has 1 at locations w/ positives, and 1 at select negative locations
such that negative-to-positive ratio of NEG_POS_RATIO is satisfied
Arguments:
* y_pred_conf: Class predictions from model,
a tensor of shape [batch_size, num_feature_map_cells * num_defaul_boxes * num_classes]
* y_pred_loc: Localization predictions from model,
a tensor of shape [batch_size, num_feature_map_cells * num_defaul_boxes * 4]
Returns relevant tensor references
"""
num_total_preds = 0
for fm_size in FM_SIZES:
num_total_preds += fm_size[0] * fm_size[1] * NUM_DEFAULT_BOXES
num_total_preds_conf = num_total_preds * NUM_CLASSES
num_total_preds_loc = num_total_preds * 4
# Input tensors
y_true_conf = tf.placeholder(tf.int32, [None, num_total_preds], name='y_true_conf') # classification ground-truth labels
y_true_loc = tf.placeholder(tf.float32, [None, num_total_preds_loc], name='y_true_loc') # localization ground-truth labels
conf_loss_mask = tf.placeholder(tf.float32, [None, num_total_preds], name='conf_loss_mask') # 1 mask "bit" per def. box
# Confidence loss
logits = tf.reshape(y_pred_conf, [-1, num_total_preds, NUM_CLASSES])
conf_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits, labels = y_true_conf)
conf_loss = conf_loss_mask * conf_loss # "zero-out" the loss for don't-care negatives
conf_loss = tf.reduce_sum(conf_loss)
# Localization loss (smooth L1 loss)
# loc_loss_mask is analagous to conf_loss_mask, except 4 times the size
diff = y_true_loc - y_pred_loc
loc_loss_l2 = 0.5 * (diff**2.0)
loc_loss_l1 = tf.abs(diff) - 0.5
smooth_l1_condition = tf.less(tf.abs(diff), 1.0)
loc_loss = tf.where(smooth_l1_condition, loc_loss_l2, loc_loss_l1)
loc_loss_mask = tf.minimum(y_true_conf, 1) # have non-zero localization loss only where we have matching ground-truth box
loc_loss_mask = tf.to_float(loc_loss_mask)
loc_loss_mask = tf.stack([loc_loss_mask] * 4, axis=2) # [0, 1, 1] -> [[[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1]], ...]
loc_loss_mask = tf.reshape(loc_loss_mask, [-1, num_total_preds_loc]) # removing the inner-most dimension of above
loc_loss = loc_loss_mask * loc_loss
loc_loss = tf.reduce_sum(loc_loss)
# Weighted average of confidence loss and localization loss
# Also add regularization loss
loss = conf_loss + LOC_LOSS_WEIGHT * loc_loss + tf.reduce_sum(slim.losses.get_regularization_losses())
optimizer = OPT.minimize(loss)
#reported_loss = loss #tf.reduce_sum(loss, 1) # DEBUG
# Class probabilities and predictions
probs_all = tf.nn.softmax(logits)
probs, preds_conf = tf.nn.top_k(probs_all) # take top-1 probability, and the index is the predicted class
probs = tf.reshape(probs, [-1, num_total_preds])
preds_conf = tf.reshape(preds_conf, [-1, num_total_preds])
# Return a dictionary of {tensor_name: tensor_reference}
ret_dict = {
'y_true_conf': y_true_conf,
'y_true_loc': y_true_loc,
'conf_loss_mask': conf_loss_mask,
'optimizer': optimizer,
'conf_loss': conf_loss,
'loc_loss': loc_loss,
'loss': loss,
'probs': probs,
'preds_conf': preds_conf,
'preds_loc': y_pred_loc,
}
return ret_dict
def AlexNet():
"""
AlexNet
"""
# Image batch tensor and dropout keep prob placeholders
x = tf.placeholder(tf.float32, [None, IMG_H, IMG_W, NUM_CHANNELS], name='x')
is_training = tf.placeholder(tf.bool, name='is_training')
# Classification and localization predictions
preds_conf = [] # conf -> classification b/c confidence loss -> classification loss
preds_loc = []
# Use batch normalization for all convolution layers
# FIXME: Not sure why setting is_training is not working well
#with slim.arg_scope([slim.conv2d], normalizer_fn=slim.batch_norm, normalizer_params={'is_training': is_training}):
with slim.arg_scope([slim.conv2d], normalizer_fn=slim.batch_norm, normalizer_params={'is_training': True},\
weights_regularizer=slim.l2_regularizer(scale=REG_SCALE)):
net = slim.conv2d(x, 64, [11, 11], 4, padding='VALID', scope='conv1')
net = slim.max_pool2d(net, [3, 3], 2, scope='pool1')
net = slim.conv2d(net, 192, [5, 5], scope='conv2')
net_conf, net_loc = SSDHook(net, 'conv2')
preds_conf.append(net_conf)
preds_loc.append(net_loc)
net = slim.max_pool2d(net, [3, 3], 2, scope='pool2')
net = slim.conv2d(net, 384, [3, 3], scope='conv3')
net = slim.conv2d(net, 384, [3, 3], scope='conv4')
net = slim.conv2d(net, 256, [3, 3], scope='conv5')
# The following layers added for SSD
net = slim.conv2d(net, 1024, [3, 3], scope='conv6')
net = slim.conv2d(net, 1024, [1, 1], scope='conv7')
net_conf, net_loc = SSDHook(net, 'conv7')
preds_conf.append(net_conf)
preds_loc.append(net_loc)
net = slim.conv2d(net, 256, [1, 1], scope='conv8')
net = slim.conv2d(net, 512, [3, 3], 2, scope='conv8_2')
net_conf, net_loc = SSDHook(net, 'conv8_2')
preds_conf.append(net_conf)
preds_loc.append(net_loc)
net = slim.conv2d(net, 128, [1, 1], scope='conv9')
net = slim.conv2d(net, 256, [3, 3], 2, scope='conv9_2')
net_conf, net_loc = SSDHook(net, 'conv9_2')
preds_conf.append(net_conf)
preds_loc.append(net_loc)
# Concatenate all preds together into 1 vector, for both classification and localization predictions
final_pred_conf = tf.concat(preds_conf,1)
final_pred_loc = tf.concat(preds_loc, 1)
# Return a dictionary of {tensor_name: tensor_reference}
ret_dict = {
'x': x,
'y_pred_conf': final_pred_conf,
'y_pred_loc': final_pred_loc,
'is_training': is_training,
}
return ret_dict
def SSDModel():
"""
Wrapper around the model and model helper
Returns dict of relevant tensor references
"""
if MODEL == 'AlexNet':
model = AlexNet()
else:
raise NotImplementedError('Model %s not supported' % MODEL)
model_helper = ModelHelper(model['y_pred_conf'], model['y_pred_loc'])
ssd_model = {}
for k in model.keys():
ssd_model[k] = model[k]
for k in model_helper.keys():
ssd_model[k] = model_helper[k]
return ssd_model
def nms(y_pred_conf, y_pred_loc, prob):
"""
Non-Maximum Suppression (NMS)
Performs NMS on all boxes of each class where predicted probability > CONF_THRES
For all boxes exceeding IOU threshold, select the box with highest confidence
Returns a lsit of box coordinates post-NMS
Arguments:
* y_pred_conf: Class predictions, numpy array of shape (num_feature_map_cells * num_defaul_boxes,)
* y_pred_loc: Bounding box coordinates, numpy array of shape (num_feature_map_cells * num_defaul_boxes * 4,)
These coordinates are normalized coordinates relative to center of feature map cell
* prob: Class probabilities, numpy array of shape (num_feature_map_cells * num_defaul_boxes,)
Returns:
* boxes: Numpy array of boxes, with shape (num_boxes, 6). shape[0] is interpreted as:
[x1, y1, x2, y2, class, probability], where x1/y1/x2/y2 are the coordinates of the
upper-left and lower-right corners. Box coordinates assume the image size is IMG_W x IMG_H.
Remember to rescale box coordinates if your target image has different dimensions.
"""
# Keep track of boxes for each class
class_boxes = {} # class -> [(x1, y1, x2, y2, prob), (...), ...]
with open('signnames.csv', 'r') as f:
for line in f:
cls, _ = line.split(',')
class_boxes[float(cls)] = []
# Go through all possible boxes and perform class-based greedy NMS (greedy based on class prediction confidence)
y_idx = 0
for fm_size in FM_SIZES:
fm_h, fm_w = fm_size # feature map height and width
for row in range(fm_h):
for col in range(fm_w):
for db in DEFAULT_BOXES:
# Only perform calculations if class confidence > CONF_THRESH and not background class
if prob[y_idx] > CONF_THRESH and y_pred_conf[y_idx] > 0.:
# Calculate absolute coordinates of predicted bounding box
xc, yc = col + 0.5, row + 0.5 # center of current feature map cell
center_coords = np.array([xc, yc, xc, yc])
abs_box_coords = center_coords + y_pred_loc[y_idx*4 : y_idx*4 + 4] # predictions are offsets to center of fm cell
# Calculate predicted box coordinates in actual image
scale = np.array([IMG_W/fm_w, IMG_H/fm_h, IMG_W/fm_w, IMG_H/fm_h])
box_coords = abs_box_coords * scale
box_coords = [int(round(x)) for x in box_coords]
# Compare this box to all previous boxes of this class
cls = y_pred_conf[y_idx]
cls_prob = prob[y_idx]
box = (*box_coords, cls, cls_prob)
if len(class_boxes[cls]) == 0:
class_boxes[cls].append(box)
else:
suppressed = False # did this box suppress other box(es)?
overlapped = False # did this box overlap with other box(es)?
for other_box in class_boxes[cls]:
iou = calc_iou(box[:4], other_box[:4])
if iou > NMS_IOU_THRESH:
overlapped = True
# If current box has higher confidence than other box
if box[5] > other_box[5]:
class_boxes[cls].remove(other_box)
suppressed = True
if suppressed or not overlapped:
class_boxes[cls].append(box)
y_idx += 1
# Gather all the pruned boxes and return them
boxes = []
for cls in class_boxes.keys():
for class_box in class_boxes[cls]:
boxes.append(class_box)
boxes = np.array(boxes)
return boxes
|
[
"tensorflow.reduce_sum",
"tensorflow.contrib.layers.flatten",
"tensorflow.reshape",
"tensorflow.contrib.slim.l2_regularizer",
"tensorflow.nn.softmax",
"tensorflow.contrib.slim.conv2d",
"tensorflow.abs",
"tensorflow.nn.top_k",
"tensorflow.concat",
"tensorflow.variable_scope",
"tensorflow.minimum",
"tensorflow.stack",
"tensorflow.placeholder",
"data_prep.calc_iou",
"tensorflow.to_float",
"tensorflow.where",
"tensorflow.contrib.slim.max_pool2d",
"tensorflow.contrib.slim.losses.get_regularization_losses",
"numpy.array",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits"
] |
[((1706, 1775), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, num_total_preds]'], {'name': '"""y_true_conf"""'}), "(tf.int32, [None, num_total_preds], name='y_true_conf')\n", (1720, 1775), True, 'import tensorflow as tf\n'), ((1829, 1903), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, num_total_preds_loc]'], {'name': '"""y_true_loc"""'}), "(tf.float32, [None, num_total_preds_loc], name='y_true_loc')\n", (1843, 1903), True, 'import tensorflow as tf\n'), ((1958, 2032), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, num_total_preds]'], {'name': '"""conf_loss_mask"""'}), "(tf.float32, [None, num_total_preds], name='conf_loss_mask')\n", (1972, 2032), True, 'import tensorflow as tf\n'), ((2092, 2151), 'tensorflow.reshape', 'tf.reshape', (['y_pred_conf', '[-1, num_total_preds, NUM_CLASSES]'], {}), '(y_pred_conf, [-1, num_total_preds, NUM_CLASSES])\n', (2102, 2151), True, 'import tensorflow as tf\n'), ((2165, 2251), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'y_true_conf'}), '(logits=logits, labels=\n y_true_conf)\n', (2211, 2251), True, 'import tensorflow as tf\n'), ((2352, 2376), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['conf_loss'], {}), '(conf_loss)\n', (2365, 2376), True, 'import tensorflow as tf\n'), ((2652, 2707), 'tensorflow.where', 'tf.where', (['smooth_l1_condition', 'loc_loss_l2', 'loc_loss_l1'], {}), '(smooth_l1_condition, loc_loss_l2, loc_loss_l1)\n', (2660, 2707), True, 'import tensorflow as tf\n'), ((2727, 2753), 'tensorflow.minimum', 'tf.minimum', (['y_true_conf', '(1)'], {}), '(y_true_conf, 1)\n', (2737, 2753), True, 'import tensorflow as tf\n'), ((2851, 2877), 'tensorflow.to_float', 'tf.to_float', (['loc_loss_mask'], {}), '(loc_loss_mask)\n', (2862, 2877), True, 'import tensorflow as tf\n'), ((2895, 2932), 'tensorflow.stack', 'tf.stack', (['([loc_loss_mask] * 4)'], {'axis': '(2)'}), '([loc_loss_mask] * 4, axis=2)\n', (2903, 2932), True, 'import tensorflow as tf\n'), ((3016, 3068), 'tensorflow.reshape', 'tf.reshape', (['loc_loss_mask', '[-1, num_total_preds_loc]'], {}), '(loc_loss_mask, [-1, num_total_preds_loc])\n', (3026, 3068), True, 'import tensorflow as tf\n'), ((3164, 3187), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['loc_loss'], {}), '(loc_loss)\n', (3177, 3187), True, 'import tensorflow as tf\n'), ((3528, 3549), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), '(logits)\n', (3541, 3549), True, 'import tensorflow as tf\n'), ((3571, 3593), 'tensorflow.nn.top_k', 'tf.nn.top_k', (['probs_all'], {}), '(probs_all)\n', (3582, 3593), True, 'import tensorflow as tf\n'), ((3667, 3707), 'tensorflow.reshape', 'tf.reshape', (['probs', '[-1, num_total_preds]'], {}), '(probs, [-1, num_total_preds])\n', (3677, 3707), True, 'import tensorflow as tf\n'), ((3722, 3767), 'tensorflow.reshape', 'tf.reshape', (['preds_conf', '[-1, num_total_preds]'], {}), '(preds_conf, [-1, num_total_preds])\n', (3732, 3767), True, 'import tensorflow as tf\n'), ((4218, 4290), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, IMG_H, IMG_W, NUM_CHANNELS]'], {'name': '"""x"""'}), "(tf.float32, [None, IMG_H, IMG_W, NUM_CHANNELS], name='x')\n", (4232, 4290), True, 'import tensorflow as tf\n'), ((4306, 4349), 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool'], {'name': '"""is_training"""'}), "(tf.bool, name='is_training')\n", (4320, 4349), True, 'import tensorflow as tf\n'), ((6211, 6235), 'tensorflow.concat', 'tf.concat', (['preds_conf', '(1)'], {}), '(preds_conf, 1)\n', (6220, 6235), True, 'import tensorflow as tf\n'), ((6253, 6276), 'tensorflow.concat', 'tf.concat', (['preds_loc', '(1)'], {}), '(preds_loc, 1)\n', (6262, 6276), True, 'import tensorflow as tf\n'), ((10156, 10171), 'numpy.array', 'np.array', (['boxes'], {}), '(boxes)\n', (10164, 10171), True, 'import numpy as np\n'), ((317, 357), 'tensorflow.variable_scope', 'tf.variable_scope', (["('ssd_hook_' + hook_id)"], {}), "('ssd_hook_' + hook_id)\n", (334, 357), True, 'import tensorflow as tf\n'), ((437, 528), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['feature_map', 'NUM_PRED_CONF', '[3, 3]'], {'activation_fn': 'None', 'scope': '"""conv_conf"""'}), "(feature_map, NUM_PRED_CONF, [3, 3], activation_fn=None, scope=\n 'conv_conf')\n", (448, 528), True, 'import tensorflow.contrib.slim as slim\n'), ((537, 572), 'tensorflow.contrib.layers.flatten', 'tf.contrib.layers.flatten', (['net_conf'], {}), '(net_conf)\n', (562, 572), True, 'import tensorflow as tf\n'), ((586, 675), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['feature_map', 'NUM_PRED_LOC', '[3, 3]'], {'activation_fn': 'None', 'scope': '"""conv_loc"""'}), "(feature_map, NUM_PRED_LOC, [3, 3], activation_fn=None, scope=\n 'conv_loc')\n", (597, 675), True, 'import tensorflow.contrib.slim as slim\n'), ((683, 717), 'tensorflow.contrib.layers.flatten', 'tf.contrib.layers.flatten', (['net_loc'], {}), '(net_loc)\n', (708, 717), True, 'import tensorflow as tf\n'), ((2571, 2583), 'tensorflow.abs', 'tf.abs', (['diff'], {}), '(diff)\n', (2577, 2583), True, 'import tensorflow as tf\n'), ((2621, 2633), 'tensorflow.abs', 'tf.abs', (['diff'], {}), '(diff)\n', (2627, 2633), True, 'import tensorflow as tf\n'), ((4914, 4977), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['x', '(64)', '[11, 11]', '(4)'], {'padding': '"""VALID"""', 'scope': '"""conv1"""'}), "(x, 64, [11, 11], 4, padding='VALID', scope='conv1')\n", (4925, 4977), True, 'import tensorflow.contrib.slim as slim\n'), ((4986, 5032), 'tensorflow.contrib.slim.max_pool2d', 'slim.max_pool2d', (['net', '[3, 3]', '(2)'], {'scope': '"""pool1"""'}), "(net, [3, 3], 2, scope='pool1')\n", (5001, 5032), True, 'import tensorflow.contrib.slim as slim\n'), ((5041, 5085), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(192)', '[5, 5]'], {'scope': '"""conv2"""'}), "(net, 192, [5, 5], scope='conv2')\n", (5052, 5085), True, 'import tensorflow.contrib.slim as slim\n'), ((5198, 5244), 'tensorflow.contrib.slim.max_pool2d', 'slim.max_pool2d', (['net', '[3, 3]', '(2)'], {'scope': '"""pool2"""'}), "(net, [3, 3], 2, scope='pool2')\n", (5213, 5244), True, 'import tensorflow.contrib.slim as slim\n'), ((5253, 5297), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(384)', '[3, 3]'], {'scope': '"""conv3"""'}), "(net, 384, [3, 3], scope='conv3')\n", (5264, 5297), True, 'import tensorflow.contrib.slim as slim\n'), ((5306, 5350), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(384)', '[3, 3]'], {'scope': '"""conv4"""'}), "(net, 384, [3, 3], scope='conv4')\n", (5317, 5350), True, 'import tensorflow.contrib.slim as slim\n'), ((5359, 5403), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(256)', '[3, 3]'], {'scope': '"""conv5"""'}), "(net, 256, [3, 3], scope='conv5')\n", (5370, 5403), True, 'import tensorflow.contrib.slim as slim\n'), ((5452, 5497), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(1024)', '[3, 3]'], {'scope': '"""conv6"""'}), "(net, 1024, [3, 3], scope='conv6')\n", (5463, 5497), True, 'import tensorflow.contrib.slim as slim\n'), ((5506, 5551), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(1024)', '[1, 1]'], {'scope': '"""conv7"""'}), "(net, 1024, [1, 1], scope='conv7')\n", (5517, 5551), True, 'import tensorflow.contrib.slim as slim\n'), ((5664, 5708), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(256)', '[1, 1]'], {'scope': '"""conv8"""'}), "(net, 256, [1, 1], scope='conv8')\n", (5675, 5708), True, 'import tensorflow.contrib.slim as slim\n'), ((5717, 5766), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(512)', '[3, 3]', '(2)'], {'scope': '"""conv8_2"""'}), "(net, 512, [3, 3], 2, scope='conv8_2')\n", (5728, 5766), True, 'import tensorflow.contrib.slim as slim\n'), ((5881, 5925), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(128)', '[1, 1]'], {'scope': '"""conv9"""'}), "(net, 128, [1, 1], scope='conv9')\n", (5892, 5925), True, 'import tensorflow.contrib.slim as slim\n'), ((5934, 5983), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(256)', '[3, 3]', '(2)'], {'scope': '"""conv9_2"""'}), "(net, 256, [3, 3], 2, scope='conv9_2')\n", (5945, 5983), True, 'import tensorflow.contrib.slim as slim\n'), ((3345, 3384), 'tensorflow.contrib.slim.losses.get_regularization_losses', 'slim.losses.get_regularization_losses', ([], {}), '()\n', (3382, 3384), True, 'import tensorflow.contrib.slim as slim\n'), ((4867, 4903), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', ([], {'scale': 'REG_SCALE'}), '(scale=REG_SCALE)\n', (4886, 4903), True, 'import tensorflow.contrib.slim as slim\n'), ((8814, 8840), 'numpy.array', 'np.array', (['[xc, yc, xc, yc]'], {}), '([xc, yc, xc, yc])\n', (8822, 8840), True, 'import numpy as np\n'), ((9037, 9103), 'numpy.array', 'np.array', (['[IMG_W / fm_w, IMG_H / fm_h, IMG_W / fm_w, IMG_H / fm_h]'], {}), '([IMG_W / fm_w, IMG_H / fm_h, IMG_W / fm_w, IMG_H / fm_h])\n', (9045, 9103), True, 'import numpy as np\n'), ((9633, 9665), 'data_prep.calc_iou', 'calc_iou', (['box[:4]', 'other_box[:4]'], {}), '(box[:4], other_box[:4])\n', (9641, 9665), False, 'from data_prep import calc_iou\n')]
|
"""
MIT License
Copyright (c) 2021 GamingGeek
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 discord.ext import commands
import humanfriendly
import datetime
import asyncio
class Ready(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
try:
self.bot.load_extension("cogs.sk1erdiscord")
except Exception:
pass
self.bot.logger.info("$GREEN-------------------------")
self.bot.logger.info(f"$GREENBot: $CYAN{self.bot.user}")
self.bot.logger.info(f"$GREENID: $CYAN{self.bot.user.id}")
self.bot.logger.info(f"$GREENGuilds: $CYAN{len(self.bot.guilds)}")
self.bot.logger.info(f"$GREENUsers: $CYAN{len(self.bot.users)}")
if not self.bot.started:
start = humanfriendly.format_timespan(datetime.datetime.now(
datetime.timezone.utc) - self.bot.launchtime)
self.bot.logger.info(f"$GREENStarted in $CYAN{start}")
self.bot.started = True
self.bot.logger.info("$GREEN-------------------------")
for c in self.bot.configs.values():
if not c.loaded and hasattr(c, '_guild'):
await c.load() # Load any stragglers that (for whatever reason) did not load on GUILD_CREATE
if self.bot.get_cog('FireStatus') and not self.bot.dev:
comps = ['gtbpmn9g33jk', 'xp3103fm3kpf']
for c in comps:
await asyncio.sleep(1) # rate limits are fun
current = await self.bot.get_cog('FireStatus').get_status(c)
if current == 'partial_outage':
# rate limits are fun 2 electric boogaloo
await asyncio.sleep(1)
await self.bot.get_cog('FireStatus').set_status(c, 'operational')
def setup(bot):
try:
bot.add_cog(Ready(bot))
bot.logger.info(f'$GREENLoaded event $CYANReady!')
except Exception as e:
bot.logger.error(
f'$REDError while loading event $CYAN"Ready"', exc_info=e)
|
[
"datetime.datetime.now",
"asyncio.sleep",
"discord.ext.commands.Cog.listener"
] |
[((1247, 1270), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (1268, 1270), False, 'from discord.ext import commands\n'), ((1841, 1885), 'datetime.datetime.now', 'datetime.datetime.now', (['datetime.timezone.utc'], {}), '(datetime.timezone.utc)\n', (1862, 1885), False, 'import datetime\n'), ((2468, 2484), 'asyncio.sleep', 'asyncio.sleep', (['(1)'], {}), '(1)\n', (2481, 2484), False, 'import asyncio\n'), ((2721, 2737), 'asyncio.sleep', 'asyncio.sleep', (['(1)'], {}), '(1)\n', (2734, 2737), False, 'import asyncio\n')]
|
"""
====================================================================
ConvSCCS cross validation on simulated longitudinal features example
====================================================================
In this example we simulate longitudinal data with preset relative incidence
for each feature. We then perform a cross validation of the ConvSCCS model
and compare the estimated coefficients to the relative incidences used for
the simulation.
"""
from time import time
import numpy as np
from scipy.sparse import csr_matrix, hstack
from matplotlib import cm
import matplotlib.pylab as plt
from tick.survival.simu_sccs import CustomEffects
from tick.survival import SimuSCCS, ConvSCCS
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Simulation parameters
seed = 0
lags = 49
n_samples = 2000
n_intervals = 750
n_corr = 3
# Relative incidence functions used for the simulation
ce = CustomEffects(lags + 1)
null_effect = [ce.constant_effect(1)] * 2
intermediate_effect = ce.bell_shaped_effect(2, 30, 15, 15)
late_effects = ce.increasing_effect(2, curvature_type=4)
sim_effects = [*null_effect, intermediate_effect, late_effects]
n_features = len(sim_effects)
n_lags = np.repeat(lags, n_features).astype('uint64')
coeffs = [np.log(c) for c in sim_effects]
# Time drift (age effect) used for the simulations.
time_drift = lambda t: np.log(8 * np.sin(.01 * t) + 9)
# Simaltion of the features.
sim = SimuSCCS(n_samples, n_intervals, n_features, n_lags,
time_drift=time_drift, coeffs=coeffs, seed=seed,
n_correlations=n_corr, verbose=False)
features, censored_features, labels, censoring, coeffs = sim.simulate()
# Plot the Hawkes kernel matrix used to generate the features.
fig, ax = plt.subplots(figsize=(7, 6))
heatmap = ax.pcolor(sim.hawkes_exp_kernels.adjacency, cmap=cm.Blues)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.5)
fig.colorbar(heatmap, cax=cax)
ax.set_title('Hawkes adjacency matrix used for the simulation');
plt.show()
## Add age_groups features to feature matrices.
agegrps = [0, 125, 250, 375, 500, 625, 750]
n_agegrps = len(agegrps) - 1
feat_agegrp = np.zeros((n_intervals, n_agegrps))
for i in range(n_agegrps):
feat_agegrp[agegrps[i]:agegrps[i + 1], i] = 1
feat_agegrp = csr_matrix(feat_agegrp)
features = [hstack([f, feat_agegrp]).tocsr() for f in features]
censored_features = [hstack([f, feat_agegrp]).tocsr() for f in
censored_features]
n_lags = np.hstack([n_lags, np.zeros(n_agegrps)])
# Learning
# Example code for cross validation
# start = time()
# learner = ConvSCCS(n_lags=n_lags.astype('uint64'),
# penalized_features=np.arange(n_features),
# random_state=42)
# C_TV_range = (1, 4)
# C_L1_range = (2, 5)
# _, cv_track = learner.fit_kfold_cv(features, labels, censoring,
# C_TV_range, C_L1_range,
# confidence_intervals=True,
# n_samples_bootstrap=20, n_cv_iter=50)
# elapsed_time = time() - start
# print("Elapsed time (model training): %.2f seconds \n" % elapsed_time)
# print("Best model hyper parameters: \n")
# print("C_tv : %f \n" % cv_track.best_model['C_tv'])
# print("C_group_l1 : %f \n" % cv_track.best_model['C_group_l1'])
# cv_track.plot_cv_report(35, 45)
# plt.show()
# confidence_intervals = cv_track.best_model['confidence_intervals']
# using the parameters resulting from cross-validation
learner = ConvSCCS(n_lags=n_lags.astype('uint64'),
penalized_features=np.arange(n_features),
random_state=42, C_tv=270.2722840570933,
C_group_l1=5216.472772625124)
_, confidence_intervals = learner.fit(features, labels, censoring,
confidence_intervals=True,
n_samples_bootstrap=20)
# Plot estimated parameters
# get bootstrap confidence intervals
refitted_coeffs = confidence_intervals['refit_coeffs']
lower_bound = confidence_intervals['lower_bound']
upper_bound = confidence_intervals['upper_bound']
n_rows = int(np.ceil(n_features / 2))
remove_last_plot = (n_features % 2 != 0)
fig, axarr = plt.subplots(n_rows, 2, sharex=True, sharey=True, figsize=(10, 6))
y = confidence_intervals['refit_coeffs']
lb = confidence_intervals['lower_bound']
ub = confidence_intervals['upper_bound']
for i, c in enumerate(y[:-6]):
ax = axarr[i // 2][i % 2]
l = n_lags[i]
ax.plot(np.exp(coeffs[i]), label="True RI")
ax.step(np.arange(l + 1), np.exp(c), label="Estimated RI")
ax.fill_between(np.arange(l + 1), np.exp(lb[i]), np.exp(ub[i]), alpha=.5,
color='orange', step='pre', label="95% boostrap CI")
plt.suptitle('Estimated relative risks with 95% confidence bands')
axarr[0][1].legend(loc='best')
[ax[0].set_ylabel('Relative incidence') for ax in axarr]
[ax.set_xlabel('Time after exposure start') for ax in axarr[-1]]
if remove_last_plot:
fig.delaxes(axarr[-1][-1])
plt.show()
normalize = lambda x: x / np.sum(x)
m = np.repeat(np.hstack(refitted_coeffs[-6:]), 125)
lb = np.repeat(np.hstack(lower_bound[-6:]), 125)
ub = np.repeat(np.hstack(upper_bound[-6:]), 125)
plt.figure()
plt.plot(np.arange(n_intervals),
normalize(np.exp(time_drift(np.arange(n_intervals)))))
plt.step(np.arange(n_intervals), normalize(np.exp(m)))
plt.fill_between(np.arange(n_intervals), np.exp(lb) / np.exp(m).sum(),
np.exp(ub) / np.exp(m).sum(), alpha=.5, color='orange',
step='pre')
plt.xlabel('Age')
plt.ylabel('Normalized Age Relative Incidence')
plt.title("Normalized age effect with 95% confidence bands");
plt.show()
|
[
"numpy.sum",
"numpy.sin",
"matplotlib.pylab.suptitle",
"numpy.arange",
"numpy.exp",
"matplotlib.pylab.title",
"matplotlib.pylab.subplots",
"matplotlib.pylab.figure",
"matplotlib.pylab.show",
"tick.survival.SimuSCCS",
"numpy.repeat",
"numpy.ceil",
"numpy.hstack",
"scipy.sparse.csr_matrix",
"matplotlib.pylab.ylabel",
"matplotlib.pylab.xlabel",
"mpl_toolkits.axes_grid1.make_axes_locatable",
"numpy.log",
"numpy.zeros",
"tick.survival.simu_sccs.CustomEffects",
"scipy.sparse.hstack"
] |
[((903, 926), 'tick.survival.simu_sccs.CustomEffects', 'CustomEffects', (['(lags + 1)'], {}), '(lags + 1)\n', (916, 926), False, 'from tick.survival.simu_sccs import CustomEffects\n'), ((1422, 1565), 'tick.survival.SimuSCCS', 'SimuSCCS', (['n_samples', 'n_intervals', 'n_features', 'n_lags'], {'time_drift': 'time_drift', 'coeffs': 'coeffs', 'seed': 'seed', 'n_correlations': 'n_corr', 'verbose': '(False)'}), '(n_samples, n_intervals, n_features, n_lags, time_drift=time_drift,\n coeffs=coeffs, seed=seed, n_correlations=n_corr, verbose=False)\n', (1430, 1565), False, 'from tick.survival import SimuSCCS, ConvSCCS\n'), ((1738, 1766), 'matplotlib.pylab.subplots', 'plt.subplots', ([], {'figsize': '(7, 6)'}), '(figsize=(7, 6))\n', (1750, 1766), True, 'import matplotlib.pylab as plt\n'), ((1846, 1869), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (1865, 1869), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((2021, 2031), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (2029, 2031), True, 'import matplotlib.pylab as plt\n'), ((2169, 2203), 'numpy.zeros', 'np.zeros', (['(n_intervals, n_agegrps)'], {}), '((n_intervals, n_agegrps))\n', (2177, 2203), True, 'import numpy as np\n'), ((2296, 2319), 'scipy.sparse.csr_matrix', 'csr_matrix', (['feat_agegrp'], {}), '(feat_agegrp)\n', (2306, 2319), False, 'from scipy.sparse import csr_matrix, hstack\n'), ((4237, 4303), 'matplotlib.pylab.subplots', 'plt.subplots', (['n_rows', '(2)'], {'sharex': '(True)', 'sharey': '(True)', 'figsize': '(10, 6)'}), '(n_rows, 2, sharex=True, sharey=True, figsize=(10, 6))\n', (4249, 4303), True, 'import matplotlib.pylab as plt\n'), ((4768, 4834), 'matplotlib.pylab.suptitle', 'plt.suptitle', (['"""Estimated relative risks with 95% confidence bands"""'], {}), "('Estimated relative risks with 95% confidence bands')\n", (4780, 4834), True, 'import matplotlib.pylab as plt\n'), ((5040, 5050), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (5048, 5050), True, 'import matplotlib.pylab as plt\n'), ((5238, 5250), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (5248, 5250), True, 'import matplotlib.pylab as plt\n'), ((5576, 5593), 'matplotlib.pylab.xlabel', 'plt.xlabel', (['"""Age"""'], {}), "('Age')\n", (5586, 5593), True, 'import matplotlib.pylab as plt\n'), ((5594, 5641), 'matplotlib.pylab.ylabel', 'plt.ylabel', (['"""Normalized Age Relative Incidence"""'], {}), "('Normalized Age Relative Incidence')\n", (5604, 5641), True, 'import matplotlib.pylab as plt\n'), ((5642, 5702), 'matplotlib.pylab.title', 'plt.title', (['"""Normalized age effect with 95% confidence bands"""'], {}), "('Normalized age effect with 95% confidence bands')\n", (5651, 5702), True, 'import matplotlib.pylab as plt\n'), ((5704, 5714), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (5712, 5714), True, 'import matplotlib.pylab as plt\n'), ((1246, 1255), 'numpy.log', 'np.log', (['c'], {}), '(c)\n', (1252, 1255), True, 'import numpy as np\n'), ((4157, 4180), 'numpy.ceil', 'np.ceil', (['(n_features / 2)'], {}), '(n_features / 2)\n', (4164, 4180), True, 'import numpy as np\n'), ((5102, 5133), 'numpy.hstack', 'np.hstack', (['refitted_coeffs[-6:]'], {}), '(refitted_coeffs[-6:])\n', (5111, 5133), True, 'import numpy as np\n'), ((5155, 5182), 'numpy.hstack', 'np.hstack', (['lower_bound[-6:]'], {}), '(lower_bound[-6:])\n', (5164, 5182), True, 'import numpy as np\n'), ((5204, 5231), 'numpy.hstack', 'np.hstack', (['upper_bound[-6:]'], {}), '(upper_bound[-6:])\n', (5213, 5231), True, 'import numpy as np\n'), ((5260, 5282), 'numpy.arange', 'np.arange', (['n_intervals'], {}), '(n_intervals)\n', (5269, 5282), True, 'import numpy as np\n'), ((5357, 5379), 'numpy.arange', 'np.arange', (['n_intervals'], {}), '(n_intervals)\n', (5366, 5379), True, 'import numpy as np\n'), ((5420, 5442), 'numpy.arange', 'np.arange', (['n_intervals'], {}), '(n_intervals)\n', (5429, 5442), True, 'import numpy as np\n'), ((1190, 1217), 'numpy.repeat', 'np.repeat', (['lags', 'n_features'], {}), '(lags, n_features)\n', (1199, 1217), True, 'import numpy as np\n'), ((2515, 2534), 'numpy.zeros', 'np.zeros', (['n_agegrps'], {}), '(n_agegrps)\n', (2523, 2534), True, 'import numpy as np\n'), ((3595, 3616), 'numpy.arange', 'np.arange', (['n_features'], {}), '(n_features)\n', (3604, 3616), True, 'import numpy as np\n'), ((4518, 4535), 'numpy.exp', 'np.exp', (['coeffs[i]'], {}), '(coeffs[i])\n', (4524, 4535), True, 'import numpy as np\n'), ((4566, 4582), 'numpy.arange', 'np.arange', (['(l + 1)'], {}), '(l + 1)\n', (4575, 4582), True, 'import numpy as np\n'), ((4584, 4593), 'numpy.exp', 'np.exp', (['c'], {}), '(c)\n', (4590, 4593), True, 'import numpy as np\n'), ((4637, 4653), 'numpy.arange', 'np.arange', (['(l + 1)'], {}), '(l + 1)\n', (4646, 4653), True, 'import numpy as np\n'), ((4655, 4668), 'numpy.exp', 'np.exp', (['lb[i]'], {}), '(lb[i])\n', (4661, 4668), True, 'import numpy as np\n'), ((4670, 4683), 'numpy.exp', 'np.exp', (['ub[i]'], {}), '(ub[i])\n', (4676, 4683), True, 'import numpy as np\n'), ((5078, 5087), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (5084, 5087), True, 'import numpy as np\n'), ((5391, 5400), 'numpy.exp', 'np.exp', (['m'], {}), '(m)\n', (5397, 5400), True, 'import numpy as np\n'), ((5444, 5454), 'numpy.exp', 'np.exp', (['lb'], {}), '(lb)\n', (5450, 5454), True, 'import numpy as np\n'), ((5491, 5501), 'numpy.exp', 'np.exp', (['ub'], {}), '(ub)\n', (5497, 5501), True, 'import numpy as np\n'), ((2332, 2356), 'scipy.sparse.hstack', 'hstack', (['[f, feat_agegrp]'], {}), '([f, feat_agegrp])\n', (2338, 2356), False, 'from scipy.sparse import csr_matrix, hstack\n'), ((2405, 2429), 'scipy.sparse.hstack', 'hstack', (['[f, feat_agegrp]'], {}), '([f, feat_agegrp])\n', (2411, 2429), False, 'from scipy.sparse import csr_matrix, hstack\n'), ((1365, 1381), 'numpy.sin', 'np.sin', (['(0.01 * t)'], {}), '(0.01 * t)\n', (1371, 1381), True, 'import numpy as np\n'), ((5321, 5343), 'numpy.arange', 'np.arange', (['n_intervals'], {}), '(n_intervals)\n', (5330, 5343), True, 'import numpy as np\n'), ((5457, 5466), 'numpy.exp', 'np.exp', (['m'], {}), '(m)\n', (5463, 5466), True, 'import numpy as np\n'), ((5504, 5513), 'numpy.exp', 'np.exp', (['m'], {}), '(m)\n', (5510, 5513), True, 'import numpy as np\n')]
|
"""Test the search API."""
from functools import partial
import os
import unittest
import jax
import jax.numpy as jnp
from jax.interpreters.pxla import Chunked, NoSharding, Replicated, ShardedAxis
import numpy as np
from flax import linen as nn
from flax import optim
import ray
import alpa
from alpa import parallelize, global_config, testing, PhysicalDeviceMesh, DeviceCluster
def get_number_of_lines(filename):
ct = 0
for _ in open(filename):
ct += 1
return ct
class SearchAPITest(unittest.TestCase):
def setUp(self):
os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
ray.init(address="auto", ignore_reinit_error=True)
def tearDown(self):
ray.shutdown()
def run_2_layer_mlp(self, batch_size, hidden_dim):
class Model(nn.Module):
@nn.compact
def __call__(self, x):
x = nn.Dense(features=hidden_dim)(x)
x = nn.Dense(features=hidden_dim)(x)
return x
@parallelize
def train_step(optimizer, batch, apply_fn):
def loss_func(params):
out = apply_fn(params, batch["x"])
return jnp.mean((out - batch["y"])**2)
grad = jax.grad(loss_func)(optimizer.target)
new_optimizer = optimizer.apply_gradient(grad)
return new_optimizer
x = jnp.ones((batch_size, hidden_dim))
y = jnp.ones((batch_size, hidden_dim))
# Init model and optimizer
model = Model()
rngkey = jax.random.PRNGKey(0)
params = model.init(rngkey, x)
optimizer = optim.GradientDescent(1e-2).create(params)
# Compile and run
optimizer = train_step(optimizer, {"x": x, "y": y}, model.apply)
def test_search_single_host(self):
alpa.set_parallelize_options(
devices=jax.devices(),
search_logical_mesh_shape=True,
mesh_shape_search_mode="measurement",
)
self.run_2_layer_mlp(batch_size=16, hidden_dim=64)
@unittest.skip("This test is broken due to unhandled cuda error in nccl.")
def test_search_multi_host(self):
physical_mesh = DeviceCluster().get_physical_mesh()
alpa.set_parallelize_options(
devices=physical_mesh,
search_logical_mesh_shape=True,
mesh_shape_search_mode="measurement",
)
self.run_2_layer_mlp(batch_size=16, hidden_dim=64)
physical_mesh.shutdown()
@unittest.skip("This test is broken due to unsupported collective permute.")
def test_measurement_record(self):
filename = "tmp.json"
alpa.set_parallelize_options(
devices=jax.devices(),
search_logical_mesh_shape=True,
mesh_shape_search_mode="measurement",
mesh_shape_search_log_file=filename,
)
if os.path.exists(filename):
os.remove(filename)
# Run search and dump results into the file
self.run_2_layer_mlp(batch_size=16, hidden_dim=64)
before = get_number_of_lines(filename)
# Load the results without search
self.run_2_layer_mlp(batch_size=16, hidden_dim=64)
after = get_number_of_lines(filename)
# The second call should not generate new records
assert before == after
def suite():
suite = unittest.TestSuite()
suite.addTest(SearchAPITest("test_search_single_host"))
suite.addTest(SearchAPITest("test_search_multi_host"))
suite.addTest(SearchAPITest("test_measurement_record"))
return suite
if __name__ == "__main__":
runner = unittest.TextTestRunner()
runner.run(suite())
|
[
"ray.init",
"os.remove",
"alpa.set_parallelize_options",
"unittest.TextTestRunner",
"unittest.TestSuite",
"flax.linen.Dense",
"alpa.DeviceCluster",
"os.path.exists",
"flax.optim.GradientDescent",
"unittest.skip",
"jax.random.PRNGKey",
"ray.shutdown",
"jax.grad",
"jax.numpy.ones",
"jax.numpy.mean",
"jax.devices"
] |
[((2048, 2121), 'unittest.skip', 'unittest.skip', (['"""This test is broken due to unhandled cuda error in nccl."""'], {}), "('This test is broken due to unhandled cuda error in nccl.')\n", (2061, 2121), False, 'import unittest\n'), ((2498, 2573), 'unittest.skip', 'unittest.skip', (['"""This test is broken due to unsupported collective permute."""'], {}), "('This test is broken due to unsupported collective permute.')\n", (2511, 2573), False, 'import unittest\n'), ((3363, 3383), 'unittest.TestSuite', 'unittest.TestSuite', ([], {}), '()\n', (3381, 3383), False, 'import unittest\n'), ((3622, 3647), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {}), '()\n', (3645, 3647), False, 'import unittest\n'), ((624, 674), 'ray.init', 'ray.init', ([], {'address': '"""auto"""', 'ignore_reinit_error': '(True)'}), "(address='auto', ignore_reinit_error=True)\n", (632, 674), False, 'import ray\n'), ((708, 722), 'ray.shutdown', 'ray.shutdown', ([], {}), '()\n', (720, 722), False, 'import ray\n'), ((1382, 1416), 'jax.numpy.ones', 'jnp.ones', (['(batch_size, hidden_dim)'], {}), '((batch_size, hidden_dim))\n', (1390, 1416), True, 'import jax.numpy as jnp\n'), ((1429, 1463), 'jax.numpy.ones', 'jnp.ones', (['(batch_size, hidden_dim)'], {}), '((batch_size, hidden_dim))\n', (1437, 1463), True, 'import jax.numpy as jnp\n'), ((1541, 1562), 'jax.random.PRNGKey', 'jax.random.PRNGKey', (['(0)'], {}), '(0)\n', (1559, 1562), False, 'import jax\n'), ((2229, 2354), 'alpa.set_parallelize_options', 'alpa.set_parallelize_options', ([], {'devices': 'physical_mesh', 'search_logical_mesh_shape': '(True)', 'mesh_shape_search_mode': '"""measurement"""'}), "(devices=physical_mesh,\n search_logical_mesh_shape=True, mesh_shape_search_mode='measurement')\n", (2257, 2354), False, 'import alpa\n'), ((2881, 2905), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (2895, 2905), False, 'import os\n'), ((2919, 2938), 'os.remove', 'os.remove', (['filename'], {}), '(filename)\n', (2928, 2938), False, 'import os\n'), ((1187, 1220), 'jax.numpy.mean', 'jnp.mean', (["((out - batch['y']) ** 2)"], {}), "((out - batch['y']) ** 2)\n", (1195, 1220), True, 'import jax.numpy as jnp\n'), ((1239, 1258), 'jax.grad', 'jax.grad', (['loss_func'], {}), '(loss_func)\n', (1247, 1258), False, 'import jax\n'), ((1622, 1649), 'flax.optim.GradientDescent', 'optim.GradientDescent', (['(0.01)'], {}), '(0.01)\n', (1643, 1649), False, 'from flax import optim\n'), ((1863, 1876), 'jax.devices', 'jax.devices', ([], {}), '()\n', (1874, 1876), False, 'import jax\n'), ((2184, 2199), 'alpa.DeviceCluster', 'DeviceCluster', ([], {}), '()\n', (2197, 2199), False, 'from alpa import parallelize, global_config, testing, PhysicalDeviceMesh, DeviceCluster\n'), ((2701, 2714), 'jax.devices', 'jax.devices', ([], {}), '()\n', (2712, 2714), False, 'import jax\n'), ((892, 921), 'flax.linen.Dense', 'nn.Dense', ([], {'features': 'hidden_dim'}), '(features=hidden_dim)\n', (900, 921), True, 'from flax import linen as nn\n'), ((945, 974), 'flax.linen.Dense', 'nn.Dense', ([], {'features': 'hidden_dim'}), '(features=hidden_dim)\n', (953, 974), True, 'from flax import linen as nn\n')]
|
import os
import json
import argparse
import csv
import time
import pandas as pd
from werkzeug.utils import secure_filename
from flask import render_template, jsonify, flash
from flask import Flask, request, redirect, send_from_directory
import sys
import pathlib
path = pathlib.Path(__file__)
sys.path.append(os.path.join(str(path.parent.parent), "inference/"))
from sentiment import Sentiment
from process import single_process, batch_process
# initialize a flask object
app = Flask(__name__)
app.config['SECRET_KEY'] = "plpsystemkey"
app.config['UPLOAD_FOLDER'] = 'upload'
app.config['SESSION_TYPE'] = 'filesystem'
ALLOWED_EXTENSIONS = {'csv'}
database = []
length = 0
sentiment = Sentiment()
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route("/error")
def error():
return render_template("error.html")
@app.route("/")
def index():
database = []
with open('./webapp/data/progress.csv','r', encoding="utf8") as data:
reader = csv.reader(data)
next(reader, None) # skip the headers
for line in reader:
database.append(line)
try:
database[0]
except IndexError:
return redirect("/error")
length = len(database)
# return the rendered template
return render_template("index.html", data=database, len=length)
@app.route('/data/<path:filename>')
def base_static(filename):
image_file = os.path.join(app.root_path + '/data/', filename)
# check whether file exist
if os.path.isfile(image_file):
return send_from_directory(app.root_path + '/data', filename)
else:
return send_from_directory(app.root_path + '/static/img', 'not_found.jpg')
#---------------------------------------------------------------------
#----------------------------Functions--------------------------------
#---------------------------------------------------------------------
@app.route('/upload',methods = ['POST', 'GET'])
def upload():
if request.method == "POST":
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect("/")
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
flash('No selected file')
return redirect("/")
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# process batch file
result = batch_process(sentiment, filename)
if result == "success":
flash('file uploaded and process successful.')
else:
flash('file uploaded or process failed.')
return redirect("/")
else:
flash('No allow file format')
return redirect("/")
@app.route('/process', methods = ['POST', 'GET'])
def process():
if request.method == "POST":
review = request.form['review']
# Get Polarity for single review
polarity = single_process(sentiment, review.strip())
output = {"data": polarity}
return jsonify(output)
# execute function
if __name__ == '__main__':
# construct the argument parser and parse command line arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--ip", type=str, default="127.0.0.1", help="ip address")
ap.add_argument("-o", "--port", type=int, default=8000, help="port number of the server")
args = vars(ap.parse_args())
# start the flask app
app.run(host=args["ip"], port=args["port"], debug=True, threaded=True, use_reloader=False)
|
[
"flask.flash",
"csv.reader",
"argparse.ArgumentParser",
"sentiment.Sentiment",
"flask.redirect",
"flask.Flask",
"werkzeug.utils.secure_filename",
"pathlib.Path",
"os.path.isfile",
"flask.jsonify",
"process.batch_process",
"flask.render_template",
"flask.send_from_directory",
"os.path.join"
] |
[((273, 295), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (285, 295), False, 'import pathlib\n'), ((483, 498), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (488, 498), False, 'from flask import Flask, request, redirect, send_from_directory\n'), ((690, 701), 'sentiment.Sentiment', 'Sentiment', ([], {}), '()\n', (699, 701), False, 'from sentiment import Sentiment\n'), ((878, 907), 'flask.render_template', 'render_template', (['"""error.html"""'], {}), "('error.html')\n", (893, 907), False, 'from flask import render_template, jsonify, flash\n'), ((1336, 1392), 'flask.render_template', 'render_template', (['"""index.html"""'], {'data': 'database', 'len': 'length'}), "('index.html', data=database, len=length)\n", (1351, 1392), False, 'from flask import render_template, jsonify, flash\n'), ((1474, 1522), 'os.path.join', 'os.path.join', (["(app.root_path + '/data/')", 'filename'], {}), "(app.root_path + '/data/', filename)\n", (1486, 1522), False, 'import os\n'), ((1561, 1587), 'os.path.isfile', 'os.path.isfile', (['image_file'], {}), '(image_file)\n', (1575, 1587), False, 'import os\n'), ((3497, 3522), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3520, 3522), False, 'import argparse\n'), ((1047, 1063), 'csv.reader', 'csv.reader', (['data'], {}), '(data)\n', (1057, 1063), False, 'import csv\n'), ((1604, 1658), 'flask.send_from_directory', 'send_from_directory', (["(app.root_path + '/data')", 'filename'], {}), "(app.root_path + '/data', filename)\n", (1623, 1658), False, 'from flask import Flask, request, redirect, send_from_directory\n'), ((1684, 1751), 'flask.send_from_directory', 'send_from_directory', (["(app.root_path + '/static/img')", '"""not_found.jpg"""'], {}), "(app.root_path + '/static/img', 'not_found.jpg')\n", (1703, 1751), False, 'from flask import Flask, request, redirect, send_from_directory\n'), ((3355, 3370), 'flask.jsonify', 'jsonify', (['output'], {}), '(output)\n', (3362, 3370), False, 'from flask import render_template, jsonify, flash\n'), ((1242, 1260), 'flask.redirect', 'redirect', (['"""/error"""'], {}), "('/error')\n", (1250, 1260), False, 'from flask import Flask, request, redirect, send_from_directory\n'), ((2167, 2188), 'flask.flash', 'flash', (['"""No file part"""'], {}), "('No file part')\n", (2172, 2188), False, 'from flask import render_template, jsonify, flash\n'), ((2208, 2221), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (2216, 2221), False, 'from flask import Flask, request, redirect, send_from_directory\n'), ((2422, 2447), 'flask.flash', 'flash', (['"""No selected file"""'], {}), "('No selected file')\n", (2427, 2447), False, 'from flask import render_template, jsonify, flash\n'), ((2469, 2482), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (2477, 2482), False, 'from flask import Flask, request, redirect, send_from_directory\n'), ((2556, 2586), 'werkzeug.utils.secure_filename', 'secure_filename', (['file.filename'], {}), '(file.filename)\n', (2571, 2586), False, 'from werkzeug.utils import secure_filename\n'), ((2729, 2763), 'process.batch_process', 'batch_process', (['sentiment', 'filename'], {}), '(sentiment, filename)\n', (2742, 2763), False, 'from process import single_process, batch_process\n'), ((2958, 2971), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (2966, 2971), False, 'from flask import Flask, request, redirect, send_from_directory\n'), ((2998, 3027), 'flask.flash', 'flash', (['"""No allow file format"""'], {}), "('No allow file format')\n", (3003, 3027), False, 'from flask import render_template, jsonify, flash\n'), ((3047, 3060), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (3055, 3060), False, 'from flask import Flask, request, redirect, send_from_directory\n'), ((2609, 2660), 'os.path.join', 'os.path.join', (["app.config['UPLOAD_FOLDER']", 'filename'], {}), "(app.config['UPLOAD_FOLDER'], filename)\n", (2621, 2660), False, 'import os\n'), ((2816, 2862), 'flask.flash', 'flash', (['"""file uploaded and process successful."""'], {}), "('file uploaded and process successful.')\n", (2821, 2862), False, 'from flask import render_template, jsonify, flash\n'), ((2897, 2938), 'flask.flash', 'flash', (['"""file uploaded or process failed."""'], {}), "('file uploaded or process failed.')\n", (2902, 2938), False, 'from flask import render_template, jsonify, flash\n')]
|
"""
This examples loads a pre-trained model and evaluates it on the STSbenchmark dataset
Usage:
python evaluation_stsbenchmark.py
OR
python evaluation_stsbenchmark.py model_name
"""
from torch.utils.data import DataLoader
from sentence_transformers import SentenceTransformer, SentencesDataset, LoggingHandler
from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator
from sentence_transformers.readers import STSBenchmarkDataReader
import logging
import sys
import os
import torch
script_folder_path = os.path.dirname(os.path.realpath(__file__))
#Limit torch to 4 threads
torch.set_num_threads(4)
#### Just some code to print debug information to stdout
logging.basicConfig(format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO,
handlers=[LoggingHandler()])
#### /print debug information to stdout
model_name = sys.argv[1] if len(sys.argv) > 1 else 'bert-base-nli-mean-tokens'
# Load a named sentence model (based on BERT). This will download the model from our server.
# Alternatively, you can also pass a filepath to SentenceTransformer()
model = SentenceTransformer(model_name)
sts_reader = STSBenchmarkDataReader(os.path.join(script_folder_path, '../datasets/stsbenchmark'))
evaluator = EmbeddingSimilarityEvaluator.from_input_examples(sts_reader.get_examples("sts-test.csv"))
model.evaluate(evaluator)
|
[
"os.path.realpath",
"sentence_transformers.LoggingHandler",
"torch.set_num_threads",
"os.path.join",
"sentence_transformers.SentenceTransformer"
] |
[((593, 617), 'torch.set_num_threads', 'torch.set_num_threads', (['(4)'], {}), '(4)\n', (614, 617), False, 'import torch\n'), ((1163, 1194), 'sentence_transformers.SentenceTransformer', 'SentenceTransformer', (['model_name'], {}), '(model_name)\n', (1182, 1194), False, 'from sentence_transformers import SentenceTransformer, SentencesDataset, LoggingHandler\n'), ((538, 564), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (554, 564), False, 'import os\n'), ((1232, 1292), 'os.path.join', 'os.path.join', (['script_folder_path', '"""../datasets/stsbenchmark"""'], {}), "(script_folder_path, '../datasets/stsbenchmark')\n", (1244, 1292), False, 'import os\n'), ((851, 867), 'sentence_transformers.LoggingHandler', 'LoggingHandler', ([], {}), '()\n', (865, 867), False, 'from sentence_transformers import SentenceTransformer, SentencesDataset, LoggingHandler\n')]
|
import numpy, math
from params_geo import *
import nanopores.py4gmsh.basic
import nanopores.py4gmsh.extra
from nanopores.py4gmsh import *
from warnings import warn
def get_geo(x0 = None, crosssections = True, exit_i = None, **params):
"""
writes a 3d geo file for an extruded axissymmetric geometry
for Howorka 'Self-Assembled aHem that spans lipid bilayers'
_________
| |
| _ |
| | |____|
| | |____|
| |_| |
| |
|________| *rotated around y-axis *
"""
reload(nanopores.py4gmsh.basic)
reload(nanopores.py4gmsh.extra)
globals().update(params)
params["synonymes"] = synonymes
X_aHem = numpy.array([[2.16, 0.0, 0.0],
[2.77, 0.0, -0.19],
[3.24, 0.0, -0.1 ],
[3.59, 0.0, -0.1 ],
[3.83, 0.0, -0.35],
[3.84, 0.0, -0.8 ],
[3.67, 0.0, -1.34],
[3.73, 0.0, -1.96],
[3.93, 0.0, -2.31],
[4.23, 0.0, -2.67],
[4.44, 0.0, -2.81],
[4.33, 0.0, -3.25],
[4.01, 0.0, -3.5 ],
[3.99, 0.0, -3.67],
[4.11, 0.0, -3.94],
[4.39, 0.0, -4.12],
[4.44, 0.0, -4.52],
[4.73, 0.0, -4.86],
[4.96, 0.0, -5.41],
[4.89, 0.0, -5.87],
[4.63, 0.0, -6.44],
[4.43, 0.0, -6.96],
[4.07, 0.0, -7.32],
[3.71, 0.0, -7.51],
[3.46, 0.0, -7.36],
[3.41, 0.0, -7.1 ],
[3.31, 0.0, -6.9 ],
[3.04, 0.0, -6.87],
[2.73, 0.0, -6.73],
[2.41, 0.0, -6.6 ],
[2.17, 0.0, -6.41],
[1.97, 0.0, -6.23],
[1.84, 0.0, -6.03],
[1.76, 0.0, -5.87],
[1.54, 0.0, -5.87],
[1.4 , 0.0, -5.96],
[1.31, 0.0, -6.16],
[1.39, 0.0, -6.57],
[1.6 , 0.0, -6.81],
[1.71, 0.0, -7.09],
[1.76, 0.0, -7.32],
[1.67, 0.0, -7.65],
[1.44, 0.0, -7.81],
[1.49, 0.0, -8.06],
[1.56, 0.0, -8.36],
[1.44, 0.0, -8.61],
[1.43, 0.0, -8.79],
[1.44, 0.0, -9.1 ],
[1.6 , 0.0, -9.48],
[1.74, 0.0, -9.84],
[1.63, 0.0, -10.0],
[1.47, 0.0, -10.19],
[1.26, 0.0, -10.21],
[1.07, 0.0, -10.05],
[1.03, 0.0, -9.76],
[1.09, 0.0, -9.44],
[1.07, 0.0, -9.02],
[0.86, 0.0, -8.79],
[0.64, 0.0, -8.68],
[0.63, 0.0, -8.36],
[0.8 , 0.0, -8.22],
[0.81, 0.0, -7.93],
[0.89, 0.0, -7.71],
[1.04, 0.0, -7.51],
[1.1 , 0.0, -7.25],
[0.91, 0.0, -7.02],
[0.91, 0.0, -6.76],
[0.91, 0.0, -6.48],
[0.69, 0.0, -6.25],
[0.69, 0.0, -6. ],
[0.66, 0.0, -5.68],
[0.59, 0.0, -5.36],
[0.53, 0.0, -5.12],
[0.54, 0.0, -4.92],
[0.79, 0.0, -4.84],
[1.03, 0.0, -4.89],
[1.21, 0.0, -4.7 ],
[1.36, 0.0, -4.42],
[1.49, 0.0, -4.16],
[1.66, 0.0, -3.92],
[1.66, 0.0, -3.7 ],
[1.8 , 0.0, -3.41],
[2. , 0.0, -3.22],
[1.91, 0.0, -2.93],
[1.8 , 0.0, -2.71],
[1.56, 0.0, -2.55],
[1.46, 0.0, -2.38],
[1.3 , 0.0, -2.19],
[1.21, 0.0, -1.93],
[1.09, 0.0, -1.64],
[0.9 , 0.0, -1.45],
[0.8 , 0.0, -1.28],
[0.84, 0.0, -1. ],
[1. , 0.0, -0.8 ],
[1.26, 0.0, -0.64],
[1.7 , 0.0, -0.31]])
#Anchor Points on aHem for membran (index)
ap1 = 18
ap2 = 49
apdiff=ap2-ap1
#Anchor Points in aHem for CrossS (index)
ac1 = 52
ac2 = 68
ac3 = 82
ac4 = 0
zcross = sorted([X_aHem[i][2] for i in [ac1, ac2, ac3, ac4]])
params["lbtm"] = -zcross[0] + zcross[1]
params["lctr"] = -zcross[1] + zcross[2]
params["ltop"] = -zcross[2] + zcross[3]
params["zporetop"] = zcross[3]
params["zporebtm"] = zcross[0]
params["ztop"] = params["zporetop"] + l3
params["zbtm"] = params["zporebtm"] - l4
r0=max([X_aHem[index][0] for index in [ac1, ac2, ac3, ac4]])+rMolecule
X_Fluid_ext = numpy.array([[0.0, 0.0, l3],
[R, 0.0, l3],
[R, 0.0, X_aHem[ap1][2]],
[R, 0.0, X_aHem[ap2][2]],
[R, 0.0, -l0-l1-l4],
[0.0, 0.0, -l0-l1-l4]])
X_Fluid_ctr = numpy.array([[0.0, 0.0, X_aHem[ac1][2]],
[0.0, 0.0, X_aHem[ac2][2]],
[0.0, 0.0, X_aHem[ac3][2]],
[0.0, 0.0, X_aHem[ac4][2]]])
p_Fluid = [Point(x, lcOuter) for x in X_Fluid_ext]
p_Fluid.extend([Point(y, lcCenter) for y in X_Fluid_ctr])
p_aHem = [Point(x, lcCenter) for x in X_aHem]
#Create Line Loops from the points sitting on the line
Comment(' Connect all Fluid points ')
e_Fluid = [Line(p_Fluid[k], p_Fluid[k+1]) for k in range(len(p_Fluid)-1)]
e_Fluid.append(Line(p_Fluid[-1], p_Fluid[0]))
Comment(' Connect all aHem points ')
e_aHem = [Line(p_aHem[k], p_aHem[k+1]) for k in range(len(p_aHem)-1)]
e_aHem.append(Line(p_aHem[-1], p_aHem[0]))
# e_Membrane = [Line(p_aHem[ap1],p_Fluid[2]), Line(p_Fluid[3], p_aHem[ap2])]
e_Membrane = [Line(Point(X_aHem[ap1],lcMembrane), Point(numpy.array([R,0.,X_aHem[ap1][2]]),lcMembrane)),\
Line(Point(numpy.array([R,0.,X_aHem[ap2][2]]),lcMembrane),Point(X_aHem[ap2],lcMembrane))]
edges_to_rot = [e_Fluid[0:5], e_aHem, e_Membrane]
geo_cs_str = "no crosssectional surface"
if crosssections:
Comment(' integrate crosssectional lines in fluid and check if molecule intersects lines')
e_CrossS = [Line(p_aHem[ac1], p_Fluid[6]), Line(p_aHem[ac2], p_Fluid[7]), Line(p_aHem[ac3], p_Fluid[8]), Line(p_aHem[ac4], p_Fluid[9])]
cs_pop_i = None
# check if molecule is near pore
if x0 is not None and (x0[0]**2 + x0[1]**2 <= r0**2):
# check z coordinate of molecule
if abs(x0[2] - X_aHem[ac4][2]) < rMolecule:
geo_cs_str = "top crosssection"
cs_pop_i = -1
elif abs(x0[2] - X_aHem[ac3][2]) < rMolecule:
geo_cs_str = "center top crosssection"
cs_pop_i = 2
elif abs(x0[2] - X_aHem[ac2][2]) < rMolecule:
geo_cs_str = "center bottom crosssection"
cs_pop_i = 1
elif abs(x0[2] - X_aHem[ac1][2]) < rMolecule:
geo_cs_str = "bottom crosssection"
cs_pop_i = 0
if cs_pop_i is not None:
e_CrossS.pop(cs_pop_i)
if cs_pop_i == 0:
top_acdiff = len(X_aHem)-ap1
bottom_end = ac2
elif cs_pop_i == 1:
top_acdiff = len(X_aHem)-ap1
bottom_end = ac3
elif cs_pop_i == 2:
top_acdiff = ac2-ap1
bottom_end = ac1
elif cs_pop_i == -1:
top_acdiff = ac3-ap1
bottom_end = ac1
edges_to_rot.append(e_CrossS)
top_acdiff = len(X_aHem)-ap1
bottom_end = ac1
rot_axis = [0.0, 0.0, 1.0]
point_on_rot_axis = [0.0, 0.0, 0.0]
# Extrude all edge 4 times Pi/2
surfs = []
angle = 'Pi/2'
n_e = len(edges_to_rot)
n_e_i = [len(edges_to_rot[i]) for i in range(n_e)]
for i in range(n_e):
surfs_i = []
Comment('Extrude in 4 steps around z-axis.')
previous = edges_to_rot[i]
for j in range(4):
Comment('Step %s' % (j+1))
for k in range(len(previous)):
name = Extrude('Line{%s}' % previous[k],
rotation_axis=rot_axis,
point_on_axis=point_on_rot_axis,
angle=angle
)
surfs_i.append(name + '[1]')
previous[k] = name + '[0]'
surfs.append(surfs_i)
# surfs:
# [0] --> outer cylinder <=> e_Fluid
# [1] --> ahem <=> e_aHem
# [2] --> membrane-fluid <=> e_Membrane
# [3] --> crosssections
# TODO: make this all less confusing
surfs_Fluid = surfs[0][:] # [:] is important for a shallow copy (-> del nextline)
surfs_Fluid_bulk_top = surfs[0][:] # prepare for Fluid_bulk
surfs_Fluid_bulk_bottom = surfs[0][:]
del surfs_Fluid[2::n_e_i[0]] # deletes outer membrane boundary (<=> e_Fluid[2])
for index in range(3):
del surfs_Fluid_bulk_top[2::n_e_i[0]-index] # delete equivalent of 2,3,4
del surfs_Fluid_bulk_bottom[0::n_e_i[0]-index] # delete equivalent of 0,1,2
#PhysicalSurface(surfs_Fluid,'fluidb') #Physical Surface Fluid
surfs_boundary_top = [surfs[0][s*5] for s in range(4)]
surfs_boundary_side_top = [surfs[0][1+s*5] for s in range(4)]
surfs_boundary_side_bottom = [surfs[0][3+s*5] for s in range(4)]
surfs_boundary_bottom = [surfs[0][4+s*5] for s in range(4)]
surfs_Fluid_aHem = surfs[1][:]
surfs_Fluid_aHem_add_top = surfs[1][:] # additional aHem surfs for surfs_Fluid_bulk
surfs_Fluid_aHem_add_bottom = surfs[1][:]
for index in range(apdiff):
del surfs_Fluid_aHem[ap1::n_e_i[1]-index] # deletes membrane
[surfs_Fluid.append(s) for s in surfs_Fluid_aHem]
[surfs_Fluid.append(s) for s in surfs[2]] # <=> surfs_Fluid += surfs[2] TODO
[surfs_Fluid_bulk_top.append(s) for s in [surfs[2][2*s] for s in range(4)]]
[surfs_Fluid_bulk_bottom.append(s) for s in [surfs[2][2*s+1] for s in range(4)]]
for index in range(top_acdiff):
del surfs_Fluid_aHem_add_top[ap1::n_e_i[1]-index]
for index in range(ap2):
del surfs_Fluid_aHem_add_bottom[0::n_e_i[1]-index]
for index in range(len(X_aHem)-bottom_end):
del surfs_Fluid_aHem_add_bottom[ac1-ap2::n_e_i[1]-ap2-index]
[surfs_Fluid_bulk_top.append(s) for s in surfs_Fluid_aHem_add_top]
[surfs_Fluid_bulk_bottom.append(s) for s in surfs_Fluid_aHem_add_bottom]
if cs_pop_i is not None:
if cs_pop_i == 0:
surfs_CrossS_bulk_top = [surfs[3][3+4*s] for s in range (4)]
surfs_CrossS_bulk_bottom = [surfs[3][1+4*s] for s in range (4)]
elif cs_pop_i == 1:
surfs_CrossS_bulk_top = [surfs[3][3+4*s] for s in range (4)]
surfs_CrossS_bulk_bottom = [surfs[3][2+4*s] for s in range (4)]
elif cs_pop_i == 2:
surfs_CrossS_bulk_top = [surfs[3][1+4*s] for s in range (4)]
surfs_CrossS_bulk_bottom = [surfs[3][4*s] for s in range (4)]
elif cs_pop_i == -1:
surfs_CrossS_bulk_top = [surfs[3][2+4*s] for s in range (4)]
surfs_CrossS_bulk_bottom = [surfs[3][4*s] for s in range (4)]
else: # no intersect with any crossS -> remove 2nd and 3rd crossS
surfs_CrossS_bulk_top = [surfs[3][3+4*s] for s in range (4)]
surfs_CrossS_bulk_bottom = [surfs[3][4*s] for s in range (4)]
# exit surface for exit time problem
# exit_i = 0,...,3, None <--> exit surface = pore btm,...,pore top, lowerb
if exit_i is not None and (cs_pop_i is None or cs_pop_i %4 != exit_i):
surfs_exit = [surfs[3][exit_i+4*s] for s in range(4)]
# surfs_exit = list of surfaces
PhysicalSurface(surfs_exit, "poreexit")
exittimeDomain = {"fluid_bulk_top"}
for i in range(3 - exit_i):
exittimeDomain.add(["poretop", "porecenter", "porebottom"][i])
params["synonymes"]["exittime"] = exittimeDomain
else:
params["synonymes"]["poreexit"] = {"lowerbulkb"}
[surfs_Fluid_bulk_top.append(s) for s in surfs_CrossS_bulk_top]
[surfs_Fluid_bulk_bottom.append(s) for s in surfs_CrossS_bulk_bottom]
sl_Fluid = SurfaceLoop(surfs_Fluid)
sl_Fluid_bulk_top = SurfaceLoop(surfs_Fluid_bulk_top)
sl_Fluid_bulk_bottom = SurfaceLoop(surfs_Fluid_bulk_bottom)
surfs_Fluid_bottom = surfs[1][:] # create Fluid_bottom/center/top - the aHem side
for index in range(ac1):
del surfs_Fluid_bottom[0::n_e_i[1]-index]
surfs_Fluid_center = surfs_Fluid_bottom[:]
surfs_Fluid_top = surfs_Fluid_bottom[:]
for index in range(n_e_i[1]-ac2):
del surfs_Fluid_bottom[ac2-ac1::n_e_i[1]-ac1-index]
for index in range(ac2-ac1):
del surfs_Fluid_center[0::n_e_i[1]-ac1-index]
for index in range(n_e_i[1]-ac3):
del surfs_Fluid_center[ac3-ac2::n_e_i[1]-ac2-index]
for index in range(ac3-ac1):
del surfs_Fluid_top[0::n_e_i[1]-ac1-index]
surfs_CrossS_bottom = surfs[3][:] # create Fluid_bottom/center/top - the CrossS side
surfs_CrossS_center = surfs[3][:]
surfs_CrossS_top = surfs[3][:]
del surfs_CrossS_bottom[2::4]
del surfs_CrossS_bottom[2::3]
del surfs_CrossS_center[0::4]
del surfs_CrossS_center[2::3]
del surfs_CrossS_top[0::4]
del surfs_CrossS_top[0::3]
[surfs_Fluid_bottom.append(s) for s in surfs_CrossS_bottom] # combine aHem side and CrossS side for surfs_Fluid_bottom/center/top
[surfs_Fluid_center.append(s) for s in surfs_CrossS_center]
[surfs_Fluid_top.append(s) for s in surfs_CrossS_top]
sl_Fluid_bottom = SurfaceLoop(surfs_Fluid_bottom)
sl_Fluid_center = SurfaceLoop(surfs_Fluid_center)
sl_Fluid_top = SurfaceLoop(surfs_Fluid_top)
PhysicalSurface(surfs_Fluid_aHem,'ahemb') #Physical Surface aHem
PhysicalSurface(surfs_boundary_top,'upperb') # Physical surfaces fluid bottom, side (without membran), top
PhysicalSurface(surfs_boundary_side_top,'uppersideb')
PhysicalSurface(surfs_boundary_side_bottom,'lowersideb')
PhysicalSurface(surfs_boundary_bottom,'lowerb')
sl_aHem = SurfaceLoop(surfs[1])
vol_aHem = Volume(sl_aHem)
surfs_Membrane = surfs[0][2::n_e_i[0]]
for index in range(apdiff):
[surfs_Membrane.append(s) for s in surfs[1][ap1+index::n_e_i[1]]]
[surfs_Membrane.append(s) for s in surfs[2]]
sl_Membrane = SurfaceLoop(surfs_Membrane)
vol_Membrane = Volume(sl_Membrane)
surfs_Membrane_ps = surfs[2]
x0_in_pore = None
if x0 is not None and (x0[0]**2 + x0[1]**2 <= r0**2) and cs_pop_i is None:
# check z coordinate of molecule
if x0[2]<ac4 and x0[2]>ac3:
x0_in_pore = 2 # Molecule is in surfs_Fluid_top
elif x0[2]<ac3 and x0[2]>ac2:
x0_in_pore = 1 # Molecule is in surfs_Fluid_center
elif x0[2]<ac2 and x0[2]>ac1:
x0_in_pore = 0 # Molecule is in surfs_Fluid_bottom
pv_fluid_top, pv_fluid_center, pv_fluid_bottom = True, True, True
if x0 is None:
vol_Fluid = Volume(sl_Fluid)
vol_Fluid_bulk_top = Volume(sl_Fluid_bulk_top)
vol_Fluid_bulk_bottom = Volume(sl_Fluid_bulk_bottom)
vol_Fluid_top = Volume(sl_Fluid_top)
vol_Fluid_center = Volume(sl_Fluid_center)
vol_Fluid_bottom = Volume(sl_Fluid_bottom)
NoPhysicalVolume("molecule")
NoPhysicalSurface("moleculeb")
else:
Comment('Add molecule ball')
Molecule = add_ball(numpy.asarray(x0), rMolecule, lcMolecule,
with_volume=True, holes=None, label=None
)
sl_Fluid_Molecule = Array([sl_Fluid] + [Molecule[1]])
vol_Fluid = Volume(sl_Fluid_Molecule)
# Molecule[0]->Volume, Molecule[1]->surface loop, Molecule[2]->surfs
vol_Molecule = Molecule[0]
PhysicalVolume(vol_Molecule, "molecule")
PhysicalSurface(Molecule[2], "moleculeb")
if x0_in_pore is not None: # NO CrossS and Molecule is in fluid_top/center/bottom
vol_Fluid_bulk_top = Volume(sl_Fluid_bulk_top)
vol_Fluid_bulk_bottom = Volume(sl_Fluid_bulk_bottom)
if x0_in_pore == 2:
sl_Fluid_top_Molecule = Array([sl_Fluid_top] + [Molecule[1]])
vol_Fluid_top = Volume(sl_Fluid_top_Molecule)
vol_Fluid_center = Volume(sl_Fluid_center)
vol_Fluid_bottom = Volume(sl_Fluid_bottom)
elif x0_in_pore == 1:
sl_Fluid_center_Molecule = Array([sl_Fluid_center] + [Molecule[1]])
vol_Fluid_center = Volume(sl_Fluid_center_Molecule)
vol_Fluid_top = Volume(sl_Fluid_top)
vol_Fluid_bottom = Volume(sl_Fluid_bottom)
elif x0_in_pore == 0:
sl_Fluid_bottom_Molecule = Array([sl_Fluid_bottom] + [Molecule[1]])
vol_Fluid_bottom = Volume(sl_Fluid_bottom_Molecule)
vol_Fluid_top = Volume(sl_Fluid_top)
vol_Fluid_center = Volume(sl_Fluid_center)
else:
if cs_pop_i is None: # Molecule is in fluid_bulk
if x0[2]>=X_aHem[ap1][2]:
sl_Fluid_bulk_top_Molecule = Array([sl_Fluid_bulk_top] + [Molecule[1]])
vol_Fluid_bulk_top = Volume(sl_Fluid_bulk_top_Molecule)
vol_Fluid_bulk_bottom = Volume(sl_Fluid_bulk_bottom)
elif x0[2]<=X_aHem[ap2][2]:
sl_Fluid_bulk_bottom_Molecule = Array([sl_Fluid_bulk_bottom] + [Molecule[1]])
vol_Fluid_bulk_bottom = Volume(sl_Fluid_bulk_bottom_Molecule)
vol_Fluid_bulk_top = Volume(sl_Fluid_bulk_top)
vol_Fluid_top = Volume(sl_Fluid_top)
vol_Fluid_center = Volume(sl_Fluid_center)
vol_Fluid_bottom = Volume(sl_Fluid_bottom)
else: # Molecule is in CrossS -> one or two of fluid_top/center/bottom are not going to be defined
if cs_pop_i == -1:
pv_fluid_top = False # fluid_top isn't defined
vol_Fluid_center = Volume(sl_Fluid_center)
vol_Fluid_bottom = Volume(sl_Fluid_bottom)
sl_Fluid_bulk_top_Molecule = Array([sl_Fluid_bulk_top] + [Molecule[1]])
vol_Fluid_bulk_top = Volume(sl_Fluid_bulk_top_Molecule)
vol_Fluid_bulk_bottom = Volume(sl_Fluid_bulk_bottom)
elif cs_pop_i == 2:
pv_fluid_top, pv_fluid_center = False, False # fluid_top/center isn't defined
vol_Fluid_bottom = Volume(sl_Fluid_bottom)
sl_Fluid_bulk_top_Molecule = Array([sl_Fluid_bulk_top] + [Molecule[1]])
vol_Fluid_bulk_top = Volume(sl_Fluid_bulk_top_Molecule)
vol_Fluid_bulk_bottom = Volume(sl_Fluid_bulk_bottom)
elif cs_pop_i == 1:
pv_fluid_center, pv_fluid_bottom = False, False # fluid_center/bottom isn't defined
vol_Fluid_top = Volume(sl_Fluid_top)
sl_Fluid_bulk_bottom_Molecule = Array([sl_Fluid_bulk_bottom] + [Molecule[1]])
vol_Fluid_bulk_bottom = Volume(sl_Fluid_bulk_bottom_Molecule)
vol_Fluid_bulk_top = Volume(sl_Fluid_bulk_top)
elif cs_pop_i == 0:
pv_fluid_bottom = False # fluid_bottom isn't defined
vol_Fluid_top = Volume(sl_Fluid_top)
vol_Fluid_center = Volume(sl_Fluid_center)
sl_Fluid_bulk_bottom_Molecule = Array([sl_Fluid_bulk_bottom] + [Molecule[1]])
vol_Fluid_bulk_bottom = Volume(sl_Fluid_bulk_bottom_Molecule)
vol_Fluid_bulk_top = Volume(sl_Fluid_bulk_top)
PhysicalVolume(vol_Fluid_bulk_top, 'fluid_bulk_top')
PhysicalVolume(vol_Fluid_bulk_bottom, 'fluid_bulk_bottom')
if pv_fluid_top:
PhysicalVolume(vol_Fluid_top, 'poretop')
if pv_fluid_center:
PhysicalVolume(vol_Fluid_center, 'porecenter')
if pv_fluid_bottom:
PhysicalVolume(vol_Fluid_bottom, 'porebottom')
#PhysicalVolume(vol_Fluid, 'fluid')
PhysicalVolume(vol_Membrane, 'membrane')
PhysicalVolume(vol_aHem, "ahem")
PhysicalSurface(surfs_Membrane_ps,'membraneb') #Physical Surface Membrane
if crosssections:
surfs_CrossS = surfs[3]
raw_code(['Surface{%s} In Volume{%s};' \
%(surfs_CrossS[k], vol_Fluid) for k in range(len(surfs_CrossS))])
if membraneblayer == True:
warn('Currently no membrane boundary layers implemented for this geometry')
membraneblayer_list = []
if moleculeblayer and x0 is not None:
moleculeblayer_list = Molecule[2]
else:
moleculeblayer_list = []
blayer_list = moleculeblayer_list + membraneblayer_list
if blayer_list:
blayer = BoundaryLayer(
edges_list=None, faces_list=blayer_list,
hfar=lcOuter, hwall_n=lcCenter*0.1, hwall_t=lcCenter*0.5,
thickness=1, ratio=2)
field_list = [blayer,]
raw_code(['bfield = newf;'])
raw_code(['Field[bfield] = Min;'])
raw_code(['Field[bfield].FieldsList = {%s};' %(','.join(field_list))])
# Uncomment for mesh size field
raw_code(['Background Field = bfield;'])
# to disable question dialogs
raw_code(['General.ExpertMode = 1;'])
# Meshing Algorithm: 2= ?, 5 = frontal (netgen)
#raw_code(['Mesh.Algorithm3D = 5;'])
meta = get_meta()
meta.update(params)
meta["x0"] = x0
geo_dict = {"gmsh mesh generating sript": __name__,
"xMolecule": x0,
#"crosssections": crosssections,
#"Number of crosssections": len(e_CrossS),
#"Total number of crossections": 4,
#"molecule crosses": geo_cs_str,
#"popped crossection index": cs_pop_i,
#"cs_pop_i": cs_pop_i,
"Typical length scale on aHem": lcCenter,
"geo_code": get_code(),
"meta": meta,
}
return geo_dict
# -----
if __name__ == '__main__':
from nanopores.geo2xml import geofile2geo
from dolfin import plot
gdict = get_geo()
geo = geofile2geo(gdict["geo_code"], gdict["meta"], name="alphahem", clscale=8.)
plot(geo.boundaries, interactive=True)
|
[
"numpy.asarray",
"dolfin.plot",
"numpy.array",
"nanopores.geo2xml.geofile2geo",
"warnings.warn"
] |
[((678, 2705), 'numpy.array', 'numpy.array', (['[[2.16, 0.0, 0.0], [2.77, 0.0, -0.19], [3.24, 0.0, -0.1], [3.59, 0.0, -0.1],\n [3.83, 0.0, -0.35], [3.84, 0.0, -0.8], [3.67, 0.0, -1.34], [3.73, 0.0, \n -1.96], [3.93, 0.0, -2.31], [4.23, 0.0, -2.67], [4.44, 0.0, -2.81], [\n 4.33, 0.0, -3.25], [4.01, 0.0, -3.5], [3.99, 0.0, -3.67], [4.11, 0.0, -\n 3.94], [4.39, 0.0, -4.12], [4.44, 0.0, -4.52], [4.73, 0.0, -4.86], [\n 4.96, 0.0, -5.41], [4.89, 0.0, -5.87], [4.63, 0.0, -6.44], [4.43, 0.0, \n -6.96], [4.07, 0.0, -7.32], [3.71, 0.0, -7.51], [3.46, 0.0, -7.36], [\n 3.41, 0.0, -7.1], [3.31, 0.0, -6.9], [3.04, 0.0, -6.87], [2.73, 0.0, -\n 6.73], [2.41, 0.0, -6.6], [2.17, 0.0, -6.41], [1.97, 0.0, -6.23], [1.84,\n 0.0, -6.03], [1.76, 0.0, -5.87], [1.54, 0.0, -5.87], [1.4, 0.0, -5.96],\n [1.31, 0.0, -6.16], [1.39, 0.0, -6.57], [1.6, 0.0, -6.81], [1.71, 0.0, \n -7.09], [1.76, 0.0, -7.32], [1.67, 0.0, -7.65], [1.44, 0.0, -7.81], [\n 1.49, 0.0, -8.06], [1.56, 0.0, -8.36], [1.44, 0.0, -8.61], [1.43, 0.0, \n -8.79], [1.44, 0.0, -9.1], [1.6, 0.0, -9.48], [1.74, 0.0, -9.84], [1.63,\n 0.0, -10.0], [1.47, 0.0, -10.19], [1.26, 0.0, -10.21], [1.07, 0.0, -\n 10.05], [1.03, 0.0, -9.76], [1.09, 0.0, -9.44], [1.07, 0.0, -9.02], [\n 0.86, 0.0, -8.79], [0.64, 0.0, -8.68], [0.63, 0.0, -8.36], [0.8, 0.0, -\n 8.22], [0.81, 0.0, -7.93], [0.89, 0.0, -7.71], [1.04, 0.0, -7.51], [1.1,\n 0.0, -7.25], [0.91, 0.0, -7.02], [0.91, 0.0, -6.76], [0.91, 0.0, -6.48],\n [0.69, 0.0, -6.25], [0.69, 0.0, -6.0], [0.66, 0.0, -5.68], [0.59, 0.0, \n -5.36], [0.53, 0.0, -5.12], [0.54, 0.0, -4.92], [0.79, 0.0, -4.84], [\n 1.03, 0.0, -4.89], [1.21, 0.0, -4.7], [1.36, 0.0, -4.42], [1.49, 0.0, -\n 4.16], [1.66, 0.0, -3.92], [1.66, 0.0, -3.7], [1.8, 0.0, -3.41], [2.0, \n 0.0, -3.22], [1.91, 0.0, -2.93], [1.8, 0.0, -2.71], [1.56, 0.0, -2.55],\n [1.46, 0.0, -2.38], [1.3, 0.0, -2.19], [1.21, 0.0, -1.93], [1.09, 0.0, \n -1.64], [0.9, 0.0, -1.45], [0.8, 0.0, -1.28], [0.84, 0.0, -1.0], [1.0, \n 0.0, -0.8], [1.26, 0.0, -0.64], [1.7, 0.0, -0.31]]'], {}), '([[2.16, 0.0, 0.0], [2.77, 0.0, -0.19], [3.24, 0.0, -0.1], [3.59,\n 0.0, -0.1], [3.83, 0.0, -0.35], [3.84, 0.0, -0.8], [3.67, 0.0, -1.34],\n [3.73, 0.0, -1.96], [3.93, 0.0, -2.31], [4.23, 0.0, -2.67], [4.44, 0.0,\n -2.81], [4.33, 0.0, -3.25], [4.01, 0.0, -3.5], [3.99, 0.0, -3.67], [\n 4.11, 0.0, -3.94], [4.39, 0.0, -4.12], [4.44, 0.0, -4.52], [4.73, 0.0, \n -4.86], [4.96, 0.0, -5.41], [4.89, 0.0, -5.87], [4.63, 0.0, -6.44], [\n 4.43, 0.0, -6.96], [4.07, 0.0, -7.32], [3.71, 0.0, -7.51], [3.46, 0.0, \n -7.36], [3.41, 0.0, -7.1], [3.31, 0.0, -6.9], [3.04, 0.0, -6.87], [2.73,\n 0.0, -6.73], [2.41, 0.0, -6.6], [2.17, 0.0, -6.41], [1.97, 0.0, -6.23],\n [1.84, 0.0, -6.03], [1.76, 0.0, -5.87], [1.54, 0.0, -5.87], [1.4, 0.0, \n -5.96], [1.31, 0.0, -6.16], [1.39, 0.0, -6.57], [1.6, 0.0, -6.81], [\n 1.71, 0.0, -7.09], [1.76, 0.0, -7.32], [1.67, 0.0, -7.65], [1.44, 0.0, \n -7.81], [1.49, 0.0, -8.06], [1.56, 0.0, -8.36], [1.44, 0.0, -8.61], [\n 1.43, 0.0, -8.79], [1.44, 0.0, -9.1], [1.6, 0.0, -9.48], [1.74, 0.0, -\n 9.84], [1.63, 0.0, -10.0], [1.47, 0.0, -10.19], [1.26, 0.0, -10.21], [\n 1.07, 0.0, -10.05], [1.03, 0.0, -9.76], [1.09, 0.0, -9.44], [1.07, 0.0,\n -9.02], [0.86, 0.0, -8.79], [0.64, 0.0, -8.68], [0.63, 0.0, -8.36], [\n 0.8, 0.0, -8.22], [0.81, 0.0, -7.93], [0.89, 0.0, -7.71], [1.04, 0.0, -\n 7.51], [1.1, 0.0, -7.25], [0.91, 0.0, -7.02], [0.91, 0.0, -6.76], [0.91,\n 0.0, -6.48], [0.69, 0.0, -6.25], [0.69, 0.0, -6.0], [0.66, 0.0, -5.68],\n [0.59, 0.0, -5.36], [0.53, 0.0, -5.12], [0.54, 0.0, -4.92], [0.79, 0.0,\n -4.84], [1.03, 0.0, -4.89], [1.21, 0.0, -4.7], [1.36, 0.0, -4.42], [\n 1.49, 0.0, -4.16], [1.66, 0.0, -3.92], [1.66, 0.0, -3.7], [1.8, 0.0, -\n 3.41], [2.0, 0.0, -3.22], [1.91, 0.0, -2.93], [1.8, 0.0, -2.71], [1.56,\n 0.0, -2.55], [1.46, 0.0, -2.38], [1.3, 0.0, -2.19], [1.21, 0.0, -1.93],\n [1.09, 0.0, -1.64], [0.9, 0.0, -1.45], [0.8, 0.0, -1.28], [0.84, 0.0, -\n 1.0], [1.0, 0.0, -0.8], [1.26, 0.0, -0.64], [1.7, 0.0, -0.31]])\n', (689, 2705), False, 'import numpy, math\n'), ((5728, 5880), 'numpy.array', 'numpy.array', (['[[0.0, 0.0, l3], [R, 0.0, l3], [R, 0.0, X_aHem[ap1][2]], [R, 0.0, X_aHem[\n ap2][2]], [R, 0.0, -l0 - l1 - l4], [0.0, 0.0, -l0 - l1 - l4]]'], {}), '([[0.0, 0.0, l3], [R, 0.0, l3], [R, 0.0, X_aHem[ap1][2]], [R, \n 0.0, X_aHem[ap2][2]], [R, 0.0, -l0 - l1 - l4], [0.0, 0.0, -l0 - l1 - l4]])\n', (5739, 5880), False, 'import numpy, math\n'), ((6041, 6171), 'numpy.array', 'numpy.array', (['[[0.0, 0.0, X_aHem[ac1][2]], [0.0, 0.0, X_aHem[ac2][2]], [0.0, 0.0, X_aHem[\n ac3][2]], [0.0, 0.0, X_aHem[ac4][2]]]'], {}), '([[0.0, 0.0, X_aHem[ac1][2]], [0.0, 0.0, X_aHem[ac2][2]], [0.0, \n 0.0, X_aHem[ac3][2]], [0.0, 0.0, X_aHem[ac4][2]]])\n', (6052, 6171), False, 'import numpy, math\n'), ((23498, 23573), 'nanopores.geo2xml.geofile2geo', 'geofile2geo', (["gdict['geo_code']", "gdict['meta']"], {'name': '"""alphahem"""', 'clscale': '(8.0)'}), "(gdict['geo_code'], gdict['meta'], name='alphahem', clscale=8.0)\n", (23509, 23573), False, 'from nanopores.geo2xml import geofile2geo\n'), ((23577, 23615), 'dolfin.plot', 'plot', (['geo.boundaries'], {'interactive': '(True)'}), '(geo.boundaries, interactive=True)\n', (23581, 23615), False, 'from dolfin import plot\n'), ((21778, 21853), 'warnings.warn', 'warn', (['"""Currently no membrane boundary layers implemented for this geometry"""'], {}), "('Currently no membrane boundary layers implemented for this geometry')\n", (21782, 21853), False, 'from warnings import warn\n'), ((16679, 16696), 'numpy.asarray', 'numpy.asarray', (['x0'], {}), '(x0)\n', (16692, 16696), False, 'import numpy, math\n'), ((6963, 7000), 'numpy.array', 'numpy.array', (['[R, 0.0, X_aHem[ap1][2]]'], {}), '([R, 0.0, X_aHem[ap1][2]])\n', (6974, 7000), False, 'import numpy, math\n'), ((7042, 7079), 'numpy.array', 'numpy.array', (['[R, 0.0, X_aHem[ap2][2]]'], {}), '([R, 0.0, X_aHem[ap2][2]])\n', (7053, 7079), False, 'import numpy, math\n')]
|
#!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: aws_application_scaling_policy
short_description: Manage Application Auto Scaling Scaling Policies
notes:
- for details of the parameters and returns see
U(http://boto3.readthedocs.io/en/latest/reference/services/application-autoscaling.html#ApplicationAutoScaling.Client.put_scaling_policy)
description:
- Creates, updates or removes a Scaling Policy
author:
- <NAME> (@gurumaia)
- <NAME> (@chenl87)
requirements: [ json, botocore, boto3 ]
options:
state:
description: Whether a policy should be present or absent
required: yes
choices: ['absent', 'present']
type: str
policy_name:
description: The name of the scaling policy.
required: yes
type: str
service_namespace:
description: The namespace of the AWS service.
required: yes
choices: ['ecs', 'elasticmapreduce', 'ec2', 'appstream', 'dynamodb']
type: str
resource_id:
description: The identifier of the resource associated with the scalable target.
required: yes
type: str
scalable_dimension:
description: The scalable dimension associated with the scalable target.
required: yes
choices: [ 'ecs:service:DesiredCount',
'ec2:spot-fleet-request:TargetCapacity',
'elasticmapreduce:instancegroup:InstanceCount',
'appstream:fleet:DesiredCapacity',
'dynamodb:table:ReadCapacityUnits',
'dynamodb:table:WriteCapacityUnits',
'dynamodb:index:ReadCapacityUnits',
'dynamodb:index:WriteCapacityUnits']
type: str
policy_type:
description: The policy type.
required: yes
choices: ['StepScaling', 'TargetTrackingScaling']
type: str
step_scaling_policy_configuration:
description: A step scaling policy. This parameter is required if you are creating a policy and the policy type is StepScaling.
required: no
type: dict
target_tracking_scaling_policy_configuration:
description:
- A target tracking policy. This parameter is required if you are creating a new policy and the policy type is TargetTrackingScaling.
- 'Full documentation of the suboptions can be found in the API documentation:'
- 'U(https://docs.aws.amazon.com/autoscaling/application/APIReference/API_TargetTrackingScalingPolicyConfiguration.html)'
required: no
type: dict
suboptions:
CustomizedMetricSpecification:
description: The metric to use if using a customized metric.
type: dict
DisableScaleIn:
description: Whether scaling-in should be disabled.
type: bool
PredefinedMetricSpecification:
description: The metric to use if using a predefined metric.
type: dict
ScaleInCooldown:
description: The time (in seconds) to wait after scaling-in before another scaling action can occur.
type: int
ScaleOutCooldown:
description: The time (in seconds) to wait after scaling-out before another scaling action can occur.
type: int
TargetValue:
description: The target value for the metric
type: float
minimum_tasks:
description: The minimum value to scale to in response to a scale in event.
This parameter is required if you are creating a first new policy for the specified service.
required: no
type: int
maximum_tasks:
description: The maximum value to scale to in response to a scale out event.
This parameter is required if you are creating a first new policy for the specified service.
required: no
type: int
override_task_capacity:
description: Whether or not to override values of minimum and/or maximum tasks if it's already set.
required: no
default: no
type: bool
extends_documentation_fragment:
- amazon.aws.aws
- amazon.aws.ec2
'''
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
# Create step scaling policy for ECS Service
- name: scaling_policy
aws_application_scaling_policy:
state: present
policy_name: test_policy
service_namespace: ecs
resource_id: service/poc-pricing/test-as
scalable_dimension: ecs:service:DesiredCount
policy_type: StepScaling
minimum_tasks: 1
maximum_tasks: 6
step_scaling_policy_configuration:
AdjustmentType: ChangeInCapacity
StepAdjustments:
- MetricIntervalUpperBound: 123
ScalingAdjustment: 2
- MetricIntervalLowerBound: 123
ScalingAdjustment: -2
Cooldown: 123
MetricAggregationType: Average
# Create target tracking scaling policy for ECS Service
- name: scaling_policy
aws_application_scaling_policy:
state: present
policy_name: test_policy
service_namespace: ecs
resource_id: service/poc-pricing/test-as
scalable_dimension: ecs:service:DesiredCount
policy_type: TargetTrackingScaling
minimum_tasks: 1
maximum_tasks: 6
target_tracking_scaling_policy_configuration:
TargetValue: 60
PredefinedMetricSpecification:
PredefinedMetricType: ECSServiceAverageCPUUtilization
ScaleOutCooldown: 60
ScaleInCooldown: 60
# Remove scalable target for ECS Service
- name: scaling_policy
aws_application_scaling_policy:
state: absent
policy_name: test_policy
policy_type: StepScaling
service_namespace: ecs
resource_id: service/cluster-name/service-name
scalable_dimension: ecs:service:DesiredCount
'''
RETURN = '''
alarms:
description: List of the CloudWatch alarms associated with the scaling policy
returned: when state present
type: complex
contains:
alarm_arn:
description: The Amazon Resource Name (ARN) of the alarm
returned: when state present
type: str
alarm_name:
description: The name of the alarm
returned: when state present
type: str
service_namespace:
description: The namespace of the AWS service.
returned: when state present
type: str
sample: ecs
resource_id:
description: The identifier of the resource associated with the scalable target.
returned: when state present
type: str
sample: service/cluster-name/service-name
scalable_dimension:
description: The scalable dimension associated with the scalable target.
returned: when state present
type: str
sample: ecs:service:DesiredCount
policy_arn:
description: The Amazon Resource Name (ARN) of the scaling policy..
returned: when state present
type: str
policy_name:
description: The name of the scaling policy.
returned: when state present
type: str
policy_type:
description: The policy type.
returned: when state present
type: str
min_capacity:
description: The minimum value to scale to in response to a scale in event. Required if I(state) is C(present).
returned: when state present
type: int
sample: 1
max_capacity:
description: The maximum value to scale to in response to a scale out event. Required if I(state) is C(present).
returned: when state present
type: int
sample: 2
role_arn:
description: The ARN of an IAM role that allows Application Auto Scaling to modify the scalable target on your behalf. Required if I(state) is C(present).
returned: when state present
type: str
sample: arn:aws:iam::123456789123:role/roleName
step_scaling_policy_configuration:
description: The step scaling policy.
returned: when state present and the policy type is StepScaling
type: complex
contains:
adjustment_type:
description: The adjustment type
returned: when state present and the policy type is StepScaling
type: str
sample: "ChangeInCapacity, PercentChangeInCapacity, ExactCapacity"
cooldown:
description: The amount of time, in seconds, after a scaling activity completes
where previous trigger-related scaling activities can influence future scaling events
returned: when state present and the policy type is StepScaling
type: int
sample: 60
metric_aggregation_type:
description: The aggregation type for the CloudWatch metrics
returned: when state present and the policy type is StepScaling
type: str
sample: "Average, Minimum, Maximum"
step_adjustments:
description: A set of adjustments that enable you to scale based on the size of the alarm breach
returned: when state present and the policy type is StepScaling
type: list
elements: dict
target_tracking_scaling_policy_configuration:
description: The target tracking policy.
returned: when state present and the policy type is TargetTrackingScaling
type: complex
contains:
predefined_metric_specification:
description: A predefined metric
returned: when state present and the policy type is TargetTrackingScaling
type: complex
contains:
predefined_metric_type:
description: The metric type
returned: when state present and the policy type is TargetTrackingScaling
type: str
sample: "ECSServiceAverageCPUUtilization, ECSServiceAverageMemoryUtilization"
resource_label:
description: Identifies the resource associated with the metric type
returned: when metric type is ALBRequestCountPerTarget
type: str
scale_in_cooldown:
description: The amount of time, in seconds, after a scale in activity completes before another scale in activity can start
returned: when state present and the policy type is TargetTrackingScaling
type: int
sample: 60
scale_out_cooldown:
description: The amount of time, in seconds, after a scale out activity completes before another scale out activity can start
returned: when state present and the policy type is TargetTrackingScaling
type: int
sample: 60
target_value:
description: The target value for the metric
returned: when state present and the policy type is TargetTrackingScaling
type: int
sample: 70
creation_time:
description: The Unix timestamp for when the scalable target was created.
returned: when state present
type: str
sample: '2017-09-28T08:22:51.881000-03:00'
''' # NOQA
from ansible_collections.amazon.aws.plugins.module_utils.aws.core import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import _camel_to_snake, camel_dict_to_snake_dict
try:
import botocore
except ImportError:
pass # handled by AnsibleAWSModule
# Merge the results of the scalable target creation and policy deletion/creation
# There's no risk in overriding values since mutual keys have the same values in our case
def merge_results(scalable_target_result, policy_result):
if scalable_target_result['changed'] or policy_result['changed']:
changed = True
else:
changed = False
merged_response = scalable_target_result['response'].copy()
merged_response.update(policy_result['response'])
return {"changed": changed, "response": merged_response}
def delete_scaling_policy(connection, module):
changed = False
try:
scaling_policy = connection.describe_scaling_policies(
ServiceNamespace=module.params.get('service_namespace'),
ResourceId=module.params.get('resource_id'),
ScalableDimension=module.params.get('scalable_dimension'),
PolicyNames=[module.params.get('policy_name')],
MaxResults=1
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to describe scaling policies")
if scaling_policy['ScalingPolicies']:
try:
connection.delete_scaling_policy(
ServiceNamespace=module.params.get('service_namespace'),
ResourceId=module.params.get('resource_id'),
ScalableDimension=module.params.get('scalable_dimension'),
PolicyName=module.params.get('policy_name'),
)
changed = True
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to delete scaling policy")
return {"changed": changed}
def create_scalable_target(connection, module):
changed = False
try:
scalable_targets = connection.describe_scalable_targets(
ServiceNamespace=module.params.get('service_namespace'),
ResourceIds=[
module.params.get('resource_id'),
],
ScalableDimension=module.params.get('scalable_dimension')
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to describe scalable targets")
# Scalable target registration will occur if:
# 1. There is no scalable target registered for this service
# 2. A scalable target exists, different min/max values are defined and override is set to "yes"
if (
not scalable_targets['ScalableTargets']
or (
module.params.get('override_task_capacity')
and (
scalable_targets['ScalableTargets'][0]['MinCapacity'] != module.params.get('minimum_tasks')
or scalable_targets['ScalableTargets'][0]['MaxCapacity'] != module.params.get('maximum_tasks')
)
)
):
changed = True
try:
connection.register_scalable_target(
ServiceNamespace=module.params.get('service_namespace'),
ResourceId=module.params.get('resource_id'),
ScalableDimension=module.params.get('scalable_dimension'),
MinCapacity=module.params.get('minimum_tasks'),
MaxCapacity=module.params.get('maximum_tasks')
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to register scalable target")
try:
response = connection.describe_scalable_targets(
ServiceNamespace=module.params.get('service_namespace'),
ResourceIds=[
module.params.get('resource_id'),
],
ScalableDimension=module.params.get('scalable_dimension')
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to describe scalable targets")
if (response['ScalableTargets']):
snaked_response = camel_dict_to_snake_dict(response['ScalableTargets'][0])
else:
snaked_response = {}
return {"changed": changed, "response": snaked_response}
def create_scaling_policy(connection, module):
try:
scaling_policy = connection.describe_scaling_policies(
ServiceNamespace=module.params.get('service_namespace'),
ResourceId=module.params.get('resource_id'),
ScalableDimension=module.params.get('scalable_dimension'),
PolicyNames=[module.params.get('policy_name')],
MaxResults=1
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to describe scaling policies")
changed = False
if scaling_policy['ScalingPolicies']:
scaling_policy = scaling_policy['ScalingPolicies'][0]
# check if the input parameters are equal to what's already configured
for attr in ('PolicyName',
'ServiceNamespace',
'ResourceId',
'ScalableDimension',
'PolicyType',
'StepScalingPolicyConfiguration',
'TargetTrackingScalingPolicyConfiguration'):
if attr in scaling_policy and scaling_policy[attr] != module.params.get(_camel_to_snake(attr)):
changed = True
scaling_policy[attr] = module.params.get(_camel_to_snake(attr))
else:
changed = True
scaling_policy = {
'PolicyName': module.params.get('policy_name'),
'ServiceNamespace': module.params.get('service_namespace'),
'ResourceId': module.params.get('resource_id'),
'ScalableDimension': module.params.get('scalable_dimension'),
'PolicyType': module.params.get('policy_type'),
'StepScalingPolicyConfiguration': module.params.get('step_scaling_policy_configuration'),
'TargetTrackingScalingPolicyConfiguration': module.params.get('target_tracking_scaling_policy_configuration')
}
if changed:
try:
if (module.params.get('step_scaling_policy_configuration')):
connection.put_scaling_policy(
PolicyName=scaling_policy['PolicyName'],
ServiceNamespace=scaling_policy['ServiceNamespace'],
ResourceId=scaling_policy['ResourceId'],
ScalableDimension=scaling_policy['ScalableDimension'],
PolicyType=scaling_policy['PolicyType'],
StepScalingPolicyConfiguration=scaling_policy['StepScalingPolicyConfiguration']
)
elif (module.params.get('target_tracking_scaling_policy_configuration')):
connection.put_scaling_policy(
PolicyName=scaling_policy['PolicyName'],
ServiceNamespace=scaling_policy['ServiceNamespace'],
ResourceId=scaling_policy['ResourceId'],
ScalableDimension=scaling_policy['ScalableDimension'],
PolicyType=scaling_policy['PolicyType'],
TargetTrackingScalingPolicyConfiguration=scaling_policy['TargetTrackingScalingPolicyConfiguration']
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to create scaling policy")
try:
response = connection.describe_scaling_policies(
ServiceNamespace=module.params.get('service_namespace'),
ResourceId=module.params.get('resource_id'),
ScalableDimension=module.params.get('scalable_dimension'),
PolicyNames=[module.params.get('policy_name')],
MaxResults=1
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
module.fail_json_aws(e, msg="Failed to describe scaling policies")
if (response['ScalingPolicies']):
snaked_response = camel_dict_to_snake_dict(response['ScalingPolicies'][0])
else:
snaked_response = {}
return {"changed": changed, "response": snaked_response}
def main():
argument_spec = dict(
state=dict(type='str', required=True, choices=['present', 'absent']),
policy_name=dict(type='str', required=True),
service_namespace=dict(type='str', required=True, choices=['appstream', 'dynamodb', 'ec2', 'ecs', 'elasticmapreduce']),
resource_id=dict(type='str', required=True),
scalable_dimension=dict(type='str',
required=True,
choices=['ecs:service:DesiredCount',
'ec2:spot-fleet-request:TargetCapacity',
'elasticmapreduce:instancegroup:InstanceCount',
'appstream:fleet:DesiredCapacity',
'dynamodb:table:ReadCapacityUnits',
'dynamodb:table:WriteCapacityUnits',
'dynamodb:index:ReadCapacityUnits',
'dynamodb:index:WriteCapacityUnits']),
policy_type=dict(type='str', required=True, choices=['StepScaling', 'TargetTrackingScaling']),
step_scaling_policy_configuration=dict(type='dict'),
target_tracking_scaling_policy_configuration=dict(
type='dict',
options=dict(
CustomizedMetricSpecification=dict(type='dict'),
DisableScaleIn=dict(type='bool'),
PredefinedMetricSpecification=dict(type='dict'),
ScaleInCooldown=dict(type='int'),
ScaleOutCooldown=dict(type='int'),
TargetValue=dict(type='float'),
)
),
minimum_tasks=dict(type='int'),
maximum_tasks=dict(type='int'),
override_task_capacity=dict(type='bool'),
)
module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
connection = module.client('application-autoscaling')
# Remove any target_tracking_scaling_policy_configuration suboptions that are None
policy_config_options = [
'CustomizedMetricSpecification', 'DisableScaleIn', 'PredefinedMetricSpecification', 'ScaleInCooldown', 'ScaleOutCooldown', 'TargetValue'
]
if isinstance(module.params['target_tracking_scaling_policy_configuration'], dict):
for option in policy_config_options:
if module.params['target_tracking_scaling_policy_configuration'][option] is None:
module.params['target_tracking_scaling_policy_configuration'].pop(option)
if module.params.get("state") == 'present':
# A scalable target must be registered prior to creating a scaling policy
scalable_target_result = create_scalable_target(connection, module)
policy_result = create_scaling_policy(connection, module)
# Merge the results of the scalable target creation and policy deletion/creation
# There's no risk in overriding values since mutual keys have the same values in our case
merged_result = merge_results(scalable_target_result, policy_result)
module.exit_json(**merged_result)
else:
policy_result = delete_scaling_policy(connection, module)
module.exit_json(**policy_result)
if __name__ == '__main__':
main()
|
[
"ansible_collections.amazon.aws.plugins.module_utils.ec2.camel_dict_to_snake_dict",
"ansible_collections.amazon.aws.plugins.module_utils.ec2._camel_to_snake",
"ansible_collections.amazon.aws.plugins.module_utils.aws.core.AnsibleAWSModule"
] |
[((21763, 21834), 'ansible_collections.amazon.aws.plugins.module_utils.aws.core.AnsibleAWSModule', 'AnsibleAWSModule', ([], {'argument_spec': 'argument_spec', 'supports_check_mode': '(True)'}), '(argument_spec=argument_spec, supports_check_mode=True)\n', (21779, 21834), False, 'from ansible_collections.amazon.aws.plugins.module_utils.aws.core import AnsibleAWSModule\n'), ((15720, 15776), 'ansible_collections.amazon.aws.plugins.module_utils.ec2.camel_dict_to_snake_dict', 'camel_dict_to_snake_dict', (["response['ScalableTargets'][0]"], {}), "(response['ScalableTargets'][0])\n", (15744, 15776), False, 'from ansible_collections.amazon.aws.plugins.module_utils.ec2 import _camel_to_snake, camel_dict_to_snake_dict\n'), ((19756, 19812), 'ansible_collections.amazon.aws.plugins.module_utils.ec2.camel_dict_to_snake_dict', 'camel_dict_to_snake_dict', (["response['ScalingPolicies'][0]"], {}), "(response['ScalingPolicies'][0])\n", (19780, 19812), False, 'from ansible_collections.amazon.aws.plugins.module_utils.ec2 import _camel_to_snake, camel_dict_to_snake_dict\n'), ((17162, 17183), 'ansible_collections.amazon.aws.plugins.module_utils.ec2._camel_to_snake', '_camel_to_snake', (['attr'], {}), '(attr)\n', (17177, 17183), False, 'from ansible_collections.amazon.aws.plugins.module_utils.ec2 import _camel_to_snake, camel_dict_to_snake_dict\n'), ((17050, 17071), 'ansible_collections.amazon.aws.plugins.module_utils.ec2._camel_to_snake', '_camel_to_snake', (['attr'], {}), '(attr)\n', (17065, 17071), False, 'from ansible_collections.amazon.aws.plugins.module_utils.ec2 import _camel_to_snake, camel_dict_to_snake_dict\n')]
|
import numpy as np
from multiagent.core import World, Agent, Landmark
from multiagent.agents import VIP, Bodyguard, StreetBystander
from multiagent.scenario import VIPScenario
import copy
class Scenario(VIPScenario):
def __init__(self, num_bodyguards=4, num_bystanders=10, communication=True, env_range=1.0, comm_dim=4, seed=1):
super().__init__(num_bodyguards, num_bystanders, communication, env_range, comm_dim, seed)
def make_world(self):
""" Creates the world, the agents, the landmarks, the communication channels etc. These are for the time being all undifferentiated
"""
world = World()
self.world = world
if self.communication:
world.dim_c = self.comm_dim
### create the landmarks, among them the start and goal of VIP ###
world.landmarks = self.create_landmarks(world, 22)
### create the agents ###
for i in range(self.num_agents):
if i == 0:
agent = VIP(self)
elif i <= self.num_bodyguards:
agent = Bodyguard(self, self.communication, alpha=2.5, beta=2)
agent.name = 'bodyguard %d' % (i)
else:
agent = StreetBystander(self)
agent.name = 'bystander %d' % (i - self.num_bodyguards)
agent.accel = 3.0
agent.max_speed = 1.0
world.agents.append(agent)
self.reset_world(world)
return world
def reset_world(self, world):
""" Resets the world and agents. Chooses a new goal position for the VIP and
arranges the bodyguards accordingly
"""
""" Resets the world and agents. Chooses a new goal position for the VIP and
arranges the bodyguards accordingly
"""
self.world = world
for agent in world.agents:
agent.reset()
# set the initial state of the VIP
goal, start = copy.deepcopy(world.landmarks[:2])
self.vip_agent.state.p_pos = start.state.p_pos + start.size
self.vip_agent.goal_a = goal
# set the initial states of the bodyguards
temp_angle = 360/self.num_bodyguards
for i, agent in enumerate(self.bodyguards):
agent_angle = (temp_angle)* np.pi / 180.
agent.state.p_pos = world.agents[0].state.p_pos + np.array([np.cos(agent_angle), np.sin(agent_angle)])*agent.allowed_distance
temp_angle += 360/self.num_bodyguards
# set position of the bystanders behind the landmarks
np.random.seed(seed=None)
seed=np.random.randint(1, 10)
np.random.seed(seed)
bystander_theta = np.random.uniform(-np.pi, np.pi, self.num_bystanders)
np.random.seed(seed=None)
seed=np.random.randint(1, 10)
np.random.seed(seed)
bystander_noise = np.random.rand(self.num_bystanders)
x = np.array([-0.6, .6])
y = np.arange(-.9, 1.0, 0.4)
bystander_p_pos=np.transpose([np.repeat(x, len(y)), np.tile(y, len(x))])
for i, agent in enumerate(self.bystanders):
agent.state.p_pos = bystander_p_pos[i]
agent.theta = bystander_theta[i]
agent.noise = bystander_noise[i]
# selecting the attacker from bystanders
attacker = np.random.choice(self.bystanders)
attacker.goal_a = self.vip_agent
def create_landmarks(self, world, number_of_landmarks):
world_landmarks = []
for i in range(number_of_landmarks):
landmark = Landmark()
landmark.name = 'landmark %d' % i
landmark.color = np.array([0.75,0.75,0.75])
landmark.state.p_vel = np.zeros(world.dim_p)
landmark.collide = True
landmark.movable = False
landmark.size = 0.050
world_landmarks.append(landmark)
x = np.array([0])
y = np.array([-0.9, 0.9])
landmark_p_pos = np.transpose([np.repeat(x, len(y)), np.tile(y, len(x))])
for i, landmark in enumerate(world_landmarks[:2]):
landmark.state.p_pos = landmark_p_pos[i]
x = np.array([-0.9, 0.9])
y = np.arange(-1, 1.5, 0.25)
landmark_p_pos = np.transpose([np.repeat(x, len(y)), np.tile(y, len(x))])
for i, landmark in enumerate(world_landmarks[2:]):
landmark.state.p_pos = landmark_p_pos[i]
world_landmarks[0].color = np.array([0.15, 0.65, 0.15])
return world_landmarks
|
[
"numpy.random.uniform",
"copy.deepcopy",
"numpy.random.choice",
"numpy.random.seed",
"multiagent.agents.StreetBystander",
"numpy.zeros",
"multiagent.core.Landmark",
"multiagent.agents.VIP",
"multiagent.agents.Bodyguard",
"numpy.random.randint",
"numpy.array",
"numpy.arange",
"numpy.cos",
"multiagent.core.World",
"numpy.random.rand",
"numpy.sin"
] |
[((628, 635), 'multiagent.core.World', 'World', ([], {}), '()\n', (633, 635), False, 'from multiagent.core import World, Agent, Landmark\n'), ((1945, 1979), 'copy.deepcopy', 'copy.deepcopy', (['world.landmarks[:2]'], {}), '(world.landmarks[:2])\n', (1958, 1979), False, 'import copy\n'), ((2546, 2571), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'None'}), '(seed=None)\n', (2560, 2571), True, 'import numpy as np\n'), ((2585, 2609), 'numpy.random.randint', 'np.random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (2602, 2609), True, 'import numpy as np\n'), ((2618, 2638), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2632, 2638), True, 'import numpy as np\n'), ((2665, 2718), 'numpy.random.uniform', 'np.random.uniform', (['(-np.pi)', 'np.pi', 'self.num_bystanders'], {}), '(-np.pi, np.pi, self.num_bystanders)\n', (2682, 2718), True, 'import numpy as np\n'), ((2728, 2753), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'None'}), '(seed=None)\n', (2742, 2753), True, 'import numpy as np\n'), ((2767, 2791), 'numpy.random.randint', 'np.random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (2784, 2791), True, 'import numpy as np\n'), ((2800, 2820), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2814, 2820), True, 'import numpy as np\n'), ((2847, 2882), 'numpy.random.rand', 'np.random.rand', (['self.num_bystanders'], {}), '(self.num_bystanders)\n', (2861, 2882), True, 'import numpy as np\n'), ((2896, 2917), 'numpy.array', 'np.array', (['[-0.6, 0.6]'], {}), '([-0.6, 0.6])\n', (2904, 2917), True, 'import numpy as np\n'), ((2929, 2954), 'numpy.arange', 'np.arange', (['(-0.9)', '(1.0)', '(0.4)'], {}), '(-0.9, 1.0, 0.4)\n', (2938, 2954), True, 'import numpy as np\n'), ((3298, 3331), 'numpy.random.choice', 'np.random.choice', (['self.bystanders'], {}), '(self.bystanders)\n', (3314, 3331), True, 'import numpy as np\n'), ((3866, 3879), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (3874, 3879), True, 'import numpy as np\n'), ((3892, 3913), 'numpy.array', 'np.array', (['[-0.9, 0.9]'], {}), '([-0.9, 0.9])\n', (3900, 3913), True, 'import numpy as np\n'), ((4122, 4143), 'numpy.array', 'np.array', (['[-0.9, 0.9]'], {}), '([-0.9, 0.9])\n', (4130, 4143), True, 'import numpy as np\n'), ((4157, 4181), 'numpy.arange', 'np.arange', (['(-1)', '(1.5)', '(0.25)'], {}), '(-1, 1.5, 0.25)\n', (4166, 4181), True, 'import numpy as np\n'), ((4412, 4440), 'numpy.array', 'np.array', (['[0.15, 0.65, 0.15]'], {}), '([0.15, 0.65, 0.15])\n', (4420, 4440), True, 'import numpy as np\n'), ((3531, 3541), 'multiagent.core.Landmark', 'Landmark', ([], {}), '()\n', (3539, 3541), False, 'from multiagent.core import World, Agent, Landmark\n'), ((3617, 3645), 'numpy.array', 'np.array', (['[0.75, 0.75, 0.75]'], {}), '([0.75, 0.75, 0.75])\n', (3625, 3645), True, 'import numpy as np\n'), ((3679, 3700), 'numpy.zeros', 'np.zeros', (['world.dim_p'], {}), '(world.dim_p)\n', (3687, 3700), True, 'import numpy as np\n'), ((992, 1001), 'multiagent.agents.VIP', 'VIP', (['self'], {}), '(self)\n', (995, 1001), False, 'from multiagent.agents import VIP, Bodyguard, StreetBystander\n'), ((1069, 1123), 'multiagent.agents.Bodyguard', 'Bodyguard', (['self', 'self.communication'], {'alpha': '(2.5)', 'beta': '(2)'}), '(self, self.communication, alpha=2.5, beta=2)\n', (1078, 1123), False, 'from multiagent.agents import VIP, Bodyguard, StreetBystander\n'), ((1216, 1237), 'multiagent.agents.StreetBystander', 'StreetBystander', (['self'], {}), '(self)\n', (1231, 1237), False, 'from multiagent.agents import VIP, Bodyguard, StreetBystander\n'), ((2359, 2378), 'numpy.cos', 'np.cos', (['agent_angle'], {}), '(agent_angle)\n', (2365, 2378), True, 'import numpy as np\n'), ((2380, 2399), 'numpy.sin', 'np.sin', (['agent_angle'], {}), '(agent_angle)\n', (2386, 2399), True, 'import numpy as np\n')]
|
from datetime import datetime
import static
import database
def process_message(reddit, message):
print(message.id)
print(message.author)
print(message.body)
def finish_task(conn, reddit, task_id, trigger_price):
sources = database.get_sources(conn, task_id)
for source in sources:
source_id = source[0]
source_comment_id = source[1]
subscribers = database.get_subscribers(conn, source_id)
task_details = database.get_task_details(conn, task_id)
symbol, target, direction_is_up, currency, before_condition = task_details
parent_comment = reddit.comment(source_comment_id).parent()
print(reddit.comment(source_comment_id))
print(parent_comment)
before_string = "" if (before_condition == datetime.max) else f" before {before_condition}"
direction_string_present_tense = "hits" if direction_is_up else "drops to"
direction_string_past_tens = "hit" if direction_is_up else "dropped to"
trigger_string = "high" if direction_is_up else "low"
emoji = "📈" if direction_is_up else "📉"
subject = f"{symbol} {direction_string_past_tens} {target} {currency}"
for subscriber_tuple in subscribers:
message_builder = []
message_builder.append(f"You asked me to remind you when {symbol} {direction_string_present_tense} {target} {currency}{before_string}.\n\n")
message_builder.append(f"{symbol} {direction_string_past_tens} {target} {currency} today with the current day {trigger_string} at {trigger_price}. {emoji}\n\n")
message_builder.append(f"You requested the reminder in [this context](https://www.reddit.com{parent_comment.permalink}).\n\n")
message_builder.append(static.BOTTOM_REPLY_SECTION)
message = "".join(message_builder)
reddit.redditor(subscriber_tuple[0]).message(subject, message)
database.remove_task(conn, task_id)
|
[
"database.get_subscribers",
"database.remove_task",
"database.get_task_details",
"database.get_sources"
] |
[((246, 281), 'database.get_sources', 'database.get_sources', (['conn', 'task_id'], {}), '(conn, task_id)\n', (266, 281), False, 'import database\n'), ((1929, 1964), 'database.remove_task', 'database.remove_task', (['conn', 'task_id'], {}), '(conn, task_id)\n', (1949, 1964), False, 'import database\n'), ((401, 442), 'database.get_subscribers', 'database.get_subscribers', (['conn', 'source_id'], {}), '(conn, source_id)\n', (425, 442), False, 'import database\n'), ((466, 506), 'database.get_task_details', 'database.get_task_details', (['conn', 'task_id'], {}), '(conn, task_id)\n', (491, 506), False, 'import database\n')]
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import sys
import os.path
import argparse
from string import Template
dirname = os.path.dirname(__file__)
imported_files = os.path.join(dirname, "../src/")
sys.path.insert(0, os.path.abspath(imported_files))
from zeo_connector_defaults import _SERVER_CONF_PATH
from zeo_connector_defaults import _CLIENT_CONF_PATH
# Functions & classes =========================================================
def create_configuration(args):
with open(_SERVER_CONF_PATH) as f:
server_template = f.read()
with open(_CLIENT_CONF_PATH) as f:
client_template = f.read()
if not args.only_server:
client = Template(client_template).substitute(
server=args.server,
port=args.port,
)
with open(os.path.basename(_CLIENT_CONF_PATH), "w") as f:
f.write(client)
if not args.only_client:
server = Template(server_template).substitute(
server=args.server,
port=args.port,
path=args.path,
)
with open(os.path.basename(_SERVER_CONF_PATH), "w") as f:
f.write(server)
# Main program ================================================================
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="""This program will create the default ZEO XML
configuration files."""
)
parser.add_argument(
"-s",
"--server",
default="localhost",
help="Server url. Default: localhost"
)
parser.add_argument(
"-p",
"--port",
default=60985,
type=int,
help="Port of the server. Default: 60985"
)
parser.add_argument(
"path",
metavar="PATH",
nargs='?',
default="",
help="""Path to the database on the server (used in server
configuration only."""
)
parser.add_argument(
"-C",
"--only-client",
action="store_true",
help="Create only CLIENT configuration."
)
parser.add_argument(
"-S",
"--only-server",
action="store_true",
help="Create only SERVER configuration."
)
args = parser.parse_args()
if not args.only_client and not args.path:
sys.stderr.write(
"You have to specify path to the database on for the DB server.\n"
)
sys.exit(1)
if args.only_client and args.only_server:
sys.stderr.write(
"You can't have --only-client and --only-server together!\n"
)
sys.exit(1)
create_configuration(args)
|
[
"sys.stderr.write",
"argparse.ArgumentParser",
"sys.exit",
"string.Template"
] |
[((1392, 1522), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""This program will create the default ZEO XML\n configuration files."""'}), '(description=\n """This program will create the default ZEO XML\n configuration files."""\n )\n', (1415, 1522), False, 'import argparse\n'), ((2417, 2506), 'sys.stderr.write', 'sys.stderr.write', (['"""You have to specify path to the database on for the DB server.\n"""'], {}), "(\n 'You have to specify path to the database on for the DB server.\\n')\n", (2433, 2506), False, 'import sys\n'), ((2532, 2543), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2540, 2543), False, 'import sys\n'), ((2599, 2677), 'sys.stderr.write', 'sys.stderr.write', (['"""You can\'t have --only-client and --only-server together!\n"""'], {}), '("You can\'t have --only-client and --only-server together!\\n")\n', (2615, 2677), False, 'import sys\n'), ((2708, 2719), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2716, 2719), False, 'import sys\n'), ((791, 816), 'string.Template', 'Template', (['client_template'], {}), '(client_template)\n', (799, 816), False, 'from string import Template\n'), ((1040, 1065), 'string.Template', 'Template', (['server_template'], {}), '(server_template)\n', (1048, 1065), False, 'from string import Template\n')]
|
import unittest
import os
import sys
sys.path.append(os.getcwd())
sys.path.append(os.path.dirname(os.getcwd()))
from src import SimpleAttribute
from src import InternalHelperUtilities as Utils
class SimpleAttributeTestCase(unittest.TestCase):
def setUp(self):
pass
def test_sa_parsing(self):
sFilename = "ut_sas.lib"
if os.path.isdir('unittest'):
sFilename = "unittest/" + sFilename
with open(sFilename, 'r') as tLibFile:
sContent = Utils.readLibertyFile(tLibFile)
sEndChar = len(sContent)
sListOfStatements = [None] * 9
tCurLine = 0
tCurChar = 0
while(tCurChar < sEndChar):
sListOfStatements[tCurLine] = SimpleAttribute()
tCurChar, tCurLine = sListOfStatements[tCurLine].parse(sContent, tCurChar, sEndChar, tCurLine)
tCurChar, tCurLine = Utils.moveToNextStatement(sContent, tCurChar, sEndChar, tCurLine)
sSortedListOfStatements = sListOfStatements.copy()
sSortedListOfStatements.sort()
self.assertEqual(sSortedListOfStatements, sListOfStatements)
self.assertEqual(sListOfStatements[0].name, 'comment')
self.assertEqual(sListOfStatements[0].value, '" "')
self.assertEqual(sListOfStatements[1].name, 'date')
self.assertEqual(sListOfStatements[1].value, '"$Date: Jun 18"')
self.assertEqual(sListOfStatements[1].comment, '/* With a regular line comment */')
self.assertEqual(sListOfStatements[2].name, 'version')
self.assertEqual(sListOfStatements[2].value, '"1.0"')
self.assertEqual(sListOfStatements[2].comment, '/* With a strange line comment \n\n*/')
self.assertEqual(sListOfStatements[3].name, 'value')
self.assertEqual(sListOfStatements[3].value, '1')
self.assertEqual(sListOfStatements[4].name, 'invalid_name')
self.assertEqual(sListOfStatements[4].value, 'invalid_value')
self.assertEqual(sListOfStatements[5].name, 'invalid_name')
self.assertEqual(sListOfStatements[5].value, 'invalid_value')
self.assertEqual(sListOfStatements[6].name, 'invalid_name')
self.assertEqual(sListOfStatements[6].value, 'invalid_value')
self.assertEqual(sListOfStatements[7].name, 'invalid_name')
self.assertEqual(sListOfStatements[7].value, 'invalid_value')
self.assertEqual(sListOfStatements[8].name, 'index')
self.assertEqual(sListOfStatements[8].value, '5')
if __name__ == "__main__":
unittest.main()
|
[
"unittest.main",
"os.getcwd",
"os.path.isdir",
"src.InternalHelperUtilities.readLibertyFile",
"src.SimpleAttribute",
"src.InternalHelperUtilities.moveToNextStatement"
] |
[((54, 65), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (63, 65), False, 'import os\n'), ((2552, 2567), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2565, 2567), False, 'import unittest\n'), ((99, 110), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (108, 110), False, 'import os\n'), ((359, 384), 'os.path.isdir', 'os.path.isdir', (['"""unittest"""'], {}), "('unittest')\n", (372, 384), False, 'import os\n'), ((504, 535), 'src.InternalHelperUtilities.readLibertyFile', 'Utils.readLibertyFile', (['tLibFile'], {}), '(tLibFile)\n', (525, 535), True, 'from src import InternalHelperUtilities as Utils\n'), ((752, 769), 'src.SimpleAttribute', 'SimpleAttribute', ([], {}), '()\n', (767, 769), False, 'from src import SimpleAttribute\n'), ((918, 983), 'src.InternalHelperUtilities.moveToNextStatement', 'Utils.moveToNextStatement', (['sContent', 'tCurChar', 'sEndChar', 'tCurLine'], {}), '(sContent, tCurChar, sEndChar, tCurLine)\n', (943, 983), True, 'from src import InternalHelperUtilities as Utils\n')]
|
# VEML6070 Driver Example Code
import time
import busio
import board
import adafruit_veml6070
with busio.I2C(board.SCL, board.SDA) as i2c:
uv = adafruit_veml6070.VEML6070(i2c)
# Alternative constructors with parameters
# uv = adafruit_veml6070.VEML6070(i2c, 'VEML6070_1_T')
# uv = adafruit_veml6070.VEML6070(i2c, 'VEML6070_HALF_T', True)
# take 10 readings
for j in range(10):
uv_raw = uv.uv_raw
risk_level = uv.get_index(uv_raw)
print("Reading: {0} | Risk Level: {1}".format(uv_raw, risk_level))
time.sleep(1)
|
[
"busio.I2C",
"adafruit_veml6070.VEML6070",
"time.sleep"
] |
[((108, 139), 'busio.I2C', 'busio.I2C', (['board.SCL', 'board.SDA'], {}), '(board.SCL, board.SDA)\n', (117, 139), False, 'import busio\n'), ((158, 189), 'adafruit_veml6070.VEML6070', 'adafruit_veml6070.VEML6070', (['i2c'], {}), '(i2c)\n', (184, 189), False, 'import adafruit_veml6070\n'), ((574, 587), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (584, 587), False, 'import time\n')]
|
#!/usr/bin/env python
# coding: utf-8
# In[4]:
#importing regular expression to parse through the inpus
special=['$','@','#']
import re
#defining the function using validation()
def validation():
#setting while loop to always be true
while True:
#taking input from the user and storing it to a value called password
password = input("Enter a password: ")
#searching through the password using search method in re to know if it does not contain a string
if re.search('[A-Za-z]',password) is None:
#printing 1 and break the loop
print(1)
break
#searching through the password using search method in re to know if it does not contain a a number
elif re.search('[0-9]',password) is None:
print(0)
break
elif re.match('[0-9A-za-z]',password) == password:
print(2)
break
else:
print(3)
break
validation()
|
[
"re.search",
"re.match"
] |
[((480, 511), 're.search', 're.search', (['"""[A-Za-z]"""', 'password'], {}), "('[A-Za-z]', password)\n", (489, 511), False, 'import re\n'), ((703, 731), 're.search', 're.search', (['"""[0-9]"""', 'password'], {}), "('[0-9]', password)\n", (712, 731), False, 'import re\n'), ((793, 826), 're.match', 're.match', (['"""[0-9A-za-z]"""', 'password'], {}), "('[0-9A-za-z]', password)\n", (801, 826), False, 'import re\n')]
|
# Generated by Django 2.0.4 on 2018-09-03 10:00
import clinic.utils.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinic', '0016_auto_20180828_0034'),
]
operations = [
migrations.AlterField(
model_name='doctor',
name='speciality',
field=models.CharField(choices=[('ped', 'Pediatrics'), ('crl', 'Cardiologist'), ('gyl', 'Gynaecolgist'), ('nrl', 'Neurologist'), ('ocl', 'Oncologist'), ('phy', 'Physician'), ('nes', 'Neuro Surgeon'), ('ges', 'General Surgeon'), ('gep', 'General Practitioner')], default='gp', max_length=3, verbose_name='Medical specialties'),
),
migrations.AlterField(
model_name='doctor',
name='username',
field=models.CharField(max_length=20, primary_key=True, serialize=False, validators=[clinic.utils.validators.validate_username]),
),
migrations.AlterField(
model_name='human',
name='phone_number',
field=models.BigIntegerField(validators=[clinic.utils.validators.validate_number]),
),
migrations.AlterField(
model_name='human',
name='pincode',
field=models.IntegerField(validators=[clinic.utils.validators.validate_pincode]),
),
]
|
[
"django.db.models.CharField",
"django.db.models.IntegerField",
"django.db.models.BigIntegerField"
] |
[((370, 706), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('ped', 'Pediatrics'), ('crl', 'Cardiologist'), ('gyl', 'Gynaecolgist'), (\n 'nrl', 'Neurologist'), ('ocl', 'Oncologist'), ('phy', 'Physician'), (\n 'nes', 'Neuro Surgeon'), ('ges', 'General Surgeon'), ('gep',\n 'General Practitioner')]", 'default': '"""gp"""', 'max_length': '(3)', 'verbose_name': '"""Medical specialties"""'}), "(choices=[('ped', 'Pediatrics'), ('crl', 'Cardiologist'), (\n 'gyl', 'Gynaecolgist'), ('nrl', 'Neurologist'), ('ocl', 'Oncologist'),\n ('phy', 'Physician'), ('nes', 'Neuro Surgeon'), ('ges',\n 'General Surgeon'), ('gep', 'General Practitioner')], default='gp',\n max_length=3, verbose_name='Medical specialties')\n", (386, 706), False, 'from django.db import migrations, models\n'), ((813, 939), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(20)', 'primary_key': '(True)', 'serialize': '(False)', 'validators': '[clinic.utils.validators.validate_username]'}), '(max_length=20, primary_key=True, serialize=False,\n validators=[clinic.utils.validators.validate_username])\n', (829, 939), False, 'from django.db import migrations, models\n'), ((1062, 1138), 'django.db.models.BigIntegerField', 'models.BigIntegerField', ([], {'validators': '[clinic.utils.validators.validate_number]'}), '(validators=[clinic.utils.validators.validate_number])\n', (1084, 1138), False, 'from django.db import migrations, models\n'), ((1260, 1334), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'validators': '[clinic.utils.validators.validate_pincode]'}), '(validators=[clinic.utils.validators.validate_pincode])\n', (1279, 1334), False, 'from django.db import migrations, models\n')]
|
# Copyright (c) 2020, NVIDIA CORPORATION.
#
# 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 cupy
from cuml.dask.cluster import KMeans
from cuml.dask.naive_bayes.naive_bayes import MultinomialNB
from cuml.test.dask.utils import load_text_corpus
from cuml.dask.datasets import make_blobs
def test_getattr(client):
# Test getattr on local param
kmeans_model = KMeans(client=client)
assert kmeans_model.client is not None
# Test getattr on local_model param with a non-distributed model
X, y = make_blobs(n_samples=5,
n_features=5,
centers=2,
n_parts=2,
cluster_std=0.01,
random_state=10)
kmeans_model.fit(X)
assert kmeans_model.cluster_centers_ is not None
assert isinstance(kmeans_model.cluster_centers_, cupy.core.ndarray)
# Test getattr on trained distributed model
X, y = load_text_corpus(client)
nb_model = MultinomialNB(client=client)
nb_model.fit(X, y)
assert nb_model.feature_count_ is not None
assert isinstance(nb_model.feature_count_, cupy.core.ndarray)
|
[
"cuml.dask.naive_bayes.naive_bayes.MultinomialNB",
"cuml.test.dask.utils.load_text_corpus",
"cuml.dask.cluster.KMeans",
"cuml.dask.datasets.make_blobs"
] |
[((876, 897), 'cuml.dask.cluster.KMeans', 'KMeans', ([], {'client': 'client'}), '(client=client)\n', (882, 897), False, 'from cuml.dask.cluster import KMeans\n'), ((1024, 1123), 'cuml.dask.datasets.make_blobs', 'make_blobs', ([], {'n_samples': '(5)', 'n_features': '(5)', 'centers': '(2)', 'n_parts': '(2)', 'cluster_std': '(0.01)', 'random_state': '(10)'}), '(n_samples=5, n_features=5, centers=2, n_parts=2, cluster_std=\n 0.01, random_state=10)\n', (1034, 1123), False, 'from cuml.dask.datasets import make_blobs\n'), ((1441, 1465), 'cuml.test.dask.utils.load_text_corpus', 'load_text_corpus', (['client'], {}), '(client)\n', (1457, 1465), False, 'from cuml.test.dask.utils import load_text_corpus\n'), ((1482, 1510), 'cuml.dask.naive_bayes.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {'client': 'client'}), '(client=client)\n', (1495, 1510), False, 'from cuml.dask.naive_bayes.naive_bayes import MultinomialNB\n')]
|
# Generated by Django 2.1.4 on 2018-12-08 16:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('quiz', '0005_auto_20181208_2329'),
]
operations = [
migrations.CreateModel(
name='AttemptAnswer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('answer', models.CharField(choices=[('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D'), ('e', 'E')], max_length=1)),
('attempt', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='quiz.QuizAttempt')),
('question', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='quiz.Question')),
],
),
]
|
[
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.AutoField"
] |
[((367, 460), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (383, 460), False, 'from django.db import migrations, models\n'), ((486, 591), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D'), ('e', 'E')]", 'max_length': '(1)'}), "(choices=[('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D'), (\n 'e', 'E')], max_length=1)\n", (502, 591), False, 'from django.db import migrations, models\n'), ((617, 707), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.PROTECT', 'to': '"""quiz.QuizAttempt"""'}), "(on_delete=django.db.models.deletion.PROTECT, to=\n 'quiz.QuizAttempt')\n", (634, 707), False, 'from django.db import migrations, models\n'), ((734, 821), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.PROTECT', 'to': '"""quiz.Question"""'}), "(on_delete=django.db.models.deletion.PROTECT, to=\n 'quiz.Question')\n", (751, 821), False, 'from django.db import migrations, models\n')]
|
## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net1(nn.Module):
def __init__(self):
super(Net1, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# 1st CNN - input image channel (grayscale 1x224x224), 32 output channels/feature maps,
# 3x3 square convolution kernel, stride=1
# output_size = (W-F)/S+1 = (224-3)/1+1 = 222
self.conv1 = nn.Conv2d(1, 32, 3)
# maxpooling layer: kernal_size=2, stride=2
# output_size = (222-2)/2+1 = 111
self.pool = nn.MaxPool2d(2, 2)
# 2nd CNN - 64 output channels/feature maps,
# 3x3 square convolution kernel, stride=1
# output_size = (111-3)/1 +1 = 109
self.conv2 = nn.Conv2d(32, 64, 3)
# maxpooling layer: kernel_size=2, stride=2
# output_size = (109-2)/2+1 = 54 (rounded down)
# reusing self.pool without needing to define extra
# fully connected layer: 64x54x54 output from previous layer
self.fc1 = nn.Linear(64*54*54, 680)
# dropout layer with prob=0.4
self.fc1_drop = nn.Dropout(p=0.4)
# fully connected layer to create final 136 output 68 pair of (x, y)
self.fc2 = nn.Linear(680, 136)
def forward(self, x):
## TODO: Define the feedforward behavior of this model
# x is the input image
# two conv+relu+pooling
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
# flatten
x = x.view(x.size(0), -1)
# two linear layers with dropout in between
x = F.relu(self.fc1(x))
x = self.fc1_drop(x)
x = self.fc2(x)
# final output
return x
class Net2(nn.Module):
def __init__(self):
super(Net2, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# output_size_1 = (224-3)/1+1 = 222
# output_size_2 = (222-3)/1+1 = 220
# output_size_2_pool = (220-2)/2+1=110
self.conv1 = nn.Conv2d(1, 32, 3)
self.conv2 = nn.Conv2d(32, 64 , 3)
# output_size_3 = (110-3)/1+1 = 108
# output_size_4 = (108-3)/1+1 = 106
# ouput_size_4_pool = (106-2)/2+1=53
self.conv3 = nn.Conv2d(64, 64, 3)
self.conv4 = nn.Conv2d(64, 128, 3)
# output_size_5 = (53-3)/1+1 = 51
# output_size_6 = (51-3)/1+1 = 49
# output_size_6_pool = (49-2)/2+1 = 24
self.conv5 = nn.Conv2d(128, 128, 3)
self.conv6 = nn.Conv2d(128, 128, 3)
self.conv2_drop = nn.Dropout2d(p=0.5)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(128 * 24 * 24, 1024)
self.fc2 = nn.Linear(1024, 136)
def forward(self, x):
x = self.conv2_drop(self.pool(F.relu(self.conv2(F.relu(self.conv1(x))))))
x = self.conv2_drop(self.pool(F.relu(self.conv4(F.relu(self.conv3(x))))))
x = self.conv2_drop(self.pool(F.relu(self.conv6(F.relu(self.conv5(x))))))
x = x.view(-1, 128 * 24 * 24)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
|
[
"torch.nn.Dropout",
"torch.nn.Dropout2d",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.MaxPool2d"
] |
[((966, 985), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(32)', '(3)'], {}), '(1, 32, 3)\n', (975, 985), True, 'import torch.nn as nn\n'), ((1101, 1119), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', (['(2)', '(2)'], {}), '(2, 2)\n', (1113, 1119), True, 'import torch.nn as nn\n'), ((1289, 1309), 'torch.nn.Conv2d', 'nn.Conv2d', (['(32)', '(64)', '(3)'], {}), '(32, 64, 3)\n', (1298, 1309), True, 'import torch.nn as nn\n'), ((1577, 1605), 'torch.nn.Linear', 'nn.Linear', (['(64 * 54 * 54)', '(680)'], {}), '(64 * 54 * 54, 680)\n', (1586, 1605), True, 'import torch.nn as nn\n'), ((1665, 1682), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.4)'}), '(p=0.4)\n', (1675, 1682), True, 'import torch.nn as nn\n'), ((1780, 1799), 'torch.nn.Linear', 'nn.Linear', (['(680)', '(136)'], {}), '(680, 136)\n', (1789, 1799), True, 'import torch.nn as nn\n'), ((2899, 2918), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(32)', '(3)'], {}), '(1, 32, 3)\n', (2908, 2918), True, 'import torch.nn as nn\n'), ((2940, 2960), 'torch.nn.Conv2d', 'nn.Conv2d', (['(32)', '(64)', '(3)'], {}), '(32, 64, 3)\n', (2949, 2960), True, 'import torch.nn as nn\n'), ((3119, 3139), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(64)', '(3)'], {}), '(64, 64, 3)\n', (3128, 3139), True, 'import torch.nn as nn\n'), ((3161, 3182), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(128)', '(3)'], {}), '(64, 128, 3)\n', (3170, 3182), True, 'import torch.nn as nn\n'), ((3344, 3366), 'torch.nn.Conv2d', 'nn.Conv2d', (['(128)', '(128)', '(3)'], {}), '(128, 128, 3)\n', (3353, 3366), True, 'import torch.nn as nn\n'), ((3388, 3410), 'torch.nn.Conv2d', 'nn.Conv2d', (['(128)', '(128)', '(3)'], {}), '(128, 128, 3)\n', (3397, 3410), True, 'import torch.nn as nn\n'), ((3438, 3457), 'torch.nn.Dropout2d', 'nn.Dropout2d', ([], {'p': '(0.5)'}), '(p=0.5)\n', (3450, 3457), True, 'import torch.nn as nn\n'), ((3494, 3512), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', (['(2)', '(2)'], {}), '(2, 2)\n', (3506, 3512), True, 'import torch.nn as nn\n'), ((3541, 3571), 'torch.nn.Linear', 'nn.Linear', (['(128 * 24 * 24)', '(1024)'], {}), '(128 * 24 * 24, 1024)\n', (3550, 3571), True, 'import torch.nn as nn\n'), ((3591, 3611), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(136)'], {}), '(1024, 136)\n', (3600, 3611), True, 'import torch.nn as nn\n')]
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" test Grover """
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from qiskit import BasicAer, QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit.algorithms import Grover
from qiskit.circuit.library import GroverOperator
from qiskit.quantum_info import Operator, Statevector
class TestGroverConstructor(QiskitAlgorithmsTestCase):
"""Test for the constructor of Grover"""
def setUp(self):
super().setUp()
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
self._expected_grover_op = GroverOperator(oracle=oracle)
def test_oracle_quantumcircuit(self):
"""Test QuantumCircuit oracle"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
grover = Grover(oracle=oracle, good_state=["11"])
grover_op = grover._grover_operator
self.assertTrue(Operator(grover_op).equiv(Operator(self._expected_grover_op)))
def test_oracle_statevector(self):
"""Test StateVector oracle"""
mark_state = Statevector.from_label('11')
grover = Grover(oracle=mark_state, good_state=['11'])
grover_op = grover._grover_operator
self.assertTrue(Operator(grover_op).equiv(Operator(self._expected_grover_op)))
def test_state_preparation_quantumcircuit(self):
"""Test QuantumCircuit state_preparation"""
state_preparation = QuantumCircuit(2)
state_preparation.h(0)
oracle = QuantumCircuit(3)
oracle.cz(0, 1)
grover = Grover(oracle=oracle, state_preparation=state_preparation,
good_state=["011"])
grover_op = grover._grover_operator
expected_grover_op = GroverOperator(oracle, state_preparation=state_preparation)
self.assertTrue(Operator(grover_op).equiv(Operator(expected_grover_op)))
def test_is_good_state_list(self):
"""Test List is_good_state"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
is_good_state = ["11", "00"]
grover = Grover(oracle=oracle, good_state=is_good_state)
self.assertListEqual(grover._is_good_state, ["11", "00"])
def test_is_good_state_statevector(self):
"""Test StateVector is_good_state"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
is_good_state = Statevector.from_label('11')
grover = Grover(oracle=oracle, good_state=is_good_state)
self.assertTrue(grover._is_good_state.equiv(Statevector.from_label('11')))
def test_grover_operator(self):
"""Test GroverOperator"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
grover_op = GroverOperator(oracle)
grover = Grover(oracle=grover_op.oracle,
grover_operator=grover_op, good_state=["11"])
grover_op = grover._grover_operator
self.assertTrue(Operator(grover_op).equiv(Operator(self._expected_grover_op)))
class TestGroverPublicMethods(QiskitAlgorithmsTestCase):
"""Test for the public methods of Grover"""
def test_is_good_state(self):
"""Test is_good_state"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
list_str_good_state = ["11"]
grover = Grover(oracle=oracle, good_state=list_str_good_state)
self.assertTrue(grover.is_good_state("11"))
statevector_good_state = Statevector.from_label('11')
grover = Grover(oracle=oracle, good_state=statevector_good_state)
self.assertTrue(grover.is_good_state("11"))
list_int_good_state = [0, 1]
grover = Grover(oracle=oracle, good_state=list_int_good_state)
self.assertTrue(grover.is_good_state("11"))
def _callable_good_state(bitstr):
if bitstr == "11":
return True, bitstr
else:
return False, bitstr
grover = Grover(oracle=oracle, good_state=_callable_good_state)
self.assertTrue(grover.is_good_state("11"))
def test_construct_circuit(self):
"""Test construct_circuit"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
grover = Grover(oracle=oracle, good_state=["11"])
constructed = grover.construct_circuit(1)
grover_op = GroverOperator(oracle)
expected = QuantumCircuit(2)
expected.compose(grover_op.state_preparation, inplace=True)
expected.compose(grover_op, inplace=True)
self.assertTrue(Operator(constructed).equiv(Operator(expected)))
def test_grover_operator_getter(self):
"""Test the getter of grover_operator"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
grover = Grover(oracle=oracle, good_state=["11"])
constructed = grover.grover_operator
expected = GroverOperator(oracle)
self.assertTrue(Operator(constructed).equiv(Operator(expected)))
class TestGroverFunctionality(QiskitAlgorithmsTestCase):
"""Test for the functionality of Grover"""
def setUp(self):
super().setUp()
self._oracle = Statevector.from_label('111')
self._expected_grover_op = GroverOperator(oracle=self._oracle)
self._expected = QuantumCircuit(self._expected_grover_op.num_qubits)
self._expected.compose(self._expected_grover_op.state_preparation, inplace=True)
self._expected.compose(self._expected_grover_op.power(2), inplace=True)
backend = BasicAer.get_backend('statevector_simulator')
self._sv = QuantumInstance(backend)
def test_iterations(self):
"""Test the iterations argument"""
grover = Grover(oracle=self._oracle, good_state=['111'], iterations=2)
ret = grover.run(self._sv)
self.assertTrue(Operator(ret['circuit']).equiv(Operator(self._expected)))
grover = Grover(oracle=self._oracle, good_state=['111'], iterations=[1, 2, 3])
ret = grover.run(self._sv)
self.assertTrue(ret.oracle_evaluation)
self.assertIn(ret.top_measurement, ['111'])
class TestGroverExecution(QiskitAlgorithmsTestCase):
"""Test for the execution of Grover"""
def setUp(self):
super().setUp()
backend = BasicAer.get_backend('qasm_simulator')
self._qasm = QuantumInstance(backend)
def test_run_circuit_oracle(self):
"""Test execution with a quantum circuit oracle"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
list_good_state = ["11"]
grover = Grover(oracle=oracle, good_state=list_good_state)
ret = grover.run(self._qasm)
self.assertIn(ret['top_measurement'], list_good_state)
def test_run_state_vector_oracle(self):
"""Test execution with a state vector oracle"""
mark_state = Statevector.from_label('11')
grover = Grover(oracle=mark_state, good_state=['11'])
ret = grover.run(self._qasm)
self.assertIn(ret['top_measurement'], ['11'])
def test_run_grover_operator_oracle(self):
"""Test execution with a grover operator oracle"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
grover_op = GroverOperator(oracle)
grover = Grover(oracle=grover_op.oracle,
grover_operator=grover_op, good_state=["11"])
ret = grover.run(self._qasm)
self.assertIn(ret['top_measurement'], ['11'])
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"qiskit.algorithms.Grover",
"qiskit.QuantumCircuit",
"qiskit.BasicAer.get_backend",
"qiskit.circuit.library.GroverOperator",
"qiskit.quantum_info.Operator",
"qiskit.quantum_info.Statevector.from_label",
"qiskit.utils.QuantumInstance"
] |
[((7790, 7805), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7803, 7805), False, 'import unittest\n'), ((973, 990), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (987, 990), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((1050, 1079), 'qiskit.circuit.library.GroverOperator', 'GroverOperator', ([], {'oracle': 'oracle'}), '(oracle=oracle)\n', (1064, 1079), False, 'from qiskit.circuit.library import GroverOperator\n'), ((1181, 1198), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (1195, 1198), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((1240, 1280), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'good_state': "['11']"}), "(oracle=oracle, good_state=['11'])\n", (1246, 1280), False, 'from qiskit.algorithms import Grover\n'), ((1511, 1539), 'qiskit.quantum_info.Statevector.from_label', 'Statevector.from_label', (['"""11"""'], {}), "('11')\n", (1533, 1539), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((1557, 1601), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'mark_state', 'good_state': "['11']"}), "(oracle=mark_state, good_state=['11'])\n", (1563, 1601), False, 'from qiskit.algorithms import Grover\n'), ((1867, 1884), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (1881, 1884), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((1933, 1950), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(3)'], {}), '(3)\n', (1947, 1950), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((1992, 2070), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'state_preparation': 'state_preparation', 'good_state': "['011']"}), "(oracle=oracle, state_preparation=state_preparation, good_state=['011'])\n", (1998, 2070), False, 'from qiskit.algorithms import Grover\n'), ((2168, 2227), 'qiskit.circuit.library.GroverOperator', 'GroverOperator', (['oracle'], {'state_preparation': 'state_preparation'}), '(oracle, state_preparation=state_preparation)\n', (2182, 2227), False, 'from qiskit.circuit.library import GroverOperator\n'), ((2404, 2421), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (2418, 2421), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((2500, 2547), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'good_state': 'is_good_state'}), '(oracle=oracle, good_state=is_good_state)\n', (2506, 2547), False, 'from qiskit.algorithms import Grover\n'), ((2723, 2740), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (2737, 2740), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((2789, 2817), 'qiskit.quantum_info.Statevector.from_label', 'Statevector.from_label', (['"""11"""'], {}), "('11')\n", (2811, 2817), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((2835, 2882), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'good_state': 'is_good_state'}), '(oracle=oracle, good_state=is_good_state)\n', (2841, 2882), False, 'from qiskit.algorithms import Grover\n'), ((3054, 3071), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (3068, 3071), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((3116, 3138), 'qiskit.circuit.library.GroverOperator', 'GroverOperator', (['oracle'], {}), '(oracle)\n', (3130, 3138), False, 'from qiskit.circuit.library import GroverOperator\n'), ((3156, 3233), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'grover_op.oracle', 'grover_operator': 'grover_op', 'good_state': "['11']"}), "(oracle=grover_op.oracle, grover_operator=grover_op, good_state=['11'])\n", (3162, 3233), False, 'from qiskit.algorithms import Grover\n'), ((3581, 3598), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (3595, 3598), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((3677, 3730), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'good_state': 'list_str_good_state'}), '(oracle=oracle, good_state=list_str_good_state)\n', (3683, 3730), False, 'from qiskit.algorithms import Grover\n'), ((3817, 3845), 'qiskit.quantum_info.Statevector.from_label', 'Statevector.from_label', (['"""11"""'], {}), "('11')\n", (3839, 3845), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((3863, 3919), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'good_state': 'statevector_good_state'}), '(oracle=oracle, good_state=statevector_good_state)\n', (3869, 3919), False, 'from qiskit.algorithms import Grover\n'), ((4027, 4080), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'good_state': 'list_int_good_state'}), '(oracle=oracle, good_state=list_int_good_state)\n', (4033, 4080), False, 'from qiskit.algorithms import Grover\n'), ((4315, 4369), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'good_state': '_callable_good_state'}), '(oracle=oracle, good_state=_callable_good_state)\n', (4321, 4369), False, 'from qiskit.algorithms import Grover\n'), ((4515, 4532), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (4529, 4532), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((4574, 4614), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'good_state': "['11']"}), "(oracle=oracle, good_state=['11'])\n", (4580, 4614), False, 'from qiskit.algorithms import Grover\n'), ((4685, 4707), 'qiskit.circuit.library.GroverOperator', 'GroverOperator', (['oracle'], {}), '(oracle)\n', (4699, 4707), False, 'from qiskit.circuit.library import GroverOperator\n'), ((4727, 4744), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (4741, 4744), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((5046, 5063), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (5060, 5063), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((5105, 5145), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'good_state': "['11']"}), "(oracle=oracle, good_state=['11'])\n", (5111, 5145), False, 'from qiskit.algorithms import Grover\n'), ((5210, 5232), 'qiskit.circuit.library.GroverOperator', 'GroverOperator', (['oracle'], {}), '(oracle)\n', (5224, 5232), False, 'from qiskit.circuit.library import GroverOperator\n'), ((5481, 5510), 'qiskit.quantum_info.Statevector.from_label', 'Statevector.from_label', (['"""111"""'], {}), "('111')\n", (5503, 5510), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((5546, 5581), 'qiskit.circuit.library.GroverOperator', 'GroverOperator', ([], {'oracle': 'self._oracle'}), '(oracle=self._oracle)\n', (5560, 5581), False, 'from qiskit.circuit.library import GroverOperator\n'), ((5607, 5658), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['self._expected_grover_op.num_qubits'], {}), '(self._expected_grover_op.num_qubits)\n', (5621, 5658), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((5846, 5891), 'qiskit.BasicAer.get_backend', 'BasicAer.get_backend', (['"""statevector_simulator"""'], {}), "('statevector_simulator')\n", (5866, 5891), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((5911, 5935), 'qiskit.utils.QuantumInstance', 'QuantumInstance', (['backend'], {}), '(backend)\n', (5926, 5935), False, 'from qiskit.utils import QuantumInstance\n'), ((6028, 6089), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'self._oracle', 'good_state': "['111']", 'iterations': '(2)'}), "(oracle=self._oracle, good_state=['111'], iterations=2)\n", (6034, 6089), False, 'from qiskit.algorithms import Grover\n'), ((6225, 6294), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'self._oracle', 'good_state': "['111']", 'iterations': '[1, 2, 3]'}), "(oracle=self._oracle, good_state=['111'], iterations=[1, 2, 3])\n", (6231, 6294), False, 'from qiskit.algorithms import Grover\n'), ((6591, 6629), 'qiskit.BasicAer.get_backend', 'BasicAer.get_backend', (['"""qasm_simulator"""'], {}), "('qasm_simulator')\n", (6611, 6629), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((6651, 6675), 'qiskit.utils.QuantumInstance', 'QuantumInstance', (['backend'], {}), '(backend)\n', (6666, 6675), False, 'from qiskit.utils import QuantumInstance\n'), ((6792, 6809), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (6806, 6809), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((6884, 6933), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'oracle', 'good_state': 'list_good_state'}), '(oracle=oracle, good_state=list_good_state)\n', (6890, 6933), False, 'from qiskit.algorithms import Grover\n'), ((7156, 7184), 'qiskit.quantum_info.Statevector.from_label', 'Statevector.from_label', (['"""11"""'], {}), "('11')\n", (7178, 7184), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((7202, 7246), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'mark_state', 'good_state': "['11']"}), "(oracle=mark_state, good_state=['11'])\n", (7208, 7246), False, 'from qiskit.algorithms import Grover\n'), ((7462, 7479), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['(2)'], {}), '(2)\n', (7476, 7479), False, 'from qiskit import BasicAer, QuantumCircuit\n'), ((7524, 7546), 'qiskit.circuit.library.GroverOperator', 'GroverOperator', (['oracle'], {}), '(oracle)\n', (7538, 7546), False, 'from qiskit.circuit.library import GroverOperator\n'), ((7564, 7641), 'qiskit.algorithms.Grover', 'Grover', ([], {'oracle': 'grover_op.oracle', 'grover_operator': 'grover_op', 'good_state': "['11']"}), "(oracle=grover_op.oracle, grover_operator=grover_op, good_state=['11'])\n", (7570, 7641), False, 'from qiskit.algorithms import Grover\n'), ((1375, 1409), 'qiskit.quantum_info.Operator', 'Operator', (['self._expected_grover_op'], {}), '(self._expected_grover_op)\n', (1383, 1409), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((1696, 1730), 'qiskit.quantum_info.Operator', 'Operator', (['self._expected_grover_op'], {}), '(self._expected_grover_op)\n', (1704, 1730), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((2278, 2306), 'qiskit.quantum_info.Operator', 'Operator', (['expected_grover_op'], {}), '(expected_grover_op)\n', (2286, 2306), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((2935, 2963), 'qiskit.quantum_info.Statevector.from_label', 'Statevector.from_label', (['"""11"""'], {}), "('11')\n", (2957, 2963), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((3352, 3386), 'qiskit.quantum_info.Operator', 'Operator', (['self._expected_grover_op'], {}), '(self._expected_grover_op)\n', (3360, 3386), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((4915, 4933), 'qiskit.quantum_info.Operator', 'Operator', (['expected'], {}), '(expected)\n', (4923, 4933), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((5285, 5303), 'qiskit.quantum_info.Operator', 'Operator', (['expected'], {}), '(expected)\n', (5293, 5303), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((6180, 6204), 'qiskit.quantum_info.Operator', 'Operator', (['self._expected'], {}), '(self._expected)\n', (6188, 6204), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((1349, 1368), 'qiskit.quantum_info.Operator', 'Operator', (['grover_op'], {}), '(grover_op)\n', (1357, 1368), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((1670, 1689), 'qiskit.quantum_info.Operator', 'Operator', (['grover_op'], {}), '(grover_op)\n', (1678, 1689), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((2252, 2271), 'qiskit.quantum_info.Operator', 'Operator', (['grover_op'], {}), '(grover_op)\n', (2260, 2271), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((3326, 3345), 'qiskit.quantum_info.Operator', 'Operator', (['grover_op'], {}), '(grover_op)\n', (3334, 3345), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((4887, 4908), 'qiskit.quantum_info.Operator', 'Operator', (['constructed'], {}), '(constructed)\n', (4895, 4908), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((5257, 5278), 'qiskit.quantum_info.Operator', 'Operator', (['constructed'], {}), '(constructed)\n', (5265, 5278), False, 'from qiskit.quantum_info import Operator, Statevector\n'), ((6149, 6173), 'qiskit.quantum_info.Operator', 'Operator', (["ret['circuit']"], {}), "(ret['circuit'])\n", (6157, 6173), False, 'from qiskit.quantum_info import Operator, Statevector\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 17 15:42:13 2018
amortization_table.py
@author: david
# source for most of Mortgage class' basic functions
# https://github.com/jbmohler/mortgage/blob/master/mortgage.py
"""
import argparse
import decimal
import os
import pandas as pd
import numpy as np
import datetime as dt
class Mortgage:
"""Contains properties of a mortgage given user inputs
Args:
_amount (float): Loan amount
_price(float): Price of house
_rate (float): Interest rate as a decimal i.e. 0.05
_term (int): Length of the loan in years
_taxes (float): Annual tax bill
_insurance (float): Annual insurance bill
_additional (float): Extra payment in each month that goes toward principal
"""
def __init__(self, amount, price, rate, term, taxes, insurance, additional=0):
"""init function for Mortgage class"""
self._amount = amount
self._price = price
self._rate = rate
self._term = term
self._taxes = taxes
self._insurance = insurance
self._add_pmt = additional
self._total_combined_payments = float(0)
self._payment_months = float(0)
self._inflation = float(0.03)
self._pv_payments = float(0)
self._pv_combined_payments = float(0)
self._first_payment = '1/1/2018' # future update
self._pay_freq = 'Monthly' # only option for now
self._compound_freq = 'Monthly' # only option for now
self._pay_type = 'End of Period' # only option for now
self.MONTHS_IN_YEAR = 12
self.DOLLAR_QUANTIZE = decimal.Decimal('.01')
def dollar(self, f, round=decimal.ROUND_CEILING):
"""Returns the passed float rounded to two decimal places"""
if not isinstance(f, decimal.Decimal):
f = decimal.Decimal(str(f)) # force f into decimal
return f.quantize(self.DOLLAR_QUANTIZE, rounding=round)
def rate(self):
"""Returns the interest rate of the loan"""
return self._rate
def monthly_growth(self):
"""Returns the monthly interest accrual of the loan"""
return 1.0 + self._rate / self.MONTHS_IN_YEAR
def loan_years(self):
"""Returns the term, in years, of the loan"""
return self._term
def loan_months(self):
"""Returns the term, in months, of the loan"""
return self._term * self.MONTHS_IN_YEAR
def price(self):
"""Returns the house price"""
return self._price
def amount(self):
"""Returns the amount of the loan"""
return self._amount
def additional_pmt(self):
"""Returns the additional monthly principal payment"""
return self._add_pmt
def taxes(self):
"""Returns the annual taxes due"""
return self._taxes
def monthly_taxes(self):
"""Returns the monthly taxes due"""
return self._taxes / self.MONTHS_IN_YEAR
def insurance(self):
"""Returns the annual insurance amount due"""
return self._insurance * self.price()
def monthly_insurance(self):
"""Returns the monthly insurance due"""
return self.insurance() / self.MONTHS_IN_YEAR
def monthly_payment(self):
"""Returns the monthly payment for the loan"""
pmt = (self.amount() * self.rate()) / (self.MONTHS_IN_YEAR * (1.0-(1.0/self.monthly_growth()) ** self.loan_months()))
return pmt
def annual_payment(self):
"""Returns the total payments during the year for the loan"""
return self.monthly_payment() * self.MONTHS_IN_YEAR
def total_payment(self):
"""Returns the total cost of the loan"""
return self.monthly_payment() * self.loan_months()
def piti(self):
"""Returns the monthly PITI"""
return self.monthly_payment() + self.monthly_taxes() + self.monthly_insurance()
def monthly_payment_schedule(self):
"""Yields amortization schedule for the given loan"""
monthly = float(self.dollar(self.monthly_payment()))
additional = float(self.dollar(self.additional_pmt()))
balance = float(self.dollar(self.amount()))
end_balance = float(self.dollar(balance))
rate = float(decimal.Decimal(str(self.rate())).quantize(decimal.Decimal('.000001')))
while True:
interest_unrounded = balance * rate * float(decimal.Decimal(1) / self.MONTHS_IN_YEAR)
interest = float(self.dollar(interest_unrounded, round=decimal.ROUND_HALF_UP))
if monthly >= balance + interest: # check if payment exceeds remaining due
# last pmt
additional = 0.0
principal = float(self.dollar(end_balance))
end_balance -= float(self.dollar(principal + additional))
yield float(self.dollar(balance)), float(self.dollar((principal + interest))), additional, interest, principal, float(self.dollar(end_balance))
break
elif (monthly + additional) >= balance + interest: # check if pmt + add exceeds remaining due
principal = float(self.dollar(monthly - interest))
additional = (balance + interest) - monthly
end_balance -= float(self.dollar(principal + additional))
yield float(self.dollar(balance)), float(self.dollar((principal + interest))), additional, interest, principal, float(self.dollar(end_balance))
break
principal = float(self.dollar(monthly - interest))
end_balance -= (principal + additional)
yield float(self.dollar(balance)), monthly, additional, interest, principal, float(self.dollar(end_balance))
balance = end_balance
def print_monthly_payment_schedule(self):
"""Prints out the monthly payment schedule"""
for index, payment in enumerate(self.monthly_payment_schedule()):
print(index + 1, payment[0], payment[1], payment[2], payment[3], payment[4], payment[5])
def amortization_dict(self):
"""Returns a dictionary with the payment schedule"""
amort_dict = {}
for index, payment in enumerate(self.monthly_payment_schedule()):
amort_dict[index + 1] = [payment[0], payment[1], payment[2], payment[3], payment[4], payment[5]]
return amort_dict
def amortization_table(self):
"""Returns a dataframe with the amortization table in it"""
names = ['Beg. Balance', 'Monthly Payment', 'Additional Payment',
'Interest', 'Principal', 'End Balance']
df = pd.DataFrame.from_dict(self.amortization_dict(), orient='index')
df.columns = names
monthly_inflation = self._inflation / 12
if sum(df['Additional Payment'].values) != 0: #check if there are additional payments
df['Total Payment'] = df['Monthly Payment'] + df['Additional Payment']
self._total_combined_payments = sum(df['Total Payment'].values)
self._payment_months = df.shape[0]
# calc PV of original terms
arr_months = np.array(range(self.loan_years() * 12))
arr_m_payment = np.array(self.monthly_payment())
list_inflation = []
for month in arr_months:
list_inflation.append((1 + monthly_inflation) ** month)
arr_inflation = np.array(list_inflation)
arr_pv_payments = np.divide(arr_m_payment, arr_inflation)
self._pv_payments = sum(arr_pv_payments)
# add combined PV factor
arr_c_months = np.array(range(self._payment_months))
list_c_inflation = []
for month in arr_c_months:
list_c_inflation.append((1 + monthly_inflation) ** month)
arr_c_inflation = np.array(list_c_inflation)
df['PV of Combined Payment'] = (df['Monthly Payment'] + df['Additional Payment']) / arr_c_inflation
self._pv_combined_payments = sum(df['PV of Combined Payment'].values)
return df
else:
# add PV factor
arr_months = np.array(range(self.loan_months()))
list_inflation = []
for month in arr_months:
list_inflation.append((1 + monthly_inflation) ** month)
arr_inflation = np.array(list_inflation)
df['PV of Payment'] = df['Monthly Payment'] / arr_inflation
self._pv_payments = sum(df['PV of Payment'].values)
return df
def amort_table_to_csv(self):
"""Outputs the amortization table to a .csv file"""
now = dt.datetime.today()
date = str(now.year) + str(now.month) + str(now.day) + '_' + str(now.hour) + str(now.minute)
self.amortization_table().to_csv('/home/david/git_repos/mortgage/output/' + date + '.csv')
def print_summary(self):
"""Prints out a summary of the given mortgage"""
print('Mortgage Summary')
print('-' * 75)
print('{0:>30s}: ${1:>11,.0f}'.format('House Price', self.price()))
print('')
print('{0:>30s}: ${1:>11,.0f}'.format('Loan Amount', self.amount()))
print('{0:>30s}: {1:>12.0f}'.format('Term (years)', self.loan_years()))
print('{0:>30s}: {1:>12.2f}%'.format('Rate', self.rate()*100))
print('{0:>30s}: ${1:>11,.0f}'.format('Monthly Mortgage Payment', self.monthly_payment()))
print('{0:>30s}: ${1:>11,.0f}'.format('Annual Mortgage Payment', self.annual_payment()))
print('{0:>30s}: ${1:>11,.0f}'.format('Total Mortgage Payment', self.total_payment()))
print('{0:>30s}: ${1:>11,.0f}'.format('Total PV of Payments', self._pv_payments))
print('')
print('{0:>30s}: ${1:>11,.0f}'.format('Annual Taxes', self.taxes()))
print('{0:>30s}: ${1:>11,.0f}'.format('Annual Insurance', self.insurance()))
print('')
print('{0:>30s}: ${1:>11,.0f}'.format('Monthly PITI', self.piti()))
print('-' * 75)
if self._total_combined_payments != 0:
new_monthly = self._total_combined_payments / self._payment_months
new_annual = self._total_combined_payments / self._payment_months * 12
change_months = self._payment_months - self.loan_months()
change_monthly = new_monthly - self.monthly_payment()
change_annual = new_annual - self.annual_payment()
change_total = self._total_combined_payments - self.total_payment()
change_pv = self._pv_combined_payments - self._pv_payments
print('Effect of paying an additional ${0:,.0f} each month:'.format(self.additional_pmt()))
print("")
print('{0:>30s}: {1:>12.1f} {2:>10.1f} years'.format('Term (years)', self._payment_months/12.0, change_months/12.0))
print('{0:>30s}: ${1:>11,.0f} ${2:>10,.0f}'.format('Monthly Mortgage Payment', new_monthly, change_monthly))
print('{0:>30s}: ${1:>11,.0f} ${2:>10,.0f}'.format('Annual Mortgage Payment', new_annual, change_annual))
print('{0:>30s}: ${1:>11,.0f} ${2:>10,.0f}'.format('Total Mortgage Payment', self._total_combined_payments, change_total))
print('{0:>30s}: ${1:>11,.0f} ${2:>10,.0f}'.format('PV of Combined Payments', self._pv_combined_payments, change_pv))
print('')
print('{0:>30s}: ${1:>11,.0f}'.format('Annual Taxes', self.taxes()))
print('{0:>30s}: ${1:>11,.0f}'.format('Annual Insurance', self.insurance()))
print('')
print('{0:>30s}: ${1:>11,.0f}'.format('Monthly PITI', new_monthly + self.monthly_taxes() + self.monthly_insurance()))
print('-' * 75)
# re-reference totals to include additional payments (new function needed)
# pv of payments
def main(self, csv=False):
"""Generates an amortization table and prints the summary"""
self.amortization_table() # print [0] for the table # need to run to get summary stats
if csv == True:
self.amort_table_to_csv() #optional, use if want to export
self.print_summary()
def main():
parser = argparse.ArgumentParser(description='Mortgage Tools')
parser.add_argument('-r', '--interest', default=5, dest='interest')
parser.add_argument('-y', '--loan-years', default=30, dest='years')
parser.add_argument('-p', '--price', default=250000, dest='price')
parser.add_argument('-a', '--amount', default=200000, dest='amount')
parser.add_argument('-t', '--taxes', default=7000, dest ='taxes')
parser.add_argument('-i', '--insurance', default=0.0035, dest='insurance')
parser.add_argument('-e', '--extra payment', default=None, dest='extra')
args = parser.parse_args()
if args.extra:
m = Mortgage(float(args.amount), float(args.price), float(args.interest) / 100.0, int(args.years), float(args.taxes), float(args.insurance), float(args.extra))
else:
m = Mortgage(float(args.amount), float(args.price), float(args.interest) / 100.0, int(args.years), float(args.taxes), float(args.insurance))
m.main()
if __name__ == '__main__':
main()
|
[
"numpy.divide",
"datetime.datetime.today",
"argparse.ArgumentParser",
"decimal.Decimal",
"numpy.array"
] |
[((12232, 12285), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Mortgage Tools"""'}), "(description='Mortgage Tools')\n", (12255, 12285), False, 'import argparse\n'), ((1697, 1719), 'decimal.Decimal', 'decimal.Decimal', (['""".01"""'], {}), "('.01')\n", (1712, 1719), False, 'import decimal\n'), ((8705, 8724), 'datetime.datetime.today', 'dt.datetime.today', ([], {}), '()\n', (8722, 8724), True, 'import datetime as dt\n'), ((7470, 7494), 'numpy.array', 'np.array', (['list_inflation'], {}), '(list_inflation)\n', (7478, 7494), True, 'import numpy as np\n'), ((7525, 7564), 'numpy.divide', 'np.divide', (['arr_m_payment', 'arr_inflation'], {}), '(arr_m_payment, arr_inflation)\n', (7534, 7564), True, 'import numpy as np\n'), ((7898, 7924), 'numpy.array', 'np.array', (['list_c_inflation'], {}), '(list_c_inflation)\n', (7906, 7924), True, 'import numpy as np\n'), ((8413, 8437), 'numpy.array', 'np.array', (['list_inflation'], {}), '(list_inflation)\n', (8421, 8437), True, 'import numpy as np\n'), ((4380, 4406), 'decimal.Decimal', 'decimal.Decimal', (['""".000001"""'], {}), "('.000001')\n", (4395, 4406), False, 'import decimal\n'), ((4485, 4503), 'decimal.Decimal', 'decimal.Decimal', (['(1)'], {}), '(1)\n', (4500, 4503), False, 'import decimal\n')]
|
from requests.utils import requote_uri
from base64 import b64decode
from hashlib import md5
from Crypto.Cipher import AES
class TwistSourceDecryptor:
BLOCK_SIZE = 16
SECRET_KEY = b'<KEY>'
def __init__(self, enc_src):
self.enc_src = enc_src.encode('utf-8')
def __pad(self, data):
length = self.BLOCK_SIZE - (len(data) % self.BLOCK_SIZE)
return data + (chr(length) * length).encode()
def __unpad(self, data):
# print(data[-1])
return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))]
def __get_key_iv(self, data, salt, output=48):
assert len(salt) == 8, len(salt)
data += salt
key = md5(data).digest()
key_iv_data = key
while len(key_iv_data) < output:
key = md5(key + data).digest()
key_iv_data += key
return key_iv_data[:output]
def decrypt(self):
enc_data = b64decode(self.enc_src)
# print("b64decode enc :", enc_data)
assert enc_data[:8] == b'Salted__'
salt = enc_data[8:16] # 8byte salt
key_iv = self.__get_key_iv(self.SECRET_KEY, salt) # key+iv is 48bytes
key = key_iv[:32] # key is 32byte
iv = key_iv[32:] # 16byte iv
# print("key :", key)
# print("iv :", iv)
aes = AES.new(key, AES.MODE_CBC, iv)
decrypt_data = aes.decrypt(enc_data[16:]) # actual data are after first 16bytes (which is salt)
decrypt_data = self.__unpad(decrypt_data).decode('utf-8').lstrip(' ')
# print(decrypt_data)
return requote_uri(decrypt_data) # parse to url safe value
# if __name__ == "__main__":
# enc = "<KEY>
# dec = TwistSourceDecryptor(enc).decrypt()
# print(dec)
|
[
"hashlib.md5",
"Crypto.Cipher.AES.new",
"base64.b64decode",
"requests.utils.requote_uri"
] |
[((928, 951), 'base64.b64decode', 'b64decode', (['self.enc_src'], {}), '(self.enc_src)\n', (937, 951), False, 'from base64 import b64decode\n'), ((1318, 1348), 'Crypto.Cipher.AES.new', 'AES.new', (['key', 'AES.MODE_CBC', 'iv'], {}), '(key, AES.MODE_CBC, iv)\n', (1325, 1348), False, 'from Crypto.Cipher import AES\n'), ((1578, 1603), 'requests.utils.requote_uri', 'requote_uri', (['decrypt_data'], {}), '(decrypt_data)\n', (1589, 1603), False, 'from requests.utils import requote_uri\n'), ((688, 697), 'hashlib.md5', 'md5', (['data'], {}), '(data)\n', (691, 697), False, 'from hashlib import md5\n'), ((792, 807), 'hashlib.md5', 'md5', (['(key + data)'], {}), '(key + data)\n', (795, 807), False, 'from hashlib import md5\n')]
|
import uuid
from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey
from sqlalchemy.orm import composite, relation
from .person import PersonType
# change of the __doc__ string as getting error in sphinx ==> should be reported to SA project
composite.__doc__ = None # composite.__doc__.replace(":ref:`mapper_composite`", "")
from ..sa_extra import _DateTime
from .._common import CallableList, hybrid_property_gncnumeric
from .._declbase import DeclarativeBaseGuid
class Billterm(DeclarativeBaseGuid):
__tablename__ = 'billterms'
__table_args__ = {}
# column definitions
guid = Column('guid', VARCHAR(length=32), primary_key=True, nullable=False, default=lambda: uuid.uuid4().hex)
name = Column('name', VARCHAR(length=2048), nullable=False)
description = Column('description', VARCHAR(length=2048), nullable=False)
refcount = Column('refcount', INTEGER(), nullable=False)
invisible = Column('invisible', INTEGER(), nullable=False)
parent_guid = Column('parent', VARCHAR(length=32), ForeignKey('billterms.guid'))
type = Column('type', VARCHAR(length=2048), nullable=False)
duedays = Column('duedays', INTEGER())
discountdays = Column('discountdays', INTEGER())
_discount_num = Column('discount_num', BIGINT())
_discount_denom = Column('discount_denom', BIGINT())
discount = hybrid_property_gncnumeric(_discount_num, _discount_denom)
cutoff = Column('cutoff', INTEGER())
# relation definitions
children = relation('Billterm',
back_populates='parent',
cascade='all, delete-orphan',
collection_class=CallableList,
)
parent = relation('Billterm',
back_populates='children',
remote_side=guid,
)
class Entry(DeclarativeBaseGuid):
__tablename__ = 'entries'
__table_args__ = {}
# column definitions
date = Column('date', _DateTime(), nullable=False)
date_entered = Column('date_entered', _DateTime())
description = Column('description', VARCHAR(length=2048))
action = Column('action', VARCHAR(length=2048))
notes = Column('notes', VARCHAR(length=2048))
_quantity_num = Column('quantity_num', BIGINT())
_quantity_denom = Column('quantity_denom', BIGINT())
_quantity_denom_basis = None
quantity = hybrid_property_gncnumeric(_quantity_num, _quantity_denom)
i_acct = Column('i_acct', VARCHAR(length=32))
_i_price_num = Column('i_price_num', BIGINT())
_i_price_denom = Column('i_price_denom', BIGINT())
_i_price_denom_basis = None
i_price = hybrid_property_gncnumeric(_i_price_num, _i_price_denom)
_i_discount_num = Column('i_discount_num', BIGINT())
_i_discount_denom = Column('i_discount_denom', BIGINT())
_i_discount_denom_basis = None
i_discount = hybrid_property_gncnumeric(_i_discount_num, _i_discount_denom)
invoice_guid = Column('invoice', VARCHAR(length=32), ForeignKey("invoices.guid"))
i_disc_type = Column('i_disc_type', VARCHAR(length=2048))
i_disc_how = Column('i_disc_how', VARCHAR(length=2048))
i_taxable = Column('i_taxable', INTEGER())
i_taxincluded = Column('i_taxincluded', INTEGER())
i_taxtable = Column('i_taxtable', VARCHAR(length=32))
b_acct = Column('b_acct', VARCHAR(length=32))
_b_price_num = Column('b_price_num', BIGINT())
_b_price_denom = Column('b_price_denom', BIGINT())
_b_price_denom_basis = None
b_price = hybrid_property_gncnumeric(_b_price_num, _b_price_denom)
bill = Column('bill', VARCHAR(length=32))
b_taxable = Column('b_taxable', INTEGER())
b_taxincluded = Column('b_taxincluded', INTEGER())
b_taxtable = Column('b_taxtable', VARCHAR(length=32))
b_paytype = Column('b_paytype', INTEGER())
billable = Column('billable', INTEGER())
billto_type = Column('billto_type', INTEGER())
billto_guid = Column('billto_guid', VARCHAR(length=32))
order_guid = Column('order_guid', VARCHAR(length=32), ForeignKey("orders.guid"))
# relation definitions
order = relation('Order', back_populates="entries")
invoice = relation('Invoice', back_populates="entries")
def __str__(self):
return "Entry<{}>".format(self.description)
class Invoice(DeclarativeBaseGuid):
__tablename__ = 'invoices'
__table_args__ = {}
# column definitions
id = Column('id', VARCHAR(length=2048), nullable=False)
date_opened = Column('date_opened', _DateTime())
date_posted = Column('date_posted', _DateTime())
notes = Column('notes', VARCHAR(length=2048), nullable=False)
active = Column('active', INTEGER(), nullable=False)
currency_guid = Column('currency', VARCHAR(length=32), ForeignKey('commodities.guid'), nullable=False)
owner_type = Column('owner_type', INTEGER())
owner_guid = Column('owner_guid', VARCHAR(length=32))
# owner = generic_relationship(owner_type, owner_guid,
# map_type2discriminator={"Customer": 2,
# "Vendor": 1,
# })
term_guid = Column('terms', VARCHAR(length=32), ForeignKey('billterms.guid'))
billing_id = Column('billing_id', VARCHAR(length=2048))
post_txn_guid = Column('post_txn', VARCHAR(length=32), ForeignKey('lots.guid'))
post_lot_guid = Column('post_lot', VARCHAR(length=32), ForeignKey('transactions.guid'))
post_acc_guid = Column('post_acc', VARCHAR(length=32), ForeignKey('accounts.guid'))
billto_type = Column('billto_type', INTEGER())
billto_guid = Column('billto_guid', VARCHAR(length=32))
_charge_amt_num = Column('charge_amt_num', BIGINT())
_charge_amt_denom = Column('charge_amt_denom', BIGINT())
charge_amt = hybrid_property_gncnumeric(_charge_amt_num, _charge_amt_denom)
# relation definitions
# todo: check all relations and understanding of types...
term = relation('Billterm')
currency = relation('Commodity')
post_account = relation('Account')
post_lot = relation('Lot')
post_txn = relation('Transaction')
entries = relation('Entry',
back_populates='invoice',
cascade='all, delete-orphan',
collection_class=CallableList,
)
def __str__(self):
return "Invoice<{}>".format(self.id)
class Job(DeclarativeBaseGuid):
__tablename__ = 'jobs'
__table_args__ = {}
# column definitions
id = Column('id', VARCHAR(length=2048), nullable=False)
name = Column('name', VARCHAR(length=2048), nullable=False)
reference = Column('reference', VARCHAR(length=2048), nullable=False)
active = Column('active', INTEGER(), nullable=False)
owner_type = Column('owner_type', INTEGER())
owner_guid = Column('owner_guid', VARCHAR(length=32))
# relation definitions
# todo: owner_guid/type links to Vendor or Customer
def __init__(self, name, owner, reference="", active=1):
self.name = name
self.reference = reference
self.active = active
self.owner_type = PersonType[type(owner)]
self.owner_guid = owner.guid
if owner.book:
owner.book.add(self)
def __str__(self):
return "Job<{self.name}>".format(self=self)
def on_book_add(self):
self._assign_id()
# hold the name of the counter to use for id
_counter_name = "counter_job"
def _assign_id(self):
if not self.id:
cnt = getattr(self.book, self._counter_name) + 1
setattr(self.book, self._counter_name, cnt)
self.id = "{:06d}".format(cnt)
# This class exists in code but not in the GUI (to confirm?)
class Order(DeclarativeBaseGuid):
__tablename__ = 'orders'
__table_args__ = {}
# column definitions
id = Column('id', VARCHAR(length=2048), nullable=False)
notes = Column('notes', VARCHAR(length=2048), nullable=False)
reference = Column('reference', VARCHAR(length=2048), nullable=False)
active = Column('active', INTEGER(), nullable=False)
date_opened = Column('date_opened', _DateTime(), nullable=False)
date_closed = Column('date_closed', _DateTime(), nullable=False)
owner_type = Column('owner_type', INTEGER(), nullable=False)
owner_guid = Column('owner_guid', VARCHAR(length=32), nullable=False)
# relation definitions
# todo: owner_guid/type links to Vendor or Customer
entries = relation('Entry',
back_populates='order',
cascade='all, delete-orphan',
collection_class=CallableList,
)
|
[
"uuid.uuid4",
"sqlalchemy.BIGINT",
"sqlalchemy.INTEGER",
"sqlalchemy.VARCHAR",
"sqlalchemy.ForeignKey",
"sqlalchemy.orm.relation"
] |
[((1498, 1608), 'sqlalchemy.orm.relation', 'relation', (['"""Billterm"""'], {'back_populates': '"""parent"""', 'cascade': '"""all, delete-orphan"""', 'collection_class': 'CallableList'}), "('Billterm', back_populates='parent', cascade='all, delete-orphan',\n collection_class=CallableList)\n", (1506, 1608), False, 'from sqlalchemy.orm import composite, relation\n'), ((1716, 1781), 'sqlalchemy.orm.relation', 'relation', (['"""Billterm"""'], {'back_populates': '"""children"""', 'remote_side': 'guid'}), "('Billterm', back_populates='children', remote_side=guid)\n", (1724, 1781), False, 'from sqlalchemy.orm import composite, relation\n'), ((4115, 4158), 'sqlalchemy.orm.relation', 'relation', (['"""Order"""'], {'back_populates': '"""entries"""'}), "('Order', back_populates='entries')\n", (4123, 4158), False, 'from sqlalchemy.orm import composite, relation\n'), ((4173, 4218), 'sqlalchemy.orm.relation', 'relation', (['"""Invoice"""'], {'back_populates': '"""entries"""'}), "('Invoice', back_populates='entries')\n", (4181, 4218), False, 'from sqlalchemy.orm import composite, relation\n'), ((6002, 6022), 'sqlalchemy.orm.relation', 'relation', (['"""Billterm"""'], {}), "('Billterm')\n", (6010, 6022), False, 'from sqlalchemy.orm import composite, relation\n'), ((6038, 6059), 'sqlalchemy.orm.relation', 'relation', (['"""Commodity"""'], {}), "('Commodity')\n", (6046, 6059), False, 'from sqlalchemy.orm import composite, relation\n'), ((6079, 6098), 'sqlalchemy.orm.relation', 'relation', (['"""Account"""'], {}), "('Account')\n", (6087, 6098), False, 'from sqlalchemy.orm import composite, relation\n'), ((6114, 6129), 'sqlalchemy.orm.relation', 'relation', (['"""Lot"""'], {}), "('Lot')\n", (6122, 6129), False, 'from sqlalchemy.orm import composite, relation\n'), ((6145, 6168), 'sqlalchemy.orm.relation', 'relation', (['"""Transaction"""'], {}), "('Transaction')\n", (6153, 6168), False, 'from sqlalchemy.orm import composite, relation\n'), ((6184, 6292), 'sqlalchemy.orm.relation', 'relation', (['"""Entry"""'], {'back_populates': '"""invoice"""', 'cascade': '"""all, delete-orphan"""', 'collection_class': 'CallableList'}), "('Entry', back_populates='invoice', cascade='all, delete-orphan',\n collection_class=CallableList)\n", (6192, 6292), False, 'from sqlalchemy.orm import composite, relation\n'), ((8539, 8645), 'sqlalchemy.orm.relation', 'relation', (['"""Entry"""'], {'back_populates': '"""order"""', 'cascade': '"""all, delete-orphan"""', 'collection_class': 'CallableList'}), "('Entry', back_populates='order', cascade='all, delete-orphan',\n collection_class=CallableList)\n", (8547, 8645), False, 'from sqlalchemy.orm import composite, relation\n'), ((631, 649), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (638, 649), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((745, 765), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (752, 765), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((823, 843), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (830, 843), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((895, 904), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (902, 904), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((958, 967), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (965, 967), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((1020, 1038), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (1027, 1038), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((1040, 1068), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""billterms.guid"""'], {}), "('billterms.guid')\n", (1050, 1068), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((1096, 1116), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (1103, 1116), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((1166, 1175), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (1173, 1175), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((1219, 1228), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (1226, 1228), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((1273, 1281), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (1279, 1281), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((1330, 1338), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (1336, 1338), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((1444, 1453), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (1451, 1453), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2117, 2137), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (2124, 2137), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2169, 2189), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (2176, 2189), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2219, 2239), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (2226, 2239), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2284, 2292), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (2290, 2292), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2341, 2349), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (2347, 2349), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2489, 2507), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (2496, 2507), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2550, 2558), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (2556, 2558), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2605, 2613), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (2611, 2613), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2766, 2774), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (2772, 2774), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2827, 2835), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (2833, 2835), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((2990, 3008), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (2997, 3008), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3010, 3037), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""invoices.guid"""'], {}), "('invoices.guid')\n", (3020, 3037), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3079, 3099), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (3086, 3099), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3139, 3159), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (3146, 3159), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3197, 3206), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (3204, 3206), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3252, 3261), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (3259, 3261), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3301, 3319), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (3308, 3319), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3352, 3370), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (3359, 3370), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3413, 3421), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (3419, 3421), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3468, 3476), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (3474, 3476), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3607, 3625), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (3614, 3625), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3663, 3672), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (3670, 3672), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3718, 3727), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (3725, 3727), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3767, 3785), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (3774, 3785), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3823, 3832), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (3830, 3832), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3868, 3877), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (3875, 3877), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3919, 3928), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (3926, 3928), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((3970, 3988), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (3977, 3988), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((4028, 4046), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (4035, 4046), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((4048, 4073), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""orders.guid"""'], {}), "('orders.guid')\n", (4058, 4073), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((4437, 4457), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (4444, 4457), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((4609, 4629), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (4616, 4629), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((4677, 4686), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (4684, 4686), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((4743, 4761), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (4750, 4761), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((4763, 4793), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""commodities.guid"""'], {}), "('commodities.guid')\n", (4773, 4793), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((4849, 4858), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (4856, 4858), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((4898, 4916), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (4905, 4916), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5218, 5236), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (5225, 5236), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5238, 5266), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""billterms.guid"""'], {}), "('billterms.guid')\n", (5248, 5266), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5306, 5326), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (5313, 5326), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5367, 5385), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (5374, 5385), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5387, 5410), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""lots.guid"""'], {}), "('lots.guid')\n", (5397, 5410), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5451, 5469), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (5458, 5469), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5471, 5502), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""transactions.guid"""'], {}), "('transactions.guid')\n", (5481, 5502), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5543, 5561), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (5550, 5561), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5563, 5590), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""accounts.guid"""'], {}), "('accounts.guid')\n", (5573, 5590), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5632, 5641), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (5639, 5641), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5683, 5701), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (5690, 5701), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5750, 5758), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (5756, 5758), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((5811, 5819), 'sqlalchemy.BIGINT', 'BIGINT', ([], {}), '()\n', (5817, 5819), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((6586, 6606), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (6593, 6606), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((6650, 6670), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (6657, 6670), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((6724, 6744), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (6731, 6744), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((6792, 6801), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (6799, 6801), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((6857, 6866), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (6864, 6866), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((6906, 6924), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (6913, 6924), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((7928, 7948), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (7935, 7948), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((7994, 8014), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (8001, 8014), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((8068, 8088), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(2048)'}), '(length=2048)\n', (8075, 8088), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((8136, 8145), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (8143, 8145), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((8340, 8349), 'sqlalchemy.INTEGER', 'INTEGER', ([], {}), '()\n', (8347, 8349), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((8405, 8423), 'sqlalchemy.VARCHAR', 'VARCHAR', ([], {'length': '(32)'}), '(length=32)\n', (8412, 8423), False, 'from sqlalchemy import Column, INTEGER, BIGINT, VARCHAR, ForeignKey\n'), ((701, 713), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (711, 713), False, 'import uuid\n')]
|
#! /usr/bin/python3
# coding: utf-8
# Generate a markdown file from Bibtex entries for "academicpages"
import os
import bibtexparser as bp
from bibtexparser.bwriter import BibTexWriter
from bibtexparser.bibdatabase import BibDatabase
bibfile = open("/home/cwatson/texmf/bib/bib/personal.bib")
bibdb = bp.load(bibfile)
## Escape special characters
# YAML is very picky about how it takes a valid string, so we are replacing single and double quotes
# (and ampersands) with their HTML encoded equivalents.
# This makes them look not so readable in raw format, but they are parsed and rendered nicely.
html_escape_table = {
"&": "&",
'"': """,
"'": "'"
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in text)
# Loop through all entries in the bibtex file and concatenate a string containing
# the markdown for each type. YAML metadata is first, then the description for each pub.
for entries in bibdb.entries_dict:
entry = bibdb.entries_dict.get(entries)
# YAML variables
#-----------------------------------
ID = entry.get('ID')
year = entry.get('year')
date = entry.get('date')
journal = html_escape(entry.get('journal'))
title = entry.get('title').replace('{', '')
title = title.replace('}', '')
if 'url' in entry:
url = entry.get('url')
else:
if 'doi' in entry:
doi = entry.get('doi')
if doi[0] == '1':
url = "https://doi.org/" + doi
else:
url = doi
else:
url = "https://cwatson.github.io/"
#TODO add bold tags around my name
citation = entry.get('author') + " (" + year + "). <u>" + title + "</u>."
citation += " <i>" + journal + "</i>. " + entry.get('volume')
if 'number' in entry:
citation += "(" + entry.get('number') + ")"
pages = entry.get('pages').replace(' ', '')
pages = pages.replace('--', '-')
citation += ":" + pages + "."
#TODO add PMID and/or PMCID if they exist
# Write the YAML header itself
#-----------------------------------
md = "---\ntitle: \"" + title + "\""
md += """\ncollection: publications"""
md += """\npermalink: /publication/""" + ID
md += "\ndate: " + date
md += "\nvenue: '" + journal + "'"
md += "\npaperurl: '" + url + "'"
md += "\ncitation: '" + html_escape(citation) + "'\n---"
# Content for individual page
#-----------------------------------
md += "\n\n<a href='" + url + "'>Download paper here</a>\n"
md_filename = ID + ".md"
md_filename = os.path.basename(md_filename)
with open("../_publications/" + md_filename, 'w') as f:
f.write(md)
|
[
"bibtexparser.load",
"os.path.basename"
] |
[((302, 318), 'bibtexparser.load', 'bp.load', (['bibfile'], {}), '(bibfile)\n', (309, 318), True, 'import bibtexparser as bp\n'), ((2637, 2666), 'os.path.basename', 'os.path.basename', (['md_filename'], {}), '(md_filename)\n', (2653, 2666), False, 'import os\n')]
|
""" This document defines the UserManager class"""
# django
from django.contrib.auth.models import BaseUserManager
from django.db import models
from django.db.models import Count
from django.db.models import F
from django.db.models import Q
from django.utils import timezone
# other
from base.managers import BaseManager
# enums
from users.enums import UserEnum
class UserQuerySet(models.QuerySet):
def members(self):
return self.filter(
is_active=True,
status=UserEnum.STATUS_ACCEPTED,
)
def top_active_users(self):
"""
Returns top 3 active users by comments and activities
"""
# exclude staff users
users = self.select_related(
'institution',
'region',
).prefetch_related(
'comment_set',
'useractivity_set',
).exclude(
is_staff=True,
).exclude(
email__endswith='lab.gob.cl',
)
# only include active and accepted users
# status 1 => Accepted
users = users.members()
users = users.filter(
Q(comment__isnull=False) | Q(useractivity__isnull=False),
)
# calculate ranking and return top 3
users = users.annotate(
activity_count=Count('useractivity', distinct=True),
comment_count=Count('comment', distinct=True)
).annotate(
ranking=F('activity_count') + F('comment_count')
).order_by('-ranking')[:3]
return users
class UserManager(BaseUserManager, BaseManager):
"""
This class is used so the user manager has both the django defined
user manager and the cusmtom defiled 'BaseManager
""
"""
def create_user(self, email, password=None, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = UserManager.normalize_email(email)
user = self.model(email=email,
is_staff=False, is_active=True, is_superuser=False,
last_login=now, date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **extra_fields):
u = self.create_user(email, password, **extra_fields)
u.is_staff = True
u.is_active = True
u.is_superuser = True
u.save(using=self._db)
return u
def get_queryset(self):
return UserQuerySet(self.model, using=self._db)
def members(self):
return self.get_queryset().members()
def top_active_users(self):
"""
Returns top 3 active users
"""
return self.get_queryset().top_active_users()
|
[
"django.utils.timezone.now",
"django.db.models.F",
"django.db.models.Count",
"django.db.models.Q"
] |
[((1917, 1931), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (1929, 1931), False, 'from django.utils import timezone\n'), ((1132, 1156), 'django.db.models.Q', 'Q', ([], {'comment__isnull': '(False)'}), '(comment__isnull=False)\n', (1133, 1156), False, 'from django.db.models import Q\n'), ((1159, 1188), 'django.db.models.Q', 'Q', ([], {'useractivity__isnull': '(False)'}), '(useractivity__isnull=False)\n', (1160, 1188), False, 'from django.db.models import Q\n'), ((1440, 1459), 'django.db.models.F', 'F', (['"""activity_count"""'], {}), "('activity_count')\n", (1441, 1459), False, 'from django.db.models import F\n'), ((1462, 1480), 'django.db.models.F', 'F', (['"""comment_count"""'], {}), "('comment_count')\n", (1463, 1480), False, 'from django.db.models import F\n'), ((1304, 1340), 'django.db.models.Count', 'Count', (['"""useractivity"""'], {'distinct': '(True)'}), "('useractivity', distinct=True)\n", (1309, 1340), False, 'from django.db.models import Count\n'), ((1368, 1399), 'django.db.models.Count', 'Count', (['"""comment"""'], {'distinct': '(True)'}), "('comment', distinct=True)\n", (1373, 1399), False, 'from django.db.models import Count\n')]
|
import miniproxypool
import logging
import sys
import time
from time import gmtime, strftime
import requests
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='[%(name)20.20s] [%(asctime)s] [%(levelname)7.7s] [%(threadName)10s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S',)
logging.getLogger('requests').setLevel(logging.WARNING) # suppress the logger from requests
logger = logging.getLogger(__name__)
def create_index_html(proxies_list):
html = """
<!DOCTYPE html>
<html lang="en">
<head>
<title>Proxy List</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Proxy List</h2>
"""
html += "<h5>[Last time updated: %s (GMT)]</h5>" % strftime("%Y-%m-%d %H:%M:%S", gmtime())
html += """
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>IP</th>
<th>PORT</th>
<th>SPEED</th>
</tr>
</thead>
<tbody>
"""
cnt = 1
for proxy in proxies_list:
html += "<tr>\n";
html +="<th scope=\"row\">%d</th>\n"%cnt
html +="<td>%s</td>\n"%proxy[0]
html +="<td>%s</td>\n"%proxy[1]
html +="<td>%.3f</td>\n"%proxy[2]
html +="</tr>\n"
cnt += 1
html += """
</tbody>
</table>
</div>
</body>
</html>
"""
return html
if __name__ == '__main__':
miniproxypool.config.VALIDATOR_URL = "http://www.google.ca"
miniproxypool.config.VALIDATOR_TIMEOUT = 0.5 # seconds
miniproxypool.config.VALIDATOR_THREAD_POOL_SIZE = 20
miniproxypool.config.VALIDATOR_CONNECTIONS_PER_THREAD = 20
miniproxypool.config.VALIDATE_THREAD_RUN_PERIOD = 5 * 60 # seconds wait after each validation
miniproxypool.config.LOAD_PORXIES_FROM_SOURCES_THREAD_RUN_PERIOD = 10 * 60 # seconds wait after each loading from sites
miniproxypool.run_as_daemon()
while(True):
filepath = "index.html"
file = open(filepath, "w")
file.write(create_index_html(miniproxypool.get_all_proxies()))
file.close()
print("File '%s' updated." % filepath)
time.sleep(60 * 10)
#print(miniproxypool.get_all_proxies())
|
[
"logging.basicConfig",
"time.gmtime",
"time.sleep",
"miniproxypool.get_all_proxies",
"miniproxypool.run_as_daemon",
"logging.getLogger"
] |
[((110, 297), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.INFO', 'format': '"""[%(name)20.20s] [%(asctime)s] [%(levelname)7.7s] [%(threadName)10s] %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(stream=sys.stdout, level=logging.INFO, format=\n '[%(name)20.20s] [%(asctime)s] [%(levelname)7.7s] [%(threadName)10s] %(message)s'\n , datefmt='%Y-%m-%d %H:%M:%S')\n", (129, 297), False, 'import logging\n'), ((391, 418), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (408, 418), False, 'import logging\n'), ((2148, 2177), 'miniproxypool.run_as_daemon', 'miniproxypool.run_as_daemon', ([], {}), '()\n', (2175, 2177), False, 'import miniproxypool\n'), ((289, 318), 'logging.getLogger', 'logging.getLogger', (['"""requests"""'], {}), "('requests')\n", (306, 318), False, 'import logging\n'), ((2410, 2429), 'time.sleep', 'time.sleep', (['(60 * 10)'], {}), '(60 * 10)\n', (2420, 2429), False, 'import time\n'), ((1079, 1087), 'time.gmtime', 'gmtime', ([], {}), '()\n', (1085, 1087), False, 'from time import gmtime, strftime\n'), ((2300, 2331), 'miniproxypool.get_all_proxies', 'miniproxypool.get_all_proxies', ([], {}), '()\n', (2329, 2331), False, 'import miniproxypool\n')]
|
# !/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
# -*- coding:utf-8 -*-
# @Author : Jiazhixiang
# 爬取前4个常见食物分类的前4页的事食物数据信息
from gevent import monkey
# 让程序变成异步模式
# 从gevent库里导入monkey模块
# monkey.patch_all()能把程序变成协作式运行,就是可以帮助程序实现异步。
monkey.patch_all()
from gevent.queue import Queue
import requests, gevent
from bs4 import BeautifulSoup
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.65 Safari/535.11"
}
# 前4个常见事务分类的前4页的事食物数据信息
# start_url = "http://www.boohee.com/food/group/1?page=2"
start_url = "http://www.boohee.com/food/group/{num}?page={page}"
# response = requests.get(url=start_url, headers=headers)
work = Queue()
# 通过两个for循环,能设置分类的数字和页数的数字
# 前3个分类的前4页的食物记录的网址:
for x in range(1, 5):
for y in range(1, 5):
real_url = start_url.format(num=x, page=y)
work.put_nowait(real_url)
# 通过for循环,能设置第11个常见食物分类的食物的页数。
# 然后,把构造好的网址用put_nowait方法添加进队列里。
# 第11个常见食物分类的前3页的食物记录的网址:
url_2 = 'http://www.boohee.com/food/view_menu?page={page}'
for i in range(1, 5):
real_url = url_2.format(page=i)
work.put_nowait(real_url) # 然后,把构造好的网址用put_nowait方法添加进队列里
def crawler(*args):
while not work.empty(): # 当队列不是空的时候,就执行下面的程序
url = work.get_nowait() # 用get_nowait()方法从队列里把刚刚放入的网址提取出来
response = requests.get(url=url, headers=headers)
bs_data = BeautifulSoup(response.text, 'html.parser')
food = bs_data.find_all(class_="item clearfix")
for food in food:
food_name = food.find_all('a')[1]['title']
food_url = 'http://www.boohee.com' + food.find_all('a')[1]['href']
food_calorie = food.find('p').text
print(food_name, food_url, food_calorie)
task_list = []
for i in range(1, 5): # 相当于创建了5个爬虫
# 用gevent.spawn()函数创建执行crawler()函数的任务
task = gevent.spawn(crawler)
task_list.append(task)
# 用gevent.joinall方法,启动协程,执行任务列表里的所有任务,让爬虫开始爬取网站
gevent.joinall(task_list)
# print(work.qsize())
|
[
"gevent.spawn",
"gevent.monkey.patch_all",
"requests.get",
"bs4.BeautifulSoup",
"gevent.queue.Queue",
"gevent.joinall"
] |
[((246, 264), 'gevent.monkey.patch_all', 'monkey.patch_all', ([], {}), '()\n', (262, 264), False, 'from gevent import monkey\n'), ((706, 713), 'gevent.queue.Queue', 'Queue', ([], {}), '()\n', (711, 713), False, 'from gevent.queue import Queue\n'), ((1962, 1987), 'gevent.joinall', 'gevent.joinall', (['task_list'], {}), '(task_list)\n', (1976, 1987), False, 'import requests, gevent\n'), ((1864, 1885), 'gevent.spawn', 'gevent.spawn', (['crawler'], {}), '(crawler)\n', (1876, 1885), False, 'import requests, gevent\n'), ((1341, 1379), 'requests.get', 'requests.get', ([], {'url': 'url', 'headers': 'headers'}), '(url=url, headers=headers)\n', (1353, 1379), False, 'import requests, gevent\n'), ((1398, 1441), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.text', '"""html.parser"""'], {}), "(response.text, 'html.parser')\n", (1411, 1441), False, 'from bs4 import BeautifulSoup\n')]
|
from __future__ import absolute_import
from hls4ml.templates.templates import Backend, register_backend, get_backend
from hls4ml.templates.vivado_template import VivadoBackend
from hls4ml.templates.oneapi_template import OneAPI
register_backend('Vivado', VivadoBackend)
register_backend('oneAPI', OneAPI)
|
[
"hls4ml.templates.templates.register_backend"
] |
[((230, 271), 'hls4ml.templates.templates.register_backend', 'register_backend', (['"""Vivado"""', 'VivadoBackend'], {}), "('Vivado', VivadoBackend)\n", (246, 271), False, 'from hls4ml.templates.templates import Backend, register_backend, get_backend\n'), ((272, 306), 'hls4ml.templates.templates.register_backend', 'register_backend', (['"""oneAPI"""', 'OneAPI'], {}), "('oneAPI', OneAPI)\n", (288, 306), False, 'from hls4ml.templates.templates import Backend, register_backend, get_backend\n')]
|
import py, weakref
from rpython.rlib import rgc
from rpython.rtyper.lltypesystem import lltype, llmemory
from rpython.rtyper.test.tool import BaseRtypingTest
class TestRweakref(BaseRtypingTest):
def test_weakref_simple(self):
class A:
pass
class B(A):
pass
class C(A):
pass
def f(n):
if n:
x = B()
x.hello = 42
r = weakref.ref(x)
else:
x = C()
x.hello = 64
r = weakref.ref(x)
return r().hello, x # returns 'x' too, to keep it alive
res = self.interpret(f, [1])
assert res.item0 == 42
res = self.interpret(f, [0])
assert res.item0 == 64
def test_prebuilt_weakref(self):
class A:
pass
a1 = A()
a1.hello = 5
w1 = weakref.ref(a1)
a2 = A()
a2.hello = 8
w2 = weakref.ref(a2)
def f(n):
if n:
r = w1
else:
r = w2
return r().hello
res = self.interpret(f, [1])
assert res == 5
res = self.interpret(f, [0])
assert res == 8
def test_prebuilt_dead_weakref(self):
class A:
pass
a1 = A()
w1 = weakref.ref(a1)
a2 = A()
w2 = weakref.ref(a2)
del a1
rgc.collect()
assert w1() is None
def f(n):
if n:
r = w1
else:
r = w2
return r() is not None
res = self.interpret(f, [1])
assert res == False
res = self.interpret(f, [0])
assert res == True
def test_multiple_prebuilt_dead_weakrefs(self):
class A:
pass
a1 = A()
w1 = weakref.ref(a1)
a2 = A()
w2 = weakref.ref(a2)
a3 = A()
w3 = weakref.ref(a3)
a4 = A()
w4 = weakref.ref(a4)
del a1, a3
rgc.collect()
assert w1() is None
assert w3() is None
def f(n):
if n > 0:
if n > 5:
r = w1
else:
r = w3
assert r() is None
else:
if n < -5:
r = w2
else:
r = w4
assert r() is not None
return r() is not None
res = self.interpret(f, [1])
assert res == False
res = self.interpret(f, [0])
assert res == True
res = self.interpret(f, [100])
assert res == False
res = self.interpret(f, [-100])
assert res == True
def test_pbc_null_weakref(self):
class A:
pass
a1 = A()
mylist = [weakref.ref(a1), None]
def fn(i):
item = mylist[i]
return item is None
assert self.interpret(fn, [0]) is False
assert self.interpret(fn, [1]) is True
def test_ll_weakref(self):
S = lltype.GcStruct('S', ('x',lltype.Signed))
def g():
s = lltype.malloc(S)
w = llmemory.weakref_create(s)
assert llmemory.weakref_deref(lltype.Ptr(S), w) == s
assert llmemory.weakref_deref(lltype.Ptr(S), w) == s
return w # 's' is forgotten here
def f():
w = g()
rgc.collect()
return llmemory.weakref_deref(lltype.Ptr(S), w)
res = self.interpret(f, [])
assert res == lltype.nullptr(S)
class TestRWeakrefDisabled(BaseRtypingTest):
def test_no_real_weakref(self):
class A:
pass
a1 = A()
mylist = [weakref.ref(a1), None]
def g():
a2 = A()
return weakref.ref(a2)
def fn(i):
w = g()
rgc.collect()
assert w() is not None
return mylist[i] is None
assert self.interpret(fn, [0], rweakref=False) is False
assert self.interpret(fn, [1], rweakref=False) is True
|
[
"rpython.rtyper.lltypesystem.lltype.nullptr",
"rpython.rlib.rgc.collect",
"rpython.rtyper.lltypesystem.lltype.GcStruct",
"rpython.rtyper.lltypesystem.lltype.Ptr",
"rpython.rtyper.lltypesystem.lltype.malloc",
"rpython.rtyper.lltypesystem.llmemory.weakref_create",
"weakref.ref"
] |
[((903, 918), 'weakref.ref', 'weakref.ref', (['a1'], {}), '(a1)\n', (914, 918), False, 'import py, weakref\n'), ((970, 985), 'weakref.ref', 'weakref.ref', (['a2'], {}), '(a2)\n', (981, 985), False, 'import py, weakref\n'), ((1345, 1360), 'weakref.ref', 'weakref.ref', (['a1'], {}), '(a1)\n', (1356, 1360), False, 'import py, weakref\n'), ((1391, 1406), 'weakref.ref', 'weakref.ref', (['a2'], {}), '(a2)\n', (1402, 1406), False, 'import py, weakref\n'), ((1431, 1444), 'rpython.rlib.rgc.collect', 'rgc.collect', ([], {}), '()\n', (1442, 1444), False, 'from rpython.rlib import rgc\n'), ((1855, 1870), 'weakref.ref', 'weakref.ref', (['a1'], {}), '(a1)\n', (1866, 1870), False, 'import py, weakref\n'), ((1901, 1916), 'weakref.ref', 'weakref.ref', (['a2'], {}), '(a2)\n', (1912, 1916), False, 'import py, weakref\n'), ((1947, 1962), 'weakref.ref', 'weakref.ref', (['a3'], {}), '(a3)\n', (1958, 1962), False, 'import py, weakref\n'), ((1993, 2008), 'weakref.ref', 'weakref.ref', (['a4'], {}), '(a4)\n', (2004, 2008), False, 'import py, weakref\n'), ((2037, 2050), 'rpython.rlib.rgc.collect', 'rgc.collect', ([], {}), '()\n', (2048, 2050), False, 'from rpython.rlib import rgc\n'), ((3092, 3134), 'rpython.rtyper.lltypesystem.lltype.GcStruct', 'lltype.GcStruct', (['"""S"""', "('x', lltype.Signed)"], {}), "('S', ('x', lltype.Signed))\n", (3107, 3134), False, 'from rpython.rtyper.lltypesystem import lltype, llmemory\n'), ((2850, 2865), 'weakref.ref', 'weakref.ref', (['a1'], {}), '(a1)\n', (2861, 2865), False, 'import py, weakref\n'), ((3167, 3183), 'rpython.rtyper.lltypesystem.lltype.malloc', 'lltype.malloc', (['S'], {}), '(S)\n', (3180, 3183), False, 'from rpython.rtyper.lltypesystem import lltype, llmemory\n'), ((3200, 3226), 'rpython.rtyper.lltypesystem.llmemory.weakref_create', 'llmemory.weakref_create', (['s'], {}), '(s)\n', (3223, 3226), False, 'from rpython.rtyper.lltypesystem import lltype, llmemory\n'), ((3453, 3466), 'rpython.rlib.rgc.collect', 'rgc.collect', ([], {}), '()\n', (3464, 3466), False, 'from rpython.rlib import rgc\n'), ((3586, 3603), 'rpython.rtyper.lltypesystem.lltype.nullptr', 'lltype.nullptr', (['S'], {}), '(S)\n', (3600, 3603), False, 'from rpython.rtyper.lltypesystem import lltype, llmemory\n'), ((3756, 3771), 'weakref.ref', 'weakref.ref', (['a1'], {}), '(a1)\n', (3767, 3771), False, 'import py, weakref\n'), ((3836, 3851), 'weakref.ref', 'weakref.ref', (['a2'], {}), '(a2)\n', (3847, 3851), False, 'import py, weakref\n'), ((3903, 3916), 'rpython.rlib.rgc.collect', 'rgc.collect', ([], {}), '()\n', (3914, 3916), False, 'from rpython.rlib import rgc\n'), ((450, 464), 'weakref.ref', 'weakref.ref', (['x'], {}), '(x)\n', (461, 464), False, 'import py, weakref\n'), ((556, 570), 'weakref.ref', 'weakref.ref', (['x'], {}), '(x)\n', (567, 570), False, 'import py, weakref\n'), ((3509, 3522), 'rpython.rtyper.lltypesystem.lltype.Ptr', 'lltype.Ptr', (['S'], {}), '(S)\n', (3519, 3522), False, 'from rpython.rtyper.lltypesystem import lltype, llmemory\n'), ((3269, 3282), 'rpython.rtyper.lltypesystem.lltype.Ptr', 'lltype.Ptr', (['S'], {}), '(S)\n', (3279, 3282), False, 'from rpython.rtyper.lltypesystem import lltype, llmemory\n'), ((3334, 3347), 'rpython.rtyper.lltypesystem.lltype.Ptr', 'lltype.Ptr', (['S'], {}), '(S)\n', (3344, 3347), False, 'from rpython.rtyper.lltypesystem import lltype, llmemory\n')]
|
"""
Descriptors
============
The descriptors module offers all kinds of acoustics related descriptors.
.. toctree::
:maxdepth: 2
Descriptors from ISO/TR 25417:2007
**********************************
Descriptors from :mod:`acoustics.standards.iso_tr_25417_2007`.
.. autoattribute:: acoustics.descriptors.REFERENCE_PRESSURE
.. autofunction:: acoustics.descriptors.sound_pressure_level
.. autofunction:: acoustics.descriptors.equivalent_sound_pressure_level
.. autofunction:: acoustics.descriptors.peak_sound_pressure
.. autofunction:: acoustics.descriptors.peak_sound_pressure_level
.. autoattribute:: acoustics.descriptors.REFERENCE_SOUND_EXPOSURE
.. autofunction:: acoustics.descriptors.sound_exposure
.. autofunction:: acoustics.descriptors.sound_exposure_level
.. autoattribute:: acoustics.descriptors.REFERENCE_POWER
.. autofunction:: acoustics.descriptors.sound_power_level
.. autofunction:: acoustics.descriptors.sound_energy
.. autofunction:: acoustics.descriptors.sound_energy_level
.. autoattribute:: acoustics.descriptors.REFERENCE_ENERGY
.. autofunction:: acoustics.descriptors.sound_intensity
.. autofunction:: acoustics.descriptors.time_averaged_sound_intensity
.. autoattribute:: acoustics.descriptors.REFERENCE_INTENSITY
.. autofunction:: acoustics.descriptors.time_averaged_sound_intensity_level
.. autofunction:: acoustics.descriptors.normal_time_averaged_sound_intensity
.. autofunction:: acoustics.descriptors.normal_time_averaged_sound_intensity_level
Other descriptors
*****************
"""
from __future__ import division
import numpy as np
from acoustics.standards.iso_tr_25417_2007 import (REFERENCE_PRESSURE,
sound_pressure_level,
equivalent_sound_pressure_level,
peak_sound_pressure,
peak_sound_pressure_level,
REFERENCE_SOUND_EXPOSURE,
sound_exposure,
sound_exposure_level,
REFERENCE_POWER,
sound_power_level,
sound_energy,
REFERENCE_ENERGY,
sound_energy_level,
sound_intensity,
time_averaged_sound_intensity,
REFERENCE_INTENSITY,
time_averaged_sound_intensity_level,
normal_time_averaged_sound_intensity,
normal_time_averaged_sound_intensity_level,
)
def _leq(levels, time):
if type(levels) is list:
levels = np.array(levels)
return 10.0 * np.log10((1.0/time) * np.sum(10.0**(levels/10.0)))
def leq(levels, int_time=1.0):
"""
Equivalent level :math:`L_{eq}`.
:param levels: Levels as function of time.
:param int_time: Integration time. Default value is 1.0 second.
:returns: Equivalent level L_{eq}.
Sum of levels in dB.
"""
if type(levels) is list:
levels = np.array(levels)
time = levels.size * int_time
return _leq(levels, time)
def sel(levels):
"""
Sound Exposure Level from ``levels`` (NumPy array).
"""
if type(levels) is list:
levels = np.array(levels)
return _leq(levels, 1.0)
def lw(W, Wref=1.0e-12):
"""
Sound power level :math:`L_{w}` for sound power :math:`W` and reference power :math:`W_{ref}`.
:param W: Sound power :math:`W`.
:param Wref: Reference power :math:`W_{ref}`. Default value is :math:`10^{12}` watt.
"""
if type(W) is list:
W = np.array(W)
return 10.0 * np.log10(W/Wref)
def lden(lday, levening, lnight):
"""
Calculate :math:`L_{den}` from :math:`L_{day}`, :math:`L_{evening}` and :math:`L_{night}`.
:param lday: Equivalent level during day period :math:`L_{day}`.
:param levening: Equivalent level during evening period :math:`L_{evening}`.
:param lnight: Equivalent level during night period :math:`L_{night}`.
:returns: :math:`L_{den}`
"""
if type(lday) is list:
lday = np.array(lday)
if type(levening) is list:
levening = np.array(levening)
if type(lnight) is list:
lnight = np.array(lnight)
day = 12.0 * 10.0**(lday/10.0)
evening = 4.0 * 10.0**((levening+5.0) / 10.0)
night = 8.0 * 10.0**((lnight+10.0) / 10.0)
return 10.0 * np.log10((day + evening + night) / 24.0)
def ldn(lday, lnight):
"""
Calculate :math:`L_{dn}` from :math:`L_{day}` and :math:`L_{night}`.
:param lday: Equivalent level during day period :math:`L_{day}`.
:param lnight: Equivalent level during night period :math:`L_{night}`.
:returns: :math:`L_{dn}`
"""
if type(lday) is list:
lday = np.array(lday)
if type(lnight) is list:
lnight = np.array(lnight)
day = 15.0 * 10.0**(lday/10.0)
night = 9.0 * 10.0**((lnight+10.0) / 10.0)
return 10.0 * np.log10((day + night) / 24.0)
|
[
"numpy.log10",
"numpy.array",
"numpy.sum"
] |
[((3138, 3154), 'numpy.array', 'np.array', (['levels'], {}), '(levels)\n', (3146, 3154), True, 'import numpy as np\n'), ((3545, 3561), 'numpy.array', 'np.array', (['levels'], {}), '(levels)\n', (3553, 3561), True, 'import numpy as np\n'), ((3763, 3779), 'numpy.array', 'np.array', (['levels'], {}), '(levels)\n', (3771, 3779), True, 'import numpy as np\n'), ((4118, 4129), 'numpy.array', 'np.array', (['W'], {}), '(W)\n', (4126, 4129), True, 'import numpy as np\n'), ((4148, 4166), 'numpy.log10', 'np.log10', (['(W / Wref)'], {}), '(W / Wref)\n', (4156, 4166), True, 'import numpy as np\n'), ((4614, 4628), 'numpy.array', 'np.array', (['lday'], {}), '(lday)\n', (4622, 4628), True, 'import numpy as np\n'), ((4679, 4697), 'numpy.array', 'np.array', (['levening'], {}), '(levening)\n', (4687, 4697), True, 'import numpy as np\n'), ((4744, 4760), 'numpy.array', 'np.array', (['lnight'], {}), '(lnight)\n', (4752, 4760), True, 'import numpy as np\n'), ((4911, 4951), 'numpy.log10', 'np.log10', (['((day + evening + night) / 24.0)'], {}), '((day + evening + night) / 24.0)\n', (4919, 4951), True, 'import numpy as np\n'), ((5291, 5305), 'numpy.array', 'np.array', (['lday'], {}), '(lday)\n', (5299, 5305), True, 'import numpy as np\n'), ((5352, 5368), 'numpy.array', 'np.array', (['lnight'], {}), '(lnight)\n', (5360, 5368), True, 'import numpy as np\n'), ((5469, 5499), 'numpy.log10', 'np.log10', (['((day + night) / 24.0)'], {}), '((day + night) / 24.0)\n', (5477, 5499), True, 'import numpy as np\n'), ((3195, 3226), 'numpy.sum', 'np.sum', (['(10.0 ** (levels / 10.0))'], {}), '(10.0 ** (levels / 10.0))\n', (3201, 3226), True, 'import numpy as np\n')]
|
# SPOC lab CAM²: hetcam-webcam
# How to make the script run on startup:
# sudo nano /etc/rc.local
# insert:
# sudo python3 /home/pi/sample.py & > /home/pi/Desktop/log.txt 2>&1
# icons from:
# https://fontawesome.com/v4.7.0/examples/
# how to schedule:
# https://stackoverflow.com/questions/21214270/how-to-schedule-a-function-to-run-every-hour-on-flask
# https://apscheduler.readthedocs.io/en/stable/modules/triggers/date.html#module-apscheduler.triggers.date
# alternatively to flask_apscheduler: from apscheduler.schedulers.background import BackgroundScheduler
# how to handle querys:
# https://www.digitalocean.com/community/tutorials/processing-incoming-request-data-in-flask
from flask import Flask, render_template, Response, request
# for gallery:
from flask import send_from_directory
from flask import redirect
from camera import VideoCamera
import time
import os
from pyserial_connection_arduino import connect_to_arduino, list_available_ports
import numpy as np
from flask_apscheduler import APScheduler
import cv2
from datetime import datetime, timedelta
# https://stackoverflow.com/questions/6871016/adding-days-to-a-date-in-python
class Config(object):
SCHEDULER_API_ENABLED = True
app = Flask(__name__)
#app = Flask(__name__, template_folder='/var/www/html/templates')
app.config.from_object(Config())
scheduler = APScheduler()
# if you don't wanna use a config, you can set options here:
# scheduler.api_enabled = True
scheduler.init_app(app)
scheduler.start()
comport = '/dev/ttyACM0' # this should be set to the standard address of the microcontroller
motor0_enable = 0
motor0_direction = 0
motor0_position = 0
motor1_enable = 0
motor1_direction = 0
motor1_position = 0
motor2_enable = 0
motor2_direction = 0
motor2_position = 0
motor3_enable = 0
motor3_direction = 0
motor3_position = 0
def motor_position(position_in_degree):
print("motor_position")
# 4800 steps are 270°, 360 should never be possible since = 0°
# degrees are divided by 90 and multiplied by 1600
# only send int values to arduino!
step_position_arduino = int(position_in_degree/90*1600)
try:
results = np.array(connect_to_arduino(comport,motor0_enable,motor0_direction,step_position_arduino,
motor1_enable,motor1_direction,motor1_position,motor2_enable,motor2_direction,motor2_position,motor3_enable,motor3_direction,motor3_position))
print(f"Received values: {results}")
except:
print("Microcontroller not found or not connected")
return
@app.route('/move_deg')
def move_deg():
degree = 0
degree = int(request.args.get('degree'))
if(degree >= 280):
degree = 270
if(degree <= -30):
degree = -30
print(f"Moving to {degree}°")
motor_position(degree)
return '''<h1>Moving to: {}</h1>'''.format(degree)
# return ("nothing")
def motor_task_creator(task_id):
print(f"start of motor task creator {task_id}")
# creating motor task that runs every minute
scheduler.add_job(func=motor_task, trigger='interval', minutes=60, args=[task_id], id='move'+str(task_id))
def picture_task_creator(task_id):
print(f"start of picture task creator {task_id}")
# creating picture task that runs every minute
scheduler.add_job(func=picture_task, trigger='interval', minutes=60, args=[task_id], id='picture'+str(task_id))
def motor_task(task_id):
# send to motor position
print(f"moving to position {task_id}")
motor_position(task_id)
#-------------------------------------------------------------------------------------
def picture_task(task_position):
print(f"start of picture task {task_position}")
filename = f'images/position{task_position}_{datetime.now().strftime("%Y%m%d-%H%M%S")}.jpg'
# foldername = 'images\'
# filename = foldername+filename
print(filename)
# frame_bytes, frame = global_video_cam.get_frame()
# writing image
cv2.imwrite(filename, global_video_frame)
@app.route('/get_toggled_status')
def toggled_status():
current_status = request.args.get('status')
# instead of if, create a list, send list and do for items in list
# this way, only in activated positions are scheduled
if(scheduler.get_jobs()):
print(bool(scheduler.get_jobs()))
print("jobs scheduled")
# current_status = 'Automatic On'
else:
print(bool(scheduler.get_jobs()))
print("no jobs scheduled")
# current_status = 'Automatic On'
# if Automatic On was sent and no jobs are scheduled
if(current_status == 'Automatic Off') and not(scheduler.get_jobs()):
print("Switching On")
schedule_start = datetime.today()
print(f"starting scheduling {schedule_start}")
moving_time = 10
print(f"moving time is assumed {moving_time} seconds")
task_seperation_increase = moving_time*2
task_seperation = 1
for i in range(0, 180, 90): # starting angle, stop angle and step angle in degrees
schedule_time_movement = schedule_start + timedelta(seconds=task_seperation)
schedule_time_picture = schedule_start + timedelta(seconds=moving_time+task_seperation)
scheduler.add_job(func=motor_task_creator, trigger='date', run_date=schedule_time_movement, args=[i], id='move_start'+str(i))
print(f"created moving job {i} running at {schedule_time_movement}")
scheduler.add_job(func=picture_task_creator, trigger='date', run_date=schedule_time_picture, args=[i], id='picture_start'+str(i))
print(f"created picture job {i} running at {schedule_time_picture}")
task_seperation = task_seperation + task_seperation_increase
print(scheduler.get_jobs())
else:
print("Switching Off")
print(scheduler.get_jobs())
print("Removing all scheduled jobs")
# scheduler.remove_job(j0)
scheduler.remove_all_jobs()
print(scheduler.get_jobs())
return 'Automatic On' if current_status == 'Automatic Off' else 'Automatic Off'
@app.route('/automatic_stop')
def automatic_stop():
# https://github.com/viniciuschiele/flask-apscheduler
# scheduler.pause()
print(scheduler.get_jobs())
print("Removing all jobs")
# scheduler.remove_job(j0)
scheduler.remove_all_jobs()
print(scheduler.get_jobs())
return ("nothing")
@app.route('/picture')
def picture(pos_name = "custom"):
picture_task(pos_name)
return ("nothing")
@app.route('/settings')
def automatic():
print("settings")
return ("nothing")
@app.route('/', methods=['GET', 'POST'])
def move():
result = ""
if request.method == 'POST':
return render_template('index.html', res_str=result)
return render_template('index.html')
def gen(camera):
while True:
frame_bytes, frame = camera.get_frame()
global global_video_frame
global_video_frame = frame
# this is executed every frame
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n\r\n')
# def gen_frame(camera):
# try:
# object_methods = [method_name for method_name in dir(camera)
# if callable(getattr(camera, method_name))]
# print(object_methods)
# frame = camera.get_frame()
# # frame, frame2 = camera.get_frame_resolution()
# print("picture with custom resolution")
# except:
# frame = camera.get_frame()
# print("picture with standard resolution, custom did not work")
# # frame 2 is an image, frame is a jpeg stream in bytes
# return frame
@app.route('/video_feed')
def video_feed():
# global global_video_cam
# global_video_cam = VideoCamera()
return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')
# gallery-------------------------------
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
@app.route("/gallery")
def gallery():
images = os.listdir('./images')
return render_template("index-gallery.html", images=images)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route("/upload", methods=["GET","POST"])
def upload_file():
if request.method=="GET":
return render_template('upload.html')
target = os.path.join(APP_ROOT, 'images/')
print(target)
if not os.path.isdir(target):
os.mkdir(target)
for file in request.files.getlist("file"):
print(file)
filename = file.filename
destination = "/".join([target, filename])
print(destination)
file.save(destination)
return render_template("uploaded.html")
@app.route('/upload/<filename>')
def send_image(filename):
return send_from_directory("images", filename)
def send_image_for_filter(image):
return render_template('filter.html', image=image)
@app.route("/filters")
def filter():
return render_template('filters.html')
@app.url_defaults
def hashed_url_for_static_file(endpoint, values):
if 'static' == endpoint or endpoint.endswith('.static'):
filename = values.get('filename')
if filename:
if '.' in endpoint: # has higher priority
blueprint = endpoint.rsplit('.', 1)[0]
else:
blueprint = request.blueprint # can be None too
if blueprint:
static_folder = app.blueprints[blueprint].static_folder
else:
static_folder = app.static_folder
param_name = 'h'
while param_name in values:
param_name = '_' + param_name
values[param_name] = static_file_hash(os.path.join(static_folder, filename))
def static_file_hash(filename):
return int(os.stat(filename).st_mtime)
# gallery-------------------------------
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=True, threaded=True)
#app.run(host='0.0.0.0', debug=True, threaded=True)
# app.run(port=5000)
|
[
"camera.VideoCamera",
"flask_apscheduler.APScheduler",
"os.path.abspath",
"os.mkdir",
"datetime.datetime.today",
"flask.request.args.get",
"flask.request.files.getlist",
"os.path.isdir",
"cv2.imwrite",
"os.stat",
"flask.Flask",
"datetime.datetime.now",
"datetime.timedelta",
"flask.render_template",
"flask.send_from_directory",
"pyserial_connection_arduino.connect_to_arduino",
"os.path.join",
"os.listdir"
] |
[((1211, 1226), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (1216, 1226), False, 'from flask import Flask, render_template, Response, request\n'), ((1340, 1353), 'flask_apscheduler.APScheduler', 'APScheduler', ([], {}), '()\n', (1351, 1353), False, 'from flask_apscheduler import APScheduler\n'), ((3906, 3947), 'cv2.imwrite', 'cv2.imwrite', (['filename', 'global_video_frame'], {}), '(filename, global_video_frame)\n', (3917, 3947), False, 'import cv2\n'), ((4027, 4053), 'flask.request.args.get', 'request.args.get', (['"""status"""'], {}), "('status')\n", (4043, 4053), False, 'from flask import Flask, render_template, Response, request\n'), ((6714, 6743), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (6729, 6743), False, 'from flask import Flask, render_template, Response, request\n'), ((7878, 7903), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (7893, 7903), False, 'import os\n'), ((8014, 8036), 'os.listdir', 'os.listdir', (['"""./images"""'], {}), "('./images')\n", (8024, 8036), False, 'import os\n'), ((8048, 8100), 'flask.render_template', 'render_template', (['"""index-gallery.html"""'], {'images': 'images'}), "('index-gallery.html', images=images)\n", (8063, 8100), False, 'from flask import Flask, render_template, Response, request\n'), ((8387, 8420), 'os.path.join', 'os.path.join', (['APP_ROOT', '"""images/"""'], {}), "(APP_ROOT, 'images/')\n", (8399, 8420), False, 'import os\n'), ((8514, 8543), 'flask.request.files.getlist', 'request.files.getlist', (['"""file"""'], {}), "('file')\n", (8535, 8543), False, 'from flask import Flask, render_template, Response, request\n'), ((8718, 8750), 'flask.render_template', 'render_template', (['"""uploaded.html"""'], {}), "('uploaded.html')\n", (8733, 8750), False, 'from flask import Flask, render_template, Response, request\n'), ((8822, 8861), 'flask.send_from_directory', 'send_from_directory', (['"""images"""', 'filename'], {}), "('images', filename)\n", (8841, 8861), False, 'from flask import send_from_directory\n'), ((8908, 8951), 'flask.render_template', 'render_template', (['"""filter.html"""'], {'image': 'image'}), "('filter.html', image=image)\n", (8923, 8951), False, 'from flask import Flask, render_template, Response, request\n'), ((9001, 9032), 'flask.render_template', 'render_template', (['"""filters.html"""'], {}), "('filters.html')\n", (9016, 9032), False, 'from flask import Flask, render_template, Response, request\n'), ((2585, 2611), 'flask.request.args.get', 'request.args.get', (['"""degree"""'], {}), "('degree')\n", (2601, 2611), False, 'from flask import Flask, render_template, Response, request\n'), ((4644, 4660), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (4658, 4660), False, 'from datetime import datetime, timedelta\n'), ((6657, 6702), 'flask.render_template', 'render_template', (['"""index.html"""'], {'res_str': 'result'}), "('index.html', res_str=result)\n", (6672, 6702), False, 'from flask import Flask, render_template, Response, request\n'), ((8343, 8373), 'flask.render_template', 'render_template', (['"""upload.html"""'], {}), "('upload.html')\n", (8358, 8373), False, 'from flask import Flask, render_template, Response, request\n'), ((8450, 8471), 'os.path.isdir', 'os.path.isdir', (['target'], {}), '(target)\n', (8463, 8471), False, 'import os\n'), ((8481, 8497), 'os.mkdir', 'os.mkdir', (['target'], {}), '(target)\n', (8489, 8497), False, 'import os\n'), ((2144, 2389), 'pyserial_connection_arduino.connect_to_arduino', 'connect_to_arduino', (['comport', 'motor0_enable', 'motor0_direction', 'step_position_arduino', 'motor1_enable', 'motor1_direction', 'motor1_position', 'motor2_enable', 'motor2_direction', 'motor2_position', 'motor3_enable', 'motor3_direction', 'motor3_position'], {}), '(comport, motor0_enable, motor0_direction,\n step_position_arduino, motor1_enable, motor1_direction, motor1_position,\n motor2_enable, motor2_direction, motor2_position, motor3_enable,\n motor3_direction, motor3_position)\n', (2162, 2389), False, 'from pyserial_connection_arduino import connect_to_arduino, list_available_ports\n'), ((7738, 7751), 'camera.VideoCamera', 'VideoCamera', ([], {}), '()\n', (7749, 7751), False, 'from camera import VideoCamera\n'), ((9837, 9854), 'os.stat', 'os.stat', (['filename'], {}), '(filename)\n', (9844, 9854), False, 'import os\n'), ((5027, 5061), 'datetime.timedelta', 'timedelta', ([], {'seconds': 'task_seperation'}), '(seconds=task_seperation)\n', (5036, 5061), False, 'from datetime import datetime, timedelta\n'), ((5115, 5163), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(moving_time + task_seperation)'}), '(seconds=moving_time + task_seperation)\n', (5124, 5163), False, 'from datetime import datetime, timedelta\n'), ((9750, 9787), 'os.path.join', 'os.path.join', (['static_folder', 'filename'], {}), '(static_folder, filename)\n', (9762, 9787), False, 'import os\n'), ((3693, 3707), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3705, 3707), False, 'from datetime import datetime, timedelta\n')]
|
"""playground music_beats
"""
import numpy as np
import matplotlib.pylab as plt
# v1: 2 patterns
# v2: 16 probs for event
t = np.linspace(0, 16-1, 16)
print("t", t)
p1 = np.zeros((16, 1))
p2 = np.zeros((16, 1))
p1[[0, 4, 8, 12],0] = 1.
p2[[0, 6, 8, 14],0] = 1.
plt.subplot(211)
plt.bar(t, p1) # , "ko")
plt.subplot(212)
plt.bar(t, p2) #, "ko")
# plt.gcf().adjust_subplots()
plt.show()
|
[
"matplotlib.pylab.subplot",
"numpy.zeros",
"matplotlib.pylab.bar",
"numpy.linspace",
"matplotlib.pylab.show"
] |
[((129, 155), 'numpy.linspace', 'np.linspace', (['(0)', '(16 - 1)', '(16)'], {}), '(0, 16 - 1, 16)\n', (140, 155), True, 'import numpy as np\n'), ((175, 192), 'numpy.zeros', 'np.zeros', (['(16, 1)'], {}), '((16, 1))\n', (183, 192), True, 'import numpy as np\n'), ((198, 215), 'numpy.zeros', 'np.zeros', (['(16, 1)'], {}), '((16, 1))\n', (206, 215), True, 'import numpy as np\n'), ((269, 285), 'matplotlib.pylab.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (280, 285), True, 'import matplotlib.pylab as plt\n'), ((286, 300), 'matplotlib.pylab.bar', 'plt.bar', (['t', 'p1'], {}), '(t, p1)\n', (293, 300), True, 'import matplotlib.pylab as plt\n'), ((311, 327), 'matplotlib.pylab.subplot', 'plt.subplot', (['(212)'], {}), '(212)\n', (322, 327), True, 'import matplotlib.pylab as plt\n'), ((328, 342), 'matplotlib.pylab.bar', 'plt.bar', (['t', 'p2'], {}), '(t, p2)\n', (335, 342), True, 'import matplotlib.pylab as plt\n'), ((382, 392), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (390, 392), True, 'import matplotlib.pylab as plt\n')]
|
from datetime import datetime
import pymongo
from aiohttp.web_request import Request
from aiohttp.web_response import (Response,
json_response)
from collector.services.persistence import (find,
save,
documents)
from collector.utils import bad_request_json
async def collect(request: Request,
collection: pymongo.collection.Collection) -> Response:
request_json = await request.json()
document = documents.normalize(documents.escape_dots(request_json))
save(document,
collection=collection)
if not request_json:
body = {'status': 'error',
'reason': 'invalid JSON.'}
return bad_request_json(body=body)
return json_response({'status': 'OK'})
def str_to_datetime(string: str,
format: str = '%Y-%m-%dT%H:%M:%S'):
return datetime.strptime(string, format)
async def search(request: Request,
collection: pymongo.collection.Collection) -> Response:
query = request.query
try:
source = query['source']
from_date_time, to_date_time = (str_to_datetime(query['dateStart']),
str_to_datetime(query['dateEnd']))
except KeyError:
body = {'status': 'error',
'reason': 'Invalid query: '
'query should contain '
'both keys "source", '
'"dateStart", "dateEnd".'}
return bad_request_json(body=body)
offset = int(query.get('offset', 0))
try:
limit = int(query['limit'])
except KeyError:
limit = None
cursor = find(source=source,
from_date_time=from_date_time,
to_date_time=to_date_time,
limit=limit,
offset=offset,
collection=collection)
count = cursor.count()
data = list(map(documents.unescape_dots,
map(documents.to_serializable,
cursor)))
return json_response({'data': data,
'offset': offset,
'count': count})
|
[
"collector.services.persistence.save",
"aiohttp.web_response.json_response",
"collector.utils.bad_request_json",
"datetime.datetime.strptime",
"collector.services.persistence.documents.escape_dots",
"collector.services.persistence.find"
] |
[((609, 646), 'collector.services.persistence.save', 'save', (['document'], {'collection': 'collection'}), '(document, collection=collection)\n', (613, 646), False, 'from collector.services.persistence import find, save, documents\n'), ((815, 846), 'aiohttp.web_response.json_response', 'json_response', (["{'status': 'OK'}"], {}), "({'status': 'OK'})\n", (828, 846), False, 'from aiohttp.web_response import Response, json_response\n'), ((949, 982), 'datetime.datetime.strptime', 'datetime.strptime', (['string', 'format'], {}), '(string, format)\n', (966, 982), False, 'from datetime import datetime\n'), ((1751, 1884), 'collector.services.persistence.find', 'find', ([], {'source': 'source', 'from_date_time': 'from_date_time', 'to_date_time': 'to_date_time', 'limit': 'limit', 'offset': 'offset', 'collection': 'collection'}), '(source=source, from_date_time=from_date_time, to_date_time=\n to_date_time, limit=limit, offset=offset, collection=collection)\n', (1755, 1884), False, 'from collector.services.persistence import find, save, documents\n'), ((2138, 2201), 'aiohttp.web_response.json_response', 'json_response', (["{'data': data, 'offset': offset, 'count': count}"], {}), "({'data': data, 'offset': offset, 'count': count})\n", (2151, 2201), False, 'from aiohttp.web_response import Response, json_response\n'), ((568, 603), 'collector.services.persistence.documents.escape_dots', 'documents.escape_dots', (['request_json'], {}), '(request_json)\n', (589, 603), False, 'from collector.services.persistence import find, save, documents\n'), ((775, 802), 'collector.utils.bad_request_json', 'bad_request_json', ([], {'body': 'body'}), '(body=body)\n', (791, 802), False, 'from collector.utils import bad_request_json\n'), ((1581, 1608), 'collector.utils.bad_request_json', 'bad_request_json', ([], {'body': 'body'}), '(body=body)\n', (1597, 1608), False, 'from collector.utils import bad_request_json\n')]
|
from multiprocessing import Pool
from functools import partial
from pathlib import Path
import pandas as pd
import numpy as np
from numpy import array
import matplotlib.pyplot as plt
import tqdm
from fire import Fire
from bifacial_radiance.main import RadianceObj,AnalysisObj, _popen
Path.ls = lambda x: sorted(list(x.iterdir()))
metadata = {'Name': 'Chamberytown',
'latitude': 45.637,
'longitude': 5.881,
'altitude': 235.0,
'State':'NZ',
'USAF':1,
'TZ':0}
def get_time_interval(model, date):
sl = model.input_meteo.index.get_loc(date)
if type(sl) is slice:
return sl.start, sl.stop
else: return (sl, sl+1)
def _convert_meteo(df):
return df[['ghi', 'dni', 'dhi']].rename(columns=str.upper)
def define_meteo(model, df):
model.input_meteo = _convert_meteo(df)
return model.readInesMeteoFile(model.input_meteo, metadata)
def define_scene(model, monitor=5,rack ='rackC3',withGroupF=False):
height = 0.77
originy = -0.1
sceneObjs = []
if rack == 'rackC3':
d = 0
m1_npanels = 2
height_m1 = height
full = True
if rack == 'rackC2':
d = 0.736
m1_npanels = 1
height_m1 = 1.63
full = True
if rack == 'rackC1':
d = 0.736
m1_npanels = 1
height_m1 = 1.63
full = False
mod1 = 'mod1'
model.makeModule(name=mod1,x=0.99,y=1.65,numpanels = m1_npanels ,xgap=0.04,ygap=0.05)
mod2 = 'mod2'
model.makeModule(name=mod2, x=0.99,y=1.65,numpanels = 2,xgap=0.04,ygap=0.05)
scDict_smGC = {'tilt':30,'pitch': 9.5,'clearance_height':height_m1,'azimuth':180, 'nMods': 1, 'nRows': 2, 'appendRadfile':True,'originx': -3.09, 'originy': originy + d}
sceneObjs += [model.makeScene(moduletype=mod1,sceneDict=scDict_smGC, hpc=True)] # sm = single module G: group
scDict_GC = {'tilt':30,'pitch': 9.5,'clearance_height':height,'azimuth':180, 'nMods': 5, 'nRows': 2, 'appendRadfile':True,'originx': 0, 'originy': originy }
sceneObjs += [model.makeScene(moduletype=mod2,sceneDict=scDict_GC, hpc=True)] #makeScene creates a .rad file
scDict_smGD = {'tilt':30,'pitch': 9.5,'clearance_height':height_m1,'azimuth':180, 'nMods': 1, 'nRows': 2, 'appendRadfile':True,'originx': 3.09, 'originy': originy + d}
sceneObjs += [model.makeScene(moduletype=mod1,sceneDict=scDict_smGD, hpc=True)]
scDict_GD = {'tilt':30,'pitch': 9.5,'clearance_height':height,'azimuth':180, 'nMods': 5, 'nRows': 2, 'appendRadfile':True,'originx': 6.17, 'originy': originy }
sceneObjs += [model.makeScene(moduletype=mod2,sceneDict=scDict_GD, hpc=True)]
scDict_GB = {'tilt':30,'pitch': 9.5,'clearance_height':height,'azimuth':180, 'nMods': 5, 'nRows': 2, 'appendRadfile':True,'originx': -6.17, 'originy': originy }
sceneObjs += [model.makeScene(moduletype=mod2,sceneDict=scDict_GB, hpc=True)]
scDict_GA = {'tilt':30,'pitch': 9.5,'clearance_height':height,'azimuth':180, 'nMods': 5, 'nRows': 2, 'appendRadfile':True,'originx': -12.36, 'originy': originy }
sceneObjs += [model.makeScene(moduletype=mod2,sceneDict=scDict_GA, hpc=True)]
scDict_GE = {'tilt':30,'pitch': 9.5,'clearance_height':height,'azimuth':180, 'nMods': 5, 'nRows': 2, 'appendRadfile':True,'originx': 12.36, 'originy': originy }
sceneObjs += [model.makeScene(moduletype=mod2,sceneDict=scDict_GE, hpc=True)]
if withGroupF:
scDict_GF = {'tilt':30,'pitch': 9.5,'clearance_height':height,'azimuth':180, 'nMods': 5, 'nRows': 2, 'appendRadfile':True,'originx': 18.54, 'originy': originy }
sceneObjs += [model.makeScene(moduletype=mod2,sceneDict=scDict_GF, hpc=True)]
if full == True:
scDict_smGE = {'tilt':30,'pitch': 9.5,'clearance_height':height_m1,'azimuth':180, 'nMods': 1, 'nRows': 2, 'appendRadfile':True,'originx': 9.26, 'originy': originy + d }
sceneObjs += [model.makeScene(moduletype=mod1,sceneDict=scDict_smGE, hpc=True)]
scDict_smGB = {'tilt':30,'pitch': 9.5,'clearance_height':height_m1,'azimuth':180, 'nMods': 1, 'nRows': 2, 'appendRadfile':True,'originx': -9.26, 'originy': originy + d }
sceneObjs += [model.makeScene(moduletype=mod1,sceneDict=scDict_smGB, hpc=True)]
scDict_smGA = {'tilt':30,'pitch': 9.5,'clearance_height':height_m1,'azimuth':180, 'nMods': 1, 'nRows': 2, 'appendRadfile':True,'originx': -15.45, 'originy': originy + d }
sceneObjs += [model.makeScene(moduletype=mod1,sceneDict=scDict_smGA, hpc=True)]
if withGroupF:
scDict_smGF = {'tilt':30,'pitch': 9.5,'clearance_height':height_m1,'azimuth':180, 'nMods': 1, 'nRows': 2, 'appendRadfile':True,'originx': 15.45, 'originy': originy + d }
sceneObjs += [model.makeScene(moduletype=mod1,sceneDict=scDict_smGF, hpc=True)]
model.module6 = sceneObjs[monitor]
return model.module6
STRUCT_HEIGHT = 0.60
def genbox(model,
name,
scene_name='cScene.rad',
material='Metal_Aluminum_Anodized',
dim=(1.0,1.0,1.0),
r=(0,0,0),
t=(0.0,0.0,0.0),
hpc=True):
genbox_cmd = f'!genbox {material} {name} {dim[0]} {dim[1]} {dim[2]} '
xform_cmd = f'| xform -rx {r[0]} -ry {r[1]} -rz {r[2]} -t {t[0]} {t[1]} {t[2]}'
cmd = genbox_cmd + xform_cmd
box = model.makeCustomObject(name, cmd)
model.appendtoScene(scene_name, box, hpc=hpc)
return
def add_vert_posts(model,
scene_name='cScene.rad',
material='Metal_Aluminum_Anodized',
rowoffset=0,
hpc=True):
height = STRUCT_HEIGHT
genbox(model,'vert_post1', scene_name, material, dim=(0.12, 0.24, height), t=(-15.965, -1.45 + rowoffset, 0), hpc=hpc)
genbox(model,'vert_post2', scene_name, material, dim=(0.12, 0.24, height), t=(-12.8750, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post3', scene_name, material, dim=(0.12, 0.24, height), t=(-9.785, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post4', scene_name, material, dim=(0.12, 0.24, height), t=(-6.685, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post5', scene_name, material, dim=(0.12, 0.24, height), t=(-3.595, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post6', scene_name, material, dim=(0.12, 0.24, height), t=(-0.505, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post7', scene_name, material, dim=(0.12, 0.24, height), t=(2.585, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post8', scene_name, material, dim=(0.12, 0.24, height), t=(5.655, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post9', scene_name, material, dim=(0.12, 0.24, height), t=(8.745, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post10', scene_name, material, dim=(0.12, 0.24, height), t=(11.835, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post11', scene_name, material, dim=(0.12, 0.24, height), t=(14.925, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post12', scene_name, material, dim=(0.12, 0.24, height), t=(18.015, -1.45+ rowoffset, 0), hpc=hpc)
genbox(model,'vert_post13', scene_name, material, dim=(0.12, 0.24, height), t=(21.105, -1.45+ rowoffset, 0), hpc=hpc)
#soil rack
genbox(model,'rack_cables', scene_name, material, dim=(24.7, 0.24, 0.1), t=(-15.965, -1.45+0.24+ rowoffset, 0), hpc=hpc)
return
def pivoting_structure(model, material='Metal_Aluminum_Anodized', angle=30,rowoffset=0, hpc=True):
def _t(alpha, h, l,rowoffset):
'disgusting geometry'
n = np.sqrt(h**2 + l**2)
alpha = np.deg2rad(alpha)
beta = np.arctan(h/l)
gamma = beta-alpha
y = -l + n*np.cos(gamma)
z = h - n*np.sin(gamma)
print(f'alpha, beta, gamma: {alpha, beta, gamma}')
print(f'n: {n}')
return (0, y + rowoffset, z)
add_diag_posts(model, 'pivoting_struct.rad', material)
add_hor_posts(model, 'pivoting_struct.rad', material)
add_diag_posts_intra(model, 'pivoting_struct.rad', material)
t = _t(angle, STRUCT_HEIGHT, 1.45,rowoffset)
print(f'moving struct to {t}')
cmd = f'!xform -rx {angle} -t {t[0]} {t[1]} {t[2]} '
print(cmd)
model.radfiles.pop() #remove non pivoted scene
model.appendtoScene(f'pivoting_struct_{angle}.rad', 'objects/pivoting_struct.rad', cmd, hpc=hpc)
return
def add_diag_posts(model,
scene_name='cScene.rad',
material='Metal_Aluminum_Anodized',
hpc=True):
length = 3.5
zheight = 0.24
height = STRUCT_HEIGHT - zheight
genbox(model,'diag_post1', scene_name, material, dim=(0.12, length, 0.24), t=(-15.965, -1.45, height), hpc=hpc)
genbox(model,'diag_post2', scene_name, material, dim=(0.12, length, 0.24), t=(-12.8750, -1.45, height), hpc=hpc)
genbox(model,'diag_post3', scene_name, material, dim=(0.12, length, 0.24), t=(-9.785, -1.45, height), hpc=hpc)
genbox(model,'diag_post4', scene_name, material, dim=(0.12, length, 0.24), t=(-6.685, -1.45, height), hpc=hpc)
genbox(model,'diag_post5', scene_name, material, dim=(0.12, length, 0.24), t=(-3.595, -1.45, height), hpc=hpc)
genbox(model,'diag_post6', scene_name, material, dim=(0.12, length, 0.24), t=(-0.505, -1.45, height), hpc=hpc)
genbox(model,'diag_post7', scene_name, material, dim=(0.12, length, 0.24), t=(2.585, -1.45, height), hpc=hpc)
genbox(model,'diag_post8', scene_name, material, dim=(0.12, length, 0.24), t=(5.655, -1.45, height), hpc=hpc)
genbox(model,'diag_post9', scene_name, material, dim=(0.12, length, 0.24), t=(8.745, -1.45, height), hpc=hpc)
genbox(model,'diag_post10', scene_name, material, dim=(0.12, length, 0.24), t=(11.835, -1.45, height), hpc=hpc)
genbox(model,'diag_post11', scene_name, material, dim=(0.12, length, 0.24), t=(14.925, -1.45, height), hpc=hpc)
genbox(model,'diag_post12', scene_name, material, dim=(0.12, length, 0.24), t=(18.015, -1.45, height), hpc=hpc)
genbox(model,'diag_post13', scene_name, material, dim=(0.12, length, 0.24), t=(21.105, -1.45, height), hpc=hpc)
return
def add_hor_posts(model,
scene_name='cScene.rad',
material='Metal_Aluminum_Anodized',
hpc=True):
size = 0.09
height = STRUCT_HEIGHT
length = 3.5 - size
bottom_left = array([-15.965, -1.45, height])
top_left = array([-15.965, -1.45+length, height])
# midde_left = (top_left + bottom_left)/2
genbox(model,'hor_post_bottom', scene_name, material, dim=(37.08, size, size), t=bottom_left, hpc=hpc)
genbox(model,'hor_post_top', scene_name, material, dim=(37.08, size, size), t=top_left, hpc=hpc)
# genbox(model,'hor_post_middle', scene_name, material, dim=(24.7, size, size), t=midde_left, hpc=hpc)
return
def add_diag_posts_intra(model,
scene_name='cScene.rad',
material='Metal_Aluminum_Anodized',
hpc=True):
zsize = 0.09
xsize = 0.045
height = STRUCT_HEIGHT
length = 3.5
z_struct=0.09
modulex = 0.99 + xsize/2
t = array([-15.965, -1.45, height+z_struct])
for i in range(24):
genbox(model,f'diag_post_intra1.{i}', scene_name, material,
dim=(xsize, length, zsize), t=t + i*array([modulex,0,0]), hpc=hpc)
return
def add_box(model,
scene_name='cScene.rad',
material='beigeroof',
hpc=True):
genbox(model,'Boite_electrique', scene_name, material, dim=(0.12, 0.20, 0.24), t=(-12.875, 0.75, 1.36), hpc=hpc)
# genbox(model,'cables', scene_name, material, dim=(0.04, 0.1, 0.07), t=(-12.83, 0.75, 1.24), hpc=hpc)
return
def add_really_big_box(model,
scene_name='cScene.rad',
material='beigeroof',
hpc=True):
genbox(model,'building', scene_name, material, dim=(67, 10, 12), r=(0, 0, 15), t=(-25.875, 58, 0), hpc=hpc)
return
def add_ref_cell(model,group_ref_cell='A2',rowoffset=0):
if group_ref_cell == 'A2':
moduletype_refCell = 'ref_cell'
model.makeModule(name=moduletype_refCell,x=0.12,y=0.12,numpanels = 1)
sceneRef_rCell = {'tilt':30,'pitch': 9.5,'clearance_height':1.3,'azimuth':180,
'nMods': 1, 'nRows': 1, 'appendRadfile':True,'originx': -12.815, 'originy': 0.55+ rowoffset}
sceneObj_rCell = model.makeScene(moduletype=moduletype_refCell, sceneDict=sceneRef_rCell, hpc=True)
if group_ref_cell == 'B2':
moduletype_refCell = 'ref_cell'
model.makeModule(name=moduletype_refCell,x=0.12,y=0.12,numpanels = 1)
sceneRef_rCell = {'tilt':30,'pitch': 9.5,'clearance_height':1.3,'azimuth':180,
'nMods': 1, 'nRows': 1, 'appendRadfile':True,'originx': -6.625, 'originy': 0.55+ rowoffset}
sceneObj_rCell = model.makeScene(moduletype=moduletype_refCell, sceneDict=sceneRef_rCell, hpc=True)
if group_ref_cell == 'C2':
moduletype_refCell = 'ref_cell'
model.makeModule(name=moduletype_refCell,x=0.12,y=0.12,numpanels = 1)
sceneRef_rCell = {'tilt':30,'pitch': 9.5,'clearance_height':1.3,'azimuth':180,
'nMods': 1, 'nRows': 1, 'appendRadfile':True,'originx': -0.505, 'originy': 0.55+ rowoffset}
sceneObj_rCell = model.makeScene(moduletype=moduletype_refCell, sceneDict=sceneRef_rCell, hpc=True)
if group_ref_cell == 'D2':
moduletype_refCell = 'ref_cell'
model.makeModule(name=moduletype_refCell,x=0.12,y=0.12,numpanels = 1)
sceneRef_rCell = {'tilt':30,'pitch': 9.5,'clearance_height':1.3,'azimuth':180,
'nMods': 1, 'nRows': 1, 'appendRadfile':True,'originx': 5.68, 'originy': 0.55+ rowoffset}
sceneObj_rCell = model.makeScene(moduletype=moduletype_refCell, sceneDict=sceneRef_rCell, hpc=True)
if group_ref_cell == 'E2':
moduletype_refCell = 'ref_cell'
model.makeModule(name=moduletype_refCell,x=0.12,y=0.12,numpanels = 1)
sceneRef_rCell = {'tilt':30,'pitch': 9.5,'clearance_height':1.3,'azimuth':180,
'nMods': 1, 'nRows': 1, 'appendRadfile':True,'originx':11.86, 'originy': 0.55+ rowoffset}
sceneObj_rCell = model.makeScene(moduletype=moduletype_refCell, sceneDict=sceneRef_rCell, hpc=True)
if group_ref_cell == 'F2':
moduletype_refCell = 'ref_cell'
model.makeModule(name=moduletype_refCell,x=0.12,y=0.12,numpanels = 1)
sceneRef_rCell = {'tilt':30,'pitch': 9.5,'clearance_height':1.3,'azimuth':180,
'nMods': 1, 'nRows': 1, 'appendRadfile':True,'originx': 18.04, 'originy': 0.55+ rowoffset}
sceneObj_rCell = model.makeScene(moduletype=moduletype_refCell, sceneDict=sceneRef_rCell, hpc=True)
if group_ref_cell == '2_B':
moduletype_refCell = 'ref_cell_2_b'
model.makeModule(name=moduletype_refCell,x=0.12,y=0.12,numpanels = 1)
sceneRef_rCell = {'tilt':30,'pitch': 9.5,'clearance_height':2.0,'azimuth':180,
'nMods': 1, 'nRows': 1, 'appendRadfile':True,'originx': -0.44, 'originy': 1.63 + rowoffset}
sceneObj_rCell = model.makeScene(moduletype=moduletype_refCell, sceneDict=sceneRef_rCell, hpc=True)
if group_ref_cell == '2_A':
moduletype_refCell = 'ref_cell_2_a'
model.makeModule(name=moduletype_refCell,x=0.12,y=0.12,numpanels = 1)
sceneRef_rCell = {'tilt':30,'pitch': 9.5,'clearance_height':1.3,'azimuth':180,
'nMods': 1, 'nRows': 1, 'appendRadfile':True,'originx': -0.44, 'originy': 0.55 + rowoffset}
sceneObj_rCell = model.makeScene(moduletype=moduletype_refCell, sceneDict=sceneRef_rCell, hpc=True)
if group_ref_cell == '2_C':
moduletype_refCell = 'ref_cell_2_c'
model.makeModule(name=moduletype_refCell,x=0.12,y=0.12,numpanels = 1)
sceneRef_rCell = {'tilt':30,'pitch': 9.5,'clearance_height':0.46,'azimuth':180,
'nMods': 1, 'nRows': 1, 'appendRadfile':True,'originx': -0.44, 'originy': -0.93 + rowoffset}
sceneObj_rCell = model.makeScene(moduletype=moduletype_refCell, sceneDict=sceneRef_rCell, hpc=True)
return sceneObj_rCell
def delete_oct_files(project_path):
for f in project_path.glob('*.oct'):
f.unlink()
print(f'Deleted .oct files')
return
def delete_rad_files(project_path):
for f in (project_path).glob('*/*.rad'):
f.unlink()
print(f'Deleted .rad files')
return
def view(file_list, view='front', program='rvu'):
'Renders a view of the file'
views = {'diag': '-vp -17 3 1 -vd 2 -1 -0.3 -vu 0 0 1 -av 0.2 0.2 0.2',
'side': '-vp -14.3 0.2 1.5 -vd 1 0 0 -vu 0 0 1 -av 0.2 0.2 0.2',
'side2': '-vp -17 -6 3.5 -vd 0.2 1 -0.3 -vu 0 0 1 -av 10 10 10 -ab 2',
'back': '-vp -13.215 2 1 -vd 0.3 -1 0 -vu 0 0 1 -av 0.2 0.2 0.2',
'front': '-vp 2.5 -40 25 -vd 0 1 -0.5 -vu 0 0 1 -av 0.2 0.2 0.2',
'top': '-vp -17.5 1.6 2.7 -vd 1 0 -0.1 -vu 0 0 1',
'bottom': '-vp -17.5 -1.55 1.0 -vd 1 0.05 -0.1 -vu 0 0 1',
'front_low': '-vp -17 -5 2 -vd 0.5 1 -0.05 -vu 0 0 1 -av 0.2 0.2 0.2'}
program = 'objview' if file_list[0].endswith('rad') else program
if isinstance(file_list,list):
files = ' '.join([file_list[0]]+[s[s.find('objects'):] for s in file_list if ('objects' in s)])
if isinstance(file_list, str):
files = file_list
vp = views[view] if view in views else view
cmd = _cmd(program, vp, files)
return _popen(cmd, None)
def _cmd(program, vp, filename):
vp = ' '+vp+' ' if program =='rvu' else f' -v "{vp}" '
cmd = program + vp + filename
print(f' cmd: {cmd}')
return cmd
def run_simulation(date='18 July 2017',
outfile='new_results',
cores=10,
albedo=0.4,
rack = 'rackc3',
rowoffset = 9.5,
add_struct=True,
ref_cell=True,
group_ref_cell='A2',
withGroupF=False,
project_name = 'INCAFixed',
lspv_path = Path.home()/Path("Documents/lspv_analyseSoft/'RayTracing_simulations/dev_nbs_fc'"),
ines_meteo_file = Path.home()/'DATA/INCA/chic_bi3p/tmy_INCA_bifi_5T.hdf'):
project_path = lspv_path/project_name
if not project_path.exists(): project_path.mkdir()
delete_oct_files(project_path)
delete_rad_files(project_path)
sim_name = 'inca'
sensorsy = 9
inca = RadianceObj(sim_name, str(project_path.absolute())) # Radiance object named model_first_test
inca.setGround(albedo)
#define the scene with all the modules and scene dicts
module6 = define_scene(inca, 5,rack,withGroupF) #unused if ref_cell present
#add strcutures
if add_struct:
pivoting_structure(inca,rowoffset)
add_box(inca)
if add_really_big_box:
add_really_big_box(inca)
inca.monitored_obj = add_ref_cell(inca,group_ref_cell) if ref_cell else module6
#append the ines meteo file
meteo_df = pd.read_hdf(ines_meteo_file).loc[date,:]
define_meteo(inca, meteo_df)
#chose the date of your sim, must be in the input meteo file
results_file = date.replace(' ', '') + 'w_'+rack+'_sf_'+group_ref_cell+'.hdf'
if withGroupF:
results_file = date.replace(' ', '') + 'w_'+rack+'_'+group_ref_cell+'.hdf'
#ti, tf = get_time_interval(inca, date)
#print(f'Timeindexes : {ti}, {tf}')
ti = 528
tf = 529
import tqdm
pool = Pool(1)
res_list = []
f = partial(compute_radiance, model=inca, sim_name=sim_name, sensorsy=sensorsy)
for x in tqdm.tqdm(pool.imap(f, range(ti,tf)), total=tf-ti):
res_list.append(x)
pass
pool.close()
pool.join()
#pool = Pool(cores)
#res_list = []
#print(f'Launching simulation with {cores} processes')
#f = partial(compute_radiance, model=inca, sim_name=sim_name, sensorsy=sensorsy)
#if cores <2:
# res_list = list(map(f, range(ti, tf)))
# res_list = [f(x) for x in range(ti, tf)]
#else:
#for x in tqdm.tqdm(pool.imap(f, range(ti,tf)), total=tf-ti):
# res_list.append(x)
# pass
#pool.close()
#pool.join()
#print(f'res_list: {res_list}')
results = pd.DataFrame(data=res_list,
index = inca.input_meteo[date].index,
columns = [f'g_{i}' for i in range(sensorsy)]+[f'gb_{i}' for i in range(sensorsy)])
print(f'Results file: {results_file}')
results.to_hdf(project_path/('results/'+results_file), key='df')
#results.to_csv(project_path/('results/'+results_file+'.csv'))
print(project_path/('results/'+results_file+'.hdf'))
return inca
if __name__ == '__main__':
Fire(run_simulation)
|
[
"functools.partial",
"fire.Fire",
"pathlib.Path.home",
"numpy.deg2rad",
"pandas.read_hdf",
"bifacial_radiance.main._popen",
"pathlib.Path",
"numpy.sin",
"numpy.array",
"numpy.cos",
"multiprocessing.Pool",
"numpy.arctan",
"numpy.sqrt"
] |
[((10446, 10477), 'numpy.array', 'array', (['[-15.965, -1.45, height]'], {}), '([-15.965, -1.45, height])\n', (10451, 10477), False, 'from numpy import array\n'), ((10493, 10533), 'numpy.array', 'array', (['[-15.965, -1.45 + length, height]'], {}), '([-15.965, -1.45 + length, height])\n', (10498, 10533), False, 'from numpy import array\n'), ((11208, 11250), 'numpy.array', 'array', (['[-15.965, -1.45, height + z_struct]'], {}), '([-15.965, -1.45, height + z_struct])\n', (11213, 11250), False, 'from numpy import array\n'), ((17743, 17760), 'bifacial_radiance.main._popen', '_popen', (['cmd', 'None'], {}), '(cmd, None)\n', (17749, 17760), False, 'from bifacial_radiance.main import RadianceObj, AnalysisObj, _popen\n'), ((19815, 19822), 'multiprocessing.Pool', 'Pool', (['(1)'], {}), '(1)\n', (19819, 19822), False, 'from multiprocessing import Pool\n'), ((19849, 19924), 'functools.partial', 'partial', (['compute_radiance'], {'model': 'inca', 'sim_name': 'sim_name', 'sensorsy': 'sensorsy'}), '(compute_radiance, model=inca, sim_name=sim_name, sensorsy=sensorsy)\n', (19856, 19924), False, 'from functools import partial\n'), ((21066, 21086), 'fire.Fire', 'Fire', (['run_simulation'], {}), '(run_simulation)\n', (21070, 21086), False, 'from fire import Fire\n'), ((7648, 7672), 'numpy.sqrt', 'np.sqrt', (['(h ** 2 + l ** 2)'], {}), '(h ** 2 + l ** 2)\n', (7655, 7672), True, 'import numpy as np\n'), ((7685, 7702), 'numpy.deg2rad', 'np.deg2rad', (['alpha'], {}), '(alpha)\n', (7695, 7702), True, 'import numpy as np\n'), ((7718, 7734), 'numpy.arctan', 'np.arctan', (['(h / l)'], {}), '(h / l)\n', (7727, 7734), True, 'import numpy as np\n'), ((18377, 18388), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (18386, 18388), False, 'from pathlib import Path\n'), ((18389, 18459), 'pathlib.Path', 'Path', (['"""Documents/lspv_analyseSoft/\'RayTracing_simulations/dev_nbs_fc\'"""'], {}), '("Documents/lspv_analyseSoft/\'RayTracing_simulations/dev_nbs_fc\'")\n', (18393, 18459), False, 'from pathlib import Path\n'), ((18498, 18509), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (18507, 18509), False, 'from pathlib import Path\n'), ((19345, 19373), 'pandas.read_hdf', 'pd.read_hdf', (['ines_meteo_file'], {}), '(ines_meteo_file)\n', (19356, 19373), True, 'import pandas as pd\n'), ((7779, 7792), 'numpy.cos', 'np.cos', (['gamma'], {}), '(gamma)\n', (7785, 7792), True, 'import numpy as np\n'), ((7811, 7824), 'numpy.sin', 'np.sin', (['gamma'], {}), '(gamma)\n', (7817, 7824), True, 'import numpy as np\n'), ((11393, 11415), 'numpy.array', 'array', (['[modulex, 0, 0]'], {}), '([modulex, 0, 0])\n', (11398, 11415), False, 'from numpy import array\n')]
|
# -*- coding: utf-8 -*-
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired, Length
from wtforms import StringField, SubmitField, SelectField, TextAreaField, ValidationError, HiddenField, \
BooleanField, PasswordField
class LoginForm(FlaskForm):
username = StringField('用户名', validators=[DataRequired(), Length(1, 20)])
password = PasswordField('密码', validators=[DataRequired(), Length(1, 20)])
remember = BooleanField('记住密码')
submit = SubmitField('登陆')
class RegisterForm(FlaskForm):
username = StringField('用户名(邮箱地址)', validators=[DataRequired(), Length(1, 20)])
truename = StringField('真实姓名', validators=[DataRequired(), Length(1, 20)])
password = PasswordField('密码', validators=[DataRequired(), Length(1, 20)])
password_again = PasswordField('<PASSWORD>', validators=[DataRequired(), Length(1, 20)])
phone_number = PasswordField('手机号', validators=[DataRequired(), Length(1, 20)])
submit = SubmitField('注册')
|
[
"wtforms.BooleanField",
"wtforms.SubmitField",
"wtforms.validators.Length",
"wtforms.validators.DataRequired"
] |
[((448, 468), 'wtforms.BooleanField', 'BooleanField', (['"""记住密码"""'], {}), "('记住密码')\n", (460, 468), False, 'from wtforms import StringField, SubmitField, SelectField, TextAreaField, ValidationError, HiddenField, BooleanField, PasswordField\n'), ((482, 499), 'wtforms.SubmitField', 'SubmitField', (['"""登陆"""'], {}), "('登陆')\n", (493, 499), False, 'from wtforms import StringField, SubmitField, SelectField, TextAreaField, ValidationError, HiddenField, BooleanField, PasswordField\n'), ((964, 981), 'wtforms.SubmitField', 'SubmitField', (['"""注册"""'], {}), "('注册')\n", (975, 981), False, 'from wtforms import StringField, SubmitField, SelectField, TextAreaField, ValidationError, HiddenField, BooleanField, PasswordField\n'), ((328, 342), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (340, 342), False, 'from wtforms.validators import DataRequired, Length\n'), ((344, 357), 'wtforms.validators.Length', 'Length', (['(1)', '(20)'], {}), '(1, 20)\n', (350, 357), False, 'from wtforms.validators import DataRequired, Length\n'), ((405, 419), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (417, 419), False, 'from wtforms.validators import DataRequired, Length\n'), ((421, 434), 'wtforms.validators.Length', 'Length', (['(1)', '(20)'], {}), '(1, 20)\n', (427, 434), False, 'from wtforms.validators import DataRequired, Length\n'), ((598, 612), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (610, 612), False, 'from wtforms.validators import DataRequired, Length\n'), ((614, 627), 'wtforms.validators.Length', 'Length', (['(1)', '(20)'], {}), '(1, 20)\n', (620, 627), False, 'from wtforms.validators import DataRequired, Length\n'), ((671, 685), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (683, 685), False, 'from wtforms.validators import DataRequired, Length\n'), ((687, 700), 'wtforms.validators.Length', 'Length', (['(1)', '(20)'], {}), '(1, 20)\n', (693, 700), False, 'from wtforms.validators import DataRequired, Length\n'), ((746, 760), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (758, 760), False, 'from wtforms.validators import DataRequired, Length\n'), ((762, 775), 'wtforms.validators.Length', 'Length', (['(1)', '(20)'], {}), '(1, 20)\n', (768, 775), False, 'from wtforms.validators import DataRequired, Length\n'), ((835, 849), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (847, 849), False, 'from wtforms.validators import DataRequired, Length\n'), ((851, 864), 'wtforms.validators.Length', 'Length', (['(1)', '(20)'], {}), '(1, 20)\n', (857, 864), False, 'from wtforms.validators import DataRequired, Length\n'), ((925, 939), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (937, 939), False, 'from wtforms.validators import DataRequired, Length\n'), ((941, 954), 'wtforms.validators.Length', 'Length', (['(1)', '(20)'], {}), '(1, 20)\n', (947, 954), False, 'from wtforms.validators import DataRequired, Length\n')]
|
from json.decoder import JSONDecoder
import serial
import json
import time
class open_motor:
def __init__(self):
self.ser = serial.Serial()
self.pos_pid_msg = {}
self.vel_pid_msg = {}
self.pid_config_msg = {}
self.msg_data = {}
self._port = None
self._baudrate = None
self._timeout = None
def init_serial_port(self, port, baudRate, timeout):
self._port = port
self._baudrate = baudRate
self._timeout = timeout
self.ser = serial.Serial(self._port, self._baudrate, timeout=self._timeout)
def send_pwm_goal(self,pwm0,pwm1,pwm2,pwm3):
self.msg_data["command"] = "pwm_direct"
self.msg_data["pwm0"] = pwm0
self.msg_data["pwm1"] = pwm1
self.msg_data["pwm2"] = pwm2
self.msg_data["pwm3"] = pwm3
msg = json.dumps(self.msg_data).encode("ascii")
self.ser.write(msg)
def send_vel_goal(self,vel0,vel1,vel2,vel3):
self.msg_data["command"] = "vel_pid"
self.msg_data["vel0"] = vel0
self.msg_data["vel1"] = vel1
self.msg_data["vel2"] = vel2
self.msg_data["vel3"] = vel3
msg = json.dumps(self.msg_data).encode("ascii")
self.ser.write(msg)
def send_pos_goal(self,pos0,pos1,pos2,pos3):
self.msg_data["command"] = "pos_pid"
self.msg_data["pos0"] = pos0
self.msg_data["pos1"] = pos1
self.msg_data["pos2"] = pos2
self.msg_data["pos3"] = pos3
msg = json.dumps(self.msg_data).encode("ascii")
self.ser.write(msg)
def get_response(self):
self.ser.flushInput()
data = self.ser.readline().decode("utf-8")
return data
def get_response_json(self):
data = self.get_response()
json_data = json.loads(data)
return json_data
def isOpen(self):
return self.ser.is_open
# def wait_for_response(self):
# response = "string"
# while(response != "msg_recieved"):
# response = self.get_response()
|
[
"serial.Serial",
"json.loads",
"json.dumps"
] |
[((138, 153), 'serial.Serial', 'serial.Serial', ([], {}), '()\n', (151, 153), False, 'import serial\n'), ((528, 592), 'serial.Serial', 'serial.Serial', (['self._port', 'self._baudrate'], {'timeout': 'self._timeout'}), '(self._port, self._baudrate, timeout=self._timeout)\n', (541, 592), False, 'import serial\n'), ((1805, 1821), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (1815, 1821), False, 'import json\n'), ((855, 880), 'json.dumps', 'json.dumps', (['self.msg_data'], {}), '(self.msg_data)\n', (865, 880), False, 'import json\n'), ((1185, 1210), 'json.dumps', 'json.dumps', (['self.msg_data'], {}), '(self.msg_data)\n', (1195, 1210), False, 'import json\n'), ((1514, 1539), 'json.dumps', 'json.dumps', (['self.msg_data'], {}), '(self.msg_data)\n', (1524, 1539), False, 'import json\n')]
|
"""Handling of skew surge data.
Two skew surge datasets are implemented: the dataset for Brest created
by Reinert et al. (2021), which can be received from the authors upon
request, and the GESLA-2 surge dataset of Marcos & Woodworth (2017).
See the file ‘tools_GESLA’ for further information on the latter.
Written by <NAME>, April 2020, May 2021.
"""
import time
import calendar
from enum import Enum
import numpy as np
from tools_GESLA import read_GESLA_surge_file, get_GESLA_surge_filename
# Path to the skew surge data file of Reinert et al. (2021)
SKEW_SURGE_FILE = "data/skew_surge_Brest.npy"
class Timeseries(Enum):
SKEW_SURGE = "skew surge (Reinert et al. 2021)"
SKEW_SURGE_GESLA = "skew surge (GESLA-2)"
def load_data(city: str, dataset: Timeseries, year_start=None, year_end=None, include_low_tide_surge=False):
"""Get ‘dataset’ for ‘city’ from ‘year_start’ to ‘year_end’.
The returned object is a dictionary with the following keys:
- city (string, the same as the input value)
- name (string, short description of the dataset)
- full_name (string, long description of the dataset)
- year_start (int, first valid year of the time series)
- year_end (int, last valid year of the time series)
- t (array, time values in s)
- h (array, height values in cm)
The returned dataset can be limited to contain only data from
‘year_start’ to ‘year_end’. Each of these two arguments is optional
and inclusive if given. They work even if no data for the given
years exists, in which case the returned values of ‘year_start’ and
‘year_end’ will be set to the actual first and last year for which
there is data within the given period.
The surge dataset by Reinert et al. (2021) is only available for
Brest. It contains both high and low tide skew surge levels, but by
default, only high tide surge levels are used. To also include low
tide surge, set the corresponding parameter to True. Surge levels
by Reinert et al. (2021) are relative to the annual mean sea level.
For the GESLA-2 skew surge dataset by <NAME> (2017),
several cities are available. This dataset contains only high tide
surge levels, so include_low_tide_surge must be False. Surge levels
in the GESLA-2 dataset contain variations in the mean sea level, in
particular the mean sea level rise.
"""
# Initialize the dictionary that is returned
data = {
"city": city,
"name": "",
"full_name": "",
"year_start": None,
"year_end": None,
"t": None,
"h": None,
}
if dataset == Timeseries.SKEW_SURGE:
if city != "Brest":
raise ValueError(
"only city Brest is available for SKEW_SURGE dataset; "
"did you want to use SKEW_SURGE_GESLA dataset?"
)
data["name"] = "surge (Reinert et al. 2021)"
data["full_name"] = "skew surge relative to annual mean sea level (Reinert et al. 2021)"
print("Reading", data["full_name"], "for", data["city"])
data["t"], data["h"], high_tides = np.load(SKEW_SURGE_FILE)
high_tides = np.array(high_tides, dtype=bool)
if include_low_tide_surge:
print("Using both high and low tide surge levels")
else:
data["name"] = "high tide " + data["name"]
data["full_name"] = "high tide " + data["full_name"]
data["t"] = data["t"][high_tides]
data["h"] = data["h"][high_tides]
elif dataset == Timeseries.SKEW_SURGE_GESLA:
if include_low_tide_surge:
raise ValueError("GESLA-2 surge dataset does not contain low tide surge levels.")
data["name"] = "surge (GESLA-2)"
data["full_name"] = "skew surge of GESLA-2 (Marcos & Woodworth 2017)"
filename = get_GESLA_surge_filename(city)
print("Reading", data["full_name"], "for", data["city"])
data["t"], data["h"] = read_GESLA_surge_file(filename)
data["t"] = np.array(data["t"])
data["h"] = np.array(data["h"])
else:
raise ValueError("unknown dataset {} requested".format(dataset))
# Limit the data to the given range
if year_start is not None:
print("Removing data before {}".format(year_start))
starttime = calendar.timegm((year_start, 1, 1, 0, 0, 0))
data["h"] = data["h"][data["t"] >= starttime]
data["t"] = data["t"][data["t"] >= starttime]
if year_end is not None:
print("Removing data after {}".format(year_end))
endtime = calendar.timegm((year_end + 1, 1, 1, 0, 0, 0))
data["h"] = data["h"][data["t"] < endtime]
data["t"] = data["t"][data["t"] < endtime]
# Convert from mm to cm
data["h"] = data["h"] / 10
# Get first and last year
data["year_start"] = time.gmtime(min(data["t"])).tm_year
data["year_end"] = time.gmtime(max(data["t"])).tm_year
print("{:9_d} records".format(len(data["t"])))
return data
|
[
"numpy.load",
"calendar.timegm",
"tools_GESLA.get_GESLA_surge_filename",
"numpy.array",
"tools_GESLA.read_GESLA_surge_file"
] |
[((3139, 3163), 'numpy.load', 'np.load', (['SKEW_SURGE_FILE'], {}), '(SKEW_SURGE_FILE)\n', (3146, 3163), True, 'import numpy as np\n'), ((3185, 3217), 'numpy.array', 'np.array', (['high_tides'], {'dtype': 'bool'}), '(high_tides, dtype=bool)\n', (3193, 3217), True, 'import numpy as np\n'), ((4331, 4375), 'calendar.timegm', 'calendar.timegm', (['(year_start, 1, 1, 0, 0, 0)'], {}), '((year_start, 1, 1, 0, 0, 0))\n', (4346, 4375), False, 'import calendar\n'), ((4588, 4634), 'calendar.timegm', 'calendar.timegm', (['(year_end + 1, 1, 1, 0, 0, 0)'], {}), '((year_end + 1, 1, 1, 0, 0, 0))\n', (4603, 4634), False, 'import calendar\n'), ((3858, 3888), 'tools_GESLA.get_GESLA_surge_filename', 'get_GESLA_surge_filename', (['city'], {}), '(city)\n', (3882, 3888), False, 'from tools_GESLA import read_GESLA_surge_file, get_GESLA_surge_filename\n'), ((3985, 4016), 'tools_GESLA.read_GESLA_surge_file', 'read_GESLA_surge_file', (['filename'], {}), '(filename)\n', (4006, 4016), False, 'from tools_GESLA import read_GESLA_surge_file, get_GESLA_surge_filename\n'), ((4037, 4056), 'numpy.array', 'np.array', (["data['t']"], {}), "(data['t'])\n", (4045, 4056), True, 'import numpy as np\n'), ((4077, 4096), 'numpy.array', 'np.array', (["data['h']"], {}), "(data['h'])\n", (4085, 4096), True, 'import numpy as np\n')]
|
import os
import sys
import datetime
from pathlib import Path
from logging import getLogger, Formatter, StreamHandler, INFO, WARNING
from logging import FileHandler
import importlib
import pandas as pd
import numpy as np
from easydict import EasyDict as edict
def is_devmode():
return True if os.uname().nodename == 'resona' else False
def prefix_path():
if not is_devmode():
return '/data'
else:
return 'data'
LOGDIR = '/wdata/working/sp5r2/models/logs/{modelname:s}'
def load_config(config_path):
mod = importlib.import_module(config_path.rstrip('.py').replace('/', '.'))
return edict(mod.CONFIG)
def set_filehandler(conf, prefix='train'):
logformat = '%(asctime)s %(levelname)s %(message)s'
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')[2:]
logfile_path = str(
Path(LOGDIR.format(modelname=conf.modelname)) /
f'{prefix:s}_{timestamp:s}.log')
Path(logfile_path).parent.mkdir(parents=True, exist_ok=True)
handler = FileHandler(logfile_path)
handler.setFormatter(Formatter(logformat))
logger = getLogger('aa')
logger.addHandler(handler)
def set_logger():
logger = getLogger('aa')
logformat = '%(asctime)s %(levelname)s %(message)s'
handler_out = StreamHandler(sys.stdout)
handler_out.setLevel(INFO)
handler_out.setFormatter(Formatter(logformat))
logger.setLevel(INFO)
logger.addHandler(handler_out)
def get_csv_folds(path, d, use_all=False):
df = pd.read_csv(path, index_col=0)
if use_all:
train = [range(len(df))]
test = [[]]
else:
m = df.max()[0] + 1
train = [[] for i in range(m)]
test = [[] for i in range(m)]
folds = {}
for i in range(m):
fold_ids = list(df[df['fold'].isin([i])].index)
folds.update({i: [n for n, l in enumerate(d) if l in fold_ids]})
for k, v in folds.items():
for i in range(m):
if i != k:
train[i].extend(v)
test[k] = v
return list(zip(np.array(train), np.array(test)))
|
[
"logging.FileHandler",
"pandas.read_csv",
"logging.StreamHandler",
"os.uname",
"logging.Formatter",
"pathlib.Path",
"numpy.array",
"easydict.EasyDict",
"datetime.datetime.now",
"logging.getLogger"
] |
[((627, 644), 'easydict.EasyDict', 'edict', (['mod.CONFIG'], {}), '(mod.CONFIG)\n', (632, 644), True, 'from easydict import EasyDict as edict\n'), ((1018, 1043), 'logging.FileHandler', 'FileHandler', (['logfile_path'], {}), '(logfile_path)\n', (1029, 1043), False, 'from logging import FileHandler\n'), ((1105, 1120), 'logging.getLogger', 'getLogger', (['"""aa"""'], {}), "('aa')\n", (1114, 1120), False, 'from logging import getLogger, Formatter, StreamHandler, INFO, WARNING\n'), ((1185, 1200), 'logging.getLogger', 'getLogger', (['"""aa"""'], {}), "('aa')\n", (1194, 1200), False, 'from logging import getLogger, Formatter, StreamHandler, INFO, WARNING\n'), ((1276, 1301), 'logging.StreamHandler', 'StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (1289, 1301), False, 'from logging import getLogger, Formatter, StreamHandler, INFO, WARNING\n'), ((1500, 1530), 'pandas.read_csv', 'pd.read_csv', (['path'], {'index_col': '(0)'}), '(path, index_col=0)\n', (1511, 1530), True, 'import pandas as pd\n'), ((1069, 1089), 'logging.Formatter', 'Formatter', (['logformat'], {}), '(logformat)\n', (1078, 1089), False, 'from logging import getLogger, Formatter, StreamHandler, INFO, WARNING\n'), ((1362, 1382), 'logging.Formatter', 'Formatter', (['logformat'], {}), '(logformat)\n', (1371, 1382), False, 'from logging import getLogger, Formatter, StreamHandler, INFO, WARNING\n'), ((2077, 2092), 'numpy.array', 'np.array', (['train'], {}), '(train)\n', (2085, 2092), True, 'import numpy as np\n'), ((2094, 2108), 'numpy.array', 'np.array', (['test'], {}), '(test)\n', (2102, 2108), True, 'import numpy as np\n'), ((301, 311), 'os.uname', 'os.uname', ([], {}), '()\n', (309, 311), False, 'import os\n'), ((763, 786), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (784, 786), False, 'import datetime\n'), ((942, 960), 'pathlib.Path', 'Path', (['logfile_path'], {}), '(logfile_path)\n', (946, 960), False, 'from pathlib import Path\n')]
|
#!/usr/bin/python
#
# Copyright 2018-2022 Polyaxon, Inc.
#
# 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.
from typing import List, Union
from fsspec import AbstractFileSystem
from polyaxon.logger import logger
from polyaxon.utils.list_utils import to_list
from polyaxon.utils.path_utils import check_or_create_path
def download_file_or_dir(
fs: AbstractFileSystem,
path_from: str,
path_to: str,
is_file: bool,
check_path: bool,
):
if check_path:
is_file = fs.isfile(path_from)
check_or_create_path(path_to, is_dir=not is_file)
fs.download(rpath=path_from, lpath=path_to, recursive=not is_file)
def delete_file_or_dir(
fs: AbstractFileSystem,
subpath: Union[str, List[str]],
is_file: bool = False,
):
subpath = to_list(subpath, check_none=True)
for sp in subpath:
try:
fs.delete(path=sp, recursive=not is_file)
except Exception as e:
logger.info("Could not delete path %s\nError: %s", sp, e)
|
[
"polyaxon.utils.path_utils.check_or_create_path",
"polyaxon.logger.logger.info",
"polyaxon.utils.list_utils.to_list"
] |
[((1016, 1065), 'polyaxon.utils.path_utils.check_or_create_path', 'check_or_create_path', (['path_to'], {'is_dir': '(not is_file)'}), '(path_to, is_dir=not is_file)\n', (1036, 1065), False, 'from polyaxon.utils.path_utils import check_or_create_path\n'), ((1271, 1304), 'polyaxon.utils.list_utils.to_list', 'to_list', (['subpath'], {'check_none': '(True)'}), '(subpath, check_none=True)\n', (1278, 1304), False, 'from polyaxon.utils.list_utils import to_list\n'), ((1438, 1498), 'polyaxon.logger.logger.info', 'logger.info', (['"""Could not delete path %s\nError: %s"""', 'sp', 'e'], {}), '("""Could not delete path %s\nError: %s""", sp, e)\n', (1449, 1498), False, 'from polyaxon.logger import logger\n')]
|
"""Elasticsearch store plugin."""
import json
import logging
from elasticsearch import Elasticsearch, ElasticsearchException
_log = logging.getLogger(__name__)
class EsStore:
"""Elasticsearch adapter to index cloud data in Elasticsearch."""
def __init__(self, host='localhost', port=9200, index='cloudmarker',
buffer_size=5000000):
"""Create an instance of :class:`EsStore` plugin.
The plugin uses the default port for Elasticsearch if not
specified.
The ``buffer_size`` for the plugin is the value for the maximum
number of bytes of data to be sent in a bulk API request to
Elasticsearch.
Arguments:
host (str): Elasticsearch host
port (int): Elasticsearch port
index (str): Elasticsearch index
buffer_size (int): Maximum number of bytes of data to hold
in the in-memory buffer.
"""
self._es = Elasticsearch([{'host': host, 'port': port}])
self._index = index
self._buffer_size = buffer_size
self._buffer = ''
self._cur_buffer_size = 0
# TODO: Add method to create mapping for efficient indexing of data.
# TODO: Add method to prune old data.
# TODO: Add support for multiple indexes
def _doc_index_body(self, doc, doc_id=None):
"""Create the body for a bulk insert API call to Elasticsearch.
Arguments:
doc (dict): Document
doc_id: Document ID
Returns:
(str): Request body corresponding to the ``doc``.
"""
action_def = {
'index': {
'_index': self._index,
'_id': doc_id
}
}
src_def = doc
return json.dumps(action_def) + '\n' + json.dumps(src_def) + '\n'
def _flush(self):
"""Bulk insert buffered records into Elasticserach."""
try:
resp = self._es.bulk(self._buffer)
except ElasticsearchException as e:
# Handles exceptions of all types defined here.
# https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch/exceptions.py
_log.error('Bulk Index Error: %s: %s', type(e).__name__, e)
return
# Read and parse the response.
items = resp['items']
records_sent = len(items)
fail_count = 0
# If response code for an item is not 2xx, increment the count of
# failed insertions.
if resp['errors']:
for item in items:
if not 199 < item['index']['status'] < 300:
fail_count += 1
_log.debug('Failed to insert record; ID: %s',
item['index']['_id'])
_log.error('Failed to write %d records', fail_count)
_log.info('Indexed %d records', records_sent - fail_count)
# Reset the buffer.
self._cur_buffer_size = 0
self._buffer = ''
def write(self, record):
"""Write JSON records to the Elasticsearch index.
Flush the buffer by saving its content to Elasticsearch when
the buffer size exceeds the configured size.
Arguments:
record (dict): Data to save to Elasticsearch.
"""
es_record = self._doc_index_body(record) # TODO: Send valid doc ID
es_record_bytes = len(es_record)
if (self._cur_buffer_size and
es_record_bytes + self._cur_buffer_size > self._buffer_size):
self._flush()
else:
self._buffer += es_record
self._cur_buffer_size += es_record_bytes
def done(self):
"""Flush pending records to Elasticsearch."""
if self._cur_buffer_size:
self._flush()
|
[
"elasticsearch.Elasticsearch",
"logging.getLogger",
"json.dumps"
] |
[((136, 163), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (153, 163), False, 'import logging\n'), ((967, 1012), 'elasticsearch.Elasticsearch', 'Elasticsearch', (["[{'host': host, 'port': port}]"], {}), "([{'host': host, 'port': port}])\n", (980, 1012), False, 'from elasticsearch import Elasticsearch, ElasticsearchException\n'), ((1812, 1831), 'json.dumps', 'json.dumps', (['src_def'], {}), '(src_def)\n', (1822, 1831), False, 'import json\n'), ((1780, 1802), 'json.dumps', 'json.dumps', (['action_def'], {}), '(action_def)\n', (1790, 1802), False, 'import json\n')]
|
import pathlib
from setuptools import setup, find_packages
base_packages = [
"scikit-learn>=1.0.0",
"cleanlab>=1.0",
"pandas>=1.3.3",
]
docs_packages = [
"mkdocs==1.1",
"mkdocs-material==4.6.3",
"mkdocstrings==0.8.0",
"mktestdocs==0.1.2",
]
test_packages = [
"interrogate>=1.5.0",
"flake8>=3.6.0",
"pytest>=4.0.2",
"black>=19.3b0",
"pre-commit>=2.2.0",
"whatlies==0.6.4",
]
all_packages = base_packages
dev_packages = all_packages + docs_packages + test_packages
setup(
name="doubtlab",
version="0.1.2",
author="<NAME>",
packages=find_packages(exclude=["notebooks", "docs"]),
description="Don't Blindly Trust Your Labels",
long_description=pathlib.Path("README.md").read_text(),
long_description_content_type="text/markdown",
url="https://koaning.github.io/doubtlab/",
project_urls={
"Documentation": "https://koaning.github.io/doubtlab/",
"Source Code": "https://github.com/koaning/doubtlab/",
"Issue Tracker": "https://github.com/koaning/doubtlab/issues",
},
install_requires=base_packages,
extras_require={"dev": dev_packages},
license_files=("LICENSE",),
classifiers=[
"Intended Audience :: Science/Research",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"License :: OSI Approved :: MIT License",
"Topic :: Scientific/Engineering",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
)
|
[
"pathlib.Path",
"setuptools.find_packages"
] |
[((605, 649), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['notebooks', 'docs']"}), "(exclude=['notebooks', 'docs'])\n", (618, 649), False, 'from setuptools import setup, find_packages\n'), ((723, 748), 'pathlib.Path', 'pathlib.Path', (['"""README.md"""'], {}), "('README.md')\n", (735, 748), False, 'import pathlib\n')]
|
import yaml
from trial_dispatcher import TrialDispatcher as Dispatcher
EMAIL_DRYRUN = True
subscriptions = """\
---
trial_abc: "ABC National Trial"
trial_def: "DEF International Trial"
site_xxx: "XXX Regional Site"
site_yyy: "YYY City Site"
---
- name: "<NAME>"
affiliation: "site_xxx"
email: "<EMAIL>"
channels: ["trial_abc"]
- name: "<NAME>"
affiliation: "site_xxx"
email: "<EMAIL>"
channels: ["site_xxx"]
- name: "<NAME>"
affiliation: "site_yyy"
email: "<EMAIL>"
channels: ["trial_abc-site_yyy"]
- name: "<NAME>"
affiliation: "site_yyy"
email: "<EMAIL>"
channels: ["trial_def"]
...
"""
def test_dispatch(dispatcher):
item = {"meta": {
"signature": {
"trial": "trial_abc",
"site": "site_yyy"
},
},
"data": "AaaBbbCcc yyy etc etc"
}
sent = dispatcher.put(item, dryrun=EMAIL_DRYRUN)
print(sent)
assert( "<NAME>" in [ item['recipient']["name"] for item in sent] )
assert( "<NAME>" in [ item['recipient']["name"] for item in sent] )
item = {"meta": {
"signature": {
"trial": "trial_abc",
"site": "site_xxx"
},
},
"data": "AaaBbbCcc xxx etc etc"
}
sent = dispatcher.put(item, dryrun=EMAIL_DRYRUN)
assert( "<NAME>" in [ item['recipient']["name"] for item in sent] )
assert( "<NAME>" in [ item['recipient']["name"] for item in sent] )
item = {"meta": {
"signature": {
"trial": "trial_def",
"site": "site_xxx"
},
},
"data": "DddEeeFff xxx etc etc"
}
sent = dispatcher.put(item, dryrun=EMAIL_DRYRUN)
assert( "<NAME>" in [ item['recipient']["name"] for item in sent] )
assert( "<NAME>" in [ item['recipient']["name"] for item in sent] )
if __name__ == "__main__":
channel_tags, subscribers = yaml.safe_load_all(subscriptions)
dispatcher = Dispatcher(channel_tags=channel_tags)
dispatcher.add_subscribers(subscribers)
test_dispatch(dispatcher)
|
[
"trial_dispatcher.TrialDispatcher",
"yaml.safe_load_all"
] |
[((1884, 1917), 'yaml.safe_load_all', 'yaml.safe_load_all', (['subscriptions'], {}), '(subscriptions)\n', (1902, 1917), False, 'import yaml\n'), ((1935, 1972), 'trial_dispatcher.TrialDispatcher', 'Dispatcher', ([], {'channel_tags': 'channel_tags'}), '(channel_tags=channel_tags)\n', (1945, 1972), True, 'from trial_dispatcher import TrialDispatcher as Dispatcher\n')]
|
import asyncio
import json
import time
from collections import namedtuple
from quickspy.color import *
from quickspy.util import get_uuid
from quickspy import jsmsg
from qss.urlmanager import UrlManager
CONN_TIMEOUT = 60000
Temp = namedtuple('Temp', ['comefrom', 'msg'])
class NoAPIError(Exception):
def __init__(self, api):
self.api = api
super()
def repr(self):
return f'None API could parse this api:{self.api}'
class Client:
def __init__(self, name, addr):
self.name = name
self.addr = addr
self.temp = []
class Avarage:
def __init__(self, _range=5):
self._range = _range
self.histoty = []
def add(self):
self.histoty.append(time.time())
def refresh(self):
self.histoty = [each for each in self.histoty if each >= time.time() - self._range]
def speed(self):
now = time.time()
useful_time = 0
#print(f'history: {self.histoty}')
for each in self.histoty:
if each >= now - self._range:
useful_time += 1
else:
continue
#print(f'useful_time: {useful_time}')
self.refresh()
return useful_time/self._range
class NetEngine:
def __init__(self):
self.ava = Avarage(5)
def add(self):
self.ava.add()
def speed(self):
return self.ava.speed()
RegedNE = namedtuple('RegedNE', ['uuid', 'NE'])
RegedUP = namedtuple('RegedUP', ['uuid', 'UP'])
RegedM = namedtuple('RegedM', ['uuid', 'M'])
RegedL = namedtuple('RegedL', ['uuid', 'L'])
class NEMannager:
def __init__(self):
self.pool = {}
def reg(self, uuid):
if uuid not in self.pool:
temp = RegedNE(uuid, NetEngine())
self.pool[uuid] = temp
return temp.NE
else:
return self.pool[uuid].NE
class UPMannager:
def __init__(self):
self.pool = {}
def reg(self, uuid):
if uuid not in self.pool:
temp = RegedUP(uuid, UrlManager())
self.pool[uuid] = temp
return temp.UP
else:
return self.pool[uuid].UP
class QSS:
def __init__(self):
self.nemanager = NEMannager()
self.upmanager = UPMannager()
#self.mmannager = MMannager()
#self.lmanager = LMannager()
self.conns = {} #{addr:time,addr:time, ....}
self.clients = {} #{name: <class Client>}
#认证
async def run(self, reader, writer):
# data = await reader.read(100)
# message = data.decode()
# addr = writer.get_extra_info('peername')
# print(f"Received {message!r} from {addr!r}"
# print(f"Send: {message!r}")
# writer.write(data)
# await writer.drain()
# print("Close the connection")
# writer.close()
#get peer info
this_client = None
this_addr = writer.get_extra_info('peername')
#添加时间
self.conns[this_addr] = time.time()
print(f'Get a new connection from addr : {this_addr}')
#发送欢迎消息
# writer.write('Welcome to use QuickSpy!'.encode())
# await writer.drain()
while True:
#timeout
if int(time.time() - self.conns[this_addr]) >= CONN_TIMEOUT:
del self.conns[this_addr]
if this_client:
del self.clients[this_client.name]
writer.write('Connections timeout!'.encode())
await writer.drain()
break
#接收命令
recived = await reader.read(2048)
print(RED(f'Reciving data: {recived}'))
#解析命令
decoded = recived.decode(errors='ignore').strip()
print(RED(f'Decoded data: {decoded}'))
#参数分离
if decoded.find(' '):
command = decoded.split(' ')[0]
if (decoded.find('\"') == -1):
args = decoded.split(' ')[1:]
else:
first = decoded.find('\"')
last = decoded.rfind('\"')
lstring = decoded[decoded.find(' ') + 1: first - 1]
rstring = decoded[first + 1: last]
if lstring.find(' ') != -1:
args = lstring.split(' ')
args.append(rstring)
else:
args = [lstring, rstring]
else:
command, args = decoded, []
print(BLUE(f'Command: {command}\nargs: {args}'))
#@@@@解释命令返回行为@@@@#
#@@@@每个命令解释都要添加异常处理??
# 欢迎
if command == 'Hello,QuickSpy!' and this_client:
writer.write('Hello, my master! Welcome to QuickSpy.'.encode())
# 认证? recv register [name]
elif command == 'register':
try:
user = args[0]
except:
user = None
if not user:
user = get_uuid()
#test
this_client = Client(user, this_addr)
self.clients[user] = this_client
writer.write('Register successifully!'.encode())
# if not user in self.clients:
# this_client = Client(user, this_addr)
# self.clients[user] = this_client
# writer.write('Register successifully!'.encode())
# else:
# writer.write(f'Name \'{user}\' has already been registered!'.encode())
elif command == 'reg':
pass
elif command == 'eval':
try:
result = eval(args[0])
writer.write(str(result).encode())
except Exception as e:
writer.write(''.encode())
print(RED(f'at qss eval: {str(e)}'.encode()))
elif command == 'exec':
try:
result = exec(args[0])
writer.write(result.encode())
except Exception as e:
writer.write(str(e).encode())
# 转发send name msg
elif command == 'send' and this_client:
if len(args) == 2:
self.clients[args[0]].temp.append(jsmsg(this_client.name, args[0], args[1]))
writer.write(jsmsg('QSS', this_client.name, 'Send successfully!').encode())
else:
writer.write('Wrong command!'.encode())
elif command == 'whoami' and this_client:
writer.write(f'Name: {this_client.name}\nAddr: {this_client.addr}\nTemp: {this_client.temp}'.encode())
#heartbeat >> return ['', '', '']
elif command == 'heartbeat' and this_client:
msgs = []
for msg in self.clients[this_client.name].temp:
msgs.append(msg)
writer.write(json.dumps(msgs).encode())
self.clients[this_client.name].temp = []
self.conns[this_client.addr] = time.time()
#show
elif command == 'show' and this_client:
#展示链接tcp
if args[0] == 'conns':
for addr, _time in self.conns.items():
writer.write(f'Addr:{addr}, Time{int(_time)}'.encode())
#clear [conns|clients]
elif command == 'clear':
_this_client = this_client
if args == []:
args[0] = 'conns|clients'
if args[0] == 'conns':
self.conns = {_this_client.addr: time.time()}
if args[0] == 'clients':
self.clients = {_this_client.name: _this_client}
if args[0] == 'conns|clients' or args[0] == 'client|conns':
self.conns = {_this_client.addr: time.time()}
self.clients = {_this_client.name: _this_client}
writer.write('Clear succesifully!'.encode())
#get name
elif command == 'get':
for msg in self.clients[args[0]].temp:
writer.write(msg.encode())
self.clients[args[0]].temp = []
#close conn
elif command == 'close' and this_client:
del self.clients[this_client.name]
del self.conns[this_client.addr]
writer.write('Close connection'.encode())
await writer.drain()
break
#展示clients
elif command == 'status' and this_client:
_msg = ''
for name, client in self.clients.items():
_msg += f'Client({name}) >> Addr: {client.addr} , Temp:{client.temp}\n'
writer.write(_msg.strip().encode())
# 保险
else:
writer.write('No command find!'.encode())
#刷新缓冲
await writer.drain()
async def main():
qss = QSS()
server = await asyncio.start_server(qss.run, '127.0.0.1', 2546)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
await server.serve_forever()
server.close()
asyncio.run(main())
|
[
"asyncio.start_server",
"quickspy.util.get_uuid",
"quickspy.jsmsg",
"json.dumps",
"time.time",
"collections.namedtuple",
"qss.urlmanager.UrlManager"
] |
[((235, 274), 'collections.namedtuple', 'namedtuple', (['"""Temp"""', "['comefrom', 'msg']"], {}), "('Temp', ['comefrom', 'msg'])\n", (245, 274), False, 'from collections import namedtuple\n'), ((1418, 1455), 'collections.namedtuple', 'namedtuple', (['"""RegedNE"""', "['uuid', 'NE']"], {}), "('RegedNE', ['uuid', 'NE'])\n", (1428, 1455), False, 'from collections import namedtuple\n'), ((1466, 1503), 'collections.namedtuple', 'namedtuple', (['"""RegedUP"""', "['uuid', 'UP']"], {}), "('RegedUP', ['uuid', 'UP'])\n", (1476, 1503), False, 'from collections import namedtuple\n'), ((1513, 1548), 'collections.namedtuple', 'namedtuple', (['"""RegedM"""', "['uuid', 'M']"], {}), "('RegedM', ['uuid', 'M'])\n", (1523, 1548), False, 'from collections import namedtuple\n'), ((1558, 1593), 'collections.namedtuple', 'namedtuple', (['"""RegedL"""', "['uuid', 'L']"], {}), "('RegedL', ['uuid', 'L'])\n", (1568, 1593), False, 'from collections import namedtuple\n'), ((899, 910), 'time.time', 'time.time', ([], {}), '()\n', (908, 910), False, 'import time\n'), ((3008, 3019), 'time.time', 'time.time', ([], {}), '()\n', (3017, 3019), False, 'import time\n'), ((9158, 9206), 'asyncio.start_server', 'asyncio.start_server', (['qss.run', '"""127.0.0.1"""', '(2546)'], {}), "(qss.run, '127.0.0.1', 2546)\n", (9178, 9206), False, 'import asyncio\n'), ((734, 745), 'time.time', 'time.time', ([], {}), '()\n', (743, 745), False, 'import time\n'), ((2039, 2051), 'qss.urlmanager.UrlManager', 'UrlManager', ([], {}), '()\n', (2049, 2051), False, 'from qss.urlmanager import UrlManager\n'), ((836, 847), 'time.time', 'time.time', ([], {}), '()\n', (845, 847), False, 'import time\n'), ((3254, 3265), 'time.time', 'time.time', ([], {}), '()\n', (3263, 3265), False, 'import time\n'), ((5063, 5073), 'quickspy.util.get_uuid', 'get_uuid', ([], {}), '()\n', (5071, 5073), False, 'from quickspy.util import get_uuid\n'), ((6392, 6433), 'quickspy.jsmsg', 'jsmsg', (['this_client.name', 'args[0]', 'args[1]'], {}), '(this_client.name, args[0], args[1])\n', (6397, 6433), False, 'from quickspy import jsmsg\n'), ((7178, 7189), 'time.time', 'time.time', ([], {}), '()\n', (7187, 7189), False, 'import time\n'), ((6468, 6520), 'quickspy.jsmsg', 'jsmsg', (['"""QSS"""', 'this_client.name', '"""Send successfully!"""'], {}), "('QSS', this_client.name, 'Send successfully!')\n", (6473, 6520), False, 'from quickspy import jsmsg\n'), ((7047, 7063), 'json.dumps', 'json.dumps', (['msgs'], {}), '(msgs)\n', (7057, 7063), False, 'import json\n'), ((7749, 7760), 'time.time', 'time.time', ([], {}), '()\n', (7758, 7760), False, 'import time\n'), ((8001, 8012), 'time.time', 'time.time', ([], {}), '()\n', (8010, 8012), False, 'import time\n')]
|
from django.shortcuts import redirect, render
def homepage(request):
return render(request, 'study/home.html')
|
[
"django.shortcuts.render"
] |
[((81, 115), 'django.shortcuts.render', 'render', (['request', '"""study/home.html"""'], {}), "(request, 'study/home.html')\n", (87, 115), False, 'from django.shortcuts import redirect, render\n')]
|
import sys
import pele_platform.Errors.custom_errors as ce
def check_limit_number_atoms(sdf:str, limit_atoms: int):
from rdkit import Chem
""" Function to check input file does not excit
certin number of atoms """
mols = Chem.SDMolSupplier(sdf)
for mol in mols:
atoms = mol.GetAtoms()
natoms = len([atom for atom in atoms])
if natoms > limit_atoms:
name_ligand = mol.GetProp("_Name")
raise ce.LigandSizeExceed(f"Ligand {name_ligand} in {sdf} exceeds size {limit_atoms}")
def chec_substructure_match(ligand, ligand_core, core_atoms):
import rdkit.Chem.rdMolAlign as rd
from rdkit import Chem
#Initialize ring information
Chem.GetSSSR(ligand); Chem.GetSSSR(ligand_core)
#Align and obtain vocabulary between atoms in core and ligand
align_obj = rd.GetO3A(ligand, ligand_core)
atom_map = align_obj.Matches()
vocabulary = { i2:i1 for i1, i2 in atom_map }
#Check the substructure search and change indexes if dont agree with alignment
for idx_atom_ligand, idx_atom_core in enumerate(core_atoms):
if idx_atom_ligand not in vocabulary: #If it's a removed hydrogen pass
continue
if vocabulary[idx_atom_ligand] == idx_atom_core: #If indexes are correct pass
continue
else: #If indexes are incorrect swap indexes
core_atoms = list(core_atoms)
core_atoms[idx_atom_ligand] = vocabulary[idx_atom_ligand]
return core_atoms
|
[
"rdkit.Chem.SDMolSupplier",
"pele_platform.Errors.custom_errors.LigandSizeExceed",
"rdkit.Chem.GetSSSR",
"rdkit.Chem.rdMolAlign.GetO3A"
] |
[((238, 261), 'rdkit.Chem.SDMolSupplier', 'Chem.SDMolSupplier', (['sdf'], {}), '(sdf)\n', (256, 261), False, 'from rdkit import Chem\n'), ((707, 727), 'rdkit.Chem.GetSSSR', 'Chem.GetSSSR', (['ligand'], {}), '(ligand)\n', (719, 727), False, 'from rdkit import Chem\n'), ((729, 754), 'rdkit.Chem.GetSSSR', 'Chem.GetSSSR', (['ligand_core'], {}), '(ligand_core)\n', (741, 754), False, 'from rdkit import Chem\n'), ((839, 869), 'rdkit.Chem.rdMolAlign.GetO3A', 'rd.GetO3A', (['ligand', 'ligand_core'], {}), '(ligand, ligand_core)\n', (848, 869), True, 'import rdkit.Chem.rdMolAlign as rd\n'), ((453, 538), 'pele_platform.Errors.custom_errors.LigandSizeExceed', 'ce.LigandSizeExceed', (['f"""Ligand {name_ligand} in {sdf} exceeds size {limit_atoms}"""'], {}), "(f'Ligand {name_ligand} in {sdf} exceeds size {limit_atoms}'\n )\n", (472, 538), True, 'import pele_platform.Errors.custom_errors as ce\n')]
|
import os
import sys
from bead.exceptions import InvalidArchive
from bead.workspace import Workspace
from bead import spec as bead_spec
from bead.archive import Archive
from bead import box as bead_box
from bead.tech.fs import Path
from bead.tech.timestamp import time_from_user, parse_iso8601
from . import arg_help
from . import arg_metavar
from .environment import Environment
TIME_LATEST = parse_iso8601('9999-12-31')
ERROR_EXIT = 1
def die(msg):
sys.stderr.write('ERROR: ')
sys.stderr.write(msg)
sys.stderr.write('\n')
sys.exit(ERROR_EXIT)
def warning(msg):
sys.stderr.write('WARNING: ')
sys.stderr.write(msg)
sys.stderr.write('\n')
def OPTIONAL_WORKSPACE(parser):
'''
Define `workspace` as option, defaulting to current directory
'''
parser.arg(
'--workspace', '-w', metavar=arg_metavar.WORKSPACE,
type=Workspace, default=Workspace.for_current_working_directory(),
help=arg_help.WORKSPACE)
def assert_valid_workspace(workspace):
if not workspace.is_valid:
die(f'{workspace.directory} is not a valid workspace')
class get_env:
'''
Make an Environment when called.
It will also create a missing config directory and provides a meaningful
text when used as default for an argparse argument.
'''
def __init__(self, config_dir):
self.config_dir = Path(config_dir)
def __call__(self):
config_dir = self.config_dir
try:
os.makedirs(config_dir)
except OSError:
if not os.path.isdir(config_dir):
raise
return Environment.from_dir(config_dir)
def __repr__(self):
return f'Environment at {self.config_dir}'
def OPTIONAL_ENV(parser):
'''
Define `env` as option, defaulting to environment config in user's home directory
'''
config_dir = parser.defaults['config_dir']
parser.arg(
'--env', '--environment', metavar=arg_metavar.ENV,
dest='get_env',
type=get_env, default=get_env(config_dir),
help=arg_help.ENV)
class DefaultArgSentinel:
'''
I am a sentinel for default values.
I.e. If you see me, it means that you got the default value.
I also provide human sensible description for the default value.
'''
def __init__(self, description):
self.description = description
def __repr__(self):
return self.description
def BEAD_TIME(parser):
parser.arg('-t', '--time', dest='bead_time', type=time_from_user, default=TIME_LATEST)
def BEAD_OFFSET(parser):
parser.arg('-N', '--next', dest='bead_offset', action='store_const', const=1, default=0)
parser.arg('-P', '--prev', '--previous', dest='bead_offset', action='store_const', const=-1)
def arg_bead_ref_base(nargs, default):
'''
Declare bead_ref_base argument - either a name or a file or something special
'''
def declare(parser):
parser.arg(
'bead_ref_base', metavar=arg_metavar.BEAD_REF, help=arg_help.BEAD_REF,
nargs=nargs, type=str, default=default)
return declare
def BEAD_REF_BASE_defaulting_to(name):
return arg_bead_ref_base(nargs='?', default=name)
BEAD_REF_BASE = arg_bead_ref_base(nargs=None, default=None)
def resolve_bead(env, bead_ref_base, time):
# prefer exact file name over box search
if os.path.isfile(bead_ref_base):
return Archive(bead_ref_base)
# not a file - try box search
unionbox = bead_box.UnionBox(env.get_boxes())
return unionbox.get_at(bead_spec.BEAD_NAME, bead_ref_base, time)
def verify_with_feedback(archive: Archive):
print(f'Verifying archive {archive.archive_filename} ...', end='', flush=True)
try:
archive.validate()
print(' OK', flush=True)
except InvalidArchive:
print(' DAMAGED!', flush=True)
raise
|
[
"os.makedirs",
"bead.workspace.Workspace.for_current_working_directory",
"os.path.isdir",
"bead.tech.timestamp.parse_iso8601",
"bead.archive.Archive",
"os.path.isfile",
"bead.tech.fs.Path",
"sys.stderr.write",
"sys.exit"
] |
[((397, 424), 'bead.tech.timestamp.parse_iso8601', 'parse_iso8601', (['"""9999-12-31"""'], {}), "('9999-12-31')\n", (410, 424), False, 'from bead.tech.timestamp import time_from_user, parse_iso8601\n'), ((461, 488), 'sys.stderr.write', 'sys.stderr.write', (['"""ERROR: """'], {}), "('ERROR: ')\n", (477, 488), False, 'import sys\n'), ((493, 514), 'sys.stderr.write', 'sys.stderr.write', (['msg'], {}), '(msg)\n', (509, 514), False, 'import sys\n'), ((519, 541), 'sys.stderr.write', 'sys.stderr.write', (['"""\n"""'], {}), "('\\n')\n", (535, 541), False, 'import sys\n'), ((546, 566), 'sys.exit', 'sys.exit', (['ERROR_EXIT'], {}), '(ERROR_EXIT)\n', (554, 566), False, 'import sys\n'), ((591, 620), 'sys.stderr.write', 'sys.stderr.write', (['"""WARNING: """'], {}), "('WARNING: ')\n", (607, 620), False, 'import sys\n'), ((625, 646), 'sys.stderr.write', 'sys.stderr.write', (['msg'], {}), '(msg)\n', (641, 646), False, 'import sys\n'), ((651, 673), 'sys.stderr.write', 'sys.stderr.write', (['"""\n"""'], {}), "('\\n')\n", (667, 673), False, 'import sys\n'), ((3354, 3383), 'os.path.isfile', 'os.path.isfile', (['bead_ref_base'], {}), '(bead_ref_base)\n', (3368, 3383), False, 'import os\n'), ((1376, 1392), 'bead.tech.fs.Path', 'Path', (['config_dir'], {}), '(config_dir)\n', (1380, 1392), False, 'from bead.tech.fs import Path\n'), ((3400, 3422), 'bead.archive.Archive', 'Archive', (['bead_ref_base'], {}), '(bead_ref_base)\n', (3407, 3422), False, 'from bead.archive import Archive\n'), ((898, 939), 'bead.workspace.Workspace.for_current_working_directory', 'Workspace.for_current_working_directory', ([], {}), '()\n', (937, 939), False, 'from bead.workspace import Workspace\n'), ((1480, 1503), 'os.makedirs', 'os.makedirs', (['config_dir'], {}), '(config_dir)\n', (1491, 1503), False, 'import os\n'), ((1547, 1572), 'os.path.isdir', 'os.path.isdir', (['config_dir'], {}), '(config_dir)\n', (1560, 1572), False, 'import os\n')]
|
from fuzzconfig import FuzzConfig
import nonrouting
import pytrellis
import fuzzloops
import interconnect
cfg = FuzzConfig(job="USRMCLK", family="ECP5", device="LFE5U-45F", ncl="empty.ncl",
tiles=["MIB_R71C4:EFB0_PICB0", "MIB_R71C5:EFB1_PICB1", "MIB_R71C6:EFB2_PICB0",
"MIB_R71C7:EFB3_PICB1", "MIB_R71C3:BANKREF8"])
def get_substs(config):
return dict(sysconfig=(" ".join(["{}={}".format(k, v) for k, v in config.items()])))
def main():
pytrellis.load_database("../../../database")
cfg.setup()
empty_bitfile = cfg.build_design(cfg.ncl, {})
nonrouting.fuzz_enum_setting(cfg, "SYSCONFIG.BACKGROUND_RECONFIG", ["OFF", "ON"],
lambda x: get_substs(dict(BACKGROUND_RECONFIG=x)), empty_bitfile, False)
nonrouting.fuzz_enum_setting(cfg, "SYSCONFIG.TRANSFR", ["OFF", "ON"],
lambda x: get_substs(dict(TRANSFR=x)), empty_bitfile, False)
nonrouting.fuzz_enum_setting(cfg, "SYSCONFIG.DONE_EX", ["OFF", "ON"],
lambda x: get_substs(dict(DONE_EX=x)), empty_bitfile, False)
nonrouting.fuzz_enum_setting(cfg, "SYSCONFIG.DONE_OD", ["OFF", "ON"],
lambda x: get_substs(dict(DONE_OD=x)), empty_bitfile, False)
nonrouting.fuzz_enum_setting(cfg, "SYSCONFIG.DONE_PULL", ["OFF", "ON"],
lambda x: get_substs(dict(DONE_PULL=x)), empty_bitfile, False)
nonrouting.fuzz_enum_setting(cfg, "SYSCONFIG.SLAVE_SPI_PORT", ["DISABLE", "ENABLE"],
lambda x: get_substs(dict(SLAVE_SPI_PORT=x)), empty_bitfile, False)
nonrouting.fuzz_enum_setting(cfg, "SYSCONFIG.MASTER_SPI_PORT", ["DISABLE", "ENABLE"],
lambda x: get_substs(dict(MASTER_SPI_PORT=x)), empty_bitfile, False)
nonrouting.fuzz_enum_setting(cfg, "SYSCONFIG.SLAVE_PARALLEL_PORT", ["DISABLE", "ENABLE"],
lambda x: get_substs(dict(SLAVE_PARALLEL_PORT=x)), empty_bitfile, False)
nonrouting.fuzz_enum_setting(cfg, "SYSCONFIG.CONFIG_IOVOLTAGE", ["1.2", "1.5", "1.8", "2.5", "3.3"],
lambda x: get_substs(dict(CONFIG_IOVOLTAGE=x, SLAVE_SPI_PORT="ENABLE")), empty_bitfile,
False)
nonrouting.fuzz_enum_setting(cfg, "SYSCONFIG.WAKE_UP", ["4", "21"],
lambda x: get_substs(dict(WAKE_UP=x)), empty_bitfile, False)
if __name__ == "__main__":
main()
|
[
"pytrellis.load_database",
"fuzzconfig.FuzzConfig"
] |
[((113, 325), 'fuzzconfig.FuzzConfig', 'FuzzConfig', ([], {'job': '"""USRMCLK"""', 'family': '"""ECP5"""', 'device': '"""LFE5U-45F"""', 'ncl': '"""empty.ncl"""', 'tiles': "['MIB_R71C4:EFB0_PICB0', 'MIB_R71C5:EFB1_PICB1', 'MIB_R71C6:EFB2_PICB0',\n 'MIB_R71C7:EFB3_PICB1', 'MIB_R71C3:BANKREF8']"}), "(job='USRMCLK', family='ECP5', device='LFE5U-45F', ncl=\n 'empty.ncl', tiles=['MIB_R71C4:EFB0_PICB0', 'MIB_R71C5:EFB1_PICB1',\n 'MIB_R71C6:EFB2_PICB0', 'MIB_R71C7:EFB3_PICB1', 'MIB_R71C3:BANKREF8'])\n", (123, 325), False, 'from fuzzconfig import FuzzConfig\n'), ((491, 535), 'pytrellis.load_database', 'pytrellis.load_database', (['"""../../../database"""'], {}), "('../../../database')\n", (514, 535), False, 'import pytrellis\n')]
|
import matplotlib.pyplot as plt
import math
import re
import sys
import glob
import os
import os.path
import numpy as np
import matplotlib.colors as mcolors
molecules = open('type_1_gephi.csv','r')
lines = molecules.readlines()
counter = 0
#print('lines'+str(lines))
with open('imagen.csv', 'a') as the_file:
the_file.write("Id,image"+'\n')
for line in lines[1:]:
counter +=1
line=line.rstrip('\n')
line=line.split('\t')
if line[1]!="2":
print(line[0])
code = "obabel -:"+"'"+line[0]+"'"+" -xb none -O "+"'"+line[0]+'.svg'+"'"
print(code)
os.system(code)
the_file.write(line[0]+","+line[0]+'.svg'+'\n')
|
[
"os.system"
] |
[((565, 580), 'os.system', 'os.system', (['code'], {}), '(code)\n', (574, 580), False, 'import os\n')]
|
from keystonev3.common import send
from keystonev3.arg_converter import get_by_name_or_uuid_multiple
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
@get_by_name_or_uuid_multiple([('user', 'user_id')])
@send('get')
def user_get_details(user_id, **kwargs):
url = '/users/{}?{}'.format(user_id, urlencode(kwargs))
return url, None
@get_by_name_or_uuid_multiple([('user', 'user_id')])
@send('patch')
def user_update(user_id, **kwargs):
url = '/users/{}'.format(user_id)
json = {
'user': kwargs,
}
return url, json
@get_by_name_or_uuid_multiple([('user', 'user_id')])
@send('delete')
def user_delete(user_id, **kwargs):
url = '/users/{}'.format(user_id)
return url, None
@send('post')
def user_create(**kwargs):
url = '/users'
json = {
'user': kwargs,
}
return url, json
|
[
"keystonev3.common.send",
"urllib.urlencode",
"keystonev3.arg_converter.get_by_name_or_uuid_multiple"
] |
[((201, 252), 'keystonev3.arg_converter.get_by_name_or_uuid_multiple', 'get_by_name_or_uuid_multiple', (["[('user', 'user_id')]"], {}), "([('user', 'user_id')])\n", (229, 252), False, 'from keystonev3.arg_converter import get_by_name_or_uuid_multiple\n'), ((254, 265), 'keystonev3.common.send', 'send', (['"""get"""'], {}), "('get')\n", (258, 265), False, 'from keystonev3.common import send\n'), ((391, 442), 'keystonev3.arg_converter.get_by_name_or_uuid_multiple', 'get_by_name_or_uuid_multiple', (["[('user', 'user_id')]"], {}), "([('user', 'user_id')])\n", (419, 442), False, 'from keystonev3.arg_converter import get_by_name_or_uuid_multiple\n'), ((444, 457), 'keystonev3.common.send', 'send', (['"""patch"""'], {}), "('patch')\n", (448, 457), False, 'from keystonev3.common import send\n'), ((599, 650), 'keystonev3.arg_converter.get_by_name_or_uuid_multiple', 'get_by_name_or_uuid_multiple', (["[('user', 'user_id')]"], {}), "([('user', 'user_id')])\n", (627, 650), False, 'from keystonev3.arg_converter import get_by_name_or_uuid_multiple\n'), ((652, 666), 'keystonev3.common.send', 'send', (['"""delete"""'], {}), "('delete')\n", (656, 666), False, 'from keystonev3.common import send\n'), ((765, 777), 'keystonev3.common.send', 'send', (['"""post"""'], {}), "('post')\n", (769, 777), False, 'from keystonev3.common import send\n'), ((348, 365), 'urllib.urlencode', 'urlencode', (['kwargs'], {}), '(kwargs)\n', (357, 365), False, 'from urllib import urlencode\n')]
|
import os
DEBUG = True
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
#not used right now.
CSRF_ENABLED = True
#Same here for session cookies.
SECRET_KEY = os.getenv("SECRET_KEY")
SESSION_TYPE="filesystem"
SECRET=os.getenv("SECRET")
MONGO_URI="mongodb+srv://{0}:{1}@mlh-summer-hacks-dqi2z.gcp.mongodb.net/geo_ip_data?retryWrites=true&w=majority".format(os.getenv('mdb_user'),os.getenv('mdb_pass'))
|
[
"os.path.dirname",
"os.getenv"
] |
[((166, 189), 'os.getenv', 'os.getenv', (['"""SECRET_KEY"""'], {}), "('SECRET_KEY')\n", (175, 189), False, 'import os\n'), ((223, 242), 'os.getenv', 'os.getenv', (['"""SECRET"""'], {}), "('SECRET')\n", (232, 242), False, 'import os\n'), ((50, 75), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (65, 75), False, 'import os\n'), ((363, 384), 'os.getenv', 'os.getenv', (['"""mdb_user"""'], {}), "('mdb_user')\n", (372, 384), False, 'import os\n'), ((385, 406), 'os.getenv', 'os.getenv', (['"""mdb_pass"""'], {}), "('mdb_pass')\n", (394, 406), False, 'import os\n')]
|
# -*- coding: utf-8 -*-
from pythonosc import udp_client
from gpiozero import CPUTemperature
import time
# Network config of the companion instance that should display the CPU Temp
targetIP = "127.0.0.1"
targetPort = 12321
targetPage = 99 # page in companion that will display the CPU Temp
targetButton = 21 # button in companion that will display the CPU Temp
tempWarning = 60 # threshold for warning background color
tempAlert = 75 # threshold for Alert background color
bgWarning = [255, 100, 0] #color for warning
bgAlert = [255, 0, 0] #color for alert
bgNormal = [0, 0, 0] #color for normal operation
########################################
#
# No changes needed beyond this Point
#
########################################
#create client
companion = udp_client.SimpleUDPClient(targetIP, targetPort)
OSCaddressText = '/style/text/'+str(targetPage)+'/'+str(targetButton)
OSCaddressBG = '/style/bgcolor/'+str(targetPage)+'/'+str(targetButton)
while True:
#get CPU temp
cpuTemp = CPUTemperature().temperature
if (cpuTemp > tempAlert):
companion.send_message(OSCaddressBG, bgAlert)
elif (cpuTemp > tempWarning):
companion.send_message(OSCaddressBG, bgWarning)
else:
companion.send_message(OSCaddressBG, bgNormal)
ButtonText = "CPU Temp "+str(cpuTemp)[:-1] + " °C"
companion.send_message(OSCaddressText, ButtonText)
time.sleep(1) #sleep for one second
|
[
"pythonosc.udp_client.SimpleUDPClient",
"gpiozero.CPUTemperature",
"time.sleep"
] |
[((797, 845), 'pythonosc.udp_client.SimpleUDPClient', 'udp_client.SimpleUDPClient', (['targetIP', 'targetPort'], {}), '(targetIP, targetPort)\n', (823, 845), False, 'from pythonosc import udp_client\n'), ((1433, 1446), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1443, 1446), False, 'import time\n'), ((1038, 1054), 'gpiozero.CPUTemperature', 'CPUTemperature', ([], {}), '()\n', (1052, 1054), False, 'from gpiozero import CPUTemperature\n')]
|
"""
clean.py
author(s): khuynh
description: this is a helper script to clean a set of facebook messages.
it outputs the facebook messages into a single .txt file with each message
on its own line
link to download your facebook messages:
https://www.facebook.com/dyi/?referrer=yfi_settings
"""
import json
import string
from pathlib import Path
DIRECTORY_MESSAGES = Path("messages/inbox").resolve()
PERSON_NAME = "<NAME>"
messages = []
printable = set(string.printable)
for directory in DIRECTORY_MESSAGES.iterdir():
if PERSON_NAME.split(" ")[0].lower() in str(directory):
directory_person = DIRECTORY_MESSAGES / directory
for f in directory_person.iterdir():
if f.suffix == ".json":
with f.open("r") as message_json:
conversation = json.load(message_json)
conversation = [
"".join(
filter(lambda x: x in printable, message.get("content", ""))
)
for message in conversation["messages"]
if message["sender_name"] == PERSON_NAME
]
messages += conversation
with open(f"{PERSON_NAME.split(' ')[0].lower()}.txt", "w", encoding="utf-8") as to_file:
for message in messages:
to_file.write(message)
to_file.write("\n")
|
[
"pathlib.Path",
"json.load"
] |
[((367, 389), 'pathlib.Path', 'Path', (['"""messages/inbox"""'], {}), "('messages/inbox')\n", (371, 389), False, 'from pathlib import Path\n'), ((805, 828), 'json.load', 'json.load', (['message_json'], {}), '(message_json)\n', (814, 828), False, 'import json\n')]
|
import os
import glob
import logging
from conans import ConanFile, tools, Meson
_meson_feature = ["disabled", "enabled", "auto"]
_features = []
class GStPluginsBadConan(ConanFile):
python_requires = "aac-sdk-tools/1.0"
python_requires_extend = "aac-sdk-tools.BaseSdkDependency"
name = "gst-plugins-bad"
version = "1.18.4"
description = "GStreamer is a development framework for creating applications like media players, video editors, " \
"streaming media broadcasters and so on"
topics = ("conan", "gstreamer", "multimedia", "video", "audio", "broadcasting", "framework", "media")
homepage = "https://gstreamer.freedesktop.org/"
license = "GPL-2.0-only"
exports = ["LICENSE.md"]
settings = "os", "arch", "compiler", "build_type"
options = dict({"shared": [True, False], "fPIC": [ True, False]}, **{f: _meson_feature for f in _features})
default_options = dict({"shared": False, "fPIC": True}, **{f: "auto" for f in _features})
exports_sources = ["patches/*.patch"]
requires = ["openssl/1.1.1i", "libxml2/2.9.10"]
build_requires = ["meson/0.56.2", "bison/3.7.1", "flex/2.6.4", "pkgconf/1.7.3"]
generators = "pkg_config"
_source_subfolder = "source_subfolder"
_build_subfolder = "build_subfolder"
def configure(self):
del self.settings.compiler.libcxx
del self.settings.compiler.cppstd
self.options['gstreamer'].shared = self.options.shared
def config_options(self):
if self.settings.os == 'Windows':
del self.options.fPIC
def requirements(self):
self.requires(f"gst-plugins-base/{self.version}@{self.user}/{self.channel}")
self.requires(f"faad2/2.10.0@{self.user}/{self.channel}")
def source(self):
tools.get(**self.conan_data["sources"][self.version])
os.rename(f"{self.name}-{self.version}", self._source_subfolder)
def _apply_patches(self):
for filename in sorted(glob.glob("patches/*.patch")):
logging.info(f"applying patch: {filename}")
tools.patch(base_path=self._source_subfolder, patch_file=filename)
def _configure_meson(self):
defs = dict()
def add_flag(name, value):
if name in defs:
defs[name] += " " + value
else:
defs[name] = value
def add_compiler_flag(value):
add_flag("c_args", value)
add_flag("cpp_args", value)
def add_linker_flag(value):
add_flag("c_link_args", value)
add_flag("cpp_link_args", value)
meson = Meson(self)
if self.settings.compiler == "Visual Studio":
add_linker_flag("-lws2_32")
add_compiler_flag(f"-{self.settings.compiler.runtime}")
if int(str(self.settings.compiler.version)) < 14:
add_compiler_flag("-Dsnprintf=_snprintf")
if self.settings.get_safe("compiler.runtime"):
defs["b_vscrt"] = str(self.settings.compiler.runtime).lower()
for x in ["tools", "examples", "benchmarks", "tests"]:
defs[x] = "disabled"
for x in _features:
defs[x] = self.options.get_safe(x)
# Disable options that cause build issues on non-Linux systems
if self.settings.os != 'Linux' or (hasattr(self, 'settings_build') and tools.cross_building(self, skip_x64_x86=True)):
meson.options["introspection"] = "disabled"
meson.options["orc"] = "disabled"
# Disable unused plugins
for plugin in ["closedcaption", "rsvg", "ttml"]:
meson.options[plugin] = "disabled"
# Enable hls explicitly for HTTP streaming
meson.options["hls"] = "enabled"
meson.options["hls-crypto"] = "openssl"
# Somehow Meson ignore PKG_CONFIG_PATH env. Force setting it with option.
meson.options["pkg_config_path"] = os.getenv('PKG_CONFIG_PATH')
meson.configure(build_folder=self._build_subfolder, source_folder=self._source_subfolder, defs=defs)
return meson
def build(self):
self._apply_patches()
with tools.environment_append({"PKG_CONFIG_PATH": [os.getcwd()]}):
meson = self._configure_meson()
meson.build()
def package(self):
meson = self._configure_meson()
meson.install()
def package_info(self):
gst_plugin_path = os.path.join(self.package_folder, "lib", "gstreamer-1.0")
if self.options.shared:
logging.info(f"Appending GST_PLUGIN_PATH env var: {gst_plugin_path}")
self.env_info.GST_PLUGIN_PATH.append(gst_plugin_path)
else:
self.cpp_info.libdirs.append(gst_plugin_path)
self.cpp_info.libs = tools.collect_libs(self)
|
[
"conans.tools.get",
"conans.Meson",
"os.getcwd",
"os.rename",
"conans.tools.patch",
"logging.info",
"glob.glob",
"os.path.join",
"os.getenv",
"conans.tools.cross_building",
"conans.tools.collect_libs"
] |
[((1781, 1834), 'conans.tools.get', 'tools.get', ([], {}), "(**self.conan_data['sources'][self.version])\n", (1790, 1834), False, 'from conans import ConanFile, tools, Meson\n'), ((1843, 1907), 'os.rename', 'os.rename', (['f"""{self.name}-{self.version}"""', 'self._source_subfolder'], {}), "(f'{self.name}-{self.version}', self._source_subfolder)\n", (1852, 1907), False, 'import os\n'), ((2610, 2621), 'conans.Meson', 'Meson', (['self'], {}), '(self)\n', (2615, 2621), False, 'from conans import ConanFile, tools, Meson\n'), ((3910, 3938), 'os.getenv', 'os.getenv', (['"""PKG_CONFIG_PATH"""'], {}), "('PKG_CONFIG_PATH')\n", (3919, 3938), False, 'import os\n'), ((4410, 4467), 'os.path.join', 'os.path.join', (['self.package_folder', '"""lib"""', '"""gstreamer-1.0"""'], {}), "(self.package_folder, 'lib', 'gstreamer-1.0')\n", (4422, 4467), False, 'import os\n'), ((1970, 1998), 'glob.glob', 'glob.glob', (['"""patches/*.patch"""'], {}), "('patches/*.patch')\n", (1979, 1998), False, 'import glob\n'), ((2013, 2056), 'logging.info', 'logging.info', (['f"""applying patch: {filename}"""'], {}), "(f'applying patch: {filename}')\n", (2025, 2056), False, 'import logging\n'), ((2069, 2135), 'conans.tools.patch', 'tools.patch', ([], {'base_path': 'self._source_subfolder', 'patch_file': 'filename'}), '(base_path=self._source_subfolder, patch_file=filename)\n', (2080, 2135), False, 'from conans import ConanFile, tools, Meson\n'), ((4513, 4582), 'logging.info', 'logging.info', (['f"""Appending GST_PLUGIN_PATH env var: {gst_plugin_path}"""'], {}), "(f'Appending GST_PLUGIN_PATH env var: {gst_plugin_path}')\n", (4525, 4582), False, 'import logging\n'), ((4754, 4778), 'conans.tools.collect_libs', 'tools.collect_libs', (['self'], {}), '(self)\n', (4772, 4778), False, 'from conans import ConanFile, tools, Meson\n'), ((3355, 3400), 'conans.tools.cross_building', 'tools.cross_building', (['self'], {'skip_x64_x86': '(True)'}), '(self, skip_x64_x86=True)\n', (3375, 3400), False, 'from conans import ConanFile, tools, Meson\n'), ((4181, 4192), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (4190, 4192), False, 'import os\n')]
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Product.browser'
db.add_column(u'feedback_product', 'browser',
self.gf('django.db.models.fields.CharField')(default=u'', max_length=30, blank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Product.browser'
db.delete_column(u'feedback_product', 'browser')
models = {
u'feedback.product': {
'Meta': {'object_name': 'Product'},
'browser': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '30', 'blank': 'True'}),
'browser_data_browser': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'blank': 'True'}),
'db_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'display_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image_file': ('django.db.models.fields.CharField', [], {'default': "u'noimage.png'", 'max_length': '100', 'null': 'True', 'blank': 'True'}),
'notes': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}),
'on_dashboard': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'on_picker': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'translation_system': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'})
},
u'feedback.response': {
'Meta': {'ordering': "['-created']", 'object_name': 'Response'},
'api': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'browser': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'browser_platform': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'browser_version': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'campaign': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}),
'category': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '50', 'null': 'True', 'blank': 'True'}),
'channel': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'country': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '4', 'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'device': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'happy': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'locale': ('django.db.models.fields.CharField', [], {'max_length': '8', 'blank': 'True'}),
'manufacturer': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'platform': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'product': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'rating': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),
'source': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}),
'translated_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'url': ('fjord.base.models.EnhancedURLField', [], {'max_length': '200', 'blank': 'True'}),
'user_agent': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'version': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'})
},
u'feedback.responsecontext': {
'Meta': {'object_name': 'ResponseContext'},
'data': ('fjord.base.models.JSONObjectField', [], {'default': '{}'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'opinion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['feedback.Response']"})
},
u'feedback.responseemail': {
'Meta': {'object_name': 'ResponseEmail'},
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'opinion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['feedback.Response']"})
},
u'feedback.responsepi': {
'Meta': {'object_name': 'ResponsePI'},
'data': ('fjord.base.models.JSONObjectField', [], {'default': '{}'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'opinion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['feedback.Response']"})
}
}
complete_apps = ['feedback']
|
[
"south.db.db.delete_column"
] |
[((559, 607), 'south.db.db.delete_column', 'db.delete_column', (['u"""feedback_product"""', '"""browser"""'], {}), "(u'feedback_product', 'browser')\n", (575, 607), False, 'from south.db import db\n')]
|
from solid_toolbox.extrusion import (
remove_adjacent_duplicates,
force_3d,
extrude_with_offsets,
)
from solid_toolbox.units import Vec, Vec2d, Point2d
def test_remove_adjacent_duplicates():
test_cases = [
([], []),
([1], [1]),
([1, 2, 1], [1, 2, 1]),
([1, 2, 2, 1], [1, 2, 1]),
([1, 2, 2, 2, 1], [1, 2, 1]),
([1, 2, 2, 4, 4, 2, 2, 1], [1, 2, 4, 2, 1]),
([1, 1, 1, 1], [1]),
]
for input_case, expected_output in test_cases:
assert remove_adjacent_duplicates(input_case) == expected_output
def test_force_3d():
assert force_3d(Vec2d(1, 2)) == Vec(1, 2, 0)
assert force_3d(Vec(1, 2, 3)) == Vec(1, 2, 3)
def test_extrude_with_offsets():
points = [
Point2d(0, 0),
Point2d(0, 10),
Point2d(10, 10),
Point2d(10, 0),
Point2d(0, 0),
]
out_cube = extrude_with_offsets(points, [[Vec(0, 0, 0)] * 5, [Vec(1, 0, 1)] * 5])
assert len(out_cube.params["points"]) == 8
assert len(out_cube.params["faces"]) == 6
out_pyramid = extrude_with_offsets(
points, [[Vec(0, 0, 0)] * 5, [Vec(5 - p.x, 5 - p.y, 3) for p in points]]
)
assert len(out_pyramid.params["points"]) == 5
assert len(out_pyramid.params["faces"]) == 5
|
[
"solid_toolbox.units.Vec",
"solid_toolbox.units.Vec2d",
"solid_toolbox.units.Point2d",
"solid_toolbox.extrusion.remove_adjacent_duplicates"
] |
[((639, 651), 'solid_toolbox.units.Vec', 'Vec', (['(1)', '(2)', '(0)'], {}), '(1, 2, 0)\n', (642, 651), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((689, 701), 'solid_toolbox.units.Vec', 'Vec', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (692, 701), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((760, 773), 'solid_toolbox.units.Point2d', 'Point2d', (['(0)', '(0)'], {}), '(0, 0)\n', (767, 773), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((783, 797), 'solid_toolbox.units.Point2d', 'Point2d', (['(0)', '(10)'], {}), '(0, 10)\n', (790, 797), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((807, 822), 'solid_toolbox.units.Point2d', 'Point2d', (['(10)', '(10)'], {}), '(10, 10)\n', (814, 822), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((832, 846), 'solid_toolbox.units.Point2d', 'Point2d', (['(10)', '(0)'], {}), '(10, 0)\n', (839, 846), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((856, 869), 'solid_toolbox.units.Point2d', 'Point2d', (['(0)', '(0)'], {}), '(0, 0)\n', (863, 869), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((522, 560), 'solid_toolbox.extrusion.remove_adjacent_duplicates', 'remove_adjacent_duplicates', (['input_case'], {}), '(input_case)\n', (548, 560), False, 'from solid_toolbox.extrusion import remove_adjacent_duplicates, force_3d, extrude_with_offsets\n'), ((623, 634), 'solid_toolbox.units.Vec2d', 'Vec2d', (['(1)', '(2)'], {}), '(1, 2)\n', (628, 634), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((672, 684), 'solid_toolbox.units.Vec', 'Vec', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (675, 684), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((1136, 1160), 'solid_toolbox.units.Vec', 'Vec', (['(5 - p.x)', '(5 - p.y)', '(3)'], {}), '(5 - p.x, 5 - p.y, 3)\n', (1139, 1160), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((923, 935), 'solid_toolbox.units.Vec', 'Vec', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (926, 935), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((943, 955), 'solid_toolbox.units.Vec', 'Vec', (['(1)', '(0)', '(1)'], {}), '(1, 0, 1)\n', (946, 955), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n'), ((1116, 1128), 'solid_toolbox.units.Vec', 'Vec', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (1119, 1128), False, 'from solid_toolbox.units import Vec, Vec2d, Point2d\n')]
|
from flask import current_app as app
from flask import Blueprint, render_template
from flask_login import login_required
from .viewmodels.DashboardViewModel import DashboardViewModel
from ...services.QuizService import QuizService
from ...repositories.SubjectRepository import SubjectRepository
home_controller = Blueprint(
'home_controller',
__name__,
template_folder='views',
url_prefix=''
)
@home_controller.before_request
@login_required
def before_request():
pass
# Home/Index
@home_controller.route('/', methods=['GET'])
def index():
"""
User Dashboard
"""
viewmodel = DashboardViewModel()
viewmodel.random_quiz_id = 0
random_subject = SubjectRepository.get_random_item()
if random_subject:
viewmodel.random_quiz_id = random_subject.id
viewmodel.dashboard_game_list_items = QuizService.get_played_games_for_quiz_game_overview(
app.config.get('DASHBOARD_AMOUNT_OF_QUIZGAMES')
)
return render_template(
'index.jinja2',
viewmodel=viewmodel
)
|
[
"flask.Blueprint",
"flask.current_app.config.get",
"flask.render_template"
] |
[((318, 396), 'flask.Blueprint', 'Blueprint', (['"""home_controller"""', '__name__'], {'template_folder': '"""views"""', 'url_prefix': '""""""'}), "('home_controller', __name__, template_folder='views', url_prefix='')\n", (327, 396), False, 'from flask import Blueprint, render_template\n'), ((979, 1031), 'flask.render_template', 'render_template', (['"""index.jinja2"""'], {'viewmodel': 'viewmodel'}), "('index.jinja2', viewmodel=viewmodel)\n", (994, 1031), False, 'from flask import Blueprint, render_template\n'), ((913, 960), 'flask.current_app.config.get', 'app.config.get', (['"""DASHBOARD_AMOUNT_OF_QUIZGAMES"""'], {}), "('DASHBOARD_AMOUNT_OF_QUIZGAMES')\n", (927, 960), True, 'from flask import current_app as app\n')]
|
"""
Tests for the :func:`dicom_parser.utils.mime_generator.generate_by_mime`
utility function.
"""
import importlib.util
import platform
from typing import Generator
from unittest import TestCase
import pytest
from dicom_parser.utils.mime_generator import check_magic, generate_by_mime
from tests.fixtures import TEST_MIME_SERIES_PATH
#: Message to display for Linux and macOS tests.
NIX_RUN: str = "Mime type generation is supported in Linux and macOS."
#: Message to display for Windows only tests.
WINDOWS_TESTS: str = "Windows-specific tests."
#: Whether the current platform OS is Windows or not.
RUNNING_ON_WINDOWS: bool = platform.system() == "Windows"
#: Whether python-magic is installed or not.
MAGIC = bool(importlib.util.find_spec("magic"))
# TODO: Fix windows test. For some reason NotImplementedError isn't raised
# when tested with GitHub Actions.
@pytest.mark.skipif(not RUNNING_ON_WINDOWS, reason=WINDOWS_TESTS)
class WindowsMimeGeneratorTestCase(TestCase):
"""
Windows-specific tests (where libmagic and python-magic are not
available).
"""
def test_check_magic(self):
"""
Tests generation by mime type on Windows raises a RuntimeError.
"""
with self.assertRaises(NotImplementedError):
check_magic()
def test_notimplemetederror_raised(self):
"""
Tests generation by mime type on Windows raises a RuntimeError.
"""
with self.assertRaises(NotImplementedError):
generate_by_mime(TEST_MIME_SERIES_PATH)
@pytest.mark.skipif(MAGIC or RUNNING_ON_WINDOWS, reason="Muggle tests.")
class MugglesMimeGeneratorTestCase(TestCase):
"""
Tests for installations without python-magic.
"""
def test_check_magic(self):
"""
Tests generation by mime type when python-magic isn't installed raises
ModuleNotFoundError.
"""
with self.assertRaises(ImportError):
check_magic()
def test_modulenotfounderror_raised(self):
"""
Tests generation by mime type when python-magic isn't installed raises
ModuleNotFoundError.
"""
with self.assertRaises(ImportError):
generate_by_mime(TEST_MIME_SERIES_PATH)
@pytest.mark.skipif(RUNNING_ON_WINDOWS or not MAGIC, reason=NIX_RUN)
class MimeGeneratorTestCase(TestCase):
"""
Tests for Linux and macOS.
"""
def setUp(self):
"""
Create a base sample generator available for each test.
"""
self.generator = generate_by_mime(TEST_MIME_SERIES_PATH)
def test_return_type(self):
"""
Tests the returned object is a generator instance.
"""
self.assertIsInstance(self.generator, Generator)
def test_number_of_files(self):
"""
Checks that the generator generates the expected number of files.
"""
n_images = len(list(self.generator))
expected = 3
self.assertEqual(n_images, expected)
|
[
"platform.system",
"dicom_parser.utils.mime_generator.generate_by_mime",
"pytest.mark.skipif",
"dicom_parser.utils.mime_generator.check_magic"
] |
[((873, 937), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not RUNNING_ON_WINDOWS)'], {'reason': 'WINDOWS_TESTS'}), '(not RUNNING_ON_WINDOWS, reason=WINDOWS_TESTS)\n', (891, 937), False, 'import pytest\n'), ((1543, 1614), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(MAGIC or RUNNING_ON_WINDOWS)'], {'reason': '"""Muggle tests."""'}), "(MAGIC or RUNNING_ON_WINDOWS, reason='Muggle tests.')\n", (1561, 1614), False, 'import pytest\n'), ((2243, 2310), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(RUNNING_ON_WINDOWS or not MAGIC)'], {'reason': 'NIX_RUN'}), '(RUNNING_ON_WINDOWS or not MAGIC, reason=NIX_RUN)\n', (2261, 2310), False, 'import pytest\n'), ((634, 651), 'platform.system', 'platform.system', ([], {}), '()\n', (649, 651), False, 'import platform\n'), ((2532, 2571), 'dicom_parser.utils.mime_generator.generate_by_mime', 'generate_by_mime', (['TEST_MIME_SERIES_PATH'], {}), '(TEST_MIME_SERIES_PATH)\n', (2548, 2571), False, 'from dicom_parser.utils.mime_generator import check_magic, generate_by_mime\n'), ((1278, 1291), 'dicom_parser.utils.mime_generator.check_magic', 'check_magic', ([], {}), '()\n', (1289, 1291), False, 'from dicom_parser.utils.mime_generator import check_magic, generate_by_mime\n'), ((1500, 1539), 'dicom_parser.utils.mime_generator.generate_by_mime', 'generate_by_mime', (['TEST_MIME_SERIES_PATH'], {}), '(TEST_MIME_SERIES_PATH)\n', (1516, 1539), False, 'from dicom_parser.utils.mime_generator import check_magic, generate_by_mime\n'), ((1949, 1962), 'dicom_parser.utils.mime_generator.check_magic', 'check_magic', ([], {}), '()\n', (1960, 1962), False, 'from dicom_parser.utils.mime_generator import check_magic, generate_by_mime\n'), ((2200, 2239), 'dicom_parser.utils.mime_generator.generate_by_mime', 'generate_by_mime', (['TEST_MIME_SERIES_PATH'], {}), '(TEST_MIME_SERIES_PATH)\n', (2216, 2239), False, 'from dicom_parser.utils.mime_generator import check_magic, generate_by_mime\n')]
|
from fabric.api import local, settings
def bump_patch():
with open('angular_scaffold/_version.py', 'r') as f:
original = f.read()
version = original.split('=')[1].strip('\" \n\'')
major, minor, patch = version.split('.')
patch = int(patch) + 1
with open('angular_scaffold/_version.py', 'w') as f:
f.write('__version__ = "%s.%s.%s"' % (major, minor, patch))
local('git add angular_scaffold/_version.py')
local('git commit -m "updated version to %s.%s.%s"' % (major, minor, patch))
local('git push')
def bump_minor():
with open('angular_scaffold/_version.py', 'r') as f:
original = f.read()
version = original.split('=')[1].strip('\" \n\'')
major, minor, patch = version.split('.')
patch = 0
minor = int(minor) + 1
with open('angular_scaffold/_version.py', 'w') as f:
f.write('__version__ = "%s.%s.%s"' % (major, minor, patch))
local('git add angular_scaffold/_version.py')
local('git commit -m "updated version to %s.%s.%s"' % (major, minor, patch))
local('git tag %s.%s -m "Update for release"' % (major, minor))
local('git push --tags origin master')
def bump_major():
with open('angular_scaffold/_version.py', 'r') as f:
original = f.read()
version = original.split('=')[1].strip('\" \n\'')
major, minor, patch = version.split('.')
patch = 0
minor = 0
major = int(major) + 1
with open('angular_scaffold/_version.py', 'w') as f:
f.write('__version__ = "%s.%s.%s"' % (major, minor, patch))
local('git add angular_scaffold/_version.py')
local('git commit -m "updated version to %s.%s.%s"' % (major, minor, patch))
local('git tag %s.%s -m "Update for release"' % (major, minor))
local('git push --tags origin master')
def update_generated_docs():
with settings(warn_only=True):
with open("README.md", 'r') as readme, open('angular_scaffold/_docs.py', 'w') as docs:
documentation = readme.read()
docs.write('docs = """')
docs.write(documentation)
docs.write('"""')
local('git add angular_scaffold/_docs.py')
local('git commit -m "updated generated docs"')
def freeze():
local("pip freeze > requirements.txt")
def test():
pass
def quality_check():
local('pep8 .')
local('xenon . -a A -m A -b A -i core')
local('prospector')
def deploy_test(release='patch'):
update_generated_docs()
if release == 'patch':
bump_patch()
elif release == 'minor':
bump_minor()
elif release == 'major':
bump_major()
elif release == 'none':
pass
else:
bump_patch()
local('python setup.py register -r pypitest')
local('python setup.py sdist upload -r pypitest')
def deploy(release='patch'):
update_generated_docs()
if release == 'patch':
bump_patch()
elif release == 'minor':
bump_minor()
elif release == 'major':
bump_major()
elif release == 'none':
pass
else:
bump_patch()
local('python setup.py register -r pypi')
local('python setup.py sdist upload -r pypi')
def deploy_both(release='patch'):
deploy_test(release)
deploy('none')
|
[
"fabric.api.local",
"fabric.api.settings"
] |
[((411, 456), 'fabric.api.local', 'local', (['"""git add angular_scaffold/_version.py"""'], {}), "('git add angular_scaffold/_version.py')\n", (416, 456), False, 'from fabric.api import local, settings\n'), ((461, 537), 'fabric.api.local', 'local', (['(\'git commit -m "updated version to %s.%s.%s"\' % (major, minor, patch))'], {}), '(\'git commit -m "updated version to %s.%s.%s"\' % (major, minor, patch))\n', (466, 537), False, 'from fabric.api import local, settings\n'), ((542, 559), 'fabric.api.local', 'local', (['"""git push"""'], {}), "('git push')\n", (547, 559), False, 'from fabric.api import local, settings\n'), ((950, 995), 'fabric.api.local', 'local', (['"""git add angular_scaffold/_version.py"""'], {}), "('git add angular_scaffold/_version.py')\n", (955, 995), False, 'from fabric.api import local, settings\n'), ((1000, 1076), 'fabric.api.local', 'local', (['(\'git commit -m "updated version to %s.%s.%s"\' % (major, minor, patch))'], {}), '(\'git commit -m "updated version to %s.%s.%s"\' % (major, minor, patch))\n', (1005, 1076), False, 'from fabric.api import local, settings\n'), ((1081, 1144), 'fabric.api.local', 'local', (['(\'git tag %s.%s -m "Update for release"\' % (major, minor))'], {}), '(\'git tag %s.%s -m "Update for release"\' % (major, minor))\n', (1086, 1144), False, 'from fabric.api import local, settings\n'), ((1149, 1187), 'fabric.api.local', 'local', (['"""git push --tags origin master"""'], {}), "('git push --tags origin master')\n", (1154, 1187), False, 'from fabric.api import local, settings\n'), ((1596, 1641), 'fabric.api.local', 'local', (['"""git add angular_scaffold/_version.py"""'], {}), "('git add angular_scaffold/_version.py')\n", (1601, 1641), False, 'from fabric.api import local, settings\n'), ((1646, 1722), 'fabric.api.local', 'local', (['(\'git commit -m "updated version to %s.%s.%s"\' % (major, minor, patch))'], {}), '(\'git commit -m "updated version to %s.%s.%s"\' % (major, minor, patch))\n', (1651, 1722), False, 'from fabric.api import local, settings\n'), ((1727, 1790), 'fabric.api.local', 'local', (['(\'git tag %s.%s -m "Update for release"\' % (major, minor))'], {}), '(\'git tag %s.%s -m "Update for release"\' % (major, minor))\n', (1732, 1790), False, 'from fabric.api import local, settings\n'), ((1795, 1833), 'fabric.api.local', 'local', (['"""git push --tags origin master"""'], {}), "('git push --tags origin master')\n", (1800, 1833), False, 'from fabric.api import local, settings\n'), ((2269, 2307), 'fabric.api.local', 'local', (['"""pip freeze > requirements.txt"""'], {}), "('pip freeze > requirements.txt')\n", (2274, 2307), False, 'from fabric.api import local, settings\n'), ((2358, 2373), 'fabric.api.local', 'local', (['"""pep8 ."""'], {}), "('pep8 .')\n", (2363, 2373), False, 'from fabric.api import local, settings\n'), ((2378, 2417), 'fabric.api.local', 'local', (['"""xenon . -a A -m A -b A -i core"""'], {}), "('xenon . -a A -m A -b A -i core')\n", (2383, 2417), False, 'from fabric.api import local, settings\n'), ((2422, 2441), 'fabric.api.local', 'local', (['"""prospector"""'], {}), "('prospector')\n", (2427, 2441), False, 'from fabric.api import local, settings\n'), ((2730, 2775), 'fabric.api.local', 'local', (['"""python setup.py register -r pypitest"""'], {}), "('python setup.py register -r pypitest')\n", (2735, 2775), False, 'from fabric.api import local, settings\n'), ((2780, 2829), 'fabric.api.local', 'local', (['"""python setup.py sdist upload -r pypitest"""'], {}), "('python setup.py sdist upload -r pypitest')\n", (2785, 2829), False, 'from fabric.api import local, settings\n'), ((3113, 3154), 'fabric.api.local', 'local', (['"""python setup.py register -r pypi"""'], {}), "('python setup.py register -r pypi')\n", (3118, 3154), False, 'from fabric.api import local, settings\n'), ((3159, 3204), 'fabric.api.local', 'local', (['"""python setup.py sdist upload -r pypi"""'], {}), "('python setup.py sdist upload -r pypi')\n", (3164, 3204), False, 'from fabric.api import local, settings\n'), ((1874, 1898), 'fabric.api.settings', 'settings', ([], {'warn_only': '(True)'}), '(warn_only=True)\n', (1882, 1898), False, 'from fabric.api import local, settings\n'), ((2150, 2192), 'fabric.api.local', 'local', (['"""git add angular_scaffold/_docs.py"""'], {}), "('git add angular_scaffold/_docs.py')\n", (2155, 2192), False, 'from fabric.api import local, settings\n'), ((2201, 2248), 'fabric.api.local', 'local', (['"""git commit -m "updated generated docs\\""""'], {}), '(\'git commit -m "updated generated docs"\')\n', (2206, 2248), False, 'from fabric.api import local, settings\n')]
|
import os
import shutil
import subprocess
import pytest
def _assert_eq(left, right):
assert left == right, '{} != {}'.format(left, right)
N_STEPS = 100
N_TRIALS = 2
N_JOBS = 1
ALGOS = ('ppo2', 'a2c', 'trpo', 'acktr')
# Not yet supported:
# ALGOS = ('acer', 'dqn')
ENV_IDS = ('CartPole-v1',)
LOG_FOLDER = 'logs/tests_optimize/'
experiments = {}
for algo in ALGOS:
for env_id in ENV_IDS:
experiments['{}-{}'.format(algo, env_id)] = (algo, env_id)
# Test for DDPG
experiments['ddpg-MountainCarContinuous-v0'] = ('ddpg', 'MountainCarContinuous-v0')
# Test for SAC
experiments['sac-Pendulum-v0'] = ('sac', 'Pendulum-v0')
# Test for TD3
experiments['td3-Pendulum-v0'] = ('td3', 'Pendulum-v0')
# Clean up
if os.path.isdir(LOG_FOLDER):
shutil.rmtree(LOG_FOLDER)
@pytest.mark.parametrize("sampler", ['random', 'tpe'])
@pytest.mark.parametrize("pruner", ['none', 'halving', 'median'])
@pytest.mark.parametrize("experiment", experiments.keys())
def test_optimize(sampler, pruner, experiment):
algo, env_id = experiments[experiment]
args = [
'-n', str(N_STEPS),
'--algo', algo,
'--env', env_id,
'--log-folder', LOG_FOLDER,
'--n-trials', str(N_TRIALS),
'--n-jobs', str(N_JOBS),
'--sampler', sampler,
'--pruner', pruner,
'-optimize'
]
return_code = subprocess.call(['python', 'train.py'] + args)
_assert_eq(return_code, 0)
|
[
"os.path.isdir",
"pytest.mark.parametrize",
"subprocess.call",
"shutil.rmtree"
] |
[((727, 752), 'os.path.isdir', 'os.path.isdir', (['LOG_FOLDER'], {}), '(LOG_FOLDER)\n', (740, 752), False, 'import os\n'), ((787, 840), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""sampler"""', "['random', 'tpe']"], {}), "('sampler', ['random', 'tpe'])\n", (810, 840), False, 'import pytest\n'), ((842, 906), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""pruner"""', "['none', 'halving', 'median']"], {}), "('pruner', ['none', 'halving', 'median'])\n", (865, 906), False, 'import pytest\n'), ((758, 783), 'shutil.rmtree', 'shutil.rmtree', (['LOG_FOLDER'], {}), '(LOG_FOLDER)\n', (771, 783), False, 'import shutil\n'), ((1356, 1402), 'subprocess.call', 'subprocess.call', (["(['python', 'train.py'] + args)"], {}), "(['python', 'train.py'] + args)\n", (1371, 1402), False, 'import subprocess\n')]
|
import digi
if __name__ == '__main__':
digi.run()
|
[
"digi.run"
] |
[((44, 54), 'digi.run', 'digi.run', ([], {}), '()\n', (52, 54), False, 'import digi\n')]
|
""" Functions and Operations for analysing a cluster's tidal tails
"""
__author__ = "<NAME>"
__all__ = [
"to_tail",
"tail_path",
"tail_path_match",
]
try:
from galpy.util import conversion
except:
import galpy.util.bovy_conversion as conversion
from galpy.util import _rotate_to_arbitrary_vector
from galpy import potential
from galpy.potential import MWPotential2014
import numpy as np
import matplotlib.pyplot as plt
from .orbit import orbital_path, orbital_path_match
from .operations import *
from ..util.recipes import binmaker,nbinmaker,roaming_binmaker,roaming_nbinmaker
from ..util.coordinates import cart_to_sky
from ..util.plots import starplot,skyplot,_plot,_lplot,_scatter
def to_tail(cluster):
"""Calculate positions and velocities of stars when rotated such that clusters velocity vector
points along x-axis
- no change to coordinates in StarCluster
Parameters
----------
cluster : class
StarCluster
Returns
-------
x_tail,y_tail,z_tail,vx_tail,vy_tail,vz_tail : float
rotated coordinates with cluster's velocity vector point along x-axis
History:
-------
2018 - Written - Webb (UofT)
"""
units0, origin0, rorder0, rorder_origin0 = save_cluster(cluster)
if origin0 != 'cluster' and origin0 != 'centre':
cluster.to_centre(sortstars=False)
v_vec = np.array([cluster.vxgc, cluster.vygc, cluster.vzgc])
new_v_vec = np.array([1.0, 0.0, 0.0])
rot = _rotate_to_arbitrary_vector(
np.atleast_2d(v_vec), new_v_vec, inv=False, _dontcutsmall=False
)
x_tail = (
cluster.x * rot[:, 0, 0] + cluster.y * rot[:, 1, 0] + cluster.z * rot[:, 2, 0]
)
y_tail = (
cluster.x * rot[:, 0, 1] + cluster.y * rot[:, 1, 1] + cluster.z * rot[:, 2, 1]
)
z_tail = (
cluster.x * rot[:, 0, 2] + cluster.y * rot[:, 1, 2] + cluster.z * rot[:, 2, 2]
)
vx_tail = (
cluster.vx * rot[:, 0, 0] + cluster.vy * rot[:, 1, 0] + cluster.vz * rot[:, 2, 0]
)
vy_tail = (
cluster.vx * rot[:, 0, 1] + cluster.vy * rot[:, 1, 1] + cluster.vz * rot[:, 2, 1]
)
vz_tail = (
cluster.vx * rot[:, 0, 2] + cluster.vy * rot[:, 1, 2] + cluster.vz * rot[:, 2, 2]
)
return_cluster(cluster, units0, origin0, rorder0, rorder_origin0)
return x_tail,y_tail,z_tail,vx_tail,vy_tail,vz_tail
def tail_path(
cluster, dt=0.1, no=1000, nt=100, ntail=100, pot=MWPotential2014, dmax=None, bintype = 'fix', from_centre=False, skypath=False,
to_path=False,
do_full=False,
ro=8.0, vo=220.0,
plot=False,projected=False,
**kwargs,
):
"""Calculate tail path +/- dt Gyr around the cluster
Parameters
----------
cluster : class
StarCluster
dt : float
timestep that StarCluster is to be moved to
no : int
number of timesteps for orbit integration (default:1000)
nt : int
number of points along the tail to set the tail spacing (default: 100)
ntail : int
number of points along the tail with roaming average (default: 1000)
pot : class
galpy Potential that orbit is to be integrate in (default: MWPotential2014)
dmax : float
maximum distance (assumed to be same units as cluster) from orbital path to be included in generating tail path (default: None)
bintype : str
type of binning for tail stars (default : 'fix')
from_centre : bool
genrate orbit from cluster's exact centre instead of its assigned galactocentric coordinates (default: False)
skypath : bool
return sky coordinates instead of cartesian coordinates (default: False)
to_path : bool
measure distance to the path itself instead of distance to central point along the path (default: False)
do_full : bool
calculate dpath all at once in a single numpy array (can be memory intensive) (default:False)
ro :float
galpy distance scale (Default: 8.)
vo : float
galpy velocity scale (Default: 220.)
plot : bool
plot a snapshot of the cluster in galactocentric coordinates with the orbital path (defualt: False)
projected : bool
match to projected orbital path, which means matching just x and y coordinates or Ra and Dec coordinates (not z, or dist) (default:False)
Returns
-------
t : float
times for which path is provided
x,y,z : float
tail path positions
vx,vy,vz : float
tail path velocities
History
-------
2018 - Written - Webb (UofT)
2019 - Implemented numpy array preallocation to minimize runtime - <NAME> (UofT)
"""
units0, origin0, rorder0, rorder_origin0 = save_cluster(cluster)
cluster.to_galaxy(sortstars=False)
cluster.to_kpckms()
#dmax is assumed to have same units as cluster
if dmax is not None:
if units0=='nbody':
dmax*=cluster.rbar/1000.0
elif units0=='pckms':
dmax/=1000.
elif units0=='galpy':
dmax*=ro
elif units0=='radec' and not skypath:
dist=np.sqrt(cluster.xgc**2.+cluster.ygc**2.+cluster.zgc**2.)
dmax=dist*np.tan(dmax)
elif units0=='kpckms' and skypath:
dist=np.sqrt(cluster.xgc**2.+cluster.ygc**2.+cluster.zgc**2.)
dmax=np.arctan(dmax/dist)
to, xo, yo, zo, vxo, vyo, vzo = orbital_path(
cluster,
dt=dt,
nt=no,
pot=pot,
from_centre=from_centre,
skypath=skypath,
initialize=False,
ro=ro,
vo=vo,
)
path=(to, xo, yo, zo, vxo, vyo, vzo)
if bintype=='fix':
if ntail > nt:
t_lower, t_mid, t_upper, t_hist = roaming_binmaker(to, nbin=nt,ntot=ntail)
else:
t_lower, t_mid, t_upper, t_hist = binmaker(to, nbin=nt)
elif bintype=='num':
if ntail>nt:
t_lower, t_mid, t_upper, t_hist = roaming_nbinmaker(to, nbin=nt,ntot=ntail)
else:
t_lower, t_mid, t_upper, t_hist = nbinmaker(to, nbin=nt)
tstar, dprog, dpath = orbital_path_match(
cluster=cluster, dt=dt, nt=no, pot=pot, path=path, from_centre=from_centre, skypath=skypath, to_path=to_path,do_full=do_full, ro=ro, vo=vo, projected=projected
)
if dmax is None:
dindx=np.ones(len(tstar),dtype=bool)
else:
dindx = (np.fabs(dpath) <= dmax)
ttail = np.array([])
xtail = np.array([])
ytail = np.array([])
ztail = np.array([])
vxtail = np.array([])
vytail = np.array([])
vztail = np.array([])
for i in range(0, len(t_mid)):
indx = (tstar >= t_lower[i]) * (tstar <= t_upper[i]) * dindx
if np.sum(indx) > 0:
ttail = np.append(ttail, t_mid[i])
xtail = np.append(xtail, np.mean(cluster.x[indx]))
ytail = np.append(ytail, np.mean(cluster.y[indx]))
ztail = np.append(ztail, np.mean(cluster.z[indx]))
vxtail = np.append(vxtail, np.mean(cluster.vx[indx]))
vytail = np.append(vytail, np.mean(cluster.vy[indx]))
vztail = np.append(vztail, np.mean(cluster.vz[indx]))
if skypath:
ratail,dectail,disttail,pmratail,pmdectail,vlostail=cart_to_sky(xtail, ytail, ztail, vxtail, vytail, vztail)
if plot:
filename = kwargs.pop("filename", None)
overplot = kwargs.pop("overplot", False)
if skypath:
skyplot(cluster,coords='radec',overplot=overplot)
_lplot(ratail,dectail,overplot=True)
else:
starplot(cluster,coords='xy',overplot=overplot)
_lplot(xtail,ytail,overplot=True)
if filename != None:
plt.savefig(filename)
return_cluster(cluster, units0, origin0, rorder0, rorder_origin0)
if skypath:
return ttail,ratail,dectail,disttail,pmratail,pmdectail,vlostail
else:
return ttail, xtail, ytail, ztail, vxtail, vytail, vztail
def tail_path_match(
cluster,
dt=0.1,
no=1000,
nt=100,
ntail=100,
pot=MWPotential2014,
path=None,
from_centre=False,
skypath=False,
to_path=False,
do_full=False,
ro=8.0,
vo=220.0,
plot=False,
projected=False,
**kwargs,
):
"""Match stars to a position along the tail path of the cluster
Parameters
----------
cluster : class
StarCluster
dt : float
timestep that StarCluster is to be moved to
no : int
number of timesteps for orbit integration (default:1000)
nt : int
number of points along the tail to set the tail spacing (default: 100)
ntail : int
number of points along the tail with roaming average (default: 1000)
pot : class
galpy Potential that orbit is to be integrate in (default: MWPotential2014)
path : array
array of (t,x,y,x,vx,vy,vz) corresponding to the tail path. If none path is calculated (default: None)
from_centre : bool
genrate orbit from cluster's exact centre instead of its assigned galactocentric coordinates (default: False)
skypath : bool
return sky coordinates instead of cartesian coordinates (default: False)
if True, projected is set to True
to_path : bool
measure distance to the path itself instead of distance to central point along the path (default: False)
do_full : bool
calculate dpath all at once in a single numpy array (can be memory intensive) (default:False)
ro :float
galpy distance scale (Default: 8.)
vo : float
galpy velocity scale (Default: 220.)
plot : bool
plot a snapshot of the cluster in galactocentric coordinates with the orbital path (defualt: False)
projected : bool
match to projected orbital path, which means matching just x and y coordinates or Ra and Dec coordinates (not z, or dist) (default:False)
Returns
-------
tstar : float
orbital time associated with star
dprog : float
distance along the path to the progenitor
dpath :
distance to centre of the tail path bin (default) or the tail path (to_path = True)
History
-------
2018 - Written - Webb (UofT)
"""
if path is None:
path = tail_path(
cluster, dt=dt, no=no, nt=nt, ntail=ntail, pot=pot, from_centre=from_centre, skypath=skypath, ro=ro, vo=vo
)
return orbital_path_match(cluster=cluster,dt=dt,nt=no,pot=pot,path=path,from_centre=from_centre,
skypath=skypath,to_path=to_path,do_full=do_full,ro=ro,vo=vo,plot=plot,projected=projected,**kwargs)
|
[
"numpy.sum",
"numpy.append",
"numpy.fabs",
"numpy.array",
"numpy.mean",
"numpy.tan",
"numpy.arctan",
"numpy.sqrt",
"matplotlib.pyplot.savefig",
"numpy.atleast_2d"
] |
[((1386, 1438), 'numpy.array', 'np.array', (['[cluster.vxgc, cluster.vygc, cluster.vzgc]'], {}), '([cluster.vxgc, cluster.vygc, cluster.vzgc])\n', (1394, 1438), True, 'import numpy as np\n'), ((1455, 1480), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (1463, 1480), True, 'import numpy as np\n'), ((6422, 6434), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6430, 6434), True, 'import numpy as np\n'), ((6447, 6459), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6455, 6459), True, 'import numpy as np\n'), ((6472, 6484), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6480, 6484), True, 'import numpy as np\n'), ((6497, 6509), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6505, 6509), True, 'import numpy as np\n'), ((6523, 6535), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6531, 6535), True, 'import numpy as np\n'), ((6549, 6561), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6557, 6561), True, 'import numpy as np\n'), ((6575, 6587), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6583, 6587), True, 'import numpy as np\n'), ((1529, 1549), 'numpy.atleast_2d', 'np.atleast_2d', (['v_vec'], {}), '(v_vec)\n', (1542, 1549), True, 'import numpy as np\n'), ((6385, 6399), 'numpy.fabs', 'np.fabs', (['dpath'], {}), '(dpath)\n', (6392, 6399), True, 'import numpy as np\n'), ((6704, 6716), 'numpy.sum', 'np.sum', (['indx'], {}), '(indx)\n', (6710, 6716), True, 'import numpy as np\n'), ((6742, 6768), 'numpy.append', 'np.append', (['ttail', 't_mid[i]'], {}), '(ttail, t_mid[i])\n', (6751, 6768), True, 'import numpy as np\n'), ((7695, 7716), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (7706, 7716), True, 'import matplotlib.pyplot as plt\n'), ((6806, 6830), 'numpy.mean', 'np.mean', (['cluster.x[indx]'], {}), '(cluster.x[indx])\n', (6813, 6830), True, 'import numpy as np\n'), ((6869, 6893), 'numpy.mean', 'np.mean', (['cluster.y[indx]'], {}), '(cluster.y[indx])\n', (6876, 6893), True, 'import numpy as np\n'), ((6932, 6956), 'numpy.mean', 'np.mean', (['cluster.z[indx]'], {}), '(cluster.z[indx])\n', (6939, 6956), True, 'import numpy as np\n'), ((6997, 7022), 'numpy.mean', 'np.mean', (['cluster.vx[indx]'], {}), '(cluster.vx[indx])\n', (7004, 7022), True, 'import numpy as np\n'), ((7063, 7088), 'numpy.mean', 'np.mean', (['cluster.vy[indx]'], {}), '(cluster.vy[indx])\n', (7070, 7088), True, 'import numpy as np\n'), ((7129, 7154), 'numpy.mean', 'np.mean', (['cluster.vz[indx]'], {}), '(cluster.vz[indx])\n', (7136, 7154), True, 'import numpy as np\n'), ((5111, 5180), 'numpy.sqrt', 'np.sqrt', (['(cluster.xgc ** 2.0 + cluster.ygc ** 2.0 + cluster.zgc ** 2.0)'], {}), '(cluster.xgc ** 2.0 + cluster.ygc ** 2.0 + cluster.zgc ** 2.0)\n', (5118, 5180), True, 'import numpy as np\n'), ((5190, 5202), 'numpy.tan', 'np.tan', (['dmax'], {}), '(dmax)\n', (5196, 5202), True, 'import numpy as np\n'), ((5263, 5332), 'numpy.sqrt', 'np.sqrt', (['(cluster.xgc ** 2.0 + cluster.ygc ** 2.0 + cluster.zgc ** 2.0)'], {}), '(cluster.xgc ** 2.0 + cluster.ygc ** 2.0 + cluster.zgc ** 2.0)\n', (5270, 5332), True, 'import numpy as np\n'), ((5337, 5359), 'numpy.arctan', 'np.arctan', (['(dmax / dist)'], {}), '(dmax / dist)\n', (5346, 5359), True, 'import numpy as np\n')]
|
# coding: utf-8
import math
print(math.atanh(math.tanh(2)))
|
[
"math.tanh"
] |
[((47, 59), 'math.tanh', 'math.tanh', (['(2)'], {}), '(2)\n', (56, 59), False, 'import math\n')]
|
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import optuna
import mlflow
import os
import numpy as np
from numpyencoder import NumpyEncoder
from argparse import Namespace
from typing import List, Dict, Tuple, Optional
from pathlib import Path
import tempfile
import json
#from utils import *
#from config import *
#from data import *
#from models import *
from recsys import utils, config, data, models, eval
class Trainer(object):
def __init__(self,
model,
device: torch.device=torch.device("cuda" if torch.cuda.is_available() else "cpu"),
loss_fn=None,
optimizer=None,
scheduler= None,
trial=None):
# Set params
self.model = model
self.device = device
self.loss_fn = loss_fn
self.optimizer = optimizer
self.scheduler = scheduler
self.trial = trial
def train_step(self, dataloader):
self.model.train()
loss = 0.0
size = len(dataloader.dataset)
for batch, (user, item, label) in enumerate(dataloader):
user = user.to(self.device)
item = item.to(self.device)
label = label.to(self.device)
# forward
self.optimizer.zero_grad()
prediction = self.model.predict(user, item)
# backward
loss = self.loss_fn(prediction, label)
loss.backward()
self.optimizer.step()
loss += loss.item() - loss
return loss
def eval_step(self, dataloader):
"""Validation or test step"""
# Set model to eval mode
self.model.eval()
loss = 0.0
predictions, labels = [], []
with torch.no_grad():
for batch, (user, item, label) in enumerate(dataloader):
prediction = self.model.predict(user, item)
J = self.loss_fn(prediction, label).item()
loss += (J - loss)/(batch + 1)
# store outputs
prediction = prediction.numpy()
predictions.extend(prediction)
labels.extend(label.numpy())
return loss, np.vstack(labels), np.vstack(predictions)
def predict_step(self, dataloader):
""" Prediction step (inference)
Loss is not calculated for this loop.
"""
self.model.eval()
predictions, labels = [], []
# Interate over val batches
with torch.no_grad():
for batch, (user, item, label) in enumerate(dataloader):
# Forward pass w/ inputs
prediction = self.model.predict(user, item)
prediction = prediction.numpy()
predictions.extend(prediction)
labels.extend(label.numpy())
return np.vstack(labels), np.vstack(predictions)
def train(self, num_epochs, patience, train_dataloader, val_dataloader):
best_val_loss = np.inf
for epoch in range(num_epochs):
# Step
train_loss = self.train_step(dataloader=train_dataloader)
val_loss, _, _ = self.eval_step(dataloader=val_dataloader)
self.scheduler.step(val_loss)
# Early stopping
if val_loss < best_val_loss:
best_val_loss = val_loss
best_model = self.model
_patience = patience # reset _patience
else:
_patience -= 1
if not _patience: # 0
print('Stopping early')
break
# Pruning based on the intermediate value
if self.trial:
self.trial.report(val_loss, epoch)
if self.trial.should_prune():
raise optuna.TrialPruned()
# Tracking
#mlflow.log_metrics(
# {'train_loss':train_loss, 'val_loss':val_loss}, step=epoch
#)
# Logging
print(
f"Epoch: {epoch + 1} |"
f"train_loss: {train_loss:.5f},"
f"val_loss: {val_loss:.5f},"
f"lr: {self.optimizer.param_groups[0]['lr']:.2E},"
f"patience: {_patience}"
)
return best_val_loss, best_model
def train(
params_fp: Path=Path(config.config_dir, "params.json"),
#train_dataloader: torch.utils.data.DataLoader,
#val_dataloader: torch.utils.data.DataLoader,
device: torch.device = torch.device('cuda:0' if torch.cuda.is_available() else "cpu"),
trial: optuna.trial._trial.Trial = None)->Tuple:
params = Namespace(**utils.load_dict(params_fp))
dataset = utils.get_data()
n_users = dataset['user_id'].nunique() + 1
n_items = dataset['item_id'].nunique() + 1
# left one out validation
dataloader = data.RCDataloader(params, dataset)
train_dataloader = dataloader.get_train_set()
test_dataloader = dataloader.get_test_set()
model = models.initialize_model(
n_users=n_users,
n_items=n_items,
params_fp=params_fp,
device=device
)
loss_fn = nn.MSELoss()
# Define optimizer & scheduler
optimizer = torch.optim.SGD(model.parameters(), lr=params.lr)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, mode = "min", factor=0.05, patience=params.patience
)
trainer = Trainer(
model=model,
device=device,
loss_fn=loss_fn,
optimizer=optimizer,
scheduler=scheduler,
trial=trial
)
best_val_loss, best_model = trainer.train(
params.n_epochs, params.patience, train_dataloader, test_dataloader
)
return params, best_model, best_val_loss
|
[
"torch.nn.MSELoss",
"recsys.utils.get_data",
"recsys.models.initialize_model",
"recsys.data.RCDataloader",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"optuna.TrialPruned",
"pathlib.Path",
"recsys.utils.load_dict",
"torch.cuda.is_available",
"torch.no_grad",
"numpy.vstack"
] |
[((4369, 4407), 'pathlib.Path', 'Path', (['config.config_dir', '"""params.json"""'], {}), "(config.config_dir, 'params.json')\n", (4373, 4407), False, 'from pathlib import Path\n'), ((4724, 4740), 'recsys.utils.get_data', 'utils.get_data', ([], {}), '()\n', (4738, 4740), False, 'from recsys import utils, config, data, models, eval\n'), ((4883, 4917), 'recsys.data.RCDataloader', 'data.RCDataloader', (['params', 'dataset'], {}), '(params, dataset)\n', (4900, 4917), False, 'from recsys import utils, config, data, models, eval\n'), ((5029, 5127), 'recsys.models.initialize_model', 'models.initialize_model', ([], {'n_users': 'n_users', 'n_items': 'n_items', 'params_fp': 'params_fp', 'device': 'device'}), '(n_users=n_users, n_items=n_items, params_fp=\n params_fp, device=device)\n', (5052, 5127), False, 'from recsys import utils, config, data, models, eval\n'), ((5178, 5190), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (5188, 5190), True, 'import torch.nn as nn\n'), ((5309, 5418), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'torch.optim.lr_scheduler.ReduceLROnPlateau', (['optimizer'], {'mode': '"""min"""', 'factor': '(0.05)', 'patience': 'params.patience'}), "(optimizer, mode='min', factor=\n 0.05, patience=params.patience)\n", (5351, 5418), False, 'import torch\n'), ((1753, 1768), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1766, 1768), False, 'import torch\n'), ((2219, 2236), 'numpy.vstack', 'np.vstack', (['labels'], {}), '(labels)\n', (2228, 2236), True, 'import numpy as np\n'), ((2238, 2260), 'numpy.vstack', 'np.vstack', (['predictions'], {}), '(predictions)\n', (2247, 2260), True, 'import numpy as np\n'), ((2522, 2537), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2535, 2537), False, 'import torch\n'), ((2866, 2883), 'numpy.vstack', 'np.vstack', (['labels'], {}), '(labels)\n', (2875, 2883), True, 'import numpy as np\n'), ((2885, 2907), 'numpy.vstack', 'np.vstack', (['predictions'], {}), '(predictions)\n', (2894, 2907), True, 'import numpy as np\n'), ((4563, 4588), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4586, 4588), False, 'import torch\n'), ((4681, 4707), 'recsys.utils.load_dict', 'utils.load_dict', (['params_fp'], {}), '(params_fp)\n', (4696, 4707), False, 'from recsys import utils, config, data, models, eval\n'), ((580, 605), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (603, 605), False, 'import torch\n'), ((3828, 3848), 'optuna.TrialPruned', 'optuna.TrialPruned', ([], {}), '()\n', (3846, 3848), False, 'import optuna\n')]
|
import json
from datetime import datetime
from decimal import Decimal
from dateparser import parse
from mt4.constants import get_mt4_symbol
class SignalAction(object):
OPEN = 'OPEN'
CLOSE = 'CLOSE'
UPDATE = 'UPDATE'
class MarketAction(object):
OPEN = 'OPEN'
CLOSE = 'CLOSE'
class EventType(object):
DEBUG = 'DEBUG'
STARTUP = 'STARTUP'
SHUTDOWN = 'SHUTDOWN'
HEARTBEAT = 'HEARTBEAT'
TICK = 'TICK'
TICK_PRICE = 'TICK_PRICE'
TIMEFRAME = 'TIMEFRAME'
SIGNAL = 'SIGNAL'
ORDER_CLOSE = 'ORDER_CLOSE'
ORDER_HOLDING = 'ORDER_HOLDING'
TRADE_OPEN = 'TRADE_OPEN'
TRADE_CLOSE = 'TRADE_CLOSE'
ORDER = 'ORDER'
MARKET = 'MARKET'
class Event(object):
type = None
def __init__(self):
self.time = datetime.utcnow()
self.tried = 0 # some event may push back to queue for re-process
def to_dict(self):
data = self.__dict__.copy()
for k in data.keys():
if type(data[k]) in (str, float, int) or data[k] is None:
pass
elif type(data[k]) is Decimal:
data[k] = float(data[k])
elif isinstance(data[k], datetime):
data[k] = 'datetime:%s' % data[k].strftime('%Y-%m-%d %H:%M:%S:%f')
else:
raise Exception('%s.%s is not serializable.' % (self.__class__.__name__, k))
data['type'] = self.type
return data
@staticmethod
def from_dict(data):
instance = Event()
for k in data.keys():
if type(data[k]) is int or data[k] is None:
pass
elif type(data[k]) is float:
data[k] = Decimal(str(data[k]))
elif type(data[k]) is str:
if data[k].startswith('datetime:'):
dt_str = data[k].replace('datetime:', '')
dt = parse(dt_str, date_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S:%f',
'%Y-%m-%dT%H:%M:%S'])
data[k] = dt or data[k]
else:
raise Exception('Event.from_dict %s=%s is not deserializable.' % (k, data[k]))
setattr(instance, k, data[k])
return instance
class StartUpEvent(Event):
type = EventType.STARTUP
class HeartBeatEvent(Event):
type = EventType.HEARTBEAT
def __init__(self, hearbeat_count=0):
super(HeartBeatEvent, self).__init__()
self.counter = hearbeat_count
class DebugEvent(Event):
type = EventType.DEBUG
def __init__(self, action):
super(DebugEvent, self).__init__()
self.action = action
class TimeFrameEvent(Event):
"""
timeframe={
1:2020-10-05 23:23:00
5:2020-10-05 23:25:00
}
"""
type = EventType.TIMEFRAME
def __init__(self, timeframes, current_time, previous, timezone, time):
super(TimeFrameEvent, self).__init__()
self.timeframes = timeframes if isinstance(timeframes, (list, tuple, set)) else (timeframes,)
self.current_time = current_time
self.previous = previous
self.timezone = timezone
self.time = time
class MarketEvent(Event):
type = EventType.MARKET
def __init__(self, action):
super(MarketEvent, self).__init__()
self.action = action
class TickEvent(Event):
type = EventType.TICK
def __init__(self, instrument, time, bid, ask):
self.instrument = instrument
self.time = time
self.bid = bid
self.ask = ask
super(TickEvent, self).__init__()
def __str__(self):
return "Type: %s, Instrument: %s, Time: %s, Bid: %s, Ask: %s" % (
str(self.type), str(self.instrument),
str(self.time), str(self.bid), str(self.ask)
)
class TickPriceEvent(Event):
type = EventType.TICK_PRICE
def __init__(self, broker, instrument, time, bid, ask):
super(TickPriceEvent, self).__init__()
self.broker = broker
self.instrument = instrument
self.time = time
self.bid = bid
self.ask = ask
def __str__(self):
return "Type: %s, Instrument: %s, Time: %s, Bid: %s, Ask: %s" % (
str(self.type), str(self.instrument),
str(self.time), str(self.bid), str(self.ask)
)
class SignalEvent(Event):
type = EventType.SIGNAL
def __init__(self, action, strategy_name, version, magic_number, instrument, side, price=None,
stop_loss=None, take_profit=None, trailing_stop=None, percent=None, trade_id=None,
order_type=None):
self.action = action
self.strategy = strategy_name
self.version = version
self.magic_number = magic_number
self.instrument = instrument
self.order_type = order_type
self.side = side
self.price = price
self.stop_loss = stop_loss
self.take_profit = take_profit
self.trailing_stop = trailing_stop
self.percent = percent
self.trade_id = trade_id
super(SignalEvent, self).__init__()
def __str__(self):
return "Type: %s, Instrument: %s, Order Type: %s, Side: %s" % (
str(self.type), str(self.instrument),
str(self.order_type), str(self.side)
)
class OrderUpdateEvent(Event):
"""order update signal"""
type = EventType.ORDER_CLOSE
def __init__(self, strategy_name, version, magic_number, instrument, stop_loss=None, take_profit=None,
trailing_stop=None, percent=None):
self.strategy = strategy_name
self.version = version
self.magic_number = magic_number
self.instrument = instrument
self.stop_loss = stop_loss
self.take_profit = take_profit
self.trailing_stop = trailing_stop
self.percent = percent
super(OrderUpdateEvent, self).__init__()
class OrderHoldingEvent(Event):
"""order holding, to notify strategy to calculate close signal"""
type = EventType.ORDER_HOLDING
def __init__(self, magic_number, orders):
self.orders = orders
self.magic_number = magic_number
super(OrderHoldingEvent, self).__init__()
class TradeCloseEvent(Event):
type = EventType.ORDER_CLOSE
def __init__(self, broker, account_id, trade_id, instrument, side, lots, profit, close_time, close_price, pips=None,
open_time=None):
self.broker = broker
self.account_id = account_id
self.trade_id = trade_id
self.instrument = get_mt4_symbol(instrument)
self.side = side
self.lots = lots
self.profit = Decimal(str(profit))
self.close_price = Decimal(str(close_price))
self.close_time = close_time
self.open_time = open_time
self.pips = Decimal(str(pips)) if pips else None
super(TradeCloseEvent, self).__init__()
def to_text(self):
last = ''
if self.open_time:
last = self.open_time - self.close_time
text = '%s#%s\n%s = %s\nprofit = %s' % (
self.instrument, self.trade_id, self.side, self.lots, self.profit)
if self.pips:
text += '\npips = %s' % self.pips
if last:
text += '\nlast = %s' % str(last)
return text
class TradeOpenEvent(Event):
type = EventType.TRADE_OPEN
def __init__(self, broker, account_id, trade_id, instrument, side, lots, open_time, open_price, stop_loss=None,
take_profit=None, magic_number=None):
self.broker = broker
self.account_id = account_id
self.trade_id = trade_id
self.instrument = get_mt4_symbol(instrument)
self.side = side
self.lots = lots
self.open_time = open_time
self.open_price = Decimal(str(open_price))
self.stop_loss = Decimal(str(stop_loss)) if stop_loss else None
self.take_profit = Decimal(str(take_profit)) if take_profit else None
self.magic_number = magic_number
super(TradeOpenEvent, self).__init__()
def to_text(self):
text = 'ST#%s\n%s#%s\n%s = %s\nprice = %s\nSL = %s\nTP = %s' % (
self.magic_number, self.instrument, self.trade_id, self.side, self.lots, self.open_price, self.stop_loss,
self.take_profit)
return text
class OrderEvent(Event):
type = EventType.ORDER
def __init__(self, instrument, units, order_type, side, expiry=None, price=None, lowerBound=None, upperBound=None,
stopLoss=None, takeProfit=None, trailingStop=None):
self.instrument = instrument
self.units = units
self.order_type = order_type
self.side = side
self.expiry = expiry
self.price = price
self.lowerBound = lowerBound
self.upperBound = upperBound
self.stopLoss = stopLoss
self.takeProfit = takeProfit
self.trailingStop = trailingStop
super(OrderEvent, self).__init__()
def __str__(self):
return "Type: %s, Instrument: %s, Units: %s, Order Type: %s, Side: %s" % (
str(self.type), str(self.instrument), str(self.units),
str(self.order_type), str(self.side)
)
class ConnectEvent(Event):
def __init__(self, action):
self.action = action.upper()
super(ConnectEvent, self).__init__()
class FillEvent(Event):
"""
When an BaseExecutionHandler receives an OrderEvent it must transact the order. Once an order has been transacted it generates a FillEvent, which describes the cost of purchase or sale as well as the transaction costs, such as fees or slippage.
The FillEvent is the Event with the greatest complexity. It contains a timestamp for when an order was filled, the symbol of the order and the exchange it was executed on, the quantity of shares transacted, the actual price of the purchase and the commission incurred.
Encapsulates the notion of a Filled Order, as returned
from a brokerage. Stores the quantity of an instrument
actually filled and at what price. In addition, stores
the commission of the trade from the brokerage.
"""
def __init__(self, timeindex, symbol, exchange, quantity,
direction, fill_cost, commission=None):
"""
Initialises the FillEvent object. Sets the symbol, exchange,
quantity, direction, cost of fill and an optional
commission.
If commission is not provided, the Fill object will
calculate it based on the trade size and Interactive
Brokers fees.
Parameters:
timeindex - The bar-resolution when the order was filled.
symbol - The instrument which was filled.
exchange - The exchange where the order was filled.
quantity - The filled quantity.
direction - The direction of fill ('BUY' or 'SELL')
fill_cost - The holdings value in dollars.
commission - An optional commission sent from IB.
"""
self.type = 'FILL'
self.timeindex = timeindex
self.symbol = symbol
self.exchange = exchange
self.quantity = quantity
self.direction = direction
self.fill_cost = fill_cost
# Calculate commission
if commission is None:
self.commission = self.calculate_ib_commission()
else:
self.commission = commission
def calculate_ib_commission(self):
"""
Calculates the fees of trading based on an Interactive
Brokers fee structure for API, in USD.
This does not include exchange or ECN fees.
Based on "US API Directed Orders":
https://www.interactivebrokers.com/en/index.php?f=commission&p=stocks2
"""
full_cost = 1.3
if self.quantity <= 500:
full_cost = max(1.3, 0.013 * self.quantity)
else: # Greater than 500
full_cost = max(1.3, 0.008 * self.quantity)
full_cost = min(full_cost, 0.5 / 100.0 * self.quantity * self.fill_cost)
return full_cost
|
[
"dateparser.parse",
"datetime.datetime.utcnow",
"mt4.constants.get_mt4_symbol"
] |
[((779, 796), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (794, 796), False, 'from datetime import datetime\n'), ((6577, 6603), 'mt4.constants.get_mt4_symbol', 'get_mt4_symbol', (['instrument'], {}), '(instrument)\n', (6591, 6603), False, 'from mt4.constants import get_mt4_symbol\n'), ((7687, 7713), 'mt4.constants.get_mt4_symbol', 'get_mt4_symbol', (['instrument'], {}), '(instrument)\n', (7701, 7713), False, 'from mt4.constants import get_mt4_symbol\n'), ((1878, 1994), 'dateparser.parse', 'parse', (['dt_str'], {'date_formats': "['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S:%f',\n '%Y-%m-%dT%H:%M:%S']"}), "(dt_str, date_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M',\n '%Y-%m-%d %H:%M:%S:%f', '%Y-%m-%dT%H:%M:%S'])\n", (1883, 1994), False, 'from dateparser import parse\n')]
|
import pandas
from sklearn.preprocessing import StandardScaler
import torch
import torch.nn.functional as F
import torch.optim as optim
# data preprocessing
data = pandas.read_csv('data/linear_800bytes_500_iterations.csv')
data = data.sort_values(by=['time_stamp'])
data = data.reset_index(drop=True)
X = data.values[:,1]
y = data.values[:,2]
for i in range(1, len(X)):
X[i] = X[i] + X[i - 1]
# scaling X
scaler = StandardScaler()
X_norm = scaler.fit_transform(X.reshape(-1,1))
m = X_norm.shape[0]
# define model
theta = torch.tensor(torch.rand(2).view(2,1), dtype=torch.float64, requires_grad=True)
X_input = torch.cat((torch.ones([m, 1], dtype=torch.float64), torch.tensor(X_norm)), dim=1)
y_input = torch.tensor(y).view(-1,1)
n_epochs = 2000
lr = 0.01
# use Gradient Descent as optimizer, registered theta as parameter that can be optimized
optimizer = optim.SGD([theta], lr=0.01)
for epoch in range(n_epochs):
# we set zero to clear gradient per epoch
optimizer.zero_grad()
y_pred = torch.mm(X_input, theta)
loss = F.mse_loss(y_pred, y_input)
# calculate gradient use pytorch autograd
loss.backward()
# call optimizer to update weight
optimizer.step()
if (epoch + 1) % 100 == 0:
print(epoch + 1, loss.item())
print(theta)
# stop autograd to track down our later calculation
theta.requires_grad_(False)
# number of bytes to predict
test_bytes = 10
# scaling test data
X_test = torch.cat((torch.ones([1, 1], dtype=torch.float64), torch.tensor(scaler.transform([[10]]))), dim=1)
# predict
y_test = torch.mm(X_test, theta)
print(y_test.item())
|
[
"torch.ones",
"sklearn.preprocessing.StandardScaler",
"pandas.read_csv",
"torch.nn.functional.mse_loss",
"torch.mm",
"torch.rand",
"torch.tensor",
"torch.optim.SGD"
] |
[((172, 230), 'pandas.read_csv', 'pandas.read_csv', (['"""data/linear_800bytes_500_iterations.csv"""'], {}), "('data/linear_800bytes_500_iterations.csv')\n", (187, 230), False, 'import pandas\n'), ((436, 452), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (450, 452), False, 'from sklearn.preprocessing import StandardScaler\n'), ((892, 919), 'torch.optim.SGD', 'optim.SGD', (['[theta]'], {'lr': '(0.01)'}), '([theta], lr=0.01)\n', (901, 919), True, 'import torch.optim as optim\n'), ((1630, 1653), 'torch.mm', 'torch.mm', (['X_test', 'theta'], {}), '(X_test, theta)\n', (1638, 1653), False, 'import torch\n'), ((1047, 1071), 'torch.mm', 'torch.mm', (['X_input', 'theta'], {}), '(X_input, theta)\n', (1055, 1071), False, 'import torch\n'), ((1084, 1111), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['y_pred', 'y_input'], {}), '(y_pred, y_input)\n', (1094, 1111), True, 'import torch.nn.functional as F\n'), ((650, 689), 'torch.ones', 'torch.ones', (['[m, 1]'], {'dtype': 'torch.float64'}), '([m, 1], dtype=torch.float64)\n', (660, 689), False, 'import torch\n'), ((691, 711), 'torch.tensor', 'torch.tensor', (['X_norm'], {}), '(X_norm)\n', (703, 711), False, 'import torch\n'), ((732, 747), 'torch.tensor', 'torch.tensor', (['y'], {}), '(y)\n', (744, 747), False, 'import torch\n'), ((1518, 1557), 'torch.ones', 'torch.ones', (['[1, 1]'], {'dtype': 'torch.float64'}), '([1, 1], dtype=torch.float64)\n', (1528, 1557), False, 'import torch\n'), ((562, 575), 'torch.rand', 'torch.rand', (['(2)'], {}), '(2)\n', (572, 575), False, 'import torch\n')]
|
import sublime
import urllib2
import json
import colt
import calendar, time
import os
import threading
from colt import ColtPreferences
runAfterAuthorization = None
statusToSet = "Disconnected from COLT"
class ColtConnection(object):
port = -1
messageId = 1
activeSessions = 0
def setStatus(status):
sublime.set_timeout(lambda: setStatus_(status), 0)
def setStatus_(status):
view = sublime.active_window().active_view()
if not view is None and not statusToSet is None :
view.erase_status("colt")
view.set_status("colt", status)
def coltStateUpdate():
if isConnected() :
ColtConnection.activeSessions = getActiveSessionsCount()
if ColtConnection.activeSessions > 0 :
# setStatus("COLT: " + str(ColtConnection.activeSessions) + " connections")
setStatus("[~] Connected to COLT")
else :
setStatus("Connected to COLT")
else :
setStatus("Disconnected from COLT")
def isConnected():
return ColtConnection.port != -1
def hasActiveSessions():
return ColtConnection.activeSessions > 0
def disconnect():
ColtConnection.port = -1
ColtConnection.messageId = 1
ColtConnection.activeSessions = 0
sublime.status_message("Disconnected from COLT")
def runAfterAuthorization():
if not runAfterAuthorization is None :
runAfterAuthorization()
runAfterAuthorization = None
return
def authorize(window):
if getSecurityToken() is None :
makeNewSecurityToken(True, window)
elif not runAfterAuthorization is None:
runAfterAuthorization()
def getSecurityToken():
settings = sublime.load_settings(ColtPreferences.NAME)
if not settings.has("securityToken") :
return None
return settings.get("securityToken")
def makeNewSecurityToken(newRequest, window):
onShortKeyInput('42')
# if newRequest :
# try :
# requestShortCode()
# except Exception :
# sublime.error_message("Authorization request failed. Make sure COLT is active and running.")
# return
#
# window.show_input_panel("Enter authorization code displayed in top of COLT window:", "", onShortKeyInput, None, None)
def onShortKeyInput(shortCode):
if shortCode :
try :
token = obtainAuthToken(shortCode)
if token is None :
sublime.error_message("Invalid short code entered")
authorize()
return
settings = sublime.load_settings(ColtPreferences.NAME)
settings.set("securityToken", token)
sublime.save_settings(ColtPreferences.NAME)
sublime.status_message("Successfully authorized with COLT")
runAfterAuthorization()
except Exception:
sublime.error_message("Unable to authorize with COLT. Make sure COLT is active and running")
return
else :
sublime.error_message("Short authorization key can't be empty")
authorize(sublime.active_window())
def obtainAuthToken(shortCode):
response = runRPC(ColtConnection.port, "obtainAuthToken", [ shortCode ])
if response.has_key("error") :
return None
return response["result"]
def requestShortCode():
runRPC(ColtConnection.port, "requestShortCode", [ "Sublime Plugin" ])
def runRPC(port, methodName, params):
jsonRequest = None
messageId = ColtConnection.messageId
ColtConnection.messageId += 1
if (params is None) :
jsonRequest = { "jsonrpc" : "2.0", "method" : methodName, "id": messageId }
else :
jsonRequest = { "jsonrpc" : "2.0", "method" : methodName, "params": params, "id": messageId }
jsonRequestStr = json.dumps(jsonRequest)
url = "http://localhost:" + str(port) + "/rpc/coltService"
req = urllib2.Request(url)
response = None
try :
response = urllib2.urlopen(req, jsonRequestStr)
except Exception :
disconnect()
raise
return json.loads(response.read())
def reload():
return runRPC(ColtConnection.port, "reload", [ getSecurityToken() ])
def clearLog():
return runRPC(ColtConnection.port, "clearLog", [ getSecurityToken() ])
def getMethodCounts():
return runRPC(ColtConnection.port, "getMethodCounts", [ getSecurityToken() ])
def getLastRuntimeError():
return runRPC(ColtConnection.port, "getLastRuntimeError", [ getSecurityToken() ])
def startLive():
securityToken = getSecurityToken()
if not getSecurityToken() is None :
try :
error = runRPC(ColtConnection.port, "startLive", [ securityToken ])["error"]["data"]["exceptionTypeName"]
if error == "codeOrchestra.colt.core.rpc.security.InvalidAuthTokenException" :
# auth code expired - we need new one
makeNewSecurityToken(True, sublime.active_window())
except KeyError :
# there was no error - good :)
return
def getState():
return runRPC(ColtConnection.port, "getState", None)
def getActiveSessionsCount():
try :
jsonState = getState()
return len(jsonState["result"]["activeConnections"])
except Exception :
return 0
def reloadScriptAt(filePath, position, currentContent):
return runRPC(ColtConnection.port, "reloadScriptAt", [ getSecurityToken(), filePath, position, currentContent ])
def getDeclarationPosition(filePath, position, currentContent):
return runRPC(ColtConnection.port, "getDeclarationPosition", [ getSecurityToken(), filePath, position, currentContent ])
def getContextForPosition(filePath, position, currentContent, contextType):
return runRPC(ColtConnection.port, "getContextForPosition", [ getSecurityToken(), filePath, position, currentContent, contextType ])
def evaluateExpression(filePath, expression, position, currentContent):
return runRPC(ColtConnection.port, "evaluateExpression", [ getSecurityToken(), filePath, expression, position, currentContent ])
def getCallCount(filePath, position, currentContent):
return runRPC(ColtConnection.port, "getCallCount", [ getSecurityToken(), filePath, position, currentContent ])
def resetCallCounts():
return runRPC(ColtConnection.port, "resetCallCounts", [ getSecurityToken() ])
def getEnclosingTagId(filePath, position, currentContent):
return runRPC(ColtConnection.port, "getEnclosingTagId", [ getSecurityToken(), filePath, position, currentContent ])
def findAndShowJavaDocs(filePath, position, currentContent):
return runRPC(ColtConnection.port, "findAndShowJavaDocs", [ getSecurityToken(), filePath, position, currentContent ])
def angularExpressionCompletion(tagId, leftExpression):
return runRPC(ColtConnection.port, "angularExpressionCompletion", [ getSecurityToken(), tagId, leftExpression ])
def angularDirectiveDeclaration(filePath, position, currentContent):
return runRPC(ColtConnection.port, "angularDirectiveDeclaration", [ getSecurityToken(), filePath, position, currentContent ])
def getLastLogMessages():
return runRPC(ColtConnection.port, "getLastLogMessages", [ getSecurityToken() ])
def getMethodId(filePath, position, currentContent):
resultJSON = runRPC(ColtConnection.port, "getMethodId", [ getSecurityToken(), filePath, position, currentContent ])
if resultJSON.has_key("error") :
return None
return resultJSON["result"]
def runMethod(methodId):
runRPC(ColtConnection.port, "runMethod", [ getSecurityToken(), methodId ])
def establishConnection(port):
ColtConnection.port = port
sublime.status_message("Established connection with COLT on port " + port)
#time.sleep(2)
def initAndConnect(settings, projectPath):
sublime.status_message("Trying to establish connection with COLT...")
port = locateCOLTServicePort(projectPath)
if not port is None :
establishConnection(port)
return port
colt.runCOLT(settings, projectPath)
timeout = 20
while timeout > 0 :
time.sleep(0.3)
timeout -= 0.3
port = locateCOLTServicePort(projectPath)
if not port is None :
establishConnection(port)
return port
sublime.error_message("Can't establish connection with COLT")
return None
def locateCOLTServicePort(projectPath):
port = getRPCPortForProject(projectPath)
if port is None :
return None
try :
runRPC(port, "ping", None)
except Exception:
return None
return port
def getRPCPortForProject(projectPath):
storageDir = colt.getProjectWorkingDir(projectPath)
if storageDir is None :
return None
rpcInfoFilePath = storageDir + os.sep + "rpc.info"
if not os.path.exists(rpcInfoFilePath) :
return None
timePassedSinceModification = int(calendar.timegm(time.gmtime())) - int(os.path.getmtime(rpcInfoFilePath))
if (timePassedSinceModification > 2) :
return None
with open(rpcInfoFilePath, "r") as rpcInfoFile :
return rpcInfoFile.read().split(":")[1]
def set_interval(func, sec):
def func_wrapper():
set_interval(func, sec)
func()
t = threading.Timer(sec, func_wrapper)
t.start()
return t
set_interval(coltStateUpdate, 0.8)
|
[
"threading.Timer",
"sublime.save_settings",
"time.gmtime",
"colt.getProjectWorkingDir",
"urllib2.Request",
"os.path.exists",
"json.dumps",
"time.sleep",
"sublime.active_window",
"sublime.status_message",
"sublime.load_settings",
"os.path.getmtime",
"sublime.error_message",
"colt.runCOLT",
"urllib2.urlopen"
] |
[((1268, 1316), 'sublime.status_message', 'sublime.status_message', (['"""Disconnected from COLT"""'], {}), "('Disconnected from COLT')\n", (1290, 1316), False, 'import sublime\n'), ((1694, 1737), 'sublime.load_settings', 'sublime.load_settings', (['ColtPreferences.NAME'], {}), '(ColtPreferences.NAME)\n', (1715, 1737), False, 'import sublime\n'), ((3844, 3867), 'json.dumps', 'json.dumps', (['jsonRequest'], {}), '(jsonRequest)\n', (3854, 3867), False, 'import json\n'), ((3942, 3962), 'urllib2.Request', 'urllib2.Request', (['url'], {}), '(url)\n', (3957, 3962), False, 'import urllib2\n'), ((7703, 7777), 'sublime.status_message', 'sublime.status_message', (["('Established connection with COLT on port ' + port)"], {}), "('Established connection with COLT on port ' + port)\n", (7725, 7777), False, 'import sublime\n'), ((7846, 7915), 'sublime.status_message', 'sublime.status_message', (['"""Trying to establish connection with COLT..."""'], {}), "('Trying to establish connection with COLT...')\n", (7868, 7915), False, 'import sublime\n'), ((8048, 8083), 'colt.runCOLT', 'colt.runCOLT', (['settings', 'projectPath'], {}), '(settings, projectPath)\n', (8060, 8083), False, 'import colt\n'), ((8325, 8386), 'sublime.error_message', 'sublime.error_message', (['"""Can\'t establish connection with COLT"""'], {}), '("Can\'t establish connection with COLT")\n', (8346, 8386), False, 'import sublime\n'), ((8721, 8759), 'colt.getProjectWorkingDir', 'colt.getProjectWorkingDir', (['projectPath'], {}), '(projectPath)\n', (8746, 8759), False, 'import colt\n'), ((9315, 9349), 'threading.Timer', 'threading.Timer', (['sec', 'func_wrapper'], {}), '(sec, func_wrapper)\n', (9330, 9349), False, 'import threading\n'), ((2993, 3056), 'sublime.error_message', 'sublime.error_message', (['"""Short authorization key can\'t be empty"""'], {}), '("Short authorization key can\'t be empty")\n', (3014, 3056), False, 'import sublime\n'), ((4013, 4049), 'urllib2.urlopen', 'urllib2.urlopen', (['req', 'jsonRequestStr'], {}), '(req, jsonRequestStr)\n', (4028, 4049), False, 'import urllib2\n'), ((8138, 8153), 'time.sleep', 'time.sleep', (['(0.3)'], {}), '(0.3)\n', (8148, 8153), False, 'import calendar, time\n'), ((8875, 8906), 'os.path.exists', 'os.path.exists', (['rpcInfoFilePath'], {}), '(rpcInfoFilePath)\n', (8889, 8906), False, 'import os\n'), ((411, 434), 'sublime.active_window', 'sublime.active_window', ([], {}), '()\n', (432, 434), False, 'import sublime\n'), ((2566, 2609), 'sublime.load_settings', 'sublime.load_settings', (['ColtPreferences.NAME'], {}), '(ColtPreferences.NAME)\n', (2587, 2609), False, 'import sublime\n'), ((2671, 2714), 'sublime.save_settings', 'sublime.save_settings', (['ColtPreferences.NAME'], {}), '(ColtPreferences.NAME)\n', (2692, 2714), False, 'import sublime\n'), ((2727, 2786), 'sublime.status_message', 'sublime.status_message', (['"""Successfully authorized with COLT"""'], {}), "('Successfully authorized with COLT')\n", (2749, 2786), False, 'import sublime\n'), ((3077, 3100), 'sublime.active_window', 'sublime.active_window', ([], {}), '()\n', (3098, 3100), False, 'import sublime\n'), ((9006, 9039), 'os.path.getmtime', 'os.path.getmtime', (['rpcInfoFilePath'], {}), '(rpcInfoFilePath)\n', (9022, 9039), False, 'import os\n'), ((2431, 2482), 'sublime.error_message', 'sublime.error_message', (['"""Invalid short code entered"""'], {}), "('Invalid short code entered')\n", (2452, 2482), False, 'import sublime\n'), ((2862, 2959), 'sublime.error_message', 'sublime.error_message', (['"""Unable to authorize with COLT. Make sure COLT is active and running"""'], {}), "(\n 'Unable to authorize with COLT. Make sure COLT is active and running')\n", (2883, 2959), False, 'import sublime\n'), ((8984, 8997), 'time.gmtime', 'time.gmtime', ([], {}), '()\n', (8995, 8997), False, 'import calendar, time\n'), ((4993, 5016), 'sublime.active_window', 'sublime.active_window', ([], {}), '()\n', (5014, 5016), False, 'import sublime\n')]
|
import os
import re
from typing import Dict
from typing import Union, List
import toml
from stnm.constants import HOME_PATH
from stnm.response import error_response, success_response
def get_config_path() -> str:
return os.path.abspath(os.path.join(HOME_PATH, "stnm.conf"))
def get_config() -> str:
with open(get_config_path(), "r") as f:
config_contents = f.read()
f.close()
return config_contents
def get_config_parsed() -> Dict:
with open(get_config_path(), "r") as f:
config_contents = f.read()
f.close()
return toml.loads(config_contents)
def put_config_parsed(obj: Dict):
with open(get_config_path(), "w") as f:
f.write(toml.dumps(obj))
f.close()
"""
Config Input Structure
+---------------------+
| parameter |
+---------------------+
input = burnchain.burn_fee_cap=20000000
|section | key | value |
+-----------------------------+
| config entry |
+-----------------------------+
"""
class InvalidConfigEntry(Exception):
pass
class UnavailableConfigParameter(Exception):
pass
class InvalidValue(Exception):
pass
def bool_validator(s: str) -> bool:
if s in ["true", "True"]:
return True
if s in ["false", "False"]:
return False
raise InvalidValue("{} is not a valid boolean value. Use True or true or False or false".format(s))
def str_validator(s: str) -> str:
return s
def int_validator(s: str):
if re.compile("^[0-9]+$").match(s):
return int(s)
raise InvalidValue("{} is not a valid integer value".format(s))
AVAILABLE_PARAMS = {
"node.miner": bool_validator,
"node.seed": str_validator,
"burnchain.burn_fee_cap": int_validator,
"burnchain.process_exit_at_block_height": int_validator,
"burnchain.rpc_port": int_validator,
"burnchain.peer_port": int_validator
}
class ConfigEntry:
def __init__(self, section: str, key: str, value: Union[str, int, bool]):
self.section = section
self.key = key
self.value = value
def __repr__(self):
return "<{}.{}={}>".format(self.section, self.key, self.value)
def config_input_parser(input_: str) -> List[ConfigEntry]:
rv = []
entries = input_.split(",")
for entry in entries:
param_split = entry.split("=")
if len(param_split) != 2:
raise InvalidConfigEntry(entry)
[param, raw_value] = param_split
if param not in AVAILABLE_PARAMS:
raise UnavailableConfigParameter(param)
value = AVAILABLE_PARAMS[param](raw_value)
[section, key] = param.split(".")
rv.append(ConfigEntry(section, key, value))
return rv
def config(input_: str):
if input_ == "show":
config_contents = get_config()
print("-" * 60)
print("Config file located at: {}".format(get_config_path()))
print("-" * 60)
print(config_contents)
print("-" * 60)
return
try:
entries = config_input_parser(input_)
except InvalidConfigEntry as ex:
error_response(5, str(ex))
return
except UnavailableConfigParameter as ex:
error_response(6, str(ex))
return
except InvalidValue as ex:
error_response(7, str(ex))
return
parsed = get_config_parsed()
for e in entries:
parsed[e.section][e.key] = e.value
parsed["__modified__"] = True
put_config_parsed(parsed)
success_response(4)
|
[
"toml.dumps",
"stnm.response.success_response",
"toml.loads",
"os.path.join",
"re.compile"
] |
[((578, 605), 'toml.loads', 'toml.loads', (['config_contents'], {}), '(config_contents)\n', (588, 605), False, 'import toml\n'), ((3550, 3569), 'stnm.response.success_response', 'success_response', (['(4)'], {}), '(4)\n', (3566, 3569), False, 'from stnm.response import error_response, success_response\n'), ((244, 280), 'os.path.join', 'os.path.join', (['HOME_PATH', '"""stnm.conf"""'], {}), "(HOME_PATH, 'stnm.conf')\n", (256, 280), False, 'import os\n'), ((702, 717), 'toml.dumps', 'toml.dumps', (['obj'], {}), '(obj)\n', (712, 717), False, 'import toml\n'), ((1554, 1576), 're.compile', 're.compile', (['"""^[0-9]+$"""'], {}), "('^[0-9]+$')\n", (1564, 1576), False, 'import re\n')]
|
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import cv2
from PIL import Image
import os
def label_to_name(labels, names):
"""
Utility function to map label to corresponding name
"""
arr_map = []
for i in range(0, labels.shape[0]):
label = labels[i]
name = names[names["ClassId"] == label]["SignName"].values[0]
arr_map.append({"id":i, "label":label, "name":name})
return pd.DataFrame(arr_map)
def label_count(mappings):
"""
Utility function to count labels in different classes
"""
return pd.pivot_table(mappings, index = ["label", "name"], values = ["id"], aggfunc = "count")
def show_random_dataset_images(group_label, imgs, to_show=7):
"""
This function takes a DataFrame of items group by labels as well as a set of images and randomly selects to_show images to display
"""
for (lid, lbl), group in group_label:
#print("[{0}] : {1}".format(lid, lbl))
rand_idx = np.random.randint(0, high=group['id'].size, size=to_show, dtype='int')
selected_rows = group.iloc[rand_idx]
selected_img = list(map(lambda id: imgs[id], selected_rows['id']))
selected_labels = list(map(lambda label: label, selected_rows['label']))
show_image_list(selected_img, selected_labels, "{0}: {1}".format(lid, lbl), cols=to_show, fig_size=(9, 9), show_ticks=False)
def show_image_list(img_list, img_labels, title, cols=2, fig_size=(15, 15), show_ticks=True):
"""
Utility function to show us a list of traffic sign images
"""
img_count = len(img_list)
rows = img_count // cols
cmap = None
fig, axes = plt.subplots(rows, cols, figsize=fig_size)
for i in range(0, img_count):
img_name = img_labels[i]
img = img_list[i]
if len(img.shape) < 3 or img.shape[-1] < 3:
cmap = "gray"
img = np.reshape(img, (img.shape[0], img.shape[1]))
if not show_ticks:
axes[i].axis("off")
axes[i].imshow(img, cmap=cmap)
fig.suptitle(title, fontsize=12, fontweight='bold', y = 0.6)
fig.tight_layout()
plt.show()
def grayscale(imgs):
"""
Converts an image in RGB format to grayscale
"""
return cv2.cvtColor(imgs, cv2.COLOR_RGB2GRAY)
def standard_normalization(imgs, dist):
"""
Nornalise the supplied images from data in dist
"""
std = np.std(dist)
mean = np.mean(dist)
return (imgs - mean) / std
def plot_model_results(metrics, axes, lbs, xlb, ylb, titles, fig_title, fig_size=(7, 5), epochs_interval=10):
"""
Nifty utility function to plot results of the execution of our model
"""
fig, axs = plt.subplots(nrows=1, ncols=len(axes), figsize=fig_size)
print("Length of axis: {0}".format(axs.shape))
total_epochs = metrics[0].shape[0]
x_values = np.linspace(1, total_epochs, num=total_epochs, dtype=np.int32)
for m, l in zip(metrics, lbs):
for i in range(0, len(axes)):
ax = axs[i]
axis = axes[i]
ax.plot(x_values, m[:, axis], linewidth=2, label=l)
ax.set(xlabel=xlb[i], ylabel=ylb[i], title=titles[i])
ax.xaxis.set_ticks(np.linspace(1, total_epochs, num=int(total_epochs/epochs_interval), dtype=np.int32))
ax.legend(loc='center right')
plt.suptitle(fig_title, fontsize=14, fontweight='bold')
plt.show()
def load_images(path, size=(32, 32), grayscale=False):
"""
Returns a list of images from a folder as a numpy array
"""
img_list = [os.path.join(path,f) for f in os.listdir(path) if f.endswith(".jpg") or f.endswith(".png")]
imgs = None
if grayscale:
imgs = np.empty([len(img_list), size[0], size[1]], dtype=np.uint8)
else:
imgs = np.empty([len(img_list), size[0], size[1], 3], dtype=np.uint8)
for i, img_path in enumerate(img_list):
img = Image.open(img_path).convert('RGB')
img = img.resize(size)
im = np.array(to_grayscale(img)) if grayscale else np.array(img)
imgs[i] = im
return imgs
def class_to_name(class_ids, sign_names):
return list(map(lambda class_id: sign_names[sign_names["ClassId"] == class_id] ["SignName"].values[0], class_ids))
|
[
"pandas.DataFrame",
"matplotlib.pyplot.show",
"pandas.pivot_table",
"os.path.join",
"cv2.cvtColor",
"numpy.std",
"matplotlib.pyplot.suptitle",
"PIL.Image.open",
"numpy.mean",
"numpy.random.randint",
"numpy.reshape",
"numpy.linspace",
"numpy.array",
"matplotlib.pyplot.subplots",
"os.listdir"
] |
[((416, 437), 'pandas.DataFrame', 'pd.DataFrame', (['arr_map'], {}), '(arr_map)\n', (428, 437), True, 'import pandas as pd\n'), ((540, 626), 'pandas.pivot_table', 'pd.pivot_table', (['mappings'], {'index': "['label', 'name']", 'values': "['id']", 'aggfunc': '"""count"""'}), "(mappings, index=['label', 'name'], values=['id'], aggfunc=\n 'count')\n", (554, 626), True, 'import pandas as pd\n'), ((1627, 1669), 'matplotlib.pyplot.subplots', 'plt.subplots', (['rows', 'cols'], {'figsize': 'fig_size'}), '(rows, cols, figsize=fig_size)\n', (1639, 1669), True, 'from matplotlib import pyplot as plt\n'), ((2144, 2154), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2152, 2154), True, 'from matplotlib import pyplot as plt\n'), ((2254, 2292), 'cv2.cvtColor', 'cv2.cvtColor', (['imgs', 'cv2.COLOR_RGB2GRAY'], {}), '(imgs, cv2.COLOR_RGB2GRAY)\n', (2266, 2292), False, 'import cv2\n'), ((2413, 2425), 'numpy.std', 'np.std', (['dist'], {}), '(dist)\n', (2419, 2425), True, 'import numpy as np\n'), ((2437, 2450), 'numpy.mean', 'np.mean', (['dist'], {}), '(dist)\n', (2444, 2450), True, 'import numpy as np\n'), ((2865, 2927), 'numpy.linspace', 'np.linspace', (['(1)', 'total_epochs'], {'num': 'total_epochs', 'dtype': 'np.int32'}), '(1, total_epochs, num=total_epochs, dtype=np.int32)\n', (2876, 2927), True, 'import numpy as np\n'), ((3354, 3409), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['fig_title'], {'fontsize': '(14)', 'fontweight': '"""bold"""'}), "(fig_title, fontsize=14, fontweight='bold')\n", (3366, 3409), True, 'from matplotlib import pyplot as plt\n'), ((3414, 3424), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3422, 3424), True, 'from matplotlib import pyplot as plt\n'), ((955, 1025), 'numpy.random.randint', 'np.random.randint', (['(0)'], {'high': "group['id'].size", 'size': 'to_show', 'dtype': '"""int"""'}), "(0, high=group['id'].size, size=to_show, dtype='int')\n", (972, 1025), True, 'import numpy as np\n'), ((3576, 3597), 'os.path.join', 'os.path.join', (['path', 'f'], {}), '(path, f)\n', (3588, 3597), False, 'import os\n'), ((1869, 1914), 'numpy.reshape', 'np.reshape', (['img', '(img.shape[0], img.shape[1])'], {}), '(img, (img.shape[0], img.shape[1]))\n', (1879, 1914), True, 'import numpy as np\n'), ((3606, 3622), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (3616, 3622), False, 'import os\n'), ((4053, 4066), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (4061, 4066), True, 'import numpy as np\n'), ((3927, 3947), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (3937, 3947), False, 'from PIL import Image\n')]
|
import textmining
import numpy
import sklearn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
m=[]
p=0
with open ("ess1.txt", "r") as myfile:
doc1=myfile.read()
#doc1=myfile.read().replace('\n', '')
with open ("ess2.txt", "r") as myfile:
doc2=myfile.read()
#doc2=myfile.read().replace('\n', '')
# Initialize class to create term-document matrix
tdm = textmining.TermDocumentMatrix()
# Add the documents
tdm.add_doc(doc1)
tdm.add_doc(doc2)
# Write out the matrix to a csv file. Note that setting cutoff=1 means
# that words which appear in 1 or more documents will be included in
# the output (i.e. every word will appear in the output). The default
# for cutoff is 2, since we usually aren't interested in words which
# appear in a single document. For this example we want to see all
# words however, hence cutoff=1.
tdm.write_csv('matrix.csv', cutoff=1)
# Instead of writing out the matrix you can also access its rows directly.
# Let's print them to the screen.
for row in tdm.rows(cutoff=1):
m.append(row)
if p==1:
arr = row
#print("p")
#print("arr=row")
#print(arr)
#print("")
p=p+1
if p>1:
arr = numpy.vstack((arr, row))
#print(p)
#print("arr = numpy.vstack((arr, row))")
#print(arr)
#print("")
p=p+1
if p==0:
#print(p)
#print("Just Increment p .... Voila !")
#print("")
p=p+1
#arr = numpy.delete(arr, (0), axis=0)
p=0
#arr = numpy.delete(arr, (0), axis=0)
print("")
print("TDM:")
print(m)
print("")
print("")
print("")
print("TDM Sparse Matrix:")
print(arr)
transformer = TfidfTransformer()
tfidf = transformer.fit_transform(arr)
a = tfidf.toarray()
numpy.savetxt("foo.csv", a, delimiter=",")
print(tfidf.toarray())
|
[
"textmining.TermDocumentMatrix",
"numpy.savetxt",
"sklearn.feature_extraction.text.TfidfTransformer",
"numpy.vstack"
] |
[((460, 491), 'textmining.TermDocumentMatrix', 'textmining.TermDocumentMatrix', ([], {}), '()\n', (489, 491), False, 'import textmining\n'), ((1803, 1821), 'sklearn.feature_extraction.text.TfidfTransformer', 'TfidfTransformer', ([], {}), '()\n', (1819, 1821), False, 'from sklearn.feature_extraction.text import TfidfTransformer\n'), ((1884, 1926), 'numpy.savetxt', 'numpy.savetxt', (['"""foo.csv"""', 'a'], {'delimiter': '""","""'}), "('foo.csv', a, delimiter=',')\n", (1897, 1926), False, 'import numpy\n'), ((1306, 1330), 'numpy.vstack', 'numpy.vstack', (['(arr, row)'], {}), '((arr, row))\n', (1318, 1330), False, 'import numpy\n')]
|
import asyncio
import logging
from dataclasses import dataclass
from time import time
from typing import Any, Awaitable, Dict, Optional, Sequence
from aioprometheus import Gauge
from aioprometheus.collectors import Registry
from bleak import BleakClient, BleakScanner
from bleak.backends.device import BLEDevice
from bleak.exc import BleakError
LOG = logging.getLogger(__name__)
# 1309,327,327,328,327,32,39,0,79,000000
@dataclass(frozen=True)
class Li3TelemetryStats:
battery_voltage: float
cell_1_voltage: float
cell_2_voltage: float
cell_3_voltage: float
cell_4_voltage: float
bms_temperature: float
battery_temperature: float
battery_power: float # This will be amps or watts ...
battery_soc: float
fault_code: int # This is hex converted to an int
class Li3Battery:
def __init__(
self,
dev_name: str,
mac_address: str,
service_uuid: str,
characteristic: str,
timeout: float,
) -> None:
self.bleak_device: Optional[BLEDevice] = None
self.dev_name = dev_name
self.mac_address = mac_address
self.float = timeout
self.service_uuid = service_uuid
self.characteristic = characteristic
self.timeout = timeout
self.str_data = ""
self.stats: Optional[Li3TelemetryStats] = None
def _telementary_handler(self, sender: str, data: bytes) -> None:
self.raw_data = data
tmp_str_data = data.decode("ascii")
if tmp_str_data.startswith(","):
self.str_data += tmp_str_data.strip()
csv_data = self.str_data.split(",")
self.stats = Li3TelemetryStats(
float(csv_data[0]) / 100,
float(csv_data[1]) / 100,
float(csv_data[2]) / 100,
float(csv_data[3]) / 100,
float(csv_data[4]) / 100,
float(csv_data[5]),
float(csv_data[6]),
float(csv_data[7]),
float(csv_data[8]),
int(csv_data[9], 16),
)
# no idea what &,1,114,006880 is.. throw it away for now
elif "&" not in tmp_str_data:
self.str_data = tmp_str_data
async def listen(self) -> None:
if not self.bleak_device:
raise BleakError(f"{self.dev_name} was not found in bleak scan!")
LOG.info(f"Attempting to start a notify for {self.dev_name}")
started_notify_uuid = ""
async with BleakClient(self.bleak_device) as client:
services = await client.get_services()
for service in services:
if service.uuid != self.service_uuid:
continue
for characteristic in service.characteristics:
if characteristic.uuid == self.characteristic:
LOG.info(
f"Starting notify for {self.dev_name}:{self.service_uuid}:"
+ f"{self.characteristic}"
)
await client.start_notify(
characteristic.uuid, self._telementary_handler
)
started_notify_uuid = characteristic.uuid
if not started_notify_uuid:
LOG.error(
f"{self.dev_name} is not listening to {started_notify_uuid}!!"
)
return
# Block while we read Bluetooth LE
# TODO: Find if a better asyncio way to allow clean exit
# Always cleanup the notify
try:
while True:
await asyncio.sleep(1)
finally:
LOG.info(f"Cleaning up bleak notify for {started_notify_uuid}")
await client.stop_notify(started_notify_uuid)
class RevelBatteries:
def __init__(
self, config: Dict, registry: Registry, stat_preifx: str = "li3_"
) -> None:
self.config = config
self.prom_registry = registry
self.stat_preifx = stat_preifx
self.batteries = []
for id, battery_settings in self.config["li3"].items():
LOG.debug(f"Loading battery {id}: {battery_settings}")
self.batteries.append(Li3Battery(**battery_settings))
self.prom_stats = {
"battery_voltage": Gauge(
f"{self.stat_preifx}battery_voltage",
"Current volts of the battery",
registry=self.prom_registry,
),
"cell_1_voltage": Gauge(
f"{self.stat_preifx}cell_1_voltage",
"Battery Cell 1 Voltage",
registry=self.prom_registry,
),
"cell_2_voltage": Gauge(
f"{self.stat_preifx}cell_2_voltage",
"Battery Cell 2 Voltage",
registry=self.prom_registry,
),
"cell_3_voltage": Gauge(
f"{self.stat_preifx}cell_3_voltage",
"Battery Cell 3 Voltage",
registry=self.prom_registry,
),
"cell_4_voltage": Gauge(
f"{self.stat_preifx}cell_4_voltage",
"Battery Cell 4 Voltage",
registry=self.prom_registry,
),
"bms_temperature": Gauge(
f"{self.stat_preifx}bms_temperature",
"The temperature of the BMS",
registry=self.prom_registry,
),
"battery_temperature": Gauge(
f"{self.stat_preifx}battery_temperature",
"Battery temperature - Remember won't charge if to cold/hot",
registry=self.prom_registry,
),
"battery_power": Gauge(
f"{self.stat_preifx}battery_power",
"Battery current power charge or draw",
registry=self.prom_registry,
),
"battery_soc": Gauge(
f"{self.stat_preifx}battery_soc",
"Percentage of battery charge left",
registry=self.prom_registry,
),
"fault_code": Gauge(
f"{self.stat_preifx}fault_code",
"Type of Battery fault (Hex converted to int)",
registry=self.prom_registry,
),
}
async def scan_devices(self, scan_time: float) -> None:
service_uuids = {b.service_uuid for b in self.batteries}
LOG.info(f"Scanning for BLE Batteries with service_uuids {service_uuids}")
scanner = BleakScanner(service_uuids=service_uuids)
discovered_devices = await scanner.discover(timeout=scan_time)
found_devs = 0
for dd in discovered_devices:
for b in self.batteries:
if dd.address == b.mac_address:
b.bleak_device = dd
found_devs += 1
continue
LOG.info(f"Found {found_devs} BLE Batteries with service_uuids {service_uuids}")
async def stats_refresh(self, refresh_interval: float) -> None:
while True:
stat_collect_start_time = time()
for battery in self.batteries:
if not battery.stats:
LOG.error(
f"{battery.dev_name} does not have valid stats ... skipping."
)
continue
for stat_name, prom_metric in self.prom_stats.items():
prom_metric.set(
{
"dev_name": battery.dev_name,
"mac_address": battery.mac_address,
"characteristic": battery.characteristic,
"service_uuid": battery.service_uuid,
},
getattr(battery.stats, stat_name),
)
LOG.info(f"Updated {battery.dev_name} stats")
run_time = time() - stat_collect_start_time
sleep_time = (
refresh_interval - run_time if run_time < refresh_interval else 0
)
LOG.info(
f"{RevelBatteries.__name__} has refreshed prometheus stats in {run_time}s. "
+ f"Sleeping for {sleep_time}s"
)
await asyncio.sleep(sleep_time)
async def get_awaitables(self, refresh_interval: float) -> Sequence[Awaitable[Any]]:
coros = [self.stats_refresh(refresh_interval)]
coros.extend([b.listen() for b in self.batteries])
return coros
|
[
"bleak.exc.BleakError",
"aioprometheus.Gauge",
"bleak.BleakScanner",
"asyncio.sleep",
"logging.getLogger",
"time.time",
"bleak.BleakClient",
"dataclasses.dataclass"
] |
[((354, 381), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (371, 381), False, 'import logging\n'), ((426, 448), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (435, 448), False, 'from dataclasses import dataclass\n'), ((6604, 6645), 'bleak.BleakScanner', 'BleakScanner', ([], {'service_uuids': 'service_uuids'}), '(service_uuids=service_uuids)\n', (6616, 6645), False, 'from bleak import BleakClient, BleakScanner\n'), ((2317, 2376), 'bleak.exc.BleakError', 'BleakError', (['f"""{self.dev_name} was not found in bleak scan!"""'], {}), "(f'{self.dev_name} was not found in bleak scan!')\n", (2327, 2376), False, 'from bleak.exc import BleakError\n'), ((2500, 2530), 'bleak.BleakClient', 'BleakClient', (['self.bleak_device'], {}), '(self.bleak_device)\n', (2511, 2530), False, 'from bleak import BleakClient, BleakScanner\n'), ((4387, 4495), 'aioprometheus.Gauge', 'Gauge', (['f"""{self.stat_preifx}battery_voltage"""', '"""Current volts of the battery"""'], {'registry': 'self.prom_registry'}), "(f'{self.stat_preifx}battery_voltage', 'Current volts of the battery',\n registry=self.prom_registry)\n", (4392, 4495), False, 'from aioprometheus import Gauge\n'), ((4586, 4687), 'aioprometheus.Gauge', 'Gauge', (['f"""{self.stat_preifx}cell_1_voltage"""', '"""Battery Cell 1 Voltage"""'], {'registry': 'self.prom_registry'}), "(f'{self.stat_preifx}cell_1_voltage', 'Battery Cell 1 Voltage',\n registry=self.prom_registry)\n", (4591, 4687), False, 'from aioprometheus import Gauge\n'), ((4778, 4879), 'aioprometheus.Gauge', 'Gauge', (['f"""{self.stat_preifx}cell_2_voltage"""', '"""Battery Cell 2 Voltage"""'], {'registry': 'self.prom_registry'}), "(f'{self.stat_preifx}cell_2_voltage', 'Battery Cell 2 Voltage',\n registry=self.prom_registry)\n", (4783, 4879), False, 'from aioprometheus import Gauge\n'), ((4970, 5071), 'aioprometheus.Gauge', 'Gauge', (['f"""{self.stat_preifx}cell_3_voltage"""', '"""Battery Cell 3 Voltage"""'], {'registry': 'self.prom_registry'}), "(f'{self.stat_preifx}cell_3_voltage', 'Battery Cell 3 Voltage',\n registry=self.prom_registry)\n", (4975, 5071), False, 'from aioprometheus import Gauge\n'), ((5162, 5263), 'aioprometheus.Gauge', 'Gauge', (['f"""{self.stat_preifx}cell_4_voltage"""', '"""Battery Cell 4 Voltage"""'], {'registry': 'self.prom_registry'}), "(f'{self.stat_preifx}cell_4_voltage', 'Battery Cell 4 Voltage',\n registry=self.prom_registry)\n", (5167, 5263), False, 'from aioprometheus import Gauge\n'), ((5355, 5461), 'aioprometheus.Gauge', 'Gauge', (['f"""{self.stat_preifx}bms_temperature"""', '"""The temperature of the BMS"""'], {'registry': 'self.prom_registry'}), "(f'{self.stat_preifx}bms_temperature', 'The temperature of the BMS',\n registry=self.prom_registry)\n", (5360, 5461), False, 'from aioprometheus import Gauge\n'), ((5557, 5704), 'aioprometheus.Gauge', 'Gauge', (['f"""{self.stat_preifx}battery_temperature"""', '"""Battery temperature - Remember won\'t charge if to cold/hot"""'], {'registry': 'self.prom_registry'}), '(f\'{self.stat_preifx}battery_temperature\',\n "Battery temperature - Remember won\'t charge if to cold/hot", registry=\n self.prom_registry)\n', (5562, 5704), False, 'from aioprometheus import Gauge\n'), ((5789, 5903), 'aioprometheus.Gauge', 'Gauge', (['f"""{self.stat_preifx}battery_power"""', '"""Battery current power charge or draw"""'], {'registry': 'self.prom_registry'}), "(f'{self.stat_preifx}battery_power',\n 'Battery current power charge or draw', registry=self.prom_registry)\n", (5794, 5903), False, 'from aioprometheus import Gauge\n'), ((5991, 6100), 'aioprometheus.Gauge', 'Gauge', (['f"""{self.stat_preifx}battery_soc"""', '"""Percentage of battery charge left"""'], {'registry': 'self.prom_registry'}), "(f'{self.stat_preifx}battery_soc', 'Percentage of battery charge left',\n registry=self.prom_registry)\n", (5996, 6100), False, 'from aioprometheus import Gauge\n'), ((6187, 6311), 'aioprometheus.Gauge', 'Gauge', (['f"""{self.stat_preifx}fault_code"""', '"""Type of Battery fault (Hex converted to int)"""'], {'registry': 'self.prom_registry'}), "(f'{self.stat_preifx}fault_code',\n 'Type of Battery fault (Hex converted to int)', registry=self.prom_registry\n )\n", (6192, 6311), False, 'from aioprometheus import Gauge\n'), ((7184, 7190), 'time.time', 'time', ([], {}), '()\n', (7188, 7190), False, 'from time import time\n'), ((8026, 8032), 'time.time', 'time', ([], {}), '()\n', (8030, 8032), False, 'from time import time\n'), ((8377, 8402), 'asyncio.sleep', 'asyncio.sleep', (['sleep_time'], {}), '(sleep_time)\n', (8390, 8402), False, 'import asyncio\n'), ((3685, 3701), 'asyncio.sleep', 'asyncio.sleep', (['(1)'], {}), '(1)\n', (3698, 3701), False, 'import asyncio\n')]
|
from PyQt5 import QtWidgets
from concertista.AboutDialog import AboutDialog
def test_about_dialog(main_window):
about_dlg = AboutDialog(main_window)
assert isinstance(about_dlg, AboutDialog)
assert about_dlg.windowTitle() == 'About'
assert isinstance(about_dlg._layout, QtWidgets.QVBoxLayout)
|
[
"concertista.AboutDialog.AboutDialog"
] |
[((130, 154), 'concertista.AboutDialog.AboutDialog', 'AboutDialog', (['main_window'], {}), '(main_window)\n', (141, 154), False, 'from concertista.AboutDialog import AboutDialog\n')]
|
from replace_expression import main
def replace_lexical_cast(line, file_dir, iteration):
if iteration == 0:
if "lexical_cast" in line and ("std::string" in line or "std::wstring" in line):
line = line.replace("< ", "<").replace(" >", ">")
line = line.replace("lexical_cast<std::string>", "std::to_string")
line = line.replace("lexical_cast<std::wstring>", "std::to_wstring")
line = line.replace("boost::std", "std")
else:
if "boost/lexical_cast.hpp" in line:
return None
if "using boost::lexical_cast;" in line:
return None
if "lexical_cast<" in line:
raise Exception(
"won't remove header boost/lexical_cast.hpp. it seems to be used."
)
return line
if __name__ == "__main__":
main(replace_lexical_cast, num_iterations=2)
|
[
"replace_expression.main"
] |
[((866, 910), 'replace_expression.main', 'main', (['replace_lexical_cast'], {'num_iterations': '(2)'}), '(replace_lexical_cast, num_iterations=2)\n', (870, 910), False, 'from replace_expression import main\n')]
|
import logging
import numpy as np
from typing import List, Tuple, Union
from autoarray import exc
from autoarray.mask import abstract_mask, mask_2d
from autoarray.structures.grids.one_d import grid_1d
from autoarray.structures.grids.one_d import grid_1d_util
from autoarray.structures.arrays.one_d import array_1d_util
logging.basicConfig()
logger = logging.getLogger(__name__)
class AbstractMask1d(abstract_mask.AbstractMask):
def __new__(
cls,
mask: np.ndarray,
pixel_scales: Tuple[float,],
sub_size: int = 1,
origin: Tuple[float,] = (0.0,),
):
"""
A 1D mask, representing 1D data on a uniform line of pixels with equal spacing.
When applied to 1D data it extracts or masks the unmasked image pixels corresponding to mask entries that
are `False` or 0).
The mask also defines the geometry of the 1D data structure it is paired to, for example how every pixel
coordinate on the 1D line of data converts to physical units via the `pixel_scales` and `origin`
parameters and a sub-grid which is used for performing calculations via super-sampling.
Parameters
----------
mask
The ndarray of shape [total_pixels] containing the bool's representing the mask, where `False`
signifies an entry is unmasked and used in calculations.
pixel_scales
The scaled units to pixel units conversion factor of each pixel.
origin
The x origin of the mask's coordinate system in scaled units.
"""
# noinspection PyArgumentList
return abstract_mask.AbstractMask.__new__(
cls=cls,
mask=mask,
pixel_scales=pixel_scales,
sub_size=sub_size,
origin=origin,
)
def __array_finalize__(self, obj):
super().__array_finalize__(obj=obj)
if isinstance(obj, Mask1D):
pass
else:
self.origin = (0.0,)
@property
def shape_native(self) -> Tuple[int]:
return self.shape
@property
def sub_shape_native(self) -> Tuple[int]:
return (self.shape[0] * self.sub_size,)
@property
def mask_sub_1(self) -> "Mask1D":
"""
Returns the mask on the same scaled coordinate system but with a sub-grid of `sub_size`.
"""
return Mask1D(
mask=self, sub_size=1, pixel_scales=self.pixel_scales, origin=self.origin
)
@property
def unmasked_mask(self) -> "Mask1D":
return Mask1D.unmasked(
shape_slim=self.shape_slim,
sub_size=self.sub_size,
pixel_scales=self.pixel_scales,
origin=self.origin,
)
@property
def unmasked_grid_sub_1(self) -> grid_1d.Grid1D:
"""
The scaled-grid of (y,x) coordinates of every pixel.
This is defined from the top-left corner, such that the first pixel at location [0, 0] will have a negative x
value y value in scaled units.
"""
grid_slim = grid_1d_util.grid_1d_slim_via_mask_from(
mask_1d=self, pixel_scales=self.pixel_scales, sub_size=1, origin=self.origin
)
return grid_1d.Grid1D(grid=grid_slim, mask=self.unmasked_mask.mask_sub_1)
@property
def to_mask_2d(self) -> mask_2d.Mask2D:
"""
Map the Mask1D to a Mask2D of shape [total_mask_1d_pixel, 1].
The change in shape and dimensions of the mask is necessary for mapping results from 1D data structures to 2D.
Returns
-------
mask_2d.Mask2D
The 1D mask mapped to a 2D mask of shape [total_mask_1d_pixel, 1].
"""
return mask_2d.Mask2D.manual(
[self],
pixel_scales=(self.pixel_scale, self.pixel_scale),
sub_size=self.sub_size,
origin=(0.0, 0.0),
)
def output_to_fits(self, file_path: str, overwrite: bool = False):
"""
Write the 1D mask to a .fits file.
Parameters
----------
file_path
The full path of the file that is output, including the file name and .fits extension.
overwrite
If `True` and a file already exists with the input file_path the .fits file is overwritten. If `False`,
an error is raised.
Returns
-------
None
Examples
--------
mask = Mask1D(mask=np.full(shape=(5,), fill_value=False))
mask.output_to_fits(file_path='/path/to/file/filename.fits', overwrite=True)
"""
array_1d_util.numpy_array_1d_to_fits(
array_1d=self.astype("float"), file_path=file_path, overwrite=overwrite
)
class Mask1D(AbstractMask1d):
@classmethod
def manual(
cls,
mask: Union[List, np.ndarray],
pixel_scales: Union[float, Tuple[float]],
sub_size: int = 1,
origin: Tuple[float] = (0.0,),
invert: bool = False,
) -> "Mask1D":
if type(mask) is list:
mask = np.asarray(mask).astype("bool")
if invert:
mask = np.invert(mask)
if type(pixel_scales) is float:
pixel_scales = (pixel_scales,)
if len(mask.shape) != 1:
raise exc.MaskException("The input mask is not a one dimensional array")
return Mask1D(
mask=mask, pixel_scales=pixel_scales, sub_size=sub_size, origin=origin
)
@classmethod
def unmasked(
cls,
shape_slim,
pixel_scales: Union[float, Tuple[float]],
sub_size: int = 1,
origin: Tuple[float] = (0.0,),
invert: bool = False,
) -> "Mask1D":
"""
Setup a 1D mask where all pixels are unmasked.
Parameters
----------
shape
The (y,x) shape of the mask in units of pixels.
pixel_scales
The scaled units to pixel units conversion factor of each pixel.
"""
return cls.manual(
mask=np.full(shape=shape_slim, fill_value=False),
pixel_scales=pixel_scales,
origin=origin,
sub_size=sub_size,
invert=invert,
)
@classmethod
def from_fits(
cls,
file_path: str,
pixel_scales: Union[float, Tuple[float]],
sub_size: int = 1,
hdu: int = 0,
origin: Tuple[float] = (0.0,),
) -> "Mask1D":
"""
Loads the 1D mask from a .fits file.
Parameters
----------
file_path
The full path of the fits file.
hdu
The HDU number in the fits file containing the image image.
pixel_scales
The scaled units to pixel units conversion factor of each pixel.
"""
return cls.manual(
array_1d_util.numpy_array_1d_from_fits(file_path=file_path, hdu=hdu),
pixel_scales=pixel_scales,
sub_size=sub_size,
origin=origin,
)
def output_to_fits(self, file_path: str, overwrite: bool = False):
array_1d_util.numpy_array_1d_to_fits(
array_1d=self.astype("float"), file_path=file_path, overwrite=overwrite
)
@property
def pixels_in_mask(self) -> int:
return int(np.size(self) - np.sum(self))
@property
def is_all_false(self) -> bool:
return self.pixels_in_mask == self.shape_slim[0]
@property
def shape_slim(self) -> Tuple[int]:
return self.shape
@property
def shape_slim_scaled(self) -> Tuple[float]:
return (float(self.pixel_scales[0] * self.shape_slim[0]),)
@property
def scaled_maxima(self) -> Tuple[float]:
return (float(self.shape_slim_scaled[0] / 2.0 + self.origin[0]),)
@property
def scaled_minima(self) -> Tuple[float]:
return (-float(self.shape_slim_scaled[0] / 2.0) + self.origin[0],)
@property
def extent(self):
return np.array([self.scaled_minima[0], self.scaled_maxima[0]])
|
[
"numpy.full",
"numpy.size",
"numpy.sum",
"logging.basicConfig",
"numpy.invert",
"autoarray.structures.arrays.one_d.array_1d_util.numpy_array_1d_from_fits",
"autoarray.mask.abstract_mask.AbstractMask.__new__",
"autoarray.mask.mask_2d.Mask2D.manual",
"numpy.asarray",
"autoarray.structures.grids.one_d.grid_1d_util.grid_1d_slim_via_mask_from",
"autoarray.structures.grids.one_d.grid_1d.Grid1D",
"numpy.array",
"autoarray.exc.MaskException",
"logging.getLogger"
] |
[((333, 354), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (352, 354), False, 'import logging\n'), ((365, 392), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (382, 392), False, 'import logging\n'), ((1685, 1805), 'autoarray.mask.abstract_mask.AbstractMask.__new__', 'abstract_mask.AbstractMask.__new__', ([], {'cls': 'cls', 'mask': 'mask', 'pixel_scales': 'pixel_scales', 'sub_size': 'sub_size', 'origin': 'origin'}), '(cls=cls, mask=mask, pixel_scales=\n pixel_scales, sub_size=sub_size, origin=origin)\n', (1719, 1805), False, 'from autoarray.mask import abstract_mask, mask_2d\n'), ((3177, 3299), 'autoarray.structures.grids.one_d.grid_1d_util.grid_1d_slim_via_mask_from', 'grid_1d_util.grid_1d_slim_via_mask_from', ([], {'mask_1d': 'self', 'pixel_scales': 'self.pixel_scales', 'sub_size': '(1)', 'origin': 'self.origin'}), '(mask_1d=self, pixel_scales=self.\n pixel_scales, sub_size=1, origin=self.origin)\n', (3216, 3299), False, 'from autoarray.structures.grids.one_d import grid_1d_util\n'), ((3337, 3403), 'autoarray.structures.grids.one_d.grid_1d.Grid1D', 'grid_1d.Grid1D', ([], {'grid': 'grid_slim', 'mask': 'self.unmasked_mask.mask_sub_1'}), '(grid=grid_slim, mask=self.unmasked_mask.mask_sub_1)\n', (3351, 3403), False, 'from autoarray.structures.grids.one_d import grid_1d\n'), ((3843, 3971), 'autoarray.mask.mask_2d.Mask2D.manual', 'mask_2d.Mask2D.manual', (['[self]'], {'pixel_scales': '(self.pixel_scale, self.pixel_scale)', 'sub_size': 'self.sub_size', 'origin': '(0.0, 0.0)'}), '([self], pixel_scales=(self.pixel_scale, self.\n pixel_scale), sub_size=self.sub_size, origin=(0.0, 0.0))\n', (3864, 3971), False, 'from autoarray.mask import abstract_mask, mask_2d\n'), ((8249, 8305), 'numpy.array', 'np.array', (['[self.scaled_minima[0], self.scaled_maxima[0]]'], {}), '([self.scaled_minima[0], self.scaled_maxima[0]])\n', (8257, 8305), True, 'import numpy as np\n'), ((5311, 5326), 'numpy.invert', 'np.invert', (['mask'], {}), '(mask)\n', (5320, 5326), True, 'import numpy as np\n'), ((5469, 5535), 'autoarray.exc.MaskException', 'exc.MaskException', (['"""The input mask is not a one dimensional array"""'], {}), "('The input mask is not a one dimensional array')\n", (5486, 5535), False, 'from autoarray import exc\n'), ((7079, 7147), 'autoarray.structures.arrays.one_d.array_1d_util.numpy_array_1d_from_fits', 'array_1d_util.numpy_array_1d_from_fits', ([], {'file_path': 'file_path', 'hdu': 'hdu'}), '(file_path=file_path, hdu=hdu)\n', (7117, 7147), False, 'from autoarray.structures.arrays.one_d import array_1d_util\n'), ((6247, 6290), 'numpy.full', 'np.full', ([], {'shape': 'shape_slim', 'fill_value': '(False)'}), '(shape=shape_slim, fill_value=False)\n', (6254, 6290), True, 'import numpy as np\n'), ((7554, 7567), 'numpy.size', 'np.size', (['self'], {}), '(self)\n', (7561, 7567), True, 'import numpy as np\n'), ((7570, 7582), 'numpy.sum', 'np.sum', (['self'], {}), '(self)\n', (7576, 7582), True, 'import numpy as np\n'), ((5237, 5253), 'numpy.asarray', 'np.asarray', (['mask'], {}), '(mask)\n', (5247, 5253), True, 'import numpy as np\n')]
|
"""Simulates Fanout-of-4 delay for a given technology.
Parameters
----------
tech : int
Node designator (16, 7, 5, 4, 3).
vdd : Optional[float], default = nominal
Supply voltage.
Returns
-------
float
Delay in picoseconds.
"""
import os
import math
import argparse
import sys
sys.path.insert(0,'..')
import setenv
import device_geometry
parser = argparse.ArgumentParser()
parser.add_argument("--tech")
parser.add_argument("--vdd")
args = parser.parse_args()
tech_node = int(args.tech)
node_index = device_geometry.node_names.index(tech_node)
GL = device_geometry.GL[node_index]
vdd = device_geometry.vdd[node_index]
try:
vdd = float(args.vdd)
except:
pass
spice_model_path = "\"%s/" % os.path.abspath("../spice_models/") + "%dnm.l\" %dNM_FINFET_HP\n"
##########################################################################
def gen_netlist():
"""Outputs the FO4 netlist.
Parameters
----------
None
Returns
-------
str
SPICE netlist.
"""
txt = ".TITLE MAX_WL\n\n"
txt += ".LIB %s\n" % (spice_model_path % (int(tech_node), int(tech_node)))
txt += ".TRAN 1p 16n\n.OPTIONS BRIEF=1\n\n"
txt += ".PARAM GL=%dn\n" % GL
txt += ".PARAM supply_v=%.2f\n\n" % vdd
txt += ".SUBCKT inv n_in n_out vdd D=1\n"
txt += "MN1 n_out n_in gnd gnd nmos L=GL nfin=D\n"
txt += "MP1 n_out n_in vdd vdd pmos L=GL nfin=D\n"
txt += ".ENDS\n\n"
txt += "Vps vdd gnd supply_v\n"
txt += "Vin n_in gnd PULSE (0 supply_v 0 0 0 2n 4n)\n\n"
txt += "Xinv1 n_in n_out_1 vdd inv D=1\n"
txt += "Xinv4 n_out_1 n_out_4 vdd inv D=4\n"
txt += "Xinv16 n_out_4 n_out_16 vdd inv D=16\n"
txt += "Xinv64 n_out_16 n_out_64 vdd inv D=64\n\n"
txt += ".MEASURE tfall TRIG V(n_out_1) VAL='supply_v/2' RISE=2\n"
txt += "+ TARG V(n_out_4) VAL='supply_v/2' FALL=2\n\n"
txt += ".MEASURE trise TRIG V(n_out_1) VAL='supply_v/2' FALL=2\n"
txt += "+ TARG V(n_out_4) VAL='supply_v/2' RISE=2\n\n"
txt += ".END"
return txt
##########################################################################
##########################################################################
def measure():
"""Measures the FO4 delay.
Parameters
----------
None
Returns
-------
float
Delay.
"""
with open("fo4.sp", "w") as outf:
outf.write(gen_netlist())
hspice_call = os.environ["HSPICE"] + " fo4.sp > hspice.dump"
os.system(hspice_call)
scale_dict = {'f' : 1e-15, 'p' : 1e-12, 'n' : 1e-9}
with open("hspice.dump", "r") as inf:
lines = inf.readlines()
os.system("rm hspice.dump")
for line in lines:
if "tfall=" in line:
# tfall = float(line.split()[1][:-1]) * scale_dict[line.split()[1][-1]]
tfall = float(line.split()[1])
elif "trise=" in line:
# trise = float(line.split()[1][:-1]) * scale_dict[line.split()[1][-1]]
trise = float(line.split()[1])
return (trise + tfall) / 2
##########################################################################
print("FO4 = %.2f ps" % (1e12 * measure()))
os.system("rm -rf fo4*")
|
[
"os.path.abspath",
"device_geometry.node_names.index",
"argparse.ArgumentParser",
"os.system",
"sys.path.insert"
] |
[((291, 315), 'sys.path.insert', 'sys.path.insert', (['(0)', '""".."""'], {}), "(0, '..')\n", (306, 315), False, 'import sys\n'), ((364, 389), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (387, 389), False, 'import argparse\n'), ((517, 560), 'device_geometry.node_names.index', 'device_geometry.node_names.index', (['tech_node'], {}), '(tech_node)\n', (549, 560), False, 'import device_geometry\n'), ((3180, 3204), 'os.system', 'os.system', (['"""rm -rf fo4*"""'], {}), "('rm -rf fo4*')\n", (3189, 3204), False, 'import os\n'), ((2500, 2522), 'os.system', 'os.system', (['hspice_call'], {}), '(hspice_call)\n', (2509, 2522), False, 'import os\n'), ((2660, 2687), 'os.system', 'os.system', (['"""rm hspice.dump"""'], {}), "('rm hspice.dump')\n", (2669, 2687), False, 'import os\n'), ((715, 750), 'os.path.abspath', 'os.path.abspath', (['"""../spice_models/"""'], {}), "('../spice_models/')\n", (730, 750), False, 'import os\n')]
|
import sys
import os
import unittest
import shutil
from io import StringIO
sys.path.append(".")
from mock_helper import gen_file
from annogesiclib.circrna import CircRNADetection
from mock_args_container import MockClass
class Mock_segemehl(object):
def mock_fasta_index(self, segemehl_path, fasta_path,
index, fasta, log):
pass
def mock_align(self, args,
index, fasta, read,
sam_file, log_file,
fasta_prefix, log):
return "test"
def mock_wait_processes(self, processes):
pass
class Mock_samtools(object):
def mock_covert_bam(self, samtools_path, out_bam, pre_sam, log):
pass
class TestCircRNADetection(unittest.TestCase):
def setUp(self):
self.segemehl = Mock_segemehl()
self.samtools = Mock_samtools()
self.mock_args = MockClass()
self.example = Example()
self.test_folder = "test_folder"
self.fasta_folder = os.path.join(self.test_folder, "fasta")
self.gff_folder = os.path.join(self.test_folder, "gff")
self.out_folder = os.path.join(self.test_folder, "output")
self.read_folder = os.path.join(self.test_folder, "read")
self.splice_folder = os.path.join(self.test_folder, "splice")
self.alignment_path = os.path.join(self.out_folder,
"segemehl_align")
if (not os.path.exists(self.test_folder)):
os.mkdir(self.test_folder)
if (not os.path.exists(self.fasta_folder)):
os.mkdir(self.fasta_folder)
os.mkdir(os.path.join(self.fasta_folder, "tmp"))
if (not os.path.exists(self.gff_folder)):
os.mkdir(self.gff_folder)
if (not os.path.exists(self.out_folder)):
os.mkdir(self.out_folder)
if (not os.path.exists(self.read_folder)):
os.mkdir(self.read_folder)
if (not os.path.exists(self.splice_folder)):
os.mkdir(self.splice_folder)
args = self.mock_args.mock()
args.output_folder = self.out_folder
args.gffs = self.gff_folder
args.align = True
args.fastas = self.fasta_folder
self.circ = CircRNADetection(args)
def tearDown(self):
if os.path.exists(self.test_folder):
shutil.rmtree(self.test_folder)
if os.path.exists("test1"):
if os.path.isfile("test1"):
os.remove("test1")
if os.path.isdir("test1"):
shutil.rmtree("test1")
if os.path.exists("test2"):
if os.path.isfile("test2"):
os.remove("test2")
if os.path.isdir("test2"):
shutil.rmtree("test2")
def test_deal_zip_file(self):
out1 = os.path.join(self.test_folder, "test1.fa")
out2 = os.path.join(self.test_folder, "test2")
gen_file(out1, self.example.fasta_file)
gen_file(out2, self.example.fasta_file)
os.system("gzip " + out1)
os.system("bzip2 -z " + out2)
log = open(os.path.join(self.test_folder, "test.log"), "w")
reads = self.circ._deal_zip_file([{"sample": "all", "files": [out1 + ".gz", out2 + ".bz2"]}], log)
self.assertEqual(reads, [{'files': ['test_folder/test1.fa.gz', 'test_folder/test2.bz2',
'test_folder/test1.fa', 'test_folder/test2.fa'],
'zips': ['test_folder/test1.fa', 'test_folder/test2.fa'],
'sample': 'all'}])
self.assertTrue(os.path.exists(out1))
self.assertTrue(os.path.exists(out2 + ".fa"))
def test_align(self):
self.circ._run_segemehl_fasta_index = self.segemehl.mock_fasta_index
self.circ._run_segemehl_align = self.segemehl.mock_align
self.circ._wait_process = self.segemehl.mock_wait_processes
fasta1 = os.path.join(os.path.join(self.fasta_folder, "tmp/test1.fa"))
fasta2 = os.path.join(os.path.join(self.fasta_folder, "tmp/test2.fa"))
read1 = os.path.join(self.read_folder, "read1.fa")
read2 = os.path.join(self.read_folder, "read2.fa")
gen_file(fasta1, self.example.fasta_file)
gen_file(fasta2, self.example.fasta_file)
gen_file(read1, self.example.fasta_file)
gen_file(read2, self.example.fasta_file)
os.mkdir(os.path.join(self.out_folder, "segemehl_alignment_files"))
args = self.mock_args.mock()
args.output_folder = self.out_folder
args.gffs = self.gff_folder
args.align = True
args.fastas = self.fasta_folder
args.segemehl_path = None
args.read_files = [read1, read2]
args.cores = 2
log = open(os.path.join(self.test_folder, "test.log"), "w")
read_datas = [{"sample": "test", "files": [read1, read2]}]
align_results, prefixs = self.circ._align(args, read_datas, log)
self.assertEqual(set(align_results), set(['read1_test1', 'read2_test1',
'read1_test2', 'read2_test2']))
self.assertEqual(set(prefixs), set(['test1', 'test2']))
def test_convert_sam2bam(self):
self.circ._run_samtools_convert_bam = self.samtools.mock_covert_bam
sam1 = os.path.join(self.test_folder, "test1.sam")
sam2 = os.path.join(self.test_folder, "test2.sam")
bam = os.path.join(self.test_folder, "test3.bam")
gen_file(sam1, self.example.align_file)
gen_file(sam2, self.example.align_file)
gen_file(bam, self.example.align_file)
align_files = ["test1"]
log = open(os.path.join(self.test_folder, "test.log"), "w")
bam_files, convert_ones, remove_ones = self.circ._convert_sam2bam(
self.test_folder, None, align_files, log)
self.assertEqual(set(bam_files), set([bam, sam1.replace("sam", "bam"),
sam2.replace("sam", "bam")]))
self.assertEqual(set(convert_ones), set([sam2.replace("sam", "bam")]))
self.assertEqual(set(remove_ones), set([sam1]))
align_files = ["test3"]
bam_files, convert_ones, remove_ones = self.circ._convert_sam2bam(
self.test_folder, None, align_files, log)
self.assertEqual(set(convert_ones), set([sam2.replace("sam", "bam"),
sam1.replace("sam", "bam")]))
self.assertEqual(set(remove_ones), set([]))
def test_merge_bed(self):
fasta1 = os.path.join(self.fasta_folder, "test1.fa")
fasta2 = os.path.join(self.fasta_folder, "test2.fa")
header1 = os.path.join(self.splice_folder,
"Staphylococcus_aureus_HG003")
header2 = os.path.join(self.splice_folder, "aaa")
header3 = os.path.join(self.splice_folder, "bbb")
os.mkdir(header1)
os.mkdir(header2)
os.mkdir(header3)
splice1 = os.path.join(header1, "Staphylococcus_aureus_HG003_a1_splicesites.bed")
splice2 = os.path.join(header2, "aaa_a1_splicesites.bed")
splice3 = os.path.join(header3, "bbb_a1_splicesites.bed")
tran1 = os.path.join(header1, "Staphylococcus_aureus_HG003_a1_transrealigned.bed")
tran2 = os.path.join(header2, "aaa_a1_transrealigned.bed")
tran3 = os.path.join(header3, "bbb_a1_transrealigned.bed")
gen_file(fasta1, self.example.fasta_file)
gen_file(fasta2, self.example.multi_fasta_file)
gen_file(splice1, self.example.splice_file)
gen_file(splice2, self.example.splice_file)
gen_file(splice3, self.example.splice_file)
gen_file(tran1, self.example.tran_file)
gen_file(tran2, self.example.tran_file)
gen_file(tran3, self.example.tran_file)
prefixs = self.circ._merge_bed(
self.fasta_folder, self.splice_folder, self.out_folder)
self.assertEqual(set(prefixs[1]), set(["test1", "test2"]))
self.assertEqual(prefixs[0][0], "_a1_")
self.assertTrue(os.path.exists(os.path.join(
self.out_folder, "test1", "test1_a1_splicesites.bed")))
self.assertTrue(os.path.exists(os.path.join(
self.out_folder, "test1", "test1_a1_transrealigned.bed")))
self.assertTrue(os.path.exists(os.path.join(
self.out_folder, "test2", "test2_a1_splicesites.bed")))
self.assertTrue(os.path.exists(os.path.join(
self.out_folder, "test2", "test2_a1_transrealigned.bed")))
self.assertTrue(os.path.exists(os.path.join(
self.out_folder, "test2", "tmp_bbb_a1_splicesites.bed")))
self.assertTrue(os.path.exists(os.path.join(
self.out_folder, "test2", "tmp_aaa_a1_splicesites.bed")))
self.assertTrue(os.path.exists(os.path.join(
self.out_folder, "test2", "tmp_aaa_a1_transrealigned.bed")))
self.assertTrue(os.path.exists(os.path.join(
self.out_folder, "test2", "tmp_bbb_a1_transrealigned.bed")))
def test_combine_read_bam(self):
bam_datas = [{"sample": "aaa", "files": [
os.path.join(self.out_folder, "segemehl_alignment_files", "aaa1.bam"),
"aaa2.bam"]},
{"sample": "bbb", "files": ["bbb1.bam", "bbb2.bam"]}]
read_datas = [{"sample": "aaa", "files": [
"aaa1.fa", "aaa3.fa", "aaa4.fa"]}]
bam_files = [os.path.join(self.out_folder,
"segemehl_alignment_files", "aaa1.bam"),
os.path.join(self.out_folder,
"segemehl_alignment_files", "aaa3.bam")]
self.circ._combine_read_bam(bam_files, bam_datas, read_datas)
self.assertDictEqual(bam_datas[0], {'files': [
'test_folder/output/segemehl_alignment_files/aaa1.bam', 'aaa2.bam',
'test_folder/output/segemehl_alignment_files/aaa3.bam'], 'sample': 'aaa'})
class Example(object):
fasta_file = """>Staphylococcus_aureus_HG003
GCAGGTTGAGTTCCTGTTCCCGATAGATCCGATAAACCCGCTTATGATTCCAGAGCTGTCCCTGCACATA
GCCGCTTCATTTTTTTCCAAGGGCTTCCTTCAGGATATCCGTCTGCATGCTCAAATCCGCATACATGCGG"""
multi_fasta_file = """>aaa
GCAGGTTGAGTTCCTGTTCCCGATAGATCCGATAAACCCGCTTATGATTCCAGAGCTGTCCCTGCACATA
GCCGCTTCATTTTTTTCCAAGGGCTTCCTTCAGGATATCCGTCTGCATGCTCAAATCCGCATACATGCGG
>bbb
GCAGGTTGAGTTCCTGTTCCCGATAGATCCGATAAACCCGCTTATGATTCCAGAGCTGTCCCTGCACATA
GCCGCTTCATTTTTTTCCAAGGGCTTCCTTCAGGATATCCGTCTGCATGCTCAAATCCGCATACATGCGG"""
align_file = """HWI-ST863:185:C1K2FACXX:7:1101:2763:1989 1:N:0:TGACCAAT 0 Staphylococcus_aureus_HG003 1821329 255 88M1D6M * 0 0 GTCAGATGACATTAAATAGCATCTCCTCGTGTTGATTATTTTGGTTGGCTGACCAATATTTATTCTAGCACGTAGAGATGCATTTTTTAAAAAA * NM:i:4 MD:Z:88^G0T0G1C2 NH:i:1 XI:i:0 XA:Z:Q
HWI-ST863:185:C1K2FACXX:7:1101:3037:1980 1:N:0:TGACCAAT 16 Staphylococcus_aureus_HG003 1923770 255 94M * 0 0 CGTCAGCAACGTCATATGAATTCTCAGTTCATGTTGTGGTGACACTTTAAACGGTCTGTGCCAGTAGCGACCGAGTCATTTCAAGAATGACCAT * NM:i:0 MD:Z:94 NH:i:1 XI:i:0 XA:Z:Q
HWI-ST863:185:C1K2FACXX:7:1101:4006:1911 1:N:0:TGACCAAT 0 Staphylococcus_aureus_HG003 498013 255 94M * 0 0 TCTGGTGACTATAGCAAGGAGGTCACACCTGTTCCCATGCCGAACACAGAAGTTAAGCTCCTTAGCGTCGATGGTAGTCGAACTTACGTTCCGC * NM:i:0 MD:Z:94 NH:i:5 XI:i:0 XA:Z:Q
HWI-ST863:185:C1K2FACXX:7:1101:4006:1911 1:N:0:TGACCAAT 0 Staphylococcus_aureus_HG003 492125 255 94M * 0 0 TCTGGTGACTATAGCAAGGAGGTCACACCTGTTCCCATGCCGAACACAGAAGTTAAGCTCCTTAGCGTCGATGGTAGTCGAACTTACGTTCCGC * NM:i:0 MD:Z:94 NH:i:5 XI:i:1 XA:Z:Q"""
splice_file = """Staphylococcus_aureus_HG003 5086 5767 splits:1:1:1:N:P 0 +
Staphylococcus_aureus_HG003 7713 8599 splits:1:1:1:N:P 0 +
Staphylococcus_aureus_HG003 8561 9362 splits:3:3:3:N:P 0 +
Staphylococcus_aureus_HG003 12668 12703 splits:1:14:1:N:P 0 +
Staphylococcus_aureus_HG003 17647 17667 splits:1:1:1:N:F 0 +"""
tran_file = """Staphylococcus_aureus_HG003 1 1 distsplice:Staphylococcus_aureus_HG003:2821337:2:2:2:L:P 0 +
Staphylococcus_aureus_HG003 2821337 2821337 distsplice:Staphylococcus_aureus_HG003:1:2:2:2:R:P 0 +
Staphylococcus_aureus_HG003 2278 2278 distsplice:Staphylococcus_aureus_HG003:450417:1:1:10:L:P 0 +"""
if __name__ == "__main__":
unittest.main()
|
[
"sys.path.append",
"unittest.main",
"os.mkdir",
"os.remove",
"os.path.isdir",
"annogesiclib.circrna.CircRNADetection",
"mock_args_container.MockClass",
"os.path.exists",
"os.system",
"os.path.isfile",
"shutil.rmtree",
"os.path.join",
"mock_helper.gen_file"
] |
[((75, 95), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (90, 95), False, 'import sys\n'), ((12529, 12544), 'unittest.main', 'unittest.main', ([], {}), '()\n', (12542, 12544), False, 'import unittest\n'), ((888, 899), 'mock_args_container.MockClass', 'MockClass', ([], {}), '()\n', (897, 899), False, 'from mock_args_container import MockClass\n'), ((1002, 1041), 'os.path.join', 'os.path.join', (['self.test_folder', '"""fasta"""'], {}), "(self.test_folder, 'fasta')\n", (1014, 1041), False, 'import os\n'), ((1068, 1105), 'os.path.join', 'os.path.join', (['self.test_folder', '"""gff"""'], {}), "(self.test_folder, 'gff')\n", (1080, 1105), False, 'import os\n'), ((1132, 1172), 'os.path.join', 'os.path.join', (['self.test_folder', '"""output"""'], {}), "(self.test_folder, 'output')\n", (1144, 1172), False, 'import os\n'), ((1200, 1238), 'os.path.join', 'os.path.join', (['self.test_folder', '"""read"""'], {}), "(self.test_folder, 'read')\n", (1212, 1238), False, 'import os\n'), ((1268, 1308), 'os.path.join', 'os.path.join', (['self.test_folder', '"""splice"""'], {}), "(self.test_folder, 'splice')\n", (1280, 1308), False, 'import os\n'), ((1339, 1386), 'os.path.join', 'os.path.join', (['self.out_folder', '"""segemehl_align"""'], {}), "(self.out_folder, 'segemehl_align')\n", (1351, 1386), False, 'import os\n'), ((2228, 2250), 'annogesiclib.circrna.CircRNADetection', 'CircRNADetection', (['args'], {}), '(args)\n', (2244, 2250), False, 'from annogesiclib.circrna import CircRNADetection\n'), ((2287, 2319), 'os.path.exists', 'os.path.exists', (['self.test_folder'], {}), '(self.test_folder)\n', (2301, 2319), False, 'import os\n'), ((2376, 2399), 'os.path.exists', 'os.path.exists', (['"""test1"""'], {}), "('test1')\n", (2390, 2399), False, 'import os\n'), ((2565, 2588), 'os.path.exists', 'os.path.exists', (['"""test2"""'], {}), "('test2')\n", (2579, 2588), False, 'import os\n'), ((2793, 2835), 'os.path.join', 'os.path.join', (['self.test_folder', '"""test1.fa"""'], {}), "(self.test_folder, 'test1.fa')\n", (2805, 2835), False, 'import os\n'), ((2851, 2890), 'os.path.join', 'os.path.join', (['self.test_folder', '"""test2"""'], {}), "(self.test_folder, 'test2')\n", (2863, 2890), False, 'import os\n'), ((2899, 2938), 'mock_helper.gen_file', 'gen_file', (['out1', 'self.example.fasta_file'], {}), '(out1, self.example.fasta_file)\n', (2907, 2938), False, 'from mock_helper import gen_file\n'), ((2947, 2986), 'mock_helper.gen_file', 'gen_file', (['out2', 'self.example.fasta_file'], {}), '(out2, self.example.fasta_file)\n', (2955, 2986), False, 'from mock_helper import gen_file\n'), ((2995, 3020), 'os.system', 'os.system', (["('gzip ' + out1)"], {}), "('gzip ' + out1)\n", (3004, 3020), False, 'import os\n'), ((3029, 3058), 'os.system', 'os.system', (["('bzip2 -z ' + out2)"], {}), "('bzip2 -z ' + out2)\n", (3038, 3058), False, 'import os\n'), ((4079, 4121), 'os.path.join', 'os.path.join', (['self.read_folder', '"""read1.fa"""'], {}), "(self.read_folder, 'read1.fa')\n", (4091, 4121), False, 'import os\n'), ((4138, 4180), 'os.path.join', 'os.path.join', (['self.read_folder', '"""read2.fa"""'], {}), "(self.read_folder, 'read2.fa')\n", (4150, 4180), False, 'import os\n'), ((4189, 4230), 'mock_helper.gen_file', 'gen_file', (['fasta1', 'self.example.fasta_file'], {}), '(fasta1, self.example.fasta_file)\n', (4197, 4230), False, 'from mock_helper import gen_file\n'), ((4239, 4280), 'mock_helper.gen_file', 'gen_file', (['fasta2', 'self.example.fasta_file'], {}), '(fasta2, self.example.fasta_file)\n', (4247, 4280), False, 'from mock_helper import gen_file\n'), ((4289, 4329), 'mock_helper.gen_file', 'gen_file', (['read1', 'self.example.fasta_file'], {}), '(read1, self.example.fasta_file)\n', (4297, 4329), False, 'from mock_helper import gen_file\n'), ((4338, 4378), 'mock_helper.gen_file', 'gen_file', (['read2', 'self.example.fasta_file'], {}), '(read2, self.example.fasta_file)\n', (4346, 4378), False, 'from mock_helper import gen_file\n'), ((5299, 5342), 'os.path.join', 'os.path.join', (['self.test_folder', '"""test1.sam"""'], {}), "(self.test_folder, 'test1.sam')\n", (5311, 5342), False, 'import os\n'), ((5358, 5401), 'os.path.join', 'os.path.join', (['self.test_folder', '"""test2.sam"""'], {}), "(self.test_folder, 'test2.sam')\n", (5370, 5401), False, 'import os\n'), ((5416, 5459), 'os.path.join', 'os.path.join', (['self.test_folder', '"""test3.bam"""'], {}), "(self.test_folder, 'test3.bam')\n", (5428, 5459), False, 'import os\n'), ((5468, 5507), 'mock_helper.gen_file', 'gen_file', (['sam1', 'self.example.align_file'], {}), '(sam1, self.example.align_file)\n', (5476, 5507), False, 'from mock_helper import gen_file\n'), ((5516, 5555), 'mock_helper.gen_file', 'gen_file', (['sam2', 'self.example.align_file'], {}), '(sam2, self.example.align_file)\n', (5524, 5555), False, 'from mock_helper import gen_file\n'), ((5564, 5602), 'mock_helper.gen_file', 'gen_file', (['bam', 'self.example.align_file'], {}), '(bam, self.example.align_file)\n', (5572, 5602), False, 'from mock_helper import gen_file\n'), ((6539, 6582), 'os.path.join', 'os.path.join', (['self.fasta_folder', '"""test1.fa"""'], {}), "(self.fasta_folder, 'test1.fa')\n", (6551, 6582), False, 'import os\n'), ((6600, 6643), 'os.path.join', 'os.path.join', (['self.fasta_folder', '"""test2.fa"""'], {}), "(self.fasta_folder, 'test2.fa')\n", (6612, 6643), False, 'import os\n'), ((6662, 6725), 'os.path.join', 'os.path.join', (['self.splice_folder', '"""Staphylococcus_aureus_HG003"""'], {}), "(self.splice_folder, 'Staphylococcus_aureus_HG003')\n", (6674, 6725), False, 'import os\n'), ((6775, 6814), 'os.path.join', 'os.path.join', (['self.splice_folder', '"""aaa"""'], {}), "(self.splice_folder, 'aaa')\n", (6787, 6814), False, 'import os\n'), ((6833, 6872), 'os.path.join', 'os.path.join', (['self.splice_folder', '"""bbb"""'], {}), "(self.splice_folder, 'bbb')\n", (6845, 6872), False, 'import os\n'), ((6881, 6898), 'os.mkdir', 'os.mkdir', (['header1'], {}), '(header1)\n', (6889, 6898), False, 'import os\n'), ((6907, 6924), 'os.mkdir', 'os.mkdir', (['header2'], {}), '(header2)\n', (6915, 6924), False, 'import os\n'), ((6933, 6950), 'os.mkdir', 'os.mkdir', (['header3'], {}), '(header3)\n', (6941, 6950), False, 'import os\n'), ((6969, 7040), 'os.path.join', 'os.path.join', (['header1', '"""Staphylococcus_aureus_HG003_a1_splicesites.bed"""'], {}), "(header1, 'Staphylococcus_aureus_HG003_a1_splicesites.bed')\n", (6981, 7040), False, 'import os\n'), ((7059, 7106), 'os.path.join', 'os.path.join', (['header2', '"""aaa_a1_splicesites.bed"""'], {}), "(header2, 'aaa_a1_splicesites.bed')\n", (7071, 7106), False, 'import os\n'), ((7125, 7172), 'os.path.join', 'os.path.join', (['header3', '"""bbb_a1_splicesites.bed"""'], {}), "(header3, 'bbb_a1_splicesites.bed')\n", (7137, 7172), False, 'import os\n'), ((7189, 7263), 'os.path.join', 'os.path.join', (['header1', '"""Staphylococcus_aureus_HG003_a1_transrealigned.bed"""'], {}), "(header1, 'Staphylococcus_aureus_HG003_a1_transrealigned.bed')\n", (7201, 7263), False, 'import os\n'), ((7280, 7330), 'os.path.join', 'os.path.join', (['header2', '"""aaa_a1_transrealigned.bed"""'], {}), "(header2, 'aaa_a1_transrealigned.bed')\n", (7292, 7330), False, 'import os\n'), ((7347, 7397), 'os.path.join', 'os.path.join', (['header3', '"""bbb_a1_transrealigned.bed"""'], {}), "(header3, 'bbb_a1_transrealigned.bed')\n", (7359, 7397), False, 'import os\n'), ((7406, 7447), 'mock_helper.gen_file', 'gen_file', (['fasta1', 'self.example.fasta_file'], {}), '(fasta1, self.example.fasta_file)\n', (7414, 7447), False, 'from mock_helper import gen_file\n'), ((7456, 7503), 'mock_helper.gen_file', 'gen_file', (['fasta2', 'self.example.multi_fasta_file'], {}), '(fasta2, self.example.multi_fasta_file)\n', (7464, 7503), False, 'from mock_helper import gen_file\n'), ((7512, 7555), 'mock_helper.gen_file', 'gen_file', (['splice1', 'self.example.splice_file'], {}), '(splice1, self.example.splice_file)\n', (7520, 7555), False, 'from mock_helper import gen_file\n'), ((7564, 7607), 'mock_helper.gen_file', 'gen_file', (['splice2', 'self.example.splice_file'], {}), '(splice2, self.example.splice_file)\n', (7572, 7607), False, 'from mock_helper import gen_file\n'), ((7616, 7659), 'mock_helper.gen_file', 'gen_file', (['splice3', 'self.example.splice_file'], {}), '(splice3, self.example.splice_file)\n', (7624, 7659), False, 'from mock_helper import gen_file\n'), ((7668, 7707), 'mock_helper.gen_file', 'gen_file', (['tran1', 'self.example.tran_file'], {}), '(tran1, self.example.tran_file)\n', (7676, 7707), False, 'from mock_helper import gen_file\n'), ((7716, 7755), 'mock_helper.gen_file', 'gen_file', (['tran2', 'self.example.tran_file'], {}), '(tran2, self.example.tran_file)\n', (7724, 7755), False, 'from mock_helper import gen_file\n'), ((7764, 7803), 'mock_helper.gen_file', 'gen_file', (['tran3', 'self.example.tran_file'], {}), '(tran3, self.example.tran_file)\n', (7772, 7803), False, 'from mock_helper import gen_file\n'), ((1437, 1469), 'os.path.exists', 'os.path.exists', (['self.test_folder'], {}), '(self.test_folder)\n', (1451, 1469), False, 'import os\n'), ((1484, 1510), 'os.mkdir', 'os.mkdir', (['self.test_folder'], {}), '(self.test_folder)\n', (1492, 1510), False, 'import os\n'), ((1527, 1560), 'os.path.exists', 'os.path.exists', (['self.fasta_folder'], {}), '(self.fasta_folder)\n', (1541, 1560), False, 'import os\n'), ((1575, 1602), 'os.mkdir', 'os.mkdir', (['self.fasta_folder'], {}), '(self.fasta_folder)\n', (1583, 1602), False, 'import os\n'), ((1680, 1711), 'os.path.exists', 'os.path.exists', (['self.gff_folder'], {}), '(self.gff_folder)\n', (1694, 1711), False, 'import os\n'), ((1726, 1751), 'os.mkdir', 'os.mkdir', (['self.gff_folder'], {}), '(self.gff_folder)\n', (1734, 1751), False, 'import os\n'), ((1768, 1799), 'os.path.exists', 'os.path.exists', (['self.out_folder'], {}), '(self.out_folder)\n', (1782, 1799), False, 'import os\n'), ((1814, 1839), 'os.mkdir', 'os.mkdir', (['self.out_folder'], {}), '(self.out_folder)\n', (1822, 1839), False, 'import os\n'), ((1856, 1888), 'os.path.exists', 'os.path.exists', (['self.read_folder'], {}), '(self.read_folder)\n', (1870, 1888), False, 'import os\n'), ((1903, 1929), 'os.mkdir', 'os.mkdir', (['self.read_folder'], {}), '(self.read_folder)\n', (1911, 1929), False, 'import os\n'), ((1946, 1980), 'os.path.exists', 'os.path.exists', (['self.splice_folder'], {}), '(self.splice_folder)\n', (1960, 1980), False, 'import os\n'), ((1995, 2023), 'os.mkdir', 'os.mkdir', (['self.splice_folder'], {}), '(self.splice_folder)\n', (2003, 2023), False, 'import os\n'), ((2333, 2364), 'shutil.rmtree', 'shutil.rmtree', (['self.test_folder'], {}), '(self.test_folder)\n', (2346, 2364), False, 'import shutil\n'), ((2416, 2439), 'os.path.isfile', 'os.path.isfile', (['"""test1"""'], {}), "('test1')\n", (2430, 2439), False, 'import os\n'), ((2491, 2513), 'os.path.isdir', 'os.path.isdir', (['"""test1"""'], {}), "('test1')\n", (2504, 2513), False, 'import os\n'), ((2605, 2628), 'os.path.isfile', 'os.path.isfile', (['"""test2"""'], {}), "('test2')\n", (2619, 2628), False, 'import os\n'), ((2680, 2702), 'os.path.isdir', 'os.path.isdir', (['"""test2"""'], {}), "('test2')\n", (2693, 2702), False, 'import os\n'), ((3078, 3120), 'os.path.join', 'os.path.join', (['self.test_folder', '"""test.log"""'], {}), "(self.test_folder, 'test.log')\n", (3090, 3120), False, 'import os\n'), ((3592, 3612), 'os.path.exists', 'os.path.exists', (['out1'], {}), '(out1)\n', (3606, 3612), False, 'import os\n'), ((3638, 3666), 'os.path.exists', 'os.path.exists', (["(out2 + '.fa')"], {}), "(out2 + '.fa')\n", (3652, 3666), False, 'import os\n'), ((3935, 3982), 'os.path.join', 'os.path.join', (['self.fasta_folder', '"""tmp/test1.fa"""'], {}), "(self.fasta_folder, 'tmp/test1.fa')\n", (3947, 3982), False, 'import os\n'), ((4014, 4061), 'os.path.join', 'os.path.join', (['self.fasta_folder', '"""tmp/test2.fa"""'], {}), "(self.fasta_folder, 'tmp/test2.fa')\n", (4026, 4061), False, 'import os\n'), ((4396, 4453), 'os.path.join', 'os.path.join', (['self.out_folder', '"""segemehl_alignment_files"""'], {}), "(self.out_folder, 'segemehl_alignment_files')\n", (4408, 4453), False, 'import os\n'), ((4756, 4798), 'os.path.join', 'os.path.join', (['self.test_folder', '"""test.log"""'], {}), "(self.test_folder, 'test.log')\n", (4768, 4798), False, 'import os\n'), ((5654, 5696), 'os.path.join', 'os.path.join', (['self.test_folder', '"""test.log"""'], {}), "(self.test_folder, 'test.log')\n", (5666, 5696), False, 'import os\n'), ((9406, 9475), 'os.path.join', 'os.path.join', (['self.out_folder', '"""segemehl_alignment_files"""', '"""aaa1.bam"""'], {}), "(self.out_folder, 'segemehl_alignment_files', 'aaa1.bam')\n", (9418, 9475), False, 'import os\n'), ((9532, 9601), 'os.path.join', 'os.path.join', (['self.out_folder', '"""segemehl_alignment_files"""', '"""aaa3.bam"""'], {}), "(self.out_folder, 'segemehl_alignment_files', 'aaa3.bam')\n", (9544, 9601), False, 'import os\n'), ((1624, 1662), 'os.path.join', 'os.path.join', (['self.fasta_folder', '"""tmp"""'], {}), "(self.fasta_folder, 'tmp')\n", (1636, 1662), False, 'import os\n'), ((2457, 2475), 'os.remove', 'os.remove', (['"""test1"""'], {}), "('test1')\n", (2466, 2475), False, 'import os\n'), ((2531, 2553), 'shutil.rmtree', 'shutil.rmtree', (['"""test1"""'], {}), "('test1')\n", (2544, 2553), False, 'import shutil\n'), ((2646, 2664), 'os.remove', 'os.remove', (['"""test2"""'], {}), "('test2')\n", (2655, 2664), False, 'import os\n'), ((2720, 2742), 'shutil.rmtree', 'shutil.rmtree', (['"""test2"""'], {}), "('test2')\n", (2733, 2742), False, 'import shutil\n'), ((8066, 8132), 'os.path.join', 'os.path.join', (['self.out_folder', '"""test1"""', '"""test1_a1_splicesites.bed"""'], {}), "(self.out_folder, 'test1', 'test1_a1_splicesites.bed')\n", (8078, 8132), False, 'import os\n'), ((8187, 8256), 'os.path.join', 'os.path.join', (['self.out_folder', '"""test1"""', '"""test1_a1_transrealigned.bed"""'], {}), "(self.out_folder, 'test1', 'test1_a1_transrealigned.bed')\n", (8199, 8256), False, 'import os\n'), ((8311, 8377), 'os.path.join', 'os.path.join', (['self.out_folder', '"""test2"""', '"""test2_a1_splicesites.bed"""'], {}), "(self.out_folder, 'test2', 'test2_a1_splicesites.bed')\n", (8323, 8377), False, 'import os\n'), ((8432, 8501), 'os.path.join', 'os.path.join', (['self.out_folder', '"""test2"""', '"""test2_a1_transrealigned.bed"""'], {}), "(self.out_folder, 'test2', 'test2_a1_transrealigned.bed')\n", (8444, 8501), False, 'import os\n'), ((8556, 8624), 'os.path.join', 'os.path.join', (['self.out_folder', '"""test2"""', '"""tmp_bbb_a1_splicesites.bed"""'], {}), "(self.out_folder, 'test2', 'tmp_bbb_a1_splicesites.bed')\n", (8568, 8624), False, 'import os\n'), ((8679, 8747), 'os.path.join', 'os.path.join', (['self.out_folder', '"""test2"""', '"""tmp_aaa_a1_splicesites.bed"""'], {}), "(self.out_folder, 'test2', 'tmp_aaa_a1_splicesites.bed')\n", (8691, 8747), False, 'import os\n'), ((8802, 8873), 'os.path.join', 'os.path.join', (['self.out_folder', '"""test2"""', '"""tmp_aaa_a1_transrealigned.bed"""'], {}), "(self.out_folder, 'test2', 'tmp_aaa_a1_transrealigned.bed')\n", (8814, 8873), False, 'import os\n'), ((8928, 8999), 'os.path.join', 'os.path.join', (['self.out_folder', '"""test2"""', '"""tmp_bbb_a1_transrealigned.bed"""'], {}), "(self.out_folder, 'test2', 'tmp_bbb_a1_transrealigned.bed')\n", (8940, 8999), False, 'import os\n'), ((9115, 9184), 'os.path.join', 'os.path.join', (['self.out_folder', '"""segemehl_alignment_files"""', '"""aaa1.bam"""'], {}), "(self.out_folder, 'segemehl_alignment_files', 'aaa1.bam')\n", (9127, 9184), False, 'import os\n')]
|
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.models.base_model_ import Model
from openapi_server import util
class Names(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
"""
def __init__(self, name=None, synonyms=None, source=None, url=None): # noqa: E501
"""Names - a model defined in OpenAPI
:param name: The name of this Names. # noqa: E501
:type name: str
:param synonyms: The synonyms of this Names. # noqa: E501
:type synonyms: List[str]
:param source: The source of this Names. # noqa: E501
:type source: str
:param url: The url of this Names. # noqa: E501
:type url: str
"""
self.openapi_types = {
'name': str,
'synonyms': List[str],
'source': str,
'url': str
}
self.attribute_map = {
'name': 'name',
'synonyms': 'synonyms',
'source': 'source',
'url': 'url'
}
self._name = name
self._synonyms = synonyms
self._source = source
self._url = url
@classmethod
def from_dict(cls, dikt) -> 'Names':
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The names of this Names. # noqa: E501
:rtype: Names
"""
return util.deserialize_model(dikt, cls)
@property
def name(self):
"""Gets the name of this Names.
Name of the compound. # noqa: E501
:return: The name of this Names.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this Names.
Name of the compound. # noqa: E501
:param name: The name of this Names.
:type name: str
"""
self._name = name
@property
def synonyms(self):
"""Gets the synonyms of this Names.
Name of the compound. # noqa: E501
:return: The synonyms of this Names.
:rtype: List[str]
"""
return self._synonyms
@synonyms.setter
def synonyms(self, synonyms):
"""Sets the synonyms of this Names.
Name of the compound. # noqa: E501
:param synonyms: The synonyms of this Names.
:type synonyms: List[str]
"""
self._synonyms = synonyms
@property
def source(self):
"""Gets the source of this Names.
Source of names and synonyms. # noqa: E501
:return: The source of this Names.
:rtype: str
"""
return self._source
@source.setter
def source(self, source):
"""Sets the source of this Names.
Source of names and synonyms. # noqa: E501
:param source: The source of this Names.
:type source: str
"""
if source is None:
raise ValueError("Invalid value for `source`, must not be `None`") # noqa: E501
self._source = source
@property
def url(self):
"""Gets the url of this Names.
URL for additional information. # noqa: E501
:return: The url of this Names.
:rtype: str
"""
return self._url
@url.setter
def url(self, url):
"""Sets the url of this Names.
URL for additional information. # noqa: E501
:param url: The url of this Names.
:type url: str
"""
self._url = url
|
[
"openapi_server.util.deserialize_model"
] |
[((1582, 1615), 'openapi_server.util.deserialize_model', 'util.deserialize_model', (['dikt', 'cls'], {}), '(dikt, cls)\n', (1604, 1615), False, 'from openapi_server import util\n')]
|
# Lint as: python3
# Copyright 2020 Google LLC.
#
# 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.
"""Tests for beam_pipeline."""
import os
import unittest
from unittest import mock
import apache_beam as beam
import tensorflow as tf
from tfrecorder import beam_pipeline
# pylint: disable=protected-access
class BeamPipelineTests(unittest.TestCase):
"""Tests for beam_pipeline.py"""
def test_processing_fn_with_int_label(self):
'Test preprocessing fn with integer label.'
element = {
'split': 'TRAIN',
'image_uri': 'gs://foo/bar.jpg',
'label': 1}
result = beam_pipeline._preprocessing_fn(element, integer_label=True)
self.assertEqual(element, result)
@mock.patch('tfrecorder.beam_pipeline.tft')
def test_processing_fn_with_string_label(self, mock_transform):
'Test preprocessing fn with string label.'
mock_transform.compute_and_apply_vocabulary.return_value = tf.constant(
0, dtype=tf.int64)
element = {
'split': 'TRAIN',
'image_uri': 'gs://foo/bar.jpg',
'label': tf.constant('cat', dtype=tf.string)}
result = beam_pipeline._preprocessing_fn(element, integer_label=False)
result['label'] = result['label'].numpy()
self.assertEqual(0, result['label'])
def test_write_to_tfrecord(self):
"""Test _write_to_tfrecord() fn."""
tfr_writer = beam_pipeline._get_write_to_tfrecord(
output_dir='tmp',
prefix='foo',
compress=True,
num_shards=2)
self.assertIsInstance(tfr_writer, beam.io.tfrecordio.WriteToTFRecord)
def test_partition_fn(self):
"""Test the partition function."""
test_data = {
'split': 'update_me',
'image_uri': 'gs://foo/bar0.jpg',
'label': 1}
for i, part in enumerate(['TRAIN', 'VALIDATION', 'TEST', 'FOO']):
test_data['split'] = part.encode('utf-8')
index = beam_pipeline._partition_fn(test_data)
self.assertEqual(
index, i,
'{} should be index {} but was index {}'.format(part, i, index))
def test_get_setup_py_filepath(self):
"""Tests `_get_setup_py_filepath`."""
filepath = beam_pipeline._get_setup_py_filepath()
self.assertTrue(os.path.isfile(filepath))
self.assertTrue(os.path.isabs(filepath))
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"tfrecorder.beam_pipeline._get_setup_py_filepath",
"os.path.isabs",
"tfrecorder.beam_pipeline._get_write_to_tfrecord",
"tensorflow.constant",
"unittest.mock.patch",
"tfrecorder.beam_pipeline._partition_fn",
"os.path.isfile",
"tfrecorder.beam_pipeline._preprocessing_fn"
] |
[((1203, 1245), 'unittest.mock.patch', 'mock.patch', (['"""tfrecorder.beam_pipeline.tft"""'], {}), "('tfrecorder.beam_pipeline.tft')\n", (1213, 1245), False, 'from unittest import mock\n'), ((2793, 2808), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2806, 2808), False, 'import unittest\n'), ((1100, 1160), 'tfrecorder.beam_pipeline._preprocessing_fn', 'beam_pipeline._preprocessing_fn', (['element'], {'integer_label': '(True)'}), '(element, integer_label=True)\n', (1131, 1160), False, 'from tfrecorder import beam_pipeline\n'), ((1422, 1452), 'tensorflow.constant', 'tf.constant', (['(0)'], {'dtype': 'tf.int64'}), '(0, dtype=tf.int64)\n', (1433, 1452), True, 'import tensorflow as tf\n'), ((1612, 1673), 'tfrecorder.beam_pipeline._preprocessing_fn', 'beam_pipeline._preprocessing_fn', (['element'], {'integer_label': '(False)'}), '(element, integer_label=False)\n', (1643, 1673), False, 'from tfrecorder import beam_pipeline\n'), ((1855, 1956), 'tfrecorder.beam_pipeline._get_write_to_tfrecord', 'beam_pipeline._get_write_to_tfrecord', ([], {'output_dir': '"""tmp"""', 'prefix': '"""foo"""', 'compress': '(True)', 'num_shards': '(2)'}), "(output_dir='tmp', prefix='foo',\n compress=True, num_shards=2)\n", (1891, 1956), False, 'from tfrecorder import beam_pipeline\n'), ((2632, 2670), 'tfrecorder.beam_pipeline._get_setup_py_filepath', 'beam_pipeline._get_setup_py_filepath', ([], {}), '()\n', (2668, 2670), False, 'from tfrecorder import beam_pipeline\n'), ((1562, 1597), 'tensorflow.constant', 'tf.constant', (['"""cat"""'], {'dtype': 'tf.string'}), "('cat', dtype=tf.string)\n", (1573, 1597), True, 'import tensorflow as tf\n'), ((2375, 2413), 'tfrecorder.beam_pipeline._partition_fn', 'beam_pipeline._partition_fn', (['test_data'], {}), '(test_data)\n', (2402, 2413), False, 'from tfrecorder import beam_pipeline\n'), ((2691, 2715), 'os.path.isfile', 'os.path.isfile', (['filepath'], {}), '(filepath)\n', (2705, 2715), False, 'import os\n'), ((2737, 2760), 'os.path.isabs', 'os.path.isabs', (['filepath'], {}), '(filepath)\n', (2750, 2760), False, 'import os\n')]
|
"""Forms for the learning_log app."""
from django import forms
from django.utils.translation import gettext_lazy as _
from .models import Entry, Topic
class TopicForm(forms.ModelForm):
"""Form for add a new topic."""
class Meta:
model = Topic
fields = ('topic_text', 'public')
labels = {
'topic_text': _('Topic name'),
'public': _('Do you want make this topic public?'),
}
help_texts = {
'public': _('Anyone will can see the entries for this topic.\
<br><strong>You can change this later.</strong>'),
}
class EntryForm(forms.ModelForm):
"""Form for add a new entry for a specific topic."""
class Meta:
model = Entry
fields = ('entry_text',)
widgets = {
'entry_text': forms.Textarea(attrs={'cols': 80, 'rows': 15}),
}
|
[
"django.forms.Textarea",
"django.utils.translation.gettext_lazy"
] |
[((351, 366), 'django.utils.translation.gettext_lazy', '_', (['"""Topic name"""'], {}), "('Topic name')\n", (352, 366), True, 'from django.utils.translation import gettext_lazy as _\n'), ((390, 430), 'django.utils.translation.gettext_lazy', '_', (['"""Do you want make this topic public?"""'], {}), "('Do you want make this topic public?')\n", (391, 430), True, 'from django.utils.translation import gettext_lazy as _\n'), ((487, 615), 'django.utils.translation.gettext_lazy', '_', (['"""Anyone will can see the entries for this topic. <br><strong>You can change this later.</strong>"""'], {}), "('Anyone will can see the entries for this topic. <br><strong>You can change this later.</strong>'\n )\n", (488, 615), True, 'from django.utils.translation import gettext_lazy as _\n'), ((835, 881), 'django.forms.Textarea', 'forms.Textarea', ([], {'attrs': "{'cols': 80, 'rows': 15}"}), "(attrs={'cols': 80, 'rows': 15})\n", (849, 881), False, 'from django import forms\n')]
|
import numpy as np
import random
class Tensor (object):
def __init__(self, data, autograd=False, creators=None, creation_op=None, id=None):
self.data = np.array(data)
self.creation_op = creation_op
self.creators = creators
self.grad = None
self.autograd = autograd
self.children = {}
if (id is None):
id = random.randint(0, 100000)
self.id = id
### Keep Track of how many children a tensor has
if (creators is not None):
for c in creators:
if self.id not in c.children:
c.children[self.id] = 1
else:
c.children[self.id] += 1
### Check whether a tensor has received the correct number of gradients from each child
def all_children_grads_accounted_for(self):
for _,cnt in self.children.items():
if(cnt != 0):
return False
return True
### Back Propogation
def backward(self, grad=None, grad_origin=None):
if(self.autograd):
if(grad_origin is not None):
if(self.children[grad_origin.id] == 0):
raise Exception("cannot backprop more than once")
else:
self.children[grad_origin.id] -= 1
if(self.grad is None):
self.grad = grad
else:
self.grad += grad
if(self.creators is not None and (self.all_children_grads_accounted_for() or grad_origin is None)):
### Addition
if(self.creation_op == "add"):
self.creators[0].backward(self.grad, self)
self.creators[1].backward(self.grad, self)
self.grad += self.grad
### Negation
if(self.creation_op == "neg"):
self.creators[0].backward(self.grad.__neg__())
### Subtraction
### Multiplication
### Matrix Multiplication
### Transpose
### Summation
### Expansion
def __add__(self, other):
if(self.autograd and other.autograd):
return Tensor(self.data + other.data, autograd=True, creators=[self,other], creation_op="add")
return Tensor(self.data + other.data, creators = [self, other], creation_op="add")
def __sub__(self, other):
if(self.autograd and other.autograd):
return Tensor(self.data - other.data, autograd=True, creators=[self, other], creation_op="sub")
return Tensor(self.data - other.data)
def __mul__(self, other):
if(self.autograd and other.autograd):
return Tensor(self.data * other.data, autograd=True, creators=[self, other], creation_op="mul")
return Tensor(self.data * other.data)
def sum(self, dim):
if(self.autograd):
return Tensor(self.data.sum(dim), autograd=True, creators=[self], creation_op="sum_"+str(dim))
return Tensor(self.data.sum(dim))
def expand(self, dim, copies):
trans_cmd = list(range(0, len(self.data.shape)))
trans_cmd.insert(dim, len(self.data.shape))
new_shape = list(self.data.shape) + [copies]
new_data = self.data.repeat(copies).reshape(new_shape)
new_data = new_data.transpose(trans_cmd)
if (self.autograd):
return Tensor(new_data, autograd=True, creators=[self], creation_op="expand_"+str(dim))
return Tensor(new_data)
def transpose(self):
if(self.autograd):
return Tensor(self.data.transpose(), autograd=True, creators=[self], creation_op="transpose")
return Tensor(self.data.transpose())
def mm(self, x):
if(self.autograd):
return Tensor(self.data.dot(x.data), autograd=True, creators=[self,x], creation_op="mm")
return Tensor(self.data.dot(x.data))
def __neg__(self):
if(self.autograd):
return Tensor(self.data * -1, autograd=True, creators=[self], creation_op="neg")
return Tensor(self.data * -1)
def __repr__(self):
return str(self.data.__repr__())
def __str__(self):
return str(self.data.__str__())
|
[
"numpy.array",
"random.randint"
] |
[((166, 180), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (174, 180), True, 'import numpy as np\n'), ((380, 405), 'random.randint', 'random.randint', (['(0)', '(100000)'], {}), '(0, 100000)\n', (394, 405), False, 'import random\n')]
|
# THIS IS A PROGRAM FOR CLUSTERING.
from clustering import clustering # 自作モジュール (clustering.py) と clusteringクラス の import
import pandas as pd
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import filedialog, image_names, ttk, messagebox
import os
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import numpy as np
# clustering の子クラスとして、クラスタリング結果をプロットするための plot_clustering クラスを作成
class plot_clustering(clustering):
# --- 元データのプロットのための関数 -------------------------------------------------------------
def data_plot(file_name):
fig = plt.Figure() # Figureインスタンスを生成
print (file_name)
csv_input = pd.read_csv(filepath_or_buffer= file_name, encoding= "utf8", sep= ",") # file_name を指定して csv を読み込む
ax = fig.add_subplot(111)
ax.set_aspect('equal') # aspect ratio is equal
ax.set_xlim([-500,1500]) # set x axis value limit
ax.set_ylim([-500,1500]) # set y axis value limit
ax.set_xlabel('x') # name x label "x"
ax.set_ylabel('y') # name y label "y"
ax.scatter(csv_input["X"], csv_input["Y"], c='red')
ax.grid()
ax.plot()
fig.savefig("original_" + file_name + ".png")
original_data_label = tk.Label(text= "original") # 元データラベルの作成
original_data_label.grid(row= 7, column= 0, sticky= 'news', padx= 5, pady= 5)
canvas_original = FigureCanvasTkAgg(fig, display)
canvas_original.get_tk_widget().grid(row= 8, column= 0, sticky= 'news', padx= 5, pady= 5)
# -----------------------------------------------------------------------------------------------------------
# --- クラスタリング済みデータのプロットのための関数 ---------------------------------------------------------------
def plot_cluster_list(file_name, cluster_list, color, method_name):
# Figureインスタンスを生成
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_aspect('equal')
ax.set_xlim([-500,1500])
ax.set_ylim([-500,1500])
for i in range(0, len(cluster_list)): # cluster_list に含まれるクラスターの数だけループする
cluster = cluster_list[i] # cluster_list から1つずつ取り出す
c = color[i % len(color)] # プロットの色
csv_input = pd.DataFrame(np.array(cluster)) # プロット用データの準備
ax.scatter(csv_input[0], csv_input[1], c=c)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid()
ax.plot()
fig.savefig(method_name + "_" + file_name + ".png")
return fig
# -----------------------------------------------------------------------------------------------------------
# --- 最短距離法 -----------------------------------------------------------------------------------------------------------
def shortest_method(num_of_cluster, file_name):
csv_input = pd.read_csv(filepath_or_buffer= file_name, encoding= "utf8", sep= ",") # file_name を指定して csv を読み込む
cluster_list = clustering.make_1elem_cluster(csv_input)
while len(cluster_list) > num_of_cluster:
cluster_list = clustering.shortest(cluster_list)
return cluster_list
# ---------------------------------------------------------------------------------------------------------------------------------------------
# --- 最長距離法 ----------------------------------------------------------------------------------------------------------
def longest_method(num_of_cluster, file_name):
csv_input = pd.read_csv(filepath_or_buffer= file_name, encoding= "utf8", sep= ",") # file_name を指定して csv を読み込む
cluster_list = clustering.make_1elem_cluster(csv_input)
while len(cluster_list) > num_of_cluster:
cluster_list = clustering.longest(cluster_list)
return cluster_list
# ---------------------------------------------------------------------------------------------------------------------------------------------
# --- 重心法 -----------------------------------------------------------------------------------------------------------------------
def balance_method(num_of_cluster, file_name):
csv_input = pd.read_csv(filepath_or_buffer= file_name, encoding= "utf8", sep= ",") # file_name を指定して csv を読み込む
cluster_list = clustering.make_1elem_cluster(csv_input)
while len(cluster_list) > num_of_cluster:
cluster_list = clustering.balance(cluster_list)
return cluster_list
# ---------------------------------------------------------------------------------------------------------------------------------------------
# 関数の定義
# --- 利用するデータファイルを選択するための関数 ----------------------------------------------------------------------------------------------------------------------------------------------------
def select_mode(): # この関数は使いません。file_select関数で参照ボタンからファイルを選択できるようになっています。
print("1. m2sd50.csv\n2. m2sd200.csv\n3. m3sd50.csv\n4. m3sd200.csv\n5. m4sd50.csv\n6. m4sd200.csv\n7. m5sd50.csv\n8. m5sd200.csv\n9. m9sd50.csv\n10. m9sd200.csv \n")
mode = input("mode = ")
if (mode == "1"):
csv_input = pd.read_csv(filepath_or_buffer="m2sd50.csv", encoding="utf8", sep=",")
print("データファイル : m2sd50.csv")
elif (mode == "2"):
csv_input = pd.read_csv(filepath_or_buffer="m2sd200.csv", encoding="utf8", sep=",")
print("データファイル : m2sd200.csv")
elif (mode == "3"):
csv_input = pd.read_csv(filepath_or_buffer="m3sd50.csv", encoding="utf8", sep=",")
print("データファイル : m3sd50.csv")
elif (mode == "4"):
csv_input = pd.read_csv(filepath_or_buffer="m3sd200.csv", encoding="utf8", sep=",")
print("データファイル : m3sd200.csv")
elif (mode == "5"):
csv_input = pd.read_csv(filepath_or_buffer="m4sd50.csv", encoding="utf8", sep=",")
print("データファイル : m4sd50.csv")
elif (mode == "6"):
csv_input = pd.read_csv(filepath_or_buffer="m4sd200.csv", encoding="utf8", sep=",")
print("データファイル : m4sd200.csv")
elif (mode == "7"):
csv_input = pd.read_csv(filepath_or_buffer="m5sd50.csv", encoding="utf8", sep=",")
print("データファイル : m5sd50.csv")
elif (mode == "8"):
csv_input = pd.read_csv(filepath_or_buffer="m5sd200.csv", encoding="utf8", sep=",")
print("データファイル : m5sd200.csv")
elif (mode == "9"):
csv_input = pd.read_csv(filepath_or_buffer="m9sd50.csv", encoding="utf8", sep=",")
print("データファイル : m9sd50.csv")
elif (mode == "10"):
csv_input = pd.read_csv(filepath_or_buffer="m9sd200.csv", encoding="utf8", sep=",")
print("データファイル : m9sd200.csv")
return csv_input
# -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# === Functions for GUI action =============================================================
# ファイル参照ボタンを押したときに実行する関数
def file_select():
dir = '/Users/kosei/yama/4EJ/4年 情報工学実験/10 クラスタリング/program4clustering' # 初期参照フォルダ
extension = [("すべて", "*"), ("CSV","*.csv")] # select file extension
file_path = tk.filedialog.askopenfilename(filetypes= extension, initialdir= dir) # get file path
file_name = os.path.basename(file_path) # get file name
ref_box.delete(0, tk.END) # 入力ボックスの初期化(空白にする)
ref_box.insert(tk.END, file_name) # show file name(入力ボックスにファイル名を入力)
os.chdir(os.path.dirname(os.path.abspath(file_path)))
print(file_path) # print
print(file_name) # print
plot_clustering.data_plot(file_name)
# 出力ボタンが押されたときに画像を表示するための関数
def draw():
file_name = ref_box.get() # get file name by getting ref_box value
scale_value = scale.get() # get scale value
num_of_cluster = scale_value
cluster_list_shortest_method = plot_clustering.shortest_method(num_of_cluster, file_name)
cluster_list_longest_method = plot_clustering.longest_method(num_of_cluster, file_name)
cluster_list_balance_method = plot_clustering.balance_method(num_of_cluster, file_name)
fig_shortest = plot_clustering.plot_cluster_list(file_name, cluster_list_shortest_method, color, "shortest")
fig_longest = plot_clustering.plot_cluster_list(file_name, cluster_list_longest_method, color, "longest")
fig_balance = plot_clustering.plot_cluster_list(file_name, cluster_list_balance_method, color, "balance")
shortest_method_name_label = tk.Label(text= 'shortest') # shortest_method_name ラベルの作成
shortest_method_name_label.grid(row= 7, column= 1, sticky= 'news', padx= 5, pady= 5)
canvas_shortest = FigureCanvasTkAgg(fig_shortest, display)
canvas_shortest.get_tk_widget().grid(row= 8, column= 1, sticky= 'news', padx= 5, pady= 5)
longest_method_name_label = tk.Label(text= 'longest') # longest_method_name ラベルの作成
longest_method_name_label.grid(row= 9, column= 0, sticky= 'news', padx= 5, pady= 5)
canvas_longest = FigureCanvasTkAgg(fig_longest, display)
canvas_longest.get_tk_widget().grid(row= 10, column= 0, sticky= 'news', padx= 5, pady= 5)
balance_method_name_label = tk.Label(text= 'balance') # balance_method_name ラベルの作成
balance_method_name_label.grid(row= 9, column= 1, sticky= 'news', padx= 5, pady= 5)
canvas_balance = FigureCanvasTkAgg(fig_balance, display)
canvas_balance.get_tk_widget().grid(row= 10, column= 1, sticky= 'news', padx= 5, pady= 5)
# ==============================================================================================
# === main ========================================================================================================================
# GUI setting
display = tk.Tk() # create instance (create main window)
display.geometry('1000x1200') # set window size
display.title('10 クラスタリング') # set title
color = ['blue', 'red', 'green', 'orange', 'blueviolet', 'gray', 'magenta'] # グラフに使用する色
# ファイル選択部分
# infoラベルの作成
select_file_label = tk.Label(text= "1. ファイル選択") # create label for selecting file
select_file_label.grid(row= 0, column= 0, sticky= 'nws', padx= 5, pady= 5) # position detail setting
# 参照先のファイル名の入力欄の作成
ref_box = tk.Entry(width= 30)
ref_box.grid(row= 1, column= 0, sticky= 'news', padx= 5, pady= 5)
# 参照ボタンの作成
ref_button = tk.Button(text= "参照", command= file_select)
ref_button.grid(row= 1, column= 1, sticky= 'nws', padx= 5, pady= 5)
# 詳細設定(クラスタ数の指定)部分
# infoラベルの作成
detail_setting_label = tk.Label(text= "2. 詳細設定")
detail_setting_label.grid(row= 2, column= 0, sticky= 'nws', padx= 5, pady= 5)
# scaleの作成
scale_label = tk.Label(text= "▷ クラスタ数")
scale_label.grid(row= 3, column= 0, sticky= 'nws')
scale = tk.Scale(orient= tk.HORIZONTAL, from_= 2, to= 100)
scale.grid(row= 4, column= 0, sticky= 'news')
# グラフ出力部分
# infoラベルの作成
graph_label = tk.Label(text= "3. グラフ")
graph_label.grid(row= 5, column= 0, sticky= 'nws', padx= 5, pady= 5)
# 出力ボタン
output_button = tk.Button(text= "グラフ出力", command= draw)
output_button.grid(row= 6, column= 0, sticky= 'nws', padx= 5, pady= 5)
# even if this program is finished, the window never disappears
display.mainloop()
# ========================================================================================
|
[
"os.path.abspath",
"clustering.clustering.balance",
"os.path.basename",
"tkinter.Button",
"pandas.read_csv",
"tkinter.Entry",
"matplotlib.pyplot.Figure",
"clustering.clustering.shortest",
"tkinter.filedialog.askopenfilename",
"tkinter.Scale",
"numpy.array",
"clustering.clustering.longest",
"clustering.clustering.make_1elem_cluster",
"tkinter.Label",
"tkinter.Tk",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg"
] |
[((9495, 9502), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (9500, 9502), True, 'import tkinter as tk\n'), ((9768, 9794), 'tkinter.Label', 'tk.Label', ([], {'text': '"""1. ファイル選択"""'}), "(text='1. ファイル選択')\n", (9776, 9794), True, 'import tkinter as tk\n'), ((9962, 9980), 'tkinter.Entry', 'tk.Entry', ([], {'width': '(30)'}), '(width=30)\n', (9970, 9980), True, 'import tkinter as tk\n'), ((10072, 10113), 'tkinter.Button', 'tk.Button', ([], {'text': '"""参照"""', 'command': 'file_select'}), "(text='参照', command=file_select)\n", (10081, 10113), True, 'import tkinter as tk\n'), ((10240, 10264), 'tkinter.Label', 'tk.Label', ([], {'text': '"""2. 詳細設定"""'}), "(text='2. 詳細設定')\n", (10248, 10264), True, 'import tkinter as tk\n'), ((10369, 10393), 'tkinter.Label', 'tk.Label', ([], {'text': '"""▷ クラスタ数"""'}), "(text='▷ クラスタ数')\n", (10377, 10393), True, 'import tkinter as tk\n'), ((10454, 10501), 'tkinter.Scale', 'tk.Scale', ([], {'orient': 'tk.HORIZONTAL', 'from_': '(2)', 'to': '(100)'}), '(orient=tk.HORIZONTAL, from_=2, to=100)\n', (10462, 10501), True, 'import tkinter as tk\n'), ((10589, 10612), 'tkinter.Label', 'tk.Label', ([], {'text': '"""3. グラフ"""'}), "(text='3. グラフ')\n", (10597, 10612), True, 'import tkinter as tk\n'), ((10707, 10744), 'tkinter.Button', 'tk.Button', ([], {'text': '"""グラフ出力"""', 'command': 'draw'}), "(text='グラフ出力', command=draw)\n", (10716, 10744), True, 'import tkinter as tk\n'), ((7001, 7067), 'tkinter.filedialog.askopenfilename', 'tk.filedialog.askopenfilename', ([], {'filetypes': 'extension', 'initialdir': 'dir'}), '(filetypes=extension, initialdir=dir)\n', (7030, 7067), True, 'import tkinter as tk\n'), ((7103, 7130), 'os.path.basename', 'os.path.basename', (['file_path'], {}), '(file_path)\n', (7119, 7130), False, 'import os\n'), ((8269, 8294), 'tkinter.Label', 'tk.Label', ([], {'text': '"""shortest"""'}), "(text='shortest')\n", (8277, 8294), True, 'import tkinter as tk\n'), ((8438, 8478), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['fig_shortest', 'display'], {}), '(fig_shortest, display)\n', (8455, 8478), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n'), ((8606, 8630), 'tkinter.Label', 'tk.Label', ([], {'text': '"""longest"""'}), "(text='longest')\n", (8614, 8630), True, 'import tkinter as tk\n'), ((8771, 8810), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['fig_longest', 'display'], {}), '(fig_longest, display)\n', (8788, 8810), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n'), ((8938, 8962), 'tkinter.Label', 'tk.Label', ([], {'text': '"""balance"""'}), "(text='balance')\n", (8946, 8962), True, 'import tkinter as tk\n'), ((9103, 9142), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['fig_balance', 'display'], {}), '(fig_balance, display)\n', (9120, 9142), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n'), ((644, 656), 'matplotlib.pyplot.Figure', 'plt.Figure', ([], {}), '()\n', (654, 656), True, 'import matplotlib.pyplot as plt\n'), ((724, 791), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': 'file_name', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer=file_name, encoding='utf8', sep=',')\n", (735, 791), True, 'import pandas as pd\n'), ((1307, 1332), 'tkinter.Label', 'tk.Label', ([], {'text': '"""original"""'}), "(text='original')\n", (1315, 1332), True, 'import tkinter as tk\n'), ((1460, 1491), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['fig', 'display'], {}), '(fig, display)\n', (1477, 1491), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n'), ((1915, 1927), 'matplotlib.pyplot.Figure', 'plt.Figure', ([], {}), '()\n', (1925, 1927), True, 'import matplotlib.pyplot as plt\n'), ((2865, 2932), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': 'file_name', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer=file_name, encoding='utf8', sep=',')\n", (2876, 2932), True, 'import pandas as pd\n'), ((2988, 3028), 'clustering.clustering.make_1elem_cluster', 'clustering.make_1elem_cluster', (['csv_input'], {}), '(csv_input)\n', (3017, 3028), False, 'from clustering import clustering\n'), ((3513, 3580), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': 'file_name', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer=file_name, encoding='utf8', sep=',')\n", (3524, 3580), True, 'import pandas as pd\n'), ((3636, 3676), 'clustering.clustering.make_1elem_cluster', 'clustering.make_1elem_cluster', (['csv_input'], {}), '(csv_input)\n', (3665, 3676), False, 'from clustering import clustering\n'), ((4171, 4238), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': 'file_name', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer=file_name, encoding='utf8', sep=',')\n", (4182, 4238), True, 'import pandas as pd\n'), ((4294, 4334), 'clustering.clustering.make_1elem_cluster', 'clustering.make_1elem_cluster', (['csv_input'], {}), '(csv_input)\n', (4323, 4334), False, 'from clustering import clustering\n'), ((5112, 5182), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': '"""m2sd50.csv"""', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer='m2sd50.csv', encoding='utf8', sep=',')\n", (5123, 5182), True, 'import pandas as pd\n'), ((3107, 3140), 'clustering.clustering.shortest', 'clustering.shortest', (['cluster_list'], {}), '(cluster_list)\n', (3126, 3140), False, 'from clustering import clustering\n'), ((3755, 3787), 'clustering.clustering.longest', 'clustering.longest', (['cluster_list'], {}), '(cluster_list)\n', (3773, 3787), False, 'from clustering import clustering\n'), ((4413, 4445), 'clustering.clustering.balance', 'clustering.balance', (['cluster_list'], {}), '(cluster_list)\n', (4431, 4445), False, 'from clustering import clustering\n'), ((5251, 5322), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': '"""m2sd200.csv"""', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer='m2sd200.csv', encoding='utf8', sep=',')\n", (5262, 5322), True, 'import pandas as pd\n'), ((7301, 7327), 'os.path.abspath', 'os.path.abspath', (['file_path'], {}), '(file_path)\n', (7316, 7327), False, 'import os\n'), ((2293, 2310), 'numpy.array', 'np.array', (['cluster'], {}), '(cluster)\n', (2301, 2310), True, 'import numpy as np\n'), ((5392, 5462), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': '"""m3sd50.csv"""', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer='m3sd50.csv', encoding='utf8', sep=',')\n", (5403, 5462), True, 'import pandas as pd\n'), ((5531, 5602), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': '"""m3sd200.csv"""', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer='m3sd200.csv', encoding='utf8', sep=',')\n", (5542, 5602), True, 'import pandas as pd\n'), ((5672, 5742), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': '"""m4sd50.csv"""', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer='m4sd50.csv', encoding='utf8', sep=',')\n", (5683, 5742), True, 'import pandas as pd\n'), ((5811, 5882), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': '"""m4sd200.csv"""', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer='m4sd200.csv', encoding='utf8', sep=',')\n", (5822, 5882), True, 'import pandas as pd\n'), ((5952, 6022), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': '"""m5sd50.csv"""', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer='m5sd50.csv', encoding='utf8', sep=',')\n", (5963, 6022), True, 'import pandas as pd\n'), ((6091, 6162), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': '"""m5sd200.csv"""', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer='m5sd200.csv', encoding='utf8', sep=',')\n", (6102, 6162), True, 'import pandas as pd\n'), ((6232, 6302), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': '"""m9sd50.csv"""', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer='m9sd50.csv', encoding='utf8', sep=',')\n", (6243, 6302), True, 'import pandas as pd\n'), ((6372, 6443), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': '"""m9sd200.csv"""', 'encoding': '"""utf8"""', 'sep': '""","""'}), "(filepath_or_buffer='m9sd200.csv', encoding='utf8', sep=',')\n", (6383, 6443), True, 'import pandas as pd\n')]
|
from urlparse import urlparse, urlunparse
import re
from bs4 import BeautifulSoup
import requests
from .base import BaseCrawler
from ...models import Entity, Author, AuthorType
class StandardMediaCrawler(BaseCrawler):
SM_RE = re.compile('(www\.)?standardmedia.co.ke')
def offer(self, url):
""" Can this crawler process this URL? """
parts = urlparse(url)
return bool(self.SM_RE.match(parts.netloc))
def extract(self, doc, raw_html):
""" Extract text and other things from the raw_html for this document. """
super(StandardMediaCrawler, self).extract(doc, raw_html)
soup = BeautifulSoup(raw_html)
# gather title
doc.title = self.extract_plaintext(soup.select(".site-wrapper .container .main-title-inner h2"))
#gather publish date
published_text = soup.find(attrs={"name":"pubdate"})['content']
doc.published_at = self.parse_timestamp(published_text)
#gather text and summary
nodes = soup.select(".main-article p")
if len(nodes) > 1:
doc.summary = self.extract_plaintext(nodes[0:1])
doc.text = "\n\n".join(p.text.strip() for p in nodes)
# gather author
author = self.extract_plaintext(soup.select(".site-wrapper .container .date")).replace("By ", '')
if author:
doc.author = Author.get_or_create(author.strip(), AuthorType.journalist())
else:
doc.author = Author.unknown()
|
[
"bs4.BeautifulSoup",
"urlparse.urlparse",
"re.compile"
] |
[((233, 275), 're.compile', 're.compile', (['"""(www\\\\.)?standardmedia.co.ke"""'], {}), "('(www\\\\.)?standardmedia.co.ke')\n", (243, 275), False, 'import re\n'), ((369, 382), 'urlparse.urlparse', 'urlparse', (['url'], {}), '(url)\n', (377, 382), False, 'from urlparse import urlparse, urlunparse\n'), ((638, 661), 'bs4.BeautifulSoup', 'BeautifulSoup', (['raw_html'], {}), '(raw_html)\n', (651, 661), False, 'from bs4 import BeautifulSoup\n')]
|
import torch
import argparse
from os import path
from sys import version_info
from collections import OrderedDict
from torch.utils.model_zoo import load_url
if version_info[0] < 3:
import urllib
else:
import urllib.request
options_list = ['all', 'caffe-vgg16', 'caffe-vgg19', 'caffe-nin', 'caffe-googlenet-places205', 'caffe-googlenet-places365', 'caffe-googlenet-bvlc', 'caffe-googlenet-cars', 'caffe-googlenet-sos', \
'caffe-resnet-opennsfw', 'pytorch-vgg16', 'pytorch-vgg19', 'pytorch-googlenet', 'pytorch-inceptionv3', 'tensorflow-inception5h', 'keras-inceptionv3', 'all-caffe', 'all-caffe-googlenet']
def main():
params = params_list()
if params.models == 'all':
params.models = options_list[1:16]
elif 'all-caffe' in params.models and 'all-caffe-googlenet' not in params.models:
params.models = options_list[1:10] + params.models.split(',')
elif 'all-caffe-googlenet' in params.models:
params.models = options_list[4:9] + params.models.split(',')
else:
params.models = params.models.split(',')
if 'caffe-vgg19' in params.models:
# Download the VGG-19 ILSVRC model and fix the layer names
print("Downloading the VGG-19 ILSVRC model")
sd = load_url("https://web.eecs.umich.edu/~justincj/models/vgg19-d01eb7cb.pth")
map = {'classifier.1.weight':u'classifier.0.weight', 'classifier.1.bias':u'classifier.0.bias', 'classifier.4.weight':u'classifier.3.weight', 'classifier.4.bias':u'classifier.3.bias'}
sd = OrderedDict([(map[k] if k in map else k,v) for k,v in sd.items()])
torch.save(sd, path.join(params.download_path, "vgg19-d01eb7cb.pth"))
if 'caffe-vgg16' in params.models:
# Download the VGG-16 ILSVRC model and fix the layer names
print("Downloading the VGG-16 ILSVRC model")
sd = load_url("https://web.eecs.umich.edu/~justincj/models/vgg16-00b39a1b.pth")
map = {'classifier.1.weight':u'classifier.0.weight', 'classifier.1.bias':u'classifier.0.bias', 'classifier.4.weight':u'classifier.3.weight', 'classifier.4.bias':u'classifier.3.bias'}
sd = OrderedDict([(map[k] if k in map else k,v) for k,v in sd.items()])
torch.save(sd, path.join(params.download_path, "vgg16-00b39a1b.pth"))
if 'caffe-nin' in params.models:
# Download the NIN model
print("Downloading the NIN model")
fileurl = "https://raw.githubusercontent.com/ProGamerGov/pytorch-nin/master/nin_imagenet.pth"
name = "nin_imagenet.pth"
download_file(fileurl, name, params.download_path)
if 'caffe-googlenet-places205' in params.models:
# Download the Caffe GoogeLeNet Places205 model
print("Downloading the Places205 GoogeLeNet model")
fileurl = "https://github.com/ProGamerGov/pytorch-places/raw/master/googlenet_places205.pth"
name = "googlenet_places205.pth"
download_file(fileurl, name, params.download_path)
if 'caffe-googlenet-places365' in params.models:
# Download the Caffe GoogeLeNet Places365 model
print("Downloading the Places365 GoogeLeNet model")
fileurl = "https://github.com/ProGamerGov/pytorch-places/raw/master/googlenet_places365.pth"
name = "googlenet_places365.pth"
download_file(fileurl, name, params.download_path)
if 'caffe-googlenet-bvlc' in params.models:
# Download the Caffe BVLC GoogeLeNet model
print("Downloading the BVLC GoogeLeNet model")
fileurl = "https://github.com/ProGamerGov/pytorch-old-caffemodels/raw/master/bvlc_googlenet.pth"
name = "bvlc_googlenet.pth"
download_file(fileurl, name, params.download_path)
if 'caffe-googlenet-cars' in params.models:
# Download the Caffe GoogeLeNet Cars model
print("Downloading the Cars GoogeLeNet model")
fileurl = "https://github.com/ProGamerGov/pytorch-old-caffemodels/raw/master/googlenet_finetune_web_cars.pth"
name = "googlenet_finetune_web_cars.pth"
download_file(fileurl, name, params.download_path)
if 'caffe-googlenet-sos' in params.models:
# Download the Caffe GoogeLeNet SOS model
print("Downloading the SOD GoogeLeNet model")
fileurl = "https://github.com/ProGamerGov/pytorch-old-caffemodels/raw/master/GoogleNet_SOS.pth"
name = "GoogleNet_SOS.pth"
download_file(fileurl, name, params.download_path)
if 'pytorch-vgg19' in params.models:
# Download the PyTorch VGG19 model
print("Downloading the PyTorch VGG 19 model")
fileurl = "https://download.pytorch.org/models/vgg19-dcbb9e9d.pth"
name = "vgg19-dcbb9e9d.pth"
download_file(fileurl, name, params.download_path)
if 'pytorch-vgg16' in params.models:
# Download the PyTorch VGG16 model
print("Downloading the PyTorch VGG 16 model")
fileurl = "https://download.pytorch.org/models/vgg16-397923af.pth"
name = "vgg16-397923af.pth"
download_file(fileurl, name, params.download_path)
if 'pytorch-googlenet' in params.models:
# Download the PyTorch GoogLeNet model
print("Downloading the PyTorch GoogLeNet model")
fileurl = "https://download.pytorch.org/models/googlenet-1378be20.pth"
name = "googlenet-1378be20.pth"
download_file(fileurl, name, params.download_path)
if 'pytorch-inception' in params.models:
# Download the PyTorch Inception V3 model
print("Downloading the PyTorch Inception V3 model")
fileurl = "https://download.pytorch.org/models/inception_v3_google-1a9a5a14.pth"
name = "inception_v3_google-1a9a5a14.pth"
download_file(fileurl, name, params.download_path)
if 'tensorflow-inception5h' in params.models:
# Download the Inception5h model
print("Downloading the TensorFlow Inception5h model")
fileurl = "https://github.com/ProGamerGov/pytorch-old-tensorflow-models/raw/master/inception5h.pth"
name = "inception5h.pth"
download_file(fileurl, name, params.download_path)
if 'keras-inceptionv3' in params.models:
# Download the Keras Inception V3 model
print("Downloading the Keras Inception V3 model")
fileurl = "https://github.com/ProGamerGov/pytorch-old-tensorflow-models/raw/master/inceptionv3_keras.pth"
name = "inceptionv3_keras.pth"
download_file(fileurl, name, params.download_path)
if 'caffe-resnet-opennsfw' in params.models:
# Download the ResNet Yahoo Open NSFW model
print("Downloading the ResNet Yahoo Open NSFW model")
fileurl = "https://github.com/ProGamerGov/pytorch-old-caffemodels/raw/master/ResNet_50_1by2_nsfw.pth"
name = "ResNet_50_1by2_nsfw.pth"
download_file(fileurl, name, params.download_path)
print("All selected models have been successfully downloaded")
def params_list():
parser = argparse.ArgumentParser()
parser.add_argument("-models", help="Models to download", default='caffe-googlenet-bvlc,caffe-nin', action=MultipleChoice)
parser.add_argument("-download_path", help="Download location for models", default='models')
params = parser.parse_args()
return params
def download_file(fileurl, name, download_path):
if version_info[0] < 3:
urllib.URLopener().retrieve(fileurl, path.join(download_path, name))
else:
urllib.request.urlretrieve(fileurl, path.join(download_path, name))
class MultipleChoice(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
self.options = options_list
e = [o.lower() for o in values.split(',') if o.lower() not in self.options]
if len(e) > 0:
raise argparse.ArgumentError(self, 'invalid choices: ' + ','.join([str(v) for v in e]) +
' (choose from ' + ','.join([ "'"+str(v)+"'" for v in self.options])+')')
setattr(namespace, self.dest, values)
if __name__ == "__main__":
main()
|
[
"urllib.URLopener",
"os.path.join",
"argparse.ArgumentParser",
"torch.utils.model_zoo.load_url"
] |
[((6906, 6931), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6929, 6931), False, 'import argparse\n'), ((1254, 1328), 'torch.utils.model_zoo.load_url', 'load_url', (['"""https://web.eecs.umich.edu/~justincj/models/vgg19-d01eb7cb.pth"""'], {}), "('https://web.eecs.umich.edu/~justincj/models/vgg19-d01eb7cb.pth')\n", (1262, 1328), False, 'from torch.utils.model_zoo import load_url\n'), ((1851, 1925), 'torch.utils.model_zoo.load_url', 'load_url', (['"""https://web.eecs.umich.edu/~justincj/models/vgg16-00b39a1b.pth"""'], {}), "('https://web.eecs.umich.edu/~justincj/models/vgg16-00b39a1b.pth')\n", (1859, 1925), False, 'from torch.utils.model_zoo import load_url\n'), ((1623, 1676), 'os.path.join', 'path.join', (['params.download_path', '"""vgg19-d01eb7cb.pth"""'], {}), "(params.download_path, 'vgg19-d01eb7cb.pth')\n", (1632, 1676), False, 'from os import path\n'), ((2220, 2273), 'os.path.join', 'path.join', (['params.download_path', '"""vgg16-00b39a1b.pth"""'], {}), "(params.download_path, 'vgg16-00b39a1b.pth')\n", (2229, 2273), False, 'from os import path\n'), ((7331, 7361), 'os.path.join', 'path.join', (['download_path', 'name'], {}), '(download_path, name)\n', (7340, 7361), False, 'from os import path\n'), ((7417, 7447), 'os.path.join', 'path.join', (['download_path', 'name'], {}), '(download_path, name)\n', (7426, 7447), False, 'from os import path\n'), ((7294, 7312), 'urllib.URLopener', 'urllib.URLopener', ([], {}), '()\n', (7310, 7312), False, 'import urllib\n')]
|
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.test.client import Client
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
class AdminTestCase(TestCase):
@classmethod
def setUpTestData(cls):
super(AdminTestCase, cls).setUpTestData()
# Editor
cls.editor = get_user_model().objects.create(
username="editor",
email="<EMAIL>",
is_superuser=True,
is_staff=True
)
cls.editor.set_password("password")
cls.editor.save()
def setUp(self):
super(AdminTestCase, self).setUp()
self.client.login(username="editor", password="password")
def test_add(self):
response = self.client.get("/admin/listing/listing/add/")
self.assertEqual(response.status_code, 200)
self.assertContains(
response,
"""<img src="/static/admin/listing/images/horizontal.png" style="max-width: 128px;" />"""
)
|
[
"django.contrib.auth.get_user_model"
] |
[((396, 412), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (410, 412), False, 'from django.contrib.auth import get_user_model\n')]
|
import pytest
from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, \
RequestFailedError
def ensure_second_feed_enabled(api_conf: callable):
feed_list_resp = http_get(['system', 'feeds'], config=api_conf)
if feed_list_resp.code != 200:
raise RequestFailedError(feed_list_resp.url, feed_list_resp.code, feed_list_resp.body)
resp = http_put(['system', 'feeds', feed_list_resp.body[0].get('name')], query={'enabled': True}, config=api_conf)
if resp.code != 200:
raise RequestFailedError(resp.url, resp.code, resp.body)
class TestSystemAPIDeleteReturns200:
@pytest.mark.skip(reason="This is taking a really long time to run for some reason")
def test_disable_and_delete_system_feeds(self, api_conf):
"""
Since this does kinda change some of the state around feeds be sure to not re-order without considering the
other feed-related tests below
"""
feed_list_resp = http_get(['system', 'feeds'], config=api_conf)
assert feed_list_resp == APIResponse(200)
# Pick arbitrary first feed to disable & then delete
feeds = feed_list_resp.body
feed_to_delete = feeds[0].get('name')
resp = http_put(['system', 'feeds', feed_to_delete], None, {'enabled': False}, config=api_conf)
assert resp == APIResponse(200)
resp = http_del(['system', 'feeds', feed_to_delete], config=api_conf)
assert resp == APIResponse(200)
@pytest.mark.skip(reason="This is taking a really long time to run for some reason")
def test_disable_and_delete_feed_group(self, api_conf):
ensure_second_feed_enabled(api_conf)
feed_list_resp = http_get(['system', 'feeds'], config=api_conf)
assert feed_list_resp == APIResponse(200)
# Pick 2nd feed
feeds = feed_list_resp.body
feed = feeds[1]
feed_name = feed.get('name')
# Arbitrarily pick 1st group
groups = feed.get('groups', [])
group_to_delete = groups[0].get('name')
resp = http_put(['system', 'feeds', feed_name, group_to_delete], None, {'enabled': False}, config=api_conf)
assert resp == APIResponse(200)
resp = http_del(['system', 'feeds', feed_name, group_to_delete], config=api_conf)
assert resp == APIResponse(200)
|
[
"tests.functional.services.utils.http_utils.APIResponse",
"tests.functional.services.utils.http_utils.http_get",
"tests.functional.services.utils.http_utils.http_put",
"tests.functional.services.utils.http_utils.http_del",
"pytest.mark.skip",
"tests.functional.services.utils.http_utils.RequestFailedError"
] |
[((213, 259), 'tests.functional.services.utils.http_utils.http_get', 'http_get', (["['system', 'feeds']"], {'config': 'api_conf'}), "(['system', 'feeds'], config=api_conf)\n", (221, 259), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((645, 733), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""This is taking a really long time to run for some reason"""'}), "(reason=\n 'This is taking a really long time to run for some reason')\n", (661, 733), False, 'import pytest\n'), ((1506, 1594), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""This is taking a really long time to run for some reason"""'}), "(reason=\n 'This is taking a really long time to run for some reason')\n", (1522, 1594), False, 'import pytest\n'), ((309, 394), 'tests.functional.services.utils.http_utils.RequestFailedError', 'RequestFailedError', (['feed_list_resp.url', 'feed_list_resp.code', 'feed_list_resp.body'], {}), '(feed_list_resp.url, feed_list_resp.code, feed_list_resp.body\n )\n', (327, 394), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((549, 599), 'tests.functional.services.utils.http_utils.RequestFailedError', 'RequestFailedError', (['resp.url', 'resp.code', 'resp.body'], {}), '(resp.url, resp.code, resp.body)\n', (567, 599), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((995, 1041), 'tests.functional.services.utils.http_utils.http_get', 'http_get', (["['system', 'feeds']"], {'config': 'api_conf'}), "(['system', 'feeds'], config=api_conf)\n", (1003, 1041), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((1252, 1344), 'tests.functional.services.utils.http_utils.http_put', 'http_put', (["['system', 'feeds', feed_to_delete]", 'None', "{'enabled': False}"], {'config': 'api_conf'}), "(['system', 'feeds', feed_to_delete], None, {'enabled': False},\n config=api_conf)\n", (1260, 1344), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((1397, 1459), 'tests.functional.services.utils.http_utils.http_del', 'http_del', (["['system', 'feeds', feed_to_delete]"], {'config': 'api_conf'}), "(['system', 'feeds', feed_to_delete], config=api_conf)\n", (1405, 1459), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((1720, 1766), 'tests.functional.services.utils.http_utils.http_get', 'http_get', (["['system', 'feeds']"], {'config': 'api_conf'}), "(['system', 'feeds'], config=api_conf)\n", (1728, 1766), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((2081, 2185), 'tests.functional.services.utils.http_utils.http_put', 'http_put', (["['system', 'feeds', feed_name, group_to_delete]", 'None', "{'enabled': False}"], {'config': 'api_conf'}), "(['system', 'feeds', feed_name, group_to_delete], None, {'enabled':\n False}, config=api_conf)\n", (2089, 2185), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((2238, 2312), 'tests.functional.services.utils.http_utils.http_del', 'http_del', (["['system', 'feeds', feed_name, group_to_delete]"], {'config': 'api_conf'}), "(['system', 'feeds', feed_name, group_to_delete], config=api_conf)\n", (2246, 2312), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((1075, 1091), 'tests.functional.services.utils.http_utils.APIResponse', 'APIResponse', (['(200)'], {}), '(200)\n', (1086, 1091), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((1364, 1380), 'tests.functional.services.utils.http_utils.APIResponse', 'APIResponse', (['(200)'], {}), '(200)\n', (1375, 1380), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((1483, 1499), 'tests.functional.services.utils.http_utils.APIResponse', 'APIResponse', (['(200)'], {}), '(200)\n', (1494, 1499), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((1800, 1816), 'tests.functional.services.utils.http_utils.APIResponse', 'APIResponse', (['(200)'], {}), '(200)\n', (1811, 1816), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((2205, 2221), 'tests.functional.services.utils.http_utils.APIResponse', 'APIResponse', (['(200)'], {}), '(200)\n', (2216, 2221), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n'), ((2336, 2352), 'tests.functional.services.utils.http_utils.APIResponse', 'APIResponse', (['(200)'], {}), '(200)\n', (2347, 2352), False, 'from tests.functional.services.utils.http_utils import http_get, APIResponse, http_put, http_del, RequestFailedError\n')]
|
import re
from typing import Any, Iterable, List, Mapping, Optional, cast
from ..language import (
BooleanValueNode, EnumValueNode, FloatValueNode, IntValueNode,
ListValueNode, NameNode, NullValueNode, ObjectFieldNode,
ObjectValueNode, StringValueNode, ValueNode)
from ..pyutils import is_nullish, is_invalid
from ..type import (
GraphQLID, GraphQLInputType, GraphQLInputObjectType,
GraphQLList, GraphQLNonNull,
is_enum_type, is_input_object_type, is_list_type,
is_non_null_type, is_scalar_type)
__all__ = ['ast_from_value']
_re_integer_string = re.compile('^-?(0|[1-9][0-9]*)$')
def ast_from_value(value: Any, type_: GraphQLInputType) -> Optional[ValueNode]:
"""Produce a GraphQL Value AST given a Python value.
A GraphQL type must be provided, which will be used to interpret different
Python values.
| JSON Value | GraphQL Value |
| ------------- | -------------------- |
| Object | Input Object |
| Array | List |
| Boolean | Boolean |
| String | String / Enum Value |
| Number | Int / Float |
| Mixed | Enum Value |
| null | NullValue |
"""
if is_non_null_type(type_):
type_ = cast(GraphQLNonNull, type_)
ast_value = ast_from_value(value, type_.of_type)
if isinstance(ast_value, NullValueNode):
return None
return ast_value
# only explicit None, not INVALID or NaN
if value is None:
return NullValueNode()
# INVALID or NaN
if is_invalid(value):
return None
# Convert Python list to GraphQL list. If the GraphQLType is a list, but
# the value is not a list, convert the value using the list's item type.
if is_list_type(type_):
type_ = cast(GraphQLList, type_)
item_type = type_.of_type
if isinstance(value, Iterable) and not isinstance(value, str):
value_nodes = [
ast_from_value(item, item_type) # type: ignore
for item in value]
return ListValueNode(values=value_nodes)
return ast_from_value(value, item_type) # type: ignore
# Populate the fields of the input object by creating ASTs from each value
# in the Python dict according to the fields in the input type.
if is_input_object_type(type_):
if value is None or not isinstance(value, Mapping):
return None
type_ = cast(GraphQLInputObjectType, type_)
field_nodes: List[ObjectFieldNode] = []
append_node = field_nodes.append
for field_name, field in type_.fields.items():
if field_name in value:
field_value = ast_from_value(value[field_name], field.type)
if field_value:
append_node(ObjectFieldNode(
name=NameNode(value=field_name), value=field_value))
return ObjectValueNode(fields=field_nodes)
if is_scalar_type(type_) or is_enum_type(type_):
# Since value is an internally represented value, it must be serialized
# to an externally represented value before converting into an AST.
serialized = type_.serialize(value) # type: ignore
if is_nullish(serialized):
return None
# Others serialize based on their corresponding Python scalar types.
if isinstance(serialized, bool):
return BooleanValueNode(value=serialized)
# Python ints and floats correspond nicely to Int and Float values.
if isinstance(serialized, int):
return IntValueNode(value=f'{serialized:d}')
if isinstance(serialized, float):
return FloatValueNode(value=f'{serialized:g}')
if isinstance(serialized, str):
# Enum types use Enum literals.
if is_enum_type(type_):
return EnumValueNode(value=serialized)
# ID types can use Int literals.
if type_ is GraphQLID and _re_integer_string.match(serialized):
return IntValueNode(value=serialized)
return StringValueNode(value=serialized)
raise TypeError(f'Cannot convert value to AST: {serialized!r}')
raise TypeError(f'Unknown type: {type_!r}.')
|
[
"typing.cast",
"re.compile"
] |
[((577, 610), 're.compile', 're.compile', (['"""^-?(0|[1-9][0-9]*)$"""'], {}), "('^-?(0|[1-9][0-9]*)$')\n", (587, 610), False, 'import re\n'), ((1312, 1339), 'typing.cast', 'cast', (['GraphQLNonNull', 'type_'], {}), '(GraphQLNonNull, type_)\n', (1316, 1339), False, 'from typing import Any, Iterable, List, Mapping, Optional, cast\n'), ((1861, 1885), 'typing.cast', 'cast', (['GraphQLList', 'type_'], {}), '(GraphQLList, type_)\n', (1865, 1885), False, 'from typing import Any, Iterable, List, Mapping, Optional, cast\n'), ((2519, 2554), 'typing.cast', 'cast', (['GraphQLInputObjectType', 'type_'], {}), '(GraphQLInputObjectType, type_)\n', (2523, 2554), False, 'from typing import Any, Iterable, List, Mapping, Optional, cast\n')]
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='presets'),
path('search', views.search, name='search'),
path('preset/<slug:slug>', views.preset, name='viewpreset')
]
|
[
"django.urls.path"
] |
[((71, 108), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""presets"""'}), "('', views.index, name='presets')\n", (75, 108), False, 'from django.urls import path\n'), ((114, 157), 'django.urls.path', 'path', (['"""search"""', 'views.search'], {'name': '"""search"""'}), "('search', views.search, name='search')\n", (118, 157), False, 'from django.urls import path\n'), ((163, 222), 'django.urls.path', 'path', (['"""preset/<slug:slug>"""', 'views.preset'], {'name': '"""viewpreset"""'}), "('preset/<slug:slug>', views.preset, name='viewpreset')\n", (167, 222), False, 'from django.urls import path\n')]
|
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 <NAME>
# 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.
"""Generic Node base class for all workers that run on hosts."""
import os
from oslo.config import cfg
from brick.i18n import _
from brick.openstack.common import importutils
from brick.openstack.common import log as logging
from brick.openstack.common import processutils
from brick.openstack.common import service
from brick import wsgi
LOG = logging.getLogger(__name__)
service_opts = [
cfg.IntOpt('report_interval',
default=10,
help='Interval, in seconds, between nodes reporting state '
'to datastore'),
cfg.IntOpt('periodic_interval',
default=60,
help='Interval, in seconds, between running periodic tasks'),
cfg.IntOpt('periodic_fuzzy_delay',
default=60,
help='Range, in seconds, to randomly delay when starting the'
' periodic task scheduler to reduce stampeding.'
' (Disable by setting to 0)'),
cfg.StrOpt('osapi_brick_listen',
default="0.0.0.0",
help='IP address on which OpenStack Volume API listens'),
cfg.IntOpt('osapi_brick_listen_port',
default=8796,
help='Port on which OpenStack Volume API listens'),
cfg.IntOpt('osapi_brick_workers',
help='Number of workers for OpenStack Volume API service. '
'The default is equal to the number of CPUs available.'), ]
CONF = cfg.CONF
CONF.register_opts(service_opts)
class WSGIService(object):
"""Provides ability to launch API from a 'paste' configuration."""
def __init__(self, name, loader=None):
"""Initialize, but do not start the WSGI server.
:param name: The name of the WSGI server given to the loader.
:param loader: Loads the WSGI application using the given name.
:returns: None
"""
self.name = name
self.manager = self._get_manager()
self.loader = loader or wsgi.Loader()
self.app = self.loader.load_app(name)
self.host = getattr(CONF, '%s_listen' % name, "0.0.0.0")
self.port = getattr(CONF, '%s_listen_port' % name, 0)
self.workers = getattr(CONF, '%s_workers' % name,
processutils.get_worker_count())
if self.workers < 1:
LOG.warn(_("Value of config option %(name)s_workers must be "
"integer greater than 1. Input value ignored.") %
{'name': name})
# Reset workers to default
self.workers = processutils.get_worker_count()
self.server = wsgi.Server(name,
self.app,
host=self.host,
port=self.port)
def _get_manager(self):
"""Initialize a Manager object appropriate for this service.
Use the service name to look up a Manager subclass from the
configuration and initialize an instance. If no class name
is configured, just return None.
:returns: a Manager instance, or None.
"""
fl = '%s_manager' % self.name
if fl not in CONF:
return None
manager_class_name = CONF.get(fl, None)
if not manager_class_name:
return None
manager_class = importutils.import_class(manager_class_name)
return manager_class()
def start(self):
"""Start serving this service using loaded configuration.
Also, retrieve updated port number in case '0' was passed in, which
indicates a random port should be used.
:returns: None
"""
if self.manager:
self.manager.init_host()
self.server.start()
self.port = self.server.port
def stop(self):
"""Stop serving this API.
:returns: None
"""
self.server.stop()
def wait(self):
"""Wait for the service to stop serving this API.
:returns: None
"""
self.server.wait()
def reset(self):
"""Reset server greenpool size to default.
:returns: None
"""
self.server.reset()
def process_launcher():
return service.ProcessLauncher()
# NOTE(vish): the global launcher is to maintain the existing
# functionality of calling service.serve +
# service.wait
_launcher = None
def serve(server, workers=None):
global _launcher
if _launcher:
raise RuntimeError(_('serve() can only be called once'))
_launcher = service.launch(server, workers=workers)
def wait():
LOG.debug('Full set of CONF:')
for flag in CONF:
flag_get = CONF.get(flag, None)
# hide flag contents from log if contains a password
# should use secret flag when switch over to openstack-common
if ("_password" in flag or "_key" in flag or
(flag == "sql_connection" and
("mysql:" in flag_get or "postgresql:" in flag_get))):
LOG.debug('%s : FLAG SET ' % flag)
else:
LOG.debug('%(flag)s : %(flag_get)s' %
{'flag': flag, 'flag_get': flag_get})
try:
_launcher.wait()
except KeyboardInterrupt:
_launcher.stop()
class Launcher(object):
def __init__(self):
self.launch_service = serve
self.wait = wait
def get_launcher():
# Note(lpetrut): ProcessLauncher uses green pipes which fail on Windows
# due to missing support of non-blocking I/O pipes. For this reason, the
# service must be spawned differently on Windows, using the ServiceLauncher
# class instead.
if os.name == 'nt':
return Launcher()
else:
return process_launcher()
|
[
"brick.openstack.common.importutils.import_class",
"brick.wsgi.Loader",
"brick.wsgi.Server",
"brick.openstack.common.service.launch",
"brick.openstack.common.processutils.get_worker_count",
"brick.openstack.common.service.ProcessLauncher",
"oslo.config.cfg.IntOpt",
"brick.i18n._",
"oslo.config.cfg.StrOpt",
"brick.openstack.common.log.getLogger"
] |
[((1107, 1134), 'brick.openstack.common.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1124, 1134), True, 'from brick.openstack.common import log as logging\n'), ((1157, 1276), 'oslo.config.cfg.IntOpt', 'cfg.IntOpt', (['"""report_interval"""'], {'default': '(10)', 'help': '"""Interval, in seconds, between nodes reporting state to datastore"""'}), "('report_interval', default=10, help=\n 'Interval, in seconds, between nodes reporting state to datastore')\n", (1167, 1276), False, 'from oslo.config import cfg\n'), ((1330, 1439), 'oslo.config.cfg.IntOpt', 'cfg.IntOpt', (['"""periodic_interval"""'], {'default': '(60)', 'help': '"""Interval, in seconds, between running periodic tasks"""'}), "('periodic_interval', default=60, help=\n 'Interval, in seconds, between running periodic tasks')\n", (1340, 1439), False, 'from oslo.config import cfg\n'), ((1470, 1661), 'oslo.config.cfg.IntOpt', 'cfg.IntOpt', (['"""periodic_fuzzy_delay"""'], {'default': '(60)', 'help': '"""Range, in seconds, to randomly delay when starting the periodic task scheduler to reduce stampeding. (Disable by setting to 0)"""'}), "('periodic_fuzzy_delay', default=60, help=\n 'Range, in seconds, to randomly delay when starting the periodic task scheduler to reduce stampeding. (Disable by setting to 0)'\n )\n", (1480, 1661), False, 'from oslo.config import cfg\n'), ((1733, 1846), 'oslo.config.cfg.StrOpt', 'cfg.StrOpt', (['"""osapi_brick_listen"""'], {'default': '"""0.0.0.0"""', 'help': '"""IP address on which OpenStack Volume API listens"""'}), "('osapi_brick_listen', default='0.0.0.0', help=\n 'IP address on which OpenStack Volume API listens')\n", (1743, 1846), False, 'from oslo.config import cfg\n'), ((1877, 1984), 'oslo.config.cfg.IntOpt', 'cfg.IntOpt', (['"""osapi_brick_listen_port"""'], {'default': '(8796)', 'help': '"""Port on which OpenStack Volume API listens"""'}), "('osapi_brick_listen_port', default=8796, help=\n 'Port on which OpenStack Volume API listens')\n", (1887, 1984), False, 'from oslo.config import cfg\n'), ((2015, 2172), 'oslo.config.cfg.IntOpt', 'cfg.IntOpt', (['"""osapi_brick_workers"""'], {'help': '"""Number of workers for OpenStack Volume API service. The default is equal to the number of CPUs available."""'}), "('osapi_brick_workers', help=\n 'Number of workers for OpenStack Volume API service. The default is equal to the number of CPUs available.'\n )\n", (2025, 2172), False, 'from oslo.config import cfg\n'), ((4988, 5013), 'brick.openstack.common.service.ProcessLauncher', 'service.ProcessLauncher', ([], {}), '()\n', (5011, 5013), False, 'from brick.openstack.common import service\n'), ((5333, 5372), 'brick.openstack.common.service.launch', 'service.launch', (['server'], {'workers': 'workers'}), '(server, workers=workers)\n', (5347, 5372), False, 'from brick.openstack.common import service\n'), ((3378, 3437), 'brick.wsgi.Server', 'wsgi.Server', (['name', 'self.app'], {'host': 'self.host', 'port': 'self.port'}), '(name, self.app, host=self.host, port=self.port)\n', (3389, 3437), False, 'from brick import wsgi\n'), ((4098, 4142), 'brick.openstack.common.importutils.import_class', 'importutils.import_class', (['manager_class_name'], {}), '(manager_class_name)\n', (4122, 4142), False, 'from brick.openstack.common import importutils\n'), ((2734, 2747), 'brick.wsgi.Loader', 'wsgi.Loader', ([], {}), '()\n', (2745, 2747), False, 'from brick import wsgi\n'), ((3010, 3041), 'brick.openstack.common.processutils.get_worker_count', 'processutils.get_worker_count', ([], {}), '()\n', (3039, 3041), False, 'from brick.openstack.common import processutils\n'), ((3324, 3355), 'brick.openstack.common.processutils.get_worker_count', 'processutils.get_worker_count', ([], {}), '()\n', (3353, 3355), False, 'from brick.openstack.common import processutils\n'), ((5278, 5314), 'brick.i18n._', '_', (['"""serve() can only be called once"""'], {}), "('serve() can only be called once')\n", (5279, 5314), False, 'from brick.i18n import _\n'), ((3094, 3197), 'brick.i18n._', '_', (['"""Value of config option %(name)s_workers must be integer greater than 1. Input value ignored."""'], {}), "('Value of config option %(name)s_workers must be integer greater than 1. Input value ignored.'\n )\n", (3095, 3197), False, 'from brick.i18n import _\n')]
|
import torch
import tensorflow as tf
from setuptools import setup
from torch.utils.cpp_extension import CppExtension, CUDA_HOME, CUDAExtension, BuildExtension
sources = ['csrc/hough_voting_binds.cpp']
source_cuda = ['csrc/hough_voting_cuda.cu']
include_dirs = ['csrc', tf.sysconfig.get_include()] # custom include dir here
define_macros = []
extra_compile_args = {"cxx": []}
extension = CUDAExtension
if torch.cuda.is_available() and CUDA_HOME is not None:
# extension = CUDAExtension
sources += source_cuda
define_macros += [("WITH_CUDA", None)]
extra_compile_args["nvcc"] = [
"-DCUDA_HAS_FP16=1",
# "-G", "-g",
"-D__CUDA_NO_HALF_OPERATORS__",
"-D__CUDA_NO_HALF_CONVERSIONS__",
"-D__CUDA_NO_HALF2_OPERATORS__",
]
else:
raise NotImplementedError
module = extension('hough_voting._C',
sources,
include_dirs=include_dirs,
define_macros=define_macros,
extra_compile_args=extra_compile_args,)
setup(name='hough_voting',
ext_modules=[module],
cmdclass={'build_ext': BuildExtension})
|
[
"tensorflow.sysconfig.get_include",
"torch.cuda.is_available",
"setuptools.setup"
] |
[((998, 1090), 'setuptools.setup', 'setup', ([], {'name': '"""hough_voting"""', 'ext_modules': '[module]', 'cmdclass': "{'build_ext': BuildExtension}"}), "(name='hough_voting', ext_modules=[module], cmdclass={'build_ext':\n BuildExtension})\n", (1003, 1090), False, 'from setuptools import setup\n'), ((270, 296), 'tensorflow.sysconfig.get_include', 'tf.sysconfig.get_include', ([], {}), '()\n', (294, 296), True, 'import tensorflow as tf\n'), ((407, 432), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (430, 432), False, 'import torch\n')]
|
import logging
from init import config
logger = logging.getLogger(__name__)
handler = logging.FileHandler(config['DEFAULT']['log_file'])
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
class OrderDto:
def __init__(self,
order_id,
customer_id,
customer_name,
ordered_on,
delivery_appointment,
delivery_method_name,
message,
order_status_name,
delivered_on,
payment_status_name,
paid_on,
total_cost,
has_up_to_date_cost_estimation,
price_to_customer,
paid_by_customer):
self.order_id = order_id
self.customer_id = customer_id
self.customer_name = customer_name
self.ordered_on = ordered_on
self.delivery_appointment = delivery_appointment
self.delivery_method_name = delivery_method_name
self.message = message
self.order_status_name = order_status_name
self.delivered_on = delivered_on
self.payment_status_name = payment_status_name
self.paid_on = paid_on
self.total_cost = total_cost
self.has_up_to_date_cost_estimation = has_up_to_date_cost_estimation
self.price_to_customer = price_to_customer
self.paid_by_customer = paid_by_customer
|
[
"logging.Formatter",
"logging.FileHandler",
"logging.getLogger"
] |
[((50, 77), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (67, 77), False, 'import logging\n'), ((88, 138), 'logging.FileHandler', 'logging.FileHandler', (["config['DEFAULT']['log_file']"], {}), "(config['DEFAULT']['log_file'])\n", (107, 138), False, 'import logging\n'), ((151, 217), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s %(name)s %(levelname)s %(message)"""'], {}), "('%(asctime)s %(name)s %(levelname)s %(message)')\n", (168, 217), False, 'import logging\n')]
|
# ===============================================================================
# Copyright 2015 <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.
# ===============================================================================
# ============= enthought library imports =======================
from __future__ import absolute_import
from pyface.qt.QtCore import Qt
from pyface.qt.QtGui import QColor
from traitsui.tree_node import TreeNode
from pychron.envisage.resources import icon
from pychron.pipeline.engine import Pipeline
from pychron.pipeline.nodes import ReviewNode
class PipelineGroupTreeNode(TreeNode):
icon_name = ""
label = "name"
ICON_MAP = {}
class PipelineTreeNode(TreeNode):
icon_name = ""
label = "name"
def get_background(self, obj):
if isinstance(obj, Pipeline):
c = QColor(Qt.white)
else:
if isinstance(obj, ReviewNode):
if not obj.enabled:
c = QColor("#ff8080") # light red
else:
c = QColor(Qt.cyan)
elif obj.skip_configure:
c = QColor("#D05BFF")
elif not obj.enabled:
c = QColor("#ff8080") # light red
else:
c = super(PipelineTreeNode, self).get_background(obj)
return c
def get_status_color(self, obj):
c = QColor(Qt.white)
if not isinstance(obj, Pipeline):
c = QColor(Qt.lightGray)
if not obj.enabled:
c = QColor("lightblue")
elif obj.visited:
c = QColor("#0dbf81")
elif obj.active:
c = QColor("orange")
return c
def get_icon(self, obj, is_expanded):
name = self.icon_name
if not isinstance(obj, Pipeline):
if not obj.enabled:
name = "cancel"
if name in ICON_MAP:
i = ICON_MAP[name]
else:
if not name:
name = "large_tiles"
i = icon(name)
ICON_MAP[name] = i
return i
# def get_background(self, obj):
# # print 'get', obj, obj.visited
# return 'green' if obj.visited else 'white'
class NodeGroupTreeNode(PipelineTreeNode):
icon_name = ""
class DataTreeNode(PipelineTreeNode):
icon_name = "table"
class FilterTreeNode(PipelineTreeNode):
icon_name = "table_filter"
class IdeogramTreeNode(PipelineTreeNode):
icon_name = "histogram"
class SpectrumTreeNode(PipelineTreeNode):
icon_name = ""
class SeriesTreeNode(PipelineTreeNode):
icon_name = ""
class PDFTreeNode(PipelineTreeNode):
icon_name = "file_pdf"
class GroupingTreeNode(PipelineTreeNode):
pass
class DBSaveTreeNode(PipelineTreeNode):
icon_name = "database_save"
class FindTreeNode(PipelineTreeNode):
icon_name = "find"
class FitTreeNode(PipelineTreeNode):
icon_name = "lightning"
class ReviewTreeNode(PipelineTreeNode):
pass
# ============= EOF =============================================
|
[
"pyface.qt.QtGui.QColor",
"pychron.envisage.resources.icon"
] |
[((1881, 1897), 'pyface.qt.QtGui.QColor', 'QColor', (['Qt.white'], {}), '(Qt.white)\n', (1887, 1897), False, 'from pyface.qt.QtGui import QColor\n'), ((1338, 1354), 'pyface.qt.QtGui.QColor', 'QColor', (['Qt.white'], {}), '(Qt.white)\n', (1344, 1354), False, 'from pyface.qt.QtGui import QColor\n'), ((1956, 1976), 'pyface.qt.QtGui.QColor', 'QColor', (['Qt.lightGray'], {}), '(Qt.lightGray)\n', (1962, 1976), False, 'from pyface.qt.QtGui import QColor\n'), ((2533, 2543), 'pychron.envisage.resources.icon', 'icon', (['name'], {}), '(name)\n', (2537, 2543), False, 'from pychron.envisage.resources import icon\n'), ((2029, 2048), 'pyface.qt.QtGui.QColor', 'QColor', (['"""lightblue"""'], {}), "('lightblue')\n", (2035, 2048), False, 'from pyface.qt.QtGui import QColor\n'), ((1473, 1490), 'pyface.qt.QtGui.QColor', 'QColor', (['"""#ff8080"""'], {}), "('#ff8080')\n", (1479, 1490), False, 'from pyface.qt.QtGui import QColor\n'), ((1550, 1565), 'pyface.qt.QtGui.QColor', 'QColor', (['Qt.cyan'], {}), '(Qt.cyan)\n', (1556, 1565), False, 'from pyface.qt.QtGui import QColor\n'), ((1623, 1640), 'pyface.qt.QtGui.QColor', 'QColor', (['"""#D05BFF"""'], {}), "('#D05BFF')\n", (1629, 1640), False, 'from pyface.qt.QtGui import QColor\n'), ((2099, 2116), 'pyface.qt.QtGui.QColor', 'QColor', (['"""#0dbf81"""'], {}), "('#0dbf81')\n", (2105, 2116), False, 'from pyface.qt.QtGui import QColor\n'), ((1695, 1712), 'pyface.qt.QtGui.QColor', 'QColor', (['"""#ff8080"""'], {}), "('#ff8080')\n", (1701, 1712), False, 'from pyface.qt.QtGui import QColor\n'), ((2166, 2182), 'pyface.qt.QtGui.QColor', 'QColor', (['"""orange"""'], {}), "('orange')\n", (2172, 2182), False, 'from pyface.qt.QtGui import QColor\n')]
|
"""
.. module:: foreground
:platform: Unix
:synopsis: functions describing behaviour of foreground spectra.
.. moduleauthor: <NAME> <<EMAIL>>
"""
import numpy as np
def BB_scaling(nu, nu_0, T):
"""Blackbody scaling factor from frequency nu, to frequency nu_0.
Parameters
----------
nu : `float`
Frequency to be scaled to.
nu_0 : `float`
Reference frequency to be scaled from.
T : `float`
Temperature of blackbody.
Returns
-------
`float`
Ratio of BB radiance between frequencies `nu` and `nu_0`.
"""
h = 6.63e-34
kb = 1.38e-23
a = np.exp(h * nu_0 * 1.e9 / (kb * T)) - 1.
b = np.exp(h * nu * 1.e9 / (kb * T)) - 1.
return (a / b) ** 2
def synch_cl(nu, ell, A_S, alpha_S, beta_S, nu_S_0, ell_S_0):
"""Model for the synchrotron power spectrum.
Parameters
----------
nu : float
Frequency at which to evaluate the spectrum.
ell : array_like(`int`, ndim=1)
Multipole range over which to evaluate spectrum.
A_S : `float`
Amplitdue of spectrum at reference multipole `ell_S_0`.
alpha_S : `float`
Index of the frequency dependence.
beta_S : `float`
Index of the multipole dependence.
nu_S_0 :`float`
Reference frequency.
ell_S_0 : `int`
Reference multipole.
Returns
-------
array_like(`float`, ndim=1)
The synchrotron spectrum at frequency `nu`.
"""
s = (nu / nu_S_0) ** (2. * alpha_S) * (ell / ell_S_0) ** beta_S
return A_S * s
def dust_cl(nu, ell, p, T, A_D, alpha_D, beta_D, nu_D_0, ell_D_0):
"""Model for the dust power spectrum.
Parameters
----------
nu : `float`
Frequency at which to evaluate the spectrum.
ell : array_like(int, ndim=1)
Multipole range over which to evaluate spectrum.
p : `float`
Polarization fraction of the dust.
T : `float`
Temperature of the dust.
A_D : `float`
Amplitude of dust spectrum at reference multipole `ell_D_0`.
alpha_D : `float`
Index of the frequency dependence of spectrum.
beta_D : `float`
Index of multipole dependence of spectrum.
nu_D_0 : `float`
Reference frequency.
ell_D_0 : `int`
Reference multipole.
Returns
-------
array_like(`float`, ndim=1)
Dust spectrum at frequency `nu`.
"""
s = (nu / nu_D_0) ** (2. * alpha_D) * (ell / ell_D_0) ** beta_D
bb = BB_scaling(nu, nu_D_0, T)
return p ** 2 * A_D * s * bb
def fg_res_sys(nu, nu_S_ref, alpha_S, nu_D_ref, alpha_D, N_chan, n_l):
"""Systematics introduced in CMB channels by foreground removal.
Parameters
----------
nu : `float`
Frequency at which to evaluate.
nu_S_ref : `float`
Reference frequency of synchrotron spectrum.
alpha_S : `float`
Index of frequency dependence of synchrotron spectrum.
nu_D_ref : `float`
Reference frequency of dust spectrum.
alpha_D : `float`
Index of frequency dependence of dust spectrum.
N_chan : `int`
Number of foreground removal.
n_l: list(array_like(float, ndim=1))
List of the instrumental noise in foreground channels.
Returns
-------
array_like(float, ndim=1)
Total noise spectrum at frequency nu due to foreground channel
systematics.
"""
f = (nu / nu_S_ref) ** (2 * alpha_S) + (nu / nu_D_ref) ** (2 * alpha_D)
summation = 1. / sum([1. / n for n in n_l])
a = 4. / (N_chan * (N_chan - 1.))
return a * summation * f
|
[
"numpy.exp"
] |
[((626, 668), 'numpy.exp', 'np.exp', (['(h * nu_0 * 1000000000.0 / (kb * T))'], {}), '(h * nu_0 * 1000000000.0 / (kb * T))\n', (632, 668), True, 'import numpy as np\n'), ((674, 714), 'numpy.exp', 'np.exp', (['(h * nu * 1000000000.0 / (kb * T))'], {}), '(h * nu * 1000000000.0 / (kb * T))\n', (680, 714), True, 'import numpy as np\n')]
|
from datetime import datetime
from typing import Dict
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Boolean
from sqlalchemy import DateTime
from sqlalchemy import ARRAY
from sqlalchemy import Enum
from sqlalchemy.orm import relationship
from literature.database.base import Base
from literature.schemas import FileCategories
class FileModel(Base):
__tablename__ = 'files'
__versioned__: Dict = {}
file_id = Column(
Integer,
primary_key=True,
autoincrement=True
)
s3_filename = Column(
String,
unique=True,
nullable=False
)
reference_id = Column(
Integer,
ForeignKey('references.reference_id',
ondelete='CASCADE'),
index=True
)
reference = relationship(
'ReferenceModel',
back_populates="files"
)
extension = Column(
String,
nullable=True
)
language = Column(
String
)
content_type = Column(
String,
nullable=True
)
category = Column(
Enum(FileCategories),
nullable=True
)
folder = Column(
String(),
unique=False,
nullable=False
)
md5sum = Column(
String(),
unique=False,
nullable=False,
index=True
)
size = Column(
Integer,
nullable=False
)
display_name = Column(
String(),
unique=False,
nullable=True
)
upload_date = Column(
DateTime,
nullable=False,
default=datetime.utcnow
)
public = Column(
Boolean,
nullable=False
)
mod_submitted = Column(
String,
nullable=True
)
mods_permitted = Column(
ARRAY(String()),
nullable=True
)
institutes_permitted = Column(
ARRAY(String()),
nullable=True
)
|
[
"sqlalchemy.Enum",
"sqlalchemy.ForeignKey",
"sqlalchemy.orm.relationship",
"sqlalchemy.Column",
"sqlalchemy.String"
] |
[((528, 581), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)', 'autoincrement': '(True)'}), '(Integer, primary_key=True, autoincrement=True)\n', (534, 581), False, 'from sqlalchemy import Column\n'), ((631, 674), 'sqlalchemy.Column', 'Column', (['String'], {'unique': '(True)', 'nullable': '(False)'}), '(String, unique=True, nullable=False)\n', (637, 674), False, 'from sqlalchemy import Column\n'), ((878, 932), 'sqlalchemy.orm.relationship', 'relationship', (['"""ReferenceModel"""'], {'back_populates': '"""files"""'}), "('ReferenceModel', back_populates='files')\n", (890, 932), False, 'from sqlalchemy.orm import relationship\n'), ((972, 1001), 'sqlalchemy.Column', 'Column', (['String'], {'nullable': '(True)'}), '(String, nullable=True)\n', (978, 1001), False, 'from sqlalchemy import Column\n'), ((1040, 1054), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (1046, 1054), False, 'from sqlalchemy import Column\n'), ((1089, 1118), 'sqlalchemy.Column', 'Column', (['String'], {'nullable': '(True)'}), '(String, nullable=True)\n', (1095, 1118), False, 'from sqlalchemy import Column\n'), ((1437, 1468), 'sqlalchemy.Column', 'Column', (['Integer'], {'nullable': '(False)'}), '(Integer, nullable=False)\n', (1443, 1468), False, 'from sqlalchemy import Column\n'), ((1606, 1663), 'sqlalchemy.Column', 'Column', (['DateTime'], {'nullable': '(False)', 'default': 'datetime.utcnow'}), '(DateTime, nullable=False, default=datetime.utcnow)\n', (1612, 1663), False, 'from sqlalchemy import Column\n'), ((1708, 1739), 'sqlalchemy.Column', 'Column', (['Boolean'], {'nullable': '(False)'}), '(Boolean, nullable=False)\n', (1714, 1739), False, 'from sqlalchemy import Column\n'), ((1783, 1812), 'sqlalchemy.Column', 'Column', (['String'], {'nullable': '(True)'}), '(String, nullable=True)\n', (1789, 1812), False, 'from sqlalchemy import Column\n'), ((758, 815), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""references.reference_id"""'], {'ondelete': '"""CASCADE"""'}), "('references.reference_id', ondelete='CASCADE')\n", (768, 815), False, 'from sqlalchemy import ForeignKey\n'), ((1173, 1193), 'sqlalchemy.Enum', 'Enum', (['FileCategories'], {}), '(FileCategories)\n', (1177, 1193), False, 'from sqlalchemy import Enum\n'), ((1253, 1261), 'sqlalchemy.String', 'String', ([], {}), '()\n', (1259, 1261), False, 'from sqlalchemy import String\n'), ((1344, 1352), 'sqlalchemy.String', 'String', ([], {}), '()\n', (1350, 1352), False, 'from sqlalchemy import String\n'), ((1527, 1535), 'sqlalchemy.String', 'String', ([], {}), '()\n', (1533, 1535), False, 'from sqlalchemy import String\n'), ((1879, 1887), 'sqlalchemy.String', 'String', ([], {}), '()\n', (1885, 1887), False, 'from sqlalchemy import String\n'), ((1968, 1976), 'sqlalchemy.String', 'String', ([], {}), '()\n', (1974, 1976), False, 'from sqlalchemy import String\n')]
|
"""
Copyright (c) 2022 ZOOMi Technologies Inc.
all rights reserved.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
maintainers : <EMAIL>
auto annotation process for AI tool.
"""
import cv2
import colorsys
import numpy as np
import time
import os
import random
import tensorflow as tf
from tensorflow.python.saved_model import tag_constants
from tensorflow.python.ops import gen_image_ops
import configparser
params = configparser.ConfigParser(os.environ)
CONFIG_FILE_PATH = 'config.cfg'
params.read(CONFIG_FILE_PATH)
OBJECTNESS_CONFIDANCE = float(f"{params.get('Inference', 'objectness_confidance')}")
NMS_THRESHOLD = float(f"{params.get('Inference', 'nms_threshold')}")
labels_file = f"{params.get('Inference', 'labels_file')}"
weight_file = f"{params.get('Inference', 'weight_file')}"
config_file = f"{params.get('Inference', 'config_file')}"
default_net_width = int(f"{params.get('Inference', 'default_net_width')}")
default_net_height = int(f"{params.get('Inference', 'default_net_height')}")
ALLOWED_EXTENSIONS_ = eval(f"{params.get('Content', 'allowed_extensions')}")
weight_tf = f"{params.get('Inference', 'weight_tf')}"
image_size = int(f"{params.get('Inference', 'image_size')}")
physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
tf.image.non_max_suppression = gen_image_ops.non_max_suppression_v2
# comment out below line to enable tensorflow logging outputs
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
class inference:
def __init__(self, target_gpu_id):
# opencv config
self.labelspath = labels_file
self.configpath = config_file
self.weightspath = weight_file
self.objectness_confidance = OBJECTNESS_CONFIDANCE
self.nms_threshold = NMS_THRESHOLD
self.gpu_id = target_gpu_id
self.avg_fps = []
self.total_detections = []
self.total_groundtruths = []
self.LABELS = self.get_classes()
self.net = cv2.dnn_DetectionModel(self.configpath, self.weightspath)
# TF
self.classes = self.read_class_names(labels_file)
self.LABELS = open(self.labelspath).read().strip().split("\n")
self.weight = weight_tf
self.image_size = image_size
# initialize a list of colors to represent each possible class label
self.COLORS = {'green': [64, 255, 64],
'blue': [255, 128, 0],
'coral': [0, 128, 255],
'yellow': [0, 255, 255],
'gray': [169, 169, 169],
'cyan': [255, 255, 0],
'magenta': [255, 0, 255],
'white': [255, 255, 255],
'red': [64, 0, 255]
}
# OpenCV GPU on CUDA support
try:
device_count = cv2.cuda.getCudaEnabledDeviceCount()
print("[INFO] GPU device count", device_count)
cv2.cuda.setDevice(self.gpu_id)
print(f"DNN_TARGET_CUDA set to GPU id {self.gpu_id}")
self.net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA_FP16)
print("[INFO] You are using DNN_TARGET_CUDA_FP16 backend to increase the FPS. "
"Please make sure your GPU supports floating point 16, or change it back to DNN_TARGET_CUDA. "
"Ref: https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#arithmetic-instructions")
except Exception as e:
print(e)
print("[INFO] Please build OpenCV with GPU support in order to use DNN_BACKEND_CUDA: "
"https://www.pyimagesearch.com/2020/02/03/how-to-use-opencvs-dnn-module-with-nvidia-"
"gpus-cuda-and-cudnn/")
print("[INFO] Shifting back to DNN_TARGET_CPU")
self.net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
pass
print("[INFO] OpenCV version:", cv2.__version__)
self.version = cv2.__version__
if self.version < '4.5.4':
print(f"[INFO] Your OpenCV version is {self.version} and it does not support the Scaled-YOLO models:"
f"yolov4-csp, yolov4-csp-swish, yolov4-p5, yolov4-p6. Please install OpenCV-4.5.3 or later")
net_width, net_height = self.get_networksize()
print('[INFO] Network width', net_width)
print('[INFO] Network height', net_height)
self.net.setInputParams(size=(int(net_width), int(net_height)), scale=1 / 255, swapRB=True, crop=False)
def get_classes(self):
names = []
with open(self.labelspath) as f:
content = f.read().splitlines()
for line in content:
names.append(line)
return names
def get_networksize(self):
file = open(self.configpath, 'r')
content = file.read()
paths = content.split("\n")
# default net size will be set as 416 if the network size is not detected from the cfg file
net_width = 416
net_height = 416
for path in paths:
if path.split("=")[0] == 'width':
net_width = path.split("=")[1]
if path.split("=")[0] == 'height':
net_height = path.split("=")[1]
return net_width, net_height
def read_class_names(self, class_file_name):
names = {}
with open(class_file_name, 'r') as data:
for ID, name in enumerate(data):
names[ID] = name.strip('\n')
return names
def draw_bbox(self, image, bboxes, frame_object, show_label=False):
num_classes = len(self.classes)
image_h, image_w, _ = image.shape
hsv_tuples = [(1.0 * x / num_classes, 1., 1.) for x in range(num_classes)]
colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))
random.seed(0)
random.shuffle(colors)
random.seed(None)
out_boxes, out_scores, out_classes, num_boxes = bboxes
for i in range(num_boxes[0]):
print(i)
if int(out_classes[0][i]) < 0 or int(out_classes[0][i]) > num_classes: continue
coor = out_boxes[0][i]
coor[0] = int(coor[0] * image_h)
coor[2] = int(coor[2] * image_h)
coor[1] = int(coor[1] * image_w)
coor[3] = int(coor[3] * image_w)
fontScale = 0.5
score = out_scores[0][i]
class_ind = int(out_classes[0][i])
bbox_color = colors[class_ind]
bbox_thick = int(0.6 * (image_h + image_w) / 600)
c1, c2 = (coor[1], coor[0]), (coor[3], coor[2])
# cv2.rectangle(image, (int(c1[0]), int(c1[1])), (int(c2[0]), int(c2[1])), bbox_color, bbox_thick)
anno = [int(c1[0]), int(c1[1]), (int(c2[0])-int(c1[0])), (int(c2[1])-int(c1[1]))]
if show_label:
bbox_mess = '%s: %.2f' % (self.classes[class_ind], score)
t_size = cv2.getTextSize(bbox_mess, 0, fontScale, thickness=bbox_thick // 2)[0]
c3 = (c1[0] + t_size[0], c1[1] - t_size[1] - 3)
cv2.rectangle(image, (int(c1[0]), int(c1[1])), (int(c3[0]), int(c3[1])), bbox_color, -1) # filled
cv2.putText(image, bbox_mess, (int(c1[0]), int(c1[1] - 2)), cv2.FONT_HERSHEY_SIMPLEX,
fontScale, (0, 0, 0), bbox_thick // 2, lineType=cv2.LINE_AA)
boundaries = {'id': i, 'type': "rectangle", 'label': "Lap Sponge", 'color': "#00d1ff",
'status': "completed",
'isPermanent': "True", 'x': anno[0], 'y': anno[1], 'w': anno[2], 'h': anno[3],
'attributeValues': {}, "autoLable_confidance": str(score)}
temp = {
"id": i,
"boundaries": boundaries,
"attributeValues": {
"state": "Ready"
}
}
frame_object['boxes'].append(temp)
return image, frame_object
def inference_selector(self, frame, service_type, frame_object):
img = None
anno_object = None
if service_type == 'opencv-inference':
img, anno_object = self.opencv_infer(frame, frame_object)
if service_type == 'tensorflow-inference':
img, anno_object = self.tensorflow_infer(frame, frame_object)
return img, anno_object
def tensorflow_infer(self, frame, frame_object):
config = tf.compat.v1.ConfigProto(allow_soft_placement=True, log_device_placement=True)
config.gpu_options.allow_growth = True
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
input_size = self.image_size
saved_model_loaded = tf.saved_model.load(self.weight, tags=[tag_constants.SERVING])
infer = saved_model_loaded.signatures['serving_default']
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image_data = cv2.resize(frame, (input_size, input_size))
image_data = image_data / 255.
image_data = image_data[np.newaxis, ...].astype(np.float32)
prev_time = time.time()
batch_data = tf.constant(image_data)
pred_bbox = infer(batch_data)
boxes = None
pred_conf = None
for key, value in pred_bbox.items():
boxes = value[:, :, 0:4]
pred_conf = value[:, :, 4:]
boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(
boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)),
scores=tf.reshape(
pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])),
max_output_size_per_class=50,
max_total_size=50,
iou_threshold=self.nms_threshold,
score_threshold=self.objectness_confidance
)
pred_bbox = [boxes.numpy(), scores.numpy(), classes.numpy(), valid_detections.numpy()]
image, frame_obj = self.draw_bbox(frame, pred_bbox, frame_object)
fps = 1.0 / (time.time() - prev_time)
print("FPS: %.2f" % fps)
result = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
return result, frame_obj
def opencv_infer(self, image, frame_object):
start_time = time.time()
class_ids, confidences, boxes = self.net.detect(image, self.objectness_confidance, self.nms_threshold)
try:
class_names = [self.LABELS[id] for id in class_ids.flatten().tolist()]
for i in range(class_ids.shape[0]):
class_id = int(class_ids[i])
confidence = float(confidences[i])
x = int(boxes[i, 0])
y = int(boxes[i, 1])
w = int(boxes[i, 2])
h = int(boxes[i, 3])
color = self.COLORS[list(self.COLORS)[class_id % len(self.COLORS)]]
label = "{}: {:.4f}".format(class_names[i], confidence)
if class_names[i] == 'name_tag':
object_name = 'Name Tag'
elif class_names[i] == 'face':
object_name = 'Face'
elif class_names[i] == 'laparotomy_sponge':
object_name = 'Lap Sponge'
else:
object_name = class_names[i]
flag_render_detections = False
if flag_render_detections:
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
cv2.putText(image, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
boundaries = {'id': i, 'type': "rectangle", 'label': object_name, 'color': "#00d1ff",
'status': "completed", 'isPermanent': "True", 'x': x, 'y': y, 'w': w, 'h': h,
'attributeValues': {}, "autoLable_confidance": str(confidences[i])}
temp = {
"id": i,
"boundaries": boundaries,
"attributeValues": {
"state": "Ready"
}
}
frame_object['boxes'].append(temp)
except Exception as e:
print(e)
pass
end_time = time.time()
self.avg_fps.append(1 / (end_time - start_time))
# avg_fps = "[INFO] approx. FPS: {:.2f}".format(sum(self.avg_fps) / len(self.avg_fps))
# print("[INFO] approx. FPS per image: {:.2f}".format(1 / (end_time - start_time)))
# print("[INFO] average FPS: {}".format(avg_fps))
# print("=================================================================================================")
return image, frame_object
# if __name__ == '__main__':
|
[
"cv2.dnn_DetectionModel",
"random.shuffle",
"cv2.rectangle",
"cv2.cuda.getCudaEnabledDeviceCount",
"cv2.cuda.setDevice",
"cv2.cvtColor",
"random.seed",
"configparser.ConfigParser",
"cv2.resize",
"tensorflow.config.experimental.set_memory_growth",
"tensorflow.constant",
"tensorflow.compat.v1.ConfigProto",
"tensorflow.config.experimental.list_physical_devices",
"tensorflow.saved_model.load",
"cv2.putText",
"colorsys.hsv_to_rgb",
"cv2.getTextSize",
"time.time",
"tensorflow.shape"
] |
[((492, 529), 'configparser.ConfigParser', 'configparser.ConfigParser', (['os.environ'], {}), '(os.environ)\n', (517, 529), False, 'import configparser\n'), ((1286, 1337), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (1330, 1337), True, 'import tensorflow as tf\n'), ((1373, 1440), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['physical_devices[0]', '(True)'], {}), '(physical_devices[0], True)\n', (1413, 1440), True, 'import tensorflow as tf\n'), ((2108, 2165), 'cv2.dnn_DetectionModel', 'cv2.dnn_DetectionModel', (['self.configpath', 'self.weightspath'], {}), '(self.configpath, self.weightspath)\n', (2130, 2165), False, 'import cv2\n'), ((6193, 6207), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (6204, 6207), False, 'import random\n'), ((6216, 6238), 'random.shuffle', 'random.shuffle', (['colors'], {}), '(colors)\n', (6230, 6238), False, 'import random\n'), ((6247, 6264), 'random.seed', 'random.seed', (['None'], {}), '(None)\n', (6258, 6264), False, 'import random\n'), ((8825, 8903), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {'allow_soft_placement': '(True)', 'log_device_placement': '(True)'}), '(allow_soft_placement=True, log_device_placement=True)\n', (8849, 8903), True, 'import tensorflow as tf\n'), ((9067, 9129), 'tensorflow.saved_model.load', 'tf.saved_model.load', (['self.weight'], {'tags': '[tag_constants.SERVING]'}), '(self.weight, tags=[tag_constants.SERVING])\n', (9086, 9129), True, 'import tensorflow as tf\n'), ((9212, 9250), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (9224, 9250), False, 'import cv2\n'), ((9272, 9315), 'cv2.resize', 'cv2.resize', (['frame', '(input_size, input_size)'], {}), '(frame, (input_size, input_size))\n', (9282, 9315), False, 'import cv2\n'), ((9443, 9454), 'time.time', 'time.time', ([], {}), '()\n', (9452, 9454), False, 'import time\n'), ((9477, 9500), 'tensorflow.constant', 'tf.constant', (['image_data'], {}), '(image_data)\n', (9488, 9500), True, 'import tensorflow as tf\n'), ((10432, 10470), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2BGR'], {}), '(image, cv2.COLOR_RGB2BGR)\n', (10444, 10470), False, 'import cv2\n'), ((10575, 10586), 'time.time', 'time.time', ([], {}), '()\n', (10584, 10586), False, 'import time\n'), ((12544, 12555), 'time.time', 'time.time', ([], {}), '()\n', (12553, 12555), False, 'import time\n'), ((2982, 3018), 'cv2.cuda.getCudaEnabledDeviceCount', 'cv2.cuda.getCudaEnabledDeviceCount', ([], {}), '()\n', (3016, 3018), False, 'import cv2\n'), ((3090, 3121), 'cv2.cuda.setDevice', 'cv2.cuda.setDevice', (['self.gpu_id'], {}), '(self.gpu_id)\n', (3108, 3121), False, 'import cv2\n'), ((10356, 10367), 'time.time', 'time.time', ([], {}), '()\n', (10365, 10367), False, 'import time\n'), ((6048, 6071), 'colorsys.hsv_to_rgb', 'colorsys.hsv_to_rgb', (['*x'], {}), '(*x)\n', (6067, 6071), False, 'import colorsys\n'), ((7303, 7370), 'cv2.getTextSize', 'cv2.getTextSize', (['bbox_mess', '(0)', 'fontScale'], {'thickness': '(bbox_thick // 2)'}), '(bbox_mess, 0, fontScale, thickness=bbox_thick // 2)\n', (7318, 7370), False, 'import cv2\n'), ((11715, 11769), 'cv2.rectangle', 'cv2.rectangle', (['image', '(x, y)', '(x + w, y + h)', 'color', '(2)'], {}), '(image, (x, y), (x + w, y + h), color, 2)\n', (11728, 11769), False, 'import cv2\n'), ((11790, 11869), 'cv2.putText', 'cv2.putText', (['image', 'label', '(x, y - 10)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', 'color', '(1)'], {}), '(image, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)\n', (11801, 11869), False, 'import cv2\n'), ((9836, 9851), 'tensorflow.shape', 'tf.shape', (['boxes'], {}), '(boxes)\n', (9844, 9851), True, 'import tensorflow as tf\n'), ((9927, 9946), 'tensorflow.shape', 'tf.shape', (['pred_conf'], {}), '(pred_conf)\n', (9935, 9946), True, 'import tensorflow as tf\n'), ((9955, 9974), 'tensorflow.shape', 'tf.shape', (['pred_conf'], {}), '(pred_conf)\n', (9963, 9974), True, 'import tensorflow as tf\n')]
|
#################################################################
# Code written by <NAME> (<EMAIL>)
# For bug report, please contact author using the email address
#################################################################
import sys, random, time, argparse
from collections import OrderedDict
import pickle
import numpy as np
import theano
import theano.tensor as T
from theano import config
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
_TEST_RATIO = 0.15
_VALIDATION_RATIO = 0.1
def unzip(zipped):
new_params = OrderedDict()
for key, value in zipped.items():
new_params[key] = value.get_value()
return new_params
def numpy_floatX(data):
return np.asarray(data, dtype=config.floatX)
def get_random_weight(dim1, dim2, left=-0.1, right=0.1):
return np.random.uniform(left, right, (dim1, dim2)).astype(config.floatX)
def load_embedding(options):
m = np.load(options['embFile'])
w = (m['w'] + m['w_tilde']) / 2.0
return w
def init_params(options):
params = OrderedDict()
np.random.seed(0)
inputDimSize = options['inputDimSize']
numAncestors = options['numAncestors']
embDimSize = options['embDimSize']
hiddenDimSize = options['hiddenDimSize'] #hidden layer does not need an extra space
attentionDimSize = options['attentionDimSize']
numClass = options['numClass']
params['W_emb'] = get_random_weight(inputDimSize+numAncestors, embDimSize)
if len(options['embFile']) > 0:
params['W_emb'] = load_embedding(options)
options['embDimSize'] = params['W_emb'].shape[1]
embDimSize = options['embDimSize']
params['W_attention'] = get_random_weight(embDimSize*2, attentionDimSize)
params['b_attention'] = np.zeros(attentionDimSize).astype(config.floatX)
params['v_attention'] = np.random.uniform(-0.1, 0.1, attentionDimSize).astype(config.floatX)
params['W_gru'] = get_random_weight(embDimSize, 3*hiddenDimSize)
params['U_gru'] = get_random_weight(hiddenDimSize, 3*hiddenDimSize)
params['b_gru'] = np.zeros(3 * hiddenDimSize).astype(config.floatX)
params['W_output'] = get_random_weight(hiddenDimSize, numClass)
params['b_output'] = np.zeros(numClass).astype(config.floatX)
return params
def init_tparams(params):
tparams = OrderedDict()
for key, value in params.items():
tparams[key] = theano.shared(value, name=key)
return tparams
def dropout_layer(state_before, use_noise, trng, prob):
proj = T.switch(use_noise, (state_before * trng.binomial(state_before.shape, p=prob, n=1, dtype=state_before.dtype)), state_before * 0.5)
return proj
def _slice(_x, n, dim):
if _x.ndim == 3:
return _x[:, :, n*dim:(n+1)*dim]
return _x[:, n*dim:(n+1)*dim]
def gru_layer(tparams, emb, options):
hiddenDimSize = options['hiddenDimSize']
timesteps = emb.shape[0]
if emb.ndim == 3: n_samples = emb.shape[1]
else: n_samples = 1
def stepFn(wx, h, U_gru):
uh = T.dot(h, U_gru)
r = T.nnet.sigmoid(_slice(wx, 0, hiddenDimSize) + _slice(uh, 0, hiddenDimSize))
z = T.nnet.sigmoid(_slice(wx, 1, hiddenDimSize) + _slice(uh, 1, hiddenDimSize))
h_tilde = T.tanh(_slice(wx, 2, hiddenDimSize) + r * _slice(uh, 2, hiddenDimSize))
h_new = z * h + ((1. - z) * h_tilde)
return h_new
Wx = T.dot(emb, tparams['W_gru']) + tparams['b_gru']
results, updates = theano.scan(fn=stepFn, sequences=[Wx], outputs_info=T.alloc(numpy_floatX(0.0), n_samples, hiddenDimSize), non_sequences=[tparams['U_gru']], name='gru_layer', n_steps=timesteps)
return results
# 计算注意力权重
def generate_attention(tparams, leaves, ancestors):
# f(ei,ej)
attentionInput = T.concatenate([tparams['W_emb'][leaves], tparams['W_emb'][ancestors]], axis=2)
mlpOutput = T.tanh(T.dot(attentionInput, tparams['W_attention']) + tparams['b_attention'])
preAttention = T.dot(mlpOutput, tparams['v_attention'])
# softmax f(ei,ej)
attention = T.nnet.softmax(preAttention)
return attention
def softmax_layer(tparams, emb):
nom = T.exp(T.dot(emb, tparams['W_output']) + tparams['b_output'])
denom = nom.sum(axis=2, keepdims=True)
output = nom / denom
return output
def build_model(tparams, leavesList, ancestorsList, options):
dropoutRate = options['dropoutRate']
trng = RandomStreams(123)
use_noise = theano.shared(numpy_floatX(0.))
x = T.tensor3('x', dtype=config.floatX)
y = T.tensor3('y', dtype=config.floatX)
mask = T.matrix('mask', dtype=config.floatX)
lengths = T.vector('lengths', dtype=config.floatX)
n_timesteps = x.shape[0]
n_samples = x.shape[1]
# 计算最终表达形式 gi = sum(a_{ij} * ej)
embList = []
for leaves, ancestors in zip(leavesList, ancestorsList):
tempAttention = generate_attention(tparams, leaves, ancestors)
tempEmb = (tparams['W_emb'][ancestors] * tempAttention[:,:,None]).sum(axis=1)
embList.append(tempEmb)
emb = T.concatenate(embList, axis=0)
# 预测模型
x_emb = T.tanh(T.dot(x, emb))
hidden = gru_layer(tparams, x_emb, options)
hidden = dropout_layer(hidden, use_noise, trng, dropoutRate)
y_hat = softmax_layer(tparams, hidden) * mask[:,:,None]
# 计算损失
logEps = 1e-8
cross_entropy = -(y * T.log(y_hat + logEps) + (1. - y) * T.log(1. - y_hat + logEps))
output_loglikelihood = cross_entropy.sum(axis=2).sum(axis=0) / lengths
cost_noreg = T.mean(output_loglikelihood)
if options['L2'] > 0.:
cost = cost_noreg + options['L2'] * ((tparams['W_output']**2).sum() + (tparams['W_attention']**2).sum() + (tparams['v_attention']**2).sum())
return use_noise, x, y, mask, lengths, cost, cost_noreg, y_hat
def load_data(seqFile, labelFile, timeFile=''):
sequences = np.array(pickle.load(open(seqFile, 'rb')))
labels = np.array(pickle.load(open(labelFile, 'rb')))
if len(timeFile) > 0:
times = np.array(pickle.load(open(timeFile, 'rb')))
np.random.seed(0)
dataSize = len(labels)
ind = np.random.permutation(dataSize)
nTest = int(_TEST_RATIO * dataSize)
nValid = int(_VALIDATION_RATIO * dataSize)
test_indices = ind[:nTest]
valid_indices = ind[nTest:nTest+nValid]
train_indices = ind[nTest+nValid:]
train_set_x = sequences[train_indices]
train_set_y = labels[train_indices]
test_set_x = sequences[test_indices]
test_set_y = labels[test_indices]
valid_set_x = sequences[valid_indices]
valid_set_y = labels[valid_indices]
train_set_t = None
test_set_t = None
valid_set_t = None
if len(timeFile) > 0:
train_set_t = times[train_indices]
test_set_t = times[test_indices]
valid_set_t = times[valid_indices]
def len_argsort(seq):
return sorted(range(len(seq)), key=lambda x: len(seq[x]))
train_sorted_index = len_argsort(train_set_x)
train_set_x = [train_set_x[i] for i in train_sorted_index]
train_set_y = [train_set_y[i] for i in train_sorted_index]
valid_sorted_index = len_argsort(valid_set_x)
valid_set_x = [valid_set_x[i] for i in valid_sorted_index]
valid_set_y = [valid_set_y[i] for i in valid_sorted_index]
test_sorted_index = len_argsort(test_set_x)
test_set_x = [test_set_x[i] for i in test_sorted_index]
test_set_y = [test_set_y[i] for i in test_sorted_index]
if len(timeFile) > 0:
train_set_t = [train_set_t[i] for i in train_sorted_index]
valid_set_t = [valid_set_t[i] for i in valid_sorted_index]
test_set_t = [test_set_t[i] for i in test_sorted_index]
train_set = (train_set_x, train_set_y, train_set_t)
valid_set = (valid_set_x, valid_set_y, valid_set_t)
test_set = (test_set_x, test_set_y, test_set_t)
return train_set, valid_set, test_set
def adadelta(tparams, grads, x, y, mask, lengths, cost):
zipped_grads = [theano.shared(p.get_value() * numpy_floatX(0.), name='%s_grad' % k) for k, p in tparams.items()]
running_up2 = [theano.shared(p.get_value() * numpy_floatX(0.), name='%s_rup2' % k) for k, p in tparams.items()]
running_grads2 = [theano.shared(p.get_value() * numpy_floatX(0.), name='%s_rgrad2' % k) for k, p in tparams.items()]
zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]
rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2)) for rg2, g in zip(running_grads2, grads)]
f_grad_shared = theano.function([x, y, mask, lengths], cost, updates=zgup + rg2up, name='adadelta_f_grad_shared')
updir = [-T.sqrt(ru2 + 1e-6) / T.sqrt(rg2 + 1e-6) * zg for zg, ru2, rg2 in zip(zipped_grads, running_up2, running_grads2)]
ru2up = [(ru2, 0.95 * ru2 + 0.05 * (ud ** 2)) for ru2, ud in zip(running_up2, updir)]
param_up = [(p, p + ud) for p, ud in zip(tparams.values(), updir)]
f_update = theano.function([], [], updates=ru2up + param_up, on_unused_input='ignore', name='adadelta_f_update')
return f_grad_shared, f_update
# V_{n-1}和label_{n}对应
def padMatrix(seqs, labels, options):
lengths = np.array([len(seq) for seq in seqs]) - 1
n_samples = len(seqs)
maxlen = np.max(lengths)
x = np.zeros((maxlen, n_samples, options['inputDimSize'])).astype(config.floatX)
y = np.zeros((maxlen, n_samples, options['numClass'])).astype(config.floatX)
mask = np.zeros((maxlen, n_samples)).astype(config.floatX)
for idx, (seq, lseq) in enumerate(zip(seqs,labels)):
for xvec, subseq in zip(x[:,idx,:], seq[:-1]): #将列表中对应元素打包为元组,返回由这些元组组成的列表,长度与最短的列表一致
xvec[subseq] = 1.
for yvec, subseq in zip(y[:,idx,:], lseq[1:]):
yvec[subseq] = 1.
mask[:lengths[idx], idx] = 1.
lengths = np.array(lengths, dtype=config.floatX)
return x, y, mask, lengths
def calculate_cost(test_model, dataset, options):
batchSize = options['batchSize']
n_batches = int(np.ceil(float(len(dataset[0])) / float(batchSize)))
costSum = 0.0
dataCount = 0
for index in range(n_batches):
batchX = dataset[0][index*batchSize:(index+1)*batchSize]
batchY = dataset[1][index*batchSize:(index+1)*batchSize]
x, y, mask, lengths = padMatrix(batchX, batchY, options)
cost = test_model(x, y, mask, lengths)
costSum += cost * len(batchX)
dataCount += len(batchX)
return costSum / dataCount
def calculate_pred(test_model, dataset, options):
x = dataset[0]
y = dataset[1]
batchSize = options['batchSize']
x, y, mask, lengths = padMatrix(x, y, options)
prediction = test_model(x, mask)
return prediction
def print2file(buf, outFile):
outfd = open(outFile, 'a')
outfd.write(buf + '\n')
outfd.close()
# 匹配叶子节点和其路径上的所有节点
def build_tree(treeFile):
treeMap = pickle.load(open(treeFile, 'rb'))
ancestors = np.array(list(treeMap.values())).astype('int32')
ancSize = ancestors.shape[1]
leaves = []
for k in treeMap.keys():
leaves.append([k] * ancSize)
leaves = np.array(leaves).astype('int32')
return leaves, ancestors
"""
FiveMap example:
{0: [0, 1670, 942, 943, 945, 951], 1: [1, 1670, 942, 957, 960, 963]}
ancestors = array([[0, 1670, 942, 943, 945, 951], [1, 1670, 942, 957, 960, 963]], dtype=int32)
ancSize = 6
leaves = array([[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1]], dtype=int32)
theano.shared(): https://www.tutorialspoint.com/theano/theano_shared_variables.htm
"""
def train_GRAM(
seqFile = 'seqFile.txt',
labelFile = 'labelFile.txt',
treeFile='tree.txt',
embFile='embFile.txt',
outFile='out.txt',
inputDimSize= 100,
numAncestors=100,
embDimSize= 100,
hiddenDimSize=200,
attentionDimSize=200,
max_epochs=100,
L2=0.,
numClass=26679,
batchSize=100,
dropoutRate=0.5,
logEps=1e-8,
verbose=False
):
options = locals().copy()
leavesList = []
ancestorsList = []
for i in range(5, 0, -1): # 使用ccs最多五个祖先(包含root)
leaves, ancestors = build_tree(treeFile+'.level'+str(i)+'.pk')
sharedLeaves = theano.shared(leaves, name='leaves'+str(i))
sharedAncestors = theano.shared(ancestors, name='ancestors'+str(i))
leavesList.append(sharedLeaves)
ancestorsList.append(sharedAncestors)
print('Building the model'),
params = init_params(options)
tparams = init_tparams(params)
use_noise, x, y, mask, lengths, cost, cost_noreg, y_hat = build_model(tparams, leavesList, ancestorsList, options)
get_cost = theano.function(inputs=[x, y, mask, lengths], outputs=cost_noreg, name='get_cost')
get_prediction = theano.function(inputs=[x, mask], outputs=y_hat, name='get_prediction')
print('Constructing the optimizer'),
grads = T.grad(cost, wrt=list(tparams.values()))
f_grad_shared, f_update = adadelta(tparams, grads, x, y, mask, lengths, cost)
print('Loading data'),
trainSet, validSet, testSet = load_data(seqFile, labelFile)
n_batches = int(np.ceil(float(len(trainSet[0])) / float(batchSize)))
pickle.dump(trainSet, open('trainSet', 'wb'), -1)
pickle.dump(testSet, open('testSet', 'wb'), -1)
print('Optimization')
bestTrainCost = 0.0
bestValidCost = 100000.0
bestTestCost = 0.0
epochDuration = 0.0
bestEpoch = 0
logFile = outFile + '.log'
for epoch in range(max_epochs):
iteration = 0
costVec = []
startTime = time.time()
for index in random.sample(range(n_batches), n_batches):
use_noise.set_value(1.)
batchX = trainSet[0][index*batchSize:(index+1)*batchSize]
batchY = trainSet[1][index*batchSize:(index+1)*batchSize]
x, y, mask, lengths = padMatrix(batchX, batchY, options)
costValue = f_grad_shared(x, y, mask, lengths)
f_update()
costVec.append(costValue)
if iteration % 100 == 0 and verbose:
buf = 'Epoch:%d, Iteration:%d/%d, Train_Cost:%f' % (epoch, iteration, n_batches, costValue)
print(buf)
iteration += 1
duration = time.time() - startTime
use_noise.set_value(0.)
trainCost = np.mean(costVec)
validCost = calculate_cost(get_cost, validSet, options)
testCost = calculate_cost(get_cost, testSet, options)
buf = 'Epoch:%d, Duration:%f, Train_Cost:%f, Valid_Cost:%f, Test_Cost:%f' % (epoch, duration, trainCost, validCost, testCost)
print(buf)
print2file(buf, logFile)
epochDuration += duration
if validCost < bestValidCost:
bestValidCost = validCost
bestTestCost = testCost
bestTrainCost = trainCost
bestEpoch = epoch
bestParams = tparams
tempParams = unzip(tparams)
np.savez_compressed(outFile + '.' + str(epoch), **tempParams)
buf = 'Best Epoch:%d, Avg_Duration:%f, Train_Cost:%f, Valid_Cost:%f, Test_Cost:%f' % (bestEpoch, epochDuration/max_epochs, bestTrainCost, bestValidCost, bestTestCost)
print(buf)
print2file(buf, logFile)
print('Making predictions')
tparams = bestParams
prediction = calculate_pred(get_prediction, testSet, options)
print(prediction)
pickle.dump(prediction, open('testPred', 'wb'), -1)
def parse_arguments(parser):
parser.add_argument('seq_file', type=str, metavar='<visit_file>', help='The path to the Pickled file containing visit information of patients')
parser.add_argument('label_file', type=str, metavar='<label_file>', help='The path to the Pickled file containing label information of patients')
parser.add_argument('tree_file', type=str, metavar='<tree_file>', help='The path to the Pickled files containing the ancestor information of the input medical codes. Only use the prefix and exclude ".level#.pk".')
parser.add_argument('out_file', metavar='<out_file>', help='The path to the output models. The models will be saved after every epoch')
parser.add_argument('--embed_file', type=str, default='', help='The path to the Pickled file containing the representation vectors of medical codes. If you are not using medical code representations, do not use this option')
parser.add_argument('--embed_size', type=int, default=128, help='The dimension size of the visit embedding. If you are providing your own medical code vectors, this value will be automatically decided. (default value: 128)')
parser.add_argument('--rnn_size', type=int, default=128, help='The dimension size of the hidden layer of the GRU (default value: 128)')
parser.add_argument('--attention_size', type=int, default=128, help='The dimension size of hidden layer of the MLP that generates the attention weights (default value: 128)')
parser.add_argument('--batch_size', type=int, default=100, help='The size of a single mini-batch (default value: 100)')
parser.add_argument('--n_epochs', type=int, default=100, help='The number of training epochs (default value: 100)')
parser.add_argument('--L2', type=float, default=0.001, help='L2 regularization coefficient for all weights except RNN (default value: 0.001)')
parser.add_argument('--dropout_rate', type=float, default=0.5, help='Dropout rate used for the hidden layer of RNN (default value: 0.5)')
parser.add_argument('--log_eps', type=float, default=1e-8, help='A small value to prevent log(0) (default value: 1e-8)')
parser.add_argument('--verbose', action='store_true', help='Print output after every 100 mini-batches (default false)')
args = parser.parse_args()
return args
def calculate_dimSize(seqFile):
seqs = pickle.load(open(seqFile, 'rb'))
codeSet = set()
for patient in seqs:
for visit in patient:
for code in visit:
codeSet.add(code)
return max(codeSet) + 1
def get_rootCode(treeFile):
tree = pickle.load(open(treeFile, 'rb'))
rootCode = list(tree.values())[0][1]
return rootCode
if __name__ == '__main__':
parser = argparse.ArgumentParser()
args = parse_arguments(parser)
inputDimSize = calculate_dimSize(args.seq_file)
numClass = calculate_dimSize(args.label_file)
numAncestors = get_rootCode(args.tree_file+'.level2.pk') - inputDimSize + 1
train_GRAM(
seqFile=args.seq_file,
inputDimSize=inputDimSize,
treeFile=args.tree_file,
numAncestors=numAncestors,
labelFile=args.label_file,
numClass=numClass,
outFile=args.out_file,
embFile=args.embed_file,
embDimSize=args.embed_size,
hiddenDimSize=args.rnn_size,
attentionDimSize=args.attention_size,
batchSize=args.batch_size,
max_epochs=args.n_epochs,
L2=args.L2,
dropoutRate=args.dropout_rate,
logEps=args.log_eps,
verbose=args.verbose
)
|
[
"numpy.load",
"theano.tensor.tensor3",
"numpy.random.seed",
"argparse.ArgumentParser",
"theano.sandbox.rng_mrg.MRG_RandomStreams",
"numpy.mean",
"theano.tensor.sqrt",
"theano.tensor.log",
"theano.tensor.concatenate",
"theano.tensor.mean",
"theano.tensor.nnet.softmax",
"numpy.max",
"theano.shared",
"theano.tensor.dot",
"numpy.asarray",
"numpy.random.permutation",
"theano.tensor.matrix",
"numpy.random.uniform",
"theano.function",
"numpy.zeros",
"time.time",
"numpy.array",
"theano.tensor.vector",
"collections.OrderedDict"
] |
[((554, 567), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (565, 567), False, 'from collections import OrderedDict\n'), ((708, 745), 'numpy.asarray', 'np.asarray', (['data'], {'dtype': 'config.floatX'}), '(data, dtype=config.floatX)\n', (718, 745), True, 'import numpy as np\n'), ((920, 947), 'numpy.load', 'np.load', (["options['embFile']"], {}), "(options['embFile'])\n", (927, 947), True, 'import numpy as np\n'), ((1039, 1052), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1050, 1052), False, 'from collections import OrderedDict\n'), ((1058, 1075), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1072, 1075), True, 'import numpy as np\n'), ((2303, 2316), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2314, 2316), False, 'from collections import OrderedDict\n'), ((3717, 3795), 'theano.tensor.concatenate', 'T.concatenate', (["[tparams['W_emb'][leaves], tparams['W_emb'][ancestors]]"], {'axis': '(2)'}), "([tparams['W_emb'][leaves], tparams['W_emb'][ancestors]], axis=2)\n", (3730, 3795), True, 'import theano.tensor as T\n'), ((3911, 3951), 'theano.tensor.dot', 'T.dot', (['mlpOutput', "tparams['v_attention']"], {}), "(mlpOutput, tparams['v_attention'])\n", (3916, 3951), True, 'import theano.tensor as T\n'), ((3991, 4019), 'theano.tensor.nnet.softmax', 'T.nnet.softmax', (['preAttention'], {}), '(preAttention)\n', (4005, 4019), True, 'import theano.tensor as T\n'), ((4355, 4373), 'theano.sandbox.rng_mrg.MRG_RandomStreams', 'RandomStreams', (['(123)'], {}), '(123)\n', (4368, 4373), True, 'from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\n'), ((4431, 4466), 'theano.tensor.tensor3', 'T.tensor3', (['"""x"""'], {'dtype': 'config.floatX'}), "('x', dtype=config.floatX)\n", (4440, 4466), True, 'import theano.tensor as T\n'), ((4475, 4510), 'theano.tensor.tensor3', 'T.tensor3', (['"""y"""'], {'dtype': 'config.floatX'}), "('y', dtype=config.floatX)\n", (4484, 4510), True, 'import theano.tensor as T\n'), ((4522, 4559), 'theano.tensor.matrix', 'T.matrix', (['"""mask"""'], {'dtype': 'config.floatX'}), "('mask', dtype=config.floatX)\n", (4530, 4559), True, 'import theano.tensor as T\n'), ((4574, 4614), 'theano.tensor.vector', 'T.vector', (['"""lengths"""'], {'dtype': 'config.floatX'}), "('lengths', dtype=config.floatX)\n", (4582, 4614), True, 'import theano.tensor as T\n'), ((4988, 5018), 'theano.tensor.concatenate', 'T.concatenate', (['embList'], {'axis': '(0)'}), '(embList, axis=0)\n', (5001, 5018), True, 'import theano.tensor as T\n'), ((5449, 5477), 'theano.tensor.mean', 'T.mean', (['output_loglikelihood'], {}), '(output_loglikelihood)\n', (5455, 5477), True, 'import theano.tensor as T\n'), ((5980, 5997), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (5994, 5997), True, 'import numpy as np\n'), ((6035, 6066), 'numpy.random.permutation', 'np.random.permutation', (['dataSize'], {}), '(dataSize)\n', (6056, 6066), True, 'import numpy as np\n'), ((8370, 8472), 'theano.function', 'theano.function', (['[x, y, mask, lengths]', 'cost'], {'updates': '(zgup + rg2up)', 'name': '"""adadelta_f_grad_shared"""'}), "([x, y, mask, lengths], cost, updates=zgup + rg2up, name=\n 'adadelta_f_grad_shared')\n", (8385, 8472), False, 'import theano\n'), ((8773, 8878), 'theano.function', 'theano.function', (['[]', '[]'], {'updates': '(ru2up + param_up)', 'on_unused_input': '"""ignore"""', 'name': '"""adadelta_f_update"""'}), "([], [], updates=ru2up + param_up, on_unused_input='ignore',\n name='adadelta_f_update')\n", (8788, 8878), False, 'import theano\n'), ((9066, 9081), 'numpy.max', 'np.max', (['lengths'], {}), '(lengths)\n', (9072, 9081), True, 'import numpy as np\n'), ((9636, 9674), 'numpy.array', 'np.array', (['lengths'], {'dtype': 'config.floatX'}), '(lengths, dtype=config.floatX)\n', (9644, 9674), True, 'import numpy as np\n'), ((12442, 12529), 'theano.function', 'theano.function', ([], {'inputs': '[x, y, mask, lengths]', 'outputs': 'cost_noreg', 'name': '"""get_cost"""'}), "(inputs=[x, y, mask, lengths], outputs=cost_noreg, name=\n 'get_cost')\n", (12457, 12529), False, 'import theano\n'), ((12546, 12617), 'theano.function', 'theano.function', ([], {'inputs': '[x, mask]', 'outputs': 'y_hat', 'name': '"""get_prediction"""'}), "(inputs=[x, mask], outputs=y_hat, name='get_prediction')\n", (12561, 12617), False, 'import theano\n'), ((17930, 17955), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (17953, 17955), False, 'import sys, random, time, argparse\n'), ((2378, 2408), 'theano.shared', 'theano.shared', (['value'], {'name': 'key'}), '(value, name=key)\n', (2391, 2408), False, 'import theano\n'), ((2992, 3007), 'theano.tensor.dot', 'T.dot', (['h', 'U_gru'], {}), '(h, U_gru)\n', (2997, 3007), True, 'import theano.tensor as T\n'), ((3350, 3378), 'theano.tensor.dot', 'T.dot', (['emb', "tparams['W_gru']"], {}), "(emb, tparams['W_gru'])\n", (3355, 3378), True, 'import theano.tensor as T\n'), ((5050, 5063), 'theano.tensor.dot', 'T.dot', (['x', 'emb'], {}), '(x, emb)\n', (5055, 5063), True, 'import theano.tensor as T\n'), ((13349, 13360), 'time.time', 'time.time', ([], {}), '()\n', (13358, 13360), False, 'import sys, random, time, argparse\n'), ((14110, 14126), 'numpy.mean', 'np.mean', (['costVec'], {}), '(costVec)\n', (14117, 14126), True, 'import numpy as np\n'), ((815, 859), 'numpy.random.uniform', 'np.random.uniform', (['left', 'right', '(dim1, dim2)'], {}), '(left, right, (dim1, dim2))\n', (832, 859), True, 'import numpy as np\n'), ((1748, 1774), 'numpy.zeros', 'np.zeros', (['attentionDimSize'], {}), '(attentionDimSize)\n', (1756, 1774), True, 'import numpy as np\n'), ((1825, 1871), 'numpy.random.uniform', 'np.random.uniform', (['(-0.1)', '(0.1)', 'attentionDimSize'], {}), '(-0.1, 0.1, attentionDimSize)\n', (1842, 1871), True, 'import numpy as np\n'), ((2058, 2085), 'numpy.zeros', 'np.zeros', (['(3 * hiddenDimSize)'], {}), '(3 * hiddenDimSize)\n', (2066, 2085), True, 'import numpy as np\n'), ((2202, 2220), 'numpy.zeros', 'np.zeros', (['numClass'], {}), '(numClass)\n', (2210, 2220), True, 'import numpy as np\n'), ((3819, 3864), 'theano.tensor.dot', 'T.dot', (['attentionInput', "tparams['W_attention']"], {}), "(attentionInput, tparams['W_attention'])\n", (3824, 3864), True, 'import theano.tensor as T\n'), ((4095, 4126), 'theano.tensor.dot', 'T.dot', (['emb', "tparams['W_output']"], {}), "(emb, tparams['W_output'])\n", (4100, 4126), True, 'import theano.tensor as T\n'), ((9091, 9145), 'numpy.zeros', 'np.zeros', (["(maxlen, n_samples, options['inputDimSize'])"], {}), "((maxlen, n_samples, options['inputDimSize']))\n", (9099, 9145), True, 'import numpy as np\n'), ((9177, 9227), 'numpy.zeros', 'np.zeros', (["(maxlen, n_samples, options['numClass'])"], {}), "((maxlen, n_samples, options['numClass']))\n", (9185, 9227), True, 'import numpy as np\n'), ((9262, 9291), 'numpy.zeros', 'np.zeros', (['(maxlen, n_samples)'], {}), '((maxlen, n_samples))\n', (9270, 9291), True, 'import numpy as np\n'), ((10914, 10930), 'numpy.array', 'np.array', (['leaves'], {}), '(leaves)\n', (10922, 10930), True, 'import numpy as np\n'), ((14034, 14045), 'time.time', 'time.time', ([], {}), '()\n', (14043, 14045), False, 'import sys, random, time, argparse\n'), ((5294, 5315), 'theano.tensor.log', 'T.log', (['(y_hat + logEps)'], {}), '(y_hat + logEps)\n', (5299, 5315), True, 'import theano.tensor as T\n'), ((5329, 5356), 'theano.tensor.log', 'T.log', (['(1.0 - y_hat + logEps)'], {}), '(1.0 - y_hat + logEps)\n', (5334, 5356), True, 'import theano.tensor as T\n'), ((8504, 8523), 'theano.tensor.sqrt', 'T.sqrt', (['(rg2 + 1e-06)'], {}), '(rg2 + 1e-06)\n', (8510, 8523), True, 'import theano.tensor as T\n'), ((8483, 8502), 'theano.tensor.sqrt', 'T.sqrt', (['(ru2 + 1e-06)'], {}), '(ru2 + 1e-06)\n', (8489, 8502), True, 'import theano.tensor as T\n')]
|
# Wrapper class around hnswlib
import hnswlib
import numpy as np
import threading
import pickle
from .typings import VectorList
class Hnswlib():
def __init__(self, space, dim):
self.index = hnswlib.Index(space, dim)
self.lock = threading.Lock()
self.dict_labels = {}
self.cur_ind = 0
def init_index(self, max_elements: int, ef_construction = 200, M = 16):
self.index.init_index(max_elements = max_elements, ef_construction = ef_construction, M = M)
def get_max_elements(self):
return self.index.get_max_elements()
def get_current_count(self):
return self.index.get_current_count()
def add_items(self, data: VectorList, ids=None):
if ids is not None:
assert len(data) == len(ids)
num_added = len(data)
with self.lock:
start = self.cur_ind
self.cur_ind += num_added
int_labels = []
if ids is not None:
for dl in ids:
int_labels.append(start)
self.dict_labels[start] = dl
start += 1
else:
for _ in range(len(data)):
int_labels.append(start)
self.dict_labels[start] = start
start += 1
self.index.add_items(data=data, ids=np.asarray(int_labels))
def set_ef(self, ef: int):
self.index.set_ef(ef)
def load_index(self, path: str, max_elements=0):
self.index.load_index(path, max_elements=max_elements)
with open(path + ".pkl", "rb") as f:
self.cur_ind, self.dict_labels = pickle.load(f)
def save_index(self, path: str):
self.index.save_index(path)
with open(path + ".pkl", "wb") as f:
pickle.dump((self.cur_ind, self.dict_labels), f)
def set_num_threads(self, num_threads:int):
self.index.set_num_threads(num_threads)
def knn_query(self, data: VectorList, k=1):
labels_int, distances = self.index.knn_query(data=data, k=k)
labels = []
for li in labels_int:
line = []
for l in li:
line.append(self.dict_labels[l])
labels.append(line)
return labels, distances
|
[
"pickle.dump",
"numpy.asarray",
"threading.Lock",
"pickle.load",
"hnswlib.Index"
] |
[((203, 228), 'hnswlib.Index', 'hnswlib.Index', (['space', 'dim'], {}), '(space, dim)\n', (216, 228), False, 'import hnswlib\n'), ((249, 265), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (263, 265), False, 'import threading\n'), ((1604, 1618), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1615, 1618), False, 'import pickle\n'), ((1750, 1798), 'pickle.dump', 'pickle.dump', (['(self.cur_ind, self.dict_labels)', 'f'], {}), '((self.cur_ind, self.dict_labels), f)\n', (1761, 1798), False, 'import pickle\n'), ((1311, 1333), 'numpy.asarray', 'np.asarray', (['int_labels'], {}), '(int_labels)\n', (1321, 1333), True, 'import numpy as np\n')]
|
from __future__ import annotations
import typing
import robopom.component_loader as pom_loader
import os
import pathlib
import robopom.RobopomPage as robopom_page
import robopom.constants as constants
import robot.parsing.model as robot_model
import robot.parsing.settings as robot_settings
class ComponentVariables:
@staticmethod
def get_variables(pages_files: typing.Union[os.PathLike, typing.List[os.PathLike]] = constants.PAGES_FILE,
model_files: typing.Union[os.PathLike, typing.List[os.PathLike]] = None) -> dict:
if model_files is None:
model_files = []
if isinstance(model_files, str):
model_files = [model_files]
if isinstance(pages_files, str):
pages_files = [pages_files]
working_dir = os.path.abspath(".")
real_files = []
for pages_file in pages_files:
if os.path.isabs(pages_file):
real_files.append(pages_file)
else:
for found in pathlib.Path(working_dir).rglob(str(pages_file)):
real_files.append(str(found))
for pages_file in real_files:
if os.path.isfile(pages_file):
res = robot_model.ResourceFile(pages_file).populate()
for page_res in res.imports.data:
page_res: robot_settings.Resource
page_res_name = os.path.splitext(page_res.name)[0]
if os.path.isabs(page_res_name):
model_files.append(page_res_name)
else:
pages_file_dir = os.path.dirname(pages_file)
model_files.append(os.path.join(pages_file_dir, page_res_name))
model_files = [robopom_page.RobopomPage.get_yaml_file(model_file) for model_file in model_files]
d = {}
for model_file in model_files:
component = pom_loader.ComponentLoader.load_component_from_file(model_file)
if component is not None:
d.update(component.variables_dictionary())
return d
|
[
"os.path.abspath",
"os.path.isabs",
"robopom.component_loader.ComponentLoader.load_component_from_file",
"os.path.dirname",
"robopom.RobopomPage.RobopomPage.get_yaml_file",
"os.path.isfile",
"pathlib.Path",
"os.path.splitext",
"robot.parsing.model.ResourceFile",
"os.path.join"
] |
[((798, 818), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (813, 818), False, 'import os\n'), ((897, 922), 'os.path.isabs', 'os.path.isabs', (['pages_file'], {}), '(pages_file)\n', (910, 922), False, 'import os\n'), ((1171, 1197), 'os.path.isfile', 'os.path.isfile', (['pages_file'], {}), '(pages_file)\n', (1185, 1197), False, 'import os\n'), ((1762, 1812), 'robopom.RobopomPage.RobopomPage.get_yaml_file', 'robopom_page.RobopomPage.get_yaml_file', (['model_file'], {}), '(model_file)\n', (1800, 1812), True, 'import robopom.RobopomPage as robopom_page\n'), ((1922, 1985), 'robopom.component_loader.ComponentLoader.load_component_from_file', 'pom_loader.ComponentLoader.load_component_from_file', (['model_file'], {}), '(model_file)\n', (1973, 1985), True, 'import robopom.component_loader as pom_loader\n'), ((1467, 1495), 'os.path.isabs', 'os.path.isabs', (['page_res_name'], {}), '(page_res_name)\n', (1480, 1495), False, 'import os\n'), ((1017, 1042), 'pathlib.Path', 'pathlib.Path', (['working_dir'], {}), '(working_dir)\n', (1029, 1042), False, 'import pathlib\n'), ((1221, 1257), 'robot.parsing.model.ResourceFile', 'robot_model.ResourceFile', (['pages_file'], {}), '(pages_file)\n', (1245, 1257), True, 'import robot.parsing.model as robot_model\n'), ((1409, 1440), 'os.path.splitext', 'os.path.splitext', (['page_res.name'], {}), '(page_res.name)\n', (1425, 1440), False, 'import os\n'), ((1622, 1649), 'os.path.dirname', 'os.path.dirname', (['pages_file'], {}), '(pages_file)\n', (1637, 1649), False, 'import os\n'), ((1693, 1736), 'os.path.join', 'os.path.join', (['pages_file_dir', 'page_res_name'], {}), '(pages_file_dir, page_res_name)\n', (1705, 1736), False, 'import os\n')]
|
import argparse
import os
import yaml
import sys
import numpy as np
import time
import json
from .eval_np import PanopticEval
from .config import global_cfg
need_nuscenes_remap = False
if global_cfg.DATA_CONFIG.DATASET_NAME == 'SemanticKitti':
DATA = yaml.safe_load(open('semantic-kitti.yaml', 'r'))
# get number of interest classes, and the label mappings
class_remap = DATA["learning_map"]
class_inv_remap = DATA["learning_map_inv"]
class_ignore = DATA["learning_ignore"]
nr_classes = len(class_inv_remap)
class_strings = DATA["labels"]
# make lookup table for mapping
maxkey = max(class_remap.keys())
# +100 hack making lut bigger just in case there are unknown labels
class_lut = np.zeros((maxkey + 100), dtype=np.int32)
class_lut[list(class_remap.keys())] = list(class_remap.values())
ignore_class = [cl for cl, ignored in class_ignore.items() if ignored]
class_inv_lut = np.zeros((20), dtype=np.int32)
class_inv_lut[list(class_inv_remap.keys())] = list(class_inv_remap.values())
things = ['car', 'truck', 'bicycle', 'motorcycle', 'other-vehicle', 'person', 'bicyclist', 'motorcyclist']
stuff = [
'road', 'sidewalk', 'parking', 'other-ground', 'building', 'vegetation', 'trunk', 'terrain', 'fence', 'pole',
'traffic-sign'
]
all_classes = things + stuff
valid_xentropy_ids = [1, 4, 2, 3, 5, 6, 7, 8]
else:
raise NotImplementedError
def init_eval(min_points = 50):
print("New evaluator with min_points of {}".format(min_points))
class_evaluator = PanopticEval(nr_classes, None, ignore_class, min_points = min_points)
return class_evaluator
def eval_one_scan(class_evaluator, gt_sem, gt_ins, pred_sem, pred_ins):
class_evaluator.addBatch(pred_sem, pred_ins, gt_sem, gt_ins)
def eval_one_scan_w_fname(class_evaluator, gt_sem, gt_ins, pred_sem, pred_ins, fname):
class_evaluator.addBatch_w_fname(pred_sem, pred_ins, gt_sem, gt_ins, fname)
def printResults(class_evaluator, logger=None, sem_only=False):
class_PQ, class_SQ, class_RQ, class_all_PQ, class_all_SQ, class_all_RQ = class_evaluator.getPQ()
class_IoU, class_all_IoU = class_evaluator.getSemIoU()
# now make a nice dictionary
output_dict = {}
# make python variables
class_PQ = class_PQ.item()
class_SQ = class_SQ.item()
class_RQ = class_RQ.item()
class_all_PQ = class_all_PQ.flatten().tolist()
class_all_SQ = class_all_SQ.flatten().tolist()
class_all_RQ = class_all_RQ.flatten().tolist()
class_IoU = class_IoU.item()
class_all_IoU = class_all_IoU.flatten().tolist()
output_dict["all"] = {}
output_dict["all"]["PQ"] = class_PQ
output_dict["all"]["SQ"] = class_SQ
output_dict["all"]["RQ"] = class_RQ
output_dict["all"]["IoU"] = class_IoU
classwise_tables = {}
for idx, (pq, rq, sq, iou) in enumerate(zip(class_all_PQ, class_all_RQ, class_all_SQ, class_all_IoU)):
class_str = class_strings[class_inv_remap[idx]]
output_dict[class_str] = {}
output_dict[class_str]["PQ"] = pq
output_dict[class_str]["SQ"] = sq
output_dict[class_str]["RQ"] = rq
output_dict[class_str]["IoU"] = iou
PQ_all = np.mean([float(output_dict[c]["PQ"]) for c in all_classes])
PQ_dagger = np.mean([float(output_dict[c]["PQ"]) for c in things] + [float(output_dict[c]["IoU"]) for c in stuff])
RQ_all = np.mean([float(output_dict[c]["RQ"]) for c in all_classes])
SQ_all = np.mean([float(output_dict[c]["SQ"]) for c in all_classes])
PQ_things = np.mean([float(output_dict[c]["PQ"]) for c in things])
RQ_things = np.mean([float(output_dict[c]["RQ"]) for c in things])
SQ_things = np.mean([float(output_dict[c]["SQ"]) for c in things])
PQ_stuff = np.mean([float(output_dict[c]["PQ"]) for c in stuff])
RQ_stuff = np.mean([float(output_dict[c]["RQ"]) for c in stuff])
SQ_stuff = np.mean([float(output_dict[c]["SQ"]) for c in stuff])
mIoU = output_dict["all"]["IoU"]
codalab_output = {}
codalab_output["pq_mean"] = float(PQ_all)
codalab_output["pq_dagger"] = float(PQ_dagger)
codalab_output["sq_mean"] = float(SQ_all)
codalab_output["rq_mean"] = float(RQ_all)
codalab_output["iou_mean"] = float(mIoU)
codalab_output["pq_stuff"] = float(PQ_stuff)
codalab_output["rq_stuff"] = float(RQ_stuff)
codalab_output["sq_stuff"] = float(SQ_stuff)
codalab_output["pq_things"] = float(PQ_things)
codalab_output["rq_things"] = float(RQ_things)
codalab_output["sq_things"] = float(SQ_things)
key_list = [
"pq_mean",
"pq_dagger",
"sq_mean",
"rq_mean",
"iou_mean",
"pq_stuff",
"rq_stuff",
"sq_stuff",
"pq_things",
"rq_things",
"sq_things"
]
if sem_only and logger != None:
evaluated_fnames = class_evaluator.evaluated_fnames
logger.info('Evaluated {} frames. Duplicated frame number: {}'.format(len(evaluated_fnames), len(evaluated_fnames) - len(set(evaluated_fnames))))
logger.info('| | IoU | PQ | RQ | SQ |')
for k, v in output_dict.items():
logger.info('|{}| {:.4f} | {:.4f} | {:.4f} | {:.4f} |'.format(
k.ljust(8)[-8:], v['IoU'], v['PQ'], v['RQ'], v['SQ']
))
return codalab_output
if sem_only and logger is None:
evaluated_fnames = class_evaluator.evaluated_fnames
print('Evaluated {} frames. Duplicated frame number: {}'.format(len(evaluated_fnames), len(evaluated_fnames) - len(set(evaluated_fnames))))
print('| | IoU | PQ | RQ | SQ |')
for k, v in output_dict.items():
print('|{}| {:.4f} | {:.4f} | {:.4f} | {:.4f} |'.format(
k.ljust(8)[-8:], v['IoU'], v['PQ'], v['RQ'], v['SQ']
))
return codalab_output
if logger != None:
evaluated_fnames = class_evaluator.evaluated_fnames
logger.info('Evaluated {} frames. Duplicated frame number: {}'.format(len(evaluated_fnames), len(evaluated_fnames) - len(set(evaluated_fnames))))
logger.info('| | PQ | RQ | SQ | IoU |')
for k, v in output_dict.items():
logger.info('|{}| {:.4f} | {:.4f} | {:.4f} | {:.4f} |'.format(
k.ljust(8)[-8:], v['PQ'], v['RQ'], v['SQ'], v['IoU']
))
logger.info('True Positive: ')
logger.info('\t|\t'.join([str(x) for x in class_evaluator.pan_tp]))
logger.info('False Positive: ')
logger.info('\t|\t'.join([str(x) for x in class_evaluator.pan_fp]))
logger.info('False Negative: ')
logger.info('\t|\t'.join([str(x) for x in class_evaluator.pan_fn]))
if logger is None:
evaluated_fnames = class_evaluator.evaluated_fnames
print('Evaluated {} frames. Duplicated frame number: {}'.format(len(evaluated_fnames), len(evaluated_fnames) - len(set(evaluated_fnames))))
print('| | PQ | RQ | SQ | IoU |')
for k, v in output_dict.items():
print('|{}| {:.4f} | {:.4f} | {:.4f} | {:.4f} |'.format(
k.ljust(8)[-8:], v['PQ'], v['RQ'], v['SQ'], v['IoU']
))
print('True Positive: ')
print('\t|\t'.join([str(x) for x in class_evaluator.pan_tp]))
print('False Positive: ')
print('\t|\t'.join([str(x) for x in class_evaluator.pan_fp]))
print('False Negative: ')
print('\t|\t'.join([str(x) for x in class_evaluator.pan_fn]))
for key in key_list:
if logger != None:
logger.info("{}:\t{}".format(key, codalab_output[key]))
else:
print("{}:\t{}".format(key, codalab_output[key]))
return codalab_output
|
[
"numpy.zeros"
] |
[((729, 767), 'numpy.zeros', 'np.zeros', (['(maxkey + 100)'], {'dtype': 'np.int32'}), '(maxkey + 100, dtype=np.int32)\n', (737, 767), True, 'import numpy as np\n'), ((935, 963), 'numpy.zeros', 'np.zeros', (['(20)'], {'dtype': 'np.int32'}), '(20, dtype=np.int32)\n', (943, 963), True, 'import numpy as np\n')]
|
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
"""Base configuration."""
SECRET_KEY = os.environ.get("SECRET_KEY") or "secret_key"
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = None # added to supress warning during testing.
SQLAFIXTURES_DIRECTORY = os.path.join(basedir, 'sqlafixtures')
SQLAFIXTURES_FILENAME = 'fixtures_file.xlsx'
SQLAFIXTURES_MODULES = ['app.users.models']
class ProdConfig(Config):
"""Production configuration."""
DEBUG = False
SQLALCHEMY_DATABASE_URI = os.environ.get(
"DATABASE_URL"
) or "sqlite:///" + os.path.join(basedir, "app.db")
class DevConfig(Config):
"""Development configuration."""
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get(
"DATABASE_URL"
) or "sqlite:///" + os.path.join(basedir, "app_dev.db")
SQLAFIXTURES_MODE = 'development'
class TestConfig(Config):
"""Testing configuration."""
TESTING = True
DEBUG = True
SQLALCHEMY_DATABASE_URI = "sqlite://"
WTF_CSRF_ENABLED = False
SQLAFIXTURES_MODE = 'testing'
|
[
"os.environ.get",
"os.path.dirname",
"os.path.join"
] |
[((37, 62), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (52, 62), False, 'import os\n'), ((332, 369), 'os.path.join', 'os.path.join', (['basedir', '"""sqlafixtures"""'], {}), "(basedir, 'sqlafixtures')\n", (344, 369), False, 'import os\n'), ((136, 164), 'os.environ.get', 'os.environ.get', (['"""SECRET_KEY"""'], {}), "('SECRET_KEY')\n", (150, 164), False, 'import os\n'), ((580, 610), 'os.environ.get', 'os.environ.get', (['"""DATABASE_URL"""'], {}), "('DATABASE_URL')\n", (594, 610), False, 'import os\n'), ((787, 817), 'os.environ.get', 'os.environ.get', (['"""DATABASE_URL"""'], {}), "('DATABASE_URL')\n", (801, 817), False, 'import os\n'), ((643, 674), 'os.path.join', 'os.path.join', (['basedir', '"""app.db"""'], {}), "(basedir, 'app.db')\n", (655, 674), False, 'import os\n'), ((850, 885), 'os.path.join', 'os.path.join', (['basedir', '"""app_dev.db"""'], {}), "(basedir, 'app_dev.db')\n", (862, 885), False, 'import os\n')]
|
# ---------------------------------------------------------------------
# fm.totaloutage
# ---------------------------------------------------------------------
# Copyright (C) 2007-2016 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# NOC modules
from noc.lib.app.extapplication import ExtApplication
from noc.core.translation import ugettext as _
from noc.config import config
class TotalOutageApplication(ExtApplication):
title = _("Total Outages")
menu = _("Total Outages")
glyph = "bolt"
link = "/api/card/view/totaloutage/1/?refresh=%s" % config.fm.total_outage_refresh
|
[
"noc.core.translation.ugettext"
] |
[((507, 525), 'noc.core.translation.ugettext', '_', (['"""Total Outages"""'], {}), "('Total Outages')\n", (508, 525), True, 'from noc.core.translation import ugettext as _\n'), ((537, 555), 'noc.core.translation.ugettext', '_', (['"""Total Outages"""'], {}), "('Total Outages')\n", (538, 555), True, 'from noc.core.translation import ugettext as _\n')]
|
import logging
import os
import sys
from pathlib import Path
from typing import Union, Optional, Any, Dict
from pydantic import BaseSettings
from sqlalchemy.engine import Engine
from sqlalchemy.ext.asyncio import AsyncEngine
from sqlalchemy.orm import sessionmaker
_log = logging.getLogger(__name__)
env_file_sentinel = str(object())
run_env = os.environ.get("RUN_ENV", None)
if not run_env:
print("No run_env specified. Exiting.")
sys.exit()
run_env = run_env.lower()
ROOT_DIR = Path(__file__).parent.parent.absolute()
env_path = ROOT_DIR / f".env.{run_env}"
if not Path(env_path).is_file():
print(f"No env file '{env_path}' found for environment. Exiting.")
sys.exit()
class Environment(BaseSettings):
run_env: str
log_level: str = "INFO"
# alpha_vantage_apikey: str = "<KEY>"
alpha_vantage_apikey: str = "<KEY>"
alpha_vantage_url: str = "https://www.alphavantage.co"
def __init__(
self,
_env_file: Union[Path, str, None] = env_file_sentinel,
_env_file_encoding: Optional[str] = None,
**values: Any,
):
super().__init__(
_env_file=_env_file, _env_file_encoding=_env_file_encoding, **values
)
def log_config(self) -> Dict:
cfg = self.dict()
skip_keys = ("api_key",)
sanitized_cfg = {k: v for k, v in cfg.items() if k not in skip_keys}
return sanitized_cfg
config = Environment(_env_file=env_path)
|
[
"os.environ.get",
"sys.exit",
"pathlib.Path",
"logging.getLogger"
] |
[((274, 301), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (291, 301), False, 'import logging\n'), ((348, 379), 'os.environ.get', 'os.environ.get', (['"""RUN_ENV"""', 'None'], {}), "('RUN_ENV', None)\n", (362, 379), False, 'import os\n'), ((444, 454), 'sys.exit', 'sys.exit', ([], {}), '()\n', (452, 454), False, 'import sys\n'), ((681, 691), 'sys.exit', 'sys.exit', ([], {}), '()\n', (689, 691), False, 'import sys\n'), ((580, 594), 'pathlib.Path', 'Path', (['env_path'], {}), '(env_path)\n', (584, 594), False, 'from pathlib import Path\n'), ((493, 507), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (497, 507), False, 'from pathlib import Path\n')]
|