code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import torch
from torch import nn
# LabelSmoothingLoss from: https://github.com/dreamgonfly/transformer-pytorch/blob/master/losses.py
# License: https://github.com/dreamgonfly/transformer-pytorch/blob/master/LICENSE
class LabelSmoothingLoss(nn.Module):
def __init__(self, classes, smoothing=0.0):
super(LabelSmoothingLoss, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.cls = classes
def forward(self, pred, target):
assert 0 <= self.smoothing < 1
pred = pred.log_softmax(dim=-1)
with torch.no_grad():
true_dist = torch.zeros_like(pred)
true_dist.fill_(self.smoothing / (self.cls - 1))
true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)
return torch.mean(torch.sum(-true_dist * pred, dim=-1))
| [
"torch.no_grad",
"torch.zeros_like",
"torch.sum"
] | [((586, 601), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (599, 601), False, 'import torch\n'), ((627, 649), 'torch.zeros_like', 'torch.zeros_like', (['pred'], {}), '(pred)\n', (643, 649), False, 'import torch\n'), ((814, 850), 'torch.sum', 'torch.sum', (['(-true_dist * pred)'], {'dim': '(-1)'}), '(-true_dist * pred, dim=-1)\n', (823, 850), False, 'import torch\n')] |
# Copyright (C) 2017 <NAME> and <NAME>
#
# This file is part of WESTPA.
#
# WESTPA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# WESTPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WESTPA. If not, see <http://www.gnu.org/licenses/>.
'''
Function(s) for the postanalysis toolkit
'''
import logging
log = logging.getLogger(__name__)
import _reweight
from _reweight import (stats_process, reweight_for_c) #@UnresolvedImport
from matrix import FluxMatrix
| [
"logging.getLogger"
] | [((762, 789), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (779, 789), False, 'import logging\n')] |
import unittest
import numpy as np
import prml.nn as nn
class TestGaussian(unittest.TestCase):
def test_gaussian_draw_forward(self):
mu = nn.array(0)
sigma = nn.softplus(nn.array(-1))
gaussian = nn.Gaussian(mu, sigma)
sample = []
for _ in range(1000):
sample.append(gaussian.draw().value)
self.assertTrue(np.allclose(np.mean(sample), 0, rtol=0.1, atol=0.1), np.mean(sample))
self.assertTrue(np.allclose(np.std(sample), gaussian.std.value, 0.1, 0.1))
def test_gaussian_draw_backward(self):
mu = nn.array(0)
s = nn.array(2)
optimizer = nn.optimizer.Gradient({0: mu, 1: s}, 0.01)
prior = nn.Gaussian(1, 1)
for _ in range(1000):
mu.cleargrad()
s.cleargrad()
gaussian = nn.Gaussian(mu, nn.softplus(s))
gaussian.draw()
loss = nn.loss.kl_divergence(gaussian, prior).sum()
optimizer.minimize(loss)
self.assertTrue(np.allclose(gaussian.mean.value, 1, 0.1, 0.1))
self.assertTrue(np.allclose(gaussian.std.value, 1, 0.1, 0.1))
if __name__ == "__main__":
unittest.main()
| [
"numpy.mean",
"numpy.allclose",
"prml.nn.softplus",
"prml.nn.optimizer.Gradient",
"prml.nn.loss.kl_divergence",
"numpy.std",
"unittest.main",
"prml.nn.Gaussian",
"prml.nn.array"
] | [((1156, 1171), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1169, 1171), False, 'import unittest\n'), ((153, 164), 'prml.nn.array', 'nn.array', (['(0)'], {}), '(0)\n', (161, 164), True, 'import prml.nn as nn\n'), ((226, 248), 'prml.nn.Gaussian', 'nn.Gaussian', (['mu', 'sigma'], {}), '(mu, sigma)\n', (237, 248), True, 'import prml.nn as nn\n'), ((582, 593), 'prml.nn.array', 'nn.array', (['(0)'], {}), '(0)\n', (590, 593), True, 'import prml.nn as nn\n'), ((606, 617), 'prml.nn.array', 'nn.array', (['(2)'], {}), '(2)\n', (614, 617), True, 'import prml.nn as nn\n'), ((638, 684), 'prml.nn.optimizer.Gradient', 'nn.optimizer.Gradient', (['{(0): mu, (1): s}', '(0.01)'], {}), '({(0): mu, (1): s}, 0.01)\n', (659, 684), True, 'import prml.nn as nn\n'), ((697, 714), 'prml.nn.Gaussian', 'nn.Gaussian', (['(1)', '(1)'], {}), '(1, 1)\n', (708, 714), True, 'import prml.nn as nn\n'), ((193, 205), 'prml.nn.array', 'nn.array', (['(-1)'], {}), '(-1)\n', (201, 205), True, 'import prml.nn as nn\n'), ((425, 440), 'numpy.mean', 'np.mean', (['sample'], {}), '(sample)\n', (432, 440), True, 'import numpy as np\n'), ((1006, 1051), 'numpy.allclose', 'np.allclose', (['gaussian.mean.value', '(1)', '(0.1)', '(0.1)'], {}), '(gaussian.mean.value, 1, 0.1, 0.1)\n', (1017, 1051), True, 'import numpy as np\n'), ((1077, 1121), 'numpy.allclose', 'np.allclose', (['gaussian.std.value', '(1)', '(0.1)', '(0.1)'], {}), '(gaussian.std.value, 1, 0.1, 0.1)\n', (1088, 1121), True, 'import numpy as np\n'), ((384, 399), 'numpy.mean', 'np.mean', (['sample'], {}), '(sample)\n', (391, 399), True, 'import numpy as np\n'), ((478, 492), 'numpy.std', 'np.std', (['sample'], {}), '(sample)\n', (484, 492), True, 'import numpy as np\n'), ((837, 851), 'prml.nn.softplus', 'nn.softplus', (['s'], {}), '(s)\n', (848, 851), True, 'import prml.nn as nn\n'), ((900, 938), 'prml.nn.loss.kl_divergence', 'nn.loss.kl_divergence', (['gaussian', 'prior'], {}), '(gaussian, prior)\n', (921, 938), True, 'import prml.nn as nn\n')] |
# Generated by Django 2.1.3 on 2018-11-24 13:52
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('monsterapi', '0022_auto_20181123_2339'),
]
operations = [
migrations.CreateModel(
name='Check',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('result', models.BooleanField(default=None)),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('game', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='monsterapi.Game')),
('melody', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='monsterapi.Melody')),
('monster', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='monsterapi.Monster')),
],
),
]
| [
"django.db.models.DateTimeField",
"django.db.models.ForeignKey",
"django.db.models.AutoField",
"django.db.models.BooleanField"
] | [((394, 487), '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", (410, 487), False, 'from django.db import migrations, models\n'), ((513, 546), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': 'None'}), '(default=None)\n', (532, 546), False, 'from django.db import migrations, models\n'), ((582, 637), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'django.utils.timezone.now'}), '(default=django.utils.timezone.now)\n', (602, 637), False, 'from django.db import migrations, models\n'), ((665, 777), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""monsterapi.Game"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to='monsterapi.Game')\n", (682, 777), False, 'from django.db import migrations, models\n'), ((802, 916), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""monsterapi.Melody"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to='monsterapi.Melody')\n", (819, 916), False, 'from django.db import migrations, models\n'), ((942, 1057), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""monsterapi.Monster"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to='monsterapi.Monster')\n", (959, 1057), False, 'from django.db import migrations, models\n')] |
import sys
import argparse
import matplotlib.pyplot as plt
import numpy as np
import pickle
def load_obj(name):
pkl_path = ""
with open(pkl_path + name + ".pkl", 'rb') as f:
return pickle.load(f)
def load_prun_obj(name):
pkl_path = ""
with open(pkl_path + name + ".pkl", 'rb') as f:
return pickle.load(f)
def result_plt(results, label):
# lists = sorted(results.items())
# x, y = zip(*lists)
plt.plot(results, label = label)
matrices = ['acc', 'loss']
# labels = ['fedavg_5iid_5niid', 'fedavg_6iid_4niid', 'fedavg_2iid_8niid', 'fedavg_8iid_2niid' ]
# labels_prun = ['fedavg_5iid_5niid_prun', 'fedavg_6iid_4niid_prun', 'fedavg_8iid_2niid_prun']
labels = ['Optimal Aggregation', 'FedAvg' ]
labels_prun = ['fedadp_5iid_5niid_0.8_prun' , 'fedadp_5iid_5niid_current_prun','fedadp_5iid_5niid']
# iid_list = [5, 6, 2, 8]
# niid_list = [10 - x for x in iid_list]
iid_list = [10]
niid_list = [10]
prob_ratio = [0.1]
model = [ 'cnn']
num_exp = 10
num_exp_3 = 3
num_round = 50
def define_and_get_arguments(args=sys.argv[1:]):
parser = argparse.ArgumentParser(
description="Run figure plot"
)
parser.add_argument("--matrice", type=str, choices=matrices, default="loss", help = "result matrices")
parser.add_argument("--iid", type=int, default=5, help="number of nodes")
parser.add_argument("--training_rounds", type=int, default = 50, help= "number of training rounds")
args = parser.parse_args(args=args)
return args
def main():
args = define_and_get_arguments()
fedavg_data = {}
fedadp_data = {}
feddel_data = {}
remove_node = {}
# for exp in range(1,num_exp+1):
# remove_node[exp] = load_obj('remove node_exp%s' %(exp))
# print(remove_node[2][0])
for exp in range(1,num_exp+1):
fedadp_data[exp] = load_obj('feddel_mnist_%s_1_exp%s' %(model[0], exp))
for exp in range(1,num_exp+1):
fedavg_data[exp] = load_obj('fedavg_mnist_%s_1_exp%s' %(model[0],exp))
if args.matrice == "acc":
overall_avg = []
for k in range(1,num_exp+1):
# print(fedadp_data[k][0])
overall_avg.extend(fedadp_data[k][0])
temp_adp = np.array([overall_avg[num_round*i:num_round*(i+1)] for i in range(num_exp)])
acc_adp = np.mean(temp_adp, axis=0)
# print(acc_adp)
result_plt(acc_adp, labels[0])
overall_avg = []
for k in range(1,num_exp+1):
overall_avg.extend(fedavg_data[k][0])
temp_avg = np.array([overall_avg[num_round*i:num_round*(i+1)] for i in range(num_exp)])
acc_avg = np.mean(temp_avg, axis=0)
# print(acc_avg)
result_plt(acc_avg, labels[-1])
ylabel = "Testing Accuracy"
elif args.matrice == "loss":
overall_avg = []
for k in range(1,num_exp+1):
# print(fedadp_data[k][0])
overall_avg.extend(fedadp_data[k][1])
temp_adp = np.array([overall_avg[num_round*i:num_round*(i+1)] for i in range(num_exp)])
acc_adp = np.mean(temp_adp, axis=0)
# print(acc_adp)
plt.plot(list(range(num_round)), acc_adp, color='#069AF3', linewidth = '1.5', label = labels[0])
overall_avg = []
for k in range(1,num_exp+1):
overall_avg.extend(fedavg_data[k][1])
temp_avg = np.array([overall_avg[num_round*i:num_round*(i+1)] for i in range(num_exp)])
acc_avg = np.mean(temp_avg, axis=0)
plt.plot(list(range(num_round)), acc_avg, '--', color='#F97306', linewidth = '1.5',label = labels[-1])
plt.xlabel("Communication Round", fontsize=13)
plt.gca().spines['right'].set_visible(False)
plt.gca().spines['top'].set_visible(False)
plt.ylabel( "Training Loss", fontsize=13)
plt.legend(frameon=False, loc=7, prop={'size': 10})
elif args.matrice == "sts":
x = load_obj('observe node_exp10' )
# print(x[0])
overall_avg = []
for i in range(3):
temp = []
for j in range(50):
# print(x[0][j][i])
temp.append(x[0][j][i])
overall_avg.extend(temp)
data = np.array([overall_avg[num_round*i:num_round*(i+1)] for i in range(3)])
# print(data[0])
# plt.figure()
# plt.subplot()
# fig, ax = plt.subplots(nrows=2, ncols=1)
label = ['Selected', 'Labeled', 'Excluded']
index = np.arange(0, 25, 1)
index_2 = np.arange(25, 50, 1)
# plt.hist()
color_index= ['lightgray','lightsteelblue','springgreen']
plt.subplot(2,1,1)
for i in range(3):
j = i+1
#index+2:是起始坐标点 #width是bar的宽度
# print(data[i])
plt.bar(index, data[i][:25],width=0.6,color=color_index[i], label= label[i])
plt.xticks(index)
plt.xticks(fontsize=7)
plt.yticks(fontsize=8)
plt.subplot(2,1,2)
for i in range(3):
j = i+1
#index+2:是起始坐标点 #width是bar的宽度
plt.bar(index_2, data[i][25:],width=0.6,color=color_index[i], label= label[i])
plt.xticks(index_2)
plt.yticks([0,15, 5, 10])
plt.legend(loc='best', prop={'size': 7})
plt.xticks(fontsize=7)
plt.yticks(fontsize=8)
# plt.gca().spines['top'].set_visible(False)
# plt.hist(data[i], index, alpha = 0.5)
# plt.hist(data[0], index, alpha = 0.5)
# plt.hist(data[1], index, alpha = 0.5)
fig_path = ""
plt.savefig(fig_path + "%s_com_%siid_%s" %(args.matrice, str(iid_list[0]), model[0]) + ".eps", format='eps', dpi=1200)
if __name__ == "__main__":
main()
| [
"numpy.mean",
"argparse.ArgumentParser",
"matplotlib.pyplot.ylabel",
"numpy.arange",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"pickle.load",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.subplot",
"ma... | [((441, 471), 'matplotlib.pyplot.plot', 'plt.plot', (['results'], {'label': 'label'}), '(results, label=label)\n', (449, 471), True, 'import matplotlib.pyplot as plt\n'), ((1087, 1141), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run figure plot"""'}), "(description='Run figure plot')\n", (1110, 1141), False, 'import argparse\n'), ((200, 214), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (211, 214), False, 'import pickle\n'), ((326, 340), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (337, 340), False, 'import pickle\n'), ((2333, 2358), 'numpy.mean', 'np.mean', (['temp_adp'], {'axis': '(0)'}), '(temp_adp, axis=0)\n', (2340, 2358), True, 'import numpy as np\n'), ((2662, 2687), 'numpy.mean', 'np.mean', (['temp_avg'], {'axis': '(0)'}), '(temp_avg, axis=0)\n', (2669, 2687), True, 'import numpy as np\n'), ((3102, 3127), 'numpy.mean', 'np.mean', (['temp_adp'], {'axis': '(0)'}), '(temp_adp, axis=0)\n', (3109, 3127), True, 'import numpy as np\n'), ((3495, 3520), 'numpy.mean', 'np.mean', (['temp_avg'], {'axis': '(0)'}), '(temp_avg, axis=0)\n', (3502, 3520), True, 'import numpy as np\n'), ((3651, 3697), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Communication Round"""'], {'fontsize': '(13)'}), "('Communication Round', fontsize=13)\n", (3661, 3697), True, 'import matplotlib.pyplot as plt\n'), ((3811, 3851), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Training Loss"""'], {'fontsize': '(13)'}), "('Training Loss', fontsize=13)\n", (3821, 3851), True, 'import matplotlib.pyplot as plt\n'), ((3870, 3921), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(False)', 'loc': '(7)', 'prop': "{'size': 10}"}), "(frameon=False, loc=7, prop={'size': 10})\n", (3880, 3921), True, 'import matplotlib.pyplot as plt\n'), ((4564, 4583), 'numpy.arange', 'np.arange', (['(0)', '(25)', '(1)'], {}), '(0, 25, 1)\n', (4573, 4583), True, 'import numpy as np\n'), ((4602, 4622), 'numpy.arange', 'np.arange', (['(25)', '(50)', '(1)'], {}), '(25, 50, 1)\n', (4611, 4622), True, 'import numpy as np\n'), ((4726, 4746), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (4737, 4746), True, 'import matplotlib.pyplot as plt\n'), ((4963, 4980), 'matplotlib.pyplot.xticks', 'plt.xticks', (['index'], {}), '(index)\n', (4973, 4980), True, 'import matplotlib.pyplot as plt\n'), ((4989, 5011), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(7)'}), '(fontsize=7)\n', (4999, 5011), True, 'import matplotlib.pyplot as plt\n'), ((5020, 5042), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(8)'}), '(fontsize=8)\n', (5030, 5042), True, 'import matplotlib.pyplot as plt\n'), ((5052, 5072), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (5063, 5072), True, 'import matplotlib.pyplot as plt\n'), ((5262, 5281), 'matplotlib.pyplot.xticks', 'plt.xticks', (['index_2'], {}), '(index_2)\n', (5272, 5281), True, 'import matplotlib.pyplot as plt\n'), ((5290, 5316), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[0, 15, 5, 10]'], {}), '([0, 15, 5, 10])\n', (5300, 5316), True, 'import matplotlib.pyplot as plt\n'), ((5324, 5364), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'prop': "{'size': 7}"}), "(loc='best', prop={'size': 7})\n", (5334, 5364), True, 'import matplotlib.pyplot as plt\n'), ((5373, 5395), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(7)'}), '(fontsize=7)\n', (5383, 5395), True, 'import matplotlib.pyplot as plt\n'), ((5404, 5426), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(8)'}), '(fontsize=8)\n', (5414, 5426), True, 'import matplotlib.pyplot as plt\n'), ((4878, 4955), 'matplotlib.pyplot.bar', 'plt.bar', (['index', 'data[i][:25]'], {'width': '(0.6)', 'color': 'color_index[i]', 'label': 'label[i]'}), '(index, data[i][:25], width=0.6, color=color_index[i], label=label[i])\n', (4885, 4955), True, 'import matplotlib.pyplot as plt\n'), ((5175, 5254), 'matplotlib.pyplot.bar', 'plt.bar', (['index_2', 'data[i][25:]'], {'width': '(0.6)', 'color': 'color_index[i]', 'label': 'label[i]'}), '(index_2, data[i][25:], width=0.6, color=color_index[i], label=label[i])\n', (5182, 5254), True, 'import matplotlib.pyplot as plt\n'), ((3706, 3715), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3713, 3715), True, 'import matplotlib.pyplot as plt\n'), ((3759, 3768), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3766, 3768), True, 'import matplotlib.pyplot as plt\n')] |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2020
# <NAME> (<EMAIL>),
# <NAME> (<EMAIL>) and
# <NAME> (<EMAIL>)
#
# 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.
#
#
# Simple script to plot a BRKGA solution as a scatter plot.
# To export a solution, use the method `Solution::writeTxt2` in
# the C++ code.
#
# @author <NAME>
#
if __name__ == "__main__":
from sys import argv
if len(argv) != 2:
print("Usage: %s <1: solution path>" % argv[0])
exit(1)
fid = open(argv[1], "rt")
fid.readline()
fid.readline()
fid.readline()
fid.readline()
from matplotlib import pyplot as plt
depot_x = -1
depot_y = -1
while True:
line = fid.readline()
if len(line) == 0:
break
tks = [int(x) for x in line.split()]
vehicle = tks[0]
route_length = tks[1]
route_x = []
route_y = []
for r in range(route_length):
line = fid.readline()
tks = [int(x) for x in line.split()]
route_x.append(tks[0])
route_y.append(tks[1])
route_x.append(route_x[0])
route_y.append(route_y[0])
depot_x = route_x[0]
depot_y = route_y[0]
plt.plot(route_x, route_y, marker='*', label=("v=" + str(vehicle)))
plt.plot(depot_x, depot_y, marker='s', color='black', markersize=10)
plt.legend()
plt.show()
| [
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((2294, 2362), 'matplotlib.pyplot.plot', 'plt.plot', (['depot_x', 'depot_y'], {'marker': '"""s"""', 'color': '"""black"""', 'markersize': '(10)'}), "(depot_x, depot_y, marker='s', color='black', markersize=10)\n", (2302, 2362), True, 'from matplotlib import pyplot as plt\n'), ((2366, 2378), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2376, 2378), True, 'from matplotlib import pyplot as plt\n'), ((2382, 2392), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2390, 2392), True, 'from matplotlib import pyplot as plt\n')] |
#!/usr/bin/env python3
"""
This Python script is designed to perform unit testing of Wordhoard's
Homophones module.
"""
__author__ = '<NAME>'
__date__ = 'September 20, 2020'
__status__ = 'Quality Assurance'
__license__ = 'MIT'
__copyright__ = "Copyright (C) 2021 <NAME>"
import unittest
from wordhoard import Homophones
class TestHomophoneFunction(unittest.TestCase):
def test_homophone_always_pass(self):
"""
This test is designed to pass, because the word "horse" has a known Homophones
and the default output format is a list
:return:
"""
self.assertIsInstance(Homophones('horse').find_homophones(), list)
def test_homophone_always_fail(self):
"""
This test is designed to fail, because the word "pig" has no known Homophones
:return:
"""
self.assertIsNone(Homophones('horse').find_homophones())
unittest.main()
| [
"unittest.main",
"wordhoard.Homophones"
] | [((904, 919), 'unittest.main', 'unittest.main', ([], {}), '()\n', (917, 919), False, 'import unittest\n'), ((622, 641), 'wordhoard.Homophones', 'Homophones', (['"""horse"""'], {}), "('horse')\n", (632, 641), False, 'from wordhoard import Homophones\n'), ((863, 882), 'wordhoard.Homophones', 'Homophones', (['"""horse"""'], {}), "('horse')\n", (873, 882), False, 'from wordhoard import Homophones\n')] |
from __future__ import annotations
from typing import Literal, TypedDict, Union, final
from typing_extensions import NotRequired
from .asset import AssetData
class YoutubeLinkEmbedMetadata(TypedDict):
type: Literal["YouTube"]
id: str
timestamp: NotRequired[str]
class TwitchLinkEmbedMetadata(TypedDict):
type: Literal["Twitch"]
content_type: Literal["Channel", "Clip", "Video"]
id: str
class SpotifyLinkEmbedMetadata(TypedDict):
type: Literal["Spotify"]
content_type: str
id: str
SoundcloudLinkEmbedMetadata = TypedDict(
"SoundcloudLinkEmbedMetadata", {"type": Literal["Soundcloud"]}
)
class BandcampLinkEmbedMetadata(TypedDict):
type: Literal["Bandcamp"]
content_type: Literal["Album", "Track"]
id: str
class EmbedMediaData(TypedDict):
# base fields that both videos and images sent in embeds will have.
url: str
width: int
height: int
class EmbedImageData(EmbedMediaData):
# this contains the data about an image sent in an embed
# for example: a banner image in a URL's embed
size: Literal["Large", "Preview"]
class WebsiteEmbedData(TypedDict):
"""Represents the data of an embed for a URL."""
type: Literal["Website"]
url: NotRequired[str]
special: NotRequired[
YoutubeLinkEmbedMetadata
| SpotifyLinkEmbedMetadata
| TwitchLinkEmbedMetadata
| SoundcloudLinkEmbedMetadata
| BandcampLinkEmbedMetadata
]
title: NotRequired[str]
description: NotRequired[str]
image: NotRequired[EmbedImageData]
video: NotRequired[EmbedMediaData]
site_name: NotRequired[str]
icon_url: NotRequired[str]
colour: NotRequired[str]
class ImageEmbedData(EmbedImageData):
"""Represents the data of an image embed."""
type: Literal["Image"]
class TextEmbedData(TypedDict):
type: Literal["Text"]
icon_url: NotRequired[str]
url: NotRequired[str]
title: NotRequired[str]
description: NotRequired[str]
media: NotRequired[AssetData]
colour: NotRequired[str]
NoneEmbed = TypedDict("NoneEmbed", {"type": Literal["None"]})
@final
class SystemMessageContent(TypedDict):
type: Literal["text"]
content: str
@final
class UserActionSystemMessageContent(TypedDict):
type: Literal[
"user_added",
"user_remove",
"user_joined",
"user_left",
"user_kicked",
"user_banned",
]
id: str
by: NotRequired[str] # sent only with user_added and user_remove
@final
class ChannelActionSystemMessageContent(TypedDict):
type: Literal[
"channel_renamed", "channel_description_changed", "channel_icon_changed"
]
by: str
name: NotRequired[str] # sent only with channel_renamed
MessageEditedData = TypedDict("MessageEditedData", {"$date": str})
class MasqueradeData(TypedDict):
name: NotRequired[str]
avatar: NotRequired[str]
EmbedType = Union[WebsiteEmbedData, ImageEmbedData, TextEmbedData, NoneEmbed]
class MessageData(TypedDict):
_id: str
nonce: NotRequired[str]
channel: str
author: str
content: (
SystemMessageContent
| UserActionSystemMessageContent
| ChannelActionSystemMessageContent
| str
)
attachments: NotRequired[list[AssetData]]
edited: NotRequired[MessageEditedData]
embeds: NotRequired[list[EmbedType]]
mentions: NotRequired[list[str]]
replies: NotRequired[list[str]]
masquerade: NotRequired[MasqueradeData]
| [
"typing.TypedDict"
] | [((557, 630), 'typing.TypedDict', 'TypedDict', (['"""SoundcloudLinkEmbedMetadata"""', "{'type': Literal['Soundcloud']}"], {}), "('SoundcloudLinkEmbedMetadata', {'type': Literal['Soundcloud']})\n", (566, 630), False, 'from typing import Literal, TypedDict, Union, final\n'), ((2069, 2118), 'typing.TypedDict', 'TypedDict', (['"""NoneEmbed"""', "{'type': Literal['None']}"], {}), "('NoneEmbed', {'type': Literal['None']})\n", (2078, 2118), False, 'from typing import Literal, TypedDict, Union, final\n'), ((2772, 2818), 'typing.TypedDict', 'TypedDict', (['"""MessageEditedData"""', "{'$date': str}"], {}), "('MessageEditedData', {'$date': str})\n", (2781, 2818), False, 'from typing import Literal, TypedDict, Union, final\n')] |
# from collections import deque
import numpy as np
import random
import torch
import pickle as pickle
from torch.autograd import Variable
class rpm(object):
# replay memory
def __init__(self, buffer_size):
self.buffer_size = buffer_size
self.buffer = []
self.priorities = []
self.index = 0
def append(self, obj):
if self.size() > self.buffer_size:
print('buffer size larger than set value, trimming...')
self.buffer = self.buffer[(self.size() - self.buffer_size):]
self.priorities = self.priorities[(self.size() - self.buffer_size):]
elif self.size() == self.buffer_size:
self.buffer[self.index] = obj
self.priorities[self.index] = max(self.priorities, default=1)
self.index += 1
self.index %= self.buffer_size
else:
self.buffer.append(obj)
self.priorities.append(max(self.priorities, default=1))
def size(self):
return len(self.buffer)
def get_probabilities(self, priority_scale):
# scaled_priorities = np.array(self.priorities)
# with torch.no_grad():
scaled_priorities_torch = Variable(torch.Tensor(self.priorities))**priority_scale
denom = torch.sum(scaled_priorities_torch)
sampled_probabilities = scaled_priorities_torch/denom
return sampled_probabilities
def get_importance(self, probabilities):
importance = 1/len(self.buffer) * 1/probabilities
importance_normalized = importance/max(importance)
return importance_normalized
def sample_batch(self, batch_size, device, only_state=False, priority_scale = 0.7):
if self.size() < batch_size:
MINIBATCH_SIZE = self.size()
# batch = random.sample(self.buffer, self.size())
else:
MINIBATCH_SIZE = batch_size
# batch = random.sample(self.buffer, batch_size)
sample_probs = self.get_probabilities(priority_scale)
# print(sample_probs)
sample_indices = random.choices(range(len(self.buffer)), k = MINIBATCH_SIZE, weights= sample_probs.tolist())
batch = [self.buffer[i] for i in sample_indices]
importance = self.get_importance(sample_probs[sample_indices])
if only_state:
res = torch.stack(tuple(item[3] for item in batch), dim=0)
return res.to(device)
else:
item_count = 5
res = []
for i in range(5):
k = torch.stack(tuple(item[i] for item in batch), dim=0)
res.append(k.to(device))
return res[0], res[1], res[2], res[3], res[4], importance, sample_indices
def set_priorities(self, indices, errors, offset=0.1):
errors = errors.tolist()
for i,e in zip(indices, errors):
self.priorities[i] = abs(e[0]) + offset
| [
"torch.sum",
"torch.Tensor"
] | [((1288, 1322), 'torch.sum', 'torch.sum', (['scaled_priorities_torch'], {}), '(scaled_priorities_torch)\n', (1297, 1322), False, 'import torch\n'), ((1225, 1254), 'torch.Tensor', 'torch.Tensor', (['self.priorities'], {}), '(self.priorities)\n', (1237, 1254), False, 'import torch\n')] |
from app import handler
from app import line_bot_api, handler
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage, ImageSendMessage
)
import random
import re
import urllib
def google_isch(q_string):
q_string= {'tbm': 'isch' , 'q' : q_string}
url = f"http://www.google.com/search?{urllib.parse.urlencode(q_string)}/"
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'
}
req = urllib.request.Request(url,headers=headers)
conn = urllib.request.urlopen(req)
data = conn.read()
pattern = '"(https://encrypted-tbn0.gstatic.com[\S]*)"'
image_list = []
for match in re.finditer(pattern, str(data, 'utf-8')):
image_list.append(match.group(1))
return image_list[2]
@handler.add(MessageEvent, message=TextMessage)
def reply_text(event):
if event.source.user_id != "FatTtyLoserfatfatFatTtyLoserfatty":
try:
image_url = google_isch(event.message.text)
message_text = image_url
line_bot_api.reply_message(
event.reply_token,
ImageSendMessage(
original_content_url = image_url,
preview_image_url = image_url
)
)
except:
message_text = '小丑,淘汰!'
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=message_text)
)
| [
"linebot.models.ImageSendMessage",
"urllib.request.Request",
"app.handler.add",
"urllib.parse.urlencode",
"linebot.models.TextSendMessage",
"urllib.request.urlopen"
] | [((836, 882), 'app.handler.add', 'handler.add', (['MessageEvent'], {'message': 'TextMessage'}), '(MessageEvent, message=TextMessage)\n', (847, 882), False, 'from app import line_bot_api, handler\n'), ((519, 563), 'urllib.request.Request', 'urllib.request.Request', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (541, 563), False, 'import urllib\n'), ((574, 601), 'urllib.request.urlopen', 'urllib.request.urlopen', (['req'], {}), '(req)\n', (596, 601), False, 'import urllib\n'), ((314, 346), 'urllib.parse.urlencode', 'urllib.parse.urlencode', (['q_string'], {}), '(q_string)\n', (336, 346), False, 'import urllib\n'), ((1173, 1250), 'linebot.models.ImageSendMessage', 'ImageSendMessage', ([], {'original_content_url': 'image_url', 'preview_image_url': 'image_url'}), '(original_content_url=image_url, preview_image_url=image_url)\n', (1189, 1250), False, 'from linebot.models import MessageEvent, TextMessage, TextSendMessage, ImageSendMessage\n'), ((1470, 1504), 'linebot.models.TextSendMessage', 'TextSendMessage', ([], {'text': 'message_text'}), '(text=message_text)\n', (1485, 1504), False, 'from linebot.models import MessageEvent, TextMessage, TextSendMessage, ImageSendMessage\n')] |
# -*- coding: utf-8 -*-
from flask import flash, make_response, request
import json
from flask_babel import lazy_gettext, gettext
from datetime import datetime
from flask_login import current_user
from flask_appbuilder.actions import action
from flask_appbuilder import expose
from flask import redirect
from plugins.common import AirflowModelView
from airflow.plugins_manager import AirflowPlugin
from airflow.settings import TIMEZONE
from airflow.www.decorators import action_logging
from flask_wtf.csrf import CSRFProtect
import logging
import os
import pandas as pd
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from flask import current_app
from wtforms.fields import StringField
from flask_appbuilder.fieldwidgets import (
BS3TextFieldWidget, Select2Widget,
)
from flask_appbuilder.forms import DynamicForm
from airflow.security import permissions
from airflow.www.widgets import AirflowModelListWidget
from qcos_addons.access_log.log import access_log
FACTORY_CODE = os.getenv('FACTORY_CODE', 'DEFAULT_FACTORY_CODE')
_logger = logging.getLogger(__name__)
csrf = CSRFProtect()
def device_type_query():
print(current_app)
session = current_app.appbuilder.get_session()
from plugins.models.device_type import DeviceTypeModel
return session.query(DeviceTypeModel)
def _get_related_pk_func(obj):
return obj.id
class TighteningControllerForm(DynamicForm):
controller_name = StringField(
lazy_gettext('Equipment Name'),
widget=BS3TextFieldWidget())
line_code = StringField(
lazy_gettext('Line Code'),
widget=BS3TextFieldWidget())
line_name = StringField(
lazy_gettext('Line Name'),
widget=BS3TextFieldWidget())
work_center_code = StringField(
lazy_gettext('Work Center Code'),
widget=BS3TextFieldWidget())
work_center_name = StringField(
lazy_gettext('Work Center Name'),
widget=BS3TextFieldWidget())
device_type = QuerySelectField(
lazy_gettext('Device Type'),
query_factory=device_type_query,
# get_pk_func=_get_related_pk_func,
widget=Select2Widget(extra_classes="readonly")
)
class TighteningControllerListWidget(AirflowModelListWidget):
template = 'tightening_controller_list_widget.html'
class TighteningControllerView(AirflowModelView):
route_base = '/tightening_controller'
list_widget = TighteningControllerListWidget
from plugins.models.tightening_controller import TighteningController
datamodel = AirflowModelView.CustomSQLAInterface(TighteningController)
extra_fields = []
list_columns = ['controller_name', 'line_code', 'line_name', 'work_center_code', 'work_center_name', 'device_type']
add_columns = edit_columns = ['controller_name', 'line_code', 'line_name', 'work_center_code',
'work_center_name', 'device_type'] + extra_fields
add_form = edit_form = TighteningControllerForm
add_template = 'tightening_controller_create.html'
edit_template = 'tightening_controller_edit.html'
list_template = 'tightening_controller_list.html'
label_columns = {
'controller_name': lazy_gettext('Controller Name'),
'line_code': lazy_gettext('Line Code'),
'line_name': lazy_gettext('Line Name'),
'work_center_code': lazy_gettext('Work Center Code'),
'work_center_name': lazy_gettext('Work Center Name'),
'device_type_id': lazy_gettext('Device Type'),
}
method_permission_name = {
'list': 'read',
'show': 'read',
'add': 'create',
'action_muldelete': 'delete',
'controllerimport': 'create',
'action_controllerexport': 'read'
}
class_permission_name = permissions.RESOURCE_CONTROLLER
base_permissions = [
permissions.ACTION_CAN_CREATE,
permissions.ACTION_CAN_READ,
permissions.ACTION_CAN_EDIT,
permissions.ACTION_CAN_DELETE,
permissions.ACTION_CAN_ACCESS_MENU
]
base_order = ('id', 'asc')
@access_log('ADD', 'TIGHTENING_CONTROLLER', '增加控制器')
def post_add(self, item):
super(TighteningControllerView, self).post_add(item)
@access_log('UPDATE', 'TIGHTENING_CONTROLLER', '修改控制器')
def post_update(self, item):
super(TighteningControllerView, self).post_update(item)
@access_log('DELETE', 'TIGHTENING_CONTROLLER', '删除控制器')
def post_delete(self, item):
super(TighteningControllerView, self).post_delete(item)
@action('muldelete', 'Delete', 'Are you sure you want to delete selected records?',
single=False)
@access_log('DELETE', 'TIGHTENING_CONTROLLER', '删除多个控制器')
def action_muldelete(self, items):
self.datamodel.delete_all(items)
self.update_redirect()
return redirect(self.get_redirect())
@expose('/controllerimport', methods=["POST"])
@action_logging
def controllerimport(self):
try:
d = pd.read_csv(request.files['file'])
if d.empty:
raise Exception('设备清单为空')
data = d.to_json(orient='records')
d = json.loads(data)
except Exception as e:
self.update_redirect()
flash(repr(e), 'error')
return redirect(self.get_redirect())
suc_count = fail_count = 0
controller: dict
for controller in d:
try:
from plugins.models.tightening_controller import TighteningController
TighteningController.add_controller(**controller)
except Exception as e:
logging.info('Controller import failed: {}'.format(repr(e)))
fail_count += 1
else:
suc_count += 1
flash("{} controller(s) successfully updated.".format(suc_count))
if fail_count:
flash("{} controller(s) failed to be updated.".format(fail_count), 'error')
self.update_redirect()
return redirect(self.get_redirect())
@action('controllerexport', 'Export', '', single=False)
def action_controllerexport(self, items):
ret = []
for controller in items:
try:
val = controller.as_dict()
except Exception as e:
val = str(controller)
ret.append(val)
d = pd.DataFrame.from_records(ret, index=[i for i in range(len(ret))])
response = make_response(d.to_csv(index=False))
response.headers["Content-Disposition"] = "attachment; filename=controllers.csv"
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response
@expose("/list/")
@access_log('VIEW', 'TIGHTENING_CONTROLLER', '查看控制器列表')
def list(self):
_has_access = self.appbuilder.sm.has_access
can_import = _has_access(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_CONTROLLER)
widgets = self._list()
return self.render_template(
self.list_template, title=self.list_title, widgets=widgets, can_import=can_import
)
class DeviceTypeView(AirflowModelView):
from plugins.models.device_type import DeviceTypeModel
datamodel = AirflowModelView.CustomSQLAInterface(DeviceTypeModel)
method_permission_name = {
'list': 'read',
'show': 'read',
'add': 'create',
}
class_permission_name = permissions.RESOURCE_DEVICE_TYPE
base_permissions = [
permissions.ACTION_CAN_CREATE,
permissions.ACTION_CAN_READ,
permissions.ACTION_CAN_EDIT,
permissions.ACTION_CAN_DELETE,
permissions.ACTION_CAN_ACCESS_MENU
]
tightening_controller_view = TighteningControllerView()
tightening_controller_package = {"name": permissions.RESOURCE_CONTROLLER,
"category": permissions.RESOURCE_MASTER_DATA_MANAGEMENT,
"view": tightening_controller_view}
device_type_view = DeviceTypeView()
device_type_package = {"name": permissions.RESOURCE_DEVICE_TYPE,
"category": permissions.RESOURCE_MASTER_DATA_MANAGEMENT,
"view": device_type_view}
class TighteningControllerViewPlugin(AirflowPlugin):
name = "tightening_controller_view"
appbuilder_views = [tightening_controller_package, device_type_package]
| [
"logging.getLogger",
"flask.current_app.appbuilder.get_session",
"json.loads",
"plugins.models.tightening_controller.TighteningController.add_controller",
"os.getenv",
"pandas.read_csv",
"flask_wtf.csrf.CSRFProtect",
"plugins.common.AirflowModelView.CustomSQLAInterface",
"flask_appbuilder.fieldwidge... | [((991, 1040), 'os.getenv', 'os.getenv', (['"""FACTORY_CODE"""', '"""DEFAULT_FACTORY_CODE"""'], {}), "('FACTORY_CODE', 'DEFAULT_FACTORY_CODE')\n", (1000, 1040), False, 'import os\n'), ((1052, 1079), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1069, 1079), False, 'import logging\n'), ((1087, 1100), 'flask_wtf.csrf.CSRFProtect', 'CSRFProtect', ([], {}), '()\n', (1098, 1100), False, 'from flask_wtf.csrf import CSRFProtect\n'), ((1165, 1201), 'flask.current_app.appbuilder.get_session', 'current_app.appbuilder.get_session', ([], {}), '()\n', (1199, 1201), False, 'from flask import current_app\n'), ((2518, 2576), 'plugins.common.AirflowModelView.CustomSQLAInterface', 'AirflowModelView.CustomSQLAInterface', (['TighteningController'], {}), '(TighteningController)\n', (2554, 2576), False, 'from plugins.common import AirflowModelView\n'), ((4036, 4087), 'qcos_addons.access_log.log.access_log', 'access_log', (['"""ADD"""', '"""TIGHTENING_CONTROLLER"""', '"""增加控制器"""'], {}), "('ADD', 'TIGHTENING_CONTROLLER', '增加控制器')\n", (4046, 4087), False, 'from qcos_addons.access_log.log import access_log\n'), ((4185, 4239), 'qcos_addons.access_log.log.access_log', 'access_log', (['"""UPDATE"""', '"""TIGHTENING_CONTROLLER"""', '"""修改控制器"""'], {}), "('UPDATE', 'TIGHTENING_CONTROLLER', '修改控制器')\n", (4195, 4239), False, 'from qcos_addons.access_log.log import access_log\n'), ((4343, 4397), 'qcos_addons.access_log.log.access_log', 'access_log', (['"""DELETE"""', '"""TIGHTENING_CONTROLLER"""', '"""删除控制器"""'], {}), "('DELETE', 'TIGHTENING_CONTROLLER', '删除控制器')\n", (4353, 4397), False, 'from qcos_addons.access_log.log import access_log\n'), ((4501, 4601), 'flask_appbuilder.actions.action', 'action', (['"""muldelete"""', '"""Delete"""', '"""Are you sure you want to delete selected records?"""'], {'single': '(False)'}), "('muldelete', 'Delete',\n 'Are you sure you want to delete selected records?', single=False)\n", (4507, 4601), False, 'from flask_appbuilder.actions import action\n'), ((4615, 4671), 'qcos_addons.access_log.log.access_log', 'access_log', (['"""DELETE"""', '"""TIGHTENING_CONTROLLER"""', '"""删除多个控制器"""'], {}), "('DELETE', 'TIGHTENING_CONTROLLER', '删除多个控制器')\n", (4625, 4671), False, 'from qcos_addons.access_log.log import access_log\n'), ((4834, 4879), 'flask_appbuilder.expose', 'expose', (['"""/controllerimport"""'], {'methods': "['POST']"}), "('/controllerimport', methods=['POST'])\n", (4840, 4879), False, 'from flask_appbuilder import expose\n'), ((6011, 6065), 'flask_appbuilder.actions.action', 'action', (['"""controllerexport"""', '"""Export"""', '""""""'], {'single': '(False)'}), "('controllerexport', 'Export', '', single=False)\n", (6017, 6065), False, 'from flask_appbuilder.actions import action\n'), ((6654, 6670), 'flask_appbuilder.expose', 'expose', (['"""/list/"""'], {}), "('/list/')\n", (6660, 6670), False, 'from flask_appbuilder import expose\n'), ((6676, 6730), 'qcos_addons.access_log.log.access_log', 'access_log', (['"""VIEW"""', '"""TIGHTENING_CONTROLLER"""', '"""查看控制器列表"""'], {}), "('VIEW', 'TIGHTENING_CONTROLLER', '查看控制器列表')\n", (6686, 6730), False, 'from qcos_addons.access_log.log import access_log\n'), ((7189, 7242), 'plugins.common.AirflowModelView.CustomSQLAInterface', 'AirflowModelView.CustomSQLAInterface', (['DeviceTypeModel'], {}), '(DeviceTypeModel)\n', (7225, 7242), False, 'from plugins.common import AirflowModelView\n'), ((1444, 1474), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Equipment Name"""'], {}), "('Equipment Name')\n", (1456, 1474), False, 'from flask_babel import lazy_gettext, gettext\n'), ((1550, 1575), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Line Code"""'], {}), "('Line Code')\n", (1562, 1575), False, 'from flask_babel import lazy_gettext, gettext\n'), ((1651, 1676), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Line Name"""'], {}), "('Line Name')\n", (1663, 1676), False, 'from flask_babel import lazy_gettext, gettext\n'), ((1759, 1791), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Work Center Code"""'], {}), "('Work Center Code')\n", (1771, 1791), False, 'from flask_babel import lazy_gettext, gettext\n'), ((1874, 1906), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Work Center Name"""'], {}), "('Work Center Name')\n", (1886, 1906), False, 'from flask_babel import lazy_gettext, gettext\n'), ((1990, 2017), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Device Type"""'], {}), "('Device Type')\n", (2002, 2017), False, 'from flask_babel import lazy_gettext, gettext\n'), ((3167, 3198), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Controller Name"""'], {}), "('Controller Name')\n", (3179, 3198), False, 'from flask_babel import lazy_gettext, gettext\n'), ((3221, 3246), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Line Code"""'], {}), "('Line Code')\n", (3233, 3246), False, 'from flask_babel import lazy_gettext, gettext\n'), ((3269, 3294), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Line Name"""'], {}), "('Line Name')\n", (3281, 3294), False, 'from flask_babel import lazy_gettext, gettext\n'), ((3324, 3356), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Work Center Code"""'], {}), "('Work Center Code')\n", (3336, 3356), False, 'from flask_babel import lazy_gettext, gettext\n'), ((3386, 3418), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Work Center Name"""'], {}), "('Work Center Name')\n", (3398, 3418), False, 'from flask_babel import lazy_gettext, gettext\n'), ((3446, 3473), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""Device Type"""'], {}), "('Device Type')\n", (3458, 3473), False, 'from flask_babel import lazy_gettext, gettext\n'), ((1491, 1511), 'flask_appbuilder.fieldwidgets.BS3TextFieldWidget', 'BS3TextFieldWidget', ([], {}), '()\n', (1509, 1511), False, 'from flask_appbuilder.fieldwidgets import BS3TextFieldWidget, Select2Widget\n'), ((1592, 1612), 'flask_appbuilder.fieldwidgets.BS3TextFieldWidget', 'BS3TextFieldWidget', ([], {}), '()\n', (1610, 1612), False, 'from flask_appbuilder.fieldwidgets import BS3TextFieldWidget, Select2Widget\n'), ((1693, 1713), 'flask_appbuilder.fieldwidgets.BS3TextFieldWidget', 'BS3TextFieldWidget', ([], {}), '()\n', (1711, 1713), False, 'from flask_appbuilder.fieldwidgets import BS3TextFieldWidget, Select2Widget\n'), ((1808, 1828), 'flask_appbuilder.fieldwidgets.BS3TextFieldWidget', 'BS3TextFieldWidget', ([], {}), '()\n', (1826, 1828), False, 'from flask_appbuilder.fieldwidgets import BS3TextFieldWidget, Select2Widget\n'), ((1923, 1943), 'flask_appbuilder.fieldwidgets.BS3TextFieldWidget', 'BS3TextFieldWidget', ([], {}), '()\n', (1941, 1943), False, 'from flask_appbuilder.fieldwidgets import BS3TextFieldWidget, Select2Widget\n'), ((2119, 2158), 'flask_appbuilder.fieldwidgets.Select2Widget', 'Select2Widget', ([], {'extra_classes': '"""readonly"""'}), "(extra_classes='readonly')\n", (2132, 2158), False, 'from flask_appbuilder.fieldwidgets import BS3TextFieldWidget, Select2Widget\n'), ((4961, 4995), 'pandas.read_csv', 'pd.read_csv', (["request.files['file']"], {}), "(request.files['file'])\n", (4972, 4995), True, 'import pandas as pd\n'), ((5125, 5141), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (5135, 5141), False, 'import json\n'), ((5501, 5550), 'plugins.models.tightening_controller.TighteningController.add_controller', 'TighteningController.add_controller', ([], {}), '(**controller)\n', (5536, 5550), False, 'from plugins.models.tightening_controller import TighteningController\n')] |
import requests
import json
from pprint import pprint
from pymongo import MongoClient
def get_vparis():
url = "https://opendata.paris.fr/api/records/1.0/search/?dataset=velib-disponibilite-en-temps-reel&q=&rows" \
"=251&facet=name&facet=is_installed&facet=is_renting&facet=is_returning&facet=nom_arrondissement_communes"
response = requests.request("GET", url)
response_json = json.loads(response.text.encode('utf8'))
return response_json.get("records", [])
v_paris = get_vparis()
v_paris_to_insert = [
{
'name': elem.get('fields', {}).get('name', '').title(),
'geometry': elem.get('geometry'),
'size': elem.get('fields', {}).get('capacity'),
'source': {
'dataset': 'Paris',
'id_ext': elem.get('fields', {}).get('stationcode')
},
'tpe': elem.get('fields', {}).get('is_renting', '') == 'OUI'
}
for elem in v_paris
]
atlas = MongoClient('mongodb+srv://main:1963<EMAIL>/vlille?retryWrites=true&w=majori'
'ty')
db = atlas.paris_bicycle
for ve_paris in v_paris_to_insert:
db.stations.insert_one(ve_paris) | [
"pymongo.MongoClient",
"requests.request"
] | [((940, 1025), 'pymongo.MongoClient', 'MongoClient', (['"""mongodb+srv://main:1963<EMAIL>/vlille?retryWrites=true&w=majority"""'], {}), "('mongodb+srv://main:1963<EMAIL>/vlille?retryWrites=true&w=majority'\n )\n", (951, 1025), False, 'from pymongo import MongoClient\n'), ((353, 381), 'requests.request', 'requests.request', (['"""GET"""', 'url'], {}), "('GET', url)\n", (369, 381), False, 'import requests\n')] |
#from twython import Twython
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
import json
CONSUMER_KEY = 'pxeqo0ylpUayIIl5Nlc2kBmkb'
CONSUMER_SECRET = '<KEY>'
ACCESS_TOKEN = '<KEY>'
ACCESS_SECRET = '<KEY>'
oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
# Initiate the connection to Twitter REST API
twitter = Twitter(auth=oauth)
# Search for latest tweets about "#nlproc"
twitter.search.tweets(q='#nlproc')
#twitter.search.tweets(q='#nlproc', result_type='recent', lang='en', count=10)
| [
"twitter.OAuth",
"twitter.Twitter"
] | [((236, 301), 'twitter.OAuth', 'OAuth', (['ACCESS_TOKEN', 'ACCESS_SECRET', 'CONSUMER_KEY', 'CONSUMER_SECRET'], {}), '(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)\n', (241, 301), False, 'from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream\n'), ((359, 378), 'twitter.Twitter', 'Twitter', ([], {'auth': 'oauth'}), '(auth=oauth)\n', (366, 378), False, 'from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream\n')] |
# -*- coding: utf-8 -*-
from app.data.DataManager import DataManager
from app.model.Simulator import Simulator
from app.data.Client import Driver
from app.tools.Logger import logger_sensitivity as logger
from app.model.ScenarioGenerator import ScenarioGeneratorFactory as SGF
from app.config.env import ScenarioGeneratorType, PipelineLayer
class RiskEngine:
"""
Risk sensitivity class
"""
def __init__(self):
"""
ctor
"""
self.dm = DataManager()
self.dm.load_data()
def compute_delta(self, scenario, shocks, with_logistics=False):
# base scenario
simulator = Simulator(dm=self.dm, monikers_filter=sum(scenario, []))
scenarios = [
simulator.nodes[layer] for layer in [
PipelineLayer.PAP, PipelineLayer.SAP,
PipelineLayer.BENEFICIATION, PipelineLayer.MINE, PipelineLayer.MINE_BENEFICIATION
] if layer in simulator.nodes
]
scenario_generator = SGF.create_scenario_generator(ScenarioGeneratorType.SPECIFIC_SCENARIOS, simulator,
[scenarios])
result_no_bump, _ = simulator.simulate(scenario_generator=scenario_generator, logistics_lp=with_logistics)
logger.info("Base: %f" % result_no_bump[1]["Cost PV"])
# bump data
result_with_bump = {}
raw_materials_df = Driver().get_data("raw_materials")
for raw_material in raw_materials_df:
item = raw_material["Item"]
if item not in shocks:
continue
unit = raw_material["Unit"]
currency = unit.split("/")[0]
# bump
self.dm.bump_raw_materials({item: shocks[item]})
bumped_simulator = Simulator(dm=self.dm, monikers_filter=sum(scenario, []))
bumped_scenarios = [
bumped_simulator.nodes[layer] for layer in [
PipelineLayer.PAP, PipelineLayer.SAP,
PipelineLayer.BENEFICIATION, PipelineLayer.MINE, PipelineLayer.MINE_BENEFICIATION
] if layer in bumped_simulator.nodes
]
scenario_generator = SGF.create_scenario_generator(ScenarioGeneratorType.SPECIFIC_SCENARIOS, bumped_simulator,
[bumped_scenarios])
result_with_bump[item], _ = bumped_simulator.simulate(scenario_generator=scenario_generator)
logger.info("Shock %s by %s%f: %f" % (item, currency, shocks[item], result_with_bump[item][1]["Cost PV"]))
# reset
self.dm.bump_raw_materials({item: -shocks[item]})
# deltas
base_price = result_no_bump[1]["Cost PV"]
deltas = {}
for item in result_with_bump:
deltas[item] = result_with_bump[item][1]["Cost PV"] - base_price
return deltas
| [
"app.tools.Logger.logger_sensitivity.info",
"app.model.ScenarioGenerator.ScenarioGeneratorFactory.create_scenario_generator",
"app.data.Client.Driver",
"app.data.DataManager.DataManager"
] | [((485, 498), 'app.data.DataManager.DataManager', 'DataManager', ([], {}), '()\n', (496, 498), False, 'from app.data.DataManager import DataManager\n'), ((1003, 1102), 'app.model.ScenarioGenerator.ScenarioGeneratorFactory.create_scenario_generator', 'SGF.create_scenario_generator', (['ScenarioGeneratorType.SPECIFIC_SCENARIOS', 'simulator', '[scenarios]'], {}), '(ScenarioGeneratorType.SPECIFIC_SCENARIOS,\n simulator, [scenarios])\n', (1032, 1102), True, 'from app.model.ScenarioGenerator import ScenarioGeneratorFactory as SGF\n'), ((1281, 1335), 'app.tools.Logger.logger_sensitivity.info', 'logger.info', (["('Base: %f' % result_no_bump[1]['Cost PV'])"], {}), "('Base: %f' % result_no_bump[1]['Cost PV'])\n", (1292, 1335), True, 'from app.tools.Logger import logger_sensitivity as logger\n'), ((2199, 2312), 'app.model.ScenarioGenerator.ScenarioGeneratorFactory.create_scenario_generator', 'SGF.create_scenario_generator', (['ScenarioGeneratorType.SPECIFIC_SCENARIOS', 'bumped_simulator', '[bumped_scenarios]'], {}), '(ScenarioGeneratorType.SPECIFIC_SCENARIOS,\n bumped_simulator, [bumped_scenarios])\n', (2228, 2312), True, 'from app.model.ScenarioGenerator import ScenarioGeneratorFactory as SGF\n'), ((2489, 2599), 'app.tools.Logger.logger_sensitivity.info', 'logger.info', (["('Shock %s by %s%f: %f' % (item, currency, shocks[item], result_with_bump[\n item][1]['Cost PV']))"], {}), "('Shock %s by %s%f: %f' % (item, currency, shocks[item],\n result_with_bump[item][1]['Cost PV']))\n", (2500, 2599), True, 'from app.tools.Logger import logger_sensitivity as logger\n'), ((1414, 1422), 'app.data.Client.Driver', 'Driver', ([], {}), '()\n', (1420, 1422), False, 'from app.data.Client import Driver\n')] |
from unittest import TestCase
from click.testing import CliRunner, Result
from poeditor_sync.cmd import poeditor
class CmdReadOnlyTokenTest(TestCase):
def setUp(self) -> None:
super().setUp()
self.runner = CliRunner(env={
'POEDITOR_CONFIG_FILE': 'tests/test.yml',
'POEDITOR_TOKEN': 'e1fc095d70eba2395fec56c6ad9e61c3',
})
def test_poeditor(self):
result: Result = self.runner.invoke(poeditor)
self.assertEqual(result.exit_code, 0)
self.assertTrue(result.stdout.startswith('Usage: poeditor'))
def test_poeditor_pull(self):
result: Result = self.runner.invoke(poeditor, ['pull'])
self.assertEqual(result.exit_code, 0, result.stdout)
def test_poeditor_push(self):
result: Result = self.runner.invoke(poeditor, 'push')
self.assertEqual(result.exit_code, 1)
def test_poeditor_push_terms(self):
result: Result = self.runner.invoke(poeditor, 'push')
self.assertEqual(result.exit_code, 1)
def test_poeditor_init_blank(self):
result: Result = self.runner.invoke(poeditor, args=['--config-file', 'test_blank_init.yml', 'init'])
self.assertEqual(result.exit_code, 0, result.stdout)
def test_poeditor_init_project_id(self):
result: Result = self.runner.invoke(poeditor, args=['--config-file', 'test_init_projectid.yml', 'init', '458528'])
self.assertEqual(result.exit_code, 0, result.stdout)
| [
"click.testing.CliRunner"
] | [((230, 345), 'click.testing.CliRunner', 'CliRunner', ([], {'env': "{'POEDITOR_CONFIG_FILE': 'tests/test.yml', 'POEDITOR_TOKEN':\n 'e1fc095d70eba2395fec56c6ad9e61c3'}"}), "(env={'POEDITOR_CONFIG_FILE': 'tests/test.yml', 'POEDITOR_TOKEN':\n 'e1fc095d70eba2395fec56c6ad9e61c3'})\n", (239, 345), False, 'from click.testing import CliRunner, Result\n')] |
import numpy as np
import cv2
import proper
from cats.cats_simus import *
def vortex(wfo, CAL, charge, f_lens, path, Debug_print):
n = int(proper.prop_get_gridsize(wfo))
ofst = 0 # no offset
ramp_sign = 1 #sign of charge is positive
#sampling = n
ramp_oversamp = 11. # vortex is oversampled for a better discretization
if charge!=0:
if CAL==1: # create the vortex for a perfectly circular pupil
if (Debug_print == True):
print ("CAL:1, charge ", charge)
writefield(path,'zz_psf', wfo.wfarr) # write the pre-vortex field
nramp = int(n*ramp_oversamp) #oversamp
# create the vortex by creating a matrix (theta) representing the ramp (created by atan 2 gradually varying matrix, x and y)
y1 = np.ones((nramp,), dtype=np.int)
y2 = np.arange(0, nramp, 1.) - (nramp/2) - int(ramp_oversamp)/2
y = np.outer(y2, y1)
x = np.transpose(y)
theta = np.arctan2(y,x)
x = 0
y = 0
#vvc_tmp_complex = np.array(np.zeros((nramp,nramp)), dtype=complex)
#vvc_tmp_complex.imag = ofst + ramp_sign*charge*theta
#vvc_tmp = np.exp(vvc_tmp_complex)
vvc_tmp = np.exp(1j*(ofst + ramp_sign*charge*theta))
theta = 0
vvc_real_resampled = cv2.resize(vvc_tmp.real, (0,0), fx=1/ramp_oversamp, fy=1/ramp_oversamp, interpolation=cv2.INTER_LINEAR) # scale the pupil to the pupil size of the simualtions
vvc_imag_resampled = cv2.resize(vvc_tmp.imag, (0,0), fx=1/ramp_oversamp, fy=1/ramp_oversamp, interpolation=cv2.INTER_LINEAR) # scale the pupil to the pupil size of the simualtions
vvc = np.array(vvc_real_resampled, dtype=complex)
vvc.imag = vvc_imag_resampled
vvcphase = np.arctan2(vvc.imag, vvc.real) # create the vortex phase
vvc_complex = np.array(np.zeros((n,n)), dtype=complex)
vvc_complex.imag = vvcphase
vvc = np.exp(vvc_complex)
vvc_tmp = 0.
writefield(path,'zz_vvc', vvc) # write the theoretical vortex field
wfo0 = wfo
proper.prop_multiply(wfo, vvc)
proper.prop_propagate(wfo, f_lens, 'OAP2')
proper.prop_lens(wfo, f_lens)
proper.prop_propagate(wfo, f_lens, 'forward to Lyot Stop')
proper.prop_circular_obscuration(wfo, 1., NORM=True) # null the amplitude iside the Lyot Stop
proper.prop_propagate(wfo, -f_lens) # back-propagation
proper.prop_lens(wfo, -f_lens)
proper.prop_propagate(wfo, -f_lens)
writefield(path,'zz_perf', wfo.wfarr) # write the perfect-result vortex field
wfo = wfo0
else:
if (Debug_print == True):
print ("CAL:0, charge ", charge)
vvc = readfield(path,'zz_vvc') # read the theoretical vortex field
vvc = proper.prop_shift_center(vvc)
scale_psf = wfo._wfarr[0,0]
psf_num = readfield(path,'zz_psf') # read the pre-vortex field
psf0 = psf_num[0,0]
psf_num = psf_num/psf0*scale_psf
perf_num = readfield(path,'zz_perf') # read the perfect-result vortex field
perf_num = perf_num/psf0*scale_psf
wfo._wfarr = (wfo._wfarr - psf_num)*vvc + perf_num # the wavefront takes into account the real pupil with the perfect-result vortex field
return
| [
"proper.prop_circular_obscuration",
"numpy.ones",
"proper.prop_lens",
"proper.prop_get_gridsize",
"proper.prop_multiply",
"proper.prop_shift_center",
"numpy.exp",
"numpy.array",
"numpy.zeros",
"numpy.outer",
"numpy.arctan2",
"proper.prop_propagate",
"cv2.resize",
"numpy.transpose",
"nump... | [((146, 175), 'proper.prop_get_gridsize', 'proper.prop_get_gridsize', (['wfo'], {}), '(wfo)\n', (170, 175), False, 'import proper\n'), ((801, 832), 'numpy.ones', 'np.ones', (['(nramp,)'], {'dtype': 'np.int'}), '((nramp,), dtype=np.int)\n', (808, 832), True, 'import numpy as np\n'), ((925, 941), 'numpy.outer', 'np.outer', (['y2', 'y1'], {}), '(y2, y1)\n', (933, 941), True, 'import numpy as np\n'), ((958, 973), 'numpy.transpose', 'np.transpose', (['y'], {}), '(y)\n', (970, 973), True, 'import numpy as np\n'), ((994, 1010), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (1004, 1010), True, 'import numpy as np\n'), ((1261, 1311), 'numpy.exp', 'np.exp', (['(1.0j * (ofst + ramp_sign * charge * theta))'], {}), '(1.0j * (ofst + ramp_sign * charge * theta))\n', (1267, 1311), True, 'import numpy as np\n'), ((1359, 1471), 'cv2.resize', 'cv2.resize', (['vvc_tmp.real', '(0, 0)'], {'fx': '(1 / ramp_oversamp)', 'fy': '(1 / ramp_oversamp)', 'interpolation': 'cv2.INTER_LINEAR'}), '(vvc_tmp.real, (0, 0), fx=1 / ramp_oversamp, fy=1 / ramp_oversamp,\n interpolation=cv2.INTER_LINEAR)\n', (1369, 1471), False, 'import cv2\n'), ((1551, 1663), 'cv2.resize', 'cv2.resize', (['vvc_tmp.imag', '(0, 0)'], {'fx': '(1 / ramp_oversamp)', 'fy': '(1 / ramp_oversamp)', 'interpolation': 'cv2.INTER_LINEAR'}), '(vvc_tmp.imag, (0, 0), fx=1 / ramp_oversamp, fy=1 / ramp_oversamp,\n interpolation=cv2.INTER_LINEAR)\n', (1561, 1663), False, 'import cv2\n'), ((1728, 1771), 'numpy.array', 'np.array', (['vvc_real_resampled'], {'dtype': 'complex'}), '(vvc_real_resampled, dtype=complex)\n', (1736, 1771), True, 'import numpy as np\n'), ((1837, 1867), 'numpy.arctan2', 'np.arctan2', (['vvc.imag', 'vvc.real'], {}), '(vvc.imag, vvc.real)\n', (1847, 1867), True, 'import numpy as np\n'), ((2019, 2038), 'numpy.exp', 'np.exp', (['vvc_complex'], {}), '(vvc_complex)\n', (2025, 2038), True, 'import numpy as np\n'), ((2179, 2209), 'proper.prop_multiply', 'proper.prop_multiply', (['wfo', 'vvc'], {}), '(wfo, vvc)\n', (2199, 2209), False, 'import proper\n'), ((2222, 2264), 'proper.prop_propagate', 'proper.prop_propagate', (['wfo', 'f_lens', '"""OAP2"""'], {}), "(wfo, f_lens, 'OAP2')\n", (2243, 2264), False, 'import proper\n'), ((2277, 2306), 'proper.prop_lens', 'proper.prop_lens', (['wfo', 'f_lens'], {}), '(wfo, f_lens)\n', (2293, 2306), False, 'import proper\n'), ((2319, 2377), 'proper.prop_propagate', 'proper.prop_propagate', (['wfo', 'f_lens', '"""forward to Lyot Stop"""'], {}), "(wfo, f_lens, 'forward to Lyot Stop')\n", (2340, 2377), False, 'import proper\n'), ((2390, 2443), 'proper.prop_circular_obscuration', 'proper.prop_circular_obscuration', (['wfo', '(1.0)'], {'NORM': '(True)'}), '(wfo, 1.0, NORM=True)\n', (2422, 2443), False, 'import proper\n'), ((2496, 2531), 'proper.prop_propagate', 'proper.prop_propagate', (['wfo', '(-f_lens)'], {}), '(wfo, -f_lens)\n', (2517, 2531), False, 'import proper\n'), ((2563, 2593), 'proper.prop_lens', 'proper.prop_lens', (['wfo', '(-f_lens)'], {}), '(wfo, -f_lens)\n', (2579, 2593), False, 'import proper\n'), ((2606, 2641), 'proper.prop_propagate', 'proper.prop_propagate', (['wfo', '(-f_lens)'], {}), '(wfo, -f_lens)\n', (2627, 2641), False, 'import proper\n'), ((2953, 2982), 'proper.prop_shift_center', 'proper.prop_shift_center', (['vvc'], {}), '(vvc)\n', (2977, 2982), False, 'import proper\n'), ((1929, 1945), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (1937, 1945), True, 'import numpy as np\n'), ((850, 874), 'numpy.arange', 'np.arange', (['(0)', 'nramp', '(1.0)'], {}), '(0, nramp, 1.0)\n', (859, 874), True, 'import numpy as np\n')] |
import turtle
screen = turtle.Screen()
# this assures that the size of the screen will always be 400x400 ...
screen.setup(400, 400)
# ... which is the same size as our image
# now set the background to our space image
screen.bgpic("game.over")
turtle.mainloop()
| [
"turtle.mainloop",
"turtle.Screen"
] | [((24, 39), 'turtle.Screen', 'turtle.Screen', ([], {}), '()\n', (37, 39), False, 'import turtle\n'), ((248, 265), 'turtle.mainloop', 'turtle.mainloop', ([], {}), '()\n', (263, 265), False, 'import turtle\n')] |
#!/usr/bin/env python3
from cryptofeed import FeedHandler
from cryptofeed.defines import TRADES
from cryptoblotter.exchanges import CoinbaseBlotter
from cryptoblotter.trades import SequentialIntegerTradeCallback, ThreshCallback
from cryptoblotter.trades.constants import VOLUME
async def trades(trade):
print(trade)
if __name__ == "__main__":
fh = FeedHandler()
fh.add_feed(
CoinbaseBlotter(
symbols=["BTC-USD"],
channels=[TRADES],
callbacks={
TRADES: SequentialIntegerTradeCallback(
ThreshCallback(
trades,
thresh_attr=VOLUME,
thresh_value=1000,
window_seconds=60,
)
)
},
)
)
fh.run()
| [
"cryptofeed.FeedHandler",
"cryptoblotter.trades.ThreshCallback"
] | [((362, 375), 'cryptofeed.FeedHandler', 'FeedHandler', ([], {}), '()\n', (373, 375), False, 'from cryptofeed import FeedHandler\n'), ((582, 667), 'cryptoblotter.trades.ThreshCallback', 'ThreshCallback', (['trades'], {'thresh_attr': 'VOLUME', 'thresh_value': '(1000)', 'window_seconds': '(60)'}), '(trades, thresh_attr=VOLUME, thresh_value=1000, window_seconds=60\n )\n', (596, 667), False, 'from cryptoblotter.trades import SequentialIntegerTradeCallback, ThreshCallback\n')] |
#!/usr/bin/env python
from setuptools import find_packages, setup
with open("README.md", "r", encoding="utf-8") as f:
long_description = f.read()
setup(
name="tplink-wr-api",
version="0.2.1",
url="https://github.com/n1k0r/tplink-wr-api",
author="n1k0r",
author_email="<EMAIL>",
description="API to some budget TP-Link routers",
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT",
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Intended Audience :: Telecommunications Industry",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Topic :: Communications",
"Topic :: Software Development :: Libraries",
"Topic :: System :: Networking",
],
packages=find_packages(exclude=["tests", "tests.*"]),
python_requires=">=3.8",
install_requires=[
"requests~=2.26",
],
)
| [
"setuptools.find_packages"
] | [((1123, 1166), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests', 'tests.*']"}), "(exclude=['tests', 'tests.*'])\n", (1136, 1166), False, 'from setuptools import find_packages, setup\n')] |
"""The module contains functions to preprocess input
datasets into usable format."""
import gc
import gzip
import json
import logging
import multiprocessing as mp
import pathlib
import sys
from itertools import repeat
import numpy as np
import scipy.sparse as smat
logging.basicConfig(
stream=sys.stdout,
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
_FUNC = None # place holder to Pool functions.
def _worker_init(func):
"init method to invoke Pool."
global _FUNC
_FUNC = func
def _worker(x):
"init function to invoke pool"
return _FUNC(x)
def open_file_helper(filename, compressed, mode="rt"):
"""
Supports reading of gzip compressed or uncompressed file.
Parameters:
----------
filename : str
Name of the file to open.
compressed : bool
If true, treat filename as gzip compressed.
mode : str
Reading mode.
Returns:
--------
file handle to the opened file.
"""
return gzip.open(filename, mode=mode) if compressed else open(filename, mode)
def _get_unique_rows_cols(filename, compressed, delim="<@@>"):
"""Function to load a json file in the format of processed session-data
for qp2q. Then it returns dictionary of query<delim>prefix as r2i and next_query
as c2i.
"""
r2i = {}
c2i = {}
logger.info("Processing file for rows and columns: {}".format(filename))
with open_file_helper(filename, compressed) as fp:
for line in fp:
try:
pline = json.loads(line)
except json.decoder.JSONDecodeError:
logger.warn(f"Failed to parse: {line}")
continue
query_prefix = delim.join([pline["prev_query"], pline["prefix"]])
kw = pline["next_query"]
if query_prefix not in r2i:
r2i[query_prefix] = 1
if kw not in c2i:
c2i[kw] = 1
return r2i, c2i
def _transform_file_to_matrix_qp2q(filename, compressed, delim, g_r2i, g_c2i):
"""
Helper Function to extract qp2q matrix from input_file which was generated
as a output of the function parallel_process_session_data_qp2p.
Parameters:
----------
input_file: filename
full filepath of input dataframe
compressed: bool
compressed or not
delim: str
delim separating query and prefix
g_r2i: dictionary
mapping for input items
g_c2i: dictionary
mapping of output item
Returns:
-------
qp2q count matrix
"""
rows = []
cols = []
data = []
logger.info("Processing file for matrix: {}".format(filename))
with open_file_helper(filename, compressed) as fp:
for line in fp:
try:
pline = json.loads(line)
except json.decoder.JSONDecodeError:
logger.warn(f"Failed to parse: {line}")
continue
query_prefix = delim.join([pline["prev_query"], pline["prefix"]])
kw = pline["next_query"]
freq = 1
data.append(freq)
rows.append(g_r2i[query_prefix])
cols.append(g_c2i[kw])
matrix = smat.coo_matrix((data, (rows, cols)), shape=(len(g_r2i), len(g_c2i)), dtype=np.float32)
return matrix
def parallel_get_qp2q_sparse_data(fdir, compressed, delim="<@@>", n_jobs=4):
"""Process session data to sparse matrix and dictionaries mapping rows and columns.
Parameters:
----------
fdir: str
path to directory having all the files in json format
compressed: bool
files being compressed or not
delim: str
delimiter between query and prefix
n_jobs: int
number of threads to be used
Returns:
-------
dictionary mapping row index to row names
dictionary mapping col index to col names
qp2q sparse csr matrix containing freq. of occurences.
"""
if compressed:
extension = "*.gz"
else:
extension = "*.json"
if pathlib.Path(fdir).is_dir():
files = pathlib.Path(fdir).glob(extension)
else:
raise ValueError(f"{fdir} is not a valid directory")
files = [str(f) for f in files]
logger.info("Getting qp2q unique rows and columns from files in {}".format(fdir))
if n_jobs > 1:
with mp.Pool(processes=n_jobs) as pool:
dicts = pool.starmap(
_get_unique_rows_cols,
zip(files, repeat(compressed), repeat(delim)),
)
else:
dicts = [_get_unique_rows_cols(file, compressed, delim) for file in files]
g_r2i = {}
g_c2i = {}
for dic in dicts:
g_r2i.update(dic[0])
g_c2i.update(dic[1])
g_i2r = {}
g_i2c = {}
for i, k in enumerate(g_r2i.keys()):
g_r2i[k] = i
g_i2r[i] = k
for i, k in enumerate(g_c2i.keys()):
g_c2i[k] = i
g_i2c[i] = k
del dicts
gc.collect()
logger.info("Number of unique rows: {}".format(len(g_r2i)))
logger.info("Number of unique cols: {}".format(len(g_c2i)))
if n_jobs > 1:
with mp.Pool(
processes=n_jobs,
initializer=_worker_init,
initargs=(
lambda x: _transform_file_to_matrix_qp2q(x, compressed, delim, g_r2i, g_c2i),
),
) as pool:
matrices = pool.map(_worker, files)
else:
matrices = [
_transform_file_to_matrix_qp2q(x, compressed, delim, g_r2i, g_c2i) for x in files
]
matrices = [m.tocsr() for m in matrices]
qp2q_matrix = matrices[0]
for i in range(1, len(matrices)):
qp2q_matrix += matrices[i]
del matrices
gc.collect()
return g_i2r, g_i2c, qp2q_matrix
| [
"logging.basicConfig",
"logging.getLogger",
"json.loads",
"pathlib.Path",
"gzip.open",
"multiprocessing.Pool",
"gc.collect",
"itertools.repeat"
] | [((266, 426), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'format': '"""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""', 'datefmt': '"""%m/%d/%Y %H:%M:%S"""', 'level': 'logging.INFO'}), "(stream=sys.stdout, format=\n '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt=\n '%m/%d/%Y %H:%M:%S', level=logging.INFO)\n", (285, 426), False, 'import logging\n'), ((446, 473), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (463, 473), False, 'import logging\n'), ((5030, 5042), 'gc.collect', 'gc.collect', ([], {}), '()\n', (5040, 5042), False, 'import gc\n'), ((5784, 5796), 'gc.collect', 'gc.collect', ([], {}), '()\n', (5794, 5796), False, 'import gc\n'), ((1095, 1125), 'gzip.open', 'gzip.open', (['filename'], {'mode': 'mode'}), '(filename, mode=mode)\n', (1104, 1125), False, 'import gzip\n'), ((4118, 4136), 'pathlib.Path', 'pathlib.Path', (['fdir'], {}), '(fdir)\n', (4130, 4136), False, 'import pathlib\n'), ((4425, 4450), 'multiprocessing.Pool', 'mp.Pool', ([], {'processes': 'n_jobs'}), '(processes=n_jobs)\n', (4432, 4450), True, 'import multiprocessing as mp\n'), ((1635, 1651), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (1645, 1651), False, 'import json\n'), ((2882, 2898), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (2892, 2898), False, 'import json\n'), ((4163, 4181), 'pathlib.Path', 'pathlib.Path', (['fdir'], {}), '(fdir)\n', (4175, 4181), False, 'import pathlib\n'), ((4560, 4578), 'itertools.repeat', 'repeat', (['compressed'], {}), '(compressed)\n', (4566, 4578), False, 'from itertools import repeat\n'), ((4580, 4593), 'itertools.repeat', 'repeat', (['delim'], {}), '(delim)\n', (4586, 4593), False, 'from itertools import repeat\n')] |
import logging
import pytest
from c4.devices.policyengine import PolicyEngineManager
from c4.messaging import Router, RouterClient
from c4.system.configuration import States, Roles
from c4.system.deviceManager import DeviceManager
from c4.system.messages import (LocalStartDeviceManager, LocalStopDeviceManager,
Status)
log = logging.getLogger(__name__)
pytestmark = pytest.mark.usefixtures("temporaryIPCPath")
@pytest.fixture
def systemManagerClusterInfo(backend):
return backend.ClusterInfo("test", "ipc://test.ipc", "ipc://test.ipc", Roles.ACTIVE, States.RUNNING)
class TestPolicyEngineManager(object):
def test_getOperations(self):
operations = PolicyEngineManager.getOperations()
assert {"setPolicies", "start", "stop"} == set(operations.keys())
def test_status(self, systemManagerClusterInfo):
router = Router("test") # @UnusedVariable
deviceManager = DeviceManager(systemManagerClusterInfo, "policyengine", PolicyEngineManager)
assert deviceManager.start()
client = RouterClient("test/policyengine")
startResponse = client.sendRequest(LocalStartDeviceManager("test", "test/policyengine"))
statuses = []
for _ in range(3):
statuses.append(client.sendRequest(Status("test/policyengine")))
stopResponse = client.sendRequest(LocalStopDeviceManager("test", "test/policyengine"))
assert deviceManager.stop()
assert startResponse["state"] == States.RUNNING
assert stopResponse["state"] == States.REGISTERED
| [
"logging.getLogger",
"c4.system.messages.Status",
"c4.system.deviceManager.DeviceManager",
"c4.system.messages.LocalStartDeviceManager",
"c4.system.messages.LocalStopDeviceManager",
"pytest.mark.usefixtures",
"c4.devices.policyengine.PolicyEngineManager.getOperations",
"c4.messaging.RouterClient",
"... | [((362, 389), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (379, 389), False, 'import logging\n'), ((404, 447), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""temporaryIPCPath"""'], {}), "('temporaryIPCPath')\n", (427, 447), False, 'import pytest\n'), ((706, 741), 'c4.devices.policyengine.PolicyEngineManager.getOperations', 'PolicyEngineManager.getOperations', ([], {}), '()\n', (739, 741), False, 'from c4.devices.policyengine import PolicyEngineManager\n'), ((888, 902), 'c4.messaging.Router', 'Router', (['"""test"""'], {}), "('test')\n", (894, 902), False, 'from c4.messaging import Router, RouterClient\n'), ((947, 1023), 'c4.system.deviceManager.DeviceManager', 'DeviceManager', (['systemManagerClusterInfo', '"""policyengine"""', 'PolicyEngineManager'], {}), "(systemManagerClusterInfo, 'policyengine', PolicyEngineManager)\n", (960, 1023), False, 'from c4.system.deviceManager import DeviceManager\n'), ((1079, 1112), 'c4.messaging.RouterClient', 'RouterClient', (['"""test/policyengine"""'], {}), "('test/policyengine')\n", (1091, 1112), False, 'from c4.messaging import Router, RouterClient\n'), ((1156, 1208), 'c4.system.messages.LocalStartDeviceManager', 'LocalStartDeviceManager', (['"""test"""', '"""test/policyengine"""'], {}), "('test', 'test/policyengine')\n", (1179, 1208), False, 'from c4.system.messages import LocalStartDeviceManager, LocalStopDeviceManager, Status\n'), ((1380, 1431), 'c4.system.messages.LocalStopDeviceManager', 'LocalStopDeviceManager', (['"""test"""', '"""test/policyengine"""'], {}), "('test', 'test/policyengine')\n", (1402, 1431), False, 'from c4.system.messages import LocalStartDeviceManager, LocalStopDeviceManager, Status\n'), ((1307, 1334), 'c4.system.messages.Status', 'Status', (['"""test/policyengine"""'], {}), "('test/policyengine')\n", (1313, 1334), False, 'from c4.system.messages import LocalStartDeviceManager, LocalStopDeviceManager, Status\n')] |
#!/usr/bin/env python3
import sys,re,os,re, datetime
import requests
import json
import hashlib
import getopt
from pprint import pprint
from pathlib import Path
################################################################################
## Hashing large files
################################################################################
def file_hash( filename, chksum="sha256" ):
BLOCKSIZE = 65536
if chksum == "sha1":
hasher = hashlib.sha1()
elif chksum == "sha224":
hasher = hashlib.sha224()
elif chksum == "sha256":
hasher = hashlib.sha256()
elif chksum == "sha384":
hasher = hashlib.sha384()
elif chksum == "sha512":
hasher = hashlib.sha512()
else:
hasher = hashlib.sha256()
with open( filename, 'rb') as f:
buf = f.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(BLOCKSIZE)
return hasher.hexdigest()
################################################################################
## HTTP operations, download large files
################################################################################
def download_file( proj, url_filename, local_filename, **opt ):
x_size = 0
l_size = 0
r_size = 0
bsize=1024
overwrite = False
timeout = 10
debug = False
if 'debug' in opt: debug = opt['debug']
if 'bsize' in opt: bsize = opt['bsize']
if 'timeout' in opt: timeout = opt['timeout']
if 'overwrite' in opt and opt['overwrite'] in (True,False):
overwrite = opt['overwrite']
if Path( local_filename ).exists():
l_size = Path( local_filename ).stat().st_size
r = requests.get( url_filename, timeout=timeout, stream=True)
if 'content-length' in r.headers:
r_size = r.headers['content-length']
if debug:
pprint( r.headers )
if r.status_code != 200:
print("# ERROR: Could not find %s, %s : " % ( url_filename, r.status_code ) )
return None
if not Path( local_filename ).exists() or overwrite:
with open( local_filename, 'wb') as f:
for chunk in r.iter_content( chunk_size=bsize ):
if chunk: # filter out keep-alive new chunks
x_size += len( chunk )
f.write(chunk)
print("# [ %s ] [ %s / %s ] --> %s" % ( proj, x_size, r_size, local_filename ), end="\r" )
print("")
else:
print("# [ %s ] [ skip ] --> %s " % ( proj, local_filename ) )
r.close()
return local_filename
################################################################################
## Local file operaitons
################################################################################
def _read_text( filename ):
result = list()
try:
fd = open( filename, "r" )
for line in fd.readlines():
result.append( line.lstrip().rstrip() )
return result
except Exception as e:
print("ERROR Reading %s: %s" % ( filename, e ))
return result
def _read_json( filename ):
return json.loads( "\n".join( _read_text( filename ) ) )
def load_file( filename ):
filesplit = re.split( r"\.", filename )
if filesplit[-1] in ( "json" ):
return _read_json( filename )
else:
return _read_text( filename )
def _write_json( filename, data ):
return _write_text( filename, json.dumps( data, indent=2, sort_keys=True ) )
def _write_text( filename, data ):
fd = open( filename, "w" )
fd.write( str( data ) )
fd.close()
def write_file( filename, data ):
filesplit = re.split( "\.", filename )
if filesplit[-1] in ( "json" ):
return _write_json( filename, data )
else:
return _write_text( filename, data )
################################################################################
def read_env( key ):
if key not in os.environ:
return None
return os.environ.get( key )
################################################################################
def _apply_version( string, version ):
return re.sub( r"<%\s*version\s*%>", version, string )
def _apply_project( string, version ):
return re.sub( r"<%\s*project\s*%>", version, string )
################################################################################
if __name__ == "__main__":
opt = dict()
opt['config'] = "collect.json"
opt['config_d'] = "collect.d"
opt['load'] = None
opt['script'] = sys.argv.pop(0)
if len( sys.argv ):
opt['load'] = sys.argv.pop(0)
config = load_file( "collect.json" )[0]
conf_dir = Path( opt['config_d'] )
for conf_file in conf_dir.iterdir():
for xo in load_file( str( conf_file ) ):
hdata = dict()
x_dir = re.split("\.", str( conf_file.name ) )[0]
if opt['load'] and opt['load'] != x_dir:
continue
if 'skip' in xo and xo['skip']:
continue
if not Path( "%s/%s" % ( config['target'], x_dir )).exists():
Path( "%s/%s" % ( config['target'], x_dir )).mkdir()
bsize = 8192
chksum = "sha256"
if 'checksum' in config: chksum = config['checksum']
if 'checksum' in xo: chksum = xo['checksum']
if 'bsize' in config: bsize = int( config['bsize'] )
if 'bsize' in xo: bsize = int( xo['bsize'] )
if 'version' not in xo: xo['version'] = ""
x_url = _apply_version( xo['url'], xo['version'] )
x_path = "%s/%s/%s" % ( config['target'], x_dir, re.split( r"\/", x_url )[-1] )
if 'filename' in xo:
x_path = "%s/%s/%s" % ( config['target'], x_dir, _apply_version( xo['filename'], xo['version'] ) )
try:
download_file( x_dir, x_url, x_path, bsize=bsize )
except Exception as e:
print( "# EXCEPTION: Failed to download %s to %s: %s" % ( x_url, x_path, e ) )
pprint( e )
if not Path( x_path ).exists():
print( "# ERROR: Failed to download %s to %s, already exists" % ( x_url, x_path ) )
continue
chkfile = "%s.%s.json" % (x_path, chksum)
fst = os.stat( x_path )
hdata['01.filename'] = x_path
hdata['02.source'] = x_url
hdata['03.atime'] = datetime.datetime.fromtimestamp( fst.st_atime ).isoformat()
hdata['04.ctime'] = datetime.datetime.fromtimestamp( fst.st_ctime ).isoformat()
hdata['05.mtime'] = datetime.datetime.fromtimestamp( fst.st_mtime ).isoformat()
hdata['06.size'] = fst.st_size
hdata['07.checksum'] = "%s:%s" % ( chksum, file_hash( x_path, chksum ) )
if 'signature' in xo:
x_sign = _apply_version( xo['signature'], xo['version'] )
x_lsign = _apply_version( "%s/%s/%s" % ( config['target'], x_dir, re.split( r"\/", xo['signature'] )[-1] ), xo['version'] )
try:
download_file( x_dir, x_sign, x_lsign, bsize=1024 )
except Exception as e:
print( "# EXCEPTION: Failed to download %s to %s" % ( x_sign, x_lsign ) )
pprint( e )
hdata['10.signature'] = x_lsign
hdata['11.signature_checksum'] = "%s:%s" % ( chksum, file_hash( x_lsign, chksum ) )
if not Path( chkfile ).exists():
write_file( chkfile, [ hdata ] )
| [
"re.split",
"hashlib.sha256",
"datetime.datetime.fromtimestamp",
"os.stat",
"pathlib.Path",
"json.dumps",
"os.environ.get",
"requests.get",
"hashlib.sha224",
"hashlib.sha384",
"hashlib.sha512",
"re.sub",
"hashlib.sha1",
"pprint.pprint",
"sys.argv.pop"
] | [((1696, 1752), 'requests.get', 'requests.get', (['url_filename'], {'timeout': 'timeout', 'stream': '(True)'}), '(url_filename, timeout=timeout, stream=True)\n', (1708, 1752), False, 'import requests\n'), ((3201, 3226), 're.split', 're.split', (['"""\\\\."""', 'filename'], {}), "('\\\\.', filename)\n", (3209, 3226), False, 'import sys, re, os, re, datetime\n'), ((3630, 3655), 're.split', 're.split', (['"""\\\\."""', 'filename'], {}), "('\\\\.', filename)\n", (3638, 3655), False, 'import sys, re, os, re, datetime\n'), ((3958, 3977), 'os.environ.get', 'os.environ.get', (['key'], {}), '(key)\n', (3972, 3977), False, 'import sys, re, os, re, datetime\n'), ((4112, 4158), 're.sub', 're.sub', (['"""<%\\\\s*version\\\\s*%>"""', 'version', 'string'], {}), "('<%\\\\s*version\\\\s*%>', version, string)\n", (4118, 4158), False, 'import sys, re, os, re, datetime\n'), ((4211, 4257), 're.sub', 're.sub', (['"""<%\\\\s*project\\\\s*%>"""', 'version', 'string'], {}), "('<%\\\\s*project\\\\s*%>', version, string)\n", (4217, 4257), False, 'import sys, re, os, re, datetime\n'), ((4501, 4516), 'sys.argv.pop', 'sys.argv.pop', (['(0)'], {}), '(0)\n', (4513, 4516), False, 'import sys, re, os, re, datetime\n'), ((4639, 4660), 'pathlib.Path', 'Path', (["opt['config_d']"], {}), "(opt['config_d'])\n", (4643, 4660), False, 'from pathlib import Path\n'), ((458, 472), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (470, 472), False, 'import hashlib\n'), ((1860, 1877), 'pprint.pprint', 'pprint', (['r.headers'], {}), '(r.headers)\n', (1866, 1877), False, 'from pprint import pprint\n'), ((3422, 3464), 'json.dumps', 'json.dumps', (['data'], {'indent': '(2)', 'sort_keys': '(True)'}), '(data, indent=2, sort_keys=True)\n', (3432, 3464), False, 'import json\n'), ((4563, 4578), 'sys.argv.pop', 'sys.argv.pop', (['(0)'], {}), '(0)\n', (4575, 4578), False, 'import sys, re, os, re, datetime\n'), ((519, 535), 'hashlib.sha224', 'hashlib.sha224', ([], {}), '()\n', (533, 535), False, 'import hashlib\n'), ((1599, 1619), 'pathlib.Path', 'Path', (['local_filename'], {}), '(local_filename)\n', (1603, 1619), False, 'from pathlib import Path\n'), ((6289, 6304), 'os.stat', 'os.stat', (['x_path'], {}), '(x_path)\n', (6296, 6304), False, 'import sys, re, os, re, datetime\n'), ((582, 598), 'hashlib.sha256', 'hashlib.sha256', ([], {}), '()\n', (596, 598), False, 'import hashlib\n'), ((645, 661), 'hashlib.sha384', 'hashlib.sha384', ([], {}), '()\n', (659, 661), False, 'import hashlib\n'), ((1649, 1669), 'pathlib.Path', 'Path', (['local_filename'], {}), '(local_filename)\n', (1653, 1669), False, 'from pathlib import Path\n'), ((2029, 2049), 'pathlib.Path', 'Path', (['local_filename'], {}), '(local_filename)\n', (2033, 2049), False, 'from pathlib import Path\n'), ((6033, 6042), 'pprint.pprint', 'pprint', (['e'], {}), '(e)\n', (6039, 6042), False, 'from pprint import pprint\n'), ((6420, 6465), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['fst.st_atime'], {}), '(fst.st_atime)\n', (6451, 6465), False, 'import sys, re, os, re, datetime\n'), ((6512, 6557), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['fst.st_ctime'], {}), '(fst.st_ctime)\n', (6543, 6557), False, 'import sys, re, os, re, datetime\n'), ((6604, 6649), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['fst.st_mtime'], {}), '(fst.st_mtime)\n', (6635, 6649), False, 'import sys, re, os, re, datetime\n'), ((708, 724), 'hashlib.sha512', 'hashlib.sha512', ([], {}), '()\n', (722, 724), False, 'import hashlib\n'), ((752, 768), 'hashlib.sha256', 'hashlib.sha256', ([], {}), '()\n', (766, 768), False, 'import hashlib\n'), ((5013, 5054), 'pathlib.Path', 'Path', (["('%s/%s' % (config['target'], x_dir))"], {}), "('%s/%s' % (config['target'], x_dir))\n", (5017, 5054), False, 'from pathlib import Path\n'), ((5084, 5125), 'pathlib.Path', 'Path', (["('%s/%s' % (config['target'], x_dir))"], {}), "('%s/%s' % (config['target'], x_dir))\n", (5088, 5125), False, 'from pathlib import Path\n'), ((5622, 5644), 're.split', 're.split', (['"""\\\\/"""', 'x_url'], {}), "('\\\\/', x_url)\n", (5630, 5644), False, 'import sys, re, os, re, datetime\n'), ((6065, 6077), 'pathlib.Path', 'Path', (['x_path'], {}), '(x_path)\n', (6069, 6077), False, 'from pathlib import Path\n'), ((7288, 7297), 'pprint.pprint', 'pprint', (['e'], {}), '(e)\n', (7294, 7297), False, 'from pprint import pprint\n'), ((7469, 7482), 'pathlib.Path', 'Path', (['chkfile'], {}), '(chkfile)\n', (7473, 7482), False, 'from pathlib import Path\n'), ((6983, 7015), 're.split', 're.split', (['"""\\\\/"""', "xo['signature']"], {}), "('\\\\/', xo['signature'])\n", (6991, 7015), False, 'import sys, re, os, re, datetime\n')] |
import os
pkg_path = os.path.dirname(__file__)
static_folder = os.path.join(pkg_path, 'static')
template_folder = os.path.join(pkg_path, 'templates')
| [
"os.path.dirname",
"os.path.join"
] | [((22, 47), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (37, 47), False, 'import os\n'), ((64, 96), 'os.path.join', 'os.path.join', (['pkg_path', '"""static"""'], {}), "(pkg_path, 'static')\n", (76, 96), False, 'import os\n'), ((115, 150), 'os.path.join', 'os.path.join', (['pkg_path', '"""templates"""'], {}), "(pkg_path, 'templates')\n", (127, 150), False, 'import os\n')] |
import sys
import io
import time
import pprint
input_txt = """
10
0 2 1 1 2 3
1 2 3 3 2 1
2 2 3 1 6 10
3 1 4 1
4 1 7 1
5 2 3 1 6 1
6 2 3 1 8 1
7 2 5 1 8 4
8 1 9 100000
9 0
"""
#sys.stdin = open("ALDS1_11_D_in11.txt","r")#io.StringIO(input_txt)
#sys.stdin = io.StringIO(input_txt)
sys.stdin = open("ALDS1_12_C_in8.txt", 'r')
#tmp = input()
start = time.time()
# copy the below part and paste to the submission form.
# ---------function------------
import sys
from collections import defaultdict
from typing import Dict
def find_shortest_distance(start_vertex: int, n: int, relations: Dict[int, Dict]) -> Dict[int, int]:
unreached_vertices = [x for x in range(1, n)]
distance = {x: sys.maxsize for x in range(n)}
distance[start_vertex] = 0
vtx = None
tmp_distance = [sys.maxsize for x in range(n)]
for k, v in relations[start_vertex].items():
tmp_distance[k] = v
while True:
min_dist = sys.maxsize
for i in unreached_vertices:
dist = tmp_distance[i]
if dist < min_dist:
min_dist = dist
vtx = i
if min_dist == sys.maxsize:
break
unreached_vertices.remove(vtx)
distance[vtx] = min_dist
neighbor_vertices = relations[vtx]
for n_vtx, n_dist in neighbor_vertices.items():
n_dist_from_start = distance[vtx] + n_dist
tmp_dist = tmp_distance[n_vtx]
if tmp_dist == sys.maxsize:
tmp_distance[n_vtx] = n_dist_from_start
else:
if n_dist_from_start < tmp_dist:
tmp_distance[n_vtx] = n_dist_from_start
return distance
def main():
n = int(input())
relations = defaultdict(dict)
lines = sys.stdin.readlines()
for i in range(n):
u, k, *vtx_wght = map(int, lines[i].split())
for v_i in range(k):
relations[u][vtx_wght[2*v_i]] = vtx_wght[2*v_i+1]
dist_from_0 = find_shortest_distance(0, n, relations)
answers = [None] * n
sorted_dist = sorted(dist_from_0.items(), key=lambda x: x[0])
for i in range(n):
answers[i] = f"{sorted_dist[i][0]} {sorted_dist[i][1]}"
[print(ans) for ans in answers]
return
main()
# -----------------------------
print("elapsed:", time.time()-start)
sys.stdin = sys.__stdin__
| [
"sys.stdin.readlines",
"time.time",
"collections.defaultdict"
] | [((374, 385), 'time.time', 'time.time', ([], {}), '()\n', (383, 385), False, 'import time\n'), ((1790, 1807), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (1801, 1807), False, 'from collections import defaultdict\n'), ((1823, 1844), 'sys.stdin.readlines', 'sys.stdin.readlines', ([], {}), '()\n', (1842, 1844), False, 'import sys\n'), ((2374, 2385), 'time.time', 'time.time', ([], {}), '()\n', (2383, 2385), False, 'import time\n')] |
# coding=utf-8
"""
Logical permission backends module
"""
from permission.conf import settings
from permission.utils.handlers import registry
from permission.utils.permissions import perm_to_permission
__all__ = ('PermissionBackend',)
class PermissionBackend(object):
"""
A handler based permission backend
"""
supports_object_permissions = True
supports_anonymous_user = True
supports_inactive_user = True
# pylint:disable=unused-argument
def authenticate(self, username, password):
"""
Always return ``None`` to prevent authentication within this backend.
"""
return None
def has_perm(self, user_obj, perm, obj=None):
"""
Check if user have permission (of object) based on registered handlers.
It will raise ``ObjectDoesNotExist`` exception when the specified
string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
Parameters
----------
user_obj : django user model instance
A django user model instance which be checked
perm : string
`app_label.codename` formatted permission string
obj : None or django model instance
None or django model instance for object permission
Returns
-------
boolean
Whether the specified user have specified permission (of specified
object).
Raises
------
django.core.exceptions.ObjectDoesNotExist
If the specified string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
"""
if settings.PERMISSION_CHECK_PERMISSION_PRESENCE:
# get permission instance from string permission (perm)
# it raise ObjectDoesNotExists when the permission is not exists
try:
perm_to_permission(perm)
except AttributeError:
# Django 1.2 internally use wrong permission string thus ignore
pass
# get permission handlers fot this perm
cache_name = '_%s_cache' % perm
if hasattr(self, cache_name):
handlers = getattr(self, cache_name)
else:
handlers = [h for h in registry.get_handlers()
if perm in h.get_supported_permissions()]
setattr(self, cache_name, handlers)
for handler in handlers:
if handler.has_perm(user_obj, perm, obj=obj):
return True
return False
def has_module_perms(self, user_obj, app_label):
"""
Check if user have permission of specified app based on registered
handlers.
It will raise ``ObjectDoesNotExist`` exception when the specified
string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
Parameters
----------
user_obj : django user model instance
A django user model instance which is checked
app_label : string
`app_label.codename` formatted permission string
Returns
-------
boolean
Whether the specified user have specified permission.
Raises
------
django.core.exceptions.ObjectDoesNotExist
If the specified string permission does not exist and
``PERMISSION_CHECK_PERMISSION_PRESENCE`` is ``True`` in ``settings``
module.
"""
# get permission handlers fot this perm
cache_name = '_%s_cache' % app_label
if hasattr(self, cache_name):
handlers = getattr(self, cache_name)
else:
handlers = [h for h in registry.get_handlers()
if app_label in h.get_supported_app_labels()]
setattr(self, cache_name, handlers)
for handler in handlers:
if handler.has_module_perms(user_obj, app_label):
return True
return False
| [
"permission.utils.handlers.registry.get_handlers",
"permission.utils.permissions.perm_to_permission"
] | [((1981, 2005), 'permission.utils.permissions.perm_to_permission', 'perm_to_permission', (['perm'], {}), '(perm)\n', (1999, 2005), False, 'from permission.utils.permissions import perm_to_permission\n'), ((2367, 2390), 'permission.utils.handlers.registry.get_handlers', 'registry.get_handlers', ([], {}), '()\n', (2388, 2390), False, 'from permission.utils.handlers import registry\n'), ((3852, 3875), 'permission.utils.handlers.registry.get_handlers', 'registry.get_handlers', ([], {}), '()\n', (3873, 3875), False, 'from permission.utils.handlers import registry\n')] |
import logging
import os
import sqlalchemy
import setproctitle
import argparse
import yaml
from apscheduler.scheduler import Scheduler
from cryptokit.rpc_wrapper import CoinRPC
from simplecoin_rpc_client.sc_rpc import SCRPCClient
logger = logging.getLogger('apscheduler.scheduler')
os_root = os.path.abspath(os.path.dirname(__file__) + '/../')
class PayoutManager(object):
def __init__(self, logger, sc_rpc, coin_rpc):
self.logger = logger
self.sc_rpc = sc_rpc
self.coin_rpc = coin_rpc
def pull_payouts(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.pull_payouts()
def send_payout(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
# Try to pay out known payouts
result = sc_rpc.send_payout()
if isinstance(result, bool):
continue
else:
coin_txid, tx, payouts = result
sc_rpc.associate_all()
# Push completed payouts to SC
sc_rpc.associate(coin_txid, payouts, tx.fee)
def associate_all_payouts(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.associate_all()
def confirm_payouts(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.confirm_trans()
def init_db(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.init_db()
def dump_incomplete(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.dump_incomplete()
def dump_complete(self):
for currency, sc_rpc in self.sc_rpc.iteritems():
sc_rpc.dump_complete()
def entry():
parser = argparse.ArgumentParser(prog='simplecoin rpc client scheduler')
parser.add_argument('-l', '--log-level',
choices=['DEBUG', 'INFO', 'WARN', 'ERROR'],
default='INFO')
parser.add_argument('-cl', '--config-location',
default='/config.yml')
args = parser.parse_args()
# Setup logging
root = logging.getLogger()
hdlr = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s [%(name)s] [%(levelname)s] %(message)s')
hdlr.setFormatter(formatter)
root.addHandler(hdlr)
root.setLevel(getattr(logging, args.log_level))
# Setup yaml configs
# =========================================================================
cfg = yaml.load(open(os_root + args.config_location))
# Setup our CoinRPCs + SCRPCClients
coin_rpc = {}
sc_rpc = {}
for curr_cfg in cfg['currencies']:
if not curr_cfg['enabled']:
continue
cc = curr_cfg['currency_code']
coin_rpc[cc] = CoinRPC(curr_cfg, logger=logger)
curr_cfg.update(cfg['sc_rpc_client'])
sc_rpc[cc] = SCRPCClient(curr_cfg, coin_rpc[cc], logger=logger)
pm = PayoutManager(logger, sc_rpc, coin_rpc)
sched = Scheduler(standalone=True)
logger.info("=" * 80)
logger.info("SimpleCoin cron scheduler starting up...")
setproctitle.setproctitle("simplecoin_scheduler")
# All these tasks actually change the database, and shouldn't
# be run by the staging server
sched.add_cron_job(pm.pull_payouts, minute='*/1')
sched.add_cron_job(pm.send_payout, hour='23')
sched.add_cron_job(pm.associate_all_payouts, hour='0')
sched.add_cron_job(pm.confirm_payouts, hour='1')
sched.start()
if __name__ == "__main__":
entry()
| [
"logging.getLogger",
"logging.StreamHandler",
"simplecoin_rpc_client.sc_rpc.SCRPCClient",
"argparse.ArgumentParser",
"logging.Formatter",
"setproctitle.setproctitle",
"cryptokit.rpc_wrapper.CoinRPC",
"os.path.dirname",
"apscheduler.scheduler.Scheduler"
] | [((241, 283), 'logging.getLogger', 'logging.getLogger', (['"""apscheduler.scheduler"""'], {}), "('apscheduler.scheduler')\n", (258, 283), False, 'import logging\n'), ((1722, 1785), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""simplecoin rpc client scheduler"""'}), "(prog='simplecoin rpc client scheduler')\n", (1745, 1785), False, 'import argparse\n'), ((2101, 2120), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (2118, 2120), False, 'import logging\n'), ((2132, 2155), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (2153, 2155), False, 'import logging\n'), ((2172, 2243), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s [%(name)s] [%(levelname)s] %(message)s"""'], {}), "('%(asctime)s [%(name)s] [%(levelname)s] %(message)s')\n", (2189, 2243), False, 'import logging\n'), ((2969, 2995), 'apscheduler.scheduler.Scheduler', 'Scheduler', ([], {'standalone': '(True)'}), '(standalone=True)\n', (2978, 2995), False, 'from apscheduler.scheduler import Scheduler\n'), ((3086, 3135), 'setproctitle.setproctitle', 'setproctitle.setproctitle', (['"""simplecoin_scheduler"""'], {}), "('simplecoin_scheduler')\n", (3111, 3135), False, 'import setproctitle\n'), ((310, 335), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (325, 335), False, 'import os\n'), ((2754, 2786), 'cryptokit.rpc_wrapper.CoinRPC', 'CoinRPC', (['curr_cfg'], {'logger': 'logger'}), '(curr_cfg, logger=logger)\n', (2761, 2786), False, 'from cryptokit.rpc_wrapper import CoinRPC\n'), ((2855, 2905), 'simplecoin_rpc_client.sc_rpc.SCRPCClient', 'SCRPCClient', (['curr_cfg', 'coin_rpc[cc]'], {'logger': 'logger'}), '(curr_cfg, coin_rpc[cc], logger=logger)\n', (2866, 2905), False, 'from simplecoin_rpc_client.sc_rpc import SCRPCClient\n')] |
bl_info = {
"name": "Import Planar Code",
"author": "<NAME>",
"version": (1, 0),
"blender": (2, 80, 0),
"location": "File > Import > Planar Code",
"description": "Import planar code and construct mesh by assigning vertex positions.",
"warning": "",
"support": "TESTING",
"wiki_url": "",
"tracker_url": "",
"category": "Import-Export",
}
import bpy
import bmesh
import numpy as np
import mathutils as mu
from bpy.props import StringProperty, IntProperty, BoolProperty
import struct
import collections
import os
import random
class PlanarCodeReader:
def __init__(self, filename, index, embed2d, embed3d):
self.faceCounters = []
verts_loc, faces = self.read(filename, index)
if (not verts_loc):
return
if (len(verts_loc) <= 0):
return
# create new mesh
name = os.path.basename(filename) + "_" + str(index)
mesh = bpy.data.meshes.new(name)
mesh.from_pydata(verts_loc,[],faces)
mesh.update(calc_edges=True)
# create new bmesh
bm = bmesh.new()
bm.from_mesh(mesh)
# enable lookup
bm.verts.ensure_lookup_table()
bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
if (embed2d):
pv = self.embed(bm)
print(pv)
if (embed3d):
self.liftup(bm, pv)
bm.to_mesh(mesh)
# create new object
obj = bpy.data.objects.new(name, mesh)
# set object location
obj.location = bpy.context.scene.cursor.location
# link the object to collection
bpy.context.scene.collection.objects.link(obj)
def read(self, filename, index):
self.f = open(filename, "rb")
verts = []
faces = []
try:
DEFAULT_HEADER = b">>planar_code<<"
header = self.f.read(len(DEFAULT_HEADER))
if (header == DEFAULT_HEADER):
print(index)
self.skip(index)
# create verts
num_vert = struct.unpack('b', self.f.read(1))
i = 0
while i < num_vert[0]:
# create vertex
verts.append((0, 0, 0))
# read adjacant vertices
adj = []
while True:
tmp = struct.unpack('b', self.f.read(1))
if (tmp[0] <= 0): # 0 means separator
break
adj.append(tmp[0])
# add face counter
lastIndex = len(adj)-1
for j in range(lastIndex):
self.addIfAbsent(collections.Counter([i, adj[j]-1, adj[j+1]-1]))
self.addIfAbsent(collections.Counter([i, adj[0]-1, adj[lastIndex]-1]))
i += 1
for counter in self.faceCounters:
faces.append(tuple(counter))
except:
print(f"Error in reading {filename}")
self.f.close()
return
self.f.close()
del self.f
return verts, faces
def skip(self, index):
# skip to target index
for i in range(index):
num_vert = struct.unpack('b', self.f.read(1))
n = num_vert[0]
while n > 0:
d = struct.unpack('b', self.f.read(1))
if (d[0] == 0):
n -= 1
def addIfAbsent(self, fc):
for counter in self.faceCounters:
if (counter == fc):
break
else:
self.faceCounters.append(fc)
def embed(self, bm):
# randomly pick up a face
outerFace = bm.faces[random.randint(0, len(bm.faces)-1)]
# embed an outer face to form a regular polygon inscribed into a circle
n = len(outerFace.verts)
inv_sqrt = 1.0 / np.sqrt(n)
angle = 360.0 / n
for i, v in enumerate(outerFace.verts):
rad = (i * angle / 180.0) * np.pi
x = inv_sqrt * np.cos(rad)
y = inv_sqrt * np.sin(rad)
v.co.x = x
v.co.y = y
rests = []
for v in bm.verts:
if (not v in outerFace.verts):
rests.append(v)
# variables for the force F_uv on a Edge(u,v)
fuv = np.zeros((len(bm.edges), 3))
# force F_v on a Vertex(v)
fv = np.zeros((len(bm.verts), 3))
# Constant value
n_pi = np.sqrt(len(bm.verts) / np.pi)
# final double A = 2.5;
avg_area = np.pi / len(bm.verts)
loop = 0
# iterations
while (loop < 500):
# Set F_v to zero
fv[:] = 0
# Calculate F_uv for Edges
for j, e in enumerate(bm.edges):
v = e.verts[0]
u = e.verts[1]
C = n_pi
x = C * np.power(v.co.x - u.co.x, 3)
y = C * np.power(v.co.y - u.co.y, 3)
if (np.isfinite(x) and np.isfinite(y)):
fuv[j] = [x, y, 0]
# Update the forces on v and u
fv[v.index] -= fuv[j]
fv[u.index] += fuv[j]
# Move Vertices
cool = np.sqrt(avg_area) / (1.0 + np.power(np.sqrt(avg_area * loop), 3))
for v in rests:
f = np.linalg.norm(fv[v.index])
size = min(f, cool)
if f != 0:
fv[v.index] /= f
fv[v.index] *= size
v.co.x += fv[v.index, 0]
v.co.y += fv[v.index, 1]
loop += 1
return self.periphericity(bm, outerFace)
def periphericity(self, bm, outer):
stack0 = []
stack1 = []
per = 0
pv = np.full(len(bm.verts), -1)
for v in outer.verts:
stack0.append(v)
while (stack0):
for v in stack0:
pv[v.index] = per
# Search adjoining verts
for vi in stack0:
links = vi.link_edges
for e in links:
vo = e.verts[1] if vi.index == e.verts[0].index else e.verts[0]
if (pv[vo.index] < 0):
if (not vo in stack1):
stack1.append(vo)
stack0.clear()
stack0.extend(stack1)
stack1.clear()
per += 1
return pv
def liftup(self, bm, pv):
H = 0.3
for v in bm.verts:
z = H * pv[v.index]
v.co.z = z
class IMPORT_OT_pcode(bpy.types.Operator):
"""Import Planar Code Operator"""
bl_idname = "import_planarcode.pcode"
bl_label = "Import planar code"
bl_description = "Embed a graph written in planar code (binary file)"
bl_options = {"REGISTER", "UNDO"}
bpy.types.Scene.ch = None
bpy.types.Scene.poly = None
filepath: StringProperty(
name="File Path",
description="Filepath used for importing the Planar code file",
maxlen=1024,
default="",
)
CODE_INDEX: IntProperty(
name="Planer code index",
description="An index follows generated order",
default=0,
min=0,
)
EMBED_2D: BoolProperty(
name="Embedding in 2D",
description="Embed a graph in the plane",
default=True,
)
EMBED_3D: BoolProperty(
name="Realizing a graph",
description="Make a polyhedron by giving the heights to the vertices",
default=True,
)
def invoke(self, context, event):
wm = context.window_manager
wm.fileselect_add(self)
return {"RUNNING_MODAL"}
def execute(self, context):
PlanarCodeReader(self.filepath, self.CODE_INDEX, self.EMBED_2D, self.EMBED_3D)
return {"FINISHED"}
def menu_func(self, context):
self.layout.operator(IMPORT_OT_pcode.bl_idname, text="Planar code (.*)")
classes = (
IMPORT_OT_pcode,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.TOPBAR_MT_file_import.append(menu_func)
def unregister():
for cls in classes:
bpy.utils.unregister_class(cls)
bpy.types.TOPBAR_MT_file_import.remove(menu_func)
if __name__ == "__main__":
register()
| [
"bpy.props.StringProperty",
"numpy.sqrt",
"bpy.data.objects.new",
"bmesh.new",
"bpy.types.TOPBAR_MT_file_import.remove",
"numpy.isfinite",
"numpy.linalg.norm",
"numpy.sin",
"bpy.context.scene.collection.objects.link",
"bpy.utils.unregister_class",
"bpy.props.BoolProperty",
"bpy.types.TOPBAR_MT... | [((7250, 7381), 'bpy.props.StringProperty', 'StringProperty', ([], {'name': '"""File Path"""', 'description': '"""Filepath used for importing the Planar code file"""', 'maxlen': '(1024)', 'default': '""""""'}), "(name='File Path', description=\n 'Filepath used for importing the Planar code file', maxlen=1024, default=''\n )\n", (7264, 7381), False, 'from bpy.props import StringProperty, IntProperty, BoolProperty\n'), ((7433, 7541), 'bpy.props.IntProperty', 'IntProperty', ([], {'name': '"""Planer code index"""', 'description': '"""An index follows generated order"""', 'default': '(0)', 'min': '(0)'}), "(name='Planer code index', description=\n 'An index follows generated order', default=0, min=0)\n", (7444, 7541), False, 'from bpy.props import StringProperty, IntProperty, BoolProperty\n'), ((7596, 7693), 'bpy.props.BoolProperty', 'BoolProperty', ([], {'name': '"""Embedding in 2D"""', 'description': '"""Embed a graph in the plane"""', 'default': '(True)'}), "(name='Embedding in 2D', description=\n 'Embed a graph in the plane', default=True)\n", (7608, 7693), False, 'from bpy.props import StringProperty, IntProperty, BoolProperty\n'), ((7739, 7867), 'bpy.props.BoolProperty', 'BoolProperty', ([], {'name': '"""Realizing a graph"""', 'description': '"""Make a polyhedron by giving the heights to the vertices"""', 'default': '(True)'}), "(name='Realizing a graph', description=\n 'Make a polyhedron by giving the heights to the vertices', default=True)\n", (7751, 7867), False, 'from bpy.props import StringProperty, IntProperty, BoolProperty\n'), ((8438, 8487), 'bpy.types.TOPBAR_MT_file_import.append', 'bpy.types.TOPBAR_MT_file_import.append', (['menu_func'], {}), '(menu_func)\n', (8476, 8487), False, 'import bpy\n'), ((8580, 8629), 'bpy.types.TOPBAR_MT_file_import.remove', 'bpy.types.TOPBAR_MT_file_import.remove', (['menu_func'], {}), '(menu_func)\n', (8618, 8629), False, 'import bpy\n'), ((974, 999), 'bpy.data.meshes.new', 'bpy.data.meshes.new', (['name'], {}), '(name)\n', (993, 999), False, 'import bpy\n'), ((1136, 1147), 'bmesh.new', 'bmesh.new', ([], {}), '()\n', (1145, 1147), False, 'import bmesh\n'), ((1536, 1568), 'bpy.data.objects.new', 'bpy.data.objects.new', (['name', 'mesh'], {}), '(name, mesh)\n', (1556, 1568), False, 'import bpy\n'), ((1708, 1754), 'bpy.context.scene.collection.objects.link', 'bpy.context.scene.collection.objects.link', (['obj'], {}), '(obj)\n', (1749, 1754), False, 'import bpy\n'), ((8401, 8430), 'bpy.utils.register_class', 'bpy.utils.register_class', (['cls'], {}), '(cls)\n', (8425, 8430), False, 'import bpy\n'), ((8543, 8574), 'bpy.utils.unregister_class', 'bpy.utils.unregister_class', (['cls'], {}), '(cls)\n', (8569, 8574), False, 'import bpy\n'), ((4087, 4097), 'numpy.sqrt', 'np.sqrt', (['n'], {}), '(n)\n', (4094, 4097), True, 'import numpy as np\n'), ((912, 938), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (928, 938), False, 'import os\n'), ((4249, 4260), 'numpy.cos', 'np.cos', (['rad'], {}), '(rad)\n', (4255, 4260), True, 'import numpy as np\n'), ((4289, 4300), 'numpy.sin', 'np.sin', (['rad'], {}), '(rad)\n', (4295, 4300), True, 'import numpy as np\n'), ((5488, 5505), 'numpy.sqrt', 'np.sqrt', (['avg_area'], {}), '(avg_area)\n', (5495, 5505), True, 'import numpy as np\n'), ((5604, 5631), 'numpy.linalg.norm', 'np.linalg.norm', (['fv[v.index]'], {}), '(fv[v.index])\n', (5618, 5631), True, 'import numpy as np\n'), ((5128, 5156), 'numpy.power', 'np.power', (['(v.co.x - u.co.x)', '(3)'], {}), '(v.co.x - u.co.x, 3)\n', (5136, 5156), True, 'import numpy as np\n'), ((5182, 5210), 'numpy.power', 'np.power', (['(v.co.y - u.co.y)', '(3)'], {}), '(v.co.y - u.co.y, 3)\n', (5190, 5210), True, 'import numpy as np\n'), ((5232, 5246), 'numpy.isfinite', 'np.isfinite', (['x'], {}), '(x)\n', (5243, 5246), True, 'import numpy as np\n'), ((5251, 5265), 'numpy.isfinite', 'np.isfinite', (['y'], {}), '(y)\n', (5262, 5265), True, 'import numpy as np\n'), ((2922, 2978), 'collections.Counter', 'collections.Counter', (['[i, adj[0] - 1, adj[lastIndex] - 1]'], {}), '([i, adj[0] - 1, adj[lastIndex] - 1])\n', (2941, 2978), False, 'import collections\n'), ((5524, 5548), 'numpy.sqrt', 'np.sqrt', (['(avg_area * loop)'], {}), '(avg_area * loop)\n', (5531, 5548), True, 'import numpy as np\n'), ((2836, 2888), 'collections.Counter', 'collections.Counter', (['[i, adj[j] - 1, adj[j + 1] - 1]'], {}), '([i, adj[j] - 1, adj[j + 1] - 1])\n', (2855, 2888), False, 'import collections\n')] |
import gevent
from gevent.queue import Queue, Empty
from gevent_subprocess import Popen, PIPE
from gsh.plugin import BaseExecutor, BaseInnerExecutor
class SshExecutor(BaseExecutor):
def __init__(self, args, kwargs):
self.ssh_opts = kwargs.get("ssh_opts", [])
super(SshExecutor, self).__init__(args, kwargs)
class Executor(BaseInnerExecutor):
def __init__(self, *args, **kwargs):
self.names = {}
self._output_queue = Queue()
super(SshExecutor.Executor, self).__init__(*args, **kwargs)
@staticmethod
def _stream_fd(fd, queue):
for line in iter(fd.readline, b""):
queue.put_nowait((fd, line))
def _consume(self, queue):
while True:
try:
output = queue.get()
except Empty:
continue
# None is explicitly sent to shutdown the consumer
if output is None:
return
fd, line = output
self.update(self.hostname, self.names[fd], line)
def run(self):
_proc = Popen(
["ssh", "-no", "PasswordAuthentication=no"] + self.parent.ssh_opts + [self.hostname] + self.command,
stdout=PIPE, stderr=PIPE
)
self.names = {
_proc.stdout: "stdout",
_proc.stderr: "stderr",
}
out_worker = gevent.spawn(self._stream_fd, _proc.stdout, self._output_queue)
err_worker = gevent.spawn(self._stream_fd, _proc.stderr, self._output_queue)
waiter = gevent.spawn(_proc.wait)
consumer = gevent.spawn(self._consume, self._output_queue)
gevent.joinall([out_worker, err_worker, waiter], timeout=self.timeout)
# If we've made it here and the process hasn't completed we've timed out.
if _proc.poll() is None:
self._output_queue.put_nowait(
(_proc.stderr, "GSH: command timed out after %s second(s).\n" % self.timeout))
_proc.kill()
rc = _proc.wait()
self._output_queue.put_nowait(None)
consumer.join()
return rc
| [
"gevent_subprocess.Popen",
"gevent.joinall",
"gevent.spawn",
"gevent.queue.Queue"
] | [((475, 482), 'gevent.queue.Queue', 'Queue', ([], {}), '()\n', (480, 482), False, 'from gevent.queue import Queue, Empty\n'), ((1161, 1297), 'gevent_subprocess.Popen', 'Popen', (["(['ssh', '-no', 'PasswordAuthentication=no'] + self.parent.ssh_opts + [self\n .hostname] + self.command)"], {'stdout': 'PIPE', 'stderr': 'PIPE'}), "(['ssh', '-no', 'PasswordAuthentication=no'] + self.parent.ssh_opts +\n [self.hostname] + self.command, stdout=PIPE, stderr=PIPE)\n", (1166, 1297), False, 'from gevent_subprocess import Popen, PIPE\n'), ((1488, 1551), 'gevent.spawn', 'gevent.spawn', (['self._stream_fd', '_proc.stdout', 'self._output_queue'], {}), '(self._stream_fd, _proc.stdout, self._output_queue)\n', (1500, 1551), False, 'import gevent\n'), ((1577, 1640), 'gevent.spawn', 'gevent.spawn', (['self._stream_fd', '_proc.stderr', 'self._output_queue'], {}), '(self._stream_fd, _proc.stderr, self._output_queue)\n', (1589, 1640), False, 'import gevent\n'), ((1662, 1686), 'gevent.spawn', 'gevent.spawn', (['_proc.wait'], {}), '(_proc.wait)\n', (1674, 1686), False, 'import gevent\n'), ((1710, 1757), 'gevent.spawn', 'gevent.spawn', (['self._consume', 'self._output_queue'], {}), '(self._consume, self._output_queue)\n', (1722, 1757), False, 'import gevent\n'), ((1771, 1841), 'gevent.joinall', 'gevent.joinall', (['[out_worker, err_worker, waiter]'], {'timeout': 'self.timeout'}), '([out_worker, err_worker, waiter], timeout=self.timeout)\n', (1785, 1841), False, 'import gevent\n')] |
from models.indicators import Indicators
import numpy as np
import matplotlib.pyplot as plt
def plot_prices(ax, prices, line_style):
i = np.arange(len(prices))
ax.plot(ax, prices, line_style)
return ax
def plot_macd(ax, prices, slow_period, fast_period, line_style='k-'):
macd = Indicators.macd(prices, slow_period, fast_period)[slow_period - 1:]
i = np.arange(len(prices))[slow_period-1:]
ax.plot(i, macd, line_style)
return ax
def plot_ema(ax, prices, period, line_style='k-'):
ema = Indicators.ema(prices, period)[period-1:]
i = np.arange(len(prices))[period-1:]
ax.plot(i, ema, line_style)
return ax
| [
"models.indicators.Indicators.ema",
"models.indicators.Indicators.macd"
] | [((299, 348), 'models.indicators.Indicators.macd', 'Indicators.macd', (['prices', 'slow_period', 'fast_period'], {}), '(prices, slow_period, fast_period)\n', (314, 348), False, 'from models.indicators import Indicators\n'), ((524, 554), 'models.indicators.Indicators.ema', 'Indicators.ema', (['prices', 'period'], {}), '(prices, period)\n', (538, 554), False, 'from models.indicators import Indicators\n')] |
"""
Unit Test for strings.basic problems
"""
from unittest import TestCase
from strings.basic import alphabetize
class TestAlphabetize(TestCase):
"""
Unit Test for alphabetize method
"""
def test_should_return_alphabet(self):
"""
Test alphabetize method using every uppercase and lowercase character
"""
self.assertEqual('aBbcDeFgHiJkLmNoPqRsTuVwXyZ', alphabetize('ZyXwVuTsRqPoNmLkJiHgFeDcBba'))
| [
"strings.basic.alphabetize"
] | [((405, 447), 'strings.basic.alphabetize', 'alphabetize', (['"""ZyXwVuTsRqPoNmLkJiHgFeDcBba"""'], {}), "('ZyXwVuTsRqPoNmLkJiHgFeDcBba')\n", (416, 447), False, 'from strings.basic import alphabetize\n')] |
#!/usr/bin/env python
from distutils.core import setup
setup(
name="python-tdlib",
version="1.4.0",
author="andrew-ld",
license="MIT",
url="https://github.com/andrew-ld/python-tdlib",
packages=["py_tdlib", "py_tdlib.constructors", "py_tdlib.factory"],
install_requires=["werkzeug", "simplejson"],
python_requires=">=3.6",
)
| [
"distutils.core.setup"
] | [((57, 336), 'distutils.core.setup', 'setup', ([], {'name': '"""python-tdlib"""', 'version': '"""1.4.0"""', 'author': '"""andrew-ld"""', 'license': '"""MIT"""', 'url': '"""https://github.com/andrew-ld/python-tdlib"""', 'packages': "['py_tdlib', 'py_tdlib.constructors', 'py_tdlib.factory']", 'install_requires': "['werkzeug', 'simplejson']", 'python_requires': '""">=3.6"""'}), "(name='python-tdlib', version='1.4.0', author='andrew-ld', license=\n 'MIT', url='https://github.com/andrew-ld/python-tdlib', packages=[\n 'py_tdlib', 'py_tdlib.constructors', 'py_tdlib.factory'],\n install_requires=['werkzeug', 'simplejson'], python_requires='>=3.6')\n", (62, 336), False, 'from distutils.core import setup\n')] |
import numpy as np
import pandas as pd
import scipy.stats as scs
import itertools
from collections import defaultdict
import textwrap
import pingouin as pg
from statsmodels.stats.multicomp import pairwise_tukeyhsd
from sklearn.neighbors import NearestNeighbors
from sklearn.decomposition import PCA
from sklearn.cluster import DBSCAN, KMeans, OPTICS
from sklearn.metrics import silhouette_samples, silhouette_score
from sklearn.preprocessing import StandardScaler
from sklearn.metrics.pairwise import cosine_distances, cosine_similarity
from sklearn.preprocessing import StandardScaler, MinMaxScaler
pd.options.display.max_columns = 150
from umap import UMAP
from statannot import add_stat_annotation
import plotly
import plotly.graph_objs as go
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.colors as mcolors
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
from mpl_toolkits import mplot3d
import matplotlib.cm as cm
from adjustText import adjust_text
import matplotlib.patheffects as PathEffects
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
###
def simple_axis(ax):
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
def run_by_group(orig_df,
**kwargs):
g = orig_df.groupby(kwargs['groupby'])
base_name = kwargs['save_name']
for group, data in g:
kwargs['title'] = group
kwargs['save_name'] = base_name+'_'+group
run_graph(data, **kwargs)
return
def run_graph(df,
**kwargs):
fig, ax = plt.subplots(figsize=kwargs['figsize'])
if 'violin' in kwargs['save_name']:
ax = run_violin(df, ax, **kwargs)
elif 'scatter' in kwargs['save_name']:
if '5' in kwargs['save_name']:
ax = run_scatter_5(df, ax, **kwargs)
else:
ax = run_scatter(df, ax, **kwargs)
if 'comp_df' in kwargs:
ax = run_loadings(df, ax, **kwargs)
elif 'reg' in kwargs['save_name']:
ax = run_scatter(df, ax, **kwargs)
elif 'hist' in kwargs['save_name']:
ax = run_hist(df, ax, **kwargs)
elif 'bar' in kwargs['save_name']:
ax = run_bar(df, ax, **kwargs)
elif 'stacked' in kwargs['save_name']:
ax = run_stacked_bar(df, ax, **kwargs)
elif 'box' in kwargs['save_name']:
ax = run_box(df, ax, **kwargs)
elif 'sil' in kwargs['save_name']:
ax = run_sil(df, ax, **kwargs)
elif 'kde' in kwargs['save_name']:
ax = run_kde(df, ax, **kwargs)
elif 'line' in kwargs['save_name']:
ax = run_line(df, ax, **kwargs)
if 'log' in kwargs:
# ax.set_xscale('symlog', linthreshx=1e-1)
# ax.set_yscale('symlog', linthreshy=1e-1)
ax.set_xscale('log')
ax.set_yscale('log')
if 'xlims' in kwargs:
if len(kwargs['xlims']) == 1:
xlims = ax.get_xlim()
kwargs['xlims'] = (kwargs['xlims'][0], xlims[1])
ax.set_xlim(kwargs['xlims'])
if 'ylims' in kwargs:
if len(kwargs['ylims']) == 1:
ylims = ax.get_ylim()
kwargs['ylims'] = (kwargs['ylims'][0], ylims[1])
ax.set_ylim(kwargs['ylims'])
ax.set_xlabel(kwargs['x_label'], fontweight='bold', fontsize=11)
ax.set_ylabel(kwargs['y_label'], fontweight='bold', fontsize=11)
# if 'comp_df' in kwargs:
# ax2 = ax.twiny()
# ax2.set_xticks( ax.get_xticks() )
# ax2.set_xbound(ax.get_xbound())
# ax2.set_xticklabels([x/ax.get_xticks().max() for x in ax.get_xticks()])
# ax2.set_xlabel('Loadings on PC'+str(kwargs['x']+1), fontweight='bold', fontsize=11)
# ax3 = ax.twinx()
# ax3.set_yticks(ax.get_yticks())
# ax3.set_ybound(ax.get_ybound())
# ax3.set_yticklabels([y/ax.get_yticks().max() for y in ax.get_yticks()])
# ax3.set_ylabel('Loadings on PC'+str(kwargs['y']+1), fontweight='bold', fontsize=11)
ax.set_title(kwargs['title'], fontweight='bold', fontsize=12)
simple_axis(ax)
plt.tight_layout()
fig.savefig('viz/'+kwargs['save_name']+'.png')
return
def sample_df(df, x):
if x==1:
return df
elif x<1:
return df.sample(frac=x, random_state=56)
else:
return df.sample(n=x, random_state=56)
def run_violin(data, ax, **kwargs):
sub_df = sample_df(data, kwargs['sample_frac'])
# get ns from full dataset
if kwargs['x'] == 'region':
df = pd.melt(data.loc[:, kwargs['cols']],
id_vars='region', value_vars='tot_thc').drop(columns=['variable'])
sub_df = pd.melt(sub_data.loc[:, kwargs['cols']],
id_vars='region', value_vars='tot_thc').drop(columns=['variable'])
order, n_dict = violin_order(df, group_by='region')
else:
if 'cols' in kwargs:
df = pd.melt(data.loc[:, kwargs['cols']], var_name=kwargs['x'])
sub_df = pd.melt(sub_df.loc[:, kwargs['cols']], var_name=kwargs['x'])
order, n_dict = violin_order(df, group_by=kwargs['x'])
else:
df = data
sub_df = sub_df
order, n_dict = violin_order(df, group_by=kwargs['x'])
# if pre-set order, use that
if 'order' in kwargs:
order = kwargs['order']
# plot with sampled data
if 'palette' in kwargs:
sns.violinplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df,
scale='width', order=order,
palette=kwargs['palette'], linewidth=0, ax=ax)
else:
sns.violinplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df,
scale='width', order=order,
color='lightslategray', linewidth=0, ax=ax)
PROPS = {
'boxprops':{'facecolor':'black', 'edgecolor':'black', 'linewidth':3},
'medianprops':{'color':'white', 'linewidth':2},
'whiskerprops':{'color':'black', 'linewidth':2}
}
boxplot = sns.boxplot(x=kwargs['x'], y=kwargs['y'],
data=df, order=order,
showcaps=False, width=0.06,
fliersize=0.5, ax=ax, **PROPS)
if kwargs['avg']:
avg_avgs = df.groupby(kwargs['x'])[kwargs['y']].mean().mean()
ax.axhline(avg_avgs, color='black', linestyle='--')
if 'axhline' in kwargs:
ax.axhline(kwargs['axhline'], color='black', linestyle='--')
if 'sil-scores' in kwargs['save_name']:
ax.axhline(0, color='black', linestyle='--')
if kwargs['sig_comp']:
box_pairs = list(itertools.combinations(order,r=2))
test_results = add_stat_annotation(ax, data=df,
x=kwargs['x'], y=kwargs['y'],
order=order,
box_pairs=box_pairs,
text_annot_custom=[get_stats(df, pair, kwargs['x']) for pair in box_pairs],
perform_stat_test=False, pvalues=[0, 0, 0],
loc='outside', verbose=0)
# ttest_df = pd.DataFrame(index=order, columns=['y_val','p_val','cohens_d'])
# ttest_df[['y_val','p_val','cohens_d']] = ttest_df.apply(run_cohens, args=(df, ), axis=1, result_type='expand')
# p_val_adj = 0.05/ttest_df.shape[0]
# ttest_df['reject'] = ttest_df['p_val'] <= p_val_adj
# bins = [0, 0.2, 0.5, 0.8, np.inf]
# names = ['', '*', '**', '***']
# ttest_df['star'] = pd.cut(np.abs(ttest_df['cohens_d']), bins, labels=names)
# for i, region in enumerate(order):
# if ttest_df.loc[region, 'reject']:
# y = ttest_df.loc[region, 'y_val']
# ax.text(i, y+2, ttest_df.loc[region, 'star'], ha='center', size=20)
if 'v_xticklabels' in kwargs:
xtick_labels = ax.get_xticklabels()
labels = [textwrap.fill(x.get_text(),10) for x in xtick_labels]
_ = ax.set_xticklabels(labels, rotation=90, ha='center')
else:
xtick_labels = ax.get_xticklabels()
labels = [x.get_text()+'\nn='+str(n_dict[x.get_text()]['value']) for x in xtick_labels]
_ = ax.set_xticklabels(labels)
return ax
def violin_order(df, group_by='Cannab'):
order = df.groupby(group_by).median().sort_values(by='value', ascending=False).index
n_dict = df.groupby(group_by).count().T.to_dict(orient='dict')
return order.values, n_dict
def run_scatter(df, ax, **kwargs):
no_nan = df.dropna(subset=[kwargs['x'], kwargs['y']], how='any')
sub_df = sample_df(no_nan, kwargs['sample_frac'])
if 'size' in kwargs:
s = kwargs['size']
else:
s = mpl.rcParams['lines.markersize']**2
if 'edgecolor' in kwargs:
ec = kwargs['edgecolor']
else:
ec = 'white'
if 'hue' in kwargs:
if 'sort_list' in kwargs:
hue_order = kwargs['sort_list']
sub_df = sub_df.sort_values(kwargs['hue'], key=make_sorter(kwargs['sort_list']))
else:
hue_order = sub_df[kwargs['hue']].value_counts().index
sns.scatterplot(x=kwargs['x'], y=kwargs['y'],
hue=kwargs['hue'],
data=sub_df,
s=s,
edgecolor=ec,
alpha=0.5,
hue_order=hue_order,
palette=kwargs['palette'],
ax=ax)
# include full ns
handles, labels = ax.get_legend_handles_labels()
if 'n_display' in kwargs:
labels_n = [(cat, df.loc[df[kwargs['hue']]==cat].shape[0]) for cat in hue_order]
labels = [cat+'\nn='+str(n) for cat, n in labels_n]
ax.legend(handles=handles[:kwargs['n_display']], labels=labels[:kwargs['n_display']], title=kwargs['hue'].title(), handlelength=4)
else:
labels_n = [(cat, df.loc[df[kwargs['hue']]==cat].shape[0]) for cat in hue_order]
labels = [cat+'\nn='+str(n) for cat, n in labels_n]
ax.legend(handles=handles, labels=labels, title=kwargs['hue'].title(), handlelength=4)
else:
sns.regplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df,
scatter_kws={'alpha':0.1, 'color':'lightslategray', 'rasterized':True},
line_kws={'color':'orange'},
ax=ax)
r, p = scs.spearmanr(no_nan[kwargs['x']], no_nan[kwargs['y']])
labels = ['rho = {:.2f}'.format(r)]
if p < 1e-300:
labels.append('p < 1e-300')
else:
labels.append('p = {:.1e}'.format(p))
ax.legend(labels=['\n'.join(labels)])
if 'prod_strains' in kwargs:
s_colors = ['black', 'gray', 'white']
s_markers = ['^', 'D', 'o']
n_strains = len(kwargs['prod_strains'])
for strain, color, marker in zip(kwargs['prod_strains'], s_colors[:n_strains], s_markers[:n_strains]):
sns.scatterplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df.loc[sub_df['strain_slug']==strain],
s=s+35,
edgecolor='black',
linewidth=1.5,
color=color,
label=strain,
marker=marker,
ax=ax)
return ax
def get_log(df, cannab_1='tot_thc', cannab_2='tot_cbd'):
# get THC_CBD ratio for batches without 0 tot_thc (avoid dividing by 0)
df['ratio'] = 0
df.loc[df[cannab_2] != 0, 'ratio'] = (df.loc[df[cannab_2] != 0, cannab_1]) / (df.loc[df[cannab_2] != 0, cannab_2])
# get log_THC_CBD vals
df['log_ratio'] = 0
df.loc[df['ratio'] != 0, 'log_ratio'] = np.log10(df.loc[df['ratio'] != 0, 'ratio'])
# set the 0 tot_cbd batches to an extraneous high bin
df.loc[df[cannab_2] == 0, 'log_ratio'] = 4
df.loc[df[cannab_1] == 0, 'log_ratio'] = -2
log_ratio = df['log_ratio']
return log_ratio
def run_hist(df, ax, **kwargs):
sub_df = sample_df(df, kwargs['sample_frac'])
# some cut-offs
ct_thresh_high = 5
ct_thresh_low = 0.25
max_log = 4
min_log = -2.0
# get log data
log_cannab = get_log(sub_df, cannab_1='tot_'+kwargs['x'], cannab_2='tot_'+kwargs['y'])
# get histogram
hist, bins = np.histogram(log_cannab, bins=np.arange(min_log-0.1, max_log+0.1, 0.05))
# get colors
colors = []
for low, high in zip(bins,bins[1:]):
avg = np.mean([low, high])
if avg >= np.log10(ct_thresh_high):
colors.append('darkblue')
elif avg <= np.log10(ct_thresh_low):
colors.append('black')
else:
colors.append('steelblue')
# plot histogram, thresholds
ax.bar(bins[:-1], hist.astype(np.float32) / hist.sum(),
width=(bins[1]-bins[0]), color=colors)
ax.plot([np.log10(ct_thresh_high), np.log10(ct_thresh_high)], [0, kwargs['ylims'][1]-0.02],
linestyle='--', color='k', linewidth=1)
ax.plot([np.log10(ct_thresh_low), np.log10(ct_thresh_low)], [0, kwargs['ylims'][1]-0.02],
linestyle='--', color='k', linewidth=1)
ax.set_xticklabels(['',float("-inf"), -1, 0, 1, 2, 3, float("inf")])
# draw legend
chemotypes = ['THC-Dom', 'Bal THC/CBD', 'CBD-Dom']
ct_1 = mpatches.Patch(color='darkblue', label='THC-Dom')
ct_2 = mpatches.Patch(color='steelblue', label='Bal THC/CBD')
ct_3 = mpatches.Patch(color='black', label='CBD-Dom')
ct_handles, ct_labels = ax.get_legend_handles_labels()
ct_labels_n = [(x, df.loc[df['chemotype']==x].shape[0]) for x in chemotypes]
ct_labels = [x+'\nn='+str(n) for x, n in ct_labels_n]
ax.legend(handles=[ct_1,ct_2,ct_3], labels=ct_labels,title='Chemotype',handlelength=4)
return ax
def normalize(df, cols):
df.loc[:, cols] = (df.loc[:, cols]
.div(df.loc[:, cols].sum(axis=1), axis=0)
.multiply(100))
return df
def max_min(arr):
return arr/(arr.max()-arr.min())
def make_sorter(sort_list):
"""
Create a dict from the list to map to 0..len(l)
Returns a mapper to map a series to this custom sort order
"""
sort_order = {k:v for k,v in zip(sort_list, range(len(sort_list)))}
return lambda s: s.map(lambda x: sort_order[x])
def run_bar(df, ax, **kwargs):
if 'hue' in kwargs:
sns.barplot(x=kwargs['x'], y=kwargs['y'],
hue=kwargs['hue'],
data=df,
palette=kwargs['palette'],
order=kwargs['order'])
elif 'palette' in kwargs:
sns.barplot(x=kwargs['x'], y=kwargs['y'],
data=df,
palette=kwargs['palette'],
order=kwargs['order'])
else:
sns.barplot(x=kwargs['x'], y=kwargs['y'],
color='lightslategray')
return ax
def run_box(df, ax, **kwargs):
if 'palette' in kwargs:
sns.boxplot(x=kwargs['x'], y=kwargs['y'],
data=df,
palette=kwargs['palette'],
order=kwargs['order'])
else:
sns.boxplot(x=kwargs['x'], y=kwargs['y'],
color='lightslategray')
return ax
def run_pca(df, cols, norm=True, n_components=2, max_min_arr=False):
df[cols] = df[cols].fillna(0)
# get rid of rows that are all 0 for specified columns
zero_bool = (df[cols]==0).sum(axis=1)==len(cols)
df = df[~zero_bool].copy()
if norm:
X = normalize(df, cols).copy()
else:
X = df.copy()
model = PCA(n_components=n_components)
model.fit(X.loc[:, cols])
arr = model.fit_transform(X.loc[:, cols])
if max_min_arr:
arr = np.apply_along_axis(max_min, arr=arr, axis=0)
# add first three component scores to df
X[0] = arr[:,0]
X[1] = arr[:,1]
X[2] = arr[:,2]
return X, arr, model
def run_loadings(df, ax, **kwargs):
comp_df = kwargs['comp_df']
comp_df['combo_score'] = np.abs(comp_df[[kwargs['x'],kwargs['y']]]).sum(axis=1)
comp_df = comp_df.sort_values(by='combo_score', ascending=False).iloc[:kwargs['n_display']]
max_x = df[kwargs['x']].max()
max_y = df[kwargs['y']].max()
texts = []
for x in comp_df.iterrows():
texts.append(ax.text(x[1][kwargs['x']]*max_x,
x[1][kwargs['y']]*max_y,
x[0],
fontweight='bold',
bbox=dict(facecolor='white', edgecolor='blue', pad=2, alpha=0.75)))
ax.arrow(0, 0,
x[1][kwargs['x']]*max_x,
x[1][kwargs['y']]*max_y,
color='black', alpha=1,
lw=2, head_width=1)
adjust_text(texts)
return ax
def run_sil(df, ax, **kwargs):
sub_df = sample_df(df, kwargs['sample_frac'])
labels = df[kwargs['hue']]
sub_labels = sub_df[kwargs['hue']]
label_list = labels.value_counts().index
silhouette_avg = silhouette_score(df[kwargs['cols']], labels)
sample_sil_val = silhouette_samples(sub_df[kwargs['cols']], sub_labels)
y_lower=0
for i, label in enumerate(label_list[:kwargs['n_display']]):
ith_cluster_sil_val = sample_sil_val[sub_labels==label]
ith_cluster_sil_val.sort()
size_cluster_i = ith_cluster_sil_val.shape[0]
y_upper = y_lower+size_cluster_i
color = kwargs['palette'][label]
ax.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_sil_val,
facecolor=color, edgecolor=color, alpha=0.7)
ax.text(-0.05, y_lower+0.5*size_cluster_i, label)
y_lower = y_upper+1
ax.axvline(silhouette_avg, color='lightslategray', linestyle='--')
ax.legend(labels=['Avg Silhouette Score {:.2f}'.format(silhouette_avg)])
ax.set_ylim(0, y_upper+10)
return ax
def score2loading(x):
return x / x.max()
def loading2score(x):
return x * x.max()
def get_ct(df):
# determine THC/CBD ratio
df['chemotype_ratio'] = df['tot_thc'].div(df['tot_cbd'], fill_value=0)
df.loc[(df['tot_thc']==0)&(df['tot_cbd']!=0), 'chemotype_ratio'] = -np.inf
df.loc[(df['tot_thc']!=0)&(df['tot_cbd']==0), 'chemotype_ratio'] = np.inf
# bin chemotypes by ratio
df['chemotype'] = pd.cut(df['chemotype_ratio'],
[-np.inf, 0.2, 5, np.inf],
labels=['CBD-Dom','Bal THC/CBD', 'THC-Dom'],
include_lowest=True)
return df
def run_stacked_bar(df, ax, **kwargs):
if 'order' in kwargs:
df[kwargs['order']].plot(kind='bar', stacked=True, color=kwargs['palette'], ax=ax)
else:
df.plot(kind='bar', stacked=True, color=kwargs['palette'], ax=ax)
# .patches is everything inside of the chart
for rect in ax.patches:
# Find where everything is located
height = rect.get_height()
width = rect.get_width()
x = rect.get_x()
y = rect.get_y()
# The height of the bar is the data value and can be used as the label
label_text = f'{height:.1f}%' # f'{height:.2f}' to format decimal values
# ax.text(x, y, text)
label_x = x + width / 2
label_y = y + height / 2
# plot only when height is greater than specified value
if height > 5:
txt = ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=10, fontweight='bold', color='black')
txt.set_path_effects([PathEffects.withStroke(linewidth=4, foreground='w')])
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
return ax
# def run_polar_plot(df, ax, **kwargs):
# # print(df.loc[:,kwargs['cols']])
# mean_cols = list(df.loc[:,kwargs['cols']].mean(axis=0))
# mean_cols2 = mean_cols + mean_cols[:1]
# angles = [n / len(mean_cols) * 2 * np.pi for n in range(len(mean_cols))]
# angles = angles + angles[:1]
# # get color
# order = np.argsort(mean_cols)[::-1]
# top_val = np.array(kwargs['cols'])[order][0]
# if 'colors' in kwargs:
# colors = kwargs['colors']
# else:
# colors = kwargs['palette'][top_val]
# # # error bars
# # err_cols = list(df.loc[:,kwargs['cols']].std(axis=0))
# # err_cols2 = err_cols + err_cols[:1]
# # ax.errorbar(angles, mean_cols2, yerr=err_cols2, capsize=0, color=colors, linestyle='solid', ecolor='lightslategray')
# # plot
# if kwargs['avg']:
# ax.plot(angles, mean_cols2, color=colors, lw=1, linestyle='solid')
# ax.fill(angles, mean_cols2, colors, alpha=0.1)
# # y limits
# ax.set_ylim(0, np.max(mean_cols2))
# else:
# for row_idx, row in df[kwargs['cols']].iterrows():
# row_list = list(row)
# row_list2 = row_list + row_list[:1]
# if type(colors)==str:
# ax.plot(angles, row_list2, color=colors, lw=0.5)
# else:
# ax.plot(angles, row_list2, color=colors[row_idx], lw=0.5)
# ax.set_ylim(0, np.max(df[kwargs['cols']].max()))
# # tick labels
# tick_labs = kwargs['cols']
# ax.set_xticks(angles[:-1])
# ax.set_xticklabels(tick_labs, color='black', size=10)
# ax.set_yticks([])
# return ax
def run_polar_plot(df, ax, **kwargs):
# print(df.loc[:,kwargs['cols']])
mean_cols = list(df.loc[:,kwargs['cols']].mean(axis=0))
mean_cols2 = mean_cols + mean_cols[:1]
angles = [n / len(mean_cols) * 2 * np.pi for n in range(len(mean_cols))]
angles = angles + angles[:1]
# plot samples
if 'sub_n' in kwargs:
sub_data = df.sort_values('n_samps', ascending=False)[:kwargs['sub_n']]
else:
sub_data = df
for row_idx, row in sub_data[kwargs['cols']].iterrows():
row_list = list(row)
row_list2 = row_list + row_list[:1]
if type(kwargs['colors'])==str:
ax.plot(angles, row_list2, color=kwargs['colors'], lw=0.5, alpha=0.5)
else:
ax.plot(angles, row_list2, color=kwargs['colors'][row_idx], lw=0.5)
if kwargs['avg']:
# get for average color
order = np.argsort(mean_cols)[::-1]
top_val = np.array(kwargs['cols'])[order][0]
avg_color = kwargs['palette'][top_val]
ax.plot(angles, mean_cols2, color=avg_color, lw=1, linestyle='solid', zorder=11)
ax.fill(angles, mean_cols2, avg_color, alpha=0.5, zorder=10)
ax.set_ylim(0, np.max(mean_cols2))
else:
ax.set_ylim(0, np.max(sub_data[kwargs['cols']].max()))
# tick labels
tick_labs = kwargs['cols']
ax.set_xticks(angles[:-1])
ax.set_xticklabels(tick_labs, color='black', size=10)
ax.set_yticks([])
return ax
def run_pairwise(df,
cann_cols, terp_cols):
df_sim = pd.DataFrame(columns=['cann','terp','all'])
for idx, cols in enumerate([cann_cols, terp_cols, cann_cols+terp_cols]):
if idx==2:
df[cols] = MinMaxScaler().fit_transform(df[cols].fillna(0))
sim_scores = cosine_similarity(df[cols].fillna(0))
sim_scores[sim_scores > 0.9999999999999] = np.nan
df_sim.iloc[:, idx] = np.nanmean(sim_scores, axis=0)
return df_sim
def get_scaled_dfs(df, cann, terps):
X_cann = df[cann].fillna(0)
X_cann_standard = MinMaxScaler().fit_transform(X_cann)
X_terps = df[terps].fillna(0)
X_terps_standard = MinMaxScaler().fit_transform(X_terps)
X_all = df[cann+terps].fillna(0)
X_all_standard = MinMaxScaler().fit_transform(X_all)
return X_cann, X_cann_standard, X_terps, X_terps_standard, X_all, X_all_standard
def avg_sd(a,b):
num = np.var(a)+np.var(b)
return np.sqrt(num/2)
def get_stats(df, pair, col):
x = df.loc[df[col]==pair[0], 'value']
y = df.loc[df[col]==pair[1], 'value']
ttest = scs.ttest_ind(x, y, equal_var=False)
d_prime = (x.mean()-y.mean())/avg_sd(x,y)
labels = []
if ttest[1] < 1e-300:
labels.append('p < 1e-300')
else:
labels.append('p = {:.1e}'.format(ttest[1]))
labels.append("d'="+str(np.round(np.abs(d_prime),2)))
return ', '.join(labels)
def get_prod_df(df, n_samp_min, n_prod_min,
common_cannabs,
common_terps):
n_samp_df = df.groupby(['anon_producer','strain_slug'])['u_id'].count()
df = df.merge(n_samp_df.rename('n_samp'), left_on=['anon_producer','strain_slug'], right_index=True)
# create producer df
prod_df = df.loc[(df['n_samp']>=n_samp_min)].groupby(['anon_producer','strain_slug'])[common_cannabs+common_terps].mean()
prod_df = get_ct(prod_df)
prod_df = prod_df.reset_index(drop=False)
# get n_prod counts
n_prod_df = prod_df.groupby('strain_slug')['anon_producer'].count()
prod_df = prod_df.merge(n_prod_df.rename('n_prod'), left_on='strain_slug', right_index=True)
prod_df = prod_df.merge(n_samp_df.rename('n_samps'), left_on=['anon_producer','strain_slug'], right_index=True)
# subset to n_prod_min and thc-dom
fin_prod_df = prod_df.loc[(prod_df['n_prod']>=n_prod_min)].sort_values(['n_prod','strain_slug','anon_producer'], ascending=[False, False, True]).copy()
fin_prod_df['strain_slug'] = fin_prod_df['strain_slug'].astype(str)
return fin_prod_df
def get_pal_dict(df, common_terps, terp_dict):
pal_dict = {}
for label in set(df['kmeans_label']):
terp_order = df.loc[df['kmeans_label']==label, common_terps].mean().sort_values(ascending=False)
pal_dict[label] = terp_dict[terp_order[:1].index[0]]
return pal_dict
def get_kmeans(df, common_terps,
k=3):
df_norm, arr, model = run_pca(df, common_terps, norm=True, n_components=3)
# set up kmeans
clust = KMeans(3, random_state=56)
# get cluster labels
df_norm['kmeans_label'] = clust.fit_predict(df_norm[common_terps])
clust_dict = {x:y for x,y in zip(df_norm['kmeans_label'].value_counts().index, ['A','B','C'])}
df_norm['kmeans_label'] = df_norm['kmeans_label'].replace(clust_dict)
return df_norm
def get_umap(df, common_terps,
n_neighbors=6,
random_state=56):
umap_ = UMAP(n_components=2, n_neighbors=n_neighbors,
random_state=random_state)
X_terps_umap = umap_.fit_transform(df[common_terps])
df['umap_0'] = X_terps_umap[:,0]
df['umap_1'] = X_terps_umap[:,1]
return df
def get_round(arr, sig_fig=1):
return np.round(arr*100,sig_fig)
def get_cos_sim(df, add_nan=False):
sim_scores = cosine_similarity(df)
if add_nan:
sim_scores[sim_scores > 0.9999999999999] = np.nan
else:
sim_scores[sim_scores > 0.9999999999999] = 1
return sim_scores
def group_cos_sim(df, group_level=False):
if df.shape[0]==1:
# if only one product, do not return cos sim
return np.nan
else:
sim_scores = get_cos_sim(df, add_nan=True)
if group_level:
return np.mean(np.nanmean(sim_scores, axis=0))
else:
return list(np.nanmean(sim_scores, axis=0))
def format_df(df):
return df.explode().to_frame().rename(columns={0:'bw_prod_sim'}).reset_index(drop=False)
def weighted_avg(avgs, weights):
return np.average(avgs, weights=weights)
def run_all_cos_sims(df, cols,
groupby='strain_slug'):
groups = df.groupby(groupby)[cols]
bw_prod_df = format_df(groups.apply(lambda x: group_cos_sim(x)))
avgs = groups.apply(lambda x: group_cos_sim(x, group_level=True))
weights = groups.size()[groups.size()>1]
return bw_prod_df, avgs, weights
def run_kde(df, ax, **kwargs):
no_nan = df.dropna(subset=[kwargs['x'], kwargs['y']], how='any')
sub_df = sample_df(no_nan, kwargs['sample_frac'])
_ = sns.kdeplot(x=kwargs['x'],
y=kwargs['y'],
data=sub_df,
fill=True,
cmap='RdBu_r',
cbar=True,
vmin=0,
levels=75,
ax=ax)
return ax
def run_line(df, ax, **kwargs):
_ = ax.plot(kwargs['x'], kwargs['y'])
return ax
def run_scatter_5(df, ax, **kwargs):
no_nan = df.dropna(subset=[kwargs['x'], kwargs['y']], how='any')
sub_df = sample_df(no_nan, kwargs['sample_frac'])
if 'size' in kwargs:
s = kwargs['size']
else:
s = mpl.rcParams['lines.markersize']**2
if 'edgecolor' in kwargs:
ec = kwargs['edgecolor']
else:
ec = 'white'
hue_order = ['THC-Dom', 'Bal THC/CBD', 'CBD-Dom']
s_colors = ['darkblue', 'steelblue', 'black']
s_markers = ['D', '^', 'o']
for ct, color, marker in zip(hue_order, s_colors, s_markers):
if ct=='THC-Dom':
sns.scatterplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df.loc[df['chemotype']==ct], alpha=.5,
color=color,
marker=marker,
s=25,
edgecolor='white',
linewidth=0.5,
label=ct,
ax=ax)
else:
sns.scatterplot(x=kwargs['x'], y=kwargs['y'],
data=sub_df.loc[df['chemotype']==ct], alpha=1,
color=color,
marker=marker,
s=25,
edgecolor='white',
linewidth=0.5,
label=ct,
ax=ax)
# include full ns
handles, labels = ax.get_legend_handles_labels()
if 'n_display' in kwargs:
labels_n = [(cat, df.loc[df[kwargs['hue']]==cat].shape[0]) for cat in hue_order]
labels = [cat+'\nn='+str(n) for cat, n in labels_n]
ax.legend(handles=handles[:kwargs['n_display']], labels=labels[:kwargs['n_display']], title=kwargs['hue'].title(), handlelength=4)
else:
labels_n = [(cat, df.loc[df[kwargs['hue']]==cat].shape[0]) for cat in hue_order]
labels = [cat+'\nn='+str(n) for cat, n in labels_n]
ax.legend(handles=handles, labels=labels, title=kwargs['hue'].title(), handlelength=4)
return ax
| [
"numpy.log10",
"numpy.sqrt",
"numpy.argsort",
"numpy.nanmean",
"sklearn.metrics.silhouette_samples",
"numpy.array",
"scipy.stats.ttest_ind",
"umap.UMAP",
"seaborn.violinplot",
"seaborn.scatterplot",
"matplotlib.patheffects.withStroke",
"numpy.arange",
"numpy.mean",
"seaborn.regplot",
"sk... | [((1130, 1163), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1153, 1163), False, 'import warnings\n'), ((1164, 1195), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (1185, 1195), False, 'import warnings\n'), ((1725, 1764), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': "kwargs['figsize']"}), "(figsize=kwargs['figsize'])\n", (1737, 1764), True, 'import matplotlib.pyplot as plt\n'), ((4215, 4233), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4231, 4233), True, 'import matplotlib.pyplot as plt\n'), ((6183, 6310), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'data': 'df', 'order': 'order', 'showcaps': '(False)', 'width': '(0.06)', 'fliersize': '(0.5)', 'ax': 'ax'}), "(x=kwargs['x'], y=kwargs['y'], data=df, order=order, showcaps=\n False, width=0.06, fliersize=0.5, ax=ax, **PROPS)\n", (6194, 6310), True, 'import seaborn as sns\n'), ((12079, 12122), 'numpy.log10', 'np.log10', (["df.loc[df['ratio'] != 0, 'ratio']"], {}), "(df.loc[df['ratio'] != 0, 'ratio'])\n", (12087, 12122), True, 'import numpy as np\n'), ((13719, 13768), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""darkblue"""', 'label': '"""THC-Dom"""'}), "(color='darkblue', label='THC-Dom')\n", (13733, 13768), True, 'import matplotlib.patches as mpatches\n'), ((13780, 13834), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""steelblue"""', 'label': '"""Bal THC/CBD"""'}), "(color='steelblue', label='Bal THC/CBD')\n", (13794, 13834), True, 'import matplotlib.patches as mpatches\n'), ((13846, 13892), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""black"""', 'label': '"""CBD-Dom"""'}), "(color='black', label='CBD-Dom')\n", (13860, 13892), True, 'import matplotlib.patches as mpatches\n'), ((16050, 16080), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'n_components'}), '(n_components=n_components)\n', (16053, 16080), False, 'from sklearn.decomposition import PCA\n'), ((17234, 17252), 'adjustText.adjust_text', 'adjust_text', (['texts'], {}), '(texts)\n', (17245, 17252), False, 'from adjustText import adjust_text\n'), ((17501, 17545), 'sklearn.metrics.silhouette_score', 'silhouette_score', (["df[kwargs['cols']]", 'labels'], {}), "(df[kwargs['cols']], labels)\n", (17517, 17545), False, 'from sklearn.metrics import silhouette_samples, silhouette_score\n'), ((17567, 17621), 'sklearn.metrics.silhouette_samples', 'silhouette_samples', (["sub_df[kwargs['cols']]", 'sub_labels'], {}), "(sub_df[kwargs['cols']], sub_labels)\n", (17585, 17621), False, 'from sklearn.metrics import silhouette_samples, silhouette_score\n'), ((18838, 18965), 'pandas.cut', 'pd.cut', (["df['chemotype_ratio']", '[-np.inf, 0.2, 5, np.inf]'], {'labels': "['CBD-Dom', 'Bal THC/CBD', 'THC-Dom']", 'include_lowest': '(True)'}), "(df['chemotype_ratio'], [-np.inf, 0.2, 5, np.inf], labels=['CBD-Dom',\n 'Bal THC/CBD', 'THC-Dom'], include_lowest=True)\n", (18844, 18965), True, 'import pandas as pd\n'), ((23450, 23495), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['cann', 'terp', 'all']"}), "(columns=['cann', 'terp', 'all'])\n", (23462, 23495), True, 'import pandas as pd\n'), ((24329, 24345), 'numpy.sqrt', 'np.sqrt', (['(num / 2)'], {}), '(num / 2)\n', (24336, 24345), True, 'import numpy as np\n'), ((24473, 24509), 'scipy.stats.ttest_ind', 'scs.ttest_ind', (['x', 'y'], {'equal_var': '(False)'}), '(x, y, equal_var=False)\n', (24486, 24509), True, 'import scipy.stats as scs\n'), ((26400, 26426), 'sklearn.cluster.KMeans', 'KMeans', (['(3)'], {'random_state': '(56)'}), '(3, random_state=56)\n', (26406, 26426), False, 'from sklearn.cluster import DBSCAN, KMeans, OPTICS\n'), ((26823, 26895), 'umap.UMAP', 'UMAP', ([], {'n_components': '(2)', 'n_neighbors': 'n_neighbors', 'random_state': 'random_state'}), '(n_components=2, n_neighbors=n_neighbors, random_state=random_state)\n', (26827, 26895), False, 'from umap import UMAP\n'), ((27109, 27137), 'numpy.round', 'np.round', (['(arr * 100)', 'sig_fig'], {}), '(arr * 100, sig_fig)\n', (27117, 27137), True, 'import numpy as np\n'), ((27190, 27211), 'sklearn.metrics.pairwise.cosine_similarity', 'cosine_similarity', (['df'], {}), '(df)\n', (27207, 27211), False, 'from sklearn.metrics.pairwise import cosine_distances, cosine_similarity\n'), ((27903, 27936), 'numpy.average', 'np.average', (['avgs'], {'weights': 'weights'}), '(avgs, weights=weights)\n', (27913, 27936), True, 'import numpy as np\n'), ((28454, 28576), 'seaborn.kdeplot', 'sns.kdeplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'data': 'sub_df', 'fill': '(True)', 'cmap': '"""RdBu_r"""', 'cbar': '(True)', 'vmin': '(0)', 'levels': '(75)', 'ax': 'ax'}), "(x=kwargs['x'], y=kwargs['y'], data=sub_df, fill=True, cmap=\n 'RdBu_r', cbar=True, vmin=0, levels=75, ax=ax)\n", (28465, 28576), True, 'import seaborn as sns\n'), ((5534, 5670), 'seaborn.violinplot', 'sns.violinplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'data': 'sub_df', 'scale': '"""width"""', 'order': 'order', 'palette': "kwargs['palette']", 'linewidth': '(0)', 'ax': 'ax'}), "(x=kwargs['x'], y=kwargs['y'], data=sub_df, scale='width',\n order=order, palette=kwargs['palette'], linewidth=0, ax=ax)\n", (5548, 5670), True, 'import seaborn as sns\n'), ((5754, 5887), 'seaborn.violinplot', 'sns.violinplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'data': 'sub_df', 'scale': '"""width"""', 'order': 'order', 'color': '"""lightslategray"""', 'linewidth': '(0)', 'ax': 'ax'}), "(x=kwargs['x'], y=kwargs['y'], data=sub_df, scale='width',\n order=order, color='lightslategray', linewidth=0, ax=ax)\n", (5768, 5887), True, 'import seaborn as sns\n'), ((9469, 9641), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'hue': "kwargs['hue']", 'data': 'sub_df', 's': 's', 'edgecolor': 'ec', 'alpha': '(0.5)', 'hue_order': 'hue_order', 'palette': "kwargs['palette']", 'ax': 'ax'}), "(x=kwargs['x'], y=kwargs['y'], hue=kwargs['hue'], data=\n sub_df, s=s, edgecolor=ec, alpha=0.5, hue_order=hue_order, palette=\n kwargs['palette'], ax=ax)\n", (9484, 9641), True, 'import seaborn as sns\n'), ((10533, 10707), 'seaborn.regplot', 'sns.regplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'data': 'sub_df', 'scatter_kws': "{'alpha': 0.1, 'color': 'lightslategray', 'rasterized': True}", 'line_kws': "{'color': 'orange'}", 'ax': 'ax'}), "(x=kwargs['x'], y=kwargs['y'], data=sub_df, scatter_kws={'alpha':\n 0.1, 'color': 'lightslategray', 'rasterized': True}, line_kws={'color':\n 'orange'}, ax=ax)\n", (10544, 10707), True, 'import seaborn as sns\n'), ((10800, 10855), 'scipy.stats.spearmanr', 'scs.spearmanr', (["no_nan[kwargs['x']]", "no_nan[kwargs['y']]"], {}), "(no_nan[kwargs['x']], no_nan[kwargs['y']])\n", (10813, 10855), True, 'import scipy.stats as scs\n'), ((12855, 12875), 'numpy.mean', 'np.mean', (['[low, high]'], {}), '([low, high])\n', (12862, 12875), True, 'import numpy as np\n'), ((14821, 14944), 'seaborn.barplot', 'sns.barplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'hue': "kwargs['hue']", 'data': 'df', 'palette': "kwargs['palette']", 'order': "kwargs['order']"}), "(x=kwargs['x'], y=kwargs['y'], hue=kwargs['hue'], data=df,\n palette=kwargs['palette'], order=kwargs['order'])\n", (14832, 14944), True, 'import seaborn as sns\n'), ((15407, 15512), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'data': 'df', 'palette': "kwargs['palette']", 'order': "kwargs['order']"}), "(x=kwargs['x'], y=kwargs['y'], data=df, palette=kwargs['palette'\n ], order=kwargs['order'])\n", (15418, 15512), True, 'import seaborn as sns\n'), ((15586, 15651), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'color': '"""lightslategray"""'}), "(x=kwargs['x'], y=kwargs['y'], color='lightslategray')\n", (15597, 15651), True, 'import seaborn as sns\n'), ((16196, 16241), 'numpy.apply_along_axis', 'np.apply_along_axis', (['max_min'], {'arr': 'arr', 'axis': '(0)'}), '(max_min, arr=arr, axis=0)\n', (16215, 16241), True, 'import numpy as np\n'), ((23809, 23839), 'numpy.nanmean', 'np.nanmean', (['sim_scores'], {'axis': '(0)'}), '(sim_scores, axis=0)\n', (23819, 23839), True, 'import numpy as np\n'), ((24298, 24307), 'numpy.var', 'np.var', (['a'], {}), '(a)\n', (24304, 24307), True, 'import numpy as np\n'), ((24308, 24317), 'numpy.var', 'np.var', (['b'], {}), '(b)\n', (24314, 24317), True, 'import numpy as np\n'), ((5037, 5095), 'pandas.melt', 'pd.melt', (["data.loc[:, kwargs['cols']]"], {'var_name': "kwargs['x']"}), "(data.loc[:, kwargs['cols']], var_name=kwargs['x'])\n", (5044, 5095), True, 'import pandas as pd\n'), ((5117, 5177), 'pandas.melt', 'pd.melt', (["sub_df.loc[:, kwargs['cols']]"], {'var_name': "kwargs['x']"}), "(sub_df.loc[:, kwargs['cols']], var_name=kwargs['x'])\n", (5124, 5177), True, 'import pandas as pd\n'), ((6810, 6844), 'itertools.combinations', 'itertools.combinations', (['order'], {'r': '(2)'}), '(order, r=2)\n', (6832, 6844), False, 'import itertools\n'), ((11373, 11570), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'data': "sub_df.loc[sub_df['strain_slug'] == strain]", 's': '(s + 35)', 'edgecolor': '"""black"""', 'linewidth': '(1.5)', 'color': 'color', 'label': 'strain', 'marker': 'marker', 'ax': 'ax'}), "(x=kwargs['x'], y=kwargs['y'], data=sub_df.loc[sub_df[\n 'strain_slug'] == strain], s=s + 35, edgecolor='black', linewidth=1.5,\n color=color, label=strain, marker=marker, ax=ax)\n", (11388, 11570), True, 'import seaborn as sns\n'), ((12723, 12768), 'numpy.arange', 'np.arange', (['(min_log - 0.1)', '(max_log + 0.1)', '(0.05)'], {}), '(min_log - 0.1, max_log + 0.1, 0.05)\n', (12732, 12768), True, 'import numpy as np\n'), ((12894, 12918), 'numpy.log10', 'np.log10', (['ct_thresh_high'], {}), '(ct_thresh_high)\n', (12902, 12918), True, 'import numpy as np\n'), ((13257, 13281), 'numpy.log10', 'np.log10', (['ct_thresh_high'], {}), '(ct_thresh_high)\n', (13265, 13281), True, 'import numpy as np\n'), ((13283, 13307), 'numpy.log10', 'np.log10', (['ct_thresh_high'], {}), '(ct_thresh_high)\n', (13291, 13307), True, 'import numpy as np\n'), ((13406, 13429), 'numpy.log10', 'np.log10', (['ct_thresh_low'], {}), '(ct_thresh_low)\n', (13414, 13429), True, 'import numpy as np\n'), ((13431, 13454), 'numpy.log10', 'np.log10', (['ct_thresh_low'], {}), '(ct_thresh_low)\n', (13439, 13454), True, 'import numpy as np\n'), ((15059, 15164), 'seaborn.barplot', 'sns.barplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'data': 'df', 'palette': "kwargs['palette']", 'order': "kwargs['order']"}), "(x=kwargs['x'], y=kwargs['y'], data=df, palette=kwargs['palette'\n ], order=kwargs['order'])\n", (15070, 15164), True, 'import seaborn as sns\n'), ((15238, 15303), 'seaborn.barplot', 'sns.barplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'color': '"""lightslategray"""'}), "(x=kwargs['x'], y=kwargs['y'], color='lightslategray')\n", (15249, 15303), True, 'import seaborn as sns\n'), ((16481, 16524), 'numpy.abs', 'np.abs', (["comp_df[[kwargs['x'], kwargs['y']]]"], {}), "(comp_df[[kwargs['x'], kwargs['y']]])\n", (16487, 16524), True, 'import numpy as np\n'), ((17968, 17995), 'numpy.arange', 'np.arange', (['y_lower', 'y_upper'], {}), '(y_lower, y_upper)\n', (17977, 17995), True, 'import numpy as np\n'), ((22773, 22794), 'numpy.argsort', 'np.argsort', (['mean_cols'], {}), '(mean_cols)\n', (22783, 22794), True, 'import numpy as np\n'), ((23092, 23110), 'numpy.max', 'np.max', (['mean_cols2'], {}), '(mean_cols2)\n', (23098, 23110), True, 'import numpy as np\n'), ((23951, 23965), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (23963, 23965), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler\n'), ((24046, 24060), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (24058, 24060), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler\n'), ((24143, 24157), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (24155, 24157), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler\n'), ((29433, 29623), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'data': "sub_df.loc[df['chemotype'] == ct]", 'alpha': '(0.5)', 'color': 'color', 'marker': 'marker', 's': '(25)', 'edgecolor': '"""white"""', 'linewidth': '(0.5)', 'label': 'ct', 'ax': 'ax'}), "(x=kwargs['x'], y=kwargs['y'], data=sub_df.loc[df[\n 'chemotype'] == ct], alpha=0.5, color=color, marker=marker, s=25,\n edgecolor='white', linewidth=0.5, label=ct, ax=ax)\n", (29448, 29623), True, 'import seaborn as sns\n'), ((29862, 30050), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': "kwargs['x']", 'y': "kwargs['y']", 'data': "sub_df.loc[df['chemotype'] == ct]", 'alpha': '(1)', 'color': 'color', 'marker': 'marker', 's': '(25)', 'edgecolor': '"""white"""', 'linewidth': '(0.5)', 'label': 'ct', 'ax': 'ax'}), "(x=kwargs['x'], y=kwargs['y'], data=sub_df.loc[df[\n 'chemotype'] == ct], alpha=1, color=color, marker=marker, s=25,\n edgecolor='white', linewidth=0.5, label=ct, ax=ax)\n", (29877, 30050), True, 'import seaborn as sns\n'), ((4652, 4728), 'pandas.melt', 'pd.melt', (["data.loc[:, kwargs['cols']]"], {'id_vars': '"""region"""', 'value_vars': '"""tot_thc"""'}), "(data.loc[:, kwargs['cols']], id_vars='region', value_vars='tot_thc')\n", (4659, 4728), True, 'import pandas as pd\n'), ((4793, 4878), 'pandas.melt', 'pd.melt', (["sub_data.loc[:, kwargs['cols']]"], {'id_vars': '"""region"""', 'value_vars': '"""tot_thc"""'}), "(sub_data.loc[:, kwargs['cols']], id_vars='region', value_vars='tot_thc'\n )\n", (4800, 4878), True, 'import pandas as pd\n'), ((12978, 13001), 'numpy.log10', 'np.log10', (['ct_thresh_low'], {}), '(ct_thresh_low)\n', (12986, 13001), True, 'import numpy as np\n'), ((22819, 22843), 'numpy.array', 'np.array', (["kwargs['cols']"], {}), "(kwargs['cols'])\n", (22827, 22843), True, 'import numpy as np\n'), ((27625, 27655), 'numpy.nanmean', 'np.nanmean', (['sim_scores'], {'axis': '(0)'}), '(sim_scores, axis=0)\n', (27635, 27655), True, 'import numpy as np\n'), ((27695, 27725), 'numpy.nanmean', 'np.nanmean', (['sim_scores'], {'axis': '(0)'}), '(sim_scores, axis=0)\n', (27705, 27725), True, 'import numpy as np\n'), ((20062, 20113), 'matplotlib.patheffects.withStroke', 'PathEffects.withStroke', ([], {'linewidth': '(4)', 'foreground': '"""w"""'}), "(linewidth=4, foreground='w')\n", (20084, 20113), True, 'import matplotlib.patheffects as PathEffects\n'), ((23613, 23627), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (23625, 23627), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler\n'), ((24744, 24759), 'numpy.abs', 'np.abs', (['d_prime'], {}), '(d_prime)\n', (24750, 24759), True, 'import numpy as np\n')] |
from itertools import chain
from django.db import models
from random import choices
class Node(object):
def neighbors(self):
raise NotImplementedError
def graph(self, depth=1):
if not depth:
return {self: set()}
elif depth == 1:
return {self: set(self.neighbors())}
else:
init = self.graph(depth=1)
for n in self.neighbors():
init.update(n.graph(depth - 1))
return init
def edges(self, depth=1):
self.g = self.graph(depth)
for vertex, edgelist in self.g.items():
for edge in edgelist:
yield (vertex, edge)
class Artist(models.Model, Node):
spotify_id = models.CharField(max_length=22, primary_key=True)
popularity = models.IntegerField(null=True)
name = models.CharField(max_length=30, default="")
# albums - ManyToManyField included in Album
# songs - ManyToManyField included in Song
# concerts = models.ManyToManyField(Concert)
def __str__(self):
return self.name + " (" + self.spotify_id + ")"
def neighbors(self):
#albums = (a for a in Album.objects.all() if self in a.artists.all())
#songs = Song.objects.filter(artist=self)
#return chain(albums, songs)
adj_songs = Song.objects.filter(artist=self)
if len(adj_songs) > 4:
return choices(Song.objects.filter(artist=self), k=4)
else:
return adj_songs
class Genre(models.Model):
name = models.CharField(max_length=30, primary_key=True)
artists = models.ManyToManyField(Artist)
# albums - ManyToManyField included in Album
# songs -
# In the spotify data, individual songs don't have genre
# data. We could extrapolate this from the album or artist genre
# data later though
class Album(models.Model, Node):
ALBUM = "A"
SINGLE = "S"
COMPILATION = "C"
ALBUM_TYPE_CHOICES = (
(ALBUM, "album"),
(SINGLE, "single"),
(COMPILATION, "compilation")
)
album_type = models.CharField(
max_length=1, choices=ALBUM_TYPE_CHOICES, default=ALBUM)
artists = models.ManyToManyField(Artist)
spotify_id = models.CharField(max_length=22, primary_key=True)
genres = models.ManyToManyField(Genre)
label = models.CharField(max_length=30, default="")
name = models.CharField(max_length=30, default="")
# Note this is going to come in
# as a string from the spotify
# API, so some conversion will
# have to be done
release_date = models.DateField(null=True)
def __str__(self):
return self.name + " (" + self.spotify_id + ")"
def neighbors(self):
songs = choices(Song.objects.filter(album=self), k=4)
return chain(self.artists.all(), songs)
class Song(models.Model, Node):
spotify_id = models.CharField(max_length=22, primary_key=True)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
album = models.ForeignKey(Album, null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=30, default="")
name = models.CharField(max_length=30, default="")
def __str__(self):
return self.title + " (" + self.spotify_id + ")"
def neighbors(self):
return [self.artist, self.album]
class Playlist(models.Model):
spotify_id = models.CharField(max_length=22, primary_key=True)
owner = models.ForeignKey('User', null=True, on_delete=models.CASCADE)
songs = models.ManyToManyField(Song)
collaborative = models.BooleanField(default=False)
description = models.CharField(max_length=5000, default="")
# followers - see ManyToManyField in User
name = models.CharField(max_length=30, default="")
public = models.BooleanField(default=True)
class RadioStation(models.Model):
pass
class Concert(models.Model):
pass
class User(models.Model):
# abstract = True
username = models.CharField(max_length=30, unique=True)
spotify_id = models.CharField(max_length=22, primary_key=True)
artist = models.ManyToManyField(Artist)
genre = models.ManyToManyField(Genre)
album = models.ManyToManyField(Album)
song = models.ManyToManyField(Song)
playlist_followed = models.ManyToManyField(Playlist)
radio_station = models.ManyToManyField(RadioStation)
friends = models.ForeignKey("self", on_delete=models.SET_NULL, null=True)
class Admin(User):
pass
class Regular(User):
pass
class Song_Graph(models.Model):
song1_id = models.CharField(max_length=22, null=True)
song2_id = models.CharField(max_length=22, null=True)
edge_weight = models.IntegerField(null=True)
class Meta:
unique_together = ("song1_id", "song2_id")
| [
"django.db.models.DateField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"django.db.models.CharField"
] | [((727, 776), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(22)', 'primary_key': '(True)'}), '(max_length=22, primary_key=True)\n', (743, 776), False, 'from django.db import models\n'), ((794, 824), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)'}), '(null=True)\n', (813, 824), False, 'from django.db import models\n'), ((836, 879), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'default': '""""""'}), "(max_length=30, default='')\n", (852, 879), False, 'from django.db import models\n'), ((1529, 1578), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'primary_key': '(True)'}), '(max_length=30, primary_key=True)\n', (1545, 1578), False, 'from django.db import models\n'), ((1593, 1623), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Artist'], {}), '(Artist)\n', (1615, 1623), False, 'from django.db import models\n'), ((2078, 2151), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(1)', 'choices': 'ALBUM_TYPE_CHOICES', 'default': 'ALBUM'}), '(max_length=1, choices=ALBUM_TYPE_CHOICES, default=ALBUM)\n', (2094, 2151), False, 'from django.db import models\n'), ((2175, 2205), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Artist'], {}), '(Artist)\n', (2197, 2205), False, 'from django.db import models\n'), ((2223, 2272), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(22)', 'primary_key': '(True)'}), '(max_length=22, primary_key=True)\n', (2239, 2272), False, 'from django.db import models\n'), ((2286, 2315), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Genre'], {}), '(Genre)\n', (2308, 2315), False, 'from django.db import models\n'), ((2328, 2371), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'default': '""""""'}), "(max_length=30, default='')\n", (2344, 2371), False, 'from django.db import models\n'), ((2383, 2426), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'default': '""""""'}), "(max_length=30, default='')\n", (2399, 2426), False, 'from django.db import models\n'), ((2575, 2602), 'django.db.models.DateField', 'models.DateField', ([], {'null': '(True)'}), '(null=True)\n', (2591, 2602), False, 'from django.db import models\n'), ((2870, 2919), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(22)', 'primary_key': '(True)'}), '(max_length=22, primary_key=True)\n', (2886, 2919), False, 'from django.db import models\n'), ((2933, 2984), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Artist'], {'on_delete': 'models.CASCADE'}), '(Artist, on_delete=models.CASCADE)\n', (2950, 2984), False, 'from django.db import models\n'), ((2997, 3058), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Album'], {'null': '(True)', 'on_delete': 'models.CASCADE'}), '(Album, null=True, on_delete=models.CASCADE)\n', (3014, 3058), False, 'from django.db import models\n'), ((3071, 3114), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'default': '""""""'}), "(max_length=30, default='')\n", (3087, 3114), False, 'from django.db import models\n'), ((3126, 3169), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'default': '""""""'}), "(max_length=30, default='')\n", (3142, 3169), False, 'from django.db import models\n'), ((3367, 3416), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(22)', 'primary_key': '(True)'}), '(max_length=22, primary_key=True)\n', (3383, 3416), False, 'from django.db import models\n'), ((3429, 3491), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""User"""'], {'null': '(True)', 'on_delete': 'models.CASCADE'}), "('User', null=True, on_delete=models.CASCADE)\n", (3446, 3491), False, 'from django.db import models\n'), ((3504, 3532), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Song'], {}), '(Song)\n', (3526, 3532), False, 'from django.db import models\n'), ((3553, 3587), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (3572, 3587), False, 'from django.db import models\n'), ((3606, 3651), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(5000)', 'default': '""""""'}), "(max_length=5000, default='')\n", (3622, 3651), False, 'from django.db import models\n'), ((3709, 3752), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'default': '""""""'}), "(max_length=30, default='')\n", (3725, 3752), False, 'from django.db import models\n'), ((3766, 3799), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (3785, 3799), False, 'from django.db import models\n'), ((3951, 3995), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'unique': '(True)'}), '(max_length=30, unique=True)\n', (3967, 3995), False, 'from django.db import models\n'), ((4013, 4062), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(22)', 'primary_key': '(True)'}), '(max_length=22, primary_key=True)\n', (4029, 4062), False, 'from django.db import models\n'), ((4076, 4106), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Artist'], {}), '(Artist)\n', (4098, 4106), False, 'from django.db import models\n'), ((4119, 4148), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Genre'], {}), '(Genre)\n', (4141, 4148), False, 'from django.db import models\n'), ((4161, 4190), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Album'], {}), '(Album)\n', (4183, 4190), False, 'from django.db import models\n'), ((4202, 4230), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Song'], {}), '(Song)\n', (4224, 4230), False, 'from django.db import models\n'), ((4255, 4287), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Playlist'], {}), '(Playlist)\n', (4277, 4287), False, 'from django.db import models\n'), ((4308, 4344), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['RadioStation'], {}), '(RadioStation)\n', (4330, 4344), False, 'from django.db import models\n'), ((4359, 4422), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""self"""'], {'on_delete': 'models.SET_NULL', 'null': '(True)'}), "('self', on_delete=models.SET_NULL, null=True)\n", (4376, 4422), False, 'from django.db import models\n'), ((4534, 4576), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(22)', 'null': '(True)'}), '(max_length=22, null=True)\n', (4550, 4576), False, 'from django.db import models\n'), ((4592, 4634), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(22)', 'null': '(True)'}), '(max_length=22, null=True)\n', (4608, 4634), False, 'from django.db import models\n'), ((4653, 4683), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)'}), '(null=True)\n', (4672, 4683), False, 'from django.db import models\n')] |
#!/usr/bin/env python3
"""
OCR with the Tesseract engine from Google
this is a wrapper around pytesser (http://code.google.com/p/pytesser/)
"""
import config as cfg
from lib.process import get_simple_cmd_output
def image_file_to_string(fname):
"""Convert an image file to text using OCR."""
cmd = "{tesseract} {fname} stdout".format(
tesseract=cfg.TESSERACT,
fname=fname
)
return get_simple_cmd_output(cmd).rstrip('\n')
| [
"lib.process.get_simple_cmd_output"
] | [((416, 442), 'lib.process.get_simple_cmd_output', 'get_simple_cmd_output', (['cmd'], {}), '(cmd)\n', (437, 442), False, 'from lib.process import get_simple_cmd_output\n')] |
"""empty message
Revision ID: 0e26a2d71475
Revises:
Create Date: 2021-03-19 00:13:23.019330
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0e26a2d71475'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_unique_constraint(None, 'audio_book', ['id'])
op.create_unique_constraint(None, 'podcast', ['id'])
op.create_unique_constraint(None, 'song', ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'song', type_='unique')
op.drop_constraint(None, 'podcast', type_='unique')
op.drop_constraint(None, 'audio_book', type_='unique')
# ### end Alembic commands ###
| [
"alembic.op.drop_constraint",
"alembic.op.create_unique_constraint"
] | [((362, 417), 'alembic.op.create_unique_constraint', 'op.create_unique_constraint', (['None', '"""audio_book"""', "['id']"], {}), "(None, 'audio_book', ['id'])\n", (389, 417), False, 'from alembic import op\n'), ((422, 474), 'alembic.op.create_unique_constraint', 'op.create_unique_constraint', (['None', '"""podcast"""', "['id']"], {}), "(None, 'podcast', ['id'])\n", (449, 474), False, 'from alembic import op\n'), ((479, 528), 'alembic.op.create_unique_constraint', 'op.create_unique_constraint', (['None', '"""song"""', "['id']"], {}), "(None, 'song', ['id'])\n", (506, 528), False, 'from alembic import op\n'), ((653, 701), 'alembic.op.drop_constraint', 'op.drop_constraint', (['None', '"""song"""'], {'type_': '"""unique"""'}), "(None, 'song', type_='unique')\n", (671, 701), False, 'from alembic import op\n'), ((706, 757), 'alembic.op.drop_constraint', 'op.drop_constraint', (['None', '"""podcast"""'], {'type_': '"""unique"""'}), "(None, 'podcast', type_='unique')\n", (724, 757), False, 'from alembic import op\n'), ((762, 816), 'alembic.op.drop_constraint', 'op.drop_constraint', (['None', '"""audio_book"""'], {'type_': '"""unique"""'}), "(None, 'audio_book', type_='unique')\n", (780, 816), False, 'from alembic import op\n')] |
import helper
from helper import greeting
def main():
#print("called hello")
helper.greeting("hello")
if __name__ == '__main__':
main() | [
"helper.greeting"
] | [((80, 104), 'helper.greeting', 'helper.greeting', (['"""hello"""'], {}), "('hello')\n", (95, 104), False, 'import helper\n')] |
# команда меню "права пользователей"
from aiogram.types import Message, CallbackQuery, ReplyKeyboardRemove
from filters import IsAdmin
from loader import dp, db, bot
from keyboards.inline.callback_data import change_button_data
from keyboards.inline.callback_data import set_status_data
from keyboards.inline.callback_data import group_users_data
@dp.message_handler(IsAdmin(), text='права пользователей')
async def rights_users(message:Message):
from keyboards.inline.group_users_buttons import create_kb_groups_users
await message.delete()
kb_groups_users = create_kb_groups_users()
await message.answer('ГРУППЫ ПОЛЬЗОВАТЕЛЕЙ:', reply_markup=kb_groups_users)
@dp.callback_query_handler(IsAdmin(), group_users_data.filter(handler='statuses'))
async def get_groups(call:CallbackQuery):
from keyboards.inline.group_users_buttons import create_kb_particular_group
await call.answer()
await call.message.delete()
print(call.data)
user_data = group_users_data.parse(call.data)
# Example of result group_users_data.parse(call.data):
# {'@': 'gud', 'group': 'admin', 'handler': 'statuses'}
all_statuses = {
'admin': 'АДМИНИСТРАТОРЫ:',
'changer': 'ЧЕЙНДЖИ:',
'operator': 'ОПЕРАТОРЫ:',
'secretary': 'СЕКРЕТАРИ:',
'executor': 'ИСПОЛНИТЕЛИ:',
'permit': 'НА ПРОПУСК:',
'request': 'В СТАТУСЕ "ЗАПРОС":',
'block': 'ЗАБЛОКИРОВАННЫ:'
}
for status in all_statuses.keys():
if user_data['group'] == status:
text = all_statuses[status]
kb_particular_group = create_kb_particular_group(user_data['group'])
await call.message.answer(text, reply_markup=kb_particular_group)
@dp.callback_query_handler(IsAdmin(), change_button_data.filter(type_button='change_button'))
async def change_status(call:CallbackQuery):
await call.answer()
await call.message.delete()
user_data = change_button_data.parse(call.data)
# Example of result change_button_data.parse(call.data):
# {'@': 'change_button', 'user_id': '1637852195', 'type_button': 'change_button'}
from keyboards.inline.avalible_rights_users_kb import create_kb_change_status_handler
keyboard = create_kb_change_status_handler(user_data)
print('@dp.callback_query_handler()')
print('user_name = db.get_user_name(user_data["user_id"])')
user_name = db.get_user_name(user_data['user_id'])
await call.message.answer(f'НОВЫЕ ПРАВА для {user_name}:', reply_markup=keyboard)
# await bot.send_message (
# chat_id = call.message.chat.id,
# text='введите сумму:'
# )
@dp.callback_query_handler(IsAdmin(), set_status_data.filter(type_btn='set_st_btn'))
async def set_status(call:CallbackQuery):
from keyboards.default.admin_keyboard import create_kb_coustom_main_menu
await call.answer()
await call.message.delete()
user_id = call.message.from_user.id
user_data = set_status_data.parse(call.data)
# Example of result set_status_data.parse(call.data):
# {'@': 'ssb', 'id': '1637852195', 'new_st': 'admin', 'type_btn': 'set_st_btn'}
print('callback_query_handler, db.get_user_name')
user_name = db.get_user_name(user_data['id'])
if user_data['new_st'] == 'delete':
print('@dp.callback_query_handler(set_status_data.filter(type_button=\'set_status_btn\'))')
db.delete_user(user_data['id'])
# await call.answer(f'пользователь {user_data["user_name"]} удален', show_alert=True)
await call.message.reply(f'пользователь {user_name} УДАЛЕН', reply_markup=create_kb_coustom_main_menu(user_id))
else:
print('@dp.callback_query_handler(set_status_data.filter(type_button=\'set_status_btn\'))')
db.update_status(user_data['new_st'], user_data['id'])
list_rights = {
'admin': 'администратор',
'changer': 'чейндж',
'operator': 'оператор',
'secretary': 'секретарь',
'executor': 'исполнитель',
'permit': 'на пропуск',
'request': 'в статус "запрос"',
'block': 'заблокировать',
'delete': 'удалить'
}
# await call.answer(f'статус установлен', show_alert=True)
await call.message.answer(f'пользователь {user_name} теперь - {list_rights[user_data["new_st"]].upper()}', reply_markup=create_kb_coustom_main_menu(user_id))
await bot.send_message (
chat_id = user_data['id'],
text=f'Ваши права - {list_rights[user_data["new_st"]].upper()}. Используйте меню.',
reply_markup=create_kb_coustom_main_menu(user_data['id'])
)
| [
"filters.IsAdmin",
"loader.db.delete_user",
"keyboards.default.admin_keyboard.create_kb_coustom_main_menu",
"keyboards.inline.callback_data.set_status_data.parse",
"keyboards.inline.callback_data.change_button_data.parse",
"loader.db.update_status",
"keyboards.inline.callback_data.group_users_data.filte... | [((579, 603), 'keyboards.inline.group_users_buttons.create_kb_groups_users', 'create_kb_groups_users', ([], {}), '()\n', (601, 603), False, 'from keyboards.inline.group_users_buttons import create_kb_groups_users\n'), ((371, 380), 'filters.IsAdmin', 'IsAdmin', ([], {}), '()\n', (378, 380), False, 'from filters import IsAdmin\n'), ((987, 1020), 'keyboards.inline.callback_data.group_users_data.parse', 'group_users_data.parse', (['call.data'], {}), '(call.data)\n', (1009, 1020), False, 'from keyboards.inline.callback_data import group_users_data\n'), ((1602, 1648), 'keyboards.inline.group_users_buttons.create_kb_particular_group', 'create_kb_particular_group', (["user_data['group']"], {}), "(user_data['group'])\n", (1628, 1648), False, 'from keyboards.inline.group_users_buttons import create_kb_particular_group\n'), ((714, 723), 'filters.IsAdmin', 'IsAdmin', ([], {}), '()\n', (721, 723), False, 'from filters import IsAdmin\n'), ((725, 768), 'keyboards.inline.callback_data.group_users_data.filter', 'group_users_data.filter', ([], {'handler': '"""statuses"""'}), "(handler='statuses')\n", (748, 768), False, 'from keyboards.inline.callback_data import group_users_data\n'), ((1934, 1969), 'keyboards.inline.callback_data.change_button_data.parse', 'change_button_data.parse', (['call.data'], {}), '(call.data)\n', (1958, 1969), False, 'from keyboards.inline.callback_data import change_button_data\n'), ((2224, 2266), 'keyboards.inline.avalible_rights_users_kb.create_kb_change_status_handler', 'create_kb_change_status_handler', (['user_data'], {}), '(user_data)\n', (2255, 2266), False, 'from keyboards.inline.avalible_rights_users_kb import create_kb_change_status_handler\n'), ((2390, 2428), 'loader.db.get_user_name', 'db.get_user_name', (["user_data['user_id']"], {}), "(user_data['user_id'])\n", (2406, 2428), False, 'from loader import dp, db, bot\n'), ((1749, 1758), 'filters.IsAdmin', 'IsAdmin', ([], {}), '()\n', (1756, 1758), False, 'from filters import IsAdmin\n'), ((1760, 1814), 'keyboards.inline.callback_data.change_button_data.filter', 'change_button_data.filter', ([], {'type_button': '"""change_button"""'}), "(type_button='change_button')\n", (1785, 1814), False, 'from keyboards.inline.callback_data import change_button_data\n'), ((2954, 2986), 'keyboards.inline.callback_data.set_status_data.parse', 'set_status_data.parse', (['call.data'], {}), '(call.data)\n', (2975, 2986), False, 'from keyboards.inline.callback_data import set_status_data\n'), ((3200, 3233), 'loader.db.get_user_name', 'db.get_user_name', (["user_data['id']"], {}), "(user_data['id'])\n", (3216, 3233), False, 'from loader import dp, db, bot\n'), ((2657, 2666), 'filters.IsAdmin', 'IsAdmin', ([], {}), '()\n', (2664, 2666), False, 'from filters import IsAdmin\n'), ((2668, 2713), 'keyboards.inline.callback_data.set_status_data.filter', 'set_status_data.filter', ([], {'type_btn': '"""set_st_btn"""'}), "(type_btn='set_st_btn')\n", (2690, 2713), False, 'from keyboards.inline.callback_data import set_status_data\n'), ((3387, 3418), 'loader.db.delete_user', 'db.delete_user', (["user_data['id']"], {}), "(user_data['id'])\n", (3401, 3418), False, 'from loader import dp, db, bot\n'), ((3753, 3807), 'loader.db.update_status', 'db.update_status', (["user_data['new_st']", "user_data['id']"], {}), "(user_data['new_st'], user_data['id'])\n", (3769, 3807), False, 'from loader import dp, db, bot\n'), ((3614, 3650), 'keyboards.default.admin_keyboard.create_kb_coustom_main_menu', 'create_kb_coustom_main_menu', (['user_id'], {}), '(user_id)\n', (3641, 3650), False, 'from keyboards.default.admin_keyboard import create_kb_coustom_main_menu\n'), ((4391, 4427), 'keyboards.default.admin_keyboard.create_kb_coustom_main_menu', 'create_kb_coustom_main_menu', (['user_id'], {}), '(user_id)\n', (4418, 4427), False, 'from keyboards.default.admin_keyboard import create_kb_coustom_main_menu\n'), ((4604, 4648), 'keyboards.default.admin_keyboard.create_kb_coustom_main_menu', 'create_kb_coustom_main_menu', (["user_data['id']"], {}), "(user_data['id'])\n", (4631, 4648), False, 'from keyboards.default.admin_keyboard import create_kb_coustom_main_menu\n')] |
from pageobject import PageObject
from homepage import HomePage
from locatormap import LocatorMap
from robot.api import logger
class LoginPage():
PAGE_TITLE = "Login - PageObjectLibrary Demo"
PAGE_URL = "/login.html"
# these are accessible via dot notaton with self.locator
# (eg: self.locator.username, etc)
_locators = {
"username": "id=id_username",
"password": "<PASSWORD>",
"submit_button": "id=id_submit",
}
def __init__(self):
self.logger = logger
self.po = PageObject()
self.se2lib = self.po.se2lib
self.locator = LocatorMap(getattr(self, "_locators", {}))
def navigate_to(self, url):
logger.console ("Navigating to %s".format(url))
self.se2lib.go_to(url)
if 'yahoo' in url:
logger.console ("Navigating to homepage")
return HomePage()
def create_browser(self, browser_name):
self.se2lib.create_webdriver(browser_name)
def enter_username(self, username):
"""Enter the given string into the username field"""
self.se2lib.input_text(self.locator.username, username)
def enter_password(self, password):
"""Enter the given string into the password field"""
self.se2lib.input_text(self.locator.password, password)
def click_the_submit_button(self):
"""Click the submit button, and wait for the page to reload"""
with self.po._wait_for_page_refresh():
self.se2lib.click_button(self.locator.submit_button)
return HomePage() | [
"robot.api.logger.console",
"homepage.HomePage",
"pageobject.PageObject"
] | [((539, 551), 'pageobject.PageObject', 'PageObject', ([], {}), '()\n', (549, 551), False, 'from pageobject import PageObject\n'), ((814, 854), 'robot.api.logger.console', 'logger.console', (['"""Navigating to homepage"""'], {}), "('Navigating to homepage')\n", (828, 854), False, 'from robot.api import logger\n'), ((875, 885), 'homepage.HomePage', 'HomePage', ([], {}), '()\n', (883, 885), False, 'from homepage import HomePage\n'), ((1560, 1570), 'homepage.HomePage', 'HomePage', ([], {}), '()\n', (1568, 1570), False, 'from homepage import HomePage\n')] |
'''Maps buttons for the Reefbot control.'''
import roslib; roslib.load_manifest('reefbot-controller')
import rospy
class JoystickButtons:
DPAD_LR = 4
DPAD_UD = 5
ALOG_LEFT_UD = 1
ALOG_LEFT_LR = 0
ALOG_RIGHT_UD = 3
ALOG_RIGHT_LR = 2
BUTTON_1 = 0
BUTTON_2 = 1
BUTTON_3 = 2
BUTTON_4 = 3
BUTTON_5 = 4
BUTTON_6 = 5
BUTTON_7 = 6
BUTTON_8 = 7
BUTTON_9 = 8
BUTTON_10 = 9
BUTTON_11 = 10
BUTTON_12 = 11
class ButtonMapper:
def __init__(self):
self.diveDownButton = rospy.get_param("~dive_down_button",
JoystickButtons.BUTTON_7)
self.diveUpButton = rospy.get_param("~dive_up_button",
JoystickButtons.BUTTON_5)
self.diveAxis = rospy.get_param("~dive_axis", None)
self.leftTurnButton = rospy.get_param("~left_turn_button", None)
self.rightTurnButton = rospy.get_param("~right_turn_button", None)
self.turnAxis = rospy.get_param("~turn_axis",
JoystickButtons.ALOG_LEFT_LR)
self.fwdButton = rospy.get_param("~fwd_button", None)
self.backButton = rospy.get_param("~back_button", None)
self.fwdBackAxis = rospy.get_param("~fwd_back_axis",
JoystickButtons.ALOG_LEFT_UD)
def GetFwdAxis(self, joyMsg):
'''Returns the value of the move fwd/backward axis. +1 is full forward.'''
return self._GetAxisValue(joyMsg, self.fwdBackAxis, self.fwdButton,
self.backButton)
def GetTurnAxis(self, joyMsg):
'''Returns the value of the turning axis. +1 is full left.'''
return self._GetAxisValue(joyMsg, self.turnAxis, self.leftTurnButton,
self.rightTurnButton)
def GetDiveAxis(self, joyMsg):
'''Returns the value of the dive axis. +1 is full up.'''
return self._GetAxisValue(joyMsg, self.diveAxis, self.diveUpButton,
self.diveDownButton)
def _GetAxisValue(self, joyMsg, axis, posButton, negButton):
if axis is not None and axis >= 0:
return joyMsg.axes[axis]
axisVal = 0.
if joyMsg.buttons[posButton] and not joyMsg.buttons[negButton]:
axisVal = 1.
if not joyMsg.buttons[posButton] and joyMsg.buttons[negButton]:
axisVal = -1.
return axisVal
def GetCeilingDisable(self, joyMsg):
'''Returns the value of the button that disables the ceiling.'''
return self._GetButtonValue(joyMsg, JoystickButtons.BUTTON_10)
def _GetButtonValue(self, joyMsg, button):
return joyMsg.buttons[button]
| [
"rospy.get_param",
"roslib.load_manifest"
] | [((60, 102), 'roslib.load_manifest', 'roslib.load_manifest', (['"""reefbot-controller"""'], {}), "('reefbot-controller')\n", (80, 102), False, 'import roslib\n'), ((505, 567), 'rospy.get_param', 'rospy.get_param', (['"""~dive_down_button"""', 'JoystickButtons.BUTTON_7'], {}), "('~dive_down_button', JoystickButtons.BUTTON_7)\n", (520, 567), False, 'import rospy\n'), ((634, 694), 'rospy.get_param', 'rospy.get_param', (['"""~dive_up_button"""', 'JoystickButtons.BUTTON_5'], {}), "('~dive_up_button', JoystickButtons.BUTTON_5)\n", (649, 694), False, 'import rospy\n'), ((755, 790), 'rospy.get_param', 'rospy.get_param', (['"""~dive_axis"""', 'None'], {}), "('~dive_axis', None)\n", (770, 790), False, 'import rospy\n'), ((817, 859), 'rospy.get_param', 'rospy.get_param', (['"""~left_turn_button"""', 'None'], {}), "('~left_turn_button', None)\n", (832, 859), False, 'import rospy\n'), ((887, 930), 'rospy.get_param', 'rospy.get_param', (['"""~right_turn_button"""', 'None'], {}), "('~right_turn_button', None)\n", (902, 930), False, 'import rospy\n'), ((951, 1010), 'rospy.get_param', 'rospy.get_param', (['"""~turn_axis"""', 'JoystickButtons.ALOG_LEFT_LR'], {}), "('~turn_axis', JoystickButtons.ALOG_LEFT_LR)\n", (966, 1010), False, 'import rospy\n'), ((1068, 1104), 'rospy.get_param', 'rospy.get_param', (['"""~fwd_button"""', 'None'], {}), "('~fwd_button', None)\n", (1083, 1104), False, 'import rospy\n'), ((1127, 1164), 'rospy.get_param', 'rospy.get_param', (['"""~back_button"""', 'None'], {}), "('~back_button', None)\n", (1142, 1164), False, 'import rospy\n'), ((1188, 1251), 'rospy.get_param', 'rospy.get_param', (['"""~fwd_back_axis"""', 'JoystickButtons.ALOG_LEFT_UD'], {}), "('~fwd_back_axis', JoystickButtons.ALOG_LEFT_UD)\n", (1203, 1251), False, 'import rospy\n')] |
import os
from datetime import datetime
from PIL import Image, ImageDraw, ImageFont
from pySmartDL import SmartDL
from telethon.tl import functions
from uniborg.util import admin_cmd
import asyncio
import shutil
import random, re
FONT_FILE_TO_USE = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
#Add telegraph media links of profile pics that are to be used
TELEGRAPH_MEDIA_LINKS = ["https://telegra.ph/file/2bc2e85fb6b256efc4088.jpg",
"https://telegra.ph/file/443fff8a7db51d390e1a7.jpg",
"https://telegra.ph/file/e49bbb9e21383f8231d85.jpg",
"https://telegra.ph/file/d6875213197a9d93ff181.jpg",
"https://telegra.ph/file/ec7da24872002e75e6af8.jpg",
"https://telegra.ph/file/468a2af386d10cd45df8f.jpg",
"https://telegra.ph/file/59c7ce59289d80f1fe830.jpg"
]
@borg.on(admin_cmd(pattern="thordp ?(.*)"))
async def autopic(event):
while True:
piclink = random.randint(0, len(TELEGRAPH_MEDIA_LINKS) - 1)
AUTOPP = TELEGRAPH_MEDIA_LINKS[piclink]
downloaded_file_name = "./ravana/original_pic.png"
downloader = SmartDL(AUTOPP, downloaded_file_name, progress_bar=True)
downloader.start(blocking=False)
photo = "photo_pfp.png"
while not downloader.isFinished():
place_holder = None
shutil.copy(downloaded_file_name, photo)
im = Image.open(photo)
current_time = datetime.now().strftime("@MrSemmy \n \nTime: %H:%M:%S \nDate: %d/%m/%y")
img = Image.open(photo)
drawn_text = ImageDraw.Draw(img)
fnt = ImageFont.truetype(FONT_FILE_TO_USE, 30)
drawn_text.text((30, 50), current_time, font=fnt, fill=(102, 209, 52))
img.save(photo)
file = await event.client.upload_file(photo) # pylint:disable=E0602
try:
await event.client(functions.photos.DeletePhotosRequest(await event.client.get_profile_photos("me", limit=1)))
await event.client(functions.photos.UploadProfilePhotoRequest( # pylint:disable=E0602
file
))
os.remove(photo)
await asyncio.sleep(600)
except:
return
| [
"uniborg.util.admin_cmd",
"PIL.Image.open",
"asyncio.sleep",
"telethon.tl.functions.photos.UploadProfilePhotoRequest",
"PIL.ImageFont.truetype",
"datetime.datetime.now",
"PIL.ImageDraw.Draw",
"shutil.copy",
"pySmartDL.SmartDL",
"os.remove"
] | [((948, 981), 'uniborg.util.admin_cmd', 'admin_cmd', ([], {'pattern': '"""thordp ?(.*)"""'}), "(pattern='thordp ?(.*)')\n", (957, 981), False, 'from uniborg.util import admin_cmd\n'), ((1221, 1277), 'pySmartDL.SmartDL', 'SmartDL', (['AUTOPP', 'downloaded_file_name'], {'progress_bar': '(True)'}), '(AUTOPP, downloaded_file_name, progress_bar=True)\n', (1228, 1277), False, 'from pySmartDL import SmartDL\n'), ((1444, 1484), 'shutil.copy', 'shutil.copy', (['downloaded_file_name', 'photo'], {}), '(downloaded_file_name, photo)\n', (1455, 1484), False, 'import shutil\n'), ((1498, 1515), 'PIL.Image.open', 'Image.open', (['photo'], {}), '(photo)\n', (1508, 1515), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1626, 1643), 'PIL.Image.open', 'Image.open', (['photo'], {}), '(photo)\n', (1636, 1643), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1665, 1684), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (1679, 1684), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1699, 1739), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['FONT_FILE_TO_USE', '(30)'], {}), '(FONT_FILE_TO_USE, 30)\n', (1717, 1739), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2203, 2219), 'os.remove', 'os.remove', (['photo'], {}), '(photo)\n', (2212, 2219), False, 'import os\n'), ((1539, 1553), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1551, 1553), False, 'from datetime import datetime\n'), ((2251, 2269), 'asyncio.sleep', 'asyncio.sleep', (['(600)'], {}), '(600)\n', (2264, 2269), False, 'import asyncio\n'), ((2087, 2135), 'telethon.tl.functions.photos.UploadProfilePhotoRequest', 'functions.photos.UploadProfilePhotoRequest', (['file'], {}), '(file)\n', (2129, 2135), False, 'from telethon.tl import functions\n')] |
import random
import numpy as np
import torch
from torch import nn
from torchbenchmark.tasks import OTHER
from ...util.model import BenchmarkModel
torch.manual_seed(1337)
random.seed(1337)
np.random.seed(1337)
# pretend we are using MLP to predict CIFAR images
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.main = nn.Sequential(
nn.Flatten(),
nn.Linear(3 * 32 * 32, 1024),
nn.ReLU(),
nn.Linear(1024, 1024),
nn.ReLU(),
nn.Linear(1024, 1024),
nn.ReLU(),
nn.Linear(1024, 1024),
nn.ReLU(),
nn.Linear(1024, 10),
nn.Softmax(dim=-1),
)
def forward(self, x):
return self.main(x)
class Model(BenchmarkModel):
task = OTHER.OTHER_TASKS
def __init__(self, device='cpu', jit=False, lr=1e-4, weight_decay=1e-4):
super().__init__()
self.device = device
self.jit = jit
batch_size = 4096
# mimic a normalized image
self.sample_inputs = torch.randn(batch_size, 3, 32,
32).clamp_(-1, 1).to(device)
self.sample_targets = torch.randint(0, 10, (batch_size, )).to(device)
self.model = MLP().to(device)
self.optimizer = torch.optim.Adam(self.model.parameters(),
lr=lr,
weight_decay=weight_decay)
self.criterion = nn.CrossEntropyLoss()
def train(self, niter=1):
if self.jit:
raise NotImplementedError()
self.model.train()
for _ in range(niter):
out = self.model(self.sample_inputs)
self.optimizer.zero_grad()
loss = self.criterion(out, self.sample_targets)
loss.backward()
self.optimizer.step()
def eval(self, niter=1):
if self.jit:
raise NotImplementedError()
self.model.eval()
with torch.no_grad():
for _ in range(niter):
out = self.model(self.sample_inputs)
def get_module(self):
if self.jit:
raise NotImplementedError()
return self.model, self.sample_inputs
if __name__ == '__main__':
for device in ['cpu', 'cuda']:
print("Testing device {}, JIT {}".format(device, False))
m = Model(device=device, jit=False)
m.train()
m.eval()
| [
"torch.manual_seed",
"torch.nn.ReLU",
"torch.nn.CrossEntropyLoss",
"torch.nn.Softmax",
"torch.nn.Flatten",
"random.seed",
"torch.randint",
"numpy.random.seed",
"torch.nn.Linear",
"torch.no_grad",
"torch.randn"
] | [((150, 173), 'torch.manual_seed', 'torch.manual_seed', (['(1337)'], {}), '(1337)\n', (167, 173), False, 'import torch\n'), ((174, 191), 'random.seed', 'random.seed', (['(1337)'], {}), '(1337)\n', (185, 191), False, 'import random\n'), ((192, 212), 'numpy.random.seed', 'np.random.seed', (['(1337)'], {}), '(1337)\n', (206, 212), True, 'import numpy as np\n'), ((1507, 1528), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1526, 1528), False, 'from torch import nn\n'), ((388, 400), 'torch.nn.Flatten', 'nn.Flatten', ([], {}), '()\n', (398, 400), False, 'from torch import nn\n'), ((414, 442), 'torch.nn.Linear', 'nn.Linear', (['(3 * 32 * 32)', '(1024)'], {}), '(3 * 32 * 32, 1024)\n', (423, 442), False, 'from torch import nn\n'), ((456, 465), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (463, 465), False, 'from torch import nn\n'), ((479, 500), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(1024)'], {}), '(1024, 1024)\n', (488, 500), False, 'from torch import nn\n'), ((514, 523), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (521, 523), False, 'from torch import nn\n'), ((537, 558), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(1024)'], {}), '(1024, 1024)\n', (546, 558), False, 'from torch import nn\n'), ((572, 581), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (579, 581), False, 'from torch import nn\n'), ((595, 616), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(1024)'], {}), '(1024, 1024)\n', (604, 616), False, 'from torch import nn\n'), ((630, 639), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (637, 639), False, 'from torch import nn\n'), ((653, 672), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(10)'], {}), '(1024, 10)\n', (662, 672), False, 'from torch import nn\n'), ((686, 704), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (696, 704), False, 'from torch import nn\n'), ((2021, 2036), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2034, 2036), False, 'import torch\n'), ((1210, 1245), 'torch.randint', 'torch.randint', (['(0)', '(10)', '(batch_size,)'], {}), '(0, 10, (batch_size,))\n', (1223, 1245), False, 'import torch\n'), ((1079, 1113), 'torch.randn', 'torch.randn', (['batch_size', '(3)', '(32)', '(32)'], {}), '(batch_size, 3, 32, 32)\n', (1090, 1113), False, 'import torch\n')] |
from src.uint8 import uint8
def test_constructor1():
assert int(uint8(20)) == 20
def test_constructor2():
assert uint8(256) == uint8(0)
assert uint8(260) == uint8(4)
assert uint8(-1) == uint8(255)
assert uint8(-5) == uint8(251)
assert uint8(-5) != uint8(252)
def test_add_other():
assert (uint8(50), 0) == uint8(20) + uint8(30)
assert (uint8(5), 1) == uint8(250) + uint8(11)
def test_add_int():
assert (uint8(50), 0) == uint8(20) + 30
assert (uint8(5), 1) == uint8(250) + 11
assert (uint8(251), 1) == uint8(1) + -6
def test_sub_other():
assert (uint8(246), 1) == uint8(20) - uint8(30)
assert (uint8(239), 0) == uint8(250) - uint8(11)
def test_sub_int():
assert (uint8(246), 1) == uint8(20) - 30
assert (uint8(239), 0) == uint8(250) - 11
assert (uint8(7), 0) == uint8(1) - -6
def test_and_other():
assert uint8(24) == uint8(31) & uint8(24)
assert uint8(0) == uint8(17) & uint8(12)
val = uint8(31)
val &= uint8(24)
assert val == uint8(24)
def test_and_int():
assert uint8(24) == uint8(31) & 24
assert uint8(0) == uint8(17) & 12
val = uint8(31)
val &= 24
assert val == uint8(24)
def test_eq_int():
assert uint8(42) == 42
assert uint8(256) == 0
assert uint8(-1) == 255
def test_mod():
assert uint8(32) % 2 == 0
assert uint8(5) % uint8(2) == 1
def test_lshift():
assert (uint8(0), 1) == uint8(128) << 1
assert (uint8(128), 1) == uint8(192) << 1
assert (uint8(64), 0) == uint8(32) << 1
def test_getitem():
assert uint8(16)[4] == 1
assert uint8(16)[5] == 0
for i in range(8):
assert uint8(255)[i] == 1
assert uint8(0)[i] == 0
| [
"src.uint8.uint8"
] | [((976, 985), 'src.uint8.uint8', 'uint8', (['(31)'], {}), '(31)\n', (981, 985), False, 'from src.uint8 import uint8\n'), ((997, 1006), 'src.uint8.uint8', 'uint8', (['(24)'], {}), '(24)\n', (1002, 1006), False, 'from src.uint8 import uint8\n'), ((1144, 1153), 'src.uint8.uint8', 'uint8', (['(31)'], {}), '(31)\n', (1149, 1153), False, 'from src.uint8 import uint8\n'), ((125, 135), 'src.uint8.uint8', 'uint8', (['(256)'], {}), '(256)\n', (130, 135), False, 'from src.uint8 import uint8\n'), ((139, 147), 'src.uint8.uint8', 'uint8', (['(0)'], {}), '(0)\n', (144, 147), False, 'from src.uint8 import uint8\n'), ((159, 169), 'src.uint8.uint8', 'uint8', (['(260)'], {}), '(260)\n', (164, 169), False, 'from src.uint8 import uint8\n'), ((173, 181), 'src.uint8.uint8', 'uint8', (['(4)'], {}), '(4)\n', (178, 181), False, 'from src.uint8 import uint8\n'), ((193, 202), 'src.uint8.uint8', 'uint8', (['(-1)'], {}), '(-1)\n', (198, 202), False, 'from src.uint8 import uint8\n'), ((206, 216), 'src.uint8.uint8', 'uint8', (['(255)'], {}), '(255)\n', (211, 216), False, 'from src.uint8 import uint8\n'), ((228, 237), 'src.uint8.uint8', 'uint8', (['(-5)'], {}), '(-5)\n', (233, 237), False, 'from src.uint8 import uint8\n'), ((241, 251), 'src.uint8.uint8', 'uint8', (['(251)'], {}), '(251)\n', (246, 251), False, 'from src.uint8 import uint8\n'), ((263, 272), 'src.uint8.uint8', 'uint8', (['(-5)'], {}), '(-5)\n', (268, 272), False, 'from src.uint8 import uint8\n'), ((276, 286), 'src.uint8.uint8', 'uint8', (['(252)'], {}), '(252)\n', (281, 286), False, 'from src.uint8 import uint8\n'), ((886, 895), 'src.uint8.uint8', 'uint8', (['(24)'], {}), '(24)\n', (891, 895), False, 'from src.uint8 import uint8\n'), ((932, 940), 'src.uint8.uint8', 'uint8', (['(0)'], {}), '(0)\n', (937, 940), False, 'from src.uint8 import uint8\n'), ((1025, 1034), 'src.uint8.uint8', 'uint8', (['(24)'], {}), '(24)\n', (1030, 1034), False, 'from src.uint8 import uint8\n'), ((1068, 1077), 'src.uint8.uint8', 'uint8', (['(24)'], {}), '(24)\n', (1073, 1077), False, 'from src.uint8 import uint8\n'), ((1107, 1115), 'src.uint8.uint8', 'uint8', (['(0)'], {}), '(0)\n', (1112, 1115), False, 'from src.uint8 import uint8\n'), ((1186, 1195), 'src.uint8.uint8', 'uint8', (['(24)'], {}), '(24)\n', (1191, 1195), False, 'from src.uint8 import uint8\n'), ((1228, 1237), 'src.uint8.uint8', 'uint8', (['(42)'], {}), '(42)\n', (1233, 1237), False, 'from src.uint8 import uint8\n'), ((1255, 1265), 'src.uint8.uint8', 'uint8', (['(256)'], {}), '(256)\n', (1260, 1265), False, 'from src.uint8 import uint8\n'), ((1282, 1291), 'src.uint8.uint8', 'uint8', (['(-1)'], {}), '(-1)\n', (1287, 1291), False, 'from src.uint8 import uint8\n'), ((70, 79), 'src.uint8.uint8', 'uint8', (['(20)'], {}), '(20)\n', (75, 79), False, 'from src.uint8 import uint8\n'), ((323, 332), 'src.uint8.uint8', 'uint8', (['(50)'], {}), '(50)\n', (328, 332), False, 'from src.uint8 import uint8\n'), ((340, 349), 'src.uint8.uint8', 'uint8', (['(20)'], {}), '(20)\n', (345, 349), False, 'from src.uint8 import uint8\n'), ((352, 361), 'src.uint8.uint8', 'uint8', (['(30)'], {}), '(30)\n', (357, 361), False, 'from src.uint8 import uint8\n'), ((374, 382), 'src.uint8.uint8', 'uint8', (['(5)'], {}), '(5)\n', (379, 382), False, 'from src.uint8 import uint8\n'), ((390, 400), 'src.uint8.uint8', 'uint8', (['(250)'], {}), '(250)\n', (395, 400), False, 'from src.uint8 import uint8\n'), ((403, 412), 'src.uint8.uint8', 'uint8', (['(11)'], {}), '(11)\n', (408, 412), False, 'from src.uint8 import uint8\n'), ((447, 456), 'src.uint8.uint8', 'uint8', (['(50)'], {}), '(50)\n', (452, 456), False, 'from src.uint8 import uint8\n'), ((464, 473), 'src.uint8.uint8', 'uint8', (['(20)'], {}), '(20)\n', (469, 473), False, 'from src.uint8 import uint8\n'), ((491, 499), 'src.uint8.uint8', 'uint8', (['(5)'], {}), '(5)\n', (496, 499), False, 'from src.uint8 import uint8\n'), ((507, 517), 'src.uint8.uint8', 'uint8', (['(250)'], {}), '(250)\n', (512, 517), False, 'from src.uint8 import uint8\n'), ((535, 545), 'src.uint8.uint8', 'uint8', (['(251)'], {}), '(251)\n', (540, 545), False, 'from src.uint8 import uint8\n'), ((553, 561), 'src.uint8.uint8', 'uint8', (['(1)'], {}), '(1)\n', (558, 561), False, 'from src.uint8 import uint8\n'), ((603, 613), 'src.uint8.uint8', 'uint8', (['(246)'], {}), '(246)\n', (608, 613), False, 'from src.uint8 import uint8\n'), ((621, 630), 'src.uint8.uint8', 'uint8', (['(20)'], {}), '(20)\n', (626, 630), False, 'from src.uint8 import uint8\n'), ((633, 642), 'src.uint8.uint8', 'uint8', (['(30)'], {}), '(30)\n', (638, 642), False, 'from src.uint8 import uint8\n'), ((655, 665), 'src.uint8.uint8', 'uint8', (['(239)'], {}), '(239)\n', (660, 665), False, 'from src.uint8 import uint8\n'), ((673, 683), 'src.uint8.uint8', 'uint8', (['(250)'], {}), '(250)\n', (678, 683), False, 'from src.uint8 import uint8\n'), ((686, 695), 'src.uint8.uint8', 'uint8', (['(11)'], {}), '(11)\n', (691, 695), False, 'from src.uint8 import uint8\n'), ((730, 740), 'src.uint8.uint8', 'uint8', (['(246)'], {}), '(246)\n', (735, 740), False, 'from src.uint8 import uint8\n'), ((748, 757), 'src.uint8.uint8', 'uint8', (['(20)'], {}), '(20)\n', (753, 757), False, 'from src.uint8 import uint8\n'), ((775, 785), 'src.uint8.uint8', 'uint8', (['(239)'], {}), '(239)\n', (780, 785), False, 'from src.uint8 import uint8\n'), ((793, 803), 'src.uint8.uint8', 'uint8', (['(250)'], {}), '(250)\n', (798, 803), False, 'from src.uint8 import uint8\n'), ((821, 829), 'src.uint8.uint8', 'uint8', (['(7)'], {}), '(7)\n', (826, 829), False, 'from src.uint8 import uint8\n'), ((837, 845), 'src.uint8.uint8', 'uint8', (['(1)'], {}), '(1)\n', (842, 845), False, 'from src.uint8 import uint8\n'), ((899, 908), 'src.uint8.uint8', 'uint8', (['(31)'], {}), '(31)\n', (904, 908), False, 'from src.uint8 import uint8\n'), ((911, 920), 'src.uint8.uint8', 'uint8', (['(24)'], {}), '(24)\n', (916, 920), False, 'from src.uint8 import uint8\n'), ((944, 953), 'src.uint8.uint8', 'uint8', (['(17)'], {}), '(17)\n', (949, 953), False, 'from src.uint8 import uint8\n'), ((956, 965), 'src.uint8.uint8', 'uint8', (['(12)'], {}), '(12)\n', (961, 965), False, 'from src.uint8 import uint8\n'), ((1081, 1090), 'src.uint8.uint8', 'uint8', (['(31)'], {}), '(31)\n', (1086, 1090), False, 'from src.uint8 import uint8\n'), ((1119, 1128), 'src.uint8.uint8', 'uint8', (['(17)'], {}), '(17)\n', (1124, 1128), False, 'from src.uint8 import uint8\n'), ((1328, 1337), 'src.uint8.uint8', 'uint8', (['(32)'], {}), '(32)\n', (1333, 1337), False, 'from src.uint8 import uint8\n'), ((1358, 1366), 'src.uint8.uint8', 'uint8', (['(5)'], {}), '(5)\n', (1363, 1366), False, 'from src.uint8 import uint8\n'), ((1369, 1377), 'src.uint8.uint8', 'uint8', (['(2)'], {}), '(2)\n', (1374, 1377), False, 'from src.uint8 import uint8\n'), ((1416, 1424), 'src.uint8.uint8', 'uint8', (['(0)'], {}), '(0)\n', (1421, 1424), False, 'from src.uint8 import uint8\n'), ((1432, 1442), 'src.uint8.uint8', 'uint8', (['(128)'], {}), '(128)\n', (1437, 1442), False, 'from src.uint8 import uint8\n'), ((1460, 1470), 'src.uint8.uint8', 'uint8', (['(128)'], {}), '(128)\n', (1465, 1470), False, 'from src.uint8 import uint8\n'), ((1478, 1488), 'src.uint8.uint8', 'uint8', (['(192)'], {}), '(192)\n', (1483, 1488), False, 'from src.uint8 import uint8\n'), ((1506, 1515), 'src.uint8.uint8', 'uint8', (['(64)'], {}), '(64)\n', (1511, 1515), False, 'from src.uint8 import uint8\n'), ((1523, 1532), 'src.uint8.uint8', 'uint8', (['(32)'], {}), '(32)\n', (1528, 1532), False, 'from src.uint8 import uint8\n'), ((1571, 1580), 'src.uint8.uint8', 'uint8', (['(16)'], {}), '(16)\n', (1576, 1580), False, 'from src.uint8 import uint8\n'), ((1600, 1609), 'src.uint8.uint8', 'uint8', (['(16)'], {}), '(16)\n', (1605, 1609), False, 'from src.uint8 import uint8\n'), ((1656, 1666), 'src.uint8.uint8', 'uint8', (['(255)'], {}), '(255)\n', (1661, 1666), False, 'from src.uint8 import uint8\n'), ((1690, 1698), 'src.uint8.uint8', 'uint8', (['(0)'], {}), '(0)\n', (1695, 1698), False, 'from src.uint8 import uint8\n')] |
"""
icons index
"""
import zoom
class MyView(zoom.View):
"""Index View"""
def index(self):
"""Index page"""
zoom.requires('fontawesome4')
content = zoom.tools.load('icons.html')
subtitle = 'Icons available as part of FontAwesome 4<br><br>'
return zoom.page(content, title='Icons', subtitle=subtitle)
def about(self):
"""About page"""
content = '{app.description}'
return zoom.page(
content.format(app=zoom.system.request.app),
title='About {app.title}'.format(app=zoom.system.request.app)
)
main = zoom.dispatch(MyView)
| [
"zoom.requires",
"zoom.dispatch",
"zoom.tools.load",
"zoom.page"
] | [((616, 637), 'zoom.dispatch', 'zoom.dispatch', (['MyView'], {}), '(MyView)\n', (629, 637), False, 'import zoom\n'), ((139, 168), 'zoom.requires', 'zoom.requires', (['"""fontawesome4"""'], {}), "('fontawesome4')\n", (152, 168), False, 'import zoom\n'), ((187, 216), 'zoom.tools.load', 'zoom.tools.load', (['"""icons.html"""'], {}), "('icons.html')\n", (202, 216), False, 'import zoom\n'), ((302, 354), 'zoom.page', 'zoom.page', (['content'], {'title': '"""Icons"""', 'subtitle': 'subtitle'}), "(content, title='Icons', subtitle=subtitle)\n", (311, 354), False, 'import zoom\n')] |
# import the function that will return an instance of a connection
from mysqlconnection import connectToMySQL
# model the class after the friend table from our database
class User:
def __init__( self , data ):
self.id = data['id']
self.first_name = data['first_name']
self.last_name = data['last_name']
self.email = data['email']
self.created_at = data['created_at']
self.updated_at = data['updated_at']
# Now we use class methods to query our database
@classmethod
def get_all(cls):
query = "SELECT * FROM users;"
# make sure to call the connectToMySQL function with the schema you are targeting.
results = connectToMySQL('users_schema').query_db(query)
# Create an empty list to append our instances of friends
users = []
# Iterate over the db results and create instances of friends with cls.
for user in results:
users.append( cls(user) )
return users
# class method to save our friend to the database
@classmethod
def save(cls, data ):
query = "INSERT INTO users ( first_name , last_name , email , created_at, updated_at ) VALUES ( %(fname)s , %(lname)s , %(email)s , NOW() , NOW() );"
# data is a dictionary that will be passed into the save method from server.py
return connectToMySQL('users_schema').query_db( query, data )
| [
"mysqlconnection.connectToMySQL"
] | [((701, 731), 'mysqlconnection.connectToMySQL', 'connectToMySQL', (['"""users_schema"""'], {}), "('users_schema')\n", (715, 731), False, 'from mysqlconnection import connectToMySQL\n'), ((1371, 1401), 'mysqlconnection.connectToMySQL', 'connectToMySQL', (['"""users_schema"""'], {}), "('users_schema')\n", (1385, 1401), False, 'from mysqlconnection import connectToMySQL\n')] |
import os
import plugin
import pluginconf
util = plugin.get("util")
FILE_COUNTER = "~/.vpn_counter"
FILE_VPN_SH = "~/.vpn_sh"
EXPECT_SCRIPT = """#!/usr/bin/expect
spawn {cmd}
expect -exact "Enter Auth Username:"
send -- "{user}\\n"
expect -exact "Enter Auth Password:"
send -- "{password}\\n"
interact
"""
class VPN:
def __init__(self):
# Read configuration
self.conf = pluginconf.get('vpn')
def is_connected(self):
with os.popen("ps aux") as f:
pcs = f.read()
return self.conf['openvpn_conf'] in pcs
def get_password(self):
file_counter = os.path.expanduser(FILE_COUNTER)
# Read usage counter
with open(file_counter, 'r') as f:
raw = f.read()
counter = int(raw.strip()) + 1
# OAuth
cmd = "oathtool -b %s -c %s" % (self.conf['secret'], counter)
with os.popen(cmd, 'r') as f:
code = f.read().strip()
# Update counter
with open(file_counter, 'w') as f:
f.write(str(counter))
password = "%<PASSWORD>" % (self.conf['pin'], code)
return password
def connect(self):
# Compose connection script
cmd = "sudo /usr/local/sbin/openvpn --config %s" % self.conf['openvpn_conf']
user = self.conf['user']
password = self.get_password()
script = EXPECT_SCRIPT.format(cmd=cmd, user=user, password=password)
# Write it to a file
vpn_script = os.path.expanduser(FILE_VPN_SH)
with open(vpn_script, 'w+') as f:
f.write(script)
os.chmod(vpn_script, 0o770)
# Run
os.system(vpn_script)
| [
"pluginconf.get",
"os.chmod",
"os.popen",
"plugin.get",
"os.system",
"os.path.expanduser"
] | [((51, 69), 'plugin.get', 'plugin.get', (['"""util"""'], {}), "('util')\n", (61, 69), False, 'import plugin\n'), ((397, 418), 'pluginconf.get', 'pluginconf.get', (['"""vpn"""'], {}), "('vpn')\n", (411, 418), False, 'import pluginconf\n'), ((613, 645), 'os.path.expanduser', 'os.path.expanduser', (['FILE_COUNTER'], {}), '(FILE_COUNTER)\n', (631, 645), False, 'import os\n'), ((1479, 1510), 'os.path.expanduser', 'os.path.expanduser', (['FILE_VPN_SH'], {}), '(FILE_VPN_SH)\n', (1497, 1510), False, 'import os\n'), ((1590, 1615), 'os.chmod', 'os.chmod', (['vpn_script', '(504)'], {}), '(vpn_script, 504)\n', (1598, 1615), False, 'import os\n'), ((1641, 1662), 'os.system', 'os.system', (['vpn_script'], {}), '(vpn_script)\n', (1650, 1662), False, 'import os\n'), ((461, 479), 'os.popen', 'os.popen', (['"""ps aux"""'], {}), "('ps aux')\n", (469, 479), False, 'import os\n'), ((885, 903), 'os.popen', 'os.popen', (['cmd', '"""r"""'], {}), "(cmd, 'r')\n", (893, 903), False, 'import os\n')] |
# -*- coding: utf-8 -*-
from openprocurement.api.validation import (
validate_json_data,
validate_data,
validate_accreditation_level,
validate_accreditation_level_mode,
)
from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents
from openprocurement.planning.api.models import Plan, Milestone
from openprocurement.planning.api.constants import PROCEDURES
from itertools import chain
from openprocurement.api.utils import get_now
from openprocurement.api.constants import PLAN_ADDRESS_KIND_REQUIRED_FROM
from copy import deepcopy
def validate_plan_data(request):
update_logging_context(request, {"plan_id": "__new__"})
data = validate_json_data(request)
model = request.plan_from_data(data, create=False)
validate_plan_accreditation_level(request, model)
data = validate_data(request, model, data=data)
validate_plan_accreditation_level_mode(request)
validate_tender_procurement_method_type(request)
return data
def validate_plan_accreditation_level(request, model):
levels = model.create_accreditations
validate_accreditation_level(request, levels, "plan", "plan", "creation")
def validate_plan_accreditation_level_mode(request):
data = request.validated["data"]
mode = data.get("mode", None)
validate_accreditation_level_mode(request, mode, "plan", "plan", "creation")
def validate_tender_procurement_method_type(request):
_procedures = deepcopy(PROCEDURES)
if get_now() >= PLAN_ADDRESS_KIND_REQUIRED_FROM:
_procedures[""] = ("centralizedProcurement", )
procurement_method_types = list(chain(*_procedures.values()))
procurement_method_types_without_above_threshold_ua_defense = list(
filter(lambda x: x != 'aboveThresholdUA.defense', procurement_method_types)
)
kind_allows_procurement_method_type_mapping = {
"defense": procurement_method_types,
"general": procurement_method_types_without_above_threshold_ua_defense,
"special": procurement_method_types_without_above_threshold_ua_defense,
"central": procurement_method_types_without_above_threshold_ua_defense,
"authority": procurement_method_types_without_above_threshold_ua_defense,
"social": procurement_method_types_without_above_threshold_ua_defense,
"other": ["belowThreshold", "reporting"],
}
data = request.validated["data"]
kind = data.get("procuringEntity", {}).get("kind", "")
tender_procurement_method_type = data.get("tender", {}).get("procurementMethodType", "")
allowed_procurement_method_types = kind_allows_procurement_method_type_mapping.get(kind)
if allowed_procurement_method_types and get_now() >= PLAN_ADDRESS_KIND_REQUIRED_FROM:
if tender_procurement_method_type not in allowed_procurement_method_types:
request.errors.add(
"procuringEntity", "kind",
"procuringEntity with {kind} kind cannot publish this type of procedure. "
"Procurement method types allowed for this kind: {methods}.".format(
kind=kind, methods=", ".join(allowed_procurement_method_types)
)
)
request.errors.status = 403
def validate_patch_plan_data(request):
return validate_data(request, Plan, True)
def validate_plan_has_not_tender(request):
plan = request.validated["plan"]
if plan.tender_id:
request.errors.add("data", "tender_id", u"This plan has already got a tender")
request.errors.status = 422
raise error_handler(request.errors)
def validate_plan_with_tender(request):
plan = request.validated["plan"]
if plan.tender_id:
json_data = request.validated["json_data"]
names = []
if "procuringEntity" in json_data:
names.append("procuringEntity")
if "budget" in json_data and "breakdown" in json_data["budget"]:
names.append("budget.breakdown")
for name in names:
request.errors.add("data", name, "Changing this field is not allowed after tender creation")
if request.errors:
request.errors.status = 422
raise error_handler(request.errors)
def validate_plan_not_terminated(request):
plan = request.validated["plan"]
if plan.status in ("cancelled", "complete"):
request.errors.add("data", "status", "Can't update plan in '{}' status".format(plan.status))
request.errors.status = 422
raise error_handler(request.errors)
def validate_plan_status_update(request):
status = request.validated["json_data"].get("status")
if status == "draft" and request.validated["plan"].status != status:
request.errors.add("data", "status", "Plan status can not be changed back to 'draft'")
request.errors.status = 422
raise error_handler(request.errors)
def validate_milestone_data(request):
update_logging_context(request, {"milestone_id": "__new__"})
model = type(request.plan).milestones.model_class
milestone = validate_data(request, model)
upload_objects_documents(
request, request.validated["milestone"],
route_kwargs = {"milestone_id": request.validated["milestone"].id}
)
return milestone
def validate_patch_milestone_data(request):
model = type(request.context)
return validate_data(request, model, partial=True)
def validate_milestone_author(request):
milestone = request.validated["milestone"]
plan = request.validated["plan"]
author = milestone.author
plan_identifier = plan.procuringEntity.identifier
milestone_identifier = author.identifier
if (plan_identifier.scheme, plan_identifier.id) != (milestone_identifier.scheme, milestone_identifier.id):
request.errors.add(
"data",
"author",
"Should match plan.procuringEntity"
)
request.errors.status = 422
raise error_handler(request.errors)
if any(
(m.author.identifier.scheme, m.author.identifier.id) == (author.identifier.scheme, author.identifier.id)
for m in plan.milestones
if m.status in Milestone.ACTIVE_STATUSES
):
request.errors.add(
"data",
"author",
"An active milestone already exists for this author"
)
request.errors.status = 422
raise error_handler(request.errors)
def validate_milestone_status_scheduled(request):
milestone = request.validated["milestone"]
if milestone.status != Milestone.STATUS_SCHEDULED:
request.errors.add(
"data",
"status",
"Cannot create milestone with status: {}".format(milestone["status"])
)
request.errors.status = 422
raise error_handler(request.errors)
| [
"openprocurement.api.utils.upload_objects_documents",
"openprocurement.api.utils.update_logging_context",
"openprocurement.api.validation.validate_json_data",
"openprocurement.api.validation.validate_data",
"openprocurement.api.validation.validate_accreditation_level_mode",
"openprocurement.api.utils.get_... | [((628, 683), 'openprocurement.api.utils.update_logging_context', 'update_logging_context', (['request', "{'plan_id': '__new__'}"], {}), "(request, {'plan_id': '__new__'})\n", (650, 683), False, 'from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents\n'), ((695, 722), 'openprocurement.api.validation.validate_json_data', 'validate_json_data', (['request'], {}), '(request)\n', (713, 722), False, 'from openprocurement.api.validation import validate_json_data, validate_data, validate_accreditation_level, validate_accreditation_level_mode\n'), ((843, 883), 'openprocurement.api.validation.validate_data', 'validate_data', (['request', 'model'], {'data': 'data'}), '(request, model, data=data)\n', (856, 883), False, 'from openprocurement.api.validation import validate_json_data, validate_data, validate_accreditation_level, validate_accreditation_level_mode\n'), ((1107, 1180), 'openprocurement.api.validation.validate_accreditation_level', 'validate_accreditation_level', (['request', 'levels', '"""plan"""', '"""plan"""', '"""creation"""'], {}), "(request, levels, 'plan', 'plan', 'creation')\n", (1135, 1180), False, 'from openprocurement.api.validation import validate_json_data, validate_data, validate_accreditation_level, validate_accreditation_level_mode\n'), ((1311, 1387), 'openprocurement.api.validation.validate_accreditation_level_mode', 'validate_accreditation_level_mode', (['request', 'mode', '"""plan"""', '"""plan"""', '"""creation"""'], {}), "(request, mode, 'plan', 'plan', 'creation')\n", (1344, 1387), False, 'from openprocurement.api.validation import validate_json_data, validate_data, validate_accreditation_level, validate_accreditation_level_mode\n'), ((1462, 1482), 'copy.deepcopy', 'deepcopy', (['PROCEDURES'], {}), '(PROCEDURES)\n', (1470, 1482), False, 'from copy import deepcopy\n'), ((3287, 3321), 'openprocurement.api.validation.validate_data', 'validate_data', (['request', 'Plan', '(True)'], {}), '(request, Plan, True)\n', (3300, 3321), False, 'from openprocurement.api.validation import validate_json_data, validate_data, validate_accreditation_level, validate_accreditation_level_mode\n'), ((4924, 4984), 'openprocurement.api.utils.update_logging_context', 'update_logging_context', (['request', "{'milestone_id': '__new__'}"], {}), "(request, {'milestone_id': '__new__'})\n", (4946, 4984), False, 'from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents\n'), ((5055, 5084), 'openprocurement.api.validation.validate_data', 'validate_data', (['request', 'model'], {}), '(request, model)\n', (5068, 5084), False, 'from openprocurement.api.validation import validate_json_data, validate_data, validate_accreditation_level, validate_accreditation_level_mode\n'), ((5089, 5224), 'openprocurement.api.utils.upload_objects_documents', 'upload_objects_documents', (['request', "request.validated['milestone']"], {'route_kwargs': "{'milestone_id': request.validated['milestone'].id}"}), "(request, request.validated['milestone'],\n route_kwargs={'milestone_id': request.validated['milestone'].id})\n", (5113, 5224), False, 'from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents\n'), ((5357, 5400), 'openprocurement.api.validation.validate_data', 'validate_data', (['request', 'model'], {'partial': '(True)'}), '(request, model, partial=True)\n', (5370, 5400), False, 'from openprocurement.api.validation import validate_json_data, validate_data, validate_accreditation_level, validate_accreditation_level_mode\n'), ((1490, 1499), 'openprocurement.api.utils.get_now', 'get_now', ([], {}), '()\n', (1497, 1499), False, 'from openprocurement.api.utils import get_now\n'), ((3564, 3593), 'openprocurement.api.utils.error_handler', 'error_handler', (['request.errors'], {}), '(request.errors)\n', (3577, 3593), False, 'from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents\n'), ((4500, 4529), 'openprocurement.api.utils.error_handler', 'error_handler', (['request.errors'], {}), '(request.errors)\n', (4513, 4529), False, 'from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents\n'), ((4850, 4879), 'openprocurement.api.utils.error_handler', 'error_handler', (['request.errors'], {}), '(request.errors)\n', (4863, 4879), False, 'from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents\n'), ((5946, 5975), 'openprocurement.api.utils.error_handler', 'error_handler', (['request.errors'], {}), '(request.errors)\n', (5959, 5975), False, 'from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents\n'), ((6386, 6415), 'openprocurement.api.utils.error_handler', 'error_handler', (['request.errors'], {}), '(request.errors)\n', (6399, 6415), False, 'from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents\n'), ((6782, 6811), 'openprocurement.api.utils.error_handler', 'error_handler', (['request.errors'], {}), '(request.errors)\n', (6795, 6811), False, 'from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents\n'), ((2700, 2709), 'openprocurement.api.utils.get_now', 'get_now', ([], {}), '()\n', (2707, 2709), False, 'from openprocurement.api.utils import get_now\n'), ((4188, 4217), 'openprocurement.api.utils.error_handler', 'error_handler', (['request.errors'], {}), '(request.errors)\n', (4201, 4217), False, 'from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents\n')] |
# Importando librerías
from numpy import array
# Listas y arreglos
a = array(['h', 101, 'l', 'l', 'o'])
x = ['h', 101, 'l', 'l', 'o']
print(a)
print(x)
print("Tamaño: ", len(x))
# Condicionales
if isinstance(x[1], int):
x[1] = chr(x[1])
elif isinstance(x[1], str):
pass
else:
raise TypeError("Tipo no soportado!. No te pases! >:c")
print(' uwu '.join(x))
# Ciclos
for item in x:
print(item)
for i in range(len(x)):
print(x[i])
for i in range(1, 10, 2):
print(i)
while len(x):
print(x.pop(0))
while len(x):
print(x.pop(0))
else:
print('F para x :C')
# Operaciones con listas
x.append('H')
x.append('o')
x.append('l')
x.append('a')
x.insert(1, 'o')
# Entrada de datos
print(x)
respuesta = input("Hola?")
print(respuesta)
# Operadores aritméticos y booleanos
print(x)
print(10.1)
print(1 + 2 - 4 * 5 / 8 % 2)
print(2 ** 5)
print(True and True)
print(False and True)
print(False or True)
print(not False)
# Listas comprimidas
print([i for i in range(1, 11) if i % 2 == 0])
print([j for j in range(2, 101) if all(j % i != 0 for i in range(2, j))])
print([j for j in range(2, 101) if not(j % 2 or j % 3 or j % 5)]) | [
"numpy.array"
] | [((72, 104), 'numpy.array', 'array', (["['h', 101, 'l', 'l', 'o']"], {}), "(['h', 101, 'l', 'l', 'o'])\n", (77, 104), False, 'from numpy import array\n')] |
import chainer
import chainer.functions as F
import chainer.links as L
class VGGNet(chainer.Chain):
"""
VGGNet
- It takes (224, 224, 3) sized image as imput
"""
def __init__(self, n_class=1000):
super(VGGNet, self).__init__()
with self.init_scope():
self.conv1_1 = L.Convolution2D(3, 64, 3, stride=1, pad=1)
self.conv1_2 = L.Convolution2D(64, 64, 3, stride=1, pad=1)
self.conv2_1 = L.Convolution2D(64, 128, 3, stride=1, pad=1)
self.conv2_2 = L.Convolution2D(128, 128, 3, stride=1, pad=1)
self.conv3_1 = L.Convolution2D(128, 256, 3, stride=1, pad=1)
self.conv3_2 = L.Convolution2D(256, 256, 3, stride=1, pad=1)
self.conv3_3 = L.Convolution2D(256, 256, 3, stride=1, pad=1)
self.conv4_1 = L.Convolution2D(256, 512, 3, stride=1, pad=1)
self.conv4_2 = L.Convolution2D(512, 512, 3, stride=1, pad=1)
self.conv4_3 = L.Convolution2D(512, 512, 3, stride=1, pad=1)
self.conv5_1 = L.Convolution2D(512, 512, 3, stride=1, pad=1)
self.conv5_2 = L.Convolution2D(512, 512, 3, stride=1, pad=1)
self.conv5_3 = L.Convolution2D(512, 512, 3, stride=1, pad=1)
self.fc6 = L.Linear(None, 4096)
self.fc7 = L.Linear(4096, 4096)
self.fc8 = L.Linear(4096, n_class)
def __call__(self, x):
h = F.relu(self.conv1_1(x))
h = F.relu(self.conv1_2(h))
h = F.max_pooling_2d(h, 2, stride=2)
h = F.relu(self.conv2_1(h))
h = F.relu(self.conv2_2(h))
h = F.max_pooling_2d(h, 2, stride=2)
h = F.relu(self.conv3_1(h))
h = F.relu(self.conv3_2(h))
h = F.relu(self.conv3_3(h))
h = F.max_pooling_2d(h, 2, stride=2)
h = F.relu(self.conv4_1(h))
h = F.relu(self.conv4_2(h))
h = F.relu(self.conv4_3(h))
h = F.max_pooling_2d(h, 2, stride=2)
h = F.relu(self.conv5_1(h))
h = F.relu(self.conv5_2(h))
h = F.relu(self.conv5_3(h))
h = F.max_pooling_2d(h, 2, stride=2)
h = F.dropout(F.relu(self.fc6(h)))
h = F.dropout(F.relu(self.fc7(h)))
h = self.fc8(h)
return h
| [
"chainer.links.Linear",
"chainer.functions.max_pooling_2d",
"chainer.links.Convolution2D"
] | [((1481, 1513), 'chainer.functions.max_pooling_2d', 'F.max_pooling_2d', (['h', '(2)'], {'stride': '(2)'}), '(h, 2, stride=2)\n', (1497, 1513), True, 'import chainer.functions as F\n'), ((1599, 1631), 'chainer.functions.max_pooling_2d', 'F.max_pooling_2d', (['h', '(2)'], {'stride': '(2)'}), '(h, 2, stride=2)\n', (1615, 1631), True, 'import chainer.functions as F\n'), ((1753, 1785), 'chainer.functions.max_pooling_2d', 'F.max_pooling_2d', (['h', '(2)'], {'stride': '(2)'}), '(h, 2, stride=2)\n', (1769, 1785), True, 'import chainer.functions as F\n'), ((1907, 1939), 'chainer.functions.max_pooling_2d', 'F.max_pooling_2d', (['h', '(2)'], {'stride': '(2)'}), '(h, 2, stride=2)\n', (1923, 1939), True, 'import chainer.functions as F\n'), ((2061, 2093), 'chainer.functions.max_pooling_2d', 'F.max_pooling_2d', (['h', '(2)'], {'stride': '(2)'}), '(h, 2, stride=2)\n', (2077, 2093), True, 'import chainer.functions as F\n'), ((317, 359), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(3)', '(64)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(3, 64, 3, stride=1, pad=1)\n', (332, 359), True, 'import chainer.links as L\n'), ((387, 430), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(64)', '(64)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(64, 64, 3, stride=1, pad=1)\n', (402, 430), True, 'import chainer.links as L\n'), ((458, 502), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(64)', '(128)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(64, 128, 3, stride=1, pad=1)\n', (473, 502), True, 'import chainer.links as L\n'), ((530, 575), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(128)', '(128)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(128, 128, 3, stride=1, pad=1)\n', (545, 575), True, 'import chainer.links as L\n'), ((603, 648), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(128)', '(256)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(128, 256, 3, stride=1, pad=1)\n', (618, 648), True, 'import chainer.links as L\n'), ((676, 721), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(256)', '(256)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(256, 256, 3, stride=1, pad=1)\n', (691, 721), True, 'import chainer.links as L\n'), ((749, 794), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(256)', '(256)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(256, 256, 3, stride=1, pad=1)\n', (764, 794), True, 'import chainer.links as L\n'), ((822, 867), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(256)', '(512)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(256, 512, 3, stride=1, pad=1)\n', (837, 867), True, 'import chainer.links as L\n'), ((895, 940), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(512)', '(512)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(512, 512, 3, stride=1, pad=1)\n', (910, 940), True, 'import chainer.links as L\n'), ((968, 1013), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(512)', '(512)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(512, 512, 3, stride=1, pad=1)\n', (983, 1013), True, 'import chainer.links as L\n'), ((1041, 1086), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(512)', '(512)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(512, 512, 3, stride=1, pad=1)\n', (1056, 1086), True, 'import chainer.links as L\n'), ((1114, 1159), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(512)', '(512)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(512, 512, 3, stride=1, pad=1)\n', (1129, 1159), True, 'import chainer.links as L\n'), ((1187, 1232), 'chainer.links.Convolution2D', 'L.Convolution2D', (['(512)', '(512)', '(3)'], {'stride': '(1)', 'pad': '(1)'}), '(512, 512, 3, stride=1, pad=1)\n', (1202, 1232), True, 'import chainer.links as L\n'), ((1257, 1277), 'chainer.links.Linear', 'L.Linear', (['None', '(4096)'], {}), '(None, 4096)\n', (1265, 1277), True, 'import chainer.links as L\n'), ((1301, 1321), 'chainer.links.Linear', 'L.Linear', (['(4096)', '(4096)'], {}), '(4096, 4096)\n', (1309, 1321), True, 'import chainer.links as L\n'), ((1345, 1368), 'chainer.links.Linear', 'L.Linear', (['(4096)', 'n_class'], {}), '(4096, n_class)\n', (1353, 1368), True, 'import chainer.links as L\n')] |
import sqlite3
import requests
from bs4 import BeautifulSoup
from login import keys
import config
ARTICLE_SEARCH_URL = 'http://api.nytimes.com/svc/search/v2/articlesearch.json?api-key={key}'
SUNLIGHT_CONGRESS_URL = 'http://congress.api.sunlightfoundation.com/{method}?{query}&apikey={key}'
def get_json(url):
return requests.get(url).json()
def sunlight_url(base, method, query, key):
return base.format(method=method, query=query, key=key)
def sunlight_query(**kwargs):
return '&'.join(key+'='+value for key,value in kwargs.items())
def save_url(url, path, name):
file_path = path + '/' + name + '.txt'
r = requests.get(url)
text = BeautifulSoup(r.text).get_text()
with open(file_path, 'w') as f:
f.write(text)
print('saved: ' + url + ', to: ' + file_path)
return file_path
def get_bills(max_pages=50):
loop = 0
while loop < max_pages:
query = sunlight_query(congress='113', per_page='50', page=str(loop))
url = sunlight_url(SUNLIGHT_CONGRESS_URL, 'bills', query, keys['sunlight'])
bills = get_json(url)
for b in bills['results']:
yield b
loop = bills['page']['page'] + 1
def main():
conn = sqlite3.connect(config.DATABASE)
c = conn.cursor()
for b in get_bills(max_pages=50):
if b['history']['active'] and b.get('last_version', None):
number = b['number']
chamber = b['chamber']
sponsor = b['sponsor_id']
congress = b['congress']
introduced_on = b['introduced_on']
title = b['official_title']
if b.get('last_version', None):
link = b['last_version']['urls']['html']
file_path = save_url(link, 'bill_text', str(number))
c.execute("""
INSERT INTO bills
VALUES
(?, ?, ?, ?, ?, ?, ?);
""",
(congress, chamber, number, introduced_on, sponsor, title, file_path))
conn.commit()
c.close()
if __name__ == '__main__':
main()
| [
"bs4.BeautifulSoup",
"sqlite3.connect",
"requests.get"
] | [((635, 652), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (647, 652), False, 'import requests\n'), ((1219, 1251), 'sqlite3.connect', 'sqlite3.connect', (['config.DATABASE'], {}), '(config.DATABASE)\n', (1234, 1251), False, 'import sqlite3\n'), ((324, 341), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (336, 341), False, 'import requests\n'), ((664, 685), 'bs4.BeautifulSoup', 'BeautifulSoup', (['r.text'], {}), '(r.text)\n', (677, 685), False, 'from bs4 import BeautifulSoup\n')] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""docstring"""
from __future__ import print_function, unicode_literals
import argparse
import sys
from .settingsdiff import dump_settings, diff_settings
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"settings_path_1",
nargs="?",
help='The path to the .pkl file of the first (i.e. "original") settings dump',
)
parser.add_argument(
"settings_path_2",
nargs="?",
help='The path to the .pkl file of the second (i.e. "new") settings dump',
)
parser.add_argument(
"-d", "--dump", metavar="PATH", help="The path the settings will be dumped to"
)
parser.add_argument(
"-t",
"--dump-type",
choices=["txt", "pkl"],
help=(
"The file type of the dump. Only needed if type cannot be derived "
"from extension give via --dump"
),
)
args = parser.parse_args()
if args.dump:
try:
dump_settings(args.dump, args.dump_type)
except NotImplementedError as error:
print("ERROR: {}".format(error), file=sys.stderr)
sys.exit(1)
elif args.settings_path_1 and args.settings_path_2:
diff_settings(args.settings_path_1, args.settings_path_2)
else:
parser.error("Invalid argument configuration!")
if __name__ == "__main__":
main()
| [
"argparse.ArgumentParser",
"sys.exit"
] | [((231, 256), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (254, 256), False, 'import argparse\n'), ((1185, 1196), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1193, 1196), False, 'import sys\n')] |
import torch
import torch.nn as nn
from ..utils.torch import pack_forward
from .pooling import GatherLastLayer
class CharEncoder(nn.Module):
FORWARD_BACKWARD_AGGREGATION_METHODS = ["cat", "linear_sum"]
def __init__(
self,
char_embedding_dim,
hidden_size,
char_fw_bw_agg_method="cat",
bidirectional=True,
train_char_embeddings=True,
use_cuda=True,
):
if char_fw_bw_agg_method not in self.FORWARD_BACKWARD_AGGREGATION_METHODS:
raise ValueError(
f"{char_fw_bw_agg_method} not recognized, try with one of "
f"{self.FORWARD_BACKWARD_AGGREGATION_METHODS}"
)
super(CharEncoder, self).__init__()
self.char_embedding_dim = char_embedding_dim
self.n_layers = 1
self.char_hidden_dim = hidden_size
self.bidirectional = bidirectional
self.num_dirs = 2 if bidirectional else 1
self.hidden_x_dirs = self.num_dirs * self.char_hidden_dim
self.use_cuda = use_cuda
self.char_lstm = nn.LSTM(
self.char_embedding_dim,
self.char_hidden_dim,
self.n_layers,
bidirectional=self.bidirectional,
dropout=0.0,
)
self.gather_last = GatherLastLayer(
self.char_hidden_dim, bidirectional=self.bidirectional
)
self.char_fw_bw_agg_method = char_fw_bw_agg_method
if self.char_fw_bw_agg_method == "cat":
self.out_dim = self.hidden_x_dirs
elif self.char_fw_bw_agg_method == "linear_sum":
self.out_dim = self.char_hidden_dim
self.linear_layer = nn.Linear(
self.hidden_x_dirs, self.char_hidden_dim
)
def forward(self, char_batch, word_lengths):
"""char_batch: (batch_size, seq_len, word_len, char_emb_dim)
word_lengths: (batch_size, seq_len)"""
(batch_size, seq_len, word_len, char_emb_dim) = char_batch.size()
# (batch_size * seq_len, word_len, char_emb_dim)
char_batch = char_batch.view(batch_size * seq_len, word_len, char_emb_dim)
# (batch_size, seq_len) -> (batch_size * seq_len)
word_lengths = word_lengths.view(batch_size * seq_len)
# (batch_size * seq_len, word_len, hidden_x_dirs)
word_lvl_repr = pack_forward(self.char_lstm, char_batch, word_lengths)
# (batch_size * seq_len, hidden_x_dirs)
word_lvl_repr = self.gather_last(word_lvl_repr, lengths=word_lengths)
# last dimension of gather_last will always correspond to concatenated
# last hidden states of lstm if bidirectional
# (batch_size, seq_len, hidden_x_dirs)
word_lvl_repr = word_lvl_repr.view(
batch_size, seq_len, self.hidden_x_dirs
)
# We store this tensor for future introspection
self.concat_fw_bw_reprs = word_lvl_repr.clone()
if self.char_fw_bw_agg_method == "linear_sum":
# Based on the paper: http://www.anthology.aclweb.org/D/D16/D16-1209.pdf
# Line below is W*word_lvl_repr + b which is equivalent to
# [W_f; W_b] * [h_f;h_b] + b which in turn is equivalent to
# W_f * h_f + W_b * h_b + b
word_lvl_repr = self.linear_layer(word_lvl_repr)
return word_lvl_repr
class LinearAggregationLayer(nn.Module):
def __init__(self, in_dim):
"""
Simply concatenate the provided tensors on their last dimension
which needs to have the same size, along with their
element-wise multiplication and difference
Taken from the paper:
"Learning Natural Language Inference using Bidirectional
LSTM model and Inner-Attention"
https://arxiv.org/abs/1605.09090
"""
super(LinearAggregationLayer, self).__init__()
self.in_dim = in_dim
self.out_dim = 4 * in_dim
def forward(self, input_1, input_2):
"""
:param : input_1
Size is (*, hidden_size)
:param input_2:
Size is (*, hidden_size)
:return:
Merged vectors, size is (*, 4*hidden size)
"""
assert input_1.size(-1) == input_2.size(-1)
mult_combined_vec = torch.mul(input_1, input_2)
diff_combined_vec = torch.abs(input_1 - input_2)
# cosine_sim = simple_columnwise_cosine_similarity(input_1, input_2)
# cosine_sim = cosine_sim.unsqueeze(1)
# euclidean_dist = distance(input_1, input_2, 2)
combined_vec = torch.cat(
(input_1, input_2, mult_combined_vec, diff_combined_vec),
input_1.dim() - 1,
)
return combined_vec
| [
"torch.nn.LSTM",
"torch.mul",
"torch.abs",
"torch.nn.Linear"
] | [((1073, 1193), 'torch.nn.LSTM', 'nn.LSTM', (['self.char_embedding_dim', 'self.char_hidden_dim', 'self.n_layers'], {'bidirectional': 'self.bidirectional', 'dropout': '(0.0)'}), '(self.char_embedding_dim, self.char_hidden_dim, self.n_layers,\n bidirectional=self.bidirectional, dropout=0.0)\n', (1080, 1193), True, 'import torch.nn as nn\n'), ((4286, 4313), 'torch.mul', 'torch.mul', (['input_1', 'input_2'], {}), '(input_1, input_2)\n', (4295, 4313), False, 'import torch\n'), ((4342, 4370), 'torch.abs', 'torch.abs', (['(input_1 - input_2)'], {}), '(input_1 - input_2)\n', (4351, 4370), False, 'import torch\n'), ((1676, 1727), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_x_dirs', 'self.char_hidden_dim'], {}), '(self.hidden_x_dirs, self.char_hidden_dim)\n', (1685, 1727), True, 'import torch.nn as nn\n')] |
import json
import uuid
from dataclasses import dataclass
from typing import Callable, Sequence, Any, Optional, Tuple, Union, List, Generic, TypeVar
from serflag import SerFlag
from handlers.graphql.graphql_handler import ContextProtocol
from handlers.graphql.utils.string import camelcase
from xenadapter.task import get_userids
from xenadapter.xenobject import XenObject
from functools import partial
import constants.re as re
from sentry_sdk import capture_exception
def call_mutation_from_string(mutable_object, changes, function):
def f():
old_value = {function: getattr(mutable_object, f'get_{function}')()}
new_value = {function: getattr(changes, function)}
getattr(mutable_object, f'set_{function}')(new_value[function])
return old_value, new_value
return f
@dataclass
class MutationMethod:
'''
Represents a mutation method - a function equipped with action name that is passed to check_access.
Attributes:
func: A mutation performer name without set prefix: a function that accepts an argument that is a part of used input named after the func.
i.e. if func == "name_label", it'll invoke set_name_label(user_input.name_label)
OR
a tuple of functions: 1st is going to be called with user input,
and 2nd is a validator, taking user input and returning a tuple of validation result and reason
access_action: An access action required for performing this mutation. None means this mutation is for administrators only
deps: Tuple of dependencies: lambdas that are called with our object as first argument and returning tuple of Boolean and reason string
'''
Input = TypeVar('Input')
InputArgument = TypeVar('InputArgument')
MutationFunction = Callable[[Input, "XenObject"], Tuple[InputArgument, InputArgument]]
MutationCheckerFunction = Callable[[Input, "XenObject"], Tuple[bool, Optional[str]]]
func: Union[str, Tuple[MutationFunction, MutationCheckerFunction]]
access_action: Optional[SerFlag]
deps: Tuple[Callable[["XenObject"], Tuple[bool, str]]] = tuple()
def call_mutation_from_function(mutable_object, changes, function: MutationMethod.MutationFunction):
return partial(function, changes, mutable_object)
@dataclass
class MutationHelper:
"""
A Mutation helper. Parameters:
- mutations: Sequence of mutations to be performed
- ctx: Request's context
- mutable_object: A Xen object to perform mutation on
"""
mutations: Sequence[MutationMethod]
ctx: ContextProtocol
mutable_object: XenObject
def prepare_mutations_for_item(self, item, changes):
dep_checks : List[Callable[[], Tuple[bool, str]]] = []
# Filling dependency checks in
for dep in item.deps:
dep_checks.append(partial(dep, self.mutable_object))
if isinstance(item.func, str):
if getattr(changes, item.func) is None:
return
else:
granted, reason = item.func[1](changes, self.mutable_object, self.ctx)
if not granted:
if not reason: # if Reason is None, we're instructed to skip this mutation as user didn't supply anything
return
else:
return reason
# Checking access
if not(item.access_action is None and \
self.ctx.user_authenticator.is_admin() or \
self.mutable_object.check_access(self.ctx.user_authenticator, item.access_action)):
if item.access_action:
return f"{camelcase(item.func if isinstance(item.func, str) else item.func[0].__name__)}: Access denied: object {self.mutable_object}; action: {item.access_action}"
else:
return f"{camelcase(item.func if isinstance(item.func, str) else item.func[0].__name__)}: Access denied: not an administrator"
else:
if isinstance(item.func, str):
function_candidate = call_mutation_from_string(self.mutable_object, changes, item.func)
else:
function_candidate = call_mutation_from_function(self.mutable_object, changes, item.func[0])
# Running dependency checks
for dep_check in dep_checks:
ret = dep_check()
if not ret[0]:
return f"{camelcase(item.func if isinstance(item.func, str) else '')}: {ret[1]}"
return function_candidate
def perform_mutations(self, changes: MutationMethod.Input) -> Tuple[bool, Optional[str]]:
'''
Perform mutations in a transaction fashion: Either all or nothing.
This method also inserts tasks in task table for each mutation.
If mutation fails, "failure" status is set.
In the result field, there's a JSON document of the following structure:
{
"old_val": {
"setting_name": "old_setting_value"
}
"new_val" : {
"setting_name": "new_setting_value"
}
}
:param changes: Graphene Input type instance with proposed changes
:return: Tuple [True, None] or [False, "String reason what's not granted"] where access is not granted]
'''
tasks : List[dict] = []
for item in self.mutations:
function_or_error = self.prepare_mutations_for_item(item, changes)
if not function_or_error:
continue
new_uuid = str(uuid.uuid4())
action = item.access_action.serialize()[0]
who = "users/" + self.ctx.user_authenticator.get_id() if not self.ctx.user_authenticator.is_admin() else None
object_ref = self.mutable_object.ref
object_type = self.mutable_object.__class__
task = {
"ref": new_uuid,
"object_ref": object_ref,
"object_type": object_type.__name__,
"action": action,
"error_info" : [],
"created": re.r.now().run(),
"name_label": f"{object_type.__name__}.{action}",
"name_description": "",
"uuid": new_uuid,
"progress": 1,
"resident_on": None,
"who": who,
"access" : {user: ['remove'] for user in get_userids(object_type, object_ref, action)}
}
if isinstance(function_or_error, str):
task['status'] = 'failure'
task['error_info'].append(function_or_error)
task['finished'] = re.r.now().run()
re.db.table('tasks').insert(task).run()
return False, function_or_error
else:
task['call'] = function_or_error
tasks.append(task)
for task in tasks:
try:
new_value, old_value = task['call']()
task['status'] = 'success'
task['result'] = json.dumps({"old_val": old_value, "new_val": new_value})
task['finished'] = re.r.now().run()
except Exception as e:
capture_exception(e)
task['status'] = 'failure'
task['error_info'].append(str(e))
task['result'] = ""
task['finished'] = re.r.now().run()
finally:
del task['call']
re.db.table('tasks').insert(task).run()
return True, None
| [
"constants.re.db.table",
"xenadapter.task.get_userids",
"json.dumps",
"uuid.uuid4",
"functools.partial",
"typing.TypeVar",
"constants.re.r.now",
"sentry_sdk.capture_exception"
] | [((1695, 1711), 'typing.TypeVar', 'TypeVar', (['"""Input"""'], {}), "('Input')\n", (1702, 1711), False, 'from typing import Callable, Sequence, Any, Optional, Tuple, Union, List, Generic, TypeVar\n'), ((1732, 1756), 'typing.TypeVar', 'TypeVar', (['"""InputArgument"""'], {}), "('InputArgument')\n", (1739, 1756), False, 'from typing import Callable, Sequence, Any, Optional, Tuple, Union, List, Generic, TypeVar\n'), ((2227, 2269), 'functools.partial', 'partial', (['function', 'changes', 'mutable_object'], {}), '(function, changes, mutable_object)\n', (2234, 2269), False, 'from functools import partial\n'), ((2813, 2846), 'functools.partial', 'partial', (['dep', 'self.mutable_object'], {}), '(dep, self.mutable_object)\n', (2820, 2846), False, 'from functools import partial\n'), ((5459, 5471), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (5469, 5471), False, 'import uuid\n'), ((6959, 7015), 'json.dumps', 'json.dumps', (["{'old_val': old_value, 'new_val': new_value}"], {}), "({'old_val': old_value, 'new_val': new_value})\n", (6969, 7015), False, 'import json\n'), ((7119, 7139), 'sentry_sdk.capture_exception', 'capture_exception', (['e'], {}), '(e)\n', (7136, 7139), False, 'from sentry_sdk import capture_exception\n'), ((6000, 6010), 'constants.re.r.now', 're.r.now', ([], {}), '()\n', (6008, 6010), True, 'import constants.re as re\n'), ((6311, 6355), 'xenadapter.task.get_userids', 'get_userids', (['object_type', 'object_ref', 'action'], {}), '(object_type, object_ref, action)\n', (6322, 6355), False, 'from xenadapter.task import get_userids\n'), ((6561, 6571), 'constants.re.r.now', 're.r.now', ([], {}), '()\n', (6569, 6571), True, 'import constants.re as re\n'), ((7051, 7061), 'constants.re.r.now', 're.r.now', ([], {}), '()\n', (7059, 7061), True, 'import constants.re as re\n'), ((7304, 7314), 'constants.re.r.now', 're.r.now', ([], {}), '()\n', (7312, 7314), True, 'import constants.re as re\n'), ((6594, 6614), 'constants.re.db.table', 're.db.table', (['"""tasks"""'], {}), "('tasks')\n", (6605, 6614), True, 'import constants.re as re\n'), ((7391, 7411), 'constants.re.db.table', 're.db.table', (['"""tasks"""'], {}), "('tasks')\n", (7402, 7411), True, 'import constants.re as re\n')] |
from django import template
from django.utils import timezone
register = template.Library()
@register.filter
def sold(oil, delta_months='12'):
total = 0
curTime = timezone.localtime(timezone.now())
from_time = curTime - timezone.timedelta(days=int(delta_months)*30)
for t in oil.trades.filter(dateTime__range=[from_time, curTime]).order_by('-dateTime'):
total += t.litreSold
return total
@register.filter
def last_checkin(oil):
last_checkin = oil.checkins.order_by('-date').last()
if last_checkin:
return last_checkin.date.strftime("%b %d, %Y")
else:
return ''
@register.filter
def checkin_cost(checkin):
cost = checkin.oil.price * checkin.bottles * checkin.oil.bottleVolume
if cost:
return round(cost, 2)
else:
return 0
@register.filter
def remaining_percent(sold, remainingLitres):
try:
if sold or sold > 0:
return 100 - round(float(sold) / (float(remainingLitres) + float(sold)) * 100, 2)
else:
return 100
except (ValueError, ZeroDivisionError):
return None
@register.filter
def multiply(value, arg):
try:
if value:
return float(value) * float(arg)
else:
return 0
except ValueError:
return None
@register.filter
def divide(value, arg):
try:
if value:
return float(value) / float(arg)
else:
return None
except (ValueError, ZeroDivisionError):
return None
@register.filter
def get_item(dictionary, key):
if dictionary:
val = dictionary[key]
if val:
return val.data
else:
return ''
@register.filter
def get_dict_value_by_key(dictionary, key):
if dictionary:
return dictionary[key]
else:
return ''
@register.filter
def chart_height(oils):
base_height = 300
if oils:
return base_height + (int(oils.__len__()) // 15) * 50
else:
return base_height
| [
"django.utils.timezone.now",
"django.template.Library"
] | [((74, 92), 'django.template.Library', 'template.Library', ([], {}), '()\n', (90, 92), False, 'from django import template\n'), ((193, 207), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (205, 207), False, 'from django.utils import timezone\n')] |
from datetime import datetime
import py42.util as util
def test_convert_timestamp_to_str_returns_expected_str():
assert util.convert_timestamp_to_str(235123656) == "1977-06-14T08:07:36.000Z"
def test_convert_datetime_to_timestamp_str_returns_expected_str():
d = datetime(2020, 4, 19, 13, 3, 2, 3)
assert util.convert_datetime_to_timestamp_str(d) == "2020-04-19T13:03:02.000Z"
| [
"datetime.datetime",
"py42.util.convert_timestamp_to_str",
"py42.util.convert_datetime_to_timestamp_str"
] | [((275, 309), 'datetime.datetime', 'datetime', (['(2020)', '(4)', '(19)', '(13)', '(3)', '(2)', '(3)'], {}), '(2020, 4, 19, 13, 3, 2, 3)\n', (283, 309), False, 'from datetime import datetime\n'), ((127, 167), 'py42.util.convert_timestamp_to_str', 'util.convert_timestamp_to_str', (['(235123656)'], {}), '(235123656)\n', (156, 167), True, 'import py42.util as util\n'), ((321, 362), 'py42.util.convert_datetime_to_timestamp_str', 'util.convert_datetime_to_timestamp_str', (['d'], {}), '(d)\n', (359, 362), True, 'import py42.util as util\n')] |
import argparse
import collections
import os
import cv2
import numpy as np
import pandas as pd
import pretrainedmodels
import torch
import torch.optim as optim
import torchsummary
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from torchvision import datasets, models, transforms
from tqdm import tqdm
import skimage.io
from sklearn.metrics import f1_score
import torch.nn as nn
import torch.nn.functional as F
import config
import utils
import classification_dataset
from triplet_dataset import TripletDataset, TripletDatasetUpdate, TripletDatasetPredict
from logger import Logger
from experiments import MODELS
class EmbeddingsModel(nn.Module):
def __init__(self, nb_embeddings=config.NB_EMBEDDINGS):
super().__init__()
self.base_model = pretrainedmodels.resnet18()
self.fc = nn.Linear(2048, nb_embeddings)
def forward(self, x):
x = self.base_model.conv1(x)
x = self.base_model.bn1(x)
x = self.base_model.relu(x)
x = self.base_model.maxpool(x)
x = self.base_model.layer1(x)
x = self.base_model.layer2(x)
x = self.base_model.layer3(x)
x = self.base_model.layer4(x)
x = self.base_model.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
class TripletLoss(nn.Module):
def __init__(self, margin):
super().__init__()
self.margin = margin
def forward(self, anchor, positive, negative):
distance_positive = (anchor - positive).pow(2).sum(1)
distance_negative = (anchor - negative).pow(2).sum(1)
losses = F.relu(distance_positive - distance_negative + self.margin)
return losses.mean()
def train(model_name, run=None):
run_str = '' if run is None or run == '' else f'_{run}'
checkpoints_dir = f'../output/checkpoints_3/{model_name}{run_str}'
tensorboard_dir = f'../output/tensorboard_3/{model_name}{run_str}'
os.makedirs(checkpoints_dir, exist_ok=True)
os.makedirs(tensorboard_dir, exist_ok=True)
print('\n', model_name, '\n')
logger = Logger(tensorboard_dir)
model = EmbeddingsModel()
model = model.cuda()
dataset_train = TripletDataset(
is_train=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
crop_size=256
)
dataset_valid = TripletDataset(
is_train=False,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
crop_size=256
)
dataset_update_train = TripletDatasetUpdate(dataset_train)
dataset_update_valid = TripletDatasetUpdate(dataset_valid)
model.training = True
print('using sgd optimiser')
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-5)
scheduler = utils.CosineAnnealingLRWithRestarts(optimizer, T_max=8, T_mult=1.2)
print('Num training images: {} valid images: {}'.format(len(dataset_train), len(dataset_valid)))
data_loader_train = DataLoader(
dataset_train,
shuffle=True,
num_workers=8,
batch_size=64)
data_loader_valid = DataLoader(
dataset_valid,
shuffle=False,
num_workers=8,
batch_size=64)
data_loader_update_train = DataLoader(
dataset_update_train,
shuffle=False,
num_workers=8,
batch_size=64)
data_loader_update_valid = DataLoader(
dataset_update_valid,
shuffle=False,
num_workers=8,
batch_size=64)
criterium = TripletLoss(margin=1.0)
for epoch_num in range(512):
model.eval()
with torch.set_grad_enabled(False):
for iter_num, data in tqdm(enumerate(data_loader_update_train), total=len(data_loader_update_train)):
img = data['img'].cuda()
samples_idx = data['idx']
vectors = model(img).detach().cpu().numpy()
dataset_train.embeddings[samples_idx] = vectors
print(np.mean(dataset_train.embeddings, axis=0), np.std(dataset_train.embeddings, axis=0))
for iter_num, data in tqdm(enumerate(data_loader_update_valid), total=len(data_loader_update_valid)):
img = data['img'].cuda()
samples_idx = data['idx']
vectors = model(img).detach().cpu().numpy()
dataset_valid.embeddings[samples_idx] = vectors
print(np.mean(dataset_train.embeddings, axis=0), np.std(dataset_valid.embeddings, axis=0))
model.train()
epoch_loss = []
with torch.set_grad_enabled(True):
data_iter = tqdm(enumerate(data_loader_train), total=len(data_loader_train))
for iter_num, data in data_iter:
img = data['img'].cuda()
img_pos = data['img_pos'].cuda()
img_neg = data['img_neg'].cuda()
optimizer.zero_grad()
output = model(img)
output_pos = model(img_pos)
output_neg = model(img_neg)
loss = criterium(output, output_pos, output_neg)
epoch_loss.append(float(loss.detach().cpu()))
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.25)
optimizer.step()
data_iter.set_description(
f'{epoch_num} Loss: {np.mean(epoch_loss):1.4f}')
logger.scalar_summary(f'loss_train', np.mean(epoch_loss), epoch_num)
epoch_loss = []
with torch.set_grad_enabled(False):
data_iter = tqdm(enumerate(data_loader_valid), total=len(data_loader_valid))
for iter_num, data in data_iter:
img = data['img'].cuda()
img_pos = data['img_pos'].cuda()
img_neg = data['img_neg'].cuda()
output = model(img)
output_pos = model(img_pos)
output_neg = model(img_neg)
loss = criterium(output, output_pos, output_neg)
epoch_loss.append(float(loss))
data_iter.set_description(
f'{epoch_num} Loss: {np.mean(epoch_loss):1.4f}')
logger.scalar_summary(f'loss_valid', np.mean(epoch_loss), epoch_num)
logger.scalar_summary('lr', optimizer.param_groups[0]['lr'], epoch_num)
scheduler.step(metrics=np.mean(epoch_loss), epoch=epoch_num)
model.eval()
torch.save(
{
'epoch': epoch_num,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
},
f'{checkpoints_dir}/{epoch_num:03}.pt'
)
def predict(model_name, epoch_num, img_dir, sample_ids, run=None):
model = EmbeddingsModel()
model = model.cuda()
run_str = '' if run is None or run == '' else f'_{run}'
checkpoints_dir = f'../output/checkpoints_3/{model_name}{run_str}'
checkpoint = torch.load(f'{checkpoints_dir}/{epoch_num:03}.pt')
model.load_state_dict(checkpoint['model_state_dict'])
dataset = TripletDatasetPredict(sample_ids=sample_ids,
img_dir=img_dir,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
crop_size=256)
data_loader_update_train = DataLoader(
dataset,
shuffle=False,
num_workers=8,
batch_size=64)
results = []
results_idx = []
with torch.set_grad_enabled(False):
for data in tqdm(data_loader_update_train):
img = data['img'].cuda()
samples_idx = data['idx']
embeddings = model(img).detach().cpu().numpy()
results.append(embeddings)
results_idx.append(samples_idx)
# for image_id in tqdm(sample_ids):
# images = []
# for color in ['red', 'green', 'blue']:
# try:
# img = cv2.imread(f'{img_dir}/{image_id}_{color}.png', cv2.IMREAD_UNCHANGED)
# img = cv2.resize(img, (256, 256), interpolation=cv2.INTER_AREA).astype("uint8")
# images.append(img)
# except:
# print(f'failed to open {img_dir}/{image_id}_{color}.png')
# raise
#
# images = np.stack(images, axis=0).astype(np.float32) / 255.0
# images = torch.from_numpy(images).cuda()
# images = normalize(images)
# images = torch.unsqueeze(images, 0)
# embeddings = model(images)
# embeddings = embeddings.detach().cpu().numpy()
# # print(image_id, embeddings.flatten())
# results.append(embeddings)
results = np.concatenate(results, axis=0)
results_idx = np.concatenate(results_idx, axis=0)
utils.print_stats('results_idx diff', np.diff(results_idx))
return results
def predict_extra(model_name, epoch_num, run=None):
data = pd.read_csv('../input/folds_4_extra.csv')
embeddings = predict(model_name=model_name, epoch_num=epoch_num,
img_dir=config.TRAIN_DIR_EXTRA,
sample_ids=data.Id.values,
run=run)
torch.save(embeddings, '../output/embeddings_extra.pt')
for i in range(embeddings.shape[1]):
data[f'emb_{i}'] = embeddings[:, i]
print(np.mean(embeddings, axis=0), np.std(embeddings, axis=0))
data.to_csv('../input/emb_extra.csv', index=False)
def predict_train(model_name, epoch_num, run=None):
data = pd.read_csv('../input/train.csv')
embeddings = predict(model_name=model_name, epoch_num=epoch_num,
img_dir=config.TRAIN_DIR,
sample_ids=data.Id.values,
run=run)
torch.save(embeddings, '../output/embeddings_train.pt')
for i in range(embeddings.shape[1]):
data[f'emb_{i}'] = embeddings[:, i]
print(np.mean(embeddings, axis=0), np.std(embeddings, axis=0))
data.to_csv('../input/emb_train.csv', index=False)
def predict_test(model_name, epoch_num, run=None):
data = pd.read_csv('../input/sample_submission.csv')
embeddings = predict(model_name=model_name, epoch_num=epoch_num,
img_dir=config.TEST_DIR,
sample_ids=data.Id.values,
run=run)
torch.save(embeddings, '../output/embeddings_test.pt')
for i in range(embeddings.shape[1]):
data[f'emb_{i}'] = embeddings[:, i]
print(np.mean(embeddings, axis=0), np.std(embeddings, axis=0))
data.to_csv('../input/emb_test.csv', index=False)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('action', type=str, default='train')
parser.add_argument('--model', type=str, default='tr_resnet18_now_8')
parser.add_argument('--epoch', type=int, default=0)
args = parser.parse_args()
action = args.action
model = args.model
np.set_printoptions(precision=3, linewidth=200)
if action == 'train':
try:
train(model_name=model)
except KeyboardInterrupt:
pass
if action == 'predict_extra':
predict_extra(model_name=model, epoch_num=args.epoch, run=None)
if action == 'predict_train':
predict_train(model_name=model, epoch_num=args.epoch, run=None)
if action == 'predict_test':
predict_test(model_name=model, epoch_num=args.epoch, run=None)
| [
"pandas.read_csv",
"utils.CosineAnnealingLRWithRestarts",
"numpy.mean",
"argparse.ArgumentParser",
"numpy.diff",
"numpy.concatenate",
"triplet_dataset.TripletDatasetUpdate",
"torchvision.transforms.ToTensor",
"logger.Logger",
"torch.save",
"numpy.std",
"torch.nn.functional.relu",
"torchvisio... | [((1957, 2000), 'os.makedirs', 'os.makedirs', (['checkpoints_dir'], {'exist_ok': '(True)'}), '(checkpoints_dir, exist_ok=True)\n', (1968, 2000), False, 'import os\n'), ((2005, 2048), 'os.makedirs', 'os.makedirs', (['tensorboard_dir'], {'exist_ok': '(True)'}), '(tensorboard_dir, exist_ok=True)\n', (2016, 2048), False, 'import os\n'), ((2097, 2120), 'logger.Logger', 'Logger', (['tensorboard_dir'], {}), '(tensorboard_dir)\n', (2103, 2120), False, 'from logger import Logger\n'), ((2712, 2747), 'triplet_dataset.TripletDatasetUpdate', 'TripletDatasetUpdate', (['dataset_train'], {}), '(dataset_train)\n', (2732, 2747), False, 'from triplet_dataset import TripletDataset, TripletDatasetUpdate, TripletDatasetPredict\n'), ((2775, 2810), 'triplet_dataset.TripletDatasetUpdate', 'TripletDatasetUpdate', (['dataset_valid'], {}), '(dataset_valid)\n', (2795, 2810), False, 'from triplet_dataset import TripletDataset, TripletDatasetUpdate, TripletDatasetPredict\n'), ((2975, 3042), 'utils.CosineAnnealingLRWithRestarts', 'utils.CosineAnnealingLRWithRestarts', (['optimizer'], {'T_max': '(8)', 'T_mult': '(1.2)'}), '(optimizer, T_max=8, T_mult=1.2)\n', (3010, 3042), False, 'import utils\n'), ((3170, 3239), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_train'], {'shuffle': '(True)', 'num_workers': '(8)', 'batch_size': '(64)'}), '(dataset_train, shuffle=True, num_workers=8, batch_size=64)\n', (3180, 3239), False, 'from torch.utils.data import DataLoader\n'), ((3298, 3368), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_valid'], {'shuffle': '(False)', 'num_workers': '(8)', 'batch_size': '(64)'}), '(dataset_valid, shuffle=False, num_workers=8, batch_size=64)\n', (3308, 3368), False, 'from torch.utils.data import DataLoader\n'), ((3434, 3511), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_update_train'], {'shuffle': '(False)', 'num_workers': '(8)', 'batch_size': '(64)'}), '(dataset_update_train, shuffle=False, num_workers=8, batch_size=64)\n', (3444, 3511), False, 'from torch.utils.data import DataLoader\n'), ((3577, 3654), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_update_valid'], {'shuffle': '(False)', 'num_workers': '(8)', 'batch_size': '(64)'}), '(dataset_update_valid, shuffle=False, num_workers=8, batch_size=64)\n', (3587, 3654), False, 'from torch.utils.data import DataLoader\n'), ((7147, 7197), 'torch.load', 'torch.load', (['f"""{checkpoints_dir}/{epoch_num:03}.pt"""'], {}), "(f'{checkpoints_dir}/{epoch_num:03}.pt')\n", (7157, 7197), False, 'import torch\n'), ((7729, 7793), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'shuffle': '(False)', 'num_workers': '(8)', 'batch_size': '(64)'}), '(dataset, shuffle=False, num_workers=8, batch_size=64)\n', (7739, 7793), False, 'from torch.utils.data import DataLoader\n'), ((9140, 9171), 'numpy.concatenate', 'np.concatenate', (['results'], {'axis': '(0)'}), '(results, axis=0)\n', (9154, 9171), True, 'import numpy as np\n'), ((9190, 9225), 'numpy.concatenate', 'np.concatenate', (['results_idx'], {'axis': '(0)'}), '(results_idx, axis=0)\n', (9204, 9225), True, 'import numpy as np\n'), ((9374, 9415), 'pandas.read_csv', 'pd.read_csv', (['"""../input/folds_4_extra.csv"""'], {}), "('../input/folds_4_extra.csv')\n", (9385, 9415), True, 'import pandas as pd\n'), ((9632, 9687), 'torch.save', 'torch.save', (['embeddings', '"""../output/embeddings_extra.pt"""'], {}), "(embeddings, '../output/embeddings_extra.pt')\n", (9642, 9687), False, 'import torch\n'), ((9962, 9995), 'pandas.read_csv', 'pd.read_csv', (['"""../input/train.csv"""'], {}), "('../input/train.csv')\n", (9973, 9995), True, 'import pandas as pd\n'), ((10206, 10261), 'torch.save', 'torch.save', (['embeddings', '"""../output/embeddings_train.pt"""'], {}), "(embeddings, '../output/embeddings_train.pt')\n", (10216, 10261), False, 'import torch\n'), ((10535, 10580), 'pandas.read_csv', 'pd.read_csv', (['"""../input/sample_submission.csv"""'], {}), "('../input/sample_submission.csv')\n", (10546, 10580), True, 'import pandas as pd\n'), ((10790, 10844), 'torch.save', 'torch.save', (['embeddings', '"""../output/embeddings_test.pt"""'], {}), "(embeddings, '../output/embeddings_test.pt')\n", (10800, 10844), False, 'import torch\n'), ((11095, 11120), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (11118, 11120), False, 'import argparse\n'), ((11397, 11444), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(3)', 'linewidth': '(200)'}), '(precision=3, linewidth=200)\n', (11416, 11444), True, 'import numpy as np\n'), ((793, 820), 'pretrainedmodels.resnet18', 'pretrainedmodels.resnet18', ([], {}), '()\n', (818, 820), False, 'import pretrainedmodels\n'), ((839, 869), 'torch.nn.Linear', 'nn.Linear', (['(2048)', 'nb_embeddings'], {}), '(2048, nb_embeddings)\n', (848, 869), True, 'import torch.nn as nn\n'), ((1626, 1685), 'torch.nn.functional.relu', 'F.relu', (['(distance_positive - distance_negative + self.margin)'], {}), '(distance_positive - distance_negative + self.margin)\n', (1632, 1685), True, 'import torch.nn.functional as F\n'), ((7875, 7904), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (7897, 7904), False, 'import torch\n'), ((7926, 7956), 'tqdm.tqdm', 'tqdm', (['data_loader_update_train'], {}), '(data_loader_update_train)\n', (7930, 7956), False, 'from tqdm import tqdm\n'), ((9268, 9288), 'numpy.diff', 'np.diff', (['results_idx'], {}), '(results_idx)\n', (9275, 9288), True, 'import numpy as np\n'), ((9784, 9811), 'numpy.mean', 'np.mean', (['embeddings'], {'axis': '(0)'}), '(embeddings, axis=0)\n', (9791, 9811), True, 'import numpy as np\n'), ((9813, 9839), 'numpy.std', 'np.std', (['embeddings'], {'axis': '(0)'}), '(embeddings, axis=0)\n', (9819, 9839), True, 'import numpy as np\n'), ((10358, 10385), 'numpy.mean', 'np.mean', (['embeddings'], {'axis': '(0)'}), '(embeddings, axis=0)\n', (10365, 10385), True, 'import numpy as np\n'), ((10387, 10413), 'numpy.std', 'np.std', (['embeddings'], {'axis': '(0)'}), '(embeddings, axis=0)\n', (10393, 10413), True, 'import numpy as np\n'), ((10941, 10968), 'numpy.mean', 'np.mean', (['embeddings'], {'axis': '(0)'}), '(embeddings, axis=0)\n', (10948, 10968), True, 'import numpy as np\n'), ((10970, 10996), 'numpy.std', 'np.std', (['embeddings'], {'axis': '(0)'}), '(embeddings, axis=0)\n', (10976, 10996), True, 'import numpy as np\n'), ((3797, 3826), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (3819, 3826), False, 'import torch\n'), ((4739, 4767), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (4761, 4767), False, 'import torch\n'), ((5631, 5650), 'numpy.mean', 'np.mean', (['epoch_loss'], {}), '(epoch_loss)\n', (5638, 5650), True, 'import numpy as np\n'), ((5701, 5730), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (5723, 5730), False, 'import torch\n'), ((6402, 6421), 'numpy.mean', 'np.mean', (['epoch_loss'], {}), '(epoch_loss)\n', (6409, 6421), True, 'import numpy as np\n'), ((4168, 4209), 'numpy.mean', 'np.mean', (['dataset_train.embeddings'], {'axis': '(0)'}), '(dataset_train.embeddings, axis=0)\n', (4175, 4209), True, 'import numpy as np\n'), ((4211, 4251), 'numpy.std', 'np.std', (['dataset_train.embeddings'], {'axis': '(0)'}), '(dataset_train.embeddings, axis=0)\n', (4217, 4251), True, 'import numpy as np\n'), ((4594, 4635), 'numpy.mean', 'np.mean', (['dataset_train.embeddings'], {'axis': '(0)'}), '(dataset_train.embeddings, axis=0)\n', (4601, 4635), True, 'import numpy as np\n'), ((4637, 4677), 'numpy.std', 'np.std', (['dataset_valid.embeddings'], {'axis': '(0)'}), '(dataset_valid.embeddings, axis=0)\n', (4643, 4677), True, 'import numpy as np\n'), ((6547, 6566), 'numpy.mean', 'np.mean', (['epoch_loss'], {}), '(epoch_loss)\n', (6554, 6566), True, 'import numpy as np\n'), ((2288, 2309), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2307, 2309), False, 'from torchvision import datasets, models, transforms\n'), ((2323, 2389), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (2343, 2389), False, 'from torchvision import datasets, models, transforms\n'), ((2542, 2563), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2561, 2563), False, 'from torchvision import datasets, models, transforms\n'), ((2577, 2643), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (2597, 2643), False, 'from torchvision import datasets, models, transforms\n'), ((7476, 7497), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (7495, 7497), False, 'from torchvision import datasets, models, transforms\n'), ((7539, 7605), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (7559, 7605), False, 'from torchvision import datasets, models, transforms\n'), ((5557, 5576), 'numpy.mean', 'np.mean', (['epoch_loss'], {}), '(epoch_loss)\n', (5564, 5576), True, 'import numpy as np\n'), ((6328, 6347), 'numpy.mean', 'np.mean', (['epoch_loss'], {}), '(epoch_loss)\n', (6335, 6347), True, 'import numpy as np\n')] |
import functools
import numpy as np
def dft2(f, alpha, npix=None, shift=(0, 0), offset=(0, 0), unitary=True, out=None):
"""Compute the 2-dimensional discrete Fourier Transform.
This function allows independent control over input shape, output shape,
and output sampling by implementing the matrix triple product algorithm
described in [1].
Parameters
----------
f : array_like
2D array to Fourier Transform
alpha : float or array_like
Output plane sampling interval (frequency). If :attr:`alpha` is an
array, ``alpha[1]`` represents row-wise sampling and ``alpha[2]``
represents column-wise sampling. If :attr:`alpha` is a scalar,
``alpha[1] = alpha[2] = alpha`` gives uniform sampling across the rows
and columns of the output plane.
npix : int or array_like, optional
Size of the output array :attr:`F`. If :attr:`npix` is an array,
``F.shape = (npix[1], npix[2])``. If :attr:`npi`` is a scalar,
``F.shape = (npix, npix)``. Default is ``f.shape``.
shift : array_like, optional
Number of pixels in (r,c) to shift the DC pixel in the output plane
with the origin centrally located in the plane. Default is ``(0,0)``.
offset : array_like, optional
Number of pixels in (r,c) that the input plane is shifted relative to
the origin. Default is ``(0,0)``.
unitary : bool, optional
Normalization flag. If ``True``, a normalization is performed on the
output such that the DFT operation is unitary and energy is conserved
through the Fourier transform operation (Parseval's theorem). In this
way, the energy in in a limited-area DFT is a fraction of the total
energy corresponding to the limited area. Default is ``True``.
out : ndarray or None
A location into which the result is stored. If provided, it must have
shape = npix and dtype = np.complex. If not provided or None, a
freshly-allocated array is returned.
Returns
-------
F : complex ndarray
Notes
-----
* Setting ``alpha = 1/f.shape`` and ``npix = f.shape`` is equivalent to
::
F = np.fft.ifftshift(np.fft.fft2(np.fft.fftshift(f)))
* ``dft2()`` is designed to place the DC pixel in the same location as a
well formed call to any standard FFT for both even and odd sized input
arrays. The DC pixel is located at ``np.floor(npix/2) + 1``, which is
consistent with calls to Numpy's FFT method where the input and output
are correctly shifted:
``np.fft.ifftshift(np.fft.fft2(np.fft.fftshift(f)))``.
* If the y-axis shift behavior is not what you are expecting, you most
likely have your plotting axes flipped (matplotlib's default behavior is
to place [0,0] in the upper left corner of the axes). This may be resolved
by either flipping the sign of the y component of ``shift`` or by passing
``origin = 'lower'`` to ``imshow()``.
References
----------
[1] Soummer, et. al. Fast computation of Lyot-style coronagraph propagation (2007)
"""
alpha_row, alpha_col = _sanitize_alpha(alpha)
f = np.asarray(f)
m, n = f.shape
if npix is None:
npix = [m, n]
M, N = _sanitize_npix(npix)
shift_row, shift_col = _sanitize_shift(shift)
offset_row, offset_col = _sanitize_npix(offset)
if out is not None:
if not np.can_cast(complex, out.dtype):
raise TypeError(f"Cannot cast complex output to dtype('{out.dtype}')")
E1, E2 = _dft2_matrices(m, n, M, N, alpha_row, alpha_col, shift_row, shift_col,
offset_row, offset_col)
F = np.dot(E1.dot(f), E2, out=out)
# now calculate the answer, without reallocating memory
if unitary:
np.multiply(F, np.sqrt(np.abs(alpha_row * alpha_col)), out=F)
return F
@functools.lru_cache(maxsize=32)
def _dft2_matrices(m, n, M, N, alphar, alphac, shiftr, shiftc, offsetr, offsetc):
R, S, U, V = _dft2_coords(m, n, M, N)
E1 = np.exp(-2.0 * 1j * np.pi * alphar * np.outer(R-shiftr+offsetr, U-shiftr)).T
E2 = np.exp(-2.0 * 1j * np.pi * alphac * np.outer(S-shiftc+offsetc, V-shiftc))
return E1, E2
@functools.lru_cache(maxsize=32)
def _dft2_coords(m, n, M, N):
# R and S are (r,c) coordinates in the (m x n) input plane f
# V and U are (r,c) coordinates in the (M x N) output plane F
R = np.arange(m) - np.floor(m/2.0)
S = np.arange(n) - np.floor(n/2.0)
U = np.arange(M) - np.floor(M/2.0)
V = np.arange(N) - np.floor(N/2.0)
return R, S, U, V
def idft2(F, alpha, npix=None, shift=(0,0), unitary=True, out=None):
"""Compute the 2-dimensional inverse discrete Fourier Transform.
This function allows independent control over input shape, output shape,
and output sampling by implementing the matrix triple product algorithm
described in [1].
Parameters
----------
F : array_like
2D array to Fourier Transform
alpha : float or array_like
Input plane sampling interval (frequency). If :attr:`alpha` is an array,
``alpha[1]`` represents row-wise sampling and ``alpha[2]`` represents
column-wise sampling. If :attr:`alpha` is a scalar,
``alpha[1] = alpha[2] = alpha`` represents uniform sampling across the
rows and columns of the input plane.
npix : int or array_like, optional
Size of the output array :attr:`F`. If :attr:`npix` is an array,
``F.shape = (npix[1], npix[2])``. If :attr:`npix` is a scalar,
``F.shape = (npix, npix)``. Default is ``F.shape``
shift : array_like, optional
Number of pixels in (x,y) to shift the DC pixel in the output plane with
the origin centrally located in the plane. Default is `[0,0]`.
unitary : bool, optional
Normalization flag. If ``True``, a normalization is performed on the
output such that the DFT operation is unitary and energy is conserved
through the Fourier transform operation (Parseval's theorem). In this
way, the energy in in a limited-area DFT is a fraction of the total
energy corresponding to the limited area. Default is ``True``.
Returns
-------
f : complex ndarray
Notes
-----
* Setting ``alpha = 1/F.shape`` and ``npix = F.shape`` is equivalent to
::
F = np.fft.ifftshift(np.fft.ifft2(np.fft.fftshift(F)))
* ``idft2()`` is designed to place the DC pixel in the same location as a
well formed call to any standard FFT for both even and odd sized input
arrays. The DC pixel is located at ``np.floor(npix/2) + 1``, which is
consistent with calls to Numpy's IFFT method where the input and output
are correctly shifted:
``np.fft.ifftshift(np.fft.ifft2(np.fft.fftshift(f)))``.
* If the y-axis shift behavior is not what you are expecting, you most
likely have your plotting axes flipped (matplotlib's default behavior is
to place [0,0] in the upper left corner of the axes). This may be resolved
by either flipping the sign of the y component of ``shift`` or by passing
``origin = 'lower'`` to ``imshow()``.
References
----------
[1] Soummer, et. al. Fast computation of Lyot-style coronagraph propagation (2007)
[2] `Expressing the inverse DFT in terms of the DFT <https://en.wikipedia.org/wiki/Discrete_Fourier_transform#Expressing_the_inverse_DFT_in_terms_of_the_DFT>`_.
"""
F = np.asarray(F)
N = F.size
# will allocate memory for F if out == None
F = dft2(np.conj(F), alpha, npix, shift, unitary=unitary, out=out)
np.conj(F, out=F)
return np.divide(F, N, out=F)
def _sanitize_alpha(x):
"""Return consistent representation of alpha as ar, ac"""
x = np.asarray(x)
if x.size == 1:
ar, ac = float(x), float(x)
else:
ar, ac = float(x[0]), float(x[1])
return ar, ac
def _sanitize_npix(x):
"""Return consistent representation of npix as M, N"""
x = np.asarray(x)
if x.size == 1:
M, N = int(x), int(x)
else:
M, N = int(x[0]), int(x[1])
return M, N
def _sanitize_shift(x):
"""Return consistent representation of shift as sr, sc"""
if isinstance(x, np.ndarray):
sr, sc = float(x[0]), float(x[1])
else:
sr, sc = x
return sr, sc
| [
"numpy.abs",
"numpy.arange",
"numpy.conj",
"numpy.asarray",
"numpy.floor",
"numpy.can_cast",
"numpy.outer",
"functools.lru_cache",
"numpy.divide"
] | [((3906, 3937), 'functools.lru_cache', 'functools.lru_cache', ([], {'maxsize': '(32)'}), '(maxsize=32)\n', (3925, 3937), False, 'import functools\n'), ((4251, 4282), 'functools.lru_cache', 'functools.lru_cache', ([], {'maxsize': '(32)'}), '(maxsize=32)\n', (4270, 4282), False, 'import functools\n'), ((3198, 3211), 'numpy.asarray', 'np.asarray', (['f'], {}), '(f)\n', (3208, 3211), True, 'import numpy as np\n'), ((7523, 7536), 'numpy.asarray', 'np.asarray', (['F'], {}), '(F)\n', (7533, 7536), True, 'import numpy as np\n'), ((7675, 7692), 'numpy.conj', 'np.conj', (['F'], {'out': 'F'}), '(F, out=F)\n', (7682, 7692), True, 'import numpy as np\n'), ((7704, 7726), 'numpy.divide', 'np.divide', (['F', 'N'], {'out': 'F'}), '(F, N, out=F)\n', (7713, 7726), True, 'import numpy as np\n'), ((7823, 7836), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (7833, 7836), True, 'import numpy as np\n'), ((8055, 8068), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (8065, 8068), True, 'import numpy as np\n'), ((4453, 4465), 'numpy.arange', 'np.arange', (['m'], {}), '(m)\n', (4462, 4465), True, 'import numpy as np\n'), ((4468, 4485), 'numpy.floor', 'np.floor', (['(m / 2.0)'], {}), '(m / 2.0)\n', (4476, 4485), True, 'import numpy as np\n'), ((4492, 4504), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (4501, 4504), True, 'import numpy as np\n'), ((4507, 4524), 'numpy.floor', 'np.floor', (['(n / 2.0)'], {}), '(n / 2.0)\n', (4515, 4524), True, 'import numpy as np\n'), ((4531, 4543), 'numpy.arange', 'np.arange', (['M'], {}), '(M)\n', (4540, 4543), True, 'import numpy as np\n'), ((4546, 4563), 'numpy.floor', 'np.floor', (['(M / 2.0)'], {}), '(M / 2.0)\n', (4554, 4563), True, 'import numpy as np\n'), ((4570, 4582), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (4579, 4582), True, 'import numpy as np\n'), ((4585, 4602), 'numpy.floor', 'np.floor', (['(N / 2.0)'], {}), '(N / 2.0)\n', (4593, 4602), True, 'import numpy as np\n'), ((7613, 7623), 'numpy.conj', 'np.conj', (['F'], {}), '(F)\n', (7620, 7623), True, 'import numpy as np\n'), ((3450, 3481), 'numpy.can_cast', 'np.can_cast', (['complex', 'out.dtype'], {}), '(complex, out.dtype)\n', (3461, 3481), True, 'import numpy as np\n'), ((4192, 4234), 'numpy.outer', 'np.outer', (['(S - shiftc + offsetc)', '(V - shiftc)'], {}), '(S - shiftc + offsetc, V - shiftc)\n', (4200, 4234), True, 'import numpy as np\n'), ((3850, 3879), 'numpy.abs', 'np.abs', (['(alpha_row * alpha_col)'], {}), '(alpha_row * alpha_col)\n', (3856, 3879), True, 'import numpy as np\n'), ((4107, 4149), 'numpy.outer', 'np.outer', (['(R - shiftr + offsetr)', '(U - shiftr)'], {}), '(R - shiftr + offsetr, U - shiftr)\n', (4115, 4149), True, 'import numpy as np\n')] |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import N_A
from numba import jit
import copy
__author__ = "<NAME>, <NAME>, <NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright 2020, The Materials Project"
__version__ = "0.1"
"""
Kinetic Monte Carlo (kMC) simulation for a reaction network, assuming spatial homogeneity. Simulation can be performed
with and without ReactionNetwork objects. The version without ReactionNetwork objects is computationally cheaper.
The algorithm is described by Gillespie (1976).
"""
def initialize_simulation(reaction_network, initial_cond, volume=10 ** -24):
"""
Initial loop through reactions to create lists, mappings, and initial states needed for simulation without
reaction network objects.
Args:
reaction_network: Fully generated ReactionNetwork
initial_cond: dict mapping mol_index to initial concentration [M]. mol_index is entry position in
reaction_network.entries_list
volume: float of system volume
:return:
initial_state: array of initial molecule amounts, indexed corresponding to reaction_network.entries_list
initial_state_dict: dict mapping molecule index to initial molecule amounts
species_rxn_mapping: 2d array; each row i contains reactions which molecule_i takes part in
molid_index_mapping: mapping between species entry id and its molecule index
reactants_array: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
products_array: (n_rxns x 2) array, each row containing product mol_index of forward reaction
coord_array: (2*n_rxns x 1) array, with coordination number of each for and rev rxn: [c1_f, c1_r, c2_f, c2_r...]
rate_constants: (2*n_rxns x 1) array, with rate constant of each for and rev rxn: [k1_f, k1_r, k2_f, k2_r ...]
propensities: (2*n_rxns x 1) array of reaction propensities, defined as coord_num*rate_constant
"""
num_rxns = len(reaction_network.reactions)
num_species = len(reaction_network.entries_list)
molid_index_mapping = dict()
initial_state = [0 for i in range(num_species)]
initial_state_dict = dict()
for ind, mol in enumerate(reaction_network.entries_list):
molid_index_mapping[mol.entry_id] = ind
this_c = initial_cond.get(mol.entry_id, 0)
this_mol_amt = int(volume * N_A * 1000 * this_c)
initial_state[ind] = this_mol_amt
if mol.entry_id in initial_cond:
initial_state_dict[ind] = this_mol_amt
# Initially compile each species' reactions in lists, later convert to a 2d array
species_rxn_mapping_list = [[] for j in range(num_species)]
reactant_array = -1 * np.ones((num_rxns, 2), dtype=int)
product_array = -1 * np.ones((num_rxns, 2), dtype=int)
coord_array = np.zeros(2 * num_rxns)
rate_constants = np.zeros(2 * num_rxns)
for id, reaction in enumerate(reaction_network.reactions):
# Keep track of reactant amounts, for later calculating coordination number
num_reactants_for = list()
num_reactants_rev = list()
rate_constants[2 * id] = reaction.k_A
rate_constants[2 * id + 1] = reaction.k_B
for idx, react in enumerate(reaction.reactants):
# for each reactant, need to find the corresponding mol_id with the index
mol_ind = molid_index_mapping[react.entry_id]
reactant_array[id, idx] = mol_ind
species_rxn_mapping_list[mol_ind].append(2 * id)
num_reactants_for.append(initial_state[mol_ind])
for idx, prod in enumerate(reaction.products):
mol_ind = molid_index_mapping[prod.entry_id]
product_array[id, idx] = mol_ind
species_rxn_mapping_list[mol_ind].append(2 * id + 1)
num_reactants_rev.append(initial_state[mol_ind])
if len(reaction.reactants) == 1:
coord_array[2 * id] = num_reactants_for[0]
elif (len(reaction.reactants) == 2) and (
reaction.reactants[0] == reaction.reactants[1]
):
coord_array[2 * id] = num_reactants_for[0] * (num_reactants_for[0] - 1)
elif (len(reaction.reactants) == 2) and (
reaction.reactants[0] != reaction.reactants[1]
):
coord_array[2 * id] = num_reactants_for[0] * num_reactants_for[1]
else:
raise RuntimeError(
"Only single and bimolecular reactions supported by this simulation"
)
# For reverse reaction
if len(reaction.products) == 1:
coord_array[2 * id + 1] = num_reactants_rev[0]
elif (len(reaction.products) == 2) and (
reaction.products[0] == reaction.products[1]
):
coord_array[2 * id + 1] = num_reactants_rev[0] * (num_reactants_rev[0] - 1)
elif (len(reaction.products) == 2) and (
reaction.products[0] != reaction.products[1]
):
coord_array[2 * id + 1] = num_reactants_rev[0] * num_reactants_rev[1]
else:
raise RuntimeError(
"Only single and bimolecular reactions supported by this simulation"
)
rxn_mapping_lengths = [len(rxn_list) for rxn_list in species_rxn_mapping_list]
max_mapping_length = max(rxn_mapping_lengths)
species_rxn_mapping = -1 * np.ones((num_species, max_mapping_length), dtype=int)
for index, rxn_list in enumerate(species_rxn_mapping_list):
this_map_length = rxn_mapping_lengths[index]
if this_map_length == max_mapping_length:
species_rxn_mapping[index, :] = rxn_list
else:
species_rxn_mapping[
index, : this_map_length - max_mapping_length
] = rxn_list
propensities = np.multiply(coord_array, rate_constants)
return [
np.array(initial_state, dtype=int),
initial_state_dict,
species_rxn_mapping,
reactant_array,
product_array,
coord_array,
rate_constants,
propensities,
molid_index_mapping,
]
@jit(nopython=True, parallel=True)
def kmc_simulate(
time_steps,
coord_array,
rate_constants,
propensity_array,
species_rxn_mapping,
reactants,
products,
state,
):
"""
KMC Simulation of reaction network and specified initial conditions. Args are all Numpy arrays, to allow
computational speed up with Numba.
Args:
time_steps: int number of time steps desired to run
coord_array: array containing coordination numbers of for and rev rxns.
rate_constants: array containing rate constants of for and rev rxns
propensity_array: array containing propensities of for and rev rxns
species_rxn_mapping: 2d array; each row i contains reactions which molecule_i takes part in
reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
products: (n_rxns x 2) array, each row containing product mol_index of forward reaction
state: array of initial molecule amounts, indexed corresponding to reaction_network.entries_list
:return: A (2 x time_steps) Numpy array. First row contains the indeces of reactions that occurred.
Second row are the time steps generated at each iteration.
"""
total_propensity = np.sum(propensity_array)
reaction_history = [0 for step in range(time_steps)]
times = [0.0 for step in range(time_steps)]
relevant_ind = np.where(propensity_array > 0)[
0
] # Take advantage of sparsity - many propensities will be 0.
for step_counter in range(time_steps):
r1 = random.random()
r2 = random.random()
tau = -np.log(r1) / total_propensity
random_propensity = r2 * total_propensity
abrgd_reaction_choice_ind = np.where(
np.cumsum(propensity_array[relevant_ind]) >= random_propensity
)[0][0]
reaction_choice_ind = relevant_ind[abrgd_reaction_choice_ind]
converted_rxn_ind = math.floor(reaction_choice_ind / 2)
if reaction_choice_ind % 2:
reverse = True
else:
reverse = False
state = update_state(reactants, products, state, converted_rxn_ind, reverse)
# Log the reactions that need to be altered after reaction is performed, for the coordination array
reactions_to_change = list()
for reactant_id in reactants[converted_rxn_ind, :]:
if reactant_id == -1:
continue
else:
reactions_to_change.extend(list(species_rxn_mapping[reactant_id, :]))
for product_id in products[converted_rxn_ind, :]:
if product_id == -1:
continue
else:
reactions_to_change.extend(list(species_rxn_mapping[product_id, :]))
rxns_change = set(reactions_to_change)
for rxn_ind in rxns_change:
if rxn_ind == -1:
continue
elif rxn_ind % 2:
this_reverse = True
else:
this_reverse = False
this_h = get_coordination(
reactants, products, state, math.floor(rxn_ind / 2), this_reverse
)
coord_array[rxn_ind] = this_h
propensity_array = np.multiply(rate_constants, coord_array)
relevant_ind = np.where(propensity_array > 0)[0]
total_propensity = np.sum(propensity_array[relevant_ind])
reaction_history[step_counter] = int(reaction_choice_ind)
times[step_counter] = tau
return np.vstack((np.array(reaction_history), np.array(times)))
@jit(nopython=True)
def update_state(reactants, products, state, rxn_ind, reverse):
"""
Updating the system state based on chosen reaction, during kMC simulation.
Args:
reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
products: (n_rxns x 2) array, each row containing product mol_index of forward reaction
state: array of initial molecule amounts, indexed corresponding to reaction_network.entries_list
rxn_ind: int of reaction index, corresponding to position in reaction_network.reactions list
reverse: bool of whether this is the reverse reaction or not
:return: updated state array, after performing the specified reaction
"""
if rxn_ind == -1:
raise RuntimeError("Incorrect reaction index when updating state")
if reverse:
for reactant_id in products[rxn_ind, :]:
if reactant_id == -1:
continue
else:
state[reactant_id] -= 1
if state[reactant_id] < 0:
raise ValueError("State invalid! Negative specie encountered")
for product_id in reactants[rxn_ind, :]:
if product_id == -1:
continue
else:
state[product_id] += 1
else:
for reactant_id in reactants[rxn_ind, :]:
if reactant_id == -1:
continue
else:
state[reactant_id] -= 1
if state[reactant_id] < 0:
raise ValueError("State invalid! Negative specie encountered")
for product_id in products[rxn_ind, :]:
if product_id == -1:
continue
else:
state[product_id] += 1
return state
@jit(nopython=True)
def get_coordination(reactants, products, state, rxn_id, reverse):
"""
Calculate the coordination number of a reaction, for reactions involving two reactions of less.
They are defined as follows:
A -> B; coord = n(A)
A + A --> B; coord = n(A) * (n(A) - 1)
A + B --> C; coord = n(A) * n(B)
Args:
reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
products: (n_rxns x 2) array, each row containing product mol_index of forward reaction
state: array of initial molecule amounts, indexed corresponding to reaction_network.entries_list
rxn_ind: int of reaction index, corresponding to position in reaction_network.reactions list
reverse: bool of whether this is the reverse reaction or not
:return: float of reaction coordination number
"""
if reverse:
reactant_array = products[rxn_id, :]
num_reactants = len(np.where(reactant_array != -1)[0])
else:
reactant_array = reactants[rxn_id, :]
num_reactants = len(np.where(reactant_array != -1)[0])
num_mols_list = list()
for reactant_id in reactant_array:
num_mols_list.append(state[reactant_id])
if num_reactants == 1:
h_prop = num_mols_list[0]
elif (num_reactants == 2) and (reactant_array[0] == reactant_array[1]):
h_prop = num_mols_list[0] * (num_mols_list[0] - 1) / 2
elif (num_reactants == 2) and (reactant_array[0] != reactant_array[1]):
h_prop = num_mols_list[0] * num_mols_list[1]
else:
raise RuntimeError(
"Only single and bimolecular reactions supported by this simulation"
)
return h_prop
class KmcDataAnalyzer:
"""
Functions to analyze (function-based) KMC outputs from many simulation runs. Ideally, the reaction history and
time history data are list of arrays.
Args:
reaction_network: fully generated ReactionNetwork, used for kMC simulation
molid_ind_mapping: dict mapping each entry's id to its index; of form {entry_id: mol_index, ... }
species_rxn_mapping: 2d array; each row i contains reactions which molecule_i takes part in
initial_state_dict: dict mapping mol_id to its initial amount {mol1_id: amt_1, mol2_id: amt2 ... }
products: (n_rxns x 2) array, each row containing product mol_index of forward reaction
reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
reaction_history: list of arrays of reaction histories of each simulation.
time_history: list of arrays of time histories of each simulation.
"""
def __init__(
self,
reaction_network,
molid_ind_mapping,
species_rxn_mapping,
initial_state_dict,
products,
reactants,
reaction_history,
time_history,
):
self.reaction_network = reaction_network
self.molid_ind_mapping = molid_ind_mapping
self.species_rxn_mapping = species_rxn_mapping
self.initial_state_dict = initial_state_dict
self.products = products
self.reactants = reactants
self.reaction_history = reaction_history
self.time_history = time_history
self.num_sims = len(self.reaction_history)
if self.num_sims != len(self.time_history):
raise RuntimeError(
"Number of datasets for rxn history and time step history should be same!"
)
self.molind_id_mapping = [
mol.entry_id for mol in self.reaction_network.entries_list
]
def generate_time_dep_profiles(self):
"""
Generate plottable time-dependent profiles of species and rxns from raw KMC output, obtain final states.
:return dict containing species profiles, reaction profiles, and final states from each simulation.
{species_profiles: [ {mol_ind1: [(t0, n(t0)), (t1, n(t1)...], mol_ind2: [...] , ... }, {...}, ... ]
reaction_profiles: [ {rxn_ind1: [t0, t1, ...], rxn_ind2: ..., ...}, {...}, ...]
final_states: [ {mol_ind1: n1, mol_ind2: ..., ...}, {...}, ...] }
"""
species_profiles = list()
reaction_profiles = list()
final_states = list()
for n_sim in range(self.num_sims):
sim_time_history = self.time_history[n_sim]
sim_rxn_history = self.reaction_history[n_sim]
sim_species_profile = dict()
sim_rxn_profile = dict()
cumulative_time = list(np.cumsum(np.array(sim_time_history)))
state = copy.deepcopy(self.initial_state_dict)
for mol_ind in state:
sim_species_profile[mol_ind] = [(0.0, self.initial_state_dict[mol_ind])]
total_iterations = len(sim_rxn_history)
for iter in range(total_iterations):
rxn_ind = sim_rxn_history[iter]
t = cumulative_time[iter]
if rxn_ind not in sim_rxn_profile:
sim_rxn_profile[rxn_ind] = [t]
else:
sim_rxn_profile[rxn_ind].append(t)
converted_ind = math.floor(rxn_ind / 2)
if rxn_ind % 2:
reacts = self.products[converted_ind, :]
prods = self.reactants[converted_ind, :]
else:
reacts = self.reactants[converted_ind, :]
prods = self.products[converted_ind, :]
for r_ind in reacts:
if r_ind == -1:
continue
else:
try:
state[r_ind] -= 1
if state[r_ind] < 0:
raise ValueError(
"State invalid: negative specie: {}".format(r_ind)
)
sim_species_profile[r_ind].append((t, state[r_ind]))
except KeyError:
raise ValueError(
"Reactant specie {} given is not in state!".format(
r_ind
)
)
for p_ind in prods:
if p_ind == -1:
continue
else:
if (p_ind in state) and (p_ind in sim_species_profile):
state[p_ind] += 1
sim_species_profile[p_ind].append((t, state[p_ind]))
else:
state[p_ind] = 1
sim_species_profile[p_ind] = [(0.0, 0), (t, state[p_ind])]
# for plotting convenience, add data point at final time
for mol_ind in sim_species_profile:
sim_species_profile[mol_ind].append(
(cumulative_time[-1], state[mol_ind])
)
species_profiles.append(sim_species_profile)
reaction_profiles.append(sim_rxn_profile)
final_states.append(state)
return {
"species_profiles": species_profiles,
"reaction_profiles": reaction_profiles,
"final_states": final_states,
}
def final_state_analysis(self, final_states):
"""
Gather statistical analysis of the final states of simulation.
Args:
final_states: list of dicts of final states, as generated in generate_time_dep_profiles()
:return: list of tuples containing statistical data for each species, sorted from highest to low avg occurrence
"""
state_arrays = (
dict()
) # For each molecule, compile an array of its final amounts
for iter, final_state in enumerate(final_states):
for mol_ind, amt in final_state.items():
# Store the amount, and convert key from mol_ind to entry_id
if self.molind_id_mapping[mol_ind] not in state_arrays:
state_arrays[self.molind_id_mapping[mol_ind]] = np.zeros(
self.num_sims
)
state_arrays[self.molind_id_mapping[mol_ind]][iter] = amt
analyzed_states = dict() # will contain statistical results of final states
for mol_entry, state_array in state_arrays.items():
analyzed_states[mol_entry] = (np.mean(state_array), np.std(state_array))
# Sort from highest avg final amount to lowest
sorted_analyzed_states = sorted(
[(entry_id, data_tup) for entry_id, data_tup in analyzed_states.items()],
key=lambda x: x[1][0],
reverse=True,
)
return sorted_analyzed_states
def plot_species_profiles(
self,
species_profiles,
final_states,
num_label=12,
num_plots=None,
filename=None,
file_dir=None,
):
"""
Sorting and plotting species profiles for a specified number of simulations. The profiles might be very similar,
so may not need to plot all of the runs for good understanding of results.
Args:
species_profiles: list of dicts of species as function of time, for each simulation
final_states: list of dicts of final states of each simulation
num_label: integer number of species in the legend
filename (str)
file_dir (str)
"""
if num_plots is None:
num_plots = self.num_sims
elif num_plots > self.num_sims:
num_plots = self.num_sims
for n_sim in range(num_plots):
# Sorting and plotting:
fig, ax = plt.subplots()
sorted_state = sorted(
[(k, v) for k, v in final_states[n_sim].items()],
key=lambda x: x[1],
reverse=True,
)
sorted_inds = [mol_tuple[0] for mol_tuple in sorted_state]
sorted_ind_id_mapping = dict()
iter_counter = 0
for id, ind in self.molid_ind_mapping.items():
if ind in sorted_inds[:num_label]:
sorted_ind_id_mapping[ind] = id
iter_counter += 1
if iter_counter == num_label:
break
colors = plt.cm.get_cmap("hsv", num_label)
this_id = 0
t_end = sum(self.time_history[n_sim])
for mol_ind in species_profiles[n_sim]:
# ts = np.append(np.array([e[0] for e in species_profiles[n_sim][mol_ind]]), t_end)
ts = np.array([e[0] for e in species_profiles[n_sim][mol_ind]])
nums = np.array([e[1] for e in species_profiles[n_sim][mol_ind]])
if mol_ind in sorted_inds[:num_label]:
mol_id = sorted_ind_id_mapping[mol_ind]
for entry in self.reaction_network.entries_list:
if mol_id == entry.entry_id:
this_composition = (
entry.molecule.composition.alphabetical_formula
)
this_charge = entry.molecule.charge
this_label = this_composition + " " + str(this_charge)
this_color = colors(this_id)
this_id += 1
break
ax.plot(ts, nums, label=this_label, color=this_color)
else:
ax.plot(ts, nums)
title = "KMC simulation, total time {}".format(t_end)
ax.set(title=title, xlabel="Time (s)", ylabel="# Molecules")
ax.legend(
loc="upper right", bbox_to_anchor=(1, 1), ncol=2, fontsize="small"
)
sim_filename = filename + "_run_" + str(n_sim + 1)
if file_dir is None:
plt.show()
else:
plt.savefig(file_dir + "/" + sim_filename)
def analyze_intermediates(self, species_profiles, cutoff=0.9):
"""
Identify intermediates from species vs time profiles. Species are intermediates if consumed nearly as much
as they are created.
Args:
species_profile: Dict of list of tuples, as generated in generate_time_dep_profiles()
cutoff: (float) fraction to adjust definition of intermediate
:return: Analyzed data in a dict, of the form:
{mol1: {'freqency': (float), 'lifetime': (avg, std), 't_max': (avg, std), 'amt_produced': (avg, std)},
mol2: {...}, ... }
"""
intermediates = dict()
for n_sim in range(self.num_sims):
for mol_ind, prof in species_profiles[n_sim].items():
history = np.array([t[1] for t in prof])
diff_history = np.diff(history)
max_amt = max(history)
amt_produced = np.sum(diff_history == 1)
amt_consumed = np.sum(diff_history == -1)
# Identify the intermediate, accounting for fluctuations
if (amt_produced >= 3) and (amt_consumed > amt_produced * cutoff):
if mol_ind not in intermediates:
intermediates[mol_ind] = dict()
intermediates[mol_ind]["lifetime"] = list()
intermediates[mol_ind]["amt_produced"] = list()
intermediates[mol_ind]["t_max"] = list()
intermediates[mol_ind]["amt_consumed"] = list()
# Intermediate lifetime is approximately the time from its max amount to when nearly all consumed
max_ind = np.where(history == max_amt)[0][0]
t_max = prof[max_ind][0]
for state in prof[max_ind + 1 :]:
if state[1] < (1 - cutoff) * amt_produced + history[0]:
intermediates[mol_ind]["lifetime"].append(state[0] - t_max)
intermediates[mol_ind]["t_max"].append(t_max)
intermediates[mol_ind]["amt_produced"].append(amt_produced)
intermediates[mol_ind]["amt_consumed"].append(amt_consumed)
break
intermediates_analysis = dict()
for mol_ind in intermediates:
entry_id = self.molind_id_mapping[mol_ind]
intermediates_analysis[entry_id] = dict() # convert keys to entry id
if len(intermediates[mol_ind]["lifetime"]) != len(
intermediates[mol_ind]["t_max"]
):
raise RuntimeError("Intermediates data should be of the same length")
intermediates_analysis[entry_id]["frequency"] = (
len(intermediates[mol_ind]["lifetime"]) / self.num_sims
)
lifetime_array = np.array(intermediates[mol_ind]["lifetime"])
intermediates_analysis[entry_id]["lifetime"] = (
np.mean(lifetime_array),
np.std(lifetime_array),
)
t_max_array = np.array(intermediates[mol_ind]["t_max"])
intermediates_analysis[entry_id]["t_max"] = (
np.mean(t_max_array),
np.std(t_max_array),
)
amt_produced_array = np.array(intermediates[mol_ind]["amt_produced"])
intermediates_analysis[entry_id]["amt_produced"] = (
np.mean(amt_produced_array),
np.std(amt_produced_array),
)
amt_consumed_array = np.array(intermediates[mol_ind]["amt_consumed"])
intermediates_analysis[entry_id]["amt_consumed"] = (
np.mean(amt_consumed_array),
np.std(amt_produced_array),
)
# Sort by highest average amount produced
sorted_intermediates_analysis = sorted(
[
(entry_id, mol_data)
for entry_id, mol_data in intermediates_analysis.items()
],
key=lambda x: x[1]["amt_produced"][0],
reverse=True,
)
return sorted_intermediates_analysis
def correlate_reactions(self, reaction_inds):
"""
Correlate two reactions, by finding the average time and steps elapsed for rxn2 to fire after rxn1,
and vice-versa.
Args:
reaction_inds: list, array, or tuple of two reaction indexes
:return: dict containing analysis of how reactions are correlated {rxn1: {'time': (float), 'steps': (float),
'occurrences': float}, rxn2: {...} }
"""
correlation_data = dict()
correlation_analysis = dict()
for rxn_ind in reaction_inds:
correlation_data[rxn_ind] = dict()
correlation_data[rxn_ind]["time"] = list()
correlation_data[rxn_ind]["steps"] = list()
correlation_data[rxn_ind]["occurrences"] = list()
correlation_analysis[rxn_ind] = dict()
for n_sim in range(self.num_sims):
cum_time = np.cumsum(self.time_history[n_sim])
rxn_locations = dict()
# Find the step numbers when reactions fire in the simulation
for rxn_ind in reaction_inds:
rxn_locations[rxn_ind] = list(
np.where(self.reaction_history[n_sim] == rxn_ind)[0]
)
rxn_locations[rxn_ind].append(len(self.reaction_history[n_sim]))
# Correlate between each reaction
for (rxn_ind, location_list) in rxn_locations.items():
time_elapse = list()
step_elapse = list()
occurrences = 0
for (rxn_ind_j, location_list_j) in rxn_locations.items():
if rxn_ind == rxn_ind_j:
continue
for i in range(1, len(location_list)):
for loc_j in location_list_j:
# Find location where reaction j happens after reaction i, before reaction i fires again
if (loc_j > location_list[i - 1]) and (
loc_j < location_list[i]
):
time_elapse.append(
cum_time[loc_j] - cum_time[location_list[i - 1]]
)
step_elapse.append(loc_j - location_list[i - 1])
occurrences += 1
break
if len(time_elapse) == 0:
correlation_data[rxn_ind]["occurrences"].append(0)
else:
correlation_data[rxn_ind]["time"].append(
np.mean(np.array(time_elapse))
)
correlation_data[rxn_ind]["steps"].append(
np.mean(np.array(step_elapse))
)
correlation_data[rxn_ind]["occurrences"].append(occurrences)
for rxn_ind, data_dict in correlation_data.items():
if len(data_dict["time"]) != 0:
correlation_analysis[rxn_ind]["time"] = (
np.mean(np.array(data_dict["time"])),
np.std(np.array(data_dict["time"])),
)
correlation_analysis[rxn_ind]["steps"] = (
np.mean(np.array(data_dict["steps"])),
np.std(np.array(data_dict["steps"])),
)
correlation_analysis[rxn_ind]["occurrences"] = (
np.mean(np.array(data_dict["occurrences"])),
np.std(np.array(data_dict["occurrences"])),
)
else:
print(
"Reaction ",
rxn_ind,
"does not lead to the other reaction in simulation ",
n_sim,
)
return correlation_analysis
def quantify_specific_reaction(self, reaction_history, reaction_index):
"""
Quantify a reaction from one simulation reaction history
Args:
reaction_history: array containing sequence of reactions fired during a simulation.
reaction_index: integer of reaction index of interest
:return: integer number of times reaction is fired
"""
if reaction_index not in reaction_history:
reaction_count = 0
else:
reaction_count = len(reaction_history[reaction_index])
return reaction_count
def quantify_rank_reactions(self, reaction_type=None, num_rxns=None):
"""
Given reaction histories, identify the most commonly occurring reactions, on average.
Can rank generally, or by reactions of a certain type.
Args:
reaction_profiles (list of dicts): reactions fired as a function of time
reaction_type (string)
num_rxns (int): the amount of reactions interested in collecting data on. If None, record for all.
Returns:
reaction_data: list of reactions and their avg, std of times fired. Sorted by the average times fired.
[(rxn1, (avg, std)), (rxn2, (avg, std)) ... ]
"""
allowed_rxn_types = [
"One electron reduction",
"One electron oxidation",
"Intramolecular single bond breakage",
"Intramolecular single bond formation",
"Coordination bond breaking AM -> A+M",
"Coordination bond forming A+M -> AM",
"Molecular decomposition breaking one bond A -> B+C",
"Molecular formation from one new bond A+B -> C",
"Concerted",
]
if reaction_type is not None:
rxns_of_type = list()
if reaction_type not in allowed_rxn_types:
raise RuntimeError(
"This reaction type does not (yet) exist in our reaction networks."
)
for ind, rxn in enumerate(self.reaction_network.reactions):
if rxn.reaction_type()["rxn_type_A"] == reaction_type:
rxns_of_type.append(2 * ind)
elif rxn.reaction_type()["rxn_type_B"] == reaction_type:
rxns_of_type.append(2 * ind + 1)
reaction_data = dict() # keeping record of each iteration
# Loop to count all reactions fired
for n_sim in range(self.num_sims):
rxns_fired = set(self.reaction_history[n_sim])
if reaction_type is not None:
relevant_rxns = [r for r in rxns_fired if r in rxns_of_type]
else:
relevant_rxns = rxns_fired
for rxn_ind in relevant_rxns:
if rxn_ind not in reaction_data:
reaction_data[rxn_ind] = list()
reaction_data[rxn_ind].append(
np.sum(self.reaction_history[n_sim] == rxn_ind)
)
reaction_analysis = dict()
for rxn_ind, counts in reaction_data.items():
reaction_analysis[rxn_ind] = (
np.mean(np.array(counts)),
np.std(np.array(counts)),
)
# Sort reactions by the average amount fired
sorted_reaction_analysis = sorted(
[(i, c) for i, c in reaction_analysis.items()],
key=lambda x: x[1][0],
reverse=True,
)
if num_rxns is None:
return sorted_reaction_analysis
else:
return sorted_reaction_analysis[:num_rxns]
def frequency_analysis(self, rxn_inds, spec_inds, partitions=100):
"""
Calculate the frequency of reaction and species formation as a function of time. Simulation data is
discretized into time intervals, and probabilities in each set are obtained.
Args:
rxn_inds: list of indeces of reactions of interest
spec_inds: list of molecule indexes of interest
partitions: number of intervals in which to discretize time
:return: dict of dicts containing the statistics of reaction fired, product formed at each time interval.
{reaction_data: {rxn_ind1: [(t0, avg0, std0), (t1, avg1, std1), ...], rxn_ind2: [...], ... rxn_ind_n: [...]}
{species_data: {spec1: [(t0, avg0, std0), (t1, avg1, std1), ...], spec2: [...], ... specn: [...]}}
"""
reaction_frequency_data = dict()
reaction_frequency_array = (
dict()
) # Growing arrays of reaction frequencies as fxn of time
species_frequency_data = dict()
species_frequency_array = dict()
new_species_counters = dict()
for ind in rxn_inds:
reaction_frequency_data[ind] = [0 for j in range(partitions)]
for ind in spec_inds:
species_frequency_data[ind] = [0 for j in range(partitions)]
new_species_counters[ind] = 0
for n_sim in range(self.num_sims):
delta_t = np.sum(self.time_history[n_sim]) / partitions
ind_0 = 0
t = 0
n = 0 # for tracking which time interval we are in
species_counters = copy.deepcopy(
new_species_counters
) # for counting species as they appear
rxn_freq_data = copy.deepcopy(reaction_frequency_data)
spec_freq_data = copy.deepcopy(species_frequency_data)
for step_num, tau in enumerate(self.time_history[n_sim]):
t += tau
this_rxn_ind = int(self.reaction_history[n_sim][step_num])
if this_rxn_ind % 2: # reverse reaction
prods = self.reactants[math.floor(this_rxn_ind / 2), :]
else:
prods = self.products[math.floor(this_rxn_ind / 2), :]
for spec_ind in spec_inds:
if spec_ind in prods:
species_counters[spec_ind] += 1
# When t reaches the next discretized time step, or end of the simulation
if (t >= (n + 1) * delta_t) or (
step_num == len(self.reaction_history[n_sim]) - 1
):
n_to_fill = n
if t >= (n + 2) * delta_t:
n += math.floor(t / delta_t - n)
else:
n += 1
steps = step_num - ind_0 + 1
for spec_ind in spec_inds:
spec_freq_data[spec_ind][n_to_fill] = (
species_counters[spec_ind] / steps
)
for rxn_ind in rxn_inds:
rxn_freq = (
np.count_nonzero(
self.reaction_history[n_sim][ind_0 : step_num + 1]
== rxn_ind
)
/ steps
)
# t_mdpt = (self.time_history[n_sim][step_num] + self.time_history[n_sim][ind_0]) / 2
rxn_freq_data[rxn_ind][n_to_fill] = rxn_freq
# Reset and update counters
species_counters = copy.deepcopy(new_species_counters)
ind_0 = step_num + 1
for rxn_ind in rxn_inds:
if n_sim == 0:
reaction_frequency_array[rxn_ind] = np.array(rxn_freq_data[rxn_ind])
else:
reaction_frequency_array[rxn_ind] = np.vstack(
(reaction_frequency_array[rxn_ind], rxn_freq_data[rxn_ind])
)
# print('reaction freq array', reaction_frequency_array)
for spec_ind in spec_inds:
if n_sim == 0:
species_frequency_array[spec_ind] = np.array(
spec_freq_data[spec_ind]
)
else:
species_frequency_array[spec_ind] = np.vstack(
(species_frequency_array[spec_ind], spec_freq_data[spec_ind])
)
# Statistical analysis
statistical_rxn_data = dict()
statistical_spec_data = dict()
avg_delta_t = (
np.mean(np.array([sum(self.time_history[i]) for i in range(self.num_sims)]))
/ partitions
)
time_list = [i * avg_delta_t + avg_delta_t / 2 for i in range(partitions)]
# print('time_list: ', time_list)
for rxn_ind in rxn_inds:
if self.num_sims == 1:
avgs = reaction_frequency_array[rxn_ind]
stds = np.zeros(partitions)
else:
avgs = np.mean(reaction_frequency_array[rxn_ind], 0)
stds = np.std(reaction_frequency_array[rxn_ind], 0)
statistical_rxn_data[rxn_ind] = [
(time_list[n], avgs[n], stds[n]) for n in range(partitions)
]
for spec_ind in spec_inds:
if self.num_sims == 1:
spec_avgs = species_frequency_array[spec_ind]
spec_stds = np.zeros(partitions)
else:
spec_avgs = np.mean(species_frequency_array[spec_ind], 0)
spec_stds = np.std(species_frequency_array[spec_ind], 0)
statistical_spec_data[spec_ind] = [
(time_list[n], spec_avgs[n], spec_stds[n]) for n in range(partitions)
]
return {
"reaction_data": statistical_rxn_data,
"species_data": statistical_spec_data,
}
def find_rxn_index(self, reaction, reverse):
"""
Find the reaction index of a given reaction object
Args:
reaction: Reaction object
reverse: bool to say whether reaction is reverse or forward
:return: integer reaction index
"""
for ind, rxn in enumerate(self.reaction_network.reactions):
if rxn == reaction:
if reverse is True:
rxn_ind = 2 * ind + 1
else:
rxn_ind = 2 * ind
break
return rxn_ind
| [
"math.floor",
"numpy.log",
"numpy.count_nonzero",
"numpy.array",
"copy.deepcopy",
"numpy.mean",
"numpy.multiply",
"numpy.where",
"numpy.diff",
"numpy.vstack",
"matplotlib.pyplot.savefig",
"numpy.ones",
"numba.jit",
"numpy.std",
"matplotlib.pyplot.cm.get_cmap",
"matplotlib.pyplot.show",... | [((6251, 6284), 'numba.jit', 'jit', ([], {'nopython': '(True)', 'parallel': '(True)'}), '(nopython=True, parallel=True)\n', (6254, 6284), False, 'from numba import jit\n'), ((9817, 9835), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (9820, 9835), False, 'from numba import jit\n'), ((11607, 11625), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (11610, 11625), False, 'from numba import jit\n'), ((2996, 3018), 'numpy.zeros', 'np.zeros', (['(2 * num_rxns)'], {}), '(2 * num_rxns)\n', (3004, 3018), True, 'import numpy as np\n'), ((3040, 3062), 'numpy.zeros', 'np.zeros', (['(2 * num_rxns)'], {}), '(2 * num_rxns)\n', (3048, 3062), True, 'import numpy as np\n'), ((5944, 5984), 'numpy.multiply', 'np.multiply', (['coord_array', 'rate_constants'], {}), '(coord_array, rate_constants)\n', (5955, 5984), True, 'import numpy as np\n'), ((7514, 7538), 'numpy.sum', 'np.sum', (['propensity_array'], {}), '(propensity_array)\n', (7520, 7538), True, 'import numpy as np\n'), ((2885, 2918), 'numpy.ones', 'np.ones', (['(num_rxns, 2)'], {'dtype': 'int'}), '((num_rxns, 2), dtype=int)\n', (2892, 2918), True, 'import numpy as np\n'), ((2944, 2977), 'numpy.ones', 'np.ones', (['(num_rxns, 2)'], {'dtype': 'int'}), '((num_rxns, 2), dtype=int)\n', (2951, 2977), True, 'import numpy as np\n'), ((5516, 5569), 'numpy.ones', 'np.ones', (['(num_species, max_mapping_length)'], {'dtype': 'int'}), '((num_species, max_mapping_length), dtype=int)\n', (5523, 5569), True, 'import numpy as np\n'), ((6006, 6040), 'numpy.array', 'np.array', (['initial_state'], {'dtype': 'int'}), '(initial_state, dtype=int)\n', (6014, 6040), True, 'import numpy as np\n'), ((7663, 7693), 'numpy.where', 'np.where', (['(propensity_array > 0)'], {}), '(propensity_array > 0)\n', (7671, 7693), True, 'import numpy as np\n'), ((7828, 7843), 'random.random', 'random.random', ([], {}), '()\n', (7841, 7843), False, 'import random\n'), ((7857, 7872), 'random.random', 'random.random', ([], {}), '()\n', (7870, 7872), False, 'import random\n'), ((8203, 8238), 'math.floor', 'math.floor', (['(reaction_choice_ind / 2)'], {}), '(reaction_choice_ind / 2)\n', (8213, 8238), False, 'import math\n'), ((9481, 9521), 'numpy.multiply', 'np.multiply', (['rate_constants', 'coord_array'], {}), '(rate_constants, coord_array)\n', (9492, 9521), True, 'import numpy as np\n'), ((9606, 9644), 'numpy.sum', 'np.sum', (['propensity_array[relevant_ind]'], {}), '(propensity_array[relevant_ind])\n', (9612, 9644), True, 'import numpy as np\n'), ((9545, 9575), 'numpy.where', 'np.where', (['(propensity_array > 0)'], {}), '(propensity_array > 0)\n', (9553, 9575), True, 'import numpy as np\n'), ((9768, 9794), 'numpy.array', 'np.array', (['reaction_history'], {}), '(reaction_history)\n', (9776, 9794), True, 'import numpy as np\n'), ((9796, 9811), 'numpy.array', 'np.array', (['times'], {}), '(times)\n', (9804, 9811), True, 'import numpy as np\n'), ((16248, 16286), 'copy.deepcopy', 'copy.deepcopy', (['self.initial_state_dict'], {}), '(self.initial_state_dict)\n', (16261, 16286), False, 'import copy\n'), ((21452, 21466), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (21464, 21466), True, 'import matplotlib.pyplot as plt\n'), ((22085, 22118), 'matplotlib.pyplot.cm.get_cmap', 'plt.cm.get_cmap', (['"""hsv"""', 'num_label'], {}), "('hsv', num_label)\n", (22100, 22118), True, 'import matplotlib.pyplot as plt\n'), ((26683, 26727), 'numpy.array', 'np.array', (["intermediates[mol_ind]['lifetime']"], {}), "(intermediates[mol_ind]['lifetime'])\n", (26691, 26727), True, 'import numpy as np\n'), ((26910, 26951), 'numpy.array', 'np.array', (["intermediates[mol_ind]['t_max']"], {}), "(intermediates[mol_ind]['t_max'])\n", (26918, 26951), True, 'import numpy as np\n'), ((27132, 27180), 'numpy.array', 'np.array', (["intermediates[mol_ind]['amt_produced']"], {}), "(intermediates[mol_ind]['amt_produced'])\n", (27140, 27180), True, 'import numpy as np\n'), ((27382, 27430), 'numpy.array', 'np.array', (["intermediates[mol_ind]['amt_consumed']"], {}), "(intermediates[mol_ind]['amt_consumed'])\n", (27390, 27430), True, 'import numpy as np\n'), ((28884, 28919), 'numpy.cumsum', 'np.cumsum', (['self.time_history[n_sim]'], {}), '(self.time_history[n_sim])\n', (28893, 28919), True, 'import numpy as np\n'), ((37088, 37123), 'copy.deepcopy', 'copy.deepcopy', (['new_species_counters'], {}), '(new_species_counters)\n', (37101, 37123), False, 'import copy\n'), ((37221, 37259), 'copy.deepcopy', 'copy.deepcopy', (['reaction_frequency_data'], {}), '(reaction_frequency_data)\n', (37234, 37259), False, 'import copy\n'), ((37289, 37326), 'copy.deepcopy', 'copy.deepcopy', (['species_frequency_data'], {}), '(species_frequency_data)\n', (37302, 37326), False, 'import copy\n'), ((7888, 7898), 'numpy.log', 'np.log', (['r1'], {}), '(r1)\n', (7894, 7898), True, 'import numpy as np\n'), ((9359, 9382), 'math.floor', 'math.floor', (['(rxn_ind / 2)'], {}), '(rxn_ind / 2)\n', (9369, 9382), False, 'import math\n'), ((12570, 12600), 'numpy.where', 'np.where', (['(reactant_array != -1)'], {}), '(reactant_array != -1)\n', (12578, 12600), True, 'import numpy as np\n'), ((12689, 12719), 'numpy.where', 'np.where', (['(reactant_array != -1)'], {}), '(reactant_array != -1)\n', (12697, 12719), True, 'import numpy as np\n'), ((16813, 16836), 'math.floor', 'math.floor', (['(rxn_ind / 2)'], {}), '(rxn_ind / 2)\n', (16823, 16836), False, 'import math\n'), ((20149, 20169), 'numpy.mean', 'np.mean', (['state_array'], {}), '(state_array)\n', (20156, 20169), True, 'import numpy as np\n'), ((20171, 20190), 'numpy.std', 'np.std', (['state_array'], {}), '(state_array)\n', (20177, 20190), True, 'import numpy as np\n'), ((22366, 22424), 'numpy.array', 'np.array', (['[e[0] for e in species_profiles[n_sim][mol_ind]]'], {}), '([e[0] for e in species_profiles[n_sim][mol_ind]])\n', (22374, 22424), True, 'import numpy as np\n'), ((22448, 22506), 'numpy.array', 'np.array', (['[e[1] for e in species_profiles[n_sim][mol_ind]]'], {}), '([e[1] for e in species_profiles[n_sim][mol_ind]])\n', (22456, 22506), True, 'import numpy as np\n'), ((23690, 23700), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (23698, 23700), True, 'import matplotlib.pyplot as plt\n'), ((23735, 23777), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(file_dir + '/' + sim_filename)"], {}), "(file_dir + '/' + sim_filename)\n", (23746, 23777), True, 'import matplotlib.pyplot as plt\n'), ((24569, 24599), 'numpy.array', 'np.array', (['[t[1] for t in prof]'], {}), '([t[1] for t in prof])\n', (24577, 24599), True, 'import numpy as np\n'), ((24631, 24647), 'numpy.diff', 'np.diff', (['history'], {}), '(history)\n', (24638, 24647), True, 'import numpy as np\n'), ((24718, 24743), 'numpy.sum', 'np.sum', (['(diff_history == 1)'], {}), '(diff_history == 1)\n', (24724, 24743), True, 'import numpy as np\n'), ((24775, 24801), 'numpy.sum', 'np.sum', (['(diff_history == -1)'], {}), '(diff_history == -1)\n', (24781, 24801), True, 'import numpy as np\n'), ((26805, 26828), 'numpy.mean', 'np.mean', (['lifetime_array'], {}), '(lifetime_array)\n', (26812, 26828), True, 'import numpy as np\n'), ((26846, 26868), 'numpy.std', 'np.std', (['lifetime_array'], {}), '(lifetime_array)\n', (26852, 26868), True, 'import numpy as np\n'), ((27026, 27046), 'numpy.mean', 'np.mean', (['t_max_array'], {}), '(t_max_array)\n', (27033, 27046), True, 'import numpy as np\n'), ((27064, 27083), 'numpy.std', 'np.std', (['t_max_array'], {}), '(t_max_array)\n', (27070, 27083), True, 'import numpy as np\n'), ((27262, 27289), 'numpy.mean', 'np.mean', (['amt_produced_array'], {}), '(amt_produced_array)\n', (27269, 27289), True, 'import numpy as np\n'), ((27307, 27333), 'numpy.std', 'np.std', (['amt_produced_array'], {}), '(amt_produced_array)\n', (27313, 27333), True, 'import numpy as np\n'), ((27512, 27539), 'numpy.mean', 'np.mean', (['amt_consumed_array'], {}), '(amt_consumed_array)\n', (27519, 27539), True, 'import numpy as np\n'), ((27557, 27583), 'numpy.std', 'np.std', (['amt_produced_array'], {}), '(amt_produced_array)\n', (27563, 27583), True, 'import numpy as np\n'), ((36907, 36939), 'numpy.sum', 'np.sum', (['self.time_history[n_sim]'], {}), '(self.time_history[n_sim])\n', (36913, 36939), True, 'import numpy as np\n'), ((40589, 40609), 'numpy.zeros', 'np.zeros', (['partitions'], {}), '(partitions)\n', (40597, 40609), True, 'import numpy as np\n'), ((40651, 40696), 'numpy.mean', 'np.mean', (['reaction_frequency_array[rxn_ind]', '(0)'], {}), '(reaction_frequency_array[rxn_ind], 0)\n', (40658, 40696), True, 'import numpy as np\n'), ((40720, 40764), 'numpy.std', 'np.std', (['reaction_frequency_array[rxn_ind]', '(0)'], {}), '(reaction_frequency_array[rxn_ind], 0)\n', (40726, 40764), True, 'import numpy as np\n'), ((41062, 41082), 'numpy.zeros', 'np.zeros', (['partitions'], {}), '(partitions)\n', (41070, 41082), True, 'import numpy as np\n'), ((41129, 41174), 'numpy.mean', 'np.mean', (['species_frequency_array[spec_ind]', '(0)'], {}), '(species_frequency_array[spec_ind], 0)\n', (41136, 41174), True, 'import numpy as np\n'), ((41203, 41247), 'numpy.std', 'np.std', (['species_frequency_array[spec_ind]', '(0)'], {}), '(species_frequency_array[spec_ind], 0)\n', (41209, 41247), True, 'import numpy as np\n'), ((16199, 16225), 'numpy.array', 'np.array', (['sim_time_history'], {}), '(sim_time_history)\n', (16207, 16225), True, 'import numpy as np\n'), ((19818, 19841), 'numpy.zeros', 'np.zeros', (['self.num_sims'], {}), '(self.num_sims)\n', (19826, 19841), True, 'import numpy as np\n'), ((34802, 34849), 'numpy.sum', 'np.sum', (['(self.reaction_history[n_sim] == rxn_ind)'], {}), '(self.reaction_history[n_sim] == rxn_ind)\n', (34808, 34849), True, 'import numpy as np\n'), ((35025, 35041), 'numpy.array', 'np.array', (['counts'], {}), '(counts)\n', (35033, 35041), True, 'import numpy as np\n'), ((35067, 35083), 'numpy.array', 'np.array', (['counts'], {}), '(counts)\n', (35075, 35083), True, 'import numpy as np\n'), ((39156, 39191), 'copy.deepcopy', 'copy.deepcopy', (['new_species_counters'], {}), '(new_species_counters)\n', (39169, 39191), False, 'import copy\n'), ((39358, 39390), 'numpy.array', 'np.array', (['rxn_freq_data[rxn_ind]'], {}), '(rxn_freq_data[rxn_ind])\n', (39366, 39390), True, 'import numpy as np\n'), ((39469, 39539), 'numpy.vstack', 'np.vstack', (['(reaction_frequency_array[rxn_ind], rxn_freq_data[rxn_ind])'], {}), '((reaction_frequency_array[rxn_ind], rxn_freq_data[rxn_ind]))\n', (39478, 39539), True, 'import numpy as np\n'), ((39782, 39816), 'numpy.array', 'np.array', (['spec_freq_data[spec_ind]'], {}), '(spec_freq_data[spec_ind])\n', (39790, 39816), True, 'import numpy as np\n'), ((39941, 40013), 'numpy.vstack', 'np.vstack', (['(species_frequency_array[spec_ind], spec_freq_data[spec_ind])'], {}), '((species_frequency_array[spec_ind], spec_freq_data[spec_ind]))\n', (39950, 40013), True, 'import numpy as np\n'), ((8026, 8067), 'numpy.cumsum', 'np.cumsum', (['propensity_array[relevant_ind]'], {}), '(propensity_array[relevant_ind])\n', (8035, 8067), True, 'import numpy as np\n'), ((29138, 29187), 'numpy.where', 'np.where', (['(self.reaction_history[n_sim] == rxn_ind)'], {}), '(self.reaction_history[n_sim] == rxn_ind)\n', (29146, 29187), True, 'import numpy as np\n'), ((31075, 31102), 'numpy.array', 'np.array', (["data_dict['time']"], {}), "(data_dict['time'])\n", (31083, 31102), True, 'import numpy as np\n'), ((31132, 31159), 'numpy.array', 'np.array', (["data_dict['time']"], {}), "(data_dict['time'])\n", (31140, 31159), True, 'import numpy as np\n'), ((31267, 31295), 'numpy.array', 'np.array', (["data_dict['steps']"], {}), "(data_dict['steps'])\n", (31275, 31295), True, 'import numpy as np\n'), ((31325, 31353), 'numpy.array', 'np.array', (["data_dict['steps']"], {}), "(data_dict['steps'])\n", (31333, 31353), True, 'import numpy as np\n'), ((31467, 31501), 'numpy.array', 'np.array', (["data_dict['occurrences']"], {}), "(data_dict['occurrences'])\n", (31475, 31501), True, 'import numpy as np\n'), ((31531, 31565), 'numpy.array', 'np.array', (["data_dict['occurrences']"], {}), "(data_dict['occurrences'])\n", (31539, 31565), True, 'import numpy as np\n'), ((38208, 38235), 'math.floor', 'math.floor', (['(t / delta_t - n)'], {}), '(t / delta_t - n)\n', (38218, 38235), False, 'import math\n'), ((25492, 25520), 'numpy.where', 'np.where', (['(history == max_amt)'], {}), '(history == max_amt)\n', (25500, 25520), True, 'import numpy as np\n'), ((30618, 30639), 'numpy.array', 'np.array', (['time_elapse'], {}), '(time_elapse)\n', (30626, 30639), True, 'import numpy as np\n'), ((30758, 30779), 'numpy.array', 'np.array', (['step_elapse'], {}), '(step_elapse)\n', (30766, 30779), True, 'import numpy as np\n'), ((37597, 37625), 'math.floor', 'math.floor', (['(this_rxn_ind / 2)'], {}), '(this_rxn_ind / 2)\n', (37607, 37625), False, 'import math\n'), ((37694, 37722), 'math.floor', 'math.floor', (['(this_rxn_ind / 2)'], {}), '(this_rxn_ind / 2)\n', (37704, 37722), False, 'import math\n'), ((38653, 38730), 'numpy.count_nonzero', 'np.count_nonzero', (['(self.reaction_history[n_sim][ind_0:step_num + 1] == rxn_ind)'], {}), '(self.reaction_history[n_sim][ind_0:step_num + 1] == rxn_ind)\n', (38669, 38730), True, 'import numpy as np\n')] |
'''
Created on 2018-12-21
Copyright (c) 2018 <NAME>
Generate code from a model and a jinja2 template.
'''
import logging
from pathlib import Path
from jinja2 import FileSystemLoader, Environment
from jinja2.exceptions import TemplateNotFound
from munch import munchify
from fashion.mirror import Mirror
# Module level code is executed when this file is loaded.
# cwd is where segment file was loaded.
def init(config, codeRegistry, verbose=False, tags=None):
'''cwd is where segment file was loaded.'''
codeRegistry.addXformObject(Generate(config))
class Generate(object):
'''Generate output by merging a model into a template to produce a file.'''
def __init__(self, config):
'''Constructor.'''
self.version = "1.0.0"
self.templatePath = []
self.name = config.moduleName
self.tags = config.tags
self.inputKinds = ["fashion.core.generate.jinja2.spec",
"fashion.core.mirror"]
self.outputKinds = [ 'fashion.core.output.file' ]
def execute(self, codeRegistry, verbose=False, tags=None):
'''cwd is project root directory.'''
# set up mirrored directories
mdb = codeRegistry.getService('fashion.prime.modelAccess')
mirCfg = munchify(mdb.getSingleton("fashion.core.mirror"))
mirror = Mirror(Path(mirCfg.projectPath), Path(mirCfg.mirrorPath), force=mirCfg.force)
genSpecs = mdb.getByKind(self.inputKinds[0])
for genSpec in genSpecs:
gs = munchify(genSpec)
if mirror.isChanged(Path(gs.targetFile)):
logging.warning("Skipping {0}, file has changed.".format(gs.targetFile))
else:
try:
env = Environment(loader=FileSystemLoader(gs.templatePath))
template = env.get_template(gs.template)
result = template.render(gs.model)
targetPath = Path(gs.targetFile)
with targetPath.open(mode="w") as tf:
tf.write(result)
mirror.copyToMirror(targetPath)
mdb.outputFile(targetPath)
except TemplateNotFound:
logging.error("TemplateNotFound: {0}".format(gs.template))
| [
"jinja2.FileSystemLoader",
"munch.munchify",
"pathlib.Path"
] | [((1345, 1369), 'pathlib.Path', 'Path', (['mirCfg.projectPath'], {}), '(mirCfg.projectPath)\n', (1349, 1369), False, 'from pathlib import Path\n'), ((1371, 1394), 'pathlib.Path', 'Path', (['mirCfg.mirrorPath'], {}), '(mirCfg.mirrorPath)\n', (1375, 1394), False, 'from pathlib import Path\n'), ((1519, 1536), 'munch.munchify', 'munchify', (['genSpec'], {}), '(genSpec)\n', (1527, 1536), False, 'from munch import munchify\n'), ((1570, 1589), 'pathlib.Path', 'Path', (['gs.targetFile'], {}), '(gs.targetFile)\n', (1574, 1589), False, 'from pathlib import Path\n'), ((1949, 1968), 'pathlib.Path', 'Path', (['gs.targetFile'], {}), '(gs.targetFile)\n', (1953, 1968), False, 'from pathlib import Path\n'), ((1765, 1798), 'jinja2.FileSystemLoader', 'FileSystemLoader', (['gs.templatePath'], {}), '(gs.templatePath)\n', (1781, 1798), False, 'from jinja2 import FileSystemLoader, Environment\n')] |
from multiprocessing.dummy import Value
from agents.Base_Agent import Base_Agent
import copy
import numpy as np
import torch
import torch.nn.functional as F
from torch.optim import Adam
class RunningMeanStd(object):
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
def __init__(self, device, epsilon=1e-4, shape=()):
self.device = device
self.mean = torch.zeros(shape).to(self.device)
self.var = torch.ones(shape).to(self.device)
self.count = epsilon
def update(self, x):
batch_mean = torch.mean(x, axis=0)
batch_var = torch.var(x, axis=0)
batch_count = x.shape[0]
self.update_from_moments(batch_mean, batch_var, batch_count)
def update_from_moments(self, batch_mean, batch_var, batch_count):
delta = batch_mean - self.mean
tot_count = self.count + batch_count
new_mean = self.mean + delta * batch_count / tot_count
m_a = self.var * (self.count)
m_b = batch_var * (batch_count)
M2 = m_a + m_b + torch.square(delta) * self.count * \
batch_count / (self.count + batch_count)
new_var = M2 / (self.count + batch_count)
new_count = batch_count + self.count
self.mean = new_mean
self.var = new_var
self.count = new_count
class Explorer(Base_Agent):
"""Random Network Distillation or count based. Not really an agent"""
agent_name = "Explorer"
def __init__(self, config, state_size=None):
Base_Agent.__init__(self, config, log_info=False, state_size=state_size)
self.hyperparameters = config.hyperparameters
self.count_based = self.hyperparameters.get('count_based', False)
self.scale = self.hyperparameters.get('scale', 1)
self.normalize = self.hyperparameters.get('normalize_rnd', False)
self.batch_size = self.hyperparameters.get('batch_size', 1)
self.rnd_actions = self.hyperparameters.get('rnd_actions', False)
self.state_actions = torch.zeros((225, self.action_size)).to(self.device)
if self.count_based:
self.visited_states = torch.ones((225,)).to(self.device)
self.visited_state_actions = torch.ones((225, self.action_size)).to(self.device)
else:
if self.rnd_actions:
self.predictors, self.targets, self.optimizers = [], [], []
for i in range(self.action_size):
predictor, target, optimizer = self._network_factory()
if i > 0:
self.copy_model_over(self.predictors[0], predictor)
self.predictors.append(predictor)
self.targets.append(target)
self.optimizers.append(optimizer)
else:
self.predictor, self.target, self.optimizer = self._network_factory()
self.steps = 0
self.reward_rms = RunningMeanStd(self.device)
self.losses = []
self.states_so_far_np = []
self._init_states_so_far()
def _init_states_so_far(self, action=None):
if self.rnd_actions:
if action:
self.states_so_far[action] = torch.zeros([0, 1]).to(self.device)
else:
self.states_so_far = [torch.zeros([0, 1]).to(self.device) for _ in range(self.action_size)]
else:
self.states_so_far = torch.zeros([0, 1]).to(self.device)
def _network_factory(self):
predictor = self.create_NN(
input_dim=self.state_size, output_dim=self.hyperparameters['features_size'],
override_seed=self.config.seed + 1, hyperparameters=self.hyperparameters)
target_hyperparameters = copy.deepcopy(self.hyperparameters)
target_hyperparameters["linear_hidden_units"] = target_hyperparameters["target_linear_hidden_units"]
target = self.create_NN(
input_dim=self.state_size, output_dim=self.hyperparameters['features_size'])
optimizer = Adam(predictor.parameters(),
lr=self.hyperparameters["learning_rate"], eps=1e-4)
return predictor, target, optimizer
def log_state_action(self, state, action):
self.state_actions[state[0], action] += 1
def compute_intrinsic_reward_and_learn(self, states, learn=True, actions=None, int_learn_batch=None):
self.steps += 1
if states.ndim == 4:
# Only get last observation for RND
states = torch.unsqueeze(states[:, -1, :, :], 1)
# Get rewards
rewards = self.compute_intrinsic_reward(states, learn=learn, actions=actions, int_learn_batch=int_learn_batch)
if self.normalize:
mean, std, count = torch.mean(rewards), torch.std(rewards), len(rewards)
self.reward_rms.update_from_moments(mean, std ** 2, count)
rewards /= torch.sqrt(self.reward_rms.var)
return rewards.reshape((-1, 1))
def compute_intrinsic_reward(self, states, learn=True, actions=None, int_learn_batch=None):
if self.count_based:
return self.compute_counts(states, learn=learn, actions=actions, int_learn_batch=int_learn_batch)
else:
return self.compute_preds(states, learn=learn, actions=actions, int_learn_batch=int_learn_batch)
def compute_counts(self, states, learn=True, actions=None, int_learn_batch=None):
if actions is not None:
if not self.rnd_actions:
raise ValueError
rewards = 1 / torch.sqrt(self.visited_state_actions[states.long().squeeze(1), actions.long().squeeze(1)]).unsqueeze(1)
if learn:
indices = torch.where(int_learn_batch == 1)[0]
states_to_learn = states[indices]
actions_to_learn = actions[indices]
self.learn_counts(states_to_learn, actions_to_learn)
else:
rewards = 1 / torch.sqrt(self.visited_states[states.long()])
if learn:
states_to_learn = states[torch.where(int_learn_batch == 1)[0]]
self.learn_counts(states_to_learn)
return rewards
def get_counts_all_actions(self, state):
return self.state_actions[state[0].long()]
def compute_preds(self, states, learn=True, actions=None, int_learn_batch=None):
if actions is not None:
if not self.rnd_actions:
raise ValueError
intrinsic_reward = torch.zeros((len(states), 1)).to(self.device)
for i in range(self.action_size):
indices = torch.where(actions == i)[0]
states_per_action = states[indices]
target_next_feature = self.targets[i](states_per_action)
predict_next_feature = self.predictors[i](states_per_action)
intrinsic_reward[indices] = self._compute_intrinsic_reward(target_next_feature, predict_next_feature).unsqueeze(1)
if learn:
self.states_so_far[i] = torch.cat(
(self.states_so_far[i], states_per_action))
self.learn_pred(index_to_train=i)
else:
target_next_feature = self.target(states)
predict_next_feature = self.predictor(states)
intrinsic_reward = self._compute_intrinsic_reward(target_next_feature, predict_next_feature)
if learn and actions is None:
self.learn_pred(predict_next_feature=predict_next_feature, target_next_feature=target_next_feature)
return self.scale * intrinsic_reward
@staticmethod
def _compute_intrinsic_reward(target_feature, predict_feature):
return ((target_feature - predict_feature).pow(2).sum(1) / 2).detach()
def learn(self, states):
""" Minimize the mse loss between predictions and target"""
if self.count_based:
self.learn_counts(states)
else:
self.learn_pred(states)
def learn_counts(self, states, actions=None):
""" Update the visitation counts"""
for i in range(len(states)):
if actions is not None:
self.visited_state_actions[int(states[i].item()), int(actions[i].item())] += 1
else:
self.visited_states[int(states[i].item())] += 1
def learn_pred(self, states=None, predict_next_feature=None, target_next_feature=None, index_to_train=None):
if predict_next_feature is None and states is None:
if index_to_train is None:
raise ValueError
samples = self.states_so_far[index_to_train]
target = self.targets[index_to_train]
predictor = self.predictors[index_to_train]
self._init_states_so_far(action=index_to_train)
if len(samples) >= self.batch_size or index_to_train is not None:
target_next_feature = target(samples)
predict_next_feature = predictor(samples)
else:
return
elif states is not None:
target_next_feature = self.target(states)
predict_next_feature = self.predictor(states)
prediction_loss = F.mse_loss(predict_next_feature, target_next_feature.detach())
self.losses.append(prediction_loss.item())
self.update_rnd_parameters(prediction_loss, index_to_train=index_to_train)
def update_rnd_parameters(self, prediction_loss, index_to_train=None):
"""Updates the parameters for the rnd"""
if index_to_train is not None:
self.take_optimisation_step(self.optimizers[index_to_train], self.predictors[index_to_train], prediction_loss,
self.hyperparameters["gradient_clipping_norm"])
else:
self.take_optimisation_step(self.optimizer, self.predictor, prediction_loss,
self.hyperparameters["gradient_clipping_norm"])
| [
"torch.mean",
"torch.unsqueeze",
"torch.sqrt",
"torch.square",
"torch.cat",
"copy.deepcopy",
"torch.zeros",
"agents.Base_Agent.Base_Agent.__init__",
"torch.std",
"torch.var",
"torch.where",
"torch.ones"
] | [((580, 601), 'torch.mean', 'torch.mean', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (590, 601), False, 'import torch\n'), ((622, 642), 'torch.var', 'torch.var', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (631, 642), False, 'import torch\n'), ((1532, 1604), 'agents.Base_Agent.Base_Agent.__init__', 'Base_Agent.__init__', (['self', 'config'], {'log_info': '(False)', 'state_size': 'state_size'}), '(self, config, log_info=False, state_size=state_size)\n', (1551, 1604), False, 'from agents.Base_Agent import Base_Agent\n'), ((3735, 3770), 'copy.deepcopy', 'copy.deepcopy', (['self.hyperparameters'], {}), '(self.hyperparameters)\n', (3748, 3770), False, 'import copy\n'), ((4497, 4536), 'torch.unsqueeze', 'torch.unsqueeze', (['states[:, -1, :, :]', '(1)'], {}), '(states[:, -1, :, :], 1)\n', (4512, 4536), False, 'import torch\n'), ((4884, 4915), 'torch.sqrt', 'torch.sqrt', (['self.reward_rms.var'], {}), '(self.reward_rms.var)\n', (4894, 4915), False, 'import torch\n'), ((416, 434), 'torch.zeros', 'torch.zeros', (['shape'], {}), '(shape)\n', (427, 434), False, 'import torch\n'), ((470, 487), 'torch.ones', 'torch.ones', (['shape'], {}), '(shape)\n', (480, 487), False, 'import torch\n'), ((2036, 2072), 'torch.zeros', 'torch.zeros', (['(225, self.action_size)'], {}), '((225, self.action_size))\n', (2047, 2072), False, 'import torch\n'), ((4736, 4755), 'torch.mean', 'torch.mean', (['rewards'], {}), '(rewards)\n', (4746, 4755), False, 'import torch\n'), ((4757, 4775), 'torch.std', 'torch.std', (['rewards'], {}), '(rewards)\n', (4766, 4775), False, 'import torch\n'), ((2152, 2170), 'torch.ones', 'torch.ones', (['(225,)'], {}), '((225,))\n', (2162, 2170), False, 'import torch\n'), ((2228, 2263), 'torch.ones', 'torch.ones', (['(225, self.action_size)'], {}), '((225, self.action_size))\n', (2238, 2263), False, 'import torch\n'), ((3422, 3441), 'torch.zeros', 'torch.zeros', (['[0, 1]'], {}), '([0, 1])\n', (3433, 3441), False, 'import torch\n'), ((5684, 5717), 'torch.where', 'torch.where', (['(int_learn_batch == 1)'], {}), '(int_learn_batch == 1)\n', (5695, 5717), False, 'import torch\n'), ((6588, 6613), 'torch.where', 'torch.where', (['(actions == i)'], {}), '(actions == i)\n', (6599, 6613), False, 'import torch\n'), ((7020, 7073), 'torch.cat', 'torch.cat', (['(self.states_so_far[i], states_per_action)'], {}), '((self.states_so_far[i], states_per_action))\n', (7029, 7073), False, 'import torch\n'), ((1068, 1087), 'torch.square', 'torch.square', (['delta'], {}), '(delta)\n', (1080, 1087), False, 'import torch\n'), ((3213, 3232), 'torch.zeros', 'torch.zeros', (['[0, 1]'], {}), '([0, 1])\n', (3224, 3232), False, 'import torch\n'), ((6042, 6075), 'torch.where', 'torch.where', (['(int_learn_batch == 1)'], {}), '(int_learn_batch == 1)\n', (6053, 6075), False, 'import torch\n'), ((3305, 3324), 'torch.zeros', 'torch.zeros', (['[0, 1]'], {}), '([0, 1])\n', (3316, 3324), False, 'import torch\n')] |
from collections import OrderedDict, defaultdict
from contextlib import contextmanager
from datetime import datetime
import torch.cuda
from ..viz.plot import plot_timeline
def time(name=None, sync=False):
return Task(name=name, sync=sync, log=True)
class Task:
__slots__ = ('name', 'start_time', 'end_time', 'meta', 'sync', 'log')
def __init__(self, name=None, start=None, end=None, meta=None, sync=False, log=False):
self.name = name
self.start_time = start
self.end_time = end
self.meta = meta or {}
self.sync = sync
self.log = log
def start(self, time=None, meta=None, sync=None):
if meta:
self.meta.update(meta)
sync = sync if sync is not None else self.sync
if sync and torch.cuda.is_available():
torch.cuda.synchronize()
self.start_time = time or datetime.now()
if self.log:
print(f'starting {self.name or id(self)}')
def end(self, time=None, meta=None, sync=None):
sync = sync if sync is not None else self.sync
if sync and torch.cuda.is_available():
torch.cuda.synchronize()
self.end_time = time or datetime.now()
if self.log:
print(f'completed {self.name or id(self)} in {self.seconds:.9g} seconds')
if meta:
self.meta.update(meta)
@classmethod
def begin(cls, name=None, meta=None, sync=None):
t = cls(name=name, meta=meta, sync=sync)
t.start()
return t
@property
def seconds(self):
if self.start_time is None or self.end_time is None:
return None
return (self.end_time - self.start_time).total_seconds()
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.end()
def __repr__(self):
return f"Task({self.name or id(self)}, seconds={self.seconds:.9g}, sync={self.sync})"
class Timer:
def __init__(self, name=None, log=False):
self.tasks = []
self.name = name
self.log = log
self.active_tasks = {}
def start(self, name, sync=True, **meta):
task = self.task(name, sync=sync, **meta)
if self.log: print('Started', name)
if task in self.active_tasks:
raise ValueError(f'Nesting tasks is not allowed, "{name}" was already started and not finished')
self.active_tasks[name] = task
def end(self, name, sync=True, **meta):
task = self.active_tasks.pop(name)
if not task:
raise ValueError(f"{name} is not an active task so can't be ended")
task.end(sync=sync, meta=meta)
if self.log:
print('Ended', task.name, ', took', task.seconds, 'seconds')
def task(self, name, sync=True, **meta):
task = Task.begin(name=name, meta=meta, sync=sync)
self.tasks.append(task)
return task
def __enter__(self):
self.start(self.name)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.end(self.name)
def plot(self):
plot_timeline(self.tasks) | [
"datetime.datetime.now"
] | [((820, 834), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (832, 834), False, 'from datetime import datetime\n'), ((1106, 1120), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1118, 1120), False, 'from datetime import datetime\n')] |
#!/usr/bin/env python3
import sys
import os.path
import re
from datetime import date, datetime, time, timedelta
# helper
def is_timeformat(s):
p = re.compile('^[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}$')
if p.match(s) is None:
return False
else:
return True
def is_time_line(l):
p = re.compile('^[0-9]{2}:')
m = p.match(l)
if m is None:
return False
else:
return True
def get_time(s):
dt = datetime.strptime(s, "%H:%M:%S,%f")
return dt.time()
def get_str(t):
return t.strftime("%H:%M:%S,%f")[:-3]
def add(t0, delta):
delta = timedelta(hours=delta.hour,
minutes=delta.minute,
seconds=delta.second,
microseconds=delta.microsecond)
dt = datetime.combine(date.today(), t0) + delta
return dt.time()
def sub(t0, delta):
delta = timedelta(hours=delta.hour,
minutes=delta.minute,
seconds=delta.second,
microseconds=delta.microsecond)
dt = datetime.combine(date.today(), t0) - delta
return dt.time()
def get_endpoints(l):
l = l.rstrip()
sep = re.compile("[ ]+-->[ ]+")
ts = sep.split(l)
return list(map(get_time, ts))
def transform_time_line(l, delta, sens):
es = get_endpoints(l)
tes = list()
for e in es:
if sens == '+':
tes.append(add(e, delta))
else:
tes.append(sub(e, delta))
return get_str(tes[0]) + " --> " + get_str(tes[1]) + "\n"
# main
if __name__ == "__main__":
filesrt = sys.argv[1]
if not os.path.isfile(filesrt):
print("ERROR: file isn't exist !")
exit(1)
filesrtnew = filesrt + ".new"
t0 = sys.argv[2]
if not is_timeformat(t0):
print("ERROR: t0 isn't correct !")
exit(1)
t0 = get_time(t0)
delta = 0
sens = ""
is_first_timeline = True
with open(filesrt) as inputf:
print("Reading {}".format(filesrt))
for l in inputf:
if is_time_line(l):
if is_first_timeline:
tt0 = get_endpoints(l)[0]
if tt0 > t0:
delta = sub(tt0, t0)
sens = '-'
print("Delta: -{}".format(get_str(delta)))
else:
delta = sub(t0, tt0)
sens = '+'
print("Delta: +{}".format(get_str(delta)))
is_first_timeline = False
with open(filesrtnew, "a") as outputf:
outputf.write(transform_time_line(l, delta, sens))
else:
with open(filesrtnew, "a") as outputf:
outputf.write(l)
print("Writing {}".format(filesrtnew))
| [
"datetime.datetime.strptime",
"datetime.timedelta",
"datetime.date.today",
"re.compile"
] | [((155, 206), 're.compile', 're.compile', (['"""^[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}$"""'], {}), "('^[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}$')\n", (165, 206), False, 'import re\n'), ((316, 340), 're.compile', 're.compile', (['"""^[0-9]{2}:"""'], {}), "('^[0-9]{2}:')\n", (326, 340), False, 'import re\n'), ((457, 492), 'datetime.datetime.strptime', 'datetime.strptime', (['s', '"""%H:%M:%S,%f"""'], {}), "(s, '%H:%M:%S,%f')\n", (474, 492), False, 'from datetime import date, datetime, time, timedelta\n'), ((608, 715), 'datetime.timedelta', 'timedelta', ([], {'hours': 'delta.hour', 'minutes': 'delta.minute', 'seconds': 'delta.second', 'microseconds': 'delta.microsecond'}), '(hours=delta.hour, minutes=delta.minute, seconds=delta.second,\n microseconds=delta.microsecond)\n', (617, 715), False, 'from datetime import date, datetime, time, timedelta\n'), ((885, 992), 'datetime.timedelta', 'timedelta', ([], {'hours': 'delta.hour', 'minutes': 'delta.minute', 'seconds': 'delta.second', 'microseconds': 'delta.microsecond'}), '(hours=delta.hour, minutes=delta.minute, seconds=delta.second,\n microseconds=delta.microsecond)\n', (894, 992), False, 'from datetime import date, datetime, time, timedelta\n'), ((1181, 1206), 're.compile', 're.compile', (['"""[ ]+-->[ ]+"""'], {}), "('[ ]+-->[ ]+')\n", (1191, 1206), False, 'import re\n'), ((804, 816), 'datetime.date.today', 'date.today', ([], {}), '()\n', (814, 816), False, 'from datetime import date, datetime, time, timedelta\n'), ((1081, 1093), 'datetime.date.today', 'date.today', ([], {}), '()\n', (1091, 1093), False, 'from datetime import date, datetime, time, timedelta\n')] |
import argparse
from typing import Optional
import annofabcli
import annofabcli.common.cli
import annofabcli.filesystem.draw_annotation
import annofabcli.filesystem.filter_annotation
import annofabcli.filesystem.mask_user_info
import annofabcli.filesystem.merge_annotation
import annofabcli.filesystem.write_annotation_image
def parse_args(parser: argparse.ArgumentParser):
subparsers = parser.add_subparsers()
# サブコマンドの定義
annofabcli.filesystem.draw_annotation.add_parser(subparsers)
annofabcli.filesystem.filter_annotation.add_parser(subparsers)
annofabcli.filesystem.mask_user_info.add_parser(subparsers)
annofabcli.filesystem.merge_annotation.add_parser(subparsers)
annofabcli.filesystem.write_annotation_image.add_parser(subparsers)
def add_parser(subparsers: Optional[argparse._SubParsersAction] = None):
subcommand_name = "filesystem"
subcommand_help = "ファイル操作関係(Web APIにアクセスしない)のサブコマンド"
description = "ファイル操作関係(Web APIにアクセスしない)のサブコマンド"
parser = annofabcli.common.cli.add_parser(
subparsers, subcommand_name, subcommand_help, description, is_subcommand=False
)
parse_args(parser)
return parser
| [
"annofabcli.filesystem.merge_annotation.add_parser",
"annofabcli.filesystem.filter_annotation.add_parser",
"annofabcli.filesystem.write_annotation_image.add_parser",
"annofabcli.filesystem.mask_user_info.add_parser",
"annofabcli.filesystem.draw_annotation.add_parser",
"annofabcli.common.cli.add_parser"
] | [((440, 500), 'annofabcli.filesystem.draw_annotation.add_parser', 'annofabcli.filesystem.draw_annotation.add_parser', (['subparsers'], {}), '(subparsers)\n', (488, 500), False, 'import annofabcli\n'), ((505, 567), 'annofabcli.filesystem.filter_annotation.add_parser', 'annofabcli.filesystem.filter_annotation.add_parser', (['subparsers'], {}), '(subparsers)\n', (555, 567), False, 'import annofabcli\n'), ((572, 631), 'annofabcli.filesystem.mask_user_info.add_parser', 'annofabcli.filesystem.mask_user_info.add_parser', (['subparsers'], {}), '(subparsers)\n', (619, 631), False, 'import annofabcli\n'), ((636, 697), 'annofabcli.filesystem.merge_annotation.add_parser', 'annofabcli.filesystem.merge_annotation.add_parser', (['subparsers'], {}), '(subparsers)\n', (685, 697), False, 'import annofabcli\n'), ((702, 769), 'annofabcli.filesystem.write_annotation_image.add_parser', 'annofabcli.filesystem.write_annotation_image.add_parser', (['subparsers'], {}), '(subparsers)\n', (757, 769), False, 'import annofabcli\n'), ((1004, 1120), 'annofabcli.common.cli.add_parser', 'annofabcli.common.cli.add_parser', (['subparsers', 'subcommand_name', 'subcommand_help', 'description'], {'is_subcommand': '(False)'}), '(subparsers, subcommand_name,\n subcommand_help, description, is_subcommand=False)\n', (1036, 1120), False, 'import annofabcli\n')] |
import getpass
import os
import sys
VER = '1.0.1.7'
VERSION = 'Version=%s' % VER
MANUFACTURER = 'Manufacturer=<NAME>'
X86 = 'Platform=x86'
X64 = 'Platform=x64'
TOWIN = 'ToWindows'
def main():
signpwd = getpass.getpass('Password for signing:')
import builddoc
builddoc.main()
os.environ['SIGNPWD'] = signpwd
import makemsi
makemsi.main(['-o', 'launchwin-%s' % VER, X86, VERSION, MANUFACTURER, TOWIN, 'launcher'])
makemsi.main(['-o', 'launcher-%s' % VER, X86, VERSION, MANUFACTURER, 'launcher'])
makemsi.main(['-o', 'launchwin-%s' % VER, X64, VERSION, MANUFACTURER, TOWIN, 'launcher'])
makemsi.main(['-o', 'launcher-%s' % VER, X64, VERSION, MANUFACTURER, 'launcher'])
if __name__ == '__main__':
sys.exit(main()) | [
"builddoc.main",
"getpass.getpass",
"makemsi.main"
] | [((220, 260), 'getpass.getpass', 'getpass.getpass', (['"""Password for signing:"""'], {}), "('Password for signing:')\n", (235, 260), False, 'import getpass\n'), ((287, 302), 'builddoc.main', 'builddoc.main', ([], {}), '()\n', (300, 302), False, 'import builddoc\n'), ((365, 458), 'makemsi.main', 'makemsi.main', (["['-o', 'launchwin-%s' % VER, X86, VERSION, MANUFACTURER, TOWIN, 'launcher']"], {}), "(['-o', 'launchwin-%s' % VER, X86, VERSION, MANUFACTURER, TOWIN,\n 'launcher'])\n", (377, 458), False, 'import makemsi\n'), ((460, 545), 'makemsi.main', 'makemsi.main', (["['-o', 'launcher-%s' % VER, X86, VERSION, MANUFACTURER, 'launcher']"], {}), "(['-o', 'launcher-%s' % VER, X86, VERSION, MANUFACTURER,\n 'launcher'])\n", (472, 545), False, 'import makemsi\n'), ((547, 640), 'makemsi.main', 'makemsi.main', (["['-o', 'launchwin-%s' % VER, X64, VERSION, MANUFACTURER, TOWIN, 'launcher']"], {}), "(['-o', 'launchwin-%s' % VER, X64, VERSION, MANUFACTURER, TOWIN,\n 'launcher'])\n", (559, 640), False, 'import makemsi\n'), ((642, 727), 'makemsi.main', 'makemsi.main', (["['-o', 'launcher-%s' % VER, X64, VERSION, MANUFACTURER, 'launcher']"], {}), "(['-o', 'launcher-%s' % VER, X64, VERSION, MANUFACTURER,\n 'launcher'])\n", (654, 727), False, 'import makemsi\n')] |
from setuptools import setup, Extension
# Compile parts of `freq.cpp` into a shared library so we can call it from Python
setup(
#...
ext_modules=[Extension('gof_test', ['freq.cpp'],),],
)
| [
"setuptools.Extension"
] | [((156, 191), 'setuptools.Extension', 'Extension', (['"""gof_test"""', "['freq.cpp']"], {}), "('gof_test', ['freq.cpp'])\n", (165, 191), False, 'from setuptools import setup, Extension\n')] |
"""
This Module defines the main the main component of the Agent service, a bridge that listens to
UDP messages from the LoRa gateway's Packet Forwarder and encapsulates and sends them using the AMQP
protocol to the Test Application Server (TAS).
"""
#################################################################################
# MIT License
#
# Copyright (c) 2018, <NAME>, Universitat Oberta de Catalunya (UOC),
# Universidad de la Republica Oriental del Uruguay (UdelaR).
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#################################################################################
import os
import random
import socket
import struct
import time
import logging
import lorawan.user_agent.bridge.udp_listener as udp_listener
import message_queueing
import lorawan.parsing.lorawan
import lorawan.parsing.gateway_forwarder
import parameters.message_broker as message_broker
from parameters.message_broker import routing_keys
from lorawan.parsing.flora_messages import GatewayMessage
logger = logging.getLogger(__name__)
PACKET_FORWARDER_VERSION_INT = int(os.environ.get('PACKET_FORWARDER_VERSION_INT'))
class SPFBridge(object):
"""
Semtech Packet Forwarder (SPF) Bridge.
The Bride service running in the agent (user side) is in charge of listening to the uplink messages from the
LoRa gateway (e.g. in the same LAN of the machine running the bridge) in order to forward them to
the broker. The broker then will be in charge of making the messages available to the
testing services (f-interop side).
The Bridge is also in charge of receiving the downlink messages from the testing platform to send them to the
user's gateway.
The user must specify the IP and port of the gateway running the packet forwarder in the environment variables:
- *PF_IP*
- *PF_UDP_PORT*
"""
VERSION = bytes([PACKET_FORWARDER_VERSION_INT])
PUSH_DATA_ID = b"\x00"
PUSH_ACK_ID = b"\x01"
PULL_DATA_ID = b"\x02"
PULL_RESP_ID = b"\x03"
PULL_ACK_ID = b"\x04"
def __init__(self):
"""
Creates a Semtech Packet Forwarder (SPF) Bridge to handle the uplink UDP messages. It is also a consumer
of downlink messages from the broker. The SPF Bridge is a MqInterface.
"""
super().__init__()
self.UDP_IP = os.environ.get('PF_IP')
self.UDP_PORT = int(os.environ.get('PF_UDP_PORT'))
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._sock.bind((self.UDP_IP, self.UDP_PORT))
self.gwdladdrLock1 = udp_listener.UDPListener.create_lock()
self.gwuladdrLock2 = udp_listener.UDPListener.create_lock()
self._gateway_dl_addr = None
self._gateway_ul_addr = None
self.downlink_ready_semaphore = udp_listener.UDPListener.create_semaphore()
self.udp_listener = udp_listener.UDPListener(self)
self._ready_to_downlink = False
self.last_uplink_time = None
self.uplink_mq_interface = message_queueing.MqInterface()
self.downlink_mq_interface = message_queueing.MqInterface()
self.downlink_mq_interface.declare_and_consume(
queue_name='down_nwk',
durable=False,
auto_delete=True,
routing_key=message_broker.routing_keys.toAgent + '.#',
callback=self.process_dlmsg)
@property
def gateway_dl_addr(self):
""" Thread safe access to the downlink address of the gateway's packet forwarder."""
with self.gwdladdrLock1:
retval = self._gateway_dl_addr
return retval
@gateway_dl_addr.setter
def gateway_dl_addr(self, downlink_addr):
""" Thread safe access to the downlink address of the gateway's packet forwarder."""
with self.gwdladdrLock1:
self._gateway_dl_addr = downlink_addr
@property
def gateway_ul_addr(self):
""" Thread safe access to the uplink address of the gateway's packet forwarder."""
with self.gwuladdrLock2:
retval = self._gateway_ul_addr
return retval
@gateway_ul_addr.setter
def gateway_ul_addr(self, uladdr):
""" Thread safe access to the uplink address of the gateway's packet forwarder."""
with self.gwuladdrLock2:
self._gateway_ul_addr = uladdr
def listen_spf(self):
""" Starts to listen for UDP uplink messages from the gateway."""
self.udp_listener.setDaemon(True)
self.udp_listener.start()
def process_dlmsg(self, channel, basic_deliver, properties, body):
"""
Downlink messages handler.
If no PULL_DATA message was previously received from the gateway (so the downlink address is unknown), the
message is ignored.
"""
body_str = body.decode()
if self._ready_to_downlink:
received_gw_message = GatewayMessage(body_str)
self.send_pull_resp(received_gw_message.get_txpk_str().encode())
elapsed_time = time.time() - self.last_uplink_time
logger.info(f"\n\n<<<<<<\nTime since the last uplink: {elapsed_time}\n<<<<<<\n")
logger.info(f"Sending DL to GW: \n{received_gw_message.get_txpk_str().encode()}")
else:
logger.info(
"Agent Bridge NOT ready to downlink: waiting for a PULL_DATA from the gateway.")
def process_uplink_data(self):
"""
Uplink message handler.
When a UDP message is received with an uplink message from the gateway,
it is sent to the broker using the
right routing key.
:return: None
"""
data, addr = self._sock.recvfrom(1024) # buffer size is 1024 bytes
self.last_uplink_time = time.time()
received_msg = lorawan.parsing.gateway_forwarder.SemtechUDPMsg(data)
logger.info(f"{str(received_msg)}")
# PUSH_DATA (ID=0) received -> Send an PUSH_ACK
if received_msg.msg_id == SPFBridge.PUSH_DATA_ID[0]:
push_ack_bytes = data[0:3] + SPFBridge.PUSH_ACK_ID
self.gateway_ul_addr = addr
self.send_ulresponse_raw(push_ack_bytes)
data_msg_list = received_msg.get_data()
if len(data_msg_list) > 0:
for packet in data_msg_list:
# packet[0]: the decoded data
# packet[1]: the json string with the decoded data in it's data field.
self.uplink_mq_interface.publish(msg=packet[1],
routing_key=routing_keys.fromAgent + '.gw1')
# PULL_DATA (ID=2) received -> Send an PULL_ACK
elif received_msg.msg_id == SPFBridge.PULL_DATA_ID[0]:
pull_ack = data[0:3] + SPFBridge.PULL_ACK_ID
self.gateway_dl_addr = addr
if not self._ready_to_downlink:
self._ready_to_downlink = True
self.downlink_ready_semaphore.release()
self.send_dl_raw(pull_ack)
def send_ulresponse_raw(self, ul_message):
"""
(SPFBridge, bytes) -> (None)
Sends a UDP message to the uplink socket of the Packet Forwarder running on the gateway.
:param ul_message: bytes to be sent as the response to an uplink message from the
Gateway's Semtech Packet Forwarder.
:return: None.
"""
assert self._gateway_ul_addr
self._sock.sendto(ul_message, self.gateway_ul_addr)
def send_dl_raw(self, dl_message):
"""
(SPFBridge, bytes) -> (None)
Sends a downlink UDP message to the Packet Forwarder running on the gateway. The IP address must be previously
obtained by receiving a PULL REQUEST message.
:param dl_message: bytes to be sent to the Gateway's Semtech Packet Forwarder.
:return: None.
"""
assert self._gateway_dl_addr is not None
# logger.info(f"Sending message to {self.gateway_dl_addr}")
self._sock.sendto(dl_message, self.gateway_dl_addr)
def send_pull_resp(self, json_bytes):
"""
(SPFBridge, bytes) -> (None)
Sends a message to the gateway using a PULL_RESP (Pull Response) message as defined in the Semtech
Packet Forwarder (SPF) Protocol.
:param json_bytes: byte sequence to be sent in the payload of a SPF PULL_RESP message.
:return: None.
"""
token = random.randint(0, 2 ** 16 - 1)
message = SPFBridge.VERSION + struct.pack(
'>H', token) + SPFBridge.PULL_RESP_ID
self.send_dl_raw(message + json_bytes)
def start_listening_downlink(self):
self.downlink_mq_interface.consume_start()
| [
"logging.getLogger",
"message_queueing.MqInterface",
"socket.socket",
"lorawan.user_agent.bridge.udp_listener.UDPListener.create_semaphore",
"os.environ.get",
"lorawan.parsing.flora_messages.GatewayMessage",
"struct.pack",
"lorawan.user_agent.bridge.udp_listener.UDPListener",
"time.time",
"random.... | [((2026, 2053), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2043, 2053), False, 'import logging\n'), ((2090, 2136), 'os.environ.get', 'os.environ.get', (['"""PACKET_FORWARDER_VERSION_INT"""'], {}), "('PACKET_FORWARDER_VERSION_INT')\n", (2104, 2136), False, 'import os\n'), ((3328, 3351), 'os.environ.get', 'os.environ.get', (['"""PF_IP"""'], {}), "('PF_IP')\n", (3342, 3351), False, 'import os\n'), ((3432, 3480), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (3445, 3480), False, 'import socket\n'), ((3564, 3602), 'lorawan.user_agent.bridge.udp_listener.UDPListener.create_lock', 'udp_listener.UDPListener.create_lock', ([], {}), '()\n', (3600, 3602), True, 'import lorawan.user_agent.bridge.udp_listener as udp_listener\n'), ((3632, 3670), 'lorawan.user_agent.bridge.udp_listener.UDPListener.create_lock', 'udp_listener.UDPListener.create_lock', ([], {}), '()\n', (3668, 3670), True, 'import lorawan.user_agent.bridge.udp_listener as udp_listener\n'), ((3785, 3828), 'lorawan.user_agent.bridge.udp_listener.UDPListener.create_semaphore', 'udp_listener.UDPListener.create_semaphore', ([], {}), '()\n', (3826, 3828), True, 'import lorawan.user_agent.bridge.udp_listener as udp_listener\n'), ((3857, 3887), 'lorawan.user_agent.bridge.udp_listener.UDPListener', 'udp_listener.UDPListener', (['self'], {}), '(self)\n', (3881, 3887), True, 'import lorawan.user_agent.bridge.udp_listener as udp_listener\n'), ((4001, 4031), 'message_queueing.MqInterface', 'message_queueing.MqInterface', ([], {}), '()\n', (4029, 4031), False, 'import message_queueing\n'), ((4069, 4099), 'message_queueing.MqInterface', 'message_queueing.MqInterface', ([], {}), '()\n', (4097, 4099), False, 'import message_queueing\n'), ((6739, 6750), 'time.time', 'time.time', ([], {}), '()\n', (6748, 6750), False, 'import time\n'), ((9406, 9436), 'random.randint', 'random.randint', (['(0)', '(2 ** 16 - 1)'], {}), '(0, 2 ** 16 - 1)\n', (9420, 9436), False, 'import random\n'), ((3380, 3409), 'os.environ.get', 'os.environ.get', (['"""PF_UDP_PORT"""'], {}), "('PF_UDP_PORT')\n", (3394, 3409), False, 'import os\n'), ((5877, 5901), 'lorawan.parsing.flora_messages.GatewayMessage', 'GatewayMessage', (['body_str'], {}), '(body_str)\n', (5891, 5901), False, 'from lorawan.parsing.flora_messages import GatewayMessage\n'), ((6006, 6017), 'time.time', 'time.time', ([], {}), '()\n', (6015, 6017), False, 'import time\n'), ((9475, 9499), 'struct.pack', 'struct.pack', (['""">H"""', 'token'], {}), "('>H', token)\n", (9486, 9499), False, 'import struct\n')] |
from abc import ABC, abstractmethod
from typing import TypeVar, Generic
T = TypeVar("T")
class AbstractResourceResolver(Generic[T], ABC):
"""
The resolver takes care of creating fully qualified names from resource keys.
For instance, when working with files this would be the file path, when working
with databases it will be the fully qualified table name, etc..
"""
@abstractmethod
def resolve(self, key: str) -> T:
pass | [
"typing.TypeVar"
] | [((77, 89), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (84, 89), False, 'from typing import TypeVar, Generic\n')] |
__author__ = '<NAME>'
from odm.document import BaseDocument
from odm.fields import StringField, ObjectIdField, ListField, IntegerField
MAX_NUMBER_OF_LOG_ENTRIES = 32
TIMEPERIOD = 'timeperiod'
PROCESS_NAME = 'process_name'
START_OBJ_ID = 'start_obj_id'
END_OBJ_ID = 'end_obj_id'
STATE = 'state'
RELATED_UNIT_OF_WORK = 'related_unit_of_work'
NUMBER_OF_FAILURES = 'number_of_failures'
# contains list of MAX_NUMBER_OF_LOG_ENTRIES last log messages
HISTORIC_LOG = 'historic_log'
# given Job was _not_ processed by aggregator because of multiple errors/missing data
# this state allows to mute current Job abd allow other timeperiods/Jobs to be processed
# only manual "re-processing" can re-run the skipped Job
STATE_SKIPPED = 'state_skipped'
# given Job was successfully processed by an aggregator
# no further processing for this Job is performed
STATE_PROCESSED = 'state_processed'
# no processing was performed for this Job
# no further processing for this Job is performed
STATE_NOOP = 'state_noop'
# Scheduler assumes that all timeperiod data is in the database, and asks an aggregator to run a "final" aggregation
# Job will be marked as STATE_PROCESSED afterwards if the processing succeed
STATE_FINAL_RUN = 'state_final_run'
# Aggregator is asked to perform a routine aggregation.
# Further state of the Job depends on the governing state machine:
# it could be either STATE_PROCESSED, STATE_IN_PROGRESS, STATE_NOOP, STATE_FINAL_RUN or STATE_SKIPPED
STATE_IN_PROGRESS = 'state_in_progress'
# Given timetable record serves as place-holder in the Tree
# TimeRecord can move to STATE_IN_PROGRESS
STATE_EMBRYO = 'state_embryo'
class Job(BaseDocument):
""" class presents status for the time-period, and indicates whether data was process by particular process"""
db_id = ObjectIdField('_id', null=True)
process_name = StringField(PROCESS_NAME)
timeperiod = StringField(TIMEPERIOD)
start_id = ObjectIdField(START_OBJ_ID)
end_id = ObjectIdField(END_OBJ_ID)
state = StringField(STATE, choices=[STATE_IN_PROGRESS, STATE_PROCESSED, STATE_FINAL_RUN,
STATE_EMBRYO, STATE_SKIPPED, STATE_NOOP])
related_unit_of_work = ObjectIdField(RELATED_UNIT_OF_WORK)
log = ListField(HISTORIC_LOG)
number_of_failures = IntegerField(NUMBER_OF_FAILURES, default=0)
@BaseDocument.key.getter
def key(self):
return self.process_name, self.timeperiod
@key.setter
def key(self, value):
""" :param value: tuple (name of the process, timeperiod as string in Synergy Data format) """
self.process_name = value[0]
self.timeperiod = value[1]
@property
def is_active(self):
return self.state in [STATE_FINAL_RUN, STATE_IN_PROGRESS, STATE_EMBRYO]
@property
def is_finished(self):
return self.state in [STATE_PROCESSED, STATE_SKIPPED, STATE_NOOP]
@property
def is_processed(self):
return self.state == STATE_PROCESSED
@property
def is_noop(self):
return self.state == STATE_NOOP
@property
def is_skipped(self):
return self.state == STATE_SKIPPED
@property
def is_embryo(self):
return self.state == STATE_EMBRYO
@property
def is_in_progress(self):
return self.state == STATE_IN_PROGRESS
@property
def is_final_run(self):
return self.state == STATE_FINAL_RUN
| [
"odm.fields.IntegerField",
"odm.fields.StringField",
"odm.fields.ListField",
"odm.fields.ObjectIdField"
] | [((1792, 1823), 'odm.fields.ObjectIdField', 'ObjectIdField', (['"""_id"""'], {'null': '(True)'}), "('_id', null=True)\n", (1805, 1823), False, 'from odm.fields import StringField, ObjectIdField, ListField, IntegerField\n'), ((1843, 1868), 'odm.fields.StringField', 'StringField', (['PROCESS_NAME'], {}), '(PROCESS_NAME)\n', (1854, 1868), False, 'from odm.fields import StringField, ObjectIdField, ListField, IntegerField\n'), ((1886, 1909), 'odm.fields.StringField', 'StringField', (['TIMEPERIOD'], {}), '(TIMEPERIOD)\n', (1897, 1909), False, 'from odm.fields import StringField, ObjectIdField, ListField, IntegerField\n'), ((1925, 1952), 'odm.fields.ObjectIdField', 'ObjectIdField', (['START_OBJ_ID'], {}), '(START_OBJ_ID)\n', (1938, 1952), False, 'from odm.fields import StringField, ObjectIdField, ListField, IntegerField\n'), ((1966, 1991), 'odm.fields.ObjectIdField', 'ObjectIdField', (['END_OBJ_ID'], {}), '(END_OBJ_ID)\n', (1979, 1991), False, 'from odm.fields import StringField, ObjectIdField, ListField, IntegerField\n'), ((2004, 2130), 'odm.fields.StringField', 'StringField', (['STATE'], {'choices': '[STATE_IN_PROGRESS, STATE_PROCESSED, STATE_FINAL_RUN, STATE_EMBRYO,\n STATE_SKIPPED, STATE_NOOP]'}), '(STATE, choices=[STATE_IN_PROGRESS, STATE_PROCESSED,\n STATE_FINAL_RUN, STATE_EMBRYO, STATE_SKIPPED, STATE_NOOP])\n', (2015, 2130), False, 'from odm.fields import StringField, ObjectIdField, ListField, IntegerField\n'), ((2194, 2229), 'odm.fields.ObjectIdField', 'ObjectIdField', (['RELATED_UNIT_OF_WORK'], {}), '(RELATED_UNIT_OF_WORK)\n', (2207, 2229), False, 'from odm.fields import StringField, ObjectIdField, ListField, IntegerField\n'), ((2240, 2263), 'odm.fields.ListField', 'ListField', (['HISTORIC_LOG'], {}), '(HISTORIC_LOG)\n', (2249, 2263), False, 'from odm.fields import StringField, ObjectIdField, ListField, IntegerField\n'), ((2289, 2332), 'odm.fields.IntegerField', 'IntegerField', (['NUMBER_OF_FAILURES'], {'default': '(0)'}), '(NUMBER_OF_FAILURES, default=0)\n', (2301, 2332), False, 'from odm.fields import StringField, ObjectIdField, ListField, IntegerField\n')] |
import pandas as pd
import os
from pathlib import Path
import warnings
warnings.filterwarnings('ignore')
DATA_PATH = os.path.join(
os.fspath(Path(__file__).parents[1]),
"data")
IMDB_DATA_PATH = os.path.join(DATA_PATH, "imdb_category.csv")
EXPORT_PATH = os.path.join(DATA_PATH, "imdb_category_binary.csv")
categories_df = pd.read_csv(IMDB_DATA_PATH)
cols_category = categories_df.iloc[:, 1:29].columns
categories_df_tmp = categories_df.copy(deep=True)
categories_df_tmp["film_category"] = (categories_df_tmp
.loc[:, cols_category]
.idxmax(axis=1)
.values)
columns_to_drop = [col
for idx, col in enumerate(categories_df_tmp.columns)
if idx in range(1, 29)]
categories_df_tmp.drop(columns_to_drop, axis=1, inplace=True)
categories_binary = categories_df_tmp.join(
pd.get_dummies(
data=categories_df_tmp.film_category,
prefix=None))
categories_binary.drop("film_category", axis=1, inplace=True)
categories_binary.to_csv(EXPORT_PATH, sep=",", index=False)
| [
"pandas.read_csv",
"pathlib.Path",
"os.path.join",
"pandas.get_dummies",
"warnings.filterwarnings"
] | [((72, 105), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (95, 105), False, 'import warnings\n'), ((205, 249), 'os.path.join', 'os.path.join', (['DATA_PATH', '"""imdb_category.csv"""'], {}), "(DATA_PATH, 'imdb_category.csv')\n", (217, 249), False, 'import os\n'), ((264, 315), 'os.path.join', 'os.path.join', (['DATA_PATH', '"""imdb_category_binary.csv"""'], {}), "(DATA_PATH, 'imdb_category_binary.csv')\n", (276, 315), False, 'import os\n'), ((334, 361), 'pandas.read_csv', 'pd.read_csv', (['IMDB_DATA_PATH'], {}), '(IMDB_DATA_PATH)\n', (345, 361), True, 'import pandas as pd\n'), ((932, 997), 'pandas.get_dummies', 'pd.get_dummies', ([], {'data': 'categories_df_tmp.film_category', 'prefix': 'None'}), '(data=categories_df_tmp.film_category, prefix=None)\n', (946, 997), True, 'import pandas as pd\n'), ((148, 162), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (152, 162), False, 'from pathlib import Path\n')] |
from functools import wraps
import numpy as np
import SimpleITK as sitk
from ..utils import array_to_image, image_to_array
def accepts_segmentations(f):
@wraps(f)
def wrapper(img, *args, **kwargs):
result = f(img, *args, **kwargs)
if isinstance(img, Segmentation):
result = sitk.Cast(result, sitk.sitkVectorUInt8)
return Segmentation(result, roi_names=img.roi_names)
else:
return result
return wrapper
def map_over_labels(segmentation, f, include_background=False, return_segmentation=True, **kwargs):
if include_background:
labels = range(segmentation.num_labels + 1)
else:
labels = range(1, segmentation.num_labels + 1)
res = [f(segmentation.get_label(label=label), **kwargs) for label in labels]
if return_segmentation and isinstance(res[0], sitk.Image):
res = [sitk.Cast(r, sitk.sitkUInt8) for r in res]
res = Segmentation(sitk.Compose(*res), roi_names=segmentation.roi_names)
return res
class Segmentation(sitk.Image):
def __init__(self, segmentation, roi_names=None):
super().__init__(segmentation)
self.num_labels = self.GetNumberOfComponentsPerPixel()
if not roi_names:
self.roi_names = {f"label_{i}": i for i in range(1, self.num_labels+1)}
else:
self.roi_names = roi_names
if 0 in self.roi_names.values():
self.roi_names = {k : v+1 for k, v in self.roi_names.items()}
if len(self.roi_names) != self.num_labels:
for i in range(1, self.num_labels+1):
if i not in self.roi_names.values():
self.roi_names[f"label_{i}"] = i
def get_label(self, label=None, name=None, relabel=False):
if label is None and name is None:
raise ValueError("Must pass either label or name.")
if label is None:
label = self.roi_names[name]
if label == 0:
# background is stored implicitly and needs to be computed
label_arr = sitk.GetArrayViewFromImage(self)
label_img = sitk.GetImageFromArray((label_arr.sum(-1) == 0).astype(np.uint8))
else:
label_img = sitk.VectorIndexSelectionCast(self, label - 1)
if relabel:
label_img *= label
return label_img
def to_label_image(self):
arr, *_ = image_to_array(self)
# TODO handle overlapping labels
label_arr = np.where(arr.sum(-1) != 0, arr.argmax(-1) + 1, 0)
label_img = array_to_image(label_arr, reference_image=self)
return label_img
# TODO also overload other operators (arithmetic, etc.)
# with some sensible behaviour
def __getitem__(self, idx):
res = super().__getitem__(idx)
if isinstance(res, sitk.Image):
res = Segmentation(res, self.roi_names)
return res
def __repr__(self):
return f"<Segmentation with ROIs: {self.roi_names!r}>"
| [
"SimpleITK.Compose",
"SimpleITK.GetArrayViewFromImage",
"functools.wraps",
"SimpleITK.VectorIndexSelectionCast",
"SimpleITK.Cast"
] | [((162, 170), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (167, 170), False, 'from functools import wraps\n'), ((317, 356), 'SimpleITK.Cast', 'sitk.Cast', (['result', 'sitk.sitkVectorUInt8'], {}), '(result, sitk.sitkVectorUInt8)\n', (326, 356), True, 'import SimpleITK as sitk\n'), ((889, 917), 'SimpleITK.Cast', 'sitk.Cast', (['r', 'sitk.sitkUInt8'], {}), '(r, sitk.sitkUInt8)\n', (898, 917), True, 'import SimpleITK as sitk\n'), ((959, 977), 'SimpleITK.Compose', 'sitk.Compose', (['*res'], {}), '(*res)\n', (971, 977), True, 'import SimpleITK as sitk\n'), ((2069, 2101), 'SimpleITK.GetArrayViewFromImage', 'sitk.GetArrayViewFromImage', (['self'], {}), '(self)\n', (2095, 2101), True, 'import SimpleITK as sitk\n'), ((2230, 2276), 'SimpleITK.VectorIndexSelectionCast', 'sitk.VectorIndexSelectionCast', (['self', '(label - 1)'], {}), '(self, label - 1)\n', (2259, 2276), True, 'import SimpleITK as sitk\n')] |
"""
Wrapper for epi_reg command
"""
import fsl.utils.assertions as asrt
from fsl.wrappers import wrapperutils as wutils
@wutils.fileOrImage('data', 'roi', outprefix='out')
@wutils.fileOrArray('veslocs', 'encdef', 'modmat')
@wutils.fileOrText(' ')
@wutils.fslwrapper
def veaslc(data, roi, veslocs, encdef, imlist, modmat, out="veaslc", **kwargs):
"""
Wrapper for the ``veasl`` command.
Required options:
Additional options:
"""
valmap = {
'inferv' : wutils.SHOW_IF_TRUE,
'debug' : wutils.SHOW_IF_TRUE,
'diff' : wutils.SHOW_IF_TRUE,
}
asrt.assertIsNifti(data)
cmd = ['veasl', '--data=%s' % data, '--mask=%s' % roi, '--enc-setup=%s' % encdef,
'--imlist=%s' % imlist, '--vessels=%s' % veslocs, '--modmat=%s' % modmat,
'--out=%s' % out]
if kwargs.pop("method", "map") == "map":
cmd.append('--map')
cmd += wutils.applyArgStyle('--=', valmap=valmap, singlechar_args=True, **kwargs)
return cmd
| [
"fsl.wrappers.wrapperutils.fileOrArray",
"fsl.utils.assertions.assertIsNifti",
"fsl.wrappers.wrapperutils.fileOrImage",
"fsl.wrappers.wrapperutils.fileOrText",
"fsl.wrappers.wrapperutils.applyArgStyle"
] | [((124, 174), 'fsl.wrappers.wrapperutils.fileOrImage', 'wutils.fileOrImage', (['"""data"""', '"""roi"""'], {'outprefix': '"""out"""'}), "('data', 'roi', outprefix='out')\n", (142, 174), True, 'from fsl.wrappers import wrapperutils as wutils\n'), ((176, 225), 'fsl.wrappers.wrapperutils.fileOrArray', 'wutils.fileOrArray', (['"""veslocs"""', '"""encdef"""', '"""modmat"""'], {}), "('veslocs', 'encdef', 'modmat')\n", (194, 225), True, 'from fsl.wrappers import wrapperutils as wutils\n'), ((227, 249), 'fsl.wrappers.wrapperutils.fileOrText', 'wutils.fileOrText', (['""" """'], {}), "(' ')\n", (244, 249), True, 'from fsl.wrappers import wrapperutils as wutils\n'), ((604, 628), 'fsl.utils.assertions.assertIsNifti', 'asrt.assertIsNifti', (['data'], {}), '(data)\n', (622, 628), True, 'import fsl.utils.assertions as asrt\n'), ((916, 990), 'fsl.wrappers.wrapperutils.applyArgStyle', 'wutils.applyArgStyle', (['"""--="""'], {'valmap': 'valmap', 'singlechar_args': '(True)'}), "('--=', valmap=valmap, singlechar_args=True, **kwargs)\n", (936, 990), True, 'from fsl.wrappers import wrapperutils as wutils\n')] |
import torchaudio.transforms
from torch import nn
from hw_asr.augmentations.base import AugmentationBase
from hw_asr.augmentations.random_apply import RandomApply
class SpecAug(AugmentationBase):
def __init__(self, freq_mask: int, time_mask: int, prob: float, *args, **kwargs):
self.augmentation = nn.Sequential(
torchaudio.transforms.FrequencyMasking(freq_mask),
torchaudio.transforms.TimeMasking(time_mask)
)
self.prob = prob
self.random_caller = RandomApply(self.augmentation, self.prob)
def __call__(self, data, *args, **kwargs):
return self.random_caller(data)
| [
"hw_asr.augmentations.random_apply.RandomApply"
] | [((512, 553), 'hw_asr.augmentations.random_apply.RandomApply', 'RandomApply', (['self.augmentation', 'self.prob'], {}), '(self.augmentation, self.prob)\n', (523, 553), False, 'from hw_asr.augmentations.random_apply import RandomApply\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 17:18:39 2021
@author: Koustav
"""
import os
import glob
import matplotlib.pyplot as plt
import seaborn as sea
import numpy as np
import pandas as pan
import math
import collections
import matplotlib.ticker as mtick
from mpl_toolkits import mplot3d
from matplotlib.collections import LineCollection
from scipy.optimize import curve_fit
import powerlaw
def pow_law(x, a, expo):
return a*(np.power(x, expo))
def trunc_pow_law(x, a, expo, trunc_expo): #Truncated Power Law
return a*(np.power(x, expo))*np.exp(trunc_expo*x)
def main_ind():
fandango = np.genfromtxt("PissingAbout15+16.csv", delimiter=",", comments='#', skip_header=1)
#Stores decay data of cross-correlation between frames as a function of p.
gaol={} #Stores truncated power law fit data.
gaol[0.60] =[]; gaol[0.70] =[]; gaol[0.75] =[];
gaol[0.80] =[]; gaol[0.90] =[]; gaol[0.95] =[];
L=0
for i in range(6,7):
base_path = r"22Apret\Apres 256+512\256" + "\\" + str(i)
files = glob.glob(base_path + "**/**/*.csv", recursive=True)
for file in files:
if (file == base_path + r"\dump\15_16_KungF---U.csv"):
continue
if (os.path.getsize(file) > 4096):
#Keeping unwanted files out.
print(file)
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1)
'''
data_temp resembles:
| L, p, lag, #, s, s + del(s) |
Hai
'''
p= data_temp[0,1]; L= int(data_temp[0,0]); CC= cross_cor(fandango, data_temp[0,2], L, p)
'''if(p == 0.728):
print("Skipped")
continue'''
data_temp[:,5] -= data_temp[:,4]
data_temp[:,5] = np.abs(data_temp[:,5])
temp_freqs = dict(collections.Counter(data_temp[:,5]))
a,b = data_temp.shape
DP_freqs = {k: v / (a) for k, v in temp_freqs.items()}
DP_freqs = np.array(list(DP_freqs.items())) #Converting dictionary to numpy array.
#Sorting array in increasing order of del(s).
#DP_freqs = DP_freqs[DP_freqs[:,0].argsort()]
#Next, to convert PDF into 1 - CDF (P(S >= (DEL(S))))
print("Sorted del(s) PDF:")
print(DP_freqs)
'''DP_freqs[-2,1] += DP_freqs[-1,1]; #DP_freqs[-1,1] = 0
k= len(DP_freqs[:,1]) #Finding total number of del(s) elements
print("Total distinct del(s) samples:\t" +str(k))
for j in range(k-3, -1, -1):
#Iterate over the PDF function in reverse.
DP_freqs[j,1] += DP_freqs[j+1,1]
print("Sorted del(s) 1-CDF:")
print(DP_freqs)'''
os.chdir("../../../figures")
if(os.path.isdir("del_S")==False):
os.mkdir("del_S")
os.chdir("del_S")
if(os.path.isdir("DP")==False):
os.mkdir("DP")
os.chdir("DP")
if(os.path.isdir("Individual")==False):
os.mkdir("Individual")
os.chdir("Individual")
'''if(os.path.isdir("1-CDF")==False):
os.mkdir("1-CDF")
os.chdir("1-CDF")'''
if(os.path.isdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))==False):
os.mkdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))
os.chdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))
print("p:\t" +str(p) + " L:\t"+ str(L) + " CC:\t" +str(CC))
#hurtlocker= pan.DataFrame(DP_freqs, columns= [r"$|\Delta s|$", r"$P (S \geq \Delta s)$"])
hurtlocker= pan.DataFrame(DP_freqs, columns= [r"$|\Delta s|$", r"$P (S = \Delta s)$"])
fig = plt.figure(figsize=(6.4,4.8))
f = sea.scatterplot(data=hurtlocker, x=r"$|\Delta s|$" , y=r"$P (S = \Delta s)$")
f.set_title('p = %f, Grid Size (G) = %d, Cross-Correlation = %3.2f' %(p, L, CC))
#Overlaying two seaborn plots.
#ax = fig.add_subplot(111)
#sea.scatterplot(data=hurtlocker, x=r"$|\Delta s|$" , y=r"$P (S \geq \Delta s)$", alpha=0.5, s=2, ax= ax)
#sea.lineplot(data=hurtlocker, x=r"$|\Delta s|$" , y=r"$P (S \geq \Delta s)$", alpha=0.2, ax= ax) #, s=1)
#ax.set_title('p = %f, Grid Size (G) = %d, Cross-Correlation = %3.2f' %(p, L, CC))
plt.yscale('log'); plt.xscale('log')
plt.xlim(1, 10**5)
plt.ylim(10**(-6.4), 10**(0.1))
plt.savefig("0P(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png" %(p,L,CC), dpi=400)
#plt.show()
plt.close()
'''x1 = np.transpose(DP_freqs[:,0])
x2 = np.transpose(DP_freqs[:,1])
popt, pcov = curve_fit(trunc_pow_law, x1, x2, p0= np.asarray([1, -0.75, -0.0005]), maxfev=5000 )
perr = np.sqrt(np.diag(pcov))
print("SD of exponent:\t" +str(perr[1]) + " for p:\t" +str(p))
tukan= (popt[0], popt[1], perr[1], popt[2], perr[2])
plt.plot(x1, trunc_pow_law(x1, *popt), 'm--', label=r'Fit: $ P (S \geq \Delta s) = %3.2f \times \Delta s^{(%4.3f \mp %4.3f)}\times e^{(%4.3f \mp %4.3f)\times \Delta s}$ ' % tukan )
plt.ylim(10**(-6.4), 10**(0.1)); plt.xlim(1, 10**5)
plt.legend()
plt.savefig("Fit 1- CDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png" %(p,L,CC), dpi=400)
#plt.show()
plt.close()
#Saving best fit data.
gaol[float(round(CC,2))].append([L, p, -popt[1], perr[1], -popt[2], perr[2]])'''
os.chdir(r"..\..\..\..\..\analysis\Mass Action\DP")
#break;
#Saving as CSVs.
'''if(os.path.isdir("del_S")==False):
os.mkdir("del_S")
os.chdir("del_S")
if(os.path.isdir("%d" %(L))==False):
os.mkdir("%d" %(L))
os.chdir("%d" %(L))
K= [0.6, 0.7, 0.75, 0.8, 0.9, 0.95]
heado = 'L, p, alpha, SD(alpha), lambda, SD(lambda)'
for k in K:
np.savetxt("BestFitCDF_CC_%3.2F.csv" %(k), gaol[k], delimiter=',', header=heado, comments='#')
os.chdir(r"../../")'''
def main_ccdf_fit():
fandango = np.genfromtxt("PissingAbout15+16.csv", delimiter=",", comments='#', skip_header=1)
#Stores decay data of cross-correlation between frames as a function of p.
gaol={} #Stores truncated power law fit data.
gaol[0.60] =[]; gaol[0.70] =[]; gaol[0.75] =[];
gaol[0.80] =[]; gaol[0.90] =[]; gaol[0.95] =[];
L=0; crosc= 0.7
for i in range(0,10):
base_path = r"22Apret\Apres 256+512\512" + "\\" + str(i)
files = glob.glob(base_path + "**/**/*.csv", recursive=True)
for file in files:
if (file == base_path + r"\dump\15_16_KungF---U.csv"):
continue
if (os.path.getsize(file) > 4096):
#Keeping unwanted files out.
print(file)
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1, max_rows=3)
p= data_temp[0,1]; L= int(data_temp[0,0]); CC= cross_cor(fandango, data_temp[0,2], L, p)
if( p == 0.678):
print(str(CC) + " " + str(p) + " shall be skipped.")
continue
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1)
'''
data_temp resembles:
| L, p, lag, #, s, s + del(s) |
'''
p= data_temp[0,1]; L= int(data_temp[0,0]); CC= cross_cor(fandango, data_temp[0,2], L, p)
data_temp[:,5] -= data_temp[:,4]
data_temp[:,5] = np.abs(data_temp[:,5])
fit = powerlaw.Fit(data_temp[:,5],discrete=True,estimate_discrete = False) #If you already know xmin pass it as an argument (xmin=value) for speed
print("p:\t" +str(p) + " L:\t"+ str(L) + " CC:\t" +str(CC))
print('x_min: ',fit.xmin)
print('alpha: ',fit.truncated_power_law.parameter1)
print('1/lambda: ',1/fit.truncated_power_law.parameter2)
tukan = (-fit.truncated_power_law.parameter1, -fit.truncated_power_law.parameter2)
fig = fit.plot_ccdf(color ='cornflowerblue', ls='-', linewidth=1.1, alpha=0.2)
fit.plot_ccdf(color='darkcyan',marker='o', linestyle='', ms=1.2, alpha=0.35, ax=fig)
#ax = fig.add_subplot(111)
fit.truncated_power_law.plot_ccdf(color='darkslateblue', linestyle='--', label=r'Fit: $ P (S \geq \Delta s) \propto \Delta s^{(%4.3f)}\times e^{(%6.5f)\times \Delta s}$ ' % tukan, ax=fig)
fig.set_title('p = %f, Grid Size (G) = %d, Cross-Correlation = %3.2f' %(p, L, CC))
#x = fit.xmins
#y = fit.Ds
#plt.ylim(10**(-6.4), 10**(0.1));
plt.xlim(1, 10**5.3)
plt.xlabel(r"$|\Delta s|$")
plt.ylabel(r"$P (S \geq \Delta s)$")
plt.legend()
os.chdir("../../../figures")
if(os.path.isdir("del_S")==False):
os.mkdir("del_S")
os.chdir("del_S")
if(os.path.isdir("DP")==False):
os.mkdir("DP")
os.chdir("DP")
if(os.path.isdir("Individual")==False):
os.mkdir("Individual")
os.chdir("Individual")
if(os.path.isdir("1-CDF")==False):
os.mkdir("1-CDF")
os.chdir("1-CDF")
if(os.path.isdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))==False):
os.mkdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))
os.chdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))
plt.savefig("Better Fit 1- CDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png" %(p,L,CC), dpi=400)
#plt.show()
plt.close()
os.chdir("../../")
if(os.path.isdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))==False):
os.mkdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))
os.chdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))
print("Done with CDF Plots And Fits. Moving On To PDF Plots...")
fig = fit.plot_pdf(color='darkcyan',marker='o', linestyle='', ms=1.5, alpha=0.4)
#fit.plot_pdf(color='darkcyan',marker='o', linestyle='', ms=1.2, alpha=0.35, ax=fig)
#ax = fig.add_subplot(111)
fit.truncated_power_law.plot_pdf(color='darkslateblue', linestyle='--', label=r'Fit: $ P (S = \Delta s) \propto \Delta s^{(%4.3f)}\times e^{(%6.5f)\times \Delta s}$ ' % tukan, ax=fig)
fig.set_title('p = %f, Grid Size (G) = %d, Cross-Correlation = %3.2f' %(p, L, CC))
#x = fit.xmins
#y = fit.Ds
#plt.ylim(10**(-6.4), 10**(0.1));
plt.xlim(1, 10**5.3)
plt.xlabel(r"$|\Delta s|$")
plt.ylabel(r"$P (S = \Delta s)$")
plt.legend()
plt.savefig("Better Fit PDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png" %(p,L,CC), dpi=400)
#plt.show()
plt.close()
comparison_tpl_exp = fit.distribution_compare('truncated_power_law','exponential',normalized_ratio=True)
comparison_tpl_streched_exp = fit.distribution_compare('truncated_power_law','stretched_exponential',normalized_ratio=True)
comparison_tpl_log_normal = fit.distribution_compare('truncated_power_law','lognormal',normalized_ratio=True)
comparison_tpl_pl = fit.distribution_compare('truncated_power_law','power_law',normalized_ratio=True)
f = open("Taupe.txt", "w+")
f.write("LR (Power Law): " + str(comparison_tpl_pl[0]) +" p-value: "+ str(comparison_tpl_pl[1]) +"\n")
f.write("LR (Exponential): " + str(comparison_tpl_exp[0]) +" p-value: "+ str(comparison_tpl_exp[1]) +"\n")
f.write("LR (Log-Normal): " + str(comparison_tpl_log_normal[0]) +" p-value: "+ str(comparison_tpl_log_normal[1]) +"\n")
f.write("LR (Stretched-Exponential): " + str(comparison_tpl_streched_exp[0]) +" p-value: "+ str(comparison_tpl_streched_exp[1]) +"\n")
f.close()
print("LR (Power Law): ",comparison_tpl_pl[0]," p-value: ",comparison_tpl_pl[1])
print("LR (Exponential): ",comparison_tpl_exp[0]," p-value: ",comparison_tpl_exp[1])
print("LR (Log-Normal): ",comparison_tpl_log_normal[0]," p-value: ",comparison_tpl_log_normal[1])
print("LR (Stretched-Exponential): ",comparison_tpl_streched_exp[0]," p-value: ",comparison_tpl_streched_exp[1])
gaol[float(round(CC,2))].append([L, p, fit.xmin, fit.truncated_power_law.parameter1, 1/fit.truncated_power_law.parameter2])
os.chdir(r"..\..\..\..\..\analysis\Mass Action\DP")
if(os.path.isdir("del_S")==False):
os.mkdir("del_S")
os.chdir("del_S")
if(os.path.isdir("%d" %(L))==False):
os.mkdir("%d" %(L))
os.chdir("%d" %(L))
K= [0.6, 0.7, 0.75, 0.8, 0.9, 0.95]
heado = 'L, p, x_min, alpha, 1/lambda'
for k in K:
np.savetxt("Nu_Pow_0_6_BestFitCDF_CC_%3.2F.csv" %(k), gaol[k], delimiter=',', header=heado, comments='#')
os.chdir(r"../../")
def main_cumulative():
p_c = 0.725194
crosc = float(input("Enter a Cross-Correlation Value To Be Analysed (Choose Between 0.95, 0.9, 0.8, 0.75, 0.7 & 0.6):\t"))
fandango = np.genfromtxt("PissingAbout15+16.csv", delimiter=",", comments='#', skip_header=1)
#Stores decay data of cross-correlation between frames as a function of p.
binder=[]; L=0;
for i in range(0,10):
base_path = r"22Apret\Apres 256+512\512" + "\\" + str(i)
files = glob.glob(base_path + "**/**/*.csv", recursive=True)
for file in files:
if (file == base_path + r"\dump\15_16_KungF---U.csv"):
print('Gandu')
continue
if (os.path.getsize(file) > 4096):
#Keeping unwanted files out.
print(file)
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1, max_rows=3)
p= data_temp[0,1]; L= int(data_temp[0,0]); CC= cross_cor(fandango, data_temp[0,2], L, p)
if( CC <= crosc - 0.01 or CC >= crosc + 0.01):
print(str(CC) + " shall be skipped.")
continue
if( p == 0.678):
print("Fuck You")
continue
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1)
'''
data_temp resembles:
| L, p, lag, #, s, s + del(s) |
'''
data_temp[:,5] -= data_temp[:,4]
data_temp[:,5] = np.abs(data_temp[:,5])
temp_freqs = dict(collections.Counter(data_temp[:,5]))
a,b = data_temp.shape
DP_freqs = {k: v / a for k, v in temp_freqs.items()}
DP_freqs = np.array(list(DP_freqs.items())) #Converting dictionary to numpy array.
a,b =DP_freqs.shape
#col_P= np.zeros((a,1)); col_P = p
DP_freqs = np.insert(DP_freqs, 0, p, axis=1)
'''DP_freqs looks like:
| p, del(s), P(del(s))|
'''
'''DP_freqs = list(DP_freqs.items()) #Converting dictionary to list.
for j in range(0,len(DP_freqs)):
DP_freqs[j].append(p)'''
print(DP_freqs)
if(len(binder)==0):
#First one in the bag.
binder = DP_freqs.tolist()
else:
binder.extend(DP_freqs.tolist())
os.chdir("../../../figures")
if(os.path.isdir("del_S")==False):
os.mkdir("del_S")
os.chdir("del_S")
if(os.path.isdir("DP")==False):
os.mkdir("DP")
os.chdir("DP")
if(os.path.isdir("3D")==False):
os.mkdir("3D")
os.chdir("3D")
if(os.path.isdir("%d" %(L))==False):
os.mkdir("%d" %(L))
os.chdir("%d" %(L))
binder= np.array(binder)
fig=plt.figure()
ax = plt.axes(projection='3d')
#surf1 =ax.plot_trisurf(np.log10(binder[:,1]), binder[:,0], np.log10(binder[:,2]), cmap='viridis', edgecolor='none')
'''for k in range(0,len(self.x1)):
#Plotting SD bars
ax.plot([self.x1[k], self.x1[k]], [self.y1[k], self.y1[k]], [self.z1[k] + self.sd_z1[k], self.z1[k] - self.sd_z1[k]], marker="_", markerfacecolor='k', color='k')
'''
surf1 =ax.scatter(np.log10(binder[:,1]), binder[:,0], np.log10(binder[:,2]), c= np.log10(binder[:,2]), cmap='viridis', linewidth=0.5)
cbar1=fig.colorbar(surf1, shrink=0.75)
cbar1.ax.get_yaxis().labelpad = 12
cbar1.ax.set_ylabel(r"$P (S=\Delta s)$", rotation=270)
ax.set_xlabel(r"$log_{10}|\Delta s|$")
ax.set_zlabel(r"$log_{10}|P (S=\Delta s)|$")
ax.set_ylabel("Occupancy rate (p)")
#plt.zscale('log'); plt.xscale('log')
ax.view_init(elev=36.0, azim=-52.0)
ax.legend()
ax.set_title(r"$P (S=\Delta s)$ vs $|\Delta s|$, L = %d, $R_{0,0}$ = %3.2f" %(L,crosc))
plt.savefig("Cumulative Scatter P(del(s)) vs del(s) --- Grid Size (G)_%d - CC_%3.2f.png" %(L,crosc), dpi=550)
plt.show()
plt.close()
'''Now for scatter plot'''
fig=plt.figure(figsize=(6.4,4.8))
#ax = plt.axes(projection='3d')
ax = fig.add_subplot(111,projection='3d')
surf1 =ax.scatter(np.log10(binder[:,1]), binder[:,0], np.log10(binder[:,2]), c= np.log10(binder[:,2]), cmap='viridis', linewidth=0.5)
'''for k in range(0,len(self.x1)):
#Plotting SD bars
ax.plot([self.x1[k], self.x1[k]], [self.y1[k], self.y1[k]], [self.z1[k] + self.sd_z1[k], self.z1[k] - self.sd_z1[k]], marker="_", markerfacecolor='k', color='k')
'''
cbar1=fig.colorbar(surf1, shrink=0.75)
cbar1.ax.get_yaxis().labelpad = 12
cbar1.ax.set_ylabel(r"$log|P (S=\Delta s)|$", rotation=270)
ax.set_xlabel(r"$log_{10}|\Delta s|$")
ax.set_xlim(-0.1, 5)
ax.set_zlabel(r"$log_{10}|P (S=\Delta s)|$")
ax.set_zlim(-6.1, 0)
ax.set_ylabel("Occupancy rate (p)")
#plt.zscale('log'); plt.xscale('log')
#Plotting p_c plane.
x = np.linspace(-1,5.5,10)
z = np.linspace(-7,1,10)
X,Z = np.meshgrid(x,z)
Y= 0*X +0*Z + p_c
#ax.hold(True) #Preserve pre-plotted elements.
ax.plot_surface(X,Y,Z, alpha= 0.3, color='k', antialiased=True)
ax.text(5, p_c, -1, "$p_{c}(q)$", color='0.5')
'''p_clin = np.array([[0,p_c], [5,p_c]])
lines = LineCollection([p_clin],zorder=1000,color='0.65',lw=2)
ax.add_collection3d(lines, zs=-90)'''
ax.view_init(elev=36.0, azim=-52.0)
ax.legend()
ax.set_title(r"$log|P (S=\Delta s)|$ vs $log|\Delta s|$, L = %d, $R_{0,0}$ = %3.2f" %(L,crosc))
plt.savefig("Cumulative Scatter Plane P(del(s)) vs del(s) --- Grid Size (G)_%d - CC_%3.2f.png" %(L,crosc), dpi=550)
ax.view_init(elev=62.0, azim=-3.0)
plt.savefig("Cumulative Scatter Plane P(del(s)) vs del(s) Top Down --- Grid Size (G)_%d - CC_%3.2f.png" %(L,crosc), dpi=550)
plt.show()
plt.close()
os.chdir(r"..\..\..\..\..\analysis\Mass Action\DP")
def main_del_s_count():
p_c = 0.725194
crosc = float(input("Enter a Cross-Correlation Value To Be Analysed (Choose Between 0.95, 0.9, 0.8, 0.75, 0.7 & 0.6):\t"))
fandango = np.genfromtxt("PissingAbout15+16.csv", delimiter=",", comments='#', skip_header=1)
#Stores decay data of cross-correlation between frames as a function of p.
binder=[]; L=0;
for i in range(0,10):
base_path = r"22Apret\Apres 256+512\256" + "\\" + str(i)
files = glob.glob(base_path + "**/**/*.csv", recursive=True)
for file in files:
if (file == base_path + r"\dump\15_16_KungF---U.csv"):
print('Gandu')
continue
if (os.path.getsize(file) > 4096):
#Keeping unwanted files out.
print(file)
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1, max_rows=3)
p= data_temp[0,1]; L= int(data_temp[0,0]); CC= cross_cor(fandango, data_temp[0,2], L, p)
if( CC <= crosc - 0.01 or CC >= crosc + 0.01):
print(str(CC) + " shall be skipped.")
continue
if( p == 0.678):
print("Fuck You")
continue
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1)
'''
data_temp resembles:
| L, p, lag, #, s, s + del(s) |
'''
data_temp[:,5] -= data_temp[:,4]
data_temp[:,5] = np.abs(data_temp[:,5])
temp_freqs = dict(collections.Counter(data_temp[:,5]))
a,b = data_temp.shape
DP_freqs = {k: v / a for k, v in temp_freqs.items()}
DP_freqs = np.array(list(DP_freqs.items())) #Converting dictionary to numpy array.
a,b =DP_freqs.shape
#col_P= np.zeros((a,1)); col_P = p
DP_freqs = np.insert(DP_freqs, 0, p, axis=1)
'''DP_freqs looks like:
| p, del(s), P(del(s))|
'''
'''DP_freqs = list(DP_freqs.items()) #Converting dictionary to list.
for j in range(0,len(DP_freqs)):
DP_freqs[j].append(p)'''
print(DP_freqs)
print("Number of del s counts: " + str(a))
binder.append([p, a])
os.chdir("../../../figures")
if(os.path.isdir("del_S")==False):
os.mkdir("del_S")
os.chdir("del_S")
if(os.path.isdir("DP")==False):
os.mkdir("DP")
os.chdir("DP")
if(os.path.isdir("Bifurcation")==False):
os.mkdir("Bifurcation")
os.chdir("Bifurcation")
if(os.path.isdir("S Count")==False):
os.mkdir("S Count")
os.chdir("S Count")
binder= np.array(binder)
hurtlocker= pan.DataFrame(binder, columns= ["p", r"Number of unique $|\Delta s|$ observations"])
f = sea.scatterplot(data=hurtlocker, x="p" , y=r"Number of unique $|\Delta s|$ observations")#, marker="+")
#sea.lineplot(data=hurtlocker, x=r"$|\Delta s|$" , y=r"$P (S \geq \Delta s)$", alpha=0.2, ax= ax) #, s=1)
f.set_title('Unique $|\Delta s|$ observations, Grid Size (G) = %d, Cross-Correlation = %3.2f' %( L, crosc))
#plt.yscale('log'); #plt.xscale('log')
#plt.ylim(1, 10**5)
plt.axvline(x= p_c, color='0.65')
plt.text(p_c+ 0.003,10**2,r'$p_{c}$',rotation=90, color ='0.65')
plt.savefig("S Count, Grid Size (G) = %d, CC = %3.2f.png" %(L, crosc), dpi=400)
plt.show()
plt.close()
os.chdir(r"..\..\..\..\..\analysis\Mass Action\DP")
def main_del_s_symmetry():
p_mask=[0.658, 0.666, 0.678, 0.689, 0.701, 0.728, 0.739, 0.743, 0.755, 0.773 ]
fandango = np.genfromtxt("PissingAbout15+16.csv", delimiter=",", comments='#', skip_header=1)
#Stores decay data of cross-correlation between frames as a function of p.
for i in range(0,10):
base_path = r"22Apret\Apres 256+512\256" + "\\" + str(i)
files = glob.glob(base_path + "**/**/*.csv", recursive=True)
MastBind=[]; L=0
for file in files:
if (file == base_path + r"\dump\15_16_KungF---U.csv"):
continue
if (os.path.getsize(file) > 4096):
#Keeping unwanted files out.
print(file)
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1, max_rows=3)
p= data_temp[0,1]; L= int(data_temp[0,0]); CC= cross_cor(fandango, data_temp[0,2], L, p)
if( p not in p_mask):
continue
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1)
'''
data_temp resembles:
| L, p, lag, #, s, s + del(s) |
'''
data_temp[:,5] -= data_temp[:,4]
#data_temp[:,5] = np.abs(data_temp[:,5])
temp_freqs = dict(collections.Counter(data_temp[:,5]))
a,b = data_temp.shape
DP_freqs = {k: v / (a) for k, v in temp_freqs.items()}
DP_freqs = np.array(list(DP_freqs.items())) #Converting dictionary to numpy array.
#Sorting array in increasing order of del(s).
DP_freqs = DP_freqs[DP_freqs[:,0].argsort()]
#Next, to convert PDF into 1 - CDF (P(S >= (DEL(S))))
print("Sorted del(s) PDF:")
print(DP_freqs)
#DP_freqs[-2,1] += DP_freqs[-1,1]; #DP_freqs[-1,1] = 0
k= len(DP_freqs[:,1]) #Finding total number of del(s) elements
print("Total distinct del(s) samples:\t" +str(k))
'''Performing a log-mod transform
https://blogs.sas.com/content/iml/2014/07/14/log-transformation-of-pos-neg.html
https://juluribk.com/dealing-with-plotting-negative-zero-and-positive-values-in-log-scale.html
'''
DP_freqs[:,0] = np.sign(DP_freqs[:,0])*(np.log10(np.abs(DP_freqs[:,0])+1))
DP_freqs = np.insert(DP_freqs, 2, float(round(CC,2)), axis=1)
DP_freqs = np.insert(DP_freqs, 3, p, axis=1)
'''DP_freqs looks like:
|del(s), P(del(s)), CC, p|
'''
print("Final del(s) PDF:")
print(DP_freqs)
if(len(MastBind)== 0):
#Empty
MastBind = DP_freqs
else:
MastBind = np.concatenate((MastBind, DP_freqs), axis=0)
'''for j in range(k-3, -1, -1):
#Iterate over the PDF function in reverse.
DP_freqs[j,1] += DP_freqs[j+1,1]
print("Sorted del(s) 1-CDF:")
print(DP_freqs)'''
os.chdir("../../../figures")
if(os.path.isdir("del_S")==False):
os.mkdir("del_S")
os.chdir("del_S")
if(os.path.isdir("DP")==False):
os.mkdir("DP")
os.chdir("DP")
if(os.path.isdir("Individual")==False):
os.mkdir("Individual")
os.chdir("Individual")
if(os.path.isdir("Symmetry")==False):
os.mkdir("Symmetry")
os.chdir("Symmetry")
if(os.path.isdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))==False):
os.mkdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))
os.chdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))
print("p:\t" +str(p) + " L:\t"+ str(L) + " CC:\t" +str(CC))
hurtlocker= pan.DataFrame(DP_freqs, columns= [r"$\Delta s$", r"$P (S = \Delta s)$", "Cross-Correlation", "p"])
fig = plt.figure(figsize=(6.4,4.8))
#Overlaying two seaborn plots.
#ax = fig.add_subplot(111)
f= sea.scatterplot(data=hurtlocker, x=r"$\Delta s$" , y=r"$P (S = \Delta s)$")#, alpha=0.5, s=2, ax= ax)
#sea.lineplot(data=hurtlocker, x=r"$\Delta s$" , y=r"$P (S = \Delta s)$", alpha=0.2, ax= ax) #, s=1)
f.set_title('p = %f, Grid Size (G) = %d, Cross-Correlation = %3.2f' %(p, L, CC))
plt.yscale('log'); #plt.xscale('log')
#plt.xlim(1, 10**5)
plt.ylim(10**(-6.4), 10**(0.1))
#plt.xlim(-5, 5)
'''x1 = np.transpose(DP_freqs[:,0])
x2 = np.transpose(DP_freqs[:,1])
popt, pcov = curve_fit(trunc_pow_law, x1, x2, p0= np.asarray([1, -0.75, -0.0005]), maxfev=5000 )
perr = np.sqrt(np.diag(pcov))
print("SD of exponent:\t" +str(perr[1]) + " for p:\t" +str(p))
tukan= (popt[0], popt[1], perr[1], popt[2], perr[2])
plt.plot(x1, trunc_pow_law(x1, *popt), 'm--', label=r'Fit: $ P (S \geq \Delta s) = %3.2f \times \Delta s^{(%4.3f \mp %4.3f)}\times e^{(%4.3f \mp %4.3f)\times \Delta s}$ ' % tukan )
plt.legend()'''
plt.savefig("Symmetry PDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png" %(p,L,CC), dpi=400)
#plt.show()
plt.close()
os.chdir(r"..\..\..\..\..\..\analysis\Mass Action\DP")
#break;
#Plotting cumulative results.
os.chdir("../../../figures")
if(os.path.isdir("del_S")==False):
os.mkdir("del_S")
os.chdir("del_S")
if(os.path.isdir("DP")==False):
os.mkdir("DP")
os.chdir("DP")
if(os.path.isdir("Individual")==False):
os.mkdir("Individual")
os.chdir("Individual")
if(os.path.isdir("Symmetry")==False):
os.mkdir("Symmetry")
os.chdir("Symmetry")
if(os.path.isdir("Cum")==False):
os.mkdir("Cum")
os.chdir("Cum")
hurtlocker= pan.DataFrame(MastBind, columns= [r"$\Delta s$", r"$P (S = \Delta s)$", "Cross-Correlation", "p"])
fig = plt.figure(figsize=(6.4,4.8))
#Overlaying two seaborn plots.
#ax = fig.add_subplot(111)
f= sea.scatterplot(data=hurtlocker, x=r"$\Delta s$" , y=r"$P (S = \Delta s)$", hue="Cross-Correlation")#, alpha=0.5, s=2, ax= ax)
#sea.lineplot(data=hurtlocker, x=r"$\Delta s$" , y=r"$P (S = \Delta s)$", alpha=0.2, ax= ax) #, s=1)
f.set_title('p = %f, Grid Size (G) = %d' %(MastBind[0,3], L))
plt.yscale('log'); #plt.xscale('log')
#plt.xlim(1, 10**5)
plt.ylim(10**(-6.4), 10**(0.1))
plt.xlim(-5, 5)
plt.savefig("Alt Cum Symmetry PDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d.png" %(MastBind[0,3], L), dpi=400)
#plt.show()
plt.close()
os.chdir(r"..\..\..\..\..\..\analysis\Mass Action\DP")
def main_bifurcation():
p_c = 0.725194
crosc = float(input("Enter a Cross-Correlation Value To Be Analysed (Choose Between 0.95, 0.9, 0.8, 0.75, 0.7 & 0.6):\t"))
#crosc =0.8
fandango = np.genfromtxt("PissingAbout15+16.csv", delimiter=",", comments='#', skip_header=1)
#Stores decay data of cross-correlation between frames as a function of p.
binder=[]; L=0;
for i in range(0,10):
base_path = r"22Apret\Apres 256+512\256" + "\\" + str(i)
files = glob.glob(base_path + "**/**/*.csv", recursive=True)
for file in files:
if (file == base_path + r"\dump\15_16_KungF---U.csv"):
print('Gandu')
continue
if (os.path.getsize(file) > 4096):
#Keeping unwanted files out.
print(file)
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1, max_rows=3)
p= data_temp[0,1]; L= int(data_temp[0,0]); CC= cross_cor(fandango, data_temp[0,2], L, p)
if( CC <= crosc - 0.01 or CC >= crosc + 0.01):
print(str(CC) + " shall be skipped.")
continue
if( p == 0.678):
print("Fuck You")
continue
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1)
'''
data_temp resembles:
| L, p, lag, #, s, s + del(s) |
'''
data_temp[:,5] -= data_temp[:,4]
data_temp[:,5] = np.abs(data_temp[:,5])
temp_freqs = dict(collections.Counter(data_temp[:,5]))
a,b = data_temp.shape
DP_freqs = {k: v / a for k, v in temp_freqs.items()}
DP_freqs = np.array(list(DP_freqs.items())) #Converting dictionary to numpy array.
a,b =DP_freqs.shape
split_data = DP_freqs[:,1] < 10**(-5.6)
DP_freqs = DP_freqs[split_data]
print("Half Done:")
print(DP_freqs)
split_data = DP_freqs[:,1] > 10**(-6)
DP_freqs_band = DP_freqs[split_data] #Stores the band of del(s) values whose probability lie between 10^(-5.85) and 10^(-5.85)
#col_P= np.zeros((a,1)); col_P = p
DP_freqs_band = np.insert(DP_freqs_band, 0, p, axis=1)
DP_freqs_band = DP_freqs_band[DP_freqs_band[:,1].argsort()]
#Sorting in increasing values of del(s)
print("Total number of points in given gap for p:\t"+str(p) +" is: \t" +str(len(DP_freqs_band[:,2])) +"\n")
print(DP_freqs_band)
'''DP_freqs looks like:
| p, del(s), P(del(s))|
'''
flag=0
for j in range(1, len(DP_freqs_band[:,2])-1):
if(abs(DP_freqs_band[j,1] -DP_freqs_band[j-1,2]) > 411 or abs(DP_freqs_band[j,1] -DP_freqs_band[j+1,2]) > 411):
# 10^(3.3) - 10^(3.2) = 410.369
binder.append([p,DP_freqs_band[j,1]])
flag=1
if(flag==0):
#No del(s) value satisfied the bandwidth demand.
#if()
binder.append([p,DP_freqs_band[-1,1]])
#Append the very last value
os.chdir("../../../figures")
if(os.path.isdir("del_S")==False):
os.mkdir("del_S")
os.chdir("del_S")
if(os.path.isdir("DP")==False):
os.mkdir("DP")
os.chdir("DP")
if(os.path.isdir("Bifurcation")==False):
os.mkdir("Bifurcation")
os.chdir("Bifurcation")
if(os.path.isdir("%d" %(L))==False):
os.mkdir("%d" %(L))
os.chdir("%d" %(L))
binder= np.array(binder)
hurtlocker= pan.DataFrame(binder, columns= ["p", r"$|\Delta s|$ s.t. $P (\Delta s \geq 10^{-6})$"])
f = sea.scatterplot(data=hurtlocker, x="p" , y=r"$|\Delta s|$ s.t. $P (\Delta s \geq 10^{-6})$", marker="+")
#sea.lineplot(data=hurtlocker, x=r"$|\Delta s|$" , y=r"$P (S \geq \Delta s)$", alpha=0.2, ax= ax) #, s=1)
f.set_title('Bifurcation Map, Grid Size (G) = %d, Cross-Correlation = %3.2f' %( L, crosc))
plt.yscale('log'); #plt.xscale('log')
plt.ylim(1, 10**5)
plt.axvline(x= p_c, color='0.65')
plt.text(p_c+ 0.003,10**1,r'$p_{c}$',rotation=90, color ='0.65')
plt.savefig("Bifurcation Map, Grid Size (G) = %d, CC = %3.2f.png" %(L, crosc), dpi=400)
plt.show()
plt.close()
os.chdir(r"..\..\..\..\..\analysis\Mass Action\DP")
def plot_fit_pdf():
twist =(-1.2912647288993737, -(1/37.72480211483688))
fandango = np.genfromtxt("PissingAbout15+16.csv", delimiter=",", comments='#', skip_header=1)
#Stores decay data of cross-correlation between frames as a function of p.
gaol={} #Stores truncated power law fit data.
gaol[0.60] =[]; gaol[0.70] =[]; gaol[0.75] =[];
gaol[0.80] =[]; gaol[0.90] =[]; gaol[0.95] =[];
L=0; crosc= 0.7
for i in range(0,1):
base_path = r"22Apret\Apres 256+512\256" + "\\" + str(i)
files = glob.glob(base_path + "**/**/*.csv", recursive=True)
for file in files:
if (file == base_path + r"\dump\15_16_KungF---U.csv"):
continue
if (os.path.getsize(file) > 4096):
#Keeping unwanted files out.
print(file)
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1, max_rows=3)
p= data_temp[0,1]; L= int(data_temp[0,0]); CC= cross_cor(fandango, data_temp[0,2], L, p)
if( CC <= crosc - 0.01 or CC >= crosc + 0.01 or p != 0.66):
print(str(CC) + " " + str(p) + " shall be skipped.")
continue
data_temp= np.genfromtxt(file, delimiter=",", comments='#', skip_header=1)
'''
data_temp resembles:
| L, p, lag, #, s, s + del(s) |
'''
'''
p= data_temp[0,1]; L= int(data_temp[0,0]); CC= cross_cor(fandango, data_temp[0,2], L, p)
data_temp[:,5] -= data_temp[:,4]
data_temp[:,5] = np.abs(data_temp[:,5])
temp_freqs = dict(collections.Counter(data_temp[:,5]))
a,b = data_temp.shape
DP_freqs = {k: v / (a) for k, v in temp_freqs.items()}
DP_freqs = np.array(list(DP_freqs.items())) #Converting dictionary to numpy array.
#Sorting array in increasing order of del(s).
DP_freqs = DP_freqs[DP_freqs[:,0].argsort()]
print("Sorted del(s) PDF:")
print(DP_freqs)
os.chdir("../../../figures")
if(os.path.isdir("del_S")==False):
os.mkdir("del_S")
os.chdir("del_S")
if(os.path.isdir("DP")==False):
os.mkdir("DP")
os.chdir("DP")
if(os.path.isdir("Individual")==False):
os.mkdir("Individual")
os.chdir("Individual")
if(os.path.isdir("1-CDF")==False):
os.mkdir("1-CDF")
os.chdir("1-CDF")
if(os.path.isdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))==False):
os.mkdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))
os.chdir("L_%d_p_%4.3f" %(int(data_temp[0,0]), data_temp[0,1]))
print("p:\t" +str(p) + " L:\t"+ str(L) + " CC:\t" +str(CC))
hurtlocker= pan.DataFrame(DP_freqs, columns= [r"$|\Delta s|$", r"$P (S = \Delta s)$"])
fig = plt.figure(figsize=(6.4,4.8))
#Overlaying two seaborn plots.
ax = fig.add_subplot(111)
sea.scatterplot(data=hurtlocker, x=r"$|\Delta s|$" , y=r"$P (S = \Delta s)$", ax= ax)#, alpha=0.5, s=2, ax= ax)
#sea.lineplot(data=hurtlocker, x=r"$|\Delta s|$" , y=r"$P (S = \Delta s)$", alpha=0.2, ax= ax) #, s=1)
ax.set_title('p = %f, Grid Size (G) = %d, Cross-Correlation = %3.2f' %(p, L, CC))
plt.yscale('log'); plt.xscale('log')
plt.xlim(1, 10**5)
plt.ylim(10**(-6.3), 10**(0.1))
x1 = np.transpose(DP_freqs[:,0])
x2 = np.transpose(DP_freqs[:,1])
#popt, pcov = curve_fit(trunc_pow_law, x1, x2, p0= np.asarray([1, -0.75, -0.0005]), maxfev=5000 )
#perr = np.sqrt(np.diag(pcov))
#print("SD of exponent:\t" +str(perr[1]) + " for p:\t" +str(p))
#tukan= (popt[0], popt[1], perr[1], popt[2], perr[2])
plt.plot(x1, trunc_pow_law(x1, *twist), color='darkslateblue', linestyle='--', label=r'Fit: $ P (S = \Delta s) = %3.2f \times \Delta s^{(%4.3f)}\times e^{(%6.5f)\times \Delta s}$ ' % tukan )
plt.ylim(10**(-6.4), 10**(0.1)); plt.xlim(1, 10**5)
plt.legend()
plt.savefig("Fit 1- CDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png" %(p,L,CC), dpi=400)
#plt.show()
plt.close()
#Next, to convert PDF into 1 - CDF (P(S >= (DEL(S))))
DP_freqs[-2,1] += DP_freqs[-1,1]; #DP_freqs[-1,1] = 0
k= len(DP_freqs[:,1]) #Finding total number of del(s) elements
print("Total distinct del(s) samples:\t" +str(k))
for j in range(k-3, -1, -1):
#Iterate over the PDF function in reverse.
DP_freqs[j,1] += DP_freqs[j+1,1]
print("Sorted del(s) 1-CDF:")
print(DP_freqs)
plt.savefig("Even Better Fit 1- CDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png" %(p,L,CC), dpi=400)
#plt.show()
plt.close()
comparison_tpl_exp = fit.distribution_compare('truncated_power_law','exponential',normalized_ratio=True)
comparison_tpl_streched_exp = fit.distribution_compare('truncated_power_law','stretched_exponential',normalized_ratio=True)
comparison_tpl_log_normal = fit.distribution_compare('truncated_power_law','lognormal',normalized_ratio=True)
comparison_tpl_pl = fit.distribution_compare('truncated_power_law','power_law',normalized_ratio=True)
print("LR (Power Law): ",comparison_tpl_pl[0]," p-value: ",comparison_tpl_pl[1])
print("LR (Exponential): ",comparison_tpl_exp[0]," p-value: ",comparison_tpl_exp[1])
print("LR (Log-Normal): ",comparison_tpl_log_normal[0]," p-value: ",comparison_tpl_log_normal[1])
print("LR (Stretched-Exponential): ",comparison_tpl_streched_exp[0]," p-value: ",comparison_tpl_streched_exp[1])
gaol[float(round(CC,2))].append([L, p, fit.xmin, fit.truncated_power_law.parameter1, 1/fit.truncated_power_law.parameter2])
os.chdir(r"..\..\..\..\..\..\analysis\Mass Action\DP")
'''
def cross_cor(grim_fandango, lag, L, p):
CC=0; k= 128/L
for t in range(0, len(grim_fandango[:,0])):
if grim_fandango[t,0] == p:
CC = grim_fandango[t,1]+ grim_fandango[t,3]*(math.exp(lag*grim_fandango[t,5]*k*k)); break;
#Calculating cross-correlation b/w frames.
print("CC:\t"+ str(CC))
return CC;
main_ind() | [
"numpy.log10",
"powerlaw.Fit",
"matplotlib.pyplot.ylabel",
"numpy.array",
"seaborn.scatterplot",
"math.exp",
"numpy.genfromtxt",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.close",
"numpy.exp",
"numpy.linspace",
"os.path.isdir",
"os.mkdir",
"numpy.concatenate",
"pandas.DataFrame",
"... | [((627, 713), 'numpy.genfromtxt', 'np.genfromtxt', (['"""PissingAbout15+16.csv"""'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "('PissingAbout15+16.csv', delimiter=',', comments='#',\n skip_header=1)\n", (640, 713), True, 'import numpy as np\n'), ((7089, 7175), 'numpy.genfromtxt', 'np.genfromtxt', (['"""PissingAbout15+16.csv"""'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "('PissingAbout15+16.csv', delimiter=',', comments='#',\n skip_header=1)\n", (7102, 7175), True, 'import numpy as np\n'), ((14506, 14523), 'os.chdir', 'os.chdir', (['"""del_S"""'], {}), "('del_S')\n", (14514, 14523), False, 'import os\n'), ((14597, 14615), 'os.chdir', 'os.chdir', (["('%d' % L)"], {}), "('%d' % L)\n", (14605, 14615), False, 'import os\n'), ((14835, 14853), 'os.chdir', 'os.chdir', (['"""../../"""'], {}), "('../../')\n", (14843, 14853), False, 'import os\n'), ((15071, 15157), 'numpy.genfromtxt', 'np.genfromtxt', (['"""PissingAbout15+16.csv"""'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "('PissingAbout15+16.csv', delimiter=',', comments='#',\n skip_header=1)\n", (15084, 15157), True, 'import numpy as np\n'), ((17627, 17655), 'os.chdir', 'os.chdir', (['"""../../../figures"""'], {}), "('../../../figures')\n", (17635, 17655), False, 'import os\n'), ((17725, 17742), 'os.chdir', 'os.chdir', (['"""del_S"""'], {}), "('del_S')\n", (17733, 17742), False, 'import os\n'), ((17806, 17820), 'os.chdir', 'os.chdir', (['"""DP"""'], {}), "('DP')\n", (17814, 17820), False, 'import os\n'), ((17884, 17898), 'os.chdir', 'os.chdir', (['"""3D"""'], {}), "('3D')\n", (17892, 17898), False, 'import os\n'), ((17972, 17990), 'os.chdir', 'os.chdir', (["('%d' % L)"], {}), "('%d' % L)\n", (17980, 17990), False, 'import os\n'), ((18021, 18037), 'numpy.array', 'np.array', (['binder'], {}), '(binder)\n', (18029, 18037), True, 'import numpy as np\n'), ((18051, 18063), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (18061, 18063), True, 'import matplotlib.pyplot as plt\n'), ((18073, 18098), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'projection': '"""3d"""'}), "(projection='3d')\n", (18081, 18098), True, 'import matplotlib.pyplot as plt\n'), ((19094, 19216), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('Cumulative Scatter P(del(s)) vs del(s) --- Grid Size (G)_%d - CC_%3.2f.png'\n % (L, crosc))"], {'dpi': '(550)'}), "(\n 'Cumulative Scatter P(del(s)) vs del(s) --- Grid Size (G)_%d - CC_%3.2f.png'\n % (L, crosc), dpi=550)\n", (19105, 19216), True, 'import matplotlib.pyplot as plt\n'), ((19209, 19219), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (19217, 19219), True, 'import matplotlib.pyplot as plt\n'), ((19224, 19235), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (19233, 19235), True, 'import matplotlib.pyplot as plt\n'), ((19290, 19320), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6.4, 4.8)'}), '(figsize=(6.4, 4.8))\n', (19300, 19320), True, 'import matplotlib.pyplot as plt\n'), ((20201, 20225), 'numpy.linspace', 'np.linspace', (['(-1)', '(5.5)', '(10)'], {}), '(-1, 5.5, 10)\n', (20212, 20225), True, 'import numpy as np\n'), ((20232, 20254), 'numpy.linspace', 'np.linspace', (['(-7)', '(1)', '(10)'], {}), '(-7, 1, 10)\n', (20243, 20254), True, 'import numpy as np\n'), ((20263, 20280), 'numpy.meshgrid', 'np.meshgrid', (['x', 'z'], {}), '(x, z)\n', (20274, 20280), True, 'import numpy as np\n'), ((20801, 20929), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('Cumulative Scatter Plane P(del(s)) vs del(s) --- Grid Size (G)_%d - CC_%3.2f.png'\n % (L, crosc))"], {'dpi': '(550)'}), "(\n 'Cumulative Scatter Plane P(del(s)) vs del(s) --- Grid Size (G)_%d - CC_%3.2f.png'\n % (L, crosc), dpi=550)\n", (20812, 20929), True, 'import matplotlib.pyplot as plt\n'), ((20966, 21102), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('Cumulative Scatter Plane P(del(s)) vs del(s) Top Down --- Grid Size (G)_%d - CC_%3.2f.png'\n % (L, crosc))"], {'dpi': '(550)'}), "(\n 'Cumulative Scatter Plane P(del(s)) vs del(s) Top Down --- Grid Size (G)_%d - CC_%3.2f.png'\n % (L, crosc), dpi=550)\n", (20977, 21102), True, 'import matplotlib.pyplot as plt\n'), ((21095, 21105), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (21103, 21105), True, 'import matplotlib.pyplot as plt\n'), ((21110, 21121), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (21119, 21121), True, 'import matplotlib.pyplot as plt\n'), ((21131, 21188), 'os.chdir', 'os.chdir', (['"""..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP"""'], {}), "('..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP')\n", (21139, 21188), False, 'import os\n'), ((21393, 21479), 'numpy.genfromtxt', 'np.genfromtxt', (['"""PissingAbout15+16.csv"""'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "('PissingAbout15+16.csv', delimiter=',', comments='#',\n skip_header=1)\n", (21406, 21479), True, 'import numpy as np\n'), ((23828, 23856), 'os.chdir', 'os.chdir', (['"""../../../figures"""'], {}), "('../../../figures')\n", (23836, 23856), False, 'import os\n'), ((23926, 23943), 'os.chdir', 'os.chdir', (['"""del_S"""'], {}), "('del_S')\n", (23934, 23943), False, 'import os\n'), ((24007, 24021), 'os.chdir', 'os.chdir', (['"""DP"""'], {}), "('DP')\n", (24015, 24021), False, 'import os\n'), ((24103, 24126), 'os.chdir', 'os.chdir', (['"""Bifurcation"""'], {}), "('Bifurcation')\n", (24111, 24126), False, 'import os\n'), ((24200, 24219), 'os.chdir', 'os.chdir', (['"""S Count"""'], {}), "('S Count')\n", (24208, 24219), False, 'import os\n'), ((24249, 24265), 'numpy.array', 'np.array', (['binder'], {}), '(binder)\n', (24257, 24265), True, 'import numpy as np\n'), ((24287, 24374), 'pandas.DataFrame', 'pan.DataFrame', (['binder'], {'columns': "['p', 'Number of unique $|\\\\Delta s|$ observations']"}), "(binder, columns=['p',\n 'Number of unique $|\\\\Delta s|$ observations'])\n", (24300, 24374), True, 'import pandas as pan\n'), ((24380, 24473), 'seaborn.scatterplot', 'sea.scatterplot', ([], {'data': 'hurtlocker', 'x': '"""p"""', 'y': '"""Number of unique $|\\\\Delta s|$ observations"""'}), "(data=hurtlocker, x='p', y=\n 'Number of unique $|\\\\Delta s|$ observations')\n", (24395, 24473), True, 'import seaborn as sea\n'), ((24777, 24809), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': 'p_c', 'color': '"""0.65"""'}), "(x=p_c, color='0.65')\n", (24788, 24809), True, 'import matplotlib.pyplot as plt\n'), ((24815, 24883), 'matplotlib.pyplot.text', 'plt.text', (['(p_c + 0.003)', '(10 ** 2)', '"""$p_{c}$"""'], {'rotation': '(90)', 'color': '"""0.65"""'}), "(p_c + 0.003, 10 ** 2, '$p_{c}$', rotation=90, color='0.65')\n", (24823, 24883), True, 'import matplotlib.pyplot as plt\n'), ((24889, 24974), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('S Count, Grid Size (G) = %d, CC = %3.2f.png' % (L, crosc))"], {'dpi': '(400)'}), "('S Count, Grid Size (G) = %d, CC = %3.2f.png' % (L, crosc), dpi=400\n )\n", (24900, 24974), True, 'import matplotlib.pyplot as plt\n'), ((24973, 24983), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (24981, 24983), True, 'import matplotlib.pyplot as plt\n'), ((24988, 24999), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (24997, 24999), True, 'import matplotlib.pyplot as plt\n'), ((25009, 25066), 'os.chdir', 'os.chdir', (['"""..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP"""'], {}), "('..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP')\n", (25017, 25066), False, 'import os\n'), ((25206, 25292), 'numpy.genfromtxt', 'np.genfromtxt', (['"""PissingAbout15+16.csv"""'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "('PissingAbout15+16.csv', delimiter=',', comments='#',\n skip_header=1)\n", (25219, 25292), True, 'import numpy as np\n'), ((33182, 33268), 'numpy.genfromtxt', 'np.genfromtxt', (['"""PissingAbout15+16.csv"""'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "('PissingAbout15+16.csv', delimiter=',', comments='#',\n skip_header=1)\n", (33195, 33268), True, 'import numpy as np\n'), ((36629, 36657), 'os.chdir', 'os.chdir', (['"""../../../figures"""'], {}), "('../../../figures')\n", (36637, 36657), False, 'import os\n'), ((36727, 36744), 'os.chdir', 'os.chdir', (['"""del_S"""'], {}), "('del_S')\n", (36735, 36744), False, 'import os\n'), ((36808, 36822), 'os.chdir', 'os.chdir', (['"""DP"""'], {}), "('DP')\n", (36816, 36822), False, 'import os\n'), ((36904, 36927), 'os.chdir', 'os.chdir', (['"""Bifurcation"""'], {}), "('Bifurcation')\n", (36912, 36927), False, 'import os\n'), ((37001, 37019), 'os.chdir', 'os.chdir', (["('%d' % L)"], {}), "('%d' % L)\n", (37009, 37019), False, 'import os\n'), ((37050, 37066), 'numpy.array', 'np.array', (['binder'], {}), '(binder)\n', (37058, 37066), True, 'import numpy as np\n'), ((37088, 37180), 'pandas.DataFrame', 'pan.DataFrame', (['binder'], {'columns': "['p', '$|\\\\Delta s|$ s.t. $P (\\\\Delta s \\\\geq 10^{-6})$']"}), "(binder, columns=['p',\n '$|\\\\Delta s|$ s.t. $P (\\\\Delta s \\\\geq 10^{-6})$'])\n", (37101, 37180), True, 'import pandas as pan\n'), ((37184, 37294), 'seaborn.scatterplot', 'sea.scatterplot', ([], {'data': 'hurtlocker', 'x': '"""p"""', 'y': '"""$|\\\\Delta s|$ s.t. $P (\\\\Delta s \\\\geq 10^{-6})$"""', 'marker': '"""+"""'}), "(data=hurtlocker, x='p', y=\n '$|\\\\Delta s|$ s.t. $P (\\\\Delta s \\\\geq 10^{-6})$', marker='+')\n", (37199, 37294), True, 'import seaborn as sea\n'), ((37498, 37515), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (37508, 37515), True, 'import matplotlib.pyplot as plt\n'), ((37540, 37560), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(1)', '(10 ** 5)'], {}), '(1, 10 ** 5)\n', (37548, 37560), True, 'import matplotlib.pyplot as plt\n'), ((37563, 37595), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': 'p_c', 'color': '"""0.65"""'}), "(x=p_c, color='0.65')\n", (37574, 37595), True, 'import matplotlib.pyplot as plt\n'), ((37601, 37669), 'matplotlib.pyplot.text', 'plt.text', (['(p_c + 0.003)', '(10 ** 1)', '"""$p_{c}$"""'], {'rotation': '(90)', 'color': '"""0.65"""'}), "(p_c + 0.003, 10 ** 1, '$p_{c}$', rotation=90, color='0.65')\n", (37609, 37669), True, 'import matplotlib.pyplot as plt\n'), ((37675, 37767), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('Bifurcation Map, Grid Size (G) = %d, CC = %3.2f.png' % (L, crosc))"], {'dpi': '(400)'}), "('Bifurcation Map, Grid Size (G) = %d, CC = %3.2f.png' % (L,\n crosc), dpi=400)\n", (37686, 37767), True, 'import matplotlib.pyplot as plt\n'), ((37767, 37777), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (37775, 37777), True, 'import matplotlib.pyplot as plt\n'), ((37782, 37793), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (37791, 37793), True, 'import matplotlib.pyplot as plt\n'), ((37803, 37860), 'os.chdir', 'os.chdir', (['"""..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP"""'], {}), "('..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP')\n", (37811, 37860), False, 'import os\n'), ((37967, 38053), 'numpy.genfromtxt', 'np.genfromtxt', (['"""PissingAbout15+16.csv"""'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "('PissingAbout15+16.csv', delimiter=',', comments='#',\n skip_header=1)\n", (37980, 38053), True, 'import numpy as np\n'), ((445, 462), 'numpy.power', 'np.power', (['x', 'expo'], {}), '(x, expo)\n', (453, 462), True, 'import numpy as np\n'), ((568, 590), 'numpy.exp', 'np.exp', (['(trunc_expo * x)'], {}), '(trunc_expo * x)\n', (574, 590), True, 'import numpy as np\n'), ((1058, 1110), 'glob.glob', 'glob.glob', (["(base_path + '**/**/*.csv')"], {'recursive': '(True)'}), "(base_path + '**/**/*.csv', recursive=True)\n", (1067, 1110), False, 'import glob\n'), ((7533, 7585), 'glob.glob', 'glob.glob', (["(base_path + '**/**/*.csv')"], {'recursive': '(True)'}), "(base_path + '**/**/*.csv', recursive=True)\n", (7542, 7585), False, 'import glob\n'), ((14444, 14466), 'os.path.isdir', 'os.path.isdir', (['"""del_S"""'], {}), "('del_S')\n", (14457, 14466), False, 'import os\n'), ((14484, 14501), 'os.mkdir', 'os.mkdir', (['"""del_S"""'], {}), "('del_S')\n", (14492, 14501), False, 'import os\n'), ((14531, 14554), 'os.path.isdir', 'os.path.isdir', (["('%d' % L)"], {}), "('%d' % L)\n", (14544, 14554), False, 'import os\n'), ((14573, 14591), 'os.mkdir', 'os.mkdir', (["('%d' % L)"], {}), "('%d' % L)\n", (14581, 14591), False, 'import os\n'), ((14725, 14833), 'numpy.savetxt', 'np.savetxt', (["('Nu_Pow_0_6_BestFitCDF_CC_%3.2F.csv' % k)", 'gaol[k]'], {'delimiter': '""","""', 'header': 'heado', 'comments': '"""#"""'}), "('Nu_Pow_0_6_BestFitCDF_CC_%3.2F.csv' % k, gaol[k], delimiter=',',\n header=heado, comments='#')\n", (14735, 14833), True, 'import numpy as np\n'), ((15360, 15412), 'glob.glob', 'glob.glob', (["(base_path + '**/**/*.csv')"], {'recursive': '(True)'}), "(base_path + '**/**/*.csv', recursive=True)\n", (15369, 15412), False, 'import glob\n'), ((17663, 17685), 'os.path.isdir', 'os.path.isdir', (['"""del_S"""'], {}), "('del_S')\n", (17676, 17685), False, 'import os\n'), ((17703, 17720), 'os.mkdir', 'os.mkdir', (['"""del_S"""'], {}), "('del_S')\n", (17711, 17720), False, 'import os\n'), ((17750, 17769), 'os.path.isdir', 'os.path.isdir', (['"""DP"""'], {}), "('DP')\n", (17763, 17769), False, 'import os\n'), ((17787, 17801), 'os.mkdir', 'os.mkdir', (['"""DP"""'], {}), "('DP')\n", (17795, 17801), False, 'import os\n'), ((17828, 17847), 'os.path.isdir', 'os.path.isdir', (['"""3D"""'], {}), "('3D')\n", (17841, 17847), False, 'import os\n'), ((17865, 17879), 'os.mkdir', 'os.mkdir', (['"""3D"""'], {}), "('3D')\n", (17873, 17879), False, 'import os\n'), ((17906, 17929), 'os.path.isdir', 'os.path.isdir', (["('%d' % L)"], {}), "('%d' % L)\n", (17919, 17929), False, 'import os\n'), ((17948, 17966), 'os.mkdir', 'os.mkdir', (["('%d' % L)"], {}), "('%d' % L)\n", (17956, 17966), False, 'import os\n'), ((18485, 18507), 'numpy.log10', 'np.log10', (['binder[:, 1]'], {}), '(binder[:, 1])\n', (18493, 18507), True, 'import numpy as np\n'), ((18521, 18543), 'numpy.log10', 'np.log10', (['binder[:, 2]'], {}), '(binder[:, 2])\n', (18529, 18543), True, 'import numpy as np\n'), ((19424, 19446), 'numpy.log10', 'np.log10', (['binder[:, 1]'], {}), '(binder[:, 1])\n', (19432, 19446), True, 'import numpy as np\n'), ((19460, 19482), 'numpy.log10', 'np.log10', (['binder[:, 2]'], {}), '(binder[:, 2])\n', (19468, 19482), True, 'import numpy as np\n'), ((21682, 21734), 'glob.glob', 'glob.glob', (["(base_path + '**/**/*.csv')"], {'recursive': '(True)'}), "(base_path + '**/**/*.csv', recursive=True)\n", (21691, 21734), False, 'import glob\n'), ((23864, 23886), 'os.path.isdir', 'os.path.isdir', (['"""del_S"""'], {}), "('del_S')\n", (23877, 23886), False, 'import os\n'), ((23904, 23921), 'os.mkdir', 'os.mkdir', (['"""del_S"""'], {}), "('del_S')\n", (23912, 23921), False, 'import os\n'), ((23951, 23970), 'os.path.isdir', 'os.path.isdir', (['"""DP"""'], {}), "('DP')\n", (23964, 23970), False, 'import os\n'), ((23988, 24002), 'os.mkdir', 'os.mkdir', (['"""DP"""'], {}), "('DP')\n", (23996, 24002), False, 'import os\n'), ((24029, 24057), 'os.path.isdir', 'os.path.isdir', (['"""Bifurcation"""'], {}), "('Bifurcation')\n", (24042, 24057), False, 'import os\n'), ((24075, 24098), 'os.mkdir', 'os.mkdir', (['"""Bifurcation"""'], {}), "('Bifurcation')\n", (24083, 24098), False, 'import os\n'), ((24134, 24158), 'os.path.isdir', 'os.path.isdir', (['"""S Count"""'], {}), "('S Count')\n", (24147, 24158), False, 'import os\n'), ((24176, 24195), 'os.mkdir', 'os.mkdir', (['"""S Count"""'], {}), "('S Count')\n", (24184, 24195), False, 'import os\n'), ((25475, 25527), 'glob.glob', 'glob.glob', (["(base_path + '**/**/*.csv')"], {'recursive': '(True)'}), "(base_path + '**/**/*.csv', recursive=True)\n", (25484, 25527), False, 'import glob\n'), ((31456, 31484), 'os.chdir', 'os.chdir', (['"""../../../figures"""'], {}), "('../../../figures')\n", (31464, 31484), False, 'import os\n'), ((31575, 31592), 'os.chdir', 'os.chdir', (['"""del_S"""'], {}), "('del_S')\n", (31583, 31592), False, 'import os\n'), ((31668, 31682), 'os.chdir', 'os.chdir', (['"""DP"""'], {}), "('DP')\n", (31676, 31682), False, 'import os\n'), ((31774, 31796), 'os.chdir', 'os.chdir', (['"""Individual"""'], {}), "('Individual')\n", (31782, 31796), False, 'import os\n'), ((31884, 31904), 'os.chdir', 'os.chdir', (['"""Symmetry"""'], {}), "('Symmetry')\n", (31892, 31904), False, 'import os\n'), ((31982, 31997), 'os.chdir', 'os.chdir', (['"""Cum"""'], {}), "('Cum')\n", (31990, 31997), False, 'import os\n'), ((32027, 32128), 'pandas.DataFrame', 'pan.DataFrame', (['MastBind'], {'columns': "['$\\\\Delta s$', '$P (S = \\\\Delta s)$', 'Cross-Correlation', 'p']"}), "(MastBind, columns=['$\\\\Delta s$', '$P (S = \\\\Delta s)$',\n 'Cross-Correlation', 'p'])\n", (32040, 32128), True, 'import pandas as pan\n'), ((32140, 32170), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6.4, 4.8)'}), '(figsize=(6.4, 4.8))\n', (32150, 32170), True, 'import matplotlib.pyplot as plt\n'), ((32272, 32375), 'seaborn.scatterplot', 'sea.scatterplot', ([], {'data': 'hurtlocker', 'x': '"""$\\\\Delta s$"""', 'y': '"""$P (S = \\\\Delta s)$"""', 'hue': '"""Cross-Correlation"""'}), "(data=hurtlocker, x='$\\\\Delta s$', y='$P (S = \\\\Delta s)$',\n hue='Cross-Correlation')\n", (32287, 32375), True, 'import seaborn as sea\n'), ((32586, 32603), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (32596, 32603), True, 'import matplotlib.pyplot as plt\n'), ((32660, 32691), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(10 ** -6.4)', '(10 ** 0.1)'], {}), '(10 ** -6.4, 10 ** 0.1)\n', (32668, 32691), True, 'import matplotlib.pyplot as plt\n'), ((32700, 32715), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-5)', '(5)'], {}), '(-5, 5)\n', (32708, 32715), True, 'import matplotlib.pyplot as plt\n'), ((32733, 32859), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('Alt Cum Symmetry PDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d.png' %\n (MastBind[0, 3], L))"], {'dpi': '(400)'}), "(\n 'Alt Cum Symmetry PDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d.png' %\n (MastBind[0, 3], L), dpi=400)\n", (32744, 32859), True, 'import matplotlib.pyplot as plt\n'), ((32877, 32888), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (32886, 32888), True, 'import matplotlib.pyplot as plt\n'), ((32897, 32958), 'os.chdir', 'os.chdir', (['"""..\\\\..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP"""'], {}), "('..\\\\..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP')\n", (32905, 32958), False, 'import os\n'), ((33471, 33523), 'glob.glob', 'glob.glob', (["(base_path + '**/**/*.csv')"], {'recursive': '(True)'}), "(base_path + '**/**/*.csv', recursive=True)\n", (33480, 33523), False, 'import glob\n'), ((36665, 36687), 'os.path.isdir', 'os.path.isdir', (['"""del_S"""'], {}), "('del_S')\n", (36678, 36687), False, 'import os\n'), ((36705, 36722), 'os.mkdir', 'os.mkdir', (['"""del_S"""'], {}), "('del_S')\n", (36713, 36722), False, 'import os\n'), ((36752, 36771), 'os.path.isdir', 'os.path.isdir', (['"""DP"""'], {}), "('DP')\n", (36765, 36771), False, 'import os\n'), ((36789, 36803), 'os.mkdir', 'os.mkdir', (['"""DP"""'], {}), "('DP')\n", (36797, 36803), False, 'import os\n'), ((36830, 36858), 'os.path.isdir', 'os.path.isdir', (['"""Bifurcation"""'], {}), "('Bifurcation')\n", (36843, 36858), False, 'import os\n'), ((36876, 36899), 'os.mkdir', 'os.mkdir', (['"""Bifurcation"""'], {}), "('Bifurcation')\n", (36884, 36899), False, 'import os\n'), ((36935, 36958), 'os.path.isdir', 'os.path.isdir', (["('%d' % L)"], {}), "('%d' % L)\n", (36948, 36958), False, 'import os\n'), ((36977, 36995), 'os.mkdir', 'os.mkdir', (["('%d' % L)"], {}), "('%d' % L)\n", (36985, 36995), False, 'import os\n'), ((38410, 38462), 'glob.glob', 'glob.glob', (["(base_path + '**/**/*.csv')"], {'recursive': '(True)'}), "(base_path + '**/**/*.csv', recursive=True)\n", (38419, 38462), False, 'import glob\n'), ((549, 566), 'numpy.power', 'np.power', (['x', 'expo'], {}), '(x, expo)\n', (557, 566), True, 'import numpy as np\n'), ((18547, 18569), 'numpy.log10', 'np.log10', (['binder[:, 2]'], {}), '(binder[:, 2])\n', (18555, 18569), True, 'import numpy as np\n'), ((19486, 19508), 'numpy.log10', 'np.log10', (['binder[:, 2]'], {}), '(binder[:, 2])\n', (19494, 19508), True, 'import numpy as np\n'), ((31505, 31527), 'os.path.isdir', 'os.path.isdir', (['"""del_S"""'], {}), "('del_S')\n", (31518, 31527), False, 'import os\n'), ((31549, 31566), 'os.mkdir', 'os.mkdir', (['"""del_S"""'], {}), "('del_S')\n", (31557, 31566), False, 'import os\n'), ((31604, 31623), 'os.path.isdir', 'os.path.isdir', (['"""DP"""'], {}), "('DP')\n", (31617, 31623), False, 'import os\n'), ((31645, 31659), 'os.mkdir', 'os.mkdir', (['"""DP"""'], {}), "('DP')\n", (31653, 31659), False, 'import os\n'), ((31694, 31721), 'os.path.isdir', 'os.path.isdir', (['"""Individual"""'], {}), "('Individual')\n", (31707, 31721), False, 'import os\n'), ((31743, 31765), 'os.mkdir', 'os.mkdir', (['"""Individual"""'], {}), "('Individual')\n", (31751, 31765), False, 'import os\n'), ((31808, 31833), 'os.path.isdir', 'os.path.isdir', (['"""Symmetry"""'], {}), "('Symmetry')\n", (31821, 31833), False, 'import os\n'), ((31855, 31875), 'os.mkdir', 'os.mkdir', (['"""Symmetry"""'], {}), "('Symmetry')\n", (31863, 31875), False, 'import os\n'), ((31916, 31936), 'os.path.isdir', 'os.path.isdir', (['"""Cum"""'], {}), "('Cum')\n", (31929, 31936), False, 'import os\n'), ((31958, 31973), 'os.mkdir', 'os.mkdir', (['"""Cum"""'], {}), "('Cum')\n", (31966, 31973), False, 'import os\n'), ((1246, 1267), 'os.path.getsize', 'os.path.getsize', (['file'], {}), '(file)\n', (1261, 1267), False, 'import os\n'), ((1394, 1457), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "(file, delimiter=',', comments='#', skip_header=1)\n", (1407, 1457), True, 'import numpy as np\n'), ((1953, 1976), 'numpy.abs', 'np.abs', (['data_temp[:, 5]'], {}), '(data_temp[:, 5])\n', (1959, 1976), True, 'import numpy as np\n'), ((3173, 3201), 'os.chdir', 'os.chdir', (['"""../../../figures"""'], {}), "('../../../figures')\n", (3181, 3201), False, 'import os\n'), ((3320, 3337), 'os.chdir', 'os.chdir', (['"""del_S"""'], {}), "('del_S')\n", (3328, 3337), False, 'import os\n'), ((3437, 3451), 'os.chdir', 'os.chdir', (['"""DP"""'], {}), "('DP')\n", (3445, 3451), False, 'import os\n'), ((3567, 3589), 'os.chdir', 'os.chdir', (['"""Individual"""'], {}), "('Individual')\n", (3575, 3589), False, 'import os\n'), ((4225, 4298), 'pandas.DataFrame', 'pan.DataFrame', (['DP_freqs'], {'columns': "['$|\\\\Delta s|$', '$P (S = \\\\Delta s)$']"}), "(DP_freqs, columns=['$|\\\\Delta s|$', '$P (S = \\\\Delta s)$'])\n", (4238, 4298), True, 'import pandas as pan\n'), ((4322, 4352), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6.4, 4.8)'}), '(figsize=(6.4, 4.8))\n', (4332, 4352), True, 'import matplotlib.pyplot as plt\n'), ((4372, 4448), 'seaborn.scatterplot', 'sea.scatterplot', ([], {'data': 'hurtlocker', 'x': '"""$|\\\\Delta s|$"""', 'y': '"""$P (S = \\\\Delta s)$"""'}), "(data=hurtlocker, x='$|\\\\Delta s|$', y='$P (S = \\\\Delta s)$')\n", (4387, 4448), True, 'import seaborn as sea\n'), ((5030, 5047), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (5040, 5047), True, 'import matplotlib.pyplot as plt\n'), ((5049, 5066), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (5059, 5066), True, 'import matplotlib.pyplot as plt\n'), ((5083, 5103), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(1)', '(10 ** 5)'], {}), '(1, 10 ** 5)\n', (5091, 5103), True, 'import matplotlib.pyplot as plt\n'), ((5118, 5149), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(10 ** -6.4)', '(10 ** 0.1)'], {}), '(10 ** -6.4, 10 ** 0.1)\n', (5126, 5149), True, 'import matplotlib.pyplot as plt\n'), ((5183, 5293), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('0P(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png' % (p, L,\n CC))"], {'dpi': '(400)'}), "(\n '0P(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png' % (p,\n L, CC), dpi=400)\n", (5194, 5293), True, 'import matplotlib.pyplot as plt\n'), ((5326, 5337), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5335, 5337), True, 'import matplotlib.pyplot as plt\n'), ((6510, 6567), 'os.chdir', 'os.chdir', (['"""..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP"""'], {}), "('..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP')\n", (6518, 6567), False, 'import os\n'), ((7721, 7742), 'os.path.getsize', 'os.path.getsize', (['file'], {}), '(file)\n', (7736, 7742), False, 'import os\n'), ((7869, 7944), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)', 'max_rows': '(3)'}), "(file, delimiter=',', comments='#', skip_header=1, max_rows=3)\n", (7882, 7944), True, 'import numpy as np\n'), ((8264, 8327), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "(file, delimiter=',', comments='#', skip_header=1)\n", (8277, 8327), True, 'import numpy as np\n'), ((8695, 8718), 'numpy.abs', 'np.abs', (['data_temp[:, 5]'], {}), '(data_temp[:, 5])\n', (8701, 8718), True, 'import numpy as np\n'), ((8757, 8826), 'powerlaw.Fit', 'powerlaw.Fit', (['data_temp[:, 5]'], {'discrete': '(True)', 'estimate_discrete': '(False)'}), '(data_temp[:, 5], discrete=True, estimate_discrete=False)\n', (8769, 8826), False, 'import powerlaw\n'), ((9941, 9963), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(1)', '(10 ** 5.3)'], {}), '(1, 10 ** 5.3)\n', (9949, 9963), True, 'import matplotlib.pyplot as plt\n'), ((9978, 10005), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$|\\\\Delta s|$"""'], {}), "('$|\\\\Delta s|$')\n", (9988, 10005), True, 'import matplotlib.pyplot as plt\n'), ((10022, 10059), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$P (S \\\\geq \\\\Delta s)$"""'], {}), "('$P (S \\\\geq \\\\Delta s)$')\n", (10032, 10059), True, 'import matplotlib.pyplot as plt\n'), ((10075, 10087), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (10085, 10087), True, 'import matplotlib.pyplot as plt\n'), ((10121, 10149), 'os.chdir', 'os.chdir', (['"""../../../figures"""'], {}), "('../../../figures')\n", (10129, 10149), False, 'import os\n'), ((10268, 10285), 'os.chdir', 'os.chdir', (['"""del_S"""'], {}), "('del_S')\n", (10276, 10285), False, 'import os\n'), ((10385, 10399), 'os.chdir', 'os.chdir', (['"""DP"""'], {}), "('DP')\n", (10393, 10399), False, 'import os\n'), ((10515, 10537), 'os.chdir', 'os.chdir', (['"""Individual"""'], {}), "('Individual')\n", (10523, 10537), False, 'import os\n'), ((10643, 10660), 'os.chdir', 'os.chdir', (['"""1-CDF"""'], {}), "('1-CDF')\n", (10651, 10660), False, 'import os\n'), ((10955, 11081), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('Better Fit 1- CDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png'\n % (p, L, CC))"], {'dpi': '(400)'}), "(\n 'Better Fit 1- CDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png'\n % (p, L, CC), dpi=400)\n", (10966, 11081), True, 'import matplotlib.pyplot as plt\n'), ((11113, 11124), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (11122, 11124), True, 'import matplotlib.pyplot as plt\n'), ((11158, 11176), 'os.chdir', 'os.chdir', (['"""../../"""'], {}), "('../../')\n", (11166, 11176), False, 'import os\n'), ((12219, 12241), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(1)', '(10 ** 5.3)'], {}), '(1, 10 ** 5.3)\n', (12227, 12241), True, 'import matplotlib.pyplot as plt\n'), ((12256, 12283), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$|\\\\Delta s|$"""'], {}), "('$|\\\\Delta s|$')\n", (12266, 12283), True, 'import matplotlib.pyplot as plt\n'), ((12300, 12333), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$P (S = \\\\Delta s)$"""'], {}), "('$P (S = \\\\Delta s)$')\n", (12310, 12333), True, 'import matplotlib.pyplot as plt\n'), ((12350, 12362), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (12360, 12362), True, 'import matplotlib.pyplot as plt\n'), ((12380, 12503), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('Better Fit PDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png'\n % (p, L, CC))"], {'dpi': '(400)'}), "(\n 'Better Fit PDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png'\n % (p, L, CC), dpi=400)\n", (12391, 12503), True, 'import matplotlib.pyplot as plt\n'), ((12535, 12546), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (12544, 12546), True, 'import matplotlib.pyplot as plt\n'), ((14368, 14425), 'os.chdir', 'os.chdir', (['"""..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP"""'], {}), "('..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP')\n", (14376, 14425), False, 'import os\n'), ((15579, 15600), 'os.path.getsize', 'os.path.getsize', (['file'], {}), '(file)\n', (15594, 15600), False, 'import os\n'), ((15727, 15802), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)', 'max_rows': '(3)'}), "(file, delimiter=',', comments='#', skip_header=1, max_rows=3)\n", (15740, 15802), True, 'import numpy as np\n'), ((16237, 16300), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "(file, delimiter=',', comments='#', skip_header=1)\n", (16250, 16300), True, 'import numpy as np\n'), ((16546, 16569), 'numpy.abs', 'np.abs', (['data_temp[:, 5]'], {}), '(data_temp[:, 5])\n', (16552, 16569), True, 'import numpy as np\n'), ((16979, 17012), 'numpy.insert', 'np.insert', (['DP_freqs', '(0)', 'p'], {'axis': '(1)'}), '(DP_freqs, 0, p, axis=1)\n', (16988, 17012), True, 'import numpy as np\n'), ((21901, 21922), 'os.path.getsize', 'os.path.getsize', (['file'], {}), '(file)\n', (21916, 21922), False, 'import os\n'), ((22049, 22124), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)', 'max_rows': '(3)'}), "(file, delimiter=',', comments='#', skip_header=1, max_rows=3)\n", (22062, 22124), True, 'import numpy as np\n'), ((22559, 22622), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "(file, delimiter=',', comments='#', skip_header=1)\n", (22572, 22622), True, 'import numpy as np\n'), ((22868, 22891), 'numpy.abs', 'np.abs', (['data_temp[:, 5]'], {}), '(data_temp[:, 5])\n', (22874, 22891), True, 'import numpy as np\n'), ((23301, 23334), 'numpy.insert', 'np.insert', (['DP_freqs', '(0)', 'p'], {'axis': '(1)'}), '(DP_freqs, 0, p, axis=1)\n', (23310, 23334), True, 'import numpy as np\n'), ((25688, 25709), 'os.path.getsize', 'os.path.getsize', (['file'], {}), '(file)\n', (25703, 25709), False, 'import os\n'), ((25836, 25911), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)', 'max_rows': '(3)'}), "(file, delimiter=',', comments='#', skip_header=1, max_rows=3)\n", (25849, 25911), True, 'import numpy as np\n'), ((26179, 26242), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "(file, delimiter=',', comments='#', skip_header=1)\n", (26192, 26242), True, 'import numpy as np\n'), ((27904, 27937), 'numpy.insert', 'np.insert', (['DP_freqs', '(3)', 'p'], {'axis': '(1)'}), '(DP_freqs, 3, p, axis=1)\n', (27913, 27937), True, 'import numpy as np\n'), ((28705, 28733), 'os.chdir', 'os.chdir', (['"""../../../figures"""'], {}), "('../../../figures')\n", (28713, 28733), False, 'import os\n'), ((28852, 28869), 'os.chdir', 'os.chdir', (['"""del_S"""'], {}), "('del_S')\n", (28860, 28869), False, 'import os\n'), ((28969, 28983), 'os.chdir', 'os.chdir', (['"""DP"""'], {}), "('DP')\n", (28977, 28983), False, 'import os\n'), ((29099, 29121), 'os.chdir', 'os.chdir', (['"""Individual"""'], {}), "('Individual')\n", (29107, 29121), False, 'import os\n'), ((29233, 29253), 'os.chdir', 'os.chdir', (['"""Symmetry"""'], {}), "('Symmetry')\n", (29241, 29253), False, 'import os\n'), ((29653, 29754), 'pandas.DataFrame', 'pan.DataFrame', (['DP_freqs'], {'columns': "['$\\\\Delta s$', '$P (S = \\\\Delta s)$', 'Cross-Correlation', 'p']"}), "(DP_freqs, columns=['$\\\\Delta s$', '$P (S = \\\\Delta s)$',\n 'Cross-Correlation', 'p'])\n", (29666, 29754), True, 'import pandas as pan\n'), ((29774, 29804), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6.4, 4.8)'}), '(figsize=(6.4, 4.8))\n', (29784, 29804), True, 'import matplotlib.pyplot as plt\n'), ((29930, 30004), 'seaborn.scatterplot', 'sea.scatterplot', ([], {'data': 'hurtlocker', 'x': '"""$\\\\Delta s$"""', 'y': '"""$P (S = \\\\Delta s)$"""'}), "(data=hurtlocker, x='$\\\\Delta s$', y='$P (S = \\\\Delta s)$')\n", (29945, 30004), True, 'import seaborn as sea\n'), ((30262, 30279), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (30272, 30279), True, 'import matplotlib.pyplot as plt\n'), ((30352, 30383), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(10 ** -6.4)', '(10 ** 0.1)'], {}), '(10 ** -6.4, 10 ** 0.1)\n', (30360, 30383), True, 'import matplotlib.pyplot as plt\n'), ((31141, 31262), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('Symmetry PDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png' %\n (p, L, CC))"], {'dpi': '(400)'}), "(\n 'Symmetry PDF(del(s)) vs del(s) --- p_%f - Grid Size (G)_%d - CC_%3.2f.png'\n % (p, L, CC), dpi=400)\n", (31152, 31262), True, 'import matplotlib.pyplot as plt\n'), ((31294, 31305), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (31303, 31305), True, 'import matplotlib.pyplot as plt\n'), ((31322, 31383), 'os.chdir', 'os.chdir', (['"""..\\\\..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP"""'], {}), "('..\\\\..\\\\..\\\\..\\\\..\\\\..\\\\analysis\\\\Mass Action\\\\DP')\n", (31330, 31383), False, 'import os\n'), ((33690, 33711), 'os.path.getsize', 'os.path.getsize', (['file'], {}), '(file)\n', (33705, 33711), False, 'import os\n'), ((33838, 33913), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)', 'max_rows': '(3)'}), "(file, delimiter=',', comments='#', skip_header=1, max_rows=3)\n", (33851, 33913), True, 'import numpy as np\n'), ((34348, 34411), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "(file, delimiter=',', comments='#', skip_header=1)\n", (34361, 34411), True, 'import numpy as np\n'), ((34657, 34680), 'numpy.abs', 'np.abs', (['data_temp[:, 5]'], {}), '(data_temp[:, 5])\n', (34663, 34680), True, 'import numpy as np\n'), ((35500, 35538), 'numpy.insert', 'np.insert', (['DP_freqs_band', '(0)', 'p'], {'axis': '(1)'}), '(DP_freqs_band, 0, p, axis=1)\n', (35509, 35538), True, 'import numpy as np\n'), ((38598, 38619), 'os.path.getsize', 'os.path.getsize', (['file'], {}), '(file)\n', (38613, 38619), False, 'import os\n'), ((38746, 38821), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)', 'max_rows': '(3)'}), "(file, delimiter=',', comments='#', skip_header=1, max_rows=3)\n", (38759, 38821), True, 'import numpy as np\n'), ((39185, 39248), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'comments': '"""#"""', 'skip_header': '(1)'}), "(file, delimiter=',', comments='#', skip_header=1)\n", (39198, 39248), True, 'import numpy as np\n'), ((2010, 2046), 'collections.Counter', 'collections.Counter', (['data_temp[:, 5]'], {}), '(data_temp[:, 5])\n', (2029, 2046), False, 'import collections\n'), ((3234, 3256), 'os.path.isdir', 'os.path.isdir', (['"""del_S"""'], {}), "('del_S')\n", (3247, 3256), False, 'import os\n'), ((3286, 3303), 'os.mkdir', 'os.mkdir', (['"""del_S"""'], {}), "('del_S')\n", (3294, 3303), False, 'import os\n'), ((3357, 3376), 'os.path.isdir', 'os.path.isdir', (['"""DP"""'], {}), "('DP')\n", (3370, 3376), False, 'import os\n'), ((3406, 3420), 'os.mkdir', 'os.mkdir', (['"""DP"""'], {}), "('DP')\n", (3414, 3420), False, 'import os\n'), ((3471, 3498), 'os.path.isdir', 'os.path.isdir', (['"""Individual"""'], {}), "('Individual')\n", (3484, 3498), False, 'import os\n'), ((3528, 3550), 'os.mkdir', 'os.mkdir', (['"""Individual"""'], {}), "('Individual')\n", (3536, 3550), False, 'import os\n'), ((10182, 10204), 'os.path.isdir', 'os.path.isdir', (['"""del_S"""'], {}), "('del_S')\n", (10195, 10204), False, 'import os\n'), ((10234, 10251), 'os.mkdir', 'os.mkdir', (['"""del_S"""'], {}), "('del_S')\n", (10242, 10251), False, 'import os\n'), ((10305, 10324), 'os.path.isdir', 'os.path.isdir', (['"""DP"""'], {}), "('DP')\n", (10318, 10324), False, 'import os\n'), ((10354, 10368), 'os.mkdir', 'os.mkdir', (['"""DP"""'], {}), "('DP')\n", (10362, 10368), False, 'import os\n'), ((10419, 10446), 'os.path.isdir', 'os.path.isdir', (['"""Individual"""'], {}), "('Individual')\n", (10432, 10446), False, 'import os\n'), ((10476, 10498), 'os.mkdir', 'os.mkdir', (['"""Individual"""'], {}), "('Individual')\n", (10484, 10498), False, 'import os\n'), ((10557, 10579), 'os.path.isdir', 'os.path.isdir', (['"""1-CDF"""'], {}), "('1-CDF')\n", (10570, 10579), False, 'import os\n'), ((10609, 10626), 'os.mkdir', 'os.mkdir', (['"""1-CDF"""'], {}), "('1-CDF')\n", (10617, 10626), False, 'import os\n'), ((16603, 16639), 'collections.Counter', 'collections.Counter', (['data_temp[:, 5]'], {}), '(data_temp[:, 5])\n', (16622, 16639), False, 'import collections\n'), ((22925, 22961), 'collections.Counter', 'collections.Counter', (['data_temp[:, 5]'], {}), '(data_temp[:, 5])\n', (22944, 22961), False, 'import collections\n'), ((26546, 26582), 'collections.Counter', 'collections.Counter', (['data_temp[:, 5]'], {}), '(data_temp[:, 5])\n', (26565, 26582), False, 'import collections\n'), ((27740, 27763), 'numpy.sign', 'np.sign', (['DP_freqs[:, 0]'], {}), '(DP_freqs[:, 0])\n', (27747, 27763), True, 'import numpy as np\n'), ((28331, 28375), 'numpy.concatenate', 'np.concatenate', (['(MastBind, DP_freqs)'], {'axis': '(0)'}), '((MastBind, DP_freqs), axis=0)\n', (28345, 28375), True, 'import numpy as np\n'), ((28766, 28788), 'os.path.isdir', 'os.path.isdir', (['"""del_S"""'], {}), "('del_S')\n", (28779, 28788), False, 'import os\n'), ((28818, 28835), 'os.mkdir', 'os.mkdir', (['"""del_S"""'], {}), "('del_S')\n", (28826, 28835), False, 'import os\n'), ((28889, 28908), 'os.path.isdir', 'os.path.isdir', (['"""DP"""'], {}), "('DP')\n", (28902, 28908), False, 'import os\n'), ((28938, 28952), 'os.mkdir', 'os.mkdir', (['"""DP"""'], {}), "('DP')\n", (28946, 28952), False, 'import os\n'), ((29003, 29030), 'os.path.isdir', 'os.path.isdir', (['"""Individual"""'], {}), "('Individual')\n", (29016, 29030), False, 'import os\n'), ((29060, 29082), 'os.mkdir', 'os.mkdir', (['"""Individual"""'], {}), "('Individual')\n", (29068, 29082), False, 'import os\n'), ((29141, 29166), 'os.path.isdir', 'os.path.isdir', (['"""Symmetry"""'], {}), "('Symmetry')\n", (29154, 29166), False, 'import os\n'), ((29196, 29216), 'os.mkdir', 'os.mkdir', (['"""Symmetry"""'], {}), "('Symmetry')\n", (29204, 29216), False, 'import os\n'), ((34714, 34750), 'collections.Counter', 'collections.Counter', (['data_temp[:, 5]'], {}), '(data_temp[:, 5])\n', (34733, 34750), False, 'import collections\n'), ((45291, 45334), 'math.exp', 'math.exp', (['(lag * grim_fandango[t, 5] * k * k)'], {}), '(lag * grim_fandango[t, 5] * k * k)\n', (45299, 45334), False, 'import math\n'), ((27773, 27795), 'numpy.abs', 'np.abs', (['DP_freqs[:, 0]'], {}), '(DP_freqs[:, 0])\n', (27779, 27795), True, 'import numpy as np\n')] |
import streamlit as st
import numpy as np
import pandas as pd
import requests
import re
import altair as alt
# Find all available data
def find_all_spreadsheets():
available_data = {}
r = requests.get('https://www.football-data.co.uk/downloadm.php')
if r.status_code != 200:
print('Oh dear. Error {}'.format(r.status_code))
return -1
matches = re.findall('(mmz(.*?)[0-9]+-[0-9]+(.*?).[xls]+")',r.text)
for match in matches:
tmp = match[0].replace('"','')
season = re.search('[0-9]+-[0-9]+',tmp).group()
available_data[season] = tmp
return available_data
def load_data(data_url):
data = pd.read_csv(data_url)
lowercase = lambda x: str(x).lower()
data.rename(lowercase, axis='columns', inplace=True)
data['datetime'] = pd.to_datetime(data['date'] + ' ' + data['time'])
data = data.drop(['date','time'],axis=1)
# Rearrange columns
cols = data.columns.tolist()
cols.remove('datetime')
cols.insert(0,'datetime')
data = data[cols]
return data
def season_spreadsheet(data_url):
url = 'https://www.football-data.co.uk/'+data_url
data = pd.read_excel(url,sheet_name=None)
return data
@st.cache
def load_all_data(spreadsheets):
# Silly. But it works..
base_url = 'https://www.football-data.co.uk/'
big_df = pd.DataFrame()
all_keys = list(spreadsheets.keys())
stop_season = '2014-2015'
# stop_season = '2018-2019'
pos = all_keys.index(stop_season)
for c,key in enumerate(all_keys):
print(key)
if key == stop_season:
break
data_state.text('Loading season {} ... only {} left to go'.format(key,pos-c))
url = base_url + spreadsheets[key]
og_spreadsheet = pd.read_excel(url,None)
big_spreadsheet = pd.concat(og_spreadsheet, ignore_index=True)
# Convert date to datetime object
#big_spreadsheet['Date'] = pd.to_datetime(big_spreadsheet['Date'])
big_spreadsheet.loc[big_spreadsheet.index,'Date'] = pd.to_datetime(big_spreadsheet['Date'])
#big_spreadsheet['season'] = key
big_spreadsheet.loc[big_spreadsheet.index,'season'] = key
#big_spreadsheet['s-year'] = key[5:]
big_spreadsheet.loc[big_spreadsheet.index,'s-year'] = key[5:]
#big_spreadsheet['s-year'] = big_spreadsheet['s-year'].astype(int)
big_spreadsheet.loc[big_spreadsheet.index,'s-year'] = big_spreadsheet['s-year'].astype(int)
if 'AG' in big_df.columns:
#big_spreadsheet['total-goals'] = big_spreadsheet['HG'] + big_spreadsheet['AG']
big_spreadsheet.loc[big_spreadsheet.index,'total-goals'] = big_spreadsheet['HG'] + big_spreadsheet['AG']
else:
#big_spreadsheet['total-goals'] = big_spreadsheet['FTHG'] + big_spreadsheet['FTAG']
big_spreadsheet.loc[big_spreadsheet.index,'total-goals'] = big_spreadsheet['FTHG'] + big_spreadsheet['FTAG']
big_df = big_df.append(big_spreadsheet, sort=False,ignore_index=True)
big_df = big_df[big_df['total-goals'].isna()==False]
return big_df.sort_values('Date',ascending=False)#.dropna(axis=0,how='any')
def prev_match(df,order_specific=False):
small = df[['Date','HomeTeam','AwayTeam','total-goals']]
small = small.dropna(how='all')
if order_specific:
small.loc[small.index,'hash'] = (small['HomeTeam'] + small['AwayTeam']).apply(hash)
else:
small.loc[small.index,'hash'] = small['HomeTeam'].apply(hash) + small['AwayTeam'].apply(hash)
return small.drop_duplicates(subset='hash', keep="first")
def prev_match_selection(df,order_specific=True,sel_type=None,total_goals=2.5):
# Return list of pairs where certain condition was satisfied
small = df[['Date','HomeTeam','AwayTeam','total-goals']]
small = small.dropna(how='all')
if order_specific:
small.loc[small.index,'hash'] = (small['HomeTeam'] + small['AwayTeam']).apply(hash)
else:
small.loc[small.index,'hash'] = small['HomeTeam'].apply(hash) + small['AwayTeam'].apply(hash)
tmp = sel_type.split('/')
games_played = int(tmp[1])
min_goals = int(tmp[0])
# Find the total matches played criteria
grouped_matches = small.groupby('hash').head(games_played)
# Only select matches where total-goals was satisfied
filtered_matches = grouped_matches[grouped_matches['total-goals'].gt(total_goals)]
# Count how many matches satisfied the total-goals criterion
hash_sizes = filtered_matches.groupby('hash').size().reset_index(name='counts')
# Only keep matches that satisfy the criterion
good_hashes = hash_sizes[hash_sizes['counts'].ge(min_goals)]
# Merge back to find Home and Away team names
merged = pd.merge(small,good_hashes,left_on='hash',right_on='hash',copy=False)
merged.loc[merged.index,'total-goals'] = np.ceil(total_goals)
return merged[['HomeTeam','AwayTeam','total-goals','hash']].drop_duplicates()
def find_stats(test_df,decision_df,order_specific=True,stats_type='last-match',misc=None):
# Add hashes appropriately
if order_specific:
test_df.loc[test_df.index,'hash'] = (test_df['HomeTeam']+test_df['AwayTeam']).apply(hash)
else:
test_df.loc[test_df.index,'hash'] = test_df['HomeTeam'].apply(hash)+test_df['AwayTeam'].apply(hash)
o = {'accuracy':0,'data':None}
if order_specific:
# Match test_df with decision_df on hashes
merged = pd.merge(test_df,decision_df,left_on='hash',right_on='hash',copy=False,suffixes=['_t','_d'])
merged_full = merged
merged = merged_full[['hash','total-goals_t','total-goals_d',#'HomeTeam_t','AwayTeam_t','HomeTeam_d','AwayTeam_d'
]]
merged.loc[merged.index,'correct'] = 0
merged.loc[(
((merged['total-goals_t']>2.5) & (merged['total-goals_d']>2.5))
|
((merged['total-goals_t']<2.5) & (merged['total-goals_d']<2.5))
)
,'correct'
] = 1
o['accuracy'] = merged['correct'].mean()
if 'Date_t' in merged_full.keys():
date_var = 'Date_t'
else:
date_var = 'Date'
o['data'] = [merged_full[[date_var,'HomeTeam_t','AwayTeam_t','total-goals_t','total-goals_d']]]
else:
# This makes it harder, if more than one game, will have to update stats in between
# Usually each season has two rounds for each team ??
first_round = test_df.drop_duplicates(subset='hash', keep="last")
second_round = test_df.drop(first_round.index)
# st.write('first round',first_round)
# st.write(first_round.shape)
# st.write('second round',second_round)
# st.write(second_round.shape)
# st.write('test_df',test_df)
# Workout decisions for the first round
merged1 = pd.merge(first_round,decision_df,on='hash',copy=False,suffixes=['_t','_d'])
merged1 = merged1.drop_duplicates(subset='hash', keep="last")
merged1 = merged1.drop(columns=['HomeTeam_d','AwayTeam_d'])
# st.write(merged1)
res = merged1[['hash']]
res['total-goals'] = merged1['total-goals_t']
# Flag correct decision
merged1.loc[merged1.index,'correct'] = 0
merged1.loc[(
((merged1['total-goals_t']>2.5) & (merged1['total-goals_d']>2.5))
|
((merged1['total-goals_t']<2.5) & (merged1['total-goals_d']<2.5))
)
,'correct'
] = 1
# st.write('first round choices',merged1[['HomeTeam_t','AwayTeam_t','total-goals_t','total-goals_d','correct']])
# Update stats for second round
if not second_round.empty:
if stats_type == 'last-match':
# Find total goals from previous play
merged2 = pd.merge(second_round,res,left_on='hash',right_on='hash',copy=False,suffixes=['_t','_d'])
merged2.loc[merged2.index,'correct'] = 0
merged2.loc[(
((merged2['total-goals_t']>2.5) & (merged2['total-goals_d']>2.5))
|
((merged2['total-goals_t']<2.5) & (merged2['total-goals_d']<2.5))
)
,'correct'
] = 1
elif stats_type == 'xytotal':
if not misc is None:
x_y_type = misc['sel_type']
total_goals = misc['total_goals']
hist_data = misc['hist_data']
new_data_dirty = merged1.drop(['hash','correct'],axis=1)
new_data = new_data_dirty.rename(columns={'HomeTeam_t':'HomeTeam','AwayTeam_t':'AwayTeam','total-goals_t':'total-goals'}).sort_values('Date',ascending=False)
combined = new_data.append(hist_data,ignore_index=True)
second_round_choices = prev_match_selection(combined,order_specific=order_specific,sel_type=x_y_type,total_goals=total_goals)
merged2 = pd.merge(second_round,second_round_choices,on='hash',copy=False,suffixes=['_t','_d'])
second_round_choices = second_round_choices[['hash','total-goals']].drop_duplicates()
# st.write('second_round_choices',second_round_choices)
# st.write(second_round_choices.shape)
# Find total goals from previous play
merged2 = pd.merge(second_round,second_round_choices,left_on='hash',right_on='hash',copy=False,suffixes=['_t','_d'])
merged2.loc[merged2.index,'correct'] = 0
# st.write(merged2[['HomeTeam','AwayTeam','total-goals_t','total-goals_d']])
merged2.loc[(
((merged2['total-goals_t']>2.5) & (merged2['total-goals_d']>2.5))
|
((merged2['total-goals_t']<2.5) & (merged2['total-goals_d']<2.5))
)
,'correct'
] = 1
o['accuracy'] = np.array(list(merged2['correct'])+list(merged1['correct'])).mean()
if 'Date_t' in merged1.keys():
date_val = 'Date_t'
else:
date_val = 'Date'
o['data'] = [merged1[[date_val,'HomeTeam_t','AwayTeam_t','total-goals_t','total-goals_d']],
merged2[['Date','HomeTeam','AwayTeam','total-goals_t','total-goals_d']]]
else:
o['accuracy'] = np.array(list(merged1['correct'])).mean()
if 'Date_t' in merged1.keys():
date_val = 'Date_t'
else:
date_val = 'Date'
o['data'] = [merged1[[date_val,'HomeTeam_t','AwayTeam_t','total-goals_t','total-goals_d']]]
return o
def calc_roi(season_odds,season_results,chosen_odds=None):
# > 2.5 goals
#BbAv>2.5 = Betbrain average over 2.5 goals
#BbAv<2.5 = Betbrain average under 2.5 goals
merged = pd.merge(season_odds,season_results,left_on=['Date','AwayTeam','HomeTeam'],right_on=['Date','AwayTeam','HomeTeam'],how='inner')
# st.write('season_odds',season_odds.shape)
# st.write('season_results',season_results.shape)
#
# st.write('merged',merged)
# st.write('merged',merged.shape)
clean = merged
bet_size = 1
# Check that total-goals column was created
# if not then go by the odds
if 'total-goals_t' in clean.keys() and 'total-goals_d' in clean.keys():
# add a flag to mark correctness
clean.loc[clean.index,'correct>2.5'] = 0
clean.loc[clean.index,'correct<2.5'] = 0
clean.loc[clean.index,'correct'] = 0
clean.loc[
((clean['total-goals_t']>2.5) & (clean['total-goals_d']>2.5))
,'correct>2.5'
] = 1
clean.loc[
((clean['total-goals_t']<2.5) & (clean['total-goals_d']<2.5))
,'correct<2.5'
] = 1
clean.loc[(clean['correct>2.5']==1) | (clean['correct<2.5']==1),'correct'] = 1
# st.write(clean)
broker_names = []
won_sizes = []
lost_sizes = []
succ_rates = []
avg_prices = []
rois = []
total_costs = []
profits = []
brokers = ['B365','P','GB','BbAv']
avail_brokers = []
# Lowest Broker for selection
available_odds_gt = []
available_odds_lt = []
for b in brokers:
b_str_gt = '{}>2.5'.format(b)
b_str_lt = '{}<2.5'.format(b)
if b_str_gt in clean.keys():
available_odds_gt.append(b_str_gt)
available_odds_lt.append(b_str_lt)
avail_brokers.append(b)
# Add new columns
clean.loc[clean.index,'min>2.5']=clean[available_odds_gt].min(axis=1)
clean.loc[clean.index,'max>2.5']=clean[available_odds_gt].max(axis=1)
clean.loc[clean.index,'min<2.5']=clean[available_odds_lt].min(axis=1)
clean.loc[clean.index,'max<2.5']=clean[available_odds_lt].max(axis=1)
clean.loc[clean.index,'min-odds']=clean[available_odds_lt+available_odds_gt].min(axis=1)
clean.loc[clean.index,'max-odds']=clean[list(available_odds_lt)+list(available_odds_gt)].max(axis=1)
for c,b in enumerate(avail_brokers):
broker = clean[[available_odds_gt[c],available_odds_lt[c],'correct','correct>2.5','correct<2.5']]
broker = broker.dropna(axis=0,how='any')
if broker.shape[0] > 0:
lost_size = broker['correct'].value_counts(dropna=False)[0]*bet_size
correct_rows_gt = broker[broker['correct>2.5']==1]
correct_rows_lt = broker[broker['correct<2.5']==1]
won_size = (bet_size*(correct_rows_gt[available_odds_gt[c]]).sum(skipna=True)
+ bet_size*(correct_rows_lt[available_odds_lt[c]]).sum(skipna=True))
profit = won_size - lost_size
succ_rate = (correct_rows_gt.shape[0]+correct_rows_lt.shape[0])/(broker.shape[0])
avg_price = np.array(list(correct_rows_gt[available_odds_gt[c]])+list(correct_rows_lt[available_odds_lt[c]])).mean()
total_cost = bet_size*broker.shape[0]
roi = profit/total_cost
broker_names.append(b)
won_sizes.append(won_size)
lost_sizes.append(lost_size)
succ_rates.append(succ_rate)
avg_prices.append(avg_price)
rois.append(roi)
total_costs.append(total_cost)
profits.append(profit)
if 'B365C>2.5' in clean.keys():
broker = clean[['B365C>2.5','B365C<2.5','correct','correct>2.5','correct<2.5']]
broker = broker.dropna(axis=0,how='any')
if broker.shape[0] > 0:
lost_size = broker['correct'].value_counts(dropna=False)[0]*bet_size
correct_rows_gt = broker[broker['correct>2.5']==1]
correct_rows_lt = broker[broker['correct<2.5']==1]
won_size = bet_size*(correct_rows_gt['B365C>2.5']+0).sum(skipna=True) + bet_size*(correct_rows_lt['B365C<2.5']+0).sum(skipna=True)
profit = won_size - lost_size
succ_rate = (correct_rows_gt.shape[0]+correct_rows_lt.shape[0])/(broker.shape[0])
avg_price = np.array(list(correct_rows_gt['B365C>2.5'])+list(correct_rows_lt['B365C<2.5'])).mean()
total_cost = bet_size*broker.shape[0]
roi = profit/total_cost
broker_names.append('Bet365Close')
won_sizes.append(won_size)
lost_sizes.append(lost_size)
succ_rates.append(succ_rate)
avg_prices.append(avg_price)
rois.append(roi)
total_costs.append(total_cost)
profits.append(profit)
if 'PC>2.5' in clean.keys():
broker = clean[['PC>2.5','PC<2.5','correct','correct>2.5','correct<2.5']]
broker = broker.dropna(axis=0,how='any')
if broker.shape[0] > 0:
lost_size = broker['correct'].value_counts(dropna=False)[0]*bet_size
correct_rows_gt = broker[broker['correct>2.5']==1]
correct_rows_lt = broker[broker['correct<2.5']==1]
won_size = bet_size*(correct_rows_gt['PC>2.5']+0).sum(skipna=True) + bet_size*(correct_rows_lt['PC<2.5']+0).sum(skipna=True)
profit = won_size - lost_size
succ_rate = (correct_rows_gt.shape[0]+correct_rows_lt.shape[0])/(broker.shape[0])
avg_price = np.array(list(correct_rows_gt['PC>2.5'])+list(correct_rows_lt['PC<2.5'])).mean()
total_cost = bet_size*broker.shape[0]
roi = profit/total_cost
broker_names.append('PinnacleClose')
won_sizes.append(won_size)
lost_sizes.append(lost_size)
succ_rates.append(succ_rate)
avg_prices.append(avg_price)
rois.append(roi)
total_costs.append(total_cost)
profits.append(profit)
# Select lowest broker
broker = clean[['min>2.5','min<2.5','correct','correct>2.5','correct<2.5']]
broker = broker.dropna(axis=0,how='any')
if broker.shape[0] > 0:
lost_size = broker['correct'].value_counts(dropna=False)[0]*bet_size
correct_rows_gt = broker[broker['correct>2.5']==1]
correct_rows_lt = broker[broker['correct<2.5']==1]
won_size = bet_size*(correct_rows_gt['min>2.5']+0).sum(skipna=True) + bet_size*(correct_rows_lt['min<2.5']+0).sum(skipna=True)
profit = won_size - lost_size
succ_rate = (correct_rows_gt.shape[0]+correct_rows_lt.shape[0])/(broker.shape[0])
avg_price = np.array(list(correct_rows_gt['min>2.5'])+list(correct_rows_lt['min<2.5'])).mean()
total_cost = bet_size*broker.shape[0]
roi = profit/total_cost
broker_names.append('MinBroker')
won_sizes.append(won_size)
lost_sizes.append(lost_size)
succ_rates.append(succ_rate)
avg_prices.append(avg_price)
rois.append(roi)
total_costs.append(total_cost)
profits.append(profit)
# Highest Broker
broker = clean[['max>2.5','max<2.5','correct','correct>2.5','correct<2.5']]
broker = broker.dropna(axis=0,how='any')
if broker.shape[0] > 0:
lost_size = broker['correct'].value_counts(dropna=False)[0]*bet_size
correct_rows_gt = broker[broker['correct>2.5']==1]
correct_rows_lt = broker[broker['correct<2.5']==1]
won_size = bet_size*(correct_rows_gt['max>2.5']+0).sum(skipna=True) + bet_size*(correct_rows_lt['max<2.5']+0).sum(skipna=True)
profit = won_size - lost_size
succ_rate = (correct_rows_gt.shape[0]+correct_rows_lt.shape[0])/(broker.shape[0])
avg_price = np.array(list(correct_rows_gt['max>2.5'])+list(correct_rows_lt['max<2.5'])).mean()
total_cost = bet_size*broker.shape[0]
roi = profit/total_cost
broker_names.append('MaxBroker')
won_sizes.append(won_size)
lost_sizes.append(lost_size)
succ_rates.append(succ_rate)
avg_prices.append(avg_price)
rois.append(roi)
total_costs.append(total_cost)
profits.append(profit)
output_table = pd.DataFrame({'broker-name':broker_names,
'won-size':won_sizes,
'profit':profits,
# 'loss':lost_sizes,
'succ-rate':succ_rates,
'avg-price':avg_prices,
'roi':rois,
'total-cost':total_costs
})
st.write('### Selected odds',clean)
st.write('### Results',output_table)
else:
#TODO: Calculate results based on odds (highest and lowest)
pass
def filter_teams(df,chosen_n=5,filter_type='TotalAll'):
# Select only last season data
last_season = df[df['s-year']==df['s-year'].max()]
# Rank = goals/num_games
if filter_type == 'Total goals Home+Away':
# Rank teams by total scored goals
try:
home = hist_data[['HomeTeam','FTHG']].rename(columns={'HomeTeam':'Team','FTHG':'Goals'})
except:
home = hist_data[['HomeTeam','HG']].rename(columns={'HomeTeam':'Team','HG':'Goals'})
try:
away = hist_data[['AwayTeam','FTAG']].rename(columns={'AwayTeam':'Team','FTAG':'Goals'})
except:
away = hist_data[['AwayTeam','AG']].rename(columns={'AwayTeam':'Team','AG':'Goals'})
teams = home.append(away)
goals_by_teams = teams[['Team','Goals']].groupby('Team').sum()
games_by_teams = teams[['Team','Goals']].groupby('Team').count()
rank = (goals_by_teams/games_by_teams).sort_values('Goals',ascending=False).head(chosen_n).index
home_teams = pd.DataFrame(rank)
merge_home = pd.merge(df,home_teams,left_on='HomeTeam',right_on='Team',how='inner')
merge_away = pd.merge(df,home_teams,left_on='AwayTeam',right_on='Team',how='inner')
merge = merge_home.append(merge_away).reset_index()
# st.write(merge)
return merge
elif filter_type == 'Total goals Home':
# Rank teams on total goals when was at home
try:
goals_by_teams = last_season[['HomeTeam','FTHG']].groupby('HomeTeam').sum()
games_by_teams = last_season[['HomeTeam','FTHG']].groupby('HomeTeam').count()
rank = (goals_by_teams/games_by_teams).sort_values('FTHG',ascending=False).head(chosen_n)
except:
goals_by_teams = last_season[['HomeTeam','HG']].groupby('HomeTeam').sum()
games_by_teams = last_season[['HomeTeam','HG']].groupby('HomeTeam').count()
rank = (goals_by_teams/games_by_teams).sort_values('HG',ascending=False).head(chosen_n).index
home_teams = pd.DataFrame(rank)
merge = pd.merge(df,home_teams,left_on='HomeTeam',right_on='HomeTeam',how='inner')
return merge
elif filter_type == 'Total goals Away':
# Rank teams on total goals when was away
try:
goals_by_teams = last_season[['AwayTeam','FTAG']].groupby('AwayTeam').sum()
games_by_teams = last_season[['AwayTeam','FTAG']].groupby('AwayTeam').count()
rank = (goals_by_teams/games_by_teams).sort_values('FTAG',ascending=False).head(chosen_n)
except:
goals_by_teams = last_season[['AwayTeam','AG']].groupby('AwayTeam').sum()
games_by_teams = last_season[['AwayTeam','AG']].groupby('AwayTeam').count()
rank = (goals_by_teams/games_by_teams).sort_values('HG',ascending=False).head(chosen_n).index
away_teams = pd.DataFrame(rank)
merge = pd.merge(df,away_teams,left_on='AwayTeam',right_on='AwayTeam',how='inner')
return merge
spreadsheets = find_all_spreadsheets()
data_state = st.text('')
data_state.text('Pre-processing')
big_df = load_all_data(spreadsheets)
data_state.text('')
season = st.selectbox(
"Select season", list(big_df['season'].unique()),1
)
division = st.selectbox(
"Select division", list(big_df['Div'].sort_values().unique()),0
)
order_specific = st.sidebar.checkbox('Order specific',1)
# Select by exact total number of goals
top_n_selection = st.sidebar.checkbox('Top n teams from the previous season',0)
st.markdown("""Select a type of Head to head. Two options are available.""")
st.markdown("1) Total goals from previous fixture looks at the previous total number of goals in the previous identical match")
st.markdown("2) x/y matching with total goals only selects matches where at least x out of y last matches had at least (however many)`total goals'")
st.markdown("More filters available i the panel on the left")
# Find previous total for all pairs
total_type = st.selectbox(
"Type of `Head to Head'", ['None','Total goals from previous fixture',"x/y & `total goals' criterion"],0
)
current_year = int(season[5:])
division_data = big_df.loc[big_df['Div'] == division]
current_data = division_data.loc[big_df['s-year']==current_year]
hist_data = division_data.loc[(big_df['s-year'] < current_year)]
if top_n_selection:
rank_type = st.sidebar.selectbox(
"Rank teams by", ['Total goals Home+Away','Total goals Home','Total goals Away'],0
)
n = st.sidebar.number_input('Number of top teams selected',
min_value=1,
max_value=len(current_data['HomeTeam'].unique()+current_data['AwayTeam'].unique()),
value=5)
# Filter teams
hist_data = filter_teams(hist_data,chosen_n=n,filter_type=rank_type)
test_data = None
stats_type = None
misc = None
if total_type == 'None':
pass
elif total_type == 'Total goals from previous fixture':
test_data = prev_match(hist_data,order_specific=order_specific)
stats_type = 'last-match'
elif total_type == "x/y & `total goals' criterion":
x_y_type = st.selectbox(
"Select x/y", ['1/1','1/2','2/2','2/3','3/3','3/4','4/4','4/5','5/5'],5
)
total_goals = st.selectbox(
"Select `total goals'", np.linspace(0.5,8.5,9),2
)
test_data = prev_match_selection(hist_data,order_specific=order_specific,sel_type=x_y_type,total_goals=total_goals)
stats_type = 'xytotal'
misc = {'sel_type':x_y_type,'total_goals':total_goals,'hist_data':hist_data}
# Workout how many matches were won with given filters
if total_type != 'None':
temp = find_stats(current_data,test_data,order_specific=order_specific,stats_type=stats_type,misc=misc)
else:
temp = {'data':[]}
if len(temp['data']) == 1:
out_data = temp['data'][0].rename(columns={'HomeTeam_t':'HomeTeam',
'AwayTeam_t':'AwayTeam',
# 'total-goals_t':'total-goals',
# 'total-goals_d':'total-goals',
'Date_t':'Date',
'Date_d':'Date'
})
# st.write('## Selection',out_data)
elif len(temp['data']) == 2:
out_data1 = temp['data'][0].rename(columns={'HomeTeam_t':'HomeTeam',
'AwayTeam_t':'AwayTeam',
# 'total-goals_t':'total-goals',
# 'total-goals_d':'total-goals',
'Date_t':'Date',
'Date_d':'Date'
})
out_data2 = temp['data'][1].rename(columns={'HomeTeam_t':'HomeTeam',
'AwayTeam_t':'AwayTeam',
# 'total-goals_t':'total-goals',
# 'total-goals_d':'total-goals',
'Date_t':'Date',
'Date_d':'Date'
})
out_data = out_data1.append(out_data2,ignore_index=True)
# st.write('## Selection',out_data)
if total_type != 'None':
calc_roi(current_data,out_data)
else:
#TODO: Choose best matches based on odds
pass
| [
"streamlit.markdown",
"numpy.ceil",
"pandas.read_csv",
"pandas.merge",
"streamlit.write",
"requests.get",
"streamlit.sidebar.checkbox",
"streamlit.text",
"numpy.linspace",
"pandas.read_excel",
"streamlit.sidebar.selectbox",
"streamlit.selectbox",
"pandas.DataFrame",
"re.findall",
"pandas... | [((24432, 24443), 'streamlit.text', 'st.text', (['""""""'], {}), "('')\n", (24439, 24443), True, 'import streamlit as st\n'), ((24732, 24772), 'streamlit.sidebar.checkbox', 'st.sidebar.checkbox', (['"""Order specific"""', '(1)'], {}), "('Order specific', 1)\n", (24751, 24772), True, 'import streamlit as st\n'), ((24831, 24893), 'streamlit.sidebar.checkbox', 'st.sidebar.checkbox', (['"""Top n teams from the previous season"""', '(0)'], {}), "('Top n teams from the previous season', 0)\n", (24850, 24893), True, 'import streamlit as st\n'), ((24894, 24966), 'streamlit.markdown', 'st.markdown', (['"""Select a type of Head to head. Two options are available."""'], {}), "('Select a type of Head to head. Two options are available.')\n", (24905, 24966), True, 'import streamlit as st\n'), ((24971, 25108), 'streamlit.markdown', 'st.markdown', (['"""1) Total goals from previous fixture looks at the previous total number of goals in the previous identical match"""'], {}), "(\n '1) Total goals from previous fixture looks at the previous total number of goals in the previous identical match'\n )\n", (24982, 25108), True, 'import streamlit as st\n'), ((25099, 25257), 'streamlit.markdown', 'st.markdown', (['"""2) x/y matching with total goals only selects matches where at least x out of y last matches had at least (however many)`total goals\'"""'], {}), '(\n "2) x/y matching with total goals only selects matches where at least x out of y last matches had at least (however many)`total goals\'"\n )\n', (25110, 25257), True, 'import streamlit as st\n'), ((25248, 25309), 'streamlit.markdown', 'st.markdown', (['"""More filters available i the panel on the left"""'], {}), "('More filters available i the panel on the left')\n", (25259, 25309), True, 'import streamlit as st\n'), ((25360, 25485), 'streamlit.selectbox', 'st.selectbox', (['"""Type of `Head to Head\'"""', '[\'None\', \'Total goals from previous fixture\', "x/y & `total goals\' criterion"]', '(0)'], {}), '("Type of `Head to Head\'", [\'None\',\n \'Total goals from previous fixture\', "x/y & `total goals\' criterion"], 0)\n', (25372, 25485), True, 'import streamlit as st\n'), ((197, 258), 'requests.get', 'requests.get', (['"""https://www.football-data.co.uk/downloadm.php"""'], {}), "('https://www.football-data.co.uk/downloadm.php')\n", (209, 258), False, 'import requests\n'), ((377, 435), 're.findall', 're.findall', (['"""(mmz(.*?)[0-9]+-[0-9]+(.*?).[xls]+")"""', 'r.text'], {}), '(\'(mmz(.*?)[0-9]+-[0-9]+(.*?).[xls]+")\', r.text)\n', (387, 435), False, 'import re\n'), ((657, 678), 'pandas.read_csv', 'pd.read_csv', (['data_url'], {}), '(data_url)\n', (668, 678), True, 'import pandas as pd\n'), ((800, 849), 'pandas.to_datetime', 'pd.to_datetime', (["(data['date'] + ' ' + data['time'])"], {}), "(data['date'] + ' ' + data['time'])\n", (814, 849), True, 'import pandas as pd\n'), ((1149, 1184), 'pandas.read_excel', 'pd.read_excel', (['url'], {'sheet_name': 'None'}), '(url, sheet_name=None)\n', (1162, 1184), True, 'import pandas as pd\n'), ((1335, 1349), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1347, 1349), True, 'import pandas as pd\n'), ((4774, 4847), 'pandas.merge', 'pd.merge', (['small', 'good_hashes'], {'left_on': '"""hash"""', 'right_on': '"""hash"""', 'copy': '(False)'}), "(small, good_hashes, left_on='hash', right_on='hash', copy=False)\n", (4782, 4847), True, 'import pandas as pd\n'), ((4889, 4909), 'numpy.ceil', 'np.ceil', (['total_goals'], {}), '(total_goals)\n', (4896, 4909), True, 'import numpy as np\n'), ((11514, 11653), 'pandas.merge', 'pd.merge', (['season_odds', 'season_results'], {'left_on': "['Date', 'AwayTeam', 'HomeTeam']", 'right_on': "['Date', 'AwayTeam', 'HomeTeam']", 'how': '"""inner"""'}), "(season_odds, season_results, left_on=['Date', 'AwayTeam',\n 'HomeTeam'], right_on=['Date', 'AwayTeam', 'HomeTeam'], how='inner')\n", (11522, 11653), True, 'import pandas as pd\n'), ((25739, 25850), 'streamlit.sidebar.selectbox', 'st.sidebar.selectbox', (['"""Rank teams by"""', "['Total goals Home+Away', 'Total goals Home', 'Total goals Away']", '(0)'], {}), "('Rank teams by', ['Total goals Home+Away',\n 'Total goals Home', 'Total goals Away'], 0)\n", (25759, 25850), True, 'import streamlit as st\n'), ((1768, 1792), 'pandas.read_excel', 'pd.read_excel', (['url', 'None'], {}), '(url, None)\n', (1781, 1792), True, 'import pandas as pd\n'), ((1826, 1870), 'pandas.concat', 'pd.concat', (['og_spreadsheet'], {'ignore_index': '(True)'}), '(og_spreadsheet, ignore_index=True)\n', (1835, 1870), True, 'import pandas as pd\n'), ((2049, 2088), 'pandas.to_datetime', 'pd.to_datetime', (["big_spreadsheet['Date']"], {}), "(big_spreadsheet['Date'])\n", (2063, 2088), True, 'import pandas as pd\n'), ((5502, 5604), 'pandas.merge', 'pd.merge', (['test_df', 'decision_df'], {'left_on': '"""hash"""', 'right_on': '"""hash"""', 'copy': '(False)', 'suffixes': "['_t', '_d']"}), "(test_df, decision_df, left_on='hash', right_on='hash', copy=False,\n suffixes=['_t', '_d'])\n", (5510, 5604), True, 'import pandas as pd\n'), ((7027, 7112), 'pandas.merge', 'pd.merge', (['first_round', 'decision_df'], {'on': '"""hash"""', 'copy': '(False)', 'suffixes': "['_t', '_d']"}), "(first_round, decision_df, on='hash', copy=False, suffixes=['_t', '_d']\n )\n", (7035, 7112), True, 'import pandas as pd\n'), ((20676, 20859), 'pandas.DataFrame', 'pd.DataFrame', (["{'broker-name': broker_names, 'won-size': won_sizes, 'profit': profits,\n 'succ-rate': succ_rates, 'avg-price': avg_prices, 'roi': rois,\n 'total-cost': total_costs}"], {}), "({'broker-name': broker_names, 'won-size': won_sizes, 'profit':\n profits, 'succ-rate': succ_rates, 'avg-price': avg_prices, 'roi': rois,\n 'total-cost': total_costs})\n", (20688, 20859), True, 'import pandas as pd\n'), ((21170, 21206), 'streamlit.write', 'st.write', (['"""### Selected odds"""', 'clean'], {}), "('### Selected odds', clean)\n", (21178, 21206), True, 'import streamlit as st\n'), ((21214, 21251), 'streamlit.write', 'st.write', (['"""### Results"""', 'output_table'], {}), "('### Results', output_table)\n", (21222, 21251), True, 'import streamlit as st\n'), ((22388, 22406), 'pandas.DataFrame', 'pd.DataFrame', (['rank'], {}), '(rank)\n', (22400, 22406), True, 'import pandas as pd\n'), ((22428, 22502), 'pandas.merge', 'pd.merge', (['df', 'home_teams'], {'left_on': '"""HomeTeam"""', 'right_on': '"""Team"""', 'how': '"""inner"""'}), "(df, home_teams, left_on='HomeTeam', right_on='Team', how='inner')\n", (22436, 22502), True, 'import pandas as pd\n'), ((22520, 22594), 'pandas.merge', 'pd.merge', (['df', 'home_teams'], {'left_on': '"""AwayTeam"""', 'right_on': '"""Team"""', 'how': '"""inner"""'}), "(df, home_teams, left_on='AwayTeam', right_on='Team', how='inner')\n", (22528, 22594), True, 'import pandas as pd\n'), ((23413, 23431), 'pandas.DataFrame', 'pd.DataFrame', (['rank'], {}), '(rank)\n', (23425, 23431), True, 'import pandas as pd\n'), ((23448, 23526), 'pandas.merge', 'pd.merge', (['df', 'home_teams'], {'left_on': '"""HomeTeam"""', 'right_on': '"""HomeTeam"""', 'how': '"""inner"""'}), "(df, home_teams, left_on='HomeTeam', right_on='HomeTeam', how='inner')\n", (23456, 23526), True, 'import pandas as pd\n'), ((26468, 26566), 'streamlit.selectbox', 'st.selectbox', (['"""Select x/y"""', "['1/1', '1/2', '2/2', '2/3', '3/3', '3/4', '4/4', '4/5', '5/5']", '(5)'], {}), "('Select x/y', ['1/1', '1/2', '2/2', '2/3', '3/3', '3/4', '4/4',\n '4/5', '5/5'], 5)\n", (26480, 26566), True, 'import streamlit as st\n'), ((517, 548), 're.search', 're.search', (['"""[0-9]+-[0-9]+"""', 'tmp'], {}), "('[0-9]+-[0-9]+', tmp)\n", (526, 548), False, 'import re\n'), ((8129, 8228), 'pandas.merge', 'pd.merge', (['second_round', 'res'], {'left_on': '"""hash"""', 'right_on': '"""hash"""', 'copy': '(False)', 'suffixes': "['_t', '_d']"}), "(second_round, res, left_on='hash', right_on='hash', copy=False,\n suffixes=['_t', '_d'])\n", (8137, 8228), True, 'import pandas as pd\n'), ((24248, 24266), 'pandas.DataFrame', 'pd.DataFrame', (['rank'], {}), '(rank)\n', (24260, 24266), True, 'import pandas as pd\n'), ((24283, 24361), 'pandas.merge', 'pd.merge', (['df', 'away_teams'], {'left_on': '"""AwayTeam"""', 'right_on': '"""AwayTeam"""', 'how': '"""inner"""'}), "(df, away_teams, left_on='AwayTeam', right_on='AwayTeam', how='inner')\n", (24291, 24361), True, 'import pandas as pd\n'), ((26648, 26672), 'numpy.linspace', 'np.linspace', (['(0.5)', '(8.5)', '(9)'], {}), '(0.5, 8.5, 9)\n', (26659, 26672), True, 'import numpy as np\n'), ((9464, 9558), 'pandas.merge', 'pd.merge', (['second_round', 'second_round_choices'], {'on': '"""hash"""', 'copy': '(False)', 'suffixes': "['_t', '_d']"}), "(second_round, second_round_choices, on='hash', copy=False,\n suffixes=['_t', '_d'])\n", (9472, 9558), True, 'import pandas as pd\n'), ((9924, 10041), 'pandas.merge', 'pd.merge', (['second_round', 'second_round_choices'], {'left_on': '"""hash"""', 'right_on': '"""hash"""', 'copy': '(False)', 'suffixes': "['_t', '_d']"}), "(second_round, second_round_choices, left_on='hash', right_on=\n 'hash', copy=False, suffixes=['_t', '_d'])\n", (9932, 10041), True, 'import pandas as pd\n')] |
import json
import requests
import tempfile
import shutil
import subprocess
import os
import logging
import urllib.request
from multiprocessing import Pool
import app.easyCI.docker as docker
from contextlib import contextmanager
LOG = logging.getLogger(__name__)
CONFIG = "config.json"
PASSWORDS = "<PASSWORD>"
MAX_COMMENT_SIZE = 10000
PROCS = 1
REQUEST_TIMEOUT = 300
class QueueTask(object):
host = None
auth = None
config = None
id = None
course = None
task = None
issue = None
event = None
files = None
def __repr__(self):
return repr(self.__dict__)
@contextmanager
def tmp_dir():
t = tempfile.mkdtemp(dir="/var/tmp")
try:
yield t
finally:
shutil.rmtree(t)
def git_clone(repo, dst_dir):
cmd = ["git", "clone", repo, dst_dir]
LOG.info("RUN: %s", cmd)
subprocess.check_call(cmd)
def prepare_dir(qtask, dirname):
git_dir = os.path.join(dirname, "git")
task_dir = os.path.join(dirname, "task")
git_clone(qtask.course["repo"], git_dir)
os.mkdir(task_dir)
for url in qtask.files:
filename = url.split('/')[-1]
dst_path = os.path.join(task_dir, filename)
LOG.info("Download '%s' -> '%s'", url, dst_path)
print(url, dst_path)
urllib.request.urlretrieve(url, dst_path)
def process_task(qtask):
LOG.info("Proccess task %s", qtask.id)
with tmp_dir() as dirname:
prepare_dir(qtask, dirname)
run_cmd = qtask.course["run_cmd"] + [qtask.task, "/task_dir/task"]
#run_cmd = ["ls", "/task_dir/task"]
ret = docker.execute(run_cmd, cwd="/task_dir/git", timeout=qtask.course["timeout"], user='root',
network='bridge', image=qtask.course["docker_image"],
volumes=["{}:/task_dir:ro".format(os.path.abspath(dirname))])
status, retcode, is_timeout, output = ret
LOG.info("Task %d done, status:%s, retcode:%d, is_timeout:%d",
qtask.id, status, retcode, is_timeout)
LOG.info(" == Task %d output start", qtask.id)
for line in output.split("\n"):
LOG.info(line)
LOG.info(" == Task %d output end", qtask.id)
if len(output) > MAX_COMMENT_SIZE:
output = output[:MAX_COMMENT_SIZE]
output += u"\n...\nTRUNCATED"
if is_timeout:
output += u"\nTIMEOUT ({} sec)".format(qtask.course["timeout"])
comment = u"[id:{}] Check DONE!<br>\nSubmited on {}<br>\n<pre>{}</pre>\n".format(qtask.id,
qtask.event_timestamp,
output)
LOG.info("{}/api/v1/issue/{}/add_comment".format(qtask.host, qtask.issue_id))
response = requests.post("{}/api/v1/issue/{}/add_comment".format(qtask.host, qtask.issue_id),
auth=qtask.auth, data={"comment":comment.encode("utf-8")}, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
LOG.info(" == Task %d DONE!, URL: %s/issue/%d", qtask.id, qtask.host, qtask.issue_id)
return qtask
def load_passwords(filename=PASSWORDS):
with open(filename) as config_fn:
return json.load(config_fn)
def load_config(filename=CONFIG):
with open(filename) as config_fn:
config_arr = json.load(config_fn)
config_dict = {}
for course in config_arr:
config_dict[course["course_id"]] = course
return config_dict
def get_auth(passwords, host):
host_auth = passwords[host]
return (host_auth["username"], host_auth["password"])
config = load_config()
passwords = load_passwords()
pool = Pool(processes=PROCS)
def put_to_pool(task):
course_id = task["course_id"]
course = config[course_id]
auth = get_auth(passwords, course["host"])
files = task["files"]
qtask = QueueTask()
qtask.host = course["host"]
qtask.auth = auth
qtask.course = course
qtask.task = task["title"]
qtask.issue_id = task["issue_id"]
qtask.files = files
qtask.id = task["event"]["id"]
qtask.event_timestamp = task["event"]["timestamp"]
print(qtask)
pool.apply_async(process_task, args=(qtask,))
| [
"logging.getLogger",
"subprocess.check_call",
"os.path.join",
"tempfile.mkdtemp",
"multiprocessing.Pool",
"os.mkdir",
"shutil.rmtree",
"json.load",
"os.path.abspath"
] | [((237, 264), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (254, 264), False, 'import logging\n'), ((3765, 3786), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'PROCS'}), '(processes=PROCS)\n', (3769, 3786), False, 'from multiprocessing import Pool\n'), ((647, 679), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'dir': '"""/var/tmp"""'}), "(dir='/var/tmp')\n", (663, 679), False, 'import tempfile\n'), ((850, 876), 'subprocess.check_call', 'subprocess.check_call', (['cmd'], {}), '(cmd)\n', (871, 876), False, 'import subprocess\n'), ((926, 954), 'os.path.join', 'os.path.join', (['dirname', '"""git"""'], {}), "(dirname, 'git')\n", (938, 954), False, 'import os\n'), ((970, 999), 'os.path.join', 'os.path.join', (['dirname', '"""task"""'], {}), "(dirname, 'task')\n", (982, 999), False, 'import os\n'), ((1050, 1068), 'os.mkdir', 'os.mkdir', (['task_dir'], {}), '(task_dir)\n', (1058, 1068), False, 'import os\n'), ((726, 742), 'shutil.rmtree', 'shutil.rmtree', (['t'], {}), '(t)\n', (739, 742), False, 'import shutil\n'), ((1154, 1186), 'os.path.join', 'os.path.join', (['task_dir', 'filename'], {}), '(task_dir, filename)\n', (1166, 1186), False, 'import os\n'), ((3303, 3323), 'json.load', 'json.load', (['config_fn'], {}), '(config_fn)\n', (3312, 3323), False, 'import json\n'), ((3419, 3439), 'json.load', 'json.load', (['config_fn'], {}), '(config_fn)\n', (3428, 3439), False, 'import json\n'), ((1831, 1855), 'os.path.abspath', 'os.path.abspath', (['dirname'], {}), '(dirname)\n', (1846, 1855), False, 'import os\n')] |
from django.contrib.gis.geos import Point
from data_collection.management.commands import BaseShpStationsShpDistrictsImporter
class Command(BaseShpStationsShpDistrictsImporter):
srid = 27700
council_id = "W06000021"
districts_name = "polling_district"
stations_name = "polling_station.shp"
elections = ["local.monmouthshire.2017-05-04", "parl.2017-06-08"]
def district_record_to_dict(self, record):
return {
"internal_council_id": str(record[1]).strip(),
"name": str(record[1]).strip(),
"polling_station_id": record[3],
}
def station_record_to_dict(self, record):
station = {
"internal_council_id": record[0],
"postcode": "",
"address": "%s\n%s" % (record[2].strip(), record[4].strip()),
}
if str(record[1]).strip() == "10033354925":
"""
There is a dodgy point in this file.
It has too many digits for a UK national grid reference.
Joe queried, Monmouthshire provided this corrected point by email
"""
station["location"] = Point(335973, 206322, srid=27700)
return station
| [
"django.contrib.gis.geos.Point"
] | [((1143, 1176), 'django.contrib.gis.geos.Point', 'Point', (['(335973)', '(206322)'], {'srid': '(27700)'}), '(335973, 206322, srid=27700)\n', (1148, 1176), False, 'from django.contrib.gis.geos import Point\n')] |
# -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @Daddy_Blamo wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. - Muad'Dib
# ----------------------------------------------------------------------------
#######################################################################
# Addon Name: Placenta
# Addon id: plugin.video.placenta
# Addon Provider: Mr.Blamo
import json
import re
import urllib
import urlparse
from resources.lib.modules import client
from resources.lib.modules import source_utils
class source:
def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['video4k.to']
self.base_link = 'http://video4k.to'
self.request_link = '/request'
def movie(self, imdb, title, localtitle, aliases, year):
try:
return urllib.urlencode({'mID': re.sub('[^0-9]', '', imdb)})
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
return urllib.urlencode({'mID': re.sub('[^0-9]', '', imdb)})
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if url == None:
return
return urllib.urlencode({'mID': re.sub('[^0-9]', '', imdb), 'season': season, 'episode': episode})
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if url == None:
return sources
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
data.update({'raw': 'true', 'language': 'de'})
data = urllib.urlencode(data)
data = client.request(urlparse.urljoin(self.base_link, self.request_link), post=data)
data = json.loads(data)
data = [i[1] for i in data[1].items()]
data = [(i['name'].lower(), i['links']) for i in data]
for host, links in data:
valid, host = source_utils.is_host_valid(host, hostDict)
if not valid: continue
for link in links:
try:sources.append({'source': host, 'quality': 'SD', 'language': 'de', 'url': link['URL'], 'direct': False, 'debridonly': False})
except: pass
return sources
except:
return sources
def resolve(self, url):
return url
| [
"urlparse.urljoin",
"json.loads",
"urlparse.parse_qs",
"resources.lib.modules.source_utils.is_host_valid",
"urllib.urlencode",
"re.sub"
] | [((1876, 1898), 'urlparse.parse_qs', 'urlparse.parse_qs', (['url'], {}), '(url)\n', (1893, 1898), False, 'import urlparse\n'), ((2058, 2080), 'urllib.urlencode', 'urllib.urlencode', (['data'], {}), '(data)\n', (2074, 2080), False, 'import urllib\n'), ((2198, 2214), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (2208, 2214), False, 'import json\n'), ((2115, 2166), 'urlparse.urljoin', 'urlparse.urljoin', (['self.base_link', 'self.request_link'], {}), '(self.base_link, self.request_link)\n', (2131, 2166), False, 'import urlparse\n'), ((2401, 2443), 'resources.lib.modules.source_utils.is_host_valid', 'source_utils.is_host_valid', (['host', 'hostDict'], {}), '(host, hostDict)\n', (2427, 2443), False, 'from resources.lib.modules import source_utils\n'), ((1158, 1184), 're.sub', 're.sub', (['"""[^0-9]"""', '""""""', 'imdb'], {}), "('[^0-9]', '', imdb)\n", (1164, 1184), False, 'import re\n'), ((1360, 1386), 're.sub', 're.sub', (['"""[^0-9]"""', '""""""', 'imdb'], {}), "('[^0-9]', '', imdb)\n", (1366, 1386), False, 'import re\n'), ((1609, 1635), 're.sub', 're.sub', (['"""[^0-9]"""', '""""""', 'imdb'], {}), "('[^0-9]', '', imdb)\n", (1615, 1635), False, 'import re\n')] |
import cv2
import numpy as np
import argparse
def main(image_file_path):
img = cv2.imread(image_file_path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
name_window_1 = "original"
name_window_2 = "grayscale"
while True:
cv2.imshow(name_window_1, img)
cv2.imshow(name_window_2, img_gray)
key = cv2.waitKey(0)
# press ESC to close
if key == 27:
break
# destroy all windows
cv2.destroyAllWindows()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--imagepath", dest = "image_file_path", type = str,
default = None, help = "Image file path")
args = parser.parse_args()
image_file_path = args.image_file_path
main(image_file_path) | [
"argparse.ArgumentParser",
"cv2.imshow",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.cvtColor",
"cv2.imread"
] | [((84, 111), 'cv2.imread', 'cv2.imread', (['image_file_path'], {}), '(image_file_path)\n', (94, 111), False, 'import cv2\n'), ((127, 164), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (139, 164), False, 'import cv2\n'), ((475, 498), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (496, 498), False, 'import cv2\n'), ((540, 565), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (563, 565), False, 'import argparse\n'), ((253, 283), 'cv2.imshow', 'cv2.imshow', (['name_window_1', 'img'], {}), '(name_window_1, img)\n', (263, 283), False, 'import cv2\n'), ((292, 327), 'cv2.imshow', 'cv2.imshow', (['name_window_2', 'img_gray'], {}), '(name_window_2, img_gray)\n', (302, 327), False, 'import cv2\n'), ((342, 356), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (353, 356), False, 'import cv2\n')] |
"""Update maritime data using update modules"""
from __future__ import annotations
from argparse import ArgumentParser
import base64
import hashlib
import os
import shelve
import toml
from .modules import get_update_module
def main():
parser = ArgumentParser(description=__doc__)
parser.add_argument('configfile', metavar='config.toml')
args = parser.parse_args()
config = toml.load(args.configfile)
statefile = config.get('statefile')
if statefile is None:
location = os.path.realpath(args.configfile)
hash = hashlib.sha256(location.encode()).digest()[:6]
encoded_hash = base64.urlsafe_b64encode(hash).decode()
statefile = f'/var/tmp/mum-{encoded_hash[:8]}.statefile'
transient_state = {}
with shelve.open(statefile, writeback=True) as db:
for updater_config in config.get('updater', []):
updater_cls = get_update_module(updater_config['module'])
if updater_config.get('enabled', True):
updater = updater_cls(**updater_config)
if updater.needs_update(db, transient_state):
updater.update(db, transient_state)
db.sync()
| [
"argparse.ArgumentParser",
"base64.urlsafe_b64encode",
"os.path.realpath",
"shelve.open",
"toml.load"
] | [((253, 288), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (267, 288), False, 'from argparse import ArgumentParser\n'), ((395, 421), 'toml.load', 'toml.load', (['args.configfile'], {}), '(args.configfile)\n', (404, 421), False, 'import toml\n'), ((507, 540), 'os.path.realpath', 'os.path.realpath', (['args.configfile'], {}), '(args.configfile)\n', (523, 540), False, 'import os\n'), ((766, 804), 'shelve.open', 'shelve.open', (['statefile'], {'writeback': '(True)'}), '(statefile, writeback=True)\n', (777, 804), False, 'import shelve\n'), ((626, 656), 'base64.urlsafe_b64encode', 'base64.urlsafe_b64encode', (['hash'], {}), '(hash)\n', (650, 656), False, 'import base64\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-15 08:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('review', '0003_auto_20170314_2217'),
]
operations = [
migrations.CreateModel(
name='GradeComponent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order', models.PositiveSmallIntegerField(default=0.0, help_text='Used to order the display of grade items')),
('explanation', models.TextField(help_text='HTML is possible; used in the template. Can include template elements.', max_length=500)),
('weight', models.FloatField(default=0.0, help_text=('Values must be between 0.0 and 1.0.', ' It is your responsibility to make sure the total weights do not sum to over 1.0 (i.e. 100%)'))),
('extra_detail', models.CharField(blank=True, choices=[('peer', 'peer'), ('instructor', 'instructor')], help_text=('Extra information used to help distinguish a phase. For ', 'example, the Peer-Evaluation phase is used for instructors as well as peers to evaluate. But the instructor(s) grades must get a higher weight. This is used to split the code.'), max_length=50)),
],
),
migrations.CreateModel(
name='GradeReportPhase',
fields=[
('prphase_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='review.PRPhase')),
],
bases=('review.prphase',),
),
migrations.AlterField(
model_name='prphase',
name='end_dt',
field=models.DateTimeField(blank=True, verbose_name='End of this phase'),
),
migrations.AlterField(
model_name='prphase',
name='start_dt',
field=models.DateTimeField(blank=True, verbose_name='Start of this phase'),
),
migrations.AddField(
model_name='gradecomponent',
name='phase',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='review.PRPhase'),
),
migrations.AddField(
model_name='gradecomponent',
name='pr',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='review.PR_process'),
),
]
| [
"django.db.models.OneToOneField",
"django.db.models.FloatField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.models.PositiveSmallIntegerField",
"django.db.models.CharField"
] | [((1885, 1951), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'verbose_name': '"""End of this phase"""'}), "(blank=True, verbose_name='End of this phase')\n", (1905, 1951), False, 'from django.db import migrations, models\n'), ((2076, 2144), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'verbose_name': '"""Start of this phase"""'}), "(blank=True, verbose_name='Start of this phase')\n", (2096, 2144), False, 'from django.db import migrations, models\n'), ((2271, 2359), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""review.PRPhase"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'review.PRPhase')\n", (2288, 2359), False, 'from django.db import migrations, models\n'), ((2478, 2569), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""review.PR_process"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'review.PR_process')\n", (2495, 2569), False, 'from django.db import migrations, models\n'), ((435, 528), '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", (451, 528), False, 'from django.db import migrations, models\n'), ((553, 657), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(0.0)', 'help_text': '"""Used to order the display of grade items"""'}), "(default=0.0, help_text=\n 'Used to order the display of grade items')\n", (585, 657), False, 'from django.db import migrations, models\n'), ((687, 812), 'django.db.models.TextField', 'models.TextField', ([], {'help_text': '"""HTML is possible; used in the template. Can include template elements."""', 'max_length': '(500)'}), "(help_text=\n 'HTML is possible; used in the template. Can include template elements.',\n max_length=500)\n", (703, 812), False, 'from django.db import migrations, models\n'), ((833, 1024), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(0.0)', 'help_text': "('Values must be between 0.0 and 1.0.',\n ' It is your responsibility to make sure the total weights do not sum to over 1.0 (i.e. 100%)'\n )"}), "(default=0.0, help_text=(\n 'Values must be between 0.0 and 1.0.',\n ' It is your responsibility to make sure the total weights do not sum to over 1.0 (i.e. 100%)'\n ))\n", (850, 1024), False, 'from django.db import migrations, models\n'), ((1046, 1416), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'choices': "[('peer', 'peer'), ('instructor', 'instructor')]", 'help_text': "('Extra information used to help distinguish a phase. For ',\n 'example, the Peer-Evaluation phase is used for instructors as well as peers to evaluate. But the instructor(s) grades must get a higher weight. This is used to split the code.'\n )", 'max_length': '(50)'}), "(blank=True, choices=[('peer', 'peer'), ('instructor',\n 'instructor')], help_text=(\n 'Extra information used to help distinguish a phase. For ',\n 'example, the Peer-Evaluation phase is used for instructors as well as peers to evaluate. But the instructor(s) grades must get a higher weight. This is used to split the code.'\n ), max_length=50)\n", (1062, 1416), False, 'from django.db import migrations, models\n'), ((1549, 1717), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'auto_created': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'parent_link': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'to': '"""review.PRPhase"""'}), "(auto_created=True, on_delete=django.db.models.deletion\n .CASCADE, parent_link=True, primary_key=True, serialize=False, to=\n 'review.PRPhase')\n", (1569, 1717), False, 'from django.db import migrations, models\n')] |
from ..helpers import IFPTestCase
from intficpy.things import Thing, Container, Liquid
class TestDropVerb(IFPTestCase):
def test_verb_func_drops_item(self):
item = Thing(self.game, self._get_unique_noun())
item.invItem = True
self.me.addThing(item)
self.assertIn(item.ix, self.me.contains)
self.assertEqual(len(self.me.contains[item.ix]), 1)
self.assertIn(item, self.me.contains[item.ix])
self.game.turnMain(f"drop {item.verbose_name}")
self.assertItemNotIn(
item, self.me.contains, "Dropped item, but item still in inventory"
)
def test_drop_item_not_in_inv(self):
item = Thing(self.game, "shoe")
item.invItem = True
self.start_room.addThing(item)
self.assertFalse(self.me.containsItem(item))
self.game.turnMain(f"drop {item.verbose_name}")
self.assertIn("You are not holding", self.app.print_stack.pop())
def test_drop_liquid_in_container(self):
cup = Container(self.game, "cup")
water = Liquid(self.game, "water", "water")
water.moveTo(cup)
cup.moveTo(self.me)
self.game.turnMain("drop water")
self.assertIn("You drop the cup", self.app.print_stack.pop())
self.assertFalse(self.game.me.containsItem(cup))
self.assertTrue(cup.containsItem(water))
def test_drop_composite_child(self):
machine = Thing(self.game, "machine")
wheel = Thing(self.game, "wheel")
machine.addComposite(wheel)
machine.moveTo(self.me)
self.game.turnMain("drop wheel")
self.assertIn("wheel is attached to the machine", self.app.print_stack.pop())
self.assertTrue(self.me.containsItem(wheel))
| [
"intficpy.things.Liquid",
"intficpy.things.Container",
"intficpy.things.Thing"
] | [((679, 703), 'intficpy.things.Thing', 'Thing', (['self.game', '"""shoe"""'], {}), "(self.game, 'shoe')\n", (684, 703), False, 'from intficpy.things import Thing, Container, Liquid\n'), ((1014, 1041), 'intficpy.things.Container', 'Container', (['self.game', '"""cup"""'], {}), "(self.game, 'cup')\n", (1023, 1041), False, 'from intficpy.things import Thing, Container, Liquid\n'), ((1058, 1093), 'intficpy.things.Liquid', 'Liquid', (['self.game', '"""water"""', '"""water"""'], {}), "(self.game, 'water', 'water')\n", (1064, 1093), False, 'from intficpy.things import Thing, Container, Liquid\n'), ((1425, 1452), 'intficpy.things.Thing', 'Thing', (['self.game', '"""machine"""'], {}), "(self.game, 'machine')\n", (1430, 1452), False, 'from intficpy.things import Thing, Container, Liquid\n'), ((1469, 1494), 'intficpy.things.Thing', 'Thing', (['self.game', '"""wheel"""'], {}), "(self.game, 'wheel')\n", (1474, 1494), False, 'from intficpy.things import Thing, Container, Liquid\n')] |
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from woot.apps.catalog.models.forum import Question, Answer
from woot.apps.catalog.models.core import Makey, Comment
from woot.apps.catalog.forms import QuestionForm, AnswerForm, CommentForm
def question(request, question_id, **kwargs):
q = get_object_or_404(Question, id=question_id)
if request.method == "GET":
q.increase_views()
context = {
'question': q,
}
elif request.method == "POST":
form = AnswerForm(request.POST)
if form.is_valid():
u = request.user
a = Answer()
a.save_from_form(form, creator=u, question=q)
context = {
'question': q,
}
else:
context = {
'question': q,
'form': form,
}
if 'form' in kwargs.keys():
context['form'] = kwargs['form']
return render(request, 'catalog/question_page.html', context)
def ask_question(request, makey_id):
m = get_object_or_404(Makey, id=makey_id)
if request.method == "GET":
context = {
'makey': m,
}
return render(request, 'catalog/ask_question.html', context)
elif request.method == "POST":
u = get_object_or_404(User, id=request.user.id)
form = QuestionForm(request.POST)
if form.is_valid():
q = Question()
q.save_from_form(form, creator=u, makey=m)
return HttpResponseRedirect(reverse('catalog:question', kwargs={
'question_id': q.id
}))
else:
context = {
'makey': m,
'form': form
}
return render(request, 'catalog/ask_question.html', context)
def add_comment(request):
if request.method == "POST":
question_id = request.POST.get('question', '')
form = CommentForm(request.POST)
if form.is_valid():
owner = form.cleaned_data['owner'].split('-')
if owner[0] == "q":
q = get_object_or_404(Question, id=int(owner[1]))
c = Comment()
c.user = request.user
c.body = form.cleaned_data['body']
c.save()
q.comments.add(c)
elif owner[0] == "a":
a = get_object_or_404(Answer, id=int(owner[1]))
c = Comment()
c.user = request.user
c.body = form.cleaned_data['body']
c.save()
a.comments.add(c)
kwargs = {
'question_id': question_id,
}
else:
q = get_object_or_404(Question, id=question_id)
kwargs = {
'question_id': question_id,
'form': form
}
return HttpResponseRedirect(reverse('catalog:question', kwargs=kwargs))
| [
"django.shortcuts.render",
"woot.apps.catalog.forms.CommentForm",
"woot.apps.catalog.models.forum.Question",
"django.shortcuts.get_object_or_404",
"django.core.urlresolvers.reverse",
"woot.apps.catalog.models.forum.Answer",
"woot.apps.catalog.forms.QuestionForm",
"woot.apps.catalog.forms.AnswerForm",
... | [((438, 481), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Question'], {'id': 'question_id'}), '(Question, id=question_id)\n', (455, 481), False, 'from django.shortcuts import get_object_or_404, render\n'), ((1083, 1137), 'django.shortcuts.render', 'render', (['request', '"""catalog/question_page.html"""', 'context'], {}), "(request, 'catalog/question_page.html', context)\n", (1089, 1137), False, 'from django.shortcuts import get_object_or_404, render\n'), ((1185, 1222), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Makey'], {'id': 'makey_id'}), '(Makey, id=makey_id)\n', (1202, 1222), False, 'from django.shortcuts import get_object_or_404, render\n'), ((1325, 1378), 'django.shortcuts.render', 'render', (['request', '"""catalog/ask_question.html"""', 'context'], {}), "(request, 'catalog/ask_question.html', context)\n", (1331, 1378), False, 'from django.shortcuts import get_object_or_404, render\n'), ((2067, 2092), 'woot.apps.catalog.forms.CommentForm', 'CommentForm', (['request.POST'], {}), '(request.POST)\n', (2078, 2092), False, 'from woot.apps.catalog.forms import QuestionForm, AnswerForm, CommentForm\n'), ((3032, 3074), 'django.core.urlresolvers.reverse', 'reverse', (['"""catalog:question"""'], {'kwargs': 'kwargs'}), "('catalog:question', kwargs=kwargs)\n", (3039, 3074), False, 'from django.core.urlresolvers import reverse\n'), ((649, 673), 'woot.apps.catalog.forms.AnswerForm', 'AnswerForm', (['request.POST'], {}), '(request.POST)\n', (659, 673), False, 'from woot.apps.catalog.forms import QuestionForm, AnswerForm, CommentForm\n'), ((1427, 1470), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['User'], {'id': 'request.user.id'}), '(User, id=request.user.id)\n', (1444, 1470), False, 'from django.shortcuts import get_object_or_404, render\n'), ((1486, 1512), 'woot.apps.catalog.forms.QuestionForm', 'QuestionForm', (['request.POST'], {}), '(request.POST)\n', (1498, 1512), False, 'from woot.apps.catalog.forms import QuestionForm, AnswerForm, CommentForm\n'), ((2846, 2889), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Question'], {'id': 'question_id'}), '(Question, id=question_id)\n', (2863, 2889), False, 'from django.shortcuts import get_object_or_404, render\n'), ((747, 755), 'woot.apps.catalog.models.forum.Answer', 'Answer', ([], {}), '()\n', (753, 755), False, 'from woot.apps.catalog.models.forum import Question, Answer\n'), ((1558, 1568), 'woot.apps.catalog.models.forum.Question', 'Question', ([], {}), '()\n', (1566, 1568), False, 'from woot.apps.catalog.models.forum import Question, Answer\n'), ((1882, 1935), 'django.shortcuts.render', 'render', (['request', '"""catalog/ask_question.html"""', 'context'], {}), "(request, 'catalog/ask_question.html', context)\n", (1888, 1935), False, 'from django.shortcuts import get_object_or_404, render\n'), ((2298, 2307), 'woot.apps.catalog.models.core.Comment', 'Comment', ([], {}), '()\n', (2305, 2307), False, 'from woot.apps.catalog.models.core import Makey, Comment\n'), ((1665, 1722), 'django.core.urlresolvers.reverse', 'reverse', (['"""catalog:question"""'], {'kwargs': "{'question_id': q.id}"}), "('catalog:question', kwargs={'question_id': q.id})\n", (1672, 1722), False, 'from django.core.urlresolvers import reverse\n'), ((2576, 2585), 'woot.apps.catalog.models.core.Comment', 'Comment', ([], {}), '()\n', (2583, 2585), False, 'from woot.apps.catalog.models.core import Makey, Comment\n')] |
"""计算分位数"""
from scipy import stats
import numpy as np
S = 47
N = 100
a = S + 1
b = (N -S) + 1
alpha = 0.05
lu = stats.beta.ppf([alpha/2, 1-alpha/2], a, b)
print(lu)
## MC方法
S = 1000
X = stats.beta.rvs(a, b, size=S)
X = np.sort(X, axis=0)
l = X[round(S*alpha/2)]
u = X[round(S*(1-alpha)/2)]
print(l,u) | [
"numpy.sort",
"scipy.stats.beta.rvs",
"scipy.stats.beta.ppf"
] | [((115, 163), 'scipy.stats.beta.ppf', 'stats.beta.ppf', (['[alpha / 2, 1 - alpha / 2]', 'a', 'b'], {}), '([alpha / 2, 1 - alpha / 2], a, b)\n', (129, 163), False, 'from scipy import stats\n'), ((190, 218), 'scipy.stats.beta.rvs', 'stats.beta.rvs', (['a', 'b'], {'size': 'S'}), '(a, b, size=S)\n', (204, 218), False, 'from scipy import stats\n'), ((223, 241), 'numpy.sort', 'np.sort', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (230, 241), True, 'import numpy as np\n')] |
from re_calc.config import *
from re_calc.exceptions import CalcException
from re_calc.util import is_number
import re_calc.meta_containers as meta_containers
def peek(stack):
return stack[-1]
def should_move_to_queue(stack, c_token_prc):
''' Checks token's precedence and associativity to decide if it should be
moved to the queue.
'''
if stack:
s_token = peek(stack)
s_token_prc = get_token_prop(s_token, 'prc')
s_token_assoc = get_token_prop(s_token, 'assoc')
return (s_token_prc > c_token_prc
or (s_token_prc == c_token_prc and
s_token_assoc == 'left')
and (s_token != '('))
else:
return False
def get_arity(fun):
''' Inspects function code object to get args count.
'''
return fun.__code__.co_argcount
def arity_is_valid(fn_token, rest_tokens):
''' Checks whether a function arguments list is valid.
'''
paren_balance = 1
properties = token_properties.get(fn_token)
op_function = properties.get('fun')
arity = get_arity(op_function)
expected_separator_count = arity - 1
arg_tokens = rest_tokens[1:]
token_idx = 0
separator_count = 0
while token_idx < len(arg_tokens) and paren_balance != 0:
c_token = arg_tokens[token_idx]
if c_token == '(':
paren_balance += 1
elif c_token == ')':
paren_balance -= 1
elif (c_token in separators) and (paren_balance == 1):
separator_count += 1
token_idx += 1
return expected_separator_count == separator_count
def infix_to_rpn(tokens):
''' Shunting yard algorithm implementation.
'''
meta_tokens = meta_containers.set_meta_indices(tokens)
output_queue = list()
stack = list()
for token in meta_tokens:
if is_number(token):
output_queue.append(token) # add number to queue
elif token in functions:
n_token_idx = token.meta + 1
if ((n_token_idx > len(meta_tokens) - 1)
or (meta_tokens[n_token_idx] != "(")):
raise CalcException(
token.meta,
meta_tokens,
message="Missing function args",
loc_string="t_missing_fn_args")
if not arity_is_valid(token, meta_tokens[token.meta + 1:]):
raise CalcException(
token.meta,
meta_tokens,
message="Invalid arity",
loc_string="t_invalid_arity")
stack.append(token) # add function to stack
elif token in separators:
if not stack or '(' not in stack:
raise CalcException(
token.meta,
meta_tokens,
message="Missing parentheses or separator",
loc_string="t_missing_separtor")
while stack and peek(stack) != "(":
output_queue.append(stack.pop()) # move operator to queue
elif token in operators:
if stack: # if stack's not empty
c_token_prc = get_token_prop(token, 'prc')
while should_move_to_queue(stack, c_token_prc):
output_queue.append(stack.pop()) # move operator to queue
stack.append(token) # add operator to stack
elif token == '(':
stack.append(token) # add open paren to stack
elif token == ')':
if not stack or '(' not in stack:
raise CalcException(
token.meta,
meta_tokens,
message="Missing open paren(s)",
loc_string="t_missing_l_paren")
while peek(stack) != '(':
output_queue.append(stack.pop()) # move operator or function to queue
if peek(stack) == '(':
stack.pop() # discard open paren
while stack: # move the rest of the stack to the queue
if peek(stack) in priorities:
raise CalcException(
peek(stack).meta,
meta_tokens,
message="Missing close paren(s)",
loc_string="t_missing_r_paren")
output_queue.append(stack.pop())
return meta_containers.pack_list(output_queue, tokens)
| [
"re_calc.util.is_number",
"re_calc.meta_containers.set_meta_indices",
"re_calc.exceptions.CalcException",
"re_calc.meta_containers.pack_list"
] | [((1709, 1749), 're_calc.meta_containers.set_meta_indices', 'meta_containers.set_meta_indices', (['tokens'], {}), '(tokens)\n', (1741, 1749), True, 'import re_calc.meta_containers as meta_containers\n'), ((4315, 4362), 're_calc.meta_containers.pack_list', 'meta_containers.pack_list', (['output_queue', 'tokens'], {}), '(output_queue, tokens)\n', (4340, 4362), True, 'import re_calc.meta_containers as meta_containers\n'), ((1836, 1852), 're_calc.util.is_number', 'is_number', (['token'], {}), '(token)\n', (1845, 1852), False, 'from re_calc.util import is_number\n'), ((2124, 2231), 're_calc.exceptions.CalcException', 'CalcException', (['token.meta', 'meta_tokens'], {'message': '"""Missing function args"""', 'loc_string': '"""t_missing_fn_args"""'}), "(token.meta, meta_tokens, message='Missing function args',\n loc_string='t_missing_fn_args')\n", (2137, 2231), False, 'from re_calc.exceptions import CalcException\n'), ((2403, 2501), 're_calc.exceptions.CalcException', 'CalcException', (['token.meta', 'meta_tokens'], {'message': '"""Invalid arity"""', 'loc_string': '"""t_invalid_arity"""'}), "(token.meta, meta_tokens, message='Invalid arity', loc_string=\n 't_invalid_arity')\n", (2416, 2501), False, 'from re_calc.exceptions import CalcException\n'), ((2737, 2857), 're_calc.exceptions.CalcException', 'CalcException', (['token.meta', 'meta_tokens'], {'message': '"""Missing parentheses or separator"""', 'loc_string': '"""t_missing_separtor"""'}), "(token.meta, meta_tokens, message=\n 'Missing parentheses or separator', loc_string='t_missing_separtor')\n", (2750, 2857), False, 'from re_calc.exceptions import CalcException\n'), ((3576, 3683), 're_calc.exceptions.CalcException', 'CalcException', (['token.meta', 'meta_tokens'], {'message': '"""Missing open paren(s)"""', 'loc_string': '"""t_missing_l_paren"""'}), "(token.meta, meta_tokens, message='Missing open paren(s)',\n loc_string='t_missing_l_paren')\n", (3589, 3683), False, 'from re_calc.exceptions import CalcException\n')] |
# Copyright (c) 2021 PPViT Authors. 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.
"""
Implement VOLO Class
"""
import math
import copy
import numpy as np
import paddle
import paddle.nn as nn
from droppath import DropPath
from fold import fold
#from utils import MyPrint
#myprint = MyPrint()
class Identity(nn.Layer):
""" Identity layer
The output of this layer is the input without any change.
Use this layer to avoid using 'if' condition in forward methods
"""
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
return x
class Downsample(nn.Layer):
"""Apply a Conv2D with kernel size = patch_size and stride = patch_size
The shape of input tensor is [N, H, W, C], which will be transposed to
[N, C, H, W] and feed into Conv, finally the output is transposed back
to [N, H, W, C].
Args:
in_embed_dim: int, input feature dimension
out_embed_dim: int, output feature dimension
patch_size: kernel_size and stride
"""
def __init__(self, in_embed_dim, out_embed_dim, patch_size):
super().__init__()
self.proj = nn.Conv2D(in_embed_dim,
out_embed_dim,
kernel_size=patch_size,
stride=patch_size)
def forward(self, x):
x = x.transpose([0, 3, 1, 2])
x = self.proj(x)
x = x.transpose([0, 2, 3, 1])
return x
class PatchEmbedding(nn.Layer):
"""Patch Embeddings with stem conv layers
If stem conv layers are set, the image is firstly feed into stem layers,
stem layers contains 3 conv-bn-relu blocks.
Then a proj (conv2d) layer is applied as the patch embedding.
Args:
image_size: int, input image size, default: 224
stem_conv: bool, if apply stem conv layers, default: False
stem_stride: int, conv stride in stem layers, default: 1
patch_size: int, patch size for patch embedding (k and stride for proj conv), default: 8
in_channels: int, input channels, default: 3
hidden_dim: int, input dimension of patch embedding (out dim for stem), default: 64
embed_dim: int, output dimension of patch embedding, default: 384
"""
def __init__(self,
image_size=224,
stem_conv=False,
stem_stride=1,
patch_size=8,
in_channels=3,
hidden_dim=64,
embed_dim=384):
super().__init__()
assert patch_size in [4, 8, 16]
# define stem conv layers
if stem_conv:
self.stem = nn.Sequential(
nn.Conv2D(in_channels,
hidden_dim,
kernel_size=7,
stride=stem_stride,
padding=3,
bias_attr=False),
nn.BatchNorm2D(hidden_dim, momentum=0.9),
nn.ReLU(),
nn.Conv2D(hidden_dim,
hidden_dim,
kernel_size=3,
stride=1,
padding=1,
bias_attr=False),
nn.BatchNorm2D(hidden_dim, momentum=0.9),
nn.ReLU(),
nn.Conv2D(hidden_dim,
hidden_dim,
kernel_size=3,
stride=1,
padding=1,
bias_attr=False),
nn.BatchNorm2D(hidden_dim, momentum=0.9),
nn.ReLU(),
)
else:
self.stem = Identity()
# define patch embeddings
self.proj = nn.Conv2D(hidden_dim,
embed_dim,
kernel_size = patch_size // stem_stride,
stride = patch_size // stem_stride)
# num patches
self.num_patches = (image_size // patch_size) * (image_size // patch_size)
def forward(self, x):
x = self.stem(x) # Identity layer if stem is not set
x = self.proj(x)
return x
class Mlp(nn.Layer):
""" MLP module
Impl using nn.Linear and activation is GELU, dropout is applied.
Ops: fc -> act -> dropout -> fc -> dropout
Attributes:
fc1: nn.Linear
fc2: nn.Linear
act: GELU
dropout1: dropout after fc1
dropout2: dropout after fc2
"""
def __init__(self, in_features, hidden_features, dropout=0.):
super(Mlp, self).__init__()
w_attr_1, b_attr_1 = self._init_weights()
self.fc1 = nn.Linear(in_features,
hidden_features,
weight_attr=w_attr_1,
bias_attr=b_attr_1)
w_attr_2, b_attr_2 = self._init_weights()
self.fc2 = nn.Linear(hidden_features,
in_features,
weight_attr=w_attr_2,
bias_attr=b_attr_2)
self.act = nn.GELU()
self.dropout = nn.Dropout(dropout)
def _init_weights(self):
weight_attr = paddle.ParamAttr(initializer=paddle.nn.initializer.XavierUniform())
bias_attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Normal(std=1e-6))
return weight_attr, bias_attr
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.dropout(x)
x = self.fc2(x)
x = self.dropout(x)
return x
class OutlookerAttention(nn.Layer):
""" Outlooker Attention
Outlooker attention firstly applies a nn.Linear op, and unfold (im2col) the output
tensor, then use tensor reshape to get the 'V'. 'Attn' is obtained by pool, linear and reshape
ops applied on input tensor. Then a matmul is applied for 'V' and 'Attn'. Finally, a
fold op is applied with a linear projection to get the output.
Args:
dim: int, all heads dimension
num_heads: int, num of heads
kernel_size: int, size used in fold/unfold, and pool, default: 3
padding: int, pad used in fold/unfold, default: 1
stride: int, stride used in fold/unfold, and pool, default: 1
qkv_bias: bool, if True, qkv linear layer is using bias, default: False
qk_scale: float, if None, qk_scale is dim_head ** -0.5, default: None
attention_dropout: float, dropout rate for attention dropout, default: 0.
dropout: float, dropout rate for projection dropout, default: 0.
"""
def __init__(self,
dim,
num_heads,
kernel_size=3,
padding=1,
stride=1,
qkv_bias=False,
qk_scale=None,
attention_dropout=0.,
dropout=0.):
super().__init__()
self.num_heads = num_heads
self.dim = dim
self.dim_head = dim // num_heads
self.scale = qk_scale or self.dim_head ** -0.5
self.kernel_size = kernel_size
self.padding = padding
self.stride = stride
self.v = nn.Linear(dim, dim, bias_attr=qkv_bias)
self.attn = nn.Linear(dim, (kernel_size ** 4) * num_heads)
self.attn_dropout = nn.Dropout(attention_dropout)
self.proj = nn.Linear(dim, dim)
self.proj_dropout = nn.Dropout(dropout)
self.softmax = nn.Softmax(axis=-1)
self.pool = nn.AvgPool2D(kernel_size=stride, stride=stride, ceil_mode=True)
self.unfold = paddle.nn.Unfold(kernel_sizes=kernel_size, strides=self.stride, paddings=self.padding)
def forward(self, x):
B, H, W, C = x.shape
v = self.v(x) # B, H, W, C
v = v.transpose([0, 3, 1, 2]) # B, C, H, W
h, w = math.ceil(H / self.stride), math.ceil(W / self.stride)
# current paddle version has bugs using nn.Unfold
v = paddle.nn.functional.unfold(v,
kernel_sizes=self.kernel_size,
paddings=self.padding,
strides=self.stride) # B, C*kernel_size*kernel_size, L(num of patches)
v = v.reshape([B,
self.num_heads,
C // self.num_heads,
self.kernel_size * self.kernel_size,
h * w])
v = v.transpose([0, 1, 4, 3, 2])
x = x.transpose([0, 3, 1, 2])
attn = self.pool(x)
attn = attn.transpose([0, 2, 3, 1]) # B, H', W', C
attn = self.attn(attn)
attn = attn.reshape([B,
h*w,
self.num_heads,
self.kernel_size * self.kernel_size,
self.kernel_size * self.kernel_size])
attn = attn.transpose([0, 2, 1, 3, 4])
attn = attn * self.scale
attn = self.softmax(attn)
attn = self.attn_dropout(attn)
z = paddle.matmul(attn, v)
z = z.transpose([0, 1, 4, 3, 2])
new_shape = [B, C * self.kernel_size * self.kernel_size, h * w]
z = z.reshape(new_shape)
# Current Paddle dose not have Fold op, we hacked our fold op, see ./fold.py for details
z = fold(z, output_size=(H, W), kernel_size=self.kernel_size,
padding=self.padding, stride=self.stride)
z = z.transpose([0, 2, 3, 1])
z = self.proj(z)
z = self.proj_dropout(z)
return z
class Outlooker(nn.Layer):
""" Outlooker
Outlooker contains norm layers, outlooker attention, mlp and droppath layers,
and residual is applied during forward.
Args:
dim: int, all heads dimension
num_heads: int, num of heads
kernel_size: int, size used in fold/unfold, and pool, default: 3
padding: int, pad used in fold/unfold, default: 1
mlp_ratio: float, ratio to multiply with dim for mlp hidden feature dim, default: 3.
stride: int, stride used in fold/unfold, and pool, default: 1
qkv_bias: bool, if True, qkv linear layer is using bias, default: False
qk_scale: float, if None, qk_scale is dim_head ** -0.5, default: None
attention_dropout: float, dropout rate for attention dropout, default: 0.
dropout: float, dropout rate for projection dropout, default: 0.
"""
def __init__(self,
dim,
kernel_size,
padding,
stride=1,
num_heads=1,
mlp_ratio=3.,
attention_dropout=0.,
droppath=0.,
qkv_bias=False,
qk_scale=None):
super().__init__()
self.norm1 = nn.LayerNorm(dim)
self.attn = OutlookerAttention(dim,
num_heads,
kernel_size=kernel_size,
padding=padding,
stride=stride,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
attention_dropout=attention_dropout)
self.drop_path = Droppath(droppath) if droppath > 0. else Identity()
self.norm2 = nn.LayerNorm(dim)
self.mlp = Mlp(in_features=dim,
hidden_features=int(dim * mlp_ratio))
def forward(self, x):
h = x
x = self.norm1(x)
x = self.attn(x)
x = self.drop_path(x)
x = h + x
h = x
x = self.norm2(x)
x = self.mlp(x)
x = self.drop_path(x)
x = h + x
return x
class Attention(nn.Layer):
""" Attention
Regular Attention module same as ViT
Args:
dim: int, all heads dimension
num_heads: int, num of heads
qkv_bias: bool, if True, qkv linear layer is using bias, default: False
qk_scale: float, if None, qk_scale is dim_head ** -0.5, default: None
attention_dropout: float, dropout rate for attention dropout, default: 0.
dropout: float, dropout rate for projection dropout, default: 0.
"""
def __init__(self,
dim,
num_heads=8,
qkv_bias=False,
qk_scale=None,
attention_dropout=0.,
dropout=0.):
super().__init__()
self.num_heads = num_heads
self.dim_head = dim // num_heads
self.scale = qk_scale or self.dim_head ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias_attr=qkv_bias)
self.attn_dropout = nn.Dropout(attention_dropout)
self.softmax = nn.Softmax(axis=-1)
self.proj = nn.Linear(dim, dim)
self.proj_dropout = nn.Dropout(dropout)
def forward(self, x):
B, H, W, C = x.shape
qkv = self.qkv(x)
qkv = qkv.reshape([B, H * W, 3, self.num_heads, C // self.num_heads])
qkv = qkv.transpose([2, 0, 3, 1, 4])
q, k, v = qkv[0], qkv[1], qkv[2]
attn = paddle.matmul(q, k, transpose_y=True)
attn = attn * self.scale
attn = self.softmax(attn)
attn = self.attn_dropout(attn)
z = paddle.matmul(attn, v)
z = z.transpose([0, 2, 1, 3])
z = z.reshape([B, H, W, C])
z = self.proj(z)
z = self.proj_dropout(z)
return z
class Transformer(nn.Layer):
"""Transformer
Transformer module, same as ViT
Args:
dim: int, all heads dimension
num_heads: int, num of heads
mlp_ratio: float, ratio to multiply with dim for mlp hidden feature dim, default: 4.
qkv_bias: bool, if True, qkv linear layer is using bias, default: False
qk_scale: float, if None, qk_scale is dim_head ** -0.5, default: None
attention_dropout: float, dropout rate for attention dropout, default: 0.
dropout: float, dropout rate for projection dropout, default: 0.
"""
def __init__(self,
dim,
num_heads,
mlp_ratio=4.,
qkv_bias=False,
qk_scale=None,
attention_dropout=0,
droppath=0.):
super().__init__()
self.norm1 = nn.LayerNorm(dim)
self.attn = Attention(dim,
num_heads=num_heads,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
attention_dropout=attention_dropout)
self.drop_path = DropPath(droppath) if droppath > 0. else Identity()
self.norm2 = nn.LayerNorm(dim)
self.mlp = Mlp(in_features=dim,
hidden_features=int(dim * mlp_ratio))
def forward(self, x):
h = x
x = self.norm1(x)
x = self.attn(x)
x = self.drop_path(x)
x = h + x
h = x
x = self.norm2(x)
x = self.mlp(x)
x = self.drop_path(x)
x = h + x
return x
class ClassAttention(nn.Layer):
""" Class Attention
Class Attention modlee same as CaiT
Args:
dim: int, all heads dimension
dim_head: int, single heads dimension, default: None
num_heads: int, num of heads
qkv_bias: bool, if True, qkv linear layer is using bias, default: False
qk_scale: float, if None, qk_scale is dim_head ** -0.5, default: None
attention_dropout: float, dropout rate for attention dropout, default: 0.
dropout: float, dropout rate for projection dropout, default: 0.
"""
def __init__(self,
dim,
num_heads=8,
dim_head=None,
qkv_bias=False,
qk_scale=None,
attention_dropout=0.,
dropout=0.):
super().__init__()
self.num_heads = num_heads
if dim_head is not None:
self.dim_head = dim_head
else:
self.dim_head = dim // num_heads
self.scale = qk_scale or self.dim_head ** -0.5
self.kv = nn.Linear(dim,
self.dim_head * self.num_heads * 2,
bias_attr=qkv_bias)
self.q = nn.Linear(dim,
self.dim_head * self.num_heads,
bias_attr=qkv_bias)
self.attn_dropout = nn.Dropout(attention_dropout)
self.proj = nn.Linear(self.dim_head * self.num_heads, dim)
self.proj_dropout = nn.Dropout(dropout)
self.softmax = nn.Softmax(axis=-1)
def forward(self, x):
B, N, C = x.shape
kv = self.kv(x)
kv = kv.reshape([B, N, 2, self.num_heads, self.dim_head])
kv = kv.transpose([2, 0, 3, 1, 4])
k, v = kv[0], kv[1]
q = self.q(x[:, :1, :])
q = q.reshape([B, self.num_heads, 1, self.dim_head])
attn = paddle.matmul(q * self.scale, k, transpose_y=True)
attn = self.softmax(attn)
attn = self.attn_dropout(attn)
cls_embed = paddle.matmul(attn, v)
cls_embed = cls_embed.transpose([0, 2, 1, 3])
cls_embed = cls_embed.reshape([B, 1, self.dim_head * self.num_heads])
cls_embed = self.proj(cls_embed)
cls_embed = self.proj_dropout(cls_embed)
return cls_embed
class ClassBlock(nn.Layer):
"""Class Attention Block (CaiT)
CaiT module
Args:
dim: int, all heads dimension
num_heads: int, num of heads
mlp_ratio: float, ratio to multiply with dim for mlp hidden feature dim, default: 4.
qkv_bias: bool, if True, qkv linear layer is using bias, default: False
qk_scale: float, if None, qk_scale is dim_head ** -0.5, default: None
attention_dropout: float, dropout rate for attention dropout, default: 0.
dropout: float, dropout rate for projection dropout, default: 0.
"""
def __init__(self,
dim,
num_heads,
dim_head=None,
mlp_ratio=4.,
qkv_bias=False,
qk_scale=None,
dropout=0.,
attention_dropout=0.,
droppath=0.):
super().__init__()
self.norm1 = nn.LayerNorm(dim)
self.attn = ClassAttention(dim,
num_heads=num_heads,
dim_head=dim_head,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
attention_dropout=attention_dropout,
dropout=dropout)
self.drop_path = DropPath(droppath) if droppath > 0. else Identity()
self.norm2 = nn.LayerNorm(dim)
self.mlp = Mlp(in_features=dim,
hidden_features=int(dim * mlp_ratio),
dropout=dropout)
def forward(self, x):
cls_embed = x[:, :1]
h = self.norm1(x)
h = self.attn(h)
h = self.drop_path(h)
cls_embed = cls_embed + h
h = cls_embed
cls_embed = self.norm2(cls_embed)
cls_embed = self.mlp(cls_embed)
cls_embed = self.drop_path(cls_embed)
cls_embed = h + cls_embed
out = paddle.concat([cls_embed, x[:, 1:]], axis=1)
return out
def rand_bbox(size, lam, scale=1):
"""
get bounding box as token labeling (https://github.com/zihangJiang/TokenLabeling)
return: bounding box
"""
W = size[1] // scale
H = size[2] // scale
cut_rat = np.sqrt(1. - lam)
cut_w = np.int(W * cut_rat)
cut_h = np.int(H * cut_rat)
# uniform
cx = np.random.randint(W)
cy = np.random.randint(H)
bbx1 = np.clip(cx - cut_w // 2, 0, W)
bby1 = np.clip(cy - cut_h // 2, 0, H)
bbx2 = np.clip(cx + cut_w // 2, 0, W)
bby2 = np.clip(cy + cut_h // 2, 0, H)
# item() get the python native dtype
return bbx1.item(), bby1.item(), bbx2.item(), bby2.item()
class VOLO(nn.Layer):
def __init__(self,
layers,
image_size=224,
in_channels=3,
num_classes=1000,
patch_size=8,
stem_hidden_dim=64,
embed_dims=None,
num_heads=None,
downsamples=None,
outlook_attention=None,
mlp_ratios=None,
qkv_bias=False,
qk_scale=None,
dropout=0.,
attention_dropout=0.,
droppath=0.,
num_post_layers=2,
return_mean=False,
return_dense=True,
mix_token=True,
pooling_scale=2,
out_kernel=3,
out_stride=2,
out_padding=1):
super().__init__()
self.num_classes = num_classes
self.patch_embed = PatchEmbedding(image_size=image_size,
stem_conv=True,
stem_stride=2,
patch_size=patch_size,
in_channels=in_channels,
hidden_dim=stem_hidden_dim,
embed_dim=embed_dims[0])
self.pos_embed = paddle.create_parameter(
shape=[1,
image_size // patch_size // pooling_scale,
image_size // patch_size // pooling_scale,
embed_dims[-1]],
dtype='float32',
default_initializer=nn.initializer.Constant(0.0))
self.pos_dropout = nn.Dropout(dropout)
layer_list = []
for i in range(len(layers)):
blocks = []
for block_idx in range(layers[i]):
block_droppath = droppath * (
block_idx + sum(layers[:i])) / (sum(layers) - 1)
if outlook_attention[i]:
blocks.append(
copy.deepcopy(
Outlooker(dim=embed_dims[i],
kernel_size=out_kernel,
padding=out_padding,
stride=out_stride,
num_heads=num_heads[i],
mlp_ratio=mlp_ratios[i],
qkv_bias=qkv_bias,
qk_scale=qk_scale,
attention_dropout=attention_dropout,
droppath=block_droppath)))
else:
blocks.append(
copy.deepcopy(
Transformer(dim=embed_dims[i],
num_heads=num_heads[i],
mlp_ratio=mlp_ratios[i],
qkv_bias=qkv_bias,
qk_scale=qk_scale,
attention_dropout=attention_dropout,
droppath=block_droppath))
)
stage = nn.Sequential(*blocks)
layer_list.append(stage)
if downsamples[i]:
layer_list.append(copy.deepcopy(Downsample(embed_dims[i], embed_dims[i + 1], 2)))
self.model = nn.LayerList(layer_list)
# POST Layers (from CaiT)
self.post_model = None
if num_post_layers is not None:
self.post_model = nn.LayerList([
copy.deepcopy(
ClassBlock(dim=embed_dims[-1],
num_heads=num_heads[-1],
mlp_ratio=mlp_ratios[-1],
qkv_bias=qkv_bias,
qk_scale=qk_scale,
attention_dropout=attention_dropout,
droppath=0.)
) for i in range(num_post_layers)
])
self.cls_token = paddle.create_parameter(
shape=[1, 1, embed_dims[-1]],
dtype='float32',
default_initializer=nn.initializer.TruncatedNormal(std=.02))
# Output
self.return_mean = return_mean # if True, return mean, not use class token
self.return_dense = return_dense # if True, return class token and all feature tokens
if return_dense:
assert not return_mean, "Cannot return both mean and dense"
self.mix_token = mix_token
self.pooling_scale = pooling_scale
if mix_token:
self.beta = 1.0
assert return_dense, 'return all tokens if mix_token is enabled'
if return_dense:
self.aux_head = nn.Linear(embed_dims[-1], num_classes) if num_classes > 0 else Identity()
self.norm = nn.LayerNorm(embed_dims[-1])
self.head = nn.Linear(embed_dims[-1], num_classes) if num_classes > 0 else Identity()
# For training:
# TODO: set pos_embed, trunc_normal
# TODO: set init weights for linear layers and layernorm layers
# TODO: set no weight decay for pos_embed and cls_token
def forward(self, x):
# Step1: patch embedding
x = self.patch_embed(x)
x = x.transpose([0, 2, 3, 1])
if self.mix_token and self.training:
lam = np.random.beta(self.beta, self.beta)
patch_h = x.shape[1] // self.pooling_scale
patch_w = x.shape[2] // self.pooling_scale
bbx1, bby1, bbx2, bby2 = rand_bbox(x.shape, lam, scale=self.pooling_scale)
temp_x = x.clone()
sbbx1 = self.pooling_scale * bbx1
sbby1 = self.pooling_scale * bby1
sbbx2 = self.pooling_scale * bbx2
sbby2 = self.pooling_scale * bby2
temp_x[:, sbbx1: sbbx2, sbby1: sbby2, :] = x.flip(axis=[0])[:, sbbx1: sbbx2, sbby1: sbby2, :]
x = temp_x
else:
bbx1, bby1, bbx2, bby2 = 0, 0, 0, 0
# Step2: 2-stages tokens learning
for idx, block in enumerate(self.model):
if idx == 2: # add pos_embed after outlooker blocks (and a downsample layer)
x = x + self.pos_embed
x = self.pos_dropout(x)
x = block(x)
x = x.reshape([x.shape[0], -1, x.shape[-1]]) # B, H*W, C
# Step3: post layers (from CaiT)
if self.post_model is not None:
cls_token = self.cls_token.expand([x.shape[0], -1, -1])
x = paddle.concat([cls_token, x], axis=1)
for block in self.post_model:
x = block(x)
x = self.norm(x)
if self.return_mean:
return self.head(x.mean(1))
x_cls = self.head(x[:, 0])
if not self.return_dense:
return x_cls
x_aux = self.aux_head(x[:, 1:])
if not self.training:
#NOTE: pytorch Tensor.max() returns a tuple of Tensor: (values, indices), while
# paddle Tensor.max() returns a single Tensor: values
return x_cls + 0.5 * x_aux.max(1)
if self.mix_token and self.training:
x_aux = x_aux.reshape([x_aux.shape[0], patch_h, patch_w, x_aux.shape[-1]])
temp_x = x_aux.clone()
temp_x[:, bbx1:bbx2, bby1:bby2, :] = x_aux.flip(axis=[0])[:, bbx1:bbx2, bby1:bby2, :]
x_aux = temp_x
x_aux = x_aux.reshape([x_aux.shape[0], patch_h*patch_w, x_aux.shape[-1]])
return x_cls, x_aux, (bbx1, bby1, bbx2, bby2)
def build_volo(config):
"""build volo model using config"""
model = VOLO(image_size=config.DATA.IMAGE_SIZE,
layers=config.MODEL.TRANS.LAYERS,
embed_dims=config.MODEL.TRANS.EMBED_DIMS,
mlp_ratios=config.MODEL.TRANS.MLP_RATIOS,
downsamples=config.MODEL.TRANS.DOWNSAMPLES,
outlook_attention=config.MODEL.TRANS.OUTLOOK_ATTENTION,
stem_hidden_dim=config.MODEL.STEM_HIDDEN_DIM,
num_heads=config.MODEL.TRANS.NUM_HEADS,
qkv_bias=config.MODEL.TRANS.QKV_BIAS,
qk_scale=config.MODEL.TRANS.QK_SCALE)
return model
| [
"numpy.clip",
"numpy.sqrt",
"paddle.matmul",
"paddle.nn.Sequential",
"paddle.nn.LayerNorm",
"paddle.nn.LayerList",
"fold.fold",
"paddle.nn.AvgPool2D",
"numpy.random.beta",
"paddle.nn.initializer.XavierUniform",
"paddle.nn.Softmax",
"paddle.nn.Unfold",
"paddle.nn.Linear",
"paddle.nn.initial... | [((20249, 20267), 'numpy.sqrt', 'np.sqrt', (['(1.0 - lam)'], {}), '(1.0 - lam)\n', (20256, 20267), True, 'import numpy as np\n'), ((20279, 20298), 'numpy.int', 'np.int', (['(W * cut_rat)'], {}), '(W * cut_rat)\n', (20285, 20298), True, 'import numpy as np\n'), ((20311, 20330), 'numpy.int', 'np.int', (['(H * cut_rat)'], {}), '(H * cut_rat)\n', (20317, 20330), True, 'import numpy as np\n'), ((20355, 20375), 'numpy.random.randint', 'np.random.randint', (['W'], {}), '(W)\n', (20372, 20375), True, 'import numpy as np\n'), ((20385, 20405), 'numpy.random.randint', 'np.random.randint', (['H'], {}), '(H)\n', (20402, 20405), True, 'import numpy as np\n'), ((20418, 20448), 'numpy.clip', 'np.clip', (['(cx - cut_w // 2)', '(0)', 'W'], {}), '(cx - cut_w // 2, 0, W)\n', (20425, 20448), True, 'import numpy as np\n'), ((20460, 20490), 'numpy.clip', 'np.clip', (['(cy - cut_h // 2)', '(0)', 'H'], {}), '(cy - cut_h // 2, 0, H)\n', (20467, 20490), True, 'import numpy as np\n'), ((20502, 20532), 'numpy.clip', 'np.clip', (['(cx + cut_w // 2)', '(0)', 'W'], {}), '(cx + cut_w // 2, 0, W)\n', (20509, 20532), True, 'import numpy as np\n'), ((20544, 20574), 'numpy.clip', 'np.clip', (['(cy + cut_h // 2)', '(0)', 'H'], {}), '(cy + cut_h // 2, 0, H)\n', (20551, 20574), True, 'import numpy as np\n'), ((1670, 1756), 'paddle.nn.Conv2D', 'nn.Conv2D', (['in_embed_dim', 'out_embed_dim'], {'kernel_size': 'patch_size', 'stride': 'patch_size'}), '(in_embed_dim, out_embed_dim, kernel_size=patch_size, stride=\n patch_size)\n', (1679, 1756), True, 'import paddle.nn as nn\n'), ((4290, 4399), 'paddle.nn.Conv2D', 'nn.Conv2D', (['hidden_dim', 'embed_dim'], {'kernel_size': '(patch_size // stem_stride)', 'stride': '(patch_size // stem_stride)'}), '(hidden_dim, embed_dim, kernel_size=patch_size // stem_stride,\n stride=patch_size // stem_stride)\n', (4299, 4399), True, 'import paddle.nn as nn\n'), ((5229, 5315), 'paddle.nn.Linear', 'nn.Linear', (['in_features', 'hidden_features'], {'weight_attr': 'w_attr_1', 'bias_attr': 'b_attr_1'}), '(in_features, hidden_features, weight_attr=w_attr_1, bias_attr=\n b_attr_1)\n', (5238, 5315), True, 'import paddle.nn as nn\n'), ((5472, 5558), 'paddle.nn.Linear', 'nn.Linear', (['hidden_features', 'in_features'], {'weight_attr': 'w_attr_2', 'bias_attr': 'b_attr_2'}), '(hidden_features, in_features, weight_attr=w_attr_2, bias_attr=\n b_attr_2)\n', (5481, 5558), True, 'import paddle.nn as nn\n'), ((5660, 5669), 'paddle.nn.GELU', 'nn.GELU', ([], {}), '()\n', (5667, 5669), True, 'import paddle.nn as nn\n'), ((5693, 5712), 'paddle.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (5703, 5712), True, 'import paddle.nn as nn\n'), ((7760, 7799), 'paddle.nn.Linear', 'nn.Linear', (['dim', 'dim'], {'bias_attr': 'qkv_bias'}), '(dim, dim, bias_attr=qkv_bias)\n', (7769, 7799), True, 'import paddle.nn as nn\n'), ((7820, 7864), 'paddle.nn.Linear', 'nn.Linear', (['dim', '(kernel_size ** 4 * num_heads)'], {}), '(dim, kernel_size ** 4 * num_heads)\n', (7829, 7864), True, 'import paddle.nn as nn\n'), ((7895, 7924), 'paddle.nn.Dropout', 'nn.Dropout', (['attention_dropout'], {}), '(attention_dropout)\n', (7905, 7924), True, 'import paddle.nn as nn\n'), ((7946, 7965), 'paddle.nn.Linear', 'nn.Linear', (['dim', 'dim'], {}), '(dim, dim)\n', (7955, 7965), True, 'import paddle.nn as nn\n'), ((7994, 8013), 'paddle.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (8004, 8013), True, 'import paddle.nn as nn\n'), ((8037, 8056), 'paddle.nn.Softmax', 'nn.Softmax', ([], {'axis': '(-1)'}), '(axis=-1)\n', (8047, 8056), True, 'import paddle.nn as nn\n'), ((8078, 8141), 'paddle.nn.AvgPool2D', 'nn.AvgPool2D', ([], {'kernel_size': 'stride', 'stride': 'stride', 'ceil_mode': '(True)'}), '(kernel_size=stride, stride=stride, ceil_mode=True)\n', (8090, 8141), True, 'import paddle.nn as nn\n'), ((8165, 8256), 'paddle.nn.Unfold', 'paddle.nn.Unfold', ([], {'kernel_sizes': 'kernel_size', 'strides': 'self.stride', 'paddings': 'self.padding'}), '(kernel_sizes=kernel_size, strides=self.stride, paddings=\n self.padding)\n', (8181, 8256), False, 'import paddle\n'), ((8538, 8648), 'paddle.nn.functional.unfold', 'paddle.nn.functional.unfold', (['v'], {'kernel_sizes': 'self.kernel_size', 'paddings': 'self.padding', 'strides': 'self.stride'}), '(v, kernel_sizes=self.kernel_size, paddings=self\n .padding, strides=self.stride)\n', (8565, 8648), False, 'import paddle\n'), ((9626, 9648), 'paddle.matmul', 'paddle.matmul', (['attn', 'v'], {}), '(attn, v)\n', (9639, 9648), False, 'import paddle\n'), ((9905, 10009), 'fold.fold', 'fold', (['z'], {'output_size': '(H, W)', 'kernel_size': 'self.kernel_size', 'padding': 'self.padding', 'stride': 'self.stride'}), '(z, output_size=(H, W), kernel_size=self.kernel_size, padding=self.\n padding, stride=self.stride)\n', (9909, 10009), False, 'from fold import fold\n'), ((11387, 11404), 'paddle.nn.LayerNorm', 'nn.LayerNorm', (['dim'], {}), '(dim)\n', (11399, 11404), True, 'import paddle.nn as nn\n'), ((11963, 11980), 'paddle.nn.LayerNorm', 'nn.LayerNorm', (['dim'], {}), '(dim)\n', (11975, 11980), True, 'import paddle.nn as nn\n'), ((13236, 13279), 'paddle.nn.Linear', 'nn.Linear', (['dim', '(dim * 3)'], {'bias_attr': 'qkv_bias'}), '(dim, dim * 3, bias_attr=qkv_bias)\n', (13245, 13279), True, 'import paddle.nn as nn\n'), ((13308, 13337), 'paddle.nn.Dropout', 'nn.Dropout', (['attention_dropout'], {}), '(attention_dropout)\n', (13318, 13337), True, 'import paddle.nn as nn\n'), ((13361, 13380), 'paddle.nn.Softmax', 'nn.Softmax', ([], {'axis': '(-1)'}), '(axis=-1)\n', (13371, 13380), True, 'import paddle.nn as nn\n'), ((13401, 13420), 'paddle.nn.Linear', 'nn.Linear', (['dim', 'dim'], {}), '(dim, dim)\n', (13410, 13420), True, 'import paddle.nn as nn\n'), ((13449, 13468), 'paddle.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (13459, 13468), True, 'import paddle.nn as nn\n'), ((13733, 13770), 'paddle.matmul', 'paddle.matmul', (['q', 'k'], {'transpose_y': '(True)'}), '(q, k, transpose_y=True)\n', (13746, 13770), False, 'import paddle\n'), ((13890, 13912), 'paddle.matmul', 'paddle.matmul', (['attn', 'v'], {}), '(attn, v)\n', (13903, 13912), False, 'import paddle\n'), ((14938, 14955), 'paddle.nn.LayerNorm', 'nn.LayerNorm', (['dim'], {}), '(dim)\n', (14950, 14955), True, 'import paddle.nn as nn\n'), ((15305, 15322), 'paddle.nn.LayerNorm', 'nn.LayerNorm', (['dim'], {}), '(dim)\n', (15317, 15322), True, 'import paddle.nn as nn\n'), ((16774, 16844), 'paddle.nn.Linear', 'nn.Linear', (['dim', '(self.dim_head * self.num_heads * 2)'], {'bias_attr': 'qkv_bias'}), '(dim, self.dim_head * self.num_heads * 2, bias_attr=qkv_bias)\n', (16783, 16844), True, 'import paddle.nn as nn\n'), ((16918, 16984), 'paddle.nn.Linear', 'nn.Linear', (['dim', '(self.dim_head * self.num_heads)'], {'bias_attr': 'qkv_bias'}), '(dim, self.dim_head * self.num_heads, bias_attr=qkv_bias)\n', (16927, 16984), True, 'import paddle.nn as nn\n'), ((17067, 17096), 'paddle.nn.Dropout', 'nn.Dropout', (['attention_dropout'], {}), '(attention_dropout)\n', (17077, 17096), True, 'import paddle.nn as nn\n'), ((17117, 17163), 'paddle.nn.Linear', 'nn.Linear', (['(self.dim_head * self.num_heads)', 'dim'], {}), '(self.dim_head * self.num_heads, dim)\n', (17126, 17163), True, 'import paddle.nn as nn\n'), ((17192, 17211), 'paddle.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (17202, 17211), True, 'import paddle.nn as nn\n'), ((17235, 17254), 'paddle.nn.Softmax', 'nn.Softmax', ([], {'axis': '(-1)'}), '(axis=-1)\n', (17245, 17254), True, 'import paddle.nn as nn\n'), ((17578, 17628), 'paddle.matmul', 'paddle.matmul', (['(q * self.scale)', 'k'], {'transpose_y': '(True)'}), '(q * self.scale, k, transpose_y=True)\n', (17591, 17628), False, 'import paddle\n'), ((17723, 17745), 'paddle.matmul', 'paddle.matmul', (['attn', 'v'], {}), '(attn, v)\n', (17736, 17745), False, 'import paddle\n'), ((18929, 18946), 'paddle.nn.LayerNorm', 'nn.LayerNorm', (['dim'], {}), '(dim)\n', (18941, 18946), True, 'import paddle.nn as nn\n'), ((19427, 19444), 'paddle.nn.LayerNorm', 'nn.LayerNorm', (['dim'], {}), '(dim)\n', (19439, 19444), True, 'import paddle.nn as nn\n'), ((19956, 20000), 'paddle.concat', 'paddle.concat', (['[cls_embed, x[:, 1:]]'], {'axis': '(1)'}), '([cls_embed, x[:, 1:]], axis=1)\n', (19969, 20000), False, 'import paddle\n'), ((22340, 22359), 'paddle.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (22350, 22359), True, 'import paddle.nn as nn\n'), ((24072, 24096), 'paddle.nn.LayerList', 'nn.LayerList', (['layer_list'], {}), '(layer_list)\n', (24084, 24096), True, 'import paddle.nn as nn\n'), ((25575, 25603), 'paddle.nn.LayerNorm', 'nn.LayerNorm', (['embed_dims[-1]'], {}), '(embed_dims[-1])\n', (25587, 25603), True, 'import paddle.nn as nn\n'), ((8411, 8437), 'math.ceil', 'math.ceil', (['(H / self.stride)'], {}), '(H / self.stride)\n', (8420, 8437), False, 'import math\n'), ((8439, 8465), 'math.ceil', 'math.ceil', (['(W / self.stride)'], {}), '(W / self.stride)\n', (8448, 8465), False, 'import math\n'), ((15232, 15250), 'droppath.DropPath', 'DropPath', (['droppath'], {}), '(droppath)\n', (15240, 15250), False, 'from droppath import DropPath\n'), ((19354, 19372), 'droppath.DropPath', 'DropPath', (['droppath'], {}), '(droppath)\n', (19362, 19372), False, 'from droppath import DropPath\n'), ((23860, 23882), 'paddle.nn.Sequential', 'nn.Sequential', (['*blocks'], {}), '(*blocks)\n', (23873, 23882), True, 'import paddle.nn as nn\n'), ((25625, 25663), 'paddle.nn.Linear', 'nn.Linear', (['embed_dims[-1]', 'num_classes'], {}), '(embed_dims[-1], num_classes)\n', (25634, 25663), True, 'import paddle.nn as nn\n'), ((26098, 26134), 'numpy.random.beta', 'np.random.beta', (['self.beta', 'self.beta'], {}), '(self.beta, self.beta)\n', (26112, 26134), True, 'import numpy as np\n'), ((27253, 27290), 'paddle.concat', 'paddle.concat', (['[cls_token, x]'], {'axis': '(1)'}), '([cls_token, x], axis=1)\n', (27266, 27290), False, 'import paddle\n'), ((3220, 3321), 'paddle.nn.Conv2D', 'nn.Conv2D', (['in_channels', 'hidden_dim'], {'kernel_size': '(7)', 'stride': 'stem_stride', 'padding': '(3)', 'bias_attr': '(False)'}), '(in_channels, hidden_dim, kernel_size=7, stride=stem_stride,\n padding=3, bias_attr=False)\n', (3229, 3321), True, 'import paddle.nn as nn\n'), ((3465, 3505), 'paddle.nn.BatchNorm2D', 'nn.BatchNorm2D', (['hidden_dim'], {'momentum': '(0.9)'}), '(hidden_dim, momentum=0.9)\n', (3479, 3505), True, 'import paddle.nn as nn\n'), ((3523, 3532), 'paddle.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (3530, 3532), True, 'import paddle.nn as nn\n'), ((3550, 3640), 'paddle.nn.Conv2D', 'nn.Conv2D', (['hidden_dim', 'hidden_dim'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias_attr': '(False)'}), '(hidden_dim, hidden_dim, kernel_size=3, stride=1, padding=1,\n bias_attr=False)\n', (3559, 3640), True, 'import paddle.nn as nn\n'), ((3784, 3824), 'paddle.nn.BatchNorm2D', 'nn.BatchNorm2D', (['hidden_dim'], {'momentum': '(0.9)'}), '(hidden_dim, momentum=0.9)\n', (3798, 3824), True, 'import paddle.nn as nn\n'), ((3842, 3851), 'paddle.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (3849, 3851), True, 'import paddle.nn as nn\n'), ((3869, 3959), 'paddle.nn.Conv2D', 'nn.Conv2D', (['hidden_dim', 'hidden_dim'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias_attr': '(False)'}), '(hidden_dim, hidden_dim, kernel_size=3, stride=1, padding=1,\n bias_attr=False)\n', (3878, 3959), True, 'import paddle.nn as nn\n'), ((4103, 4143), 'paddle.nn.BatchNorm2D', 'nn.BatchNorm2D', (['hidden_dim'], {'momentum': '(0.9)'}), '(hidden_dim, momentum=0.9)\n', (4117, 4143), True, 'import paddle.nn as nn\n'), ((4161, 4170), 'paddle.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4168, 4170), True, 'import paddle.nn as nn\n'), ((5798, 5835), 'paddle.nn.initializer.XavierUniform', 'paddle.nn.initializer.XavierUniform', ([], {}), '()\n', (5833, 5835), False, 'import paddle\n'), ((5886, 5925), 'paddle.nn.initializer.Normal', 'paddle.nn.initializer.Normal', ([], {'std': '(1e-06)'}), '(std=1e-06)\n', (5914, 5925), False, 'import paddle\n'), ((22282, 22310), 'paddle.nn.initializer.Constant', 'nn.initializer.Constant', (['(0.0)'], {}), '(0.0)\n', (22305, 22310), True, 'import paddle.nn as nn\n'), ((25481, 25519), 'paddle.nn.Linear', 'nn.Linear', (['embed_dims[-1]', 'num_classes'], {}), '(embed_dims[-1], num_classes)\n', (25490, 25519), True, 'import paddle.nn as nn\n'), ((24890, 24930), 'paddle.nn.initializer.TruncatedNormal', 'nn.initializer.TruncatedNormal', ([], {'std': '(0.02)'}), '(std=0.02)\n', (24920, 24930), True, 'import paddle.nn as nn\n')] |
#!env python3
"""
Introducing static object in the world.
Tasks:
1. File got really long - move all classes to library file and import
them here.
"""
import pygame
from pygame import K_ESCAPE, K_LEFT, K_RIGHT, K_UP, K_DOWN, QUIT
class Game():
def __init__(self):
"""
Set basic configuration for a game that can be always accessed.
"""
self.screen = {
"width": 240,
"height": 240,
}
self.bg_colour = (255, 255, 255)
self.active = False
self.reset_keys()
def start(self):
self.active = True
def stop(self):
self.active = False
def reset_keys(self):
self.keys = {
"left": False,
"right": False,
"up": False,
"down": False,
}
class Object():
def __init__(self, game):
self.pos = [0, 0]
self.game = game
self.image = None
def update(self, dt):
"""
"""
def draw(self, surface):
"""
"""
if self.image:
surface.blit(
self.image,
self.pos
)
class Wall(Object):
def __init__(self, game):
super().__init__(game)
self.image = pygame.image.load('Sprite-0002.png')
@staticmethod
def create_wall(game, x, y):
obj = Wall(game)
obj.pos[0] = x
obj.pos[1] = y
return obj
class Character(Object):
def __init__(self, game):
super().__init__(game)
self.health = 100
self.speed = 24
def set_position(self, x, y):
self.pos[0] = x
self.pos[1] = y
def get_position(self):
return int(self.pos[0]), int(self.pos[1])
def move(self, x, y=0):
self.pos[0] += x
self.pos[1] += y
class Player(Character):
"""
"""
def __init__(self, game):
super().__init__(game)
# Setup player's image
self.image = pygame.image.load('Sprite-0001.png')
def update(self, dt):
if self.game.keys["left"] and dt:
self.pos[0] -= int(self.speed * dt / 100)
if self.pos[0] < 0:
self.pos[0] = 0
elif self.game.keys["right"] and dt:
self.pos[0] += int(self.speed * dt / 100)
if self.pos[0] > self.game.screen["width"] - 32:
self.pos[0] = self.game.screen["width"] - 32
if self.game.keys["up"] and dt:
self.pos[1] -= int(self.speed * dt / 100)
if self.pos[1] < 0:
self.pos[1] = 0
elif self.game.keys["down"] and dt:
self.pos[1] += int(self.speed * dt / 100)
if self.pos[1] > self.game.screen["height"] - 32:
self.pos[1] = self.game.screen["height"] - 32
class Enemy(Character):
"""
"""
class Zombie(Enemy):
def __init__(self, game):
super().__init__(game)
self.speed = 10
class FastZombie(Zombie):
def __init__(self, game):
super().__init__(game)
self.speed = 24
self.health = 40
def read_input(game):
"""
Read user input and set game state.
Args:
game (Game): Current game state.
Returns:
bool: Should game still be running?
"""
# Look at every event in the queue
for event in pygame.event.get():
# Did the user hit a key?
if event.type == pygame.KEYDOWN:
# Was it the Escape key? If so, stop the loop.
if event.key == K_ESCAPE:
game.stop()
elif event.key == K_LEFT:
game.keys["left"] = True
elif event.key == K_RIGHT:
game.keys["right"] = True
elif event.key == K_UP:
game.keys["up"] = True
elif event.key == K_DOWN:
game.keys["down"] = True
# Did the user hit a key?
if event.type == pygame.KEYUP:
if event.key == K_LEFT:
game.keys["left"] = False
elif event.key == K_RIGHT:
game.keys["right"] = False
elif event.key == K_UP:
game.keys["up"] = False
elif event.key == K_DOWN:
game.keys["down"] = False
# Did the user click the window close button? If so, stop the loop.
elif event.type == QUIT:
game.stop()
def main():
"""
This is main function - it will be executed only explicitly, like this:
import main
main.main()
or when executing script from command line:
python3 main.py
"""
global active
# Initialize PyGame library
pygame.init()
game = Game()
player = Player(game)
player.set_position(32, 32)
# Create few walls
walls = [
Wall.create_wall(game, 0, 0),
Wall.create_wall(game, 120, 120),
]
# Set up the drawing window
screen = pygame.display.set_mode([game.screen["width"], game.screen["height"]])
# Start measuring time
clock = pygame.time.Clock()
dt = clock.tick()
game.start()
while game.active:
# Read any inputs from keyboard - this function will return False if
# we supposed to stop game (closed window or pressed Esc)
read_input(game)
# If user stopped game do not draw this frame
if not game.active:
continue
# Fill the background with white
screen.fill(game.bg_colour)
player.update(dt)
player.draw(screen)
for wall in walls:
wall.draw(screen)
# Flip the display
pygame.display.flip()
# Time passed since last call of tick()
dt = clock.tick(60)
if __name__ == '__main__':
# When executing script from command line start main function
main()
| [
"pygame.init",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.display.flip",
"pygame.time.Clock",
"pygame.image.load"
] | [((3352, 3370), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (3368, 3370), False, 'import pygame\n'), ((4695, 4708), 'pygame.init', 'pygame.init', ([], {}), '()\n', (4706, 4708), False, 'import pygame\n'), ((4957, 5027), 'pygame.display.set_mode', 'pygame.display.set_mode', (["[game.screen['width'], game.screen['height']]"], {}), "([game.screen['width'], game.screen['height']])\n", (4980, 5027), False, 'import pygame\n'), ((5068, 5087), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (5085, 5087), False, 'import pygame\n'), ((1277, 1313), 'pygame.image.load', 'pygame.image.load', (['"""Sprite-0002.png"""'], {}), "('Sprite-0002.png')\n", (1294, 1313), False, 'import pygame\n'), ((1995, 2031), 'pygame.image.load', 'pygame.image.load', (['"""Sprite-0001.png"""'], {}), "('Sprite-0001.png')\n", (2012, 2031), False, 'import pygame\n'), ((5650, 5671), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (5669, 5671), False, 'import pygame\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 29 00:56:43 2017
@author: roshi
"""
import pandas as pd
import matplotlib.pyplot as plt
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from app import app
data = pd.read_csv('./data/youth_tobacco_analysis.csv')
"""Pandas DataFrame Implemented"""
final_data = pd.DataFrame(data.groupby(['YEAR','LocationDesc']).count())
final_data.to_csv('./data/question2.csv', sep = ',', encoding='utf-8')
qn2data = pd.read_csv('./data/question2.csv')
qn2data['LocationDesc'] = qn2data['LocationDesc'].str.upper()
x=0
state_names = list(qn2data['LocationDesc'].unique())
"""
String Operation to Convert the string in each column to upper case is used.
It is used as the columns names are inconsistant with the casing
"""
for i in state_names:
state_names[x] = state_names[x].upper()
x=x+1
years = list(qn2data['YEAR'].unique())
layout = html.Div(children=[
html.Div([
dcc.Dropdown(
id='state_names',
options=[{'label': i, 'value': i} for i in state_names],
value='ARIZONA'
),
],
style={'width': '30%', 'display': 'inline-block'}),
html.Div([
dcc.Graph(id='line-chart'),
],style={'width': '49%'}),
])
@app.callback(
dash.dependencies.Output('line-chart', 'figure'),
[dash.dependencies.Input('state_names', 'value')])
def update_bar_chart(statename1):
"""
Forms a Staced Bar Chart
Keyword Arguments:
statename1 -- Gets the first state name to compare
The values of the states are fetched and compared using a line chart for the trend analysis
Functions - PandasDataFrame Operations Implemented
"""
value_list = list(qn2data['LocationAbbr'][(qn2data['LocationDesc'] == statename1)])
xvalues = list(qn2data['YEAR'][(qn2data['LocationDesc'] == statename1)])
return {
'data': ([
{'x':xvalues , 'y': value_list, 'type': 'line', 'name': 'NB'},
]),
'layout': go.Layout(
title = "Smoking Status Comarison by States",
xaxis={'title': 'Somking Status of Youth'},
yaxis={'title': 'Count of Youth Over the Years'}),
}
| [
"pandas.read_csv",
"dash.dependencies.Output",
"dash.dependencies.Input",
"dash_core_components.Dropdown",
"plotly.graph_objs.Layout",
"dash_core_components.Graph"
] | [((292, 340), 'pandas.read_csv', 'pd.read_csv', (['"""./data/youth_tobacco_analysis.csv"""'], {}), "('./data/youth_tobacco_analysis.csv')\n", (303, 340), True, 'import pandas as pd\n'), ((534, 569), 'pandas.read_csv', 'pd.read_csv', (['"""./data/question2.csv"""'], {}), "('./data/question2.csv')\n", (545, 569), True, 'import pandas as pd\n'), ((1415, 1463), 'dash.dependencies.Output', 'dash.dependencies.Output', (['"""line-chart"""', '"""figure"""'], {}), "('line-chart', 'figure')\n", (1439, 1463), False, 'import dash\n'), ((2237, 2392), 'plotly.graph_objs.Layout', 'go.Layout', ([], {'title': '"""Smoking Status Comarison by States"""', 'xaxis': "{'title': 'Somking Status of Youth'}", 'yaxis': "{'title': 'Count of Youth Over the Years'}"}), "(title='Smoking Status Comarison by States', xaxis={'title':\n 'Somking Status of Youth'}, yaxis={'title':\n 'Count of Youth Over the Years'})\n", (2246, 2392), True, 'import plotly.graph_objs as go\n'), ((1471, 1518), 'dash.dependencies.Input', 'dash.dependencies.Input', (['"""state_names"""', '"""value"""'], {}), "('state_names', 'value')\n", (1494, 1518), False, 'import dash\n'), ((1033, 1141), 'dash_core_components.Dropdown', 'dcc.Dropdown', ([], {'id': '"""state_names"""', 'options': "[{'label': i, 'value': i} for i in state_names]", 'value': '"""ARIZONA"""'}), "(id='state_names', options=[{'label': i, 'value': i} for i in\n state_names], value='ARIZONA')\n", (1045, 1141), True, 'import dash_core_components as dcc\n'), ((1316, 1342), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""line-chart"""'}), "(id='line-chart')\n", (1325, 1342), True, 'import dash_core_components as dcc\n')] |
from phc.easy.patients.name import expand_name_value
def test_name():
assert expand_name_value(
[{"text": "ARA251 LO", "given": ["ARA251"], "family": "LO"}]
) == {"name_given_0": "ARA251", "name_family": "LO"}
def test_name_with_multiple_values():
# NOTE: Official names are preferred first and then remaining names are put
# in separate column
assert expand_name_value(
[
{
"text": "<NAME>",
"given": ["Christian"],
"family": "Di Lorenzo",
},
{
"use": "official",
"given": ["Robert", "Christian"],
"family": "Di Lorenzo",
},
]
) == {
"name_given_0": "Robert",
"name_given_1": "Christian",
"name_family": "Di Lorenzo",
"name_use": "official",
"other_names": [
{
"text": "<NAME>",
"given": ["Christian"],
"family": "Di Lorenzo",
},
],
}
| [
"phc.easy.patients.name.expand_name_value"
] | [((83, 162), 'phc.easy.patients.name.expand_name_value', 'expand_name_value', (["[{'text': 'ARA251 LO', 'given': ['ARA251'], 'family': 'LO'}]"], {}), "([{'text': 'ARA251 LO', 'given': ['ARA251'], 'family': 'LO'}])\n", (100, 162), False, 'from phc.easy.patients.name import expand_name_value\n'), ((384, 558), 'phc.easy.patients.name.expand_name_value', 'expand_name_value', (["[{'text': '<NAME>', 'given': ['Christian'], 'family': 'Di Lorenzo'}, {'use':\n 'official', 'given': ['Robert', 'Christian'], 'family': 'Di Lorenzo'}]"], {}), "([{'text': '<NAME>', 'given': ['Christian'], 'family':\n 'Di Lorenzo'}, {'use': 'official', 'given': ['Robert', 'Christian'],\n 'family': 'Di Lorenzo'}])\n", (401, 558), False, 'from phc.easy.patients.name import expand_name_value\n')] |
import argparse
import datetime
import errno
import json
import logging
import os
import random
import re
import shutil
import subprocess
import sys
import time
import traceback
import zipfile
import zlib
from functools import wraps
from types import SimpleNamespace
import psutil
import py7zr
from artifactory import ArtifactoryPath
from artifactory import md5sum
from artifactory_du import artifactory_du
from dohq_artifactory import ArtifactoryException
from influxdb import InfluxDBClient
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.runtime.client_request_exception import ClientRequestException
from office365.sharepoint.client_context import ClientContext
from plyer import notification
from requests.exceptions import RequestException
from urllib3.exceptions import HTTPError
import iss_templates
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__version__ = "3.0.2"
STATISTICS_SERVER = "OTTBLD02"
STATISTICS_PORT = 8086
TIMEOUT = 90
ARTIFACTORY_DICT = {
"Azure": "http://azwec7artsrv01.ansys.com:8080/artifactory",
"Austin": "http://ausatsrv01.ansys.com:8080/artifactory",
"Boulder": "http://bouartifact.ansys.com:8080/artifactory",
"Canonsburg": "http://canartifactory.ansys.com:8080/artifactory",
"Concord": "http://convmartifact.win.ansys.com:8080/artifactory",
"Darmstadt": "http://darvmartifact.win.ansys.com:8080/artifactory",
"Evanston": "http://evavmartifact:8080/artifactory",
"Hannover": "http://hanartifact1.ansys.com:8080/artifactory",
"Horsham": "http://horvmartifact1.ansys.com:8080/artifactory",
"Lebanon": "http://lebartifactory.win.ansys.com:8080/artifactory",
"Lyon": "http://lyovmartifact.win.ansys.com:8080/artifactory",
"Otterfing": "http://ottvmartifact.win.ansys.com:8080/artifactory",
"Pune": "http://punvmartifact.win.ansys.com:8080/artifactory",
"Sheffield": "http://shfvmartifact.win.ansys.com:8080/artifactory",
"SanJose": "http://sjoartsrv01.ansys.com:8080/artifactory",
"Waterloo": "https://watartifactory.win.ansys.com:8443/artifactory",
}
SHAREPOINT_SITE_URL = r"https://ansys.sharepoint.com/sites/BetaDownloader"
class DownloaderError(Exception):
pass
def retry(exceptions, tries=4, delay=3, backoff=1, logger=None, proc_lock=False):
"""
Retry calling the decorated function using an exponential backoff.
Args:
exceptions (Exception or tuple): the exception to check. may be a tuple of exceptions to check
tries (int): number of times to try (not retry) before giving up
delay (int): initial delay between retries in seconds
backoff (int): backoff multiplier e.g. value of 2 will double the delay each retry
logger (logging): logger to use. If None, print
proc_lock (bool): if retry is applied to proc lock function
Returns: decorator
"""
def deco_retry(func):
@wraps(func)
def f_retry(self, *args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 0:
try:
return func(self, *args, **kwargs)
except exceptions as e:
msg = f"{e}. Error occurred, attempt: {tries - mtries + 1}/{tries}"
if proc_lock:
# only applied for process lock
err = "Stop all processes running from installation folder. "
err += f"Attempt: {tries - mtries + 1}/{tries}"
if mtries > 1:
err += " Autoretry in 60sec."
Downloader.toaster_notification("Failed", err)
else:
raise DownloaderError(msg)
if logger:
logger.warning(msg)
else:
print(msg)
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
else:
error = (
"Please verify that your connection is stable, avoid switching state of VPN during download. "
"For artifactory you have to be on VPN. "
f"Number of attempts: {tries}/{tries}"
)
if logger:
raise DownloaderError(error)
else:
print(error)
return f_retry # true decorator
return deco_retry
class Downloader:
"""
Main class that operates the download and installation process:
1. enables logs
2. parses arguments to get settings file
3. loads JSON to named tuple
4. gets URL for selected version based on server
5. downloads zip archive with BETA build
6. unpacks it to download folder
7. depending on the choice proceeds to installation of EDT or WB
8. uninstalls previous build if one exists
9. updates registry of EDT
10. sends statistics to the server
Performs checks:
1. if the same build date is already installed, then do not proceed to download
2. if some process is running from installation folder it will abort download
Notes:
Software attempts to download 4 times, if connection is still bad will abort
"""
def __init__(self, version, settings_folder="", settings_path=""):
"""
:parameter: version: version of the file, used if invoke file with argument -V to get version
self.build_artifactory_path (ArtifactoryPath): URL to the latest build that will be used to download archive
self.zip_file (str): path to the zip file on the PC
self.target_unpack_dir (str): path where to unpack .zip
self.installed_product_info (str): path to the product.info of the installed build
self.product_root_path (str): root path of Ansys Electronics Desktop/ Workbench installation
self.product_version (str): version to use in env variables eg 202
self.setup_exe (str): path to the setup.exe from downloaded and unpacked zip
self.remote_build_date (str): build date that receive from SharePoint
self.hash (str): hash code used for this run of the program
self.pid: pid (process ID of the current Python run, required to allow kill in UI)
self.ctx: context object to authorize in SharePoint using office365 module
self.settings_folder (str): default folder where all configurations would be saved
self.history_file (str): file where installation progress would be written (this file is tracked by UI)
self.history (dict): dict with history of installation processes
self.logging_file (str): file where detailed log for all runs is saved
"""
self.build_artifactory_path = ArtifactoryPath()
self.zip_file = ""
self.target_unpack_dir = ""
self.installed_product_info = ""
self.product_root_path = ""
self.product_version = ""
self.setup_exe = ""
self.remote_build_date = ""
self.pid = str(os.getpid())
self.ctx = None
self.warnings_list = []
self.hash = generate_hash_str()
if not settings_folder:
self.settings_folder = os.path.join(os.environ["APPDATA"], "build_downloader")
else:
self.settings_folder = settings_folder
self.check_and_make_directories(self.settings_folder)
self.history = {}
self.history_file = os.path.join(self.settings_folder, "installation_history.json")
self.get_installation_history()
self.logging_file = os.path.join(self.settings_folder, "downloader.log")
self.settings_path = settings_path if settings_path else self.parse_args(version)
with open(self.settings_path, "r") as file:
self.settings = json.load(file, object_hook=lambda d: SimpleNamespace(**d))
# this part of the code creates attributes that were added. Required for compatibility
if not hasattr(self.settings, "replace_shortcut"):
# v2.0.0
self.settings.replace_shortcut = True
if not hasattr(self.settings, "custom_flags"):
# v2.2.0
self.settings.custom_flags = ""
if not hasattr(self.settings, "license_file"):
# v3.0.0
self.settings.license_file = ""
if not hasattr(self.settings, "wb_assoc"):
# v3.0.0
self.settings.wb_assoc = ""
if "ElectronicsDesktop" in self.settings.version:
self.product_version = self.settings.version[1:4]
if float(self.product_version) >= 221:
self.product_root_path = os.path.join(
self.settings.install_path, "AnsysEM", f"v{self.product_version}", "Win64"
)
else:
self.product_root_path = os.path.join(
self.settings.install_path,
"AnsysEM",
"AnsysEM" + self.product_version[:2] + "." + self.product_version[2:],
"Win64",
)
self.installed_product_info = os.path.join(self.product_root_path, "product.info")
elif "Workbench" in self.settings.version:
self.product_root_path = os.path.join(self.settings.install_path, "ANSYS Inc", self.settings.version[:4])
elif "LicenseManager" in self.settings.version:
self.product_root_path = os.path.join(
self.settings.install_path, "ANSYS Inc", "Shared Files", "Licensing", "tools", "lmcenter"
)
def authorize_sharepoint(self):
"""
Function that uses PnP to authorize user in SharePoint using Windows account and to get actual client_id and
client_secret
Returns: ctx: authorization context for Office365 library
"""
self.update_installation_history(status="In-Progress", details="Authorizing in SharePoint")
command = "powershell.exe "
command += "Connect-PnPOnline -Url https://ansys.sharepoint.com/sites/BetaDownloader -UseWebLogin;"
command += '(Get-PnPListItem -List secret_list -Fields "Title","client_id","client_secret").FieldValues'
out_str = self.subprocess_call(command, shell=True, popen=True)
secret_list = []
try:
for line in out_str.splitlines():
if "Title" in line:
secret_dict = {"Title": line.split()[1]}
elif "client_id" in line:
secret_dict["client_id"] = line.split()[1]
elif "client_secret" in line:
secret_dict["client_secret"] = line.split()[1]
secret_list.append(secret_dict)
except NameError:
raise DownloaderError("Cannot retrieve authentication tokens for SharePoint")
secret_list.sort(key=lambda elem: elem["Title"], reverse=True)
context_auth = AuthenticationContext(url=SHAREPOINT_SITE_URL)
context_auth.acquire_token_for_app(
client_id=secret_list[0]["client_id"], client_secret=secret_list[0]["client_secret"]
)
ctx = ClientContext(SHAREPOINT_SITE_URL, context_auth)
return ctx
def run(self):
"""
Function that executes the download-installation process
:return: None
"""
try:
set_logger(self.logging_file)
logging.info(f"Settings path is set to {self.settings_path}")
if self.settings.artifactory == "SharePoint":
self.ctx = self.authorize_sharepoint()
self.update_installation_history(status="In-Progress", details="Verifying configuration")
self.check_and_make_directories(self.settings.install_path, self.settings.download_path)
if "ElectronicsDesktop" in self.settings.version or "Workbench" in self.settings.version:
space_required = 15
# License Manager can be updated even if running
self.check_process_lock()
else:
if not self.settings.license_file:
raise DownloaderError("No license file defined. Please select it in Advanced Settings")
if not os.path.isfile(self.settings.license_file):
raise DownloaderError(f"No license file was detected under {self.settings.license_file}")
space_required = 1
self.check_free_space(self.settings.download_path, space_required)
self.check_free_space(self.settings.install_path, space_required)
self.get_build_link()
if self.settings.force_install or self.newer_version_exists:
self.download_file()
if "ElectronicsDesktop" in self.settings.version or "Workbench" in self.settings.version:
self.check_process_lock() # download can take time, better to recheck again
self.install()
try:
self.send_statistics()
except Exception:
self.warnings_list.append("Connection to product improvement server failed")
self.update_installation_history(status="Success", details="Normal completion")
else:
raise DownloaderError("Versions are up to date. If issue occurred please use force install flag")
return
except DownloaderError as e:
# all caught errors are here
logging.error(e)
self.update_installation_history(status="Failed", details=str(e))
except Exception:
logging.error(traceback.format_exc())
self.update_installation_history(status="Failed", details="Unexpected error, see logs")
self.send_statistics(error=traceback.format_exc())
self.clean_temp()
@staticmethod
def check_and_make_directories(*paths):
"""
Verify that installation and download path exists.
If not tries to create a requested path
:parameter: paths: list of paths that we need to check and create
"""
for path in paths:
if not os.path.isdir(path):
try:
os.makedirs(path)
except PermissionError:
raise DownloaderError(f"{path} could not be created due to insufficient permissions")
except OSError as err:
if "BitLocker" in str(err):
raise DownloaderError("Your drive is locked by BitLocker. Please unlock!")
else:
raise DownloaderError(err)
@staticmethod
def check_free_space(path, required):
"""
Verifies that enough disk space is available. Raises error if not enough space
:param path: path where to check
:param required: value in GB that should be available on drive to pass the check
:return:
"""
free_space = shutil.disk_usage(path).free // (2**30)
if free_space < required:
err = f"Disk space in {path} is less than {required}GB. This would not be enough to proceed"
raise DownloaderError(err)
@retry((DownloaderError,), tries=3, delay=60, logger=logging, proc_lock=True)
def check_process_lock(self):
"""
Verify if some executable is running from installation folder
Abort installation if any process is running from installation folder
:return: None
"""
process_list = []
for process in psutil.process_iter():
try:
if self.product_root_path in process.exe():
process_list.append(process.name())
except psutil.AccessDenied:
pass
if process_list:
process_list.sort(key=len) # to fit into UI
raise DownloaderError(
"Following processes are running from installation directory: "
+ f"{', '.join(set(process_list))}. Please stop all processes."
)
@property
def newer_version_exists(self):
"""
verify if version on the server is newer compared to installed
Returns:
(bool) True if remote is newer or no version is installed, False if remote is the same or older
"""
if "Workbench" in self.settings.version:
product_installed = os.path.join(self.product_root_path, "package.id")
elif "LicenseManager" in self.settings.version:
# always update LM
return True
else:
product_installed = self.installed_product_info
if os.path.isfile(product_installed):
if "Workbench" in self.settings.version:
with open(product_installed) as file:
installed_product_version = next(file).rstrip().split()[-1] # get first line
try:
installed_product_version = int(installed_product_version.split("P")[0])
except ValueError:
installed_product_version = 0
else:
installed_product_version = self.get_edt_build_date(product_installed)
logging.info(f"Installed version of {self.settings.version} is {installed_product_version}")
new_product_version = self.get_new_build_date()
if not all([new_product_version, installed_product_version]):
# some of the versions could not be parsed, need installation
return True
if new_product_version <= installed_product_version:
return False
return True
def get_new_build_date(self, distribution="winx64"):
"""
Create URL for new build extraction or extract version from self.remote_build_date for SharePoint download
Returns:
new_product_version (int) version of the product on the server
"""
if self.settings.artifactory != "SharePoint":
if "Workbench" in self.settings.version:
url = self.build_artifactory_path.joinpath("package.id")
elif "ElectronicsDesktop" in self.settings.version:
system = "windows" if distribution == "winx64" else "linux"
url = self.build_artifactory_path.parent.joinpath(f"product_{system}.info")
else:
# todo add license manager handling
return 0
logging.info(f"Request info about new package: {url}")
new_product_version = self.get_build_info_file_from_artifactory(url)
else:
try:
new_product_version = int(self.remote_build_date)
except ValueError:
return 0
logging.info(f"Version on artifactory/SP is {new_product_version}")
return new_product_version
@retry((HTTPError, RequestException, ConnectionError, ConnectionResetError), 4, logger=logging)
def get_build_link(self, distribution="winx64"):
"""
Function that sends HTTP request to JFrog and get the list of folders with builds for Electronics Desktop and
checks user password
If use SharePoint then readdress to SP list
:modify: (str) self.build_artifactory_path: URL link to the latest build that will be used to download archive
"""
self.update_installation_history(status="In-Progress", details="Search latest build URL")
if self.settings.artifactory == "SharePoint":
self.get_sharepoint_build_info()
return
if not hasattr(self.settings.password, self.settings.artifactory):
raise DownloaderError(f"Please provide password for {self.settings.artifactory}")
password = getattr(self.settings.password, self.settings.artifactory)
if not self.settings.username or not password:
raise DownloaderError("Please provide username and artifactory password")
server = ARTIFACTORY_DICT[self.settings.artifactory]
art_path = ArtifactoryPath(server, auth=(self.settings.username, password), timeout=TIMEOUT)
try:
repos_list = art_path.get_repositories(lazy=True)
except ArtifactoryException as err:
raise DownloaderError(f"Cannot retrieve repositories. Error: {err}")
# fill the dictionary with Electronics Desktop and Workbench keys since builds could be different
# still parse the list because of different names on servers
artifacts_dict = {}
for repo in repos_list:
repo_name = repo.name
if "EBU_Certified" in repo_name:
version = repo_name.split("_")[0] + "_ElectronicsDesktop"
elif "Certified" in repo_name and "Licensing" not in repo_name:
version = repo_name.split("_")[0] + "_Workbench"
elif "Certified" in repo_name and "Licensing" in repo_name:
version = repo_name.split("_")[0] + "_LicenseManager"
else:
continue
if version not in artifacts_dict:
# extract real repo name in case it is cached
if art_path.joinpath(repo_name).exists():
# repo might be syncing (happens on new release addition)
artifacts_dict[version] = art_path.joinpath(repo_name).stat().repo
try:
repo = artifacts_dict[self.settings.version]
except KeyError:
raise DownloaderError(
f"Version {self.settings.version} that you have specified "
+ f"does not exist on {self.settings.artifactory}"
)
path = ""
art_path = art_path.joinpath(str(repo))
if "ElectronicsDesktop" in self.settings.version:
archive = "winx64.zip" if distribution == "winx64" else "linx64.tgz"
builds_dates = []
for relative_p in art_path:
try:
archive_exists = list(relative_p.glob(f"Electronics*{archive}"))
if archive_exists:
builds_dates.append(int(relative_p.name))
except ValueError:
pass
if not builds_dates:
raise DownloaderError("Artifact does not exist")
latest_build = sorted(builds_dates)[-1]
art_path = art_path.joinpath(str(latest_build))
for path in art_path:
if archive in path.name:
break
else:
raise DownloaderError(f"Cannot find {distribution} archive file")
elif "Workbench" in self.settings.version or "LicenseManager" in self.settings.version:
path = art_path.joinpath(distribution)
if not path:
raise DownloaderError("Cannot receive URL")
self.build_artifactory_path = path
def get_sharepoint_build_info(self):
"""
Gets link to the latest build from SharePoint and builddate itself
Returns: None
"""
product_list = self.ctx.web.lists.get_by_title("product_list")
items = product_list.items
self.ctx.load(items).execute_query()
build_list = []
for item in items:
title = item.properties["Title"]
if title != self.settings.version:
continue
build_dict = {
"Title": title,
"build_date": item.properties["build_date"],
"relative_url": item.properties["relative_url"],
}
build_list.append(build_dict)
build_list.sort(key=lambda elem: elem["build_date"], reverse=True)
build_dict = build_list[0] if build_list else {}
if not build_dict:
raise DownloaderError(f"No version of {self.settings.version} is available on SharePoint")
self.build_artifactory_path = build_dict["relative_url"]
self.remote_build_date = build_dict["build_date"]
def download_file(self):
"""
Downloads file in chunks and saves to the temp.zip file
Uses url to the zip archive or special JFrog API to download Workbench folder
:modify: (str) zip_file: link to the zip file
"""
if self.settings.artifactory == "SharePoint" or "win" in self.build_artifactory_path.name:
archive_type = "zip"
else:
archive_type = "tgz"
self.zip_file = os.path.join(self.settings.download_path, f"{self.settings.version}.{archive_type}")
chunk_size = 50 * 1024 * 1024
if self.settings.artifactory == "SharePoint":
self.download_from_sharepoint(chunk_size=chunk_size)
else:
self.download_from_artifactory(archive_type, chunk_size=chunk_size)
logging.info(f"File is downloaded to {self.zip_file}")
@retry((HTTPError, RequestException, ConnectionError, ConnectionResetError), 4, logger=logging)
def download_from_artifactory(self, archive_type, chunk_size):
"""
Download file from Artifactory
Args:
archive_type: type of the archive, zip or tgz
chunk_size: (int) chunk size in bytes when download
Returns: None
"""
if not self.build_artifactory_path.replication_status["status"] in ["ok", "never_run"]:
raise DownloaderError("Currently Artifactory repository is replicating, please try later")
logging.info(f"Start download file from {self.build_artifactory_path} to {self.zip_file}")
self.update_installation_history(
status="In-Progress", details=f"Downloading file from {self.settings.artifactory}"
)
if "ElectronicsDesktop" in self.settings.version:
file_stats = self.build_artifactory_path.stat()
arti_file_md5 = file_stats.md5
logging.info(f"Artifactory hash: {arti_file_md5}")
try:
self.build_artifactory_path.writeto(
out=self.zip_file, chunk_size=chunk_size, progress_func=self.print_download_progress
)
except RuntimeError as err:
raise DownloaderError(f"Cannot download file. Server returned status code: {err}")
local_md5_hash = md5sum(self.zip_file)
logging.info(f"Local file hash: {local_md5_hash}")
if local_md5_hash != arti_file_md5:
raise DownloaderError("Downloaded file MD5 hash is different")
elif "Workbench" in self.settings.version or "LicenseManager" in self.settings.version:
try:
file_size = self.get_artifactory_folder_size()
logging.info(f"Workbench/License Manager real file size is {file_size}")
except (TypeError, ValueError):
file_size = 14e9
archive_url = self.build_artifactory_path.archive(archive_type=archive_type)
archive_url.writeto(
out=self.zip_file,
chunk_size=chunk_size,
progress_func=lambda x, y: self.print_download_progress(x, file_size),
)
def get_artifactory_folder_size(self):
aql_query_dict, max_depth_print = artifactory_du.prepare_aql(
file=f"/{self.build_artifactory_path.name}",
max_depth=0,
repository=self.build_artifactory_path.repo,
without_downloads="",
older_than="",
)
artifacts = artifactory_du.artifactory_aql(
artifactory_url=str(self.build_artifactory_path.drive),
aql_query_dict=aql_query_dict,
username=self.build_artifactory_path.auth[0],
password=self.build_artifactory_path.auth[1],
kerberos=False,
verify=False,
)
file_size = artifactory_du.out_as_du(artifacts, max_depth_print, human_readable=False)
file_size = int(file_size.strip("/"))
return file_size
@retry(
(HTTPError, RequestException, ConnectionError, ConnectionResetError, ClientRequestException),
tries=4,
logger=logging,
)
def download_from_sharepoint(self, chunk_size):
"""
Downloads file from Sharepoint
Args:
chunk_size: (int) chunk size in bytes when download
Returns: None
"""
self.update_installation_history(status="In-Progress", details="Downloading file from SharePoint")
remote_file = self.ctx.web.get_file_by_server_relative_url(
f"/sites/BetaDownloader/{self.build_artifactory_path}"
)
remote_file.get()
try:
self.ctx.execute_query()
except ClientRequestException as err:
logging.error(str(err))
raise DownloaderError(
"URL on SharePoint is broken. Report an issue to <EMAIL>. "
"In meantime please switch to any other repository."
)
file_size = remote_file.length
self.check_free_space(self.settings.download_path, file_size / 1024 / 1024 / 1024)
try:
with open(self.zip_file, "wb") as zip_file:
try:
remote_file.download_session(
zip_file,
lambda offset: self.print_download_progress(offset, total_size=file_size),
chunk_size=chunk_size,
)
self.ctx.execute_query()
except OSError as err:
if err.errno == errno.ENOSPC:
raise DownloaderError("No disk space available in download folder!")
raise
except PermissionError as err:
msg = str(err).replace("[Errno 13]", "").strip()
raise DownloaderError(msg)
if not self.zip_file:
raise DownloaderError("ZIP download failed")
if abs(os.path.getsize(self.zip_file) - file_size) > 0.05 * file_size:
raise DownloaderError("File size difference is more than 5%")
def print_download_progress(self, offset, total_size):
msg = "Downloaded {}/{}MB...[{}%]".format(
int(offset / 1024 / 1024), int(total_size / 1024 / 1024), min(round(offset / total_size * 100, 2), 100)
)
logging.info(msg)
self.update_installation_history(status="In-Progress", details=msg)
def install(self, local_lang=False):
"""
Unpack downloaded zip and proceed to installation. Different executions for Electronics Desktop and Workbench
:param local_lang: if not specified then use English as default installation language
:return: None
"""
self.unpack_archive()
if "ElectronicsDesktop" in self.settings.version:
self.install_edt()
elif "Workbench" in self.settings.version:
self.install_wb(local_lang)
else:
self.install_license_manager()
self.update_installation_history(status="In-Progress", details="Clean temp directory")
self.clean_temp()
def unpack_archive(self):
self.update_installation_history(status="In-Progress", details="Start unpacking")
self.target_unpack_dir = self.zip_file.replace(".zip", "")
try:
with zipfile.ZipFile(self.zip_file, "r") as zip_ref:
zip_ref.extractall(self.target_unpack_dir)
except OSError as err:
if err.errno == errno.ENOSPC:
raise DownloaderError("No disk space available in download folder!")
else:
raise DownloaderError(f"Cannot unpack due to {err}")
except (zipfile.BadZipFile, zlib.error):
raise DownloaderError("Zip file is broken. Please try again later or use another repository.")
logging.info(f"File is unpacked to {self.target_unpack_dir}")
def install_edt(self):
"""
Install Electronics Desktop. Make verification that the same version is not yet installed and makes
silent installation
Get Workbench installation path from environment variable and enables integration if exists.
:return: None
"""
setup_exe, product_id, installshield_version = self.parse_iss_template(self.target_unpack_dir)
self.uninstall_edt(setup_exe, product_id, installshield_version)
install_iss_file, install_log_file = self.create_install_iss_file(installshield_version, product_id)
command = [f'"{setup_exe}"', "-s", rf'-f1"{install_iss_file}"', rf'-f2"{install_log_file}"']
command = " ".join(command)
self.update_installation_history(status="In-Progress", details="Start installation")
logging.info("Execute installation")
self.subprocess_call(command)
self.check_result_code(install_log_file)
self.update_edt_registry()
self.remove_aedt_shortcuts()
def create_install_iss_file(self, installshield_version, product_id):
install_iss_file = os.path.join(self.target_unpack_dir, "install.iss")
install_log_file = os.path.join(self.target_unpack_dir, "install.log")
integrate_wb = 0
awp_env_var = "AWP_ROOT" + self.product_version
if awp_env_var in os.environ:
run_wb = os.path.join(os.environ[awp_env_var], "Framework", "bin", "Win64", "RunWB2.exe")
if os.path.isfile(run_wb):
integrate_wb = 1
logging.info("Integration with Workbench turned ON")
# the "shared files" is created at the same level as the "AnsysEMxx.x" so if installing to unique folders,
# the Shared Files folder will be unique as well. Thus we can check install folder for license
if os.path.isfile(
os.path.join(self.settings.install_path, "AnsysEM", "Shared Files", "Licensing", "ansyslmd.ini")
):
install_iss = iss_templates.install_iss + iss_templates.existing_server
logging.info("Install using existing license configuration")
else:
install_iss = iss_templates.install_iss + iss_templates.new_server
logging.info("Install using 127.0.0.1, Otterfing and HQ license servers")
with open(install_iss_file, "w") as file:
file.write(
install_iss.format(
product_id,
os.path.join(self.settings.install_path, "AnsysEM"),
os.environ["TEMP"],
integrate_wb,
installshield_version,
)
)
return install_iss_file, install_log_file
def uninstall_edt(self, setup_exe, product_id, installshield_version):
"""
Silently uninstall build of the same version
:return: None
"""
if os.path.isfile(self.installed_product_info):
uninstall_iss_file = os.path.join(self.target_unpack_dir, "uninstall.iss")
uninstall_log_file = os.path.join(self.target_unpack_dir, "uninstall.log")
with open(uninstall_iss_file, "w") as file:
file.write(iss_templates.uninstall_iss.format(product_id, installshield_version))
command = [
f'"{setup_exe}"',
"-uninst",
"-s",
rf'-f1"{uninstall_iss_file}"',
rf'-f2"{uninstall_log_file}"',
]
command = " ".join(command)
logging.info("Execute uninstallation")
self.update_installation_history(status="In-Progress", details="Uninstall previous build")
self.subprocess_call(command)
self.check_result_code(uninstall_log_file, False)
em_main_dir = os.path.dirname(self.product_root_path)
self.remove_path(em_main_dir)
if os.path.isdir(em_main_dir):
raise DownloaderError(f"Failed to remove {em_main_dir}. Probably directory is locked.")
else:
logging.info("Version is not installed, skip uninstallation")
def check_result_code(self, log_file, installation=True):
"""
Verify result code of the InstallShield log file
:param log_file: installation log file
:param installation: True if verify log after installation elif after uninstallation False
:return: None
"""
success = "New build was successfully installed" if installation else "Previous build was uninstalled"
fail = "Installation went wrong" if installation else "Uninstallation went wrong"
if not os.path.isfile(log_file):
raise DownloaderError(f"{fail}. Check that UAC disabled or confirm UAC question manually")
msg = fail
regex = "ResultCode=(.*)"
with open(log_file) as file:
for line in file:
code = re.findall(regex, line)
if code and code[0] == "0":
logging.info(success)
break
else:
if not installation:
msg = "Official uninstaller failed, make hard remove"
logging.error(msg)
self.warnings_list.append(msg)
else:
raise DownloaderError(msg)
@staticmethod
def get_edt_build_date(product_info_file="", file_content=None):
"""
extract information about Electronics Desktop build date and version
Args:
product_info_file: path to the product.info
file_content (list): accepts list with file content as well instead of file
Returns: (int) build_date
"""
if os.path.isfile(product_info_file):
with open(product_info_file) as file:
file_content = file.readlines()
for line in file_content:
if "AnsProductBuildDate" in line:
full_build_date = line.split("=")[1].replace('"', "").replace("-", "")
build_date = full_build_date.split()[0]
break
else:
# cannot find line with build date
return 0
try:
return int(build_date)
except ValueError:
return 0
@staticmethod
def parse_iss_template(unpacked_dir):
"""
Open directory with unpacked build of Electronics Desktop and search for SilentInstallationTemplate.iss to
extract product ID which is GUID hash
Args:
unpacked_dir: directory where AEDT package was unpacked
Returns:
product_id: product GUID extracted from iss template
setup_exe: set path to setup.exe if exists
installshield_version: set version from file
"""
default_iss_file = ""
setup_exe = ""
product_id_match = []
for dir_path, dir_names, file_names in os.walk(unpacked_dir):
for filename in file_names:
if "AnsysEM" in dir_path and filename.endswith(".iss"):
default_iss_file = os.path.join(dir_path, filename)
setup_exe = os.path.join(dir_path, "setup.exe")
break
if not default_iss_file:
raise DownloaderError("SilentInstallationTemplate.iss does not exist")
if not os.path.isfile(setup_exe):
raise DownloaderError("setup.exe does not exist")
with open(default_iss_file, "r") as iss_file:
for line in iss_file:
if "DlgOrder" in line:
guid_regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
product_id_match = re.findall(guid_regex, line)
if "InstallShield Silent" in line:
installshield_version = next(iss_file).split("=")[1]
if product_id_match:
product_id = product_id_match[0]
logging.info(f"Product ID is {product_id}")
else:
raise DownloaderError("Unable to extract product ID")
return setup_exe, product_id, installshield_version
def install_license_manager(self):
"""
Install license manager and feed it with license file
"""
self.setup_exe = os.path.join(self.target_unpack_dir, "setup.exe")
if os.path.isfile(self.setup_exe):
install_path = os.path.join(self.settings.install_path, "ANSYS Inc")
if not os.path.isfile(self.settings.license_file):
raise DownloaderError(f"No license file was detected under {self.settings.license_file}")
command = [
self.setup_exe,
"-silent",
"-LM",
"-install_dir",
install_path,
"-lang",
"en",
"-licfilepath",
self.settings.license_file,
]
self.update_installation_history(status="In-Progress", details="Start installation")
logging.info("Execute installation")
self.subprocess_call(command)
package_build = self.parse_lm_installer_builddate()
installed_build = self.get_license_manager_build_date()
if all([package_build, installed_build]) and package_build == installed_build:
self.update_installation_history(status="Success", details="Normal completion")
else:
raise DownloaderError("License Manager was not installed")
else:
raise DownloaderError("No LicenseManager setup.exe file detected")
def parse_lm_installer_builddate(self):
"""
Check build date of installation package of License Manager
"""
build_file = os.path.join(self.target_unpack_dir, "builddate.txt")
lm_center_archive = os.path.join(self.target_unpack_dir, "lmcenter", "WINX64.7z")
if not os.path.isfile(build_file) and os.path.isfile(lm_center_archive):
with py7zr.SevenZipFile(lm_center_archive, "r") as archive:
archive.extractall(path=os.path.join(self.target_unpack_dir, "lmcenter"))
build_file = os.path.join(
self.target_unpack_dir,
"lmcenter",
"Shared Files",
"licensing",
"tools",
"lmcenter",
"lmcenter_blddate.txt",
)
if not os.path.isfile(build_file):
# check again if file was unpacked
logging.warning("builddate.txt was not found in installation package")
return
with open(build_file) as file:
for line in file:
if "license management center" in line.lower():
lm_build_date = line.split()[-1]
try:
logging.info(f"Build date of License Manager in installation package {lm_build_date}")
lm_build_date = int(lm_build_date)
return lm_build_date
except TypeError:
raise DownloaderError("Cannot extract build date of installation package")
def get_license_manager_build_date(self):
"""
Check build date of installed License Manager
"""
build_date_file = os.path.join(self.product_root_path, "lmcenter_blddate.txt")
if not os.path.isfile(build_date_file):
raise DownloaderError("lmcenter_blddate.txt is not available")
with open(build_date_file) as file:
lm_build_date = next(file).split()[-1]
try:
logging.info(f"Newly installed build date of License Manager: {lm_build_date}")
lm_build_date = int(lm_build_date)
return lm_build_date
except (TypeError, ValueError):
raise DownloaderError("Cannot extract build date of installed License Manager")
def install_wb(self, local_lang=False):
"""
Install Workbench to the target installation directory
:param local_lang: if not specified then use English as default installation language
"""
self.setup_exe = os.path.join(self.target_unpack_dir, "setup.exe")
if os.path.isfile(self.setup_exe):
uninstall_exe = self.uninstall_wb()
install_path = os.path.join(self.settings.install_path, "ANSYS Inc")
command = [self.setup_exe, "-silent", "-install_dir", install_path]
if not local_lang:
command += ["-lang", "en"]
command += self.settings.wb_flags.split()
# the "shared files" is created at the same level as the "ANSYS Inc" so if installing to unique folders,
# the Shared Files folder will be unique as well. Thus we can check install folder for license
if (
os.path.isfile(os.path.join(install_path, "Shared Files", "Licensing", "ansyslmd.ini"))
or "ANSYSLMD_LICENSE_FILE" in os.environ
):
logging.info("Install using existing license configuration")
else:
command += ["-licserverinfo", "2325:1055:127.0.0.1,OTTLICENSE5,PITRH6LICSRV1"]
logging.info("Install using 127.0.0.1, Otterfing and HQ license servers")
# convert command to string to easy append custom flags
command = subprocess.list2cmdline(command)
command += " " + self.settings.custom_flags
self.update_installation_history(status="In-Progress", details="Start installation")
logging.info("Execute installation")
self.subprocess_call(command)
if os.path.isfile(uninstall_exe):
logging.info("New build was installed")
else:
raise DownloaderError(
"Workbench installation failed. "
+ f"If you see this error message by mistake please report to {__email__}"
)
if self.settings.wb_assoc:
wb_assoc_exe = os.path.join(self.settings.wb_assoc, "commonfiles", "tools", "winx64", "fileassoc.exe")
if not os.path.isfile(wb_assoc_exe):
self.warnings_list.append(f"Cannot find {wb_assoc_exe}")
else:
logging.info("Run WB file association")
self.subprocess_call(wb_assoc_exe)
else:
raise DownloaderError("No Workbench setup.exe file detected")
def uninstall_wb(self):
"""
Uninstall Workbench if such exists in the target installation directory
:return: uninstall_exe: name of the executable of uninstaller"""
uninstall_exe = os.path.join(self.product_root_path, "Uninstall.exe")
if os.path.isfile(uninstall_exe):
command = [uninstall_exe, "-silent"]
self.update_installation_history(status="In-Progress", details="Uninstall previous build")
logging.info("Execute uninstallation")
self.subprocess_call(command)
logging.info("Previous build was uninstalled using uninstaller")
else:
logging.info("No Workbench Uninstall.exe file detected")
self.remove_path(self.product_root_path)
return uninstall_exe
def remove_path(self, path):
"""
Function to safely remove path if rmtree fails
:param path:
:return:
"""
def hard_remove():
try:
# try this dirty method to force remove all files in directory
all_files = os.path.join(path, "*.*")
command = ["DEL", "/F", "/Q", "/S", all_files, ">", "NUL"]
self.subprocess_call(command, shell=True)
command = ["rmdir", "/Q", "/S", path]
self.subprocess_call(command, shell=True)
except Exception as err:
logging.error(str(err))
logging.error("Failed to remove directory via hard_remove")
self.warnings_list.append("Failed to remove directory")
logging.info(f"Removing {path}")
if os.path.isdir(path):
try:
shutil.rmtree(path)
except PermissionError:
logging.warning("Permission error. Switch to CMD force mode")
hard_remove()
self.warnings_list.append("Clean remove failed due to Permissions Error")
except (FileNotFoundError, OSError, Exception):
logging.warning("FileNotFoundError or other error. Switch to CMD force mode")
hard_remove()
self.warnings_list.append("Clean remove failed due to Not Found or OS Error")
elif os.path.isfile(path):
os.remove(path)
def get_build_info_file_from_artifactory(self, build_info):
"""
Downloads product info file from artifactory
:param (ArtifactoryPath) build_info: arti path to the package_id file
:return: (int): package_id if extracted
"""
product_info = 0
package_info = build_info.read_text()
try:
if "Workbench" in self.settings.version:
first_line = package_info.split("\n")[0]
product_info = first_line.rstrip().split()[-1]
try:
product_info = int(product_info.split("P")[0])
except ValueError:
pass
else:
product_info = self.get_edt_build_date(file_content=package_info.split("\n"))
except IndexError:
pass
return product_info
def clean_temp(self):
"""
Cleans downloaded zip and unpacked folder with content
:return: None
"""
try:
if os.path.isfile(self.zip_file) and self.settings.delete_zip:
self.remove_path(self.zip_file)
logging.info("ZIP deleted")
if os.path.isdir(self.target_unpack_dir):
self.remove_path(self.target_unpack_dir)
logging.info("Unpacked directory removed")
except PermissionError:
logging.error("Temp files could not be removed due to permission error")
def remove_aedt_shortcuts(self):
"""
Function to remove newly created AEDT shortcuts and replace them with new one
"""
if not self.settings.replace_shortcut:
return
# include Public, user folder and user folder when OneDrive sync is enabled
for user in ["Public", os.getenv("username"), os.path.join(os.getenv("username"), "OneDrive - ANSYS, Inc")]:
desktop = os.path.join("C:\\", "Users", user, "Desktop")
for shortcut in [
"ANSYS Savant",
"ANSYS EMIT",
"ANSYS SIwave",
"ANSYS Twin Builder",
"Ansys Nuhertz FilterSolutions",
]:
self.remove_path(os.path.join(desktop, shortcut + ".lnk"))
new_name = os.path.join(
desktop, f"20{self.product_version[:2]}R{self.product_version[2:]} Electronics Desktop.lnk"
)
aedt_shortcut = os.path.join(desktop, "ANSYS Electronics Desktop.lnk")
if not os.path.isfile(new_name):
try:
os.rename(aedt_shortcut, new_name)
except FileNotFoundError:
pass
else:
self.remove_path(aedt_shortcut)
def update_edt_registry(self):
"""
Update Electronics Desktop registry based on the files in the HPC_Options folder that are added from UI
:return: None
"""
hpc_folder = os.path.join(self.settings_folder, "HPC_Options")
update_registry_exe = os.path.join(self.product_root_path, "UpdateRegistry.exe")
productlist_file = os.path.join(self.product_root_path, "config", "ProductList.txt")
if not os.path.isfile(productlist_file):
raise DownloaderError("Cannot update registry. Probably Electronics Desktop installation failed")
with open(productlist_file) as file:
product_version = next(file).rstrip() # get first line
self.update_installation_history(status="In-Progress", details="Update registry")
if os.path.isdir(hpc_folder):
for file in os.listdir(hpc_folder):
if ".acf" in file:
options_file = os.path.join(hpc_folder, file)
command = [update_registry_exe, "-ProductName", product_version, "-FromFile", options_file]
logging.info("Update registry")
self.subprocess_call(command)
def update_installation_history(self, status, details):
"""
Update ordered dictionary with new data and write it to the file
:param status: Failed | Success | In-Progress (important, used in JS)
:param details: Message for details field
:return:
"""
if status == "Failed" or status == "Success":
try:
self.toaster_notification(status, details)
except Exception:
msg = "Toaster notification did not work"
logging.error(msg)
self.warnings_list.append(msg)
self.get_installation_history() # in case if file was deleted during run of installation
time_now = datetime.datetime.now().strftime("%d-%m-%Y %H:%M")
shorten_path = self.settings_path.replace(os.getenv("APPDATA", "@@@"), "%APPDATA%")
if status == "Failed" or status == "Success":
if self.warnings_list:
details += "\nSome warnings occurred during process:\n" + "\n".join(self.warnings_list)
self.history[self.hash] = [status, self.settings.version, time_now, shorten_path, details, self.pid]
with open(self.history_file, "w") as file:
json.dump(self.history, file, indent=4)
@staticmethod
def toaster_notification(status, details):
"""
Send toaster notification
:param status: Failed | Success | In-Progress
:param details: Message for details field
:return:
"""
icon = "fail.ico" if status == "Failed" else "success.ico"
root_path = os.path.dirname(sys.argv[0])
icon_path = os.path.join(root_path, "notifications", icon)
if not os.path.isfile(icon_path):
root_path = os.path.dirname(os.path.realpath(__file__))
icon_path = os.path.join(root_path, "notifications", icon) # dev path
notification.notify(title=status, message=details, app_icon=icon_path, timeout=15)
def get_installation_history(self):
"""
Read a file with installation history
create a file if does not exist
:return: dict with history or empty in case if file was deleted during run of installation
"""
if os.path.isfile(self.history_file):
try:
with open(self.history_file) as file:
self.history = json.load(file)
except json.decoder.JSONDecodeError:
return
else:
self.history = {}
def send_statistics(self, error=None):
"""
Send usage statistics to the database.
Collect username, time, version and software installed
in case of crash send also crash data
:parameter: error: error message of what went wrong
:return: None
"""
version, tool = self.settings.version.split("_")
time_now = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
self.settings.username = os.getenv("username", self.settings.username)
if self.settings.artifactory == "SharePoint":
self.send_statistics_to_sharepoint(tool, version, time_now, error)
else:
self.send_statistics_to_influx(tool, version, time_now, error)
def send_statistics_to_influx(self, tool, version, time_now, error, downloader_ver=__version__):
"""
Send statistics to InfluxDB
Args:
tool: product that is installed
version: version
time_now: time
error: error if some crash occurred
downloader_ver: version of the backend
Returns:
None
"""
client = InfluxDBClient(host=STATISTICS_SERVER, port=STATISTICS_PORT)
db_name = "downloads" if not error else "crashes"
client.switch_database(db_name)
json_body = [
{
"measurement": db_name,
"tags": {
"username": self.settings.username,
"version": version,
"tool": tool,
"artifactory": self.settings.artifactory,
"downloader_ver": downloader_ver,
},
"time": time_now,
"fields": {"count": 1},
}
]
if error:
json_body[0]["tags"]["log"] = error
client.write_points(json_body)
def send_statistics_to_sharepoint(self, tool, version, time_now, error):
"""
Send statistics to SharePoint list
Args:
time_now: time
tool: product that is installed
version: version
error: error if some crash occurred
Returns:
None
"""
list_name = "statistics" if not error else "crashes"
target_list = self.ctx.web.lists.get_by_title(list_name)
item = {
"Title": self.settings.username,
"Date": str(time_now),
"tool": tool,
"version": version,
"in_influx": False,
"downloader_ver": __version__,
}
if error:
error = error.replace("\n", "#N").replace("\r", "")
item["error"] = error
target_list.add_item(item)
self.ctx.execute_query()
@staticmethod
def subprocess_call(command, shell=False, popen=False):
"""
Wrapper for subprocess call to handle non admin run or UAC issue
Args:
command: (str/list) command to run
shell: call with shell mode or not
popen: in case if you need output we need to use Popen. Pyinstaller compiles in -noconsole, need
to explicitly define stdout, in, err
Returns:
output (str), output of the command run
"""
output = ""
try:
if isinstance(command, list):
command_str = subprocess.list2cmdline(command)
else:
command_str = command
logging.info(command_str)
if popen:
p = subprocess.Popen(
command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell
)
byte_output = p.stdout.read()
output = byte_output.decode("utf-8").rstrip()
p.communicate()
else:
subprocess.call(command, shell=shell)
return output
except OSError:
raise DownloaderError("Please run as administrator and disable Windows UAC")
@staticmethod
def parse_args(version):
"""
Function to parse arguments provided to the script. Search for -p key to get settings path
:return: settings_path: path to the configuration file
"""
parser = argparse.ArgumentParser()
# Add long and short argument
parser.add_argument("--path", "-p", help="set path to the settings file generated by UI")
parser.add_argument("--version", "-V", action="version", version=f"%(prog)s version: {version}")
args = parser.parse_args()
if args.path:
settings_path = args.path
if not os.path.isfile(settings_path):
raise DownloaderError("Settings file does not exist")
return settings_path
else:
raise DownloaderError("Please provide --path argument")
def generate_hash_str():
"""
generate random hash. Letter A at the end is important to preserver Order in JS
:return: hash code (str)
"""
return f"{random.getrandbits(32):x}A".strip()
def set_logger(logging_file):
"""
Function to setup logging output to stream and log file. Will be used by UI and backend
:param: logging_file (str): path to the log file
:return: None
"""
work_dir = os.path.dirname(logging_file)
if not os.path.isdir(work_dir):
os.makedirs(work_dir)
# add logging to console and log file
# If you set the log level to INFO, it will include INFO, WARNING, ERROR, and CRITICAL messages
logging.basicConfig(
filename=logging_file,
format="%(asctime)s (%(levelname)s) %(message)s",
level=logging.INFO,
datefmt="%d.%m.%Y %H:%M:%S",
)
logging.getLogger().addHandler(logging.StreamHandler())
if __name__ == "__main__":
app = Downloader(__version__)
app.run()
| [
"logging.getLogger",
"logging.StreamHandler",
"iss_templates.uninstall_iss.format",
"zipfile.ZipFile",
"py7zr.SevenZipFile",
"time.sleep",
"artifactory_du.artifactory_du.prepare_aql",
"random.getrandbits",
"artifactory.ArtifactoryPath",
"logging.info",
"logging.error",
"os.walk",
"os.remove"... | [((60795, 60824), 'os.path.dirname', 'os.path.dirname', (['logging_file'], {}), '(logging_file)\n', (60810, 60824), False, 'import os\n'), ((61038, 61189), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': 'logging_file', 'format': '"""%(asctime)s (%(levelname)s) %(message)s"""', 'level': 'logging.INFO', 'datefmt': '"""%d.%m.%Y %H:%M:%S"""'}), "(filename=logging_file, format=\n '%(asctime)s (%(levelname)s) %(message)s', level=logging.INFO, datefmt=\n '%d.%m.%Y %H:%M:%S')\n", (61057, 61189), False, 'import logging\n'), ((2917, 2928), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (2922, 2928), False, 'from functools import wraps\n'), ((6806, 6823), 'artifactory.ArtifactoryPath', 'ArtifactoryPath', ([], {}), '()\n', (6821, 6823), False, 'from artifactory import ArtifactoryPath\n'), ((7502, 7565), 'os.path.join', 'os.path.join', (['self.settings_folder', '"""installation_history.json"""'], {}), "(self.settings_folder, 'installation_history.json')\n", (7514, 7565), False, 'import os\n'), ((7635, 7687), 'os.path.join', 'os.path.join', (['self.settings_folder', '"""downloader.log"""'], {}), "(self.settings_folder, 'downloader.log')\n", (7647, 7687), False, 'import os\n'), ((10983, 11029), 'office365.runtime.auth.authentication_context.AuthenticationContext', 'AuthenticationContext', ([], {'url': 'SHAREPOINT_SITE_URL'}), '(url=SHAREPOINT_SITE_URL)\n', (11004, 11029), False, 'from office365.runtime.auth.authentication_context import AuthenticationContext\n'), ((11196, 11244), 'office365.sharepoint.client_context.ClientContext', 'ClientContext', (['SHAREPOINT_SITE_URL', 'context_auth'], {}), '(SHAREPOINT_SITE_URL, context_auth)\n', (11209, 11244), False, 'from office365.sharepoint.client_context import ClientContext\n'), ((15630, 15651), 'psutil.process_iter', 'psutil.process_iter', ([], {}), '()\n', (15649, 15651), False, 'import psutil\n'), ((16739, 16772), 'os.path.isfile', 'os.path.isfile', (['product_installed'], {}), '(product_installed)\n', (16753, 16772), False, 'import os\n'), ((18868, 18935), 'logging.info', 'logging.info', (['f"""Version on artifactory/SP is {new_product_version}"""'], {}), "(f'Version on artifactory/SP is {new_product_version}')\n", (18880, 18935), False, 'import logging\n'), ((20156, 20242), 'artifactory.ArtifactoryPath', 'ArtifactoryPath', (['server'], {'auth': '(self.settings.username, password)', 'timeout': 'TIMEOUT'}), '(server, auth=(self.settings.username, password), timeout=\n TIMEOUT)\n', (20171, 20242), False, 'from artifactory import ArtifactoryPath\n'), ((24580, 24668), 'os.path.join', 'os.path.join', (['self.settings.download_path', 'f"""{self.settings.version}.{archive_type}"""'], {}), "(self.settings.download_path,\n f'{self.settings.version}.{archive_type}')\n", (24592, 24668), False, 'import os\n'), ((24925, 24979), 'logging.info', 'logging.info', (['f"""File is downloaded to {self.zip_file}"""'], {}), "(f'File is downloaded to {self.zip_file}')\n", (24937, 24979), False, 'import logging\n'), ((25578, 25678), 'logging.info', 'logging.info', (['f"""Start download file from {self.build_artifactory_path} to {self.zip_file}"""'], {}), "(\n f'Start download file from {self.build_artifactory_path} to {self.zip_file}'\n )\n", (25590, 25678), False, 'import logging\n'), ((27342, 27516), 'artifactory_du.artifactory_du.prepare_aql', 'artifactory_du.prepare_aql', ([], {'file': 'f"""/{self.build_artifactory_path.name}"""', 'max_depth': '(0)', 'repository': 'self.build_artifactory_path.repo', 'without_downloads': '""""""', 'older_than': '""""""'}), "(file=f'/{self.build_artifactory_path.name}',\n max_depth=0, repository=self.build_artifactory_path.repo,\n without_downloads='', older_than='')\n", (27368, 27516), False, 'from artifactory_du import artifactory_du\n'), ((27943, 28017), 'artifactory_du.artifactory_du.out_as_du', 'artifactory_du.out_as_du', (['artifacts', 'max_depth_print'], {'human_readable': '(False)'}), '(artifacts, max_depth_print, human_readable=False)\n', (27967, 28017), False, 'from artifactory_du import artifactory_du\n'), ((30423, 30440), 'logging.info', 'logging.info', (['msg'], {}), '(msg)\n', (30435, 30440), False, 'import logging\n'), ((31941, 32002), 'logging.info', 'logging.info', (['f"""File is unpacked to {self.target_unpack_dir}"""'], {}), "(f'File is unpacked to {self.target_unpack_dir}')\n", (31953, 32002), False, 'import logging\n'), ((32839, 32875), 'logging.info', 'logging.info', (['"""Execute installation"""'], {}), "('Execute installation')\n", (32851, 32875), False, 'import logging\n'), ((33138, 33189), 'os.path.join', 'os.path.join', (['self.target_unpack_dir', '"""install.iss"""'], {}), "(self.target_unpack_dir, 'install.iss')\n", (33150, 33189), False, 'import os\n'), ((33217, 33268), 'os.path.join', 'os.path.join', (['self.target_unpack_dir', '"""install.log"""'], {}), "(self.target_unpack_dir, 'install.log')\n", (33229, 33268), False, 'import os\n'), ((34932, 34975), 'os.path.isfile', 'os.path.isfile', (['self.installed_product_info'], {}), '(self.installed_product_info)\n', (34946, 34975), False, 'import os\n'), ((37783, 37816), 'os.path.isfile', 'os.path.isfile', (['product_info_file'], {}), '(product_info_file)\n', (37797, 37816), False, 'import os\n'), ((38994, 39015), 'os.walk', 'os.walk', (['unpacked_dir'], {}), '(unpacked_dir)\n', (39001, 39015), False, 'import os\n'), ((40356, 40405), 'os.path.join', 'os.path.join', (['self.target_unpack_dir', '"""setup.exe"""'], {}), "(self.target_unpack_dir, 'setup.exe')\n", (40368, 40405), False, 'import os\n'), ((40418, 40448), 'os.path.isfile', 'os.path.isfile', (['self.setup_exe'], {}), '(self.setup_exe)\n', (40432, 40448), False, 'import os\n'), ((41859, 41912), 'os.path.join', 'os.path.join', (['self.target_unpack_dir', '"""builddate.txt"""'], {}), "(self.target_unpack_dir, 'builddate.txt')\n", (41871, 41912), False, 'import os\n'), ((41941, 42002), 'os.path.join', 'os.path.join', (['self.target_unpack_dir', '"""lmcenter"""', '"""WINX64.7z"""'], {}), "(self.target_unpack_dir, 'lmcenter', 'WINX64.7z')\n", (41953, 42002), False, 'import os\n'), ((43430, 43490), 'os.path.join', 'os.path.join', (['self.product_root_path', '"""lmcenter_blddate.txt"""'], {}), "(self.product_root_path, 'lmcenter_blddate.txt')\n", (43442, 43490), False, 'import os\n'), ((44302, 44351), 'os.path.join', 'os.path.join', (['self.target_unpack_dir', '"""setup.exe"""'], {}), "(self.target_unpack_dir, 'setup.exe')\n", (44314, 44351), False, 'import os\n'), ((44364, 44394), 'os.path.isfile', 'os.path.isfile', (['self.setup_exe'], {}), '(self.setup_exe)\n', (44378, 44394), False, 'import os\n'), ((46861, 46914), 'os.path.join', 'os.path.join', (['self.product_root_path', '"""Uninstall.exe"""'], {}), "(self.product_root_path, 'Uninstall.exe')\n", (46873, 46914), False, 'import os\n'), ((46926, 46955), 'os.path.isfile', 'os.path.isfile', (['uninstall_exe'], {}), '(uninstall_exe)\n', (46940, 46955), False, 'import os\n'), ((48251, 48283), 'logging.info', 'logging.info', (['f"""Removing {path}"""'], {}), "(f'Removing {path}')\n", (48263, 48283), False, 'import logging\n'), ((48295, 48314), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (48308, 48314), False, 'import os\n'), ((51907, 51956), 'os.path.join', 'os.path.join', (['self.settings_folder', '"""HPC_Options"""'], {}), "(self.settings_folder, 'HPC_Options')\n", (51919, 51956), False, 'import os\n'), ((51988, 52046), 'os.path.join', 'os.path.join', (['self.product_root_path', '"""UpdateRegistry.exe"""'], {}), "(self.product_root_path, 'UpdateRegistry.exe')\n", (52000, 52046), False, 'import os\n'), ((52074, 52139), 'os.path.join', 'os.path.join', (['self.product_root_path', '"""config"""', '"""ProductList.txt"""'], {}), "(self.product_root_path, 'config', 'ProductList.txt')\n", (52086, 52139), False, 'import os\n'), ((52516, 52541), 'os.path.isdir', 'os.path.isdir', (['hpc_folder'], {}), '(hpc_folder)\n', (52529, 52541), False, 'import os\n'), ((54510, 54538), 'os.path.dirname', 'os.path.dirname', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (54525, 54538), False, 'import os\n'), ((54559, 54605), 'os.path.join', 'os.path.join', (['root_path', '"""notifications"""', 'icon'], {}), "(root_path, 'notifications', icon)\n", (54571, 54605), False, 'import os\n'), ((54809, 54895), 'plyer.notification.notify', 'notification.notify', ([], {'title': 'status', 'message': 'details', 'app_icon': 'icon_path', 'timeout': '(15)'}), '(title=status, message=details, app_icon=icon_path,\n timeout=15)\n', (54828, 54895), False, 'from plyer import notification\n'), ((55153, 55186), 'os.path.isfile', 'os.path.isfile', (['self.history_file'], {}), '(self.history_file)\n', (55167, 55186), False, 'import os\n'), ((55900, 55945), 'os.getenv', 'os.getenv', (['"""username"""', 'self.settings.username'], {}), "('username', self.settings.username)\n", (55909, 55945), False, 'import os\n'), ((56595, 56655), 'influxdb.InfluxDBClient', 'InfluxDBClient', ([], {'host': 'STATISTICS_SERVER', 'port': 'STATISTICS_PORT'}), '(host=STATISTICS_SERVER, port=STATISTICS_PORT)\n', (56609, 56655), False, 'from influxdb import InfluxDBClient\n'), ((59763, 59788), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (59786, 59788), False, 'import argparse\n'), ((60836, 60859), 'os.path.isdir', 'os.path.isdir', (['work_dir'], {}), '(work_dir)\n', (60849, 60859), False, 'import os\n'), ((60869, 60890), 'os.makedirs', 'os.makedirs', (['work_dir'], {}), '(work_dir)\n', (60880, 60890), False, 'import os\n'), ((61254, 61277), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (61275, 61277), False, 'import logging\n'), ((7086, 7097), 'os.getpid', 'os.getpid', ([], {}), '()\n', (7095, 7097), False, 'import os\n'), ((7263, 7318), 'os.path.join', 'os.path.join', (["os.environ['APPDATA']", '"""build_downloader"""'], {}), "(os.environ['APPDATA'], 'build_downloader')\n", (7275, 7318), False, 'import os\n'), ((9173, 9225), 'os.path.join', 'os.path.join', (['self.product_root_path', '"""product.info"""'], {}), "(self.product_root_path, 'product.info')\n", (9185, 9225), False, 'import os\n'), ((11462, 11523), 'logging.info', 'logging.info', (['f"""Settings path is set to {self.settings_path}"""'], {}), "(f'Settings path is set to {self.settings_path}')\n", (11474, 11523), False, 'import logging\n'), ((16491, 16541), 'os.path.join', 'os.path.join', (['self.product_root_path', '"""package.id"""'], {}), "(self.product_root_path, 'package.id')\n", (16503, 16541), False, 'import os\n'), ((17312, 17414), 'logging.info', 'logging.info', (['f"""Installed version of {self.settings.version} is {installed_product_version}"""'], {}), "(\n f'Installed version of {self.settings.version} is {installed_product_version}'\n )\n", (17324, 17414), False, 'import logging\n'), ((18570, 18624), 'logging.info', 'logging.info', (['f"""Request info about new package: {url}"""'], {}), "(f'Request info about new package: {url}')\n", (18582, 18624), False, 'import logging\n'), ((25989, 26039), 'logging.info', 'logging.info', (['f"""Artifactory hash: {arti_file_md5}"""'], {}), "(f'Artifactory hash: {arti_file_md5}')\n", (26001, 26039), False, 'import logging\n'), ((26403, 26424), 'artifactory.md5sum', 'md5sum', (['self.zip_file'], {}), '(self.zip_file)\n', (26409, 26424), False, 'from artifactory import md5sum\n'), ((26437, 26487), 'logging.info', 'logging.info', (['f"""Local file hash: {local_md5_hash}"""'], {}), "(f'Local file hash: {local_md5_hash}')\n", (26449, 26487), False, 'import logging\n'), ((33409, 33494), 'os.path.join', 'os.path.join', (['os.environ[awp_env_var]', '"""Framework"""', '"""bin"""', '"""Win64"""', '"""RunWB2.exe"""'], {}), "(os.environ[awp_env_var], 'Framework', 'bin', 'Win64', 'RunWB2.exe'\n )\n", (33421, 33494), False, 'import os\n'), ((33505, 33527), 'os.path.isfile', 'os.path.isfile', (['run_wb'], {}), '(run_wb)\n', (33519, 33527), False, 'import os\n'), ((33888, 33988), 'os.path.join', 'os.path.join', (['self.settings.install_path', '"""AnsysEM"""', '"""Shared Files"""', '"""Licensing"""', '"""ansyslmd.ini"""'], {}), "(self.settings.install_path, 'AnsysEM', 'Shared Files',\n 'Licensing', 'ansyslmd.ini')\n", (33900, 33988), False, 'import os\n'), ((34092, 34152), 'logging.info', 'logging.info', (['"""Install using existing license configuration"""'], {}), "('Install using existing license configuration')\n", (34104, 34152), False, 'import logging\n'), ((34258, 34331), 'logging.info', 'logging.info', (['"""Install using 127.0.0.1, Otterfing and HQ license servers"""'], {}), "('Install using 127.0.0.1, Otterfing and HQ license servers')\n", (34270, 34331), False, 'import logging\n'), ((35010, 35063), 'os.path.join', 'os.path.join', (['self.target_unpack_dir', '"""uninstall.iss"""'], {}), "(self.target_unpack_dir, 'uninstall.iss')\n", (35022, 35063), False, 'import os\n'), ((35097, 35150), 'os.path.join', 'os.path.join', (['self.target_unpack_dir', '"""uninstall.log"""'], {}), "(self.target_unpack_dir, 'uninstall.log')\n", (35109, 35150), False, 'import os\n'), ((35573, 35611), 'logging.info', 'logging.info', (['"""Execute uninstallation"""'], {}), "('Execute uninstallation')\n", (35585, 35611), False, 'import logging\n'), ((35846, 35885), 'os.path.dirname', 'os.path.dirname', (['self.product_root_path'], {}), '(self.product_root_path)\n', (35861, 35885), False, 'import os\n'), ((35944, 35970), 'os.path.isdir', 'os.path.isdir', (['em_main_dir'], {}), '(em_main_dir)\n', (35957, 35970), False, 'import os\n'), ((36102, 36163), 'logging.info', 'logging.info', (['"""Version is not installed, skip uninstallation"""'], {}), "('Version is not installed, skip uninstallation')\n", (36114, 36163), False, 'import logging\n'), ((36692, 36716), 'os.path.isfile', 'os.path.isfile', (['log_file'], {}), '(log_file)\n', (36706, 36716), False, 'import os\n'), ((39428, 39453), 'os.path.isfile', 'os.path.isfile', (['setup_exe'], {}), '(setup_exe)\n', (39442, 39453), False, 'import os\n'), ((40020, 40063), 'logging.info', 'logging.info', (['f"""Product ID is {product_id}"""'], {}), "(f'Product ID is {product_id}')\n", (40032, 40063), False, 'import logging\n'), ((40477, 40530), 'os.path.join', 'os.path.join', (['self.settings.install_path', '"""ANSYS Inc"""'], {}), "(self.settings.install_path, 'ANSYS Inc')\n", (40489, 40530), False, 'import os\n'), ((41115, 41151), 'logging.info', 'logging.info', (['"""Execute installation"""'], {}), "('Execute installation')\n", (41127, 41151), False, 'import logging\n'), ((42050, 42083), 'os.path.isfile', 'os.path.isfile', (['lm_center_archive'], {}), '(lm_center_archive)\n', (42064, 42083), False, 'import os\n'), ((42272, 42398), 'os.path.join', 'os.path.join', (['self.target_unpack_dir', '"""lmcenter"""', '"""Shared Files"""', '"""licensing"""', '"""tools"""', '"""lmcenter"""', '"""lmcenter_blddate.txt"""'], {}), "(self.target_unpack_dir, 'lmcenter', 'Shared Files',\n 'licensing', 'tools', 'lmcenter', 'lmcenter_blddate.txt')\n", (42284, 42398), False, 'import os\n'), ((42538, 42564), 'os.path.isfile', 'os.path.isfile', (['build_file'], {}), '(build_file)\n', (42552, 42564), False, 'import os\n'), ((42625, 42695), 'logging.warning', 'logging.warning', (['"""builddate.txt was not found in installation package"""'], {}), "('builddate.txt was not found in installation package')\n", (42640, 42695), False, 'import logging\n'), ((43506, 43537), 'os.path.isfile', 'os.path.isfile', (['build_date_file'], {}), '(build_date_file)\n', (43520, 43537), False, 'import os\n'), ((44472, 44525), 'os.path.join', 'os.path.join', (['self.settings.install_path', '"""ANSYS Inc"""'], {}), "(self.settings.install_path, 'ANSYS Inc')\n", (44484, 44525), False, 'import os\n'), ((45523, 45555), 'subprocess.list2cmdline', 'subprocess.list2cmdline', (['command'], {}), '(command)\n', (45546, 45555), False, 'import subprocess\n'), ((45722, 45758), 'logging.info', 'logging.info', (['"""Execute installation"""'], {}), "('Execute installation')\n", (45734, 45758), False, 'import logging\n'), ((45817, 45846), 'os.path.isfile', 'os.path.isfile', (['uninstall_exe'], {}), '(uninstall_exe)\n', (45831, 45846), False, 'import os\n'), ((47121, 47159), 'logging.info', 'logging.info', (['"""Execute uninstallation"""'], {}), "('Execute uninstallation')\n", (47133, 47159), False, 'import logging\n'), ((47214, 47278), 'logging.info', 'logging.info', (['"""Previous build was uninstalled using uninstaller"""'], {}), "('Previous build was uninstalled using uninstaller')\n", (47226, 47278), False, 'import logging\n'), ((47305, 47361), 'logging.info', 'logging.info', (['"""No Workbench Uninstall.exe file detected"""'], {}), "('No Workbench Uninstall.exe file detected')\n", (47317, 47361), False, 'import logging\n'), ((48895, 48915), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (48909, 48915), False, 'import os\n'), ((50136, 50173), 'os.path.isdir', 'os.path.isdir', (['self.target_unpack_dir'], {}), '(self.target_unpack_dir)\n', (50149, 50173), False, 'import os\n'), ((50738, 50759), 'os.getenv', 'os.getenv', (['"""username"""'], {}), "('username')\n", (50747, 50759), False, 'import os\n'), ((50846, 50892), 'os.path.join', 'os.path.join', (['"""C:\\\\"""', '"""Users"""', 'user', '"""Desktop"""'], {}), "('C:\\\\', 'Users', user, 'Desktop')\n", (50858, 50892), False, 'import os\n'), ((51219, 51333), 'os.path.join', 'os.path.join', (['desktop', 'f"""20{self.product_version[:2]}R{self.product_version[2:]} Electronics Desktop.lnk"""'], {}), "(desktop,\n f'20{self.product_version[:2]}R{self.product_version[2:]} Electronics Desktop.lnk'\n )\n", (51231, 51333), False, 'import os\n'), ((51383, 51437), 'os.path.join', 'os.path.join', (['desktop', '"""ANSYS Electronics Desktop.lnk"""'], {}), "(desktop, 'ANSYS Electronics Desktop.lnk')\n", (51395, 51437), False, 'import os\n'), ((52156, 52188), 'os.path.isfile', 'os.path.isfile', (['productlist_file'], {}), '(productlist_file)\n', (52170, 52188), False, 'import os\n'), ((52567, 52589), 'os.listdir', 'os.listdir', (['hpc_folder'], {}), '(hpc_folder)\n', (52577, 52589), False, 'import os\n'), ((53728, 53755), 'os.getenv', 'os.getenv', (['"""APPDATA"""', '"""@@@"""'], {}), "('APPDATA', '@@@')\n", (53737, 53755), False, 'import os\n'), ((54137, 54176), 'json.dump', 'json.dump', (['self.history', 'file'], {'indent': '(4)'}), '(self.history, file, indent=4)\n', (54146, 54176), False, 'import json\n'), ((54622, 54647), 'os.path.isfile', 'os.path.isfile', (['icon_path'], {}), '(icon_path)\n', (54636, 54647), False, 'import os\n'), ((54741, 54787), 'os.path.join', 'os.path.join', (['root_path', '"""notifications"""', 'icon'], {}), "(root_path, 'notifications', icon)\n", (54753, 54787), False, 'import os\n'), ((58942, 58967), 'logging.info', 'logging.info', (['command_str'], {}), '(command_str)\n', (58954, 58967), False, 'import logging\n'), ((61223, 61242), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (61240, 61242), False, 'import logging\n'), ((8713, 8805), 'os.path.join', 'os.path.join', (['self.settings.install_path', '"""AnsysEM"""', 'f"""v{self.product_version}"""', '"""Win64"""'], {}), "(self.settings.install_path, 'AnsysEM',\n f'v{self.product_version}', 'Win64')\n", (8725, 8805), False, 'import os\n'), ((8899, 9035), 'os.path.join', 'os.path.join', (['self.settings.install_path', '"""AnsysEM"""', "('AnsysEM' + self.product_version[:2] + '.' + self.product_version[2:])", '"""Win64"""'], {}), "(self.settings.install_path, 'AnsysEM', 'AnsysEM' + self.\n product_version[:2] + '.' + self.product_version[2:], 'Win64')\n", (8911, 9035), False, 'import os\n'), ((9314, 9399), 'os.path.join', 'os.path.join', (['self.settings.install_path', '"""ANSYS Inc"""', 'self.settings.version[:4]'], {}), "(self.settings.install_path, 'ANSYS Inc', self.settings.version[:4]\n )\n", (9326, 9399), False, 'import os\n'), ((13549, 13565), 'logging.error', 'logging.error', (['e'], {}), '(e)\n', (13562, 13565), False, 'import logging\n'), ((14223, 14242), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (14236, 14242), False, 'import os\n'), ((15052, 15075), 'shutil.disk_usage', 'shutil.disk_usage', (['path'], {}), '(path)\n', (15069, 15075), False, 'import shutil\n'), ((31425, 31460), 'zipfile.ZipFile', 'zipfile.ZipFile', (['self.zip_file', '"""r"""'], {}), "(self.zip_file, 'r')\n", (31440, 31460), False, 'import zipfile\n'), ((33578, 33630), 'logging.info', 'logging.info', (['"""Integration with Workbench turned ON"""'], {}), "('Integration with Workbench turned ON')\n", (33590, 33630), False, 'import logging\n'), ((36965, 36988), 're.findall', 're.findall', (['regex', 'line'], {}), '(regex, line)\n', (36975, 36988), False, 'import re\n'), ((40550, 40592), 'os.path.isfile', 'os.path.isfile', (['self.settings.license_file'], {}), '(self.settings.license_file)\n', (40564, 40592), False, 'import os\n'), ((42019, 42045), 'os.path.isfile', 'os.path.isfile', (['build_file'], {}), '(build_file)\n', (42033, 42045), False, 'import os\n'), ((42102, 42144), 'py7zr.SevenZipFile', 'py7zr.SevenZipFile', (['lm_center_archive', '"""r"""'], {}), "(lm_center_archive, 'r')\n", (42120, 42144), False, 'import py7zr\n'), ((43743, 43822), 'logging.info', 'logging.info', (['f"""Newly installed build date of License Manager: {lm_build_date}"""'], {}), "(f'Newly installed build date of License Manager: {lm_build_date}')\n", (43755, 43822), False, 'import logging\n'), ((45168, 45228), 'logging.info', 'logging.info', (['"""Install using existing license configuration"""'], {}), "('Install using existing license configuration')\n", (45180, 45228), False, 'import logging\n'), ((45358, 45431), 'logging.info', 'logging.info', (['"""Install using 127.0.0.1, Otterfing and HQ license servers"""'], {}), "('Install using 127.0.0.1, Otterfing and HQ license servers')\n", (45370, 45431), False, 'import logging\n'), ((45864, 45903), 'logging.info', 'logging.info', (['"""New build was installed"""'], {}), "('New build was installed')\n", (45876, 45903), False, 'import logging\n'), ((46199, 46290), 'os.path.join', 'os.path.join', (['self.settings.wb_assoc', '"""commonfiles"""', '"""tools"""', '"""winx64"""', '"""fileassoc.exe"""'], {}), "(self.settings.wb_assoc, 'commonfiles', 'tools', 'winx64',\n 'fileassoc.exe')\n", (46211, 46290), False, 'import os\n'), ((47745, 47770), 'os.path.join', 'os.path.join', (['path', '"""*.*"""'], {}), "(path, '*.*')\n", (47757, 47770), False, 'import os\n'), ((48349, 48368), 'shutil.rmtree', 'shutil.rmtree', (['path'], {}), '(path)\n', (48362, 48368), False, 'import shutil\n'), ((48929, 48944), 'os.remove', 'os.remove', (['path'], {}), '(path)\n', (48938, 48944), False, 'import os\n'), ((49968, 49997), 'os.path.isfile', 'os.path.isfile', (['self.zip_file'], {}), '(self.zip_file)\n', (49982, 49997), False, 'import os\n'), ((50092, 50119), 'logging.info', 'logging.info', (['"""ZIP deleted"""'], {}), "('ZIP deleted')\n", (50104, 50119), False, 'import logging\n'), ((50248, 50290), 'logging.info', 'logging.info', (['"""Unpacked directory removed"""'], {}), "('Unpacked directory removed')\n", (50260, 50290), False, 'import logging\n'), ((50335, 50407), 'logging.error', 'logging.error', (['"""Temp files could not be removed due to permission error"""'], {}), "('Temp files could not be removed due to permission error')\n", (50348, 50407), False, 'import logging\n'), ((50774, 50795), 'os.getenv', 'os.getenv', (['"""username"""'], {}), "('username')\n", (50783, 50795), False, 'import os\n'), ((51457, 51481), 'os.path.isfile', 'os.path.isfile', (['new_name'], {}), '(new_name)\n', (51471, 51481), False, 'import os\n'), ((53627, 53650), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (53648, 53650), False, 'import datetime\n'), ((54689, 54715), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (54705, 54715), False, 'import os\n'), ((55809, 55835), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (55833, 55835), False, 'import datetime\n'), ((58841, 58873), 'subprocess.list2cmdline', 'subprocess.list2cmdline', (['command'], {}), '(command)\n', (58864, 58873), False, 'import subprocess\n'), ((59011, 59124), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'stdin': 'subprocess.PIPE', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE', 'shell': 'shell'}), '(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, shell=shell)\n', (59027, 59124), False, 'import subprocess\n'), ((59334, 59371), 'subprocess.call', 'subprocess.call', (['command'], {'shell': 'shell'}), '(command, shell=shell)\n', (59349, 59371), False, 'import subprocess\n'), ((60145, 60174), 'os.path.isfile', 'os.path.isfile', (['settings_path'], {}), '(settings_path)\n', (60159, 60174), False, 'import os\n'), ((9488, 9595), 'os.path.join', 'os.path.join', (['self.settings.install_path', '"""ANSYS Inc"""', '"""Shared Files"""', '"""Licensing"""', '"""tools"""', '"""lmcenter"""'], {}), "(self.settings.install_path, 'ANSYS Inc', 'Shared Files',\n 'Licensing', 'tools', 'lmcenter')\n", (9500, 9595), False, 'import os\n'), ((12289, 12331), 'os.path.isfile', 'os.path.isfile', (['self.settings.license_file'], {}), '(self.settings.license_file)\n', (12303, 12331), False, 'import os\n'), ((13696, 13718), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (13716, 13718), False, 'import traceback\n'), ((14285, 14302), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (14296, 14302), False, 'import os\n'), ((26808, 26880), 'logging.info', 'logging.info', (['f"""Workbench/License Manager real file size is {file_size}"""'], {}), "(f'Workbench/License Manager real file size is {file_size}')\n", (26820, 26880), False, 'import logging\n'), ((30040, 30070), 'os.path.getsize', 'os.path.getsize', (['self.zip_file'], {}), '(self.zip_file)\n', (30055, 30070), False, 'import os\n'), ((34494, 34545), 'os.path.join', 'os.path.join', (['self.settings.install_path', '"""AnsysEM"""'], {}), "(self.settings.install_path, 'AnsysEM')\n", (34506, 34545), False, 'import os\n'), ((35234, 35303), 'iss_templates.uninstall_iss.format', 'iss_templates.uninstall_iss.format', (['product_id', 'installshield_version'], {}), '(product_id, installshield_version)\n', (35268, 35303), False, 'import iss_templates\n'), ((37053, 37074), 'logging.info', 'logging.info', (['success'], {}), '(success)\n', (37065, 37074), False, 'import logging\n'), ((37250, 37268), 'logging.error', 'logging.error', (['msg'], {}), '(msg)\n', (37263, 37268), False, 'import logging\n'), ((39168, 39200), 'os.path.join', 'os.path.join', (['dir_path', 'filename'], {}), '(dir_path, filename)\n', (39180, 39200), False, 'import os\n'), ((39233, 39268), 'os.path.join', 'os.path.join', (['dir_path', '"""setup.exe"""'], {}), "(dir_path, 'setup.exe')\n", (39245, 39268), False, 'import os\n'), ((39780, 39808), 're.findall', 're.findall', (['guid_regex', 'line'], {}), '(guid_regex, line)\n', (39790, 39808), False, 'import re\n'), ((45007, 45078), 'os.path.join', 'os.path.join', (['install_path', '"""Shared Files"""', '"""Licensing"""', '"""ansyslmd.ini"""'], {}), "(install_path, 'Shared Files', 'Licensing', 'ansyslmd.ini')\n", (45019, 45078), False, 'import os\n'), ((46310, 46338), 'os.path.isfile', 'os.path.isfile', (['wb_assoc_exe'], {}), '(wb_assoc_exe)\n', (46324, 46338), False, 'import os\n'), ((46459, 46498), 'logging.info', 'logging.info', (['"""Run WB file association"""'], {}), "('Run WB file association')\n", (46471, 46498), False, 'import logging\n'), ((48110, 48169), 'logging.error', 'logging.error', (['"""Failed to remove directory via hard_remove"""'], {}), "('Failed to remove directory via hard_remove')\n", (48123, 48169), False, 'import logging\n'), ((48421, 48482), 'logging.warning', 'logging.warning', (['"""Permission error. Switch to CMD force mode"""'], {}), "('Permission error. Switch to CMD force mode')\n", (48436, 48482), False, 'import logging\n'), ((48679, 48756), 'logging.warning', 'logging.warning', (['"""FileNotFoundError or other error. Switch to CMD force mode"""'], {}), "('FileNotFoundError or other error. Switch to CMD force mode')\n", (48694, 48756), False, 'import logging\n'), ((51153, 51193), 'os.path.join', 'os.path.join', (['desktop', "(shortcut + '.lnk')"], {}), "(desktop, shortcut + '.lnk')\n", (51165, 51193), False, 'import os\n'), ((51524, 51558), 'os.rename', 'os.rename', (['aedt_shortcut', 'new_name'], {}), '(aedt_shortcut, new_name)\n', (51533, 51558), False, 'import os\n'), ((52661, 52691), 'os.path.join', 'os.path.join', (['hpc_folder', 'file'], {}), '(hpc_folder, file)\n', (52673, 52691), False, 'import os\n'), ((52824, 52855), 'logging.info', 'logging.info', (['"""Update registry"""'], {}), "('Update registry')\n", (52836, 52855), False, 'import logging\n'), ((53443, 53461), 'logging.error', 'logging.error', (['msg'], {}), '(msg)\n', (53456, 53461), False, 'import logging\n'), ((55294, 55309), 'json.load', 'json.load', (['file'], {}), '(file)\n', (55303, 55309), False, 'import json\n'), ((60532, 60554), 'random.getrandbits', 'random.getrandbits', (['(32)'], {}), '(32)\n', (60550, 60554), False, 'import random\n'), ((3912, 3930), 'time.sleep', 'time.sleep', (['mdelay'], {}), '(mdelay)\n', (3922, 3930), False, 'import time\n'), ((7897, 7917), 'types.SimpleNamespace', 'SimpleNamespace', ([], {}), '(**d)\n', (7912, 7917), False, 'from types import SimpleNamespace\n'), ((13859, 13881), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (13879, 13881), False, 'import traceback\n'), ((42197, 42245), 'os.path.join', 'os.path.join', (['self.target_unpack_dir', '"""lmcenter"""'], {}), "(self.target_unpack_dir, 'lmcenter')\n", (42209, 42245), False, 'import os\n'), ((42951, 43042), 'logging.info', 'logging.info', (['f"""Build date of License Manager in installation package {lm_build_date}"""'], {}), "(\n f'Build date of License Manager in installation package {lm_build_date}')\n", (42963, 43042), False, 'import logging\n')] |
import unittest
from dmLibrary import create_app
from dmLibrary.external.googleBook import GoogleBook
import time
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class TestClass(unittest.TestCase):
def setUp(self):
app = create_app()
self.ctx = app.app_context()
self.ctx.push()
self.client = app.test_client()
self.gb = GoogleBook()
logger.debug('logged from test_something')
def tearDown(self):
"""Do the testing """
pass
def test_lentBook(self):
"""
test lent book
"""
# ===== populate book and customer need for testing ======
# book 1
data = {
"title":"ทายชีวิตคู่ด้วยเลข ๗ ตัว",
"isbn":"9789740212201"
}
response = self.client.post('/api/v1/books',json=data)
logger.info(f"rawResp: {response.status_code}")
if not ((response.status_code == 200) or (response.status_code == 201)):
self.fail("book1 cannot be create")
respData = response.get_json()
book1_id = respData["data"]["id"]
# customerA
data = {
"name":"<NAME>",
"email":"<EMAIL>",
"mobile":"0881111111"
}
response = self.client.post('/api/v1/customers',json=data)
if not ((response.status_code == 200) or (response.status_code == 201)) :
self.fail("customerA cannot be create")
respData = response.get_json()
customerA_id = respData["data"]["id"]
# customerB
data = {
"name":"<NAME>",
"email":"<EMAIL>",
"mobile":"0881111112"
}
response = self.client.post('/api/v1/customers',json=data)
if not ((response.status_code == 200) or (response.status_code == 201)) :
self.fail("customerB cannot be create")
respData = response.get_json()
customerB_id = respData["data"]["id"]
#check if book1 being lent
logger.info(f"getting book1 data: /api/v1/books/{book1_id}")
response = self.client.get(f'/api/v1/books/{book1_id}')
logger.info(f"rawResp: {response.status_code}")
if not (response.status_code == 200):
self.fail("cannot get book1 data")
respData = response.get_json()
self.assertEqual(respData["data"]['isLent'], False)
# ==== get history before lent
response = self.client.get(f'/api/v1/lentHistory?book_id={book1_id}')
if not (response.status_code == 200):
self.fail("cannot get lentHistory")
respData = response.get_json()
lentCount = len(respData["data"])
# customerA lent the book
data ={
"book_id_list":[book1_id]
}
logger.info(f"lenting book: /api/v1/customers/{customerA_id}/lent")
response = self.client.post(f'/api/v1/customers/{customerA_id}/lent',json=data)
if not (response.status_code == 200):
self.fail("customerA cannot lent book1")
respData = response.get_json()
customerA_id = respData["data"]["id"]
#check if book1 being lent
logger.info(f"getting book1 data: /api/v1/books/{book1_id}")
response = self.client.get(f'/api/v1/books/{book1_id}')
logger.info(f"rawResp: {response.status_code}")
if not (response.status_code == 200):
self.fail("cannot get book1 data")
respData = response.get_json()
self.assertEqual(respData["data"]['isLent'], True)
# customerB shouldn't be able to lent
data ={
"book_id_list":[book1_id]
}
response = self.client.post(f'/api/v1/customers/{customerB_id}/lent',json=data)
if not (response.status_code == 400):
self.fail("customerA somehow be able to lent the book")
# customerA return the book
response = self.client.post(f'/api/v1/customers/{customerA_id}/return',json=data)
if not (response.status_code == 200):
self.fail("customerA cannot return the book")
respData = response.get_json()
customerA_id = respData["data"]["id"]
#check if book1 not being lent
logger.info(f"getting book1 data: /api/v1/books/{book1_id}")
response = self.client.get(f'/api/v1/books/{book1_id}')
logger.info(f"rawResp: {response.status_code}")
if not (response.status_code == 200):
self.fail("cannot get book1 data")
respData = response.get_json()
self.assertEqual(respData["data"]['isLent'], False)
# ==== check history after lent
response = self.client.get(f'/api/v1/lentHistory?book_id={book1_id}',json=data)
if not (response.status_code == 200):
self.fail("cannot get lentHistory")
respData = response.get_json()
lentCountNew = len(respData["data"])
self.assertEqual(lentCountNew, lentCount+1)
| [
"logging.basicConfig",
"dmLibrary.create_app",
"logging.getLogger",
"dmLibrary.external.googleBook.GoogleBook"
] | [((130, 169), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (149, 169), False, 'import logging\n'), ((179, 206), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (196, 206), False, 'import logging\n'), ((279, 291), 'dmLibrary.create_app', 'create_app', ([], {}), '()\n', (289, 291), False, 'from dmLibrary import create_app\n'), ((411, 423), 'dmLibrary.external.googleBook.GoogleBook', 'GoogleBook', ([], {}), '()\n', (421, 423), False, 'from dmLibrary.external.googleBook import GoogleBook\n')] |
# pylint: disable=global-statement
"""
Module providing unittest test discovery hook for our Doctest testcases
Copyright (C) 2015, 2016 ERT Inc.
"""
import unittest
import doctest
from time import sleep
from api import app_module as app
from api import (
config_loader
,aes
,json
,resource_util
)
__author__ = "<NAME> <<EMAIL>>, "
pentaho_stopped = False
def app_stop_pentaho():
"""
helper function, to stop the WSGI app's configured Carte server
"""
global pentaho_stopped
while all((app.pentaho_started, not pentaho_stopped)):
if app.pentaho_controller.status():
app.pentaho_controller.stop()
pentaho_stopped = True
return
sleep(2)
def load_tests(loader, tests, ignore):
"""
Expose Doctest testcases to unitest discovery
per: https://docs.python.org/3/library/doctest.html#unittest-api
"""
app_doctests = doctest.DocTestSuite(app)
for app_doctest in app_doctests:
app_doctest.addCleanup(app_stop_pentaho)
tests.addTests(app_doctests)
tests.addTests(doctest.DocTestSuite(config_loader))
tests.addTests(doctest.DocTestSuite(aes))
tests.addTests(doctest.DocTestSuite(json))
tests.addTests(doctest.DocTestSuite(resource_util))
return tests
| [
"time.sleep",
"doctest.DocTestSuite",
"api.app_module.pentaho_controller.stop",
"api.app_module.pentaho_controller.status"
] | [((926, 951), 'doctest.DocTestSuite', 'doctest.DocTestSuite', (['app'], {}), '(app)\n', (946, 951), False, 'import doctest\n'), ((581, 612), 'api.app_module.pentaho_controller.status', 'app.pentaho_controller.status', ([], {}), '()\n', (610, 612), True, 'from api import app_module as app\n'), ((718, 726), 'time.sleep', 'sleep', (['(2)'], {}), '(2)\n', (723, 726), False, 'from time import sleep\n'), ((1090, 1125), 'doctest.DocTestSuite', 'doctest.DocTestSuite', (['config_loader'], {}), '(config_loader)\n', (1110, 1125), False, 'import doctest\n'), ((1146, 1171), 'doctest.DocTestSuite', 'doctest.DocTestSuite', (['aes'], {}), '(aes)\n', (1166, 1171), False, 'import doctest\n'), ((1192, 1218), 'doctest.DocTestSuite', 'doctest.DocTestSuite', (['json'], {}), '(json)\n', (1212, 1218), False, 'import doctest\n'), ((1239, 1274), 'doctest.DocTestSuite', 'doctest.DocTestSuite', (['resource_util'], {}), '(resource_util)\n', (1259, 1274), False, 'import doctest\n'), ((626, 655), 'api.app_module.pentaho_controller.stop', 'app.pentaho_controller.stop', ([], {}), '()\n', (653, 655), True, 'from api import app_module as app\n')] |
from __future__ import absolute_import
from __future__ import print_function
import unittest
from aiida.manage.fixtures import PluginTestCase
import subprocess, os
def backend_obj_users():
"""Test if aiida accesses users through backend object."""
backend_obj_flag = False
try:
from aiida.backends.utils import get_automatic_user # pylint: disable=unused-variable,no-name-in-module
except ImportError:
backend_obj_flag = True
return backend_obj_flag
def get_current_user():
"""Get current user backwards compatibly with aiida-core <= 0.12.1."""
current_user = None
if backend_obj_users():
from aiida.orm.backend import construct_backend # pylint: disable=no-name-in-module
backend = construct_backend()
current_user = backend.users.get_automatic_user()
else:
from aiida.backends.utils import get_automatic_user # pylint: disable=no-name-in-module
current_user = get_automatic_user()
return current_user
def create_authinfo(computer):
"""
Allow the current user to use the given computer.
Deal with backwards compatibility down to aiida 0.11
"""
from aiida import load_profile
load_profile()
from aiida.orm import backend as orm_backend
authinfo = None
if hasattr(orm_backend, 'construct_backend'):
backend = orm_backend.construct_backend()
authinfo = backend.authinfos.create(
computer=computer, user=get_current_user())
else:
from aiida.backends.djsite.db.models import DbAuthInfo
authinfo = DbAuthInfo(
dbcomputer=computer.dbcomputer, aiidauser=get_current_user())
return authinfo
class TestWf(PluginTestCase):
def setUp(self):
"""
"""
from aiida import work
from aiida.orm.code import Code
from aiida.orm.nodes.parameter import Dict
from aiida.orm.nodes.structure import StructureData
from aiida.orm.nodes.remote import RemoteData
from ase.spacegroup import crystal
from aiida_quantumespresso.calculations.pw import PwCalculation
from aiida_yambo.calculations.gw import YamboCalculation
from aiida.common.links import LinkType
from aiida.orm.computer import Computer as AiidaOrmComputer
from aiida.common.datastructures import calc_states
from aiida.plugins.utils import DataFactory
runner = work.Runner(
poll_interval=0., rmq_config=None, enable_persistence=None)
work.set_runner(runner)
self.computer = AiidaOrmComputer(name="testcase")
# conf_attrs hostname, description, enabled_state, transport_type, scheduler_type, workdir
# mpirun_command , default_mpiprocs_per_machine,
self.computer._set_hostname_string("localhost")
self.computer._set_enabled_state_string('True')
self.computer._set_transport_type_string("local")
self.computer._set_scheduler_type_string("direct")
self.computer._set_workdir_string("/tmp/testcase/{username}/base")
self.computer.store()
create_authinfo(computer=self.computer).store()
self.code_yambo = Code()
self.code_yambo.label = "yambo"
os_env = os.environ.copy()
yambo_path = subprocess.check_output(['which', 'mock_yambo'],
env=os_env).strip()
self.code_yambo.set_remote_computer_exec((self.computer, yambo_path))
self.code_yambo.set_input_plugin_name('yambo.yambo')
self.code_p2y = Code()
self.code_p2y.label = "p2y"
p2y_path = subprocess.check_output(['which', 'mock_p2y'],
env=os_env).strip()
self.code_p2y.set_remote_computer_exec((self.computer, p2y_path))
self.code_p2y.set_input_plugin_name('yambo.yambo')
self.code_yambo.store()
self.code_p2y.store()
self.calc_pw = PwCalculation()
self.calc_pw.set_computer(self.computer)
self.calc_pw.set_resources({
"num_machines": 1,
"num_mpiprocs_per_machine": 16,
'default_mpiprocs_per_machine': 16
})
StructureData = DataFactory('structure')
cell = [[15.8753100000, 0.0000000000, 0.0000000000],
[0.0000000000, 15.8753100000, 0.0000000000],
[0.0000000000, 0.0000000000, 2.4696584760]]
s = StructureData(cell=cell)
self.calc_pw.use_structure(s)
print((self.calc_pw.store_all(), " pw calc"))
pw_remote_folder = RemoteData(
computer=self.computer, remote_path="/tmp/testcase/work/calcPW")
print((pw_remote_folder.store(), "pw remote data"))
self.calc_pw._set_state(calc_states.PARSING)
pw_remote_folder.add_link_from(
self.calc_pw, label='remote_folder', link_type=LinkType.CREATE)
outputs = Dict(
dict={
"lsda": False,
"number_of_bands": 80,
"number_of_electrons": 8.0,
"number_of_k_points": 147,
"non_colinear_calculation": False
})
outputs.store()
outputs.add_link_from(
self.calc_pw, label='output_parameters', link_type=LinkType.CREATE)
self.calc = YamboCalculation()
self.calc.set_computer(self.computer)
self.calc.use_code(self.code_p2y)
p2y_settings = {
u'ADDITIONAL_RETRIEVE_LIST':
[u'r-*', u'o-*', u'l-*', u'l_*', u'LOG/l-*_CPU_1'],
u'INITIALISE':
True
}
yambo_settings = {
u'ADDITIONAL_RETRIEVE_LIST':
[u'r-*', u'o-*', u'l-*', u'l_*', u'LOG/l-*_CPU_1']
}
self.calc.use_settings(Dict(dict=p2y_settings))
self.calc.set_resources({
"num_machines": 1,
"num_mpiprocs_per_machine": 16,
'default_mpiprocs_per_machine': 16
})
self.calc.use_parent_calculation(self.calc_pw)
print((self.calc.store_all(), " yambo calc"))
self.calc._set_state(calc_states.PARSING)
a = 5.388
cell = crystal(
'Si', [(0, 0, 0)],
spacegroup=227,
cellpar=[a, a, a, 90, 90, 90],
primitive_cell=True)
self.struc = StructureData(ase=cell)
self.struc.store()
self.parameters = Dict(
dict={
"BndsRnXp": [1.0, 48.0],
"Chimod": "Hartree",
"DysSolver": "n",
"FFTGvecs": 25,
"FFTGvecs_units": "Ry",
"GbndRnge": [1.0, 48.0],
"HF_and_locXC": True,
"LongDrXp": [1.0, 0.0, 0.0],
"NGsBlkXp": 2,
"NGsBlkXp_units": "Ry",
"QPkrange": [[1, 145, 3, 5]],
"SE_CPU": "1 2 4",
"SE_ROLEs": "q qp b",
"X_all_q_CPU": "1 1 4 2",
"X_all_q_ROLEs": "q k c v",
"em1d": True,
"gw0": True,
"ppa": True,
"rim_cut": True
})
self.yambo_settings = Dict(
dict={
"ADDITIONAL_RETRIEVE_LIST": [
"r-*", "o-*", "l-*", "l_*", "LOG/l-*_CPU_1",
"aiida/ndb.QP", "aiida/ndb.HF_and_locXC"
]
})
self.p2y_settings = Dict(
dict={
"ADDITIONAL_RETRIEVE_LIST": [
'r-*', 'o-*', 'l-*', 'l_*', 'LOG/l-*_CPU_1',
'aiida/ndb.QP', 'aiida/ndb.HF_and_locXC'
],
'INITIALISE':
True
})
self.yambo_calc_set = Dict(
dict={
'resources': {
"num_machines": 1,
"num_mpiprocs_per_machine": 16
},
'max_wallclock_seconds': 60 * 29,
'max_memory_kb': 1 * 88 * 1000000,
"queue_name":
"s3parvc3", #'custom_scheduler_commands': u"#PBS -A Pra14_3622" ,
'environment_variables': {
"OMP_NUM_THREADS": "1"
}
})
self.p2y_calc_set = Dict(
dict={
'resources': {
"num_machines": 1,
"num_mpiprocs_per_machine": 2
},
'max_wallclock_seconds': 60 * 2,
'max_memory_kb': 1 * 10 * 1000000,
"queue_name":
"s3parvc3", # 'custom_scheduler_commands': u"#PBS -A Pra14_3622" ,
'environment_variables': {
"OMP_NUM_THREADS": "2"
}
})
self.remote_folder = RemoteData(
computer=self.computer, remote_path="/tmp/testcase/work/calcX")
self.remote_folder.store()
self.remote_folder.add_link_from(
self.calc, label='remote_folder', link_type=LinkType.CREATE)
self.calc._set_state(calc_states.FINISHED)
#self.calc.store_all()
def tearDown(self):
"""
"""
pass
def test_simple_log(self):
from aiida.engine.launch import run
from aiida.orm.nodes import Float, Str, NumericType, List, Bool
from aiida_yambo.workflows.yamborestart import YamboRestartWf
p2y_result = run(
YamboRestartWf,
precode=Str('p2y'),
yambocode=Str('yambo'),
parameters=self.parameters,
calculation_set=self.yambo_calc_set,
parent_folder=self.remote_folder,
settings=self.yambo_settings)
assert 'retrieved' in p2y_result
| [
"aiida_yambo.calculations.gw.YamboCalculation",
"subprocess.check_output",
"aiida.orm.computer.Computer",
"aiida.orm.nodes.remote.RemoteData",
"aiida.work.set_runner",
"aiida.orm.nodes.structure.StructureData",
"aiida.load_profile",
"aiida.work.Runner",
"os.environ.copy",
"aiida_quantumespresso.ca... | [((1206, 1220), 'aiida.load_profile', 'load_profile', ([], {}), '()\n', (1218, 1220), False, 'from aiida import load_profile\n'), ((754, 773), 'aiida.orm.backend.construct_backend', 'construct_backend', ([], {}), '()\n', (771, 773), False, 'from aiida.orm.backend import construct_backend\n'), ((962, 982), 'aiida.backends.utils.get_automatic_user', 'get_automatic_user', ([], {}), '()\n', (980, 982), False, 'from aiida.backends.utils import get_automatic_user\n'), ((1358, 1389), 'aiida.orm.backend.construct_backend', 'orm_backend.construct_backend', ([], {}), '()\n', (1387, 1389), True, 'from aiida.orm import backend as orm_backend\n'), ((2427, 2499), 'aiida.work.Runner', 'work.Runner', ([], {'poll_interval': '(0.0)', 'rmq_config': 'None', 'enable_persistence': 'None'}), '(poll_interval=0.0, rmq_config=None, enable_persistence=None)\n', (2438, 2499), False, 'from aiida import work\n'), ((2520, 2543), 'aiida.work.set_runner', 'work.set_runner', (['runner'], {}), '(runner)\n', (2535, 2543), False, 'from aiida import work\n'), ((2568, 2601), 'aiida.orm.computer.Computer', 'AiidaOrmComputer', ([], {'name': '"""testcase"""'}), "(name='testcase')\n", (2584, 2601), True, 'from aiida.orm.computer import Computer as AiidaOrmComputer\n'), ((3175, 3181), 'aiida.orm.code.Code', 'Code', ([], {}), '()\n', (3179, 3181), False, 'from aiida.orm.code import Code\n'), ((3239, 3256), 'os.environ.copy', 'os.environ.copy', ([], {}), '()\n', (3254, 3256), False, 'import subprocess, os\n'), ((3556, 3562), 'aiida.orm.code.Code', 'Code', ([], {}), '()\n', (3560, 3562), False, 'from aiida.orm.code import Code\n'), ((3947, 3962), 'aiida_quantumespresso.calculations.pw.PwCalculation', 'PwCalculation', ([], {}), '()\n', (3960, 3962), False, 'from aiida_quantumespresso.calculations.pw import PwCalculation\n'), ((4206, 4230), 'aiida.plugins.utils.DataFactory', 'DataFactory', (['"""structure"""'], {}), "('structure')\n", (4217, 4230), False, 'from aiida.plugins.utils import DataFactory\n'), ((4425, 4449), 'aiida.orm.nodes.structure.StructureData', 'StructureData', ([], {'cell': 'cell'}), '(cell=cell)\n', (4438, 4449), False, 'from aiida.orm.nodes.structure import StructureData\n'), ((4569, 4644), 'aiida.orm.nodes.remote.RemoteData', 'RemoteData', ([], {'computer': 'self.computer', 'remote_path': '"""/tmp/testcase/work/calcPW"""'}), "(computer=self.computer, remote_path='/tmp/testcase/work/calcPW')\n", (4579, 4644), False, 'from aiida.orm.nodes.remote import RemoteData\n'), ((4906, 5049), 'aiida.orm.nodes.parameter.Dict', 'Dict', ([], {'dict': "{'lsda': False, 'number_of_bands': 80, 'number_of_electrons': 8.0,\n 'number_of_k_points': 147, 'non_colinear_calculation': False}"}), "(dict={'lsda': False, 'number_of_bands': 80, 'number_of_electrons': 8.0,\n 'number_of_k_points': 147, 'non_colinear_calculation': False})\n", (4910, 5049), False, 'from aiida.orm.nodes.parameter import Dict\n'), ((5309, 5327), 'aiida_yambo.calculations.gw.YamboCalculation', 'YamboCalculation', ([], {}), '()\n', (5325, 5327), False, 'from aiida_yambo.calculations.gw import YamboCalculation\n'), ((6156, 6254), 'ase.spacegroup.crystal', 'crystal', (['"""Si"""', '[(0, 0, 0)]'], {'spacegroup': '(227)', 'cellpar': '[a, a, a, 90, 90, 90]', 'primitive_cell': '(True)'}), "('Si', [(0, 0, 0)], spacegroup=227, cellpar=[a, a, a, 90, 90, 90],\n primitive_cell=True)\n", (6163, 6254), False, 'from ase.spacegroup import crystal\n'), ((6321, 6344), 'aiida.orm.nodes.structure.StructureData', 'StructureData', ([], {'ase': 'cell'}), '(ase=cell)\n', (6334, 6344), False, 'from aiida.orm.nodes.structure import StructureData\n'), ((6398, 6830), 'aiida.orm.nodes.parameter.Dict', 'Dict', ([], {'dict': "{'BndsRnXp': [1.0, 48.0], 'Chimod': 'Hartree', 'DysSolver': 'n', 'FFTGvecs':\n 25, 'FFTGvecs_units': 'Ry', 'GbndRnge': [1.0, 48.0], 'HF_and_locXC': \n True, 'LongDrXp': [1.0, 0.0, 0.0], 'NGsBlkXp': 2, 'NGsBlkXp_units':\n 'Ry', 'QPkrange': [[1, 145, 3, 5]], 'SE_CPU': '1 2 4', 'SE_ROLEs':\n 'q qp b', 'X_all_q_CPU': '1 1 4 2', 'X_all_q_ROLEs': 'q k c v', 'em1d':\n True, 'gw0': True, 'ppa': True, 'rim_cut': True}"}), "(dict={'BndsRnXp': [1.0, 48.0], 'Chimod': 'Hartree', 'DysSolver': 'n',\n 'FFTGvecs': 25, 'FFTGvecs_units': 'Ry', 'GbndRnge': [1.0, 48.0],\n 'HF_and_locXC': True, 'LongDrXp': [1.0, 0.0, 0.0], 'NGsBlkXp': 2,\n 'NGsBlkXp_units': 'Ry', 'QPkrange': [[1, 145, 3, 5]], 'SE_CPU': '1 2 4',\n 'SE_ROLEs': 'q qp b', 'X_all_q_CPU': '1 1 4 2', 'X_all_q_ROLEs':\n 'q k c v', 'em1d': True, 'gw0': True, 'ppa': True, 'rim_cut': True})\n", (6402, 6830), False, 'from aiida.orm.nodes.parameter import Dict\n'), ((7172, 7304), 'aiida.orm.nodes.parameter.Dict', 'Dict', ([], {'dict': "{'ADDITIONAL_RETRIEVE_LIST': ['r-*', 'o-*', 'l-*', 'l_*', 'LOG/l-*_CPU_1',\n 'aiida/ndb.QP', 'aiida/ndb.HF_and_locXC']}"}), "(dict={'ADDITIONAL_RETRIEVE_LIST': ['r-*', 'o-*', 'l-*', 'l_*',\n 'LOG/l-*_CPU_1', 'aiida/ndb.QP', 'aiida/ndb.HF_and_locXC']})\n", (7176, 7304), False, 'from aiida.orm.nodes.parameter import Dict\n'), ((7430, 7586), 'aiida.orm.nodes.parameter.Dict', 'Dict', ([], {'dict': "{'ADDITIONAL_RETRIEVE_LIST': ['r-*', 'o-*', 'l-*', 'l_*', 'LOG/l-*_CPU_1',\n 'aiida/ndb.QP', 'aiida/ndb.HF_and_locXC'], 'INITIALISE': True}"}), "(dict={'ADDITIONAL_RETRIEVE_LIST': ['r-*', 'o-*', 'l-*', 'l_*',\n 'LOG/l-*_CPU_1', 'aiida/ndb.QP', 'aiida/ndb.HF_and_locXC'],\n 'INITIALISE': True})\n", (7434, 7586), False, 'from aiida.orm.nodes.parameter import Dict\n'), ((7742, 7977), 'aiida.orm.nodes.parameter.Dict', 'Dict', ([], {'dict': "{'resources': {'num_machines': 1, 'num_mpiprocs_per_machine': 16},\n 'max_wallclock_seconds': 60 * 29, 'max_memory_kb': 1 * 88 * 1000000,\n 'queue_name': 's3parvc3', 'environment_variables': {'OMP_NUM_THREADS': '1'}\n }"}), "(dict={'resources': {'num_machines': 1, 'num_mpiprocs_per_machine': 16},\n 'max_wallclock_seconds': 60 * 29, 'max_memory_kb': 1 * 88 * 1000000,\n 'queue_name': 's3parvc3', 'environment_variables': {'OMP_NUM_THREADS':\n '1'}})\n", (7746, 7977), False, 'from aiida.orm.nodes.parameter import Dict\n'), ((8269, 8502), 'aiida.orm.nodes.parameter.Dict', 'Dict', ([], {'dict': "{'resources': {'num_machines': 1, 'num_mpiprocs_per_machine': 2},\n 'max_wallclock_seconds': 60 * 2, 'max_memory_kb': 1 * 10 * 1000000,\n 'queue_name': 's3parvc3', 'environment_variables': {'OMP_NUM_THREADS': '2'}\n }"}), "(dict={'resources': {'num_machines': 1, 'num_mpiprocs_per_machine': 2},\n 'max_wallclock_seconds': 60 * 2, 'max_memory_kb': 1 * 10 * 1000000,\n 'queue_name': 's3parvc3', 'environment_variables': {'OMP_NUM_THREADS':\n '2'}})\n", (8273, 8502), False, 'from aiida.orm.nodes.parameter import Dict\n'), ((8796, 8870), 'aiida.orm.nodes.remote.RemoteData', 'RemoteData', ([], {'computer': 'self.computer', 'remote_path': '"""/tmp/testcase/work/calcX"""'}), "(computer=self.computer, remote_path='/tmp/testcase/work/calcX')\n", (8806, 8870), False, 'from aiida.orm.nodes.remote import RemoteData\n'), ((5772, 5795), 'aiida.orm.nodes.parameter.Dict', 'Dict', ([], {'dict': 'p2y_settings'}), '(dict=p2y_settings)\n', (5776, 5795), False, 'from aiida.orm.nodes.parameter import Dict\n'), ((3278, 3338), 'subprocess.check_output', 'subprocess.check_output', (["['which', 'mock_yambo']"], {'env': 'os_env'}), "(['which', 'mock_yambo'], env=os_env)\n", (3301, 3338), False, 'import subprocess, os\n'), ((3618, 3676), 'subprocess.check_output', 'subprocess.check_output', (["['which', 'mock_p2y']"], {'env': 'os_env'}), "(['which', 'mock_p2y'], env=os_env)\n", (3641, 3676), False, 'import subprocess, os\n'), ((9470, 9480), 'aiida.orm.nodes.Str', 'Str', (['"""p2y"""'], {}), "('p2y')\n", (9473, 9480), False, 'from aiida.orm.nodes import Float, Str, NumericType, List, Bool\n'), ((9504, 9516), 'aiida.orm.nodes.Str', 'Str', (['"""yambo"""'], {}), "('yambo')\n", (9507, 9516), False, 'from aiida.orm.nodes import Float, Str, NumericType, List, Bool\n')] |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName : knn.py
# @Time : 2020/9/25 12:29
# @Author : 陈嘉昕
# @Demand : k-临近算法,和训练的模型作比较
import csv
import math
import operator
from random import shuffle
import matplotlib.pyplot as plt
# 数据集
training_set = []
# 测试集
test_set = []
def cross_validation(file_name):
k_max = len(training_set) - 1
k_scores = []
for k in range(1, k_max):
acc = 0
for i in range(k_max):
to_predict = training_set[i]
training_set.remove(to_predict)
predictions = fit([to_predict], training_set, k)
acc += calculate_accuracy([to_predict], predictions)
training_set.insert(i, to_predict)
scores = acc / k_max
print("k =", repr(k), " accuracy = " + repr(scores))
k_scores.append(scores)
plt.plot(range(1, k_max), k_scores)
plt.xlabel('Value of K')
plt.ylabel('Accuracy')
plt.savefig(file_name)
plt.show()
max_index, max_number = max(enumerate(k_scores), key=operator.itemgetter(1))
print("\n\nThe best results: k =", repr(max_index + 1), ", accuracy = " + repr(max_number) + "\n\n")
def load_dataset(filename, training=False):
# 打开文件
with open(filename, 'rt') as camile:
next(csv.reader(camile))
lines = csv.reader(camile)
dataset = list(lines)
shuffle(dataset)
if training:
split = 0.8 * len(dataset)
else:
split = len(dataset)
for x in range(len(dataset)):
for y in range(4):
dataset[x][y] = float(dataset[x][y])
if len(training_set) <= split:
training_set.append(dataset[x])
else:
test_set.append(dataset[x])
def euclidean_distance(instance1, instance2, number_of_params):
distance = 0
for param in range(number_of_params):
distance += pow((float(instance1[param]) - float(instance2[param])), 2)
return math.sqrt(distance)
def get_neighbors(trainingSet, instance, k):
distances = []
length = len(instance) - 1
for x in range(len(trainingSet)):
dist = euclidean_distance(instance, trainingSet[x], length)
distances.append((trainingSet[x], dist))
distances.sort(key=operator.itemgetter(1))
neighbors = []
for x in range(k):
neighbors.append(distances[x][0])
return neighbors
def calculate_votes(neighbors):
class_votes = {}
for i in range(len(neighbors)):
response = neighbors[i][-1]
if response in class_votes:
class_votes[response] += 1
else:
class_votes[response] = 1
sorted_votes = sorted(class_votes.items(), key=operator.itemgetter(1), reverse=True)
return sorted_votes[0][0]
def calculate_accuracy(testSet, predictions):
correct = 0
for x in range(len(testSet)):
if testSet[x][-1] == predictions[x]:
correct += 1
return (correct / float(len(testSet))) * 100.0
def fit(to_predict, dataset, k):
predictions = []
for x in range(len(to_predict)):
neighbors = get_neighbors(dataset, to_predict[x], k)
result = calculate_votes(neighbors)
predictions.append(result)
return predictions
def predict(to_predict, data_set_path, k=12, training=False):
if len(training_set) == 0:
load_dataset(data_set_path, training)
if training:
predictions = fit(test_set, training_set, k)
accuracy = calculate_accuracy(test_set, predictions)
print('Accuracy: ' + repr(accuracy) + '%')
else:
predictions = fit(to_predict, training_set, k)
return predictions
def run_one():
training_set.clear()
test_set.clear()
load_dataset("data/video_data_for_lie_training.csv", True)
cross_validation("image/knn_model_1.png")
def run_two():
training_set.clear()
test_set.clear()
load_dataset("data/audio_data_for_lie_training.csv", True)
cross_validation("image/knn_model_2.png")
| [
"matplotlib.pyplot.savefig",
"random.shuffle",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"math.sqrt",
"operator.itemgetter",
"csv.reader",
"matplotlib.pyplot.show"
] | [((885, 909), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Value of K"""'], {}), "('Value of K')\n", (895, 909), True, 'import matplotlib.pyplot as plt\n'), ((914, 936), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (924, 936), True, 'import matplotlib.pyplot as plt\n'), ((941, 963), 'matplotlib.pyplot.savefig', 'plt.savefig', (['file_name'], {}), '(file_name)\n', (952, 963), True, 'import matplotlib.pyplot as plt\n'), ((968, 978), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (976, 978), True, 'import matplotlib.pyplot as plt\n'), ((1987, 2006), 'math.sqrt', 'math.sqrt', (['distance'], {}), '(distance)\n', (1996, 2006), False, 'import math\n'), ((1312, 1330), 'csv.reader', 'csv.reader', (['camile'], {}), '(camile)\n', (1322, 1330), False, 'import csv\n'), ((1370, 1386), 'random.shuffle', 'shuffle', (['dataset'], {}), '(dataset)\n', (1377, 1386), False, 'from random import shuffle\n'), ((1036, 1058), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (1055, 1058), False, 'import operator\n'), ((1276, 1294), 'csv.reader', 'csv.reader', (['camile'], {}), '(camile)\n', (1286, 1294), False, 'import csv\n'), ((2282, 2304), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (2301, 2304), False, 'import operator\n'), ((2716, 2738), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (2735, 2738), False, 'import operator\n')] |
# -*- coding: UTF-8 -*-
import cv2
import numpy as np
# 仿射变换(图像位置校正)
def img_three(imgPath):
# ---------------------------三点得到一个变换矩阵 ---------------------------
"""
三点确定一个平面,通过确定三个点的关系来得到转换矩阵
然后再通过warpAffine来进行变换
"""
img = cv2.imread(imgPath)
rows,cols,_ = img.shape
points1 = np.float32([[50,50],[200,50],[50,200]])
points2 = np.float32([[10,100],[200,50],[100,250]])
matrix = cv2.getAffineTransform(points1,points2)
output = cv2.warpAffine(img,matrix,(cols,rows))
cv2.imshow('input1',img)
cv2.imshow('output1',output)
cv2.waitKey(0)
cv2.destroyAllWindows()
def img_four(imgPath):
# ---------------------------四点得到一个变换矩阵---------------------------
"""
进行透视变换
可以先用四个点来确定一个3*3的变换矩阵(cv2.getPerspectiveTransform)
然后通过cv2.warpPerspective和上述矩阵对图像进行变换
"""
img = cv2.imread(imgPath)
rows,cols,_ = img.shape
points1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
points2 = np.float32([[0,0],[300,0],[0,300],[300,300]])
matrix = cv2.getPerspectiveTransform(points1,points2)
# 将四个点组成的平面转换成另四个点组成的一个平面
output = cv2.warpPerspective(img, matrix, (cols, rows))
# 通过warpPerspective函数来进行变换
cv2.imshow('input2',img)
cv2.imshow('output2',output)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
imgPath = 'src/python-opencv/a.jpg'
# img_three(imgPath)
img_four(imgPath) | [
"cv2.warpAffine",
"cv2.getPerspectiveTransform",
"cv2.imshow",
"cv2.waitKey",
"cv2.warpPerspective",
"cv2.destroyAllWindows",
"cv2.getAffineTransform",
"cv2.imread",
"numpy.float32"
] | [((260, 279), 'cv2.imread', 'cv2.imread', (['imgPath'], {}), '(imgPath)\n', (270, 279), False, 'import cv2\n'), ((322, 366), 'numpy.float32', 'np.float32', (['[[50, 50], [200, 50], [50, 200]]'], {}), '([[50, 50], [200, 50], [50, 200]])\n', (332, 366), True, 'import numpy as np\n'), ((376, 422), 'numpy.float32', 'np.float32', (['[[10, 100], [200, 50], [100, 250]]'], {}), '([[10, 100], [200, 50], [100, 250]])\n', (386, 422), True, 'import numpy as np\n'), ((432, 472), 'cv2.getAffineTransform', 'cv2.getAffineTransform', (['points1', 'points2'], {}), '(points1, points2)\n', (454, 472), False, 'import cv2\n'), ((485, 526), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'matrix', '(cols, rows)'], {}), '(img, matrix, (cols, rows))\n', (499, 526), False, 'import cv2\n'), ((529, 554), 'cv2.imshow', 'cv2.imshow', (['"""input1"""', 'img'], {}), "('input1', img)\n", (539, 554), False, 'import cv2\n'), ((558, 587), 'cv2.imshow', 'cv2.imshow', (['"""output1"""', 'output'], {}), "('output1', output)\n", (568, 587), False, 'import cv2\n'), ((591, 605), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (602, 605), False, 'import cv2\n'), ((610, 633), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (631, 633), False, 'import cv2\n'), ((872, 891), 'cv2.imread', 'cv2.imread', (['imgPath'], {}), '(imgPath)\n', (882, 891), False, 'import cv2\n'), ((934, 990), 'numpy.float32', 'np.float32', (['[[56, 65], [368, 52], [28, 387], [389, 390]]'], {}), '([[56, 65], [368, 52], [28, 387], [389, 390]])\n', (944, 990), True, 'import numpy as np\n'), ((998, 1050), 'numpy.float32', 'np.float32', (['[[0, 0], [300, 0], [0, 300], [300, 300]]'], {}), '([[0, 0], [300, 0], [0, 300], [300, 300]])\n', (1008, 1050), True, 'import numpy as np\n'), ((1058, 1103), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['points1', 'points2'], {}), '(points1, points2)\n', (1085, 1103), False, 'import cv2\n'), ((1146, 1192), 'cv2.warpPerspective', 'cv2.warpPerspective', (['img', 'matrix', '(cols, rows)'], {}), '(img, matrix, (cols, rows))\n', (1165, 1192), False, 'import cv2\n'), ((1229, 1254), 'cv2.imshow', 'cv2.imshow', (['"""input2"""', 'img'], {}), "('input2', img)\n", (1239, 1254), False, 'import cv2\n'), ((1258, 1287), 'cv2.imshow', 'cv2.imshow', (['"""output2"""', 'output'], {}), "('output2', output)\n", (1268, 1287), False, 'import cv2\n'), ((1291, 1305), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1302, 1305), False, 'import cv2\n'), ((1310, 1333), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1331, 1333), False, 'import cv2\n')] |
import os
from pathlib import Path
from shutil import copyfile
def stu_activities(rootDir):
# set the rootDir where the search will start
# that is in home dorectory
#rootDir = "Downloads"
# build rootDir from rootDir with the base as home "~"
rootDir = os.path.join(Path.home(),rootDir)
# traverse rootDir and locate the files
####
# when the path has Stu_ in it
####
# store currenet directory and build target directory based on current directory
curDir=os.path.curdir
targetDir=os.path.join(curDir,"target")
print(f'{targetDir}')
if not os.path.exists(targetDir):
os.makedirs(targetDir)
moveOn = True
for dirName, subdirList, fileList in os.walk(rootDir):
if ( "Stu_" in dirName ):
for fname in fileList:
sourceFile = os.path.join(dirName,fname)
targetFile = os.path.join(targetDir,fname)
#print('\t%s' % sourceFile)
#print(f'{targetDir}')
if not os.path.exists(targetFile):
copyfile(sourceFile, targetFile)
else:
print(f'excuse me I can not copy \n source file {sourceFile} as \n target file {targetFile} exists')
moveOn = False
break
else:
if ( not moveOn ):
break
if ( not moveOn ):
break
stu_activities("Downloads")
# test
| [
"os.path.exists",
"os.makedirs",
"pathlib.Path.home",
"os.path.join",
"shutil.copyfile",
"os.walk"
] | [((549, 579), 'os.path.join', 'os.path.join', (['curDir', '"""target"""'], {}), "(curDir, 'target')\n", (561, 579), False, 'import os\n'), ((740, 756), 'os.walk', 'os.walk', (['rootDir'], {}), '(rootDir)\n', (747, 756), False, 'import os\n'), ((295, 306), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (304, 306), False, 'from pathlib import Path\n'), ((620, 645), 'os.path.exists', 'os.path.exists', (['targetDir'], {}), '(targetDir)\n', (634, 645), False, 'import os\n'), ((656, 678), 'os.makedirs', 'os.makedirs', (['targetDir'], {}), '(targetDir)\n', (667, 678), False, 'import os\n'), ((859, 887), 'os.path.join', 'os.path.join', (['dirName', 'fname'], {}), '(dirName, fname)\n', (871, 887), False, 'import os\n'), ((917, 947), 'os.path.join', 'os.path.join', (['targetDir', 'fname'], {}), '(targetDir, fname)\n', (929, 947), False, 'import os\n'), ((1056, 1082), 'os.path.exists', 'os.path.exists', (['targetFile'], {}), '(targetFile)\n', (1070, 1082), False, 'import os\n'), ((1105, 1137), 'shutil.copyfile', 'copyfile', (['sourceFile', 'targetFile'], {}), '(sourceFile, targetFile)\n', (1113, 1137), False, 'from shutil import copyfile\n')] |
import matplotlib.pyplot as plt
import numpy as np
def plot(ac):
ac=np.array(ac)
ac=ac.reshape((28,28))
ac=[[int(ac2+0.48) for ac2 in ac1] for ac1 in ac]
plt.imshow(ac)
f=np.load("model.npz",allow_pickle=True)
f2=np.load("model2.npz",allow_pickle=True)
f3=np.load("model3.npz",allow_pickle=True)
f4=np.load("model4.npz",allow_pickle=True)
f5=np.load("model5.npz",allow_pickle=True)
model=f["model"]
print("exp model1")
model2=f2["model"]
print("exp model2")
model3=f3["model"]
print("exp model3")
model4=f4["model"]
print("exp model4")
model5=f5["model"]
print("exp model5")
models=[model,model2,model3,model4,model5]
t=f["t"]
t0=np.mean(t[np.where(t<0.5)])
t1=np.mean(t[np.where(t>0.5)])
def runmodel(inp,model):
x=inp
for l in model:
x=np.dot(x,l)
x=np.maximum(x,0)
x=np.mean(x,axis=-1)
return x
def lossbybool(inp):
"""input either 0 or 1"""
dt=t1-t0
inp/=dt
inp+=t0
ret=(runmodel(inp,models[0])-m7[0])**2
for zw,mea in zip(models[1:],m7):
ret+=(runmodel(inp,models[0])-mea)**2
return ret/len(m7)
m7=[np.mean(runmodel(t,m)) for m in models]
print("done loading")
| [
"matplotlib.pyplot.imshow",
"numpy.mean",
"numpy.where",
"numpy.array",
"numpy.dot",
"numpy.maximum",
"numpy.load"
] | [((185, 224), 'numpy.load', 'np.load', (['"""model.npz"""'], {'allow_pickle': '(True)'}), "('model.npz', allow_pickle=True)\n", (192, 224), True, 'import numpy as np\n'), ((227, 267), 'numpy.load', 'np.load', (['"""model2.npz"""'], {'allow_pickle': '(True)'}), "('model2.npz', allow_pickle=True)\n", (234, 267), True, 'import numpy as np\n'), ((270, 310), 'numpy.load', 'np.load', (['"""model3.npz"""'], {'allow_pickle': '(True)'}), "('model3.npz', allow_pickle=True)\n", (277, 310), True, 'import numpy as np\n'), ((313, 353), 'numpy.load', 'np.load', (['"""model4.npz"""'], {'allow_pickle': '(True)'}), "('model4.npz', allow_pickle=True)\n", (320, 353), True, 'import numpy as np\n'), ((356, 396), 'numpy.load', 'np.load', (['"""model5.npz"""'], {'allow_pickle': '(True)'}), "('model5.npz', allow_pickle=True)\n", (363, 396), True, 'import numpy as np\n'), ((73, 85), 'numpy.array', 'np.array', (['ac'], {}), '(ac)\n', (81, 85), True, 'import numpy as np\n'), ((167, 181), 'matplotlib.pyplot.imshow', 'plt.imshow', (['ac'], {}), '(ac)\n', (177, 181), True, 'import matplotlib.pyplot as plt\n'), ((801, 820), 'numpy.mean', 'np.mean', (['x'], {'axis': '(-1)'}), '(x, axis=-1)\n', (808, 820), True, 'import numpy as np\n'), ((656, 673), 'numpy.where', 'np.where', (['(t < 0.5)'], {}), '(t < 0.5)\n', (664, 673), True, 'import numpy as np\n'), ((687, 704), 'numpy.where', 'np.where', (['(t > 0.5)'], {}), '(t > 0.5)\n', (695, 704), True, 'import numpy as np\n'), ((763, 775), 'numpy.dot', 'np.dot', (['x', 'l'], {}), '(x, l)\n', (769, 775), True, 'import numpy as np\n'), ((781, 797), 'numpy.maximum', 'np.maximum', (['x', '(0)'], {}), '(x, 0)\n', (791, 797), True, 'import numpy as np\n')] |
import logging
import threading
import time
from datetime import datetime, timedelta
from sqlalchemy import column, func, select
from sqlalchemy.orm import SessionTransaction
from actions.discord import Discord
from actions.telegram import Telegram
from common.database import session
from common.models import Event, Voter
from config import config
class EventChecker:
_tg_bot = Telegram()
_discord_bot = Discord()
def start(self):
threading.Thread(target=self.__monitor_cycle).start()
def __monitor_cycle(self):
logging.info('Event checker starting...')
while True:
self.__check()
time.sleep(60)
def __check(self):
logging.debug('Сhecking events for readiness...')
with session.begin() as local_session:
self.__check_ready(local_session)
self.__check_started(local_session)
def __check_ready(self, local_session: SessionTransaction):
subquery = select(Voter.poll_id).\
where(Voter.will_play == True).\
group_by(Voter.poll_id).\
having(func.count(Voter.user_id) >= config['min_will_play'])
query = select(Event).\
where(
Event.start_time <= (datetime.utcnow() + timedelta(days=1)),
column('poll_id').in_(subquery),
Event.done == False,
)
result = local_session.scalars(query)
for event in result:
self._discord_bot.create_event(event)
event.done = True
def __check_started(self, local_session: SessionTransaction):
query = select(Event).\
where(Event.start_time <= datetime.utcnow())
result = local_session.scalars(query)
for event in result:
if event.message_id is not None and event.chat_id is not None and \
event.pinned:
self._tg_bot.unpin_message(event.chat_id, event.message_id)
event.pinned = False
event.done = True
| [
"sqlalchemy.func.count",
"logging.debug",
"sqlalchemy.column",
"datetime.datetime.utcnow",
"common.database.session.begin",
"time.sleep",
"actions.discord.Discord",
"sqlalchemy.select",
"threading.Thread",
"datetime.timedelta",
"logging.info",
"actions.telegram.Telegram"
] | [((388, 398), 'actions.telegram.Telegram', 'Telegram', ([], {}), '()\n', (396, 398), False, 'from actions.telegram import Telegram\n'), ((418, 427), 'actions.discord.Discord', 'Discord', ([], {}), '()\n', (425, 427), False, 'from actions.discord import Discord\n'), ((552, 593), 'logging.info', 'logging.info', (['"""Event checker starting..."""'], {}), "('Event checker starting...')\n", (564, 593), False, 'import logging\n'), ((700, 749), 'logging.debug', 'logging.debug', (['"""Сhecking events for readiness..."""'], {}), "('Сhecking events for readiness...')\n", (713, 749), False, 'import logging\n'), ((653, 667), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (663, 667), False, 'import time\n'), ((763, 778), 'common.database.session.begin', 'session.begin', ([], {}), '()\n', (776, 778), False, 'from common.database import session\n'), ((458, 503), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.__monitor_cycle'}), '(target=self.__monitor_cycle)\n', (474, 503), False, 'import threading\n'), ((1101, 1126), 'sqlalchemy.func.count', 'func.count', (['Voter.user_id'], {}), '(Voter.user_id)\n', (1111, 1126), False, 'from sqlalchemy import column, func, select\n'), ((1171, 1184), 'sqlalchemy.select', 'select', (['Event'], {}), '(Event)\n', (1177, 1184), False, 'from sqlalchemy import column, func, select\n'), ((1621, 1634), 'sqlalchemy.select', 'select', (['Event'], {}), '(Event)\n', (1627, 1634), False, 'from sqlalchemy import column, func, select\n'), ((1675, 1692), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (1690, 1692), False, 'from datetime import datetime, timedelta\n'), ((1243, 1260), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (1258, 1260), False, 'from datetime import datetime, timedelta\n'), ((1263, 1280), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (1272, 1280), False, 'from datetime import datetime, timedelta\n'), ((1299, 1316), 'sqlalchemy.column', 'column', (['"""poll_id"""'], {}), "('poll_id')\n", (1305, 1316), False, 'from sqlalchemy import column, func, select\n'), ((975, 996), 'sqlalchemy.select', 'select', (['Voter.poll_id'], {}), '(Voter.poll_id)\n', (981, 996), False, 'from sqlalchemy import column, func, select\n')] |
from math import sqrt, ceil
def isPrime(x):
"""Primality test.
Param x: int.
Returns True if x is prime, False otherwise.
"""
if x <= 0:
return False
elif x == 2 or x == 3:
return True
else:
for i in range(2, ceil(sqrt(x)) + 1):
if x % i == 0:
return False
return True
if __name__ == "__main__":
strNum = input("Enter number to check if prime (-1 to quit): ")
while strNum != '-1':
num = int(strNum)
print(isPrime(num))
strNum = input("Enter number to check if prime (-1 to quit): ")
| [
"math.sqrt"
] | [((270, 277), 'math.sqrt', 'sqrt', (['x'], {}), '(x)\n', (274, 277), False, 'from math import sqrt, ceil\n')] |
import sys, os
import shutil
def SilentMkdir(theDir):
try:
os.mkdir(theDir)
except:
pass
return 0
def Run_00_CameraInit(baseDir, binDir, srcImageDir):
# SilentMkdir(baseDir + "/00_CameraInit")
binName = binDir + "\\aliceVision_cameraInit" # .exe"
dstDir = baseDir + "/" # + "/00_CameraInit/"
cmdLine = binName
cmdLine = (
cmdLine
+ ' --defaultFieldOfView 45.0 --verboseLevel info --sensorDatabase "" --allowSingleView 1'
)
cmdLine = cmdLine + ' --imageFolder "' + srcImageDir + '"'
cmdLine = cmdLine + ' --output "' + dstDir + 'cameraInit.sfm"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_01_FeatureExtraction(baseDir, binDir, numImages):
# SilentMkdir(baseDir + "/01_FeatureExtraction")
srcSfm = baseDir + "/00_CameraInit/cameraInit.sfm"
binName = binDir + "\\aliceVision_featureExtraction" # .exe"
dstDir = baseDir + "/01_FeatureExtraction/"
cmdLine = binName
cmdLine = (
cmdLine
+ " --describerTypes sift --forceCpuExtraction True --verboseLevel info --describerPreset normal"
)
cmdLine = cmdLine + " --rangeStart 0 --rangeSize " + str(numImages)
cmdLine = cmdLine + ' --input "' + srcSfm + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_02_ImageMatching(baseDir, binDir):
# SilentMkdir(baseDir + "/02_ImageMatching")
srcSfm = baseDir + "/00_CameraInit/cameraInit.sfm"
srcFeatures = baseDir + "/01_FeatureExtraction/"
dstMatches = baseDir + "/02_ImageMatching/imageMatches.txt"
binName = binDir + "\\aliceVision_imageMatching" # .exe"
cmdLine = binName
cmdLine = (
cmdLine + " --minNbImages 200 --tree "
" --maxDescriptors 500 --verboseLevel info --weights "
" --nbMatches 50"
)
cmdLine = cmdLine + ' --input "' + srcSfm + '"'
cmdLine = cmdLine + ' --featuresFolder "' + srcFeatures + '"'
cmdLine = cmdLine + ' --output "' + dstMatches + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_03_FeatureMatching(baseDir, binDir):
# SilentMkdir(baseDir + "/03_FeatureMatching")
srcSfm = baseDir + "/00_CameraInit/cameraInit.sfm"
srcFeatures = baseDir + "/01_FeatureExtraction/"
srcImageMatches = baseDir + "/02_ImageMatching/imageMatches.txt"
dstMatches = baseDir + "/03_FeatureMatching"
binName = binDir + "\\aliceVision_featureMatching" # .exe"
cmdLine = binName
cmdLine = (
cmdLine
+ " --verboseLevel info --describerTypes sift --maxMatches 0 --exportDebugFiles False --savePutativeMatches False --guidedMatching False"
)
cmdLine = (
cmdLine
+ " --geometricEstimator acransac --geometricFilterType fundamental_matrix --maxIteration 2048 --distanceRatio 0.8"
)
cmdLine = cmdLine + " --photometricMatchingMethod ANN_L2"
cmdLine = cmdLine + ' --imagePairsList "' + srcImageMatches + '"'
cmdLine = cmdLine + ' --input "' + srcSfm + '"'
cmdLine = cmdLine + ' --featuresFolders "' + srcFeatures + '"'
cmdLine = cmdLine + ' --output "' + dstMatches + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_04_StructureFromMotion(baseDir, binDir):
# SilentMkdir(baseDir + "/04_StructureFromMotion")
srcSfm = baseDir + "/00_CameraInit/cameraInit.sfm"
srcFeatures = baseDir + "/01_FeatureExtraction/"
srcImageMatches = baseDir + "/02_ImageMatching/imageMatches.txt"
srcMatches = baseDir + "/03_FeatureMatching"
dstDir = baseDir + "/04_StructureFromMotion"
binName = binDir + "\\aliceVision_incrementalSfM" # .exe"
cmdLine = binName
cmdLine = (
cmdLine
+ " --minAngleForLandmark 2.0 --minNumberOfObservationsForTriangulation 2 --maxAngleInitialPair 40.0 --maxNumberOfMatches 0 --localizerEstimator acransac --describerTypes sift --lockScenePreviouslyReconstructed False --localBAGraphDistance 1"
)
# cmdLine = (
# cmdLine + " --initialPairA "
# " --initialPairB "
# " --interFileExtension .ply --useLocalBA True"
# )
cmdLine = cmdLine + " --interFileExtension .ply --useLocalBA True"
cmdLine = (
cmdLine
+ " --minInputTrackLength 2 --useOnlyMatchesFromInputFolder False --verboseLevel info --minAngleForTriangulation 3.0 --maxReprojectionError 4.0 --minAngleInitialPair 5.0"
)
cmdLine = cmdLine + ' --input "' + srcSfm + '"'
cmdLine = cmdLine + ' --featuresFolders "' + srcFeatures + '"'
cmdLine = cmdLine + ' --matchesFolders "' + srcMatches + '"'
cmdLine = cmdLine + ' --outputViewsAndPoses "' + dstDir + '/cameras.sfm"'
cmdLine = cmdLine + ' --extraInfoFolder "' + dstDir + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '/bundle.sfm"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_05_PrepareDenseScene(baseDir, binDir):
# SilentMkdir(baseDir + "/05_PrepareDenseScene")
# srcSfm = baseDir + "/04_StructureFromMotion/cameras.sfm"
srcSfm = baseDir + "/04_StructureFromMotion/bundle.sfm"
dstDir = baseDir + "/05_PrepareDenseScene"
binName = binDir + "\\aliceVision_prepareDenseScene" # .exe"
cmdLine = binName
cmdLine = cmdLine + " --verboseLevel info"
cmdLine = cmdLine + ' --input "' + srcSfm + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_06_CameraConnection(baseDir, binDir):
# SilentMkdir(baseDir + "/06_CameraConnection")
srcIni = baseDir + "/05_PrepareDenseScene/mvs.ini"
# This step kindof breaks the directory structure. Tt creates
# a camsPairsMatrixFromSeeds.bin file in in the same file as mvs.ini
binName = binDir + "\\aliceVision_cameraConnection" # .exe"
cmdLine = binName
cmdLine = cmdLine + " --verboseLevel info"
cmdLine = cmdLine + ' --ini "' + srcIni + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_07_DepthMap(baseDir, binDir, numImages, groupSize):
# SilentMkdir(baseDir + "/07_DepthMap")
numGroups = (numImages + (groupSize - 1)) // groupSize
srcIni = baseDir + "/05_PrepareDenseScene/mvs.ini"
binName = binDir + "\\aliceVision_depthMapEstimation" # .exe"
dstDir = baseDir + "/07_DepthMap"
cmdLine = binName
cmdLine = (
cmdLine
+ " --sgmGammaC 5.5 --sgmWSH 4 --refineGammaP 8.0 --refineSigma 15 --refineNSamplesHalf 150 --sgmMaxTCams 10 --refineWSH 3 --downscale 2 --refineMaxTCams 6 --verboseLevel info --refineGammaC 15.5 --sgmGammaP 8.0"
)
cmdLine = (
cmdLine
+ " --refineNiters 100 --refineNDepthsToRefine 31 --refineUseTcOrRcPixSize False"
)
cmdLine = cmdLine + ' --ini "' + srcIni + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '"'
for groupIter in range(numGroups):
groupStart = groupSize * groupIter
groupSize = min(groupSize, numImages - groupStart)
print(
"DepthMap Group %d/%d: %d, %d"
% (groupIter, numGroups, groupStart, groupSize)
)
cmd = cmdLine + (" --rangeStart %d --rangeSize %d" % (groupStart, groupSize))
print(cmd)
# os.system(cmd)
# cmd = "aliceVision_depthMapEstimation --sgmGammaC 5.5 --sgmWSH 4 --refineGammaP 8.0 --refineSigma 15 --refineNSamplesHalf 150 --sgmMaxTCams 10 --refineWSH 3 --downscale 2 --refineMaxTCams 6 --verboseLevel info --refineGammaC 15.5 --sgmGammaP 8.0 --ini \"c:/users/geforce/appdata/local/temp/MeshroomCache/PrepareDenseScene/4f0d6d9f9d072ed05337fd7c670811b1daa00e62/mvs.ini\" --refineNiters 100 --refineNDepthsToRefine 31 --refineUseTcOrRcPixSize False --output \"c:/users/geforce/appdata/local/temp/MeshroomCache/DepthMap/18f3bd0a90931bd749b5eda20c8bf9f6dab63af9\" --rangeStart 0 --rangeSize 3"
# cmd = binName + " --sgmGammaC 5.5 --sgmWSH 4 --refineGammaP 8.0 --refineSigma 15 --refineNSamplesHalf 150 --sgmMaxTCams 10 --refineWSH 3 --downscale 2 --refineMaxTCams 6 --verboseLevel info --refineGammaC 15.5 --sgmGammaP 8.0 --ini \"c:/users/geforce/appdata/local/temp/MeshroomCache/PrepareDenseScene/4f0d6d9f9d072ed05337fd7c670811b1daa00e62/mvs.ini\" --refineNiters 100 --refineNDepthsToRefine 31 --refineUseTcOrRcPixSize False --output \"build_files/07_DepthMap/\" --rangeStart 0 --rangeSize 3"
# cmd = binName + " --sgmGammaC 5.5 --sgmWSH 4 --refineGammaP 8.0 --refineSigma 15 --refineNSamplesHalf 150 --sgmMaxTCams 10 --refineWSH 3 --downscale 2 --refineMaxTCams 6 --verboseLevel info --refineGammaC 15.5 --sgmGammaP 8.0 --ini \"" + srcIni + "\" --refineNiters 100 --refineNDepthsToRefine 31 --refineUseTcOrRcPixSize False --output \"build_files/07_DepthMap/\" --rangeStart 0 --rangeSize 3"
# print(cmd)
# os.system(cmd)
return 0
def Run_08_DepthMapFilter(baseDir, binDir):
# SilentMkdir(baseDir + "/08_DepthMapFilter")
binName = binDir + "\\aliceVision_depthMapFiltering" # .exe"
dstDir = baseDir + "/08_DepthMapFilter"
srcIni = baseDir + "/05_PrepareDenseScene/mvs.ini"
srcDepthDir = baseDir + "/07_DepthMap"
cmdLine = binName
cmdLine = cmdLine + " --minNumOfConsistensCamsWithLowSimilarity 4"
cmdLine = (
cmdLine + " --minNumOfConsistensCams 3 --verboseLevel info --pixSizeBall 0"
)
cmdLine = cmdLine + " --pixSizeBallWithLowSimilarity 0 --nNearestCams 10"
cmdLine = cmdLine + ' --ini "' + srcIni + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '"'
cmdLine = cmdLine + ' --depthMapFolder "' + srcDepthDir + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_09_Meshing(baseDir, binDir):
# SilentMkdir(baseDir + "/09_Meshing")
binName = binDir + "\\aliceVision_meshing" # .exe"
srcIni = baseDir + "/05_PrepareDenseScene/mvs.ini"
srcDepthFilterDir = baseDir + "/08_DepthMapFilter"
srcDepthMapDir = baseDir + "/07_DepthMap"
dstDir = baseDir + "/09_Meshing"
cmdLine = binName
cmdLine = (
cmdLine
+ " --simGaussianSizeInit 10.0 --maxInputPoints 50000000 --repartition multiResolution"
)
cmdLine = (
cmdLine
+ " --simGaussianSize 10.0 --simFactor 15.0 --voteMarginFactor 4.0 --contributeMarginFactor 2.0 --minStep 2 --pixSizeMarginFinalCoef 4.0 --maxPoints 5000000 --maxPointsPerVoxel 1000000 --angleFactor 15.0 --partitioning singleBlock"
)
cmdLine = (
cmdLine
+ " --minAngleThreshold 1.0 --pixSizeMarginInitCoef 2.0 --refineFuse True --verboseLevel info"
)
cmdLine = cmdLine + ' --ini "' + srcIni + '"'
cmdLine = cmdLine + ' --depthMapFilterFolder "' + srcDepthFilterDir + '"'
cmdLine = cmdLine + ' --depthMapFolder "' + srcDepthMapDir + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '/mesh.obj"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_10_MeshFiltering(baseDir, binDir):
# SilentMkdir(baseDir + "/10_MeshFiltering")
binName = binDir + "\\aliceVision_meshFiltering" # .exe"
srcMesh = baseDir + "/09_Meshing/mesh.obj"
dstMesh = baseDir + "/10_MeshFiltering/mesh.obj"
cmdLine = binName
cmdLine = (
cmdLine
+ " --verboseLevel info --removeLargeTrianglesFactor 60.0 --iterations 5 --keepLargestMeshOnly True"
)
cmdLine = cmdLine + " --lambda 1.0"
cmdLine = cmdLine + ' --input "' + srcMesh + '"'
cmdLine = cmdLine + ' --output "' + dstMesh + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_11_Texturing(baseDir, binDir):
# SilentMkdir(baseDir + "/11_Texturing")
binName = binDir + "\\aliceVision_texturing" # .exe"
srcMesh = baseDir + "/10_MeshFiltering/mesh.obj"
srcRecon = baseDir + "/09_Meshing/denseReconstruction.bin"
srcIni = baseDir + "/05_PrepareDenseScene/mvs.ini"
dstDir = baseDir + "/11_Texturing"
cmdLine = binName
cmdLine = cmdLine + " --textureSide 8192"
cmdLine = cmdLine + " --downscale 2 --verboseLevel info --padding 15"
cmdLine = (
cmdLine
+ " --unwrapMethod Basic --outputTextureFileType png --flipNormals False --fillHoles False"
)
cmdLine = cmdLine + ' --inputDenseReconstruction "' + srcRecon + '"'
cmdLine = cmdLine + ' --inputMesh "' + srcMesh + '"'
cmdLine = cmdLine + ' --ini "' + srcIni + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def main():
print("Prepping Scan, v2.")
print(sys.argv)
print(len(sys.argv))
if len(sys.argv) != 6:
print(
"usage: python run_alicevision.py <baseDir> <imgDir> <binDir> <numImages> <runStep>"
)
print("Must pass 6 arguments.")
sys.exit(0)
baseDir = sys.argv[1]
srcImageDir = sys.argv[2]
binDir = sys.argv[3]
numImages = int(sys.argv[4])
runStep = sys.argv[5]
print("Base dir : %s" % baseDir)
print("Image dir : %s" % srcImageDir)
print("Bin dir : %s" % binDir)
print("Num images: %d" % numImages)
print("Step : %s" % runStep)
# SilentMkdir(baseDir)
if runStep == "runall":
Run_00_CameraInit(baseDir, binDir, srcImageDir)
Run_01_FeatureExtraction(baseDir, binDir, numImages)
# Run_02_ImageMatching(baseDir, binDir)
# Run_03_FeatureMatching(baseDir, binDir)
# Run_04_StructureFromMotion(baseDir, binDir)
# Run_05_PrepareDenseScene(baseDir, binDir)
# Run_06_CameraConnection(baseDir, binDir)
# Run_07_DepthMap(baseDir, binDir, numImages, 3)
# Run_08_DepthMapFilter(baseDir, binDir)
# Run_09_Meshing(baseDir, binDir)
# Run_10_MeshFiltering(baseDir, binDir)
# Run_11_Texturing(baseDir, binDir)
elif runStep == "run00":
Run_00_CameraInit(baseDir, binDir, srcImageDir)
elif runStep == "run01":
Run_01_FeatureExtraction(baseDir, binDir, numImages)
elif runStep == "run02":
Run_02_ImageMatching(baseDir, binDir)
elif runStep == "run03":
Run_03_FeatureMatching(baseDir, binDir)
elif runStep == "run04":
Run_04_StructureFromMotion(baseDir, binDir)
elif runStep == "run05":
Run_05_PrepareDenseScene(baseDir, binDir)
elif runStep == "run06":
Run_06_CameraConnection(baseDir, binDir)
elif runStep == "run07":
Run_07_DepthMap(baseDir, binDir, numImages, 3)
elif runStep == "run08":
Run_08_DepthMapFilter(baseDir, binDir)
elif runStep == "run09":
Run_09_Meshing(baseDir, binDir)
elif runStep == "run10":
Run_10_MeshFiltering(baseDir, binDir)
elif runStep == "run11":
Run_11_Texturing(baseDir, binDir)
else:
print("Invalid Step: %s" % runStep)
# print("running")
# Run_00_CameraInit(baseDir,binDir,srcImageDir)
# Run_01_FeatureExtraction(baseDir,binDir,numImages)
# Run_02_ImageMatching(baseDir,binDir)
# Run_03_FeatureMatching(baseDir,binDir)
# Run_04_StructureFromMotion(baseDir,binDir)
# Run_05_PrepareDenseScene(baseDir,binDir)
# Run_06_CameraConnection(baseDir,binDir)
# Run_07_DepthMap(baseDir,binDir,numImages,3)
# Run_08_DepthMapFilter(baseDir,binDir)
# Run_09_Meshing(baseDir,binDir)
# Run_10_MeshFiltering(baseDir,binDir)
# Run_11_Texturing(baseDir,binDir)
return 0
main()
| [
"os.mkdir",
"sys.exit"
] | [((73, 89), 'os.mkdir', 'os.mkdir', (['theDir'], {}), '(theDir)\n', (81, 89), False, 'import sys, os\n'), ((12981, 12992), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (12989, 12992), False, 'import sys, os\n')] |
from django import forms
from . import widgets
from .models import Ticket, TicketItem
#Creating html forms.
# Each class interacts with a model. Fields for a form are chosen in 'fields'
class TicketForm(forms.ModelForm):
#setting timeDue to have specific formatting
timeDue = forms.DateTimeField(
input_formats=['%Y-%m-%d %H:%M:%S'],
widget=widgets.DateTimeField()
)
class Meta:
model = Ticket
fields = ["customer", "boat", "timeDue"]
class TicketItemForm(forms.ModelForm):
class Meta:
model = TicketItem
fields = ["item", "description"]
class TicketItemCompletionForm(forms.ModelForm):
completed = forms.BooleanField(required=False, label='')
class Meta:
model = TicketItem
fields = ["completed"]
class TicketCompletionForm(forms.ModelForm):
class Meta:
model= Ticket
fields = ['completed'] | [
"django.forms.BooleanField"
] | [((679, 723), 'django.forms.BooleanField', 'forms.BooleanField', ([], {'required': '(False)', 'label': '""""""'}), "(required=False, label='')\n", (697, 723), False, 'from django import forms\n')] |
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_with_emamil_successful(self):
"""Test creating a new user with an email is successful"""
email = '<EMAIL>'
password = '<PASSWORD>'
user = get_user_model().objects.create_user( #call the create user function from the user model do not import models directly
email=email, #adds email note all these are custom properties since the user model will be changed
password=password #add password note all these are custom properties since the user model will be changed
)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password)) #you use the check_password function because passwords are encrypted | [
"django.contrib.auth.get_user_model"
] | [((288, 304), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (302, 304), False, 'from django.contrib.auth import get_user_model\n')] |