input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
the name of the fight winner, and the method of winning. Returns a cleaned pandas table.
Set round_by_round=True to use the round-by-round data. Otherwise, uses full fight stats.'''
def create_aggregated_fight_table(raw_fight_tables):
# Aggregate data from multiple tables
fight_table = process_fight(raw_fight_tables["Totals"])
fight_table2 = process_fight(raw_fight_tables["Significant Strikes"])
# Rename column names with identical data to match
fight_table2 = fight_table2.rename(columns={"Fighter 0 Sig. str": "Fighter 0 Sig. str.", "Fighter 1 Sig. str": "Fighter 1 Sig. str."})
# Bring tables together, then remove duplicates
fight_table = pd.concat([fight_table, fight_table2], axis=1)
fight_table = fight_table.loc[:,~fight_table.columns.duplicated()]
return fight_table
def create_aggregated_round_by_round_fight_table(raw_fight_tables):
##### Aggregate data totals table
tables = []
for i, row in raw_fight_tables["Per Round Totals"].iterrows():
# Get df of one round
df = pd.DataFrame(row)
values = list(df[i].to_dict().values())
cols = list(raw_fight_tables["Totals"].columns)
df = pd.DataFrame([values], columns=cols)
# Update columns with round number
new_cols = [f"Round {i+1} {c}" if c != "Fighter" else c for c in cols]
df.columns = new_cols
tables.append(process_fight(df))
# Concatenate round-by-round horizontally, so each row is for 1 fight.
# Then remove duplicates
totals_df = pd.concat(tables, axis=1)
totals_df = totals_df.loc[:,~totals_df.columns.duplicated()]
##### Aggregate data significant strikes table
tables = []
for i, row in raw_fight_tables["Per Round Significant Strikes"].iterrows():
# Get df of one round
df = pd.DataFrame(row)
values = list(df[i].to_dict().values())
cols = list(raw_fight_tables["Significant Strikes"].columns)
if len(values) != len(cols):
values = values[:-1] # Remove last column values, as shown above, has extra column for no reason
df = pd.DataFrame([values], columns=cols)
# Update columns with round number
new_cols = [f"Round {i+1} {c}" if c != "Fighter" else c for c in cols]
df.columns = new_cols
tables.append(process_fight(df))
# Concatenate round-by-round horizontally, so each row is for 1 fight
# Then remove duplicates
sig_strikes_df = pd.concat(tables, axis=1)
sig_strikes_df = sig_strikes_df.loc[:,~sig_strikes_df.columns.duplicated()]
##### Bring tables together, then remove duplicates
fight_table = pd.concat([totals_df, sig_strikes_df], axis=1)
fight_table = fight_table.loc[:,~fight_table.columns.duplicated()]
return fight_table
if round_by_round:
fight_table = create_aggregated_round_by_round_fight_table(raw_fight_tables)
else:
fight_table = create_aggregated_fight_table(raw_fight_tables)
if fight_table["Fighter 0 Name"][0] == winner:
label = 0
elif fight_table["Fighter 1 Name"][0] == winner:
label = 1
else:
print(f'ERROR: fight_table["Fighter 0 Name"]={fight_table["Fighter 0 Name"]}, fight_table["Fighter 1 Name"]={fight_table["Fighter 1 Name"]}, winner={winner}')
label = -1
fight_table['Winner'] = label
fight_table['Method'] = method
return fight_table
# + id="BUyy5MUhNTkJ"
FIGHT_TABLE = []
for i in tqdm(range(len(RAW_FIGHT_TABLES_LIST))):
FIGHT_TABLE.append(process_raw_fight_tables(RAW_FIGHT_TABLES_LIST[i], WINNERS[i], METHODS[i], round_by_round=ROUND_BY_ROUND))
FIGHT_TABLE = pd.concat(FIGHT_TABLE, ignore_index=True)
FIGHT_TABLE = FIGHT_TABLE.replace("^-+", np.nan, regex=True) # Replace -- and --- with nan
# + id="G9EhqLLcAWs-"
FIGHT_TABLE.head()
# + id="7hQjO9B2RDoZ"
FIGHT_TABLE.tail()
# + [markdown] id="pCMOvzM0efI4"
# ## Augment dataset by flipping around columns
#
# The system should work the same no matter what order we pass in the fighters. Let fighters be A and B. We want
#
# winner(fighter0=A, fighter1=B) = winner(fighter0=B, fighter1=A)
# + id="kM2b_cAif7rM"
def create_flipped_table(table):
'''Rearranges columns of table so that each fight has two rows. Let fighters be A and B.
One row has (Fighter 0 = A, Fighter 1 = B). One row has (Fighter 0 = B, Fighter 1 = A)
Ensure same column order, as column names not looked at when passed to ML model'''
# Get columns in flipped order, which moves the columns around, but changes column name order too
flipped_columns = []
for column in table.columns:
if "Fighter 0" in column:
flipped_columns.append(column.replace("Fighter 0", "Fighter 1"))
elif "Fighter 1" in column:
flipped_columns.append(column.replace("Fighter 1", "Fighter 0"))
else:
flipped_columns.append(column)
flipped_table = table[flipped_columns]
# Flips winners around
if 'Winner' in flipped_table.columns:
flipped_table['Winner'] = flipped_table['Winner'].replace([0, 1], [1, 0])
# Change column names back to normal
flipped_table.columns = table.columns
return flipped_table
# + id="KQcGgKW6k-ba"
def add_rows_of_flipped_columns(table):
flipped_table = create_flipped_table(table)
new_table = pd.concat([table, flipped_table])
return new_table
# + id="HnwZdNiplLF3"
FULL_FIGHT_TABLE = add_rows_of_flipped_columns(FIGHT_TABLE)
# + id="PlnOp-fbjknE"
FULL_FIGHT_TABLE.head()
# + [markdown] id="gu7-RmZOkP68"
# ## Example of augmented data
# + id="PHsGqr0_joHn"
FULL_FIGHT_TABLE[(FULL_FIGHT_TABLE['Fighter 0 Name'] == "<NAME>") & (FULL_FIGHT_TABLE['Fighter 1 Name'] == "<NAME>")]
# + id="samSx7Olj3vQ"
FULL_FIGHT_TABLE[(FULL_FIGHT_TABLE['Fighter 1 Name'] == "<NAME>") & (FULL_FIGHT_TABLE['Fighter 0 Name'] == "<NAME>")]
# + [markdown] id="3OOgguk84RJl"
# ## Additional data cleaning
#
# TODO: See if something better than replacing nan with 0. See if something better for labels than 0 and 1. Could remove fights with no winner, or handle them differently. Could remove fights that don't go to decision by removing based on Method.
# + id="RIS0yarnbTmj"
X = FIGHT_TABLE.drop(['Winner', 'Fighter 0 Name', 'Fighter 1 Name', 'Method'], axis=1).fillna(0)
y = FIGHT_TABLE[['Winner']]
# + id="QxOiDLXHfgDx"
X.head()
# + id="N5qqnw6Efh8K"
y.head()
# + [markdown] id="JwvrHfOCf1mh"
# ## Setup train/validate/test split
# Can't blindly use full fight table train/validate/test split, because the augmented data must stay together. If in train we know winner(A, B) = A, then we don't want to have winner(B, A) in the validation/test set.
# + id="CwlwAWNRcwJ1"
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=0)
X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size=0.33, random_state=0)
X_train, y_train = add_rows_of_flipped_columns(X_train), add_rows_of_flipped_columns(y_train)
X_valid, y_valid = add_rows_of_flipped_columns(X_valid), add_rows_of_flipped_columns(y_valid)
X_test, y_test = add_rows_of_flipped_columns(X_test), add_rows_of_flipped_columns(y_test)
# + id="aFmWIOydoJXd"
# Expect equal number of examples in Fighter 0 as Fighter 1
assert(len(y_train[y_train['Winner'] == 0]) == len(y_train[y_train['Winner'] == 1]))
assert(len(y_valid[y_valid['Winner'] == 0]) == len(y_valid[y_valid['Winner'] == 1]))
assert(len(y_test[y_test['Winner'] == 0]) == len(y_test[y_test['Winner'] == 1]))
# + id="jekwTdNAk3rE"
X_train.head()
# + id="BUeeqFtHpZQw"
y_train.head()
# + id="75PnIBkYpabr"
print(f"X_train.shape = {X_train.shape}")
print(f"X_valid.shape = {X_valid.shape}")
print(f"X_test.shape = {X_test.shape}")
print(f"y_train.shape = {y_train.shape}")
print(f"y_valid.shape = {y_valid.shape}")
print(f"y_test.shape = {y_test.shape}")
# + [markdown] id="ARUH8kxCbJpG"
# ## ML Models
# + id="0_v4cnEFbKp3"
from sklearn.ensemble import RandomForestClassifier
# + id="6gOrDS8AbPqM"
# Train
clf = RandomForestClassifier(max_depth=5, random_state=0)
clf.fit(X_train, y_train)
# Validate
accuracy_train = clf.score(X_train, y_train)
accuracy_valid = clf.score(X_valid, y_valid)
print(f"accuracy_train = {accuracy_train}")
print(f"accuracy_valid = {accuracy_valid}")
# + id="dn1Njq7ecfAT"
import matplotlib.pyplot as plt
# Visualize importances
plt.rcParams.update({'font.size': 8})
plt.barh(X_train.columns, clf.feature_importances_)
# + id="GifEEZiTq2yL"
# MLP
from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(random_state=1, max_iter=300).fit(X_train, y_train)
accuracy_train = clf.score(X_train, y_train)
accuracy_valid = clf.score(X_valid, y_valid)
print(f"accuracy_train = {accuracy_train}")
print(f"accuracy_valid = {accuracy_valid}")
# + id="r6tiCNo3rEE0"
# SVM
from sklearn.svm import SVC
clf = SVC(random_state=1).fit(X_train, y_train)
accuracy_train = clf.score(X_train, y_train)
accuracy_valid = clf.score(X_valid, y_valid)
print(f"accuracy_train = {accuracy_train}")
print(f"accuracy_valid = {accuracy_valid}")
# + id="KNxPPw2DrbpW"
# FFN
import tensorflow as tf
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=X_train.shape[1:]))
model.add(tf.keras.layers.Dense(32, activation='relu'))
model.add(tf.keras.layers.Dense(32, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
tf.keras.utils.plot_model(model, show_shapes=True, rankdir="LR")
# + id="agRwGSv2IEKa"
model.summary()
# + id="Wo9gE7_HtQhl"
model.fit(X_train, y_train, epochs=100, validation_data=(X_valid, y_valid))
# + id="RWTGwJUVtalk"
model.evaluate(X_train, y_train)
model.evaluate(X_valid, y_valid)
# + [markdown] id="ZOwm0hZTxZyr"
# ## Test out model manually
# + id="OWIypYX-uryi"
idx = 6
# + id="ofKgNtPPuC0V"
X_test.iloc[idx]
# + id="4tEAEW59ulsz"
# 0 means fighter 0 won. 1 means fighter 1 won.
y_test.iloc[idx]
# + id="67EbW0E1uXGi"
X_test.shape
# + id="3FWZP5LfuYYJ"
X_test.iloc[idx].shape
# + id="W19rlXXouGfs"
model.predict(np.expand_dims(X_test.iloc[idx], 0))
# + [markdown] id="ZOwm0hZTxZyr"
# ## Save data
#
# Store beginning file parameters.
# Use current date and time to save files uniquely.
# +
from datetime import datetime
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y_%H:%M:%S")
print("dt_string =", dt_string)
# -
parameters_string = f"NUM_EVENTS_{NUM_EVENTS_INPUT}_DATA_MODE_{DATA_MODE_INPUT}"
print("parameters_string =", parameters_string)
import pickle
filename1 = f"FULL_FIGHT_TABLE_{parameters_string}_{dt_string}.csv"
filename2 = f"FIGHT_TABLE_{parameters_string}_{dt_string}.csv"
filename3 = f"ALL_FIGHTERS_{parameters_string}_{dt_string}.csv"
filename4 = f"RAW_FIGHT_TABLES_LIST_{parameters_string}_{dt_string}.pkl"
print(f"Saving to {filename1} and {filename2} and {filename3} and {filename4}")
FULL_FIGHT_TABLE.to_csv(filename1, index=False)
FIGHT_TABLE.to_csv(filename2, index=False)
ALL_FIGHTERS.to_csv(filename3, index=False)
with open(filename4, 'wb') as handle:
pickle.dump(RAW_FIGHT_TABLES_LIST, handle, protocol=pickle.HIGHEST_PROTOCOL)
new = pd.read_csv(filename1)
new
with open(filename4, 'rb') as pickle_file:
new2 = pickle.load(pickle_file)
len(new2[0])
# ## Experimental: Get detailed fighter information
#
# TODO: Get more detailed information about fighters, so we can change the task to fight prediction using fighter stats only. http://ufcstats.com/statistics/fighters?char=a&page=all has little information compared to http://ufcstats.com/fighter-details/33a331684283900f. Still lots to improve. Better features like strikes per minute. Handling nans better. Handling non win/losses better.
def get_all_fighters_detailed():
'''Get pandas table with detailed information about all UFC fighters (KO's, strikes, etc.)'''
fighter_detailed_tables = []
# For each letter of the alphabet, get the fighters
for c in tqdm(ascii_lowercase):
# Each page has a list of fighter detail urls
all_fighters_url = f"http://ufcstats.com/statistics/fighters?char={c}&page=all"
all_fighters_html = urlopen(all_fighters_url).read().decode("utf-8")
# Regex for "http://ufcstats.com/fighter-details/<alphanumeric>"
# Eg. "http://ufcstats.com/fighter-details/27541033b97c076d"
pattern = "\"http://ufcstats.com/fighter-details/[a-zA-Z0-9_]+\""
urls = re.findall(pattern, all_fighters_html)
# Remove quotes and duplicates
urls = [url.strip("\"") for url in urls]
urls = remove_duplicates_keep_order(urls)
# For each fighter detail url, merge together their record information
# Initially in form "<NAME>", "0 0", "1:10, 0:00"
# Want just "<NAME>", "0", "1:10", then convert to numbers
# Just need to get the first value of each one, then average/sum/aggregate this together
for url in urls:
fighter_table = pd.read_html(url)[0].dropna(subset=["Time"], how='all') # Drop initial row of nans
# If no fight information, add empty dataframe
if fighter_table.shape[0] == 0:
df = pd.DataFrame()
fighter_detailed_tables.append(df)
continue
# Preprocess certain values for consistency
# TODO: Handle this better, perhaps keep more information
fighter_table = fighter_table.drop(columns=["Method", "Event"])
fighter_table.loc[~fighter_table['W/L'].isin(['win', 'loss']), 'W/L'] = "-1 -1"
fighter_table.loc[fighter_table['W/L'] == 'win', 'W/L'] = "1 1"
fighter_table.loc[fighter_table['W/L'] == 'loss', 'W/L'] = "0 0"
times = [int(min_) * 60 + int(sec) for min_, sec in fighter_table['Time'].str.split(':')]
fighter_table['Time'] = [f"{t} {t}" for t in times]
# Parse each row to remove the other fighter's information
new_rows = []
for i, row in fighter_table.iterrows():
# Get df | |
<reponame>omikabir/omEngin<filename>TBOT/mssql.py
import pandas as pd
import pyodbc
from datetime import *
soc = "Driver={SQL Server};SERVER=192.168.88.121;DATABASE=SOC_Roster;UID=sa;PWD=<PASSWORD>&"
#soc = "Driver={SQL Server};SERVER=localhost;DATABASE=SOC_Roster;UID=sa;PWD=<PASSWORD>$"
def chk_exist(qry):
conn = pyodbc.connect(soc)
df = pd.read_sql(qry, con=conn)
return df.shape[0]
def exqry(qr):
conn = pyodbc.connect(soc)
cr = conn.cursor()
print(qr)
st = 'does not exist'
if 'select' in qr:
cr.execute(qr)
rs = cr.fetchone()
try:
for i in rs:
if st == 'does not exist':
st = i
else:
st = st + ' | ' + i
return st
except:
return st
else:
if isinstance(qr, str):
try:
cr.execute(qr)
conn.commit()
return 'successfully'
except:
print(qr, 'failed')
return ''
elif isinstance(qr, list):
cnt = 0
for i in range(len(qr)):
try:
cr.execute(qr)
cnt = cnt + 1
except:
pass
else:
st = cnt + ' rows modified successfully'
return st
def execute_qry(qq, colname=[]):
conn = pyodbc.connect(soc)
print('query execute- ', qq)
if "select" in qq:
df = pd.read_sql(qq, con=conn)
heap = ''
ls = []
if len(colname) != 0:
dfx = df[colname]
df = dfx
print(df)
if df.shape[0] > 1:
for i in range(len(df)):
hp = ''
for j in df:
if hp == '':
hp = df.loc[i, j]
else:
hp = hp + ',' + df.loc[i, j]
if heap == '':
heap = hp
elif len(heap) < 3500:
heap = heap + chr(10) + hp
else:
ls.append(heap)
heap = ''
else:
ls.append(heap)
return ls
elif df.shape[0] == 1:
hp = ''
for i in df:
if hp == '':
hp = df.loc[0, i]
else:
hp = hp + chr(10) + df.loc[0, i]
return hp
else:
return 'not exist'
elif "update" in qq or "delete" in qq:
cr = conn.cursor()
try:
cr.execute(qq)
conn.commit()
return "successful"
except:
return "failed"
else:
cr = conn.cursor()
cr.execute(qq)
def qry_code_name(code, cols = []):
qry = "select Site_Name from sitebase where Site_Code LIKE '%" + code + "%'"
conn = pyodbc.connect(soc)
cr = conn.cursor()
st = ''
try:
cr.execute(qry)
rs = cr.fetchone()
for i in rs:
if st == '':
st = i
else:
st = st + ", " + i
return st
except:
return ""
def qry_select(tx2, omv):
qry = ''
qy = ''
tbl = ''
if 'CONTACT' in tx2 or 'CONTACTS' in tx2:
qry = "select Number from PeriCon where Number LIKE '%" + omv + "%'"
qy = exqry(qry)
tbl = ' periodic contacts'
elif "ABH" in tx2 or 'ABHIGHTECH' in tx2:
qry = "select Code from ABHI where Code LIKE '%" + omv + "%'"
qy = exqry(qry)
tbl = ' AB hi-tech'
elif "RMT" in tx2 or 'ROBIMT' in tx2:
qry = "select Code,Name from RMT where Code LIKE '%" + omv + "%'"
qy = exqry(qry)
tbl = ' robi mt'
elif "VIP" in tx2:
qry = "select Code,Name from VIP where Code LIKE '%" + omv + "%'"
qy = exqry(qry)
tbl = ' vip'
elif "TOP5" in tx2:
qry = "select Code,Name from TOP5 where Code LIKE '%" + omv + "%'"
qy = exqry(qry)
tbl = ' vip top5'
elif "EXCEPTION" in tx2:
qry = "select code from EXCEPTION where Code LIKE '%" + omv + "%'"
qy = exqry(qry)
tbl = 'EXCEPTION '
else:
txx = tx2.split(',')
qry = "select * from " + txx[1] + "where Code LIKE '%" + omv + "%'"
qy = exqry(qry)
if str(omv) in str(qy):
return omv + ' already exist in' + tbl
else:
return omv + ' does not exist in' + tbl
def qry_add(tx2, omv):
qry = ''
sitename = ''
result = qry_select(tx2, omv)
if 'does not exist' in result:
if 'CONTACT' in tx2:
qry = "insert into PeriCon (Number) values ('" + omv + "')"
tbl = " in periodic contacts "
elif "ABH" in tx2:
qry = "insert into ABHI (Code) values ('" + omv + "')"
tbl = " in ab-hitech "
elif "RMT" in tx2:
sitename = qry_code_name(omv)
qry = "insert into RMT (Code,Name) values ('" + omv + "','" + sitename + "')"
tbl = " in RMT "
elif "VIP" in tx2:
sitename = qry_code_name(omv)
qry = "insert into VIP (Code,Name) values ('" + omv + "','" + sitename + "')"
tbl = " in VIP "
elif "VIPTOP5" in tx2:
sitename = qry_code_name(omv)
qry = "insert into TOP5 (Code,Name) values ('" + omv + "','" + sitename + "')"
tbl = " in VIPTO5 "
elif "EXCEPTION" in tx2:
qry = "insert into EXCEPTION (code,reason) values ('" + omv + "','" + "" + "')"
tbl = " in EXCEPTION "
if qry != '':
rs = exqry(qry)
if 'failed' not in rs:
return 'added ' + omv + tbl + rs
else:
return 'adding failed - ' + omv + tbl + rs
else:
return result
def qry_delete(tx2, omv):
qry = ''
result = qry_select(tx2, omv)
print('chk result', result)
if 'does not exist' not in result:
if 'CONTACT' in tx2:
qry = "DELETE FROM PeriCon WHERE Number Like '" + omv + "'"
tbl = " from periodic contacts "
elif "ABH" in tx2:
qry = "DELETE FROM ABHI WHERE Code Like '" + omv + "'"
tbl = " from ABHI-TECH "
elif "RMT" in tx2:
qry = "DELETE FROM RMT WHERE Code Like '" + omv + "'"
tbl = " from Robi top MGT "
elif "VIP" in tx2:
qry = "DELETE FROM VIP WHERE Code Like '" + omv + "'"
tbl = " from VIP "
elif "VIPTOP5" in tx2:
qry = "DELETE FROM TOP5 WHERE Code Like '" + omv + "'"
tbl = " from VIP-TOP5 "
elif "EXCEPTION" in tx2:
qry = "DELETE FROM EXCEPTION WHERE code Like '" + omv + "'"
tbl = " from EXCEPTION "
if qry != '':
rs = exqry(qry)
return 'removed ' + omv + tbl + rs
else:
return 'failed'
else:
return result
def auth_check_db(uid):
conn = pyodbc.connect(soc)
qry = "select * from om_socbot_access"
df1 = pd.read_sql(qry, con=conn)
df = df1[df1['UID'].str.contains(uid)]
x = df.shape[0]
conn.close()
if x == 0:
return 0
else:
return 1
def query_code_or_ms(tx):
try:
if ',' in tx:
txx = tx.split(',')
xx = str(txx[2])
xxy = xx.strip(' ')
print('xx - ', xxy)
return xxy
else:
txx = tx.split(' ')
xx = str(txx[2])
if len(xx) == 10 or len(xx) == 11:
return xx
else:
return ""
except:
return ""
def private_add_rmv_upd(txt, ty='text'):
print('private_add_rmv_upd')
if ty == 'text':
tx1 = txt.upper()
rs = query_code_or_ms(tx1)
print(rs)
qx = ''
qy = ''
if rs != '':
if 'CHK' in tx1:
qx = qry_select(tx1, rs)
return qx
elif 'RMV' in tx1:
qx = qry_delete(tx1, rs)
return qx
elif 'ADD' in tx1:
qx = qry_add(tx1, rs)
return qx
else:
return "NA"
else:
print('x')
def rpa_help():
rpachk = ["chk, VIP, PBSDR01", "chk, ABHITECH, KHSDR56", "chk, TOP5, DHGUL19", "chk, contact, 01817183680", "chk, RMT, DHGULF2", "chk, exception, DHGULF2"]
rpaadd = ["add, VIP, PBSDR01", "add, ABHITECH, PBSDR01", "add, TOP5, PBSDR01", "add, contact, 01717015682", "add, RMT, DHGULF0", "add, exception, DHGULF2"]
rparmv = ["rmv, VIP, PBSDR01", "rmv, ABHITECH, PBSDR01", "rmv, TOP5, PBSDR01", "rmv, contact, 01717015682", "rmv, RMT, DHGULF0", "rmv, exception, DHGULF2"]
st = ''
for i in range(len(rpachk)):
st1 = rpachk[i]
st2 = rpaadd[i]
st3 = rparmv[i]
if st =='':
st = st1 + chr(10) + st2 + chr(10) + st3
else:
st = st + chr(10) + st1 + chr(10) + st2 + chr(10) + st3
else:
return st
def priority(txt):
tx2 = txt.upper()
qq = ''
if tx2 == "RWS":
qq = "select TOP 1 msgtext from rpa_msg where msghead ='update s' ORDER BY SL DESC"
elif tx2 == "P1":
qq = "select TOP 1 msgtext from rpa_msg where msghead ='update p1' ORDER BY SL DESC"
elif tx2 == "P2":
qq = "select TOP 1 msgtext from rpa_msg where msghead ='update p2' ORDER BY SL DESC"
if qq != '':
rs = exqry(qq)
if rs != '':
return rs
else:
return "database update on going, please try | |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 5 16:16:35 2019
@author: Meghana
"""
# import os
# os.environ['JOBLIB_START_METHOD'] = "forkserver"
# export JOBLIB_START_METHOD="forkserver"
from numpy import exp as np_exp
from numpy.random import uniform as rand_uniform
from tqdm import tqdm
from joblib import Parallel, delayed
from pickle import load as pickle_load, dump as pickle_dump
from logging import info as logging_info, debug as logging_debug
from os import mkdir as os_mkdir, path as os_path,remove as os_remove
from distutils.dir_util import copy_tree
from shutil import copyfile,rmtree
from networkx import Graph as nx_Graph
from multiprocessing import cpu_count as mul_cpu_count
from sample_helpers import *
def search_max_neig(seed_node, scaler, par_inputs_fn):
with open(par_inputs_fn, 'rb') as f:
inputs = pickle_load(f)
with open(inputs['modelfname'], 'rb') as f:
model = pickle_load(f) # Seed node
logging_debug("Seed node is", seed_node)
folNm = inputs['folNm']
folNm_out = inputs['folNm_out']
max_nodes = inputs["max_size"]
score_curr = 0
cd, g1 = starting_edge(folNm, seed_node)
if cd == 0:
return
while len(g1) < max_nodes:
# print(len(g1))
logging_debug("Adding next node")
neig_list = read_neigs(g1.nodes(), folNm)
if not neig_list: # Checking if empty
logging_debug("No more neighbors to add")
break
node_to_add = max(neig_list.items(), key=lambda elem: elem[1]['weight'])[0]
g1 = add_newnode(g1, node_to_add, neig_list[node_to_add]['graph_neigs'])
score_prev = score_curr
(score_curr, comp_bool) = get_score(g1, model, scaler, inputs['model_type'])
if score_curr < inputs["classi_thresh"]:
logging_debug("Complex found")
# Remove the node last added
g1.remove_node(node_to_add)
score_curr = score_prev
break
with open(folNm_out + "/" + seed_node, 'wb') as f:
pickle_dump((frozenset(g1.nodes()), score_curr), f)
def search_top_neigs(seed_node, scaler, par_inputs_fn):
# Picks out of a subset of its neighbors and adds the best node
# logging_debug("No. of nodes in g = ",len(G))
# Assigning original graph to temporary variable
with open(par_inputs_fn, 'rb') as f:
inputs = pickle_load(f)
with open(inputs['modelfname'], 'rb') as f:
model = pickle_load(f)
folNm = inputs['folNm']
folNm_out = inputs['folNm_out']
cd, g1 = starting_edge(folNm, seed_node)
if cd == 0:
return
score_curr = 0
max_nodes = inputs["max_size"]
thres_neig = inputs["thres_neig"] # Threshold on number of neighbors to consider
while len(g1) < max_nodes:
score_prev = score_curr
logging_debug("Adding next node")
g1, cc, node_to_add, score_curr, comp_bool, rand_flag = add_top_neig(g1, thres_neig, folNm, inputs,
model, scaler)
if (score_curr is None) or (comp_bool is None):
score_curr, comp_bool = get_score(g1, model, scaler, inputs['model_type'])
if cc == 0:
break
if score_curr < inputs["classi_thresh"]:
logging_debug("Complex found")
# Remove the node last added
g1.remove_node(node_to_add)
score_curr = score_prev
break
with open(folNm_out + "/" + seed_node, 'wb') as f:
pickle_dump((frozenset(g1.nodes()), score_curr), f)
def met(g1, model, scaler, inputs, score_prev):
max_nodes = inputs["max_size"] - len(g1)
num_iter = 1
last_iter_imp = 0
thres_neig = inputs["thres_neig"]
prob_metropolis = inputs["prob_metropolis"]
folNm = inputs['folNm']
met_low_prob_acc = 0
while num_iter < max_nodes: # Limiting number of iteration rounds
logging_debug("Adding next node")
# neig_list_old = neig_list
# g1, cc, node_to_add, score_curr, comp_bool, rand_flag, neig_list = add_top_neig(g1, thres_neig, folNm, inputs, model, scaler, neig_list)
g1, cc, node_to_add, score_curr, comp_bool, rand_flag = add_top_neig(g1, thres_neig, folNm, inputs, model, scaler)
if (score_curr is None) or (comp_bool is None):
score_curr, comp_bool = get_score(g1, model, scaler, inputs['model_type'])
if cc == 0:
break
if score_curr < inputs["classi_thresh"]:
logging_debug("Complex found")
# Remove the node last added
g1.remove_node(node_to_add)
break
cur_trial = rand_uniform(low=0.0, high=1.0)
if score_curr < score_prev:
if cur_trial > prob_metropolis:
# Remove the node last added
g1.remove_node(node_to_add)
# neig_list = neig_list_old
else:
logging_debug("Accepting with low probability")
met_low_prob_acc += 1
rand_flag = 1
elif score_curr > score_prev:
last_iter_imp = num_iter
if (num_iter - last_iter_imp) > 10: # Has been a long time since a score improvement
logging_debug("Long time since score improvement")
break
score_prev = score_curr
num_iter += 1
logging_debug("No. of low probability acceptances = ")
logging_debug(str(met_low_prob_acc))
# print(g1.nodes())
# print(g1.edges())
return frozenset(g1.nodes()), score_prev
def search_metropolis_clique_start(scaler, par_inputs_fn, G_clique):
# Picks out of a subset of its neighbors and adds the best node
# print(seed_clique)
with open(par_inputs_fn, 'rb') as f:
inputs = pickle_load(f)
with open(inputs['modelfname'], 'rb') as f:
model = pickle_load(f)
g1 = nx_Graph(G_clique)
# Finding score
score_prev, comp_bool = get_score(g1, model, scaler, inputs['model_type'])
# Removing starting points which are not complexes
if score_prev < inputs["classi_thresh"]:
return
a, b = met(g1, model, scaler, inputs, score_prev)
name = " ".join([str(n) for n in g1.nodes()])
with open(folNm_out + "/" + name, 'wb') as f:
pickle_dump((a, b), f)
def search_metropolis(seed_node, scaler, par_inputs_fn):
# Picks out of a subset of its neighbors and adds the best node
with open(par_inputs_fn, 'rb') as f:
inputs = pickle_load(f)
with open(inputs['modelfname'], 'rb') as f:
model = pickle_load(f)
folNm = inputs['folNm']
folNm_out = inputs['folNm_out']
cd, g1 = starting_edge(folNm, seed_node)
if cd == 0:
return
a, b = met(g1, model, scaler, inputs, 0)
with open(folNm_out + "/" + seed_node, 'wb') as f:
pickle_dump((a, b), f)
def search_isa(seed_node, scaler, par_inputs_fn): # Picks out of a subset of its neighbors and adds the best node
with open(par_inputs_fn, 'rb') as f:
inputs = pickle_load(f)
with open(inputs['modelfname'], 'rb') as f:
model = pickle_load(f)
folNm = inputs['folNm']
folNm_out = inputs['folNm_out']
score_prev = 0
cd, g1 = starting_edge(folNm, seed_node)
if cd == 0:
return
max_nodes = inputs["max_size"] - len(g1)
num_iter = 1
last_iter_imp = 0
thres_neig = inputs["thres_neig"]
T = inputs["T0"] # T0 value
alpha = inputs["alpha"]
while num_iter < max_nodes: # Limiting number of iteration rounds
logging_debug("Adding next node")
# neig_list_old = neig_list
# g1, cc, node_to_add, score_curr, comp_bool, rand_flag, neig_list = add_top_neig(g1, thres_neig, folNm, inputs, model, scaler, neig_list)
g1, cc, node_to_add, score_curr, comp_bool, rand_flag = add_top_neig(g1, thres_neig, folNm, inputs, model, scaler)
if (score_curr is None) or (comp_bool is None):
score_curr, comp_bool = get_score(g1, model, scaler, inputs['model_type'])
if cc == 0:
break
if score_curr < inputs["classi_thresh"]:
logging_debug("Complex found")
# Remove the node last added
g1.remove_node(node_to_add)
break
cur_trial = rand_uniform(low=0.0, high=1.0)
if score_curr < score_prev:
prob_isa = np_exp((score_curr - score_prev) / T)
if cur_trial > prob_isa:
# Remove the node last added
g1.remove_node(node_to_add)
# neig_list = neig_list_old
else:
logging_debug("Accepting with low probability")
rand_flag = 1
elif score_curr > score_prev:
last_iter_imp = num_iter
if (num_iter - last_iter_imp) > 10: # Has been a long time since a score improvement
logging_debug("Long time since score improvement")
break
score_prev = score_curr
num_iter += 1
T = float(T) / alpha
# If number of nodes is less than 2, don't write.
with open(folNm_out + "/" + seed_node, 'wb') as f:
pickle_dump((frozenset(g1.nodes()), score_prev), f)
def sample(inputs, G, modelfname, scaler, seed_nodes, max_size,transfer2tmp):
seed_mode = inputs['seed_mode']
out_comp_nm = inputs['dir_nm'] + inputs['out_comp_nm']
logging_info("Sampling complexes...")
num_cores = mul_cpu_count()
if 'num_cores' in inputs:
num_cores = inputs['num_cores']
# num_comp = 10
num_comp = len(seed_nodes)
with open(out_comp_nm + '_metrics.out', "a") as fid:
print("No. of cores = ", num_cores, file=fid)
print("No. of seeds for complex search = ", num_comp, file=fid)
search_method = inputs["search_method"]
folNm_out = "/tmp/" + out_comp_nm + "_orig_comps"
folNm = inputs['dir_nm'] + inputs['graph_files_dir'] + "/neig_dicts"
if not os_path.exists("/tmp/"):
os_mkdir("/tmp/")
if not os_path.exists("/tmp/" + inputs['dir_nm']):
os_mkdir("/tmp/" + inputs['dir_nm'])
if not os_path.exists("/tmp/" + inputs['dir_nm'] + inputs['graph_files_dir'] ):
os_mkdir("/tmp/" + inputs['dir_nm'] + inputs['graph_files_dir'] )
if not os_path.exists("/tmp/" + out_comp_nm[:-3]):
os_mkdir("/tmp/" + out_comp_nm[:-3])
out_comp_nm_model = inputs['dir_nm'] + inputs['model_dir']
if not os_path.exists("/tmp/" + out_comp_nm_model[:-3]):
os_mkdir("/tmp/" + out_comp_nm_model[:-3])
if not os_path.exists(folNm_out):
os_mkdir(folNm_out)
tmp_prefix_read = ""
if transfer2tmp:
tmp_prefix_read = "/tmp/"
if "classi_thresh" not in inputs:
inputs["classi_thresh"] = 0.5
par_inputs = {"classi_thresh": inputs["classi_thresh"],"use_all_neigs": inputs["use_all_neigs"], "min_thres_neig_sorted": inputs["min_thres_neig_sorted"],
"modelfname": tmp_prefix_read + modelfname, "folNm_out": folNm_out, "folNm": tmp_prefix_read + folNm,
"model_type": inputs["model_type"],
"max_size": max_size, "perc": inputs["perc"], "thres_neig": inputs["thres_neig"],
"T0": inputs["T0"], "alpha": inputs["alpha"], "prob_metropolis": inputs["prob_metropolis"],
"explore_prob": inputs["explore_prob"], "feats": inputs["feats"]}
par_inputs_fn = tmp_prefix_read + inputs['dir_nm'] + "/res_par_inputs"
if transfer2tmp:
if not os_path.exists("/tmp/" + modelfname):
copyfile(modelfname, "/tmp/" + modelfname)
if not os_path.exists("/tmp/" + folNm):
os_mkdir("/tmp/" + folNm)
copy_tree(folNm, "/tmp/" + folNm)
with open(par_inputs_fn, 'wb') as f:
pickle_dump(par_inputs, f)
if inputs["run_mode"] == "parallel":
# method = "threads" method = "processes" # better since we are not releasing the GIL ? prefer not required
# when backend is specified. (prefer = method in parallel args)
back = 'loky' # loky and multiprocessing for processes and threading for threads
if "backend" in inputs:
back = inputs['backend']
if seed_mode == "cliques":
Parallel(n_jobs=num_cores, backend=back)(
delayed(search_metropolis_clique_start)(scaler, par_inputs_fn, G.subgraph(clique)) for clique in
tqdm(seed_nodes))
elif search_method == "isa":
Parallel(n_jobs=num_cores, backend=back)(
delayed(search_isa)(node, scaler, par_inputs_fn) for node in tqdm(seed_nodes))
elif search_method == | |
everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1PersistentVolumeClaimList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeClaimList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_persistent_volume_claim(self, body, namespace, **kwargs):
"""
create a PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_persistent_volume_claim(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1PersistentVolumeClaim body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_persistent_volume_claim`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeClaim',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_persistent_volume_claim(self, namespace, **kwargs):
"""
delete collection of PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_persistent_volume_claim(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_persistent_volume_claim(self, namespace, name, **kwargs):
"""
read the specified PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_persistent_volume_claim(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PersistentVolumeClaim (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_persistent_volume_claim`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeClaim',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_persistent_volume_claim(self, body, namespace, name, **kwargs):
| |
<reponame>toastisme/cctbx_project<filename>mmtbx/command_line/geometry_minimization.py
# LIBTBX_SET_DISPATCHER_NAME phenix.geometry_minimization
from __future__ import absolute_import, division, print_function
import mmtbx.refinement.geometry_minimization
import mmtbx.utils
from iotbx.pdb import combine_unique_pdb_files
import iotbx.phil
from cctbx.array_family import flex
from libtbx.utils import user_plus_sys_time, Sorry
from libtbx import runtime_utils
import os
import sys
from six.moves import cStringIO as StringIO
from mmtbx.monomer_library import pdb_interpretation
from mmtbx.hydrogens import riding
import mmtbx.model
from cctbx import uctbx
base_params_str = """\
silent = False
.type = bool
write_geo_file = True
.type = bool
file_name = None
.type = path
.short_caption = Model file
.style = file_type:pdb bold input_file
show_states = False
.type = bool
restraints = None
.type = path
.multiple = True
.short_caption = Restraints
.style = file_type:cif bold input_file
restraints_directory = None
.type = path
.style = directory
output_file_name_prefix = None
.type = str
.input_size = 400
.style = bold
directory = None
.type = path
.short_caption = Output directory
.style = output_dir
include scope libtbx.phil.interface.tracking_params
fix_rotamer_outliers = True
.type = bool
.help = Remove outliers
allow_allowed_rotamers = True
.type = bool
.help = More strict fixing outliers
stop_for_unknowns = True
.type = bool
.short_caption = Stop for unknown residues
.style = noauto
include scope mmtbx.monomer_library.pdb_interpretation.grand_master_phil_str
include scope \
mmtbx.geometry_restraints.torsion_restraints.reference_model.reference_model_params
"""
master_params_str = """
%s
selection = all
.type = str
.help = Atom selection string: selected atoms are subject to move
.short_caption = Atom selection
.input_size = 400
minimization
.help = Geometry minimization parameters
.short_caption = Minimization parameters
.expert_level=1
{
max_iterations = 500
.type = int
.help = Maximun number of minimization iterations
.short_caption = Max. iterations
.style = noauto
macro_cycles = 5
.type = int
.help = Number of minimization macro-cycles
alternate_nonbonded_off_on = False
.type = bool
.short_caption = Macro cycles
.style = noauto
rmsd_bonds_termination_cutoff = 0
.type = float
.help = stop after reaching specified cutoff value
rmsd_angles_termination_cutoff = 0
.type = float
.help = stop after reaching specified cutoff value
grms_termination_cutoff = 0
.type = float
.help = stop after reaching specified cutoff value
correct_special_position_tolerance = 1.0
.type = float
riding_h = True
.type = bool
.help = Use riding model for H
move
.help = Define what to include into refinement target
.short_caption = Geometry terms
.style = box auto_align columns:4 noauto
{
bond = True
.type = bool
.short_caption = Bond lengths
nonbonded = True
.type = bool
.short_caption = Nonbonded distances
angle = True
.type = bool
.short_caption = Bond angle
dihedral = True
.type = bool
.short_caption = Dihedral angle
chirality = True
.type = bool
.short_caption = Chirality
planarity = True
.type = bool
.short_caption = Planarity
parallelity = True
.type = bool
.short_caption = Parallelity
}
}
include scope mmtbx.geometry_restraints.external.external_energy_params_str
""" % base_params_str
def master_params():
return iotbx.phil.parse(master_params_str, process_includes=True)
def broadcast(m, log):
print("-"*79, file=log)
print(m, file=log)
print("*"*len(m), file=log)
def format_usage_message(log):
print("-"*79, file=log)
msg = """\
phenix.geometry_minimization: regularize model geometry
Usage examples:
phenix.geometry_minimization model.pdb
phenix.geometry_minimization model.pdb ligands.cif
"""
print(msg, file=log)
print("-"*79, file=log)
def run_minimization(
selection,
restraints_manager,
riding_h_manager,
pdb_hierarchy,
params,
cdl,
rdl,
correct_hydrogens,
states_collector,
fix_rotamer_outliers,
allow_allowed_rotamers,
log,
ncs_restraints_group_list = [],
mon_lib_srv = None):
o = mmtbx.refinement.geometry_minimization.run2(
restraints_manager = restraints_manager,
riding_h_manager = riding_h_manager,
pdb_hierarchy = pdb_hierarchy,
ncs_restraints_group_list = ncs_restraints_group_list,
max_number_of_iterations = params.max_iterations,
number_of_macro_cycles = params.macro_cycles,
selection = selection,
correct_special_position_tolerance = params.correct_special_position_tolerance,
bond = params.move.bond,
nonbonded = params.move.nonbonded,
angle = params.move.angle,
dihedral = params.move.dihedral,
chirality = params.move.chirality,
planarity = params.move.planarity,
parallelity = params.move.parallelity,
rmsd_bonds_termination_cutoff = params.rmsd_bonds_termination_cutoff,
rmsd_angles_termination_cutoff = params.rmsd_angles_termination_cutoff,
alternate_nonbonded_off_on = params.alternate_nonbonded_off_on,
cdl = cdl,
rdl = rdl,
states_collector = states_collector,
correct_hydrogens = correct_hydrogens,
fix_rotamer_outliers = fix_rotamer_outliers,
allow_allowed_rotamers = allow_allowed_rotamers,
log = log,
mon_lib_srv = mon_lib_srv)
def run_minimization_amber(
selection,
restraints_manager,
pdb_hierarchy,
params,
log,
prmtop,
ambcrd,
):
import amber_adaptbx.amber_geometry_minimization
o = amber_adaptbx.amber_geometry_minimization.run(
restraints_manager = restraints_manager,
pdb_hierarchy = pdb_hierarchy,
max_number_of_iterations = params.max_iterations,
number_of_macro_cycles = params.macro_cycles,
selection = selection,
bond = params.move.bond,
nonbonded = params.move.nonbonded,
angle = params.move.angle,
dihedral = params.move.dihedral,
chirality = params.move.chirality,
planarity = params.move.planarity,
parallelity = params.move.parallelity,
grms_termination_cutoff = params.grms_termination_cutoff,
alternate_nonbonded_off_on = params.alternate_nonbonded_off_on,
log = log,
prmtop = prmtop,
ambcrd = ambcrd,
)
class run(object):
_pdb_suffix = "minimized"
def __init__(self, args, log, use_directory_prefix=True):
# You are not supposed to put here (in __init__) any time-consuming stuff,
# otherwise self.total_time would be unaccurate. It's not clear
# why it is important.
self.model = None
self.log = log
self.params = None
self.inputs = None
self.args = args
self.selection = None
self.restrain_selection = None
self.time_strings = []
self.total_time = 0
self.pdb_file_names = []
self.use_directory_prefix = use_directory_prefix
self.sites_cart_start = None
self.states_collector = None
self.__execute()
def __execute(self):
#
self.caller(self.initialize, "Initialization, inputs")
self.caller(self.process_inputs, "Processing inputs")
self.caller(self.atom_selection, "Atom selection")
self.caller(self.get_restraints, "Geometry Restraints")
self.caller(self.setup_riding_h, "Setup riding H")
self.caller(self.minimization, "Minimization")
self.caller(self.write_pdb_file, "Write PDB file")
self.caller(self.write_geo_file, "Write GEO file")
self.caller(self.show_model_statistics, "Model statistics")
#
self.show_times()
def master_params(self):
return master_params()
def caller(self, func, prefix):
timer = user_plus_sys_time()
func(prefix = prefix)
t = timer.elapsed()
self.total_time += t
self.time_strings.append(" %s: %s"%(prefix, str("%8.3f"%t).strip()))
def show_times(self):
broadcast(m="Detailed timing", log = self.log)
max_len = 0
for ts in self.time_strings:
lts = len(ts)
if(lts > max_len): max_len = lts
fmt = " %-"+str(lts)+"s"
for ts in self.time_strings:
sts = ts.split()
l = " ".join(sts[:len(sts)-1])
print(fmt%l, sts[len(sts)-1], file=self.log)
print(" Sum of individual times: %s"%\
str("%8.3f"%self.total_time).strip(), file=self.log)
def format_usage_message(self):
format_usage_message(log=self.log)
def setup_output_file_names(self):
# for pdb
ofn = self.params.output_file_name_prefix
directory = self.params.directory
base_name = ""
if self.use_directory_prefix and directory is not None:
base_name = directory
suffix = "_" + self._pdb_suffix + ".pdb"
if self.params.output_file_name_prefix is None:
in_fn = os.path.basename(self.pdb_file_names[0])
ind = max(0, in_fn.rfind("."))
ofn = in_fn + suffix
if ind > 0:
ofn = in_fn[:ind]+suffix
else:
ofn = self.params.output_file_name_prefix+".pdb"
self.result_model_fname = os.path.join(base_name, ofn)
self.result_states_fname = self.result_model_fname[:].replace(".pdb","_all_states.pdb")
self.final_geo_fname = self.result_model_fname[:].replace(".pdb",".geo")
def initialize(self, prefix):
if (self.log is None) : self.log = sys.stdout
if(len(self.args)==0):
self.format_usage_message()
parsed = self.master_params()
self.inputs = mmtbx.utils.process_command_line_args(args = self.args,
master_params = parsed)
self.params = self.inputs.params.extract()
if(self.params.silent): self.log = StringIO()
broadcast(m=prefix, log = self.log)
self.inputs.params.show(prefix=" ", out=self.log)
if(len(self.args)==0): sys.exit(0)
def process_inputs(self, prefix):
broadcast(m=prefix, log = self.log)
self.pdb_file_names = list(self.inputs.pdb_file_names)
if(self.params.file_name is not None):
self.pdb_file_names.append(self.params.file_name)
#=================================================
cs = self.inputs.crystal_symmetry
is_non_crystallographic_unit_cell = False
import iotbx.pdb
pdb_combined = combine_unique_pdb_files(file_names = self.pdb_file_names)
pdb_inp = iotbx.pdb.input(lines=pdb_combined.raw_records, source_info=None)
if(cs is None):
cs=pdb_inp.crystal_symmetry()
if(cs is None):
is_non_crystallographic_unit_cell = True
box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center(
sites_cart = pdb_inp.atoms().extract_xyz(),
buffer_layer = 10)
cs = box.crystal_symmetry()
cif_objects = list(self.inputs.cif_objects)
if (len(self.params.restraints) > 0):
import iotbx.cif
for file_name in self.params.restraints :
cif_object = iotbx.cif.reader(file_path=file_name, strict=False).model()
cif_objects.append((file_name, cif_object))
if (self.params.restraints_directory is not None):
restraint_files = os.listdir(self.params.restraints_directory)
for file_name in restraint_files :
if (file_name.endswith(".cif")):
full_path = os.path.join(self.params.restraints_directory, file_name)
cif_object = iotbx.cif.reader(file_path=full_path,
strict=False).model()
cif_objects.append((full_path, cif_object))
self.model = mmtbx.model.manager(
model_input = pdb_inp,
crystal_symmetry = cs,
restraint_objects = cif_objects,
pdb_interpretation_params = self.params,
stop_for_unknowns = self.params.stop_for_unknowns,
build_grm = True,
log = self.log)
self.ncs_obj = self.model.get_ncs_obj()
self.output_crystal_symmetry = not is_non_crystallographic_unit_cell
self.sites_cart_start = self.model.get_xray_structure().sites_cart().deep_copy()
if(self.params.show_states):
self.states_collector = mmtbx.utils.states(
xray_structure = self.model.get_xray_structure(),
pdb_hierarchy = self.model.get_hierarchy())
self.setup_output_file_names()
def atom_selection(self, prefix):
broadcast(m=prefix, log = self.log)
self.selection = self.model.selection(string = self.params.selection)
print(" selected %s atoms out of total %s"%(
str(self.selection.count(True)),str(self.selection.size())), file=self.log)
def get_restraints(self, prefix):
broadcast(m=prefix, log = self.log)
self.model.get_restraints_manager()
def setup_riding_h(self, prefix):
if not self.params.minimization.riding_h: return
broadcast(m=prefix, log = self.log)
self.model.setup_riding_h_manager(idealize=True)
def minimization(self, prefix): # XXX USE alternate_nonbonded_off_on etc
broadcast(m=prefix, log = self.log)
use_amber = False
if self.ncs_obj is not None:
print("Using NCS constraints:", file=self.log)
self.ncs_obj.show(format='phil', log=self.log)
ncs_restraints_group_list = []
if self.ncs_obj is not None:
ncs_restraints_group_list = self.ncs_obj.get_ncs_restraints_group_list()
run_minimization(
selection = self.selection,
restraints_manager = self.model.get_restraints_manager(),
riding_h_manager = self.model.get_riding_h_manager(),
params = self.params.minimization,
pdb_hierarchy = self.model.get_hierarchy(),
cdl = self.params.pdb_interpretation.restraints_library.cdl,
rdl = self.params.pdb_interpretation.restraints_library.rdl,
correct_hydrogens = self.params.pdb_interpretation.correct_hydrogens,
fix_rotamer_outliers = self.params.fix_rotamer_outliers,
allow_allowed_rotamers = self.params.allow_allowed_rotamers,
states_collector = self.states_collector,
log = self.log,
ncs_restraints_group_list = ncs_restraints_group_list,
mon_lib_srv = self.model.get_mon_lib_srv())
self.model.set_sites_cart_from_hierarchy()
def write_pdb_file(self, prefix):
broadcast(m=prefix, log = self.log)
# self.pdb_hierarchy.adopt_xray_structure(self.xray_structure)
print(" output file name:", self.result_model_fname, file=self.log)
print(self.min_max_mean_shift(), file=self.log)
print(self.min_max_mean_shift(), file=self.log)
r = self.model.model_as_pdb(output_cs=self.output_crystal_symmetry)
f = open(self.result_model_fname, 'w')
f.write(r)
f.close()
if(self.states_collector):
self.states_collector.write(
file_name=self.result_states_fname)
def min_max_mean_shift(self):
return "min,max,mean shift from start: %6.3f %6.3f %6.3f"%flex.sqrt((
self.sites_cart_start - self.model.get_xray_structure().sites_cart()).dot()
).min_max_mean().as_tuple()
def write_geo_file(self, prefix):
if self.params.write_geo_file:
broadcast(m=prefix, log = self.log)
# no output of NCS stuff here
restr_txt = self.model.restraints_as_geo()
f = open(self.final_geo_fname, "w")
f.write("# Geometry restraints after refinement\n")
f.write(restr_txt)
f.close()
def show_model_statistics(self, prefix):
if self.params.write_geo_file:
broadcast(m=prefix, log = self.log)
s = self.model.geometry_statistics()
s.show(log = self.log, uppercase=False)
class launcher(runtime_utils.target_with_save_result):
def run(self):
os.mkdir(self.output_dir)
os.chdir(self.output_dir)
filename = run(args=self.args, log=sys.stdout,
use_directory_prefix=False).result_model_fname
return os.path.join(self.output_dir, filename)
def validate_params(params):
if (params.file_name is None):
raise Sorry("Please specify a model file to minimize.")
if (params.restraints_directory is not None):
if (not os.path.isdir(params.restraints_directory)):
raise | |
# @endcode
class Sum (Operation2) :
"""Summation operation
>>> op = Sum ( math.sin , math.cos )
"""
def __init__ ( self , a , b ) :
super(Sum,self).__init__ ( a , b , operator.add , '+' )
# =============================================================================
## @class Sub
# Subtraction operation
# @code
# op = Sub ( math.sin , math.cos )
# @endcode
class Sub (Operation2) :
"""Subtraction operation
>>> op = Sub ( math.sin , math.cos )
"""
def __init__ ( self , a , b ) :
super(Sub,self).__init__ ( a , b , operator.sub , '-' )
# =============================================================================
## @class Mul
# Multiplication operation
# @code
# op = Mul ( math.sin , math.cos )
# @endcode
class Mul (Operation2) :
"""Multiplication operation
>>> op = Mul ( math.sin , math.cos )
"""
def __init__ ( self , a , b ) :
super(Mul,self).__init__ ( a , b , operator.mul , '*' )
# =============================================================================
## @class Div
# Division operation
# @code
# op = Div ( math.sin , math.cos )
# @endcode
class Div (Operation2) :
"""Division operation
>>> op = Div ( math.sin , math.cos )
"""
def __init__ ( self , a , b ) :
super(Div,self).__init__ ( a , b , operator.truediv , '/')
# =============================================================================
## @class Pow
# Pow-operation
# @code
# op = Pow ( lambda x : x , lambda x : x**2 )
# @endcode
class Pow (Operation2) :
"""Pow-operation
>>> op = Pow ( lambda x : x , lambda x : x**2 )
"""
def __init__ ( self , a , b ) :
super(Pow,self).__init__ ( a , b , operator.pow , '**')
# =============================================================================
## @class Square
# square-operation
class Square(Pow) :
"""square-operation
"""
def __init__ ( self , a ) :
super(Square,self).__init__ ( a , 2 )
# =============================================================================
## @class Cube
# cube-operation
class Cube(Pow) :
"""Cube-operation
"""
def __init__ ( self , a ) :
super(Cube,self).__init__ ( a , 3 )
# =============================================================================
## @class Mod
# modulo operation
# @code
# op = Mod ( math.sin , math.cos )
# @endcode
class Mod (Operation2) :
"""Modulo operation
>>> op = Mod ( math.sin , math.cos )
"""
def __init__ ( self , a , b ) :
super(Mod ,self).__init__ ( a , b , operator.mod , '%')
# =============================================================================
## @class Max
# Max-operation
# @code
# op = Max ( math.sin , math.cos )
# @endcode
class Max (Operation2) :
"""Max-operation
>>> op = Max ( math.sin , math.cos )
"""
def __init__ ( self , a , b ) :
super(Max,self).__init__ ( a , b , _Fmax() , ',' , 'max')
# =============================================================================
## @class Min
# Min-operation
# @code
# op = Min ( math.sin , math.cos )
# @endcode
class Min (Operation2) :
"""Min-operation
>>> op = Min ( math.sin , math.cos )
"""
def __init__ ( self , a , b ) :
super(Min,self).__init__ ( a , b , _Fmin() , '' , 'min')
# =============================================================================
## @class Or_l
# OR (logical) - operation
# @code
# op = LOr ( fun1 , fun2 )
# @endcode
class Or_l (Operation2) :
"""OR (logical) -operation
>>> op = Or_l ( fun1 , fun2 )
"""
def __init__ ( self , a , b ) :
super(Or_l,self).__init__ ( a , b , _For () , ' or ' )
# =============================================================================
## @class And_l
# AND (logical) -operation
# @code
# op = And_l ( fun1 , fun2 )
# @endcode
class And_l (Operation2) :
"""AND (logical) -operation
>>> op = And_l ( fun1 , fun2 )
"""
def __init__ ( self , a , b ) :
super(And_l,self).__init__ ( a , b , _Fand() , ' and ' )
# =============================================================================
## @class Or_b
# OR (bitwise) - operation
# @code
# op = Or_b ( fun1 , fun2 )
# @endcode
class Or_b (Operation2) :
"""OR (bitwise) -operation
>>> op = Or_b ( fun1 , fun2 )
"""
def __init__ ( self , a , b ) :
super(Or_b,self).__init__ ( a , b , operator.or_ , '|' )
# =============================================================================
## @class And_b
# AND (bitwise) -operation
# @code
# op = And_b ( fun1 , fun2 )
# @endcode
class And_b (Operation2) :
"""AND (bitwise) -operation
>>> op = And_b ( fun1 , fun2 )
"""
def __init__ ( self , a , b ) :
super(And_b,self).__init__ ( a , b , operator.and_ , '&' )
# =============================================================================
## @class Xor_b
# XOR (bitwise) - operation
# @code
# op = Xor_b ( fun1 , fun2 )
# @endcode
class Xor_b (Operation2) :
"""XOR (bitwise) -operation
>>> op = Xor_b ( fun1 , fun2 )
"""
def __init__ ( self , a , b ) :
super(Xor_b,self).__init__ ( a , b , operator.xor , '^' )
# =============================================================================
## @class Abs
# absolute value
class Abs(Compose) :
"""absolute value"""
def __init__ ( self , func ) :
super(Abs,self).__init__ ( abs , func , 'exp')
# =============================================================================
## @class Exp
# simple 'exponent'
class Exp(Compose) :
"""Exponent for the function"""
def __init__ ( self , func ) :
super(Exp,self).__init__ ( math.exp , func , 'exp')
# =============================================================================
## @class Log
# simple 'log'
class Log(Compose) :
"""Log for the function"""
def __init__ ( self , func ) :
super(Log,self).__init__ ( math.log , func , 'log')
# =============================================================================
## @class Log10
# simple 'log10'
class Log10(Compose) :
"""Log10 for the function"""
def __init__ ( self , func ) :
super(Log10,self).__init__ ( math.log10 , func , 'log10' )
# =============================================================================
## @class Sin
# simple 'sin'
class Sin(Compose) :
"""Sin for the function"""
def __init__ ( self , func ) :
super(Sin,self).__init__ ( math.sin , func , 'sin')
# =============================================================================
## @class Cos
# simple 'cos'
class Cos(Compose) :
"""Cos for the function"""
def __init__ ( self , func ) :
super(Cos,self).__init__ ( math.cos , func , 'cos' )
# =============================================================================
## @class Tan
# simple 'tan'
class Tan(Compose) :
"""Tan for the function"""
def __init__ ( self , func ) :
super(Tan,self).__init__ ( math.tan , func , 'tan' )
# =============================================================================
## @class Sinh
# simple 'sinh'
class Sinh(Compose) :
"""Sinh for the function"""
def __init__ ( self , func ) :
super(Sinh,self).__init__ ( math.sinh , func , 'sinh' )
# =============================================================================
## @class Cosh
# simple 'cosh'
class Cosh(Compose) :
"""Cos for the function"""
def __init__ ( self , func ) :
super(Cosh,self).__init__ ( math.cosh , func , 'cosh' )
# =============================================================================
## @class Tanh
# simple 'tan'
class Tanh(Compose) :
"""Tanh for the function"""
def __init__ ( self , func ) :
super(Tanh,self).__init__ ( math.tanh , func , 'tanh' )
# =============================================================================
## @class ASin
# simple 'asin'
class ASin(Compose) :
"""ASin for the function"""
def __init__ ( self , func ) :
super(ASin,self).__init__ ( math.asin , func , 'asinh' )
# =============================================================================
## @class ACos
# simple 'acos'
class ACos(Compose) :
"""ACos for the function"""
def __init__ ( self , func ) :
super(ACos,self).__init__ ( math.acos , func , 'acos' )
# =============================================================================
## @class ATan
# simple 'atan'
class ATan(Compose) :
"""ATan for the function"""
def __init__ ( self , func ) :
super(ATan,self).__init__ ( math.atan , func , 'atan' )
# =============================================================================
## @class ASinh
# simple 'asinh'
class ASinh(Compose) :
"""ASinh for the function"""
def __init__ ( self , func ) :
super(ASinh,self).__init__ ( math.asinh , func , 'asinh' )
# =============================================================================
## @class ACosh
# simple 'acosh'
class ACosh(Compose) :
"""ACosh for the function"""
def __init__ ( self , func ) :
super(ACosh,self).__init__ ( math.acosh , func , 'acosh' )
# =============================================================================
## @class ATanh
# simple 'atanh'
class ATanh(Compose) :
"""ATanh for the function"""
def __init__ ( self , func ) :
super(ATanh,self).__init__ ( math.atanh , func , 'atanh' )
# =============================================================================
## @class Erf
# simple 'erf'
class Erf(Compose) :
"""Erf for the function"""
def __init__ ( self , func ) :
super(Erf,self).__init__ ( math.erf , func , 'erf' )
# =============================================================================
## @class Erfc
# simple 'erfc'
class Erfc(Compose) :
"""Erfc for the function"""
def __init__ ( self , func ) :
super(Erfc,self).__init__ ( math.erfc , func , 'erfc' )
# =============================================================================
## @class Gamma
# simple 'Gamma'
class Gamma(Compose) :
"""Gamma for the function"""
def __init__ ( self , func ) :
super(Gamma,self).__init__ ( math.gamma , func , 'G' )
# =============================================================================
## @class LogGamma
# simple 'LogGamma'
class LogGamma(Compose) :
"""LogGamma for the function"""
def | |
nest1 and schedule1 with a smaller iteration space size
nest1 = Nest(shape=(16, 10))
i1, j1 = nest1.get_indices()
@nest1.iteration_logic
def _():
C[i1, j1] *= B[i1, j1]
schedule1 = nest1.create_schedule()
# Create a fused schedule: the smaller iteration space (nest1) should
# be automatically end-padded with no-ops
schedule = fuse(schedule0, schedule1)
f, i, j = schedule.get_indices()
schedule.reorder(i, j, f)
# Emitted fused loop should look like:
# for i in range(0, 16):
# for j in range(0, 10):
# for f in range(2):
# if f == 0:
# C[i, j] += A[i, j]
# if f == 1:
# C[i, j] *= B[i, j]
# for j in range(10, 16):
# for f in range(2):
# if f == 0:
# C[i, j] += A[i, j]
A_test = np.random.random(A.shape).astype(np.float32)
B_test = np.random.random(B.shape).astype(np.float32)
C_test = np.random.random(C.shape).astype(np.float32)
C_ref = C_test + A_test # nest0
C_ref[:, :B.shape[1]] = C_ref[:, :B.shape[1]] * B_test # nest1
correctness_check_values = {
"pre": [A_test, B_test, C_test],
"post": [A_test, B_test, C_ref]
}
self._verify_schedule(schedule, (A, B, C), "test_unequal_iteration_space_fusing_1", correctness_check_values)
def test_unequal_iteration_space_fusing_2(self) -> None:
from accera import fuse, Nest
A = Array(role=Array.Role.INPUT, shape=(16, 10))
B = Array(role=Array.Role.INPUT, shape=(16, 16))
C = Array(role=Array.Role.INPUT_OUTPUT, shape=(16, 16))
# Create nest0 and schedule
nest0 = Nest(shape=(16, 10))
i0, j0 = nest0.get_indices()
@nest0.iteration_logic
def _():
C[i0, j0] += A[i0, j0]
schedule0 = nest0.create_schedule()
# Create nest1 and schedule1 with a larger iteration space size
nest1 = Nest(shape=(16, 16))
i1, j1 = nest1.get_indices()
@nest1.iteration_logic
def _():
C[i1, j1] *= B[i1, j1]
schedule1 = nest1.create_schedule()
# Create a fused schedule: the smaller iteration space (nest0) should
# be automatically end-padded with no-ops
schedule = fuse(schedule0, schedule1)
f, i, j = schedule.get_indices()
schedule.reorder(i, j, f)
# Emitted fused loop should look like:
# for i in range(0, 16):
# for j in range(0, 10):
# for f in range(2):
# if f == 0:
# C[i, j] += A[i, j]
# if f == 1:
# C[i, j] *= B[i, j]
# for j in range(10, 16):
# for f in range(2):
# if f == 1:
# C[i, j] *= B[i, j]
A_test = np.random.random(A.shape).astype(np.float32)
B_test = np.random.random(B.shape).astype(np.float32)
C_test = np.random.random(C.shape).astype(np.float32)
C_ref = np.copy(C_test)
C_ref[:, :A.shape[1]] = C_test[:, :A.shape[1]] + A_test # nest0
C_ref *= B_test # nest1
correctness_check_values = {
"pre": [A_test, B_test, C_test],
"post": [A_test, B_test, C_ref]
}
self._verify_schedule(schedule, (A, B, C), "test_unequal_iteration_space_fusing_2", correctness_check_values)
def test_unequal_iteration_space_fusing_3(self) -> None:
from accera import fuse, Nest
A = Array(role=Array.Role.INPUT, shape=(16, 16))
B = Array(role=Array.Role.INPUT, shape=(16, 10))
C = Array(role=Array.Role.INPUT_OUTPUT, shape=(16, 16))
# Create nest0 and schedule
nest0 = Nest(shape=(16, 16))
i0, j0 = nest0.get_indices()
@nest0.iteration_logic
def _():
C[i0, j0] += A[i0, j0]
schedule0 = nest0.create_schedule()
# Create nest1 and schedule1 with a smaller iteration space size
nest1 = Nest(shape=(16, 10))
i1, j1 = nest1.get_indices()
@nest1.iteration_logic
def _():
C[i1, j1] *= B[i1, j1]
schedule1 = nest1.create_schedule()
# Create a fused schedule: the smaller iteration space (nest1) should
# be automatically end-padded with no-ops
schedule = fuse(schedule0, schedule1)
f, i, j = schedule.get_indices()
# computing the output block-by-block:
# first computing C[0:4, 0:4] += A[0:4, 0:4]
# then computing C[0:4, 0:4] *= B[0:4, 0:4]
ii, jj = schedule.tile({
i: 4,
j: 4
})
schedule.reorder(i, j, f, ii, jj)
# Emitted fused loop should look like:
# for i in range(0, 16, 4):
# # run both kernels in the smaller iteration spaces
# # (tiled block)
# for j in range(0, 8, 4):
# for f in range(2):
# if f == 0:
# for ii in range(0, 4):
# for jj in range(0, 4):
# C[i+ii, j+jj] += A[i+ii, j+jj]
# if f == 1:
# for ii in range(0, 4):
# for jj in range(0, 4):
# C[i+ii, j+jj] *= B[i+ii, j+jj]
#
# # run both kernels in the smaller iteration space
# # (boundary block for split)
# for j in range(8, 10): # range < split size
# for f in range(2):
# if f == 0:
# for ii in range(0, 4):
# C[i+ii, j] += A[i+ii, j]
# if f == 1:
# for ii in range(0, 4):
# C[i+ii, j] *= B[i+ii, j]
#
# # run kernel with the larger iteration space
# # (boundary block for split)
# for j in range(10, 16): # range < split size
# for f in range(2):
# if f == 0:
# for ii in range(0, 4):
# C[i+ii, j] += A[i+ii, j]
A_test = np.random.random(A.shape).astype(np.float32)
B_test = np.random.random(B.shape).astype(np.float32)
C_test = np.random.random(C.shape).astype(np.float32)
C_ref = C_test + A_test # nest0
C_ref[:, :B.shape[1]] = C_ref[:, :B.shape[1]] * B_test # nest1
correctness_check_values = {
"pre": [A_test, B_test, C_test],
"post": [A_test, B_test, C_ref]
}
self._verify_schedule(schedule, (A, B, C), "test_unequal_iteration_space_fusing_3", correctness_check_values)
def test_concat_fusing_1(self) -> None:
from accera import fuse, Nest
A = Array(role=Array.Role.INPUT_OUTPUT, shape=(3, ))
B = Array(role=Array.Role.INPUT_OUTPUT, shape=(7, ))
n1 = Nest(A.shape)
n2 = Nest(B.shape)
n1_i = n1.get_indices()
@n1.iteration_logic
def _():
A[n1_i] /= A[n1_i]
n2_i = n2.get_indices()
@n2.iteration_logic
def _():
B[n2_i] *= B[n2_i]
fused = fuse([n.create_schedule() for n in [n1, n2]], partial=0)
# Emitted fused loop should look like:
# for f in range(3):
# if f == 0:
# for i in range(3):
# A[i] /= A[i]
# if f == 1:
# for i in range(7):
# B[i] *= B[i]
A_test = np.random.random(A.shape).astype(np.float32)
B_test = np.random.random(B.shape).astype(np.float32)
A_ref = A_test / A_test
B_ref = B_test * B_test
correctness_check_values = {
"pre": [A_test, B_test],
"post": [A_ref, B_ref]
}
self._verify_schedule(fused, (A, B), "test_concat_fusing_1", correctness_check_values)
@expectedFailure(FailedReason.BUG, "Concat fusing is broken")
def test_concat_fusing_2(self) -> None:
from accera import fuse, Nest
A = Array(role=Array.Role.INPUT_OUTPUT, shape=(11, ))
B = Array(role=Array.Role.INPUT_OUTPUT, shape=(7, ))
C = Array(role=Array.Role.INPUT_OUTPUT, shape=(5, ))
n1 = Nest(A.shape)
n2 = Nest(B.shape)
n3 = Nest(C.shape)
n1_i = n1.get_indices()
@n1.iteration_logic
def _():
A[n1_i] += A[n1_i]
n2_i = n2.get_indices()
@n2.iteration_logic
def _():
B[n2_i] *= B[n2_i]
n3_i = n3.get_indices()
@n3.iteration_logic
def _():
C[n3_i] /= C[n3_i]
fused = fuse([n.create_schedule() for n in [n1, n2, n3]], partial=0)
# Emitted fused loop should look like:
# for f in range(3):
# if f == 0:
# for i in range(11):
# A[i}] += A[i}]
# if f == 1:
# for i in range(7):
# B[i}] *= B[i}]
# if f == 2:
# for i in range(5):
# C[i}] /= C[i}]
A_test = np.random.random(A.shape).astype(np.float32)
B_test = np.random.random(B.shape).astype(np.float32)
C_test = np.random.random(C.shape).astype(np.float32)
A_ref = A_test + A_test
B_ref = B_test * B_test
C_ref = C_test / C_test
correctness_check_values = {
"pre": [A_test, B_test, C_test],
"post": [A_ref, B_ref, C_ref]
}
self._verify_schedule(fused, (A, B, C), "test_concat_fusing_2", correctness_check_values)
def test_concat_fusing_3(self) -> None:
from accera import fuse, Nest
A = Array(role=Array.Role.INPUT_OUTPUT, shape=(3, 16))
B = Array(role=Array.Role.INPUT_OUTPUT, shape=(7, 16))
n1 = Nest(A.shape)
n2 = Nest(B.shape)
n1_i, n1_j = n1.get_indices()
@n1.iteration_logic
def _():
A[n1_i, n1_j] /= A[n1_i, n1_j]
n2_i, n2_j = n2.get_indices()
@n2.iteration_logic
def _():
B[n2_i, n2_j] *= B[n2_i, n2_j]
fused = fuse([n.create_schedule() for n in [n1, n2]], partial=0)
# Emitted fused loop should look like:
# for f in range(3):
# if f == 0:
# for i in range(3):
# for j in range(16):
# A[i,j] /= A[i,j]
# if f == 1:
# for i in range(7):
# for j in range(16):
# B[i,j] *= B[i,j]
A_test = np.random.random(A.shape).astype(np.float32)
B_test = np.random.random(B.shape).astype(np.float32)
A_ref = A_test / A_test
B_ref = B_test * B_test
correctness_check_values = {
"pre": [A_test, B_test],
"post": [A_ref, B_ref]
}
self._verify_schedule(fused, (A, B), "test_concat_fusing_3", correctness_check_values)
@expectedFailure(FailedReason.BUG, "Concat fusing is broken")
def test_concat_fusing_4(self) -> None:
from accera import fuse, Nest
A = Array(role=Array.Role.INPUT_OUTPUT, shape=(11, 16))
B = Array(role=Array.Role.INPUT_OUTPUT, shape=(7, 16))
C = Array(role=Array.Role.INPUT_OUTPUT, shape=(5, 16))
n1 = Nest(A.shape)
n2 = Nest(B.shape)
n3 = Nest(C.shape)
n1_i, n1_j = n1.get_indices()
@n1.iteration_logic
def _():
A[n1_i, n1_j] += A[n1_i, n1_j]
n2_i, n2_j = n2.get_indices()
@n2.iteration_logic
def _():
B[n2_i, n2_j] *= B[n2_i, n2_j]
n3_i, n3_j = n3.get_indices()
@n3.iteration_logic
def _():
C[n3_i, n3_j] /= C[n3_i, n3_j]
fused = | |
m, None)
self._scan_code(m, co, co_ast)
m.code = co
if self.replace_paths:
m.code = self._replace_paths_in_code(m.code)
return m
#FIXME: For safety, the "source_module" parameter should default to the
#root node of the current graph if unpassed. This parameter currently
#defaults to None, thus disconnected modules imported in this manner (e.g.,
#hidden imports imported by depend.analysis.initialize_modgraph()).
def import_hook(
self,
target_module_partname,
source_module=None,
target_attr_names=None,
level=DEFAULT_IMPORT_LEVEL,
edge_attr=None,
):
"""
Import the module with the passed name, all parent packages of this
module, _and_ all submodules and attributes in this module with the
passed names from the previously imported caller module signified by
the passed graph node.
Unlike most import methods (e.g., `_safe_import_hook()`), this method
is designed to be publicly called by both external and internal
callers and hence is public.
Parameters
----------
target_module_partname : str
Partially-qualified name of the target module to be imported. See
`_safe_import_hook()` for further details.
source_module : Node
Graph node for the previously imported **source module** (i.e.,
module containing the `import` statement triggering the call to
this method) _or_ `None` if this module is to be imported in a
"disconnected" manner. **Passing `None` is _not_ recommended.**
Doing so produces a disconnected graph in which the graph node
created for the module to be imported will be disconnected and
hence unreachable from all other nodes -- which frequently causes
subtle issues in external callers (namely PyInstaller, which
silently ignores unreachable nodes).
target_attr_names : list
List of the unqualified names of all submodules and attributes to
be imported from the module to be imported if this is a "from"-
style import (e.g., `[encode_base64, encode_noop]` for the import
`from email.encoders import encode_base64, encode_noop`) _or_
`None` otherwise.
level : int
Whether to perform an absolute or relative import. See
`_safe_import_hook()` for further details.
Returns
----------
list
List of the graph nodes created for all modules explicitly imported
by this call, including the passed module and all submodules listed
in `target_attr_names` _but_ excluding all parent packages
implicitly imported by this call. If `target_attr_names` is `None`
or the empty list, this is guaranteed to be a list of one element:
the graph node created for the passed module.
Raises
----------
ImportError
If the target module to be imported is unimportable.
"""
self.msg(3, "_import_hook", target_module_partname, source_module, source_module, level)
source_package = self._determine_parent(source_module)
target_package, target_module_partname = self._find_head_package(
source_package, target_module_partname, level)
target_module = self._load_tail(target_package, target_module_partname)
target_modules = [target_module]
# If this is a "from"-style import *AND* this target module is
# actually a package, import all submodules of this package specified
# by the "import" half of this import (e.g., the submodules "bar" and
# "car" of the target package "foo" in "from foo import bar, car").
#
# If this target module is a non-package, it could still contain
# importable submodules (e.g., the non-package `os` module containing
# the `os.path` submodule). In this case, these submodules are already
# imported by this target module's pure-Python code. Since our import
# scanner already detects such imports, these submodules need *NOT* be
# reimported here.
if target_attr_names and isinstance(target_module, Package):
for target_submodule in self._import_importable_package_submodules(
target_module, target_attr_names):
if target_submodule not in target_modules:
target_modules.append(target_submodule)
# Add an edge from this source module to each target module.
for target_module in target_modules:
self._updateReference(
source_module, target_module, edge_data=edge_attr)
return target_modules
def _determine_parent(self, caller):
"""
Determine the package containing a node.
"""
self.msgin(4, "determine_parent", caller)
parent = None
if caller:
pname = caller.identifier
if isinstance(caller, Package):
parent = caller
elif '.' in pname:
pname = pname[:pname.rfind('.')]
parent = self.findNode(pname)
elif caller.packagepath:
# XXX: I have no idea why this line
# is necessary.
parent = self.findNode(pname)
self.msgout(4, "determine_parent ->", parent)
return parent
def _find_head_package(
self,
source_package,
target_module_partname,
level=DEFAULT_IMPORT_LEVEL):
"""
Import the target package providing the target module with the passed
name to be subsequently imported from the previously imported source
package corresponding to the passed graph node.
Parameters
----------
source_package : Package
Graph node for the previously imported **source package** (i.e.,
package containing the module containing the `import` statement
triggering the call to this method) _or_ `None` if this module is
to be imported in a "disconnected" manner. **Passing `None` is
_not_ recommended.** See the `_import_hook()` method for further
details.
target_module_partname : str
Partially-qualified name of the target module to be imported. See
`_safe_import_hook()` for further details.
level : int
Whether to perform absolute or relative imports. See the
`_safe_import_hook()` method for further details.
Returns
----------
(target_package, target_module_tailname)
2-tuple describing the imported target package, where:
* `target_package` is the graph node created for this package.
* `target_module_tailname` is the unqualified name of the target
module to be subsequently imported (e.g., `text` when passed a
`target_module_partname` of `email.mime.text`).
Raises
----------
ImportError
If the package to be imported is unimportable.
"""
self.msgin(4, "find_head_package", source_package, target_module_partname, level)
#FIXME: Rename all local variable names to something sensible. No,
#"p_fqdn" is not a sensible name.
# If this target module is a submodule...
if '.' in target_module_partname:
target_module_headname, target_module_tailname = (
target_module_partname.split('.', 1))
# Else, this target module is a top-level module.
else:
target_module_headname = target_module_partname
target_module_tailname = ''
# If attempting both absolute and relative imports...
if level == ABSOLUTE_OR_RELATIVE_IMPORT_LEVEL:
if source_package:
target_package_name = source_package.identifier + '.' + target_module_headname
else:
target_package_name = target_module_headname
# Else if attempting only absolute imports...
elif level == ABSOLUTE_IMPORT_LEVEL:
target_package_name = target_module_headname
# Absolute import, ignore the parent
source_package = None
# Else if attempting only relative imports...
else:
if source_package is None:
self.msg(2, "Relative import outside of package")
raise InvalidRelativeImportError(
"Relative import outside of package (name=%r, parent=%r, level=%r)" % (
target_module_partname, source_package, level))
for i in range(level - 1):
if '.' not in source_package.identifier:
self.msg(2, "Relative import outside of package")
raise InvalidRelativeImportError(
"Relative import outside of package (name=%r, parent=%r, level=%r)" % (
target_module_partname, source_package, level))
p_fqdn = source_package.identifier.rsplit('.', 1)[0]
new_parent = self.findNode(p_fqdn)
if new_parent is None:
#FIXME: Repetition detected. Exterminate. Exterminate.
self.msg(2, "Relative import outside of package")
raise InvalidRelativeImportError(
"Relative import outside of package (name=%r, parent=%r, level=%r)" % (
target_module_partname, source_package, level))
assert new_parent is not source_package, (
new_parent, source_package)
source_package = new_parent
if target_module_headname:
target_package_name = (
source_package.identifier + '.' + target_module_headname)
else:
target_package_name = source_package.identifier
# Graph node of this target package.
target_package = self._safe_import_module(
target_module_headname, target_package_name, source_package)
#FIXME: Why exactly is this necessary again? This doesn't quite seem
#right but maybe it is. Shouldn't absolute imports only be performed if
#the passed "level" is either "ABSOLUTE_IMPORT_LEVEL" or
#"ABSOLUTE_OR_RELATIVE_IMPORT_LEVEL" -- or, more succinctly:
#
# if level < 1:
# If this target package is *NOT* importable and a source package was
# passed, attempt to import this target package as an absolute import.
if target_package is None and source_package is not None:
target_package_name = target_module_headname
source_package = None
# Graph node for the target package, again.
target_package = self._safe_import_module(
target_module_headname, target_package_name, source_package)
# If this target package is importable, return this package.
if target_package is not None:
self.msgout(4, "find_head_package ->", (target_package, target_module_tailname))
return target_package, target_module_tailname
# Else, raise an exception.
self.msgout(4, "raise ImportError: No module named", target_package_name)
raise ImportError("No module named " + target_package_name)
def _load_tail(self, package, submodule_name):
"""
Import the submodule with the passed name and all parent packages of
this module from the previously imported parent package corresponding
to the passed graph node.
Parameters
----------
package : Package
Graph node of the previously imported package containing this
submodule.
submodule_name : str
Name of the submodule to be imported in either qualified (e.g.,
`email.mime.base`) or unqualified (e.g., `base`) form.
Returns
----------
Node
Graph node created for this submodule.
Raises
----------
ImportError
If this submodule is unimportable.
"""
self.msgin(4, "load_tail", package, submodule_name)
submodule = package
while submodule_name:
i = submodule_name.find('.')
if i < 0:
i = len(submodule_name)
head, submodule_name = submodule_name[:i], submodule_name[i+1:]
mname = "%s.%s" % (submodule.identifier, head)
submodule = self._safe_import_module(head, mname, submodule)
if submodule is None:
# FIXME: Why do we no longer return | |
_dataflow_plus_data_3;
reg _dataflow_plus_valid_3;
wire _dataflow_plus_ready_3;
assign _dataflow_lut_ready_2 = (_dataflow_plus_ready_3 || !_dataflow_plus_valid_3) && (_dataflow_lut_valid_2 && _dataflow__delay_valid_4);
assign _dataflow__delay_ready_4 = (_dataflow_plus_ready_3 || !_dataflow_plus_valid_3) && (_dataflow_lut_valid_2 && _dataflow__delay_valid_4);
assign zdata = _dataflow_plus_data_3;
assign zvalid = _dataflow_plus_valid_3;
assign _dataflow_plus_ready_3 = zready;
always @(posedge CLK) begin
if(RST) begin
_dataflow_lut_valid_2 <= 0;
_dataflow__delay_data_4 <= 0;
_dataflow__delay_valid_4 <= 0;
_dataflow_plus_data_3 <= 0;
_dataflow_plus_valid_3 <= 0;
end else begin
if(_dataflow_lut_valid_2 && _dataflow_lut_ready_2) begin
_dataflow_lut_valid_2 <= 0;
end
if((_dataflow_lut_ready_2 || !_dataflow_lut_valid_2) && xready) begin
_dataflow_lut_valid_2 <= xvalid;
end
if((_dataflow__delay_ready_4 || !_dataflow__delay_valid_4) && yready && yvalid) begin
_dataflow__delay_data_4 <= ydata;
end
if(_dataflow__delay_valid_4 && _dataflow__delay_ready_4) begin
_dataflow__delay_valid_4 <= 0;
end
if((_dataflow__delay_ready_4 || !_dataflow__delay_valid_4) && yready) begin
_dataflow__delay_valid_4 <= yvalid;
end
if((_dataflow_plus_ready_3 || !_dataflow_plus_valid_3) && (_dataflow_lut_ready_2 && _dataflow__delay_ready_4) && (_dataflow_lut_valid_2 && _dataflow__delay_valid_4)) begin
_dataflow_plus_data_3 <= _dataflow_lut_data_2 + _dataflow__delay_data_4;
end
if(_dataflow_plus_valid_3 && _dataflow_plus_ready_3) begin
_dataflow_plus_valid_3 <= 0;
end
if((_dataflow_plus_ready_3 || !_dataflow_plus_valid_3) && (_dataflow_lut_ready_2 && _dataflow__delay_ready_4)) begin
_dataflow_plus_valid_3 <= _dataflow_lut_valid_2 && _dataflow__delay_valid_4;
end
end
end
endmodule
module _dataflow_lut_LUT_ROM_2
(
input CLK,
input [8-1:0] addr,
input enable,
output reg [32-1:0] val
);
always @(posedge CLK) begin
if(enable) begin
case(addr)
0: begin
val <= 0;
end
1: begin
val <= 1;
end
2: begin
val <= 4;
end
3: begin
val <= 9;
end
4: begin
val <= 16;
end
5: begin
val <= 25;
end
6: begin
val <= 36;
end
7: begin
val <= 49;
end
8: begin
val <= 64;
end
9: begin
val <= 81;
end
10: begin
val <= 100;
end
11: begin
val <= 121;
end
12: begin
val <= 144;
end
13: begin
val <= 169;
end
14: begin
val <= 196;
end
15: begin
val <= 225;
end
16: begin
val <= 256;
end
17: begin
val <= 289;
end
18: begin
val <= 324;
end
19: begin
val <= 361;
end
20: begin
val <= 400;
end
21: begin
val <= 441;
end
22: begin
val <= 484;
end
23: begin
val <= 529;
end
24: begin
val <= 576;
end
25: begin
val <= 625;
end
26: begin
val <= 676;
end
27: begin
val <= 729;
end
28: begin
val <= 784;
end
29: begin
val <= 841;
end
30: begin
val <= 900;
end
31: begin
val <= 961;
end
32: begin
val <= 1024;
end
33: begin
val <= 1089;
end
34: begin
val <= 1156;
end
35: begin
val <= 1225;
end
36: begin
val <= 1296;
end
37: begin
val <= 1369;
end
38: begin
val <= 1444;
end
39: begin
val <= 1521;
end
40: begin
val <= 1600;
end
41: begin
val <= 1681;
end
42: begin
val <= 1764;
end
43: begin
val <= 1849;
end
44: begin
val <= 1936;
end
45: begin
val <= 2025;
end
46: begin
val <= 2116;
end
47: begin
val <= 2209;
end
48: begin
val <= 2304;
end
49: begin
val <= 2401;
end
50: begin
val <= 2500;
end
51: begin
val <= 2601;
end
52: begin
val <= 2704;
end
53: begin
val <= 2809;
end
54: begin
val <= 2916;
end
55: begin
val <= 3025;
end
56: begin
val <= 3136;
end
57: begin
val <= 3249;
end
58: begin
val <= 3364;
end
59: begin
val <= 3481;
end
60: begin
val <= 3600;
end
61: begin
val <= 3721;
end
62: begin
val <= 3844;
end
63: begin
val <= 3969;
end
64: begin
val <= 4096;
end
65: begin
val <= 4225;
end
66: begin
val <= 4356;
end
67: begin
val <= 4489;
end
68: begin
val <= 4624;
end
69: begin
val <= 4761;
end
70: begin
val <= 4900;
end
71: begin
val <= 5041;
end
72: begin
val <= 5184;
end
73: begin
val <= 5329;
end
74: begin
val <= 5476;
end
75: begin
val <= 5625;
end
76: begin
val <= 5776;
end
77: begin
val <= 5929;
end
78: begin
val <= 6084;
end
79: begin
val <= 6241;
end
80: begin
val <= 6400;
end
81: begin
val <= 6561;
end
82: begin
val <= 6724;
end
83: begin
val <= 6889;
end
84: begin
val <= 7056;
end
85: begin
val <= 7225;
end
86: begin
val <= 7396;
end
87: begin
val <= 7569;
end
88: begin
val <= 7744;
end
89: begin
val <= 7921;
end
90: begin
val <= 8100;
end
91: begin
val <= 8281;
end
92: begin
val <= 8464;
end
93: begin
val <= 8649;
end
94: begin
val <= 8836;
end
95: begin
val <= 9025;
end
96: begin
val <= 9216;
end
97: begin
val <= 9409;
end
98: begin
val <= 9604;
end
99: begin
val <= 9801;
end
100: begin
val <= 10000;
end
101: begin
val <= 10201;
end
102: begin
val <= 10404;
end
103: begin
val <= 10609;
end
104: begin
val <= 10816;
end
105: begin
val <= 11025;
end
106: begin
val <= 11236;
end
107: begin
val <= 11449;
end
108: begin
val <= 11664;
end
109: begin
val <= 11881;
end
110: begin
val <= 12100;
end
111: begin
val <= 12321;
end
112: begin
val <= 12544;
end
113: begin
val <= 12769;
end
114: begin
val <= 12996;
end
115: begin
val <= 13225;
end
116: begin
val <= 13456;
end
117: begin
val <= 13689;
end
118: begin
val <= 13924;
end
119: begin
val <= 14161;
end
120: begin
val <= 14400;
end
121: begin
val <= 14641;
end
122: begin
val <= 14884;
end
123: begin
val <= 15129;
end
124: begin
val <= 15376;
end
125: begin
val <= 15625;
end
126: begin
val <= 15876;
end
127: begin
val <= 16129;
end
128: begin
val <= 16384;
end
129: begin
val <= 16641;
end
130: begin
val <= 16900;
end
131: begin
val <= 17161;
end
132: begin
val <= 17424;
end
133: begin
val <= 17689;
end
134: begin
val <= 17956;
end
135: begin
val <= 18225;
end
136: begin
val <= 18496;
end
137: begin
val <= 18769;
end
138: begin
val <= 19044;
end
139: begin
val <= 19321;
end
140: begin
val <= 19600;
end
141: begin
val <= 19881;
end
142: begin
val <= 20164;
end
143: begin
val <= 20449;
end
144: begin
val <= 20736;
end
145: begin
val <= 21025;
end
146: begin
val <= 21316;
end
147: begin
val <= 21609;
end
148: begin
val <= 21904;
end
149: begin
val <= 22201;
end
150: begin
val <= 22500;
end
151: begin
val <= 22801;
end
152: begin
val <= 23104;
end
153: begin
val <= 23409;
end
154: begin
val <= 23716;
end
155: begin
val <= 24025;
end
156: begin
val <= 24336;
end
157: begin
val <= 24649;
end
158: begin
val <= 24964;
end
159: begin
val <= 25281;
end
160: begin
val <= 25600;
end
161: begin
val <= 25921;
end
162: begin
val <= 26244;
end
163: begin
val <= 26569;
end
164: begin
val <= 26896;
end
165: begin
val <= 27225;
end
166: begin
val <= 27556;
end
167: begin
val <= 27889;
end
168: begin
val <= 28224;
end
169: begin
val <= 28561;
end
170: begin
val <= 28900;
end
171: begin
val <= 29241;
end
172: begin
val <= 29584;
end
173: begin
val <= 29929;
end
174: begin
val <= 30276;
end
175: begin
val <= 30625;
end
176: begin
val <= 30976;
end
177: begin
val <= 31329;
end
178: begin
val <= 31684;
end
179: begin
val <= 32041;
end
180: begin
val <= 32400;
end
181: begin
val <= 32761;
end
182: begin
val <= 33124;
end
183: begin
val <= | |
# -*- coding:utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import urllib
from networkapiclient.ApiGenericClient import ApiGenericClient
class Pool(ApiGenericClient):
def __init__(self, networkapi_url, user, password, user_ldap=None):
"""Class constructor receives parameters to connect to the networkAPI.
:param networkapi_url: URL to access the network API.
:param user: User for authentication.
:param password: Password for authentication.
"""
super(Pool, self).__init__(
networkapi_url,
user,
password,
user_ldap
)
def set_poolmember_state(self, id_pools, pools):
"""
Enable/Disable pool member by list
"""
data = dict()
uri = "api/v3/pool/real/%s/member/status/" % ';'.join(id_pools)
data["server_pools"] = pools
return self.put(uri, data=data)
def get_poolmember_state(self, id_pools, checkstatus=0):
"""
Enable/Disable pool member by list
"""
uri = "api/v3/pool/real/%s/member/status/?checkstatus=%s" % (';'.join(id_pools), checkstatus)
return self.get(uri)
def list_all(self, environment_id, pagination):
"""
List All Pools To Populate Datatable
:param pagination: Object Pagination
:return: Following dictionary:{
"total" : < total >,
"pools" :[{
"id": < id >
"default_port": < default_port >,
"identifier": < identifier >,
"healthcheck": < healthcheck >,
}, ... too ... ]}
:raise NetworkAPIException: Falha ao acessar fonte de dados
"""
uri = "api/pools/"
data = dict()
data["start_record"] = pagination.start_record
data["end_record"] = pagination.end_record
data["asorting_cols"] = pagination.asorting_cols
data["searchable_columns"] = pagination.searchable_columns
data["custom_search"] = pagination.custom_search or None
data["environment_id"] = environment_id or None
return self.post(uri, data=data)
def list_all_by_reqvip(self, id_vip, pagination):
"""
List All Pools To Populate Datatable
:param pagination: Object Pagination
:return: Following dictionary:{
"total" : < total >,
"pools" :[{
"id": < id >
"default_port": < default_port >,
"identifier": < identifier >,
"healthcheck": < healthcheck >,
}, ... too ... ]}
:raise NetworkAPIException: Falha ao acessar fonte de dados
"""
uri = "api/pools/pool_list_by_reqvip/"
data = dict()
data["start_record"] = pagination.start_record
data["end_record"] = pagination.end_record
data["asorting_cols"] = pagination.asorting_cols
data["searchable_columns"] = pagination.searchable_columns
data["custom_search"] = pagination.custom_search or None
data["id_vip"] = id_vip or None
return self.post(uri, data=data)
def inserir(self, identifier, default_port, environment, balancing, healthcheck_type, healthcheck_expect,
healthcheck_request, old_healthcheck_id, maxcon, ip_list_full, nome_equips, id_equips, priorities,
weight, ports_reals, servicedownaction=None):
uri = "api/pools/insert/"
data = dict()
data['identifier'] = identifier
data['default_port'] = default_port
data['environment'] = environment
data['balancing'] = balancing
data['servicedownaction'] = servicedownaction
data['healthcheck_type'] = healthcheck_type
data['healthcheck_expect'] = healthcheck_expect
data['healthcheck_request'] = healthcheck_request
if old_healthcheck_id == '':
old_healthcheck_id = None
data['old_healthcheck_id'] = old_healthcheck_id
data['maxcon'] = maxcon
data['ip_list_full'] = ip_list_full
data['id_equips'] = id_equips
data['priorities'] = priorities
data['ports_reals'] = ports_reals
data['nome_equips'] = nome_equips
data['weight'] = weight
return self.post(uri, data=data)
def save(self, id, identifier, default_port, environment, balancing, healthcheck_type, healthcheck_expect,
healthcheck_request, maxcon, ip_list_full, nome_equips, id_equips, priorities,
weight, ports_reals, id_pool_member, servicedownaction=None):
uri = "api/pools/save/"
data = dict()
data['id'] = id
data['identifier'] = identifier
data['default_port'] = default_port
data['environment'] = environment
data['balancing'] = balancing
data['servicedownaction'] = servicedownaction
data['healthcheck_type'] = healthcheck_type
data['healthcheck_expect'] = healthcheck_expect
data['healthcheck_request'] = healthcheck_request
data['maxcon'] = maxcon
data['id_pool_member'] = id_pool_member
data['ip_list_full'] = ip_list_full
data['id_equips'] = id_equips
data['priorities'] = priorities
data['ports_reals'] = ports_reals
data['nome_equips'] = nome_equips
data['weight'] = weight
return self.post(uri, data=data)
def save_reals(self, id_server_pool, ip_list_full, nome_equips, id_equips, priorities, weight, ports_reals, id_pool_member):
uri = "api/pools/save_reals/"
data = dict()
data['id_server_pool'] = id_server_pool
data['id_pool_member'] = id_pool_member
data['ip_list_full'] = ip_list_full
data['id_equips'] = id_equips
data['priorities'] = priorities
data['ports_reals'] = ports_reals
data['nome_equips'] = nome_equips
data['weight'] = weight
return self.post(uri, data=data)
def update(self, id_server_pool, default_port, balancing, healthcheck_type, healthcheck_expect, healthcheck_request,
old_healthcheck_id, maxcon, ip_list_full, nome_equips, id_equips, priorities, weight, ports_reals, servicedownaction=None):
uri = "api/pools/edit/"
data = dict()
# data['identifier'] = identifier
data['default_port'] = default_port
# data['environment'] = environment
data['balancing'] = balancing
data['servicedownaction'] = servicedownaction
data['healthcheck_type'] = healthcheck_type
data['healthcheck_expect'] = healthcheck_expect
data['healthcheck_request'] = healthcheck_request
if old_healthcheck_id == '':
old_healthcheck_id = None
data['old_healthcheck_id'] = old_healthcheck_id
data['maxcon'] = maxcon
data['ip_list_full'] = ip_list_full
data['id_equips'] = id_equips
data['priorities'] = priorities
data['ports_reals'] = ports_reals
data['id_server_pool'] = id_server_pool
data['nome_equips'] = nome_equips
data['weight'] = weight
return self.post(uri, data=data)
def list_all_members_by_poolll_members(self, id_pools):
uri = "api/pools/get_all_members/%s/" % id_pools
return self.get(uri)
def list_all_members_by_pool(self, id_server_pool, checkstatus=False, pagination=None):
data = dict()
uri = "api/pools/get_all_members/%s/?checkstatus=%s" % (id_server_pool, checkstatus)
if pagination:
data["start_record"] = pagination.start_record
data["end_record"] = pagination.end_record
data["asorting_cols"] = pagination.asorting_cols
data["searchable_columns"] = pagination.searchable_columns
data["custom_search"] = pagination.custom_search or None
return self.post(uri, data=data)
else:
return self.get(uri)
def get_equip_by_ip(self, id_ip):
"""
Get equipment by IP id
:param id_ip: IP id
:return: Following dictionary:{
"equipamento" :[{
"id": < id >
"tipo_equipamento": < tipo_equipamento >,
"modelo": < modelo >,
"nome": < nome >,
"grupos": < grupos >
}]
:raise NetworkAPIException: Falha ao acessar fonte de dados
"""
uri = "api/pools/get_equip_by_ip/%s/" % id_ip
return self.get(uri)
def list_healthchecks(self):
"""
List all healthchecks
:return: Following dictionary:
::
{'ambiente': [{ 'id': <id_environment>,
'grupo_l3': <id_group_l3>,
'grupo_l3_name': <name_group_l3>,
'ambiente_logico': <id_logical_environment>,
'ambiente_logico_name': <name_ambiente_logico>,
'divisao_dc': <id_dc_division>,
'divisao_dc_name': <name_divisao_dc>,
'filter': <id_filter>,
'filter_name': <filter_name>,
'link': <link> }, ... ]}
:raise DataBaseError: Falha na networkapi ao acessar o banco de dados.
"""
uri = "api/pools/list_healthchecks/"
return self.get(uri)
# def delete_pool(self, ids):
# """
# Delete Pools
# :param ids: List of ids
# :return: None on success
# :raise PoolConstraintVipException
# :raise ScriptDeletePoolException
# :raise InvalidIdPoolException
# :raise NetworkAPIException
# """
# data = dict()
# data["ids"] = ids
# uri = "api/pools/delete/"
# return self.post(uri, data)
def get_by_pk(self, pk):
uri = "api/pools/getbypk/%s/" % pk
return self.get(uri)
def remove(self, pools):
"""
Remove Pools Running Script And Update to Not Created
:param ids: List of ids
:return: None on success
:raise ScriptRemovePoolException
:raise InvalidIdPoolException
:raise NetworkAPIException
"""
data = dict()
data["pools"] = pools
uri = "api/pools/v2/"
return self.delete(uri, data)
def create(self, pools):
"""
Create Pools Running Script And Update to Created
:param pools: List of pools
:return: None on success
:raise PoolDoesNotExistException
:raise ScriptCreatePoolException
:raise InvalidIdPoolException
:raise NetworkAPIException
"""
data = dict()
data["pools"] = pools
uri = "api/pools/v2/"
return self.put(uri, data)
def enable(self, ids):
"""
Enable Pool Members Running Script
:param ids: List of ids
:return: None on success
:raise PoolMemberDoesNotExistException
:raise InvalidIdPoolMemberException
:raise ScriptEnablePoolException
:raise NetworkAPIException
"""
data = dict()
data["ids"] = ids
uri = "api/pools/enable/"
return self.post(uri, data)
def disable(self, ids):
"""
Disable Pool Members Running Script
:param ids: List of ids
:return: None on success
:raise PoolMemberDoesNotExistException
:raise InvalidIdPoolMemberException
:raise ScriptDisablePoolException
:raise NetworkAPIException
"""
data = dict()
data["ids"] = ids
uri = "api/pools/disable/"
return self.post(uri, data)
def get_opcoes_pool_by_ambiente(self, id_ambiente):
data = dict()
data["id_environment"] = id_ambiente
uri = "api/pools/get_opcoes_pool_by_ambiente/"
return self.post(uri, data=data)
def get_requisicoes_vip_by_pool(self, id_server_pool, pagination):
data = dict()
data["start_record"] = pagination.start_record
data["end_record"] = pagination.end_record
data["asorting_cols"] = pagination.asorting_cols
data["searchable_columns"] = pagination.searchable_columns
data["custom_search"] = pagination.custom_search or None
uri = "api/pools/get_requisicoes_vip_by_pool/%s/" % id_server_pool
return self.post(uri, data=data)
def list_by_environment(self, environment_id):
"""
Disable Pool Members Running Script
:param ids: List of ids
:return: Following dictionary:{
"pools" :[{
"id": < id >
"default_port": < default_port >,
"identifier": < identifier >,
"healthcheck": < healthcheck >,
}, ... too ... ]}
:raise ObjectDoesNotExistException
:raise ValidationException
:raise NetworkAPIException
"""
uri = "api/pools/list/by/environment/%s/" % (environment_id)
return self.get(uri)
def list_pool_members(self, pool_id):
"""
Disable Pool Members Running Script
:param ids: List of ids
:return:
:raise ObjectDoesNotExistException
:raise ValidationException
:raise NetworkAPIException
"""
uri = "api/pools/list/members/%s/" % (pool_id)
return self.get(uri)
def list_by_environmet_vip(self, environment_vip_id):
"""
"""
uri = "api/pools/list/by/environment/vip/%s/" % (environment_vip_id)
return self.get(uri)
def list_environments_with_pools(self):
"""
"""
uri = "api/pools/list/environment/with/pools/"
return self.get(uri)
def list_all_environment_related_environment_vip(self):
"""
"""
uri = "api/pools/list/environments/environmentvip/"
return self.get(uri)
def get_available_ips_to_add_server_pool(self, equip_name, id_ambiente):
"""
"""
uri = "api/pools/getipsbyambiente/{}/{}/".format(equip_name, id_ambiente)
return self.get(uri)
#######################
# API V3
#######################
def get_pool(self, pool_id):
uri = "api/v3/pool/%s/" % pool_id
return self.get(uri)
def list_pool(self, search):
uri = "api/v3/pool/?%s" % urllib.urlencode({"search": search})
return self.get(uri)
def save_pool(self, pool):
uri = "api/v3/pool/"
data = dict()
data['server_pools'] = list()
data['server_pools'].append(pool)
return self.post(uri, data)
def update_pool(self, pool, pool_id):
uri = "api/v3/pool/%s/" % pool_id
data = dict()
data['server_pools'] = list()
data['server_pools'].append(pool)
return self.put(uri, data)
def delete_pool(self, | |
py_attrs:
name = "p->%s" % entry.cname
code.putln("tmp = ((PyObject*)%s);" % name)
if entry.is_declared_generic:
code.put_init_to_py_none(name, py_object_type, nanny=False)
else:
code.put_init_to_py_none(name, entry.type, nanny=False)
code.putln("Py_XDECREF(tmp);")
else:
for entry in py_attrs:
code.putln("Py_CLEAR(p->%s);" % entry.cname)
for entry in py_buffers:
# Note: shouldn't this call __Pyx_ReleaseBuffer ??
code.putln("Py_CLEAR(p->%s.obj);" % entry.cname)
if cclass_entry.cname == '__pyx_memoryviewslice':
code.putln("__PYX_XDEC_MEMVIEW(&p->from_slice, 1);")
code.putln("return 0;")
code.putln("}")
def generate_getitem_int_function(self, scope, code):
# This function is put into the sq_item slot when
# a __getitem__ method is present. It converts its
# argument to a Python integer and calls mp_subscript.
code.putln(
"static PyObject *%s(PyObject *o, Py_ssize_t i) {" % (
scope.mangle_internal("sq_item")))
code.putln(
"PyObject *r;")
code.putln(
"PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0;")
code.putln(
"r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x);")
code.putln(
"Py_DECREF(x);")
code.putln(
"return r;")
code.putln(
"}")
def generate_ass_subscript_function(self, scope, code):
# Setting and deleting an item are both done through
# the ass_subscript method, so we dispatch to user's __setitem__
# or __delitem__, or raise an exception.
base_type = scope.parent_type.base_type
set_entry = scope.lookup_here("__setitem__")
del_entry = scope.lookup_here("__delitem__")
code.putln("")
code.putln(
"static int %s(PyObject *o, PyObject *i, PyObject *v) {" % (
scope.mangle_internal("mp_ass_subscript")))
code.putln(
"if (v) {")
if set_entry:
code.putln("return %s(o, i, v);" % set_entry.func_cname)
else:
self.generate_guarded_basetype_call(
base_type, "tp_as_mapping", "mp_ass_subscript", "o, i, v", code)
code.putln(
"PyErr_Format(PyExc_NotImplementedError,")
code.putln(
' "Subscript assignment not supported by %.200s", Py_TYPE(o)->tp_name);')
code.putln(
"return -1;")
code.putln(
"}")
code.putln(
"else {")
if del_entry:
code.putln(
"return %s(o, i);" % (
del_entry.func_cname))
else:
self.generate_guarded_basetype_call(
base_type, "tp_as_mapping", "mp_ass_subscript", "o, i, v", code)
code.putln(
"PyErr_Format(PyExc_NotImplementedError,")
code.putln(
' "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name);')
code.putln(
"return -1;")
code.putln(
"}")
code.putln(
"}")
def generate_guarded_basetype_call(
self, base_type, substructure, slot, args, code):
if base_type:
base_tpname = base_type.typeptr_cname
if substructure:
code.putln(
"if (%s->%s && %s->%s->%s)" % (
base_tpname, substructure, base_tpname, substructure, slot))
code.putln(
" return %s->%s->%s(%s);" % (
base_tpname, substructure, slot, args))
else:
code.putln(
"if (%s->%s)" % (
base_tpname, slot))
code.putln(
" return %s->%s(%s);" % (
base_tpname, slot, args))
def generate_ass_slice_function(self, scope, code):
# Setting and deleting a slice are both done through
# the ass_slice method, so we dispatch to user's __setslice__
# or __delslice__, or raise an exception.
base_type = scope.parent_type.base_type
set_entry = scope.lookup_here("__setslice__")
del_entry = scope.lookup_here("__delslice__")
code.putln("")
code.putln(
"static int %s(PyObject *o, Py_ssize_t i, Py_ssize_t j, PyObject *v) {" % (
scope.mangle_internal("sq_ass_slice")))
code.putln(
"if (v) {")
if set_entry:
code.putln(
"return %s(o, i, j, v);" % (
set_entry.func_cname))
else:
self.generate_guarded_basetype_call(
base_type, "tp_as_sequence", "sq_ass_slice", "o, i, j, v", code)
code.putln(
"PyErr_Format(PyExc_NotImplementedError,")
code.putln(
' "2-element slice assignment not supported by %.200s", Py_TYPE(o)->tp_name);')
code.putln(
"return -1;")
code.putln(
"}")
code.putln(
"else {")
if del_entry:
code.putln(
"return %s(o, i, j);" % (
del_entry.func_cname))
else:
self.generate_guarded_basetype_call(
base_type, "tp_as_sequence", "sq_ass_slice", "o, i, j, v", code)
code.putln(
"PyErr_Format(PyExc_NotImplementedError,")
code.putln(
' "2-element slice deletion not supported by %.200s", Py_TYPE(o)->tp_name);')
code.putln(
"return -1;")
code.putln(
"}")
code.putln(
"}")
def generate_richcmp_function(self, scope, code):
if scope.lookup_here("__richcmp__"):
# user implemented, nothing to do
return
# otherwise, we have to generate it from the Python special methods
richcmp_cfunc = scope.mangle_internal("tp_richcompare")
code.putln("")
code.putln("static PyObject *%s(PyObject *o1, PyObject *o2, int op) {" % richcmp_cfunc)
code.putln("switch (op) {")
class_scopes = []
cls = scope.parent_type
while cls is not None and not cls.entry.visibility == 'extern':
class_scopes.append(cls.scope)
cls = cls.scope.parent_type.base_type
assert scope in class_scopes
extern_parent = None
if cls and cls.entry.visibility == 'extern':
# need to call up into base classes as we may not know all implemented comparison methods
extern_parent = cls if cls.typeptr_cname else scope.parent_type.base_type
eq_entry = None
has_ne = False
for cmp_method in TypeSlots.richcmp_special_methods:
for class_scope in class_scopes:
entry = class_scope.lookup_here(cmp_method)
if entry is not None:
break
else:
continue
cmp_type = cmp_method.strip('_').upper() # e.g. "__eq__" -> EQ
code.putln("case Py_%s: {" % cmp_type)
if cmp_method == '__eq__':
eq_entry = entry
# Python itself does not do this optimisation, it seems...
#code.putln("if (o1 == o2) return __Pyx_NewRef(Py_True);")
elif cmp_method == '__ne__':
has_ne = True
# Python itself does not do this optimisation, it seems...
#code.putln("if (o1 == o2) return __Pyx_NewRef(Py_False);")
code.putln("return %s(o1, o2);" % entry.func_cname)
code.putln("}")
if eq_entry and not has_ne and not extern_parent:
code.putln("case Py_NE: {")
code.putln("PyObject *ret;")
# Python itself does not do this optimisation, it seems...
#code.putln("if (o1 == o2) return __Pyx_NewRef(Py_False);")
code.putln("ret = %s(o1, o2);" % eq_entry.func_cname)
code.putln("if (likely(ret && ret != Py_NotImplemented)) {")
code.putln("int b = __Pyx_PyObject_IsTrue(ret); Py_DECREF(ret);")
code.putln("if (unlikely(b < 0)) return NULL;")
code.putln("ret = (b) ? Py_False : Py_True;")
code.putln("Py_INCREF(ret);")
code.putln("}")
code.putln("return ret;")
code.putln("}")
code.putln("default: {")
if extern_parent and extern_parent.typeptr_cname:
code.putln("if (likely(%s->tp_richcompare)) return %s->tp_richcompare(o1, o2, op);" % (
extern_parent.typeptr_cname, extern_parent.typeptr_cname))
code.putln("return __Pyx_NewRef(Py_NotImplemented);")
code.putln("}")
code.putln("}") # switch
code.putln("}")
def generate_getattro_function(self, scope, code):
# First try to get the attribute using __getattribute__, if defined, or
# PyObject_GenericGetAttr.
#
# If that raises an AttributeError, call the __getattr__ if defined.
#
# In both cases, defined can be in this class, or any base class.
def lookup_here_or_base(n, tp=None, extern_return=None):
# Recursive lookup
if tp is None:
tp = scope.parent_type
r = tp.scope.lookup_here(n)
if r is None:
if tp.is_external and extern_return is not None:
return extern_return
if tp.base_type is not None:
return lookup_here_or_base(n, tp.base_type)
return r
has_instance_dict = lookup_here_or_base("__dict__", extern_return="extern")
getattr_entry = lookup_here_or_base("__getattr__")
getattribute_entry = lookup_here_or_base("__getattribute__")
code.putln("")
code.putln(
"static PyObject *%s(PyObject *o, PyObject *n) {" % (
scope.mangle_internal("tp_getattro")))
if getattribute_entry is not None:
code.putln(
"PyObject *v = %s(o, n);" % (
getattribute_entry.func_cname))
else:
if not has_instance_dict and scope.parent_type.is_final_type:
# Final with no dict => use faster type attribute lookup.
code.globalstate.use_utility_code(
UtilityCode.load_cached("PyObject_GenericGetAttrNoDict", "ObjectHandling.c"))
generic_getattr_cfunc = "__Pyx_PyObject_GenericGetAttrNoDict"
elif not has_instance_dict or has_instance_dict == "extern":
# No dict in the known ancestors, but don't know about extern ancestors or subtypes.
code.globalstate.use_utility_code(
UtilityCode.load_cached("PyObject_GenericGetAttr", "ObjectHandling.c"))
generic_getattr_cfunc = "__Pyx_PyObject_GenericGetAttr"
else:
generic_getattr_cfunc = "PyObject_GenericGetAttr"
code.putln(
"PyObject *v = %s(o, n);" % generic_getattr_cfunc)
if getattr_entry is not None:
code.putln(
"if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) {")
code.putln(
"PyErr_Clear();")
code.putln(
"v = %s(o, n);" % (
getattr_entry.func_cname))
code.putln(
"}")
code.putln(
"return v;")
code.putln(
"}")
def generate_setattro_function(self, scope, code):
# Setting and deleting an attribute are both done through
# the setattro method, so we dispatch to user's __setattr__
# or __delattr__ or fall back on PyObject_GenericSetAttr.
base_type = scope.parent_type.base_type
set_entry = scope.lookup_here("__setattr__")
del_entry = scope.lookup_here("__delattr__")
code.putln("")
code.putln(
"static int %s(PyObject *o, PyObject *n, PyObject *v) {" % (
scope.mangle_internal("tp_setattro")))
code.putln(
"if (v) {")
if set_entry:
code.putln(
"return %s(o, n, v);" % (
set_entry.func_cname))
else:
self.generate_guarded_basetype_call(
base_type, None, "tp_setattro", "o, n, v", code)
code.putln(
"return PyObject_GenericSetAttr(o, n, v);")
code.putln(
"}")
code.putln(
"else {")
if del_entry:
code.putln(
"return %s(o, n);" % (
del_entry.func_cname))
else:
self.generate_guarded_basetype_call(
base_type, None, "tp_setattro", "o, n, v", code)
code.putln(
"return PyObject_GenericSetAttr(o, n, 0);")
code.putln(
"}")
code.putln(
"}")
def generate_descr_get_function(self, scope, code):
# The __get__ function of a descriptor object can be
# called with NULL for the second or third arguments
# under some circumstances, so we replace them with
# None in that case.
user_get_entry = scope.lookup_here("__get__")
code.putln("")
code.putln(
"static PyObject *%s(PyObject *o, PyObject *i, PyObject *c) {" % (
scope.mangle_internal("tp_descr_get")))
code.putln(
"PyObject *r = 0;")
code.putln(
"if (!i) i = Py_None;")
code.putln(
"if (!c) c = Py_None;")
#code.put_incref("i", py_object_type)
#code.put_incref("c", py_object_type)
code.putln(
"r = %s(o, i, c);" % (
user_get_entry.func_cname))
#code.put_decref("i", py_object_type)
#code.put_decref("c", py_object_type)
code.putln(
"return r;")
code.putln(
"}")
def generate_descr_set_function(self, scope, code):
# Setting and deleting are both done through the __set__
# method of a descriptor, so we dispatch to user's __set__
# or __delete__ or raise an exception.
base_type = scope.parent_type.base_type
user_set_entry = scope.lookup_here("__set__")
user_del_entry = scope.lookup_here("__delete__")
code.putln("")
code.putln(
"static int %s(PyObject *o, PyObject *i, PyObject *v) {" % (
scope.mangle_internal("tp_descr_set")))
code.putln(
"if (v) {")
if user_set_entry:
code.putln(
"return %s(o, i, v);" % (
user_set_entry.func_cname))
else:
self.generate_guarded_basetype_call(
base_type, None, "tp_descr_set", "o, i, v", code)
code.putln(
'PyErr_SetString(PyExc_NotImplementedError, "__set__");')
code.putln(
"return -1;")
code.putln(
"}")
code.putln(
"else {")
if user_del_entry:
code.putln(
"return %s(o, i);" % (
user_del_entry.func_cname))
else:
self.generate_guarded_basetype_call(
base_type, None, "tp_descr_set", "o, i, v", code)
code.putln(
'PyErr_SetString(PyExc_NotImplementedError, "__delete__");')
code.putln(
"return -1;")
code.putln(
"}")
code.putln(
"}")
def generate_property_accessors(self, cclass_scope, code):
for entry in cclass_scope.property_entries:
property_scope = entry.scope
if property_scope.defines_any(["__get__"]):
self.generate_property_get_function(entry, code)
if property_scope.defines_any(["__set__", "__del__"]):
self.generate_property_set_function(entry, code)
def generate_property_get_function(self, | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from pytest import mark
from translate.tools import pomerge
from translate.storage import factory
from translate.storage import po
from translate.storage import xliff
from translate.misc import wStringIO
def test_str2bool():
"""test the str2bool function"""
assert pomerge.str2bool("yes")
assert pomerge.str2bool("true")
assert pomerge.str2bool("1")
assert not pomerge.str2bool("no")
assert not pomerge.str2bool("false")
assert not pomerge.str2bool("0")
pytest.raises(ValueError, pomerge.str2bool, "2")
class TestPOMerge:
xliffskeleton = '''<?xml version="1.0" ?>
<xliff version="1.1" xmlns="urn:oasis:names:tc:xliff:document:1.1">
<file original="filename.po" source-language="en-US" datatype="po">
<body>
%s
</body>
</file>
</xliff>'''
def mergestore(self, templatesource, inputsource, mergeblanks="yes",
mergefuzzy="yes",
mergecomments="yes"):
"""merges the sources of the given files and returns a new pofile
object"""
templatefile = wStringIO.StringIO(templatesource)
inputfile = wStringIO.StringIO(inputsource)
outputfile = wStringIO.StringIO()
assert pomerge.mergestore(inputfile, outputfile, templatefile,
mergeblanks=mergeblanks,
mergefuzzy=mergefuzzy,
mergecomments=mergecomments,
)
outputpostring = outputfile.getvalue()
outputpofile = po.pofile(outputpostring)
return outputpofile
def mergexliff(self, templatesource, inputsource, mergeblanks="yes",
mergefuzzy="yes",
mergecomments="yes"):
"""merges the sources of the given files and returns a new xlifffile
object"""
templatefile = wStringIO.StringIO(templatesource)
inputfile = wStringIO.StringIO(inputsource)
outputfile = wStringIO.StringIO()
assert pomerge.mergestore(inputfile, outputfile, templatefile,
mergeblanks=mergeblanks,
mergefuzzy=mergefuzzy,
mergecomments=mergecomments)
outputxliffstring = outputfile.getvalue()
print "Generated XML:"
print outputxliffstring
outputxlifffile = xliff.xlifffile(outputxliffstring)
return outputxlifffile
def countunits(self, pofile):
"""returns the number of non-header items"""
if pofile.units[0].isheader():
return len(pofile.units) - 1
else:
return len(pofile.units)
def singleunit(self, pofile):
"""checks that the pofile contains a single non-header unit, and
returns it"""
assert self.countunits(pofile) == 1
return pofile.units[-1]
def test_mergesore_bad_data(self):
"""Test that we catch bad options sent to mergestore"""
templatefile = wStringIO.StringIO("")
inputfile = wStringIO.StringIO("")
outputfile = wStringIO.StringIO()
pytest.raises(ValueError, pomerge.mergestore, inputfile, outputfile,
templatefile, mergeblanks="yay")
pytest.raises(ValueError, pomerge.mergestore, inputfile, outputfile,
templatefile, mergecomments="yay")
def test_simplemerge(self):
"""checks that a simple po entry merges OK"""
templatepo = '''#: simple.test\nmsgid "Simple String"\nmsgstr ""\n'''
inputpo = '''#: simple.test\nmsgid "Simple String"\nmsgstr "Dimpled Ring"\n'''
pofile = self.mergestore(templatepo, inputpo)
pounit = self.singleunit(pofile)
assert pounit.source == "Simple String"
assert pounit.target == "Dimpled Ring"
def test_simplemerge_no_locations(self):
"""checks that a simple po entry merges OK"""
templatepo = '''msgid "Simple String"
msgstr ""'''
inputpo = '''msgid "Simple String"
msgstr "Dimpled Ring"'''
pofile = self.mergestore(templatepo, inputpo)
pounit = self.singleunit(pofile)
assert pounit.source == "Simple String"
assert pounit.target == "Dimpled Ring"
def test_replacemerge(self):
"""checks that a simple po entry merges OK"""
templatepo = '''#: simple.test\nmsgid "Simple String"\nmsgstr "Dimpled Ring"\n'''
inputpo = '''#: simple.test\nmsgid "Simple String"\nmsgstr "Dimpled King"\n'''
pofile = self.mergestore(templatepo, inputpo)
pounit = self.singleunit(pofile)
assert pounit.source == "Simple String"
assert pounit.target == "Dimpled King"
def test_merging_blanks(self):
"""By default we will merge blanks, but we can also override that"""
templatepo = '''#: simple.test\nmsgid "Simple String"\nmsgstr "Dimpled Ring"\n'''
inputpo = '''#: simple.test\nmsgid "Simple String"\nmsgstr ""\n'''
pofile = self.mergestore(templatepo, inputpo)
pounit = self.singleunit(pofile)
assert pounit.source == "Simple String"
assert pounit.target == ""
pofile = self.mergestore(templatepo, inputpo, mergeblanks="no")
pounit = self.singleunit(pofile)
assert pounit.source == "Simple String"
assert pounit.target == "Dimpled Ring"
def test_merging_fuzzies(self):
"""By default we will merge fuzzies, but can can also override that."""
templatepo = '''#: simple.test\nmsgid "Simple String"\nmsgstr "Dimpled Ring"\n'''
inputpo = '''#: simple.test\n#, fuzzy\nmsgid "Simple String"\nmsgstr "changed fish"\n'''
pofile = self.mergestore(templatepo, inputpo)
pounit = self.singleunit(pofile)
assert pounit.source == "Simple String"
assert pounit.target == "changed fish"
assert pounit.isfuzzy()
pofile = self.mergestore(templatepo, inputpo, mergefuzzy="no")
pounit = self.singleunit(pofile)
assert pounit.source == "Simple String"
assert pounit.target == "Dimpled Ring"
assert pounit.isfuzzy() == False
def test_merging_locations(self):
"""check that locations on separate lines are output in Gettext form
of all on one line"""
templatepo = '''#: location.c:1\n#: location.c:2\nmsgid "Simple String"\nmsgstr ""\n'''
inputpo = '''#: location.c:1\n#: location.c:2\nmsgid "Simple String"\nmsgstr "Dimpled Ring"\n'''
expectedpo = '''#: location.c:1%slocation.c:2\nmsgid "Simple String"\nmsgstr "Dimpled Ring"\n''' % po.lsep
pofile = self.mergestore(templatepo, inputpo)
print pofile
assert str(pofile) == expectedpo
def test_unit_missing_in_template_with_locations(self):
"""If the unit is missing in the template we should raise an error"""
templatepo = '''#: location.c:1
msgid "Simple String"
msgstr ""'''
inputpo = '''#: location.c:1
msgid "Simple String"
msgstr "Dimpled Ring"
#: location.c:1
msgid "Extra string"
msgstr "Perplexa ring"'''
expectedpo = '''#: location.c:1
msgid "Simple String"
msgstr "Dimpled Ring"
'''
pofile = self.mergestore(templatepo, inputpo)
print pofile
assert str(pofile) == expectedpo
def test_unit_missing_in_template_no_locations(self):
"""If the unit is missing in the template we should raise an error"""
templatepo = '''msgid "Simple String"
msgstr ""'''
inputpo = '''msgid "Simple String"
msgstr "Dimpled Ring"
msgid "Extra string"
msgstr "Perplexa ring"'''
expectedpo = '''msgid "Simple String"
msgstr "Dimpled Ring"
'''
pofile = self.mergestore(templatepo, inputpo)
print pofile
assert str(pofile) == expectedpo
def test_reflowed_source_comments(self):
"""ensure that we don't duplicate source comments (locations) if they
have been reflowed"""
templatepo = '''#: newMenu.label\n#: newMenu.accesskey\nmsgid "&New"\nmsgstr ""\n'''
newpo = '''#: newMenu.label newMenu.accesskey\nmsgid "&New"\nmsgstr "&Nuwe"\n'''
expectedpo = '''#: newMenu.label%snewMenu.accesskey\nmsgid "&New"\nmsgstr "&Nuwe"\n''' % po.lsep
pofile = self.mergestore(templatepo, newpo)
pounit = self.singleunit(pofile)
print pofile
assert str(pofile) == expectedpo
def test_comments_with_blank_lines(self):
"""ensure that we don't loose empty newlines in comments"""
templatepo = '''# # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# bla bla
msgid "bla"
msgstr "blabla"
'''
newpo = templatepo
expectedpo = templatepo
pofile = self.mergestore(templatepo, newpo)
pounit = self.singleunit(pofile)
print pofile
assert str(pofile) == expectedpo
def test_merge_dont_delete_unassociated_comments(self):
"""ensure that we do not delete comments in the PO file that are not
assocaited with a message block"""
templatepo = '''# Lonely comment\n\n# Translation comment\nmsgid "Bob"\nmsgstr "Toolmaker"\n'''
mergepo = '''# Translation comment\nmsgid "Bob"\nmsgstr "Builder"\n'''
expectedpo = '''# Lonely comment\n# Translation comment\nmsgid "Bob"\nmsgstr "Builder"\n'''
pofile = self.mergestore(templatepo, mergepo)
# pounit = self.singleunit(pofile)
print pofile
assert str(pofile) == expectedpo
def test_preserve_format_trailing_newlines(self):
"""Test that we can merge messages correctly that end with a newline"""
templatepo = '''msgid "Simple string\\n"\nmsgstr ""\n'''
mergepo = '''msgid "Simple string\\n"\nmsgstr "Dimpled ring\\n"\n'''
expectedpo = '''msgid "Simple string\\n"\nmsgstr "Dimpled ring\\n"\n'''
pofile = self.mergestore(templatepo, mergepo)
print "Expected:\n%s\n\nMerged:\n%s" % (expectedpo, str(pofile))
assert str(pofile) == expectedpo
templatepo = '''msgid ""\n"Simple string\\n"\nmsgstr ""\n'''
mergepo = '''msgid ""\n"Simple string\\n"\nmsgstr ""\n"Dimpled ring\\n"\n'''
expectedpo = '''msgid ""\n"Simple string\\n"\nmsgstr "Dimpled ring\\n"\n'''
expectedpo2 = '''msgid "Simple string\\n"\nmsgstr "Dimpled ring\\n"\n'''
pofile = self.mergestore(templatepo, mergepo)
print "Expected:\n%s\n\nMerged:\n%s" % (expectedpo, str(pofile))
assert str(pofile) == expectedpo or str(pofile) == expectedpo2
def test_preserve_format_minor_start_and_end_of_sentence_changes(self):
"""Test that we are not too fussy about large diffs for simple
changes at the start or end of a sentence"""
templatepo = '''msgid "Target type:"\nmsgstr "Doelsoort"\n\n'''
mergepo = '''msgid "Target type:"\nmsgstr "Doelsoort:"\n'''
expectedpo = mergepo
pofile = self.mergestore(templatepo, mergepo)
print "Expected:\n%s\n\nMerged:\n%s" % (expectedpo, str(pofile))
assert str(pofile) == expectedpo
templatepo = '''msgid "&Select"\nmsgstr "Kies"\n\n'''
mergepo = '''msgid "&Select"\nmsgstr "&Kies"\n'''
expectedpo = mergepo
pofile = self.mergestore(templatepo, mergepo)
print "Expected:\n%s\n\nMerged:\n%s" % (expectedpo, str(pofile))
assert str(pofile) == expectedpo
templatepo = '''msgid "en-us, en"\nmsgstr "en-us, en"\n'''
mergepo = '''msgid "en-us, en"\nmsgstr "af-za, af, en-za, en-gb, en-us, en"\n'''
expectedpo = mergepo
pofile = self.mergestore(templatepo, mergepo)
print "Expected:\n%s\n\nMerged:\n%s" % (expectedpo, str(pofile))
assert str(pofile) == expectedpo
def test_preserve_format_last_entry_in_a_file(self):
"""The last entry in a PO file is usualy not followed by an empty
line. Test that we preserve this"""
templatepo = '''msgid "First"\nmsgstr ""\n\nmsgid "Second"\nmsgstr ""\n'''
mergepo = '''msgid "First"\nmsgstr "Eerste"\n\nmsgid "Second"\nmsgstr "Tweede"\n'''
expectedpo = '''msgid "First"\nmsgstr "Eerste"\n\nmsgid "Second"\nmsgstr "Tweede"\n'''
pofile = self.mergestore(templatepo, mergepo)
print "Expected:\n%s\n\nMerged:\n%s" % (expectedpo, str(pofile))
assert str(pofile) == expectedpo
templatepo = '''msgid "First"\nmsgstr ""\n\nmsgid "Second"\nmsgstr ""\n\n'''
mergepo = '''msgid "First"\nmsgstr "Eerste"\n\nmsgid "Second"\nmsgstr "Tweede"\n'''
expectedpo = '''msgid "First"\nmsgstr "Eerste"\n\nmsgid "Second"\nmsgstr "Tweede"\n'''
pofile = self.mergestore(templatepo, mergepo)
print "Expected:\n%s\n\nMerged:\n%s" % (expectedpo, str(pofile))
assert str(pofile) == expectedpo
@mark.xfail(reason="Not Implemented")
def test_escape_tabs(self):
"""Ensure that input tabs are escaped in the output, like
gettext does."""
# The strings below contains the tab character, not spaces.
templatepo = '''msgid "First Second"\nmsgstr ""\n\n'''
mergepo = '''msgid "First Second"\nmsgstr "Eerste Tweede"\n'''
expectedpo = r'''msgid "First\tSecond"
msgstr "Eerste\tTweede"
'''
pofile = self.mergestore(templatepo, mergepo)
print "Expected:\n%s\n\nMerged:\n%s" % (expectedpo, str(pofile))
assert str(pofile) == expectedpo
def test_preserve_comments_layout(self):
"""Ensure that when we merge with new '# (poconflict)' or other
comments that we don't mess formating"""
templatepo = '''#: filename\nmsgid "Desktop Background.bmp"\nmsgstr "Desktop Background.bmp"\n\n'''
mergepo = '''# (pofilter) unchanged: please translate\n#: filename\nmsgid "Desktop Background.bmp"\nmsgstr "Desktop Background.bmp"\n'''
expectedpo = mergepo
pofile = self.mergestore(templatepo, mergepo)
print "Expected:\n%s\n\nMerged:\n%s" % (expectedpo, str(pofile))
assert str(pofile) == expectedpo
def test_merge_dos2unix(self):
"""Test that merging a comment line with dos newlines doesn't add a
new line"""
templatepo = '''# User comment\n# (pofilter) Translate Toolkit comment\n#. Automatic comment\n#: location_comment.c:110\nmsgid "File"\nmsgstr "File"\n\n'''
mergepo = '''# User comment\r\n# (pofilter) Translate Toolkit comment\r\n#. Automatic comment\r\n#: location_comment.c:110\r\nmsgid "File"\r\nmsgstr "Ifayile"\r\n\r\n'''
expectedpo = '''# User comment\n# (pofilter) Translate Toolkit comment\n#. Automatic comment\n#: location_comment.c:110\nmsgid "File"\nmsgstr "Ifayile"\n'''
pofile = self.mergestore(templatepo, mergepo)
assert str(pofile) == expectedpo
# Unassociated comment
templatepo = '''# Lonely comment\n\n#: location_comment.c:110\nmsgid "Bob"\nmsgstr | |
&= ~triangle(0.6, 0.95, 0.6, 0.05, 0.18, 0.5)
_widths['K'] = 0.6
_glyphs['K'] = shape
shape = rectangle(0, 0.5, 0, 1)
shape &= ~triangle(0.1, 1, 0.5, 1, 0.1, 0.45)
shape &= ~triangle(0.36, 0, 0.1, 0, 0.1, 0.25)
shape &= ~triangle(0.6, 1, 0.5, 0.0, 0.18, 0.35)
shape &= ~triangle(0.1, 1, 0.6, 1, 0.6, 0.5)
_widths['k'] = 0.5
_glyphs['k'] = shape
shape = rectangle(0, 0.6, 0, 0.1)
shape |= rectangle(0, 0.1, 0, 1)
_widths['L'] = 0.6
_glyphs['L'] = shape
shape = rectangle(0.025, 0.125, 0, 1)
_widths['l'] = 0.15
_glyphs['l'] = shape
shape = rectangle(0, 0.1, 0, 1)
shape |= rectangle(0.7, 0.8, 0, 1)
shape |= triangle(0, 1, 0.1, 1, 0.45, 0)
shape |= triangle(0.45, 0, 0.35, 0, 0, 1)
shape |= triangle(0.7, 1, 0.8, 1, 0.35, 0)
shape |= triangle(0.35, 0, 0.8, 1, 0.45, 0)
_widths['M'] = 0.8
_glyphs['M'] = shape
shape = circle(0.175, 0.35, 0.175) & ~circle(0.175, 0.35, 0.075)
shape |= circle(0.425, 0.35, 0.175) & ~circle(0.425, 0.35, 0.075)
shape &= rectangle(0, 0.65, 0.35, 0.65)
shape |= rectangle(0, 0.1, 0, 0.525)
shape |= rectangle(0.25, 0.35, 0, 0.35)
shape |= rectangle(0.5, 0.6, 0, 0.35)
_widths['m'] = 0.6
_glyphs['m'] = shape
shape = rectangle(0, 0.1, 0, 1)
shape |= rectangle(0.5, 0.6, 0, 1)
shape |= triangle(0, 1, 0.1, 1, 0.6, 0)
shape |= triangle(0.6, 0, 0.5, 0, 0, 1)
_widths['N'] = 0.6
_glyphs['N'] = shape
shape = circle(0.275, 0.275, 0.275)
shape &= ~circle(0.275, 0.275, 0.175)
shape &= rectangle(0, 0.55, 0.325, 0.55)
shape |= rectangle(0, 0.1, 0, 0.55)
shape |= rectangle(0.45, 0.55, 0, 0.325)
_widths['n'] = 0.55
_glyphs['n'] = shape
shape = circle(0.3, 0.7, 0.3) & ~circle(0.3, 0.7, 0.2)
shape |= circle(0.3, 0.3, 0.3) & ~circle(0.3, 0.3, 0.2)
shape &= ~rectangle(0, 0.6, 0.3, 0.7)
shape |= rectangle(0, 0.1, 0.3, 0.7)
shape |= rectangle(0.5, 0.6, 0.3, 0.7)
_widths['O'] = 0.6
_glyphs['O'] = shape
shape = circle(0.275, 0.275, 0.275)
shape &= ~circle(0.275, 0.275, 0.175)
_widths['o'] = 0.55
_glyphs['o'] = shape
shape = circle(0.3, 0.725, 0.275)
shape &= ~circle(0.3, 0.725, 0.175)
shape &= rectangle(0.3, 1, 0, 1)
shape |= rectangle(0, 0.1, 0, 1)
shape |= rectangle(0.1, 0.3, 0.45, 0.55)
shape |= rectangle(0.1, 0.3, 0.9, 1)
_widths['P'] = 0.575
_glyphs['P'] = shape
shape = circle(0.275, 0.275, 0.275)
shape &= ~circle(0.275, 0.275, 0.175)
shape |= rectangle(0, 0.1, -0.375, 0.55)
_widths['p'] = 0.55
_glyphs['p'] = shape
shape = circle(0.3, 0.7, 0.3) & ~circle(0.3, 0.7, 0.2)
shape |= circle(0.3, 0.3, 0.3) & ~circle(0.3, 0.3, 0.2)
shape &= ~rectangle(0, 0.6, 0.3, 0.7)
shape |= rectangle(0, 0.1, 0.3, 0.7)
shape |= rectangle(0.5, 0.6, 0.3, 0.7)
shape |= triangle(0.5, 0.1, 0.6, 0.1, 0.6, 0)
shape |= triangle(0.5, 0.1, 0.5, 0.3, 0.6, 0.1)
_widths['Q'] = 0.6
_glyphs['Q'] = shape
shape = circle(0.275, 0.275, 0.275) & ~circle(0.275, 0.275, 0.175)
shape |= rectangle(0.45, 0.55, -0.375, 0.55)
_widths['q'] = 0.55
_glyphs['q'] = shape
shape = circle(0.3, 0.725, 0.275)
shape &= ~circle(0.3, 0.725, 0.175)
shape &= rectangle(0.3, 1, 0, 1)
shape |= rectangle(0, 0.1, 0, 1)
shape |= rectangle(0.1, 0.3, 0.45, 0.55)
shape |= rectangle(0.1, 0.3, 0.9, 1)
shape |= triangle(0.3, 0.5, 0.4, 0.5, 0.575, 0)
shape |= triangle(0.475, 0.0, 0.3, 0.5, 0.575, 0)
_widths['R'] = 0.575
_glyphs['R'] = shape
shape = circle(0.55, 0, 0.55) & ~scale_x(circle(0.55, 0, 0.45), 0.55, 0.8)
shape &= rectangle(0, 0.55, 0, 0.55)
shape = scale_x(shape, 0, 0.7)
shape |= rectangle(0, 0.1, 0, 0.55)
_widths['r'] = 0.385
_glyphs['r'] = shape
shape = circle(0.275, 0.725, 0.275)
shape &= ~circle(0.275, 0.725, 0.175)
shape &= ~rectangle(0.275, 0.55, 0.45, 0.725)
shape |= reflect_x(reflect_y(shape, 0.5), .275)
_widths['S'] = 0.55
_glyphs['S'] = shape
shape = circle(0.1625, 0.1625, 0.1625)
shape &= ~scale_x(circle(0.165, 0.165, 0.0625), 0.165, 1.5)
shape &= ~rectangle(0, 0.1625, 0.1625, 0.325)
shape |= reflect_x(reflect_y(shape, 0.275), 0.1625)
shape = scale_x(shape, 0, 1.5)
_widths['s'] = 0.4875
_glyphs['s'] = shape
shape = rectangle(0, 0.6, 0.9, 1) | rectangle(0.25, 0.35, 0, 0.9)
_widths['T'] = 0.6
_glyphs['T'] = shape
shape = circle(0.4, 0.25, 0.25) & ~circle(0.4, 0.25, 0.15)
shape &= rectangle(0, 0.4, 0, 0.25)
shape |= rectangle(0, 0.4, 0.55, 0.65)
shape |= rectangle(0.15, 0.25, 0.25, 1)
_widths['t'] = 0.4
_glyphs['t'] = shape
shape = circle(0.3, 0.3, 0.3) & ~circle(0.3, 0.3, 0.2)
shape &= rectangle(0, 0.6, 0, 0.3)
shape |= rectangle(0, 0.1, 0.3, 1)
shape |= rectangle(0.5, 0.6, 0.3, 1)
_widths['U'] = 0.6
_glyphs['U'] = shape
shape = circle(0.275, 0.275, 0.275) & ~circle(0.275, 0.275, 0.175)
shape &= rectangle(0, 0.55, 0, 0.275)
shape |= rectangle(0, 0.1, 0.275, 0.55)
shape |= rectangle(0.45, 0.55, 0, 0.55)
_widths['u'] = 0.55
_glyphs['u'] = shape
shape = triangle(0, 1, 0.1, 1, 0.35, 0)
shape |= triangle(0.35, 0, 0.25, 0, 0, 1)
shape |= reflect_x(shape, 0.3)
_widths['V'] = 0.6
_glyphs['V'] = shape
shape = triangle(0, 0.55, 0.1, 0.55, 0.35, 0)
shape |= triangle(0.35, 0, 0.25, 0, 0, 0.55)
shape |= reflect_x(shape, 0.3)
_widths['v'] = 0.6
_glyphs['v'] = shape
shape = triangle(0, 1, 0.1, 1, 0.25, 0)
shape |= triangle(0.25, 0, 0.15, 0, 0, 1)
shape |= triangle(0.15, 0, 0.35, 1, 0.45, 1)
shape |= triangle(0.45, 1, 0.25, 0, 0.15, 0)
shape |= reflect_x(shape, 0.4)
_widths['W'] = 0.8
_glyphs['W'] = shape
shape = triangle(0, 0.55, 0.1, 0.55, 0.25, 0)
shape |= triangle(0.25, 0, 0.15, 0, 0, 0.55)
shape |= triangle(0.15, 0, 0.35, 0.5, 0.45, 0.5)
shape |= triangle(0.45, 0.5, 0.25, 0, 0.15, 0)
shape |= reflect_x(shape, 0.4)
_widths['w'] = 0.8
_glyphs['w'] = shape
shape = triangle(0, 1, 0.125, 1, 0.8, 0)
shape |= triangle(0.8, 0, 0.675, 0, 0, 1)
shape |= reflect_x(shape, 0.4)
_widths['X'] = 0.8
_glyphs['X'] = shape
shape = triangle(0, 0.55, 0.125, 0.55, 0.55, 0)
shape |= triangle(0.55, 0, 0.425, 0, 0, 0.55)
shape |= reflect_x(shape, 0.275)
_widths['x'] = 0.55
_glyphs['x'] = shape
shape = triangle(0, 1, 0.1, 1, 0.45, 0.5)
shape |= triangle(0.45, 0.5, 0.35, 0.5, 0, 1)
shape |= reflect_x(shape, 0.4)
shape |= rectangle(0.35, 0.45, 0, 0.5)
_widths['Y'] = 0.8
_glyphs['Y'] = shape
shape = triangle(0, 0.55, 0.1, 0.55, 0.325, 0)
shape |= triangle(0.325, 0, 0.225, 0, 0, 0.55)
shape |= reflect_x(shape, 0.275) | move(reflect_x(shape, 0.275), -0.225, -0.55)
shape &= rectangle(0, 0.55, -0.375, 0.55)
_widths['y'] = 0.55
_glyphs['y'] = shape
shape = rectangle(0, 0.6, 0, 1)
shape &= ~triangle(0, 0.1, 0, 0.9, 0.45, 0.9)
shape &= ~triangle(0.6, 0.1, 0.15, 0.1, 0.6, 0.9)
_widths['Z'] = 0.6
_glyphs['Z'] = shape
shape = rectangle(0, 0.6, 0, 0.55)
shape &= ~triangle(0, 0.1, 0, 0.45, 0.45, 0.45)
shape &= ~triangle(0.6, 0.1, 0.15, 0.1, 0.6, 0.45)
_widths['z'] = 0.6
_glyphs['z'] = shape
shape = Shape("f1.0", 0, 0.55, 0, 1)
_widths[' '] = 0.55
_glyphs[' '] = shape
shape = circle(0.075, 0.075, 0.075)
shape = scale_y(shape, 0.075, 3)
shape &= rectangle(0.0, 0.15, -0.15, 0.075)
shape &= ~triangle(0.075, 0.075, 0.0, -0.15, -0.5, 0.075)
shape |= circle(0.1, 0.075, 0.075)
_widths[','] = 0.175
_glyphs[','] = shape
shape = circle(0.075, 0.075, 0.075)
_widths['.'] = 0.15
_glyphs['.'] = shape
shape = rectangle(0, 0.1, 0.55, 0.8)
_widths["'"] = 0.1
_glyphs["'"] = shape
shape = rectangle(0, 0.1, 0.55, 0.8) | rectangle(0.2, 0.3, 0.55, 0.8)
_widths['"'] = 0.3
_glyphs['"'] = shape
shape = circle(0.075, 0.15, 0.075) | circle(0.075, 0.45, 0.075)
_widths[':'] = 0.15
_glyphs[':'] = shape
shape = circle(0.075, 0.15, 0.075)
shape = scale_y(shape, 0.15, 3)
shape &= rectangle(0.0, 0.15, -0.075, 0.15)
shape &= ~triangle(0.075, 0.15, 0.0, -0.075, -0.5, 0.15)
shape |= circle(0.075, 0.45, 0.075)
shape |= circle(0.1, 0.15, 0.075)
_widths[';'] = 0.15
_glyphs[';'] = shape
shape = rectangle(0.025, 0.125, 0.3, 1)
shape |= circle(0.075, 0.075, 0.075)
_widths['!'] = 0.1
_glyphs['!'] = shape
shape = rectangle(0.05, 0.4, 0.35, 0.45)
_widths['-'] = 0.45
_glyphs['-'] = shape
shape = circle(0, 0.4, 0.6) & ~scale_x(circle(0, 0.4, 0.5), 0, 0.7)
shape &= rectangle(0, 0.6, -0.2, 1)
shape = scale_x(shape, 0, 1/2.)
_widths[')'] = 0.3
_glyphs[')'] = shape
shape = circle(0.6, 0.4, 0.6) & ~scale_x(circle(0.6, 0.4, 0.5), 0.6, 0.7)
shape &= rectangle(0, 0.6, -0.2, 1)
shape = scale_x(shape, 0, 1/2.)
_widths['('] = 0.3
_glyphs['('] = shape
shape = rectangle(0, 0.3, 0, 1)
shape &= ~circle(0, 1, 0.2)
shape &= ~rectangle(0, 0.2, 0, 0.7)
_widths['1'] = 0.3
_glyphs['1'] = shape
shape = circle(0.275, .725, .275)
shape &= ~circle(0.275, 0.725, 0.175)
shape &= ~rectangle(0, 0.55, 0, 0.725)
shape |= rectangle(0, 0.55, 0, 0.1)
shape |= triangle(0, 0.1, 0.45, 0.775, 0.55, 0.725)
shape |= triangle(0, 0.1, 0.55, 0.725, 0.125, 0.1)
_widths['2'] = 0.55
_glyphs['2'] = shape
shape = circle(0.3, 0.725, 0.275)
shape &= ~circle(0.3, 0.725, 0.175)
shape |= circle(0.3, 0.275, 0.275)
shape &= ~circle(0.3, 0.275, 0.175)
shape &= ~rectangle(0, 0.275, 0.275, 0.725)
_widths['3'] = 0.55
_glyphs['3'] = shape
shape = triangle(-0.10, 0.45, 0.4, 1, 0.4, 0.45)
shape |= rectangle(0.4, 0.5, 0, 1)
shape &= ~triangle(0.4, 0.85, 0.4, 0.55, 0.1, 0.55)
shape &= rectangle(0, 0.5, 0, 1)
_widths['4'] = 0.5
_glyphs['4'] = shape
shape = circle(0.325, 0.325, 0.325) & ~circle(0.325, 0.325, 0.225)
shape &= ~rectangle(0, 0.325, 0.325, 0.65)
shape |= rectangle(0, 0.325, 0.55, 0.65)
shape |= rectangle(0, 0.1, 0.55, 1)
shape |= rectangle(0.1, 0.65, 0.9, 1)
_widths['5'] = 0.65
_glyphs['5'] = shape
shape = circle(0.275, 0.725, 0.275) & ~scale_y(circle(0.275, 0.725, 0.175), .725, 1.2)
shape &= rectangle(0, 0.55, 0.725, 1)
shape &= ~triangle(0.275, 0.925, 0.55, 0.9, 0.55, 0.725)
shape = scale_y(shape, 1, 2)
shape = scale_x(shape, 0, 1.1)
shape &= ~rectangle(0.275, 0.65, 0., 0.7)
shape |= rectangle(0, 0.1, 0.275, 0.45)
shape |= circle(0.275, 0.275, 0.275) & ~circle(0.275, 0.275, 0.175)
_widths['6'] = 0.55
_glyphs['6'] = shape
shape = rectangle(0, 0.6, 0.9, 1)
shape |= triangle(0, 0, 0.475, 0.9, 0.6, 0.9)
shape |= triangle(0, 0, 0.6, 0.9, 0.125, 0)
_widths['7'] = 0.6
_glyphs['7'] = shape
shape = circle(0.3, 0.725, 0.275)
shape &= ~circle(0.3, 0.725, 0.175)
shape |= circle(0.3, 0.275, 0.275)
shape &= ~circle(0.3, 0.275, 0.175)
_widths['8'] = 0.55
_glyphs['8'] = shape
shape = reflect_x(reflect_y(_glyphs['6'], 0.5), _widths['6']/2)
_widths['9'] = _widths['6']
_glyphs['9'] = shape
shape = circle(0.5, 0.5, 0.5) & ~scale_x(circle(0.5, 0.5, 0.4), 0.5, 0.7**0.5)
shape = | |
Client, domain: str, base_score: int) -> int:
"""Analyzing premium subscription.
Args:
client: a client with relationship commands.
domain: the domain to check
base_score: the base score from basic analysis
Returns:
score calculated by relationship.
"""
return self.analyze_premium_scores(
domain,
base_score,
[
client.get_domain_communicating_files,
client.get_url_downloaded_files,
client.get_url_referrer_files
]
)
def analyze_premium_ip_score(self, client: Client, ip: str, base_score: int) -> int:
"""Analyzing premium subscription.
Args:
client: a client with relationship commands.
ip: the ip to check
base_score: the base score from basic analysis
Returns:
score calculated by relationship.
"""
return self.analyze_premium_scores(
ip,
base_score,
[
client.get_ip_communicating_files,
client.get_ip_downloaded_files,
client.get_ip_referrer_files
]
)
# endregion
# region Helper functions
def create_relationships(entity_a: str, entity_a_type: str, relationships_response: dict, reliability):
"""
Create a list of entityRelationship object from the api result
entity_a: (str) - source of the relationship
entity_a_type: (str) - type of the source of the relationship
relationships_response: (dict) - the relationship response from the api
reliability: The reliability of the source.
Returns a list of EntityRelationship objects.
"""
relationships_list: List[EntityRelationship] = []
for relationship_type, relationship_type_raw in relationships_response.items():
relationships_data = relationship_type_raw.get('data', [])
if relationships_data:
if isinstance(relationships_data, dict):
relationships_data = [relationships_data]
for relation in relationships_data:
name = RELATIONSHIP_TYPE.get(entity_a_type.lower(), {}).get(relationship_type)
entity_b = relation.get('id', '')
entity_b_type = INDICATOR_TYPE.get(relation.get('type', '').lower())
if entity_b and entity_b_type and name:
if entity_b_type == FeedIndicatorType.URL:
entity_b = dict_safe_get(relation, ['context_attributes', 'url'])
relationships_list.append(
EntityRelationship(entity_a=entity_a, entity_a_type=entity_a_type, name=name,
entity_b=entity_b, entity_b_type=entity_b_type, source_reliability=reliability,
brand=INTEGRATION_NAME))
else:
demisto.info(
f"WARNING: Relationships will not be created to entity A {entity_a} with relationship name {name}")
return relationships_list
def arg_to_number_must_int(arg: Any, arg_name: Optional[str] = None, required: bool = False):
"""Wrapper of arg_to_number that must return int
For mypy fixes.
"""
arg_num = arg_to_number(arg, arg_name, required)
assert isinstance(arg_num, int)
return arg_num
def epoch_to_timestamp(epoch: Union[int, str]) -> Optional[str]:
"""Converts epoch timestamp to a string.
Args:
epoch: Time to convert
Returns:
A formatted string if succeeded. if not, returns None.
"""
try:
return datetime.utcfromtimestamp(int(epoch)).strftime("%Y-%m-%d %H:%M:%SZ")
except (TypeError, OSError, ValueError):
return None
def decrease_data_size(data: Union[dict, list]) -> Union[dict, list]:
""" Minifying data size.
Args:
data: the data object from raw response
Returns:
the same data without:
data['attributes']['last_analysis_results']
data['attributes']['pe_info']
data['attributes']['crowdsourced_ids_results']
data['attributes']['autostart_locations']
data['attributes']['sandbox_verdicts']
data['attributes']['sigma_analysis_summary']
"""
attributes_to_remove = [
'last_analysis_results', 'pe_info', 'crowdsourced_ids_results', 'autostart_locations', 'sandbox_verdicts',
'sigma_analysis_summary'
]
if isinstance(data, list):
data = [decrease_data_size(item) for item in data]
else:
for attribute in attributes_to_remove:
try:
del data['attributes'][attribute]
except KeyError:
pass
return data
def build_domain_output(
client: Client,
score_calculator: ScoreCalculator,
domain: str,
raw_response: dict,
extended_data: bool):
data = raw_response.get('data', {})
attributes = data.get('attributes', {})
relationships_response = data.get('relationships', {})
whois: defaultdict = get_whois(attributes.get('whois', ''))
score = score_calculator.domain_score(domain, raw_response)
if score != Common.DBotScore.BAD and client.is_premium:
score = score_calculator.analyze_premium_domain_score(client, domain, score)
logs = score_calculator.get_logs()
demisto.debug(logs)
relationships_list = create_relationships(entity_a=domain, entity_a_type=FeedIndicatorType.Domain,
relationships_response=relationships_response,
reliability=client.reliability)
domain_indicator = Common.Domain(
domain=domain,
name_servers=whois['Name Server'],
creation_date=whois['Creation Date'],
updated_date=whois['Updated Date'],
expiration_date=whois['Registry Expiry Date'],
admin_name=whois['Admin Organization'],
admin_email=whois['Admin Email'],
admin_country=whois['Admin Country'],
registrant_email=whois['Registrant Email'],
registrant_country=whois['Registrant Country'],
registrar_name=whois['Registrar'],
registrar_abuse_email=whois['Registrar Abuse Contact Email'],
registrar_abuse_phone=whois['Registrar Abuse Contact Phone'],
dbot_score=Common.DBotScore(
domain,
DBotScoreType.DOMAIN,
INTEGRATION_NAME,
score=score,
malicious_description=logs,
reliability=client.reliability
),
relationships=relationships_list
)
if not extended_data:
data = decrease_data_size(data)
attributes = data.get('attributes', {})
return CommandResults(
outputs_prefix=f'{INTEGRATION_ENTRY_CONTEXT}.Domain',
outputs_key_field='id',
indicator=domain_indicator,
readable_output=tableToMarkdown(
f'Domain data of {domain}',
{
'last_modified': epoch_to_timestamp(attributes.get('last_modification_date')),
**data,
**whois,
**attributes
},
headers=[
'id',
'Registrant Country',
'last_modified',
'last_analysis_stats'
],
removeNull=True,
headerTransform=underscoreToCamelCase
),
outputs=data,
raw_response=raw_response,
relationships=relationships_list
)
def build_url_output(
client: Client,
score_calculator: ScoreCalculator,
url: str,
raw_response: dict,
extended_data: bool
) -> CommandResults:
data = raw_response.get('data', {})
score = score_calculator.url_score(url, raw_response)
if score != Common.DBotScore.BAD and client.is_premium:
score = score_calculator.analyze_premium_url_score(client, url, score)
logs = score_calculator.get_logs()
demisto.debug(logs)
# creating readable output
attributes = data.get('attributes', {})
last_analysis_stats = attributes.get('last_analysis_stats', {})
relationships_response = data.get('relationships', {})
positive_detections = last_analysis_stats.get('malicious', 0)
detection_engines = sum(last_analysis_stats.values())
relationships_list = create_relationships(entity_a=url, entity_a_type=FeedIndicatorType.URL,
relationships_response=relationships_response,
reliability=client.reliability)
url_indicator = Common.URL(
url,
category=attributes.get('categories'),
detection_engines=detection_engines,
positive_detections=positive_detections,
relationships=relationships_list,
dbot_score=Common.DBotScore(
url,
DBotScoreType.URL,
INTEGRATION_NAME,
score=score,
reliability=client.reliability,
malicious_description=logs
)
)
if not extended_data:
data = decrease_data_size(data)
return CommandResults(
outputs_prefix=f'{INTEGRATION_ENTRY_CONTEXT}.URL',
outputs_key_field='id',
indicator=url_indicator,
readable_output=tableToMarkdown(
f'URL data of "{url}"',
{
**data,
**data.get('attributes', {}),
'url': url,
'positives': f'{positive_detections}/{detection_engines}',
'last_modified': epoch_to_timestamp(attributes.get('last_modification_date'))
},
headers=[
'url',
'title',
'last_modified',
'has_content',
'last_http_response_content_sha256',
'positives',
'reputation'
],
removeNull=True,
headerTransform=underscoreToCamelCase
),
outputs=data,
raw_response=raw_response,
relationships=relationships_list
)
def build_ip_output(client: Client, score_calculator: ScoreCalculator, ip: str, raw_response: dict,
extended_data: bool) -> CommandResults:
score = score_calculator.ip_score(ip, raw_response)
if score != Common.DBotScore.BAD and client.is_premium:
score = score_calculator.analyze_premium_ip_score(client, ip, score)
logs = score_calculator.get_logs()
demisto.debug(logs)
data = raw_response.get('data', {})
attributes = data.get('attributes', {})
relationships_response = data.get('relationships', {})
last_analysis_stats = attributes.get('last_analysis_stats')
positive_engines = last_analysis_stats.get('malicious', 0)
detection_engines = sum(last_analysis_stats.values())
relationships_list = create_relationships(entity_a=ip, entity_a_type=FeedIndicatorType.IP,
relationships_response=relationships_response,
reliability=client.reliability)
ip_indicator = Common.IP(
ip,
asn=attributes.get('asn'),
geo_country=attributes.get('country'),
detection_engines=detection_engines,
positive_engines=positive_engines,
relationships=relationships_list,
dbot_score=Common.DBotScore(
ip,
DBotScoreType.IP,
INTEGRATION_NAME,
score=score,
malicious_description=logs,
reliability=client.reliability
)
)
if not extended_data:
data = decrease_data_size(data)
return CommandResults(
outputs_prefix=f'{INTEGRATION_ENTRY_CONTEXT}.IP',
outputs_key_field='id',
indicator=ip_indicator,
readable_output=tableToMarkdown(
f'IP reputation of {ip}:',
{
**data,
**attributes,
'last_modified': epoch_to_timestamp(attributes.get('last_modification_date')),
'positives': f'{positive_engines}/{detection_engines}'
},
headers=['id', 'network', 'country', 'last_modified', 'reputation', 'positives'],
headerTransform=underscoreToCamelCase
),
outputs=data,
raw_response=raw_response,
relationships=relationships_list
)
def build_file_output(
client: Client,
score_calculator: ScoreCalculator,
file_hash: str,
raw_response: dict,
extended_data: bool
) -> CommandResults:
data = raw_response.get('data', {})
attributes = data.get('attributes')
relationships_response = data.get('relationships', {})
score = score_calculator.file_score(file_hash, raw_response)
logs = score_calculator.get_logs()
demisto.debug(logs)
signature_info = attributes.get('signature_info', {})
exiftool = attributes.get('exiftool', {})
relationships_list = create_relationships(entity_a=file_hash, entity_a_type=FeedIndicatorType.File,
relationships_response=relationships_response,
reliability=client.reliability)
file_indicator = Common.File(
dbot_score=Common.DBotScore(
file_hash,
DBotScoreType.FILE,
integration_name=INTEGRATION_NAME,
score=score,
malicious_description=logs,
reliability=client.reliability
),
name=exiftool.get('OriginalFileName'),
size=attributes.get('size'),
sha1=attributes.get('sha1'),
sha256=attributes.get('sha256'),
file_type=exiftool.get('MIMEType'),
md5=attributes.get('md5'),
ssdeep=attributes.get('ssdeep'),
extension=exiftool.get('FileTypeExtension'),
company=exiftool.get('CompanyName'),
product_name=exiftool.get('ProductName'),
tags=attributes.get('tags'),
signature=Common.FileSignature(
authentihash=attributes.get('authentihash'),
copyright=signature_info.get('copyright'),
file_version=signature_info.get('file version'),
description=signature_info.get('description'),
internal_name=signature_info.get('internal name'),
original_name=signature_info.get('original name')
),
relationships=relationships_list
)
if not extended_data:
data = decrease_data_size(data)
last_analysis_stats = attributes.get("last_analysis_stats", {})
malicious = last_analysis_stats.get('malicious', 0)
total = sum(last_analysis_stats.values())
return CommandResults(
outputs_prefix=f'{INTEGRATION_ENTRY_CONTEXT}.File',
outputs_key_field='id',
indicator=file_indicator,
readable_output=tableToMarkdown(
f'Results of file hash {file_hash}',
{
**data,
**attributes,
'positives': f'{malicious}/{total}',
'creation date': epoch_to_timestamp(attributes.get('creation_date')),
'last modified': epoch_to_timestamp(attributes.get('last_modification_date', 0))
},
headers=[
'sha1', 'sha256', 'md5',
'meaningful_name', 'type_extension', 'creation date',
'last modified', 'reputation', 'positives'
],
removeNull=True,
headerTransform=underscoreToCamelCase
),
outputs=data,
raw_response=raw_response,
relationships=relationships_list
)
def get_whois(whois_string: str) -> defaultdict:
"""Gets a WHOIS string and returns a parsed dict of the WHOIS String.
Args:
whois_string: whois from domain api call
Returns:
A parsed whois
Examples:
>>> get_whois('key1:value\\nkey2:value2')
defaultdict({'key1': 'value', 'key2': 'value2'})
"""
whois: defaultdict = defaultdict(lambda: None)
for line in whois_string.splitlines():
key: str
value: str
try:
key, value = line.split(sep=':', maxsplit=1)
except ValueError:
demisto.debug(f'Could not unpack Whois string: {line}. Skipping')
continue
key = key.strip()
value = value.strip()
if key in whois:
if not isinstance(whois[key], list):
whois[key] = [whois[key]]
whois[key].append(value)
else:
whois[key] = value
return whois
def get_file_context(entry_id: str) -> dict:
"""Gets a File object from context.
Args:
entry_id: The entry ID of the file
Returns:
File object contains Name, Hashes and more information
"""
context = demisto.dt(demisto.context(), f'File(val.EntryID === "{entry_id}")')
if not context:
return {}
if isinstance(context, list):
return context[0]
return context
def raise_if_ip_not_valid(ip: str):
"""Raises an error if ip is not valid
Args:
ip: ip address
Raises:
ValueError: If IP is not valid
Examples:
>>> raise_if_ip_not_valid('not ip at all')
Traceback (most recent call last):
...
ValueError: IP "not ip at all" is not valid
>>> raise_if_ip_not_valid('8.8.8.8')
"""
if not is_ip_valid(ip, accept_v6_ips=True):
raise ValueError(f'IP "{ip}" is not valid')
def raise_if_hash_not_valid(file_hash: str):
"""Raises an error if file_hash is not valid
Args:
file_hash: file hash
Raises:
ValueError: if hash is not of type SHA-256, SHA-1 or MD5
Examples:
>>> raise_if_hash_not_valid('not a hash')
Traceback (most recent call last):
...
ValueError: Hash "not a hash" is not of type SHA-256, SHA-1 or MD5
>>> raise_if_hash_not_valid('7e641f6b9706d860baf09fe418b6cc87')
"""
if get_hash_type(file_hash) not in ('sha256', 'sha1', 'md5'):
raise ValueError(f'Hash "{file_hash}" is not of type SHA-256, SHA-1 or MD5')
def encode_url_to_base64(url: str) -> str:
"""Gets a string (in this case, url but it can not be) and return it as base64 without padding ('=')
Args:
url: A string to encode
Returns:
Base64 encoded string with no padding
Examples:
>>> encode_url_to_base64('https://example.com')
'aHR0cHM6Ly9leGFtcGxlLmNvbQ'
"""
return base64.urlsafe_b64encode(url.encode()).decode().strip('=')
def merge_two_dicts(dict_a, dict_b):
merged_dict = dict_a.copy()
merged_dict.update(dict_b)
return merged_dict
# endregion
# region Reputation commands
def ip_command(client: Client, score_calculator: ScoreCalculator, args: dict, relationships: str) -> List[CommandResults]:
"""
1 API Call for regular
1-4 API Calls for premium subscriptions
"""
ips = argToList(args['ip'])
results: List[CommandResults] = list()
for ip in ips:
raise_if_ip_not_valid(ip)
try:
raw_response = client.ip(ip, relationships)
except Exception as exception:
# If anything happens, just keep going
demisto.debug(f'Could not process IP: "{ip}"\n {str(exception)}')
continue
results.append(
build_ip_output(client, score_calculator, ip, raw_response, argToBoolean(args.get('extended_data')))
)
return results
def file_command(client: Client, score_calculator: ScoreCalculator, args: dict, relationships: str) -> List[CommandResults]:
"""
1 API Call
"""
files | |
tilts when calculating wavefront RMS
orig_modestart = self.modestart
if self.modestart < 4:
self.modestart = 4
norm_coeffs = self.norm_array
# once coeffs are normalized, the RMS is simply the sqrt of the sum of the squares of the coefficients
rms = np.sqrt(np.sum(norm_coeffs**2))
self.modestart = orig_modestart
return rms
def pretty_print(self, last=22):
"""
Overload __repr__ to print out coefficients in a nice way including units and descriptive labels.
"""
s = ""
if self.normalized:
s += "Normalized (Noll) Coefficients\n"
else:
s += "Fringe Coefficients\n"
keys = sorted(self.coeffs.keys())
if len(keys) > 0:
for k in keys:
if self._key_to_l(k) <= last:
if k in self.__zernikelabels:
label = self.label(k)
else:
label = ""
if k in self.errorbars:
s += "{0:>4s}: {1:>24s} \t {2:s}".format(
k,
"{0:8.4g} ± {1:5.3g}".format(self.coeffs[k].value, self.errorbars[k]),
label
)
else:
s += "{0:>4s}: {1:>24s} \t {2:s}".format(k, "{0:0.4g}".format(self.coeffs[k]), label)
s += "\n"
s += "\n"
if self._key_to_l(keys[-1]) > last:
hi_orders = ZernikeVector(modestart=last+1, normalized=self.normalized, units=self.units, **self.coeffs)
s += "High Orders RMS: \t {0:0.3g} {1:>3s} ➞ {2:>3s}\n".format(
hi_orders.rms,
self._l_to_key(last+1),
keys[-1]
)
s += "Total RMS: \t {0:0.4g}\n".format(self.rms)
return s
def copy(self):
"""
Make a new ZernikeVector with the same configuration and coefficients
"""
new = ZernikeVector(modestart=self.modestart, normalized=self.normalized, errorbars=copy.deepcopy(self.errorbars),
units=self.units, **self.coeffs)
return new
def save(self, filename="zernike.json"):
"""
Save Zernike vector to JSON format to retain units and normalization info.
"""
outdict = {}
outdict['units'] = self.units.to_string()
outdict['normalized'] = self.normalized
outdict['modestart'] = self.modestart
outdict['errorbars'] = {}
outdict['coeffs'] = {}
for k, c in self.coeffs.items():
outdict['coeffs'][k] = c.value
for k, v in self.errorbars.items():
outdict['errorbars'][k] = v.value
with open(filename, 'w') as f:
json.dump(outdict, f, indent=4, separators=(',', ': '), sort_keys=True)
def load(self, filename="zernike.json"):
"""
Load ZernikeVector data from JSON format.
"""
try:
with open(filename, 'r') as f:
json_data = json.load(f)
except IOError as e:
msg = f"Missing JSON file, {filename}: {e}"
raise ZernikeException(value=msg)
if 'units' in json_data:
self.units = u.Unit(json_data['units'])
if 'normalized' in json_data:
self.normalized = json_data['normalized']
if 'modestart' in json_data:
self.modestart = json_data['modestart']
self.coeffs = {}
if 'coeffs' in json_data:
for k, v in json_data['coeffs'].items():
self.__setitem__(k, v)
self.errorbars = {}
if 'errorbars' in json_data:
for k, v in json_data['coeffs'].items():
self.errorbars[k] = u.Quantity(v, self.units)
def load_lmfit(self, fit_report):
"""
Load information from a lmfit.minimizer.MinimizerResult that is output from a wavefront fit.
If there are reported errorbars, populate those, too.
"""
has_errors = fit_report.errorbars
for k, v in fit_report.params.items():
self.__setitem__(k, v)
if has_errors:
self.errorbars[k] = u.Quantity(v.stderr, self.units)
def label(self, key):
"""
If defined, return the descriptive label for mode, 'key'
"""
if key in self.__zernikelabels:
return self.__zernikelabels[key]
else:
return key
def shortlabel(self, key):
"""
If defined, return the short label for mode, 'key'
"""
if key in self.__shortlabels:
return self.__shortlabels[key]
else:
return key
def from_array(self, coeffs, zmap=None, modestart=None, errorbars=None, normalized=False):
"""
Load coefficients from a provided list/array starting from modestart. Array is assumed to start
from self.modestart if modestart is not provided.
"""
self.normalized = normalized
if errorbars is None or not isinstance(errorbars, dict):
self.errorbars = dict()
else:
self.errorbars = errorbars
if len(coeffs) > 0:
if modestart is None:
modestart = self.modestart
if zmap:
for k in zmap:
mode = self._key_to_l(k)
if mode >= modestart:
self.__setitem__(k, coeffs[zmap[k]])
else:
for i, c in enumerate(coeffs):
key = self._l_to_key(i + modestart)
if c != 0.0:
self.__setitem__(key, c)
def frac_error(self, key=None):
"""
Calculate fractional size of the error bar for mode, key.
"""
err = 0.0
if key is not None and key in self.coeffs and self.coeffs[key].value != 0.0:
err = np.abs(self.errorbars.get(key, 0.0 * self.units).value / self.coeffs[key].value)
return err
def normalize(self):
"""
Normalize coefficients to unit variance for each mode.
"""
if not self.normalized:
self.normalized = True
for k in self.coeffs:
mode = self._key_to_l(k)
noll = noll_coefficient(mode)
self.coeffs[k] /= noll
if k in self.errorbars:
self.errorbars[k] /= noll
def denormalize(self):
"""
Restore normalized coefficients to fringe coefficients.
"""
if self.normalized:
self.normalized = False
for k in self.coeffs:
mode = self._key_to_l(k)
noll = noll_coefficient(mode)
self.coeffs[k] *= noll
if k in self.errorbars:
self.errorbars[k] *= noll
def ignore(self, key):
"""
Set coefficient, key, aside for later recall if needed.
"""
if self._valid_key(key) and key in self.coeffs:
self.ignored[key] = self.coeffs[key]
self.coeffs[key] = 0.0 * self.units
def restore(self, key):
"""
Restore coefficient, key, back into set of coefficients.
"""
if self._valid_key(key) and key in self.ignored:
self.coeffs[key] = self.ignored[key]
del self.ignored[key]
def rotate(self, angle=0.0 * u.deg):
"""
Rotate the ZernikeVector by an angle. Rotation matrix algorithm taken from https://arxiv.org/pdf/1302.7106.pdf.
"""
# this is a hack to extend the vector to the largest supported term to make sure we include everything affected
# by the rotation
self.coeffs['Z99'] = 0.0
a = self.array
ang = u.Quantity(angle, u.rad) # convert angle to radians
# there must be a more concise way to do this, but this makes it clear what's going on
rotm = np.zeros((len(a), len(a)))
for r in np.arange(len(a)):
n_i, m_i = noll_to_zernike(r + self.modestart)
for c in np.arange(len(a)):
n_j, m_j = noll_to_zernike(c + self.modestart)
if n_i != n_j:
rotm[r, c] = 0.0
elif m_i == m_j:
rotm[r, c] = np.cos(m_j * ang)
elif m_i == -m_j and m_i != 0.0:
rotm[r, c] = np.sin(m_j * ang)
elif np.abs(m_i) != np.abs(m_j):
rotm[r, c] = 0.0
else:
rotm[r, c] = 1.0
rot_arr = np.dot(rotm, a)
# this will take back out the zero terms
del self.coeffs['Z99']
# i think it's correct to just pass on the uncertainties unchanged since measurements are done in unrotated space.
# might want to consider handling rotations in the pupil coordinates before doing a fit.
self.from_array(rot_arr, errorbars=self.errorbars)
def total_phase(self, rho, phi):
"""
Calculate total phase displacement at polar coordinates (rho, phi).
"""
phase = 0.0
for k, z in self.coeffs.items():
mode = self._key_to_l(k)
if self.normalized:
norm = noll_coefficient(mode)
else:
norm = 1.0
ph = z * norm * zernike_noll(mode, rho, phi)
phase += ph
return phase
def phase_map(self, n=400):
"""
Calculate a 2D polar map of total phase displacements with sampling of n points along rho and phi vectors.
"""
rho = np.linspace(0.0, 1.0, n)
phi = np.linspace(0, 2*np.pi, n)
[p, r] = np.meshgrid(phi, rho)
x = r * np.cos(p)
y = r * np.sin(p)
ph = self.total_phase(r, p)
return x, y, r, p, ph
def fringe_bar_chart(self, total=True, max_c=2000*u.nm, title=None, last_mode=None):
"""
Plot a bar chart of the fringe amplitudes of the coefficients
"""
# we want to plot bars for each of the modes we usually use and thus label.
label_keys = sorted(self.__zernikelabels.keys())
if last_mode is None:
last_label = self._key_to_l(label_keys[-1])
else:
last_label = last_mode
last_coeff = self._key_to_l(sorted(self.coeffs.keys())[-1])
if last_coeff < 22:
modes = label_keys[3:last_coeff] # ignore piston and tilts in bar plot
else:
modes = label_keys[3:22]
labels = [self.shortlabel(m) for m in modes]
if self.normalized:
coeffs = [self.__getitem__(m).value * noll_coefficient(self._key_to_l(m)) for m in modes]
errorbars = [self.errorbars.get(m, 0.0 * self.units).value * noll_coefficient(self._key_to_l(m)) for m in modes]
else:
coeffs = [self.__getitem__(m).value for m in modes]
errorbars = [self.errorbars.get(m, 0.0 * self.units).value for m in modes]
# lump higher order terms into one RMS bin.
if last_coeff > last_label:
hi_orders = ZernikeVector(modestart=last_label+1, normalized=self.normalized, units=self.units, **self.coeffs)
labels.append("Hi Ord RMS")
coeffs.append(hi_orders.rms.value)
errorbars.append(0.0)
# add total RMS
if total:
labels.append("Total RMS")
coeffs.append(self.rms.value)
errorbars.append(0.0)
max_c = u.Quantity(max_c, self.units).value
cmap = cm.ScalarMappable(col.Normalize(-max_c, max_c), cm.coolwarm_r)
cmap._A = [] # stupid matplotlib
ind = np.arange(len(labels))
fig, ax = plt.subplots(figsize=(11, 5))
fig.set_label("Fringe Wavefront Amplitude per Zernike Mode")
ax.bar(ind, coeffs, color=cmap.to_rgba(coeffs), yerr=errorbars)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.yaxis.grid(color='gray', linestyle='dotted')
ax.xaxis.grid(color='gray', linestyle='dotted', lw=1)
ax.set_axisbelow(True)
ax.set_xticks(ind)
ax.set_xticklabels(labels, rotation=45, ha='right', size='x-small')
ax.set_ylim(-max_c, max_c)
ax.set_ylabel(f"Wavefront Amplitude ({self.units})")
if title is not None:
ax.set_title(title)
cb = fig.colorbar(cmap)
cb.set_label(f"{self.units}")
return fig
def bar_chart(self, residual=None, total=True, max_c=500*u.nm, title=None, last_mode=None):
"""
Plot a bar chart of the coefficients and, optionally, a residual amount not included in the coefficients.
"""
# we want to plot bars for each of the modes we usually use and thus label.
label_keys = sorted(self.__zernikelabels.keys())
if last_mode is None:
last_label = self._key_to_l(label_keys[-1])
else:
last_label = last_mode
last_coeff = self._key_to_l(sorted(self.coeffs.keys())[-1])
if last_coeff < 22:
modes = label_keys[3:last_coeff] # ignore piston and tilts | |
also considering provided entry
# return a (l, ll, e, ee) tuple
# break entries into two groups
# 'node' is a full node that we wish to add 'entry' to
# assume 'entry' is well-formed, i.e. it has an mbr and a node pointer
def splitNode(self, node, entry):
"""
if entry.getChild().getParent() != None:
print entry.getChild() in entry.getChild().getParent().getChildren()
"""
# print "child:", entry.getChild()
# print "full node:", node
"""
if node.getParent() != None:
print "children:", node.getParent().getChildren()
"""
# print "node:", node.toString()
# print "splitting a node"
# prev_leaf_status = node.isLeafNode()
prev_leaf_status = None
# associated with this operation is one for condenseTree
# this line may be unnecessary
# node.setIsLeafNode(False)
curr_node = node
# pick seeds
E_overall = curr_node.getEntries() + [entry]
# print "E_overall:", E_overall
# result = RTree.linearPickSeeds(E_overall)
result = RTree.quadraticPickSeeds(E_overall)
seed_entry1, seed_entry2 = result
parent = curr_node.getParent()
"""
if parent != None:
parent.setIsLeafNode(True)
"""
# if parent != None:
# print "parent has a child:", node in parent.getChildren()
# print "children and entries:", parent.getChildren(), parent.getEntries()
# if parent != None:
# entries = parent.getEntries()
# if parent != None and (node in parent.getChildren()):
"""
if parent != None:
# print node, parent.getChildren()
# print node in parent.getChildren()
parent.removeEntry(parent.retrieveEntryForChild(node))
"""
# possibly questionable
# entry.getChild().setParent(parent)
# print "parent:", parent
# print curr_node == self.getRoot()
# propagating prev_leaf_status may be unnecessary
node1 = RTreeNode(parent, [seed_entry1], prev_leaf_status)
node2 = RTreeNode(parent, [seed_entry2], prev_leaf_status)
# also possibly questionable
# have seed entries in parent
seed_entry1.getChild().setParent(node1)
seed_entry2.getChild().setParent(node2)
# print node
remaining_entries = [x for x in E_overall if x != seed_entry1 and x != seed_entry2]
# print entry in remaining_entries or entry == seed_entry1 or entry == seed_entry2
# error here regarding mbr list; provided entries
curr_overall_mbr1 = CompositeMBR(seed_entry1.getMBR().getUpperLeft(), seed_entry1.getMBR().getLowerRight(), [seed_entry1])
curr_overall_mbr2 = CompositeMBR(seed_entry2.getMBR().getUpperLeft(), seed_entry2.getMBR().getLowerRight(), [seed_entry2])
for i in range(len(remaining_entries)):
curr_entry = remaining_entries[i]
next_curr_node = curr_entry.getChild()
# print curr_entry.getMBR().toString()
# have an error here - num. of remaining entries is not properly decreasing
num_remaining_entries = len(remaining_entries)
curr_mbr = curr_entry.getMBR()
# print curr_mbr.toString()
enlargement1 = MBR.getAreaEnlargement(curr_overall_mbr1, curr_mbr)
enlargement2 = MBR.getAreaEnlargement(curr_overall_mbr2, curr_mbr)
# print enlargement1, enlargement2
m = next_curr_node.getMinimumNumEntriesPerNode()
size1 = len(curr_overall_mbr1.getMBRList())
size2 = len(curr_overall_mbr2.getMBRList())
lambda_entries = num_remaining_entries
# if parent != None:
# parent.removeEntry(curr_entry)
# print "curr. node entries, curr. entry, entry:", curr_node.getEntries(), curr_entry, entry
if curr_entry != entry:
curr_node.removeEntry(curr_entry)
# print "entries for node #1:", [x.getMBR().toString() for x in node1.getEntries()]
# print "entries for node #2:", [x.getMBR().toString() for x in node2.getEntries()]
if size1 == (m - lambda_entries):
curr_overall_mbr1 = MBR.getEnlargedMBR(curr_overall_mbr1, curr_mbr)
node1.addEntry(curr_entry)
next_curr_node.setParent(node1)
continue
if size2 == (m - lambda_entries):
curr_overall_mbr2 = MBR.getEnlargedMBR(curr_overall_mbr2, curr_mbr)
node2.addEntry(curr_entry)
next_curr_node.setParent(node2)
continue
if enlargement1 > enlargement2:
curr_overall_mbr1 = MBR.getEnlargedMBR(curr_overall_mbr1, curr_mbr)
node1.addEntry(curr_entry)
next_curr_node.setParent(node1)
elif enlargement2 > enlargement1:
curr_overall_mbr2 = MBR.getEnlargedMBR(curr_overall_mbr2, curr_mbr)
node2.addEntry(curr_entry)
next_curr_node.setParent(node2)
elif enlargement2 == enlargement1:
if size1 <= size2:
curr_overall_mbr1 = MBR.getEnlargedMBR(curr_overall_mbr1, curr_mbr)
node1.addEntry(curr_entry)
next_curr_node.setParent(node1)
elif size1 > size2:
# print curr_entry.getMBR().toString()
curr_overall_mbr2 = MBR.getEnlargedMBR(curr_overall_mbr2, curr_mbr)
node2.addEntry(curr_entry)
next_curr_node.setParent(node2)
# next_parent = node.getParent()
# print parent, next_parent
if parent != None:
# print node, parent.getChildren()
# print node in parent.getChildren()
parent.removeEntry(parent.retrieveEntryForChild(node))
# print "parent children and node:", parent.getChildren(), node
# print "removed"
# nodes with composite mbr's
entry1 = RTreeEntry(curr_overall_mbr1, node1)
entry2 = RTreeEntry(curr_overall_mbr2, node2)
if node != self.getRootEntry().getChild():
# entry.getChild().setParent(parent)
# print parent.getChildren(), node
# entry_for_removal = parent.retrieveEntryForChild(node)
# parent.removeEntry(entry_for_removal)
parent.addEntry(entry1)
parent.addEntry(entry2)
# parent.addEntry(e)
# parent.addEntry(ee)
node1.setParent(parent)
node2.setParent(parent)
# node1.setParent(parent)
# print "node #1:", node1.toString()
# print "node #2:", node2.toString()
# node2.setParent(parent)
# print "parent again:", parent
else:
next_root = RTreeNode(None, [entry1, entry2], False)
self.getRootEntry().setChild(next_root)
# this causes problems
# entry.getChild().setParent(next_root)
node1.setParent(next_root)
node2.setParent(next_root)
"""
if node.getParent() != None:
print node in node.getParent().getChildren()
"""
return (node1, node2, entry1, entry2)
# adjustTree modifies parents so that their mbr's
# are enlarged and the nodes are possibly split
# with the two resulting pieces being added
# to parent's entry list
# consider whether mbr's for a group have changed
# returns an (ended_with_split, [resulting_first_entry_from_split, resulting_second_entry_from_split?]) tuple
# ended_with_split tells us whether adjustTree ended by splitting a node that is root of a subtree
"""
# also, when taken w.r.t. an operation that ends with root, ended_with_split is pre-emptive
"""
# resulting_entries_from_split give us two entries that are to be children of current node
# resulting_second_entry_from_split can be omitted
@staticmethod
def adjustTree(tree, node, resulting_entries_from_split, have_resulting_second_entry_from_split, is_first_call_after_first_pass):
# if node == tree.getRootEntry().getChild():
if node.getParent() == None:
# no parent to speak of
# print "reach root case"
# return (False, [])
entry = tree.getRootEntry()
curr_entries = entry.getChild().getEntries()
children = [x.getChild() for x in curr_entries]
mbr_list = [x.getMBR() for x in curr_entries]
tight_overall_mbr = CompositeMBR.makeMBR(mbr_list)
entry.setMBR(tight_overall_mbr)
return (have_resulting_second_entry_from_split, resulting_entries_from_split)
else:
parent = node.getParent()
curr_entries = node.getEntries()
entry = None
# print "parent:", parent
"""
if node.getParent() == None:
entry = tree.getRootEntry()
else:
entry = node.getParent().retrieveEntryForChild(node)
"""
entry = parent.retrieveEntryForChild(node)
children = [x.getChild() for x in curr_entries]
mbr_list = [x.getMBR() for x in curr_entries]
tight_overall_mbr = CompositeMBR.makeMBR(mbr_list)
entry.setMBR(tight_overall_mbr)
# set N, NN
# if N is root, stop
# let P be parent of N
# let E_N be N's entry in P
# adjust E_N.I so that it tightly encloses all entry rectangles in N
# if N has partner NN resulting from an earlier split,
# create a new entry E_NN with E_NN.p pointing to NN
# and E_NN.I enclosing all rectangles in NN
partner_entry = None
if have_resulting_second_entry_from_split == True:
first_entry, second_entry = resulting_entries_from_split
partner_entry = second_entry
# if have_resulting_second_entry_from_split == True and is_first_call_after_first_pass != True:
if have_resulting_second_entry_from_split == True:
partner_node = partner_entry.getChild()
partner_entries = partner_node.getEntries()
partner_children = [x.getChild() for x in partner_entries]
partner_mbr_list = [x.getMBR() for x in partner_entries]
partner_tight_overall_mbr = CompositeMBR.makeMBR(partner_mbr_list)
partner_entry.setMBR(partner_tight_overall_mbr)
# add E_NN to P if there is room
# otherwise, invoke SplitNode to produce P and PP
# containing E_NN and all P's old entries
# set N to P and set NN to PP if a split occurred, repeat from AT2
if node.isLeafNode() == False:
if have_resulting_second_entry_from_split == True:
# parent.removeEntry(entry)
"""
index = parent.getIndexForEntry(entry)
parent.removeIthEntry(index)
"""
# if parent.isFull() == False:
if (parent.getNumChildren() + 1) <= parent.getMaximumNumEntriesPerNode():
# parent.addEntry(entry)
parent.addEntry(partner_entry)
# entry.getChild().setParent(parent)
partner_entry.getChild().setParent(parent)
return RTree.adjustTree(tree, node.getParent(), [entry], False, False)
else:
# ought to split
parent.addEntry(entry)
entry.getChild().setParent(parent)
# following is a risky choice
split_result = tree.splitNode(parent, partner_entry)
l, ll, e, ee = split_result
return RTree.adjustTree(tree, node.getParent(), [e, ee], True, False)
else:
return RTree.adjustTree(tree, node.getParent(), [entry], False, False)
else:
return RTree.adjustTree(tree, node.getParent(), resulting_entries_from_split,
have_resulting_second_entry_from_split, False)
# note that we do not have to update mbr for parent anymore
# given that a split changes how mbrs are organized,
# but the elements are not changed
# don't care about parent overall mbr
# until we recursively call adjustTree on parent
# update all MBRs in the path from the root to L,
# so that all of them cover E.mbr
# update the MBRs of nodes that are in the path from root to L, so as to cover L1 and accommodate L2
# perform splits at the upper levels if necessary
# assume item is in tree
# returns a node, which can be None if no match is found
# finds one match if such a node exists
# def delete(self, E, RN):
def findLeaf(self, entry):
return self.findLeafHelper(entry, self.getRootEntry())
def findLeafHelper(self, entry, curr_entry):
"""
if node.isLeafNode() == False:
curr_mbr = entry.getMBR()
entries = self.getEntries()
tagged_mbr_list = [(x.getMBR(), x) for x in entries]
tagged_overlapped_mbr_list = [x for x in tagged_mbr_list if MBR.doOverlap(curr_mbr, x[0]) == True]
for tagged_overlapped_mbr in tagged_overlapped_mbr_list:
curr_mbr, curr_entry = tagged_overlapped_mbr
curr_node = curr_entry.getChild()
result = self.findLeafHelper(entry, curr_node)
if result == None:
continue
else:
return curr_node
return None
"""
# a little stilted since we don't need a O(log(n)) time operation
# to find the entry containing node; just look at parent of entry child
if curr_entry.getMBR().isRaw() == True:
if entry == | |
import sys
import os
import shutil
import gzip
import json
import requests
import uuid
import subprocess
import argparse
import time
from concurrent.futures import ThreadPoolExecutor
from random import randint, choices
from tqdm import tqdm
from zipfile import ZipFile
# support for S3
import S3
# support for SWIFT object storage
import swift
#from google.cloud import storage
import urllib3
# logging
import logging
import logging.handlers
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
logging.getLogger("urllib3").setLevel(logging.ERROR)
logging.getLogger("keystoneclient").setLevel(logging.ERROR)
logging.getLogger("swiftclient").setLevel(logging.ERROR)
# public access base for google cloud storage
gcs_base = "https://storage.googleapis.com/arxiv-dataset/arxiv/"
import pickle
import lmdb
# init LMDB
map_size = 200 * 1024 * 1024 * 1024
class ArXivHarvester(object):
def __init__(self, config):
self.config = config
self._init_lmdb()
self.s3 = None
if "bucket_name" in self.config and len(self.config["bucket_name"].strip()) > 0:
self.s3 = S3.S3(self.config)
self.swift = None
if "swift" in self.config and len(self.config["swift"])>0 and "swift_container" in self.config and len(self.config["swift_container"])>0:
self.swift = swift.Swift(self.config)
def _init_lmdb(self):
# create the data path if it does not exist
if not os.path.isdir(self.config["data_path"]):
try:
os.makedirs(self.config["data_path"])
except OSError:
logging.exception("Creation of the directory %s failed" % self.config["data_path"])
else:
logging.debug("Successfully created the directory %s" % self.config["data_path"])
# open in write mode
envFilePath = os.path.join(self.config["data_path"], 'entries')
self.env = lmdb.open(envFilePath, map_size=map_size)
def harvest(self, metadata_file):
if 'batch_size' in self.config:
batch_size_pdf = self.config['batch_size']
else:
batch_size_pdf = 10
if metadata_file is None or not os.path.isfile(metadata_file):
raise("the provided metadata file is not valid")
if not metadata_file.endswith(".zip") and not metadata_file.endswith(".json.gz") and not metadata_file.endswith(".json"):
raise("the metadata file must be a jsonl file, or a zipped or gziped jsonl file")
file_in = _get_json_file_reader(metadata_file, 'rb')
# check the overall number of entries based on the line number
print("\ncalculating number of entries...")
count = 0
while 1:
buffer = file_in.read(8192*1024)
if not buffer: break
count += buffer.count(b'\n')
print("total entries found: " + str(count) + "\n")
logging.info("total entries found: " + str(count))
file_in.close()
# iterate through the jsonl file
file_in = _get_json_file_reader(metadata_file, 'r')
i = 0
entries = []
for line in tqdm(file_in, total=count):
if i == batch_size_pdf:
result = self.processBatch(entries)
entries = []
i = 0
entry = json.loads(line)
if 'id' not in entry:
logging.info("entry without arxiv id, skipping...")
continue
arxiv_id = entry['id']
versions = _get_versions(entry)
# google cloud public access: gs://arxiv-dataset/arxiv/arxiv/pdf/0906/0906.5594v2.pdf
# public web access, preferred: http://storage.googleapis.com/arxiv-dataset/arxiv/
found = False
for version in versions:
# check if document and version are already processed
with self.env.begin() as txn:
local_object = txn.get(arxiv_id.encode(encoding='UTF-8'))
if local_object != None:
local_entry = _deserialize_pickle(local_object)
if local_entry != None:
if "version" in local_entry and local_entry["version"] == version:
found = True
break
if found:
continue
entries.append(entry)
i += 1
# we need to process the latest incomplete batch (if not empty)
if len(entries) >0:
result = self.processBatch(entries)
dump_destination = os.path.join(self.config["data_path"], "arxiv_list.json")
self.dump_map(dump_destination)
def processBatch(self, entries):
with ThreadPoolExecutor(max_workers=12) as executor:
results = executor.map(self.process_entry, entries, timeout=60)
return "success"
def process_entry(self, entry):
arxiv_id = entry['id']
versions = _get_versions(entry)
# google cloud public access: gs://arxiv-dataset/arxiv/arxiv/pdf/0906/0906.5594v2.pdf
# public web access, preferred: http://storage.googleapis.com/arxiv-dataset/arxiv/
collection, prefix, number = _generate_storage_components(arxiv_id)
if collection == 'arxiv':
full_number = prefix+"."+number
else:
full_number = prefix+number
# temporary place to download the file
destination_pdf = os.path.join(self.config["data_path"], full_number + ".pdf")
latest_version = None
for version in versions:
pdf_location = gcs_base + collection + '/pdf/' + prefix + "/" + full_number + version + ".pdf"
destination_pdf = os.path.join(self.config["data_path"], full_number + ".pdf")
# note: destination file nanme can change if compression is true in config
#print(pdf_location)
destination_pdf = self.download_file(pdf_location, destination_pdf, compression=self.config["compression"])
if destination_pdf is not None:
latest_version = version
break
if destination_pdf is None:
# if PDF not found, look for a ps file
version = versions[0]
ps_location = gcs_base + collection + '/ps/' + prefix + "/" + full_number + version + ".ps.gz"
destination_ps = os.path.join(self.config["data_path"], full_number + ".ps.gz")
destination_ps = self.download_file(ps_location, destination_ps, compression=False)
if destination_ps is None:
# if still not found, they are 44 articles in html only
logging.info("Full text article not found for " + arxiv_id + " - it might be available in html only")
destination_pdf = None
else:
latest_version = version
# for convenience, convert .ps.gz into PDF
destination_pdf = os.path.join(self.config["data_path"], arxiv_id + ".pdf")
# first gunzip the ps file
subprocess.check_call(['gunzip', '-f', destination_ps])
destination_ps = destination_ps.replace(".ps.gz", ".ps")
subprocess.check_call(['ps2pdf', destination_ps, destination_pdf])
# clean ps file
try:
if os.path.isfile(destination_ps):
os.remove(destination_ps)
except IOError:
logging.exception("temporary ps file cleaning failed")
if destination_pdf is not None:
if self.config["compression"]:
compression_suffix = ".gz"
try:
if os.path.isfile(destination_pdf):
subprocess.check_call(['gzip', '-f', destination_pdf])
destination_pdf += compression_suffix
except:
logging.error("Error compressing resource files for " + destination_pdf)
if destination_pdf is not None:
# store the pdf file in the selected storage
self.store_file(destination_pdf, arxiv_id)
# update advancement status map
profile = {}
profile['id'] = arxiv_id
profile['version'] = latest_version
if 'doi' in entry and entry['doi'] != None:
profile['doi'] = entry['doi']
with self.env.begin(write=True) as txn:
txn.put(arxiv_id.encode(encoding='UTF-8'), _serialize_pickle(profile))
# store the metadata file
destination_json = os.path.join(self.config["data_path"], arxiv_id+".json")
with open(destination_json, 'w', encoding='utf-8') as outfile:
json.dump(entry, outfile, ensure_ascii=False)
if self.config["compression"]:
compression_suffix = ".gz"
try:
if os.path.isfile(destination_json):
subprocess.check_call(['gzip', '-f', destination_json])
destination_json += compression_suffix
except:
logging.error("Error compressing resource files for " + destination_json)
self.store_file(destination_json, arxiv_id)
return "success"
def download_file(self, source_url, destination, compression=False, rolling_user_agent=True):
result = "fail"
try:
if rolling_user_agent:
HEADERS = {"""User-Agent""": _get_random_user_agent()}
file_data = requests.get(source_url, allow_redirects=True, headers=HEADERS, verify=False, timeout=30)
else:
file_data = requests.get(source_url, allow_redirects=True, verify=False, timeout=30)
if file_data.status_code == 200:
with open(destination, 'wb') as f_out:
f_out.write(file_data.content)
result = "success"
except Exception:
logging.exception("Download failed for {0} with requests".format(source_url))
if result != "success":
return None
if compression:
compression_suffix = ".gz"
try:
if os.path.isfile(destination):
subprocess.check_call(['gzip', '-f', destination])
destination += compression_suffix
except:
logging.error("Error compressing resource files for " + destination)
return destination
def store_file(self, source, identifier, clean=True):
file_name = os.path.basename(source)
collection, prefix, number = _generate_storage_components(identifier)
if collection == 'arxiv':
full_number = prefix+"."+number
else:
full_number = prefix+number
if self.s3 is not None:
try:
if os.path.isfile(source):
dest_path = os.path.join(collection, prefix, full_number, file_name)
self.s3.upload_file_to_s3(source, dest_path, storage_class='ONEZONE_IA')
except:
logging.error("Error writing on S3 bucket")
elif self.swift is not None:
# to SWIFT object storage, we can do a bulk upload for all the resources associated to the entry
try:
if os.path.isfile(source):
dest_path = os.path.join(collection, prefix, full_number)
self.swift.upload_file_to_swift(source, dest_path)
except:
logging.error("Error writing on SWIFT object storage")
else:
# save under local storate indicated by data_path in the config json
try:
local_dest_path = os.path.join(self.config["data_path"], collection, prefix, full_number)
os.makedirs(local_dest_path, exist_ok=True)
if os.path.isfile(source):
shutil.copyfile(source, os.path.join(local_dest_path, file_name))
except IOError:
logging.exception("invalid path")
# clean stored files
if clean:
try:
if os.path.isfile(source):
os.remove(source)
except IOError:
logging.exception("temporary file cleaning failed")
def dump_map(self, destination):
# init lmdb transactions
with open(destination,'w') as file_out:
with self.env.begin(write=True) as txn:
cursor = txn.cursor()
for key, value in cursor:
if txn.get(key) is None:
continue
map_entry = _deserialize_pickle(txn.get(key))
json_local_entry = json.dumps(map_entry)
file_out.write(json_local_entry)
file_out.write("\n")
if self.config["compression"]:
subprocess.check_call(['gzip', '-f', destination])
destination += ".gz"
# store dump
file_name = os.path.basename(destination)
if self.s3 is not None:
try:
if os.path.isfile(destination):
self.s3.upload_file_to_s3(destination, file_name, storage_class='ONEZONE_IA')
except:
logging.error("Error writing on S3 bucket")
elif self.swift is not None:
# to SWIFT object storage, we can do a bulk upload for all the resources associated to the entry
try:
if os.path.isfile(destination):
self.swift.upload_file_to_swift(destination, file_name)
except:
logging.error("Error writing on SWIFT object storage")
return destination
def diagnostic(self):
with self.env.begin(write=True) as txn:
nb_total = txn.stat()['entries']
print("\nnumber of successfully harvested entries:", nb_total)
def reset(self):
"""
Remove the local lmdb keeping track of the state of advancement of the harvesting and
of the failed entries
"""
# close environments
self.env.close()
envFilePath = os.path.join(self.config["data_path"], 'entries')
shutil.rmtree(envFilePath)
# re-init the environments
self._init_lmdb()
def _get_json_file_reader(filename, mode):
file_in = None
if filename.endswith(".zip"):
with ZipFile(filename, 'r') as zipObj:
list_filenames = zipObj.namelist()
for local_filename in list_filenames:
if local_filename.endswith('.json'):
file_in = zipObj.open(local_filename, mode='r')
break
elif filename.endswith(".gz"):
file_in = gzip.open(filename, mode)
else:
# uncompressed file
file_in = open(filename, mode)
return file_in
def _get_versions(json_entry):
"""
Return version labels ranked from the most recent to the earliest one
"""
versions = []
if "versions" in json_entry:
for version in json_entry["versions"]:
# time indicated by "created" attribute
versions.insert(0, version["version"])
if len(versions) == 0:
# default value
versions.append("v1")
return versions
def _generate_storage_components(identifier):
'''
Convert an arxiv identifier into components for storage path purposes
post-2007 identifier:
arXiv:YYMM.numbervV -> arxiv YYMM number
arXiv:1501.00001v1 -> arXiv 1501 00001
pre-2007 identifiers:
archive.subject_call/YYMMnumber -> archive YYMM number
| |
<reponame>sieniven/spot-it-3d
import cv2
import math
import numpy as np
import time
import queue
from camera_stabilizer import stabilize_frame
from camera_stabilizer import Camera
from filterpy.kalman import KalmanFilter
from filterpy.common import Q_discrete_white_noise
from scipy.spatial import distance
from scipy.optimize import linear_sum_assignment
from automatic_brightness import average_brightness
from object_tracker import imopen
class Track:
def __init__(self, track_id, size):
self.id = track_id
self.size = size
# Constant Velocity Model
self.kalmanFilter = KalmanFilter(dim_x=4, dim_z=2)
# # Constant Acceleration Model
# self.kalmanFilter = KalmanFilter(dim_x=6, dim_z=2)
self.age = 1
self.totalVisibleCount = 1
self.consecutiveInvisibleCount = 0
# Dilates the image multiple times to get of noise in order to get a single large contour for each background object
# Identify background objects by their shape (non-circular)
# Creates a copy of the input image which has the background contour filled in
# Returns the filled image which has the background elements filled in
def remove_ground(im_in, dilation_iterations, background_contour_circularity, frame):
kernel_dilation = np.ones((5, 5), np.uint8)
# Number of iterations determines how close objects need to be to be considered background
dilated = cv2.dilate(im_in, kernel_dilation, iterations=dilation_iterations)
imshow_resized('dilated', dilated)
contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
background_contours = []
for contour in contours:
# Identify background from foreground by the circularity of their dilated contours
circularity = 4 * math.pi * cv2.contourArea(contour) / (cv2.arcLength(contour, True) ** 2)
if circularity <= background_contour_circularity:
background_contours.append(contour)
# This bit is used to find a suitable level of dilation to remove background objects
# while keeping objects to be detected
# im_debug = cv2.cvtColor(im_in.copy(), cv2.COLOR_GRAY2BGR)
im_debug = frame.copy()
cv2.drawContours(im_debug, background_contours, -1, (0, 255, 0), 3)
imshow_resized('to_be_removed', im_debug)
im_out = im_in.copy()
cv2.drawContours(im_out, background_contours, -1, 0, -1)
return im_out
def imshow_resized(window_name, img):
aspect_ratio = img.shape[1] / img.shape[0]
window_size = (int(600), int(600 / aspect_ratio))
img = cv2.resize(img, window_size, interpolation=cv2.INTER_CUBIC)
cv2.imshow(window_name, img)
def downsample_image(img):
aspect_ratio = img.shape[1] / img.shape[0]
img_size = (int(1920), int(1920 / aspect_ratio))
img = cv2.resize(img, img_size, interpolation=cv2.INTER_CUBIC)
return img
def track_objects_realtime(filename):
if filename == 0:
realtime = True
print('Start Video Capture')
else:
realtime = False
cap = cv2.VideoCapture(filename)
global FPS, FRAME_WIDTH, FRAME_HEIGHT, SCALE_FACTOR
FPS = int(cap.get(cv2.CAP_PROP_FPS))
FRAME_WIDTH = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
FRAME_HEIGHT = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
SCALE_FACTOR = math.sqrt(FRAME_WIDTH ** 2 + FRAME_HEIGHT ** 2) / math.sqrt(848 ** 2 + 480 ** 2)
aspect_ratio = FRAME_WIDTH / FRAME_HEIGHT
downsample = False
if FRAME_WIDTH * FRAME_HEIGHT > 1920 * 1080:
downsample = True
FRAME_WIDTH = 1920
FRAME_HEIGHT = int(1920 / aspect_ratio)
SCALE_FACTOR = math.sqrt(FRAME_WIDTH ** 2 + FRAME_HEIGHT ** 2) / math.sqrt(848 ** 2 + 480 ** 2)
# recording = cv2.VideoWriter('recording.mp4', cv2.VideoWriter_fourcc(*'h264'),
# FPS, (FRAME_WIDTH, FRAME_HEIGHT))
out_combined = cv2.VideoWriter('out_real-time.mp4', cv2.VideoWriter_fourcc(*'h264'),
FPS, (FRAME_WIDTH, FRAME_HEIGHT * 2))
camera = Camera((FRAME_WIDTH, FRAME_HEIGHT))
fgbg, detector = setup_system_objects()
next_id = 0
tracks = []
frame = None
frame_before = None
frame_count = 0
fps_log = []
frame_start = time.time()
origin = np.array([0, 0])
consecutive_dropped_frames = 0
max_tolerated_consecutive_dropped_frames = 5
while cap.isOpened():
if realtime:
frame_end = time.time()
frame_time = frame_end - frame_start
if frame_time > 0.001:
fps_log.append(frame_time)
if len(fps_log) > 5:
FPS = 1 / (sum(fps_log) / len(fps_log))
fps_log.pop(0)
ret, frame = cap.read()
frame_start = time.time()
if ret:
print(frame_count)
if downsample:
frame = downsample_image(frame)
# frame, mask = camera.undistort(frame)
mask = np.ones((FRAME_HEIGHT, FRAME_WIDTH), dtype=np.uint8) * 255
if frame_count == 0:
frame_before = frame
elif frame_count >= 1:
# Frame stabilization
stabilized_frame, dx, dy = stabilize_frame(frame_before, frame)
origin[0] -= int(dx)
origin[1] -= int(dy)
frame_before = frame
frame = stabilized_frame
calibration_time = time.time()
# centroids_f, sizes_f, masked = detect_objects(frame, mask, fgbg, detector, origin) # Detect the far & small objects
# centroids = centroids_f
# sizes = sizes_f
centroids_n, sizes_n, masked = detect_objects_large(frame, mask, fgbg, detector,
origin) # Detect the near & big objects
# centroids = np.append(centroids, centroids_n)
# sizes = np.append(sizes, sizes_n)
centroids = centroids_n
sizes = sizes_n
detection_time = time.time()
else: # Failed to read file
if consecutive_dropped_frames >= max_tolerated_consecutive_dropped_frames:
break
else:
consecutive_dropped_frames += 1
# There is no frame, so we make do with the previous frame for visualization
# We still want it as a 3 channel image but in gray
frame = cv2.cvtColor(cv2.cvtColor(frame_before, cv2.COLOR_BGR2GRAY), cv2.COLOR_GRAY2BGR)
# Empty array as the masked image
masked = np.zeros((FRAME_HEIGHT, FRAME_WIDTH), dtype=np.uint8)
# Empty data for detections
centroids = np.zeros((0, 2))
sizes = np.zeros(0)
predict_new_locations_of_tracks(tracks)
prediction_time = time.time()
assignments, unassigned_tracks, unassigned_detections \
= detection_to_track_assignment(tracks, centroids, 10 * SCALE_FACTOR)
assignment_time = time.time()
update_assigned_tracks(assignments, tracks, centroids, sizes)
update_unassigned_tracks(unassigned_tracks, tracks)
tracks = delete_lost_tracks(tracks)
next_id = create_new_tracks(unassigned_detections, next_id, tracks, centroids, sizes)
return_frame = frame.copy()
masked = cv2.cvtColor(masked, cv2.COLOR_GRAY2BGR)
good_tracks = filter_tracks(frame, masked, tracks, frame_count, origin)
other_track_stuff = time.time()
# recording.write(return_frame)
frame_out = np.zeros((FRAME_HEIGHT * 2, FRAME_WIDTH, 3), dtype=np.uint8)
frame_out[0:FRAME_HEIGHT, 0:FRAME_WIDTH] = frame
frame_out[FRAME_HEIGHT:FRAME_HEIGHT * 2, 0:FRAME_WIDTH] = masked
out_combined.write(frame_out)
imshow_resized('frame', frame)
imshow_resized('masked', masked)
display_time = time.time()
print(f"The frame took {(display_time - frame_start) * 1000}ms in total.\n"
f"Camera stabilization took {(calibration_time - frame_start) * 1000}ms.\n"
f"Object detection took {(detection_time - calibration_time) * 1000}ms.\n"
f"Prediction took {(prediction_time - detection_time) * 1000}ms.\n"
f"Assignment took {(assignment_time - prediction_time) * 1000}ms.\n"
f"Other track stuff took {(other_track_stuff - assignment_time) * 1000}ms.\n"
f"Writing to file took {(display_time - other_track_stuff) * 1000}ms.\n\n")
frame_count += 1
if not realtime:
frame_start = False
yield good_tracks, origin, frame_count, return_frame, frame_start
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
# recording.release()
out_combined.release()
cv2.destroyAllWindows()
# Create VideoCapture object to extract frames from,
# background subtractor object and blob detector objects for object detection
# and VideoWriters for output videos
def setup_system_objects():
# Background subtractor works by subtracting the history from the current frame.
# Further more this model already incldues guassian blur and morphological transformations
# varThreshold affects the spottiness of the image. The lower it is, the more smaller spots.
# The larger it is, these spots will combine into large foreground areas
# fgbg = cv2.createBackgroundSubtractorMOG2(history=int(10*FPS), varThreshold=64*SCALE_FACTOR,
# detectShadows=False)
# A lower varThreshold results in more noise which is beneficial to ground subtraction (but detrimental if you want
# detections closer to the ground as there is more noise
fgbg = cv2.createBackgroundSubtractorMOG2(history=int(5 * FPS), varThreshold=16 / SCALE_FACTOR,
detectShadows=False)
# Background ratio represents the fraction of the history a frame must be present
# to be considered part of the background
# eg. history is 5s, background ratio is 0.1, frames present for 0.5s will be considered background
fgbg.setBackgroundRatio(0.05)
fgbg.setNMixtures(5)
# fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows=False)
params = cv2.SimpleBlobDetector_Params()
# params.filterByArea = True
# params.minArea = 1
# params.maxArea = 1000
params.filterByConvexity = False
params.filterByCircularity = False
detector = cv2.SimpleBlobDetector_create(params)
return fgbg, detector
# Apply image masks to prepare frame for blob detection
# Masks: 1) Increased contrast and brightness to fade out the sky and make objects stand out
# 2) Background subtractor to remove the stationary background (Converts frame to a binary image)
# 3) Further background subtraction by means of contouring around non-circular objects
# 4) Dilation to fill holes in detected drones
# 5) Inversion to make the foreground black for the blob detector to identify foreground objects
# Perform the blob detection on the masked image
# Return detected blob centroids as well as size
def detect_objects(frame, mask, fgbg, detector, origin):
# Adjust contrast and brightness of image to make foreground stand out more
# alpha used to adjust contrast, where alpha < 1 reduces contrast and alpha > 1 increases it
# beta used to increase brightness, scale of (-255 to 255) ? Needs confirmation
# formula is im_out = alpha * im_in + beta
# Therefore to change brightness before contrast, we need to do alpha = 1 first
masked = cv2.convertScaleAbs(frame, alpha=1, beta=0)
gain = 15
masked = cv2.convertScaleAbs(masked, alpha=1, beta=256 - average_brightness(16, frame, mask) + gain)
# masked = cv2.convertScaleAbs(masked, alpha=2, beta=128)
# masked = cv2.cvtColor(masked, cv2.COLOR_BGR2GRAY)
# masked = threshold_rgb(frame)
imshow_resized("pre-background subtraction", masked)
# Subtract Background
# Learning rate affects how often the model is updated
# High values > 0.5 tend to lead to patchy output
# Found that 0.1 - 0.3 is a good range
masked = fgbg.apply(masked, learningRate=-1)
imshow_resized("background subtracted", masked)
masked = remove_ground(masked, int(13 / (2.26 / SCALE_FACTOR)), 0.6, frame)
# Morphological Transforms
# Close to remove black spots
# masked = imclose(masked, | |
<filename>flaskbb/management/views.py
# -*- coding: utf-8 -*-
"""
flaskbb.management.views
~~~~~~~~~~~~~~~~~~~~~~~~
This module handles the management views.
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
import logging
import sys
from celery import __version__ as celery_version
from flask import __version__ as flask_version
from flask import (Blueprint, current_app, flash, jsonify, redirect, request,
url_for)
from flask.views import MethodView
from flask_allows import Not, Permission
from flask_babelplus import gettext as _
from flask_login import current_user, login_fresh
from pluggy import HookimplMarker
from flaskbb import __version__ as flaskbb_version
from flaskbb.extensions import allows, celery, db
from flaskbb.forum.forms import UserSearchForm
from flaskbb.forum.models import Category, Forum, Post, Report, Topic
from flaskbb.management.forms import (AddForumForm, AddGroupForm, AddUserForm,
CategoryForm, EditForumForm,
EditGroupForm, EditUserForm)
from flaskbb.management.models import Setting, SettingsGroup
from flaskbb.plugins.models import PluginRegistry, PluginStore
from flaskbb.plugins.utils import validate_plugin
from flaskbb.user.models import Group, Guest, User
from flaskbb.utils.forms import populate_settings_dict, populate_settings_form
from flaskbb.utils.helpers import (get_online_users, register_view,
render_template, time_diff, time_utcnow,
FlashAndRedirect)
from flaskbb.utils.requirements import (CanBanUser, CanEditUser, IsAdmin,
IsAtleastModerator,
IsAtleastSuperModerator)
from flaskbb.utils.settings import flaskbb_config
impl = HookimplMarker('flaskbb')
logger = logging.getLogger(__name__)
class ManagementSettings(MethodView):
decorators = [
allows.requires(
IsAdmin,
on_fail=FlashAndRedirect(
message=_("You are not allowed to access the management settings"), # noqa
level="danger",
endpoint="management.overview"
)
)
]
def _determine_active_settings(self, slug, plugin):
"""Determines which settings are active.
Returns a tuple in following order:
``form``, ``old_settings``, ``plugin_obj``, ``active_nav``
"""
# Any ideas how to do this better?
slug = slug if slug else 'general'
active_nav = {} # used to build the navigation
plugin_obj = None
if plugin is not None:
plugin_obj = PluginRegistry.query.filter_by(name=plugin
).first_or_404()
active_nav.update(
{
'key': plugin_obj.name,
'title': plugin_obj.name.title()
}
)
form = plugin_obj.get_settings_form()
old_settings = plugin_obj.settings
elif slug is not None:
group_obj = SettingsGroup.query.filter_by(key=slug).first_or_404()
active_nav.update({'key': group_obj.key, 'title': group_obj.name})
form = Setting.get_form(group_obj)()
old_settings = Setting.get_settings(group_obj)
return form, old_settings, plugin_obj, active_nav
def get(self, slug=None, plugin=None):
form, old_settings, plugin_obj, active_nav = \
self._determine_active_settings(slug, plugin)
# get all groups and plugins - used to build the navigation
all_groups = SettingsGroup.query.all()
all_plugins = PluginRegistry.query.filter(db.and_(
PluginRegistry.values != None,
PluginRegistry.enabled == True
)).all()
form = populate_settings_form(form, old_settings)
return render_template(
"management/settings.html",
form=form,
all_groups=all_groups,
all_plugins=all_plugins,
active_nav=active_nav
)
def post(self, slug=None, plugin=None):
form, old_settings, plugin_obj, active_nav = \
self._determine_active_settings(slug, plugin)
all_groups = SettingsGroup.query.all()
all_plugins = PluginRegistry.query.filter(db.and_(
PluginRegistry.values != None,
PluginRegistry.enabled == True
)).all()
if form.validate_on_submit():
new_settings = populate_settings_dict(form, old_settings)
if plugin_obj is not None:
plugin_obj.update_settings(new_settings)
else:
Setting.update(settings=new_settings)
flash(_("Settings saved."), "success")
return render_template(
"management/settings.html",
form=form,
all_groups=all_groups,
all_plugins=all_plugins,
active_nav=active_nav
)
class ManageUsers(MethodView):
decorators = [
allows.requires(
IsAtleastModerator,
on_fail=FlashAndRedirect(
message=_("You are not allowed to manage users"),
level="danger",
endpoint="management.overview"
)
)
]
form = UserSearchForm
def get(self):
page = request.args.get('page', 1, type=int)
form = self.form()
users = User.query.order_by(User.id.asc()).paginate(
page, flaskbb_config['USERS_PER_PAGE'], False
)
return render_template(
'management/users.html', users=users, search_form=form
)
def post(self):
page = request.args.get('page', 1, type=int)
form = self.form()
if form.validate():
users = form.get_results().\
paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
return render_template(
'management/users.html', users=users, search_form=form
)
users = User.query.order_by(User.id.asc()).paginate(
page, flaskbb_config['USERS_PER_PAGE'], False
)
return render_template(
'management/users.html', users=users, search_form=form
)
class EditUser(MethodView):
decorators = [
allows.requires(
IsAtleastModerator, CanEditUser,
on_fail=FlashAndRedirect(
message=_("You are not allowed to manage users"),
level="danger",
endpoint="management.overview"
)
)
]
form = EditUserForm
def get(self, user_id):
user = User.query.filter_by(id=user_id).first_or_404()
form = self.form(user)
member_group = db.and_(
* [
db.not_(getattr(Group, p))
for p in ['admin', 'mod', 'super_mod', 'banned', 'guest']
]
)
filt = db.or_(
Group.id.in_(g.id for g in current_user.groups), member_group
)
if Permission(IsAtleastSuperModerator, identity=current_user):
filt = db.or_(filt, Group.mod)
if Permission(IsAdmin, identity=current_user):
filt = db.or_(filt, Group.admin, Group.super_mod)
if Permission(CanBanUser, identity=current_user):
filt = db.or_(filt, Group.banned)
group_query = Group.query.filter(filt)
form.primary_group.query = group_query
form.secondary_groups.query = group_query
return render_template(
'management/user_form.html', form=form, title=_('Edit User')
)
def post(self, user_id):
user = User.query.filter_by(id=user_id).first_or_404()
member_group = db.and_(
* [
db.not_(getattr(Group, p))
for p in ['admin', 'mod', 'super_mod', 'banned', 'guest']
]
)
filt = db.or_(
Group.id.in_(g.id for g in current_user.groups), member_group
)
if Permission(IsAtleastSuperModerator, identity=current_user):
filt = db.or_(filt, Group.mod)
if Permission(IsAdmin, identity=current_user):
filt = db.or_(filt, Group.admin, Group.super_mod)
if Permission(CanBanUser, identity=current_user):
filt = db.or_(filt, Group.banned)
group_query = Group.query.filter(filt)
form = EditUserForm(user)
form.primary_group.query = group_query
form.secondary_groups.query = group_query
if form.validate_on_submit():
form.populate_obj(user)
user.primary_group_id = form.primary_group.data.id
# Don't override the password
if form.password.data:
user.password = form.password.data
user.save(groups=form.secondary_groups.data)
flash(_('User updated.'), 'success')
return redirect(url_for('management.edit_user', user_id=user.id))
return render_template(
'management/user_form.html', form=form, title=_('Edit User')
)
class DeleteUser(MethodView):
decorators = [
allows.requires(
IsAdmin,
on_fail=FlashAndRedirect(
message=_("You are not allowed to manage users"),
level="danger",
endpoint="management.overview"
)
)
]
def post(self, user_id=None):
# ajax request
if request.is_xhr:
ids = request.get_json()["ids"]
data = []
for user in User.query.filter(User.id.in_(ids)).all():
# do not delete current user
if current_user.id == user.id:
continue
if user.delete():
data.append(
{
"id": user.id,
"type": "delete",
"reverse": False,
"reverse_name": None,
"reverse_url": None
}
)
return jsonify(
message="{} users deleted.".format(len(data)),
category="success",
data=data,
status=200
)
user = User.query.filter_by(id=user_id).first_or_404()
if current_user.id == user.id:
flash(_("You cannot delete yourself.", "danger"))
return redirect(url_for("management.users"))
user.delete()
flash(_("User deleted."), "success")
return redirect(url_for("management.users"))
class AddUser(MethodView):
decorators = [
allows.requires(
IsAdmin,
on_fail=FlashAndRedirect(
message=_("You are not allowed to manage users"),
level="danger",
endpoint="management.overview"
)
)
]
form = AddUserForm
def get(self):
return render_template(
'management/user_form.html', form=self.form(), title=_('Add User')
)
def post(self):
form = self.form()
if form.validate_on_submit():
form.save()
flash(_('User added.'), 'success')
return redirect(url_for('management.users'))
return render_template(
'management/user_form.html', form=form, title=_('Add User')
)
class BannedUsers(MethodView):
decorators = [
allows.requires(
IsAtleastModerator,
on_fail=FlashAndRedirect(
message=_("You are not allowed to manage users"),
level="danger",
endpoint="management.overview"
)
)
]
form = UserSearchForm
def get(self):
page = request.args.get('page', 1, type=int)
search_form = self.form()
users = User.query.filter(
Group.banned == True, Group.id == User.primary_group_id
).paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
return render_template(
'management/banned_users.html',
users=users,
search_form=search_form
)
def post(self):
page = request.args.get('page', 1, type=int)
search_form = self.form()
users = User.query.filter(
Group.banned == True, Group.id == User.primary_group_id
).paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
if search_form.validate():
users = search_form.get_results().\
paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
return render_template(
'management/banned_users.html',
users=users,
search_form=search_form
)
return render_template(
'management/banned_users.html',
users=users,
search_form=search_form
)
class BanUser(MethodView):
decorators = [
allows.requires(
IsAtleastModerator,
on_fail=FlashAndRedirect(
message=_("You are not allowed to manage users"),
level="danger",
endpoint="management.overview"
)
)
]
def post(self, user_id=None):
if not Permission(CanBanUser, identity=current_user):
flash(
_("You do not have the permissions to ban this user."),
"danger"
)
return redirect(url_for("management.overview"))
# ajax request
if request.is_xhr:
ids = request.get_json()["ids"]
data = []
users = User.query.filter(User.id.in_(ids)).all()
for user in users:
# don't let a user ban himself and do not allow a moderator
# to ban a admin user
if (current_user.id == user.id or
Permission(IsAdmin, identity=user) and
Permission(Not(IsAdmin), current_user)):
continue
elif user.ban():
data.append(
{
"id":
user.id,
"type":
"ban",
"reverse":
"unban",
"reverse_name":
_("Unban"),
"reverse_url":
url_for("management.unban_user", user_id=user.id)
}
)
return jsonify(
message="{} users banned.".format(len(data)),
category="success",
data=data,
status=200
)
user = User.query.filter_by(id=user_id).first_or_404()
# Do not allow moderators to ban admins
if Permission(IsAdmin, identity=user) and Permission(
Not(IsAdmin), identity=current_user):
flash(_("A moderator cannot ban an admin user."), "danger")
return redirect(url_for("management.overview"))
if not current_user.id == user.id and user.ban():
flash(_("User is now banned."), "success")
else:
flash(_("Could not ban user."), "danger")
return redirect(url_for("management.banned_users"))
class UnbanUser(MethodView):
decorators = [
allows.requires(
IsAtleastModerator,
on_fail=FlashAndRedirect(
message=_("You are not allowed to manage users"),
level="danger",
endpoint="management.overview"
)
)
]
def post(self, user_id=None):
if not Permission(CanBanUser, identity=current_user):
flash(
_("You do not have the permissions to unban this user."),
"danger"
)
return redirect(url_for("management.overview"))
# ajax request
if request.is_xhr:
ids = request.get_json()["ids"]
data = []
for user in User.query.filter(User.id.in_(ids)).all():
if user.unban():
data.append(
{
"id": user.id,
"type": "unban",
"reverse": "ban",
"reverse_name": _("Ban"),
"reverse_url": url_for("management.ban_user",
user_id=user.id)
}
)
return jsonify(
message="{} users unbanned.".format(len(data)),
category="success",
data=data,
status=200
)
user = User.query.filter_by(id=user_id).first_or_404()
if user.unban():
flash(_("User is now unbanned."), "success")
else:
flash(_("Could not unban user."), "danger")
return redirect(url_for("management.banned_users"))
class Groups(MethodView):
decorators = [
allows.requires(
IsAdmin,
on_fail=FlashAndRedirect(
message=_("You are not allowed to modify groups."),
level="danger",
endpoint="management.overview"
)
)
]
def get(self):
page = request.args.get("page", 1, type=int)
groups = Group.query.\
order_by(Group.id.asc()).\
paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
return render_template("management/groups.html", groups=groups)
class AddGroup(MethodView):
decorators = [
allows.requires(
IsAdmin,
on_fail=FlashAndRedirect(
message=_("You are not allowed to modify groups."),
level="danger",
endpoint="management.overview"
)
)
]
form = AddGroupForm
def get(self):
return render_template(
'management/group_form.html',
form=self.form(),
title=_('Add Group')
)
def post(self):
form = AddGroupForm()
if form.validate_on_submit():
form.save()
flash(_('Group added.'), 'success')
return redirect(url_for('management.groups'))
return render_template(
'management/group_form.html', form=form, title=_('Add Group')
)
class EditGroup(MethodView):
decorators = [
allows.requires(
IsAdmin,
on_fail=FlashAndRedirect(
message=_("You are not allowed to modify groups."),
level="danger",
endpoint="management.overview"
)
)
]
form = EditGroupForm
def get(self, group_id):
group = Group.query.filter_by(id=group_id).first_or_404()
form = self.form(group)
return render_template(
'management/group_form.html', form=form, title=_('Edit Group')
)
def post(self, group_id):
group = Group.query.filter_by(id=group_id).first_or_404()
form = EditGroupForm(group)
if form.validate_on_submit():
form.populate_obj(group)
group.save()
if group.guest:
Guest.invalidate_cache()
flash(_('Group updated.'), 'success')
return redirect(url_for('management.groups', group_id=group.id))
return render_template(
'management/group_form.html', form=form, title=_('Edit | |
in Alexa global
'http://www.casadellibro.com/',
# Why: #8495 in Alexa global
'http://www.ixwebhosting.com/',
# Why: #8496 in Alexa global
'http://www.buyorbury.com/',
# Why: #8497 in Alexa global
'http://www.getglue.com/',
# Why: #8498 in Alexa global
'http://www.864321.com/',
# Why: #8499 in Alexa global
'http://www.alivv.com/',
# Why: #8500 in Alexa global
'http://www.4.cn/',
# Why: #8501 in Alexa global
'http://www.competitor.com/',
# Why: #8502 in Alexa global
'http://www.iheima.com/',
# Why: #8503 in Alexa global
'http://www.submarinoviagens.com.br/',
# Why: #8504 in Alexa global
'http://emailsrvr.com/',
# Why: #8505 in Alexa global
'http://www.udacity.com/',
# Why: #8506 in Alexa global
'http://www.mcafeesecure.com/',
# Why: #8507 in Alexa global
'http://www.laposte.fr/',
# Why: #8508 in Alexa global
'http://olhardigital.uol.com.br/',
# Why: #8509 in Alexa global
'http://ppy.sh/',
# Why: #8510 in Alexa global
'http://www.rumah.com/',
# Why: #8511 in Alexa global
'http://www.pullbear.com/',
# Why: #8512 in Alexa global
'http://www.pkt.pl/',
# Why: #8513 in Alexa global
'http://www.jayde.com/',
# Why: #8514 in Alexa global
'http://www.myjoyonline.com/',
# Why: #8515 in Alexa global
'http://www.locopengu.com/',
# Why: #8516 in Alexa global
'http://www.vsnl.net.in/',
# Why: #8517 in Alexa global
'http://www.hornbunny.com/',
# Why: #8518 in Alexa global
'http://www.royalcaribbean.com/',
# Why: #8520 in Alexa global
'http://www.football.ua/',
# Why: #8521 in Alexa global
'http://www.thaifriendly.com/',
# Why: #8522 in Alexa global
'http://www.bankofthewest.com/',
# Why: #8523 in Alexa global
'http://www.indianprice.com/',
# Why: #8524 in Alexa global
'http://www.chodientu.vn/',
# Why: #8525 in Alexa global
'http://www.alison.com/',
# Why: #8526 in Alexa global
'http://www.eveonline.com/',
# Why: #8527 in Alexa global
'http://www.blogg.se/',
# Why: #8528 in Alexa global
'http://www.jetairways.com/',
# Why: #8529 in Alexa global
'http://www.larousse.fr/',
# Why: #8530 in Alexa global
'http://www.noticierodigital.com/',
# Why: #8531 in Alexa global
'http://mkfst.com/',
# Why: #8532 in Alexa global
'http://www.anyfiledownloader.com/',
# Why: #8533 in Alexa global
'http://www.tiramillas.net/',
# Why: #8534 in Alexa global
'http://www.telus.com/',
# Why: #8535 in Alexa global
'http://www.paperblog.com/',
# Why: #8536 in Alexa global
'http://www.songsterr.com/',
# Why: #8537 in Alexa global
'http://www.entremujeres.com/',
# Why: #8538 in Alexa global
'http://www.startsiden.no/',
# Why: #8539 in Alexa global
'http://www.hotspotshield.com/',
# Why: #8540 in Alexa global
'http://www.hosteurope.de/',
# Why: #8541 in Alexa global
'http://www.ebags.com/',
# Why: #8542 in Alexa global
'http://www.eenadupratibha.net/',
# Why: #8543 in Alexa global
'http://www.uppit.com/',
# Why: #8544 in Alexa global
'http://www.piaohua.com/',
# Why: #8545 in Alexa global
'http://www.xxxymovies.com/',
# Why: #8546 in Alexa global
'http://www.netbarg.com/',
# Why: #8547 in Alexa global
'http://www.chip.com.tr/',
# Why: #8548 in Alexa global
'http://xl.co.id/',
# Why: #8549 in Alexa global
'http://www.kowalskypage.com/',
# Why: #8550 in Alexa global
'http://www.afterdawn.com/',
# Why: #8551 in Alexa global
'http://www.locanto.com/',
# Why: #8552 in Alexa global
'http://www.liilas.com/',
# Why: #8553 in Alexa global
'http://www.superboy.com/',
# Why: #8554 in Alexa global
'http://www.indiavisiontv.com/',
# Why: #8555 in Alexa global
'http://www.ixquick.com/',
# Why: #8556 in Alexa global
'http://www.hotelium.com/',
# Why: #8557 in Alexa global
'http://www.twsela.com/',
# Why: #8558 in Alexa global
'http://www.newsmeback.com/',
# Why: #8559 in Alexa global
'http://www.perfectliving.com/',
# Why: #8560 in Alexa global
'http://www.laughingsquid.com/',
# Why: #8561 in Alexa global
'http://www.designboom.com/',
# Why: #8562 in Alexa global
'http://www.zigil.ir/',
# Why: #8563 in Alexa global
'http://www.coachfactory.com/',
# Why: #8564 in Alexa global
'http://www.wst.cn/',
# Why: #8565 in Alexa global
'http://www.kaboodle.com/',
# Why: #8566 in Alexa global
'http://www.fastmail.fm/',
# Why: #8567 in Alexa global
'http://www.threadless.com/',
# Why: #8568 in Alexa global
'http://www.wiseconvert.com/',
# Why: #8569 in Alexa global
'http://www.br.de/',
# Why: #8570 in Alexa global
'http://www.promovacances.com/',
# Why: #8572 in Alexa global
'http://www.wrzuta.pl/',
# Why: #8573 in Alexa global
'http://www.fromdoctopdf.com/',
# Why: #8574 in Alexa global
'http://www.ono.es/',
# Why: #8575 in Alexa global
'http://www.zinio.com/',
# Why: #8576 in Alexa global
'http://netcoc.com/',
# Why: #8577 in Alexa global
'http://www.eanswers.com/',
# Why: #8578 in Alexa global
'http://www.wallst.com/',
# Why: #8579 in Alexa global
'http://www.ipiccy.com/',
# Why: #8580 in Alexa global
'http://www.fastweb.it/',
# Why: #8581 in Alexa global
'http://www.kaufmich.com/',
# Why: #8582 in Alexa global
'http://www.groupon.co.za/',
# Why: #8583 in Alexa global
'http://www.cyzo.com/',
# Why: #8584 in Alexa global
'http://www.addic7ed.com/',
# Why: #8585 in Alexa global
'http://www.liuliangbao.cn/',
# Why: #8586 in Alexa global
'http://www.alintibaha.net/',
# Why: #8587 in Alexa global
'http://www.indiewire.com/',
# Why: #8588 in Alexa global
'http://www.needforspeed.com/',
# Why: #8590 in Alexa global
'http://www.e24.no/',
# Why: #8591 in Alexa global
'http://www.hupso.com/',
# Why: #8592 in Alexa global
'http://www.kathimerini.gr/',
# Why: #8593 in Alexa global
'http://www.worldoffiles.net/',
# Why: #8594 in Alexa global
'http://www.express.pk/',
# Why: #8595 in Alexa global
'http://www.wieszjak.pl/',
# Why: #8597 in Alexa global
'http://www.mobile.bg/',
# Why: #8598 in Alexa global
'http://www.subway.com/',
# Why: #8599 in Alexa global
'http://www.akhbarelyom.com/',
# Why: #8600 in Alexa global
'http://www.thisoldhouse.com/',
# Why: #8601 in Alexa global
'http://www.autoevolution.com/',
# Why: #8602 in Alexa global
'http://www.public-api.wordpress.com/',
# Why: #8603 in Alexa global
'http://www.airarabia.com/',
# Why: #8604 in Alexa global
'http://www.powerball.com/',
# Why: #8605 in Alexa global
'http://www.mais.uol.com.br/',
# Why: #8606 in Alexa global
'http://www.visa.com/',
# Why: #8607 in Alexa global
'http://www.gendai.net/',
# Why: #8608 in Alexa global
'http://www.gymboree.com/',
# Why: #8609 in Alexa global
'http://www.tvp.pl/',
# Why: #8610 in Alexa global
'http://www.sinhayasocialreader.com/',
# Why: #8611 in Alexa global
'http://a963.com/',
# Why: #8612 in Alexa global
'http://www.gamgos.ae/',
# Why: #8613 in Alexa global
'http://www.fx678.com/',
# Why: #8614 in Alexa global
'http://www.mp3round.com/',
# Why: #8615 in Alexa global
'http://www.komonews.com/',
# Why: #8616 in Alexa global
'http://www.contactcars.com/',
# Why: #8617 in Alexa global
'http://www.pdftoword.com/',
# Why: #8618 in Alexa global
'http://www.songtaste.com/',
# Why: #8620 in Alexa global
'http://www.squareup.com/',
# Why: #8621 in Alexa global
'http://www.newsevent24.com/',
# Why: #8622 in Alexa global
'http://www.dti.ne.jp/',
# Why: #8623 in Alexa global
'http://www.livestation.com/',
# Why: #8624 in Alexa global
'http://www.oldertube.com/',
# Why: #8625 in Alexa global
'http://www.rtl.fr/',
# Why: #8626 in Alexa global
'http://www.gather.com/',
# Why: #8627 in Alexa global
'http://www.liderendeportes.com/',
# Why: #8628 in Alexa global
'http://www.thewrap.com/',
# Why: #8629 in Alexa global
'http://www.viber.com/',
# Why: #8630 in Alexa global
'http://www.reklama5.mk/',
# Why: #8631 in Alexa global
'http://www.fonts.com/',
# Why: #8632 in Alexa global
'http://www.hrsaccount.com/',
# Why: #8633 in Alexa global
'http://www.bizcommunity.com/',
# Why: #8634 in Alexa global
'http://www.favicon.cc/',
# Why: #8635 in Alexa global
'http://www.totalping.com/',
# Why: #8636 in Alexa global
'http://www.live365.com/',
# Why: #8637 in Alexa global
'http://www.tlife.gr/',
# Why: #8638 in Alexa global
'http://www.imasters.com.br/',
# Why: #8639 in Alexa global
'http://www.n11.com/',
# Why: #8640 in Alexa global
'http://www.iam.ma/',
# Why: #8641 in Alexa global
'http://www.qq5.com/',
# Why: #8642 in Alexa global
'http://www.tvboxnow.com/',
# Why: #8643 in Alexa global
'http://www.limetorrents.com/',
# Why: #8644 in Alexa global
'http://www.bancopopular.es/',
# Why: #8645 in Alexa global
'http://www.ray-ban.com/',
# Why: #8646 in Alexa global
'http://www.drweb.com/',
# Why: #8647 in Alexa global
'http://www.hushmail.com/',
# Why: #8648 in Alexa global
'http://www.resuelvetudeuda.com/',
# Why: #8649 in Alexa global
'http://www.sharpnews.ru/',
# Why: #8650 in Alexa global
'http://www.hellocoton.fr/',
# Why: #8651 in Alexa global
'http://buysub.com/',
# Why: #8652 in Alexa global
'http://www.homemoviestube.com/',
# Why: #8653 in Alexa global
'http://www.utsandiego.com/',
# Why: #8654 in Alexa global
'http://www.learn4good.com/',
# Why: #8655 in Alexa global
'http://www.nii.ac.jp/',
# Why: #8656 in Alexa global
'http://www.girlsgogames.ru/',
# Why: #8657 in Alexa global
'http://www.talksport.co.uk/',
# Why: #8658 in Alexa global
'http://fap.to/',
# Why: #8659 in Alexa global
'http://www.teennick.com/',
# Why: #8660 in Alexa global
'http://www.seitwert.de/',
# Why: #8661 in Alexa global
'http://www.celebritymoviearchive.com/',
# Why: #8662 in Alexa global
'http://www.sukar.com/',
# Why: #8663 in Alexa global
'http://www.astromeridian.ru/',
# Why: #8664 in Alexa global
'http://www.zen-cart.com/',
# Why: #8665 in Alexa global
'http://www.1phads.com/',
# Why: #8666 in Alexa global
'http://www.plaisio.gr/',
# Why: #8667 in Alexa global
'http://www.photozou.jp/',
# Why: #8668 in Alexa global
'http://www.cplusplus.com/',
# Why: #8669 in Alexa global
'http://www.ewebse.com/',
# Why: #8670 in Alexa global
'http://6eat.com/',
# Why: #8672 in Alexa global
'http://www.payless.com/',
# Why: #8673 in Alexa global
'http://www.subaonet.com/',
# Why: #8674 in Alexa global
'http://www.dlisted.com/',
# Why: #8675 in Alexa global
'http://www.kia.com/',
# Why: #8676 in Alexa global
'http://www.lankahotnews.net/',
# Why: #8677 in Alexa global
'http://www.vg247.com/',
# Why: #8678 in Alexa global
'http://www.formstack.com/',
# Why: #8679 in Alexa global
'http://www.jobs.net/',
# Why: #8680 in Alexa global
'http://www.coolchaser.com/',
# Why: #8681 in Alexa global
'http://www.blackplanet.com/',
# Why: #8682 in Alexa global
'http://www.unionbank.com/',
# Why: | |
"""
Synthetic Generators for labeled random graphs for SSL-H
Inspiration: http://networkx.github.io/documentation/latest/_modules/networkx/generators/random_graphs.html
Author: <NAME>
License: Apache Software License
"""
import random
import warnings
from random import randint
from numpy.random import random_sample, shuffle
import numpy as np
from scipy.sparse import csr_matrix
from scipy import optimize
from math import ceil, pi
import collections # collections.Counter
from utils import (row_normalize_matrix,
check_normalized_beliefs,
from_dictionary_beliefs,
calculate_potential_from_row_normalized)
import networkx as nx
RANDOMSEED = None # TODO: remove after removing graph generator at the end. Better initialized in experimental loop outside this file with following two lines:
# random.seed(RANDOMSEED) # seeds some other python random generator
# np.random.seed(seed=RANDOMSEED) # seeds the actually used numpy random generator; both are used and thus needed
def planted_distribution_model_H(n, alpha, H, d_out,
distribution='powerlaw', exponent=-0.5,
directed=True,
backEdgesAllowed=False,
sameInAsOutDegreeRanking=False,
debug=0):
"""Variation on planted_distribution_model_H that uses (P, m) instead of (H, d_out)
Notice that for undirected graphs, the actual average degree distribution will be double of d_out
"""
k = len(alpha)
if not isinstance(d_out, (collections.Sequence, np.ndarray)): # allow single number as input
d_out = [d_out] * k
P = calculate_potential_from_row_normalized(H, alpha, d_out)
m = np.rint(n * np.array(alpha).dot(np.array(d_out)))
# print("P:", P)
return planted_distribution_model(n=n, alpha=alpha, P=P, m=m,
distribution=distribution, exponent=exponent,
directed=directed,
backEdgesAllowed=backEdgesAllowed,
sameInAsOutDegreeRanking=sameInAsOutDegreeRanking,
debug=debug)
def planted_distribution_model(n, alpha, P, m,
distribution='powerlaw', exponent=-0.5,
directed=True,
backEdgesAllowed=False, # deprecated
sameInAsOutDegreeRanking=False, # deprecated
debug=0):
"""Creates a directed random graph with planted compatibility matrix 'P'.
Accepts (n, alpha_vec, P, m). The alternative version accepts: (n, alpha_vec, H, d_out_vec).
If directed==False: creates an undirected graph. Requires:
1) P to be symmetric, with identical row and column sum
2) ignores: backEdgesAllowed, sameInAsOutDegreeRanking
Notice: m = |W| for directed, but 2m = |W| for undirected.
Notice: Average outdegree d_out = m/n for directed, but average total degree d = 2m/n for directed and undirected
Parameters
----------
n : int
number of nodes
alpha : k-dimensional ndarray or list
node label distribution
P : [k,k] ndarray
Compatibility matrix (no need for column-normalized or symmetric)
m : int
total number of edges
distribution : string, optional (Default = 'powerlaw')
'uniform', 'triangle', 'powerlaw': used with "create_distribution_vector(n, m, distribution, exponent)"
exponent : float, optional (Default = None)
only for 'powerlaw', by default = -1
directed : Boolean, optional (Default = True)
False: then constructs an undirected graph. Requires symmetric doubly stochastic potential
backEdgesAllowed : Boolean, optional (Default = False)
False: then two nodes cannot be connected by two edges back and forth
Overwritten for undirected to be False
sameInAsOutDegreeRanking : Boolean, optional (Default = False)
True: then node with highest indegree also has highest outdegree among its peers
Overwritten for undirected to be False
debug : int (Default = 0)
0: print nothing
1: prints some statistics
2: prints even node degree distributions
Returns
-------
W : sparse.csr_matrix
sparse weighted adjacency matrix
Xd : dictionary
Explicit beliefs
"""
# -- Jump out from inner loop if graph cannot be found
# Define an exception that allows to jump out from inner loop to a certain outer loop
class GraphNotFound(Exception):
pass
# -- Initialization
alpha = np.asarray(alpha)
k = len(alpha)
k1, k2 = P.shape
assert k == k1 and k == k2
# # DEL
# n_vec = np.array(alpha*n, int) # number of nodes in each class
# P_sum = P.sum()
# P_tot = m * P / P_sum # !!!
# P_row_sum = P.sum(1, keepdims=True) # sums along horizontal axis
# H = 1. * P / P_row_sum
# m_out_vec = P_tot.sum(1, keepdims=False) # sums along vertical axis
# d_out_vec = m_out_vec / n_vec
# if not directed:
# # for i in range(k): # symmetric matrix [not important either, P + P^T (back edges) becomes symmetric
# # for j in range(k):
# # assert P[i,j] == P[j,i]
# # s_vec = P.sum(1, keepdims=False) # same col and row sum [actually not important, only symmetry]
# # for i in range(k):
# # assert s_vec[0] == s_vec[i]
# # d_out_vec = 1. * d_out_vec / 2 # use half of the desired degree since symmetric back edges are created
# # d_out_vec = 1. * d_out_vec * np.power(alpha, -1) / k # calculate the d_out vector (given doubly stoch constraint)
# if backEdgesAllowed:
# warnings.warn("'backEdgesAllowed' set to False")
# backEdgesAllowed = False # Otherwise, same edge could be created twice, redundant
# if sameInAsOutDegreeRanking:
# warnings.warn("'sameInAsOutDegreeRanking' set to False")
# sameInAsOutDegreeRanking = False # Otherwise in uniform distribution not correct
# # d_out_vec = np.asarray(d_out_vec)
# --- Big loop that attempts to create a graph for 20 times (sometimes the parameters don't allow a graph)
attempt = 0
finished = False
while attempt < 20 and not finished:
# -- (1) n_vec: np.array: number of nodes for each class
n_vec = np.array(alpha*n, int) # number of nodes in each class
delta = np.sum(n_vec) - n
n_vec[k-1] = n_vec[k-1] - delta # make sure sum(N)=n, in case there are rounding errors, correct the last entry
# -- Xd: dictionary: class of each node
Xl = [ [i]*n_vec[i] for i in range(k) ]
Xl = np.hstack(Xl) # flatten nested array
shuffle(Xl) # random order of those classes. Array that maps i -> k
Xd = {i : Xl[i] for i in range(n)} # Xd: dictionary that maps i -> k
# -- P / P_tot: nested np.array: total number of edges between each node type
# P = calculate_potential_from_row_normalized(H, alpha, d_out_vec)
P_tot = m * P / P.sum() # !!!
P_tot = np.rint(P_tot).astype(int)
# P_row_sum = P_tot.sum(1, keepdims=False) # sums along horizontal axis
delta = m - P_tot.sum()
P_tot[0][0] = P_tot[0][0] + delta
# for i in range(k):
# P_tot[i][i] = P_tot[i][i] + delta[i]
# add any delta to diagonal: that guarantees a symmetric matrix for undirected case
assert np.all(P_tot >= 0), "Negative values in P_tot due to rounding errors. Change graph parameters" # Can happen for H with 0 entries due to necessary rounding to closest integers
# -- (2) m_out_vec: np.array: number outgoing edges in each class / m: total number of edges
# m_out_vec = np.rint(n_vec * d_out_vec).astype(int) # round to nearest integer
m_out_vec = P_tot.sum(1, keepdims=False)
# delta = np.rint(np.sum(alpha * n * d_out_vec) - np.sum(m_out_vec)).astype(int)
# m_out_vec[k-1] = m_out_vec[k-1] + delta # make sure sum(m_out_vec)=expected(m), in case there are rounding errors, correct the last entry
m = np.sum(m_out_vec)
# -- m_in_vec: number of incoming edges per class / d_in_vec: np.array: average in-degree per class
m_in_vec = P_tot.sum(0, keepdims=False) # sums along vertical axis
d_in_vec = 1. * m_in_vec / n_vec
# -- (3) list_OutDegree_vecs, list_InDegree_vec: list of np.array: distribution of in/outdegrees for nodes in each class
list_OutDegree_vec = []
list_InDegree_vec = []
for i in range(k):
# if not directed: # undirected case works differently: create double the degrees
# m_out_vec[i] *= 2 # but then deduce 2 outdegrees per edge (ignoring indegrees completely)
out_distribution = create_distribution_vector(n_vec[i], m_out_vec[i], distribution=distribution, exponent=exponent)
list_OutDegree_vec.append(out_distribution)
# if directed:
# in_distribution = create_distribution_vector(n_vec[i], m_in_vec[i], distribution=distribution, exponent=exponent)
# list_InDegree_vec.append(in_distribution)
in_distribution = create_distribution_vector(n_vec[i], m_in_vec[i], distribution=distribution, exponent=exponent)
list_InDegree_vec.append(in_distribution)
# -- listlistNodes: list of randomly shuffled node ids for each class
listlistNodes = [[node for node in range(n) if Xd[node] == i] for i in range(k)]
for innerList in listlistNodes:
shuffle( innerList )
# -- list_OutDegree_nodes: list of list of node ids:
# contains for each outgoing edge in each class the start node id, later used for sampling
list_OutDegree_nodes = []
for i in range(k):
innerList = []
for j, item in enumerate(listlistNodes[i]):
innerList += [item] * list_OutDegree_vec[i][j]
list_OutDegree_nodes.append(innerList)
if not sameInAsOutDegreeRanking: # shuffle the randomly ordered list again before assigning indegrees
for innerList in listlistNodes:
np.random.shuffle(innerList)
list_InDegree_nodes = [] # list of each node times the outdegree
for i in range(k):
innerList = []
for j, item in enumerate(listlistNodes[i]):
innerList += [item] * list_InDegree_vec[i][j]
list_InDegree_nodes.append(innerList)
# if directed:
# if not sameInAsOutDegreeRanking: # shuffle the randomly ordered list again before assigning indegrees
# for innerList in listlistNodes:
# np.random.shuffle( innerList )
# list_InDegree_nodes = [] | |
probability that a person is not allowed to move to other districts
blocked_not_allowed_target_district_index = self.model.params.BLOCK_ALLOWED_PROBABILITY < np.random.random(len(target_district_ids))
# If a person is not allowed to move and target location is on lockdown
blocked_district_index = blocked_target_district_index & blocked_not_allowed_target_district_index
# If identified to be restricted, set target district to home district
target_district_ids[blocked_district_index] = self.model.district_ids[district_out_mover_ids][blocked_district_index]
#### NOTE: SCENARIO SPECIFIC: Execute check for blocking places with outbound
other_district_index = np.not_equal(target_district_ids, self.model.district_ids[district_out_mover_ids])
actual_district_out_mover_ids = district_out_mover_ids[other_district_index]
src_district_ids = self.model.district_ids[actual_district_out_mover_ids]
dst_district_ids = target_district_ids[other_district_index]
dow = current_time.weekday()
stay_idx = [(
dow,
self.model.params.DISTRICT_ID_TO_NAME.get(src),
self.model.params.DISTRICT_ID_TO_NAME.get(dst)
) for src, dst in zip(src_district_ids, dst_district_ids)]
od_stay_matrix = self.model.params.DISTRICT_WEEKDAY_OD_STAY_COUNT_MATRIX.loc[stay_idx]
return_district_params = self.model.params.get_gamma_shape_scale(
od_stay_matrix['avg_duration'],
od_stay_matrix['stddev_duration'])
return_district_at_times = current_time + np.array([
timedelta(hours=h) for h in np.random.gamma(*return_district_params)
])
self.model.return_district_at[actual_district_out_mover_ids] = return_district_at_times
self.model.current_district_ids[actual_district_out_mover_ids] = target_district_ids[other_district_index]
# We don't assign movers to households. They will be actively interacting with people in different districts.
# This also suggests that at night, people from other districts will be interacting with each other and not with locals in the district.
self.model.current_location_ids[actual_district_out_mover_ids] = target_district_ids[other_district_index]
return actual_district_out_mover_ids
class Country(Model):
def __init__(self, params, model_log_file=None, individual_log_file=None):
'''
params: class or dict containing the global parameters for the model.
start_datetime: datetime object corresponding to the start date of the simulation.
step_timedelta: timedelta corresponding to the timestep in the simulation.
'''
self.individual_log_file = individual_log_file
self.model_log_file = model_log_file
self.params = params
self.start_datetime = params.start_datetime
self.step_timedelta = params.step_timedelta
# Agent Vectors
self.person_ids = None
self.district_ids = None
self.household_ids = None
self.age = None
self.sex = None
self.economic_status_ids = None
self.economic_activity_location_ids = None
# Set initial location as the household
# Current location can be [school, household, outside] # Since we don't have specific location data yet.
self.current_location_ids = None
self.current_district_ids = None
self.left_district_at = None
self.return_district_at = None
self.economic_status_weekday_movement_probability = None
self.economic_status_other_day_movement_probability = None
self.mild_symptom_movement_probability = None
# Epidemic Vectors
## Epidemic status
self.epidemic_state = None # default to 0 -> susceptible, 1 -> infected, 2 -> contagious, 3 -> recovered, 4 -> dead
self.infection_rate = None
self.infected_symptomatic_status = None # default to -1 -> uninfected, 0 -> asymptomatic, 1 -> symptomatic
self.clinical_state = None # default to 0 -> uninfected/not hospitalized, 1 -> hospitalized, 2 -> critical
self.date_infected = None # default to np.inf
self.date_start_contagious = None # default to np.inf
self.date_start_symptomatic = None # default to np.inf
self.date_recovered = None # default to np.inf
self.infected_at_district_ids = None
self.infected_at_location_ids = None
## Clinical care
self.date_start_hospitalized = None # default to np.inf
self.date_end_hospitalized = None # default to np.inf
self.date_start_critical = None # default to np.inf
self.date_end_critical = None # default to np.inf
## Note, a person in icu can recover and need to get a hospital bed for recovery.
## Fatality status
self.date_died = None # default to np.inf
# if (self.economic_status in self.model.params.DISTRICT_MOVING_ECONOMIC_STATUS) and (self.age >= self.model.params.DISTRICT_MOVEMENT_ALLOWED_AGE):
self.district_mover = None # 0 -> not allowed to move between districts, 1 -> allowed to move between districts
# Trackers
self.infected_count = 0
self.asymptomatic_count = 0
self.symptomatic_count = 0
self.hospitalized_count = 0
self.critical_count = 0
self.died_count = 0
self.recovered_count = 0
self.scheduler = EpidemicScheduler(self)
self.lockdown = params.lockdown
self.blocked = params.blocked
# School reopening status
self.school_phase = None
self.is_school_scenario = False
def initialize_epidemic_vectors(self, size):
self.STATE_SUSCEPTIBLE = 0
self.STATE_INFECTED = 1
self.STATE_CONTAGIOUS = 2
self.STATE_RECOVERED = 3
self.STATE_DEAD = 4
self.DEAD_LOCATION_ID = -1
self.CLINICAL_NOT_HOSPITALIZED = 0
self.CLINICAL_HOSPITALIZED = 1
self.CLINICAL_CRITICAL = 2
self.CLINICAL_RELEASED_OR_DEAD = 3
self.SYMPTOM_NONE = -1
self.SYMPTOM_ASYMPTOMATIC = 0
self.SYMPTOM_SYMPTOMATIC = 1
## Epidemic status
self.epidemic_state = np.zeros(shape=size) # default to 0 -> susceptible, 1 -> infected, 2 -> contagious, 3 -> recovered, 4 -> dead
self.infection_rate = np.zeros(shape=size)
self.infected_symptomatic_status = np.full(shape=size, fill_value=self.SYMPTOM_NONE) # default to -1 -> uninfected, 0 -> asymptomatic, 1 -> symptomatic
self.clinical_state = np.full(shape=size, fill_value=self.CLINICAL_NOT_HOSPITALIZED) # default to 0 -> uninfected/not hospitalized, 1 -> hospitalized, 2 -> critical
self.date_infected = np.full(shape=size, fill_value=datetime.max) # default to np.inf
self.date_start_contagious = np.full(shape=size, fill_value=datetime.max) # default to np.inf
self.date_start_symptomatic = np.full(shape=size, fill_value=datetime.max) # default to np.inf
self.date_recovered = np.full(shape=size, fill_value=datetime.max) # default to np.inf
self.infected_at_district_ids = np.full(shape=size, fill_value=-1)
self.infected_at_location_ids = np.full(shape=size, fill_value=-1)
self.severe_disease_risk = np.ones(shape=size)
def initialize_clinical_vectors(self, size):
## Clinical care
self.date_start_hospitalized = np.full(shape=size, fill_value=datetime.max) # default to np.inf
self.date_end_hospitalized = np.full(shape=size, fill_value=datetime.max) # default to np.inf
self.date_start_critical = np.full(shape=size, fill_value=datetime.max) # default to np.inf
self.date_end_critical = np.full(shape=size, fill_value=datetime.max) # default to np.inf
## Note, a person in icu can recover and need to get a hospital bed for recovery.
## Fatality status
self.date_died = np.full(shape=size, fill_value=datetime.max) # default to np.inf
def initialize_agent_vectors(self, df):
# Agent Vectors
size = df.shape[0]
# Define household id relative to district id so that we can unify location.
self.params.HOUSEHOLD_ID_TO_NAME = dict(enumerate(
sorted(df['household_id'].unique()),
max(self.params.DISTRICT_ID_TO_NAME) + 1)
)
self.params.HOUSEHOLD_NAME_TO_ID = {j: i for i, j in self.params.HOUSEHOLD_ID_TO_NAME.items()}
if self.is_school_scenario:
# Define school id relative to district id and household id so that we can unify location.
self.params.SCHOOL_ID_TO_NAME = dict(enumerate(
sorted(df.loc[df['school_id'] != '', 'school_id'].unique()),
max(self.params.HOUSEHOLD_ID_TO_NAME) + 1)
)
self.params.SCHOOL_NAME_TO_ID = {j: i for i, j in self.params.SCHOOL_ID_TO_NAME.items()}
self.params.SEX_ID_TO_NAME = dict(enumerate(sorted(df['sex'].unique())))
self.params.SEX_NAME_TO_ID = {j: i for i, j in self.params.SEX_ID_TO_NAME.items()}
self.params.LOCATION_ID_TO_NAME = dict(self.params.DISTRICT_ID_TO_NAME)
self.params.LOCATION_ID_TO_NAME.update(self.params.HOUSEHOLD_ID_TO_NAME)
if self.is_school_scenario:
self.params.LOCATION_ID_TO_NAME.update(self.params.SCHOOL_ID_TO_NAME)
self.params.LOCATION_NAME_TO_ID = {j: i for i, j in self.params.LOCATION_ID_TO_NAME.items()}
self.person_ids = np.array(range(size), dtype=int)
self.district_ids = np.array(df['district_id'].map(self.params.DISTRICT_NAME_TO_ID))
self.household_ids = np.array(df['household_id'].map(self.params.HOUSEHOLD_NAME_TO_ID))
self.age = np.array(df['age'])
self.sex = np.array(df['sex'].map(self.params.SEX_NAME_TO_ID))
self.economic_status_ids = np.array(df['economic_status'].map(self.params.ECON_STAT_NAME_TO_ID))
self.economic_activity_location_ids = np.array(df['economic_activity_location_id'].map(
self.params.LOCATION_NAME_TO_ID))
self.economic_status_ids_person_ids = {i: set(np.where(self.economic_status_ids == i)[0]) for i in self.params.ECON_STAT_ID_TO_NAME}
self.economic_status_weekday_movement_probability = np.array(df['economic_status'].map(self.params.ECONOMIC_STATUS_WEEKDAY_MOVEMENT_PROBABILITY))
self.economic_status_other_day_movement_probability = np.array(df['economic_status'].map(self.params.ECONOMIC_STATUS_OTHER_DAY_MOVEMENT_PROBABILITY))
self.mild_symptom_movement_probability = np.ones(shape=size)
# Set initial location as the household
# Current location can be [school, household, outside] # Since we don't have specific location data yet.
self.current_location_ids = np.array(self.household_ids)
self.current_district_ids = np.array(self.district_ids)
self.left_district_at = np.full(shape=size, fill_value=datetime.max)
self.return_district_at = np.full(shape=size, fill_value=datetime.max)
district_moving_economic_status_ids = [self.params.ECON_STAT_NAME_TO_ID[es] for es in self.params.DISTRICT_MOVING_ECONOMIC_STATUS]
self.DISTRICT_MOVER_FALSE = 0
self.DISTRICT_MOVER_TRUE = 1
self.district_mover = self.DISTRICT_MOVER_TRUE * (
np.in1d(self.economic_status_ids, district_moving_economic_status_ids) &
(self.age >= self.params.DISTRICT_MOVEMENT_ALLOWED_AGE)
)
def scenario_data_preprocessing(self, df):
pass
def scenario_data_postprocessing(self, df):
pass
def set_blocked_movers_and_movement_probabilities(self):
blocked_ids = self.person_ids[np.in1d(self.district_ids, self.params.BLOCK_DISTRICTS_IDS)]
district_blocked_movers = blocked_ids[self.district_mover[blocked_ids] == self.DISTRICT_MOVER_TRUE]
district_blocked_allowed_movers = district_blocked_movers[np.random.random(len(district_blocked_movers)) < self.params.BLOCK_ALLOWED_PROBABILITY]
self.district_mover[district_blocked_movers] = self.DISTRICT_MOVER_FALSE
self.district_mover[district_blocked_allowed_movers] = self.DISTRICT_MOVER_TRUE
def set_lockdown_movers_and_movement_probabilities(self, unrestricted_ids=None):
lockdown_ids = self.person_ids[np.in1d(self.district_ids, self.params.LOCKDOWN_DISTRICTS_IDS)]
if unrestricted_ids is not None and len(unrestricted_ids) > 0:
lockdown_ids = np.array(list(set(lockdown_ids).difference(unrestricted_ids)))
district_lockdown_movers = lockdown_ids[self.district_mover[lockdown_ids] == self.DISTRICT_MOVER_TRUE]
district_lockdown_allowed_movers = district_lockdown_movers[
np.less(
np.random.random(len(district_lockdown_movers)),
np.array([
self.params.LOCKDOWN_ALLOWED_PROBABILITY[i] for i in self.district_ids[district_lockdown_movers]]))]
self.district_mover[district_lockdown_movers] = self.DISTRICT_MOVER_FALSE
self.district_mover[district_lockdown_allowed_movers] = self.DISTRICT_MOVER_TRUE
decreased_mobility_rate = np.array([self.params.LOCKDOWN_DECREASED_MOBILITY_RATE[i] for i in self.district_ids[lockdown_ids]])
self.economic_status_weekday_movement_probability[lockdown_ids] *= decreased_mobility_rate
self.economic_status_other_day_movement_probability[lockdown_ids] *= decreased_mobility_rate
def setup_selective_movement_restriction_scenarios(self, unrestricted_ids, set_lockdown):
if set_lockdown:
self.set_lockdown_movers_and_movement_probabilities(unrestricted_ids=unrestricted_ids)
# NOTE: Don't allow unrestricted_ids to move between districts
self.district_mover[unrestricted_ids] = self.DISTRICT_MOVER_FALSE
# NOTE: During weekends apply mobility restrictions to unrestricted_ids?
other_decreased_mobility_rate = np.array([self.params.LOCKDOWN_DECREASED_MOBILITY_RATE[i] for i in self.district_ids[unrestricted_ids]])
self.economic_status_other_day_movement_probability[unrestricted_ids] *= other_decreased_mobility_rate
def set_school_params(self, df):
if self.params.SCENARIO.endswith("GOVERNMENT_OPEN_SCHOOLS"):
self.school_phase = np.array(df["phase"])
self.max_school_phase = max(self.school_phase)
self.active_school_phases = [1]
self.school_ids = np.array(df['school_id'].map(self.params.SCHOOL_NAME_TO_ID))
def lockdown_schools(self, district_ids, active_school_phases):
'''
district_ids: list of location that are being locked down due to high symptomatic infection rate.
active_school_phases: list of phases of school opening that are currently active.
# Assume that people not going to school will be assigned
# a school_phase value of 0.
# lockdown_ids corresponds to school goers.
'''
lockdown_ids = self.person_ids[np.in1d(self.district_ids, district_ids) & np.in1d(self.school_phase, active_school_phases)]
district_lockdown_movers = lockdown_ids[self.district_mover[lockdown_ids] == self.DISTRICT_MOVER_TRUE]
district_lockdown_allowed_movers = district_lockdown_movers[
np.less(np.random.random(len(district_lockdown_movers)),
np.array([self.params.LOCKDOWN_ALLOWED_PROBABILITY[i] for i in self.district_ids[district_lockdown_movers]]))]
self.district_mover[district_lockdown_movers] = self.DISTRICT_MOVER_FALSE
self.district_mover[district_lockdown_allowed_movers] = self.DISTRICT_MOVER_TRUE
decreased_mobility_rate = np.array([self.params.LOCKDOWN_DECREASED_MOBILITY_RATE[i] for i in self.district_ids[lockdown_ids]])
# # Reset values before updating... No need to update other day movement since we only alter
# # weekday behaviour.
# # NOTE: Strictly, lockdown_ids should be split into In School and Teachers economic status. However, we can operate on the combined
# # set since the ECONOMIC_STATUS_WEEKDAY_MOVEMENT_PROBABILITY values for both status are the same.
# in_school_lockdown_ids = None
# teachers_lockdown_ids = None
self.economic_status_weekday_movement_probability[lockdown_ids] = self.params.ECONOMIC_STATUS_WEEKDAY_MOVEMENT_PROBABILITY["In School"]
self.economic_status_weekday_movement_probability[lockdown_ids] *= decreased_mobility_rate
# If schools are closed, revert to default external interaction location.
self.update_school_economic_activity_location(lockdown_ids, is_lockdown=True)
def open_schools(self, district_ids, active_school_phases):
school_educ_ids = self.person_ids[np.in1d(self.district_ids, district_ids) & np.in1d(self.school_phase, active_school_phases)]
# # Reset values before updating...
# # NOTE: Strictly, lockdown_ids should be split into In School and Teachers economic status. However, we can operate | |
Input structure.
prev_incar (Incar/string): Incar file from previous run.
mode (str): Supported modes are "STATIC" (default), "DIAG", "GW",
and "BSE".
nbands (int): For subsequent calculations, it is generally
recommended to perform NBANDS convergence starting from the
NBANDS of the previous run for DIAG, and to use the exact same
NBANDS for GW and BSE. This parameter is used by
from_previous_calculation to set nband.
potcar_functional (str): Defaults to "PBE_54".
copy_wavecar: Whether to copy the old WAVECAR, WAVEDER and associated
files when starting from a previous calculation.
nbands_factor (int): Multiplicative factor for NBANDS when starting
from a previous calculation. Only applies if mode=="DIAG".
Need to be tested for convergence.
ncores (int): Numbers of cores used for the calculation. VASP will alter
NBANDS if it was not dividable by ncores. Only applies if
mode=="DIAG".
**kwargs: All kwargs supported by DictSet. Typically,
user_incar_settings is a commonly used option.
"""
CONFIG = _load_yaml_config("MVLGWSet")
SUPPORTED_MODES = ("DIAG", "GW", "STATIC", "BSE")
def __init__(self, structure, prev_incar=None, nbands=None,
potcar_functional="PBE_54", reciprocal_density=100,
mode="STATIC", copy_wavecar=True, nbands_factor=5, ncores=16,
**kwargs):
super().__init__(structure, MVLGWSet.CONFIG, **kwargs)
self.prev_incar = prev_incar
self.nbands = nbands
self.potcar_functional = potcar_functional
self.reciprocal_density = reciprocal_density
self.mode = mode.upper()
if self.mode not in MVLGWSet.SUPPORTED_MODES:
raise ValueError("%s not one of the support modes : %s" %
(self.mode, MVLGWSet.SUPPORTED_MODES))
self.kwargs = kwargs
self.copy_wavecar = copy_wavecar
self.nbands_factor = nbands_factor
self.ncores = ncores
@property
def kpoints(self):
"""
Generate gamma center k-points mesh grid for GW calc,
which is requested by GW calculation.
"""
return Kpoints.automatic_density_by_vol(self.structure,
self.reciprocal_density,
force_gamma=True)
@property
def incar(self):
parent_incar = super().incar
incar = Incar(self.prev_incar) if self.prev_incar is not None else \
Incar(parent_incar)
if self.mode == "DIAG":
# Default parameters for diagonalization calculation.
incar.update({
"ALGO": "Exact",
"NELM": 1,
"LOPTICS": True,
"LPEAD": True
})
elif self.mode == "GW":
# Default parameters for GW calculation.
incar.update({
"ALGO": "GW0",
"NELM": 1,
"NOMEGA": 80,
"ENCUTGW": 250
})
incar.pop("EDIFF", None)
incar.pop("LOPTICS", None)
incar.pop("LPEAD", None)
elif self.mode == "BSE":
# Default parameters for BSE calculation.
incar.update({
"ALGO": "BSE",
"ANTIRES": 0,
"NBANDSO": 20,
"NBANDSV": 20
})
if self.nbands:
incar["NBANDS"] = self.nbands
# Respect user set INCAR.
incar.update(self.kwargs.get("user_incar_settings", {}))
return incar
def override_from_prev_calc(self, prev_calc_dir='.'):
"""
Update the input set to include settings from a previous calculation.
Args:
prev_calc_dir (str): The path to the previous calculation directory.
Returns:
The input set with the settings (structure, k-points, incar, etc)
updated using the previous VASP run.
"""
vasprun, outcar = get_vasprun_outcar(prev_calc_dir)
self.prev_incar = vasprun.incar
self._structure = vasprun.final_structure
if self.standardize:
warnings.warn("Use of standardize=True with from_prev_run is not "
"recommended as there is no guarantee the copied "
"files will be appropriate for the standardized "
"structure.")
self.nbands = int(vasprun.parameters["NBANDS"])
if self.mode.upper() == "DIAG":
self.nbands = int(np.ceil(self.nbands * self.nbands_factor /
self.ncores) * self.ncores)
# copy WAVECAR, WAVEDER (derivatives)
files_to_transfer = {}
if self.copy_wavecar:
for fname in ("WAVECAR", "WAVEDER", "WFULL"):
w = sorted(glob.glob(str(Path(prev_calc_dir) / (fname + "*"))))
if w:
if fname == "WFULL":
for f in w:
fname = Path(f).name
fname = fname.split(".")[0]
files_to_transfer[fname] = f
else:
files_to_transfer[fname] = str(w[-1])
self.files_to_transfer.update(files_to_transfer)
return self
@classmethod
def from_prev_calc(cls, prev_calc_dir, mode="DIAG", **kwargs):
"""
Generate a set of Vasp input files for GW or BSE calculations from a
directory of previous Exact Diag Vasp run.
Args:
prev_calc_dir (str): The directory contains the outputs(
vasprun.xml of previous vasp run.
mode (str): Supported modes are "STATIC", "DIAG" (default), "GW",
and "BSE".
**kwargs: All kwargs supported by MVLGWSet, other than structure,
prev_incar and mode, which are determined from the
prev_calc_dir.
"""
input_set = cls(_dummy_structure, mode=mode, **kwargs)
return input_set.override_from_prev_calc(prev_calc_dir=prev_calc_dir)
class MVLSlabSet(MPRelaxSet):
"""
Class for writing a set of slab vasp runs,
including both slabs (along the c direction) and orient unit cells (bulk),
to ensure the same KPOINTS, POTCAR and INCAR criterion.
Args:
k_product: default to 50, kpoint number * length for a & b directions,
also for c direction in bulk calculations
bulk (bool): Set to True for bulk calculation. Defaults to False.
**kwargs: Other kwargs supported by :class:`DictSet`.
"""
def __init__(self, structure, k_product=50, bulk=False,
auto_dipole=False, set_mix=True, sort_structure=True,
**kwargs):
super().__init__(structure, **kwargs)
if sort_structure:
structure = structure.get_sorted_structure()
self.k_product = k_product
self.bulk = bulk
self.auto_dipole = auto_dipole
self.kwargs = kwargs
self.set_mix = set_mix
self.kpt_calc = None
slab_incar = {"EDIFF": 1e-4, "EDIFFG": -0.02, "ENCUT": 400,
"ISMEAR": 0, "SIGMA": 0.05, "ISIF": 3}
if not self.bulk:
slab_incar["ISIF"] = 2
slab_incar["LVTOT"] = True
if self.set_mix:
slab_incar["AMIN"] = 0.01
slab_incar["AMIX"] = 0.2
slab_incar["BMIX"] = 0.001
slab_incar["NELMIN"] = 8
if self.auto_dipole:
weights = [s.species.weight for s in structure]
center_of_mass = np.average(structure.frac_coords,
weights=weights, axis=0)
slab_incar["IDIPOL"] = 3
slab_incar["LDIPOL"] = True
slab_incar["DIPOL"] = center_of_mass
self._config_dict["INCAR"].update(slab_incar)
@property
def kpoints(self):
"""
k_product, default to 50, is kpoint number * length for a & b
directions, also for c direction in bulk calculations
Automatic mesh & Gamma is the default setting.
"""
# To get input sets, the input structure has to has the same number
# of required parameters as a Structure object (ie. 4). Slab
# attributes aren't going to affect the VASP inputs anyways so
# converting the slab into a structure should not matter
kpt = super().kpoints
kpt.comment = "Automatic mesh"
kpt.style = 'Gamma'
# use k_product to calculate kpoints, k_product = kpts[0][0] * a
lattice_abc = self.structure.lattice.abc
kpt_calc = [int(self.k_product / lattice_abc[0] + 0.5),
int(self.k_product / lattice_abc[1] + 0.5), 1]
self.kpt_calc = kpt_calc
# calculate kpts (c direction) for bulk. (for slab, set to 1)
if self.bulk:
kpt_calc[2] = int(self.k_product / lattice_abc[2] + 0.5)
kpt.kpts[0] = kpt_calc
return kpt
def as_dict(self, verbosity=2):
d = MSONable.as_dict(self)
if verbosity == 1:
d.pop("structure", None)
return d
class MVLGBSet(MPRelaxSet):
"""
Class for writing a vasp input files for grain boundary calculations, slab
or bulk.
Args:
structure(Structure): provide the structure
k_product: Kpoint number * length for a & b directions, also for c
direction in bulk calculations. Default to 40.
slab_mode (bool): Defaults to False. Use default (False) for a
bulk supercell. Use True if you are performing calculations on a
slab-like (i.e., surface) of the GB, for example, when you are
calculating the work of separation.
is_metal (bool): Defaults to True. This determines whether an ISMEAR of
1 is used (for metals) or not (for insulators and semiconductors)
by default. Note that it does *not* override user_incar_settings,
which can be set by the user to be anything desired.
**kwargs:
Other kwargs supported by :class:`MPRelaxSet`.
"""
def __init__(self, structure, k_product=40, slab_mode=False, is_metal=True,
**kwargs):
super().__init__(structure, **kwargs)
self.k_product = k_product
self.slab_mode = slab_mode
self.is_metal = is_metal
@property
def kpoints(self):
"""
k_product, default to 40, is kpoint number * length for a & b
directions, also for c direction in bulk calculations
Automatic mesh & Gamma is the default setting.
"""
# To get input sets, the input structure has to has the same number
# of required parameters as a Structure object.
kpt = super().kpoints
kpt.comment = "Generated by pymatgen's MVLGBSet"
kpt.style = 'Gamma'
# use k_product to calculate kpoints, k_product = kpts[0][0] * a
lengths = self.structure.lattice.abc
kpt_calc = [int(self.k_product / lengths[0] + 0.5),
int(self.k_product / lengths[1] + 0.5),
int(self.k_product / lengths[2] + 0.5)]
if self.slab_mode:
kpt_calc[2] = 1
kpt.kpts[0] = kpt_calc
return kpt
@property
def incar(self):
incar = super().incar
# The default incar setting is used for metallic system, for
# insulator or semiconductor, ISMEAR need to be changed.
incar.update({
"LCHARG": False,
"NELM": 60,
"PREC": "Normal",
"EDIFFG": -0.02,
"ICHARG": 0,
"NSW": 200,
"EDIFF": 0.0001
})
if self.is_metal:
incar["ISMEAR"] = 1
incar["LDAU"] = False
if self.slab_mode:
# for clean grain boundary and bulk relaxation, full optimization
# relaxation (ISIF=3) is used. For slab relaxation (ISIF=2) is used.
incar["ISIF"] = 2
incar["NELMIN"] = 8
incar.update(self.user_incar_settings)
return incar
class MVLRelax52Set(DictSet):
"""
Implementation of VaspInputSet utilizing the public Materials Project
parameters for INCAR & KPOINTS and VASP's recommended PAW potentials for
POTCAR.
Keynotes from VASP manual:
1. Recommended potentials for calculations using vasp.5.2+
2. If dimers with short bonds are present in the compound (O2, CO,
N2, F2, P2, S2, Cl2), it is recommended to use the h potentials.
| |
<reponame>qingpeng/khmer
#
# This file is part of khmer, http://github.com/ged-lab/khmer/, and is
# Copyright (C) Michigan State University, 2009-2013. It is licensed under
# the three-clause BSD license; see doc/LICENSE.txt.
# Contact: <EMAIL>
#
# pylint: disable=missing-docstring,protected-access
import khmer
from khmer import ReadParser
from screed.fasta import fasta_iter
import screed
import khmer_tst_utils as utils
from nose.plugins.attrib import attr
def teardown():
utils.cleanup()
def test__get_set_tag_density():
ht = khmer.new_hashbits(32, 1, 1)
orig = ht._get_tag_density()
assert orig != 2
ht._set_tag_density(2)
assert ht._get_tag_density() == 2
def test_n_occupied_1():
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 1 # number of hashtables
# test modified c++ n_occupied code
ht1 = khmer.new_hashbits(K, HT_SIZE, N_HT)
for n, record in enumerate(fasta_iter(open(filename))):
ht1.consume(record['sequence'])
# this number calculated independently
assert ht1.n_occupied() == 3877
def test_bloom_python_1():
# test python code to count unique kmers using bloom filter
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 3 # number of hashtables
ht2 = khmer.new_hashbits(K, HT_SIZE, N_HT)
n_unique = 0
for n, record in enumerate(fasta_iter(open(filename))):
sequence = record['sequence']
seq_len = len(sequence)
for n in range(0, seq_len + 1 - K):
kmer = sequence[n:n + K]
if (not ht2.get(kmer)):
n_unique += 1
ht2.count(kmer)
assert n_unique == 3960
assert ht2.n_occupied() == 3882
assert ht2.n_unique_kmers() == 3960 # this number equals to n_unique
def test_bloom_c_1():
# test c++ code to count unique kmers using bloom filter
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 3 # number of hashtables
ht3 = khmer.new_hashbits(K, HT_SIZE, N_HT)
for n, record in enumerate(fasta_iter(open(filename))):
ht3.consume(record['sequence'])
assert ht3.n_occupied() == 3882
assert ht3.n_unique_kmers() == 3960
def test_n_occupied_2(): # simple one
K = 4
HT_SIZE = 10 # use 11
N_HT = 1
ht1 = khmer.new_hashbits(K, HT_SIZE, N_HT)
ht1.count('AAAA') # 00 00 00 00 = 0
assert ht1.n_occupied() == 1
ht1.count('ACTG') # 00 10 01 11 =
assert ht1.n_occupied() == 2
ht1.count('AACG') # 00 00 10 11 = 11 # collision 1
assert ht1.n_occupied() == 2
ht1.count('AGAC') # 00 11 00 10 # collision 2
assert ht1.n_occupied() == 2
def test_bloom_c_2(): # simple one
K = 4
HT_SIZE = 10 # use 11
N_HT1 = 1 # hashtable size = 11
N_HT2 = 2 # hashtable size = 11,13
# use only 1 hashtable, no bloom filter
ht1 = khmer.new_hashbits(K, HT_SIZE, N_HT1)
ht1.count('AAAA') # 00 00 00 00 = 0
ht1.count('ACTG') # 00 10 01 11 =
assert ht1.n_unique_kmers() == 2
ht1.count('AACG') # 00 00 10 11 = 11 # collision with 1st kmer
assert ht1.n_unique_kmers() == 2
ht1.count('AGAC') # 00 11 00 10 # collision with 2nd kmer
assert ht1.n_unique_kmers() == 2
# use two hashtables with 11,13
ht2 = khmer.new_hashbits(K, HT_SIZE, N_HT2)
ht2.count('AAAA') # 00 00 00 00 = 0
ht2.count('ACTG') # 00 10 01 11 = 2*16 +4 +3 = 39
assert ht2.n_unique_kmers() == 2
ht2.count('AACG') # 00 00 10 11 = 11 # collision with only 1st kmer
assert ht2.n_unique_kmers() == 3
ht2.count('AGAC') # 00 11 00 10 3*16 +2 = 50
# collision with both 2nd and 3rd kmers
assert ht2.n_unique_kmers() == 3
def test_filter_if_present():
ht = khmer.new_hashbits(32, 2, 2)
maskfile = utils.get_test_data('filter-test-A.fa')
inputfile = utils.get_test_data('filter-test-B.fa')
outfile = utils.get_temp_filename('filter')
ht.consume_fasta(maskfile)
ht.filter_if_present(inputfile, outfile)
records = list(fasta_iter(open(outfile)))
assert len(records) == 1
assert records[0]['name'] == '3'
def test_combine_pe():
inpfile = utils.get_test_data('combine_parts_1.fa')
ht = khmer.new_hashbits(32, 1, 1)
ht.consume_partitioned_fasta(inpfile)
assert ht.count_partitions() == (2, 0)
s1 = "CATGCAGAAGTTCCGCAACCATACCGTTCAGT"
pid1 = ht.get_partition_id(s1)
s2 = "CAAATGTACATGCACTTAAAATCATCCAGCCG"
pid2 = ht.get_partition_id(s2)
assert pid1 == 2
assert pid2 == 80293
ht.join_partitions(pid1, pid2)
pid1 = ht.get_partition_id(s1)
pid2 = ht.get_partition_id(s2)
assert pid1 == pid2
assert ht.count_partitions() == (1, 0)
def test_load_partitioned():
inpfile = utils.get_test_data('combine_parts_1.fa')
ht = khmer.new_hashbits(32, 1, 1)
ht.consume_partitioned_fasta(inpfile)
assert ht.count_partitions() == (2, 0)
s1 = "CATGCAGAAGTTCCGCAACCATACCGTTCAGT"
assert ht.get(s1)
s2 = "CAAATGTACATGCACTTAAAATCATCCAGCCG"
assert ht.get(s2)
s3 = "CATGCAGAAGTTCCGCAACCATACCGTTCAGTTCCTGGTGGCTA"[-32:]
assert ht.get(s3)
def test_count_within_radius_simple():
inpfile = utils.get_test_data('all-A.fa')
ht = khmer.new_hashbits(4, 2, 2)
print ht.consume_fasta(inpfile)
n = ht.count_kmers_within_radius('AAAA', 1)
assert n == 1
n = ht.count_kmers_within_radius('AAAA', 10)
assert n == 1
def test_count_within_radius_big():
inpfile = utils.get_test_data('random-20-a.fa')
ht = khmer.new_hashbits(20, 1e5, 4)
ht.consume_fasta(inpfile)
n = ht.count_kmers_within_radius('CGCAGGCTGGATTCTAGAGG', int(1e6))
assert n == 3960
ht = khmer.new_hashbits(21, 1e5, 4)
ht.consume_fasta(inpfile)
n = ht.count_kmers_within_radius('CGCAGGCTGGATTCTAGAGGC', int(1e6))
assert n == 39
def test_count_kmer_degree():
inpfile = utils.get_test_data('all-A.fa')
ht = khmer.new_hashbits(4, 2, 2)
ht.consume_fasta(inpfile)
assert ht.kmer_degree('AAAA') == 2
assert ht.kmer_degree('AAAT') == 1
assert ht.kmer_degree('AATA') == 0
assert ht.kmer_degree('TAAA') == 1
def test_save_load_tagset():
ht = khmer.new_hashbits(32, 1, 1)
outfile = utils.get_temp_filename('tagset')
ht.add_tag('A' * 32)
ht.save_tagset(outfile)
ht.add_tag('G' * 32)
ht.load_tagset(outfile) # implicitly => clear_tags=True
ht.save_tagset(outfile)
# if tags have been cleared, then the new tagfile will be larger (34 bytes)
# else smaller (26 bytes).
fp = open(outfile, 'rb')
data = fp.read()
fp.close()
assert len(data) == 26, len(data)
def test_save_load_tagset_noclear():
ht = khmer.new_hashbits(32, 1, 1)
outfile = utils.get_temp_filename('tagset')
ht.add_tag('A' * 32)
ht.save_tagset(outfile)
ht.add_tag('G' * 32)
ht.load_tagset(outfile, False) # set clear_tags => False; zero tags
ht.save_tagset(outfile)
# if tags have been cleared, then the new tagfile will be large (34 bytes);
# else small (26 bytes).
fp = open(outfile, 'rb')
data = fp.read()
fp.close()
assert len(data) == 34, len(data)
def test_stop_traverse():
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 1e4 # size of hashtable
N_HT = 3 # number of hashtables
ht = khmer.new_hashbits(K, HT_SIZE, N_HT)
# without tagging/joining across consume, this breaks into two partition;
# with, it is one partition.
ht.add_stop_tag('TTGCATACGTTGAGCCAGCG')
ht.consume_fasta_and_tag(filename) # DO NOT join reads across stoptags
subset = ht.do_subset_partition(0, 0, True)
ht.merge_subset(subset)
n, _ = ht.count_partitions()
assert n == 2, n
def test_tag_across_stoptraverse():
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 1e4 # size of hashtable
N_HT = 3 # number of hashtables
ht = khmer.new_hashbits(K, HT_SIZE, N_HT)
# without tagging/joining across consume, this breaks into two partition;
# with, it is one partition.
ht.add_stop_tag('CCGAATATATAACAGCGACG')
ht.consume_fasta_and_tag_with_stoptags(filename) # DO join reads across
subset = ht.do_subset_partition(0, 0)
n, _ = ht.count_partitions()
assert n == 99 # reads only connected by traversal...
n, _ = ht.subset_count_partitions(subset)
assert n == 2 # but need main to cross stoptags.
ht.merge_subset(subset)
n, _ = ht.count_partitions() # ta-da!
assert n == 1, n
def test_notag_across_stoptraverse():
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 1e4 # size of hashtable
N_HT = 3 # number of hashtables
ht = khmer.new_hashbits(K, HT_SIZE, N_HT)
# connecting k-mer at the beginning/end of a read: breaks up into two.
ht.add_stop_tag('TTGCATACGTTGAGCCAGCG')
ht.consume_fasta_and_tag_with_stoptags(filename)
subset = ht.do_subset_partition(0, 0)
ht.merge_subset(subset)
n, _ = ht.count_partitions()
assert n == 2, n
def test_find_stoptags():
ht = khmer.new_hashbits(5, 1, 1)
ht.add_stop_tag("AAAAA")
assert ht.identify_stoptags_by_position("AAAAA") == [0]
assert ht.identify_stoptags_by_position("AAAAAA") == [0, 1]
assert ht.identify_stoptags_by_position("TTTTT") == [0]
assert ht.identify_stoptags_by_position("TTTTTT") == [0, 1]
def test_find_stoptags2():
ht = khmer.new_hashbits(4, 1, 1)
ht.add_stop_tag("ATGC")
x = ht.identify_stoptags_by_position("ATGCATGCGCAT")
assert x == [0, 2, 4, 8], x
def test_get_ksize():
kh = khmer.new_hashbits(22, 1, 1)
assert kh.ksize() == 22
def test_get_hashsizes():
kh = khmer.new_hashbits(22, 100, 4)
assert kh.hashsizes() == [101, 103, 107, 109], kh.hashsizes()
def test_extract_unique_paths_0():
kh = khmer.new_hashbits(10, 4, 4)
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
assert x == ['ATGGAGAGACACAGATAGACAGGAGTGGCGATG']
kh.consume('ATGGAGAGACACAGATAGACAGGAGTGGCGATG')
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
assert not x
def test_extract_unique_paths_1():
kh = khmer.new_hashbits(10, 4, 4)
kh.consume('AGTGGCGATG')
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
print x
assert x == ['ATGGAGAGACACAGATAGACAGGAGTGGCGAT'] # all but the last k-mer
def test_extract_unique_paths_2():
kh = khmer.new_hashbits(10, 4, 4)
kh.consume('ATGGAGAGAC')
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
print x
assert x == ['TGGAGAGACACAGATAGACAGGAGTGGCGATG'] # all but the 1st k-mer
def test_extract_unique_paths_3():
kh = khmer.new_hashbits(10, 4, 4)
kh.consume('ATGGAGAGAC')
kh.consume('AGTGGCGATG')
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
print x
# all but the 1st/last k-mer
assert x == ['TGGAGAGACACAGATAGACAGGAGTGGCGAT']
def test_extract_unique_paths_4():
kh = khmer.new_hashbits(10, 4, 4)
kh.consume('ATGGAGAGAC')
kh.consume('AGTGGCGATG')
kh.consume('ATAGACAGGA')
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
print x
assert x == ['TGGAGAGACACAGATAGACAGG', 'TAGACAGGAGTGGCGAT']
def test_find_unpart():
filename = utils.get_test_data('random-20-a.odd.fa')
filename2 = utils.get_test_data('random-20-a.even.fa')
K = 20 # size of kmer
HT_SIZE = 1e4 # size of hashtable
N_HT = 3 # number of hashtables
ht = khmer.new_hashbits(K, HT_SIZE, N_HT)
ht.consume_fasta_and_tag(filename)
subset = ht.do_subset_partition(0, 0)
ht.merge_subset(subset)
n, _ = ht.count_partitions()
assert n == 49
ht.find_unpart(filename2, True, False)
n, _ = ht.count_partitions()
| |
<reponame>tupui/rbc
"""Implement Buffer type as a base class to HeavyDB Array and Column types.
HeavyDB Buffer represents the following structure:
template<typename T>
struct Buffer {
T* ptr;
size_t sz;
...
}
that is, a structure that has at least two members where the first is
a pointer to some data type and the second is the size of the buffer.
This module implements the support for the following Python operators:
len
__getitem__
__setitem__
to provide a minimal functionality for accessing and manipulating the
HeavyDB buffer objects from UDF/UDTFs.
"""
import operator
from .metatype import HeavyDBMetaType
from llvmlite import ir
import numpy as np
from rbc import typesystem, irutils, errors
from rbc.targetinfo import TargetInfo
from numba.core import datamodel, cgutils, extending, types, imputils
int8_t = ir.IntType(8)
int32_t = ir.IntType(32)
int64_t = ir.IntType(64)
void_t = ir.VoidType()
fp32 = ir.FloatType()
fp64 = ir.DoubleType()
class HeavyDBBufferType(typesystem.Type):
"""Typesystem type class for HeavyDB buffer structures.
"""
# When True, buffer type arguments are passed by value to
# functions [not recommended].
@property
def pass_by_value(self):
return False
@property
def numba_pointer_type(self):
return BufferPointer
@classmethod
def preprocess_args(cls, args):
assert len(args) == 1, args
assert len(args[0]) == 1, args
element_type = args[0][0]
if not isinstance(element_type, typesystem.Type):
element_type = typesystem.Type.fromobject(element_type)
return ((element_type,),)
@property
def element_type(self):
return self[0][0]
@property
def buffer_extra_members(self):
return ()
def tonumba(self, bool_is_int8=None):
ptr_t = typesystem.Type(self.element_type, '*', name='ptr')
size_t = typesystem.Type.fromstring('size_t sz')
extra_members = tuple(map(typesystem.Type.fromobject, self.buffer_extra_members))
buffer_type = typesystem.Type(
ptr_t,
size_t,
*extra_members
)
buffer_type._params['NumbaType'] = BufferType
buffer_type._params['NumbaPointerType'] = self.numba_pointer_type
numba_type = buffer_type.tonumba(bool_is_int8=True)
if self.pass_by_value:
return numba_type
return self.numba_pointer_type(numba_type)
class BufferType(types.Type):
"""Numba type class for HeavyDB buffer structures.
"""
@property
def eltype(self):
"""
Return buffer element dtype.
"""
return self.members[0].dtype
class BufferPointer(types.IterableType):
"""Numba type class for pointers to HeavyDB buffer structures.
We are not deriving from CPointer because BufferPointer getitem is
used to access the data stored in Buffer ptr member.
"""
mutable = True
return_as_first_argument = True
def __init__(self, dtype):
self.dtype = dtype # struct dtype
self.eltype = dtype.eltype # buffer element dtype
name = "%s[%s]*" % (type(self).__name__, dtype)
super().__init__(name)
@property
def key(self):
return self.dtype
@property
def iterator_type(self):
return BufferPointerIteratorType(self)
class BufferPointerIteratorType(types.SimpleIteratorType):
def __init__(self, buffer_type):
name = f"iter_buffer({buffer_type})"
self.buffer_type = buffer_type
super().__init__(name, self.buffer_type.eltype)
@datamodel.register_default(BufferPointerIteratorType)
class BufferPointerIteratorModel(datamodel.StructModel):
def __init__(self, dmm, fe_type):
members = [('index', types.EphemeralPointer(types.uintp)),
('buffer', fe_type.buffer_type)]
super(BufferPointerIteratorModel, self).__init__(dmm, fe_type, members)
class BufferMeta(HeavyDBMetaType):
pass
class Buffer(object, metaclass=BufferMeta):
"""Represents HeavyDB Buffer that can be constructed within UDF/UDTFs.
"""
@datamodel.register_default(BufferPointer)
class BufferPointerModel(datamodel.models.PointerModel):
"""Base class for HeavyDB buffer pointer models.
Subclasses should register the model for the corresponding
BufferPointer subclass, for instance::
@datamodel.register_default(ArrayPointer)
class ArrayPointerModel(BufferPointerModel):
pass
"""
def heavydb_buffer_constructor(context, builder, sig, args):
"""
Usage:
extending.lower_builtin(MyBuffer, numba.types.Integer, ...)(heavydb_buffer_constructor)
will enable creating MyBuffer instance from a HeavyDB UDF/UDTF definition:
b = MyBuffer(<size>, ...)
"""
ptr_type, sz_type = sig.return_type.dtype.members[:2]
if len(sig.return_type.dtype.members) > 2:
assert len(sig.return_type.dtype.members) == 3
null_type = sig.return_type.dtype.members[2]
else:
null_type = None
assert isinstance(args[0].type, ir.IntType), (args[0].type)
element_count = builder.zext(args[0], int64_t)
element_size = int64_t(ptr_type.dtype.bitwidth // 8)
alloc_fnty = ir.FunctionType(int8_t.as_pointer(), [int64_t, int64_t])
alloc_fn_name = 'allocate_varlen_buffer'
alloc_fn = irutils.get_or_insert_function(builder.module, alloc_fnty, alloc_fn_name)
ptr8 = builder.call(alloc_fn, [element_count, element_size])
ptr = builder.bitcast(ptr8, context.get_value_type(ptr_type))
fa = cgutils.create_struct_proxy(sig.return_type.dtype)(context, builder)
fa.ptr = ptr # T*
fa.sz = element_count # size_t
if null_type is not None:
is_zero = builder.icmp_signed('==', element_count, int64_t(0))
with builder.if_else(is_zero) as (then, orelse):
with then:
is_null = context.get_value_type(null_type)(1)
with orelse:
is_null = context.get_value_type(null_type)(0)
fa.is_null = is_null # int8_t
return fa._getpointer()
@extending.intrinsic
def heavydb_buffer_ptr_get_ptr_(typingctx, data):
eltype = data.eltype
ptrtype = types.CPointer(eltype)
sig = ptrtype(data)
def codegen(context, builder, signature, args):
data, = args
rawptr = cgutils.alloca_once_value(builder, value=data)
struct = builder.load(builder.gep(rawptr,
[int32_t(0)]))
return builder.load(builder.gep(struct, [int32_t(0), int32_t(0)]))
return sig, codegen
@extending.intrinsic
def heavydb_buffer_get_ptr_(typingctx, data):
eltype = data.eltype
ptrtype = types.CPointer(eltype)
sig = ptrtype(data)
def codegen(context, builder, signature, args):
data, = args
assert data.opname == 'load'
struct = data.operands[0]
return builder.load(builder.gep(struct, [int32_t(0), int32_t(0)]))
return sig, codegen
@extending.intrinsic
def heavydb_buffer_ptr_item_get_ptr_(typingctx, data, index):
eltype = data.eltype
ptrtype = types.CPointer(eltype)
sig = ptrtype(data, index)
def codegen(context, builder, signature, args):
data, index = args
rawptr = cgutils.alloca_once_value(builder, value=data)
struct = builder.load(builder.gep(rawptr, [int32_t(0)]))
ptr = builder.load(builder.gep(struct, [int32_t(0), int32_t(0)]))
return builder.gep(ptr, [index])
return sig, codegen
@extending.overload_method(BufferPointer, 'ptr')
def heavydb_buffer_get_ptr(x, index=None):
if isinstance(x, BufferPointer):
if cgutils.is_nonelike(index):
def impl(x, index=None):
return heavydb_buffer_ptr_get_ptr_(x)
else:
def impl(x, index=None):
return heavydb_buffer_ptr_item_get_ptr_(x, index)
return impl
if isinstance(x, BufferType):
if cgutils.is_nonelike(index):
def impl(x, index=None):
return heavydb_buffer_get_ptr_(x)
else:
raise NotImplementedError(f'heavydb_buffer_item_get_ptr_({x}, {index})')
return impl
@extending.intrinsic
def heavydb_buffer_ptr_len_(typingctx, data):
sig = types.int64(data)
def codegen(context, builder, signature, args):
data, = args
rawptr = cgutils.alloca_once_value(builder, value=data)
struct = builder.load(builder.gep(rawptr,
[int32_t(0)]))
return builder.load(builder.gep(
struct, [int32_t(0), int32_t(1)]))
return sig, codegen
@extending.intrinsic
def heavydb_buffer_len_(typingctx, data):
sig = types.int64(data)
def codegen(context, builder, signature, args):
data, = args
return irutils.get_member_value(builder, data, 1)
return sig, codegen
@extending.overload(len)
def heavydb_buffer_len(x):
if isinstance(x, BufferPointer):
return lambda x: heavydb_buffer_ptr_len_(x)
if isinstance(x, BufferType):
return lambda x: heavydb_buffer_len_(x)
@extending.intrinsic
def heavydb_buffer_ptr_getitem_(typingctx, data, index):
sig = data.eltype(data, index)
def codegen(context, builder, signature, args):
data, index = args
rawptr = cgutils.alloca_once_value(builder, value=data)
buf = builder.load(builder.gep(rawptr, [int32_t(0)]))
ptr = builder.load(builder.gep(
buf, [int32_t(0), int32_t(0)]))
res = builder.load(builder.gep(ptr, [index]))
return res
return sig, codegen
@extending.intrinsic
def heavydb_buffer_getitem_(typingctx, data, index):
eltype = data.eltype
sig = eltype(data, index)
def codegen(context, builder, signature, args):
data, index = args
ptr = irutils.get_member_value(builder, data, 0)
res = builder.load(builder.gep(ptr, [index]))
return res
return sig, codegen
@extending.overload(operator.getitem)
def heavydb_buffer_getitem(x, i):
if isinstance(x, BufferPointer):
return lambda x, i: heavydb_buffer_ptr_getitem_(x, i)
if isinstance(x, BufferType):
return lambda x, i: heavydb_buffer_getitem_(x, i)
# [rbc issue-197] Numba promotes operations like
# int32(a) + int32(b) to int64
def truncate_cast_or_extend(builder, value, typ, signed):
def _cast(builder, value, typ, signed):
fn = {
# unsigned int := float
(ir.IntType, ir.FloatType, False): builder.uitofp,
(ir.IntType, ir.DoubleType, False): builder.uitofp,
# signed int := float
(ir.IntType, ir.FloatType, True): builder.sitofp,
(ir.IntType, ir.DoubleType, True): builder.sitofp,
# float := unsigned int
(ir.FloatType, ir.IntType, False): builder.fptoui,
(ir.DoubleType, ir.IntType, False): builder.fptoui,
# float := signed int
(ir.FloatType, ir.IntType, True): builder.fptosi,
(ir.DoubleType, ir.IntType, True): builder.fptosi,
}[(type(value.type), type(typ), signed)]
return fn(value, typ)
def _truncate(builder, value, typ, signed):
if isinstance(typ, ir.IntType):
fn = builder.trunc
else:
fn = builder.fptrunc
return fn(value, typ)
def _extend(builder, value, typ, signed):
if isinstance(typ, ir.IntType):
fn = builder.zext if signed else builder.sext
else:
fn = builder.fpext
return fn(value, typ)
if not isinstance(value.type, (ir.IntType, ir.FloatType, ir.DoubleType)):
raise errors.NumbaTypeError('Can only truncate, cast or extend int, float or double')
if value.type.__class__ != typ.__class__ and \
ir.IntType in (value.type.__class__, typ.__class__):
value = _cast(builder, value, typ, signed)
if isinstance(value.type, ir.IntType):
if value.type.width < typ.width:
return _extend(builder, value, typ, signed)
elif value.type.width > typ.width:
return _truncate(builder, value, typ, signed)
elif isinstance(value.type, ir.FloatType):
if isinstance(typ, ir.DoubleType):
return _extend(builder, value, typ, signed)
elif isinstance(value.type, ir.DoubleType):
if isinstance(typ, ir.FloatType):
return _truncate(builder, value, typ, signed)
return value
@extending.intrinsic
def heavydb_buffer_ptr_setitem_(typingctx, data, index, value):
sig = types.none(data, index, value)
signed = value.signed if isinstance(value, types.Integer) else True
def codegen(context, builder, signature, args):
zero = int32_t(0)
data, index, value = args
rawptr = cgutils.alloca_once_value(builder, value=data)
ptr = builder.load(rawptr)
buf = builder.load(builder.gep(ptr, [zero, zero]))
value = truncate_cast_or_extend(builder, value, buf.type.pointee, signed)
builder.store(value, builder.gep(buf, [index]))
return sig, codegen
@extending.intrinsic
def heavydb_buffer_setitem_(typingctx, data, index, value):
sig = types.none(data, index, value)
signed = value.signed if isinstance(value, types.Integer) else True
def codegen(context, builder, signature, args):
data, index, value = args
ptr = irutils.get_member_value(builder, data, 0)
value = truncate_cast_or_extend(builder, value, ptr.type.pointee, signed)
builder.store(value, builder.gep(ptr, [index]))
return sig, codegen
@extending.overload(operator.setitem)
def heavydb_buffer_setitem(a, i, v):
if isinstance(a, BufferPointer):
return lambda a, i, v: heavydb_buffer_ptr_setitem_(a, i, v)
if isinstance(a, BufferType):
return lambda a, i, v: heavydb_buffer_setitem_(a, i, v)
@extending.intrinsic
def heavydb_buffer_is_null_(typingctx, data):
sig = types.int8(data)
def codegen(context, builder, sig, args):
rawptr = cgutils.alloca_once_value(builder, value=args[0])
ptr = builder.load(rawptr)
return builder.load(builder.gep(ptr, [int32_t(0), int32_t(2)]))
return sig, codegen
@extending.intrinsic
def heavydb_buffer_set_null_(typingctx, data):
sig = types.none(data)
def codegen(context, builder, sig, args):
rawptr = cgutils.alloca_once_value(builder, value=args[0])
ptr = builder.load(rawptr)
builder.store(int8_t(1), builder.gep(ptr, [int32_t(0), int32_t(2)]))
return sig, codegen
@extending.intrinsic
def heavydb_buffer_idx_is_null_(typingctx, col_var, row_idx):
T = col_var.eltype
sig = types.boolean(col_var, row_idx)
target_info = TargetInfo()
null_value = target_info.null_values[str(T)]
# The server sends numbers as unsigned values rather than signed ones.
# Thus, 129 should be read as -127 (overflow). See rbc issue #254
nv = ir.Constant(ir.IntType(T.bitwidth), null_value)
def codegen(context, builder, signature, args):
ptr, index = args
data = builder.extract_value(builder.load(ptr), [0])
res = builder.load(builder.gep(data, [index]))
if isinstance(T, types.Float):
res = builder.bitcast(res, nv.type)
return builder.icmp_signed('==', res, nv)
return sig, codegen
# "BufferPointer.is_null" checks if a given array or column is null
# as opposed to "BufferType.is_null" that checks if an index in a
# column is null
@extending.overload_method(BufferPointer, 'is_null')
def heavydb_buffer_is_null(x, | |
from __future__ import division
from . import _breaks
import itertools
import math
class Classifier(object):
def __init__(self, items, breaks, classvalues, key=None, **kwargs):
self.items = items
if isinstance(breaks, bytes):
algo = breaks
breaks = None
else:
algo = "custom"
breaks = breaks
self.algo = algo
self.breaks = breaks
self.classvalues = classvalues # the raw preinterpolated valuestops of the classvalues
self.key = key
self.kwargs = kwargs
self.classvalues_interp = None # the final interpolated classvalues
self.update()
def __repr__(self):
import pprint
metadict = dict(algo=self.algo,
breaks=self.breaks,
classvalues_interp=self.classvalues_interp)
return "Classifier object:\n" + pprint.pformat(metadict, indent=4)
def update(self):
# force update/calculate breaks and class values
# mostly used internally, though can be used to recalculate
if self.algo == "unique":
self.classvalues_interp = self.classvalues
elif self.algo == "proportional":
self.classvalues_interp = [self.classvalues[0], self.classvalues[-1]]
items,values = zip(*rescale(self.items,
newmin=self.classvalues_interp[0],
newmax=self.classvalues_interp[-1],
key=self.key,
**self.kwargs))
itemvals = [self.key(item) for item in items]
if self.classvalues_interp[0] < self.classvalues_interp[-1]:
minval,maxval = min(itemvals), max(itemvals)
else:
minval,maxval = max(itemvals), min(itemvals)
self.breaks = [minval,maxval]
else:
if self.algo != "custom":
self.breaks = breaks(items=self.items,
algorithm=self.algo,
key=self.key,
**self.kwargs)
self.classvalues_interp = class_values(len(self.breaks)-1, # -1 because break values include edgevalues so will be one more in length
self.classvalues)
def __iter__(self):
# loop and yield items along with their classnum and classvalue
if self.algo == "unique":
if isinstance(self.classvalues_interp, dict):
# only return specified uniqueval-classval pairs
for uid,subitems in unique(self.items, key=self.key, **self.kwargs):
if uid in self.classvalues_interp:
classval = self.classvalues_interp[uid]
for item in subitems:
yield item,classval
else:
# eternally iterate over classvalues for each unique value
def classvalgen ():
while True:
for classval in self.classvalues_interp:
yield classval
classvalgen = classvalgen()
for uid,subitems in unique(self.items, key=self.key, **self.kwargs):
classval = next(classvalgen)
for item in subitems:
yield item,classval
elif self.algo == "proportional":
for item,newval in rescale(self.items,
newmin=self.classvalues_interp[0],
newmax=self.classvalues_interp[-1],
key=self.key,
**self.kwargs):
yield item,newval
else:
for valrange,subitems in split(self.items, self.breaks, key=self.key, **self.kwargs):
midval = (valrange[0] + valrange[1]) / 2.0
classinfo = self.find_class(midval)
if classinfo is not None:
classnum,_ = classinfo
classval = self.classvalues_interp[classnum-1] # index is zero-based while find_class returns 1-based
for item in subitems:
yield item,classval
def find_class(self, value):
return find_class(value, self.breaks)
################################
def find_class(value, breaks):
"""
Given a set of breakpoints, calculate which two breakpoints an input
value is located between, returning the class number (1 as the first class)
and the two enclosing breakpoint values. A value that is not between any of
the breakpoints, ie larger or smaller than the break endpoints, is considered
to be a miss and returns None.
"""
prevbrk = breaks[0]
classnum = 1
for nextbrk in breaks[1:]:
if eval(bytes(prevbrk)) <= eval(bytes(value)) <= eval(bytes(nextbrk)):
return classnum, (prevbrk,nextbrk)
prevbrk = nextbrk
classnum += 1
else:
# Value was not within the range of the break points
return None
def class_values(classes, valuestops):
"""
Return x number of class values linearly interpolated
between a minimum and maximum value.
- classes: Number of classes values to return.
- valuestops: can be either a single number or sequences of numbers
where a classvalue will be interpolated for each sequence number,
and so all sequences must be equally long. Thus, specifying the
valuestops as rgb color tuples will create interpolated color gradients.
"""
# special case
if classes <= 1:
#raise Exception("Number of classes must be higher than 1")
return [valuestops[0]]
if len(valuestops) < 2:
raise Exception("There must be at least two items in valuestops for interpolating between")
def _lerp(val, oldfrom, oldto, newfrom, newto):
oldrange = oldto - oldfrom
relval = (val - oldfrom) / float(oldrange)
newrange = newto - newfrom
newval = newfrom + newrange * relval
return newval
# determine appropriate interp func for either sequenes or single values
if all(hasattr(valstop, "__iter__") for valstop in valuestops):
_len = len(valuestops[0])
if any(len(valstop) != _len for valstop in valuestops):
raise Exception("If valuestops are sequences they must all have the same length")
def _interpfunc(val):
relindex = _lerp(classnum, 0, classes-1, 0, len(valuestops)-1)
fromval = valuestops[int(math.floor(relindex))]
toval = valuestops[int(math.ceil(relindex))]
classval = [_lerp(relindex, int(relindex), int(relindex+1), ifromval, itoval)
for ifromval,itoval in zip(fromval,toval)]
return classval
else:
def _interpfunc(classnum):
relindex = _lerp(classnum, 0, classes-1, 0, len(valuestops)-1)
fromval = valuestops[int(math.floor(relindex))]
toval = valuestops[int(math.ceil(relindex))]
classval = _lerp(relindex, int(relindex), int(relindex+1), fromval, toval)
return classval
# perform
classvalues = []
for classnum in range(classes):
classval = _interpfunc(classnum)
classvalues.append(classval)
return classvalues
def breaks(items, algorithm, key=None, extrabreaks=None, exclude=None, minval=None, maxval=None, **kwargs):
"""
Only get the break points, including the start and endpoint.
"""
# ensure values are numeric
def forcenumber(val):
try:
val = float(val)
return val
except:
return None
# sort by key
if key:
keywrap = lambda x: forcenumber(key(x))
else:
keywrap = forcenumber
items = (item for item in items if keywrap(item) is not None)
if exclude is not None:
if not isinstance(exclude, (list,tuple)): exclude = [exclude]
items = (item for item in items if keywrap(item) not in exclude)
if minval is not None: items = (item for item in items if keywrap(item) >= minval)
if maxval is not None: items = (item for item in items if keywrap(item) <= maxval)
items = sorted(items, key=keywrap)
values = [keywrap(item) for item in items]
# get breaks
func = _breaks.__dict__[algorithm]
breaks = func(values, **kwargs)
# insert extra breaks (list of single break values or pairs)
if extrabreaks:
for val in extrabreaks:
oldbreaks = list(breaks)
# insert single break value anywhere after first same or greater breakpoint
# (remember that duplicate breakpoints will collect only that specific value)
prevbrk = oldbreaks[0]
i = 0
for nextbrk in oldbreaks[1:]:
if prevbrk <= val < nextbrk:
breaks.insert(i, val)
break
else:
prevbrk = nextbrk
i += 1
return breaks
def split(items, breaks, key=None, exclude=None, minval=None, maxval=None, **kwargs):
"""
Splits a list of items into n non-overlapping classes based on the
specified algorithm. Values are either the items themselves or
a value extracted from the item using the key function.
Arguments:
- **items**: The list of items or values to classify.
- **breaks**: List of custom break values, or the name of the algorithm to use.
Valid names are:
- histogram (alias for equal)
- equal
- quantile
- pretty
- stdev
- natural
- headtail
- log (base-10, uses offset to handle 0s but not negative numbers)
- **key** (optional): Function used to extract value from each item, defaults to None and treats item itself as the value.
- **classes** (optional): The number of classes to group the items into.
- more...
Returns:
- All the input items reorganized into the groups/classes that they belong to,
as a list of lists of items.
"""
# ensure values are numeric
def forcenumber(val):
try:
val = float(val)
return val
except:
return None
# sort and get key
if key:
keywrap = lambda x: forcenumber(key(x))
else:
keywrap = forcenumber
items = (item for item in items if keywrap(item) is not None)
if exclude is not None:
if not isinstance(exclude, (list,tuple)): exclude = [exclude]
items = (item for item in items if keywrap(item) not in exclude)
if minval is not None: items = (item for item in items if keywrap(item) >= minval)
if maxval is not None: items = (item for item in items if keywrap(item) <= maxval)
items = sorted(items, key=keywrap)
values = [keywrap(item) for item in items]
# if not custom specified, get break values from algorithm name
if isinstance(breaks, bytes):
func = _breaks.__dict__[breaks]
breaks = func(values, **kwargs)
else:
# custom specified breakpoints
breaks = list(breaks)
breaks_gen = (brk for brk in breaks)
loopdict = dict()
loopdict["prevbrk"] = next(breaks_gen)
loopdict["nextbrk"] = next(breaks_gen)
def find_class(item, loopdict=loopdict):
val = keywrap(item)
## while eval(bytes(val)) > eval(bytes(loopdict["nextbrk"])):
## loopdict["prevbrk"] = loopdict["nextbrk"]
## loopdict["nextbrk"] = next(breaks_gen)
## if eval(bytes(loopdict["prevbrk"])) <= eval(bytes(val)) <= eval(bytes(loopdict["nextbrk"])):
## return loopdict["prevbrk"],loopdict["nextbrk"]
## if eval(bytes(val)) < loopdict["prevbrk"]:
## # value lower than first class
## return None
## else:
## while not (eval(bytes(loopdict["prevbrk"])) <= eval(bytes(val)) <= eval(bytes(loopdict["nextbrk"]))):
## print eval(bytes(loopdict["prevbrk"])) , eval(bytes(val)) , eval(bytes(loopdict["nextbrk"]))
## # increment breaks until value is between
## loopdict["prevbrk"] = loopdict["nextbrk"]
## loopdict["nextbrk"] = next(breaks_gen, None)
## if loopdict["nextbrk"] == None:
## return None
## # | |
<filename>species/analysis/fit_model.py<gh_stars>0
"""
Module with functionalities for fitting atmospheric model spectra.
"""
import os
import math
import warnings
from typing import Optional, Union, List, Tuple, Dict
from multiprocessing import Pool, cpu_count
import emcee
import numpy as np
import spectres
from scipy import stats
try:
import ultranest
except:
warnings.warn(
"UltraNest could not be imported. Perhaps "
"because cython was not correctly compiled?"
)
try:
import pymultinest
except:
warnings.warn(
"PyMultiNest could not be imported. "
"Perhaps because MultiNest was not build "
"and/or found at the LD_LIBRARY_PATH "
"(Linux) or DYLD_LIBRARY_PATH (Mac)?"
)
from typeguard import typechecked
from species.analysis import photometry
from species.data import database
from species.core import constants
from species.read import read_model, read_object, read_planck, read_filter
from species.util import read_util, dust_util
warnings.filterwarnings("always", category=DeprecationWarning)
@typechecked
def lnprior(
param: np.ndarray,
bounds: dict,
param_index: Dict[str, int],
prior: Optional[Dict[str, Tuple[float, float]]] = None,
):
"""
Internal function for calculating the log prior.
Parameters
----------
param : np.ndarray
Parameter values.
bounds : dict
Dictionary with the parameter boundaries.
param_index : dict(str, int)
Dictionary with the parameter indices of ``param``.
prior : dict(str, tuple(float, float)), None
Dictionary with Gaussian priors for one or multiple parameters.
The prior can be set for any of the atmosphere or calibration
parameters, e.g. ``prior={'teff': (1200., 100.)}``.
Additionally, a prior can be set for the mass, e.g.
``prior={'mass': (13., 3.)}`` for an expected mass of 13 Mjup
with an uncertainty of 3 Mjup. The parameter is not used if set
to ``None``.
Returns
-------
floats
Log prior.
"""
ln_prior = 0
for key, value in bounds.items():
if value[0] <= param[param_index[key]] <= value[1]:
ln_prior += 0.0
else:
ln_prior = -np.inf
break
if prior is not None:
for key, value in prior.items():
if key == "mass":
mass = read_util.get_mass(
param[param_index["logg"]], param[param_index["radius"]]
)
ln_prior += -0.5 * (mass - value[0]) ** 2 / value[1] ** 2
else:
ln_prior += (
-0.5 * (param[param_index[key]] - value[0]) ** 2 / value[1] ** 2
)
return ln_prior
@typechecked
def lnlike(
param: np.ndarray,
bounds: dict,
param_index: Dict[str, int],
model: str,
objphot: List[Optional[np.ndarray]],
distance: Tuple[float, float],
spectrum: Optional[dict],
modelphot: Optional[
Union[List[read_model.ReadModel], List[photometry.SyntheticPhotometry]]
],
modelspec: Optional[List[read_model.ReadModel]],
n_planck: int,
fit_corr: List[str],
):
"""
Internal function for calculating the log likelihood.
Parameters
----------
param : np.ndarray
Parameter values.
bounds : dict
Dictionary with the parameter boundaries.
param_index : dict(str, int)
Dictionary with the parameter indices of ``param``.
model : str
Atmosphere model (e.g. 'bt-settl', 'exo-rem', or 'planck).
objphot : list(np.ndarray)
List with the photometric fluxes and uncertainties of the
object. Not photometric data is fitted if an empty list is
provided.
distance : tuple(float, float)
Distance and uncertainty (pc).
spectrum : dict(str, tuple(np.ndarray, np.ndarray, np.ndarray, float)), None
Dictionary with the spectra stored as wavelength (um), flux
(W m-2 um-1), and error (W m-2 um-1). Optionally the covariance
matrix, the inverse of the covariance matrix, and the spectral
resolution are included. Each of these three elements can be
set to ``None``. No spectroscopic data is fitted if
``spectrum=None``.
modelphot : list(species.read.read_model.ReadModel),
list(species.analysis.photometry.SyntheticPhotometry), None
List with the interpolated synthetic fluxes or list with the
:class:`~species.analysis.photometry.SyntheticPhotometry`
objects for calculation of synthetic photometry for Planck
spectra. No photometry is fitted if set to ``None``.
modelspec : list(species.read.read_model.ReadModel), None
List with the interpolated synthetic spectra.
n_planck : int
Number of Planck components. The argument is set to zero
if ``model`` is not equal to ``'planck'``.
fit_corr : list(str)
List with spectrum names for which the covariances are modeled
with a Gaussian process (see Wang et al. 2020). This option can
be used if the actual covariances as determined from the data
are not available. The parameters that will be fitted are the
correlation length and fractional amplitude.
Returns
-------
float
Log likelihood.
"""
param_dict = {}
spec_scaling = {}
err_scaling = {}
corr_len = {}
corr_amp = {}
for item in bounds:
if item[:8] == "scaling_" and item[8:] in spectrum:
spec_scaling[item[8:]] = param[param_index[item]]
elif item[:6] == "error_" and item[6:] in spectrum:
err_scaling[item[6:]] = param[param_index[item]]
elif item[:9] == "corr_len_" and item[9:] in spectrum:
corr_len[item[9:]] = 10.0 ** param[param_index[item]] # (um)
elif item[:9] == "corr_amp_" and item[9:] in spectrum:
corr_amp[item[9:]] = param[param_index[item]]
else:
param_dict[item] = param[param_index[item]]
if model == "planck":
param_dict["distance"] = param[param_index["distance"]]
else:
flux_scaling = (param_dict["radius"] * constants.R_JUP) ** 2 / (
param_dict["distance"] * constants.PARSEC
) ** 2
# The scaling is applied manually because of the interpolation
del param_dict["radius"]
for item in spectrum:
if item not in spec_scaling:
spec_scaling[item] = 1.0
if item not in err_scaling:
err_scaling[item] = None
ln_like = 0.0
if model == "planck" and n_planck > 1:
for i in range(n_planck - 1):
if param_dict[f"teff_{i+1}"] > param_dict[f"teff_{i}"]:
return -np.inf
if param_dict[f"radius_{i}"] > param_dict[f"radius_{i+1}"]:
return -np.inf
for i, obj_item in enumerate(objphot):
if model == "planck":
readplanck = read_planck.ReadPlanck(filter_name=modelphot[i].filter_name)
phot_flux = readplanck.get_flux(param_dict, synphot=modelphot[i])[0]
else:
phot_flux = modelphot[i].spectrum_interp(list(param_dict.values()))
phot_flux *= flux_scaling
if obj_item.ndim == 1:
ln_like += -0.5 * (obj_item[0] - phot_flux) ** 2 / obj_item[1] ** 2
else:
for j in range(obj_item.shape[1]):
ln_like += (
-0.5 * (obj_item[0, j] - phot_flux) ** 2 / obj_item[1, j] ** 2
)
for i, item in enumerate(spectrum.keys()):
# Calculate or interpolate the model spectrum
if model == "planck":
# Calculate a blackbody spectrum
readplanck = read_planck.ReadPlanck(
(0.9 * spectrum[item][0][0, 0], 1.1 * spectrum[item][0][-1, 0])
)
model_box = readplanck.get_spectrum(param_dict, 1000.0, smooth=True)
# Resample the spectrum to the observed wavelengths
model_flux = spectres.spectres(
spectrum[item][0][:, 0], model_box.wavelength, model_box.flux
)
else:
# Interpolate the model spectrum
model_flux = modelspec[i].spectrum_interp(list(param_dict.values()))[0, :]
# Scale the spectrum by the (radius/distance)^2
model_flux *= flux_scaling
# Scale the spectrum data
data_flux = spec_scaling[item] * spectrum[item][0][:, 1]
if err_scaling[item] is None:
# Variance without error inflation
data_var = spectrum[item][0][:, 2] ** 2
else:
# Variance with error inflation (see Piette & Madhusudhan 2020)
data_var = (
spectrum[item][0][:, 2] ** 2 + (err_scaling[item] * model_flux) ** 2
)
if spectrum[item][2] is not None:
# The inverted covariance matrix is available
if err_scaling[item] is None:
# Use the inverted covariance matrix directly
data_cov_inv = spectrum[item][2]
else:
# Ratio of the inflated and original uncertainties
sigma_ratio = np.sqrt(data_var) / spectrum[item][0][:, 2]
sigma_j, sigma_i = np.meshgrid(sigma_ratio, sigma_ratio)
# Calculate the inverted matrix of the inflated covariances
data_cov_inv = np.linalg.inv(spectrum[item][1] * sigma_i * sigma_j)
if spectrum[item][2] is not None:
# Calculate the log-likelihood with the covariance matrix
dot_tmp = np.dot(
data_flux - model_flux, np.dot(data_cov_inv, data_flux - model_flux)
)
ln_like += -0.5 * dot_tmp - 0.5 * np.nansum(np.log(2.0 * np.pi * data_var))
else:
if item in fit_corr:
# Calculate the log-likelihood with the
# covariance model (see Wang et al. 2020)
wavel = spectrum[item][0][:, 0] # (um)
wavel_j, wavel_i = np.meshgrid(wavel, wavel)
error = np.sqrt(data_var) # (W m-2 um-1)
error_j, error_i = np.meshgrid(error, error)
cov_matrix = (
corr_amp[item] ** 2
* error_i
* error_j
* np.exp(-((wavel_i - wavel_j) ** 2) / (2.0 * corr_len[item] ** 2))
+ (1.0 - corr_amp[item] ** 2)
* np.eye(wavel.shape[0])
* error_i ** 2
)
dot_tmp = np.dot(
data_flux - model_flux,
np.dot(np.linalg.inv(cov_matrix), data_flux - model_flux),
)
ln_like += -0.5 * dot_tmp - 0.5 * np.nansum(
np.log(2.0 * np.pi * data_var)
)
else:
# Calculate the log-likelihood without the covariance matrix but with the
# normalization term in case of the errors are inflated
ln_like += np.nansum(
-0.5 * (data_flux - model_flux) ** 2 / data_var
- 0.5 * np.log(2.0 * np.pi * data_var)
)
return ln_like
@typechecked
def lnprob(
param: np.ndarray,
bounds: dict,
model: str,
param_index: Dict[str, int],
objphot: List[Optional[np.ndarray]],
distance: Tuple[float, float],
prior: Optional[Dict[str, Tuple[float, float]]],
spectrum: Optional[dict],
modelphot: Optional[
Union[List[read_model.ReadModel], List[photometry.SyntheticPhotometry]]
],
modelspec: Optional[List[read_model.ReadModel]],
n_planck: int,
fit_corr: List[str],
) -> np.float64:
"""
Internal function for calculating the log posterior.
Parameters
----------
param : np.ndarray
Parameter values.
bounds : dict
Parameter boundaries.
model : str
Atmosphere model (e.g. 'bt-settl', 'exo-rem', or 'planck).
param_index : dict(str, int)
Dictionary with the parameter indices of ``param``.
objphot : list(np.ndarray), None
List with the photometric fluxes and uncertainties. No
photometric data is fitted if the parameter is set to ``None``.
distance : tuple(float, float)
Distance and uncertainty (pc).
prior : dict(str, tuple(float, float)), None
Dictionary with Gaussian priors for | |
#!/usr/bin/env python
import matplotlib
matplotlib.use('TkAgg')
from numpy import arange, sin, pi,log10,max,min,cos,isnan, meshgrid,sqrt,abs
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import pyPLUTO as pp
import string
import time
from Tkinter import *
import sys
import os
class App:
def __init__(self,master):
# create toplevel window
frame = Frame(master)
frame.grid(ipadx=10,ipady=10)
try:
sys.argv[1]
except:
self.datatype = None
else:
self.datatype = sys.argv[1].split('--')[1]
if self.datatype == 'hdf5':
print "GUI currently doesnot support pyPLUTO AMR Reader!!"
sys.exit()
self.I = pp.Image()
self.Tool = pp.Tools()
self.lb1=Label(frame, text="Nstep").grid(row=0,column=0)
self.enstep = Entry(frame,width=8)
self.enstep.grid(row=0,column=1)
self.enstep.insert(0, "0")
self.LoadedNstep = StringVar()
self.PresentTime = StringVar()
self.myData = self.loaddata()
self.varkeys = self.myData.vars
self.wdir = self.myData.wdir
if self.myData.n3 != 1:
self.Geom = '3D'
elif self.myData.n3 == 1 and self.myData.n2 != 1:
self.Geom = '2D'
else:
self.Geom = '1D'
self.ldatabutton=Button(frame,text="Load data",command=self.loaddata)
self.ldatabutton.grid(row=0,column=2)
############### MARK THE CUTS #################################
self.ex1 = Entry(frame,width=5)
self.ex1.grid(row=2,column=0)
self.ex1.insert(0, "x1")
self.ex2 = Entry(frame,width=5)
self.ex2.grid(row=2,column=1)
self.ex2.insert(0, "x2")
self.ex3 = Entry(frame,width=5)
self.ex3.grid(row=2,column=2)
self.ex3.insert(0, "x3")
if self.Geom == '2D':
self.ex3.config(state='disabled')
if self.Geom == '1D':
self.ex3.config(state='disabled')
self.ex2.config(state='disabled')
self.ex1.config(state='disabled')
# place a graph somewhere here
self.f = Figure(figsize=(7,7), dpi=100)
self.a = self.f.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.f, master=root)
self.canvas.show()
self.canvas.get_tk_widget().grid(row=0,column=3,columnspan=10,rowspan=10,sticky=E)
#self.toolbar = NavigationToolbar2TkAgg(self.canvas,tl)
#self.toolbar.update()
#self.canvas._tkcanvas.grid(row=60,column=15,sticky=E)
self.v = StringVar()
self.v.set("None")
################ VARIABLES TO PLOT #################################
for i in ['bx1s', 'bx2s', 'bx3s']:
try:
self.varkeys.remove(i)
except ValueError:
pass
for j in range(len(self.varkeys)):
self.ldata = Radiobutton(frame,text=self.varkeys[j],variable=self.v,value=self.varkeys[j],command=self.getmyvar)
self.ldata.grid(row=3+j,column=0,sticky=W)
################ SLICES CHOICE #################################
self.slvar = StringVar()
self.slvar.set("Choose Slice")
if self.Geom == '3D' :
SliceList = ("Along x1","Along x2","Along x3","Along x1-x2","Along x2-x3","Along x3-x1")
elif self.Geom == '2D' :
SliceList = ("Along x1", "Along x2", "Along x1-x2")
else:
SliceList = ()
for j in range(len(SliceList)):
self.sldata = Radiobutton(frame,text=SliceList[j],variable=self.slvar,value=SliceList[j],command=self.setslice)
self.sldata.grid(row=3+j,column=1,sticky=W)
############### PLOT PROPERTIES #################################
self.logvar = IntVar()
self.chkb = Checkbutton(frame,text="Log ",variable=self.logvar,onvalue=1,offvalue=0,command=self.logchkcall)
self.chkb.grid(row=3,column=2,sticky=W)#(row=15,column=0,sticky=W)
self.polarvar = IntVar()
self.polchkb = Checkbutton(frame,text="Polar",variable=self.polarvar,onvalue=1,offvalue=0,command=self.polchkcall)
self.polchkb.grid(row=4,column=2,sticky=W)#(row=15,column=1)
if self.Geom == '1D':
self.polchkb.config(state='disabled')
self.polarvar.set(0)
self.preaspect = IntVar()
self.aspectb = Checkbutton(frame,text="Aspect",variable=self.preaspect,onvalue=1,offvalue=0,command=self.aspchkcall)
self.aspectb.grid(row=5,column=2,sticky=W)#(row=15,column=2)
if self.Geom == '1D':
self.aspectb.config(state='disabled')
################ X and Y LABELS #################################
self.lb2=Label(frame,text="Labels").grid(row=22,column=0)
self.xlb = Entry(frame,width=15)
self.xlb.grid(row=22,column=1)
self.xlb.insert(0, "xlabel")
self.ylb = Entry(frame,width=15)
self.ylb.grid(row=22,column=2)
self.ylb.insert(0, "ylabel")
############### X and Y RANGE#######################
self.lb2a=Label(frame,text="XRange").grid(row=24,column=0)
self.lb2b=Label(frame,text="YRange").grid(row=26,column=0)
self.lb2c=Label(frame,text="VarRange").grid(row=28,column=0)
self.xrmin = Entry(frame,width=15)
self.xrmin.grid(row=24,column=1)
self.xrmin.insert(0,'')
self.xrmax = Entry(frame,width=15)
self.xrmax.grid(row=24,column=2)
self.xrmax.insert(0,'')
self.yrmin = Entry(frame,width=15)
self.yrmin.grid(row=26,column=1)
self.yrmin.insert(0,'')
self.yrmax = Entry(frame,width=15)
self.yrmax.grid(row=26,column=2)
self.yrmax.insert(0,'')
self.varmin = Entry(frame,width=15)
self.varmin.grid(row=28,column=1)
self.varmin.insert(0,'')
self.varmax = Entry(frame,width=15)
self.varmax.grid(row=28,column=2)
self.varmax.insert(0,'')
if self.Geom == '1D':
self.yrmin.config(state='disabled')
self.yrmax.config(state='disabled')
################ CONTOURS #################################
self.lb3=Label(frame,text="Contours").grid(row=16,column=0)
self.contvar = IntVar()
self.chkb = Checkbutton(frame,text="Contour",variable=self.contvar,onvalue=1,offvalue=0,command=self.contchkcall)
self.chkb.grid(row=6,column=2,sticky=W)#(row=16,column=0,sticky=W)
self.plcont = StringVar()
self.contkeys = ["None"]
if "bx3" in self.varkeys:
for item in self.varkeys:
self.contkeys.append(item)
self.contkeys.append("x1*bx3")
if "Ax3" in self.varkeys:
self.contkeys.append("x1*Ax3")
else:
for item in self.varkeys:
self.contkeys.append(item)
self.plcont.set("None")
self.contmenu = OptionMenu(frame, self.plcont,*self.contkeys)
self.contmenu.grid(row=16,column=1)
self.xlevb = Entry(frame,width=15)
self.xlevb.grid(row=16,column=2,sticky=W)
self.xlevb.insert(0, "Levels")
self.xlevb.config(state='disabled')
self.contmenu.config(state='disabled')
if self.Geom == '1D':
self.chkb.config(state = 'disabled')
################ ARROWS #################################
self.lb4=Label(frame,text="Arrows").grid(row=19,column=0)
self.arrowvar = IntVar()
self.arrowchkb = Checkbutton(frame,text="Arrows",variable=self.arrowvar,onvalue=1,offvalue=0,command=self.arrchkcall)
self.arrowchkb.grid(row=7,column=2,sticky=W)#(row=16,column=0,sticky=W)
self.arrspb = Entry(frame,width=15)
self.arrspb.grid(row=19,column=2,sticky=W)
self.arrspb.insert(0, "20")
self.plarr = StringVar()
self.arrkeys = ["None"]
self.arrkeys.append("Vp")
self.arrkeys.append("Vp_norm")
if "bx1" in self.varkeys:
self.arrkeys.append("Bp")
self.arrkeys.append("Bp_norm")
self.plarr.set("None")
self.arrmenu = OptionMenu(frame,self.plarr,*self.arrkeys)
self.arrmenu.grid(row=19,column=1)
self.arrmenu.config(state='disabled')
self.arrspb.config(state='disabled')
if self.Geom == '1D':
self.arrowchkb.config(state = 'disabled')
################ VARIOUS PLOTTING BUTTONS #################################
self.pltbutton=Button(frame,text="Plot",command=self.plotfinal)
self.pltbutton.grid(row=36,column=0)
if self.Geom == '1D':
self.pltbutton.config(state='active')
else:
self.pltbutton.config(state='disabled')
self.surfbutton=Button(frame,text="Surface",command=self.plotsurface)
self.surfbutton.grid(row=36,column=1)
self.surfbutton.config(state='disabled')
#if self.Geom == '1D':
# self.surfbutton.config(state='disabled')
self.clrbutton=Button(frame,text="Clear",command=self.plotclear)
self.clrbutton.grid(row=36,column=2)
################ INFORMATION #################################
self.lbinf0 = Label(frame,text="Information",font=("Times",12,"bold"))
self.lbinf0.grid(row=47,column=0,sticky=W,columnspan=3)
self.lbinf1a = Label(frame,text="Dir :",font=("Times",10,"bold")).grid(row=49,column=0,sticky=W,columnspan=3)
self.lbinf1 = Label(frame,text=self.wdir).grid(row=50,column=0,sticky=W,columnspan=3)
self.lbinf2a = Label(frame,text="Domain :",font=("Times",10,"bold")).grid(row=51,column=0,sticky=W,columnspan=3)
self.lbinf2 = Label(frame,text="n1 x n2 x n3 = %d x %d x %d " % (self.myData.n1,self.myData.n2,self.myData.n3)).grid(row=52,column=0,sticky=W,columnspan=3)
self.lbinf3a = Label(frame,text="Time Status",font=("Times",10,"bold")).grid(row=53,column=0,sticky=W,columnspan=3)
self.lbinf4 = Label(frame,text="Nlast = %d"% pp.nlast_info(w_dir=self.wdir,datatype=self.datatype)['nlast']).grid(row=54,column=0,sticky=W,columnspan=3)
self.lbinf5 = Label(frame,textvariable = self.LoadedNstep).grid(row=55,column=0,sticky=W,columnspan=3)
self.lbinf6 = Label(frame,textvariable = self.PresentTime).grid(row=56,column=0,sticky=W,columnspan=3)
################ VARIOUS FUNCTIONS #################################
def loaddata(self):
try:
int(self.enstep.get().strip().split()[0])
except (ValueError, IndexError):
print "Specify the proper value of Nstep"
else:
mynstep=int(self.enstep.get())
self.D = pp.pload(mynstep,datatype=self.datatype)
self.LoadedNstep.set("Loaded Nstep = "+self.enstep.get())
self.PresentTime.set("Present Time = "+str(self.D.SimTime) + " [cu]")
return self.D
def getmyvar(self):
try:
self.v.get() != "None"
except KeyError:
print "Specify the variable to plot"
else:
self.myvar=self.v.get()
def logchkcall(self):
self.logchk = self.logvar.get()
def contchkcall(self):
self.contchk = self.contvar.get()
if self.contchk == 1:
self.contmenu.config(state='normal')
self.xlevb.config(state='normal')
else:
self.contmenu.config(state='disabled')
self.xlevb.config(state='disabled')
def arrchkcall(self):
self.arrchk = self.arrowvar.get()
if self.arrchk == 1:
self.arrmenu.config(state='normal')
self.arrspb.config(state='normal')
else:
self.arrmenu.config(state='disabled')
self.arrspb.config(state='disabled')
def aspchkcall(self):
self.aspchk=self.preaspect.get()
def polchkcall(self):
self.polchk = self.polarvar.get()
def setslice(self):
self.slicename=self.slvar.get()
if self.slicename == "Along x1" or self.slicename == "Along x2" or self.slicename == "Along x3":
self.surfbutton.config(state='disabled')
self.arrowchkb.config(state = 'disabled')
self.arrowvar.set(0)
self.chkb.config(state = 'disabled')
self.contvar.set(0)
self.pltbutton.config(state='active')
self.polchkb.config(state='disabled')
self.polarvar.set(0)
else:
self.pltbutton.config(state='disabled')
self.arrowchkb.config(state = 'normal')
self.chkb.config(state = 'normal')
self.surfbutton.config(state='active')
self.polchkb.config(state='normal')
if self.slicename == "Along x2-x3":
self.polchkb.config(state='disabled')
self.polarvar.set(0)
def plotclear(self):
self.f.clf()
self.a = self.f.add_subplot(111)
self.canvas.show()
def plotfinal(self):
if self.getplotvar() == True:
self.a.axis([self.getxaxisrange()[0],self.getxaxisrange()[1],self.getvarrange()[0],self.getvarrange()[1]])
self.a.plot(self.x,self.var)
self.a.set_aspect('auto')
self.a.set_xlabel(self.xlb.get())
self.a.set_ylabel(self.ylb.get())
self.canvas.show()
def plotsurface(self):
tdum = time.time()
self.plotclear()
if self.preaspect.get() == 1:
self.a.set_aspect('equal')
else:
self.a.set_aspect('auto')
if self.polarvar.get() == 1:
if self.drawpolar() == True:
self.a.axis([self.getxaxisrange()[0],self.getxaxisrange()[1],self.getyaxisrange()[0],self.getyaxisrange()[1]])
self.image = self.a.imshow(self.SphData[self.myvar], origin='lower',extent=self.extent, interpolation='nearest',cmap="jet", vmin=self.getvarrange()[0],vmax=self.getvarrange()[1])
self.f.colorbar(self.image)
else:
if self.getsurfvar() == True:
self.a.axis([self.getxaxisrange()[0],self.getxaxisrange()[1],self.getyaxisrange()[0],self.getyaxisrange()[1]])
self.image=self.a.pcolormesh(self.x,self.y,self.var,cmap='jet',vmin=self.getvarrange()[0],vmax=self.getvarrange()[1])
self.f.colorbar(self.image)
if self.contvar.get() == 1:
try:
self.plcont.get() != "None"
except KeyError:
print "Specify the variable for Contour"
else:
self.drawcontour()
self.contlevlist=[]
self.contlevstr = string.split(self.xlevb.get(),',')
try:
if self.contlevstr[0] == 'log':
self.flevel = self.contlevstr[1]
self.varcont = log10(self.varcont)
else:
self.flevel = self.contlevstr[0]
float(self.flevel)
self.contlevlist = [float(self.flevel)]
except:
self.contlevlist = 5
else:
for j in range(1,len(self.contlevstr)):
self.contlevlist.append(float(self.contlevstr[j]))
self.cs1 = self.a.contour(self.xcont,self.ycont,self.varcont,self.contlevlist,colors="w")
self.a.clabel(self.cs1,inline=True)
if self.arrowvar.get() == 1:
try:
self.plarr.get() != "None"
except KeyError:
print "Specify the variable for plotting the arrow"
else:
self.drawarrow()
self.a.quiver(self.xcong, self.ycong, self.xveccong, self.yveccong,color='w')
self.a.set_xlabel(self.xlb.get())
self.a.set_ylabel(self.ylb.get())
self.canvas.show()
def getvarrange(self):
try:
float(self.varmin.get())
except:
if self.polarvar.get() != 1:
self.varminval = min(self.var)
else:
self.varminval = min(self.SphData[self.myvar][self.isnotnan].flat)#self.minPl
else:
self.varminval = float(self.varmin.get())
try:
float(self.varmax.get())
except:
if self.polarvar.get() != 1:
self.varmaxval = max(self.var)
else:
self.varmaxval = max(self.SphData[self.myvar][self.isnotnan].flat)#self.maxPl
else:
self.varmaxval = float(self.varmax.get())
return [self.varminval,self.varmaxval]
def getxaxisrange(self):
try:
float(self.xrmin.get())
except:
if self.polarvar.get() != 1:
self.xminval = min(self.x)
else:
self.xminval = min(self.R.flat)
else:
self.xminval = float(self.xrmin.get())
try:
float(self.xrmax.get())
except:
if self.polarvar.get() != 1:
self.xmaxval = max(self.x)
else:
self.xmaxval = max(self.R.flat)
else:
self.xmaxval = float(self.xrmax.get())
return [self.xminval,self.xmaxval]
def getyaxisrange(self):
try:
float(self.yrmin.get())
except:
if self.polarvar.get() != 1:
self.yminval = min(self.y)
else:
self.yminval = min(self.Z.flat)
else:
self.yminval = float(self.yrmin.get())
try:
float(self.yrmax.get())
except:
if self.polarvar.get() != 1:
self.ymaxval = max(self.y)
else:
self.ymaxval = max(self.Z.flat)
else:
self.ymaxval = float(self.yrmax.get())
return [self.yminval,self.ymaxval]
def getplotvar(self):
self.sucess = False
if self.logvar.get() == 1:
self.var = log10(self.D.__getattribute__(self.myvar))
else:
self.var = self.D.__getattribute__(self.myvar)
if self.Geom == '1D':
self.x = self.D.x1
self.sucess = True
else:
if self.slicename == "Along x1":
self.x = self.D.x1
if self.D.n3 == 1:
try:
int(self.ex2.get().strip().split()[0])
except (ValueError, IndexError):
print "Specify the value of x2 cut"
else:
self.var = self.var[:,int(self.ex2.get())]
self.sucess = True
else:
try:
int(self.ex2.get().strip().split()[0])
int(self.ex3.get().strip().split()[0])
except (ValueError, IndexError):
print "Specify the value of x2 or x3 cut"
else:
self.var = self.var[:,int(self.ex2.get()),int(self.ex3.get())]
self.sucess = True
elif self.slicename == "Along x2":
self.x = self.D.x2
if self.D.n3 == 1:
try:
int(self.ex1.get().strip().split()[0])
except (ValueError, IndexError):
print "Specify the value of x1 cut"
else:
self.var = self.var[int(self.ex1.get()),:]
self.sucess = True
else:
try:
int(self.ex1.get().strip().split()[0])
int(self.ex3.get().strip().split()[0])
except (ValueError, IndexError):
print "Specify the value of x1 or x3 cut"
else:
self.var = self.var[int(self.ex1.get()),:,int(self.ex3.get())]
self.sucess = True
else:
self.x = self.D.x3
try:
int(self.ex1.get().strip().split()[0])
int(self.ex2.get().strip().split()[0])
except (ValueError, IndexError):
print "Specify the value of x1 or x2 cut"
else:
self.var = self.var[int(self.ex1.get()),int(self.ex2.get()),:]
self.sucess = True
return self.sucess
def getsurfvar(self):
self.sucess = False
if self.logvar.get() == 1:
self.var = log10(self.D.__getattribute__(self.myvar))
else:
self.var = self.D.__getattribute__(self.myvar)
if self.slicename == "Along x1-x2":
self.x = self.D.x1
self.y = self.D.x2
xmineed = (abs(self.x-self.getxaxisrange()[0])).argmin()
xmaneed = (abs(self.x-self.getxaxisrange()[1])).argmin()
ymineed = (abs(self.y-self.getyaxisrange()[0])).argmin()
ymaneed = (abs(self.y-self.getyaxisrange()[1])).argmin()
self.x = self.x[xmineed:xmaneed]
self.y = self.y[ymineed:ymaneed]
if self.D.n3 == 1:
self.var = self.var[xmineed:xmaneed,ymineed:ymaneed].T
self.sucess = True
else:
try:
int(self.ex3.get().strip().split()[0])
except (ValueError, IndexError):
print "Specify the value of x3 cut"
else:
self.var = self.var[xmineed:xmaneed,ymineed:ymaneed,int(self.ex3.get())].T
self.sucess = True
elif self.slicename == "Along x2-x3":
self.x = self.D.x2
self.y = self.D.x3
xmineed = (abs(self.x-self.getxaxisrange()[0])).argmin()
xmaneed = (abs(self.x-self.getxaxisrange()[1])).argmin()
ymineed = (abs(self.y-self.getyaxisrange()[0])).argmin()
ymaneed = (abs(self.y-self.getyaxisrange()[1])).argmin()
self.x = self.x[xmineed:xmaneed]
self.y = self.y[ymineed:ymaneed]
try:
int(self.ex1.get().strip().split()[0])
except (ValueError, IndexError):
print "Specify the value of x1 cut"
else:
self.var = self.var[int(self.ex1.get()),xmineed:xmaneed,ymineed:ymaneed].T
self.sucess = True
else:
self.x = self.D.x1
self.y = self.D.x3
xmineed = (abs(self.x-self.getxaxisrange()[0])).argmin()
xmaneed = (abs(self.x-self.getxaxisrange()[1])).argmin()
ymineed = (abs(self.y-self.getyaxisrange()[0])).argmin()
ymaneed = (abs(self.y-self.getyaxisrange()[1])).argmin()
self.x = self.x[xmineed:xmaneed]
| |
<filename>cloudmesh/queue/jobqueue.py
import json
import multiprocessing
import os
import shlex
import sys
import time
import uuid
from dataclasses import dataclass
from datetime import datetime
from datetime import timedelta
# from pathlib import Path
from textwrap import dedent
from typing import List
import oyaml as yaml
from cloudmesh.common.Host import Host as commonHost
from cloudmesh.common.Printer import Printer
from cloudmesh.common.Shell import Shell
from cloudmesh.common.console import Console
# from cloudmesh.common.parameter import Parameter
from cloudmesh.common.util import banner
from cloudmesh.common.util import is_local
from cloudmesh.common.util import path_expand
from cloudmesh.common.util import readfile
from cloudmesh.common.util import str_banner
from yamldb.YamlDB import YamlDB
# from cloudmesh.common.variables import Variables
# from cloudmesh.configuration.Configuration import Configuration
Console.init()
def sysinfo():
# this may already exist in common, if not it should be updated or integrated.
"""
Returns value of system user from environment variables
:return: User name
"""
user = None
if sys.platform == "win32":
user = os.environ.get("USERNAME")
hostname = os.environ.get("COMPUTERNAME")
else:
user = os.environ.get("USER")
hostname = os.environ.get("HOSTNAME")
cpus = multiprocessing.cpu_count()
return user, hostname, cpus
def _to_string(obj, msg):
result = [str_banner(msg)]
for field in obj.__dataclass_fields__:
try:
value = getattr(obj, field)
result.append(f"{field:<20}: {value}")
except:
pass
return "\n".join(result) + "\n"
def _to_dict(obj):
result = {}
for field in obj.__dataclass_fields__:
try:
value = getattr(obj, field)
result[str(field)] = value
except:
pass
return result
@dataclass
class Job:
"""
The Job class creates a simple job that can be executed asynchronously
on a remote computer using ssh. The status of the job is managed through
a number of files that can be quered to identify its execution state.
I job can be created as follows
job = Job(name=f"job1",
command="/usr/bin/sleep 120",
user="user",
host="host")
it will create a n experiment directory where the job specification is
located. To run it, it needs first to be syncronized and copied to the
remote host.
job.rsync()
After this we can run it with
job.run()
Please note the the job runs asynchronously and you can probe its state with
job.state
Note this is a property and not a function for the user. The final
state is called "end". Users can define their onw states and add them
to the log file so custom actions could be called.
To retrieve the CURRENT log file as a string you can use the functions
job.get_log()
To get the pid on the remote machine we can use
job.pid
Note that prior to running the command job.run(), the variable job.pid has
the value None
"""
name: str = "TBD"
id: str = str(uuid.uuid4().hex)
experiment: str = "experiment"
directory: str = None
input: str = None
output: str = None
log: str = None
status: str = "undefined"
gpu: str = None
arguments: str = ""
executable: str = ""
command: str = None
shell: str = "bash"
shell_path: str = None
scriptname: str = None
remote_command: str = None
nohup_command: str = None # BUG: should this just be remote command?
# we may not need to store the nohubcommand as it is
# just internal
# placement
pid: str = None
host: str = None
user: str = None
pyenv: str = None
last_probe_check: str = None
def __post_init__(self):
#print(self.info())
#Console.ok(f"Creating: {self.name}")
if self.input is None:
self.input = f"{self.name}/input"
if self.output is None:
self.output = f"{self.name}.out"
if self.log is None:
self.log = f"{self.name}.log"
if self.shell_path is None:
self.shell_path = f"/usr/bin/{self.shell}"
if self.command:
self.set(self.command)
if self.host and self.user and self.status == 'undefined':
self.status = 'ready'
if self.directory is None:
self.directory = './' + self.experiment
self.scriptname = f"{self.experiment}/{self.name}/{self.name}.{self.shell}"
self.generate_command()
self.generate_script(shell=self.shell)
def ps(self):
keys = ["pid", "user", "<KEY>", "%cpu", "%mem", "cmd"]
keys_str = ",".join(keys)
command = f"ps --format {keys_str} {self.pid}"
if not is_local(self.host):
command = f"ssh {self.user}@{self.host} \"{command}\""
try:
lines = Shell.run(command).splitlines()
lines = ' '.join(lines[1].split()).split(" ", len(keys) - 1)
i = -1
entry = {}
for key in keys:
i = i + 1
entry[key] = lines[i]
return entry
except:
return None
def check_host_running(self):
host = Host(name=self.host,user=self.user)
probe_status, probe_time = host.probe()
if not probe_status:
if self.status == 'start' or self.status =='run':
self.status = 'crash'
return probe_status
def check_host_running2(self,timeout_min=10):
if self.last_probe_check is None:
raise ValueError ('Job last_probe_time is None')
last_probe_time = datetime.strptime(self.last_probe_check, "%d/%m/%Y %H:%M:%S")
if datetime.now() > last_probe_time + timedelta(minutes=timeout_min):
host = Host(name=self.host, user=self.user)
probe_status, probe_time = host.probe()
self.last_probe_check = probe_time
if not probe_status:
if self.status == 'start' or self.status == 'run':
self.status = 'crash'
return False
return True
def check_running(self):
ps = self.ps()
if ps is None:
return False
return True
def check_crashed(self,timeout_min=10):
if not is_local(self.host) and (self.status == 'start' or self.status == 'run') \
and not self.check_host_running2():
return True
elif self.state == 'start' and not self.check_running():
time.sleep(5) # TODO make this more deterministic
if self.state == 'start':
if is_local(self.host):
command = \
f"cd {self.directory}/{self.name}; " + \
f"{self.logging(msg='crash')};"
else:
command = f"ssh {self.user}@{self.host} " + \
f"'" + \
f"cd {self.directory}/{self.name}; " + \
f"{self.logging(msg='crash')};" + \
f"'"
os.system(command)
return True
elif self.status == 'start':
return False
return None
def remove_dir(self):
# remove local dir
command = \
f"cd {self.directory}; " + \
f"rm -rf ./{self.name};"
r = os.system(command)
# remove remote dir
if not is_local(self.host):
command = f"ssh {self.user}@{self.host} " + \
f"'" + \
f"cd {self.directory}; " + \
f"rm -rf ./{self.name} ;" + \
f"'"
r = os.system(command)
if r != 0:
return f'Could not delete {self.name} dir on {self.user}@{self.host}\n'
return ''
@staticmethod
def nohup(name=None, shell="bash"):
"""
returns the nohup command for a remote machine
:param name: name of the job
:param shell: name of the shell
:return: str
"""
return f"nohup {shell} {name}.{shell} >> {name}-nohup.log 2>&1 &"
def to_dict(self):
"""
Returns a dict of the Job
:return: dict
"""
return _to_dict(self)
def order(self):
"""
returns all keys of the dict represented as dataclass
:return:
"""
return self.__dataclass_fields__
def info(self, banner=None, output="table"):
"""
Returns an information of the job
:return: str
"""
return Printer.attribute(self.to_dict(), output=output)
'''
def info(self):
"""
Returns an information string of the job
:return: str
"""
result = []
keys = self.__dict__
for key in keys:
entry = f"{key} = {keys[key]}"
result.append(entry)
return "\n".join(result)
'''
def __str__(self):
"""
Returns a string of the job
:return: str
"""
return _to_string(self, f"{self.experiment}/{self.name}/{self.name}")
def example(self, name: str, user=None):
"""
Not implemented
:param name:
:param user:
:return:
"""
user, hostname, cpus = sysinfo()
self.name = name, hostname, cpus
def set(self, command: str):
"""
Sets the command
:param str command: the command to be executed
:return: None
"""
self.command = command.strip()
if " " in command:
_command = shlex.split(command)
self.executable = _command[0]
self.arguments = " ".join(_command[1:])
else:
self.executable = self.command
def generate_command(self):
"""
Generates a command to run it remotely
:return: None
"""
self.nohup_command = self.nohup(name=self.name, shell=self.shell)
if is_local(self.host):
self.remote_command = \
f"cd {self.directory}/{self.name}; " + \
f"{self.nohup_command}"
else:
self.remote_command = \
f"ssh {self.user}@{self.host} " + \
f"\"cd {self.directory}/{self.name} ; " + \
f"{self.nohup_command}\""
def generate_script(self, shell="/usr/bin/bash"):
"""
generates a job script that can be copied with sunc to the remote machine
:param shell: name of the shell
:return: None
"""
os.system(f"mkdir -p {self.experiment}/{self.name}")
with open(self.scriptname, "w") as f:
start_line = self.logging("start", append=False)
end_line = self.logging("end")
pyenv_cmd = ''
if self.pyenv is not None:
pyenv_cmd = f'\nsource {self.pyenv}; '
gpu_cmd = ''
if self.gpu is not None:
gpu_cmd = f'\nexport CUDA_VISIBLE_DEVICES={self.gpu};'
script = "\n".join([
f"#! {self.shell_path} -x",
f"echo $$ > {self.name}.pid",
f"rm -f {self.output}",
f"rm -f {self.log}",
f"{start_line}",
f'echo -ne "# date: " >> {self.log}; date >> {self.log}' + pyenv_cmd + gpu_cmd,
f"{self.command} >> {self.output}",
f'echo -ne "# date: " >> {self.log}; date >> {self.log}',
f"{end_line}",
"#"])
f.write(script)
def logging(self, msg: str, append=True):
if append:
return f'echo "# cloudmesh state: {msg}" >> {self.name}.log'
else:
return f'echo "# cloudmesh state: {msg}" > {self.name}.log'
@property
def state(self):
"""
returns the state of the remote job from the log file
:return:
"""
lines = self.get_process_file(self.log)
if lines is not None:
lines = lines.splitlines()
result = Shell.find_lines_with(lines=lines, what="cloudmesh state:")
if len(result) != 0:
self.status = result[-1].split(":", 1)[1].strip()
return self.status
@property
def rpid(self):
"""
returns the remote pid from the job
:return:
"""
if self.pid is not None:
return self.pid
try:
lines = self.get_process_file(f"{self.name}.pid")
except:
return None
if lines is | |
<reponame>birknilson/oyster
# -*- coding: utf-8 -*-
"""
Oyster
~~~~~
**A Python parser of shell commands.**
This module strives to support commands executed within the sh, bash
and zsh shells alike. An important limitation to mention is that Oyster
does not support parsing of scripted commands, i.e:
for i in $(seq 10); do echo $i; done
This might change in a future version of Oyster - at least in order to
support one-liners like the one above.
*Features to be included in upcoming releases:*
- Extended :class:`Chain` API to ease extending the chain with
additional commands and various control operators.
- Parse command substitutions
:copyright: (c) 2014 by <NAME>.
:license: MIT, see LICENSE for more details.
"""
import shlex
from subprocess import list2cmdline
__author__ = '<NAME> <<EMAIL>>'
__copyright__ = 'Copyright 2014, <NAME>'
__license__ = 'MIT'
__version__ = '0.1.0'
__all__ = [
# Constants
'RESERVED_WORDS', 'CONTROL_OPERATORS', 'STDIN',
'STDOUT', 'STDERR', 'STDFD_MAPPING', 'DEBUG',
# Classes
'Redirect', 'Chain', 'Command',
# Functions
'split_token_by_operators', 'tokenize', 'is_comment',
'is_script', 'is_quoted', 'is_command', 'parse',
]
#: How verbose Oyster debugging should be::
#: * 0 turns of debugging
#: * 1 adds basic parse debugging
#: * 2 adds tokenize debugging
DEBUG = 0
#: Set of words which are reserved in the shell.
#: See: http://bit.ly/1baSfhM#tag_02_04
RESERVED_WORDS = frozenset([
'!', ';', '{', '}', 'case',
'do', 'done', 'elif', 'else',
'esac', 'fi', 'for', 'if',
'in', 'then', 'until', 'while',
])
#: Control operators which chain multiple commands
CONTROL_OPERATORS = frozenset([';', '|', '&&', '||'])
#: Lookup dictionary of control operators
CONTROL_OPERATOR_LOOKUP = dict(zip(CONTROL_OPERATORS, CONTROL_OPERATORS))
#: The file descriptor of the standard input file
STDIN = 0
#: The file descriptor of the standard output file
STDOUT = 1
#: The file descriptor of the standard error file
STDERR = 2
#: Mapping of the standard file descriptors and their common names
STDFD_MAPPING = {
STDIN: 'stdin',
STDOUT: 'stdout',
STDERR: 'stderr',
}
class Redirect(object):
"""A :class:`Redirect` instance represents the various output redirections
performed by the command it is attached to.
Each redirect has a :attr:`source` and :attr:`destination` in which the
source is the value of the standard file descriptor to be redirected to
the given :attr:`destination` - which can be either a
file descriptor or a filename.
The method in which the redirect is performed is determined by the
:attr:`mode` which can be either ``w`` or ``a``. The ``w`` mode will
write to the :attr:`destination` while ``a`` will append to
it, i.e '>' vs. '>>'.
When a shell command is parsed all redirects will automatically be
initiated and assigned to their respective command as shown below:
>>> import oyster
>>> cmd = 'cp -v -r myfiles/* >> copied.log 2>> errors.log'
>>> command = oyster.parse(cmd)[0]
>>> str(command.redirects[0])
'>> copied.log'
>>> str(command.redirects[1])
'2>> errors.log'
>>> command.redirects[0].is_source_stdout()
True
:param source: An integer representing the standard file descriptor to
be redirected.
:param destination: Either an integer representing the standard file
descriptor which output should be redirected to or
a string representing the filename.
:param mode: Either ``w`` or ``a`` depending on whether the redirect should
write or append its output to the :attr:`destination`.
"""
def __init__(self, source, destination, mode='w'):
#: Which standard file descriptor to be redirected
self.source = source
#: The destination of the redirect which can either be a standard
#: file descriptor (integer) or a filename (string.
self.destination = destination
if self.is_destination_stdfd():
mode = 'w'
#: The mode in which the redirect should be performed.
#: ``w`` represents writes (>) & ``a`` represents appends (>>).
self.mode = mode
def is_source_stdin(self):
"""Check if the source is the standard input file descriptor."""
return self.source == STDIN
def is_source_stdout(self):
"""Check if the source is the standard output file descriptor."""
return self.source == STDOUT
def is_source_stderr(self):
"""Check if the source is the standard error file descriptor."""
return self.source == STDERR
def is_destination_stdfd(self):
"""Check if the destination is a standard file descriptor."""
return self.destination in STDFD_MAPPING
def is_destination_stdin(self):
"""Check if the destination is the standard input file descriptor."""
return self.destination == STDIN
def is_destination_stdout(self):
"""Check if the destination is the standard output file descriptor."""
return self.destination == STDOUT
def is_destination_stderr(self):
"""Check if the destination is the standard error file descriptor."""
return self.destination == STDERR
def __str__(self):
source = str(self.source) if not self.is_source_stdout() else ''
if not self.is_destination_stdfd():
separator = ' '
operator = '>' if self.mode == 'w' else '>>'
else:
separator = ''
operator = '>&'
destination = str(self.destination)
as_string = '{source}{operator}{separator}{destination}'
return as_string.format(source=source, operator=operator,
separator=separator, destination=destination)
class Chain(object):
"""A list-like object containing all the individual commands which have
been chained together using control operators in the shell.
Unlike a regular Python list the :class:`Chain` instance does not implement the
``.extend``, ``.sort`` and ``.count`` methods. Also it introduces the
``chain_by`` parameter to the ``.append`` and ``.insert`` methods.
Oyster treats all shell commands as a chain even in the case of a single
program being executed. This is a design choice to simplify usage of the
module since it is easier if :func:`parse` consistently returns the
same type. As shown here:
>>> import oyster
>>> commands = oyster.parse('ps aux | grep python')
>>> len(commands)
2
>>> ps, grep = commands
>>> ps.arguments
('aux',)
>>> ps = oyster.parse('ps aux')[0]
>>> ps.program
'ps'
"""
def __init__(self):
#: A list containing all the individual :class:`Command` instances
self.commands = []
self._strings = []
self._operators = []
def append(self, command, chained_by=None):
"""C.append(command[, chained_by=';'])
Append given ``command`` to the chain with the
``chained_by`` as the separating control operator.
:param command: A string representing the command or an
instance of :class:`Command`
:param chained_by: One of the control operators defined in the
:attr:`CONTROL_OPERATORS` constant. The default
is ``;``.
"""
command = self._normalize_command(command)
chained_by = self._normalize_chained_by(chained_by)
self.commands.append(command)
self._strings.append(str(command))
self._operators.append(chained_by)
def insert(self, index, command, chained_by=None):
"""C.insert(index, command[, chained_by=';'])
Insert given ``command`` to the chain at ``index`` with the
``chained_by`` as the separating control operator.
:param index: At which index of the chain to insert the command
:param command: A string representing the command or an
instance of :class:`Command`
:param chained_by: One of the control operators defined in the
:attr:`CONTROL_OPERATORS` constant. The default
is ``;``.
"""
command = self._normalize_command(command)
chained_by = self._normalize_chained_by(chained_by)
self.commands.insert(index, command)
self._strings.insert(index, str(command))
self._operators.insert(index, chained_by)
def index(self, command, *args):
"""C.index(command, [start, [stop]]) -> first index of command.
Raises ValueError if the command is not present.
:param command: A string representing the command or an
instance of :class:`Command`
:param start: At which index to start the search
:param stop: At which index to stop the search
"""
if hasattr(command, 'get_options'):
return self.commands.index(command, *args)
return self._strings.index(command, *args)
def pop(self, *args):
"""C.pop([index]) -> command -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
:param index: Which command to pop by index
"""
ret = self.commands.pop(*args)
self._strings.pop(*args)
self._operators.pop(*args)
return ret
def remove(self, command):
"""C.remove(command) -- remove first occurrence of command.
Raises ValueError if the value is not present.
:param command: A string representing the command or an
instance of :class:`Command`
"""
index = self.index(command)
del self.commands[index]
del self._strings[index]
del self._operators[index]
def __add__(self, chain):
if hasattr(chain, 'isalpha'):
chain = parse(chain)
c = Chain()
c.commands = self.commands + chain.commands
c._strings = self._strings + chain._strings
c._operators = self._operators + chain._operators
return c
def __iadd__(self, chain):
if hasattr(chain, 'isalpha'):
chain = parse(chain)
self.commands += chain.commands
self._strings += chain._strings
self._operators += chain._operators
return self
def __contains__(self, command):
if not hasattr(command, 'isalpha'):
return command in self.commands
return command in self._strings
def __delitem__(self, *args):
self.commands.__delitem__(*args)
self._strings.__delitem__(*args)
self._operators.__delitem__(*args)
def __delslice__(self, *args):
self.commands.__delslice__(*args)
self._strings.__delslice__(*args)
self._operators.__delslice__(*args)
def __eq__(self, chain):
return str(self) == str(chain)
def __ne__(self, chain):
return not self.__eq__(chain)
def __getitem__(self, index):
return self.commands.__getitem__(index)
def __getslice__(self, *args):
c = Chain()
c.commands = self.commands.__getslice__(*args)
c._strings = self._strings.__getslice__(*args)
c._operators = self._operators.__getslice__(*args)
return c
def __len__(self):
return self.commands.__len__()
def __str__(self):
operators = self._operators[:]
operators[0] = None
commands = [str(command) for command in self.commands]
components = []
for index, operator in enumerate(operators):
if operator:
whitespace = ' '
if operator == ';':
whitespace = ''
components.append('{0}{1} '.format(whitespace, operator))
components.append(commands[index])
return ''.join(components)
def _normalize_command(self, command):
if hasattr(command, 'get_options'):
return command
chain | |
'd')
# but that data remains the same
assert tn1['t1'].data is tn2['t1'].data
tn2['t1'].data[:] /= 2
assert_allclose(tn1['t1'].data, tn2['t1'].data)
def test_copy_deep(self):
a = rand_tensor((2, 3, 4), inds='abc', tags='t0')
b = rand_tensor((2, 3, 4), inds='abd', tags='t1')
tn1 = TensorNetwork((a, b))
tn2 = tn1.copy(deep=True)
# check can modify tensor structure
tn2['t1'].modify(inds=('a', 'b', 'X'))
assert tn1['t1'] is not tn2['t1']
assert tn2['t1'].inds == ('a', 'b', 'X')
assert tn1['t1'].inds == ('a', 'b', 'd')
# and that data is not the same
assert tn1['t1'].data is not tn2['t1'].data
tn2['t1'].data[:] /= 2
assert_allclose(tn1['t1'].data / 2, tn2['t1'].data)
def test_TensorNetwork_init_checks(self):
a = rand_tensor((2, 3, 4), inds=[0, 1, 2], tags={'red'})
b = rand_tensor((3, 4, 5), inds=[1, 2, 3], tags={'blue'})
c = rand_tensor((3, 4, 5), inds=[1, 2, 3], tags={'blue', 'c'})
with pytest.raises(TypeError):
TensorNetwork(a, b) # missing brackets around ``a, b``.
tn = a & b
with pytest.raises(TypeError):
tn['red'] = 1
tn.add_tag('foo')
assert len(tn['foo']) == 2
with pytest.raises(KeyError):
tn['foo'] = c
tn[('foo', 'blue')] = c
assert 'c' in tn.tags
assert tn[('blue', 'c')] is c
assert 'red' in tn.tags
del tn['red']
assert 'red' not in tn.tags
assert set(tn.tag_map.keys()) == {'blue', 'c'}
tn.drop_tags('c')
assert set(tn.tag_map.keys()) == {'blue'}
tn.drop_tags(['blue'])
assert set(tn.tag_map.keys()) == set()
def test_conj(self):
a_data = np.random.randn(2, 3, 4) + 1.0j * np.random.randn(2, 3, 4)
b_data = np.random.randn(3, 4, 5) + 1.0j * np.random.randn(3, 4, 5)
c_data = np.random.randn(5, 2, 6) + 1.0j * np.random.randn(5, 2, 6)
a = Tensor(a_data, inds=[0, 1, 2], tags={'red', '0'})
b = Tensor(b_data, inds=[1, 2, 3], tags={'blue', '1'})
c = Tensor(c_data, inds=[3, 0, 4], tags={'blue', '2'})
tn = a & b & c
new_tn = tn.conj()
for i, arr in enumerate((a_data, b_data, c_data)):
assert_allclose(new_tn[str(i)].data, arr.conj())
# make sure original network unchanged
for i, arr in enumerate((a_data, b_data, c_data)):
assert_allclose(tn[str(i)].data, arr)
def test_conj_inplace(self):
a_data = np.random.randn(2, 3, 4) + 1.0j * np.random.randn(2, 3, 4)
b_data = np.random.randn(3, 4, 5) + 1.0j * np.random.randn(3, 4, 5)
c_data = np.random.randn(5, 2, 6) + 1.0j * np.random.randn(5, 2, 6)
a = Tensor(a_data, inds=[0, 1, 2], tags={'red', 'I0'})
b = Tensor(b_data, inds=[1, 2, 3], tags={'blue', 'I1'})
c = Tensor(c_data, inds=[3, 0, 4], tags={'blue', 'I2'})
tn = a & b & c
tn.conj_()
for i, arr in enumerate((a_data, b_data, c_data)):
assert_allclose(tn[f"I{i}"].data, arr.conj())
def test_multiply(self):
a = rand_tensor((2, 3, 4), inds=['0', '1', '2'], tags='red')
b = rand_tensor((3, 4, 5), inds=['1', '2', '3'], tags='blue')
c = rand_tensor((5, 2, 6), inds=['3', '0', '4'], tags='blue')
tn = a & b & c
x1 = (tn & tn.H) ^ ...
x2 = ((2 * tn) & tn.H) ^ ...
assert_allclose(2 * x1, x2)
def test_multiply_inplace(self):
a = rand_tensor((2, 3, 4), inds=['0', '1', '2'], tags='red')
b = rand_tensor((3, 4, 5), inds=['1', '2', '3'], tags='blue')
c = rand_tensor((5, 2, 6), inds=['3', '0', '4'], tags='blue')
tn = a & b & c
x1 = (tn & tn.H) ^ ...
tn *= 2
x2 = (tn & tn.H) ^ ...
assert_allclose(4 * x1, x2)
def test_multiply_each(self):
a = rand_tensor((2, 3, 4), inds=['0', '1', '2'], tags='red')
b = rand_tensor((3, 4, 5), inds=['1', '2', '3'], tags='blue')
c = rand_tensor((5, 2, 6), inds=['3', '0', '4'], tags='blue')
tn = a & b & c
x1 = (tn & tn.H) ^ ...
x2 = (tn.multiply_each(2) & tn.H) ^ ...
assert_allclose(2**3 * x1, x2)
def test_divide(self):
a = rand_tensor((2, 3, 4), inds=['0', '1', '2'], tags='red')
b = rand_tensor((3, 4, 5), inds=['1', '2', '3'], tags='blue')
c = rand_tensor((5, 2, 6), inds=['3', '0', '4'], tags='blue')
tn = a & b & c
x1 = (tn & tn.H) ^ ...
x2 = ((tn / 2) & tn.H) ^ ...
assert_allclose(x1 / 2, x2)
def test_divide_inplace(self):
a = rand_tensor((2, 3, 4), inds=['0', '1', '2'], tags='red')
b = rand_tensor((3, 4, 5), inds=['1', '2', '3'], tags='blue')
c = rand_tensor((5, 2, 6), inds=['3', '0', '4'], tags='blue')
tn = a & b & c
x1 = (tn & tn.H) ^ ...
tn /= 2
x2 = (tn & tn.H) ^ ...
assert_allclose(x1 / 4, x2)
def test_multiply_spread(self):
a = rand_tensor([2, 2], inds=['a', 'b'], tags='A')
b = Tensor(a.data, ['b', 'c'], tags='B')
c = Tensor(a.data, ['c', 'd'], tags='C')
tn = (a | b | c)
tn.multiply_(-8j + 1 / 3, spread_over=3)
assert_allclose(tn['A'].data, tn['B'].data)
assert_allclose(tn['B'].data, tn['C'].data)
def test_multiply_spread_neg_stays_real(self):
a = rand_tensor([2, 2], inds=['a', 'b'], tags='A', dtype='float32')
b = Tensor(a.data, ['b', 'c'], tags='B')
c = Tensor(a.data, ['c', 'd'], tags='C')
tn = (a | b | c)
tn.multiply_(-1000)
assert a.dtype == b.dtype == c.dtype == 'float32'
assert_allclose(abs(tn['A'].data), abs(tn['B'].data))
assert_allclose(abs(tn['B'].data), abs(tn['C'].data))
def test_tensor_network_sum(self):
A = qtn.TN_rand_reg(n=6, reg=3, D=2, phys_dim=2, dtype='complex')
B = A.copy()
B.randomize_()
d1 = A.distance(B)
AmB = qtn.tensor_network_sum(A, -1 * B)
d2 = (AmB | AmB.H).contract(all)**0.5
assert d1 == pytest.approx(d2)
def test_contracting_tensors(self):
a = rand_tensor((2, 3, 4), inds=[0, 1, 2], tags='red')
b = rand_tensor((3, 4, 5), inds=[1, 2, 3], tags='blue')
c = rand_tensor((5, 2, 6), inds=[3, 0, 4], tags='blue')
a_b_c = a & b & c
print(a_b_c)
repr(a_b_c)
assert isinstance(a_b_c, TensorNetwork)
a_bc = a_b_c ^ 'blue'
assert isinstance(a_bc, TensorNetwork)
assert len(a_bc.tensors) == 2
abc = a_bc ^ ['red', 'blue']
assert isinstance(abc, Tensor)
assert_allclose(abc.data, a_b_c.contract().data)
assert len(a_b_c.tensors) == 3
a_b_c ^= 'blue'
assert len(a_b_c.tensors) == 2
def test_cumulative_contract(self):
a = rand_tensor((2, 3, 4), inds=[0, 1, 2], tags='red')
b = rand_tensor((3, 4, 5), inds=[1, 2, 3], tags='blue')
c = rand_tensor((5, 2, 6), inds=[3, 0, 4], tags='green')
d = (a & b & c)
d2 = d.copy()
cd = d >> ['red', 'green', 'blue']
assert cd.shape == (6,)
assert cd.inds == (4,)
# make sure inplace operations didn't effect original tensor
for tag, names in d2.tag_map.items():
assert d.tag_map[tag] == names
# test inplace
d >>= ['red', 'green', 'blue']
assert isinstance(d, Tensor)
def test_contract_with_slices(self):
a = rand_tensor((2, 3, 4), inds=[0, 1, 2], tags='I0')
b = rand_tensor((3, 4, 5), inds=[1, 2, 3], tags='I1')
c = rand_tensor((5, 2, 6), inds=[3, 0, 4], tags='I2')
d = rand_tensor((5, 2, 6), inds=[5, 6, 4], tags='I3')
tn = TensorNetwork((a, b, c, d))
tn.view_as_(TensorNetwork1D, L=4, site_tag_id='I{}')
assert len((tn ^ slice(2)).tensors) == 3
assert len((tn ^ slice(..., 1, -1)).tensors) == 3
assert len((tn ^ slice(-1, 1)).tensors) == 3
assert len((tn ^ slice(None, -2, -1)).tensors) == 3
assert len((tn ^ slice(-2, 0)).tensors) == 3
def test_contraction_info(self):
a = qtn.rand_tensor((8, 8), ('a', 'b'))
b = qtn.rand_tensor((8, 8), ('b', 'c'))
c = qtn.rand_tensor((8, 8), ('c', 'd'))
tn = a | b | c
assert tn.contraction_width() == 6
assert tn.contraction_cost() == 2 * 8**3
@pytest.mark.parametrize('method', ('auto', 'dense', 'overlap'))
def test_tensor_network_distance(self, method):
n = 6
A = qtn.TN_rand_reg(n=n, reg=3, D=2, phys_dim=2, dtype=complex)
Ad = A.to_dense([f'k{i}' for i in range(n)])
B = qtn.TN_rand_reg(n=6, reg=3, D=2, phys_dim=2, dtype=complex)
Bd = B.to_dense([f'k{i}' for i in range(n)])
d1 = np.linalg.norm(Ad - Bd)
d2 = A.distance(B, method=method)
assert d1 == pytest.approx(d2)
@pytest.mark.parametrize('method,opts', (
('als', (('enforce_pos', False),)),
('als', (('enforce_pos', True),)),
pytest.param('autodiff', (('distance_method', 'dense'),),
marks=autograd_mark),
pytest.param('autodiff', (('distance_method', 'overlap'),),
marks=autograd_mark),
))
def test_fit_mps(self, method, opts):
k1 = qtn.MPS_rand_state(5, 3, seed=666)
k2 = qtn.MPS_rand_state(5, 3, seed=667)
assert k1.distance(k2) > 1e-3
k1.fit_(k2, method=method, progbar=True, **dict(opts))
assert k1.distance(k2) < 1e-3
@pytest.mark.parametrize('method,opts', (
('als', (('enforce_pos', False),)),
('als', (('enforce_pos', True),)),
pytest.param('autodiff', (('distance_method', 'dense'),),
marks=autograd_mark),
pytest.param('autodiff', (('distance_method', 'overlap'),),
marks=autograd_mark),
))
def test_fit_rand_reg(self, method, opts):
r1 = qtn.TN_rand_reg(5, 4, D=2, seed=666, phys_dim=2)
k2 = qtn.MPS_rand_state(5, 3, seed=667)
assert r1.distance(k2) > 1e-3
r1.fit_(k2, method=method, progbar=True, **dict(opts))
assert r1.distance(k2) < 1e-3
@pytest.mark.parametrize('method,opts', (
('als', (('enforce_pos', False),)),
('als', (('enforce_pos', True),)),
pytest.param('autodiff', (('distance_method', 'dense'),),
marks=autograd_mark),
pytest.param('autodiff', (('distance_method', 'overlap'),),
marks=autograd_mark),
))
def test_fit_partial_tags(self, method, opts):
k1 = qtn.MPS_rand_state(5, 3, seed=666)
k2 = qtn.MPS_rand_state(5, 3, seed=667)
d0 = k1.distance(k2)
tags = ["I0", "I2", "I4"]
k1f = k1.fit(k2, tol=1e-3, tags=tags,
method=method, progbar=True, **dict(opts))
assert k1f.distance(k2) < d0
assert (k1f[0] - k1[0]).norm() > 1e-12
assert (k1f[1] - k1[1]).norm() < 1e-12
assert (k1f[2] - k1[2]).norm() > 1e-12
assert (k1f[3] - k1[3]).norm() < 1e-12
assert (k1f[4] - k1[4]).norm() > 1e-12
def test_reindex(self):
a = Tensor(np.random.randn(2, 3, 4), inds=[0, 1, 2], tags='red')
b = Tensor(np.random.randn(3, 4, 5), inds=[1, 2, 3], tags='blue')
c = Tensor(np.random.randn(5, 2, 6), inds=[3, 0, 4], tags='green')
a_b_c = (a & b & c)
d | |
from __future__ import annotations
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from logging import Logger, getLogger
from typing import Any, Callable, Iterable, Optional, Tuple, Type
from uuid import UUID
import attr
from sqlalchemy import (
Column, Integer, LargeBinary, MetaData, Table, Unicode, and_, bindparam, or_, select)
from sqlalchemy.engine import URL
from sqlalchemy.exc import CompileError, IntegrityError
from sqlalchemy.future import Engine, create_engine
from sqlalchemy.sql.ddl import DropTable
from sqlalchemy.sql.elements import BindParameter, literal
from ...abc import DataStore, Job, Schedule, Serializer
from ...enums import ConflictPolicy
from ...events import (
Event, EventHub, JobAdded, JobDeserializationFailed, ScheduleAdded,
ScheduleDeserializationFailed, ScheduleRemoved, ScheduleUpdated, SubscriptionToken, TaskAdded,
TaskRemoved, TaskUpdated)
from ...exceptions import ConflictingIdError, SerializationError, TaskLookupError
from ...marshalling import callable_to_ref
from ...serializers.pickle import PickleSerializer
from ...structures import JobResult, Task
from ...util import reentrant
@reentrant
@attr.define(eq=False)
class SQLAlchemyDataStore(DataStore):
engine: Engine
schema: Optional[str] = attr.field(default=None, kw_only=True)
serializer: Serializer = attr.field(factory=PickleSerializer, kw_only=True)
lock_expiration_delay: float = attr.field(default=30, kw_only=True)
max_poll_time: Optional[float] = attr.field(default=1, kw_only=True)
max_idle_time: float = attr.field(default=60, kw_only=True)
notify_channel: Optional[str] = attr.field(default='apscheduler', kw_only=True)
start_from_scratch: bool = attr.field(default=False, kw_only=True)
_logger: Logger = attr.field(init=False, factory=lambda: getLogger(__name__))
_events: EventHub = attr.field(init=False, factory=EventHub)
def __attrs_post_init__(self) -> None:
# Generate the table definitions
self._metadata = self.get_table_definitions()
self.t_metadata = self._metadata.tables['metadata']
self.t_tasks = self._metadata.tables['tasks']
self.t_schedules = self._metadata.tables['schedules']
self.t_jobs = self._metadata.tables['jobs']
self.t_job_results = self._metadata.tables['job_results']
# Find out if the dialect supports RETURNING
update = self.t_jobs.update().returning(self.t_jobs.c.id)
try:
update.compile(bind=self.engine)
except CompileError:
self._supports_update_returning = False
else:
self._supports_update_returning = True
@classmethod
def from_url(cls, url: str | URL, **options) -> 'SQLAlchemyDataStore':
engine = create_engine(url)
return cls(engine, **options)
def __enter__(self):
with self.engine.begin() as conn:
if self.start_from_scratch:
for table in self._metadata.sorted_tables:
conn.execute(DropTable(table, if_exists=True))
self._metadata.create_all(conn)
query = select(self.t_metadata.c.schema_version)
result = conn.execute(query)
version = result.scalar()
if version is None:
conn.execute(self.t_metadata.insert(values={'schema_version': 1}))
elif version > 1:
raise RuntimeError(f'Unexpected schema version ({version}); '
f'only version 1 is supported by this version of APScheduler')
self._events.__enter__()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._events.__exit__(exc_type, exc_val, exc_tb)
def get_table_definitions(self) -> MetaData:
if self.engine.dialect.name in ('mysql', 'mariadb'):
from sqlalchemy.dialects.mysql import TIMESTAMP
timestamp_type = TIMESTAMP(fsp=6)
else:
from sqlalchemy.types import TIMESTAMP
timestamp_type = TIMESTAMP(timezone=True)
metadata = MetaData()
Table(
'metadata',
metadata,
Column('schema_version', Integer, nullable=False)
)
Table(
'tasks',
metadata,
Column('id', Unicode(500), primary_key=True),
Column('func', Unicode(500), nullable=False),
Column('state', LargeBinary),
Column('max_running_jobs', Integer),
Column('misfire_grace_time', Unicode(16)),
Column('running_jobs', Integer, nullable=False, server_default=literal(0))
)
Table(
'schedules',
metadata,
Column('id', Unicode(500), primary_key=True),
Column('task_id', Unicode(500), nullable=False, index=True),
Column('serialized_data', LargeBinary, nullable=False),
Column('next_fire_time', timestamp_type, index=True),
Column('acquired_by', Unicode(500)),
Column('acquired_until', timestamp_type)
)
Table(
'jobs',
metadata,
Column('id', Unicode(32), primary_key=True),
Column('task_id', Unicode(500), nullable=False, index=True),
Column('serialized_data', LargeBinary, nullable=False),
Column('created_at', timestamp_type, nullable=False),
Column('acquired_by', Unicode(500)),
Column('acquired_until', timestamp_type)
)
Table(
'job_results',
metadata,
Column('job_id', Unicode(32), primary_key=True),
Column('finished_at', timestamp_type, index=True),
Column('serialized_data', LargeBinary, nullable=False)
)
return metadata
def _deserialize_jobs(self, serialized_jobs: Iterable[Tuple[UUID, bytes]]) -> list[Job]:
jobs: list[Job] = []
for job_id, serialized_data in serialized_jobs:
try:
jobs.append(self.serializer.deserialize(serialized_data))
except SerializationError as exc:
self._events.publish(JobDeserializationFailed(job_id=job_id, exception=exc))
return jobs
def _deserialize_schedules(
self, serialized_schedules: Iterable[Tuple[str, bytes]]) -> list[Schedule]:
jobs: list[Schedule] = []
for schedule_id, serialized_data in serialized_schedules:
try:
jobs.append(self.serializer.deserialize(serialized_data))
except SerializationError as exc:
self._events.publish(
ScheduleDeserializationFailed(schedule_id=schedule_id, exception=exc))
return jobs
def subscribe(self, callback: Callable[[Event], Any],
event_types: Optional[Iterable[Type[Event]]] = None) -> SubscriptionToken:
return self._events.subscribe(callback, event_types)
def unsubscribe(self, token: SubscriptionToken) -> None:
self._events.unsubscribe(token)
def add_task(self, task: Task) -> None:
insert = self.t_tasks.insert().\
values(id=task.id, func=callable_to_ref(task.func),
max_running_jobs=task.max_running_jobs,
misfire_grace_time=task.misfire_grace_time)
try:
with self.engine.begin() as conn:
conn.execute(insert)
except IntegrityError:
update = self.t_tasks.update().\
values(func=callable_to_ref(task.func), max_running_jobs=task.max_running_jobs,
misfire_grace_time=task.misfire_grace_time).\
where(self.t_tasks.c.id == task.id)
with self.engine.begin() as conn:
conn.execute(update)
self._events.publish(TaskUpdated(task_id=task.id))
else:
self._events.publish(TaskAdded(task_id=task.id))
def remove_task(self, task_id: str) -> None:
delete = self.t_tasks.delete().where(self.t_tasks.c.id == task_id)
with self.engine.begin() as conn:
result = conn.execute(delete)
if result.rowcount == 0:
raise TaskLookupError(task_id)
else:
self._events.publish(TaskRemoved(task_id=task_id))
def get_task(self, task_id: str) -> Task:
query = select([self.t_tasks.c.id, self.t_tasks.c.func, self.t_tasks.c.max_running_jobs,
self.t_tasks.c.state, self.t_tasks.c.misfire_grace_time]).\
where(self.t_tasks.c.id == task_id)
with self.engine.begin() as conn:
result = conn.execute(query)
row = result.fetch_one()
if row:
return Task.unmarshal(self.serializer, row._asdict())
else:
raise TaskLookupError
def get_tasks(self) -> list[Task]:
query = select([self.t_tasks.c.id, self.t_tasks.c.func, self.t_tasks.c.max_running_jobs,
self.t_tasks.c.state, self.t_tasks.c.misfire_grace_time]).\
order_by(self.t_tasks.c.id)
with self.engine.begin() as conn:
result = conn.execute(query)
tasks = [Task.unmarshal(self.serializer, row._asdict()) for row in result]
return tasks
def add_schedule(self, schedule: Schedule, conflict_policy: ConflictPolicy) -> None:
event: Event
serialized_data = self.serializer.serialize(schedule)
insert = self.t_schedules.insert().\
values(id=schedule.id, task_id=schedule.task_id, serialized_data=serialized_data,
next_fire_time=schedule.next_fire_time)
try:
with self.engine.begin() as conn:
conn.execute(insert)
event = ScheduleAdded(schedule_id=schedule.id,
next_fire_time=schedule.next_fire_time)
self._events.publish(event)
except IntegrityError:
if conflict_policy is ConflictPolicy.exception:
raise ConflictingIdError(schedule.id) from None
elif conflict_policy is ConflictPolicy.replace:
update = self.t_schedules.update().\
where(self.t_schedules.c.id == schedule.id).\
values(serialized_data=serialized_data,
next_fire_time=schedule.next_fire_time)
with self.engine.begin() as conn:
conn.execute(update)
event = ScheduleUpdated(schedule_id=schedule.id,
next_fire_time=schedule.next_fire_time)
self._events.publish(event)
def remove_schedules(self, ids: Iterable[str]) -> None:
with self.engine.begin() as conn:
delete = self.t_schedules.delete().where(self.t_schedules.c.id.in_(ids))
if self._supports_update_returning:
delete = delete.returning(self.t_schedules.c.id)
removed_ids: Iterable[str] = [row[0] for row in conn.execute(delete)]
else:
# TODO: actually check which rows were deleted?
conn.execute(delete)
removed_ids = ids
for schedule_id in removed_ids:
self._events.publish(ScheduleRemoved(schedule_id=schedule_id))
def get_schedules(self, ids: Optional[set[str]] = None) -> list[Schedule]:
query = select([self.t_schedules.c.id, self.t_schedules.c.serialized_data]).\
order_by(self.t_schedules.c.id)
if ids:
query = query.where(self.t_schedules.c.id.in_(ids))
with self.engine.begin() as conn:
result = conn.execute(query)
return self._deserialize_schedules(result)
def acquire_schedules(self, scheduler_id: str, limit: int) -> list[Schedule]:
with self.engine.begin() as conn:
now = datetime.now(timezone.utc)
acquired_until = now + timedelta(seconds=self.lock_expiration_delay)
schedules_cte = select(self.t_schedules.c.id).\
where(and_(self.t_schedules.c.next_fire_time.isnot(None),
self.t_schedules.c.next_fire_time <= now,
or_(self.t_schedules.c.acquired_until.is_(None),
self.t_schedules.c.acquired_until < now))).\
order_by(self.t_schedules.c.next_fire_time).\
limit(limit).cte()
subselect = select([schedules_cte.c.id])
update = self.t_schedules.update().\
where(self.t_schedules.c.id.in_(subselect)).\
values(acquired_by=scheduler_id, acquired_until=acquired_until)
if self._supports_update_returning:
update = update.returning(self.t_schedules.c.id,
self.t_schedules.c.serialized_data)
result = conn.execute(update)
else:
conn.execute(update)
query = select([self.t_schedules.c.id, self.t_schedules.c.serialized_data]).\
where(and_(self.t_schedules.c.acquired_by == scheduler_id))
result = conn.execute(query)
schedules = self._deserialize_schedules(result)
return schedules
def release_schedules(self, scheduler_id: str, schedules: list[Schedule]) -> None:
with self.engine.begin() as conn:
update_events: list[ScheduleUpdated] = []
finished_schedule_ids: list[str] = []
update_args: list[dict[str, Any]] = []
for schedule in schedules:
if schedule.next_fire_time is not None:
try:
serialized_data = self.serializer.serialize(schedule)
except SerializationError:
self._logger.exception('Error serializing schedule %r – '
'removing from data store', schedule.id)
finished_schedule_ids.append(schedule.id)
continue
update_args.append({
'p_id': schedule.id,
'p_serialized_data': serialized_data,
'p_next_fire_time': schedule.next_fire_time
})
else:
finished_schedule_ids.append(schedule.id)
# Update schedules that have a next fire time
if update_args:
p_id: BindParameter = bindparam('p_id')
p_serialized: BindParameter = bindparam('p_serialized_data')
p_next_fire_time: BindParameter = bindparam('p_next_fire_time')
update = self.t_schedules.update().\
where(and_(self.t_schedules.c.id == p_id,
self.t_schedules.c.acquired_by == scheduler_id)).\
values(serialized_data=p_serialized, next_fire_time=p_next_fire_time,
acquired_by=None, acquired_until=None)
next_fire_times = {arg['p_id']: arg['p_next_fire_time'] for arg in update_args}
if self._supports_update_returning:
update = update.returning(self.t_schedules.c.id)
updated_ids = [row[0] for row in conn.execute(update, update_args)]
else:
# TODO: actually check which rows were updated?
conn.execute(update, update_args)
updated_ids = list(next_fire_times)
for schedule_id in updated_ids:
event = ScheduleUpdated(schedule_id=schedule_id,
next_fire_time=next_fire_times[schedule_id])
update_events.append(event)
# Remove schedules that have no next fire time or failed to serialize
if finished_schedule_ids:
delete = self.t_schedules.delete().\
where(self.t_schedules.c.id.in_(finished_schedule_ids))
conn.execute(delete)
for event in update_events:
self._events.publish(event)
for schedule_id in finished_schedule_ids:
self._events.publish(ScheduleRemoved(schedule_id=schedule_id))
def get_next_schedule_run_time(self) -> Optional[datetime]:
query = select(self.t_schedules.c.id).\
where(self.t_schedules.c.next_fire_time.isnot(None)).\
order_by(self.t_schedules.c.next_fire_time).\
limit(1)
with self.engine.begin() as conn:
result = conn.execute(query)
return result.scalar()
def add_job(self, job: Job) -> None:
now = datetime.now(timezone.utc)
serialized_data = self.serializer.serialize(job)
insert = self.t_jobs.insert().values(id=job.id.hex, task_id=job.task_id,
created_at=now, serialized_data=serialized_data)
with self.engine.begin() as conn:
conn.execute(insert)
event = JobAdded(job_id=job.id, task_id=job.task_id, schedule_id=job.schedule_id,
tags=job.tags)
self._events.publish(event)
def get_jobs(self, ids: Optional[Iterable[UUID]] = None) -> list[Job]:
query = select([self.t_jobs.c.id, self.t_jobs.c.serialized_data]).\
order_by(self.t_jobs.c.id)
if ids:
job_ids = [job_id.hex for job_id in ids]
query = query.where(self.t_jobs.c.id.in_(job_ids))
with self.engine.begin() as conn:
result = conn.execute(query)
return self._deserialize_jobs(result)
def acquire_jobs(self, worker_id: str, limit: Optional[int] = None) -> list[Job]:
with self.engine.begin() as conn:
now = datetime.now(timezone.utc)
acquired_until = now + timedelta(seconds=self.lock_expiration_delay)
query = select([self.t_jobs.c.id, self.t_jobs.c.serialized_data]).\
join(self.t_tasks, self.t_tasks.c.id == self.t_jobs.c.task_id).\
where(or_(self.t_jobs.c.acquired_until.is_(None),
self.t_jobs.c.acquired_until < now)).\
order_by(self.t_jobs.c.created_at).\
limit(limit)
result = conn.execute(query)
if not result:
return []
# Mark the jobs as acquired by this worker
jobs = self._deserialize_jobs(result)
task_ids: set[str] = {job.task_id for job in jobs}
# Retrieve the limits
query = select([self.t_tasks.c.id,
self.t_tasks.c.max_running_jobs - self.t_tasks.c.running_jobs]).\
where(self.t_tasks.c.max_running_jobs.isnot(None),
self.t_tasks.c.id.in_(task_ids))
result = conn.execute(query)
job_slots_left = dict(result.fetchall())
# Filter out jobs that don't have free slots
acquired_jobs: list[Job] = []
increments: dict[str, int] = defaultdict(lambda: 0)
for job in jobs:
# Don't acquire the job if there are no free slots left
slots_left = job_slots_left.get(job.task_id)
if slots_left == 0:
continue
elif slots_left is not None:
job_slots_left[job.task_id] -= 1
acquired_jobs.append(job)
increments[job.task_id] += 1
if acquired_jobs:
# Mark the acquired jobs as acquired by this worker
acquired_job_ids = [job.id.hex for job in acquired_jobs]
update = self.t_jobs.update().\
values(acquired_by=worker_id, acquired_until=acquired_until).\
where(self.t_jobs.c.id.in_(acquired_job_ids))
conn.execute(update)
# Increment the running job counters on each task
p_id: BindParameter = bindparam('p_id')
p_increment: BindParameter = bindparam('p_increment')
params = [{'p_id': task_id, 'p_increment': increment}
for task_id, increment in increments.items()]
update = self.t_tasks.update().\
values(running_jobs=self.t_tasks.c.running_jobs + p_increment).\
where(self.t_tasks.c.id == p_id)
conn.execute(update, params)
return acquired_jobs
def release_job(self, worker_id: str, job: Job, result: Optional[JobResult]) -> None:
with self.engine.begin() as conn:
# Insert the job result
now = datetime.now(timezone.utc)
serialized_result = self.serializer.serialize(result)
insert = self.t_job_results.insert().\
values(job_id=job.id.hex, | |
import json
import httplib2
import http.client
import base64
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import ssl
import socket
import paramiko
from security.rbacTest import rbacTest
from security.rbacmain import rbacmain
from remote.remote_util import RemoteMachineShellConnection
from security.ldapGroupBase import ldapGroupBase
from ast import literal_eval
class ServerInfo():
def __init__(self,
ip,
port,
ssh_username,
ssh_password,
ssh_key=''):
self.ip = ip
self.ssh_username = ssh_username
self.ssh_password = <PASSWORD>
self.port = port
self.ssh_key = ssh_key
class rbacclitest(rbacTest):
def setUp(self):
super(rbacclitest, self).setUp()
self.ldapUser = self.input.param('ldapuser','Administrator')
self.ldapPass = self.input.param('ldappass','password')
self.user_name = self.input.param("user_name","")
self.user_id = self.input.param('user_id','')
self.auth_type = self.input.param('auth_type','local')
self.user_role = self.input.param('user_role','admin')
def tearDown(self):
super(rbacclitest, self).tearDown()
def execute_admin_role_manage(self, options):
cli_command = 'user-manage'
options = options
remote_client = RemoteMachineShellConnection(self.master)
output, error = remote_client.execute_couchbase_cli(cli_command=cli_command, \
options=options, cluster_host="localhost", user=self.ldapUser, password=self.ldapPass)
return output, error
def execute_password_policy(self, options):
cli_command = 'setting-password-policy'
options = options
remote_client = RemoteMachineShellConnection(self.master)
output, error = remote_client.execute_couchbase_cli(cli_command=cli_command, \
options=options, cluster_host="localhost", user=self.ldapUser, password=self.ldapPass)
return output, error
def _get_user_role(self):
final_user_id = rbacmain().returnUserList(self.user_id)
final_roles = rbacmain()._return_roles(self.user_role)
return final_user_id, final_roles
def test_create_user_without_auth(self):
users, roles = self._get_user_role()
options = "--set " + "--rbac-username " + users[0][0] + " --rbac-password " + users[0][1] + " --roles " + roles
output, error = self.execute_admin_role_manage(options)
self.assertTrue("ERROR: --auth-domain is required with the --set option" in output[0], "Issue with command without auth")
def test_create_user_without_rbac_user(self):
users, roles = self._get_user_role()
options = "--set " + " --rbac-password " + users[0][1] + " --roles " + roles
output, error = self.execute_admin_role_manage(options)
self.assertTrue("ERROR: --rbac-username is required with the --set option" in output[0], "Issue with command without rbacusername")
def test_create_user_without_rbac_pass(self):
users, roles = self._get_user_role()
options = "--set " + "--rbac-username " + users[0][0] + " --roles " + roles + " --auth-domain local"
output, error = self.execute_admin_role_manage(options)
self.assertTrue("ERROR: --rbac-password is required with the --set option" in output[0], "Issue with command without rbac_pass")
def test_create_user_without_role(self):
users, roles = self._get_user_role()
options = "--set " + "--rbac-username " + users[0][0] + " --rbac-password " + users[0][1] + \
" --auth-domain " + self.auth_type
output, error = self.execute_admin_role_manage(options)
self.assertTrue("ERROR: --roles is required with the --set option" in output[0],"Issue with command without role")
def test_create_user(self):
users, roles = self._get_user_role()
options = "--set " + "--rbac-username " + users[0][0] + " --roles " + roles \
+ " --auth-domain " + self.auth_type
if self.auth_type == "local":
options += " --rbac-password " + users[0][1]
output, error = self.execute_admin_role_manage(options)
self.assertTrue("SUCCESS: User " in output[0],"Issue with command create_user")
def test_create_user_name(self):
users, roles = self._get_user_role()
options = "--set " + "--rbac-username " + users[0][0] + " --rbac-password " + users[0][1] + " --roles " + roles \
+ " --auth-domain " + self.auth_type + " --rbac-name " + self.user_name
if self.auth_type == "local":
options += " --rbac-password " + users[0][1]
output, error = self.execute_admin_role_manage(options)
if 'WARNING' in output[0]:
output= output[1:]
self.assertTrue("SUCCESS: User " in output[0],"Issue with command create user name")
def test_delete_user(self):
self.test_create_user()
users, roles = self._get_user_role()
options = "--delete " + "--rbac-username " + users[0][0] + " --auth-domain " + self.auth_type
output, error = self.execute_admin_role_manage(options)
self.assertTrue("SUCCESS: User " in output[0], "Issue with command of delete user")
def test_my_role(self):
final_out = ''
options = "--my-roles "
self.test_create_user()
users, roles = self._get_user_role()
self.ldapUser = users[0][0]
self.ldapPass = users[0][1]
output, error = self.execute_admin_role_manage(options)
for out in output:
final_out = final_out + out
test = json.loads(final_out)
for role in test['roles']:
self.assertTrue(role['role'] in roles,"Issue with --my-roles")
def test_create_user_without_rbac_pass_value(self):
users, roles = self._get_user_role()
options = "--set " + " --rbac-username " + users[0][0] + " --rbac-password --roles " + roles
output, error = self.execute_admin_role_manage(options)
self.assertTrue("ERROR: argument --rbac-password: expected one argument" in output[0], "Issue with command without" + \
" rbac-password value")
def test_create_user_invalid_character(self):
self.auth_type='local'
final_users = [["\"r;itam\"",'password'],["\"r(itam\"",'password'],["\"r)itam\"",'password'], ["\"r<itam\"",'password'], \
["\"r>itam\"", 'password'], ["\"r@itam\"",'password'], ["\"r,itam\"",'password'], ["\"r;itam\"",'password'], \
["\"r:itam\"", 'password'], ["\"r\itam\"",'password'], ["\"r[itam\"",'password'], \
["\"r]itam\"", 'password'], ["\"r[itam\"", 'password'], ["\"r]itam\"", 'password'], \
["\"r=itam\"", 'password'], ["\"r{itam\"", 'password'], ["\"r}itam\"", 'password']]
#["\"r/itam\"",'password'], ["\"r?itam\"", 'password'],
roles = 'admin'
for users in final_users:
self.log.info ("------Username tested is ------------{0}".format(users[0]))
options = "--set " + "--rbac-username " + users[0] + " --roles " + roles \
+ " --auth-domain " + self.auth_type + " --rbac-name " + self.user_name
if self.auth_type == "local":
options += " --rbac-password " + users[1]
output, error = self.execute_admin_role_manage(options)
self.assertTrue("ERROR: _ - Username must not contain spaces, control or any" in output[0],
"Issue with command without" + \
" rbac-password value")
def test_invalid_password_less_6_char(self):
if self.auth_type=='local':
users, roles = self._get_user_role()
options = "--set " + " --rbac-username " + users[0][0] + " --rbac-password " + users[0][1] + " --roles " + \
roles + " --auth-domain " + self.auth_type
output, error = self.execute_admin_role_manage(options)
self.assertTrue("ERROR: password - The password must be at least 6 characters long." in output[0],
"Issue with password < 6 characters")
def test_change_password(self):
self.new_password = self.input.param("<PASSWORD>_password")
users, roles = self._get_user_role()
options = "--set " + "--rbac-username " + users[0][0] + " --roles " + roles \
+ " --auth-domain " + self.auth_type
if self.auth_type == "local":
options += " --rbac-password " + users[0][1]
output, error = self.execute_admin_role_manage(options)
self.assertTrue("SUCCESS: User {0} set".format(users[0][0]) in output[0],
"Issue with command create_user")
if self.new_password is not None:
options = ""
options = "--set " + "--rbac-username " + users[0][0] + " --roles " + roles \
+ " --auth-domain " + self.auth_type
if self.auth_type == "local":
options += " --rbac-password " + self.new_password
output, error = self.execute_admin_role_manage(options)
self.assertTrue("SUCCESS: User {0} set".format(users[0][0]) in output[0],
"Issue with command create_user")
def test_invalid_passwords(self):
final_policy = ""
users, roles = self._get_user_role()
correct_pass = self.input.param("correctpass",False)
policy_type = self.input.param("policy_type")
if ":" in policy_type:
policy_type = policy_type.split(":")
for policy in policy_type:
final_policy = final_policy + " --" + policy
policy_type = final_policy
if policy_type == "uppercase":
error_msg = "ERROR: argument --uppercase: expected one argument"
elif policy_type == "lowercase":
error_msg = "ERROR: password - The password must contain at least one lowercase letter"
elif policy_type == "digit":
error_msg = "ERROR: password - The password must contain at least one digit"
elif policy_type == "special-char":
error_msg = "ERROR: password - The password must contain at least one of the following characters: @%+\/'\"!#$^?:,(){}[]~`-_"
elif policy_type == " --special-char --digit":
error_msg = "ERROR: password - The password must contain at least one digit"
elif policy_type == " --uppercase --lowercase":
error_msg = "ERROR: password - The password must contain at least one lowercase letter"
elif policy_type == " --uppercase --lowercase --digit --special-char":
error_msg = "ERROR: password - The password must contain at least one lowercase letter"
try:
if "--" in policy_type:
options = "--set --min-length 6 " + policy_type
else:
options = "--set --min-length 6 --" + policy_type
output, error = self.execute_password_policy(options)
options = "--set " + " --rbac-username " + users[0][0] + " --rbac-password " + users[0][1] + " --roles " + \
roles + " --auth-domain " + self.auth_type
output, error = self.execute_admin_role_manage(options)
if 'WARNING' in output[0]:
output = output[1:]
if correct_pass:
self.assertTrue("SUCCESS: User {0} set".format(users[0][0]) in output[0],
"Issue with command create_user")
else:
if 'ERROR' in output[0]:
self.assertTrue(error_msg in output[0],
"Issue with password < 6 characters")
else:
self.assertTrue("SUCCESS: User " in output[0], "Issue with command create_user")
finally:
options = "--set --min-length 6"
output, error = self.execute_password_policy(options)
self.assertTrue("SUCCESS: Password policy updated" in output[0], "Issue with setting the policy ")
def test_delete_user_noexist(self):
users, roles = self._get_user_role()
options = "--delete " + "--rbac-username userdoesexist --auth-type " + self.auth_type
output, error = self.execute_admin_role_manage(options)
self.assertTrue("ERROR: \"User was not found." in output[0], "Issue with delete user that does not exist")
def test_my_role(self):
final_out = ''
options = "--my-roles "
self.test_create_user()
users, roles = self._get_user_role()
self.ldapUser = users[0][0]
self.ldapPass = users[0][1]
output, error = self.execute_admin_role_manage(options)
for out in output:
final_out = final_out + out
test = json.loads(final_out)
for role in test['roles']:
self.assertTrue(role['role'] in roles,"Issue with --my-roles")
def test_list_roles(self):
final_out = ''
options = "--list "
self.test_create_user()
users, roles = self._get_user_role()
self.ldapUser = users[0][0]
self.ldapPass = users[0][1]
output, error = self.execute_admin_role_manage(options)
final_out =""
for out in output:
final_out = final_out + out
if roles not in ['admin','ro_admin','security_admin']:
if type(final_out) == str :
self.log.info("The test failed as expected")
else:
test = json.loads(final_out)
usrTest =[]
for usr in test:
if usr['id'] | |
_API_DELETE = "/delrule"
_API_GET = "/showrule"
_API_LIST = "/showrule"
API_INIT_PARAMS = {
"name": "Name",
"pattern": "Pattern"
}
_API_BASE_PARAMS = {
"name": "Name",
"type": "Type",
"pattern": "Pattern"
}
_API_DEFAULT_ATTRIBUTES = {
"name": "Name",
"type": "Type",
"pattern": "Pattern",
"matchtype": "MatchType",
"addhost": "AddHost",
"negate": "Negate",
"caseindependant": "CaseIndependent",
"includequery": "IncludeQuery",
"header": "Header",
"mustfail": "MustFail",
"headervalue": "HeaderValue",
"replacement": "Replacement",
"setflagonmatch": "SetFlagOnMatch",
"onlyonflag": "OnlyOnFlag"
}
@property
def type_string(self):
types = {
"0": "MatchContentRule",
"1": "AddHeaderRule",
"2": "DeleteHeaderRule",
"3": "ReplaceHeaderRule",
"4": "ModifyURLRule"
}
if self.type is None:
return None
return types[str(self.type)]
@type_string.setter
def type_string(self, value):
types = {
"MatchContentRule": "0",
"AddHeaderRule": "1",
"DeleteHeaderRule": "2",
"ReplaceHeaderRule": "3",
"ModifyURLRule": "4"
}
if value is None:
self.type = None
else:
self.type = types[value]
def __init__(self, loadmaster_info, name, pattern):
self.populate_default_attributes({})
self.name = name
self.pattern = pattern
try:
self.endpoint = loadmaster_info["endpoint"]
except KeyError:
raise RuleMissingLoadmasterInfo("endpoint")
try:
self.ip_address = loadmaster_info["ip_address"]
except KeyError:
raise RuleMissingLoadmasterInfo("ip_address")
super(Rule, self).__init__(loadmaster_info)
def __str__(self):
return 'Rule {} on LoadMaster {}'.format(
self.name, self.ip_address)
def _get_base_parameters(self):
base_parameters = super(Rule, self)._get_base_parameters()
# Pattern is not necessary for AddHeader rules
if self.type == 1:
base_parameters.pop("pattern")
return base_parameters
def populate_default_attributes(self, params):
"""Populate object instance with standard defaults"""
# Get data from inside tag
# Tag is unknown since different rule types have
# different tag names. The generic code using API_TAG
# isn't usable in this case.
#params = params.popitem()[1]
for attribute, tag in self._API_DEFAULT_ATTRIBUTES.items():
setattr(self, attribute, params.get(tag, None))
self.type_string = self.type
class Sso(BaseKempObject):
def __init__(self, loadmaster_info, name):
self.name = name
try:
self.endpoint = loadmaster_info["endpoint"]
except KeyError:
raise RangeMissingLoadmasterInfo("endpoint")
super(Sso, self).__init__(loadmaster_info)
def __str__(self):
return 'SSO {} on LoadMaster {}'.format(
self.name, self.ip_address)
def _get_base_parameters(self):
"""Returns the bare minimum FQDN parameters."""
return {
"domain": self.name
}
def save(self, update=False):
if not update:
response = self._get("/adddomain", self._get_base_parameters())
if not is_successful(response):
raise KempTechApiException(get_error_msg(response))
response = self._get("/moddomain", self.to_api_dict())
if is_successful(response):
sso_data = get_data(response)
self.populate_default_attributes(sso_data)
else:
raise KempTechApiException(get_error_msg(response))
def delete(self):
response = self._get("/deldomain", self._get_base_parameters())
return send_response(response)
def populate_default_attributes(self, params):
"""Populate SSO instance with standard defaults"""
self.id = params.get('Id', None)
self.name = params.get('Name', None)
self.testuser = params.get('testuser', None)
self.ldap_version = params.get('ldap_version', None)
self.server_side = params.get('server_side', None)
self.auth_type = params.get('auth_type', None)
self.logon_fmt = params.get('logon_fmt', None)
self.logon_fmt2 = params.get('logon_fmt2', None)
self.logon_transcode = params.get('logon_transcode', None)
self.logon_domain = params.get('logon_domain', None)
self.kerberos_domain = params.get('kerberos_domain', None)
self.kerberos_kdc = params.get('kerberos_kdc', None)
self.kcd_username = params.get('kcd_username', None)
self.max_failed_auths = params.get('max_failed_auths', None)
self.reset_fail_tout = params.get('reset_fail_tout', None)
self.unblock_tout = params.get('unblock_tout', None)
self.sess_tout_type = params.get('sess_tout_type', None)
self.sess_tout_idle_pub = params.get('sess_tout_idle_pub', None)
self.sess_tout_duration_pub = params.get('sess_tout_duration_pub', None)
self.sess_tout_idle_priv = params.get('sess_tout_idle_priv', None)
self.sess_tout_duration_priv = params.get('sess_tout_duration_priv', None)
self.cert_check_asi = params.get('cert_check_asi', None)
class Fqdn(BaseKempObject):
_API_ADD = "/addfqdn"
_API_MOD = "/modfqdn"
_API_DELETE = "/delfqdn"
_API_GET = "/showfqdn"
_API_LIST = "/listfqdns"
API_TAG = "fqdn"
API_INIT_PARAMS = {
"fqdn": "FullyQualifiedDomainName"
}
_API_BASE_PARAMS = [
"fqdn"
]
_API_DEFAULT_ATTRIBUTES = {
"fqdn": "FullyQualifiedDomainName",
"status": "Status",
"selectioncriteria": "SelectionCriteria",
"failtime": "FailTime",
"siterecoverymode": "SiteRecoveryMode",
"failover": "failover",
"publicrequestvalue": "publicRequestValue",
"privaterequestvalue": "privateRequestValue",
"localsettings": "LocalSettings",
"localttl": "LocalTTL",
"localsticky": "LocalSticky",
"unanimouschecks": "UnanimousChecks"
}
def __init__(self, loadmaster_info, fqdn):
self.fqdn = fqdn # to avoid AttributeErrors later
super(Fqdn, self).__init__(loadmaster_info)
def __str__(self):
return 'FQDN {} on LoadMaster {}'.format(
self.fqdn, self.ip_address)
def save(self, update=False):
try:
if self.selectioncriteria != "lb":
# Failover is not available when not using Location Based
del self.failover
except AttributeError:
pass
super(Fqdn, self).save(update)
self.refresh()
def populate_default_attributes(self, params):
super(Fqdn, self).populate_default_attributes(params)
# Failtime is set by minute, but recorded by second
try:
# Try to cast to integer first
self.failtime = int(self.failtime)
# Check if failtime is a non-zero factor of 60
if self.failtime > 0 and self.failtime % 60 == 0:
# Convert from seconds to minutes
self.failtime = int(self.failtime / 60)
except (TypeError, AttributeError):
self.failtime = None
@property
def sites(self):
return {site.ipaddress: site for site in self.get_sites()}
def create_site(self, ip):
"""Site factory with pre-configured LoadMaster connection."""
return Site(self.access_info, ip)
def get_site(self, ip):
validate_ip(ip)
service_id = {
"fqdn": self.fqdn,
"ipaddress": ip
}
response = self._get("/showfqdn", service_id)
xml_object = get_data(response)
maps = xml_object["fqdn"].get(Site.API_TAG, {})
if not isinstance(maps, list):
maps = [maps]
map = [m for m in maps if m['IPAddress'] == service_id["ipaddress"]]
# This shouldn't happen, but we should catch it anyway
if len(map) != 1:
raise LoadMasterParameterError(
"Unexpected number of matching sites specified.", map)
return build_object(Site, self.access_info, map[0])
def get_sites(self):
fqdn = {
"fqdn": self.fqdn
}
try:
response = self._get(self._API_LIST, fqdn)
data = get_data(response)
xml_object = data[self.API_TAG].get(Site.API_TAG, [])
except KempTechApiException:
xml_object = []
obj_list = []
# If there is no API_TAG key, build will fail with a
# ValidationError, which is the best we can do for now
# (without changing the upstream code and raising an
# exception earlier, possibly retrying)
xml_object = cast_to_list(xml_object)
for x in xml_object:
obj = self.build_site(x)
obj_list.append(obj)
return obj_list
def build_site(self, site):
"""Create a object instance with standard defaults"""
build_parameters = {}
for parameter, tag in Site.API_INIT_PARAMS.items():
build_parameters[parameter] = site.get(tag)
obj = Site(self.access_info, **build_parameters)
obj.populate_default_attributes(site)
return obj
class Site(BaseKempObject):
_API_ADD = "/addmap"
_API_MOD = "/modmap"
_API_DELETE = "/delmap"
_API_GET = "/showfqdn"
_API_LIST = "/showfqdn"
API_TAG = "Map"
API_INIT_PARAMS = {
"ip": "IPAddress"
}
_API_BASE_PARAMS = {
"fqdn": "fqdn",
"ip": "ip"
}
_API_DEFAULT_ATTRIBUTES = {
"index": "Index",
"status": "Status",
"clustervsaddress": "ClusterVSAddress",
"checker": "Checker",
"checkeraddr": "checkerAddr",
"checkerport": "CheckerPort",
"weight": "Weight",
"enable": "Enable",
"locationlatitude": "LocationLatitude",
"locationlongitude": "LocationLongitude",
"continent": "continent",
"country": "country",
"customlocation": "customLocation",
"cluster": "Cluster",
"mapaddress": "MappedAddress",
"mapport": "MappedPort"
}
_API_IGNORE = (
"log_urls", "ip_address", "endpoint", "index", "status",
"continent", "country", "customlocation", "ipaddress"
)
# Remap ipaddress to ip because the API is inconsistent
@property
def ipaddress(self):
return self.ip
@ipaddress.setter
def ipaddress(self, value):
self.ip = value
@property
def mappedaddress(self):
return self.mapaddress
@mappedaddress.setter
def mappedaddress(self, value):
self.mapaddress = value
@property
def mappedport(self):
return self.mapport
@mappedport.setter
def mappedport(self, value):
self.mapport = value
def __init__(self, loadmaster_fqdn_info, ip):
self.fqdn = loadmaster_fqdn_info["fqdn"]
self.ip = ip
validate_ip(ip)
try:
self.fqdn = loadmaster_fqdn_info["fqdn"]
except KeyError:
raise SiteMissingFQDNInfo("fqdn")
try:
self.endpoint = loadmaster_fqdn_info["endpoint"]
except KeyError:
raise SiteMissingLoadmasterInfo("endpoint")
try:
self.ip_address = loadmaster_fqdn_info["ip_address"]
except KeyError:
raise SiteMissingLoadmasterInfo("ip_address")
super(Site, self).__init__(loadmaster_fqdn_info)
def __str__(self):
return 'Site {} in FQDN {} on LoadMaster {}'.format(
self.ip, self.fqdn, self.ip_address)
def _get_base_parameters(self):
return {
"fqdn": self.fqdn,
"ip": self.ip
}
def populate_default_attributes(self, params):
super(Site, self).populate_default_attributes(params)
# Fix annoying API inconsistencies
# Normalize location lists so we always get a regular list
if not isinstance(self.continent, list):
if self.continent is None:
self.continent = []
else:
self.continent = [self.continent]
if not isinstance(self.country, list):
if self.country is None:
self.country = []
else:
self.country = [self.country]
if not isinstance(self.customlocation, list):
if self.customlocation is None:
self.customlocation = []
else:
self.customlocation = [self.customlocation]
try:
self.checkerport = int(self.checkerport)
except (ValueError, AttributeError):
self.checkerport = None
finally:
if not 1 < self.checkerport < 65530:
self.checkerport = None
def save(self, update=False):
if not update:
response = self._get(self._API_ADD, self._get_base_parameters())
else:
response = self._get(self._API_MOD, self.to_api_dict())
if not is_successful(response):
raise KempTechApiException(get_error_msg(response))
# Secondary request is needed because the add/mod action
# does not return any data. Therefore, we need to explicitly
# retrieve the info.
response = self._get(self._API_GET, self._get_base_parameters())
if is_successful(response):
response = self._get(self._API_GET, self._get_base_parameters())
data = get_data(response)
maps = data["fqdn"].get(self.API_TAG, {})
if not isinstance(maps, list):
maps = [maps]
map = [m for m in maps if m['IPAddress'] == self.ipaddress]
# This shouldn't happen, but we should catch it anyway
if len(map) > 1:
raise LoadMasterParameterError(
"Multiple matching sites specified.",
map)
if len(map) < 1:
raise LoadMasterParameterError(
"No matching sites specified.",
map)
site = map[0]
self.populate_default_attributes(site)
else:
raise KempTechApiException(get_error_msg(response))
def refresh(self):
response = self._get(
self._API_GET,
self._get_base_parameters())
if is_successful(response):
response = self._get(self._API_GET, self._get_base_parameters())
data = get_data(response)
maps = data["fqdn"].get(self.API_TAG, {})
if not isinstance(maps, list):
maps = [maps]
map = [m for m in maps if m['IPAddress'] == self.ipaddress]
# This shouldn't happen, but we should catch it anyway
if len(map) > 1:
raise LoadMasterParameterError(
"Multiple matching sites specified.",
map)
if len(map) < 1:
raise LoadMasterParameterError(
"No matching sites specified.",
map)
site = map[0]
self.populate_default_attributes(site)
else:
raise KempTechApiException(get_error_msg(response))
@property
def locations(self):
return {
"continent": self.continent,
"country": self.country,
"customlocation": self.customlocation
}
@staticmethod
def __get_map_parameters(location, is_continent=False, is_custom=False):
if is_custom is False:
parameters = {
"countrycode": location.upper()
}
if is_continent is True:
parameters["iscontinent"] = "yes"
else:
parameters["iscontinent"] = "no"
else:
parameters = | |
<filename>programs/representations/representations.py
#Copyright 2020 DB Engineering
#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 json
import base64
import sys
sys.path.append('..\\')
import ontology.ontology
from pretty import PrettyPrint
def _convert_to_base64(data):
"""
Convert a data object into a base64 message.
Used as a codeword to uniquely identify each asset
"""
if isinstance(data,set):
data = list(data)
data.sort()
data = tuple(data)
data = str(data)
if isinstance(data,list):
data.sort()
data = tuple(data)
data = str(data)
if isinstance(data,tuple):
data = str(data)
encoded_bytes = base64.b64encode(data.encode("utf-8"))
encoded_str = str(encoded_bytes, "utf-8")
return encoded_str
class Asset:
""" An asset model for the loadsheet data. Holds all the relevant loadsheet asset-related data
and serves as a wrapper for the Field class, allowing user to add/update fields directly on the
asset object. """
def __init__(self,building,general_type,type_name,asset_name,full_asset_name):
"""
Initialize the model
args:
- building: string building name
- general_type: string asset type e.g. VAV
- type_name: Unique name for type definitions
- asset_name: string physical name
- full_asset_name: BMS internal name
returns: new asset objects
"""
self.building = building
self.general_type = general_type
self.type_name = type_name
self.asset_name = asset_name
self.full_asset_name = full_asset_name
self.fields = {}
self.matched = False
self.placeholderid = 10000
def add_field(self,field_name,bms_info,bacnet_address,manually_mapped=False,placeholder=False):
"""
Adds a field to the asset object
args:
- field_name: string point name
- bms_info: dictionary, describing bms type, location, controlProgram,
name, path, and type
- bacnet_address: dictionary describing deviceId, objectId,
objectName, objectType, and units
- manuallyMapped: flag if field is manually filled in, set false by default
- placeholder: flag for placeholder field creation, default false
returns: N/A
"""
assert field_name not in self.fields, "Field {} already set.".format(field_name)
if placeholder:
self.bms_info={'bms_type':"",'location':'', 'controlprogram':'', 'name':'Placeholder', 'path':'x', 'type':'x'}
self.bacnet_address={'deviceid':'', 'objectid':self.placeholderid, 'objectname':'x', 'objecttype':'x', 'units':''}
self.placeholderid += 1
self.fields[field_name] = Field(field_name,self.bms_info,self.bacnet_address,manually_mapped, placeholder = True)
else:
self.fields[field_name] = Field(field_name,bms_info,bacnet_address,manually_mapped)
def update_field(self,field_name,bms_info,bacnet_address,manually_mapped=False):
"""
Update a field on the asset.
args:
- field_name: string point name
- bms_info: dictionary, describing bms type, location, controlProgram,
name, path, and type
- bacnet_address: dictionary describing deviceID, objectID,
objectName, objectType, and units
- manuallyMapped: flag if field is manually filled in, set false by default
returns: N/A
"""
assert field_name in self.fields, "Field not defined."
del self.fields[field_name]
self.fields[field_name] = Field(field_name,bms_info,bacnet_address,manually_mapped)
def update_type(self,type_name):
"""
Sets the type_name.
args:
- type_name: #TODO
returns: N/A
"""
self.type_name = type_name
def remove_field(self,field_name):
"""
Remove a field from the asset.
args:
- field_name: string point name to be removed
returns: N/A
"""
assert field_name in self.fields, "Field not defined; cannot remove."
del self.fields[field_name]
def get_general_type(self):
"""
Get the general type for the asset.
returns: general_type string
"""
return self.general_type
def get_fields(self):
"""
Get the field names on the asset.
returns: list of field name strings
"""
return [field for field in self.fields]
def get_field_details(self,field_name):
"""
Get the details for a specified field.
args:
- field_name: string field name to retrieve
returns: dictionary of BMS info of passed field
"""
assert field_name in self.fields, "Field not defined; cannot find."
return self.fields[field_name].get_field_details()
def get_all_field_details(self):
"""
Get the details for all fields on the asset.
returns: dictionary of BMS info for all fields
"""
field_details = {}
for field in self.fields:
field_details[field] = self.fields[field].get_field_details()
return field_details
def get_asset_details(self):
"""
Get all the asset details stored in the object.
returns: dictionary of asset details
"""
asset_details = {
'building':self.building,
'general_type':self.general_type,
'type_name':self.type_name,
'asset_name':self.asset_name,
'full_asset_name':self.full_asset_name
}
return asset_details
def add_match(self, match):
"""
adds match to asset
args:
- match: match object to connect
"""
self.match = match
self.matched = True
def apply_match(self):
"""
applies match object details to the asset
adds necessary placeholder fields and updates name
"""
if self.matched:
#apply type names
self.update_type(self.match.ont_type_name)
#apply fields
existing_fields = self.get_fields()
for field in self.match.ont_type_fields:
if field[0] not in existing_fields and field[1]:
self.add_field(field[0], '', '', placeholder=True)
def dump(self):
"""
Dump all asset details.
returns: dictionary of asset and field details
"""
details = self.get_asset_details()
details.update({'fields':self.get_all_field_details()})
return details
class Field:
""" A field model for the loadsheet data. Requires BMS specific metadata and BACnet address info. """
#TODO: Add in BMS type functionality that spans the different classes
def __init__(self,field_name,bms_info,bacnet_address,manually_mapped=False,placeholder=False):
"""
Initialize the model.
args:
- field_name: string point name
- bms_info: dictionary, describing bms type, location, controlProgram,
name, path, and type
- bacnet_address: dictionary describing deviceID, objectID,
objectName, objectType, and units
- manuallyMapped: flag if field is manually filled in, set false by default
- placeholder: flag for placeholder field creation, default false
returns: field object
"""
self.field_name=field_name
self.manually_mapped=manually_mapped
if not placeholder:
self.bms_info = bms_info
assert 'bms_type' in self.bms_info, "Argument 'bms_info' requires a 'bms_type' key."
if bms_info['bms_type'] == 'ALC':
required_fields = ['location','controlprogram','name','type','path']
for field in required_fields:
assert field in self.bms_info, "Field '{}' not in 'bms_info' argument.".format(field)
self.bacnet_address = bacnet_address
bacnet_requirements = ['deviceid','objecttype','objectid','objectname','units']
for field in bacnet_requirements:
assert field in bacnet_requirements, "Field '{}' not in 'bacnet_address' argument.".format(field)
else:
self.bms_info = bms_info
self.bacnet_address = bacnet_address
def get_field_details(self):
"""
Return all the field details in a single dictionary.
returns: dictionary of BMS info of passed field
"""
details = {'bms_info':self.bms_info,'bacnet_address':self.bacnet_address,'manually_mapped':self.manually_mapped}
return details
class Assets:
"""
A wrapper class to handle asset models. Holds all relevant loadsheet data for all
asset object passed in.
"""
def __init__(self):
""" Initialize the class. """
self.assets = {}
self.determined_types = {}
self.ununsed_data = []
def add_asset(self,building,general_type,type_name,asset_name,full_asset_name):
"""
Update an asset or add it if it doesnt exist yet.
args:
- building: string building name
- general_type: string asset type e.g. VAV
- type_name: unique name for type definitions
- asset_name: string physical name
- full_asset_name: BMS internal name
"""
assert full_asset_name not in self.assets, "Asset {} already exists.".format(full_asset_name)
asset = Asset(building,general_type,type_name,asset_name,full_asset_name)
self.assets[full_asset_name] = asset
def remove_asset(self,full_asset_name):
"""
Remove an asset.
args:
- full_asset_name: name of asset to remove
"""
assert full_asset_name in self.assets, "Asset {} does not exist.".format(full_asset_name)
del self.assets[full_asset_name]
def update_type(self,full_asset_name,type_name):
"""
Update type of a given asset.
args:
- full_asset_name: name of asset to update
- type_name: string type name to update asset to match
"""
self.assets[full_asset_name].update_type(type_name)
def add_field(self,full_asset_name,field_name,bms_info,bacnet_address,manually_mapped=False):
"""
Add a field.
args:
- full_asset_name: name of asset to add field to
- field_name: string point name
- bms_info: dictionary, describing location, controlProgram,
name, path, and type
- bacnet_address: dictionary describing deviceID, objectID,
objectName, objectType, and units
- manuallyMapped: flag if field is manually filled in, set false by default
"""
self.assets[full_asset_name].add_field(field_name,bms_info,bacnet_address,manually_mapped)
def remove_field(self,full_asset_name,field_name):
"""
Remove a field.
args:
- full_asset_name: name of asset to remove field from
- field_name: string point name to be removed
"""
self.assets[full_asset_name].remove_field(field_name)
def get_fields(self,full_asset_name):
"""
Get fields for an asset.
args:
- full_asset_name: name of asset ot get fields of
returns: list of field objects
"""
return self.assets[full_asset_name].get_fields()
def get_all_asset_fields(self):
"""
Get all distinct fields in all assets. Easy for validation.
returns: list of unique fields in assets
"""
unique_fields = set()
for asset in self.assets:
fields = self.get_fields(asset)
for field in fields:
unique_fields.add(field)
return unique_fields
def get_general_type(self,full_asset_name):
"""
Get the general type for the asset.
args:
- full_asset_name: asset to get general_type of
returns: general type of asset
"""
return self.assets[full_asset_name].get_general_type()
def get_general_types(self):
"""
Get all general types defined for all assets.
returns: list of all general types
"""
general_types = set()
for asset in self.assets:
gt = self.assets[asset].get_general_type()
general_types.add(gt)
return general_types
def dump_asset(self,full_asset_name):
"""
Dump asset contents.
args:
- full_asset_name: asset to get dump
results: full asset dump
"""
dump_details = self.assets[full_asset_name].dump()
return dump_details
def dump_all_assets(self):
"""
Dump all assets.
returns: full data dump
"""
dump_details = {}
for asset in self.assets:
dump_details[asset] = self.dump_asset(asset)
return dump_details
def load_from_row(self,data_row):
"""
Load from a row of data.
args:
- data_row: row of data to add
"""
if data_row['fullassetpath'] not in self.assets:
self.add_asset(
data_row['building'],
data_row['generaltype'],
data_row['typename'],
data_row['assetname'],
data_row['fullassetpath']
)
bms_info = {
'bms_type':'ALC',
'location':data_row['location'],
'controlprogram':data_row['controlprogram'],
'name':data_row['name'],
'type':data_row['type'],
'path':data_row['path']
}
bacnet_address = {
'deviceid':data_row['deviceid'],
'objectid':data_row['objectid'],
'objecttype':data_row['objecttype'],
'objectname':data_row['objectname'],
'units':data_row['units']
}
self.add_field(data_row['fullassetpath'],data_row['standardfieldname'],bms_info,bacnet_address,data_row['manuallymapped'])
def load_from_data(self,data):
"""
Load from a data object.
args:
- data: dictionary of lists representing loadsheet data
"""
for row in data:
if row['required'] == 'YES':
self.load_from_row(row)
else:
self.ununsed_data.append(row)
def dump_to_data(self):
""" Dump the assets object into the original data format. Append any unused rows of data that were not applied
to assets.
returns: dictionary of lists representing loadsheet data
"""
# TODO: Create loadsheet config object set
data = self.dump_all_assets()
out_data = []
for asset in data:
for field in data[asset]['fields']:
fullAssetPath = data[asset]['full_asset_name']
assetName = data[asset]['asset_name']
building = data[asset]['building']
generalType = data[asset]['general_type']
typeName = data[asset]['type_name']
standardFieldName = field
deviceId = data[asset]['fields'][field]['bacnet_address']['deviceid']
objectId = data[asset]['fields'][field]['bacnet_address']['objectid']
objectName = data[asset]['fields'][field]['bacnet_address']['objectname']
objectType = data[asset]['fields'][field]['bacnet_address']['objecttype']
units = data[asset]['fields'][field]['bacnet_address']['units']
location = data[asset]['fields'][field]['bms_info']['location']
controlProgram = data[asset]['fields'][field]['bms_info']['controlprogram']
manually_mapped = data[asset]['fields'][field]['manually_mapped']
name = data[asset]['fields'][field]['bms_info']['name']
path = data[asset]['fields'][field]['bms_info']['path']
ttype = data[asset]['fields'][field]['bms_info']['type']
row = {
'location':location,
'controlprogram':controlProgram,
'name':name,
'type':ttype,
'path':path,
'deviceid':deviceId,
'objecttype':objectType,
'objectid':objectId,
'objectname':objectName,
'units':units,
'required':'YES',
'manuallymapped':manually_mapped,
'building':building,
'generaltype':generalType,
'typename':typeName,
'assetname':assetName,
'fullassetpath':fullAssetPath,
'standardfieldname':standardFieldName
}
out_data.append(row)
if len(self.ununsed_data)>0:
for row in self.ununsed_data:
out_data.append(row)
return out_data
def determine_types(self):
"""
Use the unique fields for each asset to create a list of unique types.
returns: list of unique types
"""
unique_types = {}
for asset in self.assets:
fields = self.get_fields(asset)
general_type = self.get_general_type(asset)
field_code = _convert_to_base64(fields)
if field_code not in unique_types:
unique_types[field_code] = {'general_type':general_type,'fields':fields,'assets':[asset]}
else:
unique_types[field_code]['assets'].append(asset)
return unique_types
def validate_without_errors(self, ontology):
"""
Validate the subfields and fields against the ontology.
Only prints errors seen, but runs through everything
args:
- ontology: the ontology object to validate the assets against
"""
fields = self.get_all_asset_fields()
invalid_subfields = ontology.check_subfields(fields)
invalid_fields = ontology.check_fields(fields)
has_errors = False
if len(invalid_subfields)>0:
has_errors = True
print('Undefined subfields (define them or change them):')
for subfield in invalid_subfields:
print('\t{}'.format(subfield))
if len(invalid_fields)>0:
has_errors = True
print('Undefined fields (define them or change them):')
for field in invalid_fields:
print('\t{}'.format(field))
if has_errors == False:
print("No representation errors!")
def validate(self,ontology):
"""
Validate the type subfields and fields against the ontology.
Throws errors when issue encountered
args:
- ontology: ontology object to check assets against
"""
fields = self.get_all_asset_fields()
invalid_subfields = ontology.check_subfields(fields)
invalid_fields = ontology.check_fields(fields)
assert len(invalid_subfields) == 0, "Undefined subfields (define them or change them): {}".format(str(invalid_subfields))
assert len(invalid_fields) == 0, "Undefined fields (define them or change them): {}".format(str(invalid_fields))
print("[INFO]\tNo representation errors!")
'''
#functionality not complete
#removed 20200727 akoltko
def dump_to_steve_format(self):
"""
Dump the data content to the Steve format.
args:
-
"""
# TODO: Add functionality for this to CLI and Handler
# Output for STEVE format.
steve_headers = (
'location','controlProgram','name','type','objectType','deviceId','objectName','units','path',
'required','bacnetAvailable','building','generalType','assetName','fullAssetPath','standardFieldName'
)
data = self.dump_to_data()
s = '\t'
print(s.join(steve_headers))
for row in data:
out_row = {}
for i in steve_headers:
if i in row:
if i == 'objectType':
out_row['objectType'] = row['objectType'] +':'+str(row['objectId'])
elif i == 'deviceId':
out_row['deviceId'] = 'DEV:' + str(row['deviceId'])
else:
out_row[i] = row[i]
else:
out_row[i] = ''
s = '\t'
print(s.join(out_row.values()))
'''
### Test block.
if __name__ == | |
<gh_stars>1-10
import playfab.PlayFabErrors as PlayFabErrors
import playfab.PlayFabHTTP as PlayFabHTTP
import playfab.PlayFabSettings as PlayFabSettings
""" API methods for managing multiplayer servers. API methods for managing parties. """
def CancelAllMatchmakingTicketsForPlayer(request, callback, customData = None, extraHeaders = None):
"""
Cancel all active tickets the player is a member of in a given queue.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking/cancelallmatchmakingticketsforplayer
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/Match/CancelAllMatchmakingTicketsForPlayer", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CancelAllServerBackfillTicketsForPlayer(request, callback, customData = None, extraHeaders = None):
"""
Cancel all active backfill tickets the player is a member of in a given queue.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking/cancelallserverbackfillticketsforplayer
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/Match/CancelAllServerBackfillTicketsForPlayer", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CancelMatchmakingTicket(request, callback, customData = None, extraHeaders = None):
"""
Cancel a matchmaking ticket.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking/cancelmatchmakingticket
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/Match/CancelMatchmakingTicket", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CancelServerBackfillTicket(request, callback, customData = None, extraHeaders = None):
"""
Cancel a server backfill ticket.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking/cancelserverbackfillticket
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/Match/CancelServerBackfillTicket", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CreateBuildAlias(request, callback, customData = None, extraHeaders = None):
"""
Creates a multiplayer server build alias.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/createbuildalias
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/CreateBuildAlias", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CreateBuildWithCustomContainer(request, callback, customData = None, extraHeaders = None):
"""
Creates a multiplayer server build with a custom container.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/createbuildwithcustomcontainer
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/CreateBuildWithCustomContainer", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CreateBuildWithManagedContainer(request, callback, customData = None, extraHeaders = None):
"""
Creates a multiplayer server build with a managed container.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/createbuildwithmanagedcontainer
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/CreateBuildWithManagedContainer", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CreateBuildWithProcessBasedServer(request, callback, customData = None, extraHeaders = None):
"""
Creates a multiplayer server build with the server running as a process.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/createbuildwithprocessbasedserver
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/CreateBuildWithProcessBasedServer", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CreateMatchmakingTicket(request, callback, customData = None, extraHeaders = None):
"""
Create a matchmaking ticket as a client.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking/creatematchmakingticket
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/Match/CreateMatchmakingTicket", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CreateRemoteUser(request, callback, customData = None, extraHeaders = None):
"""
Creates a remote user to log on to a VM for a multiplayer server build.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/createremoteuser
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/CreateRemoteUser", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CreateServerBackfillTicket(request, callback, customData = None, extraHeaders = None):
"""
Create a backfill matchmaking ticket as a server. A backfill ticket represents an ongoing game. The matchmaking service
automatically starts matching the backfill ticket against other matchmaking tickets. Backfill tickets cannot match with
other backfill tickets.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking/createserverbackfillticket
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/Match/CreateServerBackfillTicket", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def CreateServerMatchmakingTicket(request, callback, customData = None, extraHeaders = None):
"""
Create a matchmaking ticket as a server. The matchmaking service automatically starts matching the ticket against other
matchmaking tickets.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking/createservermatchmakingticket
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/Match/CreateServerMatchmakingTicket", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def DeleteAsset(request, callback, customData = None, extraHeaders = None):
"""
Deletes a multiplayer server game asset for a title.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/deleteasset
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/DeleteAsset", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def DeleteBuild(request, callback, customData = None, extraHeaders = None):
"""
Deletes a multiplayer server build.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/deletebuild
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/DeleteBuild", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def DeleteBuildAlias(request, callback, customData = None, extraHeaders = None):
"""
Deletes a multiplayer server build alias.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/deletebuildalias
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/DeleteBuildAlias", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def DeleteBuildRegion(request, callback, customData = None, extraHeaders = None):
"""
Removes a multiplayer server build's region.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/deletebuildregion
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/DeleteBuildRegion", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def DeleteCertificate(request, callback, customData = None, extraHeaders = None):
"""
Deletes a multiplayer server game certificate.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/deletecertificate
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/DeleteCertificate", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def DeleteContainerImageRepository(request, callback, customData = None, extraHeaders = None):
"""
Deletes a container image repository.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/deletecontainerimagerepository
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/DeleteContainerImageRepository", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def DeleteRemoteUser(request, callback, customData = None, extraHeaders = None):
"""
Deletes a remote user to log on to a VM for a multiplayer server build.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/deleteremoteuser
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/DeleteRemoteUser", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def EnableMultiplayerServersForTitle(request, callback, customData = None, extraHeaders = None):
"""
Enables the multiplayer server feature for a title.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/enablemultiplayerserversfortitle
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/EnableMultiplayerServersForTitle", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def GetAssetUploadUrl(request, callback, customData = None, extraHeaders = None):
"""
Gets the URL to upload assets to.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/getassetuploadurl
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/GetAssetUploadUrl", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def GetBuild(request, callback, customData = None, extraHeaders = None):
"""
Gets a multiplayer server build.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/getbuild
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/GetBuild", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def GetBuildAlias(request, callback, customData = None, extraHeaders = None):
"""
Gets a multiplayer server build alias.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/getbuildalias
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/GetBuildAlias", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def GetContainerRegistryCredentials(request, callback, customData = None, extraHeaders = None):
"""
Gets the credentials to the container registry.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/getcontainerregistrycredentials
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/MultiplayerServer/GetContainerRegistryCredentials", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def GetMatch(request, callback, customData = None, extraHeaders = None):
"""
Get a match.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking/getmatch
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/Match/GetMatch", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def GetMatchmakingQueue(request, callback, customData = None, extraHeaders = None):
"""
SDK support is limited to C# and Java for this API. Get a matchmaking queue configuration.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking-admin/getmatchmakingqueue
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/Match/GetMatchmakingQueue", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def GetMatchmakingTicket(request, callback, customData = None, extraHeaders = None):
"""
Get a matchmaking ticket by ticket Id.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking/getmatchmakingticket
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must call GetEntityToken before calling this method")
def wrappedCallback(playFabResult, error):
if callback:
callback(playFabResult, error)
PlayFabHTTP.DoPost("/Match/GetMatchmakingTicket", request, "X-EntityToken", PlayFabSettings._internalSettings.EntityToken, wrappedCallback, customData, extraHeaders)
def GetMultiplayerServerDetails(request, callback, customData = None, extraHeaders = None):
"""
Gets multiplayer server session details for a build.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/getmultiplayerserverdetails
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFabException("Must | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# rtk.hardware.ListBook.py is part of the RTK Project
#
# All rights reserved.
# Copyright 2007 - 2017 <NAME> andrew.rowland <AT> reliaqual <DOT> com
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
###############################
Hardware Package List Book View
###############################
"""
import sys
# Import modules for localization support.
import gettext
import locale
# Modules required for the GUI.
import pango
try:
import pygtk
pygtk.require('2.0')
except ImportError:
sys.exit(1)
try:
import gtk
except ImportError:
sys.exit(1)
try:
import gtk.glade
except ImportError:
sys.exit(1)
try:
import gobject
except ImportError:
sys.exit(1)
# Import other RTK modules.
try:
import Configuration
import gui.gtk.Widgets as Widgets
from gui.gtk.Matrix import Matrix as rtkMatrix
except ImportError:
import rtk.Configuration as Configuration
import rtk.gui.gtk.Widgets as Widgets
from rtk.gui.gtk.Matrix import Matrix as rtkMatrix
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__organization__ = 'ReliaQual Associates, LLC'
__copyright__ = 'Copyright 2007 - 2016 Andrew "weibullguy" Rowland'
try:
locale.setlocale(locale.LC_ALL, Configuration.LOCALE)
except locale.Error:
locale.setlocale(locale.LC_ALL, '')
_ = gettext.gettext
class ListView(gtk.VBox):
"""
The List Book view displays all the matrices and lists associated with the
Hardware Class. The attributes of a Hardware List Book view are:
:ivar _dtc_matrices: the :py:class:`rtk.datamodels.Matrix.Matrix` data
controller instance.
:ivar _lst_handler_id: list containing the signal handler ID's for each of
the gtk.Widget()s who have a callback method.
:ivar gtk.Button btnSaveFuncHard: the gtk.Button() to save the Hardware/
Hardware Matrix.
:ivar gtk.Button btnSaveFuncSoft: the gtk.Button() to save the Hardware/
Software Matrix.
:ivar gtk.Button btnSaveFuncTest: the gtk.Button() to save the Hardware/
Testing Matrix.
:ivar mtxHardware: the :py:class:`rtk.gui.gtk.Matrix.Matrix` that displays
the Hardware/Hardware Matrix.
:ivar mtxSoftware: the :py:class:`rtk.gui.gtk.Matrix.Matrix` that displays
the Hardware/Software Matrix.
:ivar mtxTesting: the :py:class:`rtk.gui.gtk.Matrix.Matrix` that displays
the Hardware/Testing Matrix.
:ivar gtk.TreeView tvwPartsList: the gtk.TreeView() that displays the list
of components/parts directly comprising
the selected Hardware Assembly.
:ivar gtk.TreeView tvwIncidentsList: the gtk.TreeView() that displays the
list of program incidents related to
the selected Hardware Assembly.
"""
def __init__(self, modulebook):
"""
Initializes the List Book view for the Hardware package.
:param modulebook: the :py:class:`rtk.function.ModuleBook` to associate
with this List Book.
"""
gtk.VBox.__init__(self)
# Define private dictionary attributes.
# Define private list attributes.
self._lst_handler_id = []
# Define private scalar attributes.
self._dtc_matrices = modulebook.mdcRTK.dtcMatrices
self._mdcRTK = modulebook.mdcRTK
# Define public dictionary attributes.
# Define public list attributes.
# Define public scalar attributes.
# Parts List page widgets.
self.tvwPartsList = gtk.TreeView()
self.tvwPartsList.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
# Incidents List page widgets.
self.tvwIncidentList = gtk.TreeView()
self.tvwIncidentList.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
# Testing Matrix page widgets.
self.btnSaveHardTest = Widgets.make_button(width=35, image='save')
self.mtxTesting = rtkMatrix()
self.mtxTesting.n_fixed_columns = 3
# Validation Matrix page widgets.
self.btnSaveHardVal = Widgets.make_button(width=35, image='save')
self.mtxValidation = rtkMatrix()
self.mtxValidation.n_fixed_columns = 3
# Set tooltips for the gtk.Widgets().
self.tvwPartsList.set_tooltip_markup(_(u"Displays the list of "
u"components/parts directly "
u"comprising the selected "
u"Hardware assembly."))
self.tvwIncidentList.set_tooltip_markup(_(u"Displays the list of "
u"incidents associated with "
u"the selected Hardware "
u"assembly."))
self.mtxTesting.treeview.set_tooltip_markup(_(u"Displays the "
u"relationship between "
u"system Hardware and "
u"system development "
u"tests. This matrix "
u"shows which tests "
u"partially (P) or "
u"completely (C) "
u"test a Hardware item, "
u"if at all."))
self.mtxValidation.treeview.set_tooltip_markup(_(u"Displays the "
u"relationship "
u"between system "
u"Hardware and "
u"program Validation "
u"tasks. This "
u"matrix shows which "
u"Validation task "
u"partially (P) or "
u"completely (C) "
u"validates a "
u"Hardware item, if "
u"at all."))
# Connect widget signals to callback methods. We do this here rather
# than in each method so the _lst_handler_id index is the same as the
# dicMatrix key for each Matrix.
self._lst_handler_id.append(
self.mtxTesting.connect('changed', self._on_matrix_changed, 0))
self._lst_handler_id.append(
self.mtxValidation.connect('changed', self._on_matrix_changed, 1))
self._lst_handler_id.append(
self.btnSaveHardTest.connect('clicked',
self._on_button_clicked, 2))
self._lst_handler_id.append(
self.btnSaveHardVal.connect('clicked',
self._on_button_clicked, 3))
# Put it all together.
_notebook = self._create_notebook()
self.pack_start(_notebook)
self.show_all()
def _create_notebook(self):
"""
Method to create the Hardware class List View gtk.Notebook().
:return: _notebook
:rtype: gtk.Notebook
"""
_notebook = gtk.Notebook()
# Set the user's preferred gtk.Notebook tab position.
if Configuration.TABPOS[1] == 'left':
_notebook.set_tab_pos(gtk.POS_LEFT)
elif Configuration.TABPOS[1] == 'right':
_notebook.set_tab_pos(gtk.POS_RIGHT)
elif Configuration.TABPOS[1] == 'top':
_notebook.set_tab_pos(gtk.POS_TOP)
else:
_notebook.set_tab_pos(gtk.POS_BOTTOM)
self._create_parts_list_page(_notebook)
self._create_incident_list_page(_notebook)
self._create_testing_matrix_page(_notebook)
self._create_validation_matrix_page(_notebook)
return _notebook
def _create_parts_list_page(self, notebook):
"""
Method to create the Parts List page in the List View.
:param gtk.Notebook notebook: the gtk.Notebook() to add the page.
:return: False if successful or True if an error is encountered.
:rtype: bool
"""
# Build up the containers for the Parts List page.
_scrollwindow = gtk.ScrolledWindow()
_scrollwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
_scrollwindow.add(self.tvwPartsList)
_frame = Widgets.make_frame()
_frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_frame.add(_scrollwindow)
_model = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING,
gobject.TYPE_STRING)
self.tvwPartsList.set_model(_model)
_headings = [_(u"Reference\nDesignator"), _(u"Name"),
_(u"Part Number")]
for _index, _heading in enumerate(_headings):
_cell = gtk.CellRendererText()
_cell.set_property('background', 'light grey')
_cell.set_property('editable', 0)
_cell.set_property('wrap-width', 250)
_cell.set_property('wrap-mode', pango.WRAP_WORD_CHAR)
_cell.set_property('yalign', 0.1)
_label = gtk.Label()
_label.set_line_wrap(True)
_label.set_alignment(xalign=0.5, yalign=0.5)
_label.set_justify(gtk.JUSTIFY_CENTER)
_label.set_markup("<span weight='bold'>" + _heading + "</span>")
_label.set_use_markup(True)
_label.show_all()
_column = gtk.TreeViewColumn()
_column.set_widget(_label)
_column.set_visible(True)
_column.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
_column.pack_start(_cell, True)
_column.set_attributes(_cell, text=_index)
self.tvwPartsList.append_column(_column)
# Add the Parts List page to the gtk.Notebook().
_label = gtk.Label()
_label.set_markup(_(u"<span weight='bold'>Parts\nList</span>"))
_label.set_alignment(xalign=0.5, yalign=0.5)
_label.set_justify(gtk.JUSTIFY_CENTER)
_label.show_all()
_label.set_tooltip_text(_(u"Displays the list of components/parts "
u"directly comprising the selected Hardware "
u"assembly."))
notebook.insert_page(_frame, tab_label=_label, position=-1)
return False
def _create_incident_list_page(self, notebook):
"""
Method to create the Incident List page in the List View.
:param gtk.Notebook notebook: the gtk.Notebook() to add the page.
:return: False if successful or True if an error is encountered.
:rtype: bool
"""
# Build up the containers for the Incident List page.
_scrollwindow = gtk.ScrolledWindow()
_scrollwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
_scrollwindow.add(self.tvwIncidentList)
_frame = Widgets.make_frame()
_frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_frame.add(_scrollwindow)
_model = gtk.TreeStore(gobject.TYPE_INT, gobject.TYPE_STRING,
gobject.TYPE_STRING)
self.tvwIncidentList.set_model(_model)
_headings = [_(u"Incident\nID"), _(u"Short\nDescription"),
_(u"Incident\nStatus")]
for _index, _heading in enumerate(_headings):
_cell = gtk.CellRendererText()
_cell.set_property('background', 'light grey')
_cell.set_property('editable', 0)
_cell.set_property('wrap-width', 250)
_cell.set_property('wrap-mode', pango.WRAP_WORD_CHAR)
_cell.set_property('yalign', 0.1)
_label = gtk.Label()
_label.set_line_wrap(True)
_label.set_alignment(xalign=0.5, yalign=0.5)
_label.set_justify(gtk.JUSTIFY_CENTER)
_label.set_markup("<span weight='bold'>" + _heading + "</span>")
_label.set_use_markup(True)
_label.show_all()
_column = gtk.TreeViewColumn()
_column.set_widget(_label)
_column.set_visible(True)
_column.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
_column.pack_start(_cell, True)
_column.set_attributes(_cell, text=_index)
self.tvwIncidentList.append_column(_column)
# Add the Incident List page to the gtk.Notebook().
_label = gtk.Label()
_label.set_markup(_(u"<span weight='bold'>Incident\nList</span>"))
_label.set_alignment(xalign=0.5, yalign=0.5)
_label.set_justify(gtk.JUSTIFY_CENTER)
_label.show_all()
_label.set_tooltip_text(_(u"Displays the list of incidents associated "
u"with the selected Hardware assembly or "
u"Hardware component."))
notebook.insert_page(_frame, tab_label=_label, position=-1)
return False
def _create_testing_matrix_page(self, notebook):
"""
Method to create the Hardware/Testing matrix page in the List View.
:param gtk.Notebook notebook: the gtk.Notebook() to add the page.
:return: False if successful or True if an error is encountered.
:rtype: boolean
"""
# Build up the containers for the Hardware/Testing matrix page.
_hbox = gtk.HBox()
_bbox = gtk.VButtonBox()
_bbox.set_layout(gtk.BUTTONBOX_START)
_bbox.pack_start(self.btnSaveHardTest, False, False)
_hbox.pack_start(_bbox, False, True)
_scrollwindow = gtk.ScrolledWindow()
_scrollwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
_scrollwindow.add(self.mtxTesting.treeview)
_frame = Widgets.make_frame()
_frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_frame.add(_scrollwindow)
_hbox.pack_end(_frame, True, True)
_label = gtk.Label()
_label.set_markup(_(u"<span weight='bold'>Testing\nMatrix</span>"))
_label.set_alignment(xalign=0.5, yalign=0.5)
_label.set_justify(gtk.JUSTIFY_CENTER)
_label.show_all()
_label.set_tooltip_text(_(u"Displays the matrix showing relationships "
u"between system hardware and system "
u"tests."))
notebook.insert_page(_hbox, tab_label=_label, position=-1)
return False
def _create_validation_matrix_page(self, notebook):
"""
Method to create the Hardware/Validation matrix page in the List View.
:param gtk.Notebook notebook: the gtk.Notebook() to add the page.
:return: False if successful or True if an error is encountered.
:rtype: bool
"""
# Build up the containers for the Hardware/Validation | |
<reponame>google-cloud-sdk-unofficial/google-cloud-sdk<filename>lib/googlecloudsdk/command_lib/app/staging.py<gh_stars>1-10
# -*- coding: utf-8 -*- #
# Copyright 2016 Google LLC. 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.
"""Code to provide a hook for staging.
Some App Engine runtimes require an additional staging step before deployment
(e.g. when deploying compiled artifacts, or vendoring code that normally lives
outside of the app directory). This module contains (1) a registry mapping
runtime/environment combinations to staging commands, and (2) code to run said
commands.
The interface is defined as follows:
- A staging command is an executable (binary or script) that takes two
positional parameters: the path of the `<service>.yaml` in the directory
containing the unstaged application code, and the path of an empty directory
in which to stage the application code.
- On success, the STDOUT and STDERR of the staging command are logged at the
INFO level. On failure, a StagingCommandFailedError is raised containing the
STDOUT and STDERR of the staging command (which are surfaced to the user as an
ERROR message).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import abc
import io
import os
import re
import shutil
import tempfile
from googlecloudsdk.api_lib.app import env
from googlecloudsdk.api_lib.app import runtime_registry
from googlecloudsdk.command_lib.app import jarfile
from googlecloudsdk.command_lib.util import java
from googlecloudsdk.core import config
from googlecloudsdk.core import exceptions
from googlecloudsdk.core import execution_utils
from googlecloudsdk.core import log
from googlecloudsdk.core.updater import update_manager
from googlecloudsdk.core.util import files
from googlecloudsdk.core.util import platforms
import six
_JAVA_APPCFG_ENTRY_POINT = 'com.google.appengine.tools.admin.AppCfg'
_JAVA_APPCFG_STAGE_FLAGS = ['--enable_new_staging_defaults']
_STAGING_COMMAND_OUTPUT_TEMPLATE = """\
------------------------------------ STDOUT ------------------------------------
{out}\
------------------------------------ STDERR ------------------------------------
{err}\
--------------------------------------------------------------------------------
"""
class StagingCommandNotFoundError(exceptions.Error):
"""Base error indicating that a staging command could not be found."""
class NoSdkRootError(StagingCommandNotFoundError):
def __init__(self):
super(NoSdkRootError, self).__init__(
'No SDK root could be found. Please check your installation.')
class NoMainClassError(exceptions.Error):
def __init__(self):
super(NoMainClassError, self).__init__(
'Invalid jar file: it does not contain a Main-Class Manifest entry.')
class MavenPomNotSupported(exceptions.Error):
def __init__(self):
super(MavenPomNotSupported, self).__init__(
'Maven source deployment is not supported for Java8 GAE project.')
class GradleBuildNotSupported(exceptions.Error):
def __init__(self):
super(GradleBuildNotSupported, self).__init__(
'Gradle source deployment is not supported for Java8 GAE project.')
class StagingCommandFailedError(exceptions.Error):
def __init__(self, args, return_code, output_message):
super(StagingCommandFailedError, self).__init__(
'Staging command [{0}] failed with return code [{1}].\n\n{2}'.format(
' '.join(args), return_code, output_message))
# TODO(b/65026284): eliminate "mappers" entirely by making a shim command
def _JavaStagingMapper(command_path, descriptor, app_dir, staging_dir):
"""Map a java staging request to the right args.
Args:
command_path: str, path to the jar tool file.
descriptor: str, path to the `appengine-web.xml`
app_dir: str, path to the unstaged app directory
staging_dir: str, path to the empty staging dir
Raises:
java.JavaError, if Java is not installed.
Returns:
[str], args for executable invocation.
"""
del descriptor # Unused, app_dir is sufficient
java_bin = java.RequireJavaInstalled('local staging for java')
args = ([java_bin, '-classpath', command_path, _JAVA_APPCFG_ENTRY_POINT] +
_JAVA_APPCFG_STAGE_FLAGS + ['stage', app_dir, staging_dir])
return args
class _Command(six.with_metaclass(abc.ABCMeta, object)):
"""Interface for a staging command to be invoked on the user source.
This abstract class facilitates running an executable command that conforms to
the "staging command" interface outlined in the module docstring.
It implements the parts that are common to any such command while allowing
interface implementors to swap out how the command is created.
"""
@abc.abstractmethod
def EnsureInstalled(self):
"""Ensure that the command is installed and available.
May result in a command restart if installation is required.
"""
raise NotImplementedError()
@abc.abstractmethod
def GetPath(self):
"""Returns the path to the command.
Returns:
str, the path to the command
Raises:
StagingCommandNotFoundError: if the staging command could not be found.
"""
raise NotImplementedError()
def GetArgs(self, descriptor, app_dir, staging_dir, explicit_appyaml=None):
"""Get the args for the command to execute.
Args:
descriptor: str, path to the unstaged <service>.yaml or appengine-web.xml
app_dir: str, path to the unstaged app directory
staging_dir: str, path to the directory to stage in.
explicit_appyaml: str or None, the app.yaml location
to used for deployment.
Returns:
list of str, the args for the command to run
"""
return [self.GetPath(), descriptor, app_dir, staging_dir]
def Run(self, staging_area, descriptor, app_dir, explicit_appyaml=None):
"""Invokes a staging command with a given <service>.yaml and temp dir.
Args:
staging_area: str, path to the staging area.
descriptor: str, path to the unstaged <service>.yaml or appengine-web.xml
app_dir: str, path to the unstaged app directory
explicit_appyaml: str or None, the app.yaml location
to used for deployment.
Returns:
str, the path to the staged directory or None if staging was not required.
Raises:
StagingCommandFailedError: if the staging command process exited non-zero.
"""
staging_dir = tempfile.mkdtemp(dir=staging_area)
args = self.GetArgs(descriptor, app_dir, staging_dir)
log.info('Executing staging command: [{0}]\n\n'.format(' '.join(args)))
out = io.StringIO()
err = io.StringIO()
return_code = execution_utils.Exec(
args, no_exit=True, out_func=out.write, err_func=err.write)
message = _STAGING_COMMAND_OUTPUT_TEMPLATE.format(
out=out.getvalue(), err=err.getvalue())
message = message.replace('\r\n', '\n')
log.info(message)
if return_code:
raise StagingCommandFailedError(args, return_code, message)
# Optionally use the custom app yaml if available:
if explicit_appyaml:
shutil.copyfile(explicit_appyaml, os.path.join(staging_dir, 'app.yaml'))
return staging_dir
class NoopCommand(_Command):
"""A command that does nothing.
Many runtimes do not require a staging step; this isn't a problem.
"""
def EnsureInstalled(self):
pass
def GetPath(self):
return None
def GetArgs(self, descriptor, app_dir, staging_dir, appyaml=None):
return None
def Run(self, staging_area, descriptor, app_dir, appyaml=None):
"""Does nothing."""
pass
def __eq__(self, other):
return isinstance(other, NoopCommand)
class CreateJava11ProjectCommand(_Command):
"""A command that creates a java11 runtime app.yaml."""
def EnsureInstalled(self):
pass
def GetPath(self):
return
def GetArgs(self, descriptor, staging_dir, appyaml=None):
return
def Run(self, staging_area, config_file, project_dir, explicit_appyaml=None):
# Logic is: copy/symlink the project in the staged area, and create a
# simple file app.yaml for runtime: java11 if it does not exist.
# If it exists in the standard and documented default location
# (in project_dir/src/main/appengine/app.yaml), copy it in the staged
# area.
appenginewebxml = os.path.join(project_dir, 'src', 'main', 'webapp',
'WEB-INF', 'appengine-web.xml')
if os.path.exists(appenginewebxml):
raise self.error()
if explicit_appyaml:
shutil.copyfile(explicit_appyaml, os.path.join(staging_area, 'app.yaml'))
else:
appyaml = os.path.join(project_dir, 'src', 'main', 'appengine',
'app.yaml')
if os.path.exists(appyaml):
# Put the user app.yaml at the root of the staging directory to deploy
# as required by the Cloud SDK.
shutil.copy2(appyaml, staging_area)
else:
# Create a very simple 1 liner app.yaml for Java11 runtime.
files.WriteFileContents(
os.path.join(staging_area, 'app.yaml'), 'runtime: java11\n')
for name in os.listdir(project_dir):
# Do not deploy locally built artifacts, buildpack will clean this anyway.
if name == self.ignore:
continue
srcname = os.path.join(project_dir, name)
dstname = os.path.join(staging_area, name)
try:
os.symlink(srcname, dstname)
except (AttributeError, OSError):
# AttributeError can occur if this is a Windows machine with an older
# version of Python, in which case os.symlink is not defined. If this is
# a newer version of Windows, but the user is not allowed to create
# symlinks, we'll get an OSError saying "symbolic link privilege not
# held." In both cases, we just fall back to copying the files.
log.debug('Could not symlink files in staging directory, falling back '
'to copying')
if os.path.isdir(srcname):
files.CopyTree(srcname, dstname)
else:
shutil.copy2(srcname, dstname)
return staging_area
def __eq__(self, other):
return isinstance(other, CreateJava11ProjectCommand)
class CreateJava11MavenProjectCommand(CreateJava11ProjectCommand):
"""A command that creates a java11 runtime app.yaml from a pom.xml file."""
def __init__(self):
self.error = MavenPomNotSupported
self.ignore = 'target'
super(CreateJava11MavenProjectCommand, self).__init__()
def __eq__(self, other):
return isinstance(other, CreateJava11GradleProjectCommand)
class CreateJava11GradleProjectCommand(CreateJava11ProjectCommand):
"""A command that creates a java11 runtime app.yaml from a build.gradle file."""
def __init__(self):
self.error = GradleBuildNotSupported
self.ignore = 'build'
super(CreateJava11GradleProjectCommand, self).__init__()
def __eq__(self, other):
return isinstance(other, CreateJava11GradleProjectCommand)
class CreateJava11YamlCommand(_Command):
"""A command that creates a java11 runtime app.yaml from a jar file."""
def EnsureInstalled(self):
pass
def GetPath(self):
return None
def GetArgs(self, descriptor, jar_file, staging_dir, appyaml=None):
return None
def Run(self, staging_area, jar_file, app_dir, appyaml=None):
# Logic is simple: copy the jar in the staged area, and create a simple
# file app.yaml for runtime: java11.
shutil.copy2(jar_file, staging_area)
if appyaml:
shutil.copyfile(appyaml, os.path.join(staging_area, 'app.yaml'))
else:
files.WriteFileContents(
os.path.join(staging_area, 'app.yaml'),
'runtime: java11\n',
private=True)
manifest = jarfile.ReadManifest(jar_file)
if manifest:
main_entry = manifest.main_section.get('Main-Class')
if main_entry is None:
raise NoMainClassError()
classpath_entry = manifest.main_section.get('Class-Path')
if classpath_entry:
libs = classpath_entry.split()
for lib in libs:
dependent_file = os.path.join(app_dir, lib)
# We copy the dep jar in the correct staging sub directories
# and only if it exists,
if os.path.isfile(dependent_file):
| |
#!/usr/bin/env python3
"""This script will take the output of cactus-align-batch (which was run on the output of cactus-graphmap-split). This would be
a set of .vg files, one for each chromosome. It will do the following in order to make a single output graph
- clip unmapped regions out of each graph
- join the ids of the clipped graph
- convert each clipped graph to gfa
- merge the gfas into a whole-genome graph
- convert the gfa into a gbwt/gbwt-graph pair
- export the gbwt to xg
- export the xg/gbwt to vcf
so the final output will be
- set of clipped vg graphs
- graph.gfa.gz
- graph.gbwt
- graph.gg
- graph.xg
- graph.snarls
- graph.vcf.gz
- graph.vcf.gz.tbi
"""
import os
from argparse import ArgumentParser
import xml.etree.ElementTree as ET
import copy
import timeit
from operator import itemgetter
from cactus.progressive.seqFile import SeqFile
from cactus.progressive.multiCactusTree import MultiCactusTree
from cactus.shared.common import setupBinaries, importSingularityImage
from cactus.progressive.multiCactusProject import MultiCactusProject
from cactus.shared.experimentWrapper import ExperimentWrapper
from cactus.shared.common import cactusRootPath
from cactus.shared.configWrapper import ConfigWrapper
from cactus.pipeline.cactus_workflow import CactusWorkflowArguments
from cactus.pipeline.cactus_workflow import addCactusWorkflowOptions
from cactus.shared.common import makeURL, catFiles
from cactus.shared.common import enableDumpStack
from cactus.shared.common import cactus_override_toil_options
from cactus.shared.common import cactus_call
from cactus.shared.common import getOptionalAttrib, findRequiredNode
from cactus.shared.common import unzip_gz, write_s3
from cactus.preprocessor.fileMasking import get_mask_bed_from_fasta
from toil.job import Job
from toil.common import Toil
from toil.statsAndLogging import logger
from toil.statsAndLogging import set_logging_from_options
from toil.realtimeLogger import RealtimeLogger
from toil.lib.threading import cpu_count
from sonLib.nxnewick import NXNewick
from sonLib.bioio import getTempDirectory, getTempFile, catFiles
def main():
parser = ArgumentParser()
Job.Runner.addToilOptions(parser)
addCactusWorkflowOptions(parser)
parser.add_argument("--vg", required=True, nargs='+', help = "Input vg files (PackedGraph or HashGraph format)")
parser.add_argument("--outDir", required=True, type=str, help = "Output directory")
parser.add_argument("--outName", required=True, type=str, help = "Basename of all output files")
parser.add_argument("--reference", required=True, type=str, help = "Reference event name")
parser.add_argument("--vcfReference", type=str, help = "Produce additional VCF for given reference event")
parser.add_argument("--rename", nargs='+', default = [], help = "Path renaming, each of form src>dest (see clip-vg -r)")
parser.add_argument("--clipLength", type=int, default=None, help = "clip out unaligned sequences longer than this")
parser.add_argument("--wlineSep", type=str, help = "wline separator for vg convert")
parser.add_argument("--indexCores", type=int, default=1, help = "cores for general indexing and VCF constructions")
parser.add_argument("--giraffeCores", type=int, default=None, help = "cores for giraffe-specific indexing (defaults to --indexCores)")
parser.add_argument("--decoyGraph", help= "decoy sequences vg graph to add (PackedGraph or HashGraph format)")
parser.add_argument("--hal", nargs='+', default = [], help = "Input hal files (for merging)")
parser.add_argument("--vcf", action="store_true", help= "make VCF")
parser.add_argument("--giraffe", action="store_true", help= "make Giraffe-specific indexes (distance and minimizer)")
parser.add_argument("--normalizeIterations", type=int, default=None,
help="Run this many iterations of vg normamlization (shared prefix zipping)")
parser.add_argument("--gfaffix", action="store_true",
help="Run GFAFfix normalization")
parser.add_argument("--vgClipOpts", nargs='+', help = "If specified, run vg clip with given options (surround in quotes; multiple allowed to chain multiple clip commands)")
parser.add_argument("--unclipSeqFile",type=str, help = "seqfile of unclipped sequences. If given, halUnclip will be run on the HAL output to restore original sequences (removing _sub suffixes)")
#Progressive Cactus Options
parser.add_argument("--configFile", dest="configFile",
help="Specify cactus configuration file",
default=os.path.join(cactusRootPath(), "cactus_progressive_config.xml"))
parser.add_argument("--latest", dest="latest", action="store_true",
help="Use the latest version of the docker container "
"rather than pulling one matching this version of cactus")
parser.add_argument("--containerImage", dest="containerImage", default=None,
help="Use the the specified pre-built containter image "
"rather than pulling one from quay.io")
parser.add_argument("--binariesMode", choices=["docker", "local", "singularity"],
help="The way to run the Cactus binaries", default=None)
options = parser.parse_args()
setupBinaries(options)
set_logging_from_options(options)
enableDumpStack()
if options.outDir and not options.outDir.startswith('s3://'):
if not os.path.isdir(options.outDir):
os.makedirs(options.outDir)
if options.hal and len(options.hal) != len(options.vg):
raise RuntimeError("If --hal and --vg should specify the same number of files")
if not options.giraffeCores:
options.giraffeCores = options.indexCores
if options.unclipSeqFile and not options.hal:
raise RuntimeError("--unclipSeqFile can only be used with --hal")
# Mess with some toil options to create useful defaults.
cactus_override_toil_options(options)
start_time = timeit.default_timer()
runCactusGraphMapJoin(options)
end_time = timeit.default_timer()
run_time = end_time - start_time
logger.info("cactus-graphmap-join has finished after {} seconds".format(run_time))
def runCactusGraphMapJoin(options):
with Toil(options) as toil:
importSingularityImage(options)
#Run the workflow
if options.restart:
wf_output = toil.restart()
else:
options.cactusDir = getTempDirectory()
#load cactus config
configNode = ET.parse(options.configFile).getroot()
config = ConfigWrapper(configNode)
config.substituteAllPredefinedConstantsWithLiterals()
# load up the vgs
vg_ids = []
for vg_path in options.vg:
logger.info("Importing {}".format(vg_path))
vg_ids.append(toil.importFile(makeURL(vg_path)))
# tack on the decoys
if options.decoyGraph:
logger.info("Importing decoys {}".format(options.decoyGraph))
vg_ids.append(toil.importFile(makeURL(options.decoyGraph)))
# we'll treat it like any other graph downstream, except clipping
# where we'll check first using the path name
options.vg.append(options.decoyGraph)
# load up the hals
hal_ids = []
for hal_path in options.hal:
logger.info("Importing {}".format(hal_path))
hal_ids.append(toil.importFile(makeURL(hal_path)))
# load up the sequences
unclip_seq_id_map = {}
if options.unclipSeqFile:
seqFile = SeqFile(options.unclipSeqFile)
leaves = set([seqFile.tree.getName(node) for node in seqFile.tree.getLeaves()])
for genome, seq in seqFile.pathMap.items():
if genome in leaves:
if os.path.isdir(seq):
tmpSeq = getTempFile()
catFiles([os.path.join(seq, subSeq) for subSeq in os.listdir(seq)], tmpSeq)
seq = tmpSeq
seq = makeURL(seq)
logger.info("Importing {}".format(seq))
unclip_seq_id_map[genome] = (seq, toil.importFile(seq))
# run the workflow
wf_output = toil.start(Job.wrapJobFn(graphmap_join_workflow, options, config, vg_ids, hal_ids, unclip_seq_id_map))
#export the split data
export_join_data(toil, options, wf_output[0], wf_output[1])
def graphmap_join_workflow(job, options, config, vg_ids, hal_ids, unclip_seq_id_map):
root_job = Job()
job.addChild(root_job)
# run clip-vg on each input
clipped_vg_ids = []
for vg_path, vg_id in zip(options.vg, vg_ids):
clip_job = root_job.addChildJobFn(clip_vg, options, config, vg_path, vg_id,
disk=vg_id.size * 2, memory=vg_id.size * 4)
clipped_vg_ids.append(clip_job.rv())
# join the ids
join_job = root_job.addFollowOnJobFn(join_vg, options, config, clipped_vg_ids,
disk=sum([f.size for f in vg_ids]))
clipped_vg_ids = join_job.rv()
# optional clipping -- we do this down here after joining and normalization so
# our graph is id-compatible with a graph that wasn't clipped (but run with same parameters otherwise)
if options.vgClipOpts:
clip_root_job = Job()
join_job.addFollowOn(clip_root_job)
clipped_vg_ids = []
for i in range(len(vg_ids)):
vg_clip_job = clip_root_job.addChildJobFn(vg_clip_vg, options, config, options.vg[i], join_job.rv(i),
disk=vg_ids[i].size * 2)
join_job.addFollowOn(vg_clip_job)
clipped_vg_ids.append(vg_clip_job.rv())
join_job = clip_root_job
# make a gfa for each
gfa_root_job = Job()
join_job.addFollowOn(gfa_root_job)
clipped_gfa_ids = []
for i in range(len(options.vg)):
vg_path = options.vg[i]
clipped_id = clipped_vg_ids[i] if options.vgClipOpts else join_job.rv(i)
vg_id = vg_ids[i]
gfa_job = gfa_root_job.addChildJobFn(vg_to_gfa, options, config, vg_path, clipped_id,
disk=vg_id.size * 5)
clipped_gfa_ids.append(gfa_job.rv())
# merge up the gfas and make the various vg indexes
gfa_merge_job = gfa_root_job.addFollowOnJobFn(vg_indexes, options, config, clipped_gfa_ids,
cores=options.indexCores,
disk=sum(f.size for f in vg_ids) * 5)
out_dicts = [gfa_merge_job.rv()]
# optional vcf
if options.vcf:
deconstruct_job = gfa_merge_job.addFollowOnJobFn(make_vcf, options.outName, options.reference, out_dicts[0],
cores=options.indexCores,
disk = sum(f.size for f in vg_ids) * 2)
out_dicts.append(deconstruct_job.rv())
# optional vcf with different reference
if options.vcfReference:
ref_deconstruct_job = gfa_merge_job.addFollowOnJobFn(make_vcf, options.outName, options.vcfReference, out_dicts[0],
tag=options.vcfReference + '.',
cores=options.indexCores,
disk = sum(f.size for f in vg_ids) * 2)
out_dicts.append(ref_deconstruct_job.rv())
# optional giraffe
if options.giraffe:
giraffe_job = gfa_merge_job.addFollowOnJobFn(make_giraffe_indexes, options, out_dicts[0],
cores=options.giraffeCores,
disk = sum(f.size for f in vg_ids) * 4)
out_dicts.append(giraffe_job.rv())
# optional hal merge
if hal_ids:
hal_merge_job = root_job.addChildJobFn(merge_hal, options, hal_ids,
cores = 1,
disk=sum(f.size for f in hal_ids) * 2)
hal_id_dict = hal_merge_job.rv()
if unclip_seq_id_map:
# optional hal unclip
unzip_seq_ids_job = root_job.addChildJobFn(unzip_seqfile, unclip_seq_id_map,
disk=sum(f.size for f in hal_ids) * 2)
hal_unclip_job = unzip_seq_ids_job.addFollowOnJobFn(unclip_hal, hal_merge_job.rv(), unzip_seq_ids_job.rv(),
disk=sum(f.size for f in hal_ids) * 5)
hal_merge_job.addFollowOn(hal_unclip_job)
hal_id_dict = hal_unclip_job.rv()
out_dicts.append(hal_id_dict)
return clipped_vg_ids, out_dicts
def clip_vg(job, options, config, vg_path, vg_id):
""" run clip-vg
"""
work_dir = job.fileStore.getLocalTempDir()
is_decoy = vg_path == options.decoyGraph
vg_path = os.path.join(work_dir, os.path.basename(vg_path))
job.fileStore.readGlobalFile(vg_id, vg_path)
clipped_path = vg_path + '.clip'
out_path = vg_path + '.out'
# remove masked unaligned regions with clip-vg
cmd = ['clip-vg', vg_path, '-f']
if options.clipLength is not None and not is_decoy:
cmd += ['-u', str(options.clipLength)]
for rs in options.rename:
cmd += ['-r', rs]
if options.reference:
cmd += ['-e', options.reference]
if getOptionalAttrib(findRequiredNode(config.xmlRoot, "hal2vg"), "includeMinigraph", typeFn=bool, default=False):
# our vg file has minigraph sequences -- we'll filter them out, along with any nodes
# that don't appear in a non-minigraph path
graph_event = getOptionalAttrib(findRequiredNode(config.xmlRoot, "graphmap"), "assemblyName", default="_MINIGRAPH_")
cmd += ['-d', graph_event]
cactus_call(parameters=cmd, outfile=clipped_path)
# optional normalization. this will (in theory) correct a lot of small underalignments due to cactus bugs
# by zipping up redundant nodes. done before clip-vg otherwise ref paths not guaranteed to be forwardized
# todo: would be nice if clip-vg worked on stdin
if options.normalizeIterations:
normalized_path = clipped_path + '.normalized'
mod_cmd = ['vg', 'mod', '-O', '-U', str(options.normalizeIterations), clipped_path]
if options.reference:
mod_cmd += ['-z', options.reference]
cactus_call(parameters=mod_cmd, outfile=normalized_path)
# worth it
cactus_call(parameters=['vg', 'validate', normalized_path])
clipped_path = normalized_path
# GFAFfix is a tool written just to normalize graphs, and alters a (faster) alternative to vg
# (though requires GFA conversion)
if options.gfaffix:
normalized_path = clipped_path + '.gfaffixed'
gfa_in_path = vg_path + '.gfa'
gfa_out_path = normalized_path + '.gfa'
cactus_call(parameters=['vg', 'convert', '-f', clipped_path], outfile=gfa_in_path)
fix_cmd = ['gfaffix', gfa_in_path, '--output_refined', gfa_out_path]
if | |
'''pipeline runner'''
import os
import json
import time
import glob
import logging
import tempfile
import datetime
import yaml
import utils.pipeline
import postgres.metrics
import postgres.utils
def filter_list(alist, blist):
'''remove blist from alist'''
return list(set(alist)-set(blist))
def get_cwl_steps(cwlwf):
'''get cwl steps names'''
cwl = dict()
with open(cwlwf, 'r') as fhandle:
cwl = yaml.load(fhandle)
cwl_steps = cwl['steps'].keys()
return cwl_steps
def dict_to_string(list_of_dict):
'''convert list of dict to list of strings'''
list_of_string = []
if list_of_dict:
for i in list_of_dict:
list_of_string.append(str(i))
else:
return None
return list_of_string
def run_alignment(args):
'''run alignment'''
input_data = utils.pipeline.load_template_json()['alignment_template']
sample_list = [args.aliquot_id] * len(args.readgroup_names)
pu_list = [args.job_uuid] * len(args.readgroup_names)
rgl_list = ['@RG\tCN:CGR\tPL:ILLUMINA\tID:{RG}\tSM:{SM}\tPU:{PU}\tLB:Library'\
.format(RG=rg, SM=sm, PU=pu) \
for rg, sm, pu in zip(args.readgroup_names, sample_list, pu_list)]
input_data['job_uuid'] = args.job_uuid
input_data['fastq_read1_uri'] = args.fastq_read1_uri
input_data['fastq_read2_uri'] = args.fastq_read2_uri
input_data['fastq_read1_md5'] = args.fastq_read1_md5
input_data['fastq_read2_md5'] = args.fastq_read2_md5
input_data['readgroup_lines'] = rgl_list
input_data['readgroup_names'] = args.readgroup_names
workflow_meta = {
'basedir': args.basedir,
'pipeline': args.choice,
'project': args.project,
'job_uuid': args.job_uuid,
'aliquot_id': args.aliquot_id,
'input_table': args.input_table,
'cwlwf': args.cwlwf
}
genomel = GenomelIndiv(
workflow_meta=workflow_meta,
input_data=input_data,
psql_conf=args.psql_conf
)
genomel.run()
def run_harmonization(args):
'''run harmonization'''
input_data = utils.pipeline.load_template_json()['harmonization_template']
input_data['job_uuid'] = args.job_uuid
input_data['bam_uri'] = args.bam_uri
input_data['bam_md5'] = args.bam_md5
workflow_meta = {
'basedir': args.basedir,
'pipeline': args.choice,
'project': args.project,
'job_uuid': args.job_uuid,
'aliquot_id': args.aliquot_id,
'input_table': args.input_table,
'cwlwf': args.cwlwf
}
genomel = GenomelIndiv(
workflow_meta=workflow_meta,
input_data=input_data,
psql_conf=args.psql_conf
)
genomel.run()
def run_cohort_genotyping(args):
'''run cohort genotyping'''
cohort_template_json = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"etc/cohort_genotyping.json"
)
input_data = utils.pipeline.load_json(cohort_template_json)
input_data['job_uuid'] = args.job_uuid
input_data['gvcf_files'] = utils.pipeline.create_cwl_array_input(args.gvcf_files_manifest)
input_data['gatk4_genotyping_thread_count'] = args.gatk4_genotyping_thread_count
input_data['number_of_chunks_for_gatk'] = args.number_of_chunks_for_gatk
input_data['bam_files'] = utils.pipeline.create_cwl_array_input(args.bam_files_manifest)
input_data['freebayes_thread_count'] = args.freebayes_thread_count
input_data['number_of_chunks_for_freebayes'] = args.number_of_chunks_for_freebayes
input_data['upload_s3_bucket'] = os.path.join(
args.upload_s3_bucket,
args.project,
args.batch_id,
args.job_uuid
)
workflow_meta = {
'basedir': args.basedir,
'project': args.project,
'batch_id': args.batch_id,
'job_uuid': args.job_uuid,
'input_table': args.input_table,
'cromwell_config': os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)
)
)
),
"cromwell/cromwell.conf"
),
'cromwell_jar_path': args.cromwell_jar_path,
'cwlwf': os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)
)
)
),
"genomel_cohort_genotyping.cwl"
),
'cwl_pack': os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)
)
)
),
"cwl.zip"
)
}
genomel = GenomelCohort(
workflow_meta=workflow_meta,
input_data=input_data,
psql_conf=args.psql_conf
)
genomel.run()
def run_cohort_gatk(args):
'''run cohort gatk4'''
cohort_template_json = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"etc/cohort_gatk.prod.json"
)
input_data = utils.pipeline.load_json(cohort_template_json)
input_data['job_uuid'] = args.job_uuid
input_data['gvcf_files'] = utils.pipeline.create_cwl_array_input(args.gvcf_files_manifest)
input_data['gatk4_genotyping_thread_count'] = args.gatk4_genotyping_thread_count
input_data['number_of_chunks_for_gatk'] = args.number_of_chunks_for_gatk
input_data['upload_s3_bucket'] = os.path.join(
args.upload_s3_bucket,
args.project,
args.batch_id,
args.job_uuid
)
workflow_meta = {
'basedir': args.basedir,
'project': args.project,
'batch_id': args.batch_id,
'job_uuid': args.job_uuid,
'input_table': args.input_table,
'cromwell_config': os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)
)
)
),
"cromwell/cromwell.conf"
),
'cromwell_jar_path': args.cromwell_jar_path,
'cwlwf': os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)
)
)
),
"genomel_cohort_gatk4.cwl"
),
'cwl_pack': os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)
)
)
),
"cwl.zip"
)
}
genomel = GenomelCohort(
workflow_meta=workflow_meta,
input_data=input_data,
psql_conf=args.psql_conf
)
genomel.run()
def run_cohort_freebayes(args):
'''run cohort genotyping'''
cohort_template_json = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"etc/cohort_freebayes.json"
)
input_data = utils.pipeline.load_json(cohort_template_json)
input_data['job_uuid'] = args.job_uuid
input_data['bed_files'] = utils.pipeline.create_cwl_array_input(args.bed_files_manifest)
input_data['freebayes_thread_count'] = args.freebayes_thread_count
input_data['number_of_chunks_for_freebayes'] = args.number_of_chunks_for_freebayes
input_data['upload_s3_bucket'] = os.path.join(
args.upload_s3_bucket,
args.project,
args.batch_id,
args.job_uuid
)
workflow_meta = {
'basedir': args.basedir,
'project': args.project,
'batch_id': args.batch_id,
'job_uuid': args.job_uuid,
'input_table': args.input_table,
'cromwell_config': os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)
)
)
),
"cromwell/cromwell.conf"
),
'cromwell_jar_path': args.cromwell_jar_path,
'cwlwf': os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)
)
)
),
"genomel_cohort_freebayes.cwl"
),
'cwl_pack': os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)
)
)
),
"cwl.zip"
)
}
genomel = GenomelCohort(
workflow_meta=workflow_meta,
input_data=input_data,
psql_conf=args.psql_conf
)
genomel.run()
def run_fbc(args):
'''run post-qc on freebayes chunks'''
input_data = utils.pipeline.load_template_json()['post_freebayes_template']
input_data['job_uuid'] = args.job_uuid
input_data['vcf']['path'] = args.vcf
workflow_meta = {
'basedir': args.basedir,
'job_uuid': args.job_uuid,
'bed': args.bed,
'cwlwf': args.cwlwf
}
genomel = PostFreebayes(
workflow_meta=workflow_meta,
input_data=input_data,
psql_conf=args.psql_conf
)
genomel.run()
class GenomelIndiv(object):
'''this class describes GenoMEL-Bionimbus Protected Data Cloud pipelines'''
def __init__(self, workflow_meta, input_data, psql_conf):
'''
workflow_meta.keys() = [
'basedir',
'pipeline',
'project',
'job_uuid',
'aliquot_id',
'input_table',
'cwlwf'
]
'''
self.input_data = input_data
self.pg_data = utils.pipeline.pg_data_template()
self.psql_conf = psql_conf
self.psql_class = postgres.metrics.GenomelIndividualMetrics
# setup workflow metadata
self.workflow_meta = workflow_meta
self.workflow_meta['base_s3_loc'] = os.path.join(
self.input_data['upload_s3_bucket'],
self.workflow_meta['job_uuid']
)
self.workflow_meta['log_file'] = None
self.workflow_meta['cwl_input_json'] = self._cwl_input_json()
self.workflow_meta['cwl_output_json'] = self._cwl_output_json()
self.workflow_meta['log_dir'] = None
self.workflow_meta['cwl_log_tar'] = None
self.workflow_meta['cwl_start'] = None
self.workflow_meta['cwl_end'] = None
self.workflow_meta['cwl_failure'] = False
self.workflow_meta['runner_failure'] = False
self.workflow_meta['pipeline_time'] = 0.0
self.workflow_meta['pipeline_avg_cpu_percentage'] = 0
self.workflow_meta['haplotypecaller_time'] = 0.0
self.workflow_meta['haplotypecaller_avg_cpu_percentage'] = 0
def run(self):
'''main pipeline'''
# setup start-time
self.workflow_meta['cwl_start'] = time.time()
self.workflow_meta['datetime_start'] = str(datetime.datetime.now())
# setup work env
os.chdir(self.workflow_meta['basedir'])
tmpdir = self.create_tmp_dir('tmpdir_')
logger = self._log()
# cwl cmd
cmd = [
'/home/ubuntu/.virtualenvs/p2/bin/cwltool',
'--debug',
'--relax-path-checks',
'--outdir', self.workflow_meta['basedir'],
'--tmpdir-prefix', tmpdir,
'--tmp-outdir-prefix', tmpdir,
self.workflow_meta['cwlwf'],
self.workflow_meta['cwl_input_json']
]
# run cwl
cwl_exit = utils.pipeline.run_command(cmd, logger, self.workflow_meta['cwl_output_json'])
# cwl status
if cwl_exit:
self.workflow_meta['cwl_failure'] = True
# calculate cpu percentage
self._calculate_cpu_percentage()
# tar all logs
tar_exit = self._tar_log(logger)
if tar_exit:
self.workflow_meta['runner_failure'] = True
# upload ancillary files
upload_exit = self._upload_ancillary_files(logger)
if upload_exit:
self.workflow_meta['runner_failure'] = True
# update psql
if not self.workflow_meta['cwl_failure'] and not self.workflow_meta['runner_failure']:
self._process_cwl_success()
else:
self._process_cwl_fail()
engine = postgres.utils.get_db_engine(self.psql_conf)
postgres.metrics.add_metrics(engine, self.psql_class, self.pg_data)
# clean up
utils.pipeline.remove_dir(self.workflow_meta['basedir'])
def _cwl_input_json(self):
'''prepare cwl input json'''
cwl_input_json = os.path.join(
self.workflow_meta['basedir'], 'genomel_individual.{0}.{1}.{2}.{3}.json'.format(
self.workflow_meta['pipeline'],
self.workflow_meta['project'],
self.workflow_meta['job_uuid'],
self.workflow_meta['aliquot_id']
)
)
with open(cwl_input_json, 'wt') as ohandle:
json.dump(self.input_data, ohandle, indent=4)
return cwl_input_json
def _cwl_output_json(self):
'''prepare cwl output json'''
cwl_output_json = os.path.join(
self.workflow_meta['basedir'], 'genomel_individual.{0}.{1}.{2}.{3}.output'.format(
self.workflow_meta['pipeline'],
self.workflow_meta['project'],
self.workflow_meta['job_uuid'],
self.workflow_meta['aliquot_id']
)
)
return cwl_output_json
def create_tmp_dir(self, prefix):
'''create cwl tmp directory'''
tmpdir = tempfile.mkdtemp(prefix="{}".format(prefix), dir=self.workflow_meta['basedir'])
return tmpdir
def _log(self):
'''setup log file'''
log_file = os.path.join(
os.path.dirname(self.workflow_meta['basedir']),
'genomel_individual.{0}.{1}.{2}.{3}.log'.format(
self.workflow_meta['pipeline'],
self.workflow_meta['project'],
self.workflow_meta['job_uuid'],
self.workflow_meta['aliquot_id']
)
)
self.workflow_meta['log_file'] = log_file
logger = utils.pipeline.setup_logging(
logging.INFO,
self.workflow_meta['job_uuid'],
log_file
)
return logger
def _calculate_cpu_percentage(self):
'''calculate average cpu percentage'''
cwl_logs = glob.glob(
'{}/{}*time.json'.format(
self.workflow_meta['basedir'],
self.workflow_meta['job_uuid']
)
)
pipeline_cpu_usage = []
pipeline_cpu_time = []
haplotypecaller_cpu_usage = []
haplotypecaller_cpu_time = []
if cwl_logs:
for log in cwl_logs:
dic = utils.pipeline.load_json(log)
cpu_percent = float(dic['percent_of_cpu'][:-1])
step_weight = float(dic['wall_clock'])
if 'gatk3' in log or 'picard' in log:
haplotypecaller_cpu_usage.append(cpu_percent * step_weight)
haplotypecaller_cpu_time.append(step_weight)
else:
pipeline_cpu_usage.append(cpu_percent * step_weight)
pipeline_cpu_time.append(step_weight)
pipeline_time = sum(pipeline_cpu_time)
pipeline_avg_cpu_usage = str(int(sum(pipeline_cpu_usage)/sum(pipeline_cpu_time))) + '%'
haplotypecaller_time = sum(haplotypecaller_cpu_time)
haplotypecaller_avg_cpu_usage = str(
int(sum(haplotypecaller_cpu_usage)/sum(haplotypecaller_cpu_time))
) + '%'
else:
pipeline_time = None
pipeline_avg_cpu_usage = None
haplotypecaller_time = None
haplotypecaller_avg_cpu_usage = None
self.workflow_meta['pipeline_time'] = pipeline_time
self.workflow_meta['pipeline_avg_cpu_percentage'] = pipeline_avg_cpu_usage
self.workflow_meta['haplotypecaller_time'] = haplotypecaller_time
self.workflow_meta['haplotypecaller_avg_cpu_percentage'] = haplotypecaller_avg_cpu_usage
def _tar_log(self, logger):
'''make tar for all cwl time logs'''
cwl_logs = glob.glob('{}/*time.json'.format(self.workflow_meta['basedir']))
if cwl_logs:
self.workflow_meta['log_dir'] = self.create_tmp_dir('cwl_logs_')
for log in cwl_logs:
utils.pipeline.move_file(log, self.workflow_meta['log_dir'])
self.workflow_meta['cwl_log_tar'] = os.path.join(
self.workflow_meta['basedir'], \
'genomel_individual.{0}.{1}.{2}.{3}.cwl_logs.tar.bz2'.format(
self.workflow_meta['pipeline'],
self.workflow_meta['project'],
self.workflow_meta['job_uuid'],
self.workflow_meta['aliquot_id']
)
)
exit_code = utils.pipeline.targz_compress(
logger,
self.workflow_meta['cwl_log_tar'],
self.workflow_meta['log_dir']
)
else: exit_code = 1
return exit_code
def _upload_ancillary_files(self, logger):
'''upload tar file of all cwl logs'''
to_upload_dir = self.create_tmp_dir('to_upload_')
utils.pipeline.move_file(self.workflow_meta['cwl_input_json'], to_upload_dir)
if self.workflow_meta['cwl_log_tar']:
utils.pipeline.move_file(self.workflow_meta['cwl_log_tar'], to_upload_dir)
remote_loc = os.path.join(
self.input_data['upload_s3_bucket'],
self.workflow_meta['job_uuid']
)
exit_code = utils.pipeline.aws_s3_put(
logger=logger,
remote_output=remote_loc,
local_input=to_upload_dir,
profile=self.input_data['upload_s3_profile'],
endpoint_url=self.input_data['upload_s3_endpoint'],
recursive=True
)
return exit_code
def _time(self, handle):
'''extract time from cwl logs'''
logs = glob.glob('{}/{}'.format(self.workflow_meta['log_dir'], handle))
time_list = []
if logs:
for log in logs:
dic = utils.pipeline.load_json(log)
_time = float(dic['wall_clock'])
time_list.append(_time)
total_time = sum(time_list)
else: total_time = None
return total_time
def _stage_local(self, indiv):
'''stage cwl output to local gluster'''
indiv_dir = os.path.join(
'/mnt/glusterfs',
'genomel_individual.{0}.{1}.{2}.{3}'.format(
self.workflow_meta['pipeline'],
self.workflow_meta['project'],
self.workflow_meta['job_uuid'],
self.workflow_meta['aliquot_id']
)
)
if not os.path.isdir(indiv_dir):
os.mkdir(indiv_dir)
utils.pipeline.move_file(indiv, indiv_dir)
return os.path.join(indiv_dir, os.path.basename(indiv))
def _process_cwl_success(self):
'''process when cwl successes'''
download_time = self._time('aws_download*')
bam_upload_time = self._time('aws_upload*duplicates_marked.sorted*')
gvcf_upload_time = self._time('aws_upload*haplotypecaller*')
cwl_output = utils.pipeline.load_json(self.workflow_meta['cwl_output_json'])
bam_local_path = self._stage_local(
cwl_output['genomel_bam']['path']
)
self._stage_local(cwl_output['genomel_bam']['secondaryFiles'][0]['path'])
gvcf_local_path = self._stage_local(
cwl_output['genomel_gvcf']['path']
)
self._stage_local(cwl_output['genomel_gvcf']['secondaryFiles'][0]['path'])
self.workflow_meta['cwl_end'] = time.time()
self.pg_data['job_uuid'] = self.workflow_meta['job_uuid']
self.pg_data['aliquot_id'] = self.workflow_meta['aliquot_id']
self.pg_data['input_table'] = self.workflow_meta['input_table']
self.pg_data['project'] = self.workflow_meta['project']
self.pg_data['status'] = "COMPLETED"
self.pg_data['datetime_start'] = self.workflow_meta['datetime_start']
self.pg_data['datetime_end'] = str(datetime.datetime.now())
self.pg_data['download_time'] = download_time
self.pg_data['bam_upload_time'] = bam_upload_time
self.pg_data['gvcf_upload_time'] = gvcf_upload_time
self.pg_data['bam_url'] = os.path.join(
self.workflow_meta['base_s3_loc'],
cwl_output['genomel_bam']['basename']
)
self.pg_data['gvcf_url'] = os.path.join(
self.workflow_meta['base_s3_loc'],
cwl_output['genomel_gvcf']['basename']
)
self.pg_data['bam_local_path'] = bam_local_path
self.pg_data['gvcf_local_path'] = gvcf_local_path
self.pg_data['bam_md5sum'] = utils.pipeline.get_md5(bam_local_path)
self.pg_data['gvcf_md5sum'] = utils.pipeline.get_md5(gvcf_local_path)
self.pg_data['bam_filesize'] = utils.pipeline.get_file_size(bam_local_path)
self.pg_data['gvcf_filesize'] = utils.pipeline.get_file_size(gvcf_local_path)
if self.workflow_meta['pipeline'] == 'alignment':
self.pg_data['alignment_cwl_walltime'] = self.workflow_meta['pipeline_time']
self.pg_data['alignment_cwl_cpu_percentage'] = self.workflow_meta\
['pipeline_avg_cpu_percentage']
else:
self.pg_data['harmonization_cwl_walltime'] = self.workflow_meta['pipeline_time']
self.pg_data['harmonization_cwl_cpu_percentage'] = self.workflow_meta\
['pipeline_avg_cpu_percentage']
self.pg_data['haplotypecaller_cwl_walltime'] = self.workflow_meta['haplotypecaller_time']
self.pg_data['haplotypecaller_cwl_cpu_percentage'] = self.workflow_meta\
['haplotypecaller_avg_cpu_percentage']
self.pg_data['whole_workflow_elapsed'] = float(
self.workflow_meta['cwl_end'] - self.workflow_meta['cwl_start']
)
self.pg_data['cwl_input_json'] = os.path.join(
self.workflow_meta['base_s3_loc'],
os.path.basename(self.workflow_meta['cwl_input_json'])
)
self.pg_data['time_metrics_json'] = os.path.join(
self.workflow_meta['base_s3_loc'],
os.path.basename(self.workflow_meta['cwl_log_tar'])
)
self.pg_data['debug_path'] = self.workflow_meta['log_file']
def _process_cwl_fail(self):
'''process when cwl fails'''
if self.workflow_meta['cwl_failure']:
cwl_output = utils.pipeline.load_json(self.workflow_meta['cwl_output_json'])
if cwl_output:
try:
if cwl_output['genomel_gvcf']:
status = "FAILED_WHEN_UPLOAD"
elif cwl_output['genomel_bam']:
status = "FAILED_IN_VARIANT_CALLING"
else:
status = "FAILED_IN_EARLY_STAGE"
except ValueError:
status = "FAILED"
else: status = "FAILED_IN_CWL"
else: status = "FAILED_IN_PYTHON_RUNNER"
self.workflow_meta['cwl_end'] = time.time()
self.pg_data['job_uuid'] = self.workflow_meta['job_uuid']
self.pg_data['aliquot_id'] = self.workflow_meta['aliquot_id']
self.pg_data['input_table'] = self.workflow_meta['input_table']
self.pg_data['project'] = self.workflow_meta['project']
self.pg_data['status'] = status
self.pg_data['datetime_start'] = self.workflow_meta['datetime_start']
self.pg_data['datetime_end'] = str(datetime.datetime.now())
self.pg_data['whole_workflow_elapsed'] = float(
self.workflow_meta['cwl_end'] - self.workflow_meta['cwl_start']
)
self.pg_data['cwl_input_json'] = os.path.join(
self.workflow_meta['base_s3_loc'],
os.path.basename(self.workflow_meta['cwl_input_json'])
)
self.pg_data['debug_path'] = self.workflow_meta['log_file']
class GenomelCohort(object):
'''this class describes GenoMEL-Bionimbus Protected Data Cloud cohort genotyping pipeline'''
def __init__(self, workflow_meta, input_data, psql_conf):
'''
workflow_meta.keys() = | |
Literal["BinomialJoshi4ConvertibleEngine"]
] = "BinomialJoshi4ConvertibleEngine"
value: GeneralizedBlackScholesProcess
steps: int
class Futures(BaseModel):
resource_name: Optional[Literal["Futures"]] = "Futures"
class OvernightIndexFuture(BaseModel):
resource_name: Optional[Literal["OvernightIndexFuture"]] = "OvernightIndexFuture"
class Pillar(BaseModel):
resource_name: Optional[Literal["Pillar"]] = "Pillar"
class DatedOISRateHelper(BaseModel):
resource_name: Optional[Literal["DatedOISRateHelper"]] = "DatedOISRateHelper"
startDate: Date
endDate: Date
rate: QuoteHandle
index: OvernightIndex
discountingCurve: Optional[YieldTermStructureHandle] = None
class Discount(BaseModel):
resource_name: Optional[Literal["Discount"]] = "Discount"
class ZeroYield(BaseModel):
resource_name: Optional[Literal["ZeroYield"]] = "ZeroYield"
class ForwardRate(BaseModel):
resource_name: Optional[Literal["ForwardRate"]] = "ForwardRate"
class IterativeBootstrap(BaseModel):
resource_name: Optional[Literal["IterativeBootstrap"]] = "IterativeBootstrap"
accuracy: Optional[Optional[float]] = None
minValue: Optional[Optional[float]] = None
maxValue: Optional[Optional[float]] = None
class GlobalBootstrap0(BaseModel):
resource_name: Optional[Literal["GlobalBootstrap"]] = "GlobalBootstrap"
additionalHelpers: List[RateHelper]
additionalDates: List[Date]
accuracy: Optional[Optional[float]] = None
class GlobalBootstrap1(BaseModel):
resource_name: Optional[Literal["GlobalBootstrap"]] = "GlobalBootstrap"
accuracy: Optional[Optional[float]] = None
class DefaultProbabilityTermStructureHandle(BaseModel):
resource_name: Optional[
Literal["DefaultProbabilityTermStructureHandle"]
] = "DefaultProbabilityTermStructureHandle"
value: Optional[DefaultProbabilityTermStructure] = None
class RelinkableDefaultProbabilityTermStructureHandle(BaseModel):
resource_name: Optional[
Literal["RelinkableDefaultProbabilityTermStructureHandle"]
] = "RelinkableDefaultProbabilityTermStructureHandle"
value: Optional[DefaultProbabilityTermStructure] = None
class FlatHazardRate0(BaseModel):
resource_name: Optional[Literal["FlatHazardRate"]] = "FlatHazardRate"
settlementDays: int
calendar: Calendar
hazardRate: QuoteHandle
dayCounter: DayCounter
class FlatHazardRate1(BaseModel):
resource_name: Optional[Literal["FlatHazardRate"]] = "FlatHazardRate"
todaysDate: Date
hazardRate: QuoteHandle
dayCounter: DayCounter
class HazardRate(BaseModel):
resource_name: Optional[Literal["HazardRate"]] = "HazardRate"
class DefaultDensity(BaseModel):
resource_name: Optional[Literal["DefaultDensity"]] = "DefaultDensity"
class Protection(BaseModel):
resource_name: Optional[Literal["Protection"]] = "Protection"
class FaceValueClaim(BaseModel):
resource_name: Optional[Literal["FaceValueClaim"]] = "FaceValueClaim"
class MidPointCdsEngine(BaseModel):
resource_name: Optional[Literal["MidPointCdsEngine"]] = "MidPointCdsEngine"
probability: DefaultProbabilityTermStructureHandle
recoveryRate: float
discountCurve: YieldTermStructureHandle
class BlackCdsOptionEngine(BaseModel):
resource_name: Optional[Literal["BlackCdsOptionEngine"]] = "BlackCdsOptionEngine"
value: DefaultProbabilityTermStructureHandle
recoveryRate: float
termStructure: YieldTermStructureHandle
vol: QuoteHandle
class NormalDistribution(BaseModel):
resource_name: Optional[Literal["NormalDistribution"]] = "NormalDistribution"
average: Optional[float] = None
sigma: Optional[float] = None
class CumulativeNormalDistribution(BaseModel):
resource_name: Optional[
Literal["CumulativeNormalDistribution"]
] = "CumulativeNormalDistribution"
average: Optional[float] = None
sigma: Optional[float] = None
class InverseCumulativeNormal(BaseModel):
resource_name: Optional[
Literal["InverseCumulativeNormal"]
] = "InverseCumulativeNormal"
average: Optional[float] = None
sigma: Optional[float] = None
class MoroInverseCumulativeNormal(BaseModel):
resource_name: Optional[
Literal["MoroInverseCumulativeNormal"]
] = "MoroInverseCumulativeNormal"
average: Optional[float] = None
sigma: Optional[float] = None
class BivariateCumulativeNormalDistribution(BaseModel):
resource_name: Optional[
Literal["BivariateCumulativeNormalDistribution"]
] = "BivariateCumulativeNormalDistribution"
rho: float
class BinomialDistribution(BaseModel):
resource_name: Optional[Literal["BinomialDistribution"]] = "BinomialDistribution"
p: float
n: float
class CumulativeBinomialDistribution(BaseModel):
resource_name: Optional[
Literal["CumulativeBinomialDistribution"]
] = "CumulativeBinomialDistribution"
p: float
n: float
class BivariateCumulativeNormalDistributionDr78(BaseModel):
resource_name: Optional[
Literal["BivariateCumulativeNormalDistributionDr7"]
] = "BivariateCumulativeNormalDistributionDr7"
rho: float
class BivariateCumulativeNormalDistributionWe04DP(BaseModel):
resource_name: Optional[
Literal["BivariateCumulativeNormalDistributionWe04DP"]
] = "BivariateCumulativeNormalDistributionWe04DP"
rho: float
class CumulativeChiSquareDistribution(BaseModel):
resource_name: Optional[
Literal["CumulativeChiSquareDistribution"]
] = "CumulativeChiSquareDistribution"
df: float
class NonCentralCumulativeChiSquareDistribution(BaseModel):
resource_name: Optional[
Literal["NonCentralCumulativeChiSquareDistribution"]
] = "NonCentralCumulativeChiSquareDistribution"
df: float
ncp: float
class InverseNonCentralCumulativeChiSquareDistribution(BaseModel):
resource_name: Optional[
Literal["InverseNonCentralCumulativeChiSquareDistribution"]
] = "InverseNonCentralCumulativeChiSquareDistribution"
df: float
ncp: float
maxEvaluations: Optional[int] = None
accuracy: Optional[float] = None
class CumulativeGammaDistribution(BaseModel):
resource_name: Optional[
Literal["CumulativeGammaDistribution"]
] = "CumulativeGammaDistribution"
a: float
class GammaFunction(BaseModel):
resource_name: Optional[Literal["GammaFunction"]] = "GammaFunction"
class PoissonDistribution(BaseModel):
resource_name: Optional[Literal["PoissonDistribution"]] = "PoissonDistribution"
mu: float
class CumulativePoissonDistribution(BaseModel):
resource_name: Optional[
Literal["CumulativePoissonDistribution"]
] = "CumulativePoissonDistribution"
mu: float
class InverseCumulativePoisson(BaseModel):
resource_name: Optional[
Literal["InverseCumulativePoisson"]
] = "InverseCumulativePoisson"
lambda_: float = Field(..., alias="lambda")
class StudentDistribution(BaseModel):
resource_name: Optional[Literal["StudentDistribution"]] = "StudentDistribution"
n: int
class CumulativeStudentDistribution(BaseModel):
resource_name: Optional[
Literal["CumulativeStudentDistribution"]
] = "CumulativeStudentDistribution"
n: int
class InverseCumulativeStudent(BaseModel):
resource_name: Optional[
Literal["InverseCumulativeStudent"]
] = "InverseCumulativeStudent"
n: int
accuracy: Optional[float] = None
maxIterations: Optional[int] = None
class Money0(BaseModel):
resource_name: Optional[Literal["Money"]] = "Money"
currency: Currency
value: float
class Money1(BaseModel):
resource_name: Optional[Literal["Money"]] = "Money"
value: float
currency: Currency
class ExchangeRate(BaseModel):
resource_name: Optional[Literal["ExchangeRate"]] = "ExchangeRate"
source: Currency
target: Currency
rate: float
class ExchangeRateManager(BaseModel):
resource_name: Optional[Literal["ExchangeRateManager"]] = "ExchangeRateManager"
class Settings(BaseModel):
resource_name: Optional[Literal["Settings"]] = "Settings"
class Fdm1dMesherBase(BaseModel):
resource_name: Optional[Literal["Fdm1dMesher"]] = "Fdm1dMesher"
size: int
class FdmBlackScholesMesher(BaseModel):
resource_name: Optional[Literal["FdmBlackScholesMesher"]] = "FdmBlackScholesMesher"
size: int
process: GeneralizedBlackScholesProcess
maturity: float
strike: float
xMinConstraint: Optional[Optional[float]] = None
xMaxConstraint: Optional[Optional[float]] = None
eps: Optional[float] = None
scaleFactor: Optional[float] = None
cPoint: Optional[List[Union[float, float]]] = None
dividendSchedule: Optional[List[Dividend]] = None
fdmQuantoHelper: Optional[FdmQuantoHelper] = None
spotAdjustment: Optional[float] = None
class Concentrating1dMesher0(BaseModel):
resource_name: Optional[Literal["Concentrating1dMesher"]] = "Concentrating1dMesher"
start: float
end: float
size: int
cPoints: List[List[Union[float, float, bool]]]
tol: Optional[float] = None
class Concentrating1dMesher1(BaseModel):
resource_name: Optional[Literal["Concentrating1dMesher"]] = "Concentrating1dMesher"
start: float
end: float
size: int
cPoints: Optional[List[Union[float, float]]] = None
requireCPoint: Optional[bool] = None
class ExponentialJump1dMesher(BaseModel):
resource_name: Optional[
Literal["ExponentialJump1dMesher"]
] = "ExponentialJump1dMesher"
steps: int
beta: float
jumpIntensity: float
eta: float
eps: Optional[float] = None
class FdmCEV1dMesher(BaseModel):
resource_name: Optional[Literal["FdmCEV1dMesher"]] = "FdmCEV1dMesher"
size: int
f0: float
alpha: float
beta: float
maturity: float
eps: Optional[float] = None
scaleFactor: Optional[float] = None
cPoint: Optional[List[Union[float, float]]] = None
class FdmHestonVarianceMesher(BaseModel):
resource_name: Optional[
Literal["FdmHestonVarianceMesher"]
] = "FdmHestonVarianceMesher"
size: int
process: HestonProcess
maturity: float
tAvgSteps: Optional[int] = None
epsilon: Optional[float] = None
class FdmHestonLocalVolatilityVarianceMesher(BaseModel):
resource_name: Optional[
Literal["FdmHestonLocalVolatilityVarianceMesher"]
] = "FdmHestonLocalVolatilityVarianceMesher"
size: int
process: HestonProcess
leverageFct: LocalVolTermStructure
maturity: float
tAvgSteps: Optional[int] = None
epsilon: Optional[float] = None
class Uniform1dMesher(BaseModel):
resource_name: Optional[Literal["Uniform1dMesher"]] = "Uniform1dMesher"
start: float
end: float
size: int
class Predefined1dMesher(BaseModel):
resource_name: Optional[Literal["Predefined1dMesher"]] = "Predefined1dMesher"
x: List[float]
class Glued1dMesher(BaseModel):
resource_name: Optional[Literal["Glued1dMesher"]] = "Glued1dMesher"
leftMesher: Fdm1dMesher
rightMesher: Fdm1dMesher
class MesherItem(BaseModel):
resource_name: Optional[Literal["MesherItem"]] = "MesherItem"
class FdmMesherComposite0(BaseModel):
resource_name: Optional[Literal["FdmMesherComposite"]] = "FdmMesherComposite"
mesher: Union[MesherItem, Fdm1dMesher]
class FdmMesherComposite1(BaseModel):
resource_name: Optional[Literal["FdmMesherComposite"]] = "FdmMesherComposite"
m1: Fdm1dMesher
m2: Fdm1dMesher
m3: Optional[Fdm1dMesher] = None
m4: Optional[Fdm1dMesher] = None
class FdmBlackScholesOp(BaseModel):
resource_name: Optional[Literal["FdmBlackScholesOp"]] = "FdmBlackScholesOp"
mesher: FdmMesher
process: GeneralizedBlackScholesProcess
strike: float
localVol: Optional[bool] = None
illegalLocalVolOverwrite: Optional[Optional[float]] = None
direction: Optional[int] = None
quantoHelper: Optional[FdmQuantoHelper] = None
class Fdm2dBlackScholesOp(BaseModel):
resource_name: Optional[Literal["Fdm2dBlackScholesOp"]] = "Fdm2dBlackScholesOp"
mesher: FdmMesher
p1: GeneralizedBlackScholesProcess
p2: GeneralizedBlackScholesProcess
correlation: float
maturity: float
localVol: Optional[bool] = None
illegalLocalVolOverwrite: Optional[Optional[float]] = None
class FdmCEVOp(BaseModel):
resource_name: Optional[Literal["FdmCEVOp"]] = "FdmCEVOp"
mesher: FdmMesher
rTS: YieldTermStructure
f0: float
alpha: float
beta: float
direction: int
class FdmG2Op(BaseModel):
resource_name: Optional[Literal["FdmG2Op"]] = "FdmG2Op"
mesher: FdmMesher
model: G2
direction1: int
direction2: int
class FdmHestonHullWhiteOp(BaseModel):
resource_name: Optional[Literal["FdmHestonHullWhiteOp"]] = "FdmHestonHullWhiteOp"
mesher: FdmMesher
hestonProcess: HestonProcess
hwProcess: HullWhiteProcess
equityShortRateCorrelation: float
class FdmHestonOp(BaseModel):
resource_name: Optional[Literal["FdmHestonOp"]] = "FdmHestonOp"
mesher: FdmMesher
hestonProcess: HestonProcess
quantoHelper: Optional[FdmQuantoHelper] = None
leverageFct: Optional[LocalVolTermStructure] = None
class FdmHullWhiteOp(BaseModel):
resource_name: Optional[Literal["FdmHullWhiteOp"]] = "FdmHullWhiteOp"
mesher: FdmMesher
model: HullWhite
direction: int
class FdmLocalVolFwdOp(BaseModel):
resource_name: Optional[Literal["FdmLocalVolFwdOp"]] = "FdmLocalVolFwdOp"
mesher: FdmMesher
spot: Quote
rTS: YieldTermStructure
qTS: YieldTermStructure
localVol: LocalVolTermStructure
direction: Optional[int] = None
class FdmOrnsteinUhlenbeckOp(BaseModel):
resource_name: Optional[
Literal["FdmOrnsteinUhlenbeckOp"]
] = "FdmOrnsteinUhlenbeckOp"
mesher: FdmMesher
p: OrnsteinUhlenbeckProcess
rTS: YieldTermStructure
direction: Optional[int] = None
class FdmSabrOp(BaseModel):
resource_name: Optional[Literal["FdmSabrOp"]] = "FdmSabrOp"
mesher: FdmMesher
rTS: YieldTermStructure
f0: float
alpha: float
beta: float
nu: float
rho: float
class FdmZabrOp(BaseModel):
resource_name: Optional[Literal["FdmZabrOp"]] = "FdmZabrOp"
mesher: FdmMesher
beta: float
nu: float
rho: float
gamma: float
class FdmDupire1dOp(BaseModel):
resource_name: Optional[Literal["FdmDupire1dOp"]] = "FdmDupire1dOp"
mesher: FdmMesher
localVolatility: Array
class FdmBlackScholesFwdOp(BaseModel):
resource_name: Optional[Literal["FdmBlackScholesFwdOp"]] = "FdmBlackScholesFwdOp"
mesher: FdmMesher
process: GeneralizedBlackScholesProcess
strike: float
localVol: Optional[bool] = None
illegalLocalVolOverwrite: Optional[float] = None
direction: Optional[int] = None
class TripleBandLinearOpBase(BaseModel):
resource_name: Optional[Literal["TripleBandLinearOp"]] = "TripleBandLinearOp"
direction: int
mesher: FdmMesher
class FirstDerivativeOp(BaseModel):
resource_name: Optional[Literal["FirstDerivativeOp"]] = "FirstDerivativeOp"
direction: int
mesher: FdmMesher
class SecondDerivativeOp(BaseModel):
resource_name: Optional[Literal["SecondDerivativeOp"]] = "SecondDerivativeOp"
direction: int
mesher: FdmMesher
class NinePointLinearOpBase(BaseModel):
resource_name: Optional[Literal["NinePointLinearOp"]] = "NinePointLinearOp"
d0: int
d1: int
mesher: FdmMesher
class SecondOrderMixedDerivativeOp(BaseModel):
resource_name: Optional[
Literal["SecondOrderMixedDerivativeOp"]
] = "SecondOrderMixedDerivativeOp"
d0: int
d1: int
mesher: FdmMesher
class NthOrderDerivativeOp(BaseModel):
resource_name: Optional[Literal["NthOrderDerivativeOp"]] = "NthOrderDerivativeOp"
direction: int
order: int
nPoints: int
mesher: FdmMesher
class FdmLogInnerValue(BaseModel):
resource_name: Optional[Literal["FdmLogInnerValue"]] = "FdmLogInnerValue"
payoff: Payoff
mesher: FdmMesher
direction: int
class FdmLogBasketInnerValue(BaseModel):
resource_name: Optional[
Literal["FdmLogBasketInnerValue"]
] = "FdmLogBasketInnerValue"
payoff: BasketPayoff
mesher: FdmMesher
class FdmSnapshotCondition(BaseModel):
resource_name: Optional[Literal["FdmSnapshotCondition"]] = "FdmSnapshotCondition"
t: float
class FdmAmericanStepCondition(BaseModel):
resource_name: Optional[
Literal["FdmAmericanStepCondition"]
] = "FdmAmericanStepCondition"
mesher: FdmMesher
calculator: FdmInnerValueCalculator
class FdmArithmeticAverageCondition(BaseModel):
resource_name: Optional[
Literal["FdmArithmeticAverageCondition"]
] = "FdmArithmeticAverageCondition"
averageTimes: List[float]
real: float
pastFixings: int
mesher: FdmMesher
equityDirection: int
class FdmBermudanStepCondition(BaseModel):
resource_name: Optional[
Literal["FdmBermudanStepCondition"]
] = "FdmBermudanStepCondition"
exerciseDates: List[Date]
referenceDate: Date
dayCounter: DayCounter
mesher: FdmMesher
calculator: FdmInnerValueCalculator
class FdmSimpleStorageCondition(BaseModel):
resource_name: Optional[
Literal["FdmSimpleStorageCondition"]
] = "FdmSimpleStorageCondition"
exerciseTimes: List[float]
mesher: FdmMesher
calculator: FdmInnerValueCalculator
changeRate: float
class FdmSimpleSwingCondition(BaseModel):
resource_name: Optional[
Literal["FdmSimpleSwingCondition"]
] = "FdmSimpleSwingCondition"
exerciseTimes: List[float]
mesher: FdmMesher
calculator: FdmInnerValueCalculator
swingDirection: int
minExercises: Optional[int] = None
class FdmDividendHandler(BaseModel):
resource_name: Optional[Literal["FdmDividendHandler"]] = "FdmDividendHandler"
schedule: List[Dividend]
mesher: FdmMesher
referenceDate: Date
dayCounter: DayCounter
equityDirection: int
class BSMRNDCalculator(BaseModel):
resource_name: Optional[Literal["BSMRNDCalculator"]] = "BSMRNDCalculator"
process: GeneralizedBlackScholesProcess
class CEVRNDCalculator(BaseModel):
resource_name: Optional[Literal["CEVRNDCalculator"]] = "CEVRNDCalculator"
f0: float
alpha: float
beta: float
class GBSMRNDCalculator(BaseModel):
resource_name: Optional[Literal["GBSMRNDCalculator"]] = "GBSMRNDCalculator"
process: GeneralizedBlackScholesProcess
class HestonRNDCalculator(BaseModel):
resource_name: Optional[Literal["HestonRNDCalculator"]] = "HestonRNDCalculator"
hestonProcess: HestonProcess
integrationEps: Optional[float] = None
maxIntegrationIterations: Optional[int] = None
class LocalVolRNDCalculator(BaseModel):
resource_name: Optional[Literal["LocalVolRNDCalculator"]] = "LocalVolRNDCalculator"
spot: Quote
rTS: YieldTermStructure
qTS: YieldTermStructure
localVol: LocalVolTermStructure
xGrid: Optional[int] = None
tGrid: Optional[int] = None
x0Density: Optional[float] = None
localVolProbEps: Optional[float] = None
maxIter: Optional[int] = None
gaussianStepSize: Optional[float] = None
class SquareRootProcessRNDCalculator(BaseModel):
resource_name: Optional[
Literal["SquareRootProcessRNDCalculator"]
] = "SquareRootProcessRNDCalculator"
v0: float
kappa: float
theta: float
sigma: float
class ExponentialSplinesFitting(BaseModel):
resource_name: Optional[
Literal["ExponentialSplinesFitting"]
] = "ExponentialSplinesFitting"
constrainAtZero: Optional[bool] = None
weights: Optional[Array] = None
class NelsonSiegelFitting(BaseModel):
resource_name: Optional[Literal["NelsonSiegelFitting"]] = "NelsonSiegelFitting"
weights: Optional[Array] = None
class SvenssonFitting(BaseModel):
resource_name: Optional[Literal["SvenssonFitting"]] = "SvenssonFitting"
weights: Optional[Array] = None
class CubicBSplinesFitting(BaseModel):
resource_name: Optional[Literal["CubicBSplinesFitting"]] = "CubicBSplinesFitting"
knotVector: List[float]
constrainAtZero: Optional[bool] = None
weights: Optional[Array] = None
class SimplePolynomialFitting(BaseModel):
resource_name: Optional[
Literal["SimplePolynomialFitting"]
] = "SimplePolynomialFitting"
degree: float
constrainAtZero: Optional[bool] = None
weights: Optional[Array] = None
class Position(BaseModel):
resource_name: Optional[Literal["Position"]] = "Position"
class Gsr(BaseModel):
resource_name: Optional[Literal["Gsr"]] = "Gsr"
termStructure: YieldTermStructureHandle
volstepdates: List[Date]
volatilities: List[QuoteHandle]
reversions: List[QuoteHandle]
T: Optional[float] = None
class MarkovFunctionalModelSettings0(BaseModel):
resource_name: Optional[
Literal["MarkovFunctionalModelSettings"]
] = "MarkovFunctionalModelSettings"
yGridPoints: Optional[int] | |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate Leakage': 0.00662954,
'Peak Dynamic': 0.0,
'Runtime Dynamic': 0.0,
'Subthreshold Leakage': 0.0691322,
'Subthreshold Leakage with power gating': 0.0259246},
'Core': [{'Area': 32.6082,
'Execution Unit/Area': 8.2042,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 5.66814e-06,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.202693,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 2.02403e-05,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.122718,
'Execution Unit/Instruction Scheduler/Area': 2.17927,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.328073,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.00115349,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.20978,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.369616,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.017004,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00962066,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00730101,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 1.00996,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00529112,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 2.07911,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.64004,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0800117,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0455351,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 4.84781,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.841232,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.000856399,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.55892,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.367081,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.0178624,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00897339,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 1.37674,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.114878,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.0641291,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.365347,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 5.59398,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 3.82383e-06,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.0133989,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0968933,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0990927,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.0968971,
'Execution Unit/Register Files/Runtime Dynamic': 0.112492,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0442632,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00607074,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.234135,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.601487,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.0920413,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0345155,
'Execution Unit/Runtime Dynamic': 2.69879,
'Execution Unit/Subthreshold Leakage': 1.83518,
'Execution Unit/Subthreshold Leakage with power gating': 0.709678,
'Gate Leakage': 0.372997,
'Instruction Fetch Unit/Area': 5.86007,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.00417854,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.00417854,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.00365895,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.00142708,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.00142347,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.0134395,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.0393685,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0590479,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0952604,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 6.05938,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.360214,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.323547,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 8.57647,
'Instruction Fetch Unit/Runtime Dynamic': 0.831829,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932587,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.408542,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0734183,
'L2/Runtime Dynamic': 0.0164294,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80969,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 4.12483,
'Load Store Unit/Data Cache/Runtime Dynamic': 1.41181,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0351387,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.0934243,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.0934243,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 4.5678,
'Load Store Unit/Runtime Dynamic': 1.96598,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.230368,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.460737,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591622,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283406,
'Memory Management Unit/Area': 0.434579,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.0817585,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.082562,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00813591,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.37675,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.0599378,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.676593,
'Memory Management Unit/Runtime Dynamic': 0.1425,
'Memory Management Unit/Subthreshold Leakage': 0.0769113,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0399462,
'Peak Dynamic': 24.0499,
'Renaming Unit/Area': 0.369768,
'Renaming Unit/FP Front End RAT/Area': 0.168486,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00489731,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 3.33511,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 1.38203e-05,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0437281,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.024925,
'Renaming Unit/Free List/Area': 0.0414755,
'Renaming Unit/Free List/Gate Leakage': 4.15911e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0401324,
'Renaming Unit/Free List/Runtime Dynamic': 0.0189003,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000670426,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000377987,
'Renaming Unit/Gate Leakage': 0.00863632,
'Renaming Unit/Int Front End RAT/Area': 0.114751,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.00038343,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.86945,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.191359,
'Renaming Unit/Int Front End RAT/Subthreshold | |
die niet bestaat kijken we of er iets in /etc/hostname staat (computernaam)
# maar dat is niet te testen zonder /etc/hosts aan te passen
assert rhfn.get_tldname() == 'lemoncurry.nl'
def add_to_hostsfile(self): # not really testable (yet)
pass
def add_to_server(self): # not really testable (yet)
pass
def test_init_css(self, monkeypatch, capsys):
def mock_read_settings_empty(*args):
return {'css': [] }
def mock_read_settings_basic_plus(*args):
return {'css': ['html4css1.css', 'reset.css', '960.css', 'myowncss.css',
'http://www.example.com/static/css.css'] }
def mock_copyfile(*args):
print('copying `{}` to `{}`'.format(*args))
def mock_update_settings(*args):
print('update_settings called with args `{}` `{}`'.format(*args))
monkeypatch.setattr(rhfn.dml, 'read_settings', mock_read_settings_empty)
monkeypatch.setattr(rhfn.shutil, 'copyfile', mock_copyfile)
monkeypatch.setattr(rhfn.dml, 'update_settings', mock_update_settings)
# als deze nog niet bestaat wordt er een directory css aangemaakt onder `sitename`
# alle files in BASIC_CSS die nog niet in conf['css'] zitten worden daarin opgevoerd
# en ook aan conf['css'] toegevoegd dat daarna aangepast wordt
sitename = 'testsite'
here = rhfn.HERE / 'static'
there = rhfn.WEBROOT / sitename / 'css'
there_present = there.parent.exists()
copy_lines = ['copying `{0}/{2}` to `{1}/{2}`\n'.format(here, there, x) for x in
rhfn.BASIC_CSS]
update_lines = ["'url + css/{}'".format(x) for x in rhfn.BASIC_CSS]
if not there_present: # make sure cssdir.mkdir doesn't fail
there.parent.mkdir(parents=True, exist_ok=True)
rhfn.init_css(sitename)
assert capsys.readouterr().out == (''.join(copy_lines) + "update_settings called with"
" args `testsite` `{{'css': [{}, {}, {}]}}`"
"\n".format(*update_lines))
if not there_present: # teardown if necessary
there.parent.rmdir()
monkeypatch.setattr(rhfn.dml, 'read_settings', mock_read_settings_basic_plus)
rhfn.init_css(sitename)
assert capsys.readouterr().out == ''
def test_list_confs(self, monkeypatch):
def mock_list_sites_none():
return []
def mock_list_sites_one():
return ['one']
def mock_list_sites_more():
return ['first', 'next', 'last']
monkeypatch.setattr(rhfn.dml, 'list_sites', mock_list_sites_none)
assert rhfn.list_confs() == ''
monkeypatch.setattr(rhfn.dml, 'list_sites', mock_list_sites_one)
assert rhfn.list_confs() == '<option>one</option>'
assert rhfn.list_confs('two') == '<option>one</option>'
monkeypatch.setattr(rhfn.dml, 'list_sites', mock_list_sites_more)
assert rhfn.list_confs() == ('<option>first</option><option>next</option>'
'<option>last</option>')
assert rhfn.list_confs('last') == ('<option>first</option><option>next</option>'
'<option selected="selected">last</option>')
def test_read_conf(self, monkeypatch):
mocked_settings = {'x': 'y'}
def mock_read_settings_notfound(*args):
raise FileNotFoundError
def mock_read_settings_found(*args):
return mocked_settings
monkeypatch.setattr(rhfn.dml, 'read_settings', mock_read_settings_notfound)
assert rhfn.read_conf('testsite') == ('no_such_sett', None)
monkeypatch.setattr(rhfn.dml, 'read_settings', mock_read_settings_found)
assert rhfn.read_conf('testsite') == ('', mocked_settings)
def test_conf2text(self, monkeypatch):
def mock_save_config_data(confdict, **kwargs):
return confdict
monkeypatch.setattr(rhfn, 'save_config_data', mock_save_config_data)
conf_in = {'test': 'tested', 'url': 'gargl', 'css': ['gargl/snork.css', 'test.css']}
conf_out = {'test': 'tested', 'url': 'gargl', 'css': ['url + snork.css', 'test.css']}
assert rhfn.conf2text(conf_in) == conf_out
def check_url(self, monkeypatch):
def mock_urlopen_fout(*args):
raise rhfn.urllib.error.HTTPError
def test_text2conf(self, monkeypatch):
def mock_get_text(*args):
return args[0] + ': {}'
def mock_load_config_data_error(*args):
raise rhfn.ParserError
def mock_load_config_data_empty(*args):
return {}
def mock_load_config_data_basic(*args):
return rhfn.DFLT_CONF
def mock_load_config_data_hig_fout(*args):
conf = {x: y for x, y in rhfn.DFLT_CONF.items()}
conf['hig'] = 'hallo'
return conf
def mock_load_config_data_lang_fout(*args):
conf = {x: y for x, y in rhfn.DFLT_CONF.items()}
conf['lang'] = 'du'
return conf
def mock_load_config_url_not_http(*args):
conf = {x: y for x, y in rhfn.DFLT_CONF.items()}
conf['url'] = 'x'
print(conf)
return conf
def mock_load_config_url_other(*args):
conf = {x: y for x, y in rhfn.DFLT_CONF.items()}
conf['url'] = 'http://x/'
return conf
def mock_check_url(*args):
# raise rhfn.urllib.error.HTTPError
raise rhfn.urllib.error.URLError('x')
def mock_load_config_css_simple(*args):
conf = {x: y for x, y in rhfn.DFLT_CONF.items()}
conf['css'] = 'a_string'
return conf
def mock_load_config_css_double(*args):
conf = {x: y for x, y in rhfn.DFLT_CONF.items()}
conf['url'] = 'http://x'
conf['css'] = ['url + a_string', 'http://stuff']
return conf
def mock_check_url_ok(*args):
pass
monkeypatch.setattr(rhfn, 'get_text', mock_get_text)
monkeypatch.setattr(rhfn, 'load_config_data', mock_load_config_data_error)
assert rhfn.text2conf('') == ('sett_no_good: {}', {})
monkeypatch.setattr(rhfn, 'load_config_data', mock_load_config_data_empty)
assert rhfn.text2conf('') == ('sett_invalid: wid', {})
monkeypatch.setattr(rhfn, 'load_config_data', mock_load_config_data_basic)
assert rhfn.text2conf('') == ('', rhfn.DFLT_CONF)
monkeypatch.setattr(rhfn, 'load_config_data', mock_load_config_data_hig_fout)
assert rhfn.text2conf('') == ('sett_invalid: hig', {})
monkeypatch.setattr(rhfn, 'load_config_data', mock_load_config_data_lang_fout)
assert rhfn.text2conf('') == ('sett_invalid: lang', {})
monkeypatch.setattr(rhfn, 'load_config_data', mock_load_config_url_not_http)
assert rhfn.text2conf('') == ('sett_invalid: url', {})
monkeypatch.setattr(rhfn, 'load_config_data', mock_load_config_url_other)
monkeypatch.setattr(rhfn, 'check_url', mock_check_url)
assert rhfn.text2conf('') == ('sett_invalid: url', {})
monkeypatch.setattr(rhfn, 'load_config_data', mock_load_config_css_simple)
expected = {x: y for x, y in rhfn.DFLT_CONF.items()}
expected.update({'css': ['https://a_string']})
assert rhfn.text2conf('') == ('', expected)
monkeypatch.setattr(rhfn, 'load_config_data', mock_load_config_css_double)
monkeypatch.setattr(rhfn, 'check_url', mock_check_url_ok)
expected = {x: y for x, y in rhfn.DFLT_CONF.items()}
expected.update({'url': 'http://x','css': ['http://x/a_string', 'http://stuff']})
assert rhfn.text2conf('') == ('', expected)
def test_check_url(self, monkeypatch):
def mock_urlopen_ok(*args):
pass
def mock_urlopen(*args):
raise rhfn.urllib.error.URLError('x')
monkeypatch.setattr(rhfn.urllib.request, 'urlopen', mock_urlopen_ok)
assert rhfn.check_url('') == None
monkeypatch.setattr(rhfn.urllib.request, 'urlopen', mock_urlopen)
with pytest.raises(rhfn.urllib.error.URLError):
rhfn.check_url('http://test/testerdetest')
def test_save_conf(self, monkeypatch, capsys):
def mock_read_settings_error(*args):
raise FileNotFoundError
def mock_read_settings(*args):
return {}
def mock_get_text(*args):
return 'no_such_sett for `{}`'
def mock_text2conf_error(*args):
return True, {}
def mock_text2conf(*args):
return False, {'url': False}
def mock_update_settings(*args):
print('called update_settings for `{}` `{}`'.format(*args))
monkeypatch.setattr(rhfn.dml, 'read_settings', mock_read_settings_error)
monkeypatch.setattr(rhfn, 'get_text', mock_get_text)
assert rhfn.save_conf('testsite', '') == 'no_such_sett for `testsite`'
monkeypatch.setattr(rhfn.dml, 'read_settings', mock_read_settings)
monkeypatch.setattr(rhfn, 'text2conf', mock_text2conf_error)
assert rhfn.save_conf('testsite', '')
monkeypatch.setattr(rhfn, 'text2conf', mock_text2conf)
monkeypatch.setattr(rhfn.dml, 'update_settings', mock_update_settings)
assert not rhfn.save_conf('testsite', '')
assert capsys.readouterr().out == "called update_settings for `testsite` `{'url': False}`\n"
class TestSiteRelated:
def test_list_subdirs(self, monkeypatch, capsys):
def mock_list_dirs(*args):
print('ext arg is', args[1])
return ['my_hovercraft', 'cheese_shop']
def mock_list_dirs_empty(*args):
print('ext arg is', args[1])
return []
def mock_list_dirs_error(*args):
print('ext arg is', args[1])
raise FileNotFoundError
sitename = 'testsite'
monkeypatch.setattr(rhfn.dml, 'list_dirs', mock_list_dirs)
assert rhfn.list_subdirs(sitename) == ['cheese_shop/', 'my_hovercraft/']
assert capsys.readouterr().out == 'ext arg is src\n'
monkeypatch.setattr(rhfn.dml, 'list_dirs', mock_list_dirs_empty)
assert rhfn.list_subdirs(sitename, 'dest') == []
assert capsys.readouterr().out == 'ext arg is dest\n'
monkeypatch.setattr(rhfn.dml, 'list_dirs', mock_list_dirs)
assert rhfn.list_subdirs(sitename, 'xxxx') == ['cheese_shop/', 'my_hovercraft/']
assert capsys.readouterr().out == 'ext arg is dest\n'
monkeypatch.setattr(rhfn.dml, 'list_dirs', mock_list_dirs_error)
assert rhfn.list_subdirs(sitename, 'src') == []
assert capsys.readouterr().out == 'ext arg is src\n'
def test_list_files(self, monkeypatch):
def mock_list_docs(*args, **kwargs):
return ['luxury-yacht', 'throatwobbler-mangrove']
def mock_list_docs_empty(*args, **kwargs):
return []
def mock_list_docs_not_found(*args, **kwargs):
raise FileNotFoundError
def mock_list_docs_wrong_type(*args, **kwargs):
return
def mock_list_subdirs(*args):
return ['my_hovercraft/', 'cheese_shop/']
def mock_list_subdirs_empty(*args):
return []
def mock_list_templates(*args):
return ['letter.tpl', 'number.tpl']
def mock_list_templates_empty(*args):
return []
sitename = 'testsite'
monkeypatch.setattr(rhfn.dml, 'list_docs', mock_list_docs_not_found)
assert rhfn.list_files(sitename) == 'Site not found'
monkeypatch.setattr(rhfn.dml, 'list_docs', mock_list_docs_wrong_type)
assert rhfn.list_files(sitename, ext='xxx') == 'Wrong type: `xxx`'
monkeypatch.setattr(rhfn.dml, 'list_docs', mock_list_docs)
assert rhfn.list_files(sitename, deleted=True) == ['luxury-yacht', 'throatwobbler-mangrove']
monkeypatch.setattr(rhfn.dml, 'list_templates', mock_list_templates_empty)
assert rhfn.list_files(sitename) == ('<option>luxury-yacht.rst</option>'
'<option>throatwobbler-mangrove.rst</option>')
monkeypatch.setattr(rhfn, 'list_subdirs', mock_list_subdirs_empty)
assert rhfn.list_files(sitename, current='enormous') == (
'<option>..</option>'
'<option>luxury-yacht.rst</option>'
'<option>throatwobbler-mangrove.rst</option>')
monkeypatch.setattr(rhfn.dml, 'list_templates', mock_list_templates)
assert rhfn.list_files(sitename, naam='luxury-yacht.rst') == (
'<option>-- letter.tpl --</option>'
'<option>-- number.tpl --</option>'
'<option selected="selected">luxury-yacht.rst</option>'
'<option>throatwobbler-mangrove.rst</option>')
monkeypatch.setattr(rhfn, 'list_subdirs', mock_list_subdirs)
assert rhfn.list_files(sitename, ext='dest') == (
'<option>my_hovercraft/</option>'
'<option>cheese_shop/</option>'
'<option>luxury-yacht.html</option>'
'<option>throatwobbler-mangrove.html</option>')
def test_make_new_dir(self, monkeypatch, capsys):
def mock_create_new_dir(*args):
print('create_new_dir called')
def mock_create_new_dir_failed(*args):
raise FileExistsError
sitename, filename = 'testsite', 'testname'
monkeypatch.setattr(rhfn.dml, 'create_new_dir', mock_create_new_dir)
assert rhfn.make_new_dir(sitename, filename) == ''
assert capsys.readouterr().out == 'create_new_dir called\n'
monkeypatch.setattr(rhfn.dml, 'create_new_dir', mock_create_new_dir_failed)
assert rhfn.make_new_dir(sitename, filename) == 'dir_name_taken'
class TestSourceRelated:
sitename, filename = 'testsite', 'testname'
def test_read_src_data(self, monkeypatch, capsys):
def mock_get_doc_contents(*args, **kwargs):
print('got args `{}`, `{}`, `{}`, `{}`'.format(*args))
def mock_get_doc_contents_error_1(*args, **kwargs):
raise AttributeError
def mock_get_doc_contents_error_2(*args, **kwargs):
raise FileNotFoundError
assert rhfn.read_src_data(self.sitename, '', self.filename + '.x') == (
'rst_filename_error', '')
monkeypatch.setattr(rhfn.dml, 'get_doc_contents', mock_get_doc_contents)
rhfn.read_src_data(self.sitename, '', self.filename + '.rst')
assert capsys.readouterr().out == 'got args `testsite`, `testname`, `src`, ``\n'
monkeypatch.setattr(rhfn.dml, 'get_doc_contents', mock_get_doc_contents_error_1)
assert rhfn.read_src_data(self.sitename, '', self.filename) == ('src_name_missing', '')
monkeypatch.setattr(rhfn.dml, 'get_doc_contents', mock_get_doc_contents_error_2)
assert rhfn.read_src_data(self.sitename, '', self.filename) == ('src_file_missing', '')
def test_check_if_rst(self, monkeypatch):
assert rhfn.check_if_rst('', '') == 'supply_text'
assert rhfn.check_if_rst('...', '') == 'rst_invalid'
assert rhfn.check_if_rst('...', rhfn.RST) == ''
assert rhfn.check_if_rst('...', rhfn.RST, 'x') == ''
assert rhfn.check_if_rst('...', rhfn.RST, '') == 'src_name_missing'
assert rhfn.check_if_rst('...', rhfn.RST, 'x/') == 'src_name_missing'
assert rhfn.check_if_rst('...', rhfn.RST, '-- new --') == 'src_name_missing'
assert rhfn.check_if_rst('...', rhfn.RST, '..') == 'src_name_missing'
def test_save_src_data(self, monkeypatch, capsys):
def mock_list_subdirs(*args):
return ['hello/']
def mock_create_new_dir(*args):
print('args for creating dir: `{}` `{}`'.format(*args))
def mock_create_new_dir_exists(*args):
raise FileExistsError
def mock_create_new_doc(*args, **kwargs):
print('args for creating doc: `{}` `{}`'.format(args[0], args[1], kwargs['directory']))
def mock_create_new_doc_exists(*args, **kwargs):
raise FileExistsError
def mock_update_rst(*args, **kwargs):
print('args for update_rst: `{}` `{}` `{}` `{}`'.format(args[0], args[1], args[2],
kwargs['directory']))
def mock_update_rst_error_1(*args, **kwargs):
raise AttributeError('name')
def mock_update_rst_error_2(*args, **kwargs):
raise AttributeError('contents')
def mock_update_rst_error_3(*args, **kwargs):
raise AttributeError('something else')
def mock_update_rst_error_4(*args, **kwargs):
raise FileNotFoundError
assert rhfn.save_src_data(self.sitename, '', self.filename + '.x', '...') == (
'rst_filename_error')
monkeypatch.setattr(rhfn.dml, 'create_new_dir', mock_create_new_dir)
monkeypatch.setattr(rhfn.dml, 'create_new_doc', mock_create_new_doc_exists)
monkeypatch.setattr(rhfn.dml, 'update_rst', mock_update_rst)
assert rhfn.save_src_data(self.sitename, 'test', self.filename + '.rst', '...', True) == (
'src_name_taken')
assert capsys.readouterr().out == 'args for creating dir: `testsite` `test`\n'
monkeypatch.setattr(rhfn.dml, 'create_new_doc', mock_create_new_doc)
assert rhfn.save_src_data(self.sitename, 'test', self.filename + '.rst', '...') == ''
assert capsys.readouterr().out == ('args for creating dir: `testsite` `test`\n'
'args for update_rst: `testsite` `testname` `...` '
'`test`\n')
monkeypatch.setattr(rhfn.dml, 'create_new_dir', mock_create_new_dir_exists)
assert rhfn.save_src_data(self.sitename, 'test', self.filename + '.rst', '...', True) == ''
assert capsys.readouterr().out == ('args for creating doc: `testsite` `testname.rst`\n'
'args for update_rst: `testsite` `testname` `...` '
'`test`\n')
monkeypatch.setattr(rhfn.dml, 'update_rst', mock_update_rst_error_1)
assert rhfn.save_src_data(self.sitename, 'hello', self.filename + '.rst', '...') == (
'src_name_missing')
monkeypatch.setattr(rhfn.dml, 'update_rst', mock_update_rst_error_2)
assert rhfn.save_src_data(self.sitename, 'hello', self.filename + '.rst', '...') == (
'supply_text')
monkeypatch.setattr(rhfn.dml, 'update_rst', mock_update_rst_error_3)
assert rhfn.save_src_data(self.sitename, 'hello', self.filename + '.rst', '...') == (
'something else')
monkeypatch.setattr(rhfn.dml, 'update_rst', mock_update_rst_error_4)
assert rhfn.save_src_data(self.sitename, 'hello', self.filename + '.rst', '...') == (
'src_file_missing')
def test_revert_src(self, monkeypatch, capsys):
def | |
#
# This file is part of LiteX.
#
# Copyright (c) 2019-2020 <NAME> <<EMAIL>>
# Copyright (c) 2020 <NAME> <<EMAIL>>
# Copyright (c) 2020 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
import os
from migen import *
from migen.fhdl.specials import Tristate
from migen.genlib.resetsync import AsyncResetSynchronizer
from litex.soc.interconnect import wishbone
from litex.soc.interconnect import axi
from litex.soc.cores.cpu import CPU
# Zynq 7000 ----------------------------------------------------------------------------------------
class Zynq7000(CPU):
variants = ["standard"]
family = "arm"
name = "zynq7000"
human_name = "Zynq7000"
data_width = 32
endianness = "little"
reset_address = 0x00000000
gcc_triple = "arm-xilinx-eabi"
linker_output_format = "elf32-littlearm"
nop = "nop"
io_regions = {0x00000000: 0x100000000} # Origin, Length.
# Memory Mapping.
@property
def mem_map(self):
return {"csr": 0x00000000}
def __init__(self, platform, variant):
platform.ps7_cfg = {}
self.platform = platform
self.reset = Signal()
self.periph_buses = [] # Peripheral buses (Connected to main SoC's bus).
self.memory_buses = [] # Memory buses (Connected directly to LiteDRAM).
self.axi_gp_masters = [] # General Purpose AXI Masters.
self.axi_gp_slaves = [] # General Purpose AXI Slaves.
self.axi_hp_slaves = [] # High Performance AXI Slaves.
# # #
# PS7 Clocking.
self.clock_domains.cd_ps7 = ClockDomain()
# PS7 (Minimal) ----------------------------------------------------------------------------
self.ps7_name = None
self.ps7_tcl = []
ps7_rst_n = Signal()
ps7_ddram_pads = platform.request("ps7_ddram")
self.cpu_params = dict(
# Clk / Rst.
io_PS_CLK = platform.request("ps7_clk"),
io_PS_PORB = platform.request("ps7_porb"),
io_PS_SRSTB = platform.request("ps7_srstb"),
# MIO.
io_MIO = platform.request("ps7_mio"),
# DDRAM.
io_DDR_Addr = ps7_ddram_pads.addr,
io_DDR_BankAddr = ps7_ddram_pads.ba,
io_DDR_CAS_n = ps7_ddram_pads.cas_n,
io_DDR_Clk_n = ps7_ddram_pads.ck_n,
io_DDR_Clk = ps7_ddram_pads.ck_p,
io_DDR_CKE = ps7_ddram_pads.cke,
io_DDR_CS_n = ps7_ddram_pads.cs_n,
io_DDR_DM = ps7_ddram_pads.dm,
io_DDR_DQ = ps7_ddram_pads.dq,
io_DDR_DQS_n = ps7_ddram_pads.dqs_n,
io_DDR_DQS = ps7_ddram_pads.dqs_p,
io_DDR_ODT = ps7_ddram_pads.odt,
io_DDR_RAS_n = ps7_ddram_pads.ras_n,
io_DDR_DRSTB = ps7_ddram_pads.reset_n,
io_DDR_WEB = ps7_ddram_pads.we_n,
io_DDR_VRN = ps7_ddram_pads.vrn,
io_DDR_VRP = ps7_ddram_pads.vrp,
# USB0.
i_USB0_VBUS_PWRFAULT = 0,
# Fabric Clk / Rst.
o_FCLK_CLK0 = ClockSignal("ps7"),
o_FCLK_RESET0_N = ps7_rst_n
)
self.specials += AsyncResetSynchronizer(self.cd_ps7, ~ps7_rst_n)
# Enet0 mdio -------------------------------------------------------------------------------
ps7_enet0_mdio_pads = platform.request("ps7_enet0_mdio", loose=True)
if ps7_enet0_mdio_pads is not None:
self.cpu_params.update(
o_ENET0_MDIO_MDC = ps7_enet0_mdio_pads.mdc,
i_ENET0_MDIO_I = ps7_enet0_mdio_pads.i,
o_ENET0_MDIO_O = ps7_enet0_mdio_pads.o,
o_ENET0_MDIO_T = ps7_enet0_mdio_pads.t
)
# Enet0 ------------------------------------------------------------------------------------
ps7_enet0_pads = platform.request("ps7_enet0", loose=True)
if ps7_enet0_pads is not None:
self.cpu_params.update(
o_ENET0_GMII_TX_EN = ps7_enet0_pads.tx_en,
o_ENET0_GMII_TX_ER = ps7_enet0_pads.tx_er,
o_ENET0_GMII_TXD = ps7_enet0_pads.txd,
i_ENET0_GMII_COL = ps7_enet0_pads.col,
i_ENET0_GMII_CRS = ps7_enet0_pads.crs,
i_ENET0_GMII_RX_CLK = ps7_enet0_pads.rx_clk,
i_ENET0_GMII_RX_DV = ps7_enet0_pads.rx_dv,
i_ENET0_GMII_RX_ER = ps7_enet0_pads.rx_er,
i_ENET0_GMII_TX_CLK = ps7_enet0_pads.tx_clk,
i_ENET0_GMII_RXD = ps7_enet0_pads.rxd
)
# SDIO0 ------------------------------------------------------------------------------------
ps7_sdio0_pads = platform.request("ps7_sdio0", loose=True)
if ps7_sdio0_pads is not None:
self.cpu_params.update(
o_SDIO0_CLK = ps7_sdio0_pads.clk,
i_SDIO0_CLK_FB = ps7_sdio0_pads.clk_fb,
o_SDIO0_CMD_O = ps7_sdio0_pads.cmd_o,
i_SDIO0_CMD_I = ps7_sdio0_pads.cmd_i,
o_SDIO0_CMD_T = ps7_sdio0_pads.cmd_t,
o_SDIO0_DATA_O = ps7_sdio0_pads.data_o,
i_SDIO0_DATA_I = ps7_sdio0_pads.data_i,
o_SDIO0_DATA_T = ps7_sdio0_pads.data_t,
o_SDIO0_LED = ps7_sdio0_pads.led,
o_SDIO0_BUSPOW = ps7_sdio0_pads.buspow,
o_SDIO0_BUSVOLT = ps7_sdio0_pads.busvolt,
)
# SDIO0_CD ---------------------------------------------------------------------------------
ps7_sdio0_cd_pads = platform.request("ps7_sdio0_cd", loose=True)
if ps7_sdio0_cd_pads is not None:
self.cpu_params.update(i_SDIO0_CDN = ps7_sdio0_cd_pads.cdn)
# SDIO0_WP ---------------------------------------------------------------------------------
ps7_sdio0_wp_pads = platform.request("ps7_sdio0_wp", loose=True)
if ps7_sdio0_wp_pads is not None:
self.cpu_params.update(i_SDIO0_WP = ps7_sdio0_wp_pads.wp)
# TODO compare this possibly redundant homebrew zynq config thingy against upstream litex functionality
def gen_ps7_ip(self, preset='ZedBoard'):
'''
To customize Zynq PS configuration, add key value pairs to
self.platform.ps7_cfg. Use vivado gui to find valid settings:
* open project: `build/gateware/*.xpr`
* open `ps7_cfg` in the project manager
* customize Peripheral I/O Pins / Fabric clocks / etc, OK
* Generate Output Products: Skip
* File, Project, Open Journal File
* Copy the lines starting with `set_proerty`, strip the `CONFIG.`
from the key and add them to ps7_cfg dict
TODO better integration with the litex build process
'''
print('gen_ps7_ip()', self.platform.ps7_cfg)
cmds = self.platform.toolchain.pre_synthesis_commands
preset = '{{' + preset + '}}'
cmds += [
'create_ip -name processing_system7 -vendor xilinx.com -library ip -version 5.5 -module_name ps7_cfg',
f'set_property -dict [list CONFIG.preset {preset}] [get_ips ps7_cfg]',
]
for k, v in self.platform.ps7_cfg.items():
v = '{{' + v + '}}'
cmds.append(f'set_property CONFIG.{k} {v} [get_ips ps7_cfg]')
cmds += [
'upgrade_ip [get_ips ps7_cfg]',
'generate_target all [get_ips ps7_cfg]',
'set_msg_config -id {{Vivado 12-5447}} -new_severity {{Info}}',
'synth_ip [get_ips ps7_cfg]'
]
def set_ps7_xci(self, xci):
# Add .xci as Vivado IP and set ps7_name from .xci filename.
self.ps7_xci = xci
self.ps7_name = os.path.splitext(os.path.basename(xci))[0]
self.platform.add_ip(xci)
def add_ps7_config(self, config):
# Check that PS7 has been set.
if self.ps7_name is None:
raise Exception("Please set PS7 with set_ps7 method first.")
# Config must be provided as a config, value dict.
assert isinstance(config, dict)
# Add configs to PS7.
self.ps7_tcl.append("set_property -dict [list \\")
for config, value in config.items():
self.ps7_tcl.append("CONFIG.{} {} \\".format(config, '{{' + value + '}}'))
self.ps7_tcl.append(f"] [get_ips {self.ps7_name}]")
def set_ps7(self, name=None, xci=None, preset=None, config=None):
# Check that PS7 has not already been set.
if self.ps7_name is not None:
raise Exception(f"PS7 has already been set to {self.ps7_name}.")
self.ps7_name = preset if name is None else name
# User should provide an .xci file, preset_name or config dict but not all at once.
if (xci is not None) and (preset is not None):
raise Exception("PS7 .xci and preset specified, please only provide one.")
# User provides an .xci file...
if xci is not None:
self.set_ps7_xci(xci)
# User provides a preset or/and config
else:
self.ps7_tcl.append(f"set ps7 [create_ip -vendor xilinx.com -name processing_system7 -module_name {self.ps7_name}]")
if preset is not None:
assert isinstance(preset, str)
self.ps7_tcl.append("set_property -dict [list CONFIG.preset {}] [get_ips {}]".format("{{" + preset + "}}", self.ps7_name))
if config is not None:
self.add_ps7_config(config)
# AXI General Purpose Master -------------------------------------------------------------------
def add_axi_gp_master(self):
assert len(self.axi_gp_masters) < 2
n = len(self.axi_gp_masters)
axi_gpn = axi.AXIInterface(data_width=32, address_width=32, id_width=12)
self.axi_gp_masters.append(axi_gpn)
self.cpu_params.update({
# AXI GP clk.
f"i_M_AXI_GP{n}_ACLK" : ClockSignal("ps7"),
# AXI GP aw.
f"o_M_AXI_GP{n}_AWVALID" : axi_gpn.aw.valid,
f"i_M_AXI_GP{n}_AWREADY" : axi_gpn.aw.ready,
f"o_M_AXI_GP{n}_AWADDR" : axi_gpn.aw.addr,
f"o_M_AXI_GP{n}_AWBURST" : axi_gpn.aw.burst,
f"o_M_AXI_GP{n}_AWLEN" : axi_gpn.aw.len[:4],
f"o_M_AXI_GP{n}_AWSIZE" : axi_gpn.aw.size[:3],
f"o_M_AXI_GP{n}_AWID" : axi_gpn.aw.id,
f"o_M_AXI_GP{n}_AWLOCK" : axi_gpn.aw.lock,
f"o_M_AXI_GP{n}_AWPROT" : axi_gpn.aw.prot,
f"o_M_AXI_GP{n}_AWCACHE" : axi_gpn.aw.cache,
f"o_M_AXI_GP{n}_AWQOS" : axi_gpn.aw.qos,
# AXI GP w.
f"o_M_AXI_GP{n}_WVALID" : axi_gpn.w.valid,
f"o_M_AXI_GP{n}_WLAST" : axi_gpn.w.last,
f"i_M_AXI_GP{n}_WREADY" : axi_gpn.w.ready,
f"o_M_AXI_GP{n}_WID" : axi_gpn.w.id,
f"o_M_AXI_GP{n}_WDATA" : axi_gpn.w.data,
f"o_M_AXI_GP{n}_WSTRB" : axi_gpn.w.strb,
# AXI GP b.
f"i_M_AXI_GP{n}_BVALID" : axi_gpn.b.valid,
f"o_M_AXI_GP{n}_BREADY" : axi_gpn.b.ready,
f"i_M_AXI_GP{n}_BID" : axi_gpn.b.id,
f"i_M_AXI_GP{n}_BRESP" : axi_gpn.b.resp,
# AXI GP ar.
f"o_M_AXI_GP{n}_ARVALID" : axi_gpn.ar.valid,
f"i_M_AXI_GP{n}_ARREADY" : axi_gpn.ar.ready,
f"o_M_AXI_GP{n}_ARADDR" : axi_gpn.ar.addr,
f"o_M_AXI_GP{n}_ARBURST" : axi_gpn.ar.burst,
f"o_M_AXI_GP{n}_ARLEN" : axi_gpn.ar.len[:4],
f"o_M_AXI_GP{n}_ARID" : axi_gpn.ar.id,
f"o_M_AXI_GP{n}_ARLOCK" : axi_gpn.ar.lock,
f"o_M_AXI_GP{n}_ARSIZE" : axi_gpn.ar.size[:3],
f"o_M_AXI_GP{n}_ARPROT" : axi_gpn.ar.prot,
f"o_M_AXI_GP{n}_ARCACHE" : axi_gpn.ar.cache,
f"o_M_AXI_GP{n}_ARQOS" : axi_gpn.ar.qos,
# AXI GP r.
f"i_M_AXI_GP{n}_RVALID" : axi_gpn.r.valid,
f"o_M_AXI_GP{n}_RREADY" : axi_gpn.r.ready,
f"i_M_AXI_GP{n}_RLAST" : axi_gpn.r.last,
f"i_M_AXI_GP{n}_RID" : axi_gpn.r.id,
f"i_M_AXI_GP{n}_RRESP" : axi_gpn.r.resp,
f"i_M_AXI_GP{n}_RDATA" : axi_gpn.r.data,
})
return axi_gpn
# AXI General Purpose Slave --------------------------------------------------------------------
def add_axi_gp_slave(self):
raise NotImplementedError
# AXI High Performance Slave -------------------------------------------------------------------
def add_axi_hp_slave(self):
assert len(self.axi_hp_slaves) < 4
n = len(self.axi_hp_slaves)
axi_hpn = axi.AXIInterface(data_width=64, address_width=32, id_width=6)
self.axi_hp_slaves.append(axi_hpn)
self.cpu_params.update({
# AXI HP0 clk.
f"i_S_AXI_HP{n}_ACLK" : ClockSignal("ps7"),
# AXI HP0 aw.
f"i_S_AXI_HP{n}_AWVALID" : axi_hpn.aw.valid,
f"o_S_AXI_HP{n}_AWREADY" : axi_hpn.aw.ready,
f"i_S_AXI_HP{n}_AWADDR" : axi_hpn.aw.addr,
f"i_S_AXI_HP{n}_AWBURST" : axi_hpn.aw.burst,
f"i_S_AXI_HP{n}_AWLEN" : axi_hpn.aw.len,
f"i_S_AXI_HP{n}_AWSIZE" : axi_hpn.aw.size,
f"i_S_AXI_HP{n}_AWID" : axi_hpn.aw.id,
f"i_S_AXI_HP{n}_AWLOCK" : axi_hpn.aw.lock,
f"i_S_AXI_HP{n}_AWPROT" : axi_hpn.aw.prot,
f"i_S_AXI_HP{n}_AWCACHE" : axi_hpn.aw.cache,
f"i_S_AXI_HP{n}_AWQOS" : axi_hpn.aw.qos,
# AXI HP0 w.
f"i_S_AXI_HP{n}_WVALID" : axi_hpn.w.valid,
f"i_S_AXI_HP{n}_WLAST" : axi_hpn.w.last,
f"o_S_AXI_HP{n}_WREADY" : axi_hpn.w.ready,
f"i_S_AXI_HP{n}_WID" : axi_hpn.w.id,
f"i_S_AXI_HP{n}_WDATA" : axi_hpn.w.data,
f"i_S_AXI_HP{n}_WSTRB" : axi_hpn.w.strb,
# AXI HP0 b.
f"o_S_AXI_HP{n}_BVALID" : axi_hpn.b.valid,
f"i_S_AXI_HP{n}_BREADY" : axi_hpn.b.ready,
f"o_S_AXI_HP{n}_BID" : axi_hpn.b.id,
f"o_S_AXI_HP{n}_BRESP" : axi_hpn.b.resp,
# AXI HP0 ar.
f"i_S_AXI_HP{n}_ARVALID" : axi_hpn.ar.valid,
f"o_S_AXI_HP{n}_ARREADY" : axi_hpn.ar.ready,
f"i_S_AXI_HP{n}_ARADDR" : axi_hpn.ar.addr,
f"i_S_AXI_HP{n}_ARBURST" : axi_hpn.ar.burst,
f"i_S_AXI_HP{n}_ARLEN" : axi_hpn.ar.len,
f"i_S_AXI_HP{n}_ARID" : axi_hpn.ar.id,
f"i_S_AXI_HP{n}_ARLOCK" : axi_hpn.ar.lock,
f"i_S_AXI_HP{n}_ARSIZE" : axi_hpn.ar.size,
f"i_S_AXI_HP{n}_ARPROT" : axi_hpn.ar.prot,
f"i_S_AXI_HP{n}_ARCACHE" : axi_hpn.ar.cache,
f"i_S_AXI_HP{n}_ARQOS" : axi_hpn.ar.qos,
# AXI HP0 r.
f"o_S_AXI_HP{n}_RVALID" : axi_hpn.r.valid,
f"i_S_AXI_HP{n}_RREADY" : axi_hpn.r.ready,
f"o_S_AXI_HP{n}_RLAST" : axi_hpn.r.last,
f"o_S_AXI_HP{n}_RID" : axi_hpn.r.id,
f"o_S_AXI_HP{n}_RRESP" : axi_hpn.r.resp,
f"o_S_AXI_HP{n}_RDATA" : axi_hpn.r.data,
})
return axi_hpn
def add_emio_spi(self, spi_pads, n=0):
'''
Connect a PS SPI interfaces to some IO pads.
n selects which one (0 or 1).
'''
self.platform.ps7_cfg[f'CONFIG.PCW_SPI{n}_PERIPHERAL_ENABLE'] = '1'
p = spi_pads
for s, v in zip(["SCLK", "MOSI", "SS"], [p.clk, p.mosi, p.cs_n]):
self.cpu_params["o_SPI{}_{}_O".format(n, s)] = v
try:
miso = p.miso
except AttributeError:
print("add_emio_spi(): MISO pin hard-wired to 0")
miso = 0
self.cpu_params["i_SPI{}_MISO_I".format(n)] = miso
# ----------------
# unused PS pins
# ----------------
for s, v in zip(["SCLK", "MOSI", "SS"], [0, 0, 1]):
self.cpu_params["i_SPI{}_{}_I".format(n, s)] = v
# o_SPI0_SS1_O=
# o_SPI0_SS2_O=
# o_SPI0_SCLK_T=
# o_SPI0_MOSI_T=
# o_SPI0_SS_T=
def add_emio_gpio(self, target_pads=None, N=32):
'''
Connect a PS GPIO interfaces to some IO pads.
N selects width of GPIO port.
'''
self.platform.ps7_cfg.update(
PCW_GPIO_EMIO_GPIO_ENABLE='1',
PCW_GPIO_EMIO_GPIO_IO=str(N)
)
GPIO_O = Signal(N)
GPIO_T = Signal(N)
GPIO_I = Signal(N)
self.cpu_params.update(
o_GPIO_O=GPIO_O,
o_GPIO_T=GPIO_T,
i_GPIO_I=GPIO_I
)
if target_pads:
self.specials += Tristate(target_pads, GPIO_O, ~GPIO_T, GPIO_I)
def add_emio_i2c(self, | |
<reponame>online-ml/creme<filename>river/tree/hoeffding_tree.py
import collections
import functools
import io
import math
import typing
from abc import ABC, abstractmethod
from river import base
from river.utils.skmultiflow_utils import (
calculate_object_size,
normalize_values_in_dict,
)
from .nodes.branch import (
DTBranch,
NominalBinaryBranch,
NominalMultiwayBranch,
NumericBinaryBranch,
NumericMultiwayBranch,
)
from .nodes.leaf import HTLeaf
try:
import graphviz
GRAPHVIZ_INSTALLED = True
except ImportError:
GRAPHVIZ_INSTALLED = False
class HoeffdingTree(ABC):
"""Base class for Hoeffding Decision Trees.
This is an **abstract class**, so it cannot be used directly. It defines base operations
and properties that all the Hoeffding decision trees must inherit or implement according to
their own design.
Parameters
----------
max_depth
The maximum depth a tree can reach. If `None`, the tree will grow indefinitely.
binary_split
If True, only allow binary splits.
max_size
The max size of the tree, in Megabytes (MB).
memory_estimate_period
Interval (number of processed instances) between memory consumption checks.
stop_mem_management
If True, stop growing as soon as memory limit is hit.
remove_poor_attrs
If True, disable poor attributes to reduce memory usage.
merit_preprune
If True, enable merit-based tree pre-pruning.
"""
def __init__(
self,
max_depth: int = None,
binary_split: bool = False,
max_size: float = 100.0,
memory_estimate_period: int = 1000000,
stop_mem_management: bool = False,
remove_poor_attrs: bool = False,
merit_preprune: bool = True,
):
# Properties common to all the Hoeffding trees
self._split_criterion: str = ""
self._leaf_prediction: str = ""
self.max_depth: float = max_depth if max_depth is not None else math.inf
self.binary_split: bool = binary_split
self._max_size: float = max_size
self._max_byte_size: float = self._max_size * (2**20) # convert to byte
self.memory_estimate_period: int = memory_estimate_period
self.stop_mem_management: bool = stop_mem_management
self.remove_poor_attrs: bool = remove_poor_attrs
self.merit_preprune: bool = merit_preprune
self._root: typing.Union[DTBranch, HTLeaf, None] = None
self._n_active_leaves: int = 0
self._n_inactive_leaves: int = 0
self._inactive_leaf_size_estimate: float = 0.0
self._active_leaf_size_estimate: float = 0.0
self._size_estimate_overhead_fraction: float = 1.0
self._growth_allowed = True
self._train_weight_seen_by_model: float = 0.0
@staticmethod
def _hoeffding_bound(range_val, confidence, n):
r"""Compute the Hoeffding bound, used to decide how many samples are necessary at each
node.
Notes
-----
The Hoeffding bound is defined as:
$\\epsilon = \\sqrt{\\frac{R^2\\ln(1/\\delta))}{2n}}$
where:
$\\epsilon$: Hoeffding bound.
$R$: Range of a random variable. For a probability the range is 1, and for an
information gain the range is log *c*, where *c* is the number of classes.
$\\delta$: Confidence. 1 minus the desired probability of choosing the correct
attribute at any given node.
$n$: Number of samples.
Parameters
----------
range_val
Range value.
confidence
Confidence of choosing the correct attribute.
n
Number of processed samples.
"""
return math.sqrt(
(range_val * range_val * math.log(1.0 / confidence)) / (2.0 * n)
)
@property
def max_size(self):
"""Max allowed size tree can reach (in MB)."""
return self._max_size
@max_size.setter
def max_size(self, size):
self._max_size = size
self._max_byte_size = self._max_size * (2**20)
@property
def height(self) -> int:
if self._root:
return self._root.height
@property
def n_nodes(self):
if self._root:
return self._root.n_nodes
@property
def n_branches(self):
if self._root:
return self._root.n_branches
@property
def n_leaves(self):
if self._root:
return self._root.n_leaves
@property
def n_active_leaves(self):
return self._n_active_leaves
@property
def n_inactive_leaves(self):
return self._n_inactive_leaves
@property
def summary(self):
"""Collect metrics corresponding to the current status of the tree
in a string buffer.
"""
summary = {
"n_nodes": self.n_nodes,
"n_branches": self.n_branches,
"n_leaves": self.n_leaves,
"n_active_leaves": self.n_active_leaves,
"n_inactive_leaves": self.n_inactive_leaves,
"height": self.height,
"total_observed_weight": self._train_weight_seen_by_model,
}
return summary
def to_dataframe(self):
"""Return a representation of the current tree structure organized in a
`pandas.DataFrame` object.
In case the tree is empty or it only contains a single node (a leaf), `None` is returned.
Returns
-------
df
A `pandas.DataFrame` depicting the tree structure.
"""
if self._root is not None and isinstance(self._root, DTBranch):
return self._root.to_dataframe()
def _branch_selector(
self, numerical_feature=True, multiway_split=False
) -> typing.Type[DTBranch]:
"""Create a new split node."""
if numerical_feature:
if not multiway_split:
return NumericBinaryBranch
else:
return NumericMultiwayBranch
else:
if not multiway_split:
return NominalBinaryBranch
else:
return NominalMultiwayBranch
@abstractmethod
def _new_leaf(
self, initial_stats: dict = None, parent: typing.Union[HTLeaf, DTBranch] = None
) -> HTLeaf:
"""Create a new learning node.
The characteristics of the learning node depends on the tree algorithm.
Parameters
----------
initial_stats
Target statistics set from the parent node.
parent
Parent node to inherit from.
Returns
-------
A new learning node.
"""
@property
def split_criterion(self) -> str:
"""Return a string with the name of the split criterion being used by the tree."""
return self._split_criterion
@split_criterion.setter
@abstractmethod
def split_criterion(self, split_criterion):
"""Define the split criterion to be used by the tree."""
@property
def leaf_prediction(self) -> str:
"""Return the prediction strategy used by the tree at its leaves."""
return self._leaf_prediction
@leaf_prediction.setter
@abstractmethod
def leaf_prediction(self, leaf_prediction):
"""Define the prediction strategy used by the tree in its leaves."""
def _enforce_size_limit(self):
"""Track the size of the tree and disable/enable nodes if required.
This memory-management routine shared by all the Hoeffding Trees is based on [^1].
References
----------
[^1]: <NAME>., 2007. Improving hoeffding trees (Doctoral dissertation,
The University of Waikato).
"""
tree_size = self._size_estimate_overhead_fraction * (
self._active_leaf_size_estimate
+ self._n_inactive_leaves * self._inactive_leaf_size_estimate
)
if self._n_inactive_leaves > 0 or tree_size > self._max_byte_size:
if self.stop_mem_management:
self._growth_allowed = False
return
leaves = self._find_leaves()
leaves.sort(key=lambda leaf: leaf.calculate_promise())
max_active = 0
while max_active < len(leaves):
max_active += 1
if (
(
max_active * self._active_leaf_size_estimate
+ (len(leaves) - max_active) * self._inactive_leaf_size_estimate
)
* self._size_estimate_overhead_fraction
) > self._max_byte_size:
max_active -= 1
break
cutoff = len(leaves) - max_active
for i in range(cutoff):
if leaves[i].is_active():
leaves[i].deactivate()
self._n_inactive_leaves += 1
self._n_active_leaves -= 1
for i in range(cutoff, len(leaves)):
if not leaves[i].is_active() and leaves[i].depth < self.max_depth:
leaves[i].activate()
self._n_active_leaves += 1
self._n_inactive_leaves -= 1
def _estimate_model_size(self):
"""Calculate the size of the model and trigger tracker function
if the actual model size exceeds the max size in the configuration.
This memory-management routine shared by all the Hoeffding Trees is based on [^1].
References
----------
[^1]: <NAME>., 2007. Improving hoeffding trees (Doctoral dissertation,
The University of Waikato).
"""
leaves = self._find_leaves()
total_active_size = 0
total_inactive_size = 0
for leaf in leaves:
if leaf.is_active():
total_active_size += calculate_object_size(leaf)
else:
total_inactive_size += calculate_object_size(leaf)
if total_active_size > 0:
self._active_leaf_size_estimate = total_active_size / self._n_active_leaves
if total_inactive_size > 0:
self._inactive_leaf_size_estimate = (
total_inactive_size / self._n_inactive_leaves
)
actual_model_size = calculate_object_size(self)
estimated_model_size = (
self._n_active_leaves * self._active_leaf_size_estimate
+ self._n_inactive_leaves * self._inactive_leaf_size_estimate
)
self._size_estimate_overhead_fraction = actual_model_size / estimated_model_size
if actual_model_size > self._max_byte_size:
self._enforce_size_limit()
def _deactivate_all_leaves(self):
"""Deactivate all leaves."""
leaves = self._find_leaves()
for leaf in leaves:
leaf.deactivate()
self._n_inactive_leaves += 1
self._n_active_leaves -= 1
def _find_leaves(self) -> typing.List[HTLeaf]:
"""Find learning nodes in the tree.
Returns
-------
List of learning nodes in the tree.
"""
return [leaf for leaf in self._root.iter_leaves()]
# Adapted from creme's original implementation
def debug_one(self, x: dict) -> typing.Union[str, None]:
"""Print an explanation of how `x` is predicted.
Parameters
----------
x
A dictionary of features.
Returns
-------
A representation of the path followed by the tree to predict `x`; `None` if
the tree is empty.
Notes
-----
Currently, Label Combination Hoeffding Tree Classifier (for multi-label
classification) is not supported.
"""
if self._root is None:
return
# We'll redirect all the print statement to a buffer, we'll return the content of the
# buffer at the end
buffer = io.StringIO()
_print = functools.partial(print, file=buffer)
for node in self._root.walk(x, until_leaf=True):
if isinstance(node, HTLeaf):
_print(repr(node))
else:
try:
child_index = node.branch_no(x) # noqa
except KeyError:
child_index, _ = node.most_common_path()
_print(node.repr_branch(child_index)) # noqa
return buffer.getvalue()
def draw(self, max_depth: int = None):
"""Draw the tree using the `graphviz` library.
Since the tree is drawn without passing incoming samples, classification trees
will show the majority class in their leaves, whereas regression trees will
use the target mean.
Parameters
----------
max_depth
Only the root will be drawn when set to `0`. Every node will be drawn when
set to `None`.
Notes
-----
Currently, Label Combination Hoeffding Tree Classifier (for multi-label
classification) is not supported.
Examples
--------
>>> from river import datasets
>>> from river import tree
>>> model = tree.HoeffdingTreeClassifier(
... grace_period=5,
... split_confidence=1e-5,
... split_criterion='gini',
... max_depth=10,
... tie_threshold=0.05,
... )
>>> for x, y in datasets.Phishing():
... model = model.learn_one(x, y)
>>> dot = model.draw()
.. image:: ../../docs/img/dtree_draw.svg
:align: center
"""
counter = 0
def iterate(node=None):
if node is None:
yield None, None, self._root, 0, None
yield from iterate(self._root)
nonlocal counter
| |
prop
@pulumi.output_type
class KikChannelPropertiesResponse(dict):
"""
The parameters to provide for the Kik channel.
"""
def __init__(__self__, *,
api_key: str,
is_enabled: bool,
user_name: str,
is_validated: Optional[bool] = None):
"""
The parameters to provide for the Kik channel.
:param str api_key: Kik API key. Value only returned through POST to the action Channel List API, otherwise empty.
:param bool is_enabled: Whether this channel is enabled for the bot
:param str user_name: The Kik user name
:param bool is_validated: Whether this channel is validated for the bot
"""
pulumi.set(__self__, "api_key", api_key)
pulumi.set(__self__, "is_enabled", is_enabled)
pulumi.set(__self__, "user_name", user_name)
if is_validated is not None:
pulumi.set(__self__, "is_validated", is_validated)
@property
@pulumi.getter(name="apiKey")
def api_key(self) -> str:
"""
Kik API key. Value only returned through POST to the action Channel List API, otherwise empty.
"""
return pulumi.get(self, "api_key")
@property
@pulumi.getter(name="isEnabled")
def is_enabled(self) -> bool:
"""
Whether this channel is enabled for the bot
"""
return pulumi.get(self, "is_enabled")
@property
@pulumi.getter(name="userName")
def user_name(self) -> str:
"""
The Kik user name
"""
return pulumi.get(self, "user_name")
@property
@pulumi.getter(name="isValidated")
def is_validated(self) -> Optional[bool]:
"""
Whether this channel is validated for the bot
"""
return pulumi.get(self, "is_validated")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class KikChannelResponse(dict):
"""
Kik channel definition
"""
def __init__(__self__, *,
channel_name: str,
properties: Optional['outputs.KikChannelPropertiesResponse'] = None):
"""
Kik channel definition
:param str channel_name: The channel name
Expected value is 'KikChannel'.
:param 'KikChannelPropertiesResponseArgs' properties: The set of properties specific to Kik channel resource
"""
pulumi.set(__self__, "channel_name", 'KikChannel')
if properties is not None:
pulumi.set(__self__, "properties", properties)
@property
@pulumi.getter(name="channelName")
def channel_name(self) -> str:
"""
The channel name
Expected value is 'KikChannel'.
"""
return pulumi.get(self, "channel_name")
@property
@pulumi.getter
def properties(self) -> Optional['outputs.KikChannelPropertiesResponse']:
"""
The set of properties specific to Kik channel resource
"""
return pulumi.get(self, "properties")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class MsTeamsChannelPropertiesResponse(dict):
"""
The parameters to provide for the Microsoft Teams channel.
"""
def __init__(__self__, *,
is_enabled: bool,
calling_web_hook: Optional[str] = None,
enable_calling: Optional[bool] = None):
"""
The parameters to provide for the Microsoft Teams channel.
:param bool is_enabled: Whether this channel is enabled for the bot
:param str calling_web_hook: Webhook for Microsoft Teams channel calls
:param bool enable_calling: Enable calling for Microsoft Teams channel
"""
pulumi.set(__self__, "is_enabled", is_enabled)
if calling_web_hook is not None:
pulumi.set(__self__, "calling_web_hook", calling_web_hook)
if enable_calling is not None:
pulumi.set(__self__, "enable_calling", enable_calling)
@property
@pulumi.getter(name="isEnabled")
def is_enabled(self) -> bool:
"""
Whether this channel is enabled for the bot
"""
return pulumi.get(self, "is_enabled")
@property
@pulumi.getter(name="callingWebHook")
def calling_web_hook(self) -> Optional[str]:
"""
Webhook for Microsoft Teams channel calls
"""
return pulumi.get(self, "calling_web_hook")
@property
@pulumi.getter(name="enableCalling")
def enable_calling(self) -> Optional[bool]:
"""
Enable calling for Microsoft Teams channel
"""
return pulumi.get(self, "enable_calling")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class MsTeamsChannelResponse(dict):
"""
Microsoft Teams channel definition
"""
def __init__(__self__, *,
channel_name: str,
properties: Optional['outputs.MsTeamsChannelPropertiesResponse'] = None):
"""
Microsoft Teams channel definition
:param str channel_name: The channel name
Expected value is 'MsTeamsChannel'.
:param 'MsTeamsChannelPropertiesResponseArgs' properties: The set of properties specific to Microsoft Teams channel resource
"""
pulumi.set(__self__, "channel_name", 'MsTeamsChannel')
if properties is not None:
pulumi.set(__self__, "properties", properties)
@property
@pulumi.getter(name="channelName")
def channel_name(self) -> str:
"""
The channel name
Expected value is 'MsTeamsChannel'.
"""
return pulumi.get(self, "channel_name")
@property
@pulumi.getter
def properties(self) -> Optional['outputs.MsTeamsChannelPropertiesResponse']:
"""
The set of properties specific to Microsoft Teams channel resource
"""
return pulumi.get(self, "properties")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class ServiceProviderParameterResponseResult(dict):
"""
Extra Parameters specific to each Service Provider
"""
def __init__(__self__, *,
default: str,
description: str,
display_name: str,
help_url: str,
name: str,
type: str):
"""
Extra Parameters specific to each Service Provider
:param str default: Default Name for the Service Provider
:param str description: Description of the Service Provider
:param str display_name: Display Name of the Service Provider
:param str help_url: Help Url for the Service Provider
:param str name: Name of the Service Provider
:param str type: Type of the Service Provider
"""
pulumi.set(__self__, "default", default)
pulumi.set(__self__, "description", description)
pulumi.set(__self__, "display_name", display_name)
pulumi.set(__self__, "help_url", help_url)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def default(self) -> str:
"""
Default Name for the Service Provider
"""
return pulumi.get(self, "default")
@property
@pulumi.getter
def description(self) -> str:
"""
Description of the Service Provider
"""
return pulumi.get(self, "description")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> str:
"""
Display Name of the Service Provider
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter(name="helpUrl")
def help_url(self) -> str:
"""
Help Url for the Service Provider
"""
return pulumi.get(self, "help_url")
@property
@pulumi.getter
def name(self) -> str:
"""
Name of the Service Provider
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def type(self) -> str:
"""
Type of the Service Provider
"""
return pulumi.get(self, "type")
@pulumi.output_type
class ServiceProviderPropertiesResponseResult(dict):
"""
The Object used to describe a Service Provider supported by Bot Service
"""
def __init__(__self__, *,
dev_portal_url: str,
display_name: str,
icon_url: str,
id: str,
service_provider_name: str,
parameters: Optional[Sequence['outputs.ServiceProviderParameterResponseResult']] = None):
"""
The Object used to describe a Service Provider supported by Bot Service
:param str dev_portal_url: Display Name of the Service Provider
:param str display_name: Display Name of the Service Provider
:param str icon_url: Display Name of the Service Provider
:param str id: Id for Service Provider
:param str service_provider_name: Display Name of the Service Provider
:param Sequence['ServiceProviderParameterResponseArgs'] parameters: The list of parameters for the Service Provider
"""
pulumi.set(__self__, "dev_portal_url", dev_portal_url)
pulumi.set(__self__, "display_name", display_name)
pulumi.set(__self__, "icon_url", icon_url)
pulumi.set(__self__, "id", id)
pulumi.set(__self__, "service_provider_name", service_provider_name)
if parameters is not None:
pulumi.set(__self__, "parameters", parameters)
@property
@pulumi.getter(name="devPortalUrl")
def dev_portal_url(self) -> str:
"""
Display Name of the Service Provider
"""
return pulumi.get(self, "dev_portal_url")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> str:
"""
Display Name of the Service Provider
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter(name="iconUrl")
def icon_url(self) -> str:
"""
Display Name of the Service Provider
"""
return pulumi.get(self, "icon_url")
@property
@pulumi.getter
def id(self) -> str:
"""
Id for Service Provider
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="serviceProviderName")
def service_provider_name(self) -> str:
"""
Display Name of the Service Provider
"""
return pulumi.get(self, "service_provider_name")
@property
@pulumi.getter
def parameters(self) -> Optional[Sequence['outputs.ServiceProviderParameterResponseResult']]:
"""
The list of parameters for the Service Provider
"""
return pulumi.get(self, "parameters")
@pulumi.output_type
class ServiceProviderResponseResult(dict):
"""
Service Provider Definition
"""
def __init__(__self__, *,
properties: Optional['outputs.ServiceProviderPropertiesResponseResult'] = None):
"""
Service Provider Definition
:param 'ServiceProviderPropertiesResponseArgs' properties: The Properties of a Service Provider Object
"""
if properties is not None:
pulumi.set(__self__, "properties", properties)
@property
@pulumi.getter
def properties(self) -> Optional['outputs.ServiceProviderPropertiesResponseResult']:
"""
The Properties of a Service Provider Object
"""
return pulumi.get(self, "properties")
@pulumi.output_type
class SkuResponse(dict):
"""
The SKU of the cognitive services account.
"""
def __init__(__self__, *,
name: str,
tier: str):
"""
The SKU of the cognitive services account.
:param str name: The sku name
:param str tier: Gets the sku tier. This is based on the SKU name.
"""
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "tier", tier)
@property
@pulumi.getter
def name(self) -> str:
"""
The sku name
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def tier(self) -> str:
"""
Gets the sku tier. This is based on the SKU name.
"""
return pulumi.get(self, "tier")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class SkypeChannelPropertiesResponse(dict):
"""
The parameters to provide for the Microsoft Teams channel.
"""
def __init__(__self__, *,
is_enabled: bool,
calling_web_hook: Optional[str] = None,
enable_calling: Optional[bool] = None,
enable_groups: Optional[bool] = None,
enable_media_cards: Optional[bool] = None,
enable_messaging: Optional[bool] = None,
enable_screen_sharing: Optional[bool] = None,
enable_video: Optional[bool] = None,
groups_mode: Optional[str] = None):
"""
The parameters to provide for the Microsoft Teams channel.
:param bool is_enabled: Whether this channel is enabled for the bot
:param str calling_web_hook: Calling web hook for Skype channel
:param bool enable_calling: Enable calling for Skype channel
:param bool enable_groups: Enable groups for Skype channel
:param bool enable_media_cards: Enable media cards for Skype channel
:param bool enable_messaging: Enable messaging for Skype channel
:param bool enable_screen_sharing: Enable screen sharing for Skype channel
:param bool enable_video: Enable video for Skype channel
:param str groups_mode: Group mode for Skype channel
"""
pulumi.set(__self__, "is_enabled", is_enabled)
if calling_web_hook is not None:
pulumi.set(__self__, "calling_web_hook", calling_web_hook)
if enable_calling is not None:
pulumi.set(__self__, "enable_calling", enable_calling)
if enable_groups is not None:
pulumi.set(__self__, "enable_groups", enable_groups)
if enable_media_cards is not None:
pulumi.set(__self__, "enable_media_cards", enable_media_cards)
| |
from __future__ import unicode_literals, print_function
import uuid
from django.test import TestCase
from kong_admin import models
from kong_admin import logic
from kong_admin.factory import get_kong_client
from kong_admin.enums import Plugins
from .factories import APIReferenceFactory, PluginConfigurationReferenceFactory, ConsumerReferenceFactory, \
BasicAuthReferenceFactory, KeyAuthReferenceFactory, OAuth2ReferenceFactory
from .fake import fake
from kong_admin.models import PluginConfigurationReference
class APIReferenceLogicTestCase(TestCase):
def setUp(self):
self.client = get_kong_client()
self._cleanup_api = []
def tearDown(self):
self.client.close()
for api_ref in self._cleanup_api:
self.assertTrue(isinstance(api_ref, models.APIReference))
api_ref = models.APIReference.objects.get(id=api_ref.id) # reloads!!
logic.withdraw_api(self.client, api_ref)
def test_sync_incomplete_api(self):
# Create incomplete api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url())
# Mark for auto cleanup
self._cleanup_afterwards(api_ref)
# Try to sync, expect an error
with self.assertRaises(ValueError):
logic.synchronize_api(self.client, api_ref)
self.assertFalse(api_ref.synchronized)
# Fix api_ref
api_ref.request_host = fake.domain_name()
api_ref.save()
# Sync again
logic.synchronize_api(self.client, api_ref)
self.assertTrue(api_ref.synchronized)
# Check kong
result = self.client.apis.retrieve(api_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['upstream_url'], api_ref.upstream_url)
self.assertEqual(result['request_host'], api_ref.request_host)
def test_sync_api(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Mark for auto cleanup
self._cleanup_afterwards(api_ref)
# Sync
logic.synchronize_api(self.client, api_ref)
self.assertTrue(api_ref.synchronized)
# Check kong
result = self.client.apis.retrieve(api_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['upstream_url'], api_ref.upstream_url)
self.assertEqual(result['request_host'], api_ref.request_host)
def test_sync_updated_api(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Mark for auto cleanup
self._cleanup_afterwards(api_ref)
# Publish
logic.synchronize_api(self.client, api_ref)
self.assertTrue(api_ref.synchronized)
# Check kong
result = self.client.apis.retrieve(api_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['upstream_url'], api_ref.upstream_url)
self.assertEqual(result['request_host'], api_ref.request_host)
self.assertEqual(result['name'], api_ref.request_host)
# Update
new_name = fake.api_name()
self.assertNotEqual(new_name, api_ref.name)
api_ref.name = new_name
api_ref.save()
# Publish
logic.synchronize_api(self.client, api_ref)
self.assertTrue(api_ref.synchronized)
# Check kong
result = self.client.apis.retrieve(api_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['upstream_url'], api_ref.upstream_url)
self.assertEqual(result['request_host'], api_ref.request_host)
self.assertEqual(result['name'], new_name)
def test_withdraw_api(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Publish
logic.synchronize_api(self.client, api_ref)
self.assertTrue(api_ref.synchronized)
# Check kong
result = self.client.apis.retrieve(api_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['upstream_url'], api_ref.upstream_url)
self.assertEqual(result['request_host'], api_ref.request_host)
# Store kong_id
kong_id = api_ref.kong_id
# You can delete afterwards
logic.withdraw_api(self.client, api_ref)
self.assertFalse(api_ref.synchronized)
# Check kong
with self.assertRaises(ValueError):
_ = self.client.apis.retrieve(kong_id)
def test_delete_api(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Publish
logic.synchronize_api(self.client, api_ref)
self.assertTrue(api_ref.synchronized)
# Check kong
result = self.client.apis.retrieve(api_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['upstream_url'], api_ref.upstream_url)
self.assertEqual(result['request_host'], api_ref.request_host)
# You can delete afterwards
api_kong_id = api_ref.kong_id
api_ref.delete()
# Check kong
with self.assertRaises(ValueError):
_ = self.client.apis.retrieve(api_kong_id)
def test_sync_plugin_configuration_before_api(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Mark for auto cleanup
self._cleanup_afterwards(api_ref)
# Create plugin_configuration
plugin_configuration_ref = PluginConfigurationReferenceFactory(api=api_ref)
# Attempt to publish
with self.assertRaises(ValueError):
logic.synchronize_plugin_configuration(self.client, plugin_configuration_ref)
def test_sync_plugin_configuration_without_fields(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Mark for auto cleanup
self._cleanup_afterwards(api_ref)
# Publish api
logic.synchronize_api(self.client, api_ref)
# Check if remote upstream_url matches the locally known upstream_url
result = self.client.apis.retrieve(api_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['upstream_url'], api_ref.upstream_url)
# Create plugin_configuration
plugin_configuration_ref = PluginConfigurationReferenceFactory(api=api_ref, config={})
# Attempt to publish
with self.assertRaises(ValueError):
logic.synchronize_plugin_configuration(self.client, plugin_configuration_ref)
# Make sure we did not get a Kong ID (meaning it did not sync to Kong)
self.assertIsNone(plugin_configuration_ref.kong_id)
def test_sync_plugin_configuration(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Mark for auto cleanup
self._cleanup_afterwards(api_ref)
# Publish api
logic.synchronize_api(self.client, api_ref)
# Check if remote upstream_url matches the locally known upstream_url
result = self.client.apis.retrieve(api_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['upstream_url'], api_ref.upstream_url)
# Create plugin_configuration
plugin_configuration_ref = PluginConfigurationReferenceFactory(api=api_ref)
# Publish plugin_configuration
logic.synchronize_plugin_configuration(self.client, plugin_configuration_ref)
# Check
result = self.client.apis.plugins(api_ref.kong_id).retrieve(plugin_configuration_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['name'], Plugins.label(plugin_configuration_ref.plugin))
def test_withdraw_plugin_configuration(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Mark for auto cleanup
self._cleanup_afterwards(api_ref)
# Publish api
logic.synchronize_api(self.client, api_ref)
# Create plugin_configuration
plugin_configuration_ref = PluginConfigurationReferenceFactory(api=api_ref)
# Publish plugin_configuration
logic.synchronize_plugin_configuration(self.client, plugin_configuration_ref)
# Check if remote plugin name matches the locally known plugin
result = self.client.apis.plugins(api_ref.kong_id).retrieve(plugin_configuration_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['name'], Plugins.label(plugin_configuration_ref.plugin))
# Withdraw plugin_configuration
logic.withdraw_plugin_configuration(self.client, plugin_configuration_ref)
# Check
with self.assertRaises(ValueError):
_ = self.client.apis.plugins(api_ref.kong_id).retrieve(plugin_configuration_ref.kong_id)
def test_delete_synchronized_plugin_configuration(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Mark for auto cleanup
self._cleanup_afterwards(api_ref)
# Publish api
logic.synchronize_api(self.client, api_ref)
# Create plugin_configuration
plugin_configuration_ref = PluginConfigurationReferenceFactory(api=api_ref)
# Publish plugin_configuration
logic.synchronize_plugin_configuration(self.client, plugin_configuration_ref)
# Check if remote plugin name matches the locally known plugin
result = self.client.apis.plugins(api_ref.kong_id).retrieve(plugin_configuration_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['name'], Plugins.label(plugin_configuration_ref.plugin))
# Delete plugin_configuration
plugin_configuration_kong_id = plugin_configuration_ref.kong_id
plugin_configuration_ref.delete()
# Check
with self.assertRaises(ValueError):
_ = self.client.apis.plugins(api_ref.kong_id).retrieve(plugin_configuration_kong_id)
def test_disable_synchronized_plugin_configuration(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Mark for auto cleanup
self._cleanup_afterwards(api_ref)
# Publish api
logic.synchronize_api(self.client, api_ref)
# Create plugin_configuration
plugin_configuration_ref = PluginConfigurationReferenceFactory(api=api_ref)
# Publish plugin_configuration
logic.synchronize_plugin_configuration(self.client, plugin_configuration_ref)
# Check if remote plugin name matches the locally known plugin, and that it is enabled
result = self.client.apis.plugins(api_ref.kong_id).retrieve(plugin_configuration_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['name'], Plugins.label(plugin_configuration_ref.plugin))
self.assertTrue(result['enabled'])
# Update plugin_configuration
logic.enable_plugin_configuration(self.client, plugin_configuration_ref, enabled=False)
# Check
result = self.client.apis.plugins(api_ref.kong_id).retrieve(plugin_configuration_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['name'], Plugins.label(plugin_configuration_ref.plugin))
self.assertFalse(result['enabled'])
def test_update_synchronized_plugin_configuration(self):
# Create api_ref
api_ref = APIReferenceFactory(upstream_url=fake.url(), request_host=fake.domain_name())
# Mark for auto cleanup
self._cleanup_afterwards(api_ref)
# Publish api
logic.synchronize_api(self.client, api_ref)
# Create plugin_configuration
plugin_configuration_ref = PluginConfigurationReferenceFactory(api=api_ref)
# Publish plugin_configuration
logic.synchronize_plugin_configuration(self.client, plugin_configuration_ref)
# Check if remote plugin name matches the locally known plugin, and that the configuration matches the locally
# known configuration
result = self.client.apis.plugins(api_ref.kong_id).retrieve(plugin_configuration_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['name'], Plugins.label(plugin_configuration_ref.plugin))
self.assertEqual(result['config']['second'], plugin_configuration_ref.config['second'])
# Update plugin_configuration
new_value = 5
self.assertNotEqual(new_value, plugin_configuration_ref.config['second'])
plugin_configuration_ref.config['second'] = new_value
plugin_configuration_ref.save()
logic.publish_plugin_configuration(self.client, plugin_configuration_ref)
# Check
result = self.client.apis.plugins(api_ref.kong_id).retrieve(plugin_configuration_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['name'], Plugins.label(plugin_configuration_ref.plugin))
self.assertEqual(result['config']['second'], plugin_configuration_ref.config['second'])
def _cleanup_afterwards(self, api_ref):
self._cleanup_api.append(api_ref)
return api_ref
class ConsumerReferenceLogicTestCase(TestCase):
def setUp(self):
self.client = get_kong_client()
self._cleanup_consumers = []
def tearDown(self):
self.client.close()
for consumer_ref in self._cleanup_consumers:
self.assertTrue(isinstance(consumer_ref, models.ConsumerReference))
consumer_ref = models.ConsumerReference.objects.get(id=consumer_ref.id) # reloads!!
logic.withdraw_consumer(self.client, consumer_ref)
def test_incomplete_consumer(self):
# Create incomplete consumer_ref
consumer_ref = ConsumerReferenceFactory()
# Mark for auto cleanup
self._cleanup_afterwards(consumer_ref)
# Try to sync, expect an error
with self.assertRaises(ValueError):
logic.synchronize_consumer(self.client, consumer_ref)
self.assertFalse(consumer_ref.synchronized)
# Fix consumer_ref
consumer_ref.username = fake.consumer_name()
consumer_ref.save()
# Sync again
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Make sure the remote username matches the locally known username
result = self.client.consumers.retrieve(consumer_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['username'], consumer_ref.username)
def test_sync_consumer(self):
# Create consumer_ref
consumer_ref = ConsumerReferenceFactory(username=fake.consumer_name())
# Mark for auto cleanup
self._cleanup_afterwards(consumer_ref)
# Sync
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Make sure the remote username matches the locally known username
result = self.client.consumers.retrieve(consumer_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['username'], consumer_ref.username)
def test_sync_updated_consumer(self):
# Create consumer_ref
consumer_ref = ConsumerReferenceFactory(username=fake.consumer_name())
# Mark for auto cleanup
self._cleanup_afterwards(consumer_ref)
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Make sure the remote username matches the locally known username
result = self.client.consumers.retrieve(consumer_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['username'], consumer_ref.username)
# Update
new_name = fake.consumer_name()
self.assertNotEqual(new_name, consumer_ref.username)
consumer_ref.username = new_name
consumer_ref.save()
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Make sure the remote username matches the new username
result = self.client.consumers.retrieve(consumer_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['username'], new_name)
def test_withdraw_consumer(self):
# Create consumer_ref
consumer_ref = ConsumerReferenceFactory(username=fake.consumer_name())
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Make sure the remote username matches the locally known username
result = self.client.consumers.retrieve(consumer_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['username'], consumer_ref.username)
# Store kong_id
kong_id = consumer_ref.kong_id
# You can delete afterwards
logic.withdraw_consumer(self.client, consumer_ref)
self.assertFalse(consumer_ref.synchronized)
# Check kong
with self.assertRaises(ValueError):
_ = self.client.consumers.retrieve(kong_id)
def test_delete_consumer(self):
# Create consumer_ref
consumer_ref = ConsumerReferenceFactory(username=fake.consumer_name())
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Make sure the remote username matches the locally known username
result = self.client.consumers.retrieve(consumer_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['username'], consumer_ref.username)
# You can delete afterwards
consumer_kong_id = consumer_ref.kong_id
consumer_ref.delete()
# Check kong
with self.assertRaises(ValueError):
_ = self.client.consumers.retrieve(consumer_kong_id)
def test_sync_consumer_basic_auth(self):
# Create consumer_ref
consumer_ref = ConsumerReferenceFactory(username=fake.consumer_name())
# Mark for auto cleanup
self._cleanup_afterwards(consumer_ref)
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Check kong
amount = self.client.consumers.basic_auth(consumer_ref.kong_id).count()
self.assertEqual(amount, 0)
# Create auth
auth_ref = BasicAuthReferenceFactory(consumer=consumer_ref)
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Reload
auth_ref = models.BasicAuthReference.objects.get(id=auth_ref.id)
self.assertIsNotNone(auth_ref.kong_id)
# Make sure the remote username matches the locally known username
result = self.client.consumers.basic_auth(consumer_ref.kong_id).retrieve(auth_ref.kong_id)
self.assertIsNotNone(result)
self.assertEqual(result['username'], auth_ref.username)
self.assertIsNotNone(result['password'])
def test_sync_consumer_multiple_basic_auth(self):
amount = 3
# Create consumer_ref
consumer_ref = ConsumerReferenceFactory(username=fake.consumer_name())
# Mark for auto cleanup
self._cleanup_afterwards(consumer_ref)
# Create auths
auths = []
for i in range(amount):
auths.append(BasicAuthReferenceFactory(consumer=consumer_ref))
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Check
self.assertEqual(self.client.consumers.basic_auth(consumer_ref.kong_id).count(), amount)
# Reload
for i in range(len(auths)):
auths[i] = models.BasicAuthReference.objects.get(id=auths[i].id)
self.assertIsNotNone(auths[i].kong_id)
# Check kong
result = self.client.consumers.basic_auth(consumer_ref.kong_id).list()
self.assertIsNotNone(result)
self.assertEqual(
sorted([(uuid.UUID(r['id']), r['username']) for r in result['data']], key=lambda x: x[0]),
sorted([(obj.kong_id, obj.username) for obj in auths], key=lambda x: x[0]))
def test_withdraw_consumer_basic_auth(self):
# Create consumer_ref
consumer_ref = ConsumerReferenceFactory(username=fake.consumer_name())
# Create auth
auth_ref = BasicAuthReferenceFactory(consumer=consumer_ref)
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Reload
auth_ref = models.BasicAuthReference.objects.get(id=auth_ref.id)
self.assertIsNotNone(auth_ref.kong_id)
self.assertTrue(auth_ref.synchronized)
# Withdraw
logic.withdraw_consumer(self.client, consumer_ref)
self.assertFalse(consumer_ref.synchronized)
# Reload
auth_ref = models.BasicAuthReference.objects.get(id=auth_ref.id)
self.assertIsNone(auth_ref.kong_id)
self.assertFalse(auth_ref.synchronized)
def test_delete_consumer_basic_auth(self):
# Create consumer_ref
consumer_ref = ConsumerReferenceFactory(username=fake.consumer_name())
# Create auth
auth_ref1 = BasicAuthReferenceFactory(consumer=consumer_ref)
BasicAuthReferenceFactory(consumer=consumer_ref)
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Check
self.assertEqual(self.client.consumers.basic_auth(consumer_ref.kong_id).count(), 2)
# Delete auth_ref1
auth_ref1.delete()
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Check
self.assertEqual(self.client.consumers.basic_auth(consumer_ref.kong_id).count(), 1)
# Delete consumer
consumer_kong_id = consumer_ref.kong_id
consumer_ref.delete()
# Check
with self.assertRaises(ValueError):
self.client.consumers.basic_auth(consumer_kong_id).count()
def test_sync_consumer_key_auth(self):
# Create consumer_ref
consumer_ref = ConsumerReferenceFactory(username=fake.consumer_name())
# Mark for auto cleanup
self._cleanup_afterwards(consumer_ref)
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Check kong
amount = self.client.consumers.key_auth(consumer_ref.kong_id).count()
self.assertEqual(amount, 0)
# Create auth
auth_ref = KeyAuthReferenceFactory(consumer=consumer_ref)
# Publish
logic.synchronize_consumer(self.client, consumer_ref)
self.assertTrue(consumer_ref.synchronized)
# Reload
auth_ref = models.KeyAuthReference.objects.get(id=auth_ref.id)
self.assertIsNotNone(auth_ref.kong_id)
# | |
"""Module for general matrix class and related unit tests."""
import random
import unittest
import exceptions as exc
__version__ = "0.1"
class Matrix:
"""A class to represent a general matrix."""
def __init__(self, m, n, init=True):
"""Initalise matrix dimensions and contents."""
# initialise matrix dimensions
if not (isinstance(m, int) and isinstance(n, int)):
raise TypeError("dimensions must be integral")
if m <= 0 or n <= 0:
raise ValueError("dimensions must be positive")
self.m = m
self.n = n
# initalise matrix contents
if not isinstance(init, bool):
raise TypeError("init must be Boolean")
if init:
self.rows = [[0]*n for _ in range(m)]
else:
self.rows = []
def __str__(self):
"""Generate text representation of matrix."""
s = '\n'.join([' '.join([str(elem) for elem in row])
for row in self.rows])
return s + '\n'
def __repl__(self):
"""Generate reproducible representation of matrix."""
s = "Matrix of dimension " + str(self.m) + " by " \
+ str(self.n) + '\n'
s = s + "with data" + '\n'
s = s + '\n'.join([' '.join([str(elem) for elem in row])
for row in self.rows])
return s + '\n'
def __eq__(self, mtrx):
"""Evaluate whether two matrices are equivalent."""
return self.rows == mtrx.rows
def __add__(self, obj):
"""Add a valid object to this matrix and return the result.
Doesn't modify the current matrix. Valid objects include other matrices
and numeric scalars
"""
if isinstance(obj, Matrix):
if not (self.m == obj.m and self.n == obj.n):
raise exc.ComformabilityError(
"matrices must have the same dimensions")
res = Matrix(self.m, self.n)
for i in range(self.m):
for j in range(self.n):
val = self[i, j] + obj[i, j]
res[i, j] = val
return res
elif self.isNumeric(obj):
res = Matrix(self.m, self.n)
for i in range(self.m):
for j in range(self.n):
val = self[i, j] + obj
res[i, j] = val
return res
else:
raise TypeError(
"cannot add object of type " + type(obj) + " to matrix")
def __sub__(self, obj):
"""Subtract a valid object from this matrix and return the result.
Doesn't modify the current matrix. Valid objects include other matrices
and numeric scalars
"""
if isinstance(obj, Matrix):
if not (self.m == obj.m and self.n == obj.n):
raise exc.ComformabilityError(
"matrices must have the same dimensions")
res = Matrix(self.m, self.n)
for i in range(self.m):
for j in range(self.n):
val = self[i, j] - obj[i, j]
res[i, j] = val
return res
elif self.isNumeric(obj):
res = Matrix(self.m, self.n)
for i in range(self.m):
for j in range(self.n):
val = self[i, j] - obj
res[i, j] = val
return res
else:
raise TypeError(
"cannot subtract object of type " + type(obj) +
"from matrix")
def __mul__(self, obj):
"""Multiply this matrix by a valid object and return the result.
Doesn't modify the current matrix. Valid objects include other matrices
and numeric scalars. In the case where the other object is a matrix,
multiplication occurs with the current matrix on the left-hand side
"""
if isinstance(obj, Matrix):
if not self.n == obj.m:
raise exc.ComformabilityError(
"column dimension of first matrix much match row " +
"dimension of second matrix")
res = Matrix(self.m, obj.n)
for i in range(self.m):
for j in range(obj.n):
val = sum([self[i, k] * obj[k, j]
for k in range(self.m)])
res[i, j] = val
return res
elif self.isNumeric(obj):
res = Matrix(self.m, self.n)
for i in range(self.m):
for j in range(self.n):
val = self[i, j] * obj
res[i, j] = val
return res
else:
raise TypeError(
"cannot multiply matrix by object of type " + type(obj))
def __pos__(self):
"""Make all elements of matrix positive."""
res = Matrix(self.m, self.n)
for i in range(self.m):
for j in range(self.n):
val = +self[i, j]
res[i, j] = val
return res
def __neg__(self):
"""Make all elements of matrix negative."""
res = Matrix(self.m, self.n)
for i in range(self.m):
for j in range(self.n):
val = -self[i, j]
res[i, j] = val
return res
def __iadd__(self, mtrx):
"""Add a matrix to this matrix, modifying it in the process."""
# calls __add__
tmp = self + mtrx
self.rows = tmp.rows
return self
def __isub__(self, mtrx):
"""Subtract a matrix from this matrix, modifying it in the process."""
# calls __sub__
tmp = self - mtrx
self.rows = tmp.rows
return self
def __imul__(self, mtrx):
"""Right multiply this matrix by another and modify.
Multiply this matrix by another matrix (on the right), modifying
it in the process.
"""
# calls __mul__
tmp = self * mtrx
self.rows = tmp.rows
self.m, self.n = tmp.dim()
return self
def dim(self):
"""Get matrix dimensions as tuple."""
return (self.m, self.n)
def __getitem__(self, key):
"""Get element in (i, j)th position."""
self.__check_key_validity(key)
return self.rows[key[0]][key[1]]
def __setitem__(self, key, val):
"""Set element in (i, j)th position."""
self.__check_key_validity(key)
self.rows[key[0]][key[1]] = val
def __check_key_validity(self, key):
if not isinstance(key, tuple):
raise TypeError("key must be a tuple")
if len(key) != 2:
raise ValueError("key must be of length two")
if not (isinstance(key[0], int) and isinstance(key[1], int)):
raise TypeError("elements of key must be integers")
if not ((0 <= key[0] < self.m) and (0 <= key[1] < self.n)):
raise exc.OutOfBoundsError("key is out of bounds")
def subset(self, rows, cols):
# validation on rows/cols
if not (isinstance(rows, list) and isinstance(rows, list)):
raise TypeError("arguments must be lists")
if len(rows) == 0 or len(cols) == 0:
raise ValueError("subset cannot be empty")
# validation on elements of rows/cols
for i, elem in enumerate(rows + cols):
if not isinstance(elem, int):
raise TypeError("elements of rows/cols must be integers")
# if element represents a row
if i < len(rows):
if not 0 <= elem < self.m:
raise exc.OutOfBoundsError("key is out of bounds")
else:
if not 0 <= elem < self.n:
raise exc.OutOfBoundsError("key is out of bounds")
# subset matrix
obj = Matrix(len(rows), len(cols), init=False)
for r in rows:
obj.rows.append([self[r, c] for c in cols])
return obj
@classmethod
def makeRandom(cls, m, n, min=0, max=1):
"""Create random matrix.
Make a random matrix of dimension m by n with elements chosen
independently and uniformly from the interval (min, max).
"""
obj = Matrix(m, n, init=False)
for _1 in range(m):
obj.rows.append([random.randrange(min, max) for _2 in range(n)])
return obj
@classmethod
def makeZero(cls, m, n):
"""Make a zero matrix of dimension m by n."""
return Matrix(m, n, init=True)
@classmethod
def makeIdentity(cls, m):
"""Make an identity matrix of dimension m by m."""
obj = Matrix(m, m, init=False)
for i in range(m):
obj.rows.append([1 if i == j else 1 for j in range(m)])
return obj
@classmethod
def fromRows(cls, rows):
"""Make a matrix from a list of rows."""
m = len(rows)
n = len(rows[0])
# check that list of rows is valid
if any([len(row) != n for row in rows[1:]]):
raise ValueError("inconsistent row lengths")
obj = Matrix(m, n, init=False)
obj.rows = rows
return(obj)
@classmethod
def fromList(cls, elems, **kwargs):
"""Make matrix from list.
Make a matrix from a list of elements, filling along rows,
when given at least one dimension of the matrix.
"""
if not ('m' in kwargs or 'n' in kwargs):
raise ValueError("at least one of m and n must be specified")
m = kwargs['m']
n = kwargs['n']
if m * n != len(elems):
raise ValueError("dimension does not match number of elements in"
"list")
obj = Matrix(m, m, init=False)
for i in range(m):
obj.rows.append(elems[i * m: i * (m + 1)])
return obj
@classmethod
def isNumeric(cls, obj):
"""Check if a given object is of a numeric type.
Note that since bool inherits from int, that this will accept
Boolean values
"""
return isinstance(obj, (int, float, complex))
class MatrixTests(unittest.TestCase):
"""Unit test functions."""
def testAdd(self):
"""Test addition operator."""
# test addition by matrix
m1 = Matrix.fromRows([[1, 2], [3, 4]])
m2 = Matrix.fromRows([[5, 6], [7, 8]])
m3 = m1 + m2
self.assertTrue(m3 == Matrix.fromRows([[6, 8], [10, 12]]))
# test addition by scalar
m4 = m1 + 1
self.assertTrue(m4 == Matrix.fromRows([[2, 3], [4, 5]]))
# test addition by non-conforming matrix
m5 = Matrix.fromRows([[9, 10]])
with self.assertRaises(exc.ComformabilityError):
m1 + m5
# test addition by non-matrix/numeric object
with self.assertRaises(TypeError):
m1 + 'spam'
def testSub(self):
"""Test subtraction operator."""
# test subtraction by matrix
m1 = Matrix.fromRows([[1, 2], [3, 4]])
m2 | |
###############################################################################
#
# Package: NetMsgs
#
# File: NetMsgsBase.py
#
"""
NetMsgs Base Data Module
"""
## \file
## \package NetMsgs.NetMsgsBase
##
## $LastChangedDate: 2012-07-23 14:06:10 -0600 (Mon, 23 Jul 2012) $
## $Rev: 2098 $
##
## \brief NetMsgs Base Data Module
##
## \sa
## \htmlonly
## <a href="../pydoc/NetMsgs.NetMsgsBase.html">PyDoc Generated Documentation</a>
## \endhtmlonly
##
## \author <NAME> (<EMAIL>)
##
## \copyright
## \h_copy 2009-2017. RoadNarrows LLC.\n
## http://www.roadnarrows.com\n
## All Rights Reserved
##
# Permission is hereby granted, without written agreement and without
# license or royalty fees, to use, copy, modify, and distribute this
# software and its documentation for any purpose, provided that
# (1) The above copyright notice and the following two paragraphs
# appear in all copies of the source code and (2) redistributions
# including binaries reproduces these notices in the supporting
# documentation. Substantial modifications to this software may be
# copyrighted by their authors and need not follow the licensing terms
# described here, provided that the new terms are clearly indicated in
# all files where they apply.
#
# IN NO EVENT SHALL THE AUTHOR, ROADNARROWS LLC, OR ANY MEMBERS/EMPLOYEES
# OF ROADNARROW LLC OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY
# PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
# DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
# EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
#
# THE AUTHOR AND ROADNARROWS LLC SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN
# "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO
# PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#
###############################################################################
import sys
from NetMsgs.NetMsgsCore import *
## Message Encoding Type Enumeration
NMEncoding = ['flat', 'itv'] # future , 'cli']
## Message Byte Ordering Type Enumeration
NMEndian = ['big', 'little', 'native']
##
## Built-In message field types, keyed by XML field type name.
## code - message field type byte code
## desc - short description
## flen - packed message field length (bytes)
## comp - complexity. one of: simple compound na
## T - C/C++ type specifier
## pre - member name prefix (quasi-Hungarian)
##
NMBuiltInFieldTypes = {
'pad': { # not really a field type
'code': NMFTypePad,
'desc': "pad byte",
'flen': 1,
'comp': 'na',
'T': '',
'pre': '',
},
'char': {
'code': NMFTypeChar,
'desc': "8-bit character",
'flen': NMFVAL_LEN_CHAR,
'comp': 'simple',
'T': 'char',
'pre': 'c',
},
'u8': {
'code': NMFTypeU8,
'desc': "unsigned 8-bit integer",
'flen': NMFVAL_LEN_U8,
'comp': 'simple',
'T': 'byte_t',
'pre': 'by',
},
's8': {
'code': NMFTypeS8,
'desc': "signed 8-bit integer",
'flen': NMFVAL_LEN_S8,
'comp': 'simple',
'T': 'signed char',
'pre': 'hhi',
},
'bool': {
'code': NMFTypeBool,
'desc': "boolean 0=false, 1(non-zero)=true",
'flen': NMFVAL_LEN_BOOL,
'comp': 'simple',
'T': 'bool_t',
'pre': 'b',
},
'u16': {
'code': NMFTypeU16,
'desc': "unsigned 16-bit integer",
'flen': NMFVAL_LEN_U16,
'comp': 'simple',
'T': 'ushort_t',
'pre': 'hu',
},
's16': {
'code': NMFTypeS16,
'desc': "signed 16-bit integer",
'flen': NMFVAL_LEN_S16,
'comp': 'simple',
'T': 'short',
'pre': 'hi',
},
'u32': {
'code': NMFTypeU32,
'desc': "unsigned 32-bit integer",
'flen': NMFVAL_LEN_U32,
'comp': 'simple',
'T': 'uint_t',
'pre': 'u',
},
's32': {
'code': NMFTypeS32,
'desc': "signed 32-bit integer",
'flen': NMFVAL_LEN_S32,
'comp': 'simple',
'T': 'int',
'pre': 'i',
},
'u64': {
'code': NMFTypeU64,
'desc': "unsigned 64-bit integer",
'flen': NMFVAL_LEN_U64,
'comp': 'simple',
'T': 'ulonglong_t',
'pre': 'llu',
},
's64': {
'code': NMFTypeS64,
'desc': "signed 64-bit integer",
'flen': NMFVAL_LEN_S64,
'comp': 'simple',
'T': 'long long',
'pre': 'lli',
},
'f32': {
'code': NMFTypeF32,
'desc': "32-bit floating-point number",
'flen': NMFVAL_LEN_F32,
'comp': 'simple',
'T': 'float',
'pre': 'hf',
},
'f64': {
'code': NMFTypeF64,
'desc': "64-bit floating-point number",
'flen': NMFVAL_LEN_F64,
'comp': 'simple',
'T': 'double',
'pre': 'f',
},
'p32': {
'code': NMFTypeP32,
'desc': "32-bit pointer",
'flen': NMFVAL_LEN_P32,
'comp': 'simple',
'T': 'void *',
'pre': 'p',
},
'p64': {
'code': NMFTypeP64,
'desc': "64-bit pointer",
'flen': NMFVAL_LEN_P64,
'comp': 'simple',
'T': 'void *',
'pre': 'p',
},
'string': {
'code': NMFTypeString,
'desc': "char[] string",
'flen': 'variable',
'comp': 'compound',
'T': 'char',
'pre': 's',
},
'struct': {
'code': NMFTypeStruct,
'desc': "structure",
'flen': 'variable',
'comp': 'compound',
'T': 'struct',
'pre': 'st',
},
'vector': {
'code': NMFTypeVector,
'desc': "vector - one dimensional array",
'flen': 'variable',
'comp': 'compound',
'T': '',
'pre': 'vec',
},
}
##
#
# Aliases
#
NMBuiltInFieldTypes['byte'] = NMBuiltInFieldTypes['u8']
NMBuiltInFieldTypes['schar'] = NMBuiltInFieldTypes['s8']
NMBuiltInFieldTypes['ushort'] = NMBuiltInFieldTypes['u16']
NMBuiltInFieldTypes['short'] = NMBuiltInFieldTypes['s16']
NMBuiltInFieldTypes['uint'] = NMBuiltInFieldTypes['u32']
NMBuiltInFieldTypes['int'] = NMBuiltInFieldTypes['s32']
NMBuiltInFieldTypes['ulonglong'] = NMBuiltInFieldTypes['u64']
NMBuiltInFieldTypes['longlong'] = NMBuiltInFieldTypes['s64']
NMBuiltInFieldTypes['pointer'] = NMBuiltInFieldTypes['p32']
NMBuiltInFieldTypes['longpointer'] = NMBuiltInFieldTypes['p64']
NMBuiltInFieldTypes['float'] = NMBuiltInFieldTypes['f32']
NMBuiltInFieldTypes['double'] = NMBuiltInFieldTypes['f64']
## Get NetMsgs field type code given the XML field type.
NMFCode = lambda xmlftype: NMBuiltInFieldTypes[xmlftype]['code']
## The full set of XML ftype values
NMAliasMap = {
'byte': 'u8', 'schar': 's8', 'ushort': 'u16', 'short': 'u16',
'uint': 'u32', 'int': 's32', 'ulonglong': 'u64', 'longlong': 's64',
'pointer': 'p32', 'longpointer': 'p64', 'float': 'f32', 'double': 'f64',
}
## Special DB dictionary order key
NMKeyOrder = '>'
## Special DB pad field key
NMKeyPad = '#'
## XML ftype attribute vector suffix string
NMVectorSuffix = '[]'
## List of simple field types by XML ftype
NMFTypeSimple = [
'char', 'u8', 's8', 'bool', 'u16', 's16', 'u32', 's32', 'u64',
's64', 'f32', 'f64', 'p32', 'p64', ]
## List of simple field types by field type code
NMFTypeCodeSimple = [
NMFCode('char'), NMFCode('u8'), NMFCode('s8'), NMFCode('bool'),
NMFCode('u16'), NMFCode('s16'), NMFCode('u32'), NMFCode('s32'),
NMFCode('u64'), NMFCode('s64'), NMFCode('f32'), NMFCode('f64'),
NMFCode('p32'), NMFCode('p64') ]
## List of compound field types by XML ftype
NMFTypeCompound = [ 'string', 'struct', 'vector' ]
## List of compound field types by field type code
NMFTypeCodeCompound = [NMFCode('string'), NMFCode('struct'), NMFCode('vector')]
## List of number field types by XML ftype
NMFTypeNumber = [
'u8', 's8', 'u16', 's16', 'u32', 's32', 'u64', 's64', 'f32', 'f64' ]
## Field type code to XML file type map
NMFTypeCode2Xml = {
NMFCode('bool'): 'bool', NMFCode('char'): 'char',
NMFCode('u8'): 'u8', NMFCode('s8'): 's8',
NMFCode('u16'): 'u16', NMFCode('s16'): 's16',
NMFCode('u32'): 'u32', NMFCode('s32'): 's32',
NMFCode('u64'): 'u64', NMFCode('s64'): 's64',
NMFCode('f32'): 'f32', NMFCode('f64'): 'f64',
NMFCode('p32'): 'p32', NMFCode('p64'): 'p64',
NMFCode('string'): 'string', NMFCode('pad'): 'pad',
NMFCode('struct'): 'struct', NMFCode('vector'): 'vector'
}
## Field Header Lengths keyed by message encoding
NMFHdrLen = {
'flat': {'simple': 0, 'string': 0, 'struct': 0, 'vector': 0},
'itv': {
'simple': NMITV_FHDR_SIZE_SIMPLE, 'string': NMITV_FHDR_SIZE_STRING,
'struct': NMITV_FHDR_SIZE_STRUCT, 'vector': NMITV_FHDR_SIZE_VECTOR},
}
## No field id value
NMFIdNone = NMFID_NONE
## Default pad count
NMPadDftCount = 1
## Pad field value
NMPadFVal = NMFTypePadTr
## Maximum and default string maximum length
NMStringMaxCount = NMFVAL_LEN_MAX_STRING
## Maximum and default vector maximum item count
NMVectorMaxCount = NMFVAL_LEN_MAX_VECTOR
## space quickie
space = lambda indent: "%*s" % (indent, '')
#--
def StrError(ecode):
""" Get the error string describing the NetMsgs error code.
The absolute value of the error code is taken prior retrieving the
string. An unknown or out-of-range error code will be mapped to
NM_ECODE_BADEC.
Parameters:
ecode - NetMsgs error code.
Return:
The appropriate error code string.
"""
sErr = nmStrError(ecode)
if not sErr:
sErr = 'Error'
return sErr
##
#------------------------------------------------------------------------------
# CLASS: NetMsgsError
#------------------------------------------------------------------------------
class NetMsgsError(Exception):
""" NetMsgs Exception Class. """
def __init__(self, msg='XML Parser Error'):
""" Raise exception.
Parameters:
msg - Exception message string.
"""
Exception.__init__(self, msg)
##
#-------------------------------------------------------------------------------
# Support Utilities
#-------------------------------------------------------------------------------
#--
def IsIdentifier(token):
""" Returns True if token is a valid identifier, else False.
Parameters:
token - Parsed token.
"""
if not token:
return False
c = token[0]
if not c.isalpha() and c != "_":
return False
for c in token[1:]:
if not c.isalnum() and c != "_":
return False
return True
##
#--
def PrettyPrintCols(fp, cursor, *args, **kwargs):
""" Pretty print argument strings aligned to column.
Parameters:
cursor - Current column cursor position.
args - List of argument (pos, s) 2-tuples.
kwargs - Print control keywords.
"""
while len(args) >= 2:
linecont = kwargs.get('linecont', '')
force = kwargs.get('force', False)
pos = args[0]
s = args[1]
args = args[2:]
if (pos <= cursor) and (cursor > 0):
if not force or cursor > 78:
fp.write("%s\n" % (linecont))
cursor = 0
else:
fp.write(" ")
cursor += 1
if pos > cursor:
fp.write(space(pos-cursor))
cursor = pos
fp.write("%s" % (s))
cursor += len(s)
return cursor
##
#--
def PrintBuf(buf, count=None, preface='', nlfreq=None, indent=0, col=0,
fp=sys.stderr):
""" Pretty print binary buffer to opened file stream.
Parameters:
buf - Buffer to print.
count - Number of bytes to print.
preface - Optional buffer preface string.
nlfreq - Newline frequency (None for no newlines).
ident - Indentation column alignment.
col - Current column position.
fp - Output file pointer.
"""
if preface:
s = "%s: " % (preface)
col += len(s)
fp.write(s)
if count is None:
count = len(buf)
if (count > 0) and (col < indent):
fp.write(space(indent-col))
i = 0
while i | |
pd.DataFrame(frame_data2)
pandas_df2 = pandas.DataFrame(frame_data2)
join_types = ["left", "right", "outer", "inner"]
for how in join_types:
modin_join = modin_df.join(modin_df2, how=how)
pandas_join = pandas_df.join(pandas_df2, how=how)
df_equals(modin_join, pandas_join)
frame_data3 = {"col7": [1, 2, 3, 5, 6, 7, 8]}
modin_df3 = pd.DataFrame(frame_data3)
pandas_df3 = pandas.DataFrame(frame_data3)
join_types = ["left", "outer", "inner"]
for how in join_types:
modin_join = modin_df.join([modin_df2, modin_df3], how=how)
pandas_join = pandas_df.join([pandas_df2, pandas_df3], how=how)
df_equals(modin_join, pandas_join)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_keys(self, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.keys(), pandas_df.keys())
def test_kurt(self):
data = test_data_values[0]
with pytest.warns(UserWarning):
pd.DataFrame(data).kurt()
def test_kurtosis(self):
data = test_data_values[0]
with pytest.warns(UserWarning):
pd.DataFrame(data).kurtosis()
def test_last(self):
i = pd.date_range("2018-04-09", periods=4, freq="2D")
ts = pd.DataFrame({"A": [1, 2, 3, 4]}, index=i)
with pytest.warns(UserWarning):
ts.last("3D")
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_last_valid_index(self, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
assert modin_df.last_valid_index() == (pandas_df.last_valid_index())
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_loc(self, request, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
# We skip nan datasets because nan != nan
if "nan" not in request.node.name:
key1 = modin_df.columns[0]
key2 = modin_df.columns[1]
# Scaler
assert modin_df.loc[0, key1] == pandas_df.loc[0, key1]
# Series
df_equals(modin_df.loc[0], pandas_df.loc[0])
df_equals(modin_df.loc[1:, key1], pandas_df.loc[1:, key1])
df_equals(modin_df.loc[1:2, key1], pandas_df.loc[1:2, key1])
# DataFrame
df_equals(modin_df.loc[[1, 2]], pandas_df.loc[[1, 2]])
# List-like of booleans
indices = [
True if i % 3 == 0 else False for i in range(len(modin_df.index))
]
columns = [
True if i % 5 == 0 else False for i in range(len(modin_df.columns))
]
modin_result = modin_df.loc[indices, columns]
pandas_result = pandas_df.loc[indices, columns]
df_equals(modin_result, pandas_result)
# See issue #80
# df_equals(modin_df.loc[[1, 2], ['col1']], pandas_df.loc[[1, 2], ['col1']])
df_equals(modin_df.loc[1:2, key1:key2], pandas_df.loc[1:2, key1:key2])
# From issue #421
df_equals(modin_df.loc[:, [key2, key1]], pandas_df.loc[:, [key2, key1]])
df_equals(modin_df.loc[[2, 1], :], pandas_df.loc[[2, 1], :])
# Write Item
modin_df_copy = modin_df.copy()
pandas_df_copy = pandas_df.copy()
modin_df_copy.loc[[1, 2]] = 42
pandas_df_copy.loc[[1, 2]] = 42
df_equals(modin_df_copy, pandas_df_copy)
def test_loc_multi_index(self):
modin_df = pd.read_csv(
"modin/pandas/test/data/blah.csv", header=[0, 1, 2, 3], index_col=0
)
pandas_df = pandas.read_csv(
"modin/pandas/test/data/blah.csv", header=[0, 1, 2, 3], index_col=0
)
df_equals(modin_df.loc[1], pandas_df.loc[1])
df_equals(modin_df.loc[1, "Presidents"], pandas_df.loc[1, "Presidents"])
df_equals(
modin_df.loc[1, ("Presidents", "Pure mentions")],
pandas_df.loc[1, ("Presidents", "Pure mentions")],
)
assert (
modin_df.loc[1, ("Presidents", "Pure mentions", "IND", "all")]
== pandas_df.loc[1, ("Presidents", "Pure mentions", "IND", "all")]
)
df_equals(
modin_df.loc[(1, 2), "Presidents"], pandas_df.loc[(1, 2), "Presidents"]
)
tuples = [
("bar", "one"),
("bar", "two"),
("bar", "three"),
("bar", "four"),
("baz", "one"),
("baz", "two"),
("baz", "three"),
("baz", "four"),
("foo", "one"),
("foo", "two"),
("foo", "three"),
("foo", "four"),
("qux", "one"),
("qux", "two"),
("qux", "three"),
("qux", "four"),
]
modin_index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])
pandas_index = pandas.MultiIndex.from_tuples(tuples, names=["first", "second"])
frame_data = np.random.randint(0, 100, size=(16, 100))
modin_df = pd.DataFrame(
frame_data,
index=modin_index,
columns=["col{}".format(i) for i in range(100)],
)
pandas_df = pandas.DataFrame(
frame_data,
index=pandas_index,
columns=["col{}".format(i) for i in range(100)],
)
df_equals(modin_df.loc["bar", "col1"], pandas_df.loc["bar", "col1"])
assert (
modin_df.loc[("bar", "one"), "col1"]
== pandas_df.loc[("bar", "one"), "col1"]
)
df_equals(
modin_df.loc["bar", ("col1", "col2")],
pandas_df.loc["bar", ("col1", "col2")],
)
def test_lookup(self):
data = test_data_values[0]
with pytest.warns(UserWarning):
pd.DataFrame(data).lookup([0, 1], ["col1", "col2"])
def test_mad(self):
data = test_data_values[0]
with pytest.warns(UserWarning):
pd.DataFrame(data).mad()
def test_mask(self):
df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=["A", "B"])
m = df % 3 == 0
with pytest.warns(UserWarning):
try:
df.mask(~m, -df)
except ValueError:
pass
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
@pytest.mark.parametrize(
"skipna", bool_arg_values, ids=arg_keys("skipna", bool_arg_keys)
)
@pytest.mark.parametrize(
"numeric_only", bool_arg_values, ids=arg_keys("numeric_only", bool_arg_keys)
)
def test_max(self, request, data, axis, skipna, numeric_only):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas_df.max(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
except Exception:
with pytest.raises(TypeError):
modin_df.max(axis=axis, skipna=skipna, numeric_only=numeric_only)
else:
modin_result = modin_df.max(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
df_equals(modin_result, pandas_result)
try:
pandas_result = pandas_df.T.max(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
except Exception:
with pytest.raises(TypeError):
modin_df.T.max(axis=axis, skipna=skipna, numeric_only=numeric_only)
else:
modin_result = modin_df.T.max(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
@pytest.mark.parametrize(
"skipna", bool_arg_values, ids=arg_keys("skipna", bool_arg_keys)
)
@pytest.mark.parametrize(
"numeric_only", bool_arg_values, ids=arg_keys("numeric_only", bool_arg_keys)
)
def test_mean(self, request, data, axis, skipna, numeric_only):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas_df.mean(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
except Exception as e:
with pytest.raises(type(e)):
modin_df.mean(axis=axis, skipna=skipna, numeric_only=numeric_only)
else:
modin_result = modin_df.mean(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
df_equals(modin_result, pandas_result)
try:
pandas_result = pandas_df.T.mean(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
except Exception as e:
with pytest.raises(type(e)):
modin_df.T.mean(axis=axis, skipna=skipna, numeric_only=numeric_only)
else:
modin_result = modin_df.T.mean(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
@pytest.mark.parametrize(
"skipna", bool_arg_values, ids=arg_keys("skipna", bool_arg_keys)
)
@pytest.mark.parametrize(
"numeric_only", bool_arg_values, ids=arg_keys("numeric_only", bool_arg_keys)
)
def test_median(self, request, data, axis, skipna, numeric_only):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas_df.median(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
except Exception:
with pytest.raises(TypeError):
modin_df.median(axis=axis, skipna=skipna, numeric_only=numeric_only)
else:
modin_result = modin_df.median(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
df_equals(modin_result, pandas_result)
try:
pandas_result = pandas_df.T.median(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
except Exception:
with pytest.raises(TypeError):
modin_df.T.median(axis=axis, skipna=skipna, numeric_only=numeric_only)
else:
modin_result = modin_df.T.median(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
df_equals(modin_result, pandas_result)
class TestDFPartTwo:
def test_melt(self):
data = test_data_values[0]
with pytest.warns(UserWarning):
pd.DataFrame(data).melt()
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize(
"index", bool_arg_values, ids=arg_keys("index", bool_arg_keys)
)
def test_memory_usage(self, data, index):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data) # noqa F841
modin_result = modin_df.memory_usage(index=index)
pandas_result = pandas_df.memory_usage(index=index)
df_equals(modin_result, pandas_result)
def test_merge(self):
frame_data = {
"col1": [0, 1, 2, 3],
"col2": [4, 5, 6, 7],
"col3": [8, 9, 0, 1],
"col4": [2, 4, 5, 6],
}
modin_df = pd.DataFrame(frame_data)
pandas_df = pandas.DataFrame(frame_data)
frame_data2 = {"col1": [0, 1, 2], "col2": [1, 5, 6]}
modin_df2 = pd.DataFrame(frame_data2)
pandas_df2 = pandas.DataFrame(frame_data2)
join_types = ["outer", "inner"]
for how in join_types:
# Defaults
modin_result = modin_df.merge(modin_df2, how=how)
pandas_result = pandas_df.merge(pandas_df2, how=how)
df_equals(modin_result, pandas_result)
# left_on and right_index
modin_result = modin_df.merge(
modin_df2, how=how, left_on="col1", right_index=True
)
pandas_result = pandas_df.merge(
pandas_df2, how=how, left_on="col1", right_index=True
)
df_equals(modin_result, pandas_result)
# left_index and right_on
modin_result = modin_df.merge(
modin_df2, how=how, left_index=True, right_on="col1"
)
pandas_result = pandas_df.merge(
pandas_df2, how=how, left_index=True, right_on="col1"
)
df_equals(modin_result, pandas_result)
# left_on and right_on col1
modin_result = modin_df.merge(
modin_df2, how=how, left_on="col1", right_on="col1"
)
pandas_result = pandas_df.merge(
pandas_df2, how=how, left_on="col1", right_on="col1"
)
df_equals(modin_result, pandas_result)
# left_on and right_on col2
modin_result = modin_df.merge(
modin_df2, how=how, left_on="col2", right_on="col2"
)
pandas_result = pandas_df.merge(
pandas_df2, how=how, left_on="col2", right_on="col2"
)
df_equals(modin_result, pandas_result)
# left_index and right_index
modin_result = modin_df.merge(
modin_df2, how=how, left_index=True, right_index=True
)
pandas_result = pandas_df.merge(
pandas_df2, how=how, left_index=True, right_index=True
)
df_equals(modin_result, pandas_result)
# Named Series promoted to DF
s = pd.Series(frame_data2.get("col1"))
with pytest.raises(ValueError):
modin_df.merge(s)
s = pd.Series(frame_data2.get("col1"), name="col1")
df_equals(modin_df.merge(s), modin_df.merge(modin_df2[["col1"]]))
with pytest.raises(ValueError):
modin_df.merge("Non-valid type")
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
@pytest.mark.parametrize(
"skipna", bool_arg_values, ids=arg_keys("skipna", bool_arg_keys)
)
@pytest.mark.parametrize(
"numeric_only", bool_arg_values, ids=arg_keys("numeric_only", bool_arg_keys)
)
def test_min(self, data, axis, skipna, numeric_only):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas_df.min(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
except Exception:
with pytest.raises(TypeError):
modin_df.min(axis=axis, skipna=skipna, numeric_only=numeric_only)
else:
modin_result = modin_df.min(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
df_equals(modin_result, pandas_result)
try:
pandas_result = pandas_df.T.min(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
except Exception:
with pytest.raises(TypeError):
modin_df.T.min(axis=axis, skipna=skipna, numeric_only=numeric_only)
else:
modin_result = modin_df.T.min(
axis=axis, skipna=skipna, numeric_only=numeric_only
)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
@pytest.mark.parametrize(
"numeric_only", bool_arg_values, ids=arg_keys("numeric_only", bool_arg_keys)
)
def test_mode(self, request, data, axis, numeric_only):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
try:
pandas_result = pandas_df.mode(axis=axis, numeric_only=numeric_only)
except Exception:
with pytest.raises(TypeError):
modin_df.mode(axis=axis, numeric_only=numeric_only)
else:
modin_result = modin_df.mode(axis=axis, numeric_only=numeric_only)
df_equals(modin_result, pandas_result)
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_ndim(self, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
assert modin_df.ndim == pandas_df.ndim
def test_nlargest(self):
df = pd.DataFrame(
{
"population": [
59000000,
65000000,
434000,
434000,
434000,
337000,
11300,
11300,
11300,
],
"GDP": [1937894, 2583560, 12011, 4520, 12128, 17036, 182, 38, 311],
"alpha-2": ["IT", "FR", "MT", "MV", "BN", "IS", "NR", "TV", "AI"],
},
index=[
"Italy",
"France",
"Malta",
"Maldives",
"Brunei",
"Iceland",
"Nauru",
"Tuvalu",
"Anguilla",
],
)
with pytest.warns(UserWarning):
df.nlargest(3, "population")
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_notna(self, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.notna(), pandas_df.notna())
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
def test_notnull(self, data):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
df_equals(modin_df.notnull(), pandas_df.notnull())
def test_nsmallest(self):
df = pd.DataFrame(
{
"population": [
59000000,
65000000,
434000,
434000,
434000,
337000,
11300,
11300,
11300,
],
"GDP": [1937894, 2583560, 12011, 4520, 12128, 17036, 182, 38, 311],
"alpha-2": ["IT", "FR", "MT", "MV", "BN", "IS", "NR", "TV", "AI"],
},
index=[
"Italy",
"France",
"Malta",
"Maldives",
"Brunei",
"Iceland",
"Nauru",
"Tuvalu",
"Anguilla",
],
)
with pytest.warns(UserWarning):
df.nsmallest(3, "population")
@pytest.mark.parametrize("data", test_data_values, ids=test_data_keys)
@pytest.mark.parametrize("axis", axis_values, ids=axis_keys)
@pytest.mark.parametrize(
"dropna", bool_arg_values, ids=arg_keys("dropna", bool_arg_keys)
)
def test_nunique(self, data, axis, dropna):
modin_df = pd.DataFrame(data)
pandas_df = pandas.DataFrame(data)
modin_result = modin_df.nunique(axis=axis, dropna=dropna)
pandas_result = pandas_df.nunique(axis=axis, dropna=dropna)
df_equals(modin_result, pandas_result)
modin_result | |
sg filters
resolved_filters = filters
results = [
# Apply the filters for every single entities for the given entity type.
row for row in self._db[entity_type].values()
if self._row_matches_filters(
entity_type, row, resolved_filters, filter_operator, retired_only
)
]
# handle the ordering of the recordset
if order:
# order: [{"field_name": "code", "direction": "asc"}, ... ]
for order_entry in order:
if "field_name" not in order_entry:
raise ValueError("Order clauses must be list of dicts with keys 'field_name' and 'direction'!")
order_field = order_entry["field_name"]
if order_entry["direction"] == "asc":
desc_order = False
elif order_entry["direction"] == "desc":
desc_order = True
else:
raise ValueError("Unknown ordering direction")
results = sorted(results, key=lambda k: k[order_field], reverse=desc_order)
if fields is None:
fields = set(["type", "id"])
else:
fields = set(fields) | set(["type", "id"])
# get the values requested
val = [dict((field, self._get_field_from_row(entity_type, row, field)) for field in fields) for row in results]
return val
def find_one(
self, entity_type, filters, fields=None, order=None, filter_operator=None,
retired_only=False
):
results = self.find(
entity_type, filters, fields=fields,
order=order, filter_operator=filter_operator, retired_only=retired_only
)
return results[0] if results else None
def batch(self, requests):
results = []
for request in requests:
if request["request_type"] == "create":
results.append(self.create(request["entity_type"], request["data"]))
elif request["request_type"] == "update":
# note: Shotgun.update returns a list of a single item
results.append(self.update(request["entity_type"], request["entity_id"], request["data"])[0])
elif request["request_type"] == "delete":
results.append(self.delete(request["entity_type"], request["entity_id"]))
else:
raise ShotgunError("Invalid request type %s in request %s" % (request["request_type"], request))
return results
def create(self, entity_type, data, return_fields=None):
# special handling of storage fields - if a field value
# is a dict with a key local_path, then add fields
# local_path_linux, local_path_windows, local_path_mac
# as a reflection of this
for d in data:
if isinstance(data[d], dict) and "local_path" in data[d]:
# partly imitate some of the business logic happening on the
# server side of shotgun when a file/link entity value is created
if "local_storage" not in data[d]:
data[d]["local_storage"] = {"id": 0, "name": "auto_generated_by_mockgun", "type": "LocalStorage"}
if "local_path_linux" not in data[d]:
data[d]["local_path_linux"] = data[d]["local_path"]
if "local_path_windows" not in data[d]:
data[d]["local_path_windows"] = data[d]["local_path"]
if "local_path_mac" not in data[d]:
data[d]["local_path_mac"] = data[d]["local_path"]
self._validate_entity_type(entity_type)
self._validate_entity_data(entity_type, data)
self._validate_entity_fields(entity_type, return_fields)
try:
# get next id in this table
next_id = max(self._db[entity_type]) + 1
except ValueError:
next_id = 1
row = self._get_new_row(entity_type)
self._update_row(entity_type, row, data)
row["id"] = next_id
self._db[entity_type][next_id] = row
if return_fields is None:
result = dict((field, self._get_field_from_row(entity_type, row, field)) for field in data)
else:
result = dict((field, self._get_field_from_row(entity_type, row, field)) for field in return_fields)
result["type"] = row["type"]
result["id"] = row["id"]
return result
def update(self, entity_type, entity_id, data):
self._validate_entity_type(entity_type)
self._validate_entity_data(entity_type, data)
self._validate_entity_exists(entity_type, entity_id)
row = self._db[entity_type][entity_id]
self._update_row(entity_type, row, data)
return [dict((field, item) for field, item in row.items() if field in data or field in ("type", "id"))]
def delete(self, entity_type, entity_id):
self._validate_entity_type(entity_type)
self._validate_entity_exists(entity_type, entity_id)
row = self._db[entity_type][entity_id]
if not row["__retired"]:
row["__retired"] = True
return True
else:
return False
def revive(self, entity_type, entity_id):
self._validate_entity_type(entity_type)
self._validate_entity_exists(entity_type, entity_id)
row = self._db[entity_type][entity_id]
if row["__retired"]:
row["__retired"] = False
return True
else:
return False
def upload(self, entity_type, entity_id, path, field_name=None, display_name=None, tag_list=None):
raise NotImplementedError
def upload_thumbnail(self, entity_type, entity_id, path, **kwargs):
pass
###################################################################################################
# internal methods and members
def _validate_entity_type(self, entity_type):
if entity_type not in self._schema:
raise ShotgunError("%s is not a valid entity" % entity_type)
def _validate_entity_data(self, entity_type, data):
if "id" in data or "type" in data:
raise ShotgunError("Can't set id or type on create or update")
self._validate_entity_fields(entity_type, data.keys())
for field, item in data.items():
if item is None:
# none is always ok
continue
field_info = self._schema[entity_type][field]
if field_info["data_type"]["value"] == "multi_entity":
if not isinstance(item, list):
raise ShotgunError(
"%s.%s is of type multi_entity, but data %s is not a list" %
(entity_type, field, item)
)
elif item and any(not isinstance(sub_item, dict) for sub_item in item):
raise ShotgunError(
"%s.%s is of type multi_entity, but data %s contains a non-dictionary" %
(entity_type, field, item)
)
elif item and any("id" not in sub_item or "type" not in sub_item for sub_item in item):
raise ShotgunError(
"%s.%s is of type multi-entity, but an item in data %s does not contain 'type' and 'id'" %
(entity_type, field, item)
)
elif item and any(
sub_item["type"] not in field_info["properties"]["valid_types"]["value"] for sub_item in item
):
raise ShotgunError(
"%s.%s is of multi-type entity, but an item in data %s has an invalid type (expected one of %s)"
% (entity_type, field, item, field_info["properties"]["valid_types"]["value"])
)
elif field_info["data_type"]["value"] == "entity":
if not isinstance(item, dict):
raise ShotgunError(
"%s.%s is of type entity, but data %s is not a dictionary" %
(entity_type, field, item)
)
elif "id" not in item or "type" not in item:
raise ShotgunError(
"%s.%s is of type entity, but data %s does not contain 'type' and 'id'"
% (entity_type, field, item)
)
# elif item["type"] not in field_info["properties"]["valid_types"]["value"]:
# raise ShotgunError(
# "%s.%s is of type entity, but data %s has an invalid type (expected one of %s)" %
# (entity_type, field, item, field_info["properties"]["valid_types"]["value"])
# )
else:
try:
sg_type = field_info["data_type"]["value"]
python_type = {"number": int,
"float": float,
"checkbox": bool,
"percent": int,
"text": six.string_types,
"serializable": dict,
"date": datetime.date,
"date_time": datetime.datetime,
"list": six.string_types,
"status_list": six.string_types,
"url": dict}[sg_type]
except KeyError:
raise ShotgunError(
"Field %s.%s: Handling for ShotGrid type %s is not implemented" %
(entity_type, field, sg_type)
)
if not isinstance(item, python_type):
raise ShotgunError(
"%s.%s is of type %s, but data %s is not of type %s" %
(entity_type, field, type(item), sg_type, python_type)
)
# TODO: add check for correct timezone
def _validate_entity_fields(self, entity_type, fields):
self._validate_entity_type(entity_type)
if fields is not None:
valid_fields = set(self._schema[entity_type].keys())
for field in fields:
try:
field2, entity_type2, field3 = field.split(".", 2)
self._validate_entity_fields(entity_type2, [field3])
except ValueError:
if field not in valid_fields and field not in ("type", "id"):
raise ShotgunError("%s is not a valid field for entity %s" % (field, entity_type))
def _get_default_value(self, entity_type, field):
field_info = self._schema[entity_type][field]
if field_info["data_type"]["value"] == "multi_entity":
default_value = []
else:
default_value = field_info["properties"]["default_value"]["value"]
return default_value
def _get_new_row(self, entity_type):
row = {"type": entity_type, "__retired": False}
for field in self._schema[entity_type]:
field_info = self._schema[entity_type][field]
if field_info["data_type"]["value"] == "multi_entity":
default_value = []
else:
default_value = field_info["properties"]["default_value"]["value"]
row[field] = default_value
return row
def _compare(self, field_type, lval, operator, rval):
"""
Compares a field using the operator and value provide by the filter.
:param str field_type: Type of the field we are operating on.
:param lval: Value inside that field. Can be of any type: datetime, date, int, str, bool, etc.
:param str operator: Name of the operator to use.
:param rval: The value following the operator in a filter.
:returns: The result of the operator that was applied.
:rtype: bool
"""
# If we have a list of scalar values
if isinstance(lval, list) and field_type != "multi_entity":
# Compare each one. If one matches the predicate we're good!
return any((self._compare(field_type, sub_val, operator, rval)) for sub_val in lval)
if field_type == "checkbox":
if operator == "is":
return lval == rval
elif operator == "is_not":
return lval != rval
elif field_type in ("float", "number", "date", "date_time"):
if operator == "is":
return lval == rval
elif operator == "is_not":
return lval != rval
elif operator == "less_than":
return lval < rval
elif operator == "greater_than":
return lval > rval
elif operator == "between":
return lval >= rval[0] and lval <= rval[1]
elif operator == "not_between":
return lval < rval[0] or lval > rval[1]
elif operator == "in":
return lval in rval
elif field_type in ("list", "status_list"):
if operator == "is":
return lval == rval
elif operator == "is_not":
return lval != rval
elif operator == "in":
return lval in rval
elif operator == "not_in":
return lval not in rval
elif field_type == "entity_type":
if operator == "is":
return lval == rval
elif field_type == "text":
if operator == "is":
return lval == rval
elif operator == "is_not":
return lval != rval
elif operator == "in":
return lval in rval
elif operator == "contains":
return rval in lval
elif operator == "not_contains":
return lval not in rval
elif operator == "starts_with":
return lval.startswith(rval)
elif operator == "ends_with":
return lval.endswith(rval)
elif operator == "not_in":
return lval | |
# e means error.
if (self.show_stream and self.augmented) or self.show_stream:
self.mark_object(self.current_frame, ex, ey, ew, eh, 30, 50, (255, 0, 0), 2)
self.target_locker.check_error(ex, ey, ew, eh)
break
if self.__check_loop_ended(stop_thread):
break
self.stop_recording()
self.is_watching = False
def detect_initiate(self, stop_thread, format="bgr"):
"""Method to serve as the entry point to detection, recognition and tracking features of t_system's vision ability.
Args:
stop_thread: Stop flag of the tread about terminating it outside of the function's loop.
format: Color space format.
"""
self.is_watching = True
detected_boxes = []
rgb = None
self.target_locker.scan(False)
for frame in self.camera.capture_continuous(self.raw_capture, format=format, use_video_port=True):
self.current_frame = frame.array
self.__truncate_stream()
rgb, detected_boxes = self.detect_things(self.current_frame)
if not detected_boxes:
gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
if (self.show_stream and self.augmented) or self.show_stream:
cv2.putText(gray, "Scanning...", (int(self.frame_width - self.frame_width * 0.2), int(self.frame_height * 0.1)), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (200, 0, 0), 2)
# self.__show_frame(gray, "Initiate")
if self.__check_loop_ended(lambda: False):
break
else:
self.target_locker.scan_thread_stop = True
break
if self.__check_loop_ended(lambda: False) or self.stop_thread:
self.target_locker.scan_thread_stop = True
break
self.is_watching = False
return rgb, detected_boxes
def scan(self, stop_thread, resolution=3):
"""Method to provide the scanning around for security mode of T_System.
Args:
stop_thread: Stop flag of the tread about terminating it outside of the function's loop.
resolution: angle's step width between 0 - 180 degree.
"""
while True:
if stop_thread():
break
for angle in range(0, 180, resolution):
if stop_thread():
break
self.target_locker.pan.move(float(angle), 180.0)
angle_for_ellipse_move = calc_ellipsoidal_angle(float(angle) - 90, 180.0, 75.0) # 75 degree is for physical conditions.
self.target_locker.tilt.move(angle_for_ellipse_move, 75.0) # last parameter not used for both funcs
time.sleep(0.1)
for angle in range(180, 0, resolution * -1):
if stop_thread():
break
self.target_locker.pan.move(float(angle), 180.0)
angle_for_ellipse_move = calc_ellipsoidal_angle(float(angle) - 90, 180.0, 75.0)
self.target_locker.tilt.move(angle_for_ellipse_move, 75.0) # last parameter not used for both funcs
time.sleep(0.1)
def reload_target_locker(self, ai=None, non_moving_target=None, arm_expansion=None, current_angles=None):
"""The top-level method to set locking system's locker of Vision as given AI and target object status parameters.
Args:
ai (str): AI type that will using during locking the target.
non_moving_target (bool): Non-moving target flag.
arm_expansion (bool): Flag for the loading locker as expansion of the T_System's robotic arm.
current_angles (list): Current angles of the target locking system's collimators.
"""
if current_angles is None:
current_angles = [None, None]
return self.target_locker.load_locker(ai, non_moving_target, arm_expansion, current_angles)
def serve_frame_online(self):
"""The top-level method to provide the serving video stream online for sending Flask framework based remote_ui.
"""
is_success, im_buf_arr = cv2.imencode(".jpg", self.current_frame)
return im_buf_arr.tobytes() # image in byte format.
def track_focused_point(self):
"""Method to provide the tracking predetermined non-moving target according to with locking_system's current position for track mode of T_System.
"""
pass
def __show_frame(self, frame, window="Frame"):
"""Method to show the captured frame.
Args:
frame: Frame matrix in bgr format.
window: Name of the frame showing window.
"""
if (self.show_stream and self.augmented) or self.show_stream:
# show the frame
cv2.imshow(window, frame)
def __truncate_stream(self):
"""Method to clear the stream in preparation for the next frame.
"""
self.raw_capture.seek(0)
self.raw_capture.truncate()
def __check_loop_ended(self, stop_thread):
"""Method to control end of the vision loop.
Args:
stop_thread: Stop flag of the tread about terminating it outside of the function's loop.
"""
# if the `q` key was pressed, break from the loop
key = cv2.waitKey(1) & 0xFF
if (key == ord("q") or stop_thread()) and (self.augmented or self.active_threads):
logger.info("All threads killed. In progress...")
return True
elif (key == ord("q") or stop_thread()) and not self.augmented:
cv2.destroyAllWindows()
self.release_members()
return True
def __detect_with_hog_or_cnn(self, frame):
"""Method to detecting FACES with hog or cnn methoda.
Args:
frame: Frame matrix in bgr format.
"""
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# rgb = cv2.resize(rgb, (0, 0), fx=0.25, fy=0.25)
# r = frame.shape[1] / float(rgb.shape[1])
detected_boxes = face_recognition.face_locations(rgb, model=self.detection_model)
return rgb, detected_boxes
def __detect_with_haarcascade(self, frame):
"""Method to detecting objects with haarcascade method.
Args:
frame: Frame matrix in bgr format.
"""
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# gray = cv2.equalizeHist(gray)
reworked_boxes = []
for object_cascade in self.object_cascades:
detected_boxes = object_cascade.detectMultiScale(gray, 1.3, 5)
# Following list's member change is for face recognition format compatibility.
for box in detected_boxes:
# box[3] is x,
# box[0] is y,
# box[1] is x + w,
# box[2] is y + h.
reworked_boxes.append((box[1], box[0] + box[2], box[1] + box[3], box[0]))
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # For __recognize_things compatibility.
return rgb, reworked_boxes
def __recognize_things(self, rgb, boxes):
"""Method to recognizing objects with encodings pickle files.
Args:
rgb: Frame matrix in rgb format.
boxes: Tuple variable of locations of detected objects.
"""
encodings = face_recognition.face_encodings(rgb, boxes)
names = []
for encoding in encodings:
# attempt to match each face in the input image to our known encodings
matches = face_recognition.compare_faces(self.recognition_data["encodings"], encoding)
name = "Unknown"
# check to see if we have found a match
if True in matches:
# find the indexes of all matched faces then initialize a
# dictionary to count the total number of times each face
# was matched
matched_idxs = [i for (i, b) in enumerate(matches) if b]
counts = {}
# loop over the matched indexes and maintain a count for
# each recognized face
for i in matched_idxs:
name = self.recognition_data["names"][i]
counts[name] = counts.get(name, 0) + 1
# determine the recognized face with the largest number
# of votes (note: in the event of an unlikely tie Python
# will select first entry in the dictionary)
name = max(counts, key=counts.get)
# update the list of names
names.append(name)
return names
def __create_tracker_by_name(self):
"""Method to creating a tracker object via type that is chosen by the user.
"""
if self.tracker_type == self.tracker_types[0]:
tracker = cv2.TrackerBoosting_create()
elif self.tracker_type == self.tracker_types[1]:
tracker = cv2.TrackerMIL_create()
elif self.tracker_type == self.tracker_types[2]:
tracker = cv2.TrackerKCF_create()
elif self.tracker_type == self.tracker_types[3]:
tracker = cv2.TrackerTLD_create()
elif self.tracker_type == self.tracker_types[4]:
tracker = cv2.TrackerMedianFlow_create()
elif self.tracker_type == self.tracker_types[5]:
tracker = cv2.TrackerGOTURN_create()
elif self.tracker_type == self.tracker_types[6]:
tracker = cv2.TrackerMOSSE_create()
elif self.tracker_type == self.tracker_types[7]:
tracker = cv2.TrackerCSRT_create()
else:
tracker = None
logger.error('Incorrect tracker name')
logger.info('Available trackers are:')
for t in self.tracker_types:
logger.info(t)
return tracker
@staticmethod
def __relocate_detected_coords(detected_boxes):
"""Method to relocating members of detected boxes from given shape to wanted shape.
Args:
detected_boxes (tuple): Top left and bottom right coordinates of the detected thing.
"""
reworked_boxes = []
for box in detected_boxes:
# box[3] is x,
# box[0] is y,
# box[1] is x + w,
# box[2] is y + h.
reworked_boxes.append((box[3], box[0], box[1] - box[3], box[2] - box[0]))
return reworked_boxes
def change_tracked_thing(self, file):
"""The top-level method to changing tracking objects.
Args:
file: The haarcascade trained xml file.
"""
self.object_cascades = []
ccade_xml_file = T_SYSTEM_PATH + "/haarcascade/" + file + ".xml"
self.object_cascades.append(cv2.CascadeClassifier(ccade_xml_file))
self.decider.set_db(file)
@staticmethod
def __mark_as_single_rect(frame, x, y, w, h, radius, physically_distance, color, thickness):
"""Method to set mark_object method as drawing method with OpenCV's basic rectangle.
Args:
frame: Frame matrix.
x : the column number of the top left point of found object from the detection method.
y : the row number of the top left point of found object from the detection method.
w : the width of found object from the detection method.
h : the height of found object from the detection method.
radius: Radius of the aim.
physically_distance: Physically distance of the targeted object as pixel count.
color (tuple): Color of the drawing shape. In RGB Space.
thickness (int): Thickness of the drawing shape.
"""
cv2.rectangle(frame, (x, y), (x + w, y + h), color, thickness)
def __mark_as_partial_rect(self, frame, x, y, w, h, radius, physically_distance, color, thickness):
"""Method to set mark_object method as drawing method with aimer's partial rect.
Args:
frame: Frame matrix.
x : the column number of the top left point of found object from the detection method.
y : the row number of the top left point of found object from the detection method.
w : the width of found object from the detection method.
h : the height of found object from the detection method.
radius: Radius of the aim.
physically_distance: Physically distance of the targeted object as pixel count.
color (tuple): Color of the drawing shape. In RGB | |
# some qsub error, e.g. maybe wrong queue specified, don't have permission to submit, etc...
msg = ('Error in job submission with PBS file {f} and cmd {c}\n'.format(f=script_file, c=cmd) +
'The error response reads: {}'.format(process.stderr.read()))
raise self.Error(msg)
except Exception as exc:
# random error, e.g. no qsub on machine!
raise self.Error("Running qsub caused an error...\n%s" % str(exc))
def get_njobs_in_queue(self, username=None):
return None
# Initialize username
if username is None:
username = getpass.getuser()
# run qstat
try:
qstat = Command(['qstat', '-a', '-u', username]).run(timeout=5)
# parse the result
if qstat.status == 0:
# lines should have this form
# '1339044.sdb username queuename 2012-02-29-16-43 20460 -- -- -- 00:20 C 00:09'
# count lines that include the username in it
# TODO: only count running or queued jobs. or rather, *don't* count jobs that are 'C'.
outs = qstat.output.split('\n')
njobs = len([line.split() for line in outs if username in line])
logger.info('The number of jobs currently in the queue is: {}'.format(njobs))
return njobs
except:
# there's a problem talking to qstat server?
print(qstat.output.split('\n'))
err_msg = ('Error trying to get the number of jobs in the queue using qstat service\n' +
'The error response reads: {}'.format(qstat.error))
logger.critical(boxed(err_msg))
return None
# no need to raise an error, if False is returned the fixer may try something else, we don't need to kill the
# scheduler just yet
def exclude_nodes(self, nodes):
logger.warning('exluding nodes, not implemented yet pbs')
return False
def increase_mem(self, factor=1):
base_increase = 2001
new_mem = self.qparams["pvmem"] + factor*base_increase
if new_mem < self.LIMITS['mem']:
self.set_mem_per_cpu(new_mem)
print('set mem to ', new_mem)
return True
else:
logger.warning('could not increase mem further')
print('new_mem reached max ', new_mem)
return False
def increase_time(self, factor=1.5):
days, hours, minutes = 0, 0, 0
try:
# a pbe time parser [HH:MM]:SS
# feel free to pull this out and mak time in minutes always
n = str(self.qparams['time']).count(':')
if n == 0:
hours = int(float(self.qparams['time']))
elif n > 1:
hours = int(float(self.qparams['time'].split(':')[0]))
minutes = int(float(self.qparams['time'].split(':')[1]))
time = hours * 60 + minutes
time *= factor
if time < self.LIMITS['time']:
self.qparams['time'] = str(int(time / 60)) + ':' + str(int(time - 60 * int(time / 60))) + ':00'
logger.info('increased time to %s minutes' % time)
return True
else:
raise QueueAdapterError
except (KeyError, QueueAdapterError):
return False
def increase_cpus(self, factor):
base_increase = 12
new_cpus = self.qparams['select'] + factor * base_increase
if new_cpus < self.LIMITS['max_select']:
self.qparams['select'] = new_cpus
return True
else:
logger.warning('increasing cpus reached the limit')
return False
class TorqueAdapter(PbsProAdapter):
"""Adapter for Torque."""
QTYPE = "torque"
QTEMPLATE = """\
#!/bin/bash
#PBS -A $${account}
#PBS -N $${job_name}
#PBS -l walltime=$${walltime}
#PBS -q $${queue}
#PBS -l model=$${model}
#PBS -l place=$${place}
#PBS -W group_list=$${group_list}
####PBS -l select=$${select}:ncpus=1:vmem=$${vmem}mb:mpiprocs=1:ompthreads=$${ompthreads}
####PBS -l pvmem=$${pvmem}mb
#PBS -l pmem=$${pmem}mb
####PBS -l mppwidth=$${mppwidth}
#PBS -l nodes=$${nodes}:ppn=$${ppn}
#PBS -M $${mail_user}
#PBS -m $${mail_type}
# Submission environment
#PBS -V
#PBS -o $${_qout_path}
#PBS -e $${_qerr_path}
"""
LIMITS = {'max_total_tasks': 3888, 'time': 48, 'max_nodes': 16}
def set_mem_per_cpu(self, mem_mb):
"""Set the memory per core in Megabytes"""
self.qparams["pmem"] = mem_mb
self.qparams["mem"] = mem_mb
@property
def mpi_procs(self):
"""Number of MPI processes."""
return self.qparams.get("nodes", 1)*self.qparams.get("ppn", 1)
def set_mpi_procs(self, mpi_procs):
"""Set the number of CPUs used for MPI."""
self.qparams["nodes"] = 1
self.qparams["ppn"] = mpi_procs
def increase_nodes(self, factor):
base_increase = 1
new_nodes = self.qparams['nodes'] + factor * base_increase
if new_nodes < self.LIMITS['max_nodes']:
self.qparams['nodes'] = new_nodes
return True
else:
logger.warning('increasing cpus reached the limit')
return False
class SGEAdapter(AbstractQueueAdapter):
"""
Adapter for Sun Grid Engine (SGE) task submission software.
"""
QTYPE = "sge"
QTEMPLATE = """\
#!/bin/bash
#$ -A $${account}
#$ -N $${job_name}
#$ -l h rt=$${walltime}
#$ -pe $${queue} $${ncpus}
#$ -cwd
#$ -j y
#$ -m n
#$ -e $${_qerr_path}
#$ -o $${_qout_path}
#$ -S /bin/bash
"""
@property
def mpi_procs(self):
"""Number of CPUs used for MPI."""
return self.qparams.get("ncpus", 1)
def set_mpi_procs(self, mpi_procs):
"""Set the number of CPUs used for MPI."""
self.qparams["ncpus"] = mpi_procs
def set_omp_threads(self, omp_threads):
"""Set the number of OpenMP threads."""
self.omp_env["OMP_NUM_THREADS"] = omp_threads
warnings.warn("set_omp_threads not availabe for %s" % self.__class__.__name__)
def set_mem_per_cpu(self, mem_mb):
"""Set the memory per CPU in Megabytes"""
raise NotImplementedError("")
#self.qparams["mem_per_cpu"] = mem_mb
## Remove mem if it's defined.
#self.qparams.pop("mem", None)
def cancel(self, job_id):
return os.system("qdel %d" % job_id)
def submit_to_queue(self, script_file):
"""Submit a job script to the queue."""
if not os.path.exists(script_file):
raise self.Error('Cannot find script file located at: {}'.format(script_file))
# submit the job
try:
cmd = ['qsub', script_file]
process = Popen(cmd, stdout=PIPE, stderr=PIPE)
process.wait()
# grab the returncode. SGE returns 0 if the job was successful
if process.returncode == 0:
try:
# output should of the form
# Your job 1659048 ("NAME_OF_JOB") has been submitted
queue_id = int(process.stdout.read().split(' ')[2])
logger.info('Job submission was successful and queue_id is {}'.format(queue_id))
except:
# probably error parsing job code
logger.warning("Could not parse job id following qsub...")
queue_id = None
finally:
return process, queue_id
else:
# some qsub error, e.g. maybe wrong queue specified, don't have permission to submit, etc...
msg = ('Error in job submission with PBS file {f} and cmd {c}\n'.format(f=script_file, c=cmd) +
'The error response reads: {}'.format(process.stderr.read()))
raise self.Error(msg)
except:
# random error, e.g. no qsub on machine!
raise self.Error("Running qsub caused an error...")
def get_njobs_in_queue(self, username=None):
# Initialize username
if username is None:
username = getpass.getuser()
# run qstat
qstat = Command(['qstat', '-u', username]).run(timeout=5)
# parse the result
if qstat.status == 0:
# lines should contain username
# count lines that include the username in it
# TODO: only count running or queued jobs. or rather, *don't* count jobs that are 'C'.
outs = qstat.output.split('\n')
njobs = len([line.split() for line in outs if username in line])
logger.info('The number of jobs currently in the queue is: {}'.format(njobs))
return njobs
# there's a problem talking to qstat server?
err_msg = ('Error trying to get the number of jobs in the queue using qstat service\n' +
'The error response reads: {}'.format(qstat.error))
logger.critical(err_msg)
return None
def exclude_nodes(self, nodes):
"""
Method to exclude nodes in the calculation
"""
raise NotImplementedError("exclude_nodes")
def increase_mem(self, factor):
"""
Method to increase the amount of memory asked for, by factor.
"""
raise NotImplementedError("increase_mem")
def increase_time(self, factor):
"""
Method to increase the available wall time asked for, by factor.
"""
raise NotImplementedError("increase_time")
def increase_cpus(self, factor):
raise NotImplementedError("increase_cpus")
class MOABAdapter(AbstractQueueAdapter):
"""https://computing.llnl.gov/tutorials/moab/"""
QTYPE = "moab"
QTEMPLATE = """\
#!/bin/bash
#MSUB -a $${eligible_date}
#MSUB -A $${account}
#MSUB -c $${checkpoint_interval}
#MSUB -l feature=$${feature}
#MSUB -l gres=$${gres}
#MSUB -l nodes=$${nodes}
#MSUB -l partition=$${partition}
#MSUB -l procs=$${procs}
#MSUB -l ttc=$${ttc}
#MSUB -l walltime=$${walltime}
#MSUB -l $${resources}
#MSUB -p $${priority}
#MSUB -q $${queue}
#MSUB -S $${shell}
#MSUB -N $${job_name}
#MSUB -v $${variable_list}
#MSUB -o $${_qout_path}
#MSUB -e $${_qerr_path}
"""
@property
def mpi_procs(self):
"""Number of CPUs used for MPI."""
return self.qparams.get("procs", 1)
def set_mpi_procs(self, mpi_procs):
"""Set the number of CPUs used for MPI."""
self.qparams["procs"] = mpi_procs
def set_omp_threads(self, omp_threads):
"""Set the number of OpenMP threads."""
self.omp_env["OMP_NUM_THREADS"] = omp_threads
def cancel(self, job_id):
return os.system("canceljob %d" % job_id)
def submit_to_queue(self, script_file, submit_err_file="sbatch.err"):
"""Submit a job script to the queue."""
if not os.path.exists(script_file):
raise self.Error('Cannot find script file located at: {}'.format(script_file))
submit_err_file = os.path.join(os.path.dirname(script_file), submit_err_file)
# submit the job
try:
cmd = ['msub', script_file]
process = Popen(cmd, stdout=PIPE, stderr=PIPE)
# write the err output to file, a error parser may read it and a fixer may know what to do ...
with open(submit_err_file, mode='w') as f:
f.write('msub submit process stderr:')
f.write(str(process.stderr.read()))
f.write('qparams:')
f.write(str(self.qparams))
process.wait()
# grab the returncode. MOAB returns 0 if the job was successful
if process.returncode == 0:
try:
# output should be the queue_id
queue_id = int(process.stdout.read().split()[0])
logger.info('Job submission was successful and queue_id is {}'.format(queue_id))
except:
# probably error parsing job code
queue_id = None
logger.warning('Could not parse job id following msub...')
finally:
return process, queue_id
else:
# some qsub error, e.g. maybe wrong queue specified, don't have permission to submit, etc...
err_msg = ("Error in job submission with MOAB file {f} and cmd {c}\n".format(f=script_file, c=cmd) +
"The error response reads: {c}".format(c=process.stderr.read()))
raise self.Error(err_msg)
except Exception as details:
msg = 'Error while submitting job:\n' + str(details)
logger.critical(msg)
with open(submit_err_file, mode='a') as f:
f.write(msg)
try:
print('sometimes we land here, no idea what is happening ... Michiel')
print("details:\n", details, "cmd\n", cmd, "\nprocess.returcode:", process.returncode)
except:
pass
# random error, e.g. no qsub on machine!
| |
| | | as it gives moire’-free results. But when the image |
| | | is zoomed, it is similar to the INTER_NEAREST method. |
+-----+-----------------+-------------------------------------------------------+
|(4) | INTER_LANCZOS4 | Lanczos interpolation over 8x8 pixel neighborhood |
+-----+-----------------+-------------------------------------------------------+
:param mmode: (None) mmode to create mapped file. if mpath is specified loads image, converts
to mapped file and then loads mapping file with mode {None, 'r+', 'r', 'w+', 'c'}
(it is slow for big images). If None, loads mapping file to memory (useful to keep
image copy for session even if original image is deleted or modified).
:param mpath: (None) path to create mapped file.
None, do not create mapping file
"", uses path directory;
"*", uses working directory;
else, uses specified directory.
.. note:: If mmode is None and mpath is given it creates mmap file but loads from it to memory.
It is useful to create physical copy of data to keep loading from (data can be reloaded
even if original file is moved or deleted).
"""
def __init__(self, path, flag=0, dsize=None, dst=None, fx=None, fy=None,
interpolation=None, mmode=None, mpath=None, throw=True):
self.path = path
self._flag = flag
self._dsize = dsize
self._dst = dst
self._fx = fx
self._fy = fy
self._interpolation = interpolation
self._mmode = mmode
self._mpath = mpath
self._throw = throw
self.load = loadFunc(flag, dsize, dst, fx, fy,
interpolation, mmode, mpath, throw)
#i = loadFunc.__doc__.find(":param")
#__init__.__doc__ = loadFunc.__doc__[:i] + __init__.__doc__ + loadFunc.__doc__[i:] # builds documentation dynamically
# del i # job done, delete
def __call__(self):
return self.load(self.path)
def getConfiguration(self, **kwargs):
"""
Get Custom configuration from default configuration.
:param kwargs: keys to customize default configuration.
If no key is provided default configuration is returned.
:return: dictionary of configuration
"""
temp = {"flag": self._flag, "dsize": self._dsize, "dst": self._dst, "fx": self._fx, "fy": self._fy,
"interpolation": self._interpolation, "mmode": self._mmode, "mpath": self._mpath, "throw": self._throw}
if kwargs:
temp.update(kwargs)
return temp
def temp(self, **kwargs):
"""
loads from temporal loader created with customized and default parameters.
:param kwargs: keys to customize default configuration.
:return: loaded image.
"""
if len(kwargs) == 1 and "path" in kwargs:
return self.load(kwargs["path"])
path = kwargs.get("path", self.path) # get path
# build a new loader and load path
return loadFunc(**self.getConfiguration(**kwargs))(path)
class PathLoader(MutableSequence):
"""
Class to standardize loading images from list of paths and offer lazy evaluations.
:param fns: list of paths
:param loader: path loader (loadcv,loadsfrom, or function from loadFunc)
Also see:: :func:`loadcv`, :func:`loadsfrom`, :func:`loadFunc`
Example::
fns = ["/path to/image 1.ext","/path to/image 2.ext"]
imgs = pathLoader(fns)
print imgs[0] # loads image in path 0
print imgs[1] # loads image in path 1
"""
def __init__(self, fns=None, loader=None):
# create factory functions
self._fns = fns or []
self._loader = loader or loadFunc()
def __call__(self):
"""
if called returns the list of paths
"""
return self._fns
def __getitem__(self, key):
return self._loader(self._fns[key])
def __setitem__(self, key, value):
self._fns[key] = value
def __delitem__(self, key):
del self._fns[key]
def __len__(self):
return len(self._fns)
def insert(self, index, value):
self._fns.insert(index, value)
class LoaderDict(ResourceManager):
"""
Class to standardize loading objects and manage memory efficiently.
:param loader: default loader for objects (e.g. load from file or create instance object)
:param maxMemory: (None) max memory in specified unit to keep in check optimization (it does
not mean that memory never surpasses maxMemory).
:param margin: (0.8) margin from maxMemory to trigger optimization.
It is in percentage of maxMemory ranging from 0 (0%) to maximum 1 (100%).
So optimal memory is inside range: maxMemory*margin < Memory < maxMemory
:param unit: (MB) maxMemory unit, it can be GB (Gigabytes), MB (Megabytes), B (bytes)
:param all: if True used memory is from all alive references,
if False used memory is only from keptAlive references.
:param config: (Not Implemented)
"""
def __init__(self, loader=None, maxMemory=None, margin=0.8,
unit="MB", all=True, config=None):
super(LoaderDict, self).__init__(maxMemory, margin, unit, all)
# create factory functions
#if config is None: from config import MANAGER as config
#self._config = config
self._default_loader = loader or loadFunc()
def register(self, key, path=None, method=None):
if method is not None:
def func(): return method(func.path)
else:
def func(): return self._default_loader(func.path)
func.path = path
super(LoaderDict, self).register(key=key, method=func)
def try_loads(fns, func=cv2.imread, paths=None, debug=False, addpath=False):
"""
Try to load images from paths.
:param fns: list of file names
:param func: loader function
:param paths: paths to try. By default it loads working dir and test path
:param debug: True to show debug messages
:param addpath: add path as second argument
:return: image else None
"""
default = ("", str(MANAGER["TESTPATH"]))
if paths is None:
paths = []
if isinstance(paths, basestring):
paths = [paths]
paths = list(paths)
for i in default:
if i not in paths:
paths.append(i)
for fn in fns:
for path in paths:
try:
if path[-1] not in ("/", "\\"): # ensures path
path += "/"
except:
pass
path += fn
im = func(path) # foreground
if im is not None:
if debug:
print(path, " Loaded...")
if addpath:
return im, path
return im
def hist_match(source, template, alpha=None):
"""
Adjust the pixel values of an image to match those of a template image.
:param source: image to transform colors to template
:param template: template image ()
:param alpha:
:return: transformed source
"""
# theory https://en.wikipedia.org/wiki/Histogram_matching
# explanation http://dsp.stackexchange.com/a/16175 and
# http://fourier.eng.hmc.edu/e161/lectures/contrast_transform/node3.html
# based on implementation http://stackoverflow.com/a/33047048/5288758
# see http://www.mathworks.com/help/images/ref/imhistmatch.html
if len(source.shape) > 2:
matched = np.zeros_like(source)
for i in range(3):
matched[:, :, i] = hist_match(source[:, :, i], template[:, :, i])
return matched
else:
oldshape = source.shape
source = source.ravel()
template = template.ravel()
# get the set of unique pixel values and their corresponding indices and
# counts
s_values, bin_idx, s_counts = np.unique(source, return_inverse=True,
return_counts=True)
t_values, t_counts = np.unique(template, return_counts=True)
# take the cumsum of the counts and normalize by the number of pixels to
# get the empirical cumulative distribution functions for the source and
# template images (maps pixel value --> quantile)
s_quantiles = np.cumsum(s_counts).astype(np.float64)
s_quantiles /= s_quantiles[-1]
t_quantiles = np.cumsum(t_counts).astype(np.float64)
t_quantiles /= t_quantiles[-1]
# interpolate linearly to find the pixel values in the template image
# that correspond most closely to the quantiles in the source image
interp_t_values = np.interp(s_quantiles, t_quantiles, t_values)
return interp_t_values[bin_idx].reshape(oldshape) # reconstruct image
############################# GETCOORS ###################################
# http://docs.opencv.org/master/db/d5b/tutorial_py_mouse_handling.html
# http://docs.opencv.org/modules/highgui/doc/qt_new_functions.html
class ImCoors(object):
"""
Image's coordinates class.
Example::
a = ImCoors(np.array([(116, 161), (295, 96), (122, 336), (291, 286)]))
print a.__dict__
print "mean depend on min and max: ", a.mean
print a.__dict__
print "after mean max has been already been calculated: ", a.max
a.data = np.array([(116, 161), (295, 96)])
print a.__dict__
print "mean and all its dependencies are processed again: ", a.mean
"""
def __init__(self, pts, dtype=FLOAT, deg=False):
"""
Initiliazes ImCoors.
:param pts: list of points
:param dtype: return data as dtype. Default is config.FLOAT
"""
self._pts = pts # supports bigger numbers
self._dtype = dtype
self._deg = deg
@property
def pts(self):
return self._pts
@pts.setter
def pts(self, value):
getattr(self, "__dict__").clear()
self._pts = value
@pts.deleter
def pts(self):
raise Exception("Cannot delete attribute")
@property
def dtype(self):
return self._dtype
@dtype.setter
def dtype(self, value):
getattr(self, "__dict__").clear()
self._dtype = value
@dtype.deleter
def dtype(self):
raise Exception("Cannot delete attribute")
# DATA METHODS
def __len__(self):
return len(self._pts)
@cache
def max(self):
"""
Maximum in each axis.
:return: x_max, y_max
"""
#self.max_x, self.max_y = np.max(self.data,0)
return tuple(np.max(self._pts, 0))
@cache
def min(self):
"""
Minimum in each axis.
:return: x_min, y_min
"""
#self.min_x, self.min_y = np.min(self.data,0)
return tuple(np.min(self._pts, 0))
@cache
def rectbox(self):
"""
Rectangular box enclosing points (origin and end point or rectangle).
:return: (x0,y0),(x,y)
"""
return (self.min, self.max)
@cache
def boundingRect(self):
"""
Rectangular box dimensions enclosing points.
example::
P = np.ones((400,400))
a = ImCoors(np.array([(116, 161), (295, 96), (122, 336), (291, 286)]))
x0,y0,w,h = a.boundingRect
P[y0:y0+h,x0:x0+w] = 0
:return: x0,y0,w,h
"""
return cv2.boundingRect(self._pts)
@cache
def minAreaRect(self):
return cv2.minAreaRect(self._pts)
@cache
def rotatedBox(self):
"""
Rotated rectangular box enclosing points.
:return: 4 points.
"""
try: # opencv 2
return self._dtype(cv2.cv.BoxPoints(self.minAreaRect))
except AttributeError: # opencv 3
return self._dtype(cv2.boxPoints(self.minAreaRect))
@cache
def boxCenter(self):
"""
Mean in each axis.
:return: x_mean, y_mean
"""
#self.mean_x = (self.max_x+self.min_x)/2
#self.mean_y = (self.max_y+self.min_y)/2
xX, xY = self.max
nX, nY = self.min
| |
import time
import argparse
from copy import deepcopy
from progress.bar import IncrementalBar
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import utils as vutils
from itertools import chain
from gan.generator import MuseGenerator
from gan.critic import MuseCritic
from gan.utils import initialize_weights, Normal
from criterion import WassersteinLoss, GradientPenalty
def copy_G_params(model):
flatten = deepcopy(list(p.data for p in model.parameters()))
return flatten
def load_params(model, new_param):
for p, new_p in zip(model.parameters(), new_param):
p.data.copy_(new_p)
def get_item(pred):
return pred.mean().item()
dist = Normal()
class MuseGAN():
def __init__(self,
c_dimension=10,
z_dimension=32,
g_channels=1024,
g_features=1024,
c_channels=128,
c_features=1024,
g_lr=0.001,
c_lr=0.001,
device='cpu'):
self.c_dim = c_dimension
self.z_dim = z_dimension
self.device = device
self.one_hot = True
# generator and optimizer
self.generator = MuseGenerator(c_dimension = c_dimension,
z_dimension = z_dimension,
hid_channels = g_channels,
hid_features = g_features,
out_channels = 1).to(device)
self.generator = self.generator.apply(initialize_weights)
self.g_optimizer = torch.optim.Adam(self.generator.parameters(),
lr=g_lr, betas=(0.5, 0.9))
# critic and optimizer
self.critic = MuseCritic(c_dimension = c_dimension,
hid_channels = c_channels,
hid_features = c_features,
out_features = 1).to(device)
self.critic = self.critic.apply(initialize_weights)
self.c_optimizer = torch.optim.Adam(self.critic.parameters(),
lr=c_lr, betas=(0.5, 0.9))
self.opt_info = optim.Adam(chain(self.generator.parameters(), self.critic.pred_c.parameters()), lr=(g_lr+c_lr)/2, betas=(0.5, 0.99))
self.running_avg_g = None
self.real_images = None
self.prob_c = False
self.recon_weight = 1.0
self.onehot_weight = 1.0
# loss functions and gradient penalty (critic is wasserstein-like gan)
self.g_criterion = WassersteinLoss().to(device)
self.c_criterion = WassersteinLoss().to(device)
self.c_penalty = GradientPenalty().to(device)
# dictionary to save history
self.data = {'g_loss':[],
'c_loss':[],
'cf_loss':[],
'cr_loss':[],
'cp_loss':[],
'cs_loss':[],
'o_loss':[]}
print('MuseGAN initialized.')
def generate_random_sample(self, save_path, z=None, c=None, batch_size=16):
backup_para = copy_G_params(self.generator)
load_params(self.generator, self.running_avg_g)
#self.generator.eval()
if self.z_dim > 0 and z is None:
z = torch.randn(batch_size, self.z_dim).to(self.device)
if self.c_dim > 0 and c is None:
c = torch.randn(batch_size, self.c_dim).uniform_(0,1).to(self.device)
#c = torch.randn(1, self.c_dim).uniform_(0,1).repeat(batch_size,1).to(self.device)
with torch.no_grad():
g_img = self.generator(c=c, z=z).cpu()
vutils.save_image(g_img.add_(1).mul_(0.5), save_path.replace(".jpg", "_random.jpg"), pad_value=0)
del g_img
#self.generator.train()
load_params(self.generator, backup_para)
def generate_each_dim(self, save_path, dim=0, z=None, c=None, num_interpolate=10, num_samples=8):
#self.generator.eval()
if self.running_avg_g is not None:
backup_para = copy_G_params(self.generator)
load_params(self.generator, self.running_avg_g)
if self.z_dim > 0 and z is None:
z = torch.randn(num_samples, self.z_dim).to(self.device)
z = z.unsqueeze(1).repeat(1, num_interpolate, 1).view(-1, self.z_dim)
if self.c_dim > 0 and c is None:
c = torch.randn(num_samples, self.c_dim).uniform_(0.2, 0.6).to(self.device)
c = c.unsqueeze(1).repeat(1, num_interpolate, 1) #.view(-1, self.z_dim)
c_line = torch.linspace(0, 1, num_interpolate).to(self.device)
c_line = c_line.unsqueeze(0).repeat(num_samples, 1)
c[:,:,dim] = c_line
c = c.view(-1, self.c_dim)
with torch.no_grad():
g_img = self.generator(c=c, z=z)
vutils.save_image(g_img.add_(1).mul_(0.5), \
save_path.replace(".jpg", "_dim_%d.jpg"%(dim)), pad_value=0,nrow=num_interpolate)
del g_img
if self.running_avg_g is not None:
load_params(self.generator, backup_para)
def neg_log_density(self, sample, params):
constant = torch.Tensor([np.log(2 * np.pi)]).to(self.device)
mu = params[:,:self.c_dim]
logsigma = params[:,self.c_dim:]
inv_sigma = torch.exp(-logsigma)
tmp = (sample - mu) * inv_sigma
return 0.5 * (tmp * tmp + 2 * logsigma + constant)
def sample_hot_c(self, batch_size, c_dim, num_hot=1):
y_onehot = torch.zeros(batch_size, c_dim)
# print("num_hot: ", num_hot)
if num_hot==1:
y = torch.LongTensor(batch_size, 1).random_() % c_dim
# print("y_onehot: ", y_onehot.shape, y_onehot.dtype)
# print("torch.ones_like(y_onehot).to(y_onehot): ", torch.ones_like(y_onehot).to(y_onehot).shape, torch.ones_like(y_onehot).to(y_onehot).dtype)
# print("y: ", y.shape, y.dtype)
# print("torch.ones_like(y): ", torch.ones_like(y).shape, torch.ones_like(y).dtype)
# print("torch.ones_like(y).to(y): ", torch.ones_like(y).to(y).shape, torch.ones_like(y).to(y).dtype)
y_onehot.scatter_(1, y, 1.0)
# print("c_idx: ", y.view(-1).shape, y.view(-1, 1).shape, y.view([-1, 1]).shape)
return y_onehot.to(self.device), y.to(self.device)
else:
for _ in range(num_hot):
y = torch.LongTensor(batch_size,1).random_() % c_dim
y_onehot.scatter_(1, y, torch.ones_like(y).to(y))
return y_onehot.to(self.device)
def sample_z_and_c(self, batch_size, n_iter):
# sample z from Normal distribution
z = None
if self.z_dim > 0:
z = torch.randn(batch_size, 10, self.z_dim).to(self.device)
# sample c alternativaly from uniform and onehot
c_idx = None
if n_iter%4==0 and self.one_hot:
c = torch.Tensor(batch_size, self.c_dim).uniform_(0.2,0.6).to(self.device)
# chosen_section = np.random.randint(0, 10)
choosen_dim = np.random.randint(0, self.c_dim)
c[:, choosen_dim] = 1
c_idx = torch.Tensor(batch_size).fill_(choosen_dim).long().to(self.device)
elif n_iter%2==0 and self.one_hot:
c, c_idx = self.sample_hot_c(batch_size, c_dim=self.c_dim, num_hot=1)
else:
c = torch.Tensor(batch_size, self.c_dim).uniform_(0, 1).to(self.device)
return z, c, c_idx
def compute_gradient_penalty(self, real_images, fake_images):
# Compute gradient penalty
# print("real_images, fake_images: ", real_images.shape, fake_images.shape)
alpha = torch.rand(real_images.size(0), 1, 1, 1, 1).expand_as(real_images).to(self.device)
interpolated = (alpha * real_images + (1 - alpha) * fake_images).clone().detach().requires_grad_(True)
out = self.critic(interpolated)[0]
exp_grad = torch.ones(out.size()).to(self.device)
grad = torch.autograd.grad(outputs=out,
inputs=interpolated,
grad_outputs=exp_grad,
retain_graph=True,
create_graph=True,
only_inputs=True)[0]
grad = grad.view(grad.size(0), -1)
grad_l2norm = torch.sqrt(torch.sum(grad ** 2, dim=1))
d_loss_gp = torch.mean((grad_l2norm - 1) ** 2)
return d_loss_gp
def compute_total_correlation(self):
real_images = torch.cat(self.real_images, dim=0)
batch_size = real_images.size(0)
# print(batch_size)
self.critic.eval()
with torch.no_grad():
c_params = self.critic(real_images)[1]
self.critic.train()
sample_c = dist.sample(params=c_params.view(batch_size, self.c_dim, 2))
_logqc = dist.log_density( sample_c.view(-1, 1, self.c_dim), c_params.view(1, -1, self.c_dim, 2) )
logqc_prodmarginals = (logsumexp(_logqc, dim=1, keepdim=False) - math.log(batch_size)).sum(1)
logqc = (logsumexp(_logqc.sum(2), dim=1, keepdim=False) - math.log(batch_size))
#print( logqc, logqc_prodmarginals )
self.real_images = None
return (logqc - logqc_prodmarginals).mean().item()
def train_step(self, real_image, n_iter):
cfb_loss, crb_loss, cpb_loss, cb_loss = 0, 0, 0, 0
if self.running_avg_g is None:
self.running_avg_g = copy_G_params(self.generator)
batch_size = real_image.size(0)
c_ratio = 5
for _ in range(c_ratio):
### prepare data part
z, c, c_idx = self.sample_z_and_c(batch_size, n_iter)
g_img = self.generator(c=c, z=z)
r_img = real_image.to(self.device)
### critic part
self.critic.zero_grad()
# pred_r, _ = self.critic(r_img)
# pred_f, _ = self.critic(g_img.detach())
# get critic's `fake` loss
fake_pred, _ = self.critic(g_img)
fake_target = - torch.ones_like(fake_pred)
fake_loss = self.c_criterion(fake_pred, fake_target)
# get critic's `real` loss
real_pred, _ = self.critic(r_img)
real_target = torch.ones_like(real_pred)
real_loss = self.c_criterion(real_pred, real_target)
# mix `real` and `fake` melody
realfake = self.alpha * r_img + (1. - self.alpha) * g_img
# get critic's penalty
realfake_pred, _ = self.critic(realfake)
# print("realfake: ", realfake.shape)
# print("realfake_pred: ", realfake_pred.shape)
penalty = self.c_penalty(realfake, realfake_pred)
# sum up losses
closs = fake_loss + real_loss + 10 * penalty
# retain graph
closs.backward(retain_graph=True)
# update critic parameters
self.c_optimizer.step()
# devide by number of critic updates in the loop (5)
cfb_loss += fake_loss.item()/c_ratio
crb_loss += real_loss.item()/c_ratio
cpb_loss += 10* penalty.item()/c_ratio
cb_loss += closs.item()/c_ratio
### prepare data part
z, c, c_idx = self.sample_z_and_c(batch_size, n_iter)
g_img = self.generator(c=c, z=z)
r_img = real_image.to(self.device)
### Generator part
self.generator.zero_grad()
pred_g, _ = self.critic(g_img)
loss_g = -pred_g.mean()
loss_g.backward()
self.g_optimizer.step()
### Mutual Information between c and c' Part
self.generator.zero_grad()
self.critic.zero_grad()
z, c, c_idx = self.sample_z_and_c(batch_size, n_iter)
g_img = self.generator(c=c, z=z)
pred_g, pred_c_params = self.critic(g_img)
# print("c, c_pred: ", c.shape, pred_c_params.shape)
if self.prob_c:
loss_g_recon_c = self.neg_log_density(c, pred_c_params).mean()
else:
loss_g_recon_c = F.l1_loss(pred_c_params, c)
loss_g_onehot = torch.Tensor([0]).to(self.device)
# if n_iter%2==0 and self.one_hot:
# print("cp, c_idx: ", pred_c_params[:,:self.c_dim].shape, c_idx.shape)
if n_iter%4==0 and self.one_hot:
loss_g_onehot = 0.2*F.cross_entropy(pred_c_params[:,:self.c_dim], c_idx.view(-1))
elif n_iter%2==0 and self.one_hot:
loss_g_onehot = 0.8*F.cross_entropy(pred_c_params[:,:self.c_dim], c_idx.view(-1))
loss_info = self.recon_weight * loss_g_recon_c + self.onehot_weight * loss_g_onehot
loss_info.backward()
self.opt_info.step()
for p, avg_p in zip(self.generator.parameters(), self.running_avg_g):
avg_p.mul_(0.999).add_(0.001, p.data)
# print("losses: ", cfb_loss, crb_loss, cpb_loss, cb_loss, loss_g.item(), loss_g_onehot.item(), loss_g_recon_c.item())
return cfb_loss, crb_loss, cpb_loss, cb_loss, loss_g.item(), loss_g_onehot.item(), loss_g_recon_c.item()
def train(self,
dataloader,
epochs=500,
batch_size=64,
display_epoch=10,
device='cpu'):
# alpha parameter for mixing images
self.alpha = torch.rand((batch_size, 1, 1, 1, 1)).requires_grad_().to(device)
for epoch in range(epochs):
ge_loss, ce_loss = 0, 0
cfe_loss, cre_loss, cpe_loss, oe_loss, cse_loss = 0, 0, 0, 0, 0
start = time.time()
bar = IncrementalBar(f'[Epoch {epoch+1}/{epochs}]', max=len(dataloader))
# print("epoch: ", epoch)
for real in dataloader:
# real: real image batch
# print("real: ", real.shape)
cfb_loss, crb_loss, cpb_loss, cb_loss, gb_loss, ob_loss, csb_loss = self.train_step(real, epoch)
"""
real = real.to(device)
# train Critic
cb_loss=0
cfb_loss, crb_loss, cpb_loss = 0, 0, 0
for _ in range(5):
# create random `noises`
cords = torch.randn(batch_size, 32).to(device)
style = torch.randn(batch_size, 32).to(device)
melody = torch.randn(batch_size, 4, 32).to(device)
groove = torch.randn(batch_size, 4, 32).to(device)
# forward to generator
self.c_optimizer.zero_grad()
with torch.no_grad():
fake = self.generator(cords, style, melody, groove).detach()
# get critic's `fake` loss
fake_pred, c_pred = self.critic(fake)
fake_target = - torch.ones_like(fake_pred)
fake_loss = self.c_criterion(fake_pred, fake_target)
# get critic's `real` loss
real_pred = self.critic(real)
real_target = torch.ones_like(real_pred)
real_loss = self.c_criterion(real_pred, real_target)
# mix `real` and `fake` melody
realfake = self.alpha * real + (1. - self.alpha) * fake
# get critic's penalty
realfake_pred = self.critic(realfake)
penalty = self.c_penalty(realfake, realfake_pred)
# sum up losses
closs = fake_loss + real_loss + 10 * penalty
# retain graph
closs.backward(retain_graph=True)
# update critic parameters
self.c_optimizer.step()
# devide by number of critic updates in the loop (5)
cfb_loss += fake_loss.item()/5
crb_loss += real_loss.item()/5
cpb_loss += 10* penalty.item()/5
cb_loss += closs.item()/5
cfe_loss += cfb_loss/len(dataloader)
cre_loss += crb_loss/len(dataloader)
cpe_loss += cpb_loss/len(dataloader)
ce_loss += cb_loss/len(dataloader)
# train generator
self.g_optimizer.zero_grad()
# create random `noises`
cords = torch.randn(batch_size, 32).to(device)
style = torch.randn(batch_size, 32).to(device)
melody = torch.randn(batch_size, 4, 32).to(device)
groove = torch.randn(batch_size, 4, 32).to(device)
# forward to | |
label=ugettext_lazy("Web Apps should use"),
initial=None,
required=False,
choices=(
('stars', ugettext_lazy('Latest starred version')),
('nostars', ugettext_lazy('Highest numbered version (not recommended)')),
),
help_text=ugettext_lazy("Choose whether Web Apps should use the latest starred build or highest numbered "
"build in your application.")
)
def __init__(self, *args, **kwargs):
super(DomainMetadataForm, self).__init__(*args, **kwargs)
if self.project.cloudcare_releases == 'default' or not domain_has_privilege(self.domain, privileges.CLOUDCARE):
# if the cloudcare_releases flag was just defaulted, don't bother showing
# this setting at all
del self.fields['cloudcare_releases']
if not domain_has_privilege(self.domain, privileges.GEOCODER):
del self.fields['default_geocoder_location']
def save(self, request, domain):
res = DomainGlobalSettingsForm.save(self, request, domain)
if not res:
return False
try:
cloudcare_releases = self.cleaned_data.get('cloudcare_releases')
if cloudcare_releases and domain.cloudcare_releases != 'default':
# you're never allowed to change from default
domain.cloudcare_releases = cloudcare_releases
domain.save()
return True
except Exception as e:
logging.exception("couldn't save project settings - error is %s" % e)
return False
def tuple_of_copies(a_list, blank=True):
ret = [(item, item) for item in a_list]
if blank:
ret.insert(0, ('', '---'))
return tuple(ret)
class PrivacySecurityForm(forms.Form):
restrict_superusers = BooleanField(
label=ugettext_lazy("Restrict Dimagi Staff Access"),
required=False,
help_text=ugettext_lazy(
"CommCare support staff sometimes require access "
"to your project space to provide rapid, in-depth support. "
"Checking this box will restrict the degree of support they "
"will be able to provide in the event that you report an issue. "
"You may also miss out on important communications and updates. "
"Regardless of whether this option is checked, "
"Commcare support staff will have access "
"to your billing information and project metadata; "
"and CommCare system administrators will also have direct access "
"to data infrastructure strictly for the purposes of system administration "
"as outlined in our "
'<a href="https://www.dimagi.com/terms/latest/privacy/">Privacy Policy</a>.'
)
)
secure_submissions = BooleanField(
label=ugettext_lazy("Secure submissions"),
required=False,
help_text=ugettext_lazy(mark_safe(
"Secure Submissions prevents others from impersonating your mobile workers."
"This setting requires all deployed applications to be using secure "
"submissions as well. "
"<a href='https://help.commcarehq.org/display/commcarepublic/Project+Space+Settings'>"
"Read more about secure submissions here</a>"))
)
secure_sessions = BooleanField(
label=ugettext_lazy("Shorten Inactivity Timeout"),
required=False,
help_text=ugettext_lazy("All web users on this project will be logged out after {} minutes "
"of inactivity").format(settings.SECURE_TIMEOUT)
)
secure_sessions_timeout = IntegerField(
label=ugettext_lazy("Inactivity Timeout Length"),
required=False,
help_text=ugettext_lazy("Override the default {}-minute length of the inactivity timeout. Has no effect "
"unless inactivity timeout is on. Note that when this is updated, users may need "
"to log out and back in for it to take effect.").format(settings.SECURE_TIMEOUT)
)
allow_domain_requests = BooleanField(
label=ugettext_lazy("Web user requests"),
required=False,
help_text=ugettext_lazy("Allow unknown users to request web access to the domain."),
)
hipaa_compliant = BooleanField(
label=ugettext_lazy("HIPAA compliant"),
required=False,
)
two_factor_auth = BooleanField(
label=ugettext_lazy("Two Factor Authentication"),
required=False,
help_text=ugettext_lazy("All users on this project will be required to enable two factor authentication")
)
strong_mobile_passwords = BooleanField(
label=ugettext_lazy("Require Strong Passwords for Mobile Workers"),
required=False,
help_text=ugettext_lazy("All mobile workers in this project will be required to have a strong password")
)
ga_opt_out = BooleanField(
label=ugettext_lazy("Disable Google Analytics"),
required=False,
)
def __init__(self, *args, **kwargs):
user_name = kwargs.pop('user_name')
domain = kwargs.pop('domain')
super(PrivacySecurityForm, self).__init__(*args, **kwargs)
self.helper = hqcrispy.HQFormHelper(self)
self.helper[0] = twbscrispy.PrependedText('restrict_superusers', '')
self.helper[1] = twbscrispy.PrependedText('secure_submissions', '')
self.helper[2] = twbscrispy.PrependedText('secure_sessions', '')
self.helper[3] = crispy.Field('secure_sessions_timeout')
self.helper[4] = twbscrispy.PrependedText('allow_domain_requests', '')
self.helper[5] = twbscrispy.PrependedText('hipaa_compliant', '')
self.helper[6] = twbscrispy.PrependedText('two_factor_auth', '')
self.helper[7] = twbscrispy.PrependedText('strong_mobile_passwords', '')
self.helper[8] = twbscrispy.PrependedText('ga_opt_out', '')
if not domain_has_privilege(domain, privileges.ADVANCED_DOMAIN_SECURITY):
self.helper.layout.pop(8)
self.helper.layout.pop(7)
self.helper.layout.pop(6)
if not HIPAA_COMPLIANCE_CHECKBOX.enabled(user_name):
self.helper.layout.pop(5)
if not SECURE_SESSION_TIMEOUT.enabled(domain):
self.helper.layout.pop(3)
if not domain_has_privilege(domain, privileges.ADVANCED_DOMAIN_SECURITY):
self.helper.layout.pop(2)
self.helper.all().wrap_together(crispy.Fieldset, 'Edit Privacy Settings')
self.helper.layout.append(
hqcrispy.FormActions(
StrictButton(
_("Update Privacy Settings"),
type="submit",
css_class='btn-primary',
)
)
)
def save(self, domain):
domain.restrict_superusers = self.cleaned_data.get('restrict_superusers', False)
domain.allow_domain_requests = self.cleaned_data.get('allow_domain_requests', False)
domain.secure_sessions = self.cleaned_data.get('secure_sessions', False)
domain.secure_sessions_timeout = self.cleaned_data.get('secure_sessions_timeout', None)
new_two_factor_auth_setting = self.cleaned_data.get('two_factor_auth', False)
if domain.two_factor_auth != new_two_factor_auth_setting and MONITOR_2FA_CHANGES.enabled(domain.name):
from corehq.apps.hqwebapp.utils import monitor_2fa_soft_assert
status = "ON" if new_two_factor_auth_setting else "OFF"
monitor_2fa_soft_assert(False, f'{domain.name} turned 2FA {status}')
domain.two_factor_auth = new_two_factor_auth_setting
domain.strong_mobile_passwords = self.cleaned_data.get('strong_mobile_passwords', False)
secure_submissions = self.cleaned_data.get(
'secure_submissions', False)
apps_to_save = []
if secure_submissions != domain.secure_submissions:
for app in get_apps_in_domain(domain.name):
if app.secure_submissions != secure_submissions:
app.secure_submissions = secure_submissions
apps_to_save.append(app)
domain.secure_submissions = secure_submissions
domain.hipaa_compliant = self.cleaned_data.get('hipaa_compliant', False)
domain.ga_opt_out = self.cleaned_data.get('ga_opt_out', False)
domain.save()
if apps_to_save:
apps = [app for app in apps_to_save if isinstance(app, Application)]
remote_apps = [app for app in apps_to_save if isinstance(app, RemoteApp)]
if apps:
Application.bulk_save(apps)
if remote_apps:
RemoteApp.bulk_save(remote_apps)
return True
class DomainInternalForm(forms.Form, SubAreaMixin):
sf_contract_id = CharField(label="Salesforce Contract ID", required=False)
sf_account_id = CharField(label="Salesforce Account ID", required=False)
initiative = forms.MultipleChoiceField(label="Initiative",
widget=forms.CheckboxSelectMultiple(),
choices=tuple_of_copies(DATA_DICT["initiatives"], blank=False),
required=False)
workshop_region = CharField(
label="Workshop Region",
required=False,
help_text="e.g. US, LAC, SA, Sub-Saharan Africa, Southeast Asia, etc.")
self_started = ChoiceField(
label="Self Started?",
choices=tf_choices('Yes', 'No'),
required=False,
help_text=(
"The organization built and deployed their app themselves. Dimagi may have provided indirect support"
))
is_test = ChoiceField(
label="Real Project",
choices=(('none', 'Unknown'),
('true', 'Test'),
('false', 'Real'),)
)
area = ChoiceField(
label="Sector*",
required=False,
choices=tuple_of_copies(AREA_CHOICES))
sub_area = ChoiceField(
label="Sub-Sector*",
required=False,
choices=tuple_of_copies(SUB_AREA_CHOICES))
organization_name = CharField(
label="Organization Name*",
required=False,
help_text="Quick 1-2 sentence summary of the project.",
)
notes = CharField(label="Notes*", required=False, widget=forms.Textarea)
phone_model = CharField(
label="Device Model",
help_text="Add Web Apps, if this project is using Web Apps as well",
required=False,
)
business_unit = forms.ChoiceField(
label='Business Unit',
choices=tuple_of_copies(BUSINESS_UNITS),
required=False,
)
countries = forms.MultipleChoiceField(
label="Countries",
choices=sorted(list(COUNTRIES.items()), key=lambda x: x[0]),
required=False,
)
commtrack_domain = ChoiceField(
label="CommCare Supply Project",
choices=tf_choices('Yes', 'No'),
required=False,
help_text="This app aims to improve the supply of goods and materials"
)
performance_threshold = IntegerField(
label="Performance Threshold",
required=False,
help_text=(
'The number of forms submitted per month for a user to count as "performing well". '
'The default value is 15.'
)
)
experienced_threshold = IntegerField(
label="Experienced Threshold",
required=False,
help_text=(
"The number of different months in which a worker must submit forms to count as experienced. "
"The default value is 3."
)
)
amplifies_workers = ChoiceField(
label="Service Delivery App",
choices=[(AMPLIFIES_NOT_SET, '* Not Set'), (AMPLIFIES_YES, 'Yes'), (AMPLIFIES_NO, 'No')],
required=False,
help_text=("This application is used for service delivery. Examples: An "
"FLW who uses CommCare to improve counseling and screening of pregnant women. "
"An FLW that uses CommCare Supply to improve their supply of medicines. A teacher "
"who uses CommCare to assess and improve students' performance."
)
)
amplifies_project = ChoiceField(
label="Amplifies Project",
choices=[(AMPLIFIES_NOT_SET, '* Not Set'), (AMPLIFIES_YES, 'Yes'), (AMPLIFIES_NO, 'No')],
required=False,
help_text=("Amplifies the impact of a Frontline Program (FLP). "
"Examples: Programs that use M&E data collected by CommCare. "
"Programs that use CommCare data to make programmatic decisions."
)
)
data_access_threshold = IntegerField(
label="Minimum Monthly Data Accesses",
required=False,
help_text=(
"Minimum number of times project staff are expected to access CommCare data each month. "
"The default value is 20."
)
)
partner_technical_competency = IntegerField(
label="Partner Technical Competency",
required=False,
min_value=1,
max_value=5,
help_text=(
"Please rate the technical competency of the partner on a scale from "
"1 to 5. 1 means low-competency, and we should expect LOTS of basic "
"hand-holding. 5 means high-competency, so if they report a bug it's "
"probably a real issue with CommCareHQ or a really good idea."
),
)
support_prioritization = IntegerField(
label="Support Prioritization",
required=False,
min_value=1,
max_value=3,
help_text=(
"Based on the impact of this project and how good this partner was "
"to work with, how much would you prioritize support for this "
'partner? 1 means "Low. Take your time." You might rate a partner '
'"1" because they\'ve been absolutely terrible to you and low impact. '
'3 means "High priority. Be nice". You might rate a partner "3" '
"because even though they can't afford a PRO plan, you know they "
"are changing the world. Or they are an unusually high priority "
"strategic partner."
),
)
gs_continued_involvement = ChoiceField(
label="GS Continued Involvement",
choices=[(AMPLIFIES_NOT_SET, '* Not Set'), (AMPLIFIES_YES, 'Yes'), (AMPLIFIES_NO, 'No')],
required=False,
help_text=(
"Do you want to continue to be involved in this project? No, please "
"only reach out if absolutely necessary. Yes. I want to see what "
"happens and be kept in the loop."
),
)
technical_complexity = ChoiceField(
label="Technical Complexity",
choices=[(AMPLIFIES_NOT_SET, '* Not Set'), (AMPLIFIES_YES, 'Yes'), (AMPLIFIES_NO, 'No')],
required=False,
help_text=(
"Is this an innovation project involving unusual technology which"
"we expect will require different support than a typical deployment?"
),
)
app_design_comments = CharField(
label="App Design Comments",
widget=forms.Textarea,
required=False,
help_text=(
| |
peridural, durante o puerpério'),
('O89.6', 'Falha na ou dificuldade de entubação, durante o puerpério'),
('O89.8', 'Outras complicações da anestesia durante o puerpério'),
('O89.9', 'Complicação devida a anestesia, durante o puerpério, não especificada'),
('O90.0', 'Ruptura da incisão de cesariana'),
('O90.1', 'Ruptura da incisão obstétrica, no períneo'),
('O90.2', 'Hematoma da incisão obstétrica'),
('O90.3', 'Cardiomiopatia no puerpério'),
('O90.4', 'Insuficiência renal aguda do pós-parto'),
('O90.5', 'Tireoidite do pós-parto'),
('O90.8', 'Outras complicações do puerpério, não classificadas em outra parte'),
('O90.9', 'Complicação do puerpério não especificada'),
('O91.0', 'Infecção do mamilo associada ao parto'),
('O91.1', 'Abscesso da mama associada ao parto'),
('O91.2', 'Mastite não purulenta associada ao parto'),
('O92.0', 'Mamilo retraído associado ao parto'),
('O92.1', 'Fissuras do mamilo associadas ao parto'),
('O92.2', 'Outras afecções da mama, e as não especificadas, associadas ao parto'),
('O92.3', 'Agalactia'),
('O92.4', 'Hipogalactia'),
('O92.5', 'Suspensão da lactação'),
('O92.6', 'Galactorréia'),
('O92.7', 'Outros distúrbios da lactação e os não especificados'),
('O95', ' Morte obstétrica de causa não especificada'),
('O96', ' Morte, por qualquer causa obstétrica, que ocorre mais de 42 dias, mas menos de 1 ano, após o parto'),
('O97', ' Morte por seqüelas de causas obstétricas diretas'),
('O98.0', 'Tuberculose complicando a gravidez, o parto e o puerpério'),
('O98.1', 'Sífilis complicando a gravidez, o parto e o puerpério'),
('O98.2', 'Gonorréia complicando a gravidez, o parto e o puerpério'),
('O98.3', 'Outras infecções em que a via de transmissão é predominantemente sexual, complicando a gravidez, o parto e o puerpério'),
('O98.4', 'Hepatite viral complicando a gravidez, o parto e o puerpério'),
('O98.5', 'Outras doenças virais complicando a gravidez, o parto e o puerpério'),
('O98.6', 'Doenças causadas por protozoários complicando a gravidez, o parto e o puerpério'),
('O98.8', 'Outras doenças infecciosas e parasitárias maternas complicando a gravidez, o parto e o puerpério'),
('O98.9', 'Doenças infecciosas e parasitárias maternas, não especificadas, complicando a gravidez, o parto e o puerpério'),
('O99.0', 'Anemia complicando a gravidez, o parto e o puerpério'),
('O99.1', 'Outras doenças do sangue e dos órgãos hematopoéticos e alguns transtornos que comprometem o sistema imunológico, complicando a gravidez, o parto e o puerpério'),
('O99.2', 'Doenças endócrinas, nutricionais e metabólicas complicando a gravidez, o parto e o puerpério'),
('O99.3', 'Transtornos mentais e doenças do sistema nervoso complicando a gravidez, o parto e o puerpério'),
('O99.4', 'Doenças do aparelho circulatório complicando a gravidez, o parto e o puerpério'),
('O99.5', 'Doenças do aparelho respiratório complicando a gravidez, o parto e o puerpério'),
('O99.6', 'Doenças do aparelho digestivo complicando a gravidez, o parto e o puerpério'),
('O99.7', 'Doenças da pele e do tecido subcutâneo complicando a gravidez, o parto e o puerpério'),
('O99.8', 'Outras doenças e afecções especificadas complicando a gravidez, o parto e o puerpério'),
('P00.0', 'Feto e recém-nascido afetados por transtornos maternos hipertensivos'),
('P00.1', 'Feto e recém-nascido afetados por doenças maternas renais e das vias urinárias'),
('P00.2', 'Feto e recém-nascido afetados por doenças infecciosas e parasitárias da mãe'),
('P00.3', 'Feto e recém-nascido afetados por outras doenças circulatórias e respiratórias maternas'),
('P00.4', 'Feto e recém-nascido afetados por transtornos nutricionais maternos'),
('P00.5', 'Feto e recém-nascido afetados por traumatismo materno'),
('P00.6', 'Feto e recém-nascido afetados por intervenção cirúrgica na mãe'),
('P00.7', 'Feto e recém-nascido afetados por outros procedimentos médicos na mãe, não classificados em outra parte'),
('P00.8', 'Feto e recém-nascido afetados por outras afecções maternas'),
('P00.9', 'Feto e recém-nascido afetados por afecção materna não especificada'),
('P01.0', 'Feto e recém-nascido afetados por incompetência do colo uterino'),
('P01.1', 'Feto e recém-nascido afetados por ruptura prematura das membranas'),
('P01.2', 'Feto e recém-nascido afetados por oligohidrâmnio'),
('P01.3', 'Feto e recém-nascido afetados por polihidrâmnio'),
('P01.4', 'Feto e recém-nascido afetados por gravidez ectópica'),
('P01.5', 'Feto e recém-nascido afetados por gravidez múltipla'),
('P01.6', 'Feto e recém-nascido afetados por morte materna'),
('P01.7', 'Feto e recém-nascido afetados por apresentação anormal antes do trabalho de parto'),
('P01.8', 'Feto e recém-nascido afetados por outras complicações maternas da gravidez'),
('P01.9', 'Feto e recém-nascido afetados por afecções maternas da gravidez, não especificadas'),
('P02.0', 'Feto e recém-nascido afetados por placenta prévia'),
('P02.1', 'Feto e recém-nascido afetados por outras formas de descolamento da placenta e hemorragia'),
('P02.2', 'Feto e recém-nascido afetados por outras anormalidades morfológicas e funcionais da placenta e as não especificadas'),
('P02.3', 'Feto e recém-nascido afetados por síndromes de transfusão placentária'),
('P02.4', 'Feto e recém-nascido afetados por prolapso de cordão umbilical'),
('P02.5', 'Feto e recém-nascido afetados por outras compressões do cordão umbilical'),
('P02.6', 'Feto e recém-nascido afetados por outras afecções do cordão umbilical e as não especificadas'),
('P02.7', 'Feto e recém-nascido afetados por corioamnionite'),
('P02.8', 'Feto e recém-nascido afetados por outras anormalidades das membranas'),
('P02.9', 'Feto e recém-nascido afetados por anormalidade não especificada das membranas'),
('P03.0', 'Feto e recém-nascido afetados por parto e extração pélvicas'),
('P03.1', 'Feto e recém-nascido afetados por outras apresentações anormais, má-posições e desproporções durante o trabalho de parto e o parto'),
('P03.2', 'Feto e recém-nascido afetados por parto por fórceps'),
('P03.3', 'Feto e recém-nascido afetados por parto por vácuo-extrator [ventosa]'),
('P03.4', 'Feto e recém-nascido afetados por parto por cesariana'),
('P03.5', 'Feto e recém-nascido afetados por parto precipitado'),
('P03.6', 'Feto e recém-nascido afetados por contrações uterinas anormais'),
('P03.8', 'Feto e recém-nascido afetados por outras complicações especificadas do trabalho de parto e do parto'),
('P03.9', 'Feto e recém-nascido afetados por complicações não especificadas do trabalho de parto e do parto'),
('P04.0', 'Feto e recém-nascido afetados por anestesia e analgesia materna durante a gravidez, trabalho de parto e parto'),
('P04.1', 'Feto e recém-nascido afetados por outros medicamentos utilizados pela mãe'),
('P04.2', 'Feto e recém-nascido afetados pelo uso de fumo pela mãe'),
('P04.3', 'Feto e recém-nascido afetados pelo uso de álcool pela mãe'),
('P04.4', 'Feto e recém-nascido afetados pelo uso de drogas que causam dependência pela mãe'),
('P04.5', 'Feto e recém-nascido afetados por uso materno de substâncias químicas dos alimentos'),
('P04.6', 'Feto e recém-nascido afetados pela exposição da mãe a substâncias químicas do meio ambiente'),
('P04.8', 'Feto e recém-nascido afetados por outras influências nocivas maternas'),
('P04.9', 'Feto e recém-nascido afetados por influências nocivas maternas não especificadas'),
('P05.0', 'Recém-nascido de baixo peso para a idade gestacional'),
('P05.1', 'Pequeno para a idade gestacional'),
('P05.2', 'Desnutrição fetal sem menção de peso e comprimento baixos para a idade gestacional'),
('P05.9', 'Retardo não especificado do crescimento fetal'),
('P07.0', 'Recém-nascido com peso muito baixo'),
('P07.1', 'Outros recém-nascidos de peso baixo'),
('P07.2', 'Imaturidade extrema'),
('P07.3', 'Outros recém-nascidos de pré-termo'),
('P08.0', 'Recém-nascido de tamanho excessivamente grande'),
('P08.1', 'Outros recém-nascidos grandes para a idade gestacional'),
('P08.2', 'Recém-nascido pós-termo, não-grande para a idade gestacional'),
('P10.0', 'Hemorragia subdural devida a traumatismo de parto'),
('P10.1', 'Hemorragia cerebral devida a traumatismo de parto'),
('P10.2', 'Hemorragia intraventricular devida a traumatismo de parto'),
('P10.3', 'Hemorragia subaracnoídea devida a traumatismo de parto'),
('P10.4', 'Ruptura tentorial devida a traumatismo de parto'),
('P10.8', 'Outras lacerações e hemorragias intracranianas devidas a traumatismo de parto'),
('P10.9', 'Laceração e hemorragia intracranianas não especificadas devidas a traumatismo de parto'),
('P11.0', 'Edema cerebral devido a traumatismo de parto'),
('P11.1', 'Outras lesões cerebrais especificadas devidas a traumatismo de parto'),
('P11.2', 'Lesão cerebral não especificada devida a traumatismo de parto'),
('P11.3', 'Traumatismo de parto do nervo facial'),
('P11.4', 'Traumatismo de parto de outros nervos cranianos'),
('P11.5', 'Traumatismo de parto da coluna e da medula espinhal'),
('P11.9', 'Traumatismo de parto não especificado do sistema nervoso central'),
('P12.0', 'Céfalo-hematoma devido a traumatismo de parto'),
('P12.1', '"Chignon" devido a traumatismo de parto'),
('P12.2', 'Hemorragia subaponeurótica epicraniana devida a traumatismo de parto'),
('P12.3', 'Esmagamento do couro cabeludo devido a traumatismo de parto'),
('P12.4', 'Lesão por monitorização do couro cabeludo do recém-nascido'),
('P12.8', 'Outras lesões do couro cabeludo devidas a traumatismo de parto'),
('P12.9', 'Lesão não especificada do couro cabeludo devida a traumatismo de parto'),
('P13.0', 'Fratura de crânio devida a traumatismo de parto'),
('P13.1', 'Outras lesões cranianas devidas a traumatismo de parto'),
('P13.2', 'Lesão do fêmur devida a traumatismo de parto'),
('P13.3', 'Lesão de outros ossos longos devida a traumatismo de parto'),
('P13.4', 'Fratura da clavícula devida a traumatismo de parto'),
('P13.8', 'Lesões de outras partes do esqueleto devidas a traumatismo de parto'),
('P13.9', 'Lesões não especificadas do esqueleto devidas a traumatismo de parto'),
('P14.0', 'Paralisia de Erb devida a traumatismo de parto'),
('P14.1', 'Paralisia de Klumpke devida a traumatismo de parto'),
('P14.2', 'Paralisia do nervo frênico devida a traumatismo de parto'),
('P14.3', 'Outras lesões do plexo braquial devidas a traumatismo de parto'),
('P14.8', 'Outras lesões de outras partes do sistema nervoso periférico devidas a traumatismo de parto'),
('P14.9', 'Lesão não especificada do sistema nervoso periférico devida a traumatismo de parto'),
('P15.0', 'Lesão do fígado devida a traumatismo de parto'),
('P15.1', 'Lesão do baço devida a traumatismo de parto'),
('P15.2', 'Lesão do esternomastóide devida a traumatismo de parto'),
('P15.3', 'Lesão dos olhos devida a traumatismo de parto'),
('P15.4', 'Lesão da face ao nascer'),
('P15.5', 'Lesão dos órgãos | |
self._state_a.change_state(data, False)
if self._pipe_condition_mask:
return condition_mask
return changed
class ChangeStateConditionalTransition(_Transition, ConditionalMixin):
"""
Change a state where external condition is true
Parameters:
name: str
state_a: Union[_State, Tuple[_State, Union[bool,
Callable[[DataDict, TCondition], np.ndarray]]]
State to change. Can either be a `_State`, in which case the state
will be set to true or a tuple, where the second item
is the value the state should be set to or a Callable returning the
value.
condition: TCondition
pipe_condition_mask: bool
If true, the call to this transition will return a boolean
`np.ndarray` encoding the rows for which `condition` is True.
"""
_state_a: _State
_state_a_val: bool
def __init__(
self,
name: str,
state_a: Union[
_State,
Tuple[
_State,
Union[bool, Callable[[DataDict, TCondition], np.ndarray]]
]
],
condition: TCondition = None,
pipe_condition_mask: bool = False,
*args,
**kwargs,
):
_Transition.__init__(self, name, pipe_condition_mask, *args, **kwargs)
ConditionalMixin.__init__(self, condition, *args, **kwargs)
if isinstance(state_a, tuple):
self._state_a = state_a[0]
self._state_a_val = state_a[1]
else:
self._state_a = state_a
self._state_a_val = True
@log_call
def __call__(
self,
data: DataDict,
condition_mask: Optional[np.ndarray] = None) -> np.ndarray:
"""
Perform the transition.
All rows in data which are in state A and for which the
external condition is true are transitioned to a new value.
Parameters:
data: DataDict
condition_mask: Optional[np.ndarray]
Additional condition in form of a boolean np.ndarray.
"""
cond = self.unify_condition(data)
if condition_mask is not None:
cond = cond & condition_mask
if callable(self._state_a_val):
parsed_val = self._state_a_val(data, cond & self._state_a(data))
else:
parsed_val = self._state_a_val
changed = self._state_a.change_state(data, parsed_val, cond)
if self._pipe_condition_mask:
return condition_mask
return changed
class ConditionalTransition(_Transition, ConditionalMixin):
"""
Perform a transition from state_a to state_b where an external condition
is true
Parameters:
name: str
state_a: _State
state_b: _State
condition: TCondition,
pipe_condition_mask: bool
If true, the call to this transition will return a boolean
`np.ndarray` encoding the rows for which `condition` is True.
"""
def __init__(
self,
name: str,
state_a: _State,
state_b: _State,
condition: TCondition,
pipe_condition_mask: bool = False,
*args,
**kwargs,
):
_Transition.__init__(self, name, pipe_condition_mask, *args, **kwargs)
ConditionalMixin.__init__(self, condition, *args, **kwargs)
self._state_a = state_a
self._state_b = state_b
@log_call
def __call__(
self,
data: DataDict,
condition_mask: Optional[np.ndarray] = None) -> np.ndarray:
cond = self.unify_condition(data)
if condition_mask is not None:
cond = cond & condition_mask
(~self._state_b).change_state(data, True, cond & self._state_a(data))
changed = self._state_a.change_state(data, False, cond)
if self._pipe_condition_mask:
return condition_mask
return changed
class DecreaseTimerTransition(_Transition, ConditionalMixin):
"""
Decrease the value of a FloatState by one
Parameters:
name: str
state_a: FloatState
condition: Optional[TCondition],
pipe_condition_mask: bool
If true, the call to this transition will return a boolean
`np.ndarray` encoding the rows for which `condition` is True.
"""
def __init__(
self,
name: str,
state_a: FloatState,
condition: TCondition = None,
pipe_condition_mask: bool = False,
*args,
**kwargs,
):
_Transition.__init__(self, name, pipe_condition_mask, *args, **kwargs)
ConditionalMixin.__init__(self, condition, *args, **kwargs)
self._state_a = state_a
@log_call
def __call__(
self,
data: DataDict,
condition_mask: Optional[np.ndarray] = None) -> np.ndarray:
cond = self.unify_condition(data)
if condition_mask is not None:
cond = cond & condition_mask
state_condition = self._state_a(data)
# Current state value
cur_state = self._state_a.get_state_value(data)[cond & state_condition]
changed = self._state_a.change_state(data, cur_state - 1, cond)
if self._pipe_condition_mask:
return condition_mask
return changed
class IncreaseTimerTransition(_Transition, ConditionalMixin):
"""
Increase the value of a FloatState by one
Parameters:
name: str
state_a: FloatState
condition: Optional[TCondition],
pipe_condition_mask: bool
If true, the call to this transition will return a boolean
`np.ndarray` encoding the rows for which `condition` is True.
"""
def __init__(
self,
name: str,
state_a: FloatState,
condition: TCondition = None,
pipe_condition_mask = False,
*args,
**kwargs,
):
_Transition.__init__(self, name, pipe_condition_mask, *args, **kwargs)
ConditionalMixin.__init__(self, condition, *args, **kwargs)
self._state_a = state_a
@log_call
def __call__(
self,
data: DataDict,
condition_mask: Optional[np.ndarray] = None) -> np.ndarray:
cond = self.unify_condition(data)
if condition_mask is not None:
cond = cond & condition_mask
state_condition = self._state_a(data)
# Current state value
cur_state = self._state_a.get_state_value(data)[cond & state_condition]
changed = self._state_a.change_state(data, cur_state + 1, cond)
if self._pipe_condition_mask:
return condition_mask
return changed
class InitializeTimerTransition(_Transition, ConditionalMixin):
"""
Initialize a timer state to values drawn from a PDF
Parameters:
name: str
state_a: FloatState
initialization_pdf: Optional[PDF]
This pdf is used to initialize the state values upon activation.
condition: Optional[TCondition]
pipe_condition_mask: bool
If true, the call to this transition will return a boolean
`np.ndarray` encoding the rows for which `condition` is True.
stateful_init_func: Optional[
Callable[[DataDict, np.ndarray], np.ndarray]]
Supply a Callable that takes a DataDict as first and a boolean mask
encoding the inactive states as second argument when
`initialization_pdf` is None. The callable will be used to
initialize the state.
"""
def __init__(
self,
name: str,
state_a: FloatState,
initialization_pdf: Optional[PDF] = None,
condition: TCondition = None,
pipe_condition_mask: bool = False,
stateful_init_func: Callable[[DataDict, np.ndarray], np.ndarray]=None,
log=False,
*args,
**kwargs,
):
_Transition.__init__(self, name, *args, **kwargs)
ConditionalMixin.__init__(self, condition)
self._state_a = state_a
if initialization_pdf is None and stateful_init_func is None:
raise ValueError(
"Must either supply initialization_pdf or stateful_init_func")
if initialization_pdf is not None and stateful_init_func is not None:
raise ValueError(
"Supply only one of initialization_pdf or stateful_init_func")
self._initialization_pdf = initialization_pdf
self._stateful_init_func = stateful_init_func
self._log = log
@log_call
def __call__(
self,
data: DataDict,
condition_mask: Optional[np.ndarray] = None) -> np.ndarray:
cond = self.unify_condition(data)
if condition_mask is not None:
cond = cond & condition_mask
# Rows which are currently 0
zero_rows = (~self._state_a(data)) & cond
num_zero_rows = zero_rows.sum(axis=0)
if self._initialization_pdf is not None:
initial_vals = self._initialization_pdf.rvs(num_zero_rows)
else:
initial_vals = self._stateful_init_func(data, zero_rows)
# print(len(initial_vals), (~self._state_a(data)).sum())
changed = (~self._state_a).change_state(data, initial_vals, cond)
if self._log:
print(self._name)
# print("Nonzero cond ", np.nonzero(condition_mask))
if np.any(np.nonzero(cond)[0] == 0):
print("Time until second ", data["time_until_second_test"][0])
if self._pipe_condition_mask:
return condition_mask
return changed
class InitializeCounterTransition(_Transition, ConditionalMixin):
"""
Initialize a counter state
Parameters:
name: str
state_a: FloatState
start: int
condition: Optional[TCondition]
"""
def __init__(
self,
name: str,
state_a: FloatState,
start: int = 0,
condition: TCondition = None,
pipe_condition_mask: bool = False,
*args,
**kwargs,
):
_Transition.__init__(self, name, *args, **kwargs)
ConditionalMixin.__init__(self, condition)
self._state_a = state_a
self._start = start
self._pipe_condition_mask = pipe_condition_mask
@log_call
def __call__(
self,
data: DataDict,
condition_mask: Optional[np.ndarray] = None) -> np.ndarray:
cond = self.unify_condition(data)
if condition_mask is not None:
cond = cond & condition_mask
initial_vals = self._start # Initializes counter at 1
changed = (~self._state_a).change_state(data, initial_vals, cond)
if self._pipe_condition_mask:
return condition_mask
return changed
class MultiStateConditionalTransition(_Transition, ConditionalMixin):
"""
Perform a transition from state_a to multiple other states
Parameters:
name: str
state_a: Union[_State, Tuple[_State, bool]]
State to change. Can either be a `_State`, in which case the state
will be set to true or a Tuple[_State, bool], where the second item
is the value the state should be set to.
states_b: List[Union[_State, Tuple[_State, bool]]]
List of states to change. Can either be a `_State`, in which case
the state will be set to true or a Tuple[_State, bool], where
the second item is the value the state should be set to.
"""
_states_b: List[_State]
_states_b_vals: List[bool]
def __init__(
self,
name: str,
state_a: Union[
_State, Tuple[_State, bool],
Tuple[_State, Callable[[DataDict, np.ndarray], np.ndarray]]
],
states_b: List[Union[_State, Tuple[_State, bool]]],
condition: TCondition,
pipe_condition_mask: bool = False,
*args,
**kwargs,
):
_Transition.__init__(self, name, *args, **kwargs)
ConditionalMixin.__init__(self, condition, *args, **kwargs)
self._pipe_condition_mask = pipe_condition_mask
if isinstance(state_a, tuple):
self._state_a = state_a[0]
self._state_a_val = state_a[1]
else:
self._state_a = state_a
self._state_a_val = False
self._states_b = []
self._states_b_vals = []
for state in states_b:
if isinstance(state, tuple):
self._states_b.append(state[0])
self._states_b_vals.append(state[1])
else:
self._states_b.append(state)
self._states_b_vals.append(True)
@log_call
def __call__(
self,
data: DataDict,
condition_mask: Optional[np.ndarray] = None):
cond = self.unify_condition(data)
if condition_mask is not None:
cond = cond & condition_mask
is_in_state_a = self._state_a(data)
cond_and_a = cond & is_in_state_a
for state, val in zip(self._states_b, self._states_b_vals):
if callable(val):
parsed_val = val(data, cond_and_a)
else:
parsed_val = val
(~state).change_state(data, parsed_val, cond_and_a)
changed = self._state_a.change_state(data, self._state_a_val, cond)
if self._pipe_condition_mask:
return condition_mask
return changed
class TransitionChain(ConditionalMixin):
def __init__(
self,
name: str,
transitions: List[_Transition],
carry_condition: bool = True,
loop_until: Optional[TCondition] = None,
*args,
**kwargs,
):
ConditionalMixin.__init__(self, loop_until, *args, **kwargs)
self._name = name
self._transitions = transitions
self._carry_condition = carry_condition
def __call__(self, data: DataDict) -> np.ndarray:
changed = None
loopcnt = 0
while True:
for transition in self._transitions:
try:
if self._carry_condition:
changed = transition(data, changed)
else:
transition(data)
except Exception as e:
print("Caught exception in transition: ", transition.name)
raise e
cond = self.unify_condition(data)
if ~np.any(cond) or self._condition is None:
break
loopcnt += 1
@property
def name(self):
return self._name
class | |
Machine.objects.filter(machine_group=machine_group).filter(deployed=deployed)
else:
machines = Machine.objects.none()
# send the machines and the data to the plugin
for plugin in manager.getAllPlugins():
if plugin.name == pluginName:
(machines, title) = plugin.plugin_object.filter_machines(machines, data)
return machines, title
# Table ajax for dataTables
@login_required
def tableajax(request, pluginName, data, page='front', theID=None):
# Pull our variables out of the GET request
get_data = request.GET['args']
get_data = json.loads(get_data.decode('string_escape'))
draw = get_data.get('draw', 0)
start = int(get_data.get('start', 0))
length = int(get_data.get('length', 0))
search_value = ''
if 'search' in get_data:
if 'value' in get_data['search']:
search_value = get_data['search']['value']
# default ordering
order_column = 2
order_direction = 'desc'
order_name = ''
if 'order' in get_data:
order_column = get_data['order'][0]['column']
order_direction = get_data['order'][0]['dir']
for column in get_data.get('columns', None):
if column['data'] == order_column:
order_name = column['name']
break
if pluginName == 'Status' and data == 'undeployed_machines':
deployed = False
else:
deployed = True
(machines, title) = plugin_machines(request, pluginName, data, page, theID)
# machines = machines.filter(deployed=deployed)
if len(order_name) != 0:
if order_direction == 'desc':
order_string = "-%s" % order_name
else:
order_string = "%s" % order_name
if len(search_value) != 0:
searched_machines = machines.filter(Q(hostname__icontains=search_value) | Q(console_user__icontains=search_value) | Q(last_checkin__icontains=search_value)).order_by(order_string)
else:
searched_machines = machines.order_by(order_string)
limited_machines = searched_machines[start:(start+length)]
return_data = {}
return_data['draw'] = int(draw)
return_data['recordsTotal'] = machines.count()
return_data['recordsFiltered'] = machines.count()
return_data['data'] = []
settings_time_zone = None
try:
settings_time_zone = pytz.timezone(settings.TIME_ZONE)
except:
pass
for machine in limited_machines:
if machine.last_checkin:
#formatted_date = pytz.utc.localize(machine.last_checkin)
if settings_time_zone:
formatted_date = machine.last_checkin.astimezone(settings_time_zone).strftime("%Y-%m-%d %H:%M %Z")
else:
formatted_date = machine.last_checkin.strftime("%Y-%m-%d %H:%M")
else:
formatted_date = ""
hostname_link = "<a href=\"%s\">%s</a>" % (reverse('machine_detail', args=[machine.id]), machine.hostname)
list_data = [hostname_link, machine.console_user, formatted_date]
return_data['data'].append(list_data)
return JsonResponse(return_data)
# Plugin machine list
@login_required
def machine_list(request, pluginName, data, page='front', theID=None):
(machines, title) = plugin_machines(request, pluginName, data, page, theID, get_machines=False)
user = request.user
c = {'user':user, 'plugin_name': pluginName, 'machines': machines, 'req_type': page, 'title': title, 'bu_id': theID, 'request':request, 'data':data }
return render(request, 'server/overview_list_all.html', c)
# Plugin machine list
@login_required
def plugin_load(request, pluginName, page='front', theID=None):
user = request.user
title = None
# Build the manager
manager = PluginManager()
# Tell it the default place(s) where to find plugins
manager.setPluginPlaces([settings.PLUGIN_DIR, os.path.join(settings.PROJECT_DIR, 'server/plugins')])
# Load all plugins
manager.collectPlugins()
# get a list of machines (either from the BU or the group)
if page == 'front':
# get all machines
if user.userprofile.level == 'GA':
machines = Machine.deployed_objects.all()
else:
machines = Machine.objects.none()
for business_unit in user.businessunit_set.all():
for group in business_unit.machinegroup_set.all():
machines = machines | group.machine_set.all().filter(deployed=True)
if page == 'bu_dashboard':
# only get machines for that BU
# Need to make sure the user is allowed to see this
business_unit = get_object_or_404(BusinessUnit, pk=theID)
machine_groups = MachineGroup.objects.filter(business_unit=business_unit).all()
machines = Machine.deployed_objects.filter(machine_group__in=machine_groups)
if page == 'group_dashboard':
# only get machines from that group
machine_group = get_object_or_404(MachineGroup, pk=theID)
# check that the user has access to this
machines = Machine.deployed_objects.filter(machine_group=machine_group)
if page =='machine_detail':
machines = Machine.objects.get(pk=theID)
# send the machines and the data to the plugin
for plugin in manager.getAllPlugins():
if plugin.name == pluginName:
html = plugin.plugin_object.widget_content(page, machines, theID)
return HttpResponse(html)
@login_required
def report_load(request, pluginName, page='front', theID=None):
user = request.user
title = None
business_unit = None
machine_group = None
# Build the manager
manager = PluginManager()
# Tell it the default place(s) where to find plugins
manager.setPluginPlaces([settings.PLUGIN_DIR, os.path.join(settings.PROJECT_DIR, 'server/plugins')])
# Load all plugins
manager.collectPlugins()
# get a list of machines (either from the BU or the group)
if page == 'front':
# get all machines
if user.userprofile.level == 'GA':
machines = Machine.deployed_objects.all()
else:
machines = Machine.objects.none()
for business_unit in user.businessunit_set.all():
for group in business_unit.machinegroup_set.all():
machines = machines | group.machine_set.all().filter(deployed=True)
if page == 'bu_dashboard':
# only get machines for that BU
# Need to make sure the user is allowed to see this
business_unit = get_object_or_404(BusinessUnit, pk=theID)
machine_groups = MachineGroup.objects.filter(business_unit=business_unit).all()
machines = Machine.deployed_objects.filter(machine_group=machine_groups)
if page == 'group_dashboard':
# only get machines from that group
machine_group = get_object_or_404(MachineGroup, pk=theID)
# check that the user has access to this
machines = Machine.deployed_objects.filter(machine_group=machine_group)
if page =='machine_detail':
machines = Machine.objects.get(pk=theID)
output = ''
# send the machines and the data to the plugin
for plugin in manager.getAllPlugins():
if plugin.name == pluginName:
output = plugin.plugin_object.widget_content(page, machines, theID)
reports = []
enabled_reports = Report.objects.all()
for enabled_report in enabled_reports:
for plugin in manager.getAllPlugins():
if enabled_report.name == plugin.name:
# If plugin_type isn't set, it can't be a report
try:
plugin_type = plugin.plugin_object.plugin_type()
except:
plugin_type = 'widget'
if plugin_type == 'report':
data = {}
data['name'] = plugin.name
data['title'] = plugin.plugin_object.get_title()
reports.append(data)
break
c = {'user': request.user, 'output': output, 'page':page, 'business_unit': business_unit, 'machine_group': machine_group, 'reports': reports}
return render(request, 'server/display_report.html', c)
class Echo(object):
"""An object that implements just the write method of the file-like interface.
"""
def write(self, value):
"""Write the value by returning it, instead of storing in a buffer."""
return value
def get_csv_row(machine, facter_headers, condition_headers, plugin_script_headers):
row = []
for name, value in machine.get_fields():
if name != 'id' and name !='machine_group' and name != 'report' and name != 'activity' and name != 'os_family' and name != 'install_log' and name != 'install_log_hash':
try:
row.append(utils.safe_unicode(value))
except:
row.append('')
row.append(machine.machine_group.business_unit.name)
row.append(machine.machine_group.name)
return row
def stream_csv(header_row, machines, facter_headers, condition_headers, plugin_script_headers): # Helper function to inject headers
if header_row:
yield header_row
for machine in machines:
yield get_csv_row(machine, facter_headers, condition_headers, plugin_script_headers)
@login_required
def export_csv(request, pluginName, data, page='front', theID=None):
user = request.user
title = None
# Build the manager
manager = PluginManager()
# Tell it the default place(s) where to find plugins
manager.setPluginPlaces([settings.PLUGIN_DIR, os.path.join(settings.PROJECT_DIR, 'server/plugins')])
# Load all plugins
manager.collectPlugins()
if pluginName == 'Status' and data == 'undeployed_machines':
deployed = False
else:
deployed = True
# get a list of machines (either from the BU or the group)
if page == 'front':
# get all machines
if user.userprofile.level == 'GA':
# machines = Machine.objects.all().prefetch_related('facts','conditions','pluginscriptsubmission_set','pluginscriptsubmission_set__pluginscriptrow_set')
machines = Machine.objects.all().filter(deployed=deployed).defer('report','activity','os_family','install_log', 'install_log_hash')
else:
machines = Machine.objects.none().defer('report','activity','os_family','install_log', 'install_log_hash')
for business_unit in user.businessunit_set.all():
for group in business_unit.machinegroup_set.all():
machines = machines | group.machine_set.all().filter(deployed=deployed)
if page == 'bu_dashboard':
# only get machines for that BU
# Need to make sure the user is allowed to see this
business_unit = get_object_or_404(BusinessUnit, pk=theID)
machine_groups = MachineGroup.objects.filter(business_unit=business_unit).prefetch_related('machine_set').all()
if machine_groups.count() != 0:
machines = machine_groups[0].machine_set.all()
for machine_group in machine_groups[1:]:
machines = machines | machine_group.machine_set.all().filter(deployed=deployed).defer('report','activity','os_family','install_log', 'install_log_hash')
else:
machines = None
if page == 'group_dashboard':
# only get machines from that group
machine_group = get_object_or_404(MachineGroup, pk=theID)
# check that the user has access to this
# machines = Machine.objects.filter(machine_group=machine_group).prefetch_related('facts','conditions','pluginscriptsubmission_set','pluginscriptsubmission_set__pluginscriptrow_set')
machines = Machine.objects.filter(machine_group=machine_group).filter(deployed=deployed).defer('report','activity','os_family','install_log', 'install_log_hash')
if page =='machine_detail':
machines = Machine.objects.get(pk=theID)
# send the machines and the data to the plugin
for plugin in manager.getAllPlugins():
if plugin.name == pluginName:
(machines, title) = plugin.plugin_object.filter_machines(machines, data)
pseudo_buffer = Echo()
writer = csv.writer(pseudo_buffer)
# Fields
header_row = []
fields = Machine._meta.get_fields()
for field in fields:
if not field.is_relation and field.name != 'id' and field.name != 'report' and field.name != 'activity' and field.name != 'os_family' and field.name != 'install_log' and field.name != 'install_log_hash':
header_row.append(field.name)
# distinct_facts = Fact.objects.values('fact_name').distinct().order_by('fact_name')
facter_headers = []
condition_headers = []
plugin_script_headers = []
header_row.append('business_unit')
header_row.append('machine_group')
response = StreamingHttpResponse(
(writer.writerow(row) for row in stream_csv(
header_row=header_row,
machines=machines,
facter_headers=facter_headers,
condition_headers=condition_headers,
plugin_script_headers=plugin_script_headers)),
content_type="text/csv")
# Create the HttpResponse object with the appropriate CSV header.
if getattr(settings, 'DEBUG_CSV', False):
pass
else:
response['Content-Disposition'] = 'attachment; filename="%s.csv"' % title
#
#
# if getattr(settings, 'DEBUG_CSV', False):
# writer.writerow(['</body>'])
return response
# New BU
@login_required
def new_business_unit(request):
c = {}
c.update(csrf(request))
if request.method == 'POST':
form = BusinessUnitForm(request.POST)
if form.is_valid():
new_business_unit = form.save(commit=False)
new_business_unit.save()
form.save_m2m()
return redirect('bu_dashboard', new_business_unit.id)
else:
form = BusinessUnitForm()
c = {'form': form}
user = request.user
user_level = user.userprofile.level
if user_level != 'GA':
return redirect(index)
return render(request, 'forms/new_business_unit.html', c)
# Edit BU
@login_required
def edit_business_unit(request, bu_id):
user = request.user
user_level = user.userprofile.level
if user_level != 'GA':
return redirect(index)
business_unit = get_object_or_404(BusinessUnit, pk=int(bu_id))
c = {}
c.update(csrf(request))
if request.method == 'POST':
if user.is_staff:
form = EditUserBusinessUnitForm(request.POST, instance=business_unit)
else:
form = EditBusinessUnitForm(request.POST, instance=business_unit)
if form.is_valid():
new_business_unit = form.save(commit=False)
new_business_unit.save()
form.save_m2m()
return redirect('bu_dashboard', new_business_unit.id)
else:
if user.is_staff:
form = EditUserBusinessUnitForm(instance=business_unit)
else:
form = EditBusinessUnitForm(instance=business_unit)
c = {'form': form, 'business_unit':business_unit}
user = request.user
user_level = user.userprofile.level
if user_level != 'GA':
return redirect(index)
return render(request, 'forms/edit_business_unit.html', c)
@login_required
def delete_business_unit(request, bu_id):
user = request.user
user_level = user.userprofile.level
if user_level != 'GA':
return redirect(index)
business_unit = get_object_or_404(BusinessUnit, pk=int(bu_id))
machine_groups = business_unit.machinegroup_set.all()
machines = | |
27, 5, -1): (0, 1),
(7, 27, 5, 0): (0, 1),
(7, 27, 5, 1): (0, 1),
(7, 27, 5, 2): (0, 0),
(7, 27, 5, 3): (-1, -1),
(7, 27, 5, 4): (0, 1),
(7, 27, 5, 5): (0, 1),
(7, 28, -5, -5): (0, 1),
(7, 28, -5, -4): (0, 1),
(7, 28, -5, -3): (0, 1),
(7, 28, -5, -2): (0, 1),
(7, 28, -5, -1): (0, 1),
(7, 28, -5, 0): (0, 1),
(7, 28, -5, 1): (0, 1),
(7, 28, -5, 2): (0, 1),
(7, 28, -5, 3): (0, 1),
(7, 28, -5, 4): (0, 0),
(7, 28, -5, 5): (-1, -1),
(7, 28, -4, -5): (0, 1),
(7, 28, -4, -4): (0, 1),
(7, 28, -4, -3): (0, 1),
(7, 28, -4, -2): (0, 1),
(7, 28, -4, -1): (0, 1),
(7, 28, -4, 0): (-1, 1),
(7, 28, -4, 1): (-1, 1),
(7, 28, -4, 2): (-1, 1),
(7, 28, -4, 3): (0, 1),
(7, 28, -4, 4): (0, 0),
(7, 28, -4, 5): (-1, -1),
(7, 28, -3, -5): (0, 1),
(7, 28, -3, -4): (0, 1),
(7, 28, -3, -3): (0, 1),
(7, 28, -3, -2): (0, 1),
(7, 28, -3, -1): (0, 1),
(7, 28, -3, 0): (0, 1),
(7, 28, -3, 1): (-1, 1),
(7, 28, -3, 2): (-1, 1),
(7, 28, -3, 3): (0, 1),
(7, 28, -3, 4): (0, 0),
(7, 28, -3, 5): (-1, -1),
(7, 28, -2, -5): (0, 1),
(7, 28, -2, -4): (0, 1),
(7, 28, -2, -3): (0, 1),
(7, 28, -2, -2): (0, 1),
(7, 28, -2, -1): (0, 1),
(7, 28, -2, 0): (1, 1),
(7, 28, -2, 1): (1, 1),
(7, 28, -2, 2): (-1, 1),
(7, 28, -2, 3): (-1, 1),
(7, 28, -2, 4): (-1, 0),
(7, 28, -2, 5): (-1, -1),
(7, 28, -1, -5): (-1, 1),
(7, 28, -1, -4): (-1, 1),
(7, 28, -1, -3): (-1, 1),
(7, 28, -1, -2): (-1, 1),
(7, 28, -1, -1): (1, 1),
(7, 28, -1, 0): (1, 1),
(7, 28, -1, 1): (0, 1),
(7, 28, -1, 2): (0, 0),
(7, 28, -1, 3): (-1, 1),
(7, 28, -1, 4): (-1, 1),
(7, 28, -1, 5): (-1, 1),
(7, 28, 0, -5): (-1, 1),
(7, 28, 0, -4): (1, 1),
(7, 28, 0, -3): (1, 1),
(7, 28, 0, -2): (1, 1),
(7, 28, 0, -1): (0, 1),
(7, 28, 0, 0): (0, 1),
(7, 28, 0, 1): (-1, 1),
(7, 28, 0, 2): (-1, 0),
(7, 28, 0, 3): (-1, -1),
(7, 28, 0, 4): (-1, -1),
(7, 28, 0, 5): (-1, -1),
(7, 28, 1, -5): (1, 1),
(7, 28, 1, -4): (1, 1),
(7, 28, 1, -3): (1, 1),
(7, 28, 1, -2): (1, 1),
(7, 28, 1, -1): (-1, 1),
(7, 28, 1, 0): (-1, 1),
(7, 28, 1, 1): (-1, 0),
(7, 28, 1, 2): (-1, -1),
(7, 28, 1, 3): (-1, -1),
(7, 28, 1, 4): (-1, -1),
(7, 28, 1, 5): (-1, 1),
(7, 28, 2, -5): (1, 1),
(7, 28, 2, -4): (1, 1),
(7, 28, 2, -3): (1, 1),
(7, 28, 2, -2): (1, 1),
(7, 28, 2, -1): (1, 1),
(7, 28, 2, 0): (1, 1),
(7, 28, 2, 1): (1, 0),
(7, 28, 2, 2): (1, -1),
(7, 28, 2, 3): (1, 1),
(7, 28, 2, 4): (1, 0),
(7, 28, 2, 5): (1, 0),
(7, 28, 3, -5): (0, 1),
(7, 28, 3, -4): (0, 1),
(7, 28, 3, -3): (0, 1),
(7, 28, 3, -2): (0, 1),
(7, 28, 3, -1): (0, 1),
(7, 28, 3, 0): (0, 1),
(7, 28, 3, 1): (0, 0),
(7, 28, 3, 2): (0, -1),
(7, 28, 3, 3): (0, 1),
(7, 28, 3, 4): (0, 1),
(7, 28, 3, 5): (0, 1),
(7, 28, 4, -5): (0, 1),
(7, 28, 4, -4): (0, 1),
(7, 28, 4, -3): (0, 1),
(7, 28, 4, -2): (0, 1),
(7, 28, 4, -1): (0, 1),
(7, 28, 4, 0): (0, 1),
(7, 28, 4, 1): (0, 0),
(7, 28, 4, 2): (-1, -1),
(7, 28, 4, 3): (0, 1),
(7, 28, 4, 4): (0, 1),
(7, 28, 4, 5): (0, 1),
(7, 28, 5, -5): (0, 1),
(7, 28, 5, -4): (0, 1),
(7, 28, 5, -3): (0, 1),
(7, 28, 5, -2): (0, 1),
(7, 28, 5, -1): (0, 1),
(7, 28, 5, 0): (0, 1),
(7, 28, 5, 1): (0, 0),
(7, 28, 5, 2): (-1, -1),
(7, 28, 5, 3): (0, 1),
(7, 28, 5, 4): (0, 1),
(7, 28, 5, 5): (0, 1),
(7, 29, -5, -5): (0, 1),
(7, 29, -5, -4): (0, 1),
(7, 29, -5, -3): (0, 1),
(7, 29, -5, -2): (0, 1),
(7, 29, -5, -1): (0, 1),
(7, 29, -5, 0): (0, 1),
(7, 29, -5, 1): (0, 1),
(7, 29, -5, 2): (0, 1),
(7, 29, -5, 3): (0, 0),
(7, 29, -5, 4): (-1, -1),
(7, 29, -5, 5): (0, 1),
(7, 29, -4, -5): (0, 1),
(7, 29, -4, -4): (0, 1),
(7, 29, -4, -3): (0, 1),
(7, 29, -4, -2): (0, 1),
(7, 29, -4, -1): (-1, 1),
(7, 29, -4, 0): (-1, 1),
(7, 29, -4, 1): (-1, 1),
(7, 29, -4, 2): (0, 1),
(7, 29, -4, 3): (0, 0),
(7, 29, -4, 4): (-1, -1),
(7, 29, -4, 5): (0, 1),
(7, 29, -3, -5): (0, 1),
(7, 29, -3, -4): (0, 1),
(7, 29, -3, -3): (0, 1),
(7, 29, -3, -2): (0, 1),
(7, 29, -3, -1): (0, 1),
(7, 29, -3, 0): (-1, 1),
(7, 29, -3, 1): (-1, 1),
(7, 29, -3, 2): (0, 1),
(7, 29, -3, 3): (0, 0),
(7, 29, -3, 4): (-1, -1),
(7, 29, -3, 5): (0, 1),
(7, 29, -2, -5): (0, 1),
(7, 29, -2, -4): (0, 1),
(7, 29, -2, -3): (0, 1),
(7, 29, -2, -2): (0, 1),
(7, 29, -2, -1): (0, 1),
(7, 29, -2, 0): (1, 1),
(7, 29, -2, 1): (1, 1),
(7, 29, -2, 2): (-1, 1),
(7, 29, -2, 3): (-1, 0),
(7, 29, -2, 4): (-1, -1),
(7, 29, -2, 5): (-1, 1),
(7, 29, -1, -5): (-1, 1),
(7, 29, -1, -4): (-1, 1),
(7, 29, -1, -3): (-1, 1),
(7, 29, -1, -2): (-1, 1),
(7, 29, -1, -1): (1, 1),
(7, 29, -1, 0): (0, 1),
(7, 29, -1, 1): (0, 1),
(7, 29, -1, 2): (-1, 1),
(7, 29, -1, 3): (-1, 0),
(7, 29, -1, 4): (-1, -1),
(7, 29, -1, 5): (-1, 1),
(7, 29, 0, -5): (1, 1),
(7, 29, 0, -4): (1, 1),
(7, 29, 0, -3): (1, 1),
(7, 29, 0, -2): (1, 1),
(7, 29, 0, -1): (0, 1),
(7, 29, 0, 0): (-1, 1),
(7, 29, 0, 1): (-1, 1),
(7, 29, 0, 2): (-1, 0),
(7, 29, 0, 3): (-1, -1),
(7, 29, 0, 4): (-1, -1),
(7, 29, 0, 5): (-1, 1),
(7, 29, 1, -5): (1, 1),
(7, 29, 1, -4): (1, 1),
(7, 29, 1, -3): (1, 1),
(7, 29, 1, -2): (1, 1),
(7, 29, 1, -1): (-1, 1),
(7, 29, 1, 0): (-1, 1),
(7, 29, 1, 1): (-1, 0),
(7, 29, 1, 2): (-1, -1),
(7, 29, 1, 3): (-1, -1),
(7, 29, 1, 4): (-1, -1),
(7, 29, 1, 5): (-1, 1),
(7, 29, 2, -5): (1, 1),
(7, 29, 2, -4): (1, 1),
(7, 29, 2, -3): (1, 1),
(7, 29, 2, -2): (1, 1),
(7, 29, 2, -1): (1, 1),
(7, 29, 2, 0): (1, 0),
(7, 29, 2, 1): (1, -1),
(7, 29, 2, 2): (1, 1),
(7, 29, 2, | |
How widgets are aligned within their cells.
See `set_alignment()` for more details about this option.
"""
custom_default_cell_size = 'expand'
"""
How much space a cell will consume if no size is specified.
See `set_default_cell_size()` for more details about this option.
"""
def __init__(self, default_cell_size=None):
"""
Initialize the container.
See `add()` for more details about the `default_cell_size` argument.
"""
super().__init__()
self._children = []
self._children_can_overlap = False
self._sizes = {}
self._grid = drawing.Grid()
self.cell_padding = first_not_none((
self.custom_cell_padding, self.custom_padding, 0))
self.cell_alignment = self.custom_cell_alignment
self.default_cell_size = first_not_none((
default_cell_size, self.custom_default_cell_size))
def __iter__(self):
yield from self._children
def add(self, widget, size=None):
"""
Add the given widget to the layout.
The widget will be added to the back of the layout (i.e. right for
`HBox`, bottom for `VBox`). The `size` argument specifies how much
space (i.e. width for `HBox`, height for `VBox`) to allocate for the
"cell" that will contain the widget (if you think of the hbox/vbox as a
1-dimensional grid). The size can either be an integer number of
pixels or the string `'expand'`:
- number of pixels (int): The specified number of pixels will be
allocated for the widget, unless that number is smaller than the
widget's minimum size (i.e. its claim). In that case, the widget's
minimum size will be allocated instead (because a widget can't be
smaller than its minimum size). For this reason, `size=0` is a
common setting meaning: "take as little space as possible". Of
course, you can also specify `size=100` to make a cell exactly 100px
wide/tall, assuming that the widget in question is smaller than that.
- `'expand'` (str): A special value indicating that the widget should
expand to fill any space available to the container but not used by
any other cells. For example, imagine you have a `HBox` that's 500px
wide (or a `VBox that's 500 px tall). If you add two widgets with
`size='expand'`, each will get 250 px. If you add one widget with `size=100` and two with `size='expand'`, the first will
If no size is specified, a default is used. The default can be set (in
order of precedence) either via `set_default_cell_size()`, an argument
to the constructor, or the `custom_default_cell_size` class variable.
Examples:
These are with `HBox`, but could equivalently be with `VBox`. Assume
for the sake of simplicity that the `HBox` is 500px wide. Further
assume that `w1`, `w2`, and `w3` are arbitrary widgets with no minimum
size (e.g. `Placeholder`).
In this example, `w1` and `w2` will both be 250px wide (i.e. half the
width of the container):
>>> h1 = glooey.HBox() # 500px wide
>>> h1.add(w1, size='expand')
>>> h1.add(w2, size='expand')
In this example, `w1` will be 100px wide and `w2` and `w3` will split
the remaining space and be 200px each:
>>> h2 = glooey.HBox() # 500px wide
>>> h2.add(w1, size=100)
>>> h2.add(w2, size='expand')
>>> h2.add(w3, size='expand')
"""
self.add_back(widget, size)
def add_front(self, widget, size=None):
"""
Add the given widget to the front of the layout.
The same as `add()`, except the widget will be added to the front of
the layout (i.e. left for `HBox`, top for `VBox`).
"""
self.insert(widget, 0, size)
def add_back(self, widget, size=None):
"""
Add the given widget to the back of the layout.
This is an alias for `add()`.
"""
self.insert(widget, len(self._children), size)
def pack(self, widget):
"""
Add the given widget to the layout such that it takes as little space
as possible.
This is an alias for `add(widget, size=0)`
"""
self.add(widget, size=0)
def pack_front(self, widget):
"""
Add the given widget to the front of layout such that it takes as
little space as possible.
This is an alias for `add_front(widget, size=0)`
"""
self.add_front(widget, size=0)
def pack_back(self, widget):
"""
Add the given widget to the back of layout such that it takes as
little space as possible.
This is an alias for `add_back(widget, size=0)`
"""
self.add_back(widget, size=0)
def insert(self, widget, index, size=None):
"""
Insert the given widget at the given position in the layout.
See `add()` for details about the `size` argument.
"""
self._attach_child(widget)
self._children.insert(index, widget)
self._sizes[widget] = size
self._repack_and_regroup_children()
def replace(self, old_widget, new_widget):
"""
Remove the given old widget from the layout and replace it with the
given new widget.
The new widget will be given the same size (e.g. the `size` argument to
`add()`) as the old widget. That said, the new widget could still take
up a different amount of space, if it's claim is different. The layout
will be repacked automatically if this is the case.
"""
old_index = self._children.index(old_widget)
old_size = self._sizes[old_widget]
with self.hold_updates():
self.remove(old_widget)
self.insert(new_widget, old_index, old_size)
def remove(self, widget):
"""
Remove the given widget from the layout.
"""
self._detach_child(widget)
self._children.remove(widget)
del self._sizes[widget]
self._repack_and_regroup_children()
def clear(self):
"""
Remove every widget from the layout.
"""
for child in self._children:
self._detach_child(child)
self._children = []
self._sizes = {}
self._repack_and_regroup_children()
def do_claim(self):
"""
Claim enough space for all the child widgets put together in the
direction of the layout (e.g. horizontal for `HBox`, vertical for
`VBox`) and just enough space for the largest child widget in the
opposite direction.
"""
self.do_set_row_col_sizes({
i: self._sizes[child]
for i, child in enumerate(self._children)
if self._sizes[child] is not None
})
min_cell_rects = {
self.do_get_row_col(i): child.claimed_rect
for i, child in enumerate(self._children)
}
return self._grid.make_claim(min_cell_rects)
def do_resize_children(self):
"""
Allocate space to the child widgets according to how much space they
asked for when added to the layout (e.g. their "size") and how much
space they need (e.g. their "claim").
"""
cell_rects = self._grid.make_cells(self.rect)
for i, child in enumerate(self._children):
box = cell_rects[self.do_get_row_col(i)]
align_widget_in_box(child, box, self.cell_alignment)
def do_find_children_near_mouse(self, x, y):
"""
Speed up the search for the child widget under the mouse based
This reimplementation is faster than the default implementation, which
simply checks every child widget for collisions with the given mouse
coordinate, because it searches underlying the grid layout instead.
This takes advantage of the following two facts:
1. We know that only one widget can be under the mouse, so we can stop
the search as soon as we find that widget.
2. We only need to check for collisions in the direction of the layout
(i.e. horizontal for `HBox`, vertical for `VBox`), because we know
that all the child widgets will overlap in the opposite direction.
"""
cell = self._grid.find_cell_under_mouse(x, y)
if cell is None: return
child = self._children[self.do_get_index(*cell)]
if child is None: return
yield child
def do_get_index(self, row, col):
"""
Given row and columns number of a child widget, return the index of
that widget in the 1-dimensional `_children` data structure.
This would be the column for `HBox` and the row for `VBox`.
"""
raise NotImplementedError
def do_get_row_col(self, index):
"""
Given the index of a child widget, return its row and column numbers as
a tuple.
The "on-axis" number (e.g. column for `Hbox`, row for `VBox`) should
just be the given index. The "off-axis" number should be 1.
"""
raise NotImplementedError
def do_set_row_col_sizes(self, sizes):
"""
Copy child size information into the underlying grid data structure.
The `sizes` argument is a dictionary mapping 1-dimensional child
indices to the sizes provided by `add()` (e.g. 0, 'expand', etc). This
information either needs to be applied to the columns (`HBox`) or rows
(`VBox`) of the underlying grid data structure.
"""
raise NotImplementedError
def get_children(self):
"""
Return the child widgets being organized by this container.
The return value is a tuple so that the list of children won't be
mutable, and so the caller can't somehow inadvertently change the list
of children held by the container.
"""
return tuple(self._children)
def get_padding(self):
"""
| |
= 2*np.pi * np.sqrt( (np.clip(a, 0, a)**3)/(GLOB_G*M) ) # Units = sec * pc / km
T = _t * GLOB_SecToYr * GLOB_PcToKm
_OE = OrbitElem(a, e_norm, omega * 180 / np.pi, LAN * 180 / np.pi, i * 180 / np.pi, MeanM * 180 / np.pi, T, nu)
return _OE
def OE_Essentials(_parVec:list) -> OrbitElem:
"""
Only calculate e and T to be bounds checked for fit
Parameters
----------
_parVec : Parameter Vector for current orbit
Returns
-------
OrbitalElem Object
"""
Pars = ParVecToParams(_parVec)
M = Pars[0]
r0 = Pars[1]
v0 = Pars[2]
# momentum vector
h = np.cross(r0, v0)
# eccentricity vector
e = np.cross(v0, h) / (GLOB_G*M) - r0/np.linalg.norm(r0)
# eccentricity
e_norm = np.linalg.norm(e)
# semi mayor axis
a = 1/( 2/np.linalg.norm(r0) - np.linalg.norm(v0)**2/(GLOB_G * M) )
_t = 2*np.pi * np.sqrt( (np.clip(a, 0, a)**3)/(GLOB_G*M) ) # Units = sec * pc / km
T = _t * GLOB_SecToYr * GLOB_PcToKm
_OE = OrbitElem(a, e_norm, 0, 0, 0, 0, T, 0)
return _OE
# UTILITY
def PosRadToReal(_r:np.ndarray, _dist:float) -> np.ndarray:
'''
converts the first 2 radial elements to real distance, given the distance
returns position vector in pc
'''
return _r*_dist*GLOB_masToRad
def RadToReal(_x:float, _dist:float) -> float:
'''
return distance in pc for one coordinate
'''
return _x*_dist*GLOB_masToRad
def PosRealToRad(_r:np.ndarray, _dist:float) -> np.ndarray:
'''
converts the real position to radial position in the first 2 elements.
Used for plotting only
returns postion vector with units ('','',pc)
'''
_t = np.array([ _dist*GLOB_masToRad, _dist*GLOB_masToRad, 1 ])
return _r/_t
def potential(r:np.ndarray,v:np.ndarray,_M:float, r_SGRA:np.ndarray=np.array([0,0,0])) -> np.ndarray:
"""
return Kepler acceleration
Parameters
----------
r : [vector]
position of particle to evaluate potential at
_M : [scalar]
Mass of central object
Returns
-------
Potential Strength
"""
# true distance from star to srg a*
dist = r - r_SGRA
return -(GLOB_G*_M*dist) / (np.linalg.norm(dist)**3)
def potentialSchwarz(r:np.ndarray,v:np.ndarray,_M:float, r_SGRA:np.ndarray=np.array([0,0,0])) -> np.ndarray:
"""
return the Schwarzschild acceleration
Parameters
----------
r : [vector]
position of particle to evaluate potential at
v : [vector]
velocity of particle
_M : [scalar]
Mass of central object
Returns
-------
Schwarzschild Potential Strength: Kepler Potential + a/r^3
"""
h = np.cross(r,v) # specific angular momentum
kepl = potential(r,v,_M)
Schw = (3 * GLOB_G * _M * np.dot(h,h) * r) / (GLOB_c**2 * np.linalg.norm(r)**5)
return kepl + Schw
def VerletStep(h:float,r0:np.ndarray,v0:np.ndarray,f0:np.ndarray,_M:float, r_SGRA:np.ndarray=np.array([0,0,0])) -> np.ndarray:
"""
Orbital Integration using the Verlet Algorithm
Parameters
----------
h : [scalar]
stepsize -> delta t
r0 : [vector]
position of particle from last evaluation
v0 : [vector]
velocity of particle from last evaluation
f0 : [scalar]
potential strength from last evaluation step
_M : [scalar]
Mass of central object
func : [function]
Potential function to evaluate
Returns
-------
[r1, v1, f1]
position, velocity and potential of new step
"""
pp = np.add(v0, h/2*f0) # 1/2 Delta velocity
r1 = np.add(r0, h*pp) # new position = r0 + del v*del t
f1 = potential(r1,v0,_M, r_SGRA) # new potential at new position
v1 = np.add(pp, h/2*f1) # new velocity = v0 + 1/2 del a0*del t + 1/2 del a1*del t
return np.array([r1,v1,f1])
def VerletStepSchwarz(h:float,r0:np.ndarray,v0:np.ndarray,f0:np.ndarray,_M:float, r_SGRA:np.ndarray=np.array([0,0,0])) -> np.ndarray:
"""
Orbital Integration using the Verlet Algorithm
Parameters
----------
h : [scalar]
stepsize -> delta t
r0 : [vector]
position of particle from last evaluation
v0 : [vector]
velocity of particle from last evaluation
f0 : [scalar]
potential strength from last evaluation step
_M : [scalar]
Mass of central object
func : [function]
Potential function to evaluate
Returns
-------
[r1, v1, f1]
position, velocity and potential of new step
"""
pp = np.add(v0, h/2*f0) # 1/2 Delta velocity
r1 = np.add(r0, h*pp) # new position = r0 + del v*del t
f1 = potentialSchwarz(r1,pp,_M) # new potential at new position
v1 = np.add(pp, h/2*f1) # new velocity = v0 + 1/2 del a0*del t + 1/2 del a1*del t
return np.array([r1,v1,f1])
def returnDataError(rData:np.ndarray, rDataErr:np.ndarray, rTime:np.ndarray, Fake:np.ndarray, fTimeEnd:float) -> list:
"""
evaluates how much fake deviates from data
data and fake must begin at the same point, for this to work
Parameters
----------
rData : np.ndarray
real Data to compare Fake Data against
rDataErr : np.ndarray
Error for real Data, used in chi calculation
rTime : np.ndarray
Timestamps for all real Data points
Fake : np.ndarray
Fake Data points that will be compared to real Data
fTimeEnd : float
Total End Time of Fake Data, this function will create its own time array based on this value
Returns
-------
[ x_time, y_UsedData, chi^2 value]
"""
# create timing for fake data
fakeTimeline = np.linspace(0,fTimeEnd, len(Fake))
newTimeOfFake = np.empty(len(rTime))
newValues = np.empty(len(rTime))
j = 0
# determine closest fakeTime for every measured timestamp
# if fake orbit shorter than measured time => last measured points get ignored
# if fake orbit longer than measured time => last fake points get ignored
for i in range(len(rTime)):
for k in range(j, len(fakeTimeline)):
if (fakeTimeline[k] >= rTime[i]):
newTimeOfFake[i] = fakeTimeline[k]
newValues[i] = Fake[k]
j = k
break
chi2 = ((rData - newValues)/rDataErr)**2
return [newTimeOfFake, newValues, np.sum( chi2 ), chi2]
def returnCombinedError(StarData:DataContainer, FitData:FitContainer, _in, redshiftCorr:bool = False) -> float:
"""
combines all measurement errors
Parameters
----------
StarData : DataContainer
The Star Data
FitData : FitContainer
The Fit Data, prior to any Error Calculation, Error will be overwritten
_in : [_index_R, _index_V]
Index point of starting data
redshiftCorr : bool
use redshift correction in error calculation? Only for Schwarzschild potential
Returns
-------
chi^2 value for current parameters
"""
if FitData.success:
# create timing for fake data
_eT = StarData.TimeP[_in[0]] - StarData.TimeP[0] + FitData.OrbitNumber * FitData.OrbElem.Period
# error on every measurement
Err_RA = returnDataError(StarData.RA, StarData.eRA, StarData.TimeP - StarData.TimeP[0], FitData.PosPath[0], _eT)
Err_DE = returnDataError(StarData.DE, StarData.eDE, StarData.TimeP - StarData.TimeP[0], FitData.PosPath[1], _eT)
# rad vel points need to be shifted by the same amount as the position data for consistency
if redshiftCorr:
fakeTimeline = np.linspace(0,_eT, len(FitData.VPath))
j = 0
rTime = StarData.TimeV - StarData.TimeP[0]
#newVR_Timeline = np.empty(len(rTime))
LengthAtVR = np.empty(len(rTime))
newFakeVR = np.empty(len(rTime))
for i in range(len(rTime)):
for k in range(j, len(fakeTimeline)):
if (fakeTimeline[k] >= rTime[i]):
#newVR_Timeline[i] = fakeTimeline[k]
LengthAtVR[i] = np.linalg.norm(FitData.PositionArray[k]) #FitData.PositionArray[k][2] #
newFakeVR[i] = FitData.VPath[k]
j = k
break
PN_VR = StarData.VR - getGravRedshift(FitData.Mass, LengthAtVR)
_chi2 = ((PN_VR - newFakeVR)/StarData.eVR)**2
Err_Vz = [StarData.TimeV - StarData.TimeP[0], PN_VR, np.sum( _chi2 ), _chi2]
else:
Err_Vz = returnDataError(StarData.VR, StarData.eVR, StarData.TimeV - StarData.TimeP[0], FitData.VPath, _eT)
lenPos = len(StarData.RA)
lenVel = len(StarData.VR)
NPos = lenPos / (lenPos + lenVel)
NVel = lenVel / (lenPos + lenVel)
#print("len: ", len(Err_RA[3]) + len(Err_DE[3]) + len(Err_Vz[3]))
FitData.initErrorData(Err_RA, Err_DE, Err_Vz) # save individual errors in FitData
# chi^2 value
#chi2 = (Err_RA[2] + Err_DE[2] + Err_Vz[2])
chi2 = (NPos * Err_RA[2] + NPos * Err_DE[2] + NVel * Err_Vz[2])
#Nlen = len(Err_RA[3]) + len(Err_DE[3]) + len(Err_Vz[3])
#chi2 = chi2/Nlen
return chi2
else:
return 1E10
def returnCombinedErrorFromFile(SD:DataContainer, FitData:FitContainer, _in) -> float:
_OFile = open(OrbitFileForewrd, 'r')
_line = _OFile.readline()
NumberLines = -2
StartBackwards = -1
while _line:
NumberLines += 1
if _line[0] == '#' and NumberLines > 0:
StartBackwards = NumberLines
_line = _OFile.readline()
_OFile.close()
_OFile = open(OrbitFileForewrd, 'r')
_line = _OFile.readline()
chi2RA = 0
chi2DE = 0
chi2VR = 0
fCount = -1
PositionRealTime = SD.TimeP - SD.TimeP[0]
VelocityRealTime = SD.TimeV - SD.TimeP[0]
# end of time
_eT = SD.TimeP[_in[0]] - SD.TimeP[0] + FitData.OrbitNumber * FitData.OrbElem.Period
# time from index point to ent of time
fakeTimeline = np.linspace(SD.TimeP[_in[0]] - SD.TimeP[0], _eT, StartBackwards - 1)
fakeTimelineBack = np.linspace(0, SD.TimeP[_in[0]] - SD.TimeP[0], NumberLines - StartBackwards)
fakeTimelineBack = np.flip(fakeTimelineBack)
rUsedF = []
vUsedF = []
RAIndex = 0
VRIndex = 0
count = 1
# forward
while _line:
if count > StartBackwards:
break
count += 1
_t = _line.strip()
_line = _OFile.readline()
if _t[0] != '#':
_t = _t.split(" ")
_t = [float(x) for x in _t]
r = np.array(_t[:3])
v = np.array(_t[3:])
if fakeTimeline[count-1] >= PositionRealTime[RAIndex]:
rUsedF.append(r)
RAIndex = count - 1
if fakeTimeline[count - 1] >= VelocityRealTime[VRIndex]:
vUsedF.append(v)
VRIndex | |
numpy.
if issubclass(b.dtype.type, numpy.complexfloating):
# if complex roots are all complex conjugates, the roots are real.
roots = numpy.asarray(z, complex)
pos_roots = numpy.compress(roots.imag > 0, roots)
neg_roots = numpy.conjugate(numpy.compress(roots.imag < 0, roots))
if len(pos_roots) == len(neg_roots):
if numpy.all(numpy.sort_complex(neg_roots) ==
numpy.sort_complex(pos_roots)):
b = b.real.copy()
if issubclass(a.dtype.type, numpy.complexfloating):
# if complex roots are all complex conjugates, the roots are real.
roots = numpy.asarray(p, complex)
pos_roots = numpy.compress(roots.imag > 0, roots)
neg_roots = numpy.conjugate(numpy.compress(roots.imag < 0, roots))
if len(pos_roots) == len(neg_roots):
if numpy.all(numpy.sort_complex(neg_roots) ==
numpy.sort_complex(pos_roots)):
a = a.real.copy()
return b, a
def tf2sos(b, a, pairing='nearest'):
"""
Return second-order sections from transfer function representation
Parameters
----------
b : array_like
Numerator polynomial coefficients.
a : array_like
Denominator polynomial coefficients.
pairing : {'nearest', 'keep_odd'}, optional
The method to use to combine pairs of poles and zeros into sections.
See `zpk2sos`.
Returns
-------
sos : ndarray
Array of second-order filter coefficients, with shape
``(n_sections, 6)``. See `sosfilt` for the SOS filter format
specification.
See Also
--------
zpk2sos, sosfilt
Notes
-----
It is generally discouraged to convert from TF to SOS format, since doing
so usually will not improve numerical precision errors. Instead, consider
designing filters in ZPK format and converting directly to SOS. TF is
converted to SOS by first converting to ZPK format, then converting
ZPK to SOS.
.. versionadded:: 0.16.0
"""
return zpk2sos(*tf2zpk(b, a), pairing=pairing)
def sos2tf(sos):
"""
Return a single transfer function from a series of second-order sections
Parameters
----------
sos : array_like
Array of second-order filter coefficients, must have shape
``(n_sections, 6)``. See `sosfilt` for the SOS filter format
specification.
Returns
-------
b : ndarray
Numerator polynomial coefficients.
a : ndarray
Denominator polynomial coefficients.
Notes
-----
.. versionadded:: 0.16.0
"""
sos = np.asarray(sos)
b = [1.]
a = [1.]
n_sections = sos.shape[0]
for section in range(n_sections):
b = np.polymul(b, sos[section, :3])
a = np.polymul(a, sos[section, 3:])
return b, a
def sos2zpk(sos):
"""
Return zeros, poles, and gain of a series of second-order sections
Parameters
----------
sos : array_like
Array of second-order filter coefficients, must have shape
``(n_sections, 6)``. See `sosfilt` for the SOS filter format
specification.
Returns
-------
z : ndarray
Zeros of the transfer function.
p : ndarray
Poles of the transfer function.
k : float
System gain.
Notes
-----
.. versionadded:: 0.16.0
"""
sos = np.asarray(sos)
n_sections = sos.shape[0]
z = np.empty(n_sections*2, np.complex128)
p = np.empty(n_sections*2, np.complex128)
k = 1.
for section in range(n_sections):
zpk = tf2zpk(sos[section, :3], sos[section, 3:])
z[2*section:2*(section+1)] = zpk[0]
p[2*section:2*(section+1)] = zpk[1]
k *= zpk[2]
return z, p, k
def _nearest_real_complex_idx(fro, to, which):
"""Get the next closest real or complex element based on distance"""
assert which in ('real', 'complex')
order = np.argsort(np.abs(fro - to))
mask = np.isreal(fro[order])
if which == 'complex':
mask = ~mask
return order[np.where(mask)[0][0]]
def zpk2sos(z, p, k, pairing='nearest'):
"""
Return second-order sections from zeros, poles, and gain of a system
Parameters
----------
z : array_like
Zeros of the transfer function.
p : array_like
Poles of the transfer function.
k : float
System gain.
pairing : {'nearest', 'keep_odd'}, optional
The method to use to combine pairs of poles and zeros into sections.
See Notes below.
Returns
-------
sos : ndarray
Array of second-order filter coefficients, with shape
``(n_sections, 6)``. See `sosfilt` for the SOS filter format
specification.
See Also
--------
sosfilt
Notes
-----
The algorithm used to convert ZPK to SOS format is designed to
minimize errors due to numerical precision issues. The pairing
algorithm attempts to minimize the peak gain of each biquadratic
section. This is done by pairing poles with the nearest zeros, starting
with the poles closest to the unit circle.
*Algorithms*
The current algorithms are designed specifically for use with digital
filters. (The output coefficents are not correct for analog filters.)
The steps in the ``pairing='nearest'`` and ``pairing='keep_odd'``
algorithms are mostly shared. The ``nearest`` algorithm attempts to
minimize the peak gain, while ``'keep_odd'`` minimizes peak gain under
the constraint that odd-order systems should retain one section
as first order. The algorithm steps and are as follows:
As a pre-processing step, add poles or zeros to the origin as
necessary to obtain the same number of poles and zeros for pairing.
If ``pairing == 'nearest'`` and there are an odd number of poles,
add an additional pole and a zero at the origin.
The following steps are then iterated over until no more poles or
zeros remain:
1. Take the (next remaining) pole (complex or real) closest to the
unit circle to begin a new filter section.
2. If the pole is real and there are no other remaining real poles [#]_,
add the closest real zero to the section and leave it as a first
order section. Note that after this step we are guaranteed to be
left with an even number of real poles, complex poles, real zeros,
and complex zeros for subsequent pairing iterations.
3. Else:
1. If the pole is complex and the zero is the only remaining real
zero*, then pair the pole with the *next* closest zero
(guaranteed to be complex). This is necessary to ensure that
there will be a real zero remaining to eventually create a
first-order section (thus keeping the odd order).
2. Else pair the pole with the closest remaining zero (complex or
real).
3. Proceed to complete the second-order section by adding another
pole and zero to the current pole and zero in the section:
1. If the current pole and zero are both complex, add their
conjugates.
2. Else if the pole is complex and the zero is real, add the
conjugate pole and the next closest real zero.
3. Else if the pole is real and the zero is complex, add the
conjugate zero and the real pole closest to those zeros.
4. Else (we must have a real pole and real zero) add the next
real pole closest to the unit circle, and then add the real
zero closest to that pole.
.. [#] This conditional can only be met for specific odd-order inputs
with the ``pairing == 'keep_odd'`` method.
.. versionadded:: 0.16.0
Examples
--------
Design a 6th order low-pass elliptic digital filter for a system with a
sampling rate of 8000 Hz that has a pass-band corner frequency of
1000 Hz. The ripple in the pass-band should not exceed 0.087 dB, and
the attenuation in the stop-band should be at least 90 dB.
In the following call to `signal.ellip`, we could use ``output='sos'``,
but for this example, we'll use ``output='zpk'``, and then convert to SOS
format with `zpk2sos`:
>>> from scipy import signal
>>> z, p, k = signal.ellip(6, 0.087, 90, 1000/(0.5*8000), output='zpk')
Now convert to SOS format.
>>> sos = signal.zpk2sos(z, p, k)
The coefficients of the numerators of the sections:
>>> sos[:, :3]
array([[ 0.0014154 , 0.00248707, 0.0014154 ],
[ 1. , 0.72965193, 1. ],
[ 1. , 0.17594966, 1. ]])
The symmetry in the coefficients occurs because all the zeros are on the
unit circle.
The coefficients of the denominators of the sections:
>>> sos[:, 3:]
array([[ 1. , -1.32543251, 0.46989499],
[ 1. , -1.26117915, 0.6262586 ],
[ 1. , -1.25707217, 0.86199667]])
The next example shows the effect of the `pairing` option. We have a
system with three poles and three zeros, so the SOS array will have
shape (2, 6). The means there is, in effect, an extra pole and an extra
zero at the origin in the SOS representation.
>>> z1 = np.array([-1, -0.5-0.5j, -0.5+0.5j])
>>> p1 = np.array([0.75, 0.8+0.1j, 0.8-0.1j])
With ``pairing='nearest'`` (the default), we obtain
>>> signal.zpk2sos(z1, p1, 1)
array([[ 1. , 1. , 0.5 , 1. , -0.75, 0. ],
[ 1. , 1. , 0. , 1. , -1.6 , 0.65]])
The first section has the zeros {-0.5-0.05j, -0.5+0.5j} and the poles
{0, 0.75}, and the second section has the zeros {-1, 0} | |
# coding: utf-8
"""
Copyright (c) 2021 Aspose.Cells Cloud
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
"""
from pprint import pformat
from six import iteritems
import re
class Shape(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'link': 'Link',
'alternative_text': 'str',
'bottom': 'int',
'top': 'int',
'width': 'int',
'html_text': 'str',
'text_vertical_alignment': 'str',
'auto_shape_type': 'str',
'is_printable': 'bool',
'upper_left_column': 'int',
'is_lock_aspect_ratio': 'bool',
'is_group': 'bool',
'rotation_angle': 'float',
'z_order_position': 'int',
'text_horizontal_overflow': 'str',
'mso_drawing_type': 'str',
'text_orientation_type': 'str',
'placement': 'str',
'name': 'str',
'is_word_art': 'bool',
'linked_cell': 'str',
'upper_left_row': 'int',
'is_locked': 'bool',
'lower_right_row': 'int',
'is_text_wrapped': 'bool',
'y': 'int',
'x': 'int',
'is_hidden': 'bool',
'left': 'int',
'right': 'int',
'text': 'str',
'lower_right_column': 'int',
'height': 'int',
'text_horizontal_alignment': 'str',
'text_vertical_overflow': 'str'
}
attribute_map = {
'link': 'link',
'alternative_text': 'AlternativeText',
'bottom': 'Bottom',
'top': 'Top',
'width': 'Width',
'html_text': 'HtmlText',
'text_vertical_alignment': 'TextVerticalAlignment',
'auto_shape_type': 'AutoShapeType',
'is_printable': 'IsPrintable',
'upper_left_column': 'UpperLeftColumn',
'is_lock_aspect_ratio': 'IsLockAspectRatio',
'is_group': 'IsGroup',
'rotation_angle': 'RotationAngle',
'z_order_position': 'ZOrderPosition',
'text_horizontal_overflow': 'TextHorizontalOverflow',
'mso_drawing_type': 'MsoDrawingType',
'text_orientation_type': 'TextOrientationType',
'placement': 'Placement',
'name': 'Name',
'is_word_art': 'IsWordArt',
'linked_cell': 'LinkedCell',
'upper_left_row': 'UpperLeftRow',
'is_locked': 'IsLocked',
'lower_right_row': 'LowerRightRow',
'is_text_wrapped': 'IsTextWrapped',
'y': 'Y',
'x': 'X',
'is_hidden': 'IsHidden',
'left': 'Left',
'right': 'Right',
'text': 'Text',
'lower_right_column': 'LowerRightColumn',
'height': 'Height',
'text_horizontal_alignment': 'TextHorizontalAlignment',
'text_vertical_overflow': 'TextVerticalOverflow'
}
@staticmethod
def get_swagger_types():
return Shape.swagger_types
@staticmethod
def get_attribute_map():
return Shape.attribute_map
def get_from_container(self, attr):
if attr in self.container:
return self.container[attr]
return None
def __init__(self, link=None, alternative_text=None, bottom=None, top=None, width=None, html_text=None, text_vertical_alignment=None, auto_shape_type=None, is_printable=None, upper_left_column=None, is_lock_aspect_ratio=None, is_group=None, rotation_angle=None, z_order_position=None, text_horizontal_overflow=None, mso_drawing_type=None, text_orientation_type=None, placement=None, name=None, is_word_art=None, linked_cell=None, upper_left_row=None, is_locked=None, lower_right_row=None, is_text_wrapped=None, y=None, x=None, is_hidden=None, left=None, right=None, text=None, lower_right_column=None, height=None, text_horizontal_alignment=None, text_vertical_overflow=None, **kw):
"""
Associative dict for storing property values
"""
self.container = {}
"""
Shape - a model defined in Swagger
"""
self.container['link'] = None
self.container['alternative_text'] = None
self.container['bottom'] = None
self.container['top'] = None
self.container['width'] = None
self.container['html_text'] = None
self.container['text_vertical_alignment'] = None
self.container['auto_shape_type'] = None
self.container['is_printable'] = None
self.container['upper_left_column'] = None
self.container['is_lock_aspect_ratio'] = None
self.container['is_group'] = None
self.container['rotation_angle'] = None
self.container['z_order_position'] = None
self.container['text_horizontal_overflow'] = None
self.container['mso_drawing_type'] = None
self.container['text_orientation_type'] = None
self.container['placement'] = None
self.container['name'] = None
self.container['is_word_art'] = None
self.container['linked_cell'] = None
self.container['upper_left_row'] = None
self.container['is_locked'] = None
self.container['lower_right_row'] = None
self.container['is_text_wrapped'] = None
self.container['y'] = None
self.container['x'] = None
self.container['is_hidden'] = None
self.container['left'] = None
self.container['right'] = None
self.container['text'] = None
self.container['lower_right_column'] = None
self.container['height'] = None
self.container['text_horizontal_alignment'] = None
self.container['text_vertical_overflow'] = None
if link is not None:
self.link = link
if alternative_text is not None:
self.alternative_text = alternative_text
if bottom is not None:
self.bottom = bottom
if top is not None:
self.top = top
if width is not None:
self.width = width
if html_text is not None:
self.html_text = html_text
if text_vertical_alignment is not None:
self.text_vertical_alignment = text_vertical_alignment
if auto_shape_type is not None:
self.auto_shape_type = auto_shape_type
if is_printable is not None:
self.is_printable = is_printable
if upper_left_column is not None:
self.upper_left_column = upper_left_column
if is_lock_aspect_ratio is not None:
self.is_lock_aspect_ratio = is_lock_aspect_ratio
if is_group is not None:
self.is_group = is_group
if rotation_angle is not None:
self.rotation_angle = rotation_angle
if z_order_position is not None:
self.z_order_position = z_order_position
if text_horizontal_overflow is not None:
self.text_horizontal_overflow = text_horizontal_overflow
if mso_drawing_type is not None:
self.mso_drawing_type = mso_drawing_type
if text_orientation_type is not None:
self.text_orientation_type = text_orientation_type
if placement is not None:
self.placement = placement
if name is not None:
self.name = name
if is_word_art is not None:
self.is_word_art = is_word_art
if linked_cell is not None:
self.linked_cell = linked_cell
if upper_left_row is not None:
self.upper_left_row = upper_left_row
if is_locked is not None:
self.is_locked = is_locked
if lower_right_row is not None:
self.lower_right_row = lower_right_row
if is_text_wrapped is not None:
self.is_text_wrapped = is_text_wrapped
if y is not None:
self.y = y
if x is not None:
self.x = x
if is_hidden is not None:
self.is_hidden = is_hidden
if left is not None:
self.left = left
if right is not None:
self.right = right
if text is not None:
self.text = text
if lower_right_column is not None:
self.lower_right_column = lower_right_column
if height is not None:
self.height = height
if text_horizontal_alignment is not None:
self.text_horizontal_alignment = text_horizontal_alignment
if text_vertical_overflow is not None:
self.text_vertical_overflow = text_vertical_overflow
@property
def link(self):
"""
Gets the link of this Shape.
:return: The link of this Shape.
:rtype: Link
"""
return self.container['link']
@link.setter
def link(self, link):
"""
Sets the link of this Shape.
:param link: The link of this Shape.
:type: Link
"""
self.container['link'] = link
@property
def alternative_text(self):
"""
Gets the alternative_text of this Shape.
:return: The alternative_text of this Shape.
:rtype: str
"""
return self.container['alternative_text']
@alternative_text.setter
def alternative_text(self, alternative_text):
"""
Sets the alternative_text of this Shape.
:param alternative_text: The alternative_text of this Shape.
:type: str
"""
self.container['alternative_text'] = alternative_text
@property
def bottom(self):
"""
Gets the bottom of this Shape.
:return: The bottom of this Shape.
:rtype: int
"""
return self.container['bottom']
@bottom.setter
def bottom(self, bottom):
"""
Sets the bottom of this Shape.
:param bottom: The bottom of this Shape.
:type: int
"""
self.container['bottom'] = bottom
@property
def top(self):
"""
Gets the top of this Shape.
:return: The top of this Shape.
:rtype: int
"""
return self.container['top']
@top.setter
def top(self, top):
"""
Sets the top of this Shape.
:param top: The top of this Shape.
:type: int
"""
self.container['top'] = top
@property
def width(self):
"""
Gets the width of this Shape.
:return: The width of this Shape.
:rtype: int
"""
return self.container['width']
@width.setter
def width(self, width):
"""
Sets the width of this Shape.
:param width: The width of this Shape.
:type: int
"""
self.container['width'] = width
@property
def html_text(self):
"""
Gets the html_text of this Shape.
:return: The html_text of this Shape.
:rtype: str
"""
return self.container['html_text']
@html_text.setter
def html_text(self, html_text):
"""
Sets the html_text of this Shape.
:param html_text: The html_text of this Shape.
:type: str
"""
self.container['html_text'] = html_text
@property
def text_vertical_alignment(self):
"""
Gets the text_vertical_alignment of this Shape.
:return: The text_vertical_alignment of this Shape.
:rtype: str
"""
return self.container['text_vertical_alignment']
@text_vertical_alignment.setter
def text_vertical_alignment(self, text_vertical_alignment):
"""
Sets the text_vertical_alignment of this Shape.
:param text_vertical_alignment: The text_vertical_alignment of this Shape.
:type: str
"""
self.container['text_vertical_alignment'] = text_vertical_alignment
@property
def auto_shape_type(self):
"""
Gets the auto_shape_type of this Shape.
:return: The auto_shape_type of this Shape.
:rtype: str
"""
return self.container['auto_shape_type']
@auto_shape_type.setter
def auto_shape_type(self, auto_shape_type):
"""
Sets the auto_shape_type of this Shape.
:param auto_shape_type: The auto_shape_type of this Shape.
:type: str
"""
self.container['auto_shape_type'] = auto_shape_type
@property
def is_printable(self):
"""
Gets the is_printable of this Shape.
:return: The is_printable of this Shape.
:rtype: bool
"""
return self.container['is_printable']
@is_printable.setter
def is_printable(self, is_printable):
"""
Sets the is_printable of this Shape.
:param is_printable: The is_printable of this Shape.
:type: bool
"""
self.container['is_printable'] = is_printable
@property
def upper_left_column(self):
"""
Gets the upper_left_column of this Shape.
:return: The upper_left_column of this Shape.
:rtype: int
"""
return self.container['upper_left_column']
@upper_left_column.setter
def upper_left_column(self, upper_left_column):
"""
Sets the upper_left_column of this Shape.
:param upper_left_column: The upper_left_column of this Shape.
:type: int
"""
self.container['upper_left_column'] = upper_left_column
| |
"""+==========================+========-========*========-========+==========================+
|| Lab11.5: Othello2 ||
|| Name: <NAME> Date: 01/13/15 ||
+==========================+========-========*========-========+==========================+
This program plays a game of Othello using alpha and beta
"""
##############################################<START OF PROGRAM>##############################################
def setUpCanvas(root): # These are the REQUIRED magic lines to enter graphics mode.
root.title("A Tk/Python Graphics Program") # Your screen size may be different from 1270 x 780.
canvas = Canvas(root, width = 1270, height = 780, bg = 'GREY30')
canvas.pack(expand = YES, fill = BOTH)
return canvas
#----------------------------------------------------------------------------------------------------Othello--
def createMatrix(): # = the initial position, with Black = 1, and white = -1. OK
M = [ [0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0,-1, 1, 0, 0, 0,], # The matrix M is GLOBAL.
[0, 0, 0, 1,-1, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0,],]
return M
#----------------------------------------------------------------------------------------------------Othello--
def initializePointMatrices():
global pointValueMatrixforWhite, pointValueMatrixforBlack
#---The COMPUTER's strategy will be based off of this GLOBAL matrix, which will be modified as
# the board configuration changes. Remember: row (going down) is first: P[row][col].
pointValueMatrixforWhite = \
[ [48, 6, 6, 6, 6, 6, 6, 48,], # P[0][0], P[0][1], ..., P[0][7]
[ 6, -24, -4, -4, -4, -4, -24, 6,], # P[1][0], P[1][1], ..., P[1][7]
[ 6, -4, 1, 1, 1, 1, -4, 6,], # P[2][0], P[2][1], ..., P[2][7]
[ 6, -4, 1, 1, 1, 1, -4, 6,], # P[3][0], P[3][1], ..., P[3][7]
[ 6, -4, 1, 1, 1, 1, -4, 6,], # P[4][0], P[4][1], ..., P[4][7]
[ 6, -4, 1, 1, 1, 1, -4, 6,], # P[5][0], P[5][1], ..., P[5][7]
[ 6, -24, -4, -4, -4, -4, -24, 6,], # P[6][0], P[6][1], ..., P[6][7]
[48, 6, 6, 6, 6, 6, 6, 48,],]# P[7][0], P[7][1], ..., P[7][7]
from copy import deepcopy
pointValueMatrixforBlack = deepcopy(pointValueMatrixforWhite)
return pointValueMatrixforWhite, pointValueMatrixforBlack
#----------------------------------------------------------------------------------------------------Othello--
def updateTheFourCorners():
global pointValueMatrixforWhite, pointValueMatrixforBlack
#---1B. Modify upper-left corner cell's values if the HUMAN has taken that corner.
if M[0][0] == 1:
if M[0][2] in [0,-1]: pointValueMatrixforWhite[0][1] = -4 # bad move for white (computer)
if M[2][0] in [0,-1]: pointValueMatrixforWhite[1][0] = -4 # bad move for white (computer)
pointValueMatrixforWhite[1][1] = -4 # bad move for white (computer)
pointValueMatrixforBlack[1][1] = 3 # good move for black (human)
#---2B. Modify upper-right corner cell's values if the HUMAN has taken that corner.
if M[0][7] == 1:
if M[0][5] in [0,-1]: pointValueMatrixforWhite[0][6] = -4 # bad move for white (computer)
if M[2][7] in [0,-1]: pointValueMatrixforWhite[1][7] = -4 # bad move for white (computer)
pointValueMatrixforWhite[1][6] = -4 # bad move for white (computer)
pointValueMatrixforBlack[1][6] = 3 # good move for black (human)
#---3B. Modify lower-left corner cell's values if the HUMAN has taken that corner.
if M[7][0] == 1:
if M[5][0] in [0,-1]: pointValueMatrixforWhite[6][0] = -4 # bad move for white (computer)
if M[7][2] in [0,-1]: pointValueMatrixforWhite[7][1] = -4 # bad move for white (computer)
pointValueMatrixforWhite[6][1] = -4 # bad move for white (computer)
pointValueMatrixforBlack[6][1] = 3 # good move for black (human)
#---4B. Modify lower-right corner cell's values if the HUMAN has taken that corner.
if M[7][7] == 1:
if M[7][5] in [0,-1]: pointValueMatrixforWhite[7][6] = -4 # bad move for white (computer)
if M[5][7] in [0,-1]: pointValueMatrixforWhite[6][7] = -4 # bad move for white (computer)
pointValueMatrixforWhite[6][6] = -4 # bad move for white (computer)
pointValueMatrixforBlack[6][6] = 3 # good move for black (human)
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#---1W. Modify upper-left corner cell's values if the COMPUTER has taken that corner.
if M[0][0] == -1:
if M[0][2] in [0,1]: pointValueMatrixforBlack[0][1] = -4 # bad move for black (human)
if M[2][0] in [0,1]: pointValueMatrixforBlack[1][0] = -4 # bad move for black (human)
pointValueMatrixforBlack[1][1] = -4 # bad move for black (human)
pointValueMatrixforWhite[1][1] = 3 # good move for white (computer)
#---2W. Modify upper-right corner cell's values if the COMPUTER has taken that corner.
if M[0][7] == -1:
if M[0][5] in [0,1]: pointValueMatrixforBlack[0][6] = -4 # bad move for black (human)
if M[2][7] in [0,1]: pointValueMatrixforBlack[1][7] = -4 # bad move for black (human)
pointValueMatrixforBlack[1][6] = -4 # bad move for black (human)
pointValueMatrixforWhite[1][6] = 3 # good move for white (computer)
#---3W. Modify lower-left corner cell's values if the COMPUTER has taken that corner.
if M[7][0] == -1:
if M[5][0] in [0,1]: pointValueMatrixforBlack[6][0] = -4 # bad move for black (human)
if M[7][2] in [0,1]: pointValueMatrixforBlack[7][1] = -4 # bad move for black (human)
pointValueMatrixforBlack[6][1] = -4 # bad move for black (human)
pointValueMatrixforWhite[6][1] = 3 # good move for white (computer)
#---4W. Modify lower-right corner cell's values if the COMPUTER has taken that corner.
if M[7][7] == -1:
if M[7][5] in [0,1]: pointValueMatrixforBlack[7][6] = -4 # bad move for black (human)
if M[5][7] in [0,1]: pointValueMatrixforBlack[6][7] = -4 # bad move for black (human)
pointValueMatrixforBlack[6][6] = -4 # bad move for black (human))
pointValueMatrixforWhite[6][6] = 3 # good move for white (computer)
#----------------------------------------------------------------------------------------------------Othello--
def updateTheMiddleRowsAndColumns():
global pointValueMatrixforWhite, pointValueMatrixforBlack
for n in range (2, 6):
if M[0][n] == -1:
pointValueMatrixforWhite[1][n] = 2 # TOP row
pointValueMatrixforBlack[1][n] = -1 # TOP row
if M[7][n] == -1:
pointValueMatrixforWhite[6][n] = 2 # BOTTOM row
pointValueMatrixforBlack[6][n] = -1 # BOTTOM row
if M[n][0] == -1:
pointValueMatrixforWhite[n][1] = 2 # LEFT column
pointValueMatrixforBlack[n][1] = -1 # LEFT column
if M[n][7] == -1:
pointValueMatrixforWhite[n][6] = 2 # RIGHT column
pointValueMatrixforBlack[n][6] = -1 # RIGHT column
if M[0][n] == 1:
pointValueMatrixforWhite[1][n] = -1 # TOP row
pointValueMatrixforBlack[1][n] = 2 # TOP row
if M[7][n] == 1:
pointValueMatrixforWhite[6][n] = -1 # BOTTOM row
pointValueMatrixforBlack[6][n] = 2 # BOTTOM row
if M[n][0] == 1:
pointValueMatrixforWhite[n][1] = -1 # LEFT column
pointValueMatrixforBlack[n][1] = 2 # LEFT column
if M[n][7] == 1:
pointValueMatrixforWhite[n][6] = -1 # RIGHT column
pointValueMatrixforBlack[n][6] = 2 # RIGHT column
#----------------------------------------------------------------------------------------------------Othello--
def updateThePointMatrices():
initializePointMatrices()
updateTheFourCorners()
updateTheMiddleRowsAndColumns()
#----------------------------------------------------------------------------------------------------Othello--
def copyMatrixToScreen():
canvas.create_text(30,30, text="x", fill = 'BLACK', font = ('Helvetica',1))
for r in range (8):
for c in range (8):
if M[r][c] == 1:
sx = c*70 + 85
sy = r*70 + 105
canvas.create_oval(sx-25,sy-25, sx+25, sy+25, fill = 'BLACK')
if M[r][c] == -1:
sx = c*70 + 85
sy = r*70 + 105
canvas.create_oval(sx-25,sy-25, sx+25, sy+25, fill = 'WHITE')
canvas.update()
#----------------------------------------------------------------------------------------------------Othello--
def showComputersMovesInRedOnScreen (r, c, pieces):
#---If white just moved, then make that stone red
sy = r*70 + 105
sx = c*70 + 85
canvas.create_oval(sx-15,sy-15, sx+15, sy+15, fill = 'RED')
#------Turn any black stones partially white if they are about to be about to be turned over.
for r,c in pieces:
sy = r*70 + 105
sx = c*70 + 85
canvas.create_oval(sx-15,sy-15, sx+15, sy+15, fill = 'WHITE')
canvas.update()
sleep(PAUSE_TIME)
#----------------------------------------------------------------------------------------------------Othello--
def copyOldBoardToScreenInMiniaturizedForm(rr, cc):
#--erase previous miniature board
canvas.create_rectangle(650, 400, 821, 567, width = 5, fill = 'GRAY30')
ch = chr(9679)
for r in range (8):
for c in range (8):
sx = c*20 + 665
sy = r*20 + 412
if M[r][c] == 1:
canvas.create_text(sx, sy, text = ch, fill = 'BLACK', font = ('Helvetica', 20, 'bold') )
if M[r][c] == -1:
canvas.create_text(sx, sy, text = ch, fill = 'WHITE', font = ('Helvetica', 20, 'bold') )
canvas.create_text(cc*20 + 665, rr*20 + 413, text = 'B', fill = 'BLACK', \
font = ('Helvetica', 9, 'bold') )
canvas.update() # make all previous changes to the canvas
#----------------------------------------------------------------------------------------------------Othello--
def score(): # returns the number of black disks and white disks.
whiteTotal = 0; blackTotal = 0
for r in range(8):
for c in range (8):
if M[r][c] == 1: blackTotal += 1
if M[r][c] == -1: whiteTotal += 1
return (blackTotal, whiteTotal)
#----------------------------------------------------------------------------------------------------Othello--
# This function prints the matrices M , pointValueMatrixforWhite, and pointValueMatrixforBlack
# to the console for debugging.
def printMatrices():
print('\n Matrix M')
print (' 0 1 2 3 4 5 6 7')
print (' +--------------------------+')
for r in range(8):
print (r, '|', end = '')
for c in range (8):
if M[r][c] == 1: ch = '#'
if M[r][c] ==-1: ch = 'O'
if M[r][c] == 0: ch = '-'
if M[r][c] | |
direction and value of D[7:0] pins
# 8b<value>: 0 - low level, 1 - high level
# 8b<direction>: 0 - input, 1 - output
# Selected direction stays until explicitly changed
# It seems that the value gets written to the pin first and only then it's direction gets written
# Therefore attention needs to be paid when changing both port value from 1 to 0 and it's direction from output to input as it might produce a narrow runt pulse as there are 75 kOhm internal pull-up on every I/O pin
'get_pins_d' : 0x81, # Get value of D[7:0] pins
'set_pins_c' : 0x82, # Set direction and value of C[7:0] pins
'get_pins_c' : 0x83, # Get value of C[7:0] pins
#--------------------------------------------------
'enable_loopback' : 0x84, # Enable internal TDI->TDO loopback
'disable_loopback' : 0x85, # Disable internal TDI->TDO loopback
'set_clock_divider' : 0x86, # Set master clock divider to obtain required TCK/SCK/SCL frequency
'send_immediate' : 0x87, # Send RESPONSES back to host immediately not waiting for the read latency timer
'wait_pin_high' : 0x88, # Wait until GPIOL1 is high. Following MPSSE instructions are kept in TX buffer and not processed during this wait
'wait_pin_low' : 0x89, # Wait until GPIOL1 is low. Following MPSSE instructions are kept in TX buffer and not processed during this wait
'disable_x5_clock_divider' : 0x8A, # Disable master clock x5 divider
'enable_3_phase_clocking' : 0x8C, # Enable 3-phase clocking (required for I2C): data setup for 1/2 clock period -> pulse clock for 1/2 clock period -> data hold for 1/2 clock period
'disable_3_phase_clocking' : 0x8D, # Disable 3-phase clocking: data setup for 1/2 clock period -> pulse clock for 1/2 clock period
'clock_pulse_bit' : 0x8E, # 8b<length>
# Pulse clock with no data transfer
# 8b<length>: 0 - generate 1 pulse, ..., 7 - generate 8 pulses
'clock_pulse_byte' : 0x8F, # 8b<length[7:0]>, 8b<length[15:8]>
# Pulse clock with no data transfer
# 16b<length>: 0x0000 - generate 8 pulses, ..., 0xFFFF - generate 524288 pulses
'invalid_command_0' : 0xAA, # First invalid command for checking if MPSSE is operational
'invalid_command_1' : 0xAB} # Second invalid command for checking if MPSSE is operational
RESPONSES = {'invalid_command' : 0xFA} # Response to invalid command which is followed by echoing the invalid command
# Master clock is 60 MHz after /5 clock divider is disabled
# required_clock = master_clock / ((1 + divider) * 2)
# divider = master_clock / required_clock / 2 - 1
FREQUENCIES = {'1 kHz' : 29999,
'10 kHz' : 2999,
'100 kHz' : 299, # I2C Standard-mode
'400 kHz' : 74, # I2C Fast-mode
'1 MHz' : 29, # I2C Fast-mode Plus
'1.11 MHz' : 26,
'1.2 MHz' : 24,
'1.25 MHz' : 23,
'1.5 MHz' : 19,
'1.67 MHz' : 17,
'1.875 MHz' : 15,
'2 MHz' : 14,
'2.5 MHz' : 11,
'3 MHz' : 9,
'3.33 MHz' : 8,
'3.75 MHz' : 7,
'5 MHz' : 5,
'6 MHz' : 4,
'7.5 MHz' : 3,
'10 MHz' : 2,
'15 MHz' : 1,
'30 MHz' : 0}
# These delays are created using high-speed USB microframe time (125 us) and are equal to half of the selected clock period
# Minimum achievable delay is 250 us (based on actual measurements)
DELAYS = {'1 kHz' : 2000, # 2000 * 250 ns = 500 us
'10 kHz' : 200, # 200 * 250 ns = 50 us
'100 kHz' : 20, # 20 * 250 ns = 5 us
'400 kHz' : 5, # 5 * 250 ns = 1.25 us
'1 MHz' : 2, # 2 * 250 ns = 0.5 us
'2 MHz' : 1, # 1 * 250 ns = 0.25 us
'3 MHz' : 1, # 1 * 250 ns = 0.25 us, minimum achievable delay
'5 MHz' : 1, # 1 * 250 ns = 0.25 us, minimum achievable delay
'6 MHz' : 1, # 1 * 250 ns = 0.25 us, minimum achievable delay
'7.5 MHz' : 1, # 1 * 250 ns = 0.25 us, minimum achievable delay
'10 MHz' : 1, # 1 * 250 ns = 0.25 us, minimum achievable delay
'15 MHz' : 1, # 1 * 250 ns = 0.25 us, minimum achievable delay
'30 MHz' : 1} # 1 * 250 ns = 0.25 us, minimum achievable delay
#===============================================================================
# exceptions
#===============================================================================
class FTDIError(Exception):
'''Custom class for recoverable error handling'''
pass
class FTDICritical(Exception):
'''Custom class for unrecoverable error handling'''
pass
#===============================================================================
# classes
#===============================================================================
class FTDI:
def __init__(self, device):
self.device = device
self.port_jtag = None
self.port_spi = None
self.port_i2c = None
if PRODUCT_IDS[self.device.idProduct] == 'FT232H':
self.ports = {'A' : 0x0001}
self.jtag_buffer_size = 1000
self.spi_buffer_size = 1000
self.i2c_buffer_size = 1000
elif PRODUCT_IDS[self.device.idProduct] == 'FT2232H':
# FTDI device port indexes
self.ports = {'A' : 0x0001,
'B' : 0x0002}
# FTDI device uses FIFO for data transfer so there is no fixed-size buffer per se
self.jtag_buffer_size = 8000 # This value was determined experimentally by shifting 65465 bits through TDI->TDO when in internal loopback mode at TCK = 100 kHz, 1 MHz, 10 MHz, 30 MHz
self.spi_buffer_size = 8000 # This value was determined experimentally by shifting 65465 bits through MOSI->MISO when in internal loopback mode at SCK = 100 kHz, 1 MHz, 10 MHz, 30 MHz
self.i2c_buffer_size = 4000 # This value was determined experimentally by writing and reading full array of the Microchip 24LC512 EEPROM (64 kbyte) at SCL = 100 kHz, 400 kHz, 1 MHz
elif PRODUCT_IDS[self.device.idProduct] == 'FT4232H':
self.ports = {'A' : 0x0001,
'B' : 0x0002}
self.jtag_buffer_size = 4000
self.spi_buffer_size = 4000
self.i2c_buffer_size = 2000
else:
logger.critical(f'FAIL: Wrong USB idProduct: 0x{self.device.idProduct:04X}')
raise FTDICritical
def __enter__(self):
logger.debug('Initialize FTDI device')
# Set default timeout (ms)
self.device.default_timeout = 1000 # 1 s timeout
# logger.debug(f'| FTDI device found on bus {self.device.bus:03d}, address {self.device.address:03d}\n{self.device}')
# Detach from kernel driver
for configuration in self.device: # Iterate over device configurations
for interface in configuration: # Iterate over configuration interfaces
if self.device.is_kernel_driver_active(interface = interface.bInterfaceNumber) is True:
logger.debug(f'| OS: Detach kernel driver from configuration {configuration.bConfigurationValue}, interface {interface.bInterfaceNumber}')
self.device.detach_kernel_driver(interface = interface.bInterfaceNumber)
# Set configuration
configuration = self.device.get_active_configuration()
logger.debug(f'| USB: Active configuration: {"none" if configuration is None else configuration.bConfigurationValue}')
if configuration is None or configuration.bConfigurationValue != 1:
logger.debug('| USB: Set active configuration: 1')
self.device.set_configuration(configuration = 1)
# Claim interfaces
for configuration in self.device: # Iterate over device configurations
for interface in configuration: # Iterate over configuration interfaces
logger.debug(f'| USB: Claim configuration {configuration.bConfigurationValue}, interface {interface.bInterfaceNumber}')
usb.util.claim_interface(device = self.device, interface = interface.bInterfaceNumber)
# Check if active configuration is still the same as other software might have activated another one
configuration = self.device.get_active_configuration()
if configuration is None or configuration.bConfigurationValue != 1:
logger.error(f'FAIL: Wrong current active configuration: {"none" if configuration is None else configuration.bConfigurationValue}')
raise FTDIError
# Reset the USB port device is connected to (generic USB command)
logger.debug('| USB: Reset port device is connected to')
self.device.reset()
for port in self.ports.keys():
# Reset UART BUFFERS (vendor-specific command)
logger.debug(f'| FTDI device, port {port}: Reset UART BUFFERS')
self.device.ctrl_transfer(bmRequestType = usb.util.build_request_type(direction = usb.util.CTRL_OUT, type = usb.util.CTRL_TYPE_VENDOR, recipient = usb.util.CTRL_RECIPIENT_DEVICE),
bRequest = CONTROL_REQUESTS['reset_buffer'],
wValue = BUFFERS['rx_tx'],
wIndex = self.ports[port])
# Set receive buffer latency timer (vendor-specific command)
# Latency Timer is used as a timeout to flush short packets of data back to the host
# The default is 16 ms, but it can be altered between 0 ms and 255 ms
# At 0 ms latency packet transfer is done on every high speed microframe (every 125 us)
# For MPSSE it's recommended to set it to the default 16 ms and use "send_immediate" command to send bytes back to host when required
# This approach seems to be working fine for FT2232H but with FT232H there seems to be a latency delay present on the first small packet transfer therefore latency is set to 1
# This was observed while programming SPI flash and checking its status register | |
<reponame>cdleong/shiba<gh_stars>10-100
import json
import math
import os
import urllib
from pathlib import Path
from types import SimpleNamespace
from typing import Dict, Optional, Tuple
import torch
from shiba.codepoint_tokenizer import CodepointTokenizer
from shiba.local_transformer_encoder_layer import LocalTransformerEncoderLayer
from shiba.multi_hashing_embedder import MultiHashingEmbedder
from shiba.position_embedder import PositionEmbedder
class ShibaConfig(SimpleNamespace):
def to_dict(self):
out = self.__dict__.copy()
del out['self']
return out
def to_json_string(self):
return json.dumps(self.to_dict())
class Shiba(torch.nn.Module):
# defaults modeled after CANINE
# https://github.com/google-research/language/blob/186ce9002180d0c45bfa2a680085b890c76647dc/language/canine/modeling.py#L40
def __init__(self, downsampling_rate: int = 4,
upsampling_kernel_size: int = 4,
embedder_slice_count: int = 8,
embedder_bucket_count: int = 16000,
hidden_size: int = 768,
local_attention_window: int = 128,
deep_transformer_stack: Optional[torch.nn.Module] = None,
deep_transformer_requires_transpose: bool = True,
attention_heads: int = 12,
transformer_ff_size: int = 3072,
dropout: float = 0.1,
activation: str = 'gelu',
padding_id: int = 0,
max_length: int = 2048,
shiba_specific_code: bool = False,
deep_transformer_stack_layers: Optional[int] = None):
super(Shiba, self).__init__()
self.config = ShibaConfig(**{key: val for key, val in locals().items()
if key in self.__init__.__code__.co_varnames})
if max_length % downsampling_rate != 0:
# if this isn't true, padding so we don't miss any characters can bring us over max length
raise RuntimeError(f"max length must be divisible by downsampling rate, but got "
f"{max_length} and {downsampling_rate} respectively")
activations = {
'relu': torch.nn.ReLU,
'gelu': torch.nn.GELU
}
if activation not in activations:
raise RuntimeError(f'activation must be in {set(activations.keys())}, but was {activation}')
else:
self.activation = activations[activation]()
self.dropout = torch.nn.Dropout(p=dropout)
# "Hash Embedding"
self.embedder = MultiHashingEmbedder(hidden_size, slice_count=embedder_slice_count,
bucket_count=embedder_bucket_count)
self.position_embedder = PositionEmbedder(max_length, hidden_size)
self.embedder_ln = torch.nn.LayerNorm(hidden_size)
# "Single Local Transformer"
# note the CANINE paper says "local transformer", but it means "local transformer encoder" just like BERT
self.local_transformer = LocalTransformerEncoderLayer(hidden_size, attention_heads, dropout=dropout,
activation=activation,
dim_feedforward=transformer_ff_size)
# "Downsample (Strided Convolution) "
self.downsample_conv = torch.nn.Conv1d(hidden_size, hidden_size, kernel_size=downsampling_rate,
stride=downsampling_rate)
self.downsample_attention_pool = torch.nn.MaxPool1d(kernel_size=downsampling_rate, stride=downsampling_rate)
self.downsample_ln = torch.nn.LayerNorm(hidden_size)
self.cls_linear = torch.nn.Linear(hidden_size, hidden_size)
# "Deep Transformer Stack"
if deep_transformer_stack is not None:
if deep_transformer_stack_layers is not None:
raise RuntimeError('deep_transformer_stack_layers and deep_transformer_stack both provided - please '
'provide only one.')
# TODO: perform some kind of basic verification that this is actually a torch module that can be used
# in place of the default deep transformer stack
self.deep_transformer = deep_transformer_stack
else:
layers = deep_transformer_stack_layers if deep_transformer_stack_layers is not None else 12
self.deep_transformer = torch.nn.TransformerEncoder(torch.nn.TransformerEncoderLayer(hidden_size,
attention_heads,
dim_feedforward=transformer_ff_size,
dropout=dropout,
activation=activation),
num_layers=layers)
self.config.deep_transformer_requires_transpose = True
# "Conv + Single Transformer"
self.upsample_conv = torch.nn.Conv1d(hidden_size * 2, hidden_size, kernel_size=upsampling_kernel_size, stride=1)
self.upsample_ln = torch.nn.LayerNorm(hidden_size)
self.final_transformer = torch.nn.TransformerEncoder(
torch.nn.TransformerEncoderLayer(hidden_size, attention_heads,
dim_feedforward=transformer_ff_size,
dropout=dropout,
activation=activation),
1)
# CLS Token
self.cls_linear_final = torch.nn.Linear(hidden_size, hidden_size)
self.cls_activation = torch.nn.Tanh()
# "Upsampling"
def _repeat_molecules(self, molecules: torch.Tensor, char_seq_length: int):
repeated_molecules = molecules.repeat_interleave(self.config.downsampling_rate, axis=1)
remainder_length = char_seq_length % self.config.downsampling_rate
# as the canine implementation does, we repeat the last molecule extra times to get to a multiple of 4
last_molecule = molecules[:, -1:, :]
last_molecule_repeated = last_molecule.repeat_interleave(remainder_length, axis=1)
return torch.cat((repeated_molecules, last_molecule_repeated), dim=1)
def forward(self, input_ids: torch.Tensor,
attention_mask: torch.Tensor,
predict_indices: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
if input_ids.shape[1] > self.config.max_length:
raise RuntimeError(f'Input tensor of shape {input_ids.shape} exceeded configured max length'
f'{self.config.max_length}')
if any(input_ids[:, 0:1] != CodepointTokenizer.CLS):
raise RuntimeError('All input sequences must start wit [CLS] codepoint')
# https://github.com/google-research/language/blob/186ce9002180d0c45bfa2a680085b890c76647dc/language/canine/modeling.py#L221
# https://github.com/google-research/language/blob/13dc35ccad77309354ff8ed2950c560c16b083b1/language/canine/bert_modeling.py#L448
char_embeddings = self.position_embedder(self.embedder(input_ids))
# https://github.com/google-research/language/blob/186ce9002180d0c45bfa2a680085b890c76647dc/language/canine/modeling.py#L253
contextualized_chars = self.local_transformer(char_embeddings, attention_mask) # h_init
# https://github.com/google-research/language/blob/186ce9002180d0c45bfa2a680085b890c76647dc/language/canine/modeling.py#L287
cls_embedding = self.dropout(self.cls_linear(contextualized_chars[:, 0:1, :]))
if self.config.shiba_specific_code:
# remove the CLS token from the tokens that get downsampled so its information isn't used twice
contextualized_chars = contextualized_chars[:, 1:, :]
attention_mask = attention_mask[:, 1:]
# pad so the convolution can't drop information from final characters
contextualized_chars = self._pad_to_avoid_missed_characters(contextualized_chars)
attention_mask = self._pad_to_avoid_missed_characters(attention_mask.unsqueeze(2)).squeeze()
# note that even with shiba specific code turned off, we don't truncate the last char like CANINE does
sampleable_characters = contextualized_chars.transpose(1, 2).contiguous()
sampleable_mask = attention_mask.float()
molecules = self.downsample_conv(sampleable_characters).transpose(1, 2) # h_down
molecules = self.downsample_ln(self.activation(molecules))
molecules = torch.cat((cls_embedding, molecules), dim=1)
# unlike CANINE we don't assume a fixed size and truncate, so we have to add to the attention mask for the
# CLS slot. squeezing and unsqueezing is a fix for https://github.com/pytorch/pytorch/issues/51954
downsampled_attention_mask = self.downsample_attention_pool(sampleable_mask.unsqueeze(0)).squeeze(0)
molecule_attention_mask = torch.nn.functional.pad(downsampled_attention_mask.bool(), (1, 0), value=True)
# https://github.com/google-research/language/blob/186ce9002180d0c45bfa2a680085b890c76647dc/language/canine/modeling.py#L343
if self.config.deep_transformer_requires_transpose:
# TODO: if we switch out the deep transformer to something that calls its attention mask
# anything other than "src_key_padding_mask" this will break
contextualized_molecules = self.deep_transformer(molecules.transpose(0, 1),
src_key_padding_mask=molecule_attention_mask).transpose(0, 1) # h`_down
else:
contextualized_molecules = self.deep_transformer(molecules, src_key_padding_mask=molecule_attention_mask)
# https://github.com/google-research/language/blob/186ce9002180d0c45bfa2a680085b890c76647dc/language/canine/modeling.py#L371
molecules_without_cls = contextualized_molecules[:, 1:, :] # remove CLS to avoid upsampling it
repeated_molecules = self._repeat_molecules(molecules_without_cls, contextualized_chars.shape[1])
# https://github.com/google-research/language/blob/186ce9002180d0c45bfa2a680085b890c76647dc/language/canine/modeling.py#L468
concatenated = torch.cat((contextualized_chars, repeated_molecules), dim=2)
concatenated = self._pad_for_convolution_to_same_length(concatenated, self.upsample_conv)
upsampled_embeddings = self.activation(self.upsample_conv(concatenated.transpose(1, 2).contiguous()).
transpose(1, 2))
upsampled_embeddings = self.dropout(self.upsample_ln(upsampled_embeddings)) # h_up
if predict_indices is not None:
# this is MLM of some kind - we don't need to do the final CLS computation and we can only do the
# final transformer for the positions we're predicting
embeddings_for_pred = torch.stack([upsampled_embeddings[i, predict_indices[i], :]
for i in range(upsampled_embeddings.shape[0])])
# no attention mask because we are presumably not trying to predict padding
final_embeddings = self.final_transformer(embeddings_for_pred.transpose(0, 1)).transpose(0, 1)
else:
# https://github.com/google-research/language/blob/master/language/canine/modeling.py#L551
contextualized_cls = contextualized_molecules[:, 0:1, :]
final_cls = self.cls_activation(self.cls_linear_final(contextualized_cls))
# confusingly, key_padding_mask does for the pytorch transformer what attention_mask does for the
# local attention implementation (and huggingface/allennlp)
# also, we drop the first embedding (CLS token) because we're going to use final_cls anyway
final_embeddings = self.final_transformer(upsampled_embeddings[:, 1:, :].transpose(0, 1),
src_key_padding_mask=attention_mask[:, 1:]).transpose(0, 1)
final_embeddings = torch.cat((final_cls, final_embeddings), dim=1) # replace CLS embedding
return {
'embeddings': final_embeddings
}
def _pad_to_avoid_missed_characters(self, char_embeddings: torch.Tensor) -> torch.Tensor:
if char_embeddings.shape[1] % self.config.downsampling_rate == 0:
return char_embeddings
else:
target_length = math.ceil(char_embeddings.shape[1] / self.config.downsampling_rate)\
* self.config.downsampling_rate
total_padding = target_length - char_embeddings.shape[1]
lhs_padding = math.floor(total_padding / 2)
rhs_padding = math.ceil(total_padding / 2)
return torch.nn.functional.pad(char_embeddings, (0, 0, lhs_padding, rhs_padding))
def _pad_for_convolution_to_same_length(self, hidden_state: torch.Tensor,
convolution: torch.nn.Conv1d) -> torch.Tensor:
# we have to manually pad, see: https://discuss.pytorch.org/t/same-padding-equivalent-in-pytorch/85121/2
# so we solve for total padding from the formula for output length
# https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
# hidden state has shape [batch_size, sequence_length, embedding_size]
l = hidden_state.shape[1]
s = convolution.stride[0]
d = convolution.dilation[0]
k = convolution.kernel_size[0]
total_padding = l * s - l + d * k - d + 1 - s
lhs_padding = math.floor(total_padding / 2)
rhs_padding = math.ceil(total_padding / 2)
return torch.nn.functional.pad(hidden_state, (0, 0, lhs_padding, rhs_padding))
def get_pretrained_state_dict():
download_url = 'https://storage.googleapis.com/shiba.octanove.com/published_checkpoints/shiba_check45k.pt'
save_location = Path.home() / '.shiba' / 'pretrained_shiba.pt'
if not save_location.parent.exists():
os.makedirs(save_location.parent, exist_ok=True)
if not save_location.exists():
print('Downloading shiba state dict to', save_location)
with open(save_location, 'wb') as state_dict_file:
response = urllib.request.urlopen(download_url)
data = response.read()
state_dict_file.write(data)
print('Done')
return torch.load(save_location, map_location=torch.device('cpu'))
class ShibaForTask(torch.nn.Module):
def __init__(self, **kwargs):
super(ShibaForTask, self).__init__()
self.shiba_model = Shiba(**kwargs)
def load_encoder_checkpoint(self, checkpoint_location: Optional[str] = None):
if checkpoint_location is None:
state_dict = get_pretrained_state_dict()
else:
state_dict = torch.load(checkpoint_location, map_location=torch.device('cpu'))
self.shiba_model.load_state_dict(state_dict)
class ShibaForSequenceLabeling(ShibaForTask):
def __init__(self, vocab_size: int, **kwargs):
super(ShibaForSequenceLabeling, self).__init__(**kwargs)
self.vocab_size = vocab_size
self.config = self.shiba_model.config
self.config.vocab_size = self.vocab_size
self.label_layer = torch.nn.Linear(self.shiba_model.config.hidden_size, self.vocab_size)
self.dropout = torch.nn.Dropout(p=self.shiba_model.config.dropout)
self.log_softmax = torch.nn.LogSoftmax(dim=2)
self.loss = torch.nn.NLLLoss()
def forward(self, input_ids: torch.Tensor, labels: Optional[torch.Tensor],
attention_mask: torch.Tensor) -> Tuple:
embeddings = self.shiba_model(input_ids, attention_mask, None)['embeddings']
label_hidden_states = self.label_layer(self.dropout(embeddings))
label_probs = self.log_softmax(label_hidden_states)
output = {
'embeddings': embeddings,
'label_probs': label_probs
}
if labels is not None:
output['loss'] = self.loss(label_probs.transpose(1, 2), labels)
return output.get('loss', None), output['label_probs'], output['embeddings']
class ShibaForClassification(ShibaForTask):
def __init__(self, vocab_size: int, **kwargs):
super(ShibaForClassification, self).__init__(**kwargs)
self.vocab_size = vocab_size
self.config = self.shiba_model.config
self.config.vocab_size = self.vocab_size
self.label_layer = torch.nn.Linear(self.shiba_model.config.hidden_size, self.vocab_size)
self.dropout = torch.nn.Dropout(p=self.shiba_model.config.dropout)
self.log_softmax = torch.nn.LogSoftmax(dim=1)
self.loss = torch.nn.NLLLoss()
def forward(self, input_ids: torch.Tensor, labels: Optional[torch.Tensor],
attention_mask: torch.Tensor) -> Tuple:
cls_embeddings = self.shiba_model(input_ids, attention_mask, None)['embeddings'][:, 0, :]
class_hidden_states = self.label_layer(self.dropout(cls_embeddings))
class_probs = self.log_softmax(class_hidden_states)
output = {
'cls_embeddings': cls_embeddings,
'class_probs': class_probs
}
if labels is not None:
output['loss'] = self.loss(class_probs, labels)
return output.get('loss', None), output['class_probs'], output['cls_embeddings']
class ShibaForMaskedLanguageModeling(ShibaForTask):
def __init__(self, vocab_size: int, **kwargs):
"""If vocab size is < than special token codepoints (which it likely is, at least for Japanese), the model will
be unable to predict special tokens. However, the model shouldn't be trained to predict special tokens anyway"""
super(ShibaForMaskedLanguageModeling, self).__init__(**kwargs)
self.vocab_size = vocab_size + 1
self.unk_token = vocab_size # we hash the input so there are unknown tokens, but our output vocab is limited
self.lm_layer = torch.nn.Linear(self.shiba_model.config.hidden_size, self.vocab_size)
self.config = self.shiba_model.config
self.config.vocab_size = self.vocab_size
self.log_softmax = torch.nn.LogSoftmax(dim=2)
self.loss = torch.nn.NLLLoss(reduction="none") # https://github.com/microsoft/DeepSpeed/issues/962
def _replace_unkown_tokens(self, labels: torch.Tensor) -> torch.Tensor:
return labels.where(labels < self.vocab_size, torch.full(labels.shape, self.unk_token,
device=labels.device).long())
def | |
"""Base Plotting module."""
from __future__ import annotations
from . import State, units
from CoolProp.CoolProp import PropsSI
import matplotlib.pyplot as plt
import numpy as np
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
@dataclass
class PlottedState:
"""Data class to efficiently store states in the self.states dictionary."""
key: str
state: State
# key: Plot axes string (Tv, pv)
# value: Line2D instance for that plot of the marker for this state
markers: dict = field(default_factory=dict)
class PlottingBase(ABC):
"""Basic Plotting manager for thermodynamic states.
Parameters
----------
substance : `str`
One of the substances supported by CoolProp
"""
axis_units = {
"v": "m**3/kg",
"T": "K",
"s": "J/(kg*K)",
"p": "pascal",
"u": "J/kg",
"h": "J/kg",
"x": "dimensionless",
}
allowed_processes = {
"isochoric": "v",
"isovolumetric": "v",
"isometric": "v",
"isobaric": "p",
"isothermal": "T",
"isoenergetic": "u",
"isoenthalpic": "h",
"isentropic": "s",
}
def __init__(self, substance: str):
self.states = {}
self.plots = {}
self.processes = {}
@abstractmethod
def plot(self, x_axis: str, y_axis: str): # pragma: no cover
"""Hold the place of a plot function that a child class must establish."""
pass
def add_state(self, state: State, key: str | None = None, label: str | None = None):
"""Add a state to the self.states dictionary and plot it."""
if key is None:
key = repr(state)
if label is not None:
state.label = label
plotted_state = PlottedState(key=key, state=state)
for plot_key, value in self.plots.items():
x_data = []
y_data = []
fig, axis = value
x_axis, y_axis = plot_key
x_data.append(getattr(state, x_axis).magnitude)
y_data.append(getattr(state, y_axis).magnitude)
x_data = np.array(x_data) * getattr(units, self.axis_units[x_axis])
y_data = np.array(y_data) * getattr(units, self.axis_units[y_axis])
(line,) = axis.plot(x_data, y_data, marker="o")
if state.label is not None:
axis.annotate(
state.label,
(x_data[0], y_data[0]),
textcoords="offset pixels",
xytext=(5, 5),
)
plotted_state.markers[plot_key] = line
self.states[key] = plotted_state
def remove_state(self, state: State | None = None, key: str | None = None):
"""Remove a state from the self.states dictionary and plots."""
if state is None and key is None:
raise ValueError("No state or key was entered. Unable to find state")
if state is not None and repr(state) in self.states:
state_to_be_removed = self.states[repr(state)]
elif key is not None and key in self.states:
state_to_be_removed = self.states[key]
elif key is not None and key not in self.states and state is None:
raise ValueError("Couldn't find key")
else:
for key, s_2 in self.states.items():
if state == s_2.state:
state_to_be_removed = self.states[key]
break
else:
raise ValueError("Couldn't find the state")
for line in state_to_be_removed.markers.values():
line.remove()
del self.states[state_to_be_removed.key]
def remove_process(
self, state_1: State, state_2: State, remove_states: bool = False
):
"""Remove a process from the self.process dictionary.
The process to be removed is specified by the states that were used to
initially create the process. It is optional to keep the points associated
with the states while still removing the line object.
Parameters
----------
state_1: `~thermostate.thermostate.State`
The starting state for this process.
state_2: `~thermostate.thermostate.State`
The final state for this process.
remove_states: `bool`
If ``True``, the associated states are removed from the instance.
"""
key_1 = None
key_2 = None
for key, plotted_state in self.states.items():
if state_1 is plotted_state.state:
key_1 = key
if state_2 is plotted_state.state:
key_2 = key
for line in self.processes[key_1 + key_2].values():
line.remove()
del self.processes[key_1 + key_2]
if remove_states:
self.remove_state(state_1)
self.remove_state(state_2)
def add_process(
self,
state_1: State,
state_2: State,
process_type: str | None = None,
label_1: str | None = None,
label_2: str | None = None,
):
"""Add a thermodynamic process to the self.process dictionary and plots it.
A property of the states is held constant and all intermediate states are traced
out in a line between the two states on the graph. The property that is held
constant is specified by the user with the ``process_type`` input.
If no property is to be held constant then a straight line between the
two points is drawn.
Parameters
----------
state_1: `~thermostate.thermostate.State`
The starting state for this process.
state_2: `~thermostate.thermostate.State`
The final state for this process.
process_type: optional, `str`
If given, specifies the property that is held constant during the process.
Must be one of ``"isochoric"``, ``"isovolumetric"``, ``"isobaric"``,
``"isothermal"``, ``"isoenergetic"``, ``"isoenthalpic"``,
``"isentropic"``, or ``None``. If not specified, a straight line is drawn
between the states.
label_1: optional, `str`
If given, will be used to label the first state.
label_2: optional, `str`
If given, will be used to label the second state.
"""
if (
process_type not in self.allowed_processes.keys()
and process_type is not None
):
raise ValueError(
f"Not a supported process type: '{process_type}.\n"
f"Supported process types are: {list(self.allowed_processes.keys())}"
)
if process_type is not None:
constant_prop = self.allowed_processes[process_type]
constant1 = getattr(state_1, constant_prop)
constant2 = getattr(state_2, constant_prop)
if not np.isclose(constant1, constant2):
raise ValueError(f"Property: '{constant_prop}' was not held constant")
missing_state_1 = True
missing_state_2 = True
key_1 = None
key_2 = None
sub1 = state_1.sub
sub2 = state_2.sub
if sub1 != sub2:
raise ValueError(
f"Substance of input states do not match: '{sub1}', '{sub2}'"
)
for key, plotted_state in self.states.items():
if state_1 is plotted_state.state:
missing_state_1 = False
key_1 = key
if state_2 is plotted_state.state:
missing_state_2 = False
key_2 = key
if missing_state_1:
key_1 = repr(state_1)
self.add_state(state_1, key_1, label_1)
if missing_state_2:
key_2 = repr(state_2)
self.add_state(state_2, key_2, label_2)
plot_key = key_1 + key_2
self.processes[plot_key] = {}
if process_type in ("isochoric", "isovolumetric", "isometric"):
p_1 = np.log10(state_1.p.magnitude)
p_2 = np.log10(state_2.p.magnitude)
v_range = np.logspace(p_1, p_2) * units.pascal
elif process_type is not None:
v_1 = np.log10(state_1.v.magnitude)
v_2 = np.log10(state_2.v.magnitude)
# Due to numerical approximation by CoolProp, an error occurs
# if the state is too close to a saturated liquid. Here an
# imperceptibly small offset is introduced to the specific volume
# to avoid this error.
if state_1.x is not None:
if np.isclose(state_1.x.magnitude, 0.0):
v_1 *= 1.0 + 1.0e-14
elif np.isclose(state_1.x.magnitude, 1.0):
v_1 *= 1.0 - 1.0e-12
if state_2.x is not None:
if np.isclose(state_2.x.magnitude, 0.0):
v_2 *= 1.0 + 1.0e-14
elif np.isclose(state_2.x.magnitude, 1.0):
v_2 *= 1.0 - 1.0e-12
v_range = np.logspace(v_1, v_2) * units("m**3/kg")
for key, value in self.plots.items():
x_data = []
y_data = []
fig, axis = value
x_axis, y_axis = key
if process_type is None:
x_data.append(getattr(state_1, x_axis).magnitude)
y_data.append(getattr(state_1, y_axis).magnitude)
x_data.append(getattr(state_2, x_axis).magnitude)
y_data.append(getattr(state_2, y_axis).magnitude)
x_data = np.array(x_data) * getattr(units, self.axis_units[x_axis])
y_data = np.array(y_data) * getattr(units, self.axis_units[y_axis])
(line,) = axis.plot(x_data, y_data, marker="None", linestyle="--")
self.processes[plot_key][key] = line
else:
state = State(state_1.sub)
for v in v_range:
if process_type in ("isochoric", "isovolumetric", "isometric"):
state.pv = v, state_1.v
elif process_type == "isobaric":
state.pv = state_1.p, v
elif process_type == "isothermal":
state.Tv = state_1.T, v
elif process_type == "isoenergetic":
state.uv = state_1.u, v
elif process_type == "isoenthalpic":
state.hv = state_1.h, v
elif process_type == "isentropic":
state.sv = state_1.s, v
x_data.append(getattr(state, x_axis).magnitude)
y_data.append(getattr(state, y_axis).magnitude)
x_data = np.array(x_data) * getattr(units, self.axis_units[x_axis])
y_data = np.array(y_data) * getattr(units, self.axis_units[y_axis])
(line,) = axis.plot(x_data, y_data, linestyle="-")
self.processes[plot_key][key] = line
def set_xscale(self, x_axis, y_axis, scale="linear"):
"""Access a plot in self.plots and change the scale of its x axis."""
key = x_axis + y_axis
fig, axis = self.plots[key]
axis.set_xscale(scale)
def set_yscale(self, x_axis, y_axis, scale="linear"):
"""Access a plot in self.plots and change the scale of its y axis."""
key = x_axis + y_axis
fig, axis = self.plots[key]
axis.set_yscale(scale)
class VaporDome(PlottingBase):
"""Class for plotting graphs with a vapor dome."""
def __init__(self, substance, *args):
super().__init__(substance)
min_temp = PropsSI("Tmin", substance)
max_temp = PropsSI("Tcrit", substance)
T_range = np.logspace(np.log10(min_temp), np.log10(max_temp), 400) * units.K
self.st_f = [State(substance, T=T, x=0 * units.dimensionless) for T in T_range]
self.st_g = [State(substance, T=T, x=1 * units.dimensionless) for T in T_range]
for axes in args:
self.plot(axes[0], axes[1])
def plot(self, x_axis, y_axis):
"""Add a plot with a vapor dome to this instance with given x and y axes.
Parameters
----------
x_axis: `str`
The string representing the x axis for this plot. Allowed axes are
"T", "p", "u", "s", "v", and "h".
y_axis: `str`
The string representing the y axis for this plot. Allowed axes are
"T", "p", "u", "s", "v", and "h".
"""
if x_axis + y_axis not in self.plots:
fig, axis = plt.subplots()
self.plots[x_axis + y_axis] = (fig, axis)
x_f = [getattr(st, x_axis).magnitude for st in self.st_f]
x_f = np.array(x_f) * getattr(units, self.axis_units[x_axis])
y_f = [getattr(st, y_axis).magnitude | |
absoluteFidelity.__class__.__name__
)
raise BaseException(strMessage)
def delAbsoluteFidelity(self):
self._absoluteFidelity = None
absoluteFidelity = property(
getAbsoluteFidelity,
setAbsoluteFidelity,
delAbsoluteFidelity,
"Property for absoluteFidelity",
)
# Methods and properties for the 'relativeFidelity' attribute
def getRelativeFidelity(self):
return self._relativeFidelity
def setRelativeFidelity(self, relativeFidelity):
if relativeFidelity is None:
self._relativeFidelity = None
elif relativeFidelity.__class__.__name__ == "XSDataDouble":
self._relativeFidelity = relativeFidelity
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSmartMergev1_0.setRelativeFidelity argument is not XSDataDouble but %s"
% relativeFidelity.__class__.__name__
)
raise BaseException(strMessage)
def delRelativeFidelity(self):
self._relativeFidelity = None
relativeFidelity = property(
getRelativeFidelity,
setRelativeFidelity,
delRelativeFidelity,
"Property for relativeFidelity",
)
# Methods and properties for the 'sample' attribute
def getSample(self):
return self._sample
def setSample(self, sample):
if sample is None:
self._sample = None
elif sample.__class__.__name__ == "XSDataBioSaxsSample":
self._sample = sample
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSmartMergev1_0.setSample argument is not XSDataBioSaxsSample but %s"
% sample.__class__.__name__
)
raise BaseException(strMessage)
def delSample(self):
self._sample = None
sample = property(getSample, setSample, delSample, "Property for sample")
# Methods and properties for the 'mergedCurve' attribute
def getMergedCurve(self):
return self._mergedCurve
def setMergedCurve(self, mergedCurve):
if mergedCurve is None:
self._mergedCurve = None
elif mergedCurve.__class__.__name__ == "XSDataFile":
self._mergedCurve = mergedCurve
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSmartMergev1_0.setMergedCurve argument is not XSDataFile but %s"
% mergedCurve.__class__.__name__
)
raise BaseException(strMessage)
def delMergedCurve(self):
self._mergedCurve = None
mergedCurve = property(
getMergedCurve, setMergedCurve, delMergedCurve, "Property for mergedCurve"
)
# Methods and properties for the 'subtractedCurve' attribute
def getSubtractedCurve(self):
return self._subtractedCurve
def setSubtractedCurve(self, subtractedCurve):
if subtractedCurve is None:
self._subtractedCurve = None
elif subtractedCurve.__class__.__name__ == "XSDataFile":
self._subtractedCurve = subtractedCurve
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSmartMergev1_0.setSubtractedCurve argument is not XSDataFile but %s"
% subtractedCurve.__class__.__name__
)
raise BaseException(strMessage)
def delSubtractedCurve(self):
self._subtractedCurve = None
subtractedCurve = property(
getSubtractedCurve,
setSubtractedCurve,
delSubtractedCurve,
"Property for subtractedCurve",
)
# Methods and properties for the 'runId' attribute
def getRunId(self):
return self._runId
def setRunId(self, runId):
if runId is None:
self._runId = None
elif runId.__class__.__name__ == "XSDataString":
self._runId = runId
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSmartMergev1_0.setRunId argument is not XSDataString but %s"
% runId.__class__.__name__
)
raise BaseException(strMessage)
def delRunId(self):
self._runId = None
runId = property(getRunId, setRunId, delRunId, "Property for runId")
# Methods and properties for the 'bufferCurves' attribute
def getBufferCurves(self):
return self._bufferCurves
def setBufferCurves(self, bufferCurves):
if bufferCurves is None:
self._bufferCurves = []
elif bufferCurves.__class__.__name__ == "list":
self._bufferCurves = bufferCurves
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSmartMergev1_0.setBufferCurves argument is not list but %s"
% bufferCurves.__class__.__name__
)
raise BaseException(strMessage)
def delBufferCurves(self):
self._bufferCurves = None
bufferCurves = property(
getBufferCurves, setBufferCurves, delBufferCurves, "Property for bufferCurves"
)
def addBufferCurves(self, value):
if value is None:
strMessage = "ERROR! XSDataInputBioSaxsSmartMergev1_0.addBufferCurves argument is None"
raise BaseException(strMessage)
elif value.__class__.__name__ == "XSDataFile":
self._bufferCurves.append(value)
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSmartMergev1_0.addBufferCurves argument is not XSDataFile but %s"
% value.__class__.__name__
)
raise BaseException(strMessage)
def insertBufferCurves(self, index, value):
if index is None:
strMessage = "ERROR! XSDataInputBioSaxsSmartMergev1_0.insertBufferCurves argument 'index' is None"
raise BaseException(strMessage)
if value is None:
strMessage = "ERROR! XSDataInputBioSaxsSmartMergev1_0.insertBufferCurves argument 'value' is None"
raise BaseException(strMessage)
elif value.__class__.__name__ == "XSDataFile":
self._bufferCurves[index] = value
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSmartMergev1_0.addBufferCurves argument is not XSDataFile but %s"
% value.__class__.__name__
)
raise BaseException(strMessage)
def export(self, outfile, level, name_="XSDataInputBioSaxsSmartMergev1_0"):
showIndent(outfile, level)
outfile.write(unicode("<%s>\n" % name_))
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write(unicode("</%s>\n" % name_))
def exportChildren(self, outfile, level, name_="XSDataInputBioSaxsSmartMergev1_0"):
XSDataInput.exportChildren(self, outfile, level, name_)
for inputCurves_ in self.getInputCurves():
inputCurves_.export(outfile, level, name_="inputCurves")
if self.getInputCurves() == []:
warnEmptyAttribute("inputCurves", "XSDataFile")
if self._absoluteFidelity is not None:
self.absoluteFidelity.export(outfile, level, name_="absoluteFidelity")
if self._relativeFidelity is not None:
self.relativeFidelity.export(outfile, level, name_="relativeFidelity")
if self._sample is not None:
self.sample.export(outfile, level, name_="sample")
if self._mergedCurve is not None:
self.mergedCurve.export(outfile, level, name_="mergedCurve")
else:
warnEmptyAttribute("mergedCurve", "XSDataFile")
if self._subtractedCurve is not None:
self.subtractedCurve.export(outfile, level, name_="subtractedCurve")
if self._runId is not None:
self.runId.export(outfile, level, name_="runId")
for bufferCurves_ in self.getBufferCurves():
bufferCurves_.export(outfile, level, name_="bufferCurves")
def build(self, node_):
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(":")[-1]
self.buildChildren(child_, nodeName_)
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "inputCurves":
obj_ = XSDataFile()
obj_.build(child_)
self.inputCurves.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "absoluteFidelity":
obj_ = XSDataDouble()
obj_.build(child_)
self.setAbsoluteFidelity(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "relativeFidelity":
obj_ = XSDataDouble()
obj_.build(child_)
self.setRelativeFidelity(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "sample":
obj_ = XSDataBioSaxsSample()
obj_.build(child_)
self.setSample(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "mergedCurve":
obj_ = XSDataFile()
obj_.build(child_)
self.setMergedCurve(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "subtractedCurve":
obj_ = XSDataFile()
obj_.build(child_)
self.setSubtractedCurve(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "runId":
obj_ = XSDataString()
obj_.build(child_)
self.setRunId(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "bufferCurves":
obj_ = XSDataFile()
obj_.build(child_)
self.bufferCurves.append(obj_)
XSDataInput.buildChildren(self, child_, nodeName_)
# Method for marshalling an object
def marshal(self):
oStreamString = StringIO()
oStreamString.write(unicode('<?xml version="1.0" ?>\n'))
self.export(oStreamString, 0, name_="XSDataInputBioSaxsSmartMergev1_0")
oStringXML = oStreamString.getvalue()
oStreamString.close()
return oStringXML
# Only to export the entire XML tree to a file stream on disk
def exportToFile(self, _outfileName):
outfile = open(_outfileName, "w")
outfile.write(unicode('<?xml version="1.0" ?>\n'))
self.export(outfile, 0, name_="XSDataInputBioSaxsSmartMergev1_0")
outfile.close()
# Deprecated method, replaced by exportToFile
def outputFile(self, _outfileName):
print(
"WARNING: Method outputFile in class XSDataInputBioSaxsSmartMergev1_0 is deprecated, please use instead exportToFile!"
)
self.exportToFile(_outfileName)
# Method for making a copy in a new instance
def copy(self):
return XSDataInputBioSaxsSmartMergev1_0.parseString(self.marshal())
# Static method for parsing a string
def parseString(_inString):
doc = minidom.parseString(_inString)
rootNode = doc.documentElement
rootObj = XSDataInputBioSaxsSmartMergev1_0()
rootObj.build(rootNode)
# Check that all minOccurs are obeyed by marshalling the created object
oStreamString = StringIO()
rootObj.export(oStreamString, 0, name_="XSDataInputBioSaxsSmartMergev1_0")
oStreamString.close()
return rootObj
parseString = staticmethod(parseString)
# Static method for parsing a file
def parseFile(_inFilePath):
doc = minidom.parse(_inFilePath)
rootNode = doc.documentElement
rootObj = XSDataInputBioSaxsSmartMergev1_0()
rootObj.build(rootNode)
return rootObj
parseFile = staticmethod(parseFile)
# end class XSDataInputBioSaxsSmartMergev1_0
class XSDataInputBioSaxsSubtractv1_0(XSDataInput):
"""Runs sequentially subtraction of buffer and SaxsAnalysis"""
def __init__(
self,
configuration=None,
gnomFile=None,
subtractedCurve=None,
sample=None,
bufferCurves=None,
sampleCurve=None,
):
XSDataInput.__init__(self, configuration)
if sampleCurve is None:
self._sampleCurve = None
elif sampleCurve.__class__.__name__ == "XSDataFile":
self._sampleCurve = sampleCurve
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSubtractv1_0 constructor argument 'sampleCurve' is not XSDataFile but %s"
% self._sampleCurve.__class__.__name__
)
raise BaseException(strMessage)
if bufferCurves is None:
self._bufferCurves = []
elif bufferCurves.__class__.__name__ == "list":
self._bufferCurves = bufferCurves
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSubtractv1_0 constructor argument 'bufferCurves' is not list but %s"
% self._bufferCurves.__class__.__name__
)
raise BaseException(strMessage)
if sample is None:
self._sample = None
elif sample.__class__.__name__ == "XSDataBioSaxsSample":
self._sample = sample
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSubtractv1_0 constructor argument 'sample' is not XSDataBioSaxsSample but %s"
% self._sample.__class__.__name__
)
raise BaseException(strMessage)
if subtractedCurve is None:
self._subtractedCurve = None
elif subtractedCurve.__class__.__name__ == "XSDataFile":
self._subtractedCurve = subtractedCurve
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSubtractv1_0 constructor argument 'subtractedCurve' is not XSDataFile but %s"
% self._subtractedCurve.__class__.__name__
)
raise BaseException(strMessage)
if gnomFile is None:
self._gnomFile = None
elif gnomFile.__class__.__name__ == "XSDataFile":
self._gnomFile = gnomFile
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSubtractv1_0 constructor argument 'gnomFile' is not XSDataFile but %s"
% self._gnomFile.__class__.__name__
)
raise BaseException(strMessage)
# Methods and properties for the 'sampleCurve' attribute
def getSampleCurve(self):
return self._sampleCurve
def setSampleCurve(self, sampleCurve):
if sampleCurve is None:
self._sampleCurve = None
elif sampleCurve.__class__.__name__ == "XSDataFile":
self._sampleCurve = sampleCurve
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSubtractv1_0.setSampleCurve argument is not XSDataFile but %s"
% sampleCurve.__class__.__name__
)
raise BaseException(strMessage)
def delSampleCurve(self):
self._sampleCurve = None
sampleCurve = property(
getSampleCurve, setSampleCurve, delSampleCurve, "Property for sampleCurve"
)
# Methods and properties for the 'bufferCurves' attribute
def getBufferCurves(self):
return self._bufferCurves
def setBufferCurves(self, bufferCurves):
if bufferCurves is None:
self._bufferCurves = []
elif bufferCurves.__class__.__name__ == "list":
self._bufferCurves = bufferCurves
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSubtractv1_0.setBufferCurves argument is not list but %s"
% bufferCurves.__class__.__name__
)
raise BaseException(strMessage)
def delBufferCurves(self):
self._bufferCurves = None
bufferCurves = property(
getBufferCurves, setBufferCurves, delBufferCurves, "Property for bufferCurves"
)
def addBufferCurves(self, value):
if value is None:
strMessage = (
"ERROR! XSDataInputBioSaxsSubtractv1_0.addBufferCurves argument is None"
)
raise BaseException(strMessage)
elif value.__class__.__name__ == "XSDataFile":
self._bufferCurves.append(value)
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSubtractv1_0.addBufferCurves argument is not XSDataFile but %s"
% value.__class__.__name__
)
raise BaseException(strMessage)
def insertBufferCurves(self, index, value):
if index is None:
strMessage = "ERROR! XSDataInputBioSaxsSubtractv1_0.insertBufferCurves argument 'index' is None"
raise BaseException(strMessage)
if value is None:
strMessage = "ERROR! XSDataInputBioSaxsSubtractv1_0.insertBufferCurves argument 'value' is None"
raise BaseException(strMessage)
elif value.__class__.__name__ == "XSDataFile":
self._bufferCurves[index] = value
else:
strMessage = (
"ERROR! XSDataInputBioSaxsSubtractv1_0.addBufferCurves argument is not XSDataFile but %s"
% value.__class__.__name__
)
raise BaseException(strMessage)
# Methods and properties for the 'sample' attribute
def getSample(self):
return self._sample
def setSample(self, sample):
if sample is None:
self._sample | |
<filename>cgnet/tests/test_geometry_statistics.py
# Author: <NAME>
# Contributors : <NAME>
import numpy as np
import scipy.spatial
import torch
from cgnet.feature import GeometryFeature, GeometryStatistics
# The following sets up our pseud-simulation data
# Number of frames
frames = np.random.randint(1, 10)
# Number of coarse-grained beads. We need at least 8 so we can do
# dihedrals in the backbone tests (where every other atom is designated
# as a backbone atom)
beads = np.random.randint(8, 20)
# Number of dimensions; for now geometry only handles 3
dims = 3
# Create a pseudo simulation dataset
data = np.random.randn(frames, beads, dims).astype(np.float64)
data_tensor = torch.Tensor(data).double()
geom_feature = GeometryFeature(feature_tuples='all_backbone',
n_beads=beads)
_ = geom_feature.forward(data_tensor)
stats = GeometryStatistics(data_tensor, backbone_inds='all',
get_all_distances=True,
get_backbone_angles=True,
get_backbone_dihedrals=True,
get_redundant_distance_mapping=True)
def test_feature_tuples():
# Tests to see if the feature_tuples attribute is assembled correctly
unique_tuples = []
for desc in stats.order: # for each type of feature
sub_list = stats.descriptions[desc] # list the feature tuples
for bead_tuple in sub_list:
if bead_tuple not in unique_tuples:
unique_tuples.append(bead_tuple)
np.testing.assert_array_equal(unique_tuples, stats.feature_tuples)
def test_custom_feature_shapes():
# Tests whether statistics object has the right number of distances,
# angles, and dihedrals when custom features are given
# First generate the starts of features to be used for distances,
# angles, and dihedrals
custom_starts = np.unique([np.random.randint(beads - 4) for _ in range(5)])
custom_distance_pairs = [(i, i+2) for i in custom_starts]
custom_angle_triples = [(i, i+1, i+2) for i in custom_starts]
custom_dihed_quads = [(i, i+1, i+2, i+3) for i in custom_starts]
custom_features = (custom_distance_pairs +
custom_angle_triples + custom_dihed_quads)
custom_stats = GeometryStatistics(data_tensor, custom_features)
# We just want to make sure that no other features (like backbone)
# showed up
assert len(custom_starts) == len(custom_stats._distance_pairs)
assert len(custom_starts) == len(custom_stats._angle_trips)
assert len(custom_starts) == len(custom_stats._dihedral_quads)
def test_custom_feature_consistency_with_backbone():
# Tests whether manually specifying backbone indices gives the same result
# as automatically calculating backbone features
backbone_angles = [(i, i+1, i+2) for i in range(beads - 2)]
backbone_diheds = [(i, i+1, i+2, i+3) for i in range(beads - 3)]
custom_features = backbone_angles + backbone_diheds
backbone_stats = GeometryStatistics(data_tensor, backbone_inds='all',
get_backbone_angles=True,
get_backbone_dihedrals=True)
backbone_stats_dict = backbone_stats.get_prior_statistics()
custom_stats = GeometryStatistics(data_tensor, custom_features)
custom_stats_dict = custom_stats.get_prior_statistics()
np.testing.assert_array_equal(backbone_stats_dict, custom_stats_dict)
def test_manual_backbone_calculations():
# Make sure backbone distance, angle, and dihedral statistics work
# for manually specified backbone
# Arbitrarily specify backbone indices
# The test should be robust to changing this
backbone_inds = [i for i in range(beads) if i % 2 == 0]
# Create a backbone-only coordinate data tensor
data_tensor_bb_only = data_tensor[:, backbone_inds]
stats_bb_inds = GeometryStatistics(data_tensor,
backbone_inds=backbone_inds,
get_all_distances=True,
get_backbone_angles=True,
get_backbone_dihedrals=True)
stats_bb_only = GeometryStatistics(data_tensor_bb_only,
backbone_inds='all',
get_all_distances=True,
get_backbone_angles=True,
get_backbone_dihedrals=True)
# Distances will be different because there are a different number
# of beads in each dataset, but the bonds (which default to the adjacent
# backbone beads unless bond_pairs are specified) will be the same
# in each case, so we use return_indices to get only the "bond" distances
# for testing
stats_bb_inds_bond_dists = stats_bb_inds.distances[:,
stats_bb_inds.return_indices(stats_bb_inds.bond_pairs)]
stats_bb_only_bond_dists = stats_bb_only.distances[:,
stats_bb_only.return_indices(stats_bb_only.bond_pairs)]
np.testing.assert_allclose(stats_bb_inds_bond_dists,
stats_bb_only_bond_dists)
# Angles and dihedrals calculate the backbone only by default, so we don't
# need to process these first
np.testing.assert_allclose(stats_bb_inds.angles,
stats_bb_only.angles)
np.testing.assert_allclose(stats_bb_inds.dihedral_cosines,
stats_bb_only.dihedral_cosines)
np.testing.assert_allclose(stats_bb_inds.dihedral_sines,
stats_bb_only.dihedral_sines)
def test_manual_backbone_descriptions():
# Make sure backbone distance, angle, and dihedral descriptions work
# for manually specified backbone
# Arbitrarily specify backbone indices
# The test should be robust to changing this
backbone_inds = [i for i in range(beads) if i % 2 == 0]
# Create a backbone-only coordinate data tensor
data_tensor_bb_only = data_tensor[:, backbone_inds]
stats_bb_inds = GeometryStatistics(data_tensor,
backbone_inds=backbone_inds,
get_all_distances=True,
get_backbone_angles=True,
get_backbone_dihedrals=True)
stats_bb_only = GeometryStatistics(data_tensor_bb_only,
backbone_inds='all',
get_all_distances=True,
get_backbone_angles=True,
get_backbone_dihedrals=True)
# Manually specify what all the descriptions should be
bb_inds_bond_descs = [(backbone_inds[i], backbone_inds[i+1])
for i in range(len(backbone_inds)-1)]
bb_only_bond_descs = [(i, i+1) for i in range(len(backbone_inds)-1)]
bb_ind_angle_descs = [(backbone_inds[i], backbone_inds[i+1],
backbone_inds[i+2])
for i in range(len(backbone_inds)-2)]
bb_only_angle_descs = [(i, i+1, i+2) for i in range(len(backbone_inds)-2)]
bb_ind_dihed_descs = [(backbone_inds[i], backbone_inds[i+1],
backbone_inds[i+2], backbone_inds[i+3])
for i in range(len(backbone_inds)-3)]
bb_only_dihed_descs = [(i, i+1, i+2, i+3)
for i in range(len(backbone_inds)-3)]
np.testing.assert_array_equal(stats_bb_inds.bond_pairs,
bb_inds_bond_descs)
np.testing.assert_array_equal(stats_bb_only.bond_pairs,
bb_only_bond_descs)
np.testing.assert_array_equal(stats_bb_inds.descriptions['Angles'],
bb_ind_angle_descs)
np.testing.assert_array_equal(stats_bb_only.descriptions['Angles'],
bb_only_angle_descs)
np.testing.assert_array_equal(stats_bb_inds.descriptions['Dihedral_cosines'],
bb_ind_dihed_descs)
np.testing.assert_array_equal(stats_bb_only.descriptions['Dihedral_cosines'],
bb_only_dihed_descs)
np.testing.assert_array_equal(stats_bb_inds.descriptions['Dihedral_sines'],
bb_ind_dihed_descs)
np.testing.assert_array_equal(stats_bb_only.descriptions['Dihedral_sines'],
bb_only_dihed_descs)
def test_backbone_means_and_stds():
# Make sure distance, angle, and dihedral statistics are consistent with
# numpy
feature_dist_mean = np.mean(geom_feature.distances.numpy(), axis=0)
feature_dist_std = np.std(geom_feature.distances.numpy(), axis=0)
np.testing.assert_allclose(feature_dist_mean,
stats._stats_dict['Distances']['mean'],
rtol=1e-6)
np.testing.assert_allclose(feature_dist_std,
stats._stats_dict['Distances']['std'],
rtol=1e-6)
feature_angle_mean = np.mean(geom_feature.angles.numpy(), axis=0)
feature_angle_std = np.std(geom_feature.angles.numpy(), axis=0)
np.testing.assert_allclose(feature_angle_mean,
stats._stats_dict['Angles']['mean'], rtol=1e-5)
np.testing.assert_allclose(feature_angle_std,
stats._stats_dict['Angles']['std'], rtol=1e-5)
feature_dihed_cos_mean = np.mean(geom_feature.dihedral_cosines.numpy(),
axis=0)
feature_dihed_cos_std = np.std(geom_feature.dihedral_cosines.numpy(),
axis=0)
feature_dihed_sin_mean = np.mean(geom_feature.dihedral_sines.numpy(),
axis=0)
feature_dihed_sin_std = np.std(geom_feature.dihedral_sines.numpy(),
axis=0)
np.testing.assert_allclose(feature_dihed_cos_mean,
stats._stats_dict['Dihedral_cosines']['mean'],
rtol=1e-4)
np.testing.assert_allclose(feature_dihed_cos_std,
stats._stats_dict['Dihedral_cosines']['std'],
rtol=1e-4)
np.testing.assert_allclose(feature_dihed_sin_mean,
stats._stats_dict['Dihedral_sines']['mean'],
rtol=1e-4)
np.testing.assert_allclose(feature_dihed_sin_std,
stats._stats_dict['Dihedral_sines']['std'],
rtol=1e-4)
def test_prior_statistics_shape_1():
# Make sure the "flipped" prior statistics dict has the right structure
# We want to arbitrarily choose among the get_* arguments of
# GeometryStatistics, so we create a bool_list that has at minimum
# one True entry, and shuffle it
bool_list = [True] + [bool(np.random.randint(2)) for _ in range(2)]
np.random.shuffle(bool_list)
stats_ = GeometryStatistics(data_tensor, backbone_inds='all',
get_all_distances=bool_list[0],
get_backbone_angles=bool_list[1],
get_backbone_dihedrals=bool_list[2])
zscore_dict = stats_.get_prior_statistics(flip_dict=True)
# The outer keys in the flipped dictionary are the feature tuples.
# So we can calculate how many keys it should have by knowing how
# many of each calculated feature there should be.
n_keys = (bool_list[0]*beads*(beads-1)/2 + bool_list[1]*(beads-2)
+ bool_list[2]*2*(beads-3))
assert len(zscore_dict) == n_keys
def test_prior_statistics_shape_2():
# Make sure the prior statistics dict has the right structure
# We want to arbitrarily choose among the get_* arguments of
# GeometryStatistics, so we create a bool_list that has at minimum
# one True entry, and shuffle it
bool_list = [True] + [bool(np.random.randint(2)) for _ in range(2)]
np.random.shuffle(bool_list)
stats_ = GeometryStatistics(data_tensor, backbone_inds='all',
get_all_distances=bool_list[0],
get_backbone_angles=bool_list[1],
get_backbone_dihedrals=bool_list[2])
zscore_dict = stats_.get_prior_statistics(flip_dict=False)
n_keys = (bool_list[0]*beads*(beads-1)/2 + bool_list[1]*(beads-2)
+ bool_list[2]*2*(beads-3))
# The INNER keys in the flipped dictionary are the feature tuples.
# So we can calculate how many keys each entry of zscore_dict has
# by knowing how many of each calculated feature there should be.
for k in zscore_dict.keys():
assert len(zscore_dict[k]) == n_keys
def test_prior_statistics():
# Make sure distance means and stds are returned correctly
# Here we choose some random beads at which to start bonds and then
# create bonds of random lengths for our random starts
bond_starts = [np.random.randint(beads-4) for _ in range(4)]
bond_starts = np.unique(bond_starts)
custom_bond_pairs = [(bs, bs+np.random.randint(1, 5))
for bs in bond_starts]
# We manually calculate the means and stds of the bond distances
pair_means = []
pair_stds = []
for pair in sorted(custom_bond_pairs):
pair_means.append(np.mean(np.linalg.norm(data[:, pair[1], :]
- data[:, pair[0], :], axis=1)))
pair_stds.append(np.std(np.linalg.norm(data[:, pair[1], :]
- data[:, pair[0], :], axis=1)))
# We input our custom bonds into stats, and see if they match our
# manual calculations
stats_dict = stats.get_prior_statistics(custom_bond_pairs, tensor=False)
np.testing.assert_allclose(pair_means, [stats_dict[k]['mean']
for k in sorted(stats_dict.keys())],
rtol=1e-6)
np.testing.assert_allclose(pair_stds, [stats_dict[k]['std']
for k in sorted(stats_dict.keys())],
rtol=1e-5)
def test_prior_statistics_2():
# Make sure that prior statistics shuffle correctly
# Here we create a shuffled list of feature tuples
all_possible_features = stats.master_description_tuples
my_inds = np.arange(len(all_possible_features))
np.random.shuffle(my_inds)
cutoff = np.random.randint(1, len(my_inds))
my_inds = my_inds[:cutoff]
all_stats = stats.get_prior_statistics()
some_stats = stats.get_prior_statistics([all_possible_features[i]
for i in my_inds])
# We make sure that the shuffling returns the correct statistics
# by indexing all_corresponding_dicts by our shuffled feature tuples
some_dicts = [some_stats[k] for k in some_stats.keys()]
all_corresponding_dicts = [all_stats[k] for k in some_stats.keys()]
np.testing.assert_array_equal(some_dicts, all_corresponding_dicts)
def test_return_indices_shape_1():
# Test proper retrieval of feature indices for sizes
# We want to arbitrarily choose among the get_* arguments of
# GeometryStatistics, so we create a bool_list that has at minimum
# one True entry, and shuffle it
bool_list = [True] + [bool(np.random.randint(2)) for _ in range(2)]
np.random.shuffle(bool_list)
stats_ = GeometryStatistics(data_tensor, backbone_inds='all',
get_all_distances=bool_list[0],
get_backbone_angles=bool_list[1],
get_backbone_dihedrals=bool_list[2])
# We know how many of each feature there should be, so we manually
# calculate those numbers and compare them to what we get out.
if bool_list[0]:
assert len(stats_.return_indices('Distances')) == (
beads) * (beads - 1) / 2
assert len(stats_.return_indices('Bonds')) == beads - 1
if bool_list[1]:
assert len(stats_.return_indices('Angles')) == beads - 2
if bool_list[2]:
assert len(stats_.return_indices('Dihedral_cosines')) == beads - 3
assert len(stats_.return_indices('Dihedral_sines')) == beads - 3
sum_feats = np.sum([len(stats_.descriptions[feat_name])
for feat_name in stats_.order])
check_sum_feats = (bool_list[0] * (beads) * (beads - 1) / 2 +
bool_list[1] * (beads - 2) +
bool_list[2] * (beads - 3) * 2
)
assert sum_feats == check_sum_feats
def test_return_indices_1():
# Test proper retrieval of | |
far. A list of the on-line status of all generators.
overall_online = [g.online for g in case.generators]
# The objective function value is the total system cost.
overall_cost = solution["f"]
# Best case for this stage.
stage_online = overall_online
stage_cost = overall_cost
# Shutdown at most one generator per stage.
while True:
# 4. Form a candidate list of generators with minimum
# generation limits binding.
# Activate generators according to the stage best.
for i, generator in enumerate(case.generators):
generator.online = stage_online[i]
# Get candidates for shutdown. Lagrangian multipliers are often
# very small so we round to four decimal places.
candidates = [g for g in case.online_generators if \
(round(g.mu_pmin, 4) > 0.0) and (g.p_min > 0.0)]
if len(candidates) == 0:
break
# Assume no improvement during this stage.
done = True
i_stage += 1
logger.debug("De-commitment stage %d." % i_stage)
for candidate in candidates:
# 5. For each generator on the candidate list, solve an OPF to
# find the total system cost with the generator shut down.
# Activate generators according to the stage best.
for i, generator in enumerate(case.generators):
generator.online = stage_online[i]
# Shutdown candidate generator.
candidate.online = False
logger.debug("Solving OPF with generator '%s' shutdown." %
candidate.name)
# Run OPF.
solution = super(UDOPF, self).solve(solver_klass)
# Compare total system costs for improvement.
if solution["converged"] == True \
and (solution["f"] < overall_cost):
logger.debug("System cost improvement: $%.3f ($%.3f)" %
(stage_cost - solution["f"], solution["f"]))
# 6. Replace the current best solution with this one if
# it has a lower cost.
overall_online = [g.online for g in case.generators]
overall_cost = solution["f"]
best_candidate = candidate
# Check for further decommitment.
done = False
else:
logger.debug("Candidate OPF failed [%s]." %
solution["output"]["message"])
# Reactivate the candidate before deactivating the next.
# candidate.online = True
if done:
# Decommits at this stage did not help.
break
else:
# 7. If any of the candidate solutions produced an improvement,
# return to step 3.
# Shutting something else down helps, so let's keep going.
logger.info("Shutting down generator '%s'.",
best_candidate.name)
stage_online = overall_online
stage_cost = overall_cost
# 8. Use the best overall solution as the final solution.
for i, generator in enumerate(case.generators):
generator.online = overall_online[i]
# One final solve using the best case to ensure all results are
# up-to-date.
solution = super(UDOPF, self).solve(solver_klass)
logger.debug("UDOPF system cost: $%.3f" % solution["f"])
# Compute elapsed time and log it.
elapsed = time() - t0
plural = "" if i_stage == 1 else "s"
logger.info("Unit decommitment OPF solved in %.3fs (%d decommitment "
"stage%s)." % (elapsed, i_stage, plural))
return solution
#------------------------------------------------------------------------------
# "OPFModel" class:
#------------------------------------------------------------------------------
class OPFModel(object):
""" Defines a model for optimal power flow.
Based on @opf_model in MATPOWER by <NAME>, developed at PSERC
Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info.
"""
def __init__(self, case):
#: Case to which the model relates.
self.case = case
#: Optimisation variables.
self.vars = []
#: Linear constraints.
self.lin_constraints = []
#: Non-linear constraints.
self.nln_constraints = []
#: User defined costs.
self.costs = []
@property
def var_N(self):
return sum([v.N for v in self.vars])
def add_var(self, var):
""" Adds a variable to the model.
"""
if var.name in [v.name for v in self.vars]:
logger.error("Variable set named '%s' already exists." % var.name)
return
var.i1 = self.var_N
var.iN = self.var_N + var.N - 1
self.vars.append(var)
def add_vars(self, vars):
""" Adds a set of variables to the model.
"""
for var in vars:
self.add_var(var)
def get_var(self, name):
""" Returns the variable set with the given name.
"""
for var in self.vars:
if var.name == name:
return var
else:
raise ValueError
def get_var_N(self, name):
""" Return the number of variables in the named set.
"""
return self.get_var(name).N
@property
def nln_N(self):
return sum([c.N for c in self.nln_constraints])
@property
def lin_N(self):
return sum([c.N for c in self.lin_constraints])
@property
def lin_NS(self):
return len(self.lin_constraints)
def linear_constraints(self):
""" Returns the linear constraints.
"""
if self.lin_N == 0:
return None, array([]), array([])
A = lil_matrix((self.lin_N, self.var_N), dtype=float64)
l = -Inf * ones(self.lin_N)
u = -l
for lin in self.lin_constraints:
if lin.N: # non-zero number of rows to add
Ak = lin.A # A for kth linear constrain set
i1 = lin.i1 # starting row index
iN = lin.iN # ending row index
vsl = lin.vs # var set list
kN = -1 # initialize last col of Ak used
Ai = lil_matrix((lin.N, self.var_N), dtype=float64)
for v in vsl:
var = self.get_var(v)
j1 = var.i1 # starting column in A
jN = var.iN # ending column in A
k1 = kN + 1 # starting column in Ak
kN = kN + var.N # ending column in Ak
if j1 == jN:
# FIXME: Single column slicing broken in lil.
for i in range(Ai.shape[0]):
Ai[i, j1] = Ak[i, k1]
else:
Ai[:, j1:jN + 1] = Ak[:, k1:kN + 1]
A[i1:iN + 1, :] = Ai
l[i1:iN + 1] = lin.l
u[i1:iN + 1] = lin.u
return A.tocsr(), l, u
def add_constraint(self, con):
""" Adds a constraint to the model.
"""
if isinstance(con, LinearConstraint):
N, M = con.A.shape
if con.name in [c.name for c in self.lin_constraints]:
logger.error("Constraint set named '%s' already exists."
% con.name)
return False
else:
con.i1 = self.lin_N# + 1
con.iN = self.lin_N + N - 1
nv = 0
for vs in con.vs:
nv = nv + self.get_var_N(vs)
if M != nv:
logger.error("Number of columns of A does not match number"
" of variables, A is %d x %d, nv = %d", N, M, nv)
self.lin_constraints.append(con)
elif isinstance(con, NonLinearConstraint):
N = con.N
if con.name in [c.name for c in self.nln_constraints]:
logger.error("Constraint set named '%s' already exists."
% con.name)
return False
else:
con.i1 = self.nln_N# + 1
con.iN = self.nln_N + N
self.nln_constraints.append(con)
else:
raise ValueError
return True
def add_constraints(self, constraints):
""" Adds constraints to the model.
"""
for con in constraints:
self.add_constraint(con)
def get_lin_constraint(self, name):
""" Returns the constraint set with the given name.
"""
for c in self.lin_constraints:
if c.name == name:
return c
else:
raise ValueError
def get_nln_constraint(self, name):
""" Returns the constraint set with the given name.
"""
for c in self.nln_constraints:
if c.name == name:
return c
else:
raise ValueError
@property
def cost_N(self):
return sum([c.N for c in self.costs])
def get_cost_params(self):
""" Returns the cost parameters.
"""
return [c.params for c in self.costs]
#------------------------------------------------------------------------------
# "_Set" class:
#------------------------------------------------------------------------------
class _Set(_Named):
def __init__(self, name, N):
#: String identifier.
self.name = name
#: Starting index.
self.i0 = 0
#: Ending index.
self.iN = 0
#: Number in set.
self.N = N
#: Number of sets.
self.NS = 0
#: Ordered list of sets.
self.order = []
#------------------------------------------------------------------------------
# "Variable" class:
#------------------------------------------------------------------------------
class Variable(_Set):
""" Defines a set of variables.
"""
def __init__(self, name, N, v0=None, vl=None , vu=None):
""" Initialises a new Variable instance.
"""
super(Variable, self).__init__(name, N)
#: Initial value of the variables. Zero by default.
if v0 is None:
self.v0 = zeros(N)
else:
self.v0 = v0
#: Lower bound on the variables. Unbounded below be default.
if vl is None:
self.vl = -Inf * ones(N)
else:
self.vl = vl
#: Upper bound on the variables. Unbounded above by default.
if vu is None:
self.vu = Inf * ones(N)
else:
self.vu = vu
#------------------------------------------------------------------------------
# "LinearConstraint" class:
#------------------------------------------------------------------------------
class LinearConstraint(_Set):
""" Defines a set of linear constraints.
"""
def __init__(self, name, AorN, l=None, u=None, vs=None):
N, _ = AorN.shape
super(LinearConstraint, self).__init__(name, N)
self.A = AorN
self.l = -Inf * ones(N) if l is None else l
self.u = Inf * ones(N) if u is None else u
# Varsets.
self.vs = [] if vs is None else vs
if (self.l.shape[0] != N) or (self.u.shape[0] != N):
logger.error("Sizes of A, l and u must match.")
#------------------------------------------------------------------------------
# "NonLinearConstraint" class:
#------------------------------------------------------------------------------
class NonLinearConstraint(_Set):
""" Defines a set of non-linear constraints.
"""
pass
#------------------------------------------------------------------------------
# "Cost" class:
#------------------------------------------------------------------------------
class Cost(_Set):
def __init__(self):
self.N = None
self.H = None
self.Cw = None
self.dd = None
self.rh = None
self.kk = None
self.mm = None
self.vs = None
self.params = None
# | |
u('\u6e56\u5357\u7701\u682a\u6d32\u5e02')},
'861586975':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')},
'861586976':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')},
'861586977':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')},
'861586978':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')},
'861586979':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')},
'861586980':{'en': 'Chenzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u90f4\u5dde\u5e02')},
'861586981':{'en': 'Chenzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u90f4\u5dde\u5e02')},
'861586982':{'en': 'Chenzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u90f4\u5dde\u5e02')},
'861586983':{'en': 'Chenzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u90f4\u5dde\u5e02')},
'861586984':{'en': 'Chenzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u90f4\u5dde\u5e02')},
'861586985':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'861586986':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'861586987':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'861586988':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'861586989':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'861586990':{'en': 'Huaihua, Hunan', 'zh': u('\u6e56\u5357\u7701\u6000\u5316\u5e02')},
'861586991':{'en': 'Huaihua, Hunan', 'zh': u('\u6e56\u5357\u7701\u6000\u5316\u5e02')},
'861586992':{'en': 'Huaihua, Hunan', 'zh': u('\u6e56\u5357\u7701\u6000\u5316\u5e02')},
'861586993':{'en': 'Huaihua, Hunan', 'zh': u('\u6e56\u5357\u7701\u6000\u5316\u5e02')},
'861586994':{'en': 'Huaihua, Hunan', 'zh': u('\u6e56\u5357\u7701\u6000\u5316\u5e02')},
'861586995':{'en': 'Yongzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u6c38\u5dde\u5e02')},
'861586996':{'en': 'Yongzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u6c38\u5dde\u5e02')},
'861586997':{'en': 'Yongzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u6c38\u5dde\u5e02')},
'861586998':{'en': 'Yongzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u6c38\u5dde\u5e02')},
'861586999':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u6c38\u5dde\u5e02')},
'861587000':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u5357\u660c\u5e02')},
'861587001':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u5357\u660c\u5e02')},
'861587002':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u5357\u660c\u5e02')},
'861587003':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u5357\u660c\u5e02')},
'861587004':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u8d63\u5dde\u5e02')},
'861587005':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u666f\u5fb7\u9547\u5e02')},
'861587006':{'en': 'Jingdezhen, Jiangxi', 'zh': u('\u6c5f\u897f\u7701\u666f\u5fb7\u9547\u5e02')},
'861587007':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u840d\u4e61\u5e02')},
'861587008':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u840d\u4e61\u5e02')},
'861587009':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u65b0\u4f59\u5e02')},
'861587010':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u9075\u4e49\u5e02')},
'861587011':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u9075\u4e49\u5e02')},
'861587012':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u9075\u4e49\u5e02')},
'861587013':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u9075\u4e49\u5e02')},
'861587014':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u9075\u4e49\u5e02')},
'861587015':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u5b89\u987a\u5e02')},
'861587016':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u5b89\u987a\u5e02')},
'861587017':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u5b89\u987a\u5e02')},
'861587018':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u94dc\u4ec1\u5730\u533a')},
'861587019':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u94dc\u4ec1\u5730\u533a')},
'86158702':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u9ed4\u4e1c\u5357\u82d7\u65cf\u4f97\u65cf\u81ea\u6cbb\u5dde')},
'86158703':{'en': '<NAME>', 'zh': u('\u8d35\u5dde\u7701\u9ed4\u897f\u5357\u5e03\u4f9d\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde')},
'861587030':{'en': 'Liupanshui, Guizhou', 'zh': u('\u8d35\u5dde\u7701\u516d\u76d8\u6c34\u5e02')},
'861587031':{'en': 'Liupanshui, Guizhou', 'zh': u('\u8d35\u5dde\u7701\u516d\u76d8\u6c34\u5e02')},
'861587032':{'en': 'Liupanshui, Guizhou', 'zh': u('\u8d35\u5dde\u7701\u516d\u76d8\u6c34\u5e02')},
'86158704':{'en': 'Chongqing', 'zh': u('\u91cd\u5e86\u5e02')},
'86158705':{'en': 'Chongqing', 'zh': u('\u91cd\u5e86\u5e02')},
'86158706':{'en': 'Nanchang, Jiangxi', 'zh': u('\u6c5f\u897f\u7701\u5357\u660c\u5e02')},
'861587070':{'en': 'Ganzhou, Jiangxi', 'zh': u('\u6c5f\u897f\u7701\u8d63\u5dde\u5e02')},
'861587071':{'en': 'Ganzhou, Jiangxi', 'zh': u('\u6c5f\u897f\u7701\u8d63\u5dde\u5e02')},
'861587072':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u8d63\u5dde\u5e02')},
'861587073':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u8d63\u5dde\u5e02')},
'861587074':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u8d63\u5dde\u5e02')},
'861587075':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u629a\u5dde\u5e02')},
'861587076':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u629a\u5dde\u5e02')},
'861587077':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u629a\u5dde\u5e02')},
'861587078':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u629a\u5dde\u5e02')},
'861587079':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u629a\u5dde\u5e02')},
'86158708':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u4e5d\u6c5f\u5e02')},
'86158709':{'en': '<NAME>', 'zh': u('\u6c5f\u897f\u7701\u4e0a\u9976\u5e02')},
'86158710':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8944\u6a0a\u5e02')},
'861587108':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u5341\u5830\u5e02')},
'861587109':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u5341\u5830\u5e02')},
'86158711':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u9ec4\u77f3\u5e02')},
'861587110':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u5341\u5830\u5e02')},
'861587111':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u5341\u5830\u5e02')},
'861587112':{'en': 'Shiyan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5341\u5830\u5e02')},
'861587120':{'en': 'Huangshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u9ec4\u77f3\u5e02')},
'861587121':{'en': 'Huangshi, Hubei', 'zh': u('\u6e56\u5317\u7701\u9ec4\u77f3\u5e02')},
'861587122':{'en': 'Suizhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u968f\u5dde\u5e02')},
'861587123':{'en': 'Suizhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u968f\u5dde\u5e02')},
'861587124':{'en': 'Suizhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u968f\u5dde\u5e02')},
'861587125':{'en': 'Suizhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u968f\u5dde\u5e02')},
'861587126':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'861587127':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'861587128':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'861587129':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'861587130':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'861587131':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'861587132':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'861587133':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'861587134':{'en': 'Xiaogan, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b5d\u611f\u5e02')},
'861587135':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587136':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587137':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587138':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587139':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'86158714':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'86158715':{'en': 'Yichang, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b9c\u660c\u5e02')},
'861587150':{'en': 'Ezhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u9102\u5dde\u5e02')},
'861587151':{'en': 'Ezhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u9102\u5dde\u5e02')},
'861587152':{'en': 'Ezhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u9102\u5dde\u5e02')},
'861587153':{'en': 'Ezhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u9102\u5dde\u5e02')},
'86158716':{'en': 'Yichang, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b9c\u660c\u5e02')},
'861587168':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587169':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'86158717':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'86158718':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587190':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587191':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587192':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587193':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587194':{'en': 'Xianning, Hubei', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'861587195':{'en': 'Xianning, Hubei', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'861587196':{'en': 'Xiangfan, Hubei', 'zh': u('\u6e56\u5317\u7701\u8944\u6a0a\u5e02')},
'861587197':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8944\u6a0a\u5e02')},
'861587198':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8346\u95e8\u5e02')},
'861587199':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8346\u95e8\u5e02')},
'86158720':{'en': '<NAME>i', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'861587209':{'en': 'Jingzhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u8346\u5dde\u5e02')},
'86158721':{'en': 'Jingzhou, Hubei', 'zh': u('\u6e56\u5317\u7701\u8346\u5dde\u5e02')},
'861587216':{'en': '<NAME>i', 'zh': u('\u6e56\u5317\u7701\u8346\u95e8\u5e02')},
'861587217':{'en': '<NAME>i', 'zh': u('\u6e56\u5317\u7701\u8346\u95e8\u5e02')},
'861587218':{'en': 'Jingmen, Hubei', 'zh': u('\u6e56\u5317\u7701\u8346\u95e8\u5e02')},
'861587219':{'en': 'Jingmen, Hubei', 'zh': u('\u6e56\u5317\u7701\u8346\u95e8\u5e02')},
'86158722':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8944\u6a0a\u5e02')},
'861587230':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8944\u6a0a\u5e02')},
'861587231':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8944\u6a0a\u5e02')},
'861587232':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8944\u6a0a\u5e02')},
'861587233':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8944\u6a0a\u5e02')},
'861587234':{'en': 'Xiangfan, Hubei', 'zh': u('\u6e56\u5317\u7701\u8944\u6a0a\u5e02')},
'861587235':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587236':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587237':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587238':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587239':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587240':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587241':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587242':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587243':{'en': 'Wuhan, Hubei', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')},
'861587244':{'en': 'Xiangfan, Hubei', 'zh': u('\u6e56\u5317\u7701\u8944\u6a0a\u5e02')},
'861587245':{'en': 'Yichang, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b9c\u660c\u5e02')},
'861587246':{'en': 'Yichang, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b9c\u660c\u5e02')},
'861587247':{'en': 'Yichang, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b9c\u660c\u5e02')},
'861587248':{'en': 'Yichang, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b9c\u660c\u5e02')},
'861587249':{'en': 'Yichang, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b9c\u660c\u5e02')},
'86158725':{'en': 'Yichang, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b9c\u660c\u5e02')},
'86158726':{'en': 'Yichang, Hubei', 'zh': u('\u6e56\u5317\u7701\u5b9c\u660c\u5e02')},
'861587268':{'en': 'Sh<NAME>', 'zh': u('\u6e56\u5317\u7701\u5341\u5830\u5e02')},
'861587269':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u5341\u5830\u5e02')},
'86158727':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u5341\u5830\u5e02')},
'861587276':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'861587277':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'861587278':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'861587279':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'86158728':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u54b8\u5b81\u5e02')},
'861587288':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8346\u95e8\u5e02')},
'861587289':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8346\u95e8\u5e02')},
'86158729':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u8346\u95e8\u5e02')},
'86158730':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u5cb3\u9633\u5e02')},
'86158731':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u957f\u6c99\u5e02')},
'86158732':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u6e58\u6f6d\u5e02')},
'86158733':{'en': 'Zhuzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u682a\u6d32\u5e02')},
'86158734':{'en': 'Hengyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u8861\u9633\u5e02')},
'86158735':{'en': 'Chenzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u90f4\u5dde\u5e02')},
'86158736':{'en': 'Changde, Hunan', 'zh': u('\u6e56\u5357\u7701\u5e38\u5fb7\u5e02')},
'861587370':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')},
'861587371':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')},
'861587372':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')},
'861587373':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')},
'861587374':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')},
'861587375':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'861587376':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'861587377':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'861587378':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'861587379':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'86158738':{'en': 'Loudi, Hunan', 'zh': u('\u6e56\u5357\u7701\u5a04\u5e95\u5e02')},
'86158739':{'en': 'Shaoyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')},
'86158740':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u957f\u6c99\u5e02')},
'86158741':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u957f\u6c99\u5e02')},
'86158742':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u957f\u6c99\u5e02')},
'86158743':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u6e58\u897f\u571f\u5bb6\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde')},
'86158744':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u5f20\u5bb6\u754c\u5e02')},
'86158745':{'en': 'Hu<NAME>', 'zh': u('\u6e56\u5357\u7701\u6000\u5316\u5e02')},
'86158746':{'en': 'Yongzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u6c38\u5dde\u5e02')},
'86158747':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u8861\u9633\u5e02')},
'86158748':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u957f\u6c99\u5e02')},
'86158749':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u957f\u6c99\u5e02')},
'86158750':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861587510':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u97f6\u5173\u5e02')},
'861587511':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u97f6\u5173\u5e02')},
'861587512':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u97f6\u5173\u5e02')},
'861587513':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u97f6\u5173\u5e02')},
'861587514':{'en': 'Yangjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u9633\u6c5f\u5e02')},
'861587515':{'en': 'Yangjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u9633\u6c5f\u5e02')},
'861587516':{'en': 'Yangjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u9633\u6c5f\u5e02')},
'861587517':{'en': 'Yangjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u9633\u6c5f\u5e02')},
'861587518':{'en': 'Yangjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u9633\u6c5f\u5e02')},
'861587519':{'en': 'Jieyang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u63ed\u9633\u5e02')},
'86158752':{'en': 'Huizhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')},
'861587530':{'en': 'Guangzhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u5e7f\u5dde\u5e02')},
'861587531':{'en': 'Guangzhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u5e7f\u5dde\u5e02')},
'861587532':{'en': 'Guangzhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u5e7f\u5dde\u5e02')},
'861587533':{'en': 'Guangzhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u5e7f\u5dde\u5e02')},
'861587534':{'en': 'Guangzhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u5e7f\u5dde\u5e02')},
'861587535':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861587536':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861587537':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861587538':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861587539':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'86158754':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'86158755':{'en': 'Shenzhen, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')},
'86158756':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'86158757':{'en': 'Foshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4f5b\u5c71\u5e02')},
'861587580':{'en': 'Zhaoqing, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'861587581':{'en': 'Zhaoqing, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'861587582':{'en': 'Zhaoqing, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'861587583':{'en': 'Zhaoqing, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'861587584':{'en': 'Zhaoqing, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8087\u5e86\u5e02')},
'861587585':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'861587586':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'861587587':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'861587588':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'861587589':{'en': 'Maoming, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u8302\u540d\u5e02')},
'86158759':{'en': 'Zhanjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6e5b\u6c5f\u5e02')},
'86158760':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861587610':{'en': 'Foshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4f5b\u5c71\u5e02')},
'861587611':{'en': 'Foshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4f5b\u5c71\u5e02')},
'861587612':{'en': 'Foshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4f5b\u5c71\u5e02')},
'861587613':{'en': 'Foshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4f5b\u5c71\u5e02')},
'861587614':{'en': 'Foshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4f5b\u5c71\u5e02')},
'861587615':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861587616':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861587617':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861587618':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861587619':{'en': 'Shantou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5934\u5e02')},
'861587620':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6cb3\u6e90\u5e02')},
'861587621':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6cb3\u6e90\u5e02')},
'861587622':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6cb3\u6e90\u5e02')},
'861587623':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6cb3\u6e90\u5e02')},
'861587624':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6cb3\u6e90\u5e02')},
'861587625':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861587626':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861587627':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861587628':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'861587629':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c5f\u95e8\u5e02')},
'86158763':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6e05\u8fdc\u5e02')},
'861587636':{'en': 'Zhanjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6e5b\u6c5f\u5e02')},
'861587637':{'en': 'Zhanjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6e5b\u6c5f\u5e02')},
'861587638':{'en': 'Zhanjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6e5b\u6c5f\u5e02')},
'861587639':{'en': 'Zhanjiang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6e5b\u6c5f\u5e02')},
'86158764':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')},
'86158765':{'en': 'Guangzhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u5e7f\u5dde\u5e02')},
'86158766':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')},
'861587660':{'en': 'Yunfu, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e91\u6d6e\u5e02')},
'861587661':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u4e91\u6d6e\u5e02')},
'861587670':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6885\u5dde\u5e02')},
'861587671':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6885\u5dde\u5e02')},
'861587672':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6885\u5dde\u5e02')},
'861587673':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6885\u5dde\u5e02')},
'861587674':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5c3e\u5e02')},
'861587675':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5c3e\u5e02')},
'861587676':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5c3e\u5e02')},
'861587677':{'en': 'Shanwei, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6c55\u5c3e\u5e02')},
'861587678':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'861587679':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')},
'86158768':{'en': 'Chaozhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6f6e\u5dde\u5e02')},
'861587689':{'en': 'Guangzhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u5e7f\u5dde\u5e02')},
'86158769':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')},
'861587700':{'en': 'Guilin, Guangxi', 'zh': u('\u5e7f\u897f\u6842\u6797\u5e02')},
'861587701':{'en': 'Guilin, Guangxi', 'zh': u('\u5e7f\u897f\u6842\u6797\u5e02')},
'861587702':{'en': '<NAME>', 'zh': u('\u5e7f\u897f\u6842\u6797\u5e02')},
'861587703':{'en': '<NAME>', 'zh': u('\u5e7f\u897f\u6842\u6797\u5e02')},
'861587704':{'en': '<NAME>', 'zh': u('\u5e7f\u897f\u6842\u6797\u5e02')},
'861587705':{'en': '<NAME>', 'zh': u('\u5e7f\u897f\u7389\u6797\u5e02')},
'861587706':{'en': '<NAME>', 'zh': u('\u5e7f\u897f\u7389\u6797\u5e02')},
'861587707':{'en': '<NAME>', 'zh': u('\u5e7f\u897f\u7389\u6797\u5e02')},
'861587708':{'en': '<NAME>', 'zh': u('\u5e7f\u897f\u7389\u6797\u5e02')},
'861587709':{'en': '<NAME>', 'zh': u('\u5e7f\u897f\u7389\u6797\u5e02')},
'86158771':{'en': '<NAME>', 'zh': u('\u5e7f\u897f\u5357\u5b81\u5e02')},
'86158772':{'en': '<NAME>', 'zh': u('\u5e7f\u897f\u67f3\u5dde\u5e02')},
'861587730':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u6c49\u4e2d\u5e02')},
'861587731':{'en': '<NAME>', 'zh': | |
<reponame>Apteco/apteco-api<gh_stars>1-10
# coding: utf-8
"""
Apteco API
An API to allow access to Apteco Marketing Suite resources # noqa: E501
The version of the OpenAPI document: v2
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class CommunicationStatistics(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'days': 'list[str]',
'communications_counts': 'list[int]',
'total_communications_count': 'int',
'deliveries_counts': 'list[int]',
'total_deliveries_count': 'int',
'messages_counts': 'list[int]',
'total_messages_count': 'int',
'campaigns_counts': 'list[int]',
'total_campaigns_count': 'int',
'people_counts': 'list[int]',
'communication_statistics_timestamp': 'datetime',
'campaign_statistics_timestamp': 'datetime',
'people_statistics_timestamp': 'datetime'
}
attribute_map = {
'days': 'days',
'communications_counts': 'communicationsCounts',
'total_communications_count': 'totalCommunicationsCount',
'deliveries_counts': 'deliveriesCounts',
'total_deliveries_count': 'totalDeliveriesCount',
'messages_counts': 'messagesCounts',
'total_messages_count': 'totalMessagesCount',
'campaigns_counts': 'campaignsCounts',
'total_campaigns_count': 'totalCampaignsCount',
'people_counts': 'peopleCounts',
'communication_statistics_timestamp': 'communicationStatisticsTimestamp',
'campaign_statistics_timestamp': 'campaignStatisticsTimestamp',
'people_statistics_timestamp': 'peopleStatisticsTimestamp'
}
def __init__(self, days=None, communications_counts=None, total_communications_count=None, deliveries_counts=None, total_deliveries_count=None, messages_counts=None, total_messages_count=None, campaigns_counts=None, total_campaigns_count=None, people_counts=None, communication_statistics_timestamp=None, campaign_statistics_timestamp=None, people_statistics_timestamp=None): # noqa: E501
"""CommunicationStatistics - a model defined in OpenAPI""" # noqa: E501
self._days = None
self._communications_counts = None
self._total_communications_count = None
self._deliveries_counts = None
self._total_deliveries_count = None
self._messages_counts = None
self._total_messages_count = None
self._campaigns_counts = None
self._total_campaigns_count = None
self._people_counts = None
self._communication_statistics_timestamp = None
self._campaign_statistics_timestamp = None
self._people_statistics_timestamp = None
self.discriminator = None
self.days = days
self.communications_counts = communications_counts
self.total_communications_count = total_communications_count
self.deliveries_counts = deliveries_counts
self.total_deliveries_count = total_deliveries_count
self.messages_counts = messages_counts
self.total_messages_count = total_messages_count
self.campaigns_counts = campaigns_counts
self.total_campaigns_count = total_campaigns_count
self.people_counts = people_counts
if communication_statistics_timestamp is not None:
self.communication_statistics_timestamp = communication_statistics_timestamp
if campaign_statistics_timestamp is not None:
self.campaign_statistics_timestamp = campaign_statistics_timestamp
if people_statistics_timestamp is not None:
self.people_statistics_timestamp = people_statistics_timestamp
@property
def days(self):
"""Gets the days of this CommunicationStatistics. # noqa: E501
The set of days where communication information is available # noqa: E501
:return: The days of this CommunicationStatistics. # noqa: E501
:rtype: list[str]
"""
return self._days
@days.setter
def days(self, days):
"""Sets the days of this CommunicationStatistics.
The set of days where communication information is available # noqa: E501
:param days: The days of this CommunicationStatistics. # noqa: E501
:type: list[str]
"""
if days is None:
raise ValueError("Invalid value for `days`, must not be `None`") # noqa: E501
self._days = days
@property
def communications_counts(self):
"""Gets the communications_counts of this CommunicationStatistics. # noqa: E501
The set of counts representing the number of communications on the corresponding day. The first figure is data for the first day in the Days list, and so on. # noqa: E501
:return: The communications_counts of this CommunicationStatistics. # noqa: E501
:rtype: list[int]
"""
return self._communications_counts
@communications_counts.setter
def communications_counts(self, communications_counts):
"""Sets the communications_counts of this CommunicationStatistics.
The set of counts representing the number of communications on the corresponding day. The first figure is data for the first day in the Days list, and so on. # noqa: E501
:param communications_counts: The communications_counts of this CommunicationStatistics. # noqa: E501
:type: list[int]
"""
if communications_counts is None:
raise ValueError("Invalid value for `communications_counts`, must not be `None`") # noqa: E501
self._communications_counts = communications_counts
@property
def total_communications_count(self):
"""Gets the total_communications_count of this CommunicationStatistics. # noqa: E501
The total number of communications across all days # noqa: E501
:return: The total_communications_count of this CommunicationStatistics. # noqa: E501
:rtype: int
"""
return self._total_communications_count
@total_communications_count.setter
def total_communications_count(self, total_communications_count):
"""Sets the total_communications_count of this CommunicationStatistics.
The total number of communications across all days # noqa: E501
:param total_communications_count: The total_communications_count of this CommunicationStatistics. # noqa: E501
:type: int
"""
if total_communications_count is None:
raise ValueError("Invalid value for `total_communications_count`, must not be `None`") # noqa: E501
self._total_communications_count = total_communications_count
@property
def deliveries_counts(self):
"""Gets the deliveries_counts of this CommunicationStatistics. # noqa: E501
The set of counts representing the number of deliveries that have run on the corresponding day. The first figure is data for the first day in the Days list, and so on. # noqa: E501
:return: The deliveries_counts of this CommunicationStatistics. # noqa: E501
:rtype: list[int]
"""
return self._deliveries_counts
@deliveries_counts.setter
def deliveries_counts(self, deliveries_counts):
"""Sets the deliveries_counts of this CommunicationStatistics.
The set of counts representing the number of deliveries that have run on the corresponding day. The first figure is data for the first day in the Days list, and so on. # noqa: E501
:param deliveries_counts: The deliveries_counts of this CommunicationStatistics. # noqa: E501
:type: list[int]
"""
if deliveries_counts is None:
raise ValueError("Invalid value for `deliveries_counts`, must not be `None`") # noqa: E501
self._deliveries_counts = deliveries_counts
@property
def total_deliveries_count(self):
"""Gets the total_deliveries_count of this CommunicationStatistics. # noqa: E501
The total number of deliveries that have run across all days # noqa: E501
:return: The total_deliveries_count of this CommunicationStatistics. # noqa: E501
:rtype: int
"""
return self._total_deliveries_count
@total_deliveries_count.setter
def total_deliveries_count(self, total_deliveries_count):
"""Sets the total_deliveries_count of this CommunicationStatistics.
The total number of deliveries that have run across all days # noqa: E501
:param total_deliveries_count: The total_deliveries_count of this CommunicationStatistics. # noqa: E501
:type: int
"""
if total_deliveries_count is None:
raise ValueError("Invalid value for `total_deliveries_count`, must not be `None`") # noqa: E501
self._total_deliveries_count = total_deliveries_count
@property
def messages_counts(self):
"""Gets the messages_counts of this CommunicationStatistics. # noqa: E501
The set of counts representing the number of messages that have had at least one delivery run on the corresponding day. The first figure is data for the first day in the Days list, and so on. # noqa: E501
:return: The messages_counts of this CommunicationStatistics. # noqa: E501
:rtype: list[int]
"""
return self._messages_counts
@messages_counts.setter
def messages_counts(self, messages_counts):
"""Sets the messages_counts of this CommunicationStatistics.
The set of counts representing the number of messages that have had at least one delivery run on the corresponding day. The first figure is data for the first day in the Days list, and so on. # noqa: E501
:param messages_counts: The messages_counts of this CommunicationStatistics. # noqa: E501
:type: list[int]
"""
if messages_counts is None:
raise ValueError("Invalid value for `messages_counts`, must not be `None`") # noqa: E501
self._messages_counts = messages_counts
@property
def total_messages_count(self):
"""Gets the total_messages_count of this CommunicationStatistics. # noqa: E501
The total number of messages that have had at least one delivery run across all days # noqa: E501
:return: The total_messages_count of this CommunicationStatistics. # noqa: E501
:rtype: int
"""
return self._total_messages_count
@total_messages_count.setter
def total_messages_count(self, total_messages_count):
"""Sets the total_messages_count of this CommunicationStatistics.
The total number of messages that have had at least one delivery run across all days # noqa: E501
:param total_messages_count: The total_messages_count of this CommunicationStatistics. # noqa: E501
:type: int
"""
if total_messages_count is None:
raise ValueError("Invalid value for `total_messages_count`, must not be `None`") # noqa: E501
self._total_messages_count = total_messages_count
@property
def campaigns_counts(self):
"""Gets the campaigns_counts of this CommunicationStatistics. # noqa: E501
The set of counts representing the number of campaigns that have had at least one delivery run on the corresponding day. The first figure is data for the first day in the Days list, and so on. # noqa: E501
:return: The campaigns_counts of this CommunicationStatistics. # noqa: E501
:rtype: list[int]
"""
return self._campaigns_counts
@campaigns_counts.setter
def campaigns_counts(self, campaigns_counts):
"""Sets the campaigns_counts of this CommunicationStatistics.
The set of counts representing the number of campaigns that have had at least one delivery run on the corresponding day. The first figure is data for the first day in the Days list, and so on. # noqa: E501
:param campaigns_counts: The campaigns_counts of this CommunicationStatistics. # noqa: E501
:type: list[int]
"""
if campaigns_counts is None:
raise ValueError("Invalid value for `campaigns_counts`, must not be `None`") # noqa: E501
self._campaigns_counts = campaigns_counts
@property
def total_campaigns_count(self):
"""Gets the total_campaigns_count of this CommunicationStatistics. # noqa: E501
The total number of campaigns that have had at least one delivery run across all days # noqa: E501
:return: The total_campaigns_count of this CommunicationStatistics. # noqa: E501
:rtype: int
"""
return self._total_campaigns_count
@total_campaigns_count.setter
def total_campaigns_count(self, total_campaigns_count):
"""Sets the total_campaigns_count of this CommunicationStatistics.
The total number of campaigns | |
other
elif other%2 == 1: # odd power
powL = self.__lo ** other
powH = self.__hi ** other
elif other < 0:
if other%2 == 0: # even power
if self.__lo >= 0:
powL = self.__hi ** other
powH = self.__lo ** other
elif self.__hi < 0:
powL = self.__lo ** other
powH = self.__hi ** other
else: # interval contains zero
print("Error. \nThe interval contains zero, so negative powers should return \u00B1 Infinity")
elif other%2 == 1: # odd power
if self.__lo != 0:
powL = self.__hi ** other
powH = self.__lo ** other
else: # interval contains zero
print("Error. \nThe interval contains zero, so negative powers should return \u00B1 Infinity")
elif otherType == "float":
if self.__lo >= 0:
if other > 0:
powL = self.__lo ** other
powH = self.__hi ** other
elif other < 0:
powL = self.__hi ** other
powH = self.__lo ** other
elif other == 0:
powL = 1
powH = 1
return Interval(powL,powH)
def __rpow__(self,left):
raise TypeError('Interval exponents are not needed for this library.')
def __lt__(self, other):
if other.__class__.__name__ in intervalDataTypes():
return self.sup() < other.inf()
elif other.__class__.__name__ in numberDataTypes():
return self.sup() < other
def __rlt__(self,left):
if left.__class__.__name__ in intervalDataTypes():
return left.sup() < self.inf()
elif left.__class__.__name__ in numberDataTypes():
return left < self.inf()
def __gt__(self, other):
if other.__class__.__name__ in intervalDataTypes():
return self.inf() > other.sup()
elif other.__class__.__name__ in numberDataTypes():
return self.inf() > other
def __rgt__(self, left):
if left.__class__.__name__ in intervalDataTypes():
return left.inf() > self.sup()
elif left.__class__.__name__ in numberDataTypes():
return left > self.sup()
def __le__(self, other):
if other.__class__.__name__ in intervalDataTypes():
return self.sup() <= other.inf()
elif other.__class__.__name__ in numberDataTypes():
return self.sup() <= other
def __rle__(self,left):
if left.__class__.__name__ in intervalDataTypes():
return left.sup() <= self.inf()
elif left.__class__.__name__ in numberDataTypes():
return left <= self.inf()
def __ge__(self, other):
if other.__class__.__name__ in intervalDataTypes():
return self.inf() >= other.sup()
elif other.__class__.__name__ in numberDataTypes():
return self.inf() >= other
def __rge__(self, left):
if left.__class__.__name__ in intervalDataTypes():
return left.inf() >= self.sup()
elif left.__class__.__name__ in numberDataTypes():
return left >= self.sup()
def __eq__(self, other):
if other.__class__.__name__ in intervalDataTypes():
return hash(self)==hash(other)
else:
return False
def __ne__(self,other):
return not(self == other)
#------------------------------------------------------------------------------------------------------
# Override arithmetic operators END
#------------------------------------------------------------------------------------------------------
class ComplexInterval(): # simple complex interval class
"""
Created on Mon Jul 13 2020
Author: <NAME>
University of Liverpool
github.com/marcodeangelis
GNU LGPL v3.0
In the *interval Fourier transform* code this class is only used for addition and scalar multiplication.
Support for subintervalization was also removed to make the code slimmer.
"""
def __repr__(self): # return
return "【%g%+gi, %g%+gi】"%(self.__lo.real,self.__lo.imag,self.__hi.real,self.__hi.imag)
def __str__(self): # print
return "【%g%+gi, %g%+gi】"%(self.__lo.real,self.__lo.imag,self.__hi.real,self.__hi.imag)
def __init__(self,*args):
if (args is None) | (len(args)==0):
lo, hi = -1-1j, 1+1j
if len(args)==1:
lo, hi = args[0], args[0]
if len(args)==2:
lo, hi = args[0], args[1]
self.__lo = lo
self.__hi = hi
# ------------------------------------ #
## ---- Class methods start here ---- ##
def lo(self):
return self.__lo
def hi(self):
return self.__hi
def mid(self):
return (self.__lo + self.__hi)/2
def rad(self):
return (self.__hi - self.__lo)/2
def width(self):
return self.__hi - self.__lo
def stradzero(self):
iszeroin = [False,False]
if (self.__lo.real <= 0) & (self.__hi.real >= 0):
iszeroin[0] = True
if (self.__lo.imag <= 0) & (self.__hi.imag >= 0):
iszeroin[1] = True
return iszeroin
def slider(self,p):
return self.__lo + p * self.width()
def real(self):
return Interval(self.__lo.real, self.__hi.real)
def imag(self):
return Interval(self.__lo.imag, self.__hi.imag)
def conjugate(self):
return ComplexInterval(self.__lo.conjugate(),self.__hi.conjugate())
def absolute(self):
return (self.real()**2 + self.imag()**2)**0.5
def __abs__(self):
return self.absolute()
## ------ Class methods end here ------ ##
#----------------------------------------#
# Override arithmetical operations START #
#----------------------------------------#
def __add__(self,other):
otherType = other.__class__.__name__
if otherType in numberDataTypes(): # add support for numpy
addL = self.__lo + other
addH = self.__hi + other
return ComplexInterval(addL,addH)
elif otherType in intervalDataTypes():
addL = self.__lo + other.lo()
addH = self.__hi + other.hi()
return ComplexInterval(addL,addH)
else:
raise TypeError('Addition only allowed between numbers.')
def __radd__(self, left):
leftType = left.__class__.__name__
if leftType in numberDataTypes():
return self.__add__(left)
else:
raise TypeError('Addition only allowed between numbers.')
def __sub__(self, other):
otherType = other.__class__.__name__
if otherType in numberDataTypes():
subL = self.__lo - other
subH = self.__hi - other
return ComplexInterval(subL,subH)
elif otherType in intervalDataTypes():
subL = self.__lo - other.hi()
subH = self.__hi - other.lo()
return ComplexInterval(subL,subH)
def __rsub__(self, left):
leftType = left.__class__.__name__
if leftType in numberDataTypes():
subL = left - self.__hi
subH = left - self.__lo
return ComplexInterval(subL,subH)
else:
raise TypeError('Subtraction only allowed between numbers.')
def __mul__(self,other):
otherType = other.__class__.__name__
if otherType in numberDataTypes():
Real = self.real()*other.real - self.imag()*other.imag
Imag = self.real()*other.imag + self.imag()*other.real
mulL = Real.lo()+1j*Imag.lo()
mulH = Real.hi()+1j*Imag.hi()
return ComplexInterval(mulL,mulH)
elif otherType in intervalDataTypes():
if otherType == 'ComplexInterval':
Real = self.real()*other.real() - self.imag()*other.imag()
Imag = self.real()*other.imag() + self.imag()*other.real()
mulL = Real.lo()+1j*Imag.lo()
mulH = Real.hi()+1j*Imag.hi()
return ComplexInterval(mulL,mulH)
else:
Real = self.real()*other # - self.imag()*other.imag()
Imag = self.imag()*other #self.real()*other.imag() + self.imag()*other.real()
mulL = Real.lo()+1j*Imag.lo()
mulH = Real.hi()+1j*Imag.hi()
return ComplexInterval(mulL,mulH)
def __rmul__(self, left):
leftType = left.__class__.__name__
if leftType in numberDataTypes():
return self.__mul__(left)
else:
raise TypeError('Multiplication only allowed between numbers.')
def __truediv__(self,other):
otherType = other.__class__.__name__
if otherType in numberDataTypes():
a,b,c,d = self.real(), self.imag(), other.real, other.imag
Real = (a*c + b*d)/(c**2 + d**2)
Imag = (b*c - a*d)/(c**2 + d**2)
divL = Real.lo()+1j*Imag.lo()
divH = Real.hi()+1j*Imag.hi()
return ComplexInterval(divL,divH)
elif otherType in intervalDataTypes():
if otherType == 'ComplexInterval':
a,b = self.real(), self.imag()#, other.real(), other.imag()
a,b,c,d = self.real(), self.imag(), other.real(), other.imag()
Real = (a*c + b*d)/(c**2 + d**2)
Imag = (b*c - a*d)/(c**2 + d**2)
divL = Real.lo()+1j*Imag.lo()
divH = Real.hi()+1j*Imag.hi()
return ComplexInterval(divL,divH)
else:
a,b,c = self.real(), self.imag(), other
Real = a/c
Imag = b/c
divL = Real.lo()+1j*Imag.lo()
divH = Real.hi()+1j*Imag.hi()
return ComplexInterval(divL,divH)
def __rtruediv__(self, left):
leftType = left.__class__.__name__
if leftType in numberDataTypes():
if leftType in complexNumberTypes():
a,b,c,d = left.real, left.imag, self.real(), self.imag()
Real = (a*c + b*d)/(c**2 + d**2)
Imag = (b*c - a*d)/(c**2 + d**2)
divL = Real.lo()+1j*Imag.lo()
divH = Real.hi()+1j*Imag.hi()
return ComplexInterval(divL,divH)
else:
a,c,d = left, self.real(), self.imag()
Real = (a*c)/(c**2 + d**2)
Imag = -(a*d)/(c**2 + d**2)
divL = Real.lo()+1j*Imag.lo()
divH = Real.hi()+1j*Imag.hi()
return ComplexInterval(divL,divH)
else:
raise TypeError('Division only allowed between numbers.')
#-------------------------------------#
# Override arithmetical operations END
#-------------------------------------#
class IntervalVector(): # wrapper class of the scalar class interval with some plotting facilities
"""
Created on Mon Jul 24 17:09:51 2020
@author: <NAME>
University of Liverpool
github.com/marcodeangelis
GNU LGPL v3.0
"""
def __repr__(self): # return
if len(self)>10:
a = [str(i) for i in self]
s = '\n'.join(a[:5]+['...']+a[-5:-1])
else:
s = '\n'.join([str(i) for i in self])
return s
def __str__(self): # print
return self.__repr__()
def __len__(self):
return len([i for i in self])
def __init__(self,*args,notation='infsup',axis=1,name=''):
self.name = name # initialise this with an empty string
if len(args)==0: # what should an empty IntervalArray(object) look like?
self.__lo = [-1]
self.__hi = [1]
elif len(args)==1: # this must be a list, tuple (array?) of intervals
assert args[0].__class__.__name__ in ['list', 'tuple','IntervalVector'], 'single input must be list or a tuple of intervals.'
if args[0][0].__class__.__name__ in ['Interval','ComplexInterval']:
self.__lo = [x.lo() for x in args[0]]
self.__hi = [x.hi() for x in args[0]]
elif args[0][0].__class__.__name__ in ['list','tuple']:
if axis == 0:
assert len(args[0]) == 2, 'a list or tuple is needed.'
self.__lo, self.__hi = args[0][0], args[0][1]
elif axis == 1:
self.__lo = list([x for x in zip(*args[0])][0])
self.__hi = list([x for x in zip(*args[0])][1])
elif len(args)==2:
if args[0].__class__.__name__ == 'list':
self.__lo, self.__hi = args[0], args[1]
else:
self.__lo = list()
self.__hi = list()
for a in args:
if a.__class__.__name__ == 'tuple':
self.__lo.append(a[0])
self.__hi.append(a[1])
elif a.__class__.__name__ == 'Interval':
self.__lo.append(a.lo())
self.__hi.append(a.hi())
else:
raise TypeError('multiple arguments must be a tuple or an interval.')
def __iter__(self): # make class iterable
for l,u in zip(self.__lo,self.__hi):
yield Interval(l,u)
def __getitem__(self,index): # make class subscrictable
if index.__class__.__name__ in ['list','tuple']:
if len(index)>0:
return IntervalVector([Interval(self.__lo[i],self.__hi[i]) for i in index])
else:
return IntervalVector([]) # todo: create empty dataset
else:
return Interval(self.__lo[index],self.__hi[index])
def inf(self):
return self.__lo
def lo(self):
return self.__lo
def sup(self):
return self.__hi
def hi(self):
return self.__hi
def tolist(self):
return [Interval(l,h) for l,h in zip(self.__lo,self.__hi)]
def toarray(self, order='F'):
if order=='F':
return numpy.array([self.__lo, self.__hi])
elif order=='C':
return numpy.array([self.__lo, self.__hi]).T
def slider(self,p=0.5):
if p.__class__.__name__ in | |
child."""
def doFit():
size = self.GetBestChildSize()
if size == self.ManagedChild.Size: return
self.ManagedChild.Size = size
self.AdjustToSize(size)
self.Parent.ContainingSizer.Layout()
self._fit = True
doFit()
wx.CallLater(1, doFit) # Might need recalculation after first layout
def GetBestChildSize(self):
"""Returns size for managed child fitting content in resize directions."""
linesmax, widthmax = -1, -1
if "posix" == os.name:
# GetLineLength() does not account for wrapped lines in linux
w, dc = self.ManagedChild.Size[0], wx.ClientDC(self.ManagedChild)
t = wx.lib.wordwrap.wordwrap(self.ManagedChild.Value, w, dc)
linesmax = t.count("\n")
# DoGetBorderSize() appears not implemented under Gtk
borderw, borderh = (x / 2. for x in self.ManagedChild.GetWindowBorderSize())
else:
while self.ManagedChild.GetLineLength(linesmax + 1) >= 0:
linesmax += 1
t = self.ManagedChild.GetLineText(linesmax)
widthmax = max(widthmax, self.ManagedChild.GetTextExtent(t)[0])
borderw, borderh = self.ManagedChild.DoGetBorderSize()
_, charh = self.ManagedChild.GetTextExtent("X")
size = self.Size
size[0] -= wx.lib.resizewidget.RW_THICKNESS
size[1] -= wx.lib.resizewidget.RW_THICKNESS
if self._direction & wx.HORIZONTAL:
size[0] = 2 * borderw + widthmax
if self._direction & wx.VERTICAL:
size[1] = 2 * borderh + charh * (linesmax + 1)
return size
def OnLeftDClick(self, event=None):
"""Handles the wx.EVT_LEFT_DCLICK event, toggling fit-mode on or off."""
if self._fit:
self._fit = False
self.ManagedChild.Size = self.ManagedChild.EffectiveMinSize
self.AdjustToSize(self.ManagedChild.Size)
self.Parent.ContainingSizer.Layout()
else: self.Fit()
def OnLeftUp(self, evt):
"""Handles the wx.EVT_LEFT_UP event."""
self._dragPos = None
if self.HasCapture():
self.ReleaseMouse()
self.InvalidateBestSize()
def OnMouseLeave(self, event):
"""Handles the wx.EVT_LEAVE_WINDOW event."""
if not self.HasCapture() and self._resizeCursor:
self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
self._resizeCursor = False
def OnMouseMove(self, evt):
"""
Handles wx.EVT_MOTION event. Overrides inherited .OnMouseMove
to constrain resize to configured directions only.
"""
pos = evt.GetPosition()
if self._hitTest(pos) and self._resizeEnabled:
if not self._resizeCursor:
self.SetCursor(wx.Cursor(wx.CURSOR_SIZENWSE))
self._resizeCursor = True
elif not self.HasCapture():
if self._resizeCursor:
self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
self._resizeCursor = False
if evt.Dragging() and self._dragPos is not None:
self._fit = False
delta, posDelta = wx.Size(), self._dragPos - pos
if self._direction & wx.HORIZONTAL: delta[0] = posDelta[0]
if self._direction & wx.VERTICAL: delta[1] = posDelta[1]
newSize = self.GetSize() - delta
self._adjustNewSize(newSize)
if newSize != self.GetSize():
self.SetSize(newSize)
self._dragPos = pos
self._bestSize = newSize
self.InvalidateBestSize()
self._sendEvent()
def OnSize(self, evt):
"""Handles wx.EVT_SIZE event, resizing control if control fitted."""
if self._ignoresizeevt: return
super(ResizeWidget, self).OnSize(evt)
if self._fit and not self._ignoresizeevt:
self._ignoresizeevt = True
wx.CallAfter(self.Fit)
wx.CallLater(100, setattr, self, "_ignoresizeevt", False)
def DoGetBestSize(self):
"""Returns the best size."""
if self.HasCapture(): return self._bestSize
HANDLE = wx.lib.resizewidget.RW_THICKNESS
c = self.ManagedChild
size, csize = wx.Size(*self._bestSize), c.EffectiveMinSize
# Allow external resizing to function from child size
if not self._direction & wx.HORIZONTAL: size[0] = csize[0] + HANDLE
if not self._direction & wx.VERTICAL: size[1] = csize[1] + HANDLE
return size
class SortableUltimateListCtrl(wx.lib.agw.ultimatelistctrl.UltimateListCtrl,
wx.lib.mixins.listctrl.ColumnSorterMixin):
"""
A sortable list control that can be batch-populated, autosizes its columns,
can be filtered by string value matched on any row column,
supports clipboard copy.
"""
COL_PADDING = 30
SORT_ARROW_UP = wx.lib.embeddedimage.PyEmbeddedImage(
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAADxJ"
"REFUOI1jZGRiZqA<KEY>P/f3/9kGwDTjM8QnAaga8JlCG3CAJdt2MQxDCAUaOjyjKMp"
"cRAYAABS2CPsss3BWQAAAABJRU5ErkJggg==")
#----------------------------------------------------------------------
SORT_ARROW_DOWN = wx.lib.embeddedimage.PyEmbeddedImage(
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAEhJ"
"<KEY>"
"<KEY>)
def __init__(self, *args, **kwargs):
kwargs.setdefault("agwStyle", 0)
if hasattr(wx.lib.agw.ultimatelistctrl, "ULC_USER_ROW_HEIGHT"):
kwargs["agwStyle"] |= wx.lib.agw.ultimatelistctrl.ULC_USER_ROW_HEIGHT
if hasattr(wx.lib.agw.ultimatelistctrl, "ULC_SHOW_TOOLTIPS"):
kwargs["agwStyle"] |= wx.lib.agw.ultimatelistctrl.ULC_SHOW_TOOLTIPS
wx.lib.agw.ultimatelistctrl.UltimateListCtrl.__init__(self, *args, **kwargs)
wx.lib.mixins.listctrl.ColumnSorterMixin.__init__(self, 0)
try:
ColourManager.Manage(self._headerWin, "ForegroundColour", wx.SYS_COLOUR_BTNTEXT)
ColourManager.Manage(self._mainWin, "BackgroundColour", wx.SYS_COLOUR_WINDOW)
except Exception: pass
self.itemDataMap = {} # {item_id: [values], } for ColumnSorterMixin
self._data_map = {} # {item_id: row dict, } currently visible data
self._id_rows = [] # [(item_id, {row dict}), ] all data items
self._id_images = {} # {item_id: imageIds}
self._columns = [] # [(name, label), ]
self._filter = "" # Filter string
self._col_widths = {} # {col_index: width in pixels, }
self._col_maxwidth = -1 # Maximum width for auto-sized columns
self._top_row = None # List top row data dictionary, if any
self._drag_start = None # Item index currently dragged
self.counter = lambda x={"c": 0}: x.update(c=1+x["c"]) or x["c"]
self.AssignImageList(self._CreateImageList(), wx.IMAGE_LIST_SMALL)
# Default row column formatter function
frmt = lambda: lambda r, c: "" if r.get(c) is None else unicode(r[c])
self._formatters = collections.defaultdict(frmt)
id_copy = wx.NewIdRef().Id
entries = [(wx.ACCEL_CMD, x, id_copy) for x in KEYS.INSERT + (ord("C"), )]
self.SetAcceleratorTable(wx.AcceleratorTable(entries))
self.Bind(wx.EVT_MENU, self.OnCopy, id=id_copy)
self.Bind(wx.EVT_LIST_COL_CLICK, self.OnSort)
self.Bind(wx.lib.agw.ultimatelistctrl.EVT_LIST_BEGIN_DRAG, self.OnDragStart)
self.Bind(wx.lib.agw.ultimatelistctrl.EVT_LIST_END_DRAG, self.OnDragStop)
self.Bind(wx.lib.agw.ultimatelistctrl.EVT_LIST_BEGIN_RDRAG, self.OnDragCancel)
self.Bind(wx.EVT_SYS_COLOUR_CHANGED, self.OnSysColourChange)
def GetScrollThumb(self, orientation):
"""Returns the scrollbar size in pixels."""
# Workaround for wxpython v4 bug of missing orientation parameter
return self._mainWin.GetScrollThumb(orientation) if self._mainWin else 0
def GetScrollRange(self, orientation):
"""Returns the scrollbar range in pixels."""
# Workaround for wxpython v4 bug of missing orientation parameter
return self._mainWin.GetScrollRange(orientation) if self._mainWin else 0
def GetSortImages(self):
"""For ColumnSorterMixin."""
return (0, 1)
def AssignImages(self, images):
"""
Assigns images associated with the control.
SetTopRow/AppendRow/InsertRow/Populate use imageIds from this list.
@param images list of wx.Bitmap objects
"""
for x in images: self.GetImageList(wx.IMAGE_LIST_SMALL).Add(x)
if hasattr(self, "SetUserLineHeight"):
h = images[0].Size[1]
self.SetUserLineHeight(int(h * 1.5))
def SetTopRow(self, data, imageIds=()):
"""
Adds special top row to list, not subject to sorting or filtering.
@param data item data dictionary
@param imageIds list of indexes for the images associated to top row
"""
self._top_row = data
if imageIds: self._id_images[-1] = self._ConvertImageIds(imageIds)
else: self._id_images.pop(-1, None)
self._PopulateTopRow()
def SetColumnFormatters(self, formatters):
"""
Sets the functions used for formatting displayed column values.
@param formatters {col_name: function(rowdict, col_name), }
"""
self._formatters.clear()
if formatters: self._formatters.update(formatters)
def Populate(self, rows, imageIds=()):
"""
Populates the control with rows, clearing previous data, if any.
Re-selects the previously selected row, if any.
@param rows a list of data dicts
@param imageIds list of indexes for the images associated to rows
"""
if rows: self._col_widths.clear()
self._id_rows[:] = []
if imageIds: imageIds = self._ConvertImageIds(imageIds)
for r in rows:
item_id = self.counter()
self._id_rows += [(item_id, r)]
if imageIds: self._id_images[item_id] = imageIds
self.RefreshRows()
def AppendRow(self, data, imageIds=()):
"""
Appends the specified data to the control as a new row.
@param data item data dictionary
@param imageIds list of indexes for the images associated to this row
"""
self.InsertRow(self.GetItemCount(), data, imageIds)
def InsertRow(self, index, data, imageIds=()):
"""
Inserts the specified data to the control at specified index as a new row.
@param data item data dictionary
@param imageIds list of indexes for the images associated to this row
"""
item_id = self.counter()
if imageIds:
imageIds = self._id_images[item_id] = self._ConvertImageIds(imageIds)
index = min(index, self.GetItemCount())
if self._RowMatchesFilter(data):
columns = [c[0] for c in self._columns]
for i, col_name in enumerate(columns):
col_value = self._formatters[col_name](data, col_name)
if imageIds and not i: self.InsertImageStringItem(index, col_value, imageIds)
elif not i: self.InsertStringItem(index, col_value)
else: self.SetStringItem(index, i, col_value)
self.SetItemData(index, item_id)
self.itemDataMap[item_id] = [data[c] for c in columns]
self._data_map[item_id] = data
self.SetItemTextColour(index, self.ForegroundColour)
self.SetItemBackgroundColour(index, self.BackgroundColour)
self._id_rows.insert(index - (1 if self._top_row else 0), (item_id, data))
if self.GetSortState()[0] >= 0:
self.SortListItems(*self.GetSortState())
def GetFilter(self):
return self._filter
def SetFilter(self, value, force_refresh=False):
"""
Sets the text to filter list by. Any row not containing the text in any
column will be hidden.
@param force_refresh if True, all content is refreshed even if
filter value did not change
"""
if force_refresh or value != self._filter:
self._filter = value
if force_refresh: self._col_widths.clear()
if self._id_rows: self.RefreshRows()
def FindItem(self, text):
"""
Find an item whose primary label matches the text.
@return item index, or -1 if not found
"""
for i in range(self.GetItemCount()):
if self.GetItemText(i) == text: return i
return -1
def RefreshRows(self):
"""
Clears the list and inserts all unfiltered rows, auto-sizing the
columns.
"""
selected_ids, selected_idxs, selected = [], [], self.GetFirstSelected()
while selected >= 0:
selected_ids.append(self.GetItemData(selected))
selected_idxs.append(selected)
selected = self.GetNextSelected(selected)
self.Freeze()
try:
for i in selected_idxs:
self._mainWin.SendNotify(i, wx.wxEVT_COMMAND_LIST_ITEM_DESELECTED)
wx.lib.agw.ultimatelistctrl.UltimateListCtrl.DeleteAllItems(self)
self._PopulateTopRow()
self._PopulateRows(selected_ids)
finally: self.Thaw()
def RefreshRow(self, row):
"""Refreshes row with specified index from item data."""
if not self.GetItemCount(): return
if row < 0: row = row % self.GetItemCount()
data = not row and self._top_row or self._data_map.get(self.GetItemData(row))
if not data: return
for i, col_name in enumerate([c[0] for c in self._columns]):
col_value = self._formatters[col_name](data, col_name)
self.SetStringItem(row, i, col_value)
self.SetItemTextColour(row, self.ForegroundColour)
self.SetItemBackgroundColour(row, self.BackgroundColour)
def ResetColumnWidths(self):
"""Resets the stored column widths, triggering a fresh autolayout."""
self._col_widths.clear()
self.RefreshRows()
def DeleteItem(self, index):
"""Deletes the row at the specified index."""
item_id = self.GetItemData(index)
data = self._data_map.get(item_id)
del self._data_map[item_id]
self._id_rows.remove((item_id, data))
self._id_images.pop(item_id, None)
return wx.lib.agw.ultimatelistctrl.UltimateListCtrl.DeleteItem(self, index)
def DeleteAllItems(self):
"""Deletes all items data and clears the list."""
self.itemDataMap = {}
self._data_map = {}
self._id_rows = []
for item_id in self._id_images:
if item_id >= 0: self._id_images.pop(item_id)
self.Freeze()
try:
result = wx.lib.agw.ultimatelistctrl.UltimateListCtrl.DeleteAllItems(self)
self._PopulateTopRow()
finally: self.Thaw()
return result
def GetItemCountFull(self):
"""Returns the full row count, including items hidden by filter."""
return len(self._id_rows) + bool(self._top_row)
def GetItemTextFull(self, | |
<gh_stars>10-100
import base64
import datetime
import jsonschema
import os
import pymongo
import traceback
import webapp2
from .. import util
from .. import config
from ..types import Origin
from ..auth.authproviders import AuthProvider
from ..auth.apikeys import APIKey
from ..web import errors
from elasticsearch import ElasticsearchException
from ..dao.hierarchy import get_parent_tree
from ..web.request import log_access, AccessType
class RequestHandler(webapp2.RequestHandler):
json_schema = None
def __init__(self, request=None, response=None): # pylint: disable=super-init-not-called
"""Set uid, public_request, and superuser"""
self.initialize(request, response)
self.uid = None
self.origin = None
# If user is attempting to log in through `/login`, ignore Auth here:
# In future updates, move login and logout handlers to class that overrides this init
if self.request.path == '/api/login':
return
try:
# TODO: This should be taken out of base.RequestHandler so `handle_exception()`
# can properly catch exceptions raised by this logic as well as uninteded exceptions
# For now, wrap in a try/catch to prevent stack traces from getting to the client
# For more info see scitran/core #733
self.initialization_auth()
except Exception as e: # pylint: disable=broad-except
error = self.handle_exception(e, self.app.debug, return_json=True)
self.abort(error['status_code'], error['message'])
def initialize(self, request, response):
super(RequestHandler, self).initialize(request, response)
request.logger.debug("Initialized request")
def initialization_auth(self):
drone_request = False
job_context = None
session_token = self.request.headers.get('Authorization', None)
drone_secret = self.request.headers.get('X-SciTran-Auth', None)
drone_method = self.request.headers.get('X-SciTran-Method', None)
drone_name = self.request.headers.get('X-SciTran-Name', None)
if session_token:
if session_token.startswith('<PASSWORD> '):
# User (API key) authentication
key = session_token.split()[1]
api_key = APIKey.validate(key)
self.uid = api_key['uid']
if 'job' in api_key:
job_context = api_key['job']
elif session_token.startswith('sc<PASSWORD>-drone '):
# Drone (API key) authentication
# When supported, remove custom headers and shared secret
self.abort(401, 'Drone API keys are not yet supported')
else:
# User (oAuth) authentication
self.uid = self.authenticate_user_token(session_token)
# Drone shared secret authentication
elif drone_secret is not None:
if drone_method is None or drone_name is None:
self.abort(400, 'X-SciTran-Method or X-SciTran-Name header missing')
if config.get_item('core', 'drone_secret') is None:
self.abort(401, 'drone secret not configured')
if drone_secret != config.get_item('core', 'drone_secret'):
self.abort(401, 'invalid drone secret')
drone_request = True
self.public_request = not drone_request and not self.uid
if self.public_request:
self.superuser_request = False
self.user_is_admin = False
elif drone_request:
self.superuser_request = True
self.user_is_admin = True
else:
user = config.db.users.find_one({'_id': self.uid}, ['root', 'disabled'])
if not user:
self.abort(402, 'User {} will need to be added to the system before managing data.'.format(self.uid))
if user.get('disabled', False) is True:
self.abort(402, 'User {} is disabled.'.format(self.uid))
if user.get('root'):
self.user_is_admin = True
else:
self.user_is_admin = False
if self.is_true('root'):
if user.get('root'):
self.superuser_request = True
else:
self.abort(403, 'user ' + self.uid + ' is not authorized to make superuser requests')
else:
self.superuser_request = False
self.origin = None
self.set_origin(drone_request, job_context)
def authenticate_user_token(self, session_token):
"""
AuthN for user accounts. Calls self.abort on failure.
Returns the user's UID.
"""
uid = None
timestamp = datetime.datetime.utcnow()
cached_token = config.db.authtokens.find_one({'_id': session_token})
if cached_token:
# Check if site has inactivity timeout
try:
inactivity_timeout = config.get_item('site', 'inactivity_timeout')
except KeyError:
inactivity_timeout = None
if inactivity_timeout:
last_seen = cached_token.get('last_seen')
# If now - last_seen is greater than inactivity timeout, clear out session
if last_seen and (timestamp - last_seen).total_seconds() > inactivity_timeout:
# Token expired and no refresh token, remove and deny request
config.db.authtokens.delete_one({'_id': cached_token['_id']})
config.db.refreshtokens.delete({'uid': cached_token['uid'], 'auth_type': cached_token['auth_type']})
self.abort(401, 'Inactivity timeout')
# set last_seen to now
config.db.authtokens.update_one({'_id': cached_token['_id']}, {'$set': {'last_seen': timestamp}})
# Check if token is expired
if cached_token.get('expires') and timestamp > cached_token['expires']:
# look to see if the user has a stored refresh token:
unverified_uid = cached_token['uid']
auth_type = cached_token['auth_type']
refresh_token = config.db.refreshtokens.find_one({'uid': unverified_uid, 'auth_type': cached_token['auth_type']})
if refresh_token:
# Attempt to refresh the token, update db
try:
auth_provider = AuthProvider.factory(auth_type)
except NotImplementedError as e:
self.abort(401, str(e))
try:
updated_token_info = auth_provider.refresh_token(refresh_token['token'])
except errors.APIAuthProviderException as e:
# Remove the bad refresh token and session token:
config.db.refreshtokens.delete_one({'_id': refresh_token['_id']})
config.db.authtokens.delete_one({'_id': cached_token['_id']})
# TODO: Rework auth so it's not tied to init, then:
# - Raise a refresh token exception specifically in this situation
# - Alerts clients they may need to re-ask for `offline` permission
# Until then, the key `invalid_refresh_token` alerts the client
self.abort(401, 'invalid_refresh_token')
config.db.authtokens.update_one({'_id': cached_token['_id']}, {'$set': updated_token_info})
else:
# Token expired and no refresh token, remove and deny request
config.db.authtokens.delete_one({'_id': cached_token['_id']})
self.abort(401, 'invalid_refresh_token')
uid = cached_token['uid']
else:
self.abort(401, 'Invalid session token')
return uid
@log_access(AccessType.user_login)
def log_in(self):
"""
Return succcess boolean if user successfully authenticates.
Used for access logging.
Not required to use system as logged in user.
"""
payload = self.request.json_body
if 'code' not in payload or 'auth_type' not in payload:
self.abort(400, 'Auth code and type required for login')
auth_type = payload['auth_type']
try:
auth_provider = AuthProvider.factory(auth_type)
except NotImplementedError as e:
self.abort(400, str(e))
registration_code = payload.get('registration_code')
token_entry = auth_provider.validate_code(payload['code'], registration_code=registration_code)
timestamp = datetime.datetime.utcnow()
self.uid = token_entry['uid']
# If this is the first time they've logged in, record that
config.db.users.update_one({'_id': self.uid, 'firstlogin': None}, {'$set': {'firstlogin': timestamp}})
# Unconditionally set their most recent login time
config.db.users.update_one({'_id': self.uid}, {'$set': {'lastlogin': timestamp}})
session_token = base64.urlsafe_b64encode(os.urandom(42))
token_entry['_id'] = session_token
token_entry['timestamp'] = timestamp
config.db.authtokens.insert_one(token_entry)
# Set origin now that the uid is known
self.set_origin(False, None)
return {'token': session_token}
@log_access(AccessType.user_logout)
def log_out(self):
"""
Remove all cached auth tokens associated with caller's uid.
"""
token = self.request.headers.get('Authorization', None)
if not token:
self.abort(401, 'User not logged in.')
result = config.db.authtokens.delete_one({'_id': token})
return {'tokens_removed': result.deleted_count}
def set_origin(self, drone_request, job_context):
"""
Add an origin to the request object. Used later in request handler logic.
Pretty clear duplication of logic with superuser_request / drone_request;
this map serves a different purpose, and specifically matches the desired file-origin map.
Might be a good future project to remove one or the other.
"""
if self.uid is not None:
self.origin = {
'type': str(Origin.user),
'id': self.uid
}
if job_context:
self.origin['via'] = {
'type': str(Origin.job),
'id': job_context
}
elif drone_request:
method = self.request.headers.get('X-SciTran-Method')
name = self.request.headers.get('X-SciTran-Name')
self.origin = {
'id': (method + '_' + name).replace(' ', '_'),
'type': str(Origin.device),
'method': method,
'name': name
}
# Upsert device record, with last-contacted time.
# In the future, consider merging any keys into self.origin?
config.db['devices'].find_one_and_update({
'_id': self.origin['id']
}, {
'$set': {
'_id': self.origin['id'],
'last_seen': datetime.datetime.utcnow(),
'method': self.origin['method'],
'name': self.origin['name'],
'errors': [] # Reset errors list if device checks in
}
},
upsert=True,
return_document=pymongo.collection.ReturnDocument.AFTER
)
# Bit hackish - detect from route if a job is the origin, and if so what job ID.
# Could be removed if routes get reorganized. POST /api/jobs/id/result, maybe?
is_job_upload = self.request.path.startswith('/api/engine')
job_id = self.request.GET.get('job')
# This runs after the standard drone-request upsert above so that we can still update the last-seen timestamp.
if is_job_upload and job_id is not None:
self.origin = {
'type': str(Origin.job),
'id': job_id
}
else:
self.origin = {
'type': str(Origin.unknown),
'id': None
}
def is_true(self, param):
return self.request.GET.get(param, '').lower() in ('1', 'true')
def get_param(self, param, default=None):
return self.request.GET.get(param, default)
def handle_exception(self, exception, debug, return_json=False): # pylint: disable=arguments-differ
"""
Send JSON response for exception
For HTTP and other known exceptions, use its error code
For all others use a generic 500 error code and log the stack trace
"""
request_id = self.request.id
custom_errors = None
message = str(exception)
if isinstance(exception, webapp2.HTTPException):
code = exception.code
elif isinstance(exception, errors.InputValidationException):
code = 400
elif isinstance(exception, errors.APIAuthProviderException):
code = 401
elif isinstance(exception, errors.APIRefreshTokenException):
code = 401
custom_errors = exception.errors
elif isinstance(exception, errors.APIUnknownUserException):
code = 402
elif isinstance(exception, errors.APIConsistencyException):
code = 400
elif isinstance(exception, errors.APIPermissionException):
custom_errors = exception.errors
code = 403
elif isinstance(exception, errors.APINotFoundException):
code = 404
elif isinstance(exception, errors.APIConflictException):
code = 409
elif isinstance(exception, errors.APIValidationException):
code = 422
custom_errors = exception.errors
elif isinstance(exception, errors.FileStoreException):
code = 400
elif isinstance(exception, errors.FileFormException):
code = 400
elif isinstance(exception, errors.FileFormException):
code = 400
elif isinstance(exception, ElasticsearchException):
code = 503
message = "Search is currently down. Try again later."
self.request.logger.error(traceback.format_exc())
elif isinstance(exception, KeyError):
code = 500
message = "Key {} was not found".format(str(exception))
else:
code = 500
if code == 500:
tb = traceback.format_exc()
self.request.logger.error(tb)
if return_json:
return util.create_json_http_exception_response(message, code, request_id, custom=custom_errors)
util.send_json_http_exception(self.response, message, code, request_id, custom=custom_errors)
def log_user_access(self, access_type, cont_name=None, cont_id=None, filename=None, multifile=False, origin_override=None):
if not config.get_item('core', 'access_log_enabled'):
return
if not isinstance(access_type, AccessType):
raise Exception('Unknown access type.')
log_map = {
'access_type': access_type.value,
'request_method': self.request.method,
'request_path': self.request.path,
'origin': origin_override if origin_override is not None else self.origin,
'timestamp': datetime.datetime.utcnow()
}
| |
<filename>xcs_soxs/spectra.py
from __future__ import division
import numpy as np
import subprocess
import tempfile
import shutil
import os
from xcs_soxs.utils import soxs_files_path, mylog, \
parse_prng, parse_value, soxs_cfg, line_width_equiv, \
DummyPbar
from xcs_soxs.lib.broaden_lines import broaden_lines
from xcs_soxs.constants import erg_per_keV, hc, \
cosmic_elem, metal_elem, atomic_weights, clight, \
m_u, elem_names, sigma_to_fwhm, abund_tables, sqrt2pi
import astropy.io.fits as pyfits
import astropy.units as u
import h5py
from scipy.interpolate import InterpolatedUnivariateSpline
from xcs_soxs.instrument import AuxiliaryResponseFile
from six import string_types
from astropy.modeling.functional_models import \
Gaussian1D
import glob
from tqdm import tqdm
class Energies(u.Quantity):
def __new__(cls, energy, flux):
ret = u.Quantity.__new__(cls, energy, unit="keV")
ret.flux = u.Quantity(flux, "erg/(cm**2*s)")
return ret
def _generate_energies(spec, t_exp, rate, prng, quiet=False):
cumspec = spec.cumspec
n_ph = prng.poisson(t_exp*rate)
if not quiet:
mylog.info("Creating %d energies from this spectrum." % n_ph)
randvec = prng.uniform(size=n_ph)
randvec.sort()
e = np.interp(randvec, cumspec, spec.ebins.value)
if not quiet:
mylog.info("Finished creating energies.")
return e
class Spectrum(object):
_units = "photon/(cm**2*s*keV)"
def __init__(self, ebins, flux):
self.ebins = u.Quantity(ebins, "keV")
self.emid = 0.5*(self.ebins[1:]+self.ebins[:-1])
self.flux = u.Quantity(flux, self._units)
self.nbins = len(self.emid)
self.de = self.ebins[1]-self.ebins[0]
self._compute_total_flux()
def _compute_total_flux(self):
self.total_flux = self.flux.sum()*self.de
self.total_energy_flux = (self.flux*self.emid.to("erg")).sum()*self.de/(1.0*u.photon)
cumspec = np.cumsum(self.flux.value*self.de.value)
cumspec = np.insert(cumspec, 0, 0.0)
cumspec /= cumspec[-1]
self.cumspec = cumspec
self.func = lambda e: np.interp(e, self.emid.value, self.flux.value)
def __add__(self, other):
if self.nbins != other.nbins or \
not np.isclose(self.ebins.value, other.ebins.value).all():
raise RuntimeError("Energy binning for these two "
"spectra is not the same!!")
if self._units != other._units:
raise RuntimeError("The units for these two spectra "
"are not the same!")
return Spectrum(self.ebins, self.flux+other.flux)
def __mul__(self, other):
if isinstance(other, AuxiliaryResponseFile):
return ConvolvedSpectrum(self, other)
else:
return Spectrum(self.ebins, other*self.flux)
__rmul__ = __mul__
def __truediv__(self, other):
return Spectrum(self.ebins, self.flux/other)
__div__ = __truediv__
def __repr__(self):
s = "Spectrum (%s - %s)\n" % (self.ebins[0], self.ebins[-1])
s += " Total Flux:\n %s\n %s\n" % (self.total_flux, self.total_energy_flux)
return s
def __call__(self, e):
if hasattr(e, "to_astropy"):
e = e.to_astropy()
if isinstance(e, u.Quantity):
e = e.to("keV").value
return u.Quantity(self.func(e), self._units)
def get_flux_in_band(self, emin, emax):
"""
Determine the total flux within a band specified
by an energy range.
Parameters
----------
emin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The minimum energy in the band, in keV.
emax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The maximum energy in the band, in keV.
Returns
-------
A tuple of values for the flux/intensity in the
band: the first value is in terms of the photon
rate, the second value is in terms of the energy rate.
"""
emin = parse_value(emin, "keV")
emax = parse_value(emax, "keV")
range = np.logical_and(self.emid.value >= emin, self.emid.value <= emax)
pflux = self.flux[range].sum()*self.de
eflux = (self.flux*self.emid.to("erg"))[range].sum()*self.de/(1.0*u.photon)
return pflux, eflux
@classmethod
def from_xspec_script(cls, infile, emin, emax, nbins):
"""
Create a model spectrum using a script file as
input to XSPEC.
Parameters
----------
infile : string
Path to the script file to use.
emin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The minimum energy of the spectrum in keV.
emax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The maximum energy of the spectrum in keV.
nbins : integer
The number of bins in the spectrum.
"""
f = open(infile, "r")
xspec_in = f.readlines()
f.close()
return cls._from_xspec(xspec_in, emin, emax, nbins)
@classmethod
def from_xspec_model(cls, model_string, params, emin, emax, nbins):
"""
Create a model spectrum using a model string and parameters
as input to XSPEC.
Parameters
----------
model_string : string
The model to create the spectrum from. Use standard XSPEC
model syntax. Example: "wabs*mekal"
params : list
The list of parameters for the model. Must be in the order
that XSPEC expects.
emin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The minimum energy of the spectrum in keV
emax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The maximum energy of the spectrum in keV
nbins : integer
The number of bins in the spectrum.
"""
xspec_in = []
model_str = "%s &" % model_string
for param in params:
model_str += " %g &" % param
model_str += " /*"
xspec_in.append("model %s\n" % model_str)
return cls._from_xspec(xspec_in, emin, emax, nbins)
@classmethod
def from_xspec(cls, model_string, params, emin, emax, nbins):
mylog.warning("The 'from_xspec' method has been deprecated: "
"use 'from_xspec_model' instead.")
cls.from_xspec_model(model_string, params, emin, emax, nbins)
@classmethod
def _from_xspec(cls, xspec_in, emin, emax, nbins):
emin = parse_value(emin, "keV")
emax = parse_value(emax, "keV")
tmpdir = tempfile.mkdtemp()
curdir = os.getcwd()
os.chdir(tmpdir)
xspec_in.append("dummyrsp %g %g %d lin\n" % (emin, emax, nbins))
xspec_in += ["set fp [open spec_therm.xspec w+]\n",
"tclout energies\n", "puts $fp $xspec_tclout\n",
"tclout modval\n", "puts $fp $xspec_tclout\n",
"close $fp\n", "quit\n"]
f_xin = open("xspec.in", "w")
f_xin.writelines(xspec_in)
f_xin.close()
logfile = os.path.join(curdir, "xspec.log")
with open(logfile, "ab") as xsout:
subprocess.call(["xspec", "-", "xspec.in"],
stdout=xsout, stderr=xsout)
f_s = open("spec_therm.xspec", "r")
lines = f_s.readlines()
f_s.close()
ebins = np.array(lines[0].split()).astype("float64")
de = np.diff(ebins)[0]
flux = np.array(lines[1].split()).astype("float64")/de
os.chdir(curdir)
shutil.rmtree(tmpdir)
return cls(ebins, flux)
@classmethod
def from_powerlaw(cls, photon_index, redshift, norm, emin, emax,
nbins):
"""
Create a spectrum from a power-law model.
Parameters
----------
photon_index : float
The photon index of the source.
redshift : float
The redshift of the source.
norm : float
The normalization of the source in units of
photons/s/cm**2/keV at 1 keV in the source
frame.
emin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The minimum energy of the spectrum in keV.
emax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The maximum energy of the spectrum in keV.
nbins : integer
The number of bins in the spectrum.
"""
emin = parse_value(emin, 'keV')
emax = parse_value(emax, 'keV')
ebins = np.linspace(emin, emax, nbins+1)
emid = 0.5*(ebins[1:]+ebins[:-1])
flux = norm*(emid*(1.0+redshift))**(-photon_index)
return cls(ebins, flux)
@classmethod
def from_file(cls, filename):
"""
Read a spectrum from an ASCII or HDF5 file.
If ASCII: accepts a file with two columns,
the first being the center energy of the bin in
keV and the second being the spectrum in the
appropriate units, assuming a linear binning
with constant bin widths.
If HDF5: accepts a file with one array dataset,
named "spectrum", which is the spectrum in the
appropriate units, and two scalar datasets,
"emin" and "emax", which are the minimum and
maximum energies in keV.
Parameters
----------
filename : string
The path to the file containing the spectrum.
"""
if filename.endswith(".h5"):
f = h5py.File(filename, "r")
flux = f["spectrum"][()]
nbins = flux.size
ebins = np.linspace(f["emin"][()], f["emax"][()], nbins+1)
f.close()
else:
emid, flux = np.loadtxt(filename, unpack=True)
de = np.diff(emid)[0]
ebins = np.append(emid-0.5*de, emid[-1]+0.5*de)
return cls(ebins, flux)
@classmethod
def from_constant(cls, const_flux, emin, emax, nbins):
"""
Create a spectrum from a constant model using
XSPEC.
Parameters
----------
const_flux : float
The value of the constant flux in the units
of the spectrum.
emin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The minimum energy of the spectrum in keV.
emax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The maximum energy of the spectrum in keV.
nbins : integer
The number of bins in the spectrum.
"""
emin = parse_value(emin, "keV")
emax = parse_value(emax, 'keV')
ebins = np.linspace(emin, emax, nbins+1)
flux = const_flux*np.ones(nbins)
return cls(ebins, flux)
def new_spec_from_band(self, emin, emax):
"""
Create a new :class:`~xcs_soxs.spectra.Spectrum` object
from a subset of an existing one defined by a particular
energy band.
Parameters
----------
emin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The minimum energy of the band in keV.
emax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The maximum energy of the band in keV.
"""
emin = parse_value(emin, "keV")
emax = parse_value(emax, 'keV')
band = np.logical_and(self.ebins.value >= emin,
self.ebins.value <= emax)
idxs = np.where(band)[0]
ebins = self.ebins.value[idxs]
flux = self.flux.value[idxs[:-1]]
return Spectrum(ebins, flux)
def rescale_flux(self, new_flux, emin=None, emax=None, flux_type="photons"):
"""
Rescale the flux of the spectrum, optionally using
a specific energy band.
Parameters
----------
new_flux : float
The new flux in units of photons/s/cm**2.
emin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional
The minimum energy of the band to consider,
in keV. Default: Use the minimum energy of
the entire spectrum.
emax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional
The maximum energy of the band to consider,
in keV. Default: Use the maximum energy | |
configuration of the "
f"reader {get_full_module_name(reader)} cannot be serialized "
"in JSON. To resolve this issue, you can consider implementing"
" a JSON serialization for that parameter type or changing the"
" parameters of this reader. Note that in order for the reader"
" to be serialized in JSON, all the variables defined in both "
"the default_configs and the configuration passed in during "
"pipeline.set_reader() need to be JSON-serializable. You can "
"find in the stack trace the type of the un-serializable "
"parameter."
),
"component": lambda component: (
"One component of the pipeline cannot be JSON serialized. This"
" is likely due to some parameters in the configuration of the"
f" component {get_full_module_name(component)} cannot be "
"serialized in JSON. To resolve this issue, you can consider "
"implementing a JSON serialization for that parameter type or "
"changing the parameters of the component. Note that in order "
"for the component to be serialized in JSON, all the variables"
" defined in both the default_configs and the configuration "
"passed in during pipeline.add() need to be JSON-serializable."
" You can find in the stack trace the type of the "
"un-serializable parameter."
),
"selector": lambda selector: (
"A selector cannot be JSON serialized. This is likely due to "
"some __init__ parameters for class "
f"{get_full_module_name(selector)} cannot be serialized in "
"JSON. To resolve this issue, you can consider implementing a "
"JSON serialization for that parameter type or changing the "
"signature of the __init__ function. You can find in the stack"
" trace the type of the un-serializable parameter."
),
}
configs: Dict = {
"forte_ir_version": FORTE_IR_VERSION,
"components": [],
"states": {},
}
# Serialize pipeline components
configs["components"].append(
{
"type": get_full_module_name(self._reader),
"configs": test_jsonable(
test_dict=self._reader_config.todict(),
err_msg=get_err_msg["reader"](self._reader),
),
}
)
for component, config, selector, selector_config in zip(
self.components,
self.component_configs,
self._selectors,
self._selectors_configs,
):
configs["components"].append(
{
"type": get_full_module_name(component),
"configs": test_jsonable(
test_dict=config.todict(),
err_msg=get_err_msg["component"](component),
),
"selector": {
"type": get_full_module_name(selector),
"configs": test_jsonable(
# pylint: disable=protected-access
test_dict=selector_config.todict(),
# pylint: enable=protected-access
err_msg=get_err_msg["selector"](selector),
),
},
}
)
# Serialize current states of pipeline
configs["states"].update(
{
"attribute": {
attr: getattr(self, attr)
for attr in (
"_initialized",
"_enable_profiling",
"_check_type_consistency",
"_do_init_type_check",
)
if hasattr(self, attr)
},
"resource": {},
}
)
if self.resource.contains("onto_specs_dict"):
configs["states"]["resource"].update(
{"onto_specs_dict": self.resource.get("onto_specs_dict")}
)
if self.resource.contains("merged_entry_tree"):
configs["states"]["resource"].update(
{
"merged_entry_tree": self.resource.get(
"merged_entry_tree"
).todict()
}
)
return configs
def save(self, path: str):
r"""Store the pipeline as an IR(intermediate representation) in yaml.
The path can then be passed to ``init_from_config_path`` to initialize
a pipeline. Note that calling ``init_from_config`` from a different
python environment may not work for some self defined component classes
because their module name is `__main__`.
Args:
path: The file path to save configurations.
"""
with open(path, "w", encoding="utf-8") as f:
yaml.safe_dump(self._dump_to_config(), f)
def _remote_service_app(
self, service_name: str = "", input_format: str = "string"
):
r"""Return a FastAPI app that can be used to serve the pipeline.
Args:
service_name: Assign a name to the pipeline service for validation.
This will appear in the `service_name` field on default page
and can be queried and validated against the expected service
name set by user. Default to `''`.
input_format: Specify format of the input for validation. It can be
`"string"` or `"DataPack"`. This will appear in the
`input_format` field on default page and can be queried and
validated against the expected input format set by user.
Default to `"string"`.
Returns:
FastAPI: A FastAPI app for remote service.
"""
# TODO: Currently we only support the `process` function, but it can
# be extended by adding new interfaces that wrap up any Pipeline
# method. Refer to https://fastapi.tiangolo.com for more info.
app = FastAPI()
records: Optional[Dict[str, Set[str]]] = None
class RequestBody(BaseModel):
args: str = "[]"
kwargs: str = "{}"
# pylint: disable=unused-variable
@app.get("/")
def default_page():
return {
"status": "OK",
"service_name": service_name,
"input_format": input_format,
"pipeline": self._dump_to_config(),
}
@app.get("/records")
def get_records():
nonlocal records
if records is None:
# Collect records of each pipeline component for validation
records = {}
for component in [self._reader] + self.components:
component.record(records)
return {"status": "OK", "records": records}
@app.get("/expectation")
def get_expectation():
expectation: Dict[str, Set[str]] = {}
if len(self.components) > 0:
expectation = self.components[0].expected_types_and_attributes()
return {"status": "OK", "expectation": expectation}
@app.post("/process")
def run_pipeline(body: RequestBody):
args = json.loads(body.args)
kwargs = json.loads(body.kwargs)
result = self.process(*args, **kwargs)
return {"status": "OK", "result": result.to_string()}
# pylint: enable=unused-variable
return app
def serve(
self,
host: str = "localhost",
port: int = 8008,
service_name: str = "",
input_format: str = "string",
):
r"""Start a service of the current pipeline at a specified host
and port.
Args:
host: Port number of pipeline service.
port: Host name of pipeline service.
service_name: Assign a name to the pipeline service for validation.
This will appear in the `service_name` field on default page
and can be queried and validated against the expected service
name set by user. Default to `''`.
input_format: Specify format of the input for validation. It can be
`"string"` or `"DataPack"`. This will appear in the
`input_format` field on default page and can be queried and
validated against the expected input format set by user.
Default to `"string"`.
"""
self.initialize()
uvicorn.run(
self._remote_service_app(
service_name=service_name, input_format=input_format
),
host=host,
port=port,
log_level="info",
)
def set_profiling(self, enable_profiling: bool = True):
r"""Set profiling option.
Args:
enable_profiling: A boolean of whether to enable profiling
for the pipeline or not (the default is True).
"""
self._enable_profiling = enable_profiling
def initialize(self) -> "Pipeline":
"""
This function should be called before the pipeline can be used to
process the actual data. This function will call the `initialize` of
all the components inside this pipeline.
Returns:
"""
# create EntryTree type object merged_entry_tree to store the parsed
# entry tree from ontology specification file passed in as part of
# resource and add the result to resource with key of merged_entry_tree.
merged_entry_tree = EntryTree()
if self.resource.get("onto_specs_path"):
OntologyCodeGenerator().parse_schema_for_no_import_onto_specs_file(
ontology_path=self.resource.get("onto_specs_path"),
ontology_dict=self.resource.get("onto_specs_dict"),
merged_entry_tree=merged_entry_tree,
)
self.resource.update(merged_entry_tree=merged_entry_tree)
# The process manager need to be assigned first.
self._proc_mgr = ProcessManager(len(self._components))
if self._initialized:
# The pipeline has already been initialized, so we are doing
# re-initialization here.
logging.info("Re-initializing the Pipeline.")
# Reset the flags of the components before initializing them.
self._reader.reset_flags()
for c in self._components:
c.reset_flags()
# Handle the reader.
if not self._reader.is_initialized:
self._reader.initialize(self.resource, self._reader_config)
else:
logging.info(
"The reader [%s] has already initialized, "
"will skip its initialization.",
self._reader.name,
)
if self._check_type_consistency:
self.reader.enforce_consistency(enforce=True)
else:
self.reader.enforce_consistency(enforce=False)
# Handle other components and their selectors.
self.initialize_components()
self.initialize_selectors()
self._initialized = True
# Create profiler
if self._enable_profiling:
self.reader.set_profiling(True)
self._profiler = [0.0] * len(self.components)
# Check record types and attributes of each pipeline component
if self._do_init_type_check:
current_records: Dict[str, Set[str]] = {}
self._reader.record(current_records)
for component in self.components:
if hasattr(component, "expected_types_and_attributes"):
record_types_and_attributes_check(
component.expected_types_and_attributes(), # type: ignore
current_records,
)
if hasattr(component, "record"):
component.record(current_records) # type: ignore
return self
def initialize_components(self):
"""
This function will initialize all the components in this pipeline,
except the reader. The components are initialized in a FIFO manner
based on the order of insertion,
During initialization, the component will be configured based on its
corresponding configuration. However, if the component is already
initialized (for example, being initialized manually or used twice
in the same pipeline), the new configuration will be ignored.
The pipeline will check for type dependencies between the components
inside this pipeline, see
:func:`~forte.pipeline_component.PipelineComponent.enforce_consistency`
for more details.
"""
for component, config in zip(self.components, self.component_configs):
try:
if not component.is_initialized:
component.initialize(self.resource, config)
else:
logging.info(
"The component [%s] has already initialized, "
"will skip its initialization.",
component.name,
)
except ProcessorConfigError as e:
logging.error(
"Exception occur when initializing " "processor %s",
component.name,
)
raise e
component.enforce_consistency(enforce=self._check_type_consistency)
def initialize_selectors(self):
"""
This function will reset the states of selectors
"""
for selector, config in zip(self._selectors, self._selectors_configs):
try:
selector.initialize(config)
except ValueError as e:
logging.error("Exception occur when initializing selectors")
raise e
def set_reader(
self,
reader: BaseReader,
config: Optional[Union[Config, Dict[str, Any]]] = None,
) -> "Pipeline":
"""
Set the reader of the pipeline. A reader is the entry point of
this pipeline, data flown | |
dbgDict = self.calcRewardAndCheckDone(debug)
#observation of current state
obs = self.getObs()
if (self.checkBestState) and (rwd > self.bestStRwd):
self.bestStRwd = rwd
self.bestState = self.state_vector()
#ob, reward, done, infoDict
return obs, rwd, done, d, dbgDict
#calculate the distance between the COm projected onto the level of the COP and the COP itself
#if no COP val passed, derive current COP val
def calcCOMCOPDist(self, COM, COPVal):
COMatCOPHt = np.copy(COM)
COMatCOPHt[1] = COPVal[1]
#distance is just x/z
distCOMCop = np.linalg.norm(COMatCOPHt - COPVal)
#distance between COM projected to plane of foot and COP - want to be small
return distCOMCop
#return skeleton qdot - maybe clipped, maybe not
def getSkelqDot(self):
return np.clip(self.skel.dq, -self.qDotBnd , self.qDotBnd )
#base check goal functionality - this should be same for all agents,
#access by super()
def checkSimIsBroken(self):
s = self.state_vector()
if not(self.isFrwrdSim):#if not frwrd simed then sim won't be broken
return False, s, 'FINE'
if not (np.isfinite(s).all()):
return True, s, 'INFINITE'
if not ((np.abs(s[2:]) < 1000).all()):
return True, s, 'EXPLODE'
return False, s, 'FINE'
def checkBNinNameList(self, name, nameList):
return any(name in bodyNodeName for bodyNodeName in nameList)
#check if passed body nodes are on two different, non-ground, skeletons - return true
#don't want this - skeletons should not contact each other except through the ball joint constraint
def checkBNKickOtr(self, bn1, bn2):
if ('ground' in bn1.name) or ('ground' in bn2.name):
return False
#if not touching ground, then this is bad contact between robot and ANA - need to check if eef contact, which is good
#if != then they are different skeletons contacting each other
return (bn1.skel.name != bn2.skel.name)
#returns dictionary of per-body node contact info objects
def getMyContactInfo(self):
allCntctInfo = self.env.getContactInfo()
return allCntctInfo[self.skel.name]
#returns true only if one body node is a foot on this skeleton and the other is the ground in a contact
#also returns body node that is responsible for contact (not ground) whether foot or not
def checkMyFootWithGround(self, bn1, bn2):
if ('ground' in bn1.name) :
return (self.checkBNinNameList(bn2.name, self.feetBodyNames) and (self.skel.name == bn2.skel.name)), bn2
elif ('ground' in bn2.name) :
return (self.checkBNinNameList(bn1.name, self.feetBodyNames) and (self.skel.name == bn1.skel.name)), bn1
return False, None
#calculate average foot body locations based on COM
def calcAvgFootBodyLoc(self):
avgFootLoc = np.zeros(3)
avgLFootLoc = np.zeros(3)
avgRtFootLoc = np.zeros(3)
if(len(self.feetBodyNames) >0):
for ftBdyName in self.leftFootBodyNames:
footLoc = self.skel.body(ftBdyName).com()
avgFootLoc += footLoc
avgLFootLoc += footLoc
avgLFootLoc /= len(self.leftFootBodyNames)
for ftBdyName in self.rightFootBodyNames:
footLoc = self.skel.body(ftBdyName).com()
avgFootLoc += footLoc
avgRtFootLoc += footLoc
avgLFootLoc /= len(self.rightFootBodyNames)
#for each body considered part of a "foot"
# for ftBdyName in self.feetBodyNames:
# avgFootLoc += self.skel.body(ftBdyName).com()
avgFootLoc /= len(self.feetBodyNames)
else :
print('skelHolder::calcAvgFootBodyLoc : No feet for skelholder {} defined in self.feetBodyNames so avg loc is origin'.format(self.name))
return [avgFootLoc, avgLFootLoc, avgRtFootLoc]
#calculate contact's contribution to total contact torques around distant point for COP derivation
#cntctBN : the body node in contact with the ground
#contact : the contact object
def calcSumTrqsForCOP(self, cntctBN, contact):
trqPt = contact.point - self.env.ctrTauPt
# if(contact.point[1] != 0):
# print('!!!!!!!!!!!!!!!!!!!!!! non zero ground contact y : {}'.format(contact.point))
new_COP_tau = np.cross(trqPt, contact.force)
new_COP_ttlFrc = contact.force
return new_COP_tau,new_COP_ttlFrc
#calculate foot contact count and other terms if we want to use them for reward calc
def calcAllContactData(self):
contacts = self.env.dart_world.collision_result.contacts
contactDict = defaultdict(float)
COPval = np.zeros(3)
COP_tau = np.zeros(3)
COP_ttlFrc = np.zeros(3)
#tau = loc x frc
#COP calculation is the location that, when crossed with total force, will give total moment
#we can calculate total moment by crossing all contact forces with all contact locations
#we can get total force, and from this we can find the location that would produce the total
#torque given the total force (by first constraining one of the dimensions of the point in question)
#we choose to constrain the y coordinate to be 0 since we want the cop on the ground
for contact in contacts:
if (self.skel.name != contact.bodynode1.skeleton.name ) and (self.skel.name != contact.bodynode2.skeleton.name ) :
#contact not from this skeleton
continue
#penalize contact between the two skeletons - getup-human should not touch assistant bot except with assisting hand
#only true if one skel contacts other and the other is not the ground - i.e. non-ground non-self contact
if self.checkBNKickOtr(contact.bodynode1, contact.bodynode2):
contactDict['kickBotContacts'] +=1
#only true if feet are contacting skeleton - kicking self - i.e. non-ground self contact
elif (contact.bodynode1.skel.name == contact.bodynode2.skel.name):
contactDict['selfContact'] +=1
else:
#this is a contact between this skeleton with the ground
#cntctBN is skeleton body node responsible for ground contact, or none if no ground contact
isGndCntctWFoot, cntctBN = self.checkMyFootWithGround(contact.bodynode1,contact.bodynode2)
#save refs to each contact force and which body had contact with ground
contactDict[cntctBN.name] +=1
if isGndCntctWFoot: #save for COP calc
#foot contact with ground
contactDict['COPcontacts'] += 1
contactDict['footGroundContacts'] +=1
#print('With Ground : contact body 1 : {} skel : {} | contact body 2 : {} skel : {} : frc {}'.format(contact.bodynode1,contact.bodynode1.skeleton.name, contact.bodynode2,contact.bodynode2.skeleton.name, contact.force))
#COP shouldnt use butt contact in calculation - want a target to get up
#find total moment of all contacts
cTau, cTtlFrc = self.calcSumTrqsForCOP(cntctBN, contact)
COP_tau += cTau
COP_ttlFrc += cTtlFrc
elif(self.checkBNinNameList(cntctBN.name, self.handBodyNames)):
#hand contact with ground
contactDict['COPcontacts'] += 1
contactDict['handGroundContacts']+=1
#non-foot contact with ground - check if contact with non-reaching hand
#print('Not Foot With Ground : contact body 1 : {} skel : {} | contact body 2 : {} skel : {}'.format(contact.bodynode1,contact.bodynode1.skeleton.name, contact.bodynode2,contact.bodynode2.skeleton.name))
#find total moment of all contacts of hand to ground
cTau, cTtlFrc = self.calcSumTrqsForCOP(cntctBN, contact)
COP_tau += cTau
COP_ttlFrc += cTtlFrc
else :
#nonHand nonFoot Contact with ground
contactDict['badGroundContact']+=1
#find average foot location (idx 0)
avgFootLocAra = self.calcAvgFootBodyLoc()
#determines COP based on foot contacts with ground - ignore non-foot contacts for COP calc
#COP loc might be redundant - using foot location might be sufficient
if((0 < contactDict['COPcontacts']) and (np.abs(COP_ttlFrc[1]) > 0)):#(COP_ttlFrc[1] > 0) and (COP_ttlFrc[0] > 0)):
#COP_tau = COPval cross COP_ttlFrc ==> need to constrain possible COPvals -> set COPval.y == 0 since we want the COP at the ground, and then solve eqs :
COPval = self.calcCOPFromTauFrc(COP_tau, COP_ttlFrc, self.env.ctrTauPt)
else : #estimate COP as center of both feet body node com locations
COPval = np.copy(avgFootLocAra[0])
#put it on the ground
COPval[1]= 0
return contactDict, COPval, avgFootLocAra
#Take total moments, total force, return a suitable point of application of that force to provide that moment - more than 1 answer, want answer on ground plane
#COP_tau = COPval cross COP_ttlFrc ==> need to constrain possible COPvals
#so set COPval.y == 0 since we want the COP at the ground, and then solve eqs :
#ctrTauPt is point far away around which torques are initially calculated, then summed, and then reversed to find COP loc
#ctrTauPt[1] should be 0, since can be chosen arbitrarily
def calcCOPFromTauFrc(self,COP_tau, COP_ttlFrc, ctrTauPt):
#given a cross b (==c : total tau) and b (total force), find a (location vector) : a = (bxc)/(b.b) + tb, where t is any real scalar
COPvalTmp = np.cross(COP_ttlFrc,COP_tau)/np.dot(COP_ttlFrc,COP_ttlFrc)#soln for t==0
#solve for t by finding frc[1]*t - COPval[1]=0 since we want COP val to lie on y=0 plane
try:
t = -float(COPvalTmp[1])/COP_ttlFrc[1]
COPval = COPvalTmp + t*COP_ttlFrc
#print('Cop Val : {} from COPvalTmp {} W/(t = {}) + ctrTauPt == {}'.format(COPval, COPvalTmp,t,(COPval+ctrTauPt)))
except ZeroDivisionError:
#should never hit this -> COP ttl force in y dir is not allowed to be 0 to call this - if it is then we use avg loc of feet as COP
#print('Cop Val w/ttlFrc[1] == 0 : {} + ctrTauPt : {} '.format(COPvalTmp,ctrTauPt))
COPval = COPvalTmp
#displacing COPval by ctrTauPt
COPval += ctrTauPt
return COPval
# def calcCOPFromTauFrc(self,COP_tau, COP_ttlFrc, ctrTauPt):
# COPval = np.zeros(3)
# COPval[0] = COP_tau[2]/COP_ttlFrc[1] + ctrTauPt[0]
# COPval[2] = COP_tau[1]/COP_ttlFrc[0] + (COP_ttlFrc[2] * COPval[0]/COP_ttlFrc[0]) + ctrTauPt[2]
# return | |
<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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.
#
# @@license_version:1.7@@
import base64
import json
import logging
import threading
import time
import traceback
import types
import uuid
from copy import deepcopy
from random import choice
from types import NoneType
from concurrent import futures # @UnresolvedImport
from google.appengine.api import urlfetch, memcache
from google.appengine.api.apiproxy_stub_map import UserRPC
from google.appengine.api.app_identity.app_identity import get_application_id
from google.appengine.api.taskqueue import TaskRetryOptions
from google.appengine.ext import db, deferred
from hyper import HTTP20Connection
from jose import jwt
from jose.constants import Algorithms
from mcfw.cache import set_cache_key
from mcfw.consts import MISSING
from mcfw.properties import azzert
from mcfw.rpc import arguments, returns, check_function_metadata, get_parameter_types, run, get_parameters, \
get_type_details, serialize_value, parse_parameter
from rogerthat.consts import DEBUG, HIGH_LOAD_WORKER_QUEUE, FAST_QUEUE
from rogerthat.dal.app import get_app_by_id
from rogerthat.dal.mobile import get_mobile_settings_cached
from rogerthat.dal.rpc_call import get_rpc_capi_backlog_parent_by_account, get_rpc_capi_backlog_parent_by_mobile
from rogerthat.models import UserProfile
from rogerthat.rpc import users
from rogerthat.rpc.models import Mobile, RpcAPIResult, RpcCAPICall, OutStandingFirebaseKick, \
ServiceAPICallback, RpcException
from rogerthat.settings import get_server_settings
from rogerthat.to.push import PushData
from rogerthat.to.system import LogErrorRequestTO
from rogerthat.utils import now, privatize
from rogerthat.utils.cloud_tasks import create_task, schedule_tasks
from rogerthat.utils.crypto import encrypt_for_jabber_cloud, decrypt_from_jabber_cloud
from rogerthat.utils.transactions import on_trans_committed
_CALL_ACTION_RESEND = 1
_CALL_ACTION_MUST_PROCESS = 2
_CALL_ACTION_DO_NOT_PROCESS = 3
BACKLOG_CONCURRENCY_PROTECTION_INTERVAL = 120
MESSAGE_LINGER_INTERVAL = 3600 * 24 * 20 # 20 days
MESSAGE_ALLOWED_FUTURE_TIME_INTERVAL = 3600 * 24
BACKLOG_MESSAGE_RETENTION_INTERVAL = 3600 * 24 + MESSAGE_LINGER_INTERVAL # 21 days
BACKLOG_DUPLICATE_AVOIDANCE_RETENTION_INTERVAL = 3600 * 24 # 1 day
APPENGINE_APP_ID = get_application_id()
DO_NOT_SAVE_RPCCALL_OBJECTS = "DO_NOT_SAVE_RPCCALL_OBJECTS"
PERFORM_CALLBACK_SYNCHRONOUS = "PERFORM_CALLBACK_SYNCHRONOUS"
SKIP_ACCOUNTS = "SKIP_ACCOUNTS"
MOBILE_ACCOUNT = "MOBILE_ACCOUNT"
DEFER_KICK = "DEFER_KICK"
TARGET_MFR = "TARGET_MFR"
API_VERSION = u"av"
API_DIRECT_PATH_KEY = u"ap"
CALL_ID = u"ci"
FUNCTION = u"f"
PARAMETERS = u"a"
STATUS = u"s"
STATUS_SUCCESS = u"success"
STATUS_FAIL = u"fail"
RESULT = u"r"
ERROR = u"e"
CALL_TIMESTAMP = u"t"
CALL_RESEND_TIMEOUT = 120
DEFAULT_RETENTION = 3600 * 24
MANDATORY_CALL_KEYS_SET = {PARAMETERS, API_VERSION, CALL_ID, FUNCTION}
SEND_ACK = 1
IGNORE = 2
PRIORITY_NORMAL = 5
PRIORITY_HIGH = 10
DEFAULT_APPLE_PUSH_MESSAGE = base64.encodestring('{"aps":{"content-available":1}}')
CAPI_KEYWORD_ARG_PRIORITY = "_cka_priority_"
CAPI_KEYWORD_ARG_APPLE_PUSH_MESSAGE = "_cka_apple_push_message_"
CAPI_KEYWORD_PUSH_DATA = '_push_data_'
def _call_rpc(endpoint, payload):
settings = get_server_settings()
jabberEndpoint = choice(settings.jabberEndPoints)
challenge, data = encrypt_for_jabber_cloud(settings.jabberSecret.encode('utf8'), payload)
response = urlfetch.fetch(url="http://%s/%s" % (jabberEndpoint, endpoint),
payload=data, method="POST",
allow_truncated=False, follow_redirects=False, validate_certificate=False)
if response.status_code != 200:
logging.error("Failed to call jabber cloud with the following info:\nendpoint: %s\npayload: %s" %
(endpoint, payload))
raise Exception(response.content)
decrypt_from_jabber_cloud(settings.jabberSecret.encode('utf8'), challenge, response.content)
def process_callback(response, sik, service_api_callback, synchronous):
# type: (urlfetch._URLFetchResult, str, ServiceAPICallback, bool) -> object
from rogerthat.dal.service import get_sik
from rogerthat.rpc.service import _process_callback_result
if response.status_code != 200:
raise Exception("%s failed with http status code %s.\nBody:\n%s" %
(response.final_url, response.status_code, response.content))
sik_model = get_sik(sik)
if service_api_callback.resultFunction:
callback_result = json.loads(response.content)
else:
callback_result = {
'error': None,
'id': service_api_callback.callid,
'result': None
}
raw_result_unicode = json.dumps(privatize(deepcopy(callback_result)), ensure_ascii=False)
result = _process_callback_result(sik_model, callback_result, raw_result_unicode, service_api_callback, True,
synchronous)
if result:
return result
def send_service_api_callback(service_api_callback, sik, url, synchronous, custom_headers=None):
response = api_callbacks.append(url, service_api_callback, sik, synchronous=synchronous, custom_headers=custom_headers)
if response:
return process_callback(response, sik, service_api_callback, synchronous)
def _make_api_callback_rpc(service_api_call, sik, endpoint, custom_headers=None):
rpc_item = urlfetch.create_rpc(10, None)
payload = service_api_call.call.encode('utf8')
headers = {}
if custom_headers:
headers.update(custom_headers)
headers.update({
'Content-type': 'application/json-rpc; charset=utf-8',
'X-Nuntiuz-Service-Key': sik
})
urlfetch.make_fetch_call(rpc_item, endpoint, payload, urlfetch.POST, headers, allow_truncated=False,
follow_redirects=False)
return rpc_item
def _finalize_api_callback_rpc(rpc_item, endpoint, start_time, sik, service_api_call, synchronous):
# type: (UserRPC, str, int, str, ServiceAPICallback, bool) -> None
check_time = time.time()
response = rpc_item.get_result()
response_time = time.time()
logging.info('DirectRpc - Called %s. Elapsed: %sms, checked after %sms', endpoint,
int((response_time - start_time) * 1000), int((check_time - start_time) * 1000))
logging.debug('HTTP response status %d and content:\n%s', response.status_code,
response.content.decode('utf8'))
return process_callback(response, sik, service_api_call, synchronous)
def _retry_api_callback(service_api_call, sik, endpoint, custom_headers=None):
start_time = now()
rpc = _make_api_callback_rpc(service_api_call, sik, endpoint, custom_headers=custom_headers)
_finalize_api_callback_rpc(rpc, endpoint, start_time, sik, service_api_call, False)
class DirectRpcCaller(threading.local):
def __init__(self):
self.items = []
def append(self, endpoint, service_api_call, sik, synchronous=False, custom_headers=None):
rpc_item = _make_api_callback_rpc(service_api_call, sik, endpoint, custom_headers=custom_headers)
if synchronous:
return rpc_item.get_result()
self.items.append((rpc_item, endpoint, time.time(), service_api_call, sik, custom_headers))
def finalize(self):
for rpc_item, endpoint, start_time, service_api_call, sik, custom_headers in self.items:
try:
_finalize_api_callback_rpc(rpc_item, endpoint, start_time, sik, service_api_call, False)
except:
logging.warning('Failed to reach %s! Retrying.' % endpoint, exc_info=1)
retry_options = TaskRetryOptions(min_backoff_seconds=5, task_retry_limit=3)
deferred.defer(_retry_api_callback, service_api_call, sik, endpoint, custom_headers=custom_headers,
_queue=HIGH_LOAD_WORKER_QUEUE, _retry_options=retry_options)
del self.items[:]
class APNSCache(object):
def __init__(self):
self.jwts = {}
def get_jwt(self, app):
now_ = time.time()
if app.ios_dev_team not in self.jwts or self.jwts[app.ios_dev_team]['expires'] < now_:
self.jwts[app.ios_dev_team] = {'data': self._create_jwt(app, now_),
'expires': now_ + 40 * 60}
return self.jwts[app.ios_dev_team]['data']
def _create_jwt(self, app, now_):
logging.info("APNSConnections._create_jwt start app:%s", app.app_id)
token = jwt.encode({'iss': app.ios_dev_team, 'iat': now_},
app.apns_key,
algorithm=Algorithms.ES256,
headers={ 'alg': Algorithms.ES256, 'kid': app.apns_key_id})
logging.info("APNSConnections._create_jwt end")
return token
class JabberRpcCaller(threading.local):
def __init__(self, endpoint):
self.items = list()
self.endpoint = endpoint
def append(self, payload):
settings = get_server_settings()
if DEBUG and not settings.jabberEndPoints:
logging.debug('Skipping KICK, No jabberEndPoints configured.')
return
try:
payload_dict = json.loads(payload)
if 'apns' in payload_dict['t']:
app_id = payload_dict['a']
app = get_app_by_id(app_id)
if not app:
logging.error('Not sending apns to "%s" app doesn\' exist', app_id)
return
if not app.apple_push_cert_valid_until:
logging.debug('Not sending apns to "%s" app is expired', app_id)
return
if not app.apple_push_cert or not app.apple_push_key:
logging.error('Not sending apns to "%s" cert or key was empty', app_id)
return
else:
app = None
except:
logging.exception("Failed to process JabberRpcCaller.append")
return
if app and app.apns_key_id:
self.do_kick(app, payload_dict)
else:
jabberEndpoint = choice(settings.jabberEndPoints)
rpc_item = urlfetch.create_rpc(5, None)
challenge, data = encrypt_for_jabber_cloud(settings.jabberSecret.encode('utf8'), payload)
url = "http://%s/%s" % (jabberEndpoint, self.endpoint)
urlfetch.make_fetch_call(rpc=rpc_item, url=url, payload=data, method="POST",
allow_truncated=False, follow_redirects=False, validate_certificate=False)
self.items.append((1, rpc_item, payload, challenge, time.time(), url))
def finalize(self):
# Don't fetch server settings when not needed
settings = None
for item_tuple in self.items:
version = item_tuple[0]
if version == 1:
_, rpc_item, payload, challenge, start_time, url = item_tuple
if not settings:
settings = get_server_settings()
try:
check_time = time.time()
response = rpc_item.get_result()
response_time = time.time()
logging.info("JabberRpc - Called %s. Elapsed: %sms, checked after %sms\npayload: %s", url,
int((response_time - start_time) * 1000), int((check_time - start_time) * 1000), payload)
if response.status_code != 200:
logging.error("Failed to call jabber cloud with the following info:\nendpoint: %s\npayload: %s",
self.endpoint, payload)
raise Exception(response.content)
decrypt_from_jabber_cloud(settings.jabberSecret.encode('utf8'), challenge, response.content)
except:
logging.warn("Failed to reach jabber endpoint on %s, deferring ..." % url)
deferred.defer(_call_rpc, self.endpoint, payload)
elif version == 2:
_, conn, stream_id = item_tuple
try:
resp = conn.get_response(stream_id)
if resp.status != 200:
logging.error("Failed to send apple push %s", resp.read())
except:
logging.info("failed to get response", exc_info=True)
try:
stream = conn.streams[stream_id]
stream.close()
except:
logging.info("failed to close stream", exc_info=True)
try:
conn.reset_streams.discard(stream_id)
except:
logging.info("failed to discard reset_streams", exc_info=True)
del self.items[:]
def do_kick(self, app, payload_dict):
# todo improve how connections work
# 1 connection for every ios_dev_team
# 1 jwt for every connection
# renew jwt every 40 minutes
# APNs does not support authentication tokens from multiple developer accounts over a single connection.
# Refresh your token no more than once every 20 minutes and no less than once every 60 minutes.
# https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/establishing_a_token-based_connection_to_apns
if 'd' not in payload_dict:
return
if not app.ios_dev_team or not app.apns_key_id or not app.apns_key:
logging.error('Not sending apns to "%s" ios_dev_team or apns_key_id or apns_key was empty', app.app_id)
return
token = apns_cache.get_jwt(app)
path = '/3/device/{0}'.format(payload_dict['d'])
request_headers = {
'apns-expiration': '0',
'apns-priority': str(payload_dict['p']),
'apns-topic': 'com.mobicage.rogerthat.{0}'.format(app.app_id),
'authorization': 'bearer {0}'.format(token.decode('ascii'))
}
# todo don't base64 and json encode
payload_data = json.loads(base64.decodestring(payload_dict['m']))
payload = json.dumps(payload_data).encode('utf-8')
conn = HTTP20Connection('api.push.apple.com:443', force_proto='h2')
stream_id = conn.request(
'POST',
path,
payload,
headers=request_headers
)
self.items.append((2, conn, stream_id))
def create_firebase_request(data, is_gcm=False):
# type: (dict) -> UserRPC
# See https://firebase.google.com/docs/cloud-messaging/http-server-ref
settings = get_server_settings()
rpc_item = urlfetch.create_rpc(5, None)
url = 'https://fcm.googleapis.com/fcm/send'
headers = {
'Content-Type': 'application/json',
'Authorization': 'key=%s' % (settings.gcmKey if is_gcm else settings.firebaseKey)
}
urlfetch.make_fetch_call(rpc_item, url, json.dumps(data), urlfetch.POST, headers)
return rpc_item
def retry_firebase_request(payload, is_gcm=False):
rpc_item = create_firebase_request(payload, is_gcm=is_gcm)
response = rpc_item.get_result() # type: urlfetch._URLFetchResult
if response.status_code != 200:
raise Exception(response.content)
class FirebaseKicker(threading.local):
def __init__(self):
self.items = []
self.outstandingKicks = []
def kick(self, registration_id, priority, push_data=None, is_gcm=False):
if not push_data:
push_data = PushData()
collapse_key = "rogerthat" if priority == PRIORITY_NORMAL else "rogerthat_high_prio"
priority_string = "normal" if priority == PRIORITY_NORMAL else "high"
registration_ids = [registration_id] if not isinstance(registration_id, list) else registration_id
data = {
'registration_ids': registration_ids,
'collapse_key': collapse_key,
'priority': priority_string
}
data.update(push_data.to_dict())
if priority == PRIORITY_NORMAL:
# There is no guarantee this message will ever reach the device
# but in order to avoid throttling of kicks while the user is actively using
# Rogerthat we add time_to_live = 0
data['time_to_live'] = 0
self.outstandingKicks.append(
(db.get_async(OutStandingFirebaseKick.createKey(registration_id)), | |
de Configuración: Repositorio</h5>
<ul>
<li> <b>Repositorio:</b> Repositorio de inversores dispuestos por PVlib.</li>
<li> <b>Fabricantes:</b> Lista de fabricantes del repositorio seleccionado.</li>
<li> <b>Inversores:</b> Lista de equipos disponibles en el repositorio según el fabricante seleccionado.</li>
</ul>
<h5>Método de Configuración: PVsyst</h5>
<ul>
<li> Seleccione el archivo del inversor generado por PVsyst (extensión .OND) y dé clic en 'Cargar OND'.</li>
</ul>
<h5>Método de Configuración: Manual</h5>
<ul>
<li> <b>SNL PVlib</b>
<ul class='square'>
<li> <b>$P_{AC}$ Nominal:</b> Potencia AC nominal del inversor en W.</li>
<li> <b>$P_{DC}$ Nominal:</b> Potencia DC nominal del inversor en W.</li>
<li> <b>$V_{DC}$ Nominal:</b> Voltaje DC al que se alcanza la Potencia AC nominal con la entrada de Potencia DC en V.</li>
<li> <b>$P_{DC}$ de Arraque:</b> Potencia DC necesaria para iniciar el proceso de inversión en W.</li>
<li> <b>$C_0$:</b> Parámetro que define la curvatura de la relación entre la Potencia AC y Potencia DC en condición STC en 1/W.</li>
<li> <b>$C_1$:</b> Coeficiente empírico que permite que la Potencia DC Nominal varíe linealmente con el Voltaje DC en 1/V.</li>
<li> <b>$C_2$:</b> Coeficiente empírico que permite que la Potencia DC de Arranque varíe linealmente con el Voltaje DC en 1/V.</li>
<li> <b>$C_3$:</b> Coeficiente empírico que permite que $C_0$ varíe linealmente con el Voltaje DC en 1/V.</li>
<li> <b>$P_{AC}$ Consumo Nocturno:</b> Potencia AC consumida por el inversor durante la noche en W.</li>
</ul>
</li>
<li> <b>NREL PVWatts</b>
<ul class='square'>
<li> <b>$P_{DC}$ Nominal:</b> Potencia DC nominal del inversor en W.</li>
<li> <b>Eficiencia Nominal:</b> Eficiencia nominal del inversor en magnitud adimensional.</li>
</ul>
</li>
</ul>
''', layout=widgets.Layout(height='auto'))
doc_module = widgets.HTMLMath('''
<h5>Método de Configuración: Repositorio</h5>
<ul>
<li> <b>Repositorio:</b> Repositorio de módulos fotovoltaicos dispuestos por PVlib (CEC y Sandia).</li>
<li> <b>PVFree</b>
<ul class='square'>
<li> <b>Base de Datos:</b> Repositorio de módulos fotovoltaicos dispuestos en PVFree.</li>
<li> <b>ID:</b> Número de identificación del módulo indicado en PVFree.</li>
</ul>
</li>
<li> <b>CEC y Sandia</b>
<ul class='square'>
<li> <b>Fabricantes:</b> Lista de fabricantes del repositorio seleccionado.</li>
<li> <b>Módulos:</b> Lista de equipos disponibles en el repositorio según el fabricante seleccionado.</li>
</ul>
</li>
</ul>
<h5>Método de Configuración: PVsyst</h5>
<ul>
<li> Seleccione el archivo del módulo fotovoltaico generado por PVsyst (extensión .PAN) y dé clic en 'Cargar PAN'.</li>
</ul>
<h5>Método de Configuración: Manual</h5>
<ul>
<li> <b>$T_{NOCT}$:</b> Temperatura nominal de funcionamiento de la celda en ºC. </li>
<li> <b>Tecnología:</b> Tecnología de la celda fotovoltaica. </li>
<li> <b>Número Celdas:</b> Número de celdas fotovoltaicas en serie. </li>
<li> <b>$I_{SC}$ en STC:</b> Corriente de corto circuito en condiciones STC en A. </li>
<li> <b>$V_{OC}$ en STC:</b> Voltaje de circuito abierto en condiciones STC en V. </li>
<li> <b>$I_{MP}$ en STC:</b> Corriente en el punto de máxima potencia en condiciones STC en A. </li>
<li> <b>$V_{MP}$ en STC:</b> Voltaje en el punto de máxima potencia en condiciones STC en V.</b> </li>
<li> <b>Coef. Temp. $I_{SC}$:</b> Coeficiente de temperatura de la corriente de cortocircuito en A/ºC. </li>
<li> <b>Coef. Temp. $V_{OC}$:</b> Coeficiente de temperatura de voltaje de circuito abierto en V/ºC. </li>
<li> <b>Coef. Temp. $P_{MP}$:</b> Coeficiente de temperatura de la potencia en el punto máximo en %/ºC. </li>
<li> <b>$P_{Nominal}$ en STC:</b> Potencia nominal del módulo fotovoltaico en condiciones STC en W.</li>
</ul>
<h5>Parámetros Bifacialidad</h5>
<ul>
<li> <b>Panel Bifacial:</b> Si el panel fotovoltaico es bifacial o no. </li>
<li> <b>Bifacialidad:</b> Relación entre la eficiencia del lado frontal y posterior del módulo fotovoltaico, medida en condiciones STC. Utilice un valor porcentual en escala entre 0 y 1. </li>
<li> <b>Alto Fila Paneles:</b> Altura de las filas de paneles fotovoltaicos medida en su centro en unidades de metros. </li>
<li> <b>Ancho Fila Paneles:</b> Ancho de las filas de paneles fotovoltaicos en el plano 2D considerado en unidades de metros (e.g., 1P, 2P, 4L). </li>
</ul>
''', layout=widgets.Layout(height='auto'))
doc_sysdesign = widgets.HTMLMath('''
<h5>Subarrays</h5>
<ul>
<li> <b>Cantidad Subarrays:</b> Conjunto de arreglos conectados a un inversor. Cada subarray se compone de módulos en serie por string, strings en paralelo y el número de entradas al inversor (ya sea entradas completas por inversor o número de entradas MPPT).</li>
</ul>
<h5>Configuración Eléctrica</h5>
<ul>
<li> <b>Módulos por String:</b> Cantidad de módulos en serie por string en cada subarray. Para múltiples subarrays, separe los valores con una coma de manera ordenada.</li>
<li> <b>Strings por Inversor:</b> Cantidad de strings en paralelo en cada subarray. Para múltiples subarrays, separe los valores con una coma de manera ordenada.</li>
<li> <b>Número de Inversores:</b> Cantidad de inversores con configuración eléctrica exactamente igual a la definida. Permite escalar los cálculos de producción.</li>
</ul>
<h5>Seguidores y Orientación</h5>
<ul>
<li> <b>Sin Seguidor</b>
<ul class='square'>
<li> <b>Azimutal:</b> Ángulo azimutal en grados decimales (Norte = 0, Sur = 180, Este = 90, Oeste = 270). Para múltiples subarrays, separe los valores con una coma de manera ordenada (también aplica si el azimutal es el mismo).</li>
<li> <b>Elevación:</b> Ángulos de inclinación desde la horizontal en grados decimales. Para múltiples subarrays, separe los valores con una coma de manera ordenada (también aplica si la elevación es la misma).</li>
<li> <b>Racking:</b> Tipo de ventilación del montaje. Se utiliza para identificar un conjunto de parámetros para el modelo de temperatura de la celda.</li>
</ul>
</li>
<li> <b>Seguidor 1-Eje</b><br>
El ángulo de rotación se determina en un sistema de coordenadas diestro. El seguidor define el eje-y positivo, el eje-x positivo está a 90º en sentido horario desde el eje-y y es paralelo a la superficie, y el eje-z positivo es normal a ambos ejes (-x y -y), y está orientado hacia el cielo. El ángulo de rotación es una rotación hacia la derecha alrededor del eje-y en el sistema de coordenadas e indica la posición del seguidor en relación con la horizontal. Por ejemplo, si Azimutal Eje es 180º (orientado al sur) y Elevación Eje es 0º, entonces un ángulo del seguidor de 0º es horizontal, de 30º es una rotación hacia el oeste, y -90º es una rotación al plano vertical hacia el este.
<ul class='square'>
<li> <b>Elevación Eje:</b> Elevación del eje de rotación con respecto a la horizontal en grados decimales (e.g., un valor de 0º indica que el eje de soporte de los paneles fotovoltaicos está horizontal). Para múltiples subarrays, separe los valores con una coma de manera ordenada (también aplica si la elevación del eje es la misma).</li>
<li> <b>Azimutal Eje:</b> Ángulo perpendicular por regla de la mano derecha al eje de rotación en grados decimales (e.g., un valor de 180º --i.e., dirección sur-- indica una rotación de este a oeste). Para múltiples subarrays, separe los valores con una coma de manera ordenada (también aplica si el azimutal del eje es el mismo).</li>
<li> <b>Ángulo Máximo:</b> Ángulo de rotación máximo del seguidor desde su posición horizontal en grados decimales (e.g., un valor de 90º permite que el seguidor gire desde y hasta una posición vertical en la que el panel mira hacia el horizonte). Para múltiples subarrays, separe los valores con una coma de manera ordenada (también aplica si el ángulo máximo es el mismo).</li>
<li> <b>Racking:</b> Tipo de ventilación del montaje. Se utiliza para identificar un conjunto de parámetros para el modelo de temperatura de la celda.</li>
</ul>
</li>
</ul>
<h5>Parámetros Globales</h5>
<ul>
<li> <b>Pérdidas DC:</b> Porcentaje de pérdidas globales DC del sistema. Por defecto: 14.6%.</li>
<li> <b>$k_{pc}$:</b> Pérdidas de transmisión hasta el punto común de acople de los inversores. Por defecto: 0%.</li>
<li> <b>$k_{t}$:</b> Pérdidas asociadas a la transformación (elevación de tensión). Por defecto: 0%.</li>
<li> <b>$k_{in}$:</b> Pérdidas de interconexión, transmisión hasta la frontera comercial. Por defecto: 0%.</li>
<li> <b>Nombre Planta:</b> Sufijo al nombre del archivo de configuración (system_config_<i>sufijo</i>). Por defecto: system_config.</li>
</ul>
<h5>Archivo Configuración</h5>
<ul>
<li> <b>Generar Configuración:</b> Dé clic en este botón para que el algoritmo genere internamente el archivo de configuración con los parámetros previamente asignados. El ícono y la descripción del botón cambiarán para notificar la ejecución de la configuración.</li>
<li> <b>Descargar Configuración:</b> Dé | |
threading.Event().wait(2)
final_message = "Finished with 3 errors"
completed = True
all_ok = False
else:
custom_env = os.environ.copy()
custom_env["LC_ALL"] = "C"
pipe = subprocess.Popen(
(
"sudo",
"-n",
"badblocks",
"-w",
"-s",
"-p",
"0",
"-t",
"0x00",
"-b",
"4096",
dev,
),
stderr=subprocess.PIPE,
env=custom_env,
) # , stdout=subprocess.PIPE)
# TODO: restore this code and kill badblocks if it's too slow (the disk is probably broken)
# disk_gb = self.disk['features']['capacity-byte'] / 1024 ** 3
# mins_per_gb = 2 # TODO: could be set with a config file?
# timeout = 60 * mins_per_gb * disk_gb
percent = 0.0
reading_and_comparing = False
errors = -1
deleting = False
buffer = bytearray()
for char in iter(lambda: pipe.stderr.read(1), b""):
if char == b"":
if pipe.poll() is not None:
break
elif char == b"\b":
if not deleting:
result = buffer.decode("utf-8")
errors_print = "?"
reading_and_comparing = reading_and_comparing or (
"Reading and comparing" in result
)
# If other messages are printed, ignore them
i = result.index("% done")
if i >= 0:
# /2 due to the 0x00 test + read & compare
percent = float(result[i - 6 : i]) / 2
if reading_and_comparing:
percent += 50
i = result.index("(", i)
if i >= 0:
# errors_str = result[i+1:].split(")", 1)[0]
errors_str = result[i + 1 :].split(" ", 1)[0]
# The errors are read, write and corruption
errors_str = errors_str.split("/")
errors = 0 # badblocks prints the 3 totals every time
for error in errors_str:
errors += int(error)
errors_print = str(errors)
self._queued_command.notify_percentage(
percent, f"{errors_print} errors"
)
buffer.clear()
deleting = True
# elif char == b'\n':
# # Skip the first lines (total number of blocks)
# buffer.clear()
else:
if deleting:
deleting = False
buffer += char
# TODO: was this needed? Why were we doing it twice?
# pipe.wait()
exitcode = pipe.wait()
if errors <= -1:
all_ok = None
errors_print = "an unknown amount of"
elif errors == 0:
all_ok = True
errors_print = "no"
else:
all_ok = False
errors_print = str(errors)
final_message = f"Finished with {errors_print} errors"
if exitcode == 0:
# self._queued_command.notify_finish(final_message)
completed = True
else:
self._queued_command.notify_error()
final_message += f" and badblocks exited with status {exitcode}"
# self._queued_command.notify_finish(final_message)
completed = False
# print(pipe.stdout.readline().decode('utf-8'))
# print(pipe.stderr.readline().decode('utf-8'))
with disks_lock:
update_disks_if_needed(self)
disk_ref = disks[dev]
# noinspection PyBroadException
try:
disk_ref.update_erase(completed, all_ok)
except BaseException as e:
final_message = f"Error during upload. {final_message}"
self._queued_command.notify_error(final_message)
logging.warning(
f"[{self._the_id}] Can't update badblocks results of {dev} on tarallo",
exc_info=e,
)
self._queued_command.notify_finish(final_message)
def ping(self, _cmd: str, _nothing: str):
self.send_msg("pong", None)
# noinspection PyMethodMayBeStatic
def close_at_end(self, _cmd: str, _nothing: str):
logging.info("Server will close at end")
with CLOSE_AT_END_LOCK:
global CLOSE_AT_END
# Do not start the timer twice
if CLOSE_AT_END:
return
CLOSE_AT_END = True
# noinspection PyUnresolvedReferences
reactor.callFromThread(reactor.callLater, CLOSE_AT_END_TIMER, try_stop_at_end)
def cannolo(self, _cmd: str, dev_and_iso: str):
parts: list[Optional[str]] = dev_and_iso.split(" ", 1)
while len(parts) < 2:
parts.append(None)
dev, iso = parts
if iso is None:
self._queued_command.notify_finish_with_error(f"No iso selected")
return
if not os.path.exists(iso):
self._queued_command.notify_finish_with_error(f"File {iso} does not exist")
return
if not os.path.isfile(iso):
self._queued_command.notify_finish_with_error(
f"{iso} is not a file (is it a directory?)"
)
return
go_ahead = self._unswap()
if not go_ahead:
return
success = True
self._queued_command.notify_start("Cannoling")
if TEST_MODE:
self._queued_command.notify_percentage(10)
threading.Event().wait(2)
self._queued_command.notify_percentage(20)
threading.Event().wait(2)
self._queued_command.notify_percentage(30)
threading.Event().wait(2)
self._queued_command.notify_percentage(40)
threading.Event().wait(2)
self._queued_command.notify_percentage(50)
threading.Event().wait(2)
self._queued_command.notify_percentage(60)
threading.Event().wait(2)
self._queued_command.notify_percentage(70)
threading.Event().wait(2)
self._queued_command.notify_percentage(80)
threading.Event().wait(2)
self._queued_command.notify_percentage(90)
threading.Event().wait(2)
else:
pipe = subprocess.Popen(
("sudo", "-n", "cannolo", iso, dev)
) # stderr=subprocess.PIPE), stdout=subprocess.PIPE)
exitcode = pipe.wait()
if exitcode != 0:
self._queued_command.notify_error("cannolo returned " + str(exitcode))
success = False
if success:
with disks_lock:
update_disks_if_needed(self)
disk_ref = disks[dev]
pretty_iso = self._pretty_print_iso(iso)
self._queued_command.notify_percentage(100.0, f"{pretty_iso} installed!")
final_message = f"{pretty_iso} installed, Tarallo updated"
# noinspection PyBroadException
try:
disk_ref.update_software(pretty_iso)
except BaseException as e:
final_message = f"{pretty_iso} installed, failed to update Tarallo"
self._queued_command.notify_error(
f"{pretty_iso} installed, failed to update Tarallo"
)
logging.warning(
f"[{self._the_id}] Can't update software of {dev} on tarallo",
exc_info=e,
)
self._queued_command.notify_finish(final_message)
else:
self._queued_command.notify_finish()
def _unswap(self) -> bool:
if TEST_MODE:
return True
self._queued_command.disk.update_mountpoints()
mountpoints = self._queued_command.disk.get_mountpoints_map()
unswap_them = []
oh_no = None
for part in mountpoints:
if mountpoints[part] == "[SWAP]":
unswap_them.append(part)
else:
oh_no = part
break
if oh_no:
self._queued_command.notify_finish_with_error(
f"Partition {oh_no} is mounted as {mountpoints[oh_no]}"
)
return False
if len(unswap_them) > 0:
self._queued_command.notify_start("Unswapping the disk")
for path in unswap_them:
sp = subprocess.Popen(("sudo", "swapoff", path))
exitcode = sp.wait()
if exitcode != 0:
self._queued_command.notify_finish_with_error(
f"Failed to unswap {path}, exit code {str(exitcode)}"
)
return False
self._queued_command.disk.update_mountpoints()
return True
def sleep(self, _cmd: str, dev: str):
self._queued_command.notify_start("Calling hdparm")
exitcode = self.call_hdparm_for_sleep(dev)
if exitcode == 0:
self._queued_command.notify_finish("Good night!")
else:
self._queued_command.notify_finish_with_error(
f"hdparm exited with status {str(exitcode)}"
)
def call_hdparm_for_sleep(self, dev):
if TEST_MODE:
logging.debug(f"Fake putting {dev} to sleep")
return 0
logging.debug(f"[{self._the_id}] Putting {dev} to sleep")
res = subprocess.Popen(
("sudo", "hdparm", "-Y", dev),
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
)
exitcode = res.wait()
if exitcode != 0:
logging.warning(
f"[{self._the_id}] hdparm for {dev} returned {str(exitcode)}"
)
return exitcode
def get_smartctl(self, cmd: str, args: str):
params = self._get_smartctl(args, False)
if params:
self.send_msg(cmd, params)
def queued_get_smartctl(self, cmd: str, args: str):
params = self._get_smartctl(args, True)
if params:
self.send_msg(cmd, params)
def _get_smartctl(self, dev: str, queued: bool):
if queued:
self._queued_command.notify_start("Getting smarter")
pipe = subprocess.Popen(
("sudo", "-n", "smartctl", "-a", dev),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
output = pipe.stdout.read().decode("utf-8")
stderr = pipe.stderr.read().decode("utf-8")
exitcode = pipe.wait()
if exitcode == 0:
smartctl_returned_valid = True
else:
exitcode_bytes = exitcode.to_bytes(8, "little")
if (
exitcode_bytes[0] == 1
or exitcode_bytes[1] == 1
or exitcode_bytes[2] == 1
):
smartctl_returned_valid = False
else:
# TODO: parse remaining bits (https://github.com/WEEE-Open/pesto/issues/65)
smartctl_returned_valid = True
updated = False
status = None
if smartctl_returned_valid:
status = get_smartctl_status(output)
if queued:
if not status:
self._queued_command.notify_error(
"Error while parsing smartctl status"
)
return {
"disk": dev,
"status": status,
"updated": updated,
"exitcode": exitcode,
"output": output,
"stderr": stderr,
}
else:
if queued:
self._queued_command.notify_error("smartctl failed")
return {
"disk": dev,
"status": status,
"updated": updated,
"exitcode": exitcode,
"output": output,
"stderr": stderr,
}
if queued and status:
self._queued_command.notify_percentage(50.0, "Updating tarallo if needed")
with disks_lock:
update_disks_if_needed(self)
disk_ref = disks[dev]
# noinspection PyBroadException
try:
updated = disk_ref.update_status(status)
except BaseException as e:
self._queued_command.notify_error("Error during upload")
logging.warning(
f"[{self._the_id}] Can't update status of {dev} on tarallo",
exc_info=e,
)
self._queued_command.notify_finish(f"Disk is {status}")
return {
"disk": dev,
"status": status,
"updated": updated,
"exitcode": exitcode,
"output": output,
"stderr": stderr,
}
@staticmethod
def _encode_param(param):
return json.dumps(param, separators=(",", ":"), indent=None)
def send_msg(self, cmd: str, param=None, the_id: Optional[int] = None):
logging.debug(
f"[{self._the_id}] Sending {cmd}{ ' with args' if param else ''} to client"
)
the_id = the_id or self._the_id
thread = clients.get(the_id)
if thread is None:
logging.info(
f"[{the_id}] Connection already closed while trying to send {cmd}"
)
else:
thread: TurboProtocol
# noinspection PyBroadException
try:
if param is None:
response_string = cmd
else:
j_param = self._encode_param(param)
response_string = f"{cmd} {j_param}"
# It's there but pycharm doesn't believe it
# noinspection PyUnresolvedReferences
reactor.callFromThread(TurboProtocol.send_msg, thread, response_string)
except BaseException:
logging.warning(
f"[{the_id}] Something blew up while trying to send {cmd} (connection already closed?)"
)
def get_disks(self, cmd: str, _nothing: str):
result = []
with disks_lock:
# Sent regardless
update_disks_if_needed(self, False)
for disk in disks:
result.append(disks[disk].serialize_disk())
self.send_msg(cmd, result)
@staticmethod
def _pretty_print_iso(iso: str):
filename = iso.rsplit("/", 1)[-1]
filename = filename.split(".", 1)[0]
filename = filename.replace("-", " ").replace("_", " ")
return filename
class QueuedCommand:
def __init__(self, disk: Disk, command_runner: CommandRunner):
self.disk = disk
self._target = self.disk.get_path()
self.command_runner = command_runner
self._percentage = 0.0
self._started = False
self._finished = False
self._error = False
self._stopped = False
self._stale = False
self._notifications_lock = threading.Lock()
self._text = "Queued"
self._to_delete = False
self._deleted = False
date = datetime.today().strftime("%Y%m%d%H%M")
with queued_commands_lock:
self._id = f"{date}-{str(len(queued_commands))}"
queued_commands.append(self)
with self._notifications_lock:
self.send_to_all_clients()
def id_is(self, the_id: str):
return self._id == the_id
def lock_notifications(self):
self._notifications_lock.acquire()
def unlock_notifications(self):
self._notifications_lock.release()
def notify_start(self, text: Optional[str] = None):
with self._notifications_lock:
if text is not None:
self._text = text
self._started = True
self._percentage = 0.0
self.send_to_all_clients()
def notify_finish_safe(self, text: Optional[str] = None):
with self._notifications_lock:
if self._finished:
return
# TODO: RLock? Probably not needed
self.notify_finish(text)
def notify_finish(self, text: Optional[str] = None):
with self._notifications_lock:
if text is not None:
self._text = text
self._finished = True
self._percentage = 100.0
self.send_to_all_clients()
if self._to_delete:
self.notify_delete()
def notify_finish_with_error(self, text: Optional[str] = None):
with self._notifications_lock:
if text is not None:
self._text = text
self._finished = True
self._error = True
| |
<gh_stars>0
import cv2
import numpy as np
import scipy.misc
import imageio
import os
import warnings
from helper_code.registration_funcs import model_arena
from helper_code.processing_funcs import speed_colors, register_frame
def visualize_escape(self):
''' Generate and save escape video clip and dlc tracking clip '''
warnings.filterwarnings("ignore")
''' Initialize variables and backgrounds '''
# open the behaviour video
vid = cv2.VideoCapture(self.video_path)
vid.set(cv2.CAP_PROP_POS_FRAMES, self.start_frame)
# set up the escape clips for saving
video = cv2.VideoWriter(os.path.join(self.save_folder, self.videoname + ' vid.mp4'), self.fourcc, self.fps, (self.width, self.height), False)
video_dlc = cv2.VideoWriter(os.path.join(self.save_folder, self.videoname + ' vid (DLC).mp4'), self.fourcc,self.fps, (self.width , self.height), True)
# load fisheye mapping
maps = np.load(self.folders['fisheye_map_location']); map1 = maps[:, :, 0:2]; map2 = maps[:, :, 2] * 0
# set up model arena
arena, _, _ = model_arena((self.height, self.width), self.trial_type != 0, registration = False, #self.trial_type > 0
obstacle_type = self.obstacle_type, shelter = ('down' in self.videoname or not 'no shelter' in self.videoname) and not 'food' in self.videoname, dark = self.dark_theme)
arena = cv2.cvtColor(arena, cv2.COLOR_GRAY2RGB)
# initialize arenas for mouse mask
model_mouse_mask_previous = np.zeros(arena.shape[0:2]).astype(np.uint8)
model_mouse_mask_initial = np.zeros(arena.shape[0:2]).astype(np.uint8)
# initialize more quantities
trial_plot = arena.copy()
frames_past_stimulus = 0
arrived_at_shelter = False
count_down = np.inf
color_trail = np.array([.02, -.02, -.02]) # red
# color_trail = np.array([-.1, -.1, -.1]) # gray
# color_trail = np.array([-.02, -.01, .02]) # blue
contour_color = (255, 100, 100) # red
# contour_color = (150, 150, 150) # gray
# contour_color = (100, 200, 250) # blue
# when is the stimulus on, and how is the arena shaped
stim_timing_array, shape, size = initialize_stim_visualization(self.obstacle_type)
# make a smooth speed trace for coloration
smoothed_speed = np.concatenate((np.zeros(6 - 1), np.convolve(self.coordinates['speed'], np.ones(12), mode='valid'), np.zeros(6))) / 12
# set up background arena with previous obstacle dulled out
if self.trial_type==0 and (('down' in self.videoname) or ('up' in self.videoname and 'void' in self.videoname)) and False:
former_arena, _, _ = model_arena((self.height, self.width), 1, registration = False,
obstacle_type = self.obstacle_type, shelter = not 'no shelter' in self.videoname and not 'food' in self.videoname, dark = self.dark_theme)
former_arena = cv2.cvtColor(former_arena, cv2.COLOR_GRAY2RGB)
discrepancy = ~((arena - former_arena)==0)
self.arena_with_prev_trials[discrepancy] = 255 #((former_arena[discrepancy] * 1 + arena[discrepancy].astype(float) * 9) / 10).astype(np.uint8)
trial_plot[discrepancy] = 255 # ((former_arena[discrepancy] * 1 + arena[discrepancy].astype(float) * 9) / 10).astype(np.uint8)
''' Loop over each frame, making the video and images '''
# loop over each frame
while True:
# get the frame
ret, frame = vid.read()
#get the frame number
frame_num = int(vid.get(cv2.CAP_PROP_POS_FRAMES))
frames_past_stimulus = frame_num - self.stim_frame
frames_til_abort = count_down - frame_num
# stop after 2 secs of shelter
if not frames_til_abort: break
# apply the registration and fisheye correction
if False: frame = register_frame(frame, self.x_offset, self.y_offset, self.session.Registration, map1, map2)
# prior to stimulus onset, refresh frame to initialized frame
if frames_past_stimulus < 0:
video_arena = self.arena_with_prev_trials.copy() #TEMPORARY: arena.copy() #
model_mouse_mask_previous = 0
# extract DLC coordinates and make a model mouse mask
model_mouse_mask, large_mouse_mask, body_location = make_model_mouse_mask(self.coordinates, frame_num, model_mouse_mask_initial)
# use speed to determine model mouse coloration
speed_color_light, speed_color_dark = speed_colors(smoothed_speed[frame_num - 1], blue = True)
# at the stimulus onset
if (frame_num+1) == self.stim_frame:
# get a contour of the mouse mask
_, contours, _ = cv2.findContours(model_mouse_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# and store the position of the mouse
x_stim = float(body_location[0]); y_stim = float(body_location[1])
# add dark mouse silhouette if distant from the previous dark one
elif np.sum(large_mouse_mask * model_mouse_mask_previous) == 0 and not arrived_at_shelter and frames_past_stimulus:
# add dark mouse to the video arena
video_arena[model_mouse_mask.astype(bool)] = video_arena[model_mouse_mask.astype(bool)] * speed_color_dark
if frames_past_stimulus >= -1: trial_plot[model_mouse_mask.astype(bool)] = trial_plot[model_mouse_mask.astype(bool)] * speed_color_dark
# set the current model mouse mask as the one to be compared to to see if dark mouse should be added
model_mouse_mask_previous = model_mouse_mask
# continuous shading, after stimulus onset
elif frames_past_stimulus >= 0:
# once at shelter, end it
if np.sum(self.shelter_roi * large_mouse_mask) \
and not 'no shelter' in self.videoname and not 'Circle shelter moved' in self.videoname: # or 'down' in self.videoname:
if not arrived_at_shelter:
# end video in 2 seconds
arrived_at_shelter = True
count_down = frame_num + self.fps * 2
else:
# add light mouse to video arena
video_arena[model_mouse_mask.astype(bool)] = video_arena[model_mouse_mask.astype(bool)] * speed_color_light
# add light mouse to escape image
trial_plot[model_mouse_mask.astype(bool)] = trial_plot[model_mouse_mask.astype(bool)] * speed_color_light
# add red trail to the previous trials' arena
if frames_past_stimulus > 0 and not arrived_at_shelter:
dist_from_start = np.sqrt((x_stim - float(body_location[0]))**2 + (y_stim - float(body_location[1]))**2)
dist_to_make_red = 150
prev_homing_color = np.array([.98, .98, .98]) + np.max((0,dist_to_make_red - dist_from_start))/dist_to_make_red * color_trail
self.arena_with_prev_trials[model_mouse_mask.astype(bool)] = self.arena_with_prev_trials[model_mouse_mask.astype(bool)] * prev_homing_color
# redraw this contour on each frame after the stimulus
if frame_num >= self.stim_frame:
cv2.drawContours(video_arena, contours, 0, (255,255,255), thickness = 1)
cv2.drawContours(trial_plot, contours, 0, (255,255,255), thickness = 1)
# if wall falls or rises, color mouse in RED
if (self.trial_type==1 or self.trial_type==-1) and (frame_num == self.wall_change_frame):
_, contours_wall_change, _ = cv2.findContours(model_mouse_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(video_arena, contours_wall_change, 0, (220,0,220), thickness=-1)
cv2.drawContours(trial_plot, contours_wall_change, 0, (220,0,220), thickness=-1)
if self.trial_type==1:
video_arena[arena==90] = arena[arena==90]
self.arena_with_prev_trials[arena == 90] = arena[arena == 90]
else:
middle_replace_arena = self.arena_with_prev_trials.copy()
video_arena[arena==90] = self.arena_with_prev_trials[arena==90] * (255 / 90)
video_arena[video_arena==122] = 255
# add a looming spot - for actual loom
self.stim_type = 'visual'
if self.stim_type == 'visual': stim_radius = 30 * (frame_num - self.stim_frame) * ( (frame_num - self.stim_frame) < 10) * (frame_num > self.stim_frame)
else: stim_radius = size * stim_timing_array[frame_num - self.stim_frame] #218 for planning #334 for barnes #347 for void
stim_radius = 0
session_trials_plot_show = video_arena.copy()
trial_plot_show = trial_plot.copy()
if stim_radius:
frame = frame.copy()
loom_frame = frame.copy()
loom_arena = video_arena.copy()
loom_arena2 = trial_plot.copy()
if self.stim_type == 'visual':
# for actual loom
stimulus_location = tuple(self.coordinates['center_body_location'][:, self.stim_frame - 1].astype(np.uint16))
cv2.circle(loom_frame, stimulus_location, stim_radius, 100, -1)
cv2.circle(loom_arena, stimulus_location, stim_radius, (100,100,100), -1)
else:
center = (int(frame.shape[1] / 2), int(frame.shape[0] / 2))
if shape == 'circle':
cv2.circle(loom_frame, center, stim_radius, 200, 12)
cv2.circle(loom_arena, center, stim_radius, (200, 200, 200), 12)
cv2.circle(loom_arena2, center, stim_radius, (200, 200, 200), 12)
elif shape == 'square':
cv2.rectangle(loom_frame, tuple([c+stim_radius for c in center]), tuple([c-stim_radius for c in center]), 200, 12)
cv2.rectangle(loom_arena, tuple([c+stim_radius for c in center]), tuple([c-stim_radius for c in center]), (200, 200, 200), 12)
cv2.rectangle(loom_arena2, tuple([c+stim_radius for c in center]), tuple([c-stim_radius for c in center]), (200, 200, 200), 12)
alpha = .3
cv2.addWeighted(frame, alpha, loom_frame, 1 - alpha, 0, frame)
cv2.addWeighted(video_arena, alpha, loom_arena, 1 - alpha, 0, session_trials_plot_show)
cv2.addWeighted(trial_plot, alpha, loom_arena2, 1 - alpha, 0, trial_plot_show)
# invert colors for opencv display
arena_with_prev_trials_show = cv2.cvtColor(self.arena_with_prev_trials, cv2.COLOR_BGR2RGB)
video_arena_show = cv2.cvtColor(video_arena, cv2.COLOR_BGR2RGB)
# put minute of stimulation in clip
# stim_minute = str(int(np.round(self.stim_frame / 60 / 30))) + "'"
# frame = frame.copy()
# cv2.putText(frame, stim_minute, (20, 50), 0, 1, (255, 255, 255), thickness=2)
# display current frames
cv2.imshow(self.session_videoname, frame);
cv2.imshow(self.session_videoname + ' DLC', video_arena_show)
if cv2.waitKey(1) & 0xFF == ord('q'): break
# write current frame to video
video.write(frame); self.session_video.write(frame)
video_dlc.write(video_arena_show); self.session_video_dlc.write(video_arena_show)
# end video
if frame_num >= self.end_frame: break
# wrap up
vid.release(); video.release(); video_dlc.release()
# draw red silhouette for previous trial arena
cv2.drawContours(self.arena_with_prev_trials, contours, 0, contour_color, thickness=-1)
# cv2.drawContours(self.arena_with_prev_trials, contours, 0, (0,0,0), thickness=1)
# draw purple silhouette for wall change
if (self.trial_type == 1 or self.trial_type == -1):
try:
cv2.drawContours(video_arena, contours_wall_change, 0, (220, 0, 220), thickness=-1)
cv2.drawContours(trial_plot, contours_wall_change, 0, (220, 0, 220), thickness=-1)
except:
print('Obstacle change not picked up for' + self.videoname)
# save trial images
imageio.imwrite(os.path.join(self.save_folder, self.videoname + ' image.tif'), trial_plot)
imageio.imwrite(os.path.join(self.save_folder, self.videoname + ' image with history.tif'), video_arena)
# after the last trial, save the session workspace image
if self.trial_num == self.number_of_trials:
# make all the trials the last frame of the DLC video
self.session_video.write(self.arena_with_prev_trials)
# save the all trials image
scipy.misc.imsave(os.path.join(self.summary_folder, self.videoname + ' image (all trials).tif'), self.arena_with_prev_trials)
# wrap up
self.session_video.release()
self.session_video_dlc.release()
cv2.destroyAllWindows()
# cv2.drawContours(trial_plot_show, contours, 0, (255, 255, 255), thickness=1)
def raw_escape_video(processing):
''' Generate and save peri-stimulus video clip '''
# set up border colors
pre_stim_color = [0]
post_stim_color = [200]
border_size = 40
# open the behaviour video
vid = cv2.VideoCapture(processing.video_path)
# set up the trial clip for saving
video = cv2.VideoWriter(os.path.join(processing.save_folder,videoname+'.mp4'), processing.fourcc, processing.fps,
(processing.width, processing.height), False)
vid.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
# set up fisheye correction
if registration:
maps = np.load(registration[3]); map1 = maps[:, | |
<gh_stars>0
from http import HTTPStatus
from typing import List, Optional
from fastapi import APIRouter, Depends, Header, Query, Response
from sqlalchemy.orm import Session
import mlrun.api.crud
import mlrun.api.utils.auth.verifier
import mlrun.api.utils.singletons.project_member
import mlrun.errors
import mlrun.feature_store
from mlrun import v3io_cred
from mlrun.api import schemas
from mlrun.api.api import deps
from mlrun.api.api.utils import log_and_raise, parse_reference
from mlrun.data_types import InferOptions
from mlrun.datastore.targets import get_default_prefix_for_target
from mlrun.feature_store.api import RunConfig, ingest
from mlrun.model import DataSource, DataTargetBase
router = APIRouter()
@router.post("/projects/{project}/feature-sets", response_model=schemas.FeatureSet)
def create_feature_set(
project: str,
feature_set: schemas.FeatureSet,
versioned: bool = True,
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.singletons.project_member.get_project_member().ensure_project(
db_session, project, auth_info=auth_info
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_set,
project,
feature_set.metadata.name,
mlrun.api.schemas.AuthorizationAction.create,
auth_info,
)
feature_set_uid = mlrun.api.crud.FeatureStore().create_feature_set(
db_session, project, feature_set, versioned,
)
return mlrun.api.crud.FeatureStore().get_feature_set(
db_session,
project,
feature_set.metadata.name,
feature_set.metadata.tag or "latest",
feature_set_uid,
)
@router.put(
"/projects/{project}/feature-sets/{name}/references/{reference}",
response_model=schemas.FeatureSet,
)
def store_feature_set(
project: str,
name: str,
reference: str,
feature_set: schemas.FeatureSet,
versioned: bool = True,
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.singletons.project_member.get_project_member().ensure_project(
db_session, project, auth_info=auth_info
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_set,
project,
name,
mlrun.api.schemas.AuthorizationAction.store,
auth_info,
)
tag, uid = parse_reference(reference)
uid = mlrun.api.crud.FeatureStore().store_feature_set(
db_session, project, name, feature_set, tag, uid, versioned,
)
return mlrun.api.crud.FeatureStore().get_feature_set(
db_session, project, feature_set.metadata.name, tag, uid,
)
@router.patch("/projects/{project}/feature-sets/{name}/references/{reference}")
def patch_feature_set(
project: str,
name: str,
feature_set_update: dict,
reference: str,
patch_mode: schemas.PatchMode = Header(
schemas.PatchMode.replace, alias=schemas.HeaderNames.patch_mode
),
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_set,
project,
name,
mlrun.api.schemas.AuthorizationAction.update,
auth_info,
)
tag, uid = parse_reference(reference)
mlrun.api.crud.FeatureStore().patch_feature_set(
db_session, project, name, feature_set_update, tag, uid, patch_mode,
)
return Response(status_code=HTTPStatus.OK.value)
@router.get(
"/projects/{project}/feature-sets/{name}/references/{reference}",
response_model=schemas.FeatureSet,
)
def get_feature_set(
project: str,
name: str,
reference: str,
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
tag, uid = parse_reference(reference)
feature_set = mlrun.api.crud.FeatureStore().get_feature_set(
db_session, project, name, tag, uid
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_set,
project,
name,
mlrun.api.schemas.AuthorizationAction.read,
auth_info,
)
return feature_set
@router.delete("/projects/{project}/feature-sets/{name}")
@router.delete("/projects/{project}/feature-sets/{name}/references/{reference}")
def delete_feature_set(
project: str,
name: str,
reference: str = None,
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_set,
project,
name,
mlrun.api.schemas.AuthorizationAction.delete,
auth_info,
)
tag = uid = None
if reference:
tag, uid = parse_reference(reference)
mlrun.api.crud.FeatureStore().delete_feature_set(
db_session, project, name, tag, uid
)
return Response(status_code=HTTPStatus.NO_CONTENT.value)
@router.get(
"/projects/{project}/feature-sets", response_model=schemas.FeatureSetsOutput
)
def list_feature_sets(
project: str,
name: str = None,
state: str = None,
tag: str = None,
entities: List[str] = Query(None, alias="entity"),
features: List[str] = Query(None, alias="feature"),
labels: List[str] = Query(None, alias="label"),
partition_by: schemas.FeatureStorePartitionByField = Query(
None, alias="partition-by"
),
rows_per_partition: int = Query(1, alias="rows-per-partition", gt=0),
partition_sort_by: schemas.SortField = Query(None, alias="partition-sort-by"),
partition_order: schemas.OrderType = Query(
schemas.OrderType.desc, alias="partition-order"
),
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_permissions(
project, mlrun.api.schemas.AuthorizationAction.read, auth_info,
)
feature_sets = mlrun.api.crud.FeatureStore().list_feature_sets(
db_session,
project,
name,
tag,
state,
entities,
features,
labels,
partition_by,
rows_per_partition,
partition_sort_by,
partition_order,
)
feature_sets = mlrun.api.utils.auth.verifier.AuthVerifier().filter_project_resources_by_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_set,
feature_sets.feature_sets,
lambda feature_set: (feature_set.metadata.project, feature_set.metadata.name,),
auth_info,
)
return mlrun.api.schemas.FeatureSetsOutput(feature_sets=feature_sets)
@router.get(
"/projects/{project}/feature-sets/{name}/tags",
response_model=schemas.FeatureSetsTagsOutput,
)
def list_feature_sets_tags(
project: str,
name: str,
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
if name != "*":
raise mlrun.errors.MLRunInvalidArgumentError(
"Listing a specific feature set tags is not supported, set name to *"
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_permissions(
project, mlrun.api.schemas.AuthorizationAction.read, auth_info,
)
tag_tuples = mlrun.api.crud.FeatureStore().list_feature_sets_tags(
db_session, project,
)
feature_set_name_to_tag = {tag_tuple[1]: tag_tuple[2] for tag_tuple in tag_tuples}
allowed_feature_set_names = mlrun.api.utils.auth.verifier.AuthVerifier().filter_project_resources_by_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_set,
list(feature_set_name_to_tag.keys()),
lambda feature_set_name: (project, feature_set_name,),
auth_info,
)
tags = {
tag_tuple[2]
for tag_tuple in tag_tuples
if tag_tuple[1] in allowed_feature_set_names
}
return mlrun.api.schemas.FeatureSetsTagsOutput(tags=list(tags))
def _has_v3io_path(data_source, data_targets, feature_set):
paths = []
# If no data targets received, then use targets from the feature-set spec. In case it's empty as well, use
# default targets (by calling set_targets())
if not data_targets:
if not feature_set.spec.targets:
feature_set.set_targets()
data_targets = feature_set.spec.targets
if data_targets:
for target in data_targets:
# If the target does not have a path (i.e. default target), then retrieve the default path from config.
paths.append(target.path or get_default_prefix_for_target(target.kind))
source = data_source or feature_set.spec.source
if source:
paths.append(source.path)
return any(
path and (path.startswith("v3io://") or path.startswith("v3ios://"))
for path in paths
)
@router.post(
"/projects/{project}/feature-sets/{name}/references/{reference}/ingest",
response_model=schemas.FeatureSetIngestOutput,
status_code=HTTPStatus.ACCEPTED.value,
)
def ingest_feature_set(
project: str,
name: str,
reference: str,
ingest_parameters: Optional[
schemas.FeatureSetIngestInput
] = schemas.FeatureSetIngestInput(),
username: str = Header(None, alias="x-remote-user"),
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_set,
project,
name,
mlrun.api.schemas.AuthorizationAction.update,
auth_info,
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.run,
project,
"",
mlrun.api.schemas.AuthorizationAction.create,
auth_info,
)
data_source = data_targets = None
if ingest_parameters.source:
data_source = DataSource.from_dict(ingest_parameters.source.dict())
if data_source.schedule:
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.schedule,
project,
"",
mlrun.api.schemas.AuthorizationAction.create,
auth_info,
)
tag, uid = parse_reference(reference)
feature_set_record = mlrun.api.crud.FeatureStore().get_feature_set(
db_session, project, name, tag, uid
)
feature_set = mlrun.feature_store.FeatureSet.from_dict(feature_set_record.dict())
if feature_set.spec.function and feature_set.spec.function.function_object:
function = feature_set.spec.function.function_object
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.function,
function.metadata.project,
function.metadata.name,
mlrun.api.schemas.AuthorizationAction.read,
auth_info,
)
# Need to override the default rundb since we're in the server.
feature_set._override_run_db(db_session)
if ingest_parameters.targets:
data_targets = [
DataTargetBase.from_dict(data_target.dict())
for data_target in ingest_parameters.targets
]
run_config = RunConfig(
owner=username,
credentials=mlrun.model.Credentials(ingest_parameters.credentials.access_key),
)
# Try to deduce whether the ingest job will need v3io mount, by analyzing the paths to the source and
# targets. If it needs it, apply v3io mount to the run_config. Note that the access-key and username are
# user-context parameters, we cannot use the api context.
if _has_v3io_path(data_source, data_targets, feature_set):
access_key = auth_info.data_session
if not access_key or not username:
log_and_raise(
HTTPStatus.BAD_REQUEST.value,
reason="Request needs v3io access key and username in header",
)
run_config = run_config.apply(v3io_cred(access_key=access_key, user=username))
infer_options = ingest_parameters.infer_options or InferOptions.default()
run_params = ingest(
feature_set,
data_source,
data_targets,
infer_options=infer_options,
return_df=False,
run_config=run_config,
)
# ingest may modify the feature-set contents, so returning the updated feature-set.
result_feature_set = schemas.FeatureSet(**feature_set.to_dict())
return schemas.FeatureSetIngestOutput(
feature_set=result_feature_set, run_object=run_params.to_dict()
)
@router.get("/projects/{project}/features", response_model=schemas.FeaturesOutput)
def list_features(
project: str,
name: str = None,
tag: str = None,
entities: List[str] = Query(None, alias="entity"),
labels: List[str] = Query(None, alias="label"),
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_permissions(
project, mlrun.api.schemas.AuthorizationAction.read, auth_info,
)
features = mlrun.api.crud.FeatureStore().list_features(
db_session, project, name, tag, entities, labels
)
features = mlrun.api.utils.auth.verifier.AuthVerifier().filter_project_resources_by_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature,
features.features,
lambda feature_list_output: (
feature_list_output.feature_set_digest.metadata.project,
feature_list_output.feature.name,
),
auth_info,
)
return mlrun.api.schemas.FeaturesOutput(features=features)
@router.get("/projects/{project}/entities", response_model=schemas.EntitiesOutput)
def list_entities(
project: str,
name: str = None,
tag: str = None,
labels: List[str] = Query(None, alias="label"),
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_permissions(
project, mlrun.api.schemas.AuthorizationAction.read, auth_info,
)
entities = mlrun.api.crud.FeatureStore().list_entities(
db_session, project, name, tag, labels
)
entities = mlrun.api.utils.auth.verifier.AuthVerifier().filter_project_resources_by_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.entity,
entities.entities,
lambda entity_list_output: (
entity_list_output.feature_set_digest.metadata.project,
entity_list_output.entity.name,
),
auth_info,
)
return mlrun.api.schemas.EntitiesOutput(entities=entities)
@router.post(
"/projects/{project}/feature-vectors", response_model=schemas.FeatureVector
)
def create_feature_vector(
project: str,
feature_vector: schemas.FeatureVector,
versioned: bool = True,
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.singletons.project_member.get_project_member().ensure_project(
db_session, project, auth_info=auth_info
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_vector,
project,
feature_vector.metadata.name,
mlrun.api.schemas.AuthorizationAction.create,
auth_info,
)
_verify_feature_vector_features_permissions(
auth_info, project, feature_vector.dict()
)
feature_vector_uid = mlrun.api.crud.FeatureStore().create_feature_vector(
db_session, project, feature_vector, versioned,
)
return mlrun.api.crud.FeatureStore().get_feature_vector(
db_session,
project,
feature_vector.metadata.name,
feature_vector.metadata.tag or "latest",
feature_vector_uid,
)
@router.get(
"/projects/{project}/feature-vectors/{name}/references/{reference}",
response_model=schemas.FeatureVector,
)
def get_feature_vector(
project: str,
name: str,
reference: str,
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
tag, uid = parse_reference(reference)
feature_vector = mlrun.api.crud.FeatureStore().get_feature_vector(
db_session, project, name, tag, uid
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_vector,
project,
name,
mlrun.api.schemas.AuthorizationAction.read,
auth_info,
)
_verify_feature_vector_features_permissions(
auth_info, project, feature_vector.dict()
)
return feature_vector
@router.get(
"/projects/{project}/feature-vectors", response_model=schemas.FeatureVectorsOutput
)
def list_feature_vectors(
project: str,
name: str = None,
state: str = None,
tag: str = None,
labels: List[str] = Query(None, alias="label"),
partition_by: schemas.FeatureStorePartitionByField = Query(
None, alias="partition-by"
),
rows_per_partition: int = Query(1, alias="rows-per-partition", gt=0),
partition_sort_by: schemas.SortField = Query(None, alias="partition-sort-by"),
partition_order: schemas.OrderType = Query(
schemas.OrderType.desc, alias="partition-order"
),
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_permissions(
project, mlrun.api.schemas.AuthorizationAction.read, auth_info,
)
feature_vectors = mlrun.api.crud.FeatureStore().list_feature_vectors(
db_session,
project,
name,
tag,
state,
labels,
partition_by,
rows_per_partition,
partition_sort_by,
partition_order,
)
feature_vectors = mlrun.api.utils.auth.verifier.AuthVerifier().filter_project_resources_by_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_vector,
feature_vectors.feature_vectors,
lambda feature_vector: (
feature_vector.metadata.project,
feature_vector.metadata.name,
),
auth_info,
)
for feature_vector in feature_vectors:
_verify_feature_vector_features_permissions(
auth_info, project, feature_vector.dict()
)
return mlrun.api.schemas.FeatureVectorsOutput(feature_vectors=feature_vectors)
@router.get(
"/projects/{project}/feature-vectors/{name}/tags",
response_model=schemas.FeatureVectorsTagsOutput,
)
def list_feature_vectors_tags(
project: str,
name: str,
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
if name != "*":
raise mlrun.errors.MLRunInvalidArgumentError(
"Listing a specific feature vector tags is not supported, set name to *"
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_permissions(
project, mlrun.api.schemas.AuthorizationAction.read, auth_info,
)
tag_tuples = mlrun.api.crud.FeatureStore().list_feature_vectors_tags(
db_session, project,
)
feature_vector_name_to_tag = {
tag_tuple[1]: tag_tuple[2] for tag_tuple in tag_tuples
}
allowed_feature_vector_names = mlrun.api.utils.auth.verifier.AuthVerifier().filter_project_resources_by_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_vector,
list(feature_vector_name_to_tag.keys()),
lambda feature_vector_name: (project, feature_vector_name,),
auth_info,
)
tags = {
tag_tuple[2]
for tag_tuple in tag_tuples
if tag_tuple[1] in allowed_feature_vector_names
}
return mlrun.api.schemas.FeatureVectorsTagsOutput(tags=list(tags))
@router.put(
"/projects/{project}/feature-vectors/{name}/references/{reference}",
response_model=schemas.FeatureVector,
)
def store_feature_vector(
project: str,
name: str,
reference: str,
feature_vector: schemas.FeatureVector,
versioned: bool = True,
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.singletons.project_member.get_project_member().ensure_project(
db_session, project, auth_info=auth_info
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_vector,
project,
name,
mlrun.api.schemas.AuthorizationAction.update,
auth_info,
)
_verify_feature_vector_features_permissions(
auth_info, project, feature_vector.dict()
)
tag, uid = parse_reference(reference)
uid = mlrun.api.crud.FeatureStore().store_feature_vector(
db_session, project, name, feature_vector, tag, uid, versioned,
)
return mlrun.api.crud.FeatureStore().get_feature_vector(
db_session, project, name, tag, uid
)
@router.patch("/projects/{project}/feature-vectors/{name}/references/{reference}")
def patch_feature_vector(
project: str,
name: str,
feature_vector_patch: dict,
reference: str,
patch_mode: schemas.PatchMode = Header(
schemas.PatchMode.replace, alias=schemas.HeaderNames.patch_mode
),
auth_info: mlrun.api.schemas.AuthInfo = Depends(deps.authenticate_request),
db_session: Session = Depends(deps.get_db_session),
):
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.feature_vector,
project,
name,
mlrun.api.schemas.AuthorizationAction.update,
auth_info,
)
_verify_feature_vector_features_permissions(
auth_info, project, feature_vector_patch
| |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Function:
Implementation approach of Noisy Input Gaussian Processing (NIGP); also the Paper implementation :
"Gaussian Process Training with Input Noise"
Direct calculate the posterior mean and covariance of GP, even the posterior distribution is unknown
Parameters:
var_x: input noise variance
var_y: output noise variance
varf : kernal hyperparameter sigma_f
l : kernal hyperparameter lengthscale or parameter set
Figure 3 with 2 subfigure in PAC-NIGP
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import math
from scipy.spatial.distance import cdist, pdist, squareform
from scipy.optimize import minimize
def plot_gp(mu, std, X, X_train=None, Y_train=None, title='NIGP'): # samples=[]
X = X.ravel()
mu = mu.ravel()
# uncertainty = 1.96 * np.sqrt(np.diag(cov))
uncertainty = 1.96 * std
plt.fill_between(X, mu + uncertainty, mu - uncertainty, alpha=0.1)
plt.plot(X, mu, label='Estimation')
# for i, sample in enumerate(samples):
# plt.plot(X, sample, lw=1, ls='--', label=f'Sample {i + 1}')
if X_train is not None:
plt.plot(Xcv, sincsig(Xcv), 'rx', label='Real data')
plt.legend()
plt.title(title)
plt.show()
class GPRegressor:
# l - Correlation length. Scalar or array of length num_features in X
# varf - Signal variance.
# normalize_y - Subtract mean of y from y if True. Often a good idea since
# we are modeling a zero-mean GP.
# num_restarts_hyper - Number of randomly initialized optimizations of the hyperparameters,
# that should be performed. More than one is usually a good idea since
# the log_marinal_likelihood often has local maxima.
#
def __init__(self, l=1.0, varf=1.0, normalize_y=True, num_restarts_hyper=1):
self.varf = varf
self.normalize_y = normalize_y
self.num_restarts = num_restarts_hyper
self.l = np.array(l)
# X - Input prediction data
# return_std - Returns GP std.dev. if True
# np.zeros_like(M): create zero-matrix with the same shape as M
def predict(self, X, return_std=False):
l = self.l
# [K2]: k(x, X); [self.pred_vec]: K(X,X)+sigma_y*I + sigma_x_regularization
self.K2 = self.kernel(X, self.X_train, np.zeros_like(X), self.var_x, l, self.varf)
# k(x,X) * inv( K(X,X)+sigma_y*I + sigma_x_regul ) * y
mean = np.dot(self.K2, self.pred_vec) + self.mu
if return_std:
# See equation (7) in paper NIGP:
std2 = np.sqrt(np.diag(
self.autokernel(X, np.zeros_like(X), l, self.varf)
- np.dot(self.K2, np.dot(self.pred_fac, self.K2.T)) ))
return mean, std2
else:
return mean, 0.0
# kernel and autokernel same shape with different data
def kernel(self, X1, X2, var_x1, var_x2, l, varf): # K(x_star,X) kernal func
# Equation 9 in NIGPf
# squared exponential kernel with Automatic Relevance Determination
tmp = 0.0
tmp2 = 1.0
l = l * np.ones(len(self.X_train[0, :]))
for i in range(0, len(X1[0, :])):
l2 = l[i] * l[i] # !
d1 = cdist(X1[:, i].reshape(-1, 1), X2[:, i].reshape(-1, 1), metric='sqeuclidean')
d2 = cdist(var_x1[:, i].reshape(-1, 1), -var_x2[:, i].reshape(-1, 1), metric='euclidean')
tmp += d1 / (l2 + d2)
tmp2 *= (1.0 + d2 / l2)
return varf * np.power(tmp2, -0.5) * np.exp(-0.5 * tmp)
def autokernel(self, X, var_x, l, varf): # (self.X_train, self.var_x, l, varf)
tmp = 0.0
tmp2 = 1.0
l = l * np.ones(len(self.X_train[0, :])) # diagonal matrix of the kernal
for i in range(0, len(X[0, :])):
l2 = l[i] * l[i] # Lambda : square of lengthscale of kernal
d1 = cdist(X[:, i].reshape(-1, 1), X[:, i].reshape(-1, 1), metric='sqeuclidean') # ||x-x'||^2_2 (N*N)
d2 = cdist(var_x[:, i].reshape(-1, 1), -var_x[:, i].reshape(-1, 1), metric='euclidean') # (N*N) Sigma_x variance of input
tmp += d1 / (l2 + d2) # (N*N)
tmp2 *= (1.0 + d2 / l2) # (N*N) sigma_f^2 * sqrt[Sigma_x in v(Lambda) + I] * exp(-0.5*(x_i-x_j))
return varf * np.power(tmp2, -0.5) * np.exp(-0.5 * tmp)
# y_train - Output data (num_samples)
# var_x - Variance in input points x
# var_y - Variance in output points y
# l_bounds - Bounds for the hyperparameters.
# Array size (3x2) or ((2+num_features)x2).
# l[0] is varf(signal variance), l[1] is noise_variance
# and l[2::] is correlation length(s) <---> res here?
# None means using the supplied hyperparameters.
def fit(self, X_train, y_train, var_x, var_y, l_bounds=None):
if self.normalize_y:
self.mu = np.mean(y_train, 0)
else:
self.mu = 0.0
self.X_train = X_train
self.y_train = (y_train - self.mu)
#
if np.iterable(var_x):
self.var_x = var_x
else:
self.var_x = var_x * np.ones_like(X_train)
self.var_y = var_y
# Fit hyperparameters by maximizing log marginal likelihood.
if l_bounds is not None:
bounds = []
for i in range(0, len(l_bounds)):
bounds.append(l_bounds[i])
best_f = 1e6
# repeat many times to get better parameters
for j in range(0, self.num_restarts):
loglb = np.log10(l_bounds[:, 0])
loghb = np.log10(l_bounds[:, 1])
l0 = loglb + (loghb - loglb) * np.random.random(size=loglb.shape)
l0 = 10.0 ** l0
res = minimize(self.neg_log_marginal_likelihood, l0,
method='l-bfgs-b',
bounds=bounds,
tol=1e-12,
options={'disp': False, 'eps': 0.001})
# res: final optimized parameters; l0 is the initialize parameter
if res['fun'] < best_f:
self.varf = res['x'][0] # kernal hyper-parameter
self.alpha = res['x'][1] # varn in nlml function
self.l = res['x'][2::] # lengthscale parameter for kernal
self.opt_params = res['x'] #
print("iter: " + str(j) + ". params: " + "Output variance:" + "varf: " + str(self.varf) +
", alpha: " + str(self.alpha) + ", l: " + str(self.l))
self.var_y += self.alpha
# Calculate factors needed for prediction.
# K1 = K(X,X)
self.K1 = self.autokernel(self.X_train, self.var_x, self.l, self.varf)
# self.pred_fac:
self.pred_fac = np.linalg.pinv(self.K1 + np.identity(len(self.K1[:, 0])) * self.var_y)
# self.pred_vec:
self.pred_vec = np.dot(self.pred_fac, self.y_train)
def neg_log_marginal_likelihood(self, l):
# This nlml three hyperparameters: SEE (2.31) in book GPML
varf = l[0] # output variance
varn = l[1] # input noise introduced variance, total variance
l = l[2::] # lengthscale parameter for kernal
# calculate the kernal matrix: K(X,X) + sigma^2 * I + varn'
# varn or l[1]: (slope of mean func)^T * Sigma_x * (slope of mean func)
K = self.autokernel(self.X_train, self.var_x, l, varf) \
+ np.identity(len(self.X_train[:, 0])) * (self.var_y + varn)
Kinv = np.linalg.pinv(K) # Calculate the pseudo-inverse of a matrix
# print('varf:', varf, 'varn:', varn, 'lenghtscale:', l)
return 0.5 * np.dot(self.y_train, np.dot(Kinv, self.y_train)) + 0.5 * np.log(np.linalg.det(K)) \
+ 0.5 * len(K[:, 0]) * np.log(2 * math.pi)
## Example insipired from 'Learning Gaussian Process Models from Uncertain Data', Dallaire.
if __name__ == "__main__":
# def sincsig(x):
# return (x >= 0) * np.sinc(x / math.pi) + (x < 0) * (0.5 * (1 + np.exp(-10 * x - 5)) ** (-1) + 0.5)
def sincsig(x):
return np.sin(x)
np.random.seed(9527)
Fig_path = None
# std: covariance of noisy_X and noisy_y
noise_y = 0.1 # Output noisy std
noise_x = 0.4 # Iutput noisy std
X_train = np.linspace(-10, 10, 150).reshape(-1, 1)
Y_train = np.sin(X_train) + noise_y * np.random.randn(*X_train.shape)
X_train_obs = X_train + noise_x * np.random.randn(*X_train.shape)
X_train = X_train_obs
# X_train = np.random.random((150, 1)) * 20.0 - 10.0 # generate 150 data points from interval [-10, 10]
y_train = sincsig(X_train[:, 0])
# y_train = sincsig(X_train[:, 0])
X_std = np.random.random(X_train.shape) * 0.0 + noise_x
y_std = noise_y * np.ones_like(y_train)
y_train += np.random.normal(0.0, y_std)
X_train += np.random.normal(0.0, X_std)
# create data by constant interval
X_test = np.linspace(-10, 10, 100).reshape(-1, 1)
Y_test = np.sin(X_test)
Xcv = np.linspace(-10, 10, 100).reshape(-1, 1)
ycv = sincsig(Xcv[:, 0])
# ************************** GPR ************************ #
print('Start standard GP')
l_bounds = np.array([[0.01, 0.3], [0.02, 0.2], [0.1, 5.0]])
gp = GPRegressor(1, 1, num_restarts_hyper=1)
gp.fit(X_train, y_train, 0.0, 0.0, l_bounds=l_bounds)
yp, std = gp.predict(Xcv, True)
print('End standard GP')
# ************************** GPR plot ************************ #
plt.figure(figsize=(6, 4))
plt.style.use('bmh')
fontsize = 11
fontfamily = 'Times New Roman'
matplotlib.rcParams['font.size'] = fontsize
matplotlib.rcParams['font.family'] = fontfamily
plt.fill_between(Xcv[:, 0], yp - 1.96 * std, yp + 1.96 * std, alpha=0.2)
plt.plot(Xcv[:, 0], yp, '-', label='Estimation')
plt.plot(Xcv[:, 0], sincsig(Xcv), '--', label='Real data')
# plt.legend(['With input noisy', 'Without input noisy'], loc='best')
plt.legend(loc='best')
plt.xlabel('Test input')
plt.ylabel('Output')
# plt.savefig(fname=Fig_path+"Reprod_method1_GPR_4_noisy_input.pdf", format="pdf")
plt.show()
# ************************** NIGP ************************ #
print('Start NIGP')
l_bounds = np.array([[0.01, 0.3], [0.01, 0.1], [0.1, 5.0]])
gp = GPRegressor(1, 1, num_restarts_hyper=1)
gp.fit(X_train, y_train, X_std ** 2, 0.0, l_bounds=l_bounds)
yp, std = gp.predict(Xcv, True)
print('End NIGP')
# ************************** NIGPR plot ************************ #
plt.figure(figsize=(6, 4))
plt.style.use('bmh')
fontsize = 11
fontfamily = 'Times New Roman'
matplotlib.rcParams['font.size'] = fontsize
matplotlib.rcParams['font.family'] = fontfamily
plt.fill_between(Xcv[:, 0], yp - 1.96 * std, yp + 1.96 * std, alpha=0.2)
plt.plot(Xcv[:, 0], yp, '-', label='Estimation')
plt.plot(Xcv[:, 0], sincsig(Xcv), '--', label='Real data')
# plt.legend(['With | |
<= header_size): continue
star_X_coord = self.find_star_info(line, star_X_coord_column)
star_Y_coord = self.find_star_info(line, star_Y_coord_column)
## avoid empty lines by checking if the X and Y coordinates exist
if not star_X_coord:
continue
if not star_Y_coord:
continue
counter += 1
star_coord = (int(float(star_X_coord)), int(float(star_Y_coord)))
img_coord = self.star2gif(star_coord, self.get_scale_factor(PARAMS['mrc_dimensions'], PARAMS['img_dimensions']))
image_coordinates[ img_coord ] = star_coord # data are linked in this way to avoid transformation data loss
print(">> %s particles read from star file %s" % (counter, starfile) )
## update global dictionary after parsing is complete
PARAMS['img_coords'] = image_coordinates
return
def update_input_widgets(self):
""" Updates the input widgets on the main GUI to take on the values of the global dictionary.
Mainly used after loading a new settings file.
"""
global PARAMS
mrc_pixel_size_x = PARAMS['mrc_dimensions'][0]
mrc_pixel_size_y = PARAMS['mrc_dimensions'][1]
box_size = PARAMS['box_size']
angpix = PARAMS['angpix']
self.input_mrc_dimensions.delete(0, tk.END)
self.input_mrc_dimensions.insert(0, "%s, %s" % (mrc_pixel_size_x, mrc_pixel_size_y) )
self.input_mrc_box_size.delete(0, tk.END)
self.input_mrc_box_size.insert(0, box_size)
self.input_angpix.delete(0, tk.END)
self.input_angpix.insert(0, angpix)
return
def save_settings(self):
""" Write out a settings file for ease of use on re-launching the program in the same directory
"""
global PARAMS, brush_size, current_im_data
image_list = PARAMS['img_list']
n = PARAMS['index']
mrc_pixel_size_x = PARAMS['mrc_dimensions'][0]
mrc_pixel_size_y = PARAMS['mrc_dimensions'][1]
angpix = PARAMS['angpix']
box_size= PARAMS['box_size']
save_fname = '.em_dataset_curator.config'
## sanity check a file is loaded into buffer, otherwise no reason to save settings
try:
current_im_data.any()
except:
print("Abort autopick :: Image not loaded")
return
current_img = image_list[n] # os.path.splitext(image_list[n])[0]
## save a settings file only if a project is actively open, as assessed by image_list being populated
if len(image_list) > 0:
with open(save_fname, 'w') as f :
f.write("## Last used settings for em_dataset_curator.py\n")
f.write("mrc_pixel_size_x %s\n" % mrc_pixel_size_x)
f.write("mrc_pixel_size_y %s\n" % mrc_pixel_size_y)
f.write("angpix %s\n" % angpix)
f.write("brush_size %s\n" % brush_size)
f.write("img_on_save %s\n" % current_img)
f.write("box_size %s\n" % box_size)
print(" >> Saved current settings to '%s'" % save_fname)
def load_settings(self):
""" On loadup, search the directory for input files and load them into memory automatically
>> marked_imgs.txt :: load these filenames into the 'marked_imgs' list variable
"""
global PARAMS, brush_size
print("============================")
print(" load_settings ")
print("----------------------------")
## reset marked_imgs global variable
marked_imgs = []
## repopulate the global marked_imgs variable based on the file 'marked_imgs.txt', if present
if os.path.exists('marked_imgs.txt'):
## update marked file list with file in directory
with open('marked_imgs.txt', 'r') as f :
for line in f:
if not line.strip() in marked_imgs:
marked_imgs.append(line.strip())
PARAMS['marked_imgs'] = marked_imgs
settingsfile = '.em_dataset_curator.config'
if os.path.exists(settingsfile):
## update marked file list with file in directory
with open(settingsfile, 'r') as f :
for line in f:
line2list = line.split()
if not '#' in line2list[0]: ## ignore comment lines
if line2list[0] == 'mrc_pixel_size_x':
mrc_pixel_size_x = int(line2list[1])
# PARAMS['mrc_pixel_size_x'] = int(line2list[1])
elif line2list[0] == 'mrc_pixel_size_y':
mrc_pixel_size_y = int(line2list[1])
# PARAMS['mrc_pixel_size_y'] = int(line2list[1])
elif line2list[0] == 'angpix':
PARAMS['angpix'] = float(line2list[1])
elif line2list[0] == 'brush_size':
brush_size = int(line2list[1])
elif line2list[0] == 'img_on_save':
PARAMS['img_on_save'] = line2list[1]
elif line2list[0] == 'box_size':
PARAMS['box_size'] = int(line2list[1])
print(" box_size = %s" % PARAMS['box_size'])
## set the dimensions
PARAMS['mrc_dimensions'] = (mrc_pixel_size_x, mrc_pixel_size_y)
## update the widgets with the loaded values
self.input_mrc_box_size.delete(0, tk.END)
self.input_mrc_box_size.insert(0, PARAMS['box_size'])
self.input_angpix.delete(0, tk.END)
self.input_angpix.insert(0, PARAMS['angpix'])
self.input_mrc_dimensions.delete(0, tk.END)
self.input_mrc_dimensions.insert(0, "%s, %s" % (PARAMS['mrc_dimensions'][0], PARAMS['mrc_dimensions'][1]))
# extract file information from selection
file_name = PARAMS['img_on_save']
print("File selected: "+ file_name)
# erase any previous image list and repopulate it with the new directory
image_list = []
image_list = self.images_in_dir('.')
PARAMS['img_list'] = image_list
# find the index of the selected image in the new list
try:
PARAMS['index'] = image_list.index(file_name)
except:
print(" ERROR: Settings file points to image that does not exist in working directory! Resetting index to 0")
## redraw canvas items with updated global values as the given image index
self.load_img()
return
def new_box_size(self):
global PARAMS
mrc_pixel_size_x = PARAMS['mrc_dimensions'][0]
mrc_pixel_size_y = PARAMS['mrc_dimensions'][1]
img_pixel_size_x = PARAMS['img_dimensions'][0]
angpix = PARAMS['angpix']
user_input = self.input_mrc_box_size.get().strip()
temp = re.findall(r'\d+', user_input)
res = list(map(int, temp))
## kill function if no entry is given or if value is not even
if not len(res) == 1 or not isinstance(res[0], int) or not res[0] > 0:
self.input_mrc_box_size.delete(0, tk.END)
self.input_mrc_box_size.insert(0, "ang boxsize")
return
elif not (res[0] % 2 == 0): # check if value is even
self.input_mrc_box_size.delete(0, tk.END)
self.input_mrc_box_size.insert(0, "value must be even")
return
## set the global box_size to the input field value
box_size = res[0]
## update the global dictionary
PARAMS['box_size'] = box_size
## calculate the image box size in pixels
scale_factor = mrc_pixel_size_x / img_pixel_size_x
img_angpix = angpix * scale_factor
img_box_size = int(box_size / img_angpix)
PARAMS['img_box_size'] = img_box_size
## redraw boxes by first deleting it then redrawing it
self.draw_image_coordinates()
## revert focus to main canvas
self.canvas.focus_set()
return
def new_mrc_dimensions(self):
""" Update the global variables for mrc_dimensions from user input in the main window.
Call a redraw of the image & boxes after.
"""
global PARAMS
n = PARAMS['index']
image_list = PARAMS['img_list']
file_dir = PARAMS['file_dir']
user_input = self.input_mrc_dimensions.get().strip()
temp = re.findall(r'\d+', user_input)
res = list(map(int, temp))
if not len(res) == 2:
self.input_mrc_dimensions.delete(0, tk.END)
self.input_mrc_dimensions.insert(0, "mrc_X, mrc_Y")
return
else:
mrc_pixel_size_x = res[0]
mrc_pixel_size_y = res[1]
PARAMS['mrc_dimensions'] = (mrc_pixel_size_x, mrc_pixel_size_y)
## check for an associated .star file with input coordinates to read
counter = 0
star_coordinate_file = ""
## find the matching star file if it exists
for fname in os.listdir(file_dir): ## iterate over the directory
base_image_name = os.path.splitext(image_list[n])[0] ## get the base name of the .GIF file
counter = 0
star_coordinate_file = ""
if base_image_name in fname and fname[-5:] == ".star": ## find any files that match the base .GIF file name and end in .STAR
counter += 1
star_coordinate_file = fname
if counter > 1: print(">>> WARNING: Multiple .STAR files found for this image (e.g. multiple files match: " + base_image_name + "*.star)")
## This program writes out ..._CURATED.star files, if we find one - use that over all other available .STAR files
if star_coordinate_file[-13:] == "_CURATED.star": break
## if a star file is found, load its coordinates
# print(" STAR FILE USED FOR COORDS = ", star_coordinate_file)
if (star_coordinate_file != ""):
self.read_coords_from_star(star_coordinate_file)
## redraw particle positions and boxsize with the new remapped data
self.draw_image_coordinates()
## revert focus to main canvas
self.canvas.focus_set()
return
def new_angpix(self):
""" Update the global 'angpix' variable from user input in the main window
"""
global PARAMS
user_input = self.input_angpix.get().strip()
try:
res = float(user_input)
angpix = res
PARAMS['angpix'] = angpix
## we need to recalculate the label for box size in angstroms
# self.box_size_ang.config(text="%s Angstroms" % (box_size * angpix))
except:
self.input_angpix.delete(0, tk.END)
self.input_angpix.insert(0, "angpix")
## redraw the picked coordinates
self.draw_image_coordinates()
## revert focus to main canvas
self.canvas.focus_set()
def MouseWheelHandler(self, event):
""" See: https://stackoverflow.com/questions/17355902/python-tkinter-binding-mousewheel-to-scrollbar
Tie the mousewheel to the brush size, draw a green square to show the user the final setting
"""
global brush_size, PARAMS
def delta(event):
if event.num == 5 or event.delta < 0:
return -2
return 2
brush_size += delta(event)
## avoid negative brush_size values
if brush_size <= 0:
brush_size = 0
## draw new brush size
x, y = event.x, event.y
x_max = int(x + brush_size/2)
x_min = int(x - brush_size/2)
y_max = int(y + brush_size/2)
y_min = int(y - brush_size/2)
brush = self.canvas.create_rectangle(x_max, y_max, x_min, y_min, outline="green2", tags='brush')
def check_if_two_ranges_intersect(self, x0, x1, y0, y1):
""" For two well-ordered ranges (x0 < x1; y0 < 1), check if there is any intersection between them.
See: https://stackoverflow.com/questions/3269434/whats-the-most-efficient-way-to-test-two-integer-ranges-for-overlap/25369187
An efficient way to quickly calculate if the erase brush hits a marked coordinate in the image.
"""
## sanity check input
if (x0 > x1):
print("ERROR: Incorrect range provided, x0 -> x1 == %s -> %s" % (x0, x1))
if y0 > y1:
print("ERROR: Incorrect range provided, y0 -> y1 == %s -> %s" % (y0, y1))
if x0 <= y1 and y0 <= x1:
return True
else:
return False
def delete_brush_cursor(self, event):
""" This function is tied to the <Motion> event.
It constantly checks if the condition RIGHT_MOUSE_PRESSED is True, in which case it runs the erase-coordinates algorithm
"""
global RIGHT_MOUSE_PRESSED, brush_size, PARAMS
image_coordinates = PARAMS['img_coords']
box_size = PARAMS['box_size']
n | |
<gh_stars>1-10
from __future__ import annotations
__all__ = ('StateBase', 'State', 'StateCollection')
import abc
import asyncio
import collections
import itertools
from typing import (
Any,
AsyncIterable,
AsyncIterator,
Awaitable,
Callable,
cast,
Collection,
Coroutine,
Final,
Generator,
Generic,
Iterator,
Literal,
Mapping,
NoReturn,
overload,
TypeVar,
Union,
)
from typing_extensions import ParamSpec, Self, TypeAlias
from . import amap_iter
from ._typing import awaitable, Comparable, Maybe, Nothing, NothingType
from .exceptions import StateError, StopAnyIteration
_T = TypeVar('_T')
_KT = TypeVar('_KT')
_VT = TypeVar('_VT')
_RT = TypeVar('_RT')
_S = TypeVar('_S', bound=object)
_RS = TypeVar('_RS', bound=object)
_SS = TypeVar('_SS', bound=Collection)
_P = ParamSpec('_P')
_FutureOrCoro: TypeAlias = Union[asyncio.Future[_T], Coroutine[Any, Any, _T]]
_MaybeAsync: TypeAlias = Union[Callable[_P, _T], Callable[_P, Awaitable[_T]]]
_DoneStatus: TypeAlias = Literal['stop', 'error', 'cancel']
_DONE_STATUS_KEYS: Final[tuple[_DoneStatus, ...]] = 'stop', 'error', 'cancel'
_ST = TypeVar('_ST', bound='State')
class StateBase(Generic[_S]):
__slots__ = ('__loop', '__future', )
__match_args__ = ('_value_raw',)
__loop: asyncio.AbstractEventLoop | None
__future: asyncio.Future[_S] | None
def __init__(self):
self.__loop = None
self.__future = None
def __del__(self):
if (future := self.__future) is None:
return
try:
future.cancel()
except RuntimeError:
pass
def __await__(self) -> Generator[Any, None, _S]:
return self._future.__await__()
def __repr__(self) -> str:
return f'<{type(self).__name__}{self._format()} at {id(self):#x}>'
def __str__(self) -> str:
return f'<{type(self).__name__}{self._format()}>'
@property
def readonly(self) -> bool:
"""Returns true if an asyncio.Task will set the result, otherwise, the
asyncio.Future can be set manually.
"""
return isinstance(self._future, asyncio.Task)
@property
def is_done(self) -> bool:
return self._future.done()
@property
def is_set(self) -> bool:
future = self._future
if not future.done():
return False
if future.cancelled():
return False
return future.exception() is None
@property
def is_error(self) -> bool:
future = self._future
if not future.done():
return False
if future.cancelled():
return False
if (exc := future.exception()) is None:
return False
return not isinstance(exc, asyncio.CancelledError)
@property
def is_cancelled(self) -> bool:
future = self._future
if not future.done():
return False
if future.cancelled():
return True
return isinstance(future.exception(), asyncio.CancelledError)
@property
def _loop(self) -> asyncio.AbstractEventLoop:
if (loop := self.__loop) is None:
if (future := self.__future) is not None:
loop = future.get_loop()
else:
loop = asyncio.get_running_loop()
self.__loop = loop
return loop
@property
def _future(self) -> asyncio.Future[_S]:
if (future := self.__future) is None:
future = self.__future = self._loop.create_future()
return future
@_future.setter
def _future(self, value: asyncio.Future[_S] | _S):
if done := (future := self._future).done():
future.result()
if asyncio.isfuture(value):
future = value
else:
if done:
future = future.get_loop().create_future()
future.set_result(cast(_S, value))
self.__future = future
@_future.deleter
def _future(self):
if (future := self.__future) is None or not future.done():
return
if future.cancelled():
future.result() # will raise asyncio.CancelledError
self.__future = future.get_loop().create_future()
@property
def _value_raw(self) -> _S | BaseException | None:
"""For pattern matching."""
fut = self._future
if not fut.done():
return None
try:
return fut.result()
except (SystemExit, KeyboardInterrupt):
raise
except BaseException as exc:
return exc
def _set(self, value: _S) -> None:
self.__as_unset_future().set_result(value)
self._on_set(value)
def _raise(self, exc: BaseException) -> None:
if isinstance(exc, asyncio.CancelledError):
self._cancel()
return
self.__as_unset_future().set_exception(exc)
self._on_error(exc)
def _cancel(self) -> bool:
cancelled = self._future.cancel()
self._on_cancel()
return cancelled
def _on_set(self, value: _S) -> None:
...
def _on_error(self, exc: BaseException) -> None:
...
def _on_cancel(self) -> None:
...
def _format(self) -> str:
fut = self._future
if fut.done():
return f'({self._value_raw!r})'
return ''
def __as_unset_future(self):
future = self._future
if isinstance(future, asyncio.Task):
raise StateError(f'{self!r} is readonly')
if future.done():
current = future.result()
raise StateError(f'{self!r} is already set: {current!r}')
return future
class State(AsyncIterator[_S], StateBase[_S], Generic[_S]):
__slots__ = (
'_key',
'_collections',
'_producer',
'_consumer',
'_is_set',
'_is_stopped',
'_is_error',
'_is_cancelled',
'__waiters',
'__waiter_counter',
)
# when provided, states are mapped before they're compared
_key: Callable[[_S], Comparable]
# change notification to e.g. StateVarTuple
_collections: list[tuple[Any, StateCollection[Any, _S, Any]]]
# see _set_from(), can be set only once
_producer: Maybe[AsyncIterable[Any]]
_consumer: Maybe[asyncio.Task[None | NoReturn]]
def __init__(
self,
*,
key: Callable[[_S], Comparable] = lambda s: s
) -> None:
super().__init__()
self._key = key
self._consumer = Nothing
self._producer = Nothing
# TODO use weakref
self._collections = []
self._is_set = False
self._is_stopped = False
self._is_error = False
self._is_cancelled = False
self.__waiters = {}
self.__waiter_counter = itertools.count(0).__next__
def __del__(self):
super().__del__()
try:
self._future.cancel()
for waiter in self.__waiters.values():
waiter.cancel()
except RuntimeError:
pass
self._collections.clear()
def __eq__(self, other: _S) -> bool:
if not self.is_set:
return False
value = self._get()
return bool(value is other or value == other)
def __await__(self) -> Generator[Any, None, _S]:
if not self.is_set:
if (future := self._future).done():
future.result() # reraise if needed
return self._wait_next().__await__()
return super().__await__()
async def __aiter__(self, *, buffer: int | None = 4) -> AsyncIterator[_S]:
futures = collections.deque(maxlen=buffer)
if self.is_set:
futures.append(self._future)
waiters = self.__waiters
waiter_id = self.__waiter_counter()
def _schedule_next(present=None):
if present:
if present.cancelled():
return
if isinstance(present.exception(), StopAsyncIteration):
return
loop = present.get_loop()
else:
loop = asyncio.get_running_loop()
future = loop.create_future()
future.add_done_callback(_schedule_next)
assert waiter_id not in waiters or waiters[waiter_id].done()
waiters[waiter_id] = future
futures.append(future)
try:
_schedule_next()
while not self.is_done:
if not len(futures):
await asyncio.sleep(0)
assert len(futures)
try:
yield await futures.popleft()
except StopAnyIteration:
break
finally:
if waiter_id in waiters:
del waiters[waiter_id]
async def __anext__(self) -> _S:
try:
return await self._wait_next()
except asyncio.CancelledError:
raise StopAsyncIteration
__hash__ = None # type: ignore
async def _wait_next(self) -> _S:
waiters = self.__waiters
waiter_id = self.__waiter_counter()
future = waiters[waiter_id] = self._loop.create_future()
try:
return await future
finally:
del waiters[waiter_id]
@property
def readonly(self) -> bool:
"""Returns true if an asyncio.Task will set the result, otherwise, the
asyncio.Future can be set manually.
"""
return self._producer is not Nothing or super().readonly
@property
def is_set(self) -> bool:
return self._is_set
@property
def is_done(self) -> bool:
return self._is_stopped or self._is_error or self._is_cancelled
@property
def is_stopped(self) -> bool:
return self._is_stopped
@property
def is_error(self) -> bool:
return self._is_error
@property
def is_cancelled(self) -> bool:
return self._is_cancelled
@overload
def map(self, function: Callable[[_S], Awaitable[_S]]) -> Self: ...
@overload
def map(self, function: Callable[[_S], _S]) -> Self: ...
@overload
def map(
self,
function: Callable[[_S], Awaitable[object]],
cls: type[_ST],
*cls_args: Any,
**cls_kwargs: Any,
) -> _ST:
...
@overload
def map(
self,
function: Callable[[_S], object],
cls: type[_ST],
*cls_args: Any,
**cls_kwargs: Any,
) -> _ST:
...
def map(
self,
function: Callable[[_S], Awaitable[_RS]] | Callable[[_S], _RS],
cls: type[_ST] | None = None,
*cls_args: Any,
**cls_kwargs: Any,
) -> _ST:
"""Create a new instance from this state, with the function applied to
its value.
The function can be either sync or async.
Unless specified, the mapped state type will be type(self).
"""
if cls_kwargs is None:
cls_kwargs = {}
if 'name' not in cls_kwargs:
cls_kwargs['name'] = f'{function.__name__}({self})'
res: _ST
if cls is None:
res = cast(_ST, type(self)(*cls_args, **cls_kwargs))
else:
res = cls(*cls_args, **cls_kwargs)
if self.is_set:
initial = function(self._get())
if awaitable(initial):
async def _set_after():
res._set(cast(_RS, await initial))
asyncio.create_task(_set_after())
else:
res._set(cast(_RS, initial))
res._set_from(amap_iter(function, self))
return res
async def _consume(self) -> None | NoReturn:
assert self._producer is not Nothing
try:
async for state in self._producer:
self._set_item(state)
except (SystemExit, KeyboardInterrupt) as exc:
self._raise(exc)
raise
except GeneratorExit:
# don't attempt to "stop" if the loop was closed
try:
asyncio.get_running_loop()
except RuntimeError:
self._cancel()
else:
self._stop()
except StopAnyIteration:
self._stop()
except asyncio.CancelledError:
self._cancel()
except BaseException as exc:
self._raise(exc)
else:
await asyncio.sleep(0)
self._stop()
@overload
def _get(self, default: _T) -> _S | _T: ...
@overload
def _get(self, default: NothingType = ...) -> _S: ...
def _get(self, default: Maybe[_T] = Nothing) -> _S | _T:
if (future := self._future).done():
try:
return future.result()
except (GeneratorExit, StopAsyncIteration, asyncio.CancelledError):
if default is Nothing:
raise
return default
if default is Nothing:
raise LookupError(repr(self))
return default
def _set_from(self, producer: AsyncIterable[Any]) -> None:
if self._producer is not Nothing:
raise StateError(f'{self!r} is already being set')
self._producer = producer
task_name = f'{self}.consumer'
self._consumer = asyncio.create_task(self._consume(), name=task_name)
def _set_item(self, value: Any):
"""Used by the consumer to set the next item"""
self._set(cast(_S, value))
def _set(self, value: _S, always: bool = False):
if not always and self._equals(value):
return 0
del self._future
cast(asyncio.Future[_S], self._future).set_result(value)
self._on_set(value)
self.__notify_waiters(value)
def _clear(self) -> None:
del self._future
self._on_clear()
def _stop(self) -> None:
exc = StopAsyncIteration
future = self._future
if not future.done():
future.set_exception(exc)
self._on_stop()
self.__notify_waiters(exc=exc)
def _raise(self, exc: type[BaseException] | BaseException) -> None:
if isinstance(exc, type):
exc = exc()
if isinstance(exc, asyncio.CancelledError):
self._cancel()
elif isinstance(exc, StopAsyncIteration):
self._stop()
else:
del self._future
cast(asyncio.Future[_S], self._future).set_exception(exc)
self._on_error(exc)
self.__notify_waiters(exc=exc)
def _cancel(self) -> None:
if self._is_cancelled:
return
self._future.cancel()
self._on_cancel()
self.__notify_waiters(cancel=True)
def _on_set(self, state: _S) -> None:
self._is_set = True
for j, parent in self._collections:
# noinspection PyProtectedMember
parent._on_item_set(j, state)
def _on_clear(self) -> None:
assert not self._is_cancelled
self._is_set = False
self._is_error = False
self._is_stopped = False
for j, parent in self._collections:
# noinspection PyProtectedMember
| |
np.isfinite(u_xsum)
bg_tcp = interpolate.splrep(np.arange(nx)[u_xsum_ok],
np.asarray(u_xsum)[u_xsum_ok], s=smo1)
# representative background profile in column
u_x = interpolate.splev(np.arange(nx), bg_tcp, )
return u_xsum, u_x, u_std
def findBackground(extimg,background_lower=[None,None], background_upper=[None,None],yloc_spectrum=int(slit_width/2),
smo1=None, smo2=None, chatter=2):
'''Extract the background from the image slice containing the spectrum.
Parameters
----------
extimg : 2D array
image containing spectrum. Dispersion approximately along x-axis.
background_lower : list
distance in pixels from `yloc_spectrum` of the limits of the lower background region.
background_upper : list
distance in pixels from `yloc_spectrum` of the limits of the upper background region.
yloc_spectrum : int
pixel `Y` location of spectrum
smo1 : float
smoothing parameter passed to smoothing spline fitting routine. `None` for default.
smo2 : float
smoothing parameter passed to smoothing spline fitting routine. `None` for default.
chatter : int
verbosity
Returns
-------
bg : float
mean background
bg1, bg2 : 1D arrays
bg1 = lower background; bg2 = upper background
inherits size from extimg.shape x-xoordinate
bgsig : float
standard deviation of background
bgimg : 2D array
image of the background constructed from bg1 and/or bg2
bg_limits_used : list, length 4
limits used for the background in the following order: lower background, upper background
(bg1_good, bg1_dis, bg1_dis_good, bg2_good, bg2_dis, bg2_dis_good, bgimg_lin) : tuple
various other background measures
Notes
-----
**Global parameter**
- **background_method** : {'boxcar','splinefit'}
The two background images can be computed 2 ways:
1. 'splinefit': sigma clip image, then fit a smoothing spline to each
row, then average in y for each background region
2. 'boxcar': select the background from the smoothed image created
by method 1 below.
3. 'sigmaclip': do sigma clipping on rows and columns to get column
profile background, then clip image and mask, interpolate over masked
bits.
extimg is the image containing the spectrum in the 1-axis centered in 0-axis
`ank` is the position of the anchor in the image
I create two background images:
1. split the image strip into 40 portions in x, so that the background variation is small
compute the mean
sigma clip (3 sigma) each area to to the local mean
replace out-of-image pixels with mean of whole image (2-sigma clipped)
smooth with a boxcar by the smoothing factor
2. compute the background in two regions upper and lower
linearly interpolate in Y between the two regions to create a background image
bg1 = lower background; bg2 = upper background
smo1, smo2 allow one to relax the smoothing factor in computing the smoothing spline fit
History
-------
- 8 Nov 2011 NPM Kuin complete overhaul
things to do: get quality flagging of bad background points, edges perhaps done here?
- 13 Aug 2012: possible problem was seen of very bright sources not getting masked out properly
and causing an error in the background that extends over a large distance due to the smoothing.
The cause is that the sources are more extended than can be handled by this method.
A solution would be to derive a global background
- 30 Sep 2014: background fails in visible grism e.g., 57977004+1 nearby bright spectrum
new method added (4x slower processing) to screen the image using sigma clipping
'''
import sys
import numpy as np
try:
from convolve import boxcar
except:
from stsci.convolve import boxcar
from scipy import interpolate
import stsci.imagestats as imagestats
# initialize parameters
bgimg = extimg.copy()
out = np.where( (np.abs(bgimg-cval) <= 1e-6) )
in_img = np.where( (np.abs(bgimg-cval) > 1e-6) & np.isfinite(bgimg) )
nx = bgimg.shape[1] # number of points in direction of dispersion
ny = bgimg.shape[0] # width of the image
# sigma screening of background taking advantage of the dispersion being
# basically along the x-axis
if _PROFILE_BACKGROUND_:
bg, u_x, bg_sig = background_profile(bgimg, smo1=30, badval=cval)
u_mask = np.zeros((ny,nx),dtype=bool)
for i in range(ny):
u_mask[i,(bgimg[i,:].flatten() < u_x) &
np.isfinite(bgimg[i,:].flatten())] = True
bkg_sc = np.zeros((ny,nx),dtype=float)
# the following leaves larger disps in the dispersion but less noise;
# tested but not implemented, as it is not as fast and the mean results
# are comparable:
#for i in range(ny):
# uf = interpolate.interp1d(np.where(u_mask[i,:])[0],bgimg[i,u_mask[i,:]],bounds_error=False,fill_value=cval)
# bkg_sc[i,:] = uf(np.arange(nx))
#for i in range(nx):
# ucol = bkg_sc[:,i]
# if len(ucol[ucol != cval]) > 0:
# ucol[ucol == cval] = ucol[ucol != cval].mean()
for i in range(nx):
ucol = bgimg[:,i]
if len(ucol[u_mask[:,i]]) > 0:
ucol[np.where(u_mask[:,i] == False)[0] ] = ucol[u_mask[:,i]].mean()
bkg_sc[:,i] = ucol
if background_method == 'sigmaclip':
return bkg_sc
else:
# continue now with the with screened image
bgimg = bkg_sc
kx0 = 0 ; kx1 = nx # default limits for valid lower background
kx2 = 0 ; kx3 = nx # default limits for valid upper background
ny4 = int(0.25*ny) # default width of each default background region
sig1 = 1 # unit for background offset, width
bg_limits_used = [0,0,0,0] # return values used
## in the next section I replace the > 2.5 sigma peaks with the mean
## after subdividing the image strip to allow for the
## change in background level which can be > 2 over the
## image. Off-image parts are set to image mean.
# this works most times in the absence of the sigma screening,but
# can lead to overestimates of the background.
# the call to the imagestats package is only done here, and should
# consider replacement. Its not critical for the program.
#
xlist = np.linspace(0,bgimg.shape[1],80)
xlist = np.asarray(xlist,dtype=int)
imgstats = imagestats.ImageStats(bgimg[in_img[0],in_img[1]],nclip=3)
bg = imgstats.mean
bgsig = imgstats.stddev
if chatter > 2:
sys.stderr.write( 'background statistics: mean=%10.2f, sigma=%10.2f '%
(imgstats.mean, imgstats.stddev))
# create boolean image flagging good pixels
img_good = np.ones(extimg.shape,dtype=bool)
# flag area out of picture as bad
img_good[out] = False
# replace high values in image with estimate of mean and flag them as not good
for i in range(78):
# after the sigma screening this is a bit of overkill, leave in for now
sub_bg = boxcar(bgimg[:,xlist[i]:xlist[i+2]] , (5,5), mode='reflect', cval=cval)
sub_bg_use = np.where( np.abs(sub_bg - cval) > 1.0e-5 ) # list of coordinates
imgstats = None
if sub_bg_use[0].size > 0:
imgstats = imagestats.ImageStats(sub_bg[sub_bg_use],nclip=3)
# patch values in image (not out of image) with mean if outliers
aval = 2.0*imgstats.stddev
img_clip_ = (
(np.abs(bgimg[:,xlist[i]:xlist[i+2]]-cval) < 1e-6) |
(np.abs(sub_bg - imgstats.mean) > aval) |
(sub_bg <= 0.) | np.isnan(sub_bg) )
bgimg[:,xlist[i]:xlist[i+2]][img_clip_] = imgstats.mean # patch image
img_good[:,xlist[i]:xlist[i+2]][img_clip_] = False # flag patches
# the next section selects the user-selected or default background for further processing
if chatter > 1:
if background_method == 'boxcar':
sys.stderr.write( "BACKGROUND METHOD: %s; background smoothing = %s\n"%
(background_method,background_smoothing))
else:
sys.stderr.write( "BACKGROUND METHOD:%s\n"%(background_method ))
if not ((background_method == 'splinefit') | (background_method == 'boxcar') ):
sys.stderr.write('background method missing; currently reads : %s\n'%(background_method))
if background_method == 'boxcar':
# boxcar smooth in x,y using the global parameter background_smoothing
bgimg = boxcar(bgimg,background_smoothing,mode='reflect',cval=cval)
if background_lower[0] == None:
bg1 = bgimg[0:ny4,:].copy()
bg_limits_used[0]=0
bg_limits_used[1]=ny4
bg1_good = img_good[0:ny4,:]
kx0 = np.min(np.where(img_good[0,:]))+10 # assuming the spectrum is in the top two thirds of the detector
kx1 = np.max(np.where(img_good[0,:]))-10
else:
# no curvature, no second order: limits
bg1_1= np.max(np.array([yloc_spectrum - sig1*background_lower[0],20 ]))
#bg1_0= np.max(np.array([yloc_spectrum - sig1*(background_lower[0]+background_lower[1]),0]))
bg1_0= np.max(np.array([yloc_spectrum - sig1*(background_lower[1]),0]))
bg1 = bgimg[int(bg1_0):int(bg1_1),:].copy()
bg_limits_used[0]=bg1_0
bg_limits_used[1]=bg1_1
bg1_good = img_good[int(bg1_0):int(bg1_1),:]
kx0 = np.min(np.where(img_good[int(bg1_0),:]))+10 # assuming the spectrum is in the top two thirds of the detector
kx1 = np.max(np.where(img_good[int(bg1_0),:]))-10 # corrected for edge effects
#if ((kx2-kx0) < 20):
# print 'not | |
bool)
def initialize(self, infr=None, use_image=False, init_mode='rereview',
review_cfg=None):
print('[viz_graph] initialize')
self.init_mode = init_mode
print('self.init_mode = %r' % (self.init_mode,))
if review_cfg is None:
mode = 'filtered' if self.init_mode == 'split' else 'unfiltered'
self.preset_config(mode)
self.infr = infr
self.initialize_menus()
self.graph_tab_widget = self.addNewTabWidget(verticalStretch=1)
self.statbar1 = self.addNewWidget(
ori='horiz', verticalStretch=1, margin=1, spacing=1)
self.statbar2 = self.addNewWidget(
ori='horiz', verticalStretch=1, margin=1, spacing=1)
self.prog_bar = self.addNewProgressBar(visible=False)
self.initialize_api_tabs()
self.statbar1.addNewButton('Match and Score', min_width=1,
pressed=self.match_and_score_edges)
self.statbar1.addNewButton('ScoreVsOne', min_width=1,
pressed=self.score_edges_vsone)
self.statbar1.addNewButton('Edit Filters', min_width=1,
pressed=self.edit_filters)
self.statbar1.addNewButton('Repopulate', min_width=1,
pressed=self.repopulate)
self.statbar2.addNewButton('Reset DBState', min_width=1,
pressed=self.reset_review)
self.statbar2.addNewButton('Reset Rereview', min_width=1,
pressed=self.reset_rereview)
self.num_names_lbl = self.statbar2.addNewLabel('NUM_NAMES_LBL')
self.state_lbl = self.statbar2.addNewLabel('STATE_LBL')
self.statbar2.addNewButton('Accept', pressed=self.accept)
# _show_graph = self.init_mode in ['split', 'rereview', 'review']
_show_graph = True
if _show_graph:
# TODO: separate graph view into its own class
self.graph_tab = self.graph_tab_widget.addNewTab('Graph')
# TODO: make this its own proper widget
self.graph_widget = DevGraphWidget(parent=self, self_parent=self,
use_image=use_image)
self.graph_tab.addWidget(self.graph_widget)
# self.graph_widget.connect_kepress_to_slot
else:
self.graph_widget = None
self.graph_tab = None
self.init_signals_and_slots()
def init_signals_and_slots(self):
# https://doc.qt.io/archives/qtjambi-4.5.2_01/com/trolltech/qt/core/Qt.ConnectionType.html
# connection_type = QtCore.Qt.AutoConnection
# connection_type = QtCore.Qt.BlockingQueuedConnection
connection_type = QtCore.Qt.DirectConnection
# connection_type = QtCore.Qt.QueuedConnection
self.signal_state_update.connect(self.update_state,
type=connection_type)
def initialize_api_tabs(self):
self.api_tabs = {}
self.api_widgets = {}
def _add_item_widget_tab(key, view_class='table'):
title = key.title().replace('_', ' ')
self.api_tabs[key] = self.graph_tab_widget.addNewTab(title)
self.api_widgets[key] = gt.APIItemWidget(view_class=view_class)
self.api_tabs[key].addWidget(self.api_widgets[key])
_add_item_widget_tab('edges')
_add_item_widget_tab('nodes')
_add_item_widget_tab('name_nodes', view_class='tree')
_add_item_widget_tab('name_edges', view_class='tree')
node_view = self.api_widgets['nodes'].view
node_view.contextMenuClicked.connect(self.node_context)
node_view.connect_single_key_to_slot(gt.ALT_KEY, self.on_alt_pressed)
name_node_view = self.api_widgets['name_nodes'].view
name_node_view.contextMenuClicked.connect(self.node_context)
name_node_view.connect_single_key_to_slot(gt.ALT_KEY, self.on_alt_pressed)
edge_view = self.api_widgets['edges'].view
edge_view.doubleClicked.connect(self.edge_doubleclick)
edge_view.contextMenuClicked.connect(self.edge_context)
edge_view.connect_keypress_to_slot(self.edge_keypress)
edge_view.connect_single_key_to_slot(gt.ALT_KEY, self.on_alt_pressed)
name_edge_view = self.api_widgets['name_edges'].view
name_edge_view.doubleClicked.connect(self.edge_doubleclick)
name_edge_view.contextMenuClicked.connect(self.edge_context)
name_edge_view.connect_keypress_to_slot(self.edge_keypress)
name_edge_view.connect_single_key_to_slot(gt.ALT_KEY, self.on_alt_pressed)
def populate_edge_model(self):
print('[viz_graph] populate_edge_model')
# if self.init_mode is None:
# self.review_cfg['show_match_thumb'] = False
key = 'edges'
tab = self.api_tabs[key]
widget = self.api_widgets[key]
api = make_edge_api(self.infr, review_cfg=self.review_cfg)
title = key.title().replace('_', ' ')
headers = api.make_headers(tblnice=title, tblname=key)
widget.change_headers(headers)
widget.resize_headers(api)
widget.view.verticalHeader().setVisible(True)
tab.setTabText('%s (%r)' % (title, widget.model.num_rows_total))
widget.view.verticalHeader().setDefaultSectionSize(221)
def populate_node_model(self):
print('[viz_graph] populate_node_model')
api = make_node_api(self.infr)
key = 'nodes'
tab = self.api_tabs[key]
widget = self.api_widgets[key]
title = key.title().replace('_', ' ')
headers = api.make_headers(tblnice=title, tblname=key)
widget.change_headers(headers)
widget.view.verticalHeader().setVisible(True)
try:
widget.view.verticalHeader().setMovable(True)
except AttributeError:
widget.view.verticalHeader().setSectionsMovable(True)
tab.setTabText('%s (%r)' % (title, widget.model.num_rows_total))
def populate_name_node_model(self):
api = make_name_node_api(self.infr, review_cfg=self.review_cfg)
key = 'name_nodes'
tab = self.api_tabs[key]
widget = self.api_widgets[key]
title = key.title().replace('_', ' ')
headers = api.make_headers(tblnice=title, tblname=key)
widget.change_headers(headers)
tab.setTabText('%s (%r)' % (title, widget.model.num_rows_total))
def populate_name_edge_model(self):
api = make_name_edge_api(self.infr, review_cfg=self.review_cfg)
key = 'name_edges'
tab = self.api_tabs[key]
widget = self.api_widgets[key]
title = key.title().replace('_', ' ')
headers = api.make_headers(tblnice=title, tblname=key)
widget.change_headers(headers)
tab.setTabText('%s (%r)' % (title, widget.model.num_rows_total))
def initialize_menus(self):
self.menubar = gt.newMenubar(self)
self.menus = {}
key = 'Dev'
menu = self.menus[key] = self.menubar.newMenu(key)
menu.newAction(triggered=self.print_info)
menu.newAction(triggered=self.embed, shortcut='ctrl+shift+I')
menu.newAction(triggered=self.expand_image_and_names)
menu.newAction(triggered=self.emit_state_update)
menu.newAction(triggered=self.print_staging_table)
menu.newAction(triggered=self.print_annotmatch_table)
menu.newAction(triggered=self.print_deltas)
key = 'Actions'
menu = self.menus[key] = self.menubar.newMenu(key)
menu.newAction(triggered=self.commit_to_staging)
key = 'Debug'
menu = self.menus[key] = self.menubar.newMenu(key)
menu.newAction(triggered=self.use_ibeis_names)
menu.newAction(triggered=self.reset_staging)
menu.newAction(triggered=self.reset_annotmatch)
menu.newAction(triggered=self.ensure_full)
menu.newAction(triggered=self.ensure_cliques)
menu.newAction(triggered=self.vsone_subset)
menu.newAction(text='relabel_using_reviews', triggered=lambda: self.infr.relabel_using_reviews())
menu.newAction(text='apply_nondynamic_update', triggered=lambda: self.infr.apply_nondynamic_update())
def preset_config(self, mode='filtered'):
print('[graph] preset_config mode=%r' % (mode,))
if mode == 'filtered':
self.review_cfg = GRAPH_REVIEW_CFG_DEFAULTS.copy()
elif mode == 'unfiltered':
self.review_cfg = GRAPH_REVIEW_CFG_DEFAULTS.copy()
for key in self.review_cfg.keys():
if key.startswith('filter_'):
self.review_cfg[key] = False
def showEvent(self, event):
super(AnnotGraphWidget, self).showEvent(event)
ut.cprint('[viz_graph] showEvent', 'green')
# Fire initialize event after we show the GUI
QtCore.QTimer.singleShot(50, self.init_inference)
def init_inference(self):
print('[viz_graph] init_inference mode=%r' % (self.init_mode))
if self.init_mode is None:
pass
elif self.init_mode == 'split':
self.preset_config('filtered')
self.reset_split()
elif self.init_mode == 'rereview':
self.preset_config('unfiltered')
self.reset_rereview()
elif self.init_mode == 'review':
self.reset_review()
else:
raise ValueError('Unknown init_mode=%r' % (self.init_mode,))
self.repopulate()
if ut.get_argflag('--graphtab'):
index = self.graph_tab_widget.indexOf(self.graph_tab)
self.graph_tab_widget.setCurrentIndex(index)
# self.graph_tab_widget.setCurrentIndex(2)
match = ut.get_argval('--match', type_=list, default=None)
import ubelt as ub
if match:
pairs = list(ub.chunks(match, 2))
self.mark_pair_state(pairs, POSTV)
nomatch = ut.get_argval('--nomatch', type_=list, default=None)
if nomatch:
pairs = list(ub.chunks(nomatch, 2))
self.mark_pair_state(pairs, NEGTV)
def repopulate(self):
# self.update_state(structure_changed=True)
self.emit_state_update(structure_changed=True)
def emit_state_update(self, structure_changed=False, disable_global_update=False):
self.signal_state_update.emit(structure_changed, disable_global_update)
def update_state(self, structure_changed=False, disable_global_update=False):
print('[viz_graph] update_state mode=%s' % (self.init_mode,))
#if self.init_mode in ['split', 'rereview']:
if not disable_global_update:
if self.init_mode == 'split':
self.infr.apply_feedback_edges()
self.infr.relabel_using_reviews()
elif self.init_mode == 'rereview':
self.infr.apply_feedback_edges()
# self.infr.apply_match_scores()
self.infr.relabel_using_reviews()
elif self.init_mode == 'review':
self.infr.apply_match_edges()
self.infr.ensure_mst()
self.infr.apply_feedback_edges()
# self.infr.apply_match_scores()
self.infr.relabel_using_reviews()
self.infr.apply_nondynamic_update()
# Set gui status indicators
status = self.infr.connected_component_status()
truth_colors = self.infr._get_truth_colors()
if status['num_inconsistent']:
self.state_lbl.setText('Inconsistent Names: %d' % (status['num_inconsistent'],))
self.state_lbl.setColor('black', truth_colors[NEGTV][0:3] * 255)
else:
self.state_lbl.setText('Consistent')
self.state_lbl.setColor('black', truth_colors[POSTV][0:3] * 255)
self.num_names_lbl.setText('Names: max=%r' % (status['num_names_max']))
# print('[viz_graph] on_update_state mode=%s' % (self.init_mode,))
if structure_changed:
# TODO: only make this API if the tab is clicked
self.populate_node_model()
self.populate_edge_model()
self.populate_name_node_model()
self.populate_name_edge_model()
if self.graph_widget is not None:
self.graph_widget.emit_graph_update()
for widget in self.api_widgets.values():
model = widget.view.model()
# FIXME: should only clear cache in viewport
model.clear_cache()
model.layoutChanged.emit()
def ensure_cliques(self):
self.infr.ensure_cliques()
self.infr.relabel_using_reviews()
self.infr.apply_nondynamic_update()
self.repopulate()
def ensure_full(self):
self.infr.ensure_full()
self.infr.relabel_using_reviews()
self.infr.apply_nondynamic_update()
self.repopulate()
def match_and_score_edges(self):
with gt.GuiProgContext('Scoring Edges', self.prog_bar) as ctx:
# TODO: add in a cfgdict here with settable params
self.infr.exec_matching(prog_hook=ctx.prog_hook)
self.infr.apply_match_edges(self.review_cfg)
# self.infr.apply_match_scores()
self.repopulate()
def score_edges_vsone(self):
# DEPRICATE
# TODO: replace with new interface
with gt.GuiProgContext('Scoring Edges', self.prog_bar) as ctx:
edges = list(self.infr.edges())
self.infr.exec_vsone_subset(edges, prog_hook=ctx.prog_hook)
# self.infr.exec_vsone(prog_hook=ctx.prog_hook)
# self.infr.apply_match_scores()
self.repopulate()
def reset_review(self):
print('[viz_graph] reset_review')
infr = self.infr
with gt.GuiProgContext('Reset Review', self.prog_bar) as ctx:
ctx.set_progress(0, 3)
with ut.Timer('reset_feedback'):
infr.reset_feedback('staging', apply=True)
with ut.Timer('reinit_name_labels'):
infr.reset_labels_to_ibeis()
if self.graph_widget is not None:
self.graph_widget.set_pin_state(True)
with ut.Timer('ensure_mst'):
infr.ensure_mst()
with ut.Timer('apply_match_edges'):
infr.apply_match_edges()
# with ut.Timer('apply_match_scores'):
# infr.apply_match_scores()
# with ut.Timer('relabel_using_reviews'):
# self.infr.relabel_using_reviews()
# with ut.Timer('apply_nondynamic_update'):
# self.infr.apply_nondynamic_update()
self.repopulate()
ctx.set_progress(3, 3)
def reset_annotmatch(self):
print('[viz_graph] reset_rereview')
infr = self.infr
with gt.GuiProgContext('Reset Review', self.prog_bar) as ctx:
ctx.set_progress(0, 3)
infr.reset_feedback('annotmatch', apply=True)
infr.relabel_using_reviews()
ctx.set_progress(msg='repopulate')
self.repopulate()
ctx.set_progress(8, 8)
def reset_staging(self):
print('[viz_graph] reset_rereview')
infr = self.infr
with gt.GuiProgContext('Reset Review', self.prog_bar) as ctx:
ctx.set_progress(0, 3)
infr.reset_feedback('staging', apply=True)
infr.relabel_using_reviews()
ctx.set_progress(msg='repopulate')
self.repopulate()
ctx.set_progress(8, 8)
def reset_rereview(self):
"""
Goal:
All names are removed.
Reset edges so only reviewed edges are shown.
You can change the state of those edges.
They are not filtered.
"""
print('[viz_graph] reset_rereview')
infr = self.infr
self.init_mode = 'rereview'
with gt.GuiProgContext('Reset Review', self.prog_bar) as ctx:
ctx.set_progress(0, 3)
infr.initialize_graph()
if self.graph_widget is not None:
self.graph_widget.set_pin_state(True)
ctx.set_progress(msg='reset name labels')
infr.reset_name_labels()
ctx.set_progress(msg='reset feedback')
infr.reset_feedback('staging', apply=True)
ctx.set_progress(msg='remove name labels')
infr.clear_name_labels()
# ctx.set_progress(msg='apply match scores')
# infr.apply_match_scores()
ctx.set_progress(msg='repopulate')
self.repopulate()
ctx.set_progress(8, 8)
def reset_split(self):
infr = self.infr
self.init_mode = 'split'
with gt.GuiProgContext('Initializing', self.prog_bar) as ctx:
ctx.set_progress(0, 3)
infr.initialize_graph()
if self.graph_widget is not None:
self.graph_widget.set_pin_state(True)
ctx.set_progress(1, 3)
infr.remove_feedback()
ctx.set_progress(2, 3)
infr.clear_name_labels()
ctx.set_progress(3, 3)
def edit_filters(self):
# TODO: split up review configs / show thumbs etc...
config = dtool.Config.from_dict(self.review_cfg)
dlg = gt.ConfigConfirmWidget.as_dialog(self, title='Edit Filters',
msg='Edit Filters',
with_spoiler=False,
config=config)
dlg.resize(700, 500)
dlg.exec_()
print('config = %r' % (config,))
updated_config = dlg.widget.config # NOQA
print('updated_config = %r' % (updated_config,))
self.review_cfg = updated_config.asdict()
self.repopulate()
def edge_doubleclick(self, qtindex):
"""
qtindex = qtindex = self.api_widgets['edges'].view.get_row_and_qtindex_from_id(1)[0]
"""
print('[viz_graph] DoubleClicked: ' + str(gt.qtype.qindexinfo(qtindex)))
model = qtindex.model()
aid1 = model.get_header_data('aid1', qtindex)
aid2 = model.get_header_data('aid2', qtindex)
cm, aid1, aid2 = self.infr.lookup_cm(aid1, aid2)
if cm is not None:
cm.ishow_single_annotmatch(self.infr.qreq_, aid2, mode=0)
else:
# Hack
self.graph_widget.deselect()
self.graph_widget.toggle_selected_aid([aid1, aid2])
#self.graph_widget.selected_aids = [aid1, aid2]
self.graph_widget.show_selected()
def mark_pair_state(self, pairs, state):
valid_states = {POSTV, NEGTV, INCMP, UNREV}
statetags = state.split('+')
state = statetags[0]
tags = statetags[1].split(';') if len(statetags) > 1 else []
assert state in valid_states
for aid1, aid2 in pairs:
user_id = ut.get_user_name() + '@' + ut.get_computer_name() + ':qt-mark'
self.infr.add_feedback((aid1, aid2), state, tags=tags,
user_id=user_id)
self.emit_state_update(disable_global_update=True)
def make_mark_state_funcs(self, selection_func):
def _mark_selected_pair_state(state):
self.mark_pair_state(selection_func(), state)
options = [
('Mark &True', ut.partial(_mark_selected_pair_state, POSTV)),
('Mark &False', ut.partial(_mark_selected_pair_state, NEGTV)),
('Mark &Not-Comparable', ut.partial(_mark_selected_pair_state, INCMP)),
('Mark &Photobomb', ut.partial(_mark_selected_pair_state, 'nomatch+photobomb')),
('Mark &SceneryMatch', ut.partial(_mark_selected_pair_state, 'nomatch+scenerymatch')),
('&Unreview', ut.partial(_mark_selected_pair_state, UNREV)),
# unreview will only remove internal feedback, anything commited will not change
]
return options
def name_selection(self, view):
selected_qtindex_list_ = view.selectedRows()
selected_qtindex_names = []
for qtindex in selected_qtindex_list_:
model = qtindex.model()
if model.name in {'name_edges', 'name_nodes'}:
level = qtindex.internalPointer().level
if level == 0:
selected_qtindex_names.append(qtindex)
name_labels = []
for qtindex in selected_qtindex_names:
model = qtindex.model()
name_label = model.get_header_data('name_label', qtindex)
name_labels.append(name_label)
return name_labels
def edge_selection(self, view):
selected_qtindex_list_ = view.selectedRows()
selected_qtindex_edges = []
for qtindex in selected_qtindex_list_:
model = qtindex.model()
if model.name == 'name_edges':
level = qtindex.internalPointer().level
if level == 1:
selected_qtindex_edges.append(qtindex)
elif model.name == 'edges':
selected_qtindex_edges.append(qtindex)
aid_pairs = []
for qtindex in selected_qtindex_edges:
model = qtindex.model()
aid1 = model.get_header_data('aid1', qtindex)
aid2 = model.get_header_data('aid2', qtindex)
aid_pairs.append((aid1, aid2))
return aid_pairs
def node_selection(self, view):
selected_qtindex_list = view.selectedRows()
aids = [
qtindex.model().get_header_data('aid', qtindex)
for qtindex in selected_qtindex_list
]
return aids
def get_node_options(self, aids):
"""
Context-menu options for annotation nodes
"""
from ibeis.viz.interact import interact_chip
options = []
if len(aids) == 1:
options += interact_chip.build_annot_context_options(
self.infr.ibs, aids[0], refresh_func=None,
with_interact_name=False,
config2_=None)
if len(aids) > 1:
aid_pairs = list(it.combinations(aids, 2))
options += self.get_edge_options(aid_pairs)
return options
def | |
# -*- coding: utf-8 -*-
"""This file contains the Windows NT time zone definitions.
The Windows time zone names can be obtained from the following
Windows Registry key:
HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones
"""
# Dictionary to map Windows time zone names to Python equivalents.
# Note that spaces have been stripped from the Windows time zone names.
TIME_ZONES = {
'AlaskanStandardTime': 'US/Alaska',
'Arabic Standard Time': 'Asia/Baghdad',
'AtlanticStandardTime': 'Canada/Atlantic',
'AzoresStandardTime': 'Atlantic/Azores',
'CanadaCentralStandardTime': 'CST6CDT',
'CapeVerdeStandardTime': 'Atlantic/Azores',
'CentralAmericaStandardTime': 'CST6CDT',
'CentralDaylightTime': 'CST6CDT',
'CentralEuropeanStandardTime': 'Europe/Belgrade',
'CentralEuropeStandardTime': 'Europe/Belgrade',
'Central Standard Time': 'CST6CDT',
'CentralStandardTime': 'CST6CDT',
'ChinaStandardTime': 'Asia/Bangkok',
'EasternDaylightTime': 'EST5EDT',
'EasternStandardTime': 'EST5EDT',
'E.EuropeStandardTime': 'Egypt',
'EgyptStandardTime': 'Egypt',
'GMTStandardTime': 'GMT',
'GreenwichStandardTime': 'GMT',
'HawaiianStandardTime': 'US/Hawaii',
'IndiaStandardTime': 'Asia/Kolkata',
'IsraelStandardTime': 'Egypt',
'KoreaStandardTime': 'Asia/Seoul',
'MalayPeninsulaStandardTime': 'Asia/Kuching',
'MexicoStandardTime2': 'MST7MDT',
'MexicoStandardTime': 'CST6CDT',
'MountainDaylightTime': 'MST7MDT',
'MountainStandardTime': 'MST7MDT',
'NewfoundlandStandardTime': 'Canada/Newfoundland',
'NorthAsiaEastStandardTime': 'Asia/Bangkok',
'PacificDaylightTime': 'PST8PDT',
'PacificSAStandardTime': 'Canada/Atlantic',
'Pacific Standard Time': 'PST8PDT',
'PacificStandardTime': 'PST8PDT',
'RomanceStandardTime': 'Europe/Belgrade',
'RomanceDaylightTime': 'Europe/Belgrade',
'SamoaStandardTime': 'US/Samoa',
'SAPacificStandardTime': 'EST5EDT',
'SAWesternStandardTime': 'Canada/Atlantic',
'SingaporeStandardTime': 'Asia/Bangkok',
'SouthAfricaStandardTime': 'Egypt',
'TaipeiStandardTime': 'Asia/Bangkok',
'TokyoStandardTime': 'Asia/Tokyo',
'@tzres.dll,-1010': 'Asia/Aqtau',
'@tzres.dll,-1020': 'Asia/Dhaka',
'@tzres.dll,-1021': 'Asia/Dhaka',
'@tzres.dll,-1022': 'Asia/Dhaka',
'@tzres.dll,-104': 'America/Cuiaba',
'@tzres.dll,-105': 'America/Cuiaba',
'@tzres.dll,-1070': 'Asia/Tbilisi',
'@tzres.dll,-10': 'Atlantic/Azores',
'@tzres.dll,-110': 'EST5EDT',
'@tzres.dll,-111': 'EST5EDT',
'@tzres.dll,-1120': 'America/Cuiaba',
'@tzres.dll,-112': 'EST5EDT',
'@tzres.dll,-1140': 'Pacific/Fiji',
'@tzres.dll,-11': 'Atlantic/Azores',
'@tzres.dll,-120': 'EST5EDT',
'@tzres.dll,-121': 'EST5EDT',
'@tzres.dll,-122': 'EST5EDT',
'@tzres.dll,-12': 'Atlantic/Azores',
'@tzres.dll,-130': 'EST5EDT',
'@tzres.dll,-131': 'EST5EDT',
'@tzres.dll,-132': 'EST5EDT',
'@tzres.dll,-140': 'CST6CDT',
'@tzres.dll,-141': 'CST6CDT',
'@tzres.dll,-142': 'CST6CDT',
'@tzres.dll,-1460': 'Pacific/Port_Moresby',
'@tzres.dll,-150': 'America/Guatemala',
'@tzres.dll,-151': 'America/Guatemala',
'@tzres.dll,-152': 'America/Guatemala',
'@tzres.dll,-1530': 'Asia/Yekaterinburg',
'@tzres.dll,-160': 'CST6CDT',
'@tzres.dll,-161': 'CST6CDT',
'@tzres.dll,-162': 'CST6CDT',
'@tzres.dll,-1630': 'Europe/Nicosia',
'@tzres.dll,-1660': 'America/Bahia',
'@tzres.dll,-1661': 'America/Bahia',
'@tzres.dll,-1662': 'America/Bahia',
'@tzres.dll,-170': 'America/Mexico_City',
'@tzres.dll,-171': 'America/Mexico_City',
'@tzres.dll,-172': 'America/Mexico_City',
'@tzres.dll,-180': 'MST7MDT',
'@tzres.dll,-181': 'MST7MDT',
'@tzres.dll,-182': 'MST7MDT',
'@tzres.dll,-190': 'MST7MDT',
'@tzres.dll,-191': 'MST7MDT',
'@tzres.dll,-192': 'MST7MDT',
'@tzres.dll,-200': 'MST7MDT',
'@tzres.dll,-201': 'MST7MDT',
'@tzres.dll,-202': 'MST7MDT',
'@tzres.dll,-20': 'Atlantic/Cape_Verde',
'@tzres.dll,-210': 'PST8PDT',
'@tzres.dll,-211': 'PST8PDT',
'@tzres.dll,-212': 'PST8PDT',
'@tzres.dll,-21': 'Atlantic/Cape_Verde',
'@tzres.dll,-220': 'US/Alaska',
'@tzres.dll,-221': 'US/Alaska',
'@tzres.dll,-222': 'US/Alaska',
'@tzres.dll,-22': 'Atlantic/Cape_Verde',
'@tzres.dll,-230': 'US/Hawaii',
'@tzres.dll,-231': 'US/Hawaii',
'@tzres.dll,-232': 'US/Hawaii',
'@tzres.dll,-260': 'GMT',
'@tzres.dll,-261': 'GMT',
'@tzres.dll,-262': 'GMT',
'@tzres.dll,-271': 'UTC',
'@tzres.dll,-272': 'UTC',
'@tzres.dll,-280': 'Europe/Budapest',
'@tzres.dll,-281': 'Europe/Budapest',
'@tzres.dll,-282': 'Europe/Budapest',
'@tzres.dll,-290': 'Europe/Warsaw',
'@tzres.dll,-291': 'Europe/Warsaw',
'@tzres.dll,-292': 'Europe/Warsaw',
'@tzres.dll,-300': 'Europe/Paris',
'@tzres.dll,-301': 'Europe/Paris',
'@tzres.dll,-302': 'Europe/Paris',
'@tzres.dll,-320': 'Europe/Berlin',
'@tzres.dll,-321': 'Europe/Berlin',
'@tzres.dll,-322': 'Europe/Berlin',
'@tzres.dll,-331': 'Europe/Nicosia',
'@tzres.dll,-332': 'Europe/Nicosia',
'@tzres.dll,-340': 'Africa/Cairo',
'@tzres.dll,-341': 'Africa/Cairo',
'@tzres.dll,-342': 'Africa/Cairo',
'@tzres.dll,-350': 'Europe/Sofia',
'@tzres.dll,-351': 'Europe/Sofia',
'@tzres.dll,-352': 'Europe/Sofia',
'@tzres.dll,-365': 'Egypt',
'@tzres.dll,-371': 'Asia/Jerusalem',
'@tzres.dll,-372': 'Asia/Jerusalem',
'@tzres.dll,-380': 'Africa/Harare',
'@tzres.dll,-381': 'Africa/Harare',
'@tzres.dll,-382': 'Africa/Harare',
'@tzres.dll,-390': 'Asia/Kuwait',
'@tzres.dll,-391': 'Asia/Kuwait',
'@tzres.dll,-392': 'Asia/Kuwait',
'@tzres.dll,-400': 'Asia/Baghdad',
'@tzres.dll,-401': 'Asia/Baghdad',
'@tzres.dll,-402': 'Asia/Baghdad',
'@tzres.dll,-40': 'Brazil/East',
'@tzres.dll,-410': 'Africa/Nairobi',
'@tzres.dll,-411': 'Africa/Nairobi',
'@tzres.dll,-412': 'Africa/Nairobi',
'@tzres.dll,-41': 'Brazil/East',
'@tzres.dll,-42': 'Brazil/East',
'@tzres.dll,-420': 'Europe/Moscow',
'@tzres.dll,-421': 'Europe/Moscow',
'@tzres.dll,-422': 'Europe/Moscow',
'@tzres.dll,-434': 'Asia/Tbilisi',
'@tzres.dll,-435': 'Asia/Tbilisi',
'@tzres.dll,-440': 'Asia/Muscat',
'@tzres.dll,-441': 'Asia/Muscat',
'@tzres.dll,-442': 'Asia/Muscat',
'@tzres.dll,-447': 'Asia/Baku',
'@tzres.dll,-448': 'Asia/Baku',
'@tzres.dll,-449': 'Asia/Baku',
'@tzres.dll,-450': 'Asia/Yerevan',
'@tzres.dll,-451': 'Asia/Yerevan',
'@tzres.dll,-452': 'Asia/Yerevan',
'@tzres.dll,-460': 'Asia/Kabul',
'@tzres.dll,-461': 'Asia/Kabul',
'@tzres.dll,-462': 'Asia/Kabul',
'@tzres.dll,-471': 'Asia/Yekaterinburg',
'@tzres.dll,-472': 'Asia/Yekaterinburg',
'@tzres.dll,-480': 'Asia/Karachi',
'@tzres.dll,-481': 'Asia/Karachi',
'@tzres.dll,-482': 'Asia/Karachi',
'@tzres.dll,-490': 'Asia/Kolkata',
'@tzres.dll,-491': 'Asia/Kolkata',
'@tzres.dll,-492': 'Asia/Kolkata',
'@tzres.dll,-500': 'Asia/Kathmandu',
'@tzres.dll,-501': 'Asia/Kathmandu',
'@tzres.dll,-502': 'Asia/Kathmandu',
'@tzres.dll,-510': 'Asia/Dhaka',
'@tzres.dll,-511': 'Asia/Aqtau',
'@tzres.dll,-512': 'Asia/Aqtau',
'@tzres.dll,-570': 'Asia/Chongqing',
'@tzres.dll,-571': 'Asia/Chongqing',
'@tzres.dll,-572': 'Asia/Chongqing',
'@tzres.dll,-60': 'America/Buenos_Aires',
'@tzres.dll,-611': 'Australia/Perth',
'@tzres.dll,-612': 'Australia/Perth',
'@tzres.dll,-621': 'Asia/Seoul',
'@tzres.dll,-622': 'Asia/Seoul',
'@tzres.dll,-631': 'Asia/Tokyo',
'@tzres.dll,-632': 'Asia/Tokyo',
'@tzres.dll,-650': 'Australia/Darwin',
'@tzres.dll,-651': 'Australia/Darwin',
'@tzres.dll,-652': 'Australia/Darwin',
'@tzres.dll,-660': 'Australia/Adelaide',
'@tzres.dll,-661': 'Australia/Adelaide',
'@tzres.dll,-662': 'Australia/Adelaide',
'@tzres.dll,-670': 'Australia/Sydney',
'@tzres.dll,-671': 'Australia/Sydney',
'@tzres.dll,-672': 'Australia/Sydney',
'@tzres.dll,-680': 'Australia/Brisbane',
'@tzres.dll,-681': 'Australia/Brisbane',
'@tzres.dll,-682': 'Australia/Brisbane',
'@tzres.dll,-691': 'Australia/Hobart',
'@tzres.dll,-692': 'Australia/Hobart',
'@tzres.dll,-70': 'Canada/Newfoundland',
'@tzres.dll,-71': 'Canada/Newfoundland',
'@tzres.dll,-721': 'Pacific/Port_Moresby',
'@tzres.dll,-722': 'Pacific/Port_Moresby',
'@tzres.dll,-72': 'Canada/Newfoundland',
'@tzres.dll,-731': 'Pacific/Fiji',
'@tzres.dll,-732': 'Pacific/Fiji',
'@tzres.dll,-740': 'Pacific/Auckland',
'@tzres.dll,-741': 'Pacific/Auckland',
'@tzres.dll,-742': 'Pacific/Auckland',
'@tzres.dll,-80': 'Canada/Atlantic',
'@tzres.dll,-81': 'Canada/Atlantic',
'@tzres.dll,-82': 'Canada/Atlantic',
'@tzres.dll,-840': 'America/Argentina/Buenos_Aires',
'@tzres.dll,-841': 'America/Argentina/Buenos_Aires',
'@tzres.dll,-842': 'America/Argentina/Buenos_Aires',
'@tzres.dll,-870': 'Asia/Karachi',
'@tzres.dll,-871': 'Asia/Karachi',
'@tzres.dll,-872': 'Asia/Karachi',
'@tzres.dll,-880': 'UTC',
'@tzres.dll,-930': 'UTC',
'@tzres.dll,-931': 'UTC',
'@tzres.dll,-932': 'UTC',
'USEasternStandardTime': 'EST5EDT',
'USMountainStandardTime': 'MST7MDT',
'W.AustraliaStandardTime': 'Australia/Perth',
'W.CentralAfricaStandardTime': 'Europe/Belgrade',
'W.EuropeStandardTime': 'Europe/Belgrade',
'(UTC) Coordinated Universal Time': 'UTC',
}
# Values of @tzres.dll,-[0-9]+
# 10 (UTC-01:00) Azores
# 11 Azores Daylight Time
# 12 Azores Standard Time
# 20 (UTC-01:00) Cape Verde Is.
# 21 Cape Verde Daylight Time
# 22 Cape Verde Standard Time
# 30 (UTC-02:00) Mid-Atlantic
# 31 Mid-Atlantic Daylight Time
# 32 Mid-Atlantic Standard Time
# 40 (UTC-03:00) Brasilia
# 41 E. South America Daylight Time
# 42 E. South America Standard Time
# 50 (UTC-03:00) Greenland
# 51 Greenland Daylight Time
# 52 Greenland Standard Time
# 60 (UTC-03:00) Buenos Aires, Georgetown
# 61 SA Eastern Daylight Time
# 62 SA Eastern Standard Time
# 70 (UTC-03:30) Newfoundland
# 71 Newfoundland Daylight Time
# 72 Newfoundland Standard Time
# 80 (UTC-04:00) Atlantic Time (Canada)
# 81 Atlantic Daylight Time
# 82 Atlantic Standard Time
# 90 (UTC-04:00) Santiago
# 91 Pacific SA Daylight Time
# 92 Pacific SA Standard Time
# 100 (UTC-04:00) Caracas, La Paz
# 101 SA Western Daylight Time
# 102 SA Western Standard Time
# 103 (UTC-04:00) Manaus
# 104 Central Brazilian Daylight Time
# 105 Central Brazilian Standard Time
# 110 (UTC-05:00) Eastern Time (US & Canada)
# 111 Eastern Daylight Time
# 112 Eastern Standard Time
# 120 (UTC-05:00) Bogota, Lima, Quito, Rio Branco
# 121 SA Pacific Daylight Time
# 122 SA Pacific Standard Time
# 130 (UTC-05:00) Indiana (East)
# 131 US Eastern Daylight Time
# 132 US Eastern Standard Time
# 140 (UTC-06:00) Saskatchewan
# 141 Canada Central Daylight Time
# 142 Canada Central Standard Time
# 150 (UTC-06:00) Central America
# 151 Central America Daylight Time
# 152 Central America Standard Time
# 160 (UTC-06:00) Central Time (US & Canada)
# 161 Central Daylight Time
# 162 Central Standard Time
# 170 (UTC-06:00) Guadalajara, Mexico City, Monterrey
# 171 Central Daylight Time (Mexico)
# 172 Central Standard Time (Mexico)
# 180 (UTC-07:00) Chihuahua, La Paz, Mazatlan
# 181 Mountain Daylight Time (Mexico)
# 182 Mountain Standard Time (Mexico)
# 190 (UTC-07:00) Mountain Time (US & Canada)
# 191 Mountain Daylight Time
# 192 Mountain Standard Time
# 200 (UTC-07:00) Arizona
# 201 US Mountain Daylight Time
# 202 US Mountain Standard Time
# 210 (UTC-08:00) Pacific Time (US & Canada)
# 211 Pacific Daylight Time
# 212 Pacific Standard Time
# 213 (UTC-08:00) Tijuana, Baja California
# 214 Pacific Daylight Time (Mexico)
# 215 Pacific Standard Time (Mexico)
# 220 (UTC-09:00) Alaska
# 221 Alaskan Daylight Time
# 222 Alaskan Standard Time
# 230 (UTC-10:00) Hawaii
# 231 Hawaiian Daylight Time
# 232 Hawaiian Standard Time
# 240 (UTC-11:00) Midway Island, Samoa
# 241 Samoa Daylight Time
# 242 Samoa Standard Time
# 250 (UTC-12:00) International Date Line West
# 251 Dateline Daylight Time
# 252 Dateline Standard Time
# 260 (UTC) Dublin, Edinburgh, Lisbon, London
# 261 GMT Daylight Time
# 262 GMT Standard Time
# 270 (UTC) Casablanca, Monrovia, Reykjavik
# 271 Greenwich Daylight Time
# 272 Greenwich Standard Time
# 280 (UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague
# 281 Central Europe Daylight Time
# 282 Central Europe Standard Time
# 290 (UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb
# 291 Central European Daylight Time
# 292 Central European Standard Time
# 300 (UTC+01:00) Brussels, Copenhagen, Madrid, Paris
# 301 Romance Daylight Time
# 302 Romance Standard Time
# 310 (UTC+01:00) West Central Africa
# 311 W. Central Africa Daylight Time
# 312 W. Central Africa Standard Time
# 320 (UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna
# 321 W. Europe Daylight Time
# 322 W. Europe Standard Time
# 330 (UTC+02:00) Minsk
# 331 E. Europe Daylight Time
# 332 E. Europe Standard Time
# 333 (UTC+02:00) Amman
# 334 Jordan Daylight Time
# 335 Jordan Standard Time
# 340 (UTC+02:00) Cairo
# 341 Egypt Daylight Time
# 342 Egypt Standard Time
# 350 (UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius
# 351 FLE Daylight Time
# 352 FLE Standard Time
# 360 (UTC+02:00) Athens, Bucharest, Istanbul
# 361 GTB Daylight Time
# 362 GTB Standard Time
# 363 (UTC+02:00) Beirut
# 364 Middle East Daylight Time
# 365 Middle East Standard Time
# 370 (UTC+02:00) Jerusalem
# 371 Jerusalem Daylight Time
# 372 Jerusalem Standard Time
# 380 (UTC+02:00) Harare, Pretoria
# 381 South Africa Daylight Time
# 382 South Africa Standard Time
# 383 (UTC+02:00) Windhoek
# 384 Namibia Daylight Time
# 385 Namibia Standard Time
# 390 (UTC+03:00) Kuwait, Riyadh
# 391 Arab Daylight Time
# 392 Arab Standard Time
# 400 (UTC+03:00) Baghdad
# 401 Arabic Daylight Time
# 402 Arabic Standard Time
# 410 (UTC+03:00) Nairobi
# 411 E. Africa Daylight Time
# 412 E. Africa Standard Time
# 420 (UTC+03:00) Moscow, St. Petersburg, Volgograd
# 421 Russian Daylight Time
# 422 Russian Standard Time
# 430 (UTC+03:30) Tehran
# 431 Iran Daylight Time
# 432 Iran Standard Time
# 433 (UTC+03:00) Tbilisi
# 434 Georgian Daylight Time
# 435 Georgian Standard Time
# 440 (UTC+04:00) Abu Dhabi, Muscat
# 441 Arabian Daylight Time
# 442 Arabian Standard Time
# 447 (UTC+04:00) Baku
# 448 Azerbaijan Daylight Time
# 449 Azerbaijan Standard Time
# 450 (UTC+04:00) Yerevan
# 451 Caucasus Daylight Time
# 452 Caucasus Standard Time
# 460 (UTC+04:30) Kabul
# 461 Afghanistan Daylight Time
# 462 Afghanistan Standard Time
# 470 (UTC+05:00) Ekaterinburg
# 471 Ekaterinburg Daylight Time
# 472 Ekaterinburg Standard Time
# 480 (UTC+05:00) Islamabad, Karachi, Tashkent
# 481 West Asia Daylight Time
# 482 West Asia Standard Time
# 490 (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi
# 491 India Daylight Time
# 492 India Standard Time
# 500 (UTC+05:45) Kathmandu
# 501 Nepal Daylight Time
# 502 Nepal Standard Time
# 510 (UTC+06:00) Astana, Dhaka
# 511 Central Asia Daylight Time
# 512 Central Asia Standard Time
# 520 (UTC+06:00) Almaty, Novosibirsk
# 521 N. Central Asia Daylight Time
# 522 N. Central Asia Standard Time
# 530 (UTC+05:30) Sri Jayawardenepura
# 531 Sri Lanka Daylight Time
# 532 Sri Lanka Standard Time
# 540 (UTC+06:30) Yangon (Rangoon)
# 541 Myanmar Daylight Time
# 542 Myanmar Standard Time
# 550 (UTC+07:00) Krasnoyarsk
# 551 North Asia Daylight Time
# 552 North Asia Standard Time
# 560 (UTC+07:00) Bangkok, Hanoi, Jakarta
# 561 SE Asia Daylight Time
# 562 SE Asia Standard Time
# 570 (UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi
# 571 China Daylight Time
# 572 China Standard Time
# 580 (UTC+08:00) Irkutsk, Ulaan Bataar
# 581 North Asia East Daylight Time
# 582 North Asia East Standard Time
# 590 (UTC+08:00) Kuala Lumpur, Singapore
# 591 Malay Peninsula Daylight Time
# 592 Malay Peninsula Standard Time
# 600 (UTC+08:00) Taipei
# 601 Taipei Daylight Time
# 602 Taipei Standard Time
# 610 (UTC+08:00) Perth
# 611 W. Australia Daylight Time
# 612 W. Australia Standard Time
# 620 (UTC+09:00) Seoul
# 621 Korea Daylight Time
# 622 Korea Standard Time
# 630 (UTC+09:00) Osaka, Sapporo, Tokyo
# 631 Tokyo Daylight Time
# 632 Tokyo Standard Time
# 640 (UTC+09:00) Yakutsk
# 641 Yakutsk Daylight Time
# 642 Yakutsk Standard Time
# 650 (UTC+09:30) Darwin
# 651 AUS Central Daylight Time
# 652 AUS Central Standard Time
# 660 (UTC+09:30) Adelaide
# 661 Cen. Australia Daylight Time
# 662 Cen. Australia | |
from __future__ import absolute_import, print_function, division, unicode_literals
import six
from sys import version_info
import pytest
import requests
import responses
from requests.exceptions import ConnectionError
from responses import matchers
def assert_response(resp, body=None, content_type="text/plain"):
assert resp.status_code == 200
assert resp.reason == "OK"
assert resp.headers["Content-Type"] == content_type
assert resp.text == body
def assert_reset():
assert len(responses._default_mock._matches) == 0
assert len(responses.calls) == 0
def test_query_string_matcher():
@responses.activate
def run():
url = "http://example.com?test=1&foo=bar"
responses.add(
responses.GET,
url,
body=b"test",
match=[matchers.query_string_matcher("test=1&foo=bar")],
)
resp = requests.get("http://example.com?test=1&foo=bar")
assert_response(resp, "test")
resp = requests.get("http://example.com?foo=bar&test=1")
assert_response(resp, "test")
resp = requests.get("http://example.com/?foo=bar&test=1")
assert_response(resp, "test")
run()
assert_reset()
def test_request_matches_post_params():
@responses.activate
def run(deprecated):
if deprecated:
json_params_matcher = getattr(responses, "json_params_matcher")
urlencoded_params_matcher = getattr(responses, "urlencoded_params_matcher")
else:
json_params_matcher = matchers.json_params_matcher
urlencoded_params_matcher = matchers.urlencoded_params_matcher
responses.add(
method=responses.POST,
url="http://example.com/",
body="one",
match=[json_params_matcher({"page": {"name": "first", "type": "json"}})],
)
responses.add(
method=responses.POST,
url="http://example.com/",
body="two",
match=[urlencoded_params_matcher({"page": "second", "type": "urlencoded"})],
)
resp = requests.request(
"POST",
"http://example.com/",
headers={"Content-Type": "x-www-form-urlencoded"},
data={"page": "second", "type": "urlencoded"},
)
assert_response(resp, "two")
resp = requests.request(
"POST",
"http://example.com/",
headers={"Content-Type": "application/json"},
json={"page": {"name": "first", "type": "json"}},
)
assert_response(resp, "one")
with pytest.deprecated_call():
run(deprecated=True)
assert_reset()
run(deprecated=False)
assert_reset()
def test_request_matches_empty_body():
def run():
with responses.RequestsMock(assert_all_requests_are_fired=True) as rsps:
# test that both json and urlencoded body are empty in matcher and in request
rsps.add(
method=responses.POST,
url="http://example.com/",
body="one",
match=[matchers.json_params_matcher(None)],
)
rsps.add(
method=responses.POST,
url="http://example.com/",
body="two",
match=[matchers.urlencoded_params_matcher(None)],
)
resp = requests.request("POST", "http://example.com/")
assert_response(resp, "one")
resp = requests.request(
"POST",
"http://example.com/",
headers={"Content-Type": "x-www-form-urlencoded"},
)
assert_response(resp, "two")
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
# test exception raise if matcher body is None but request data is not None
rsps.add(
method=responses.POST,
url="http://example.com/",
body="one",
match=[matchers.json_params_matcher(None)],
)
with pytest.raises(ConnectionError) as excinfo:
resp = requests.request(
"POST",
"http://example.com/",
json={"my": "data"},
headers={"Content-Type": "application/json"},
)
msg = str(excinfo.value)
assert "request.body doesn't match: {my: data} doesn't match {}" in msg
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.POST,
url="http://example.com/",
body="two",
match=[matchers.urlencoded_params_matcher(None)],
)
with pytest.raises(ConnectionError) as excinfo:
resp = requests.request(
"POST",
"http://example.com/",
headers={"Content-Type": "x-www-form-urlencoded"},
data={"page": "second", "type": "urlencoded"},
)
msg = str(excinfo.value)
assert (
"request.body doesn't match: {page: second, type: urlencoded} doesn't match {}"
in msg
)
run()
assert_reset()
def test_request_matches_params():
@responses.activate
def run():
url = "http://example.com/test"
params = {"hello": "world", "I am": "a big test"}
responses.add(
method=responses.GET,
url=url,
body="test",
match=[matchers.query_param_matcher(params)],
match_querystring=False,
)
# exchange parameter places for the test
params = {
"I am": "a big test",
"hello": "world",
}
resp = requests.get(url, params=params)
if six.PY3 and version_info[1] >= 7:
# only after py 3.7 dictionaries are ordered, so we can check URL
constructed_url = r"http://example.com/test?I+am=a+big+test&hello=world"
assert resp.url == constructed_url
assert resp.request.url == constructed_url
resp_params = getattr(resp.request, "params")
assert resp_params == params
run()
assert_reset()
def test_fail_matchers_error():
"""
Validate that Exception is raised if request does not match responses.matchers
validate matchers.urlencoded_params_matcher
validate matchers.json_params_matcher
validate matchers.query_param_matcher
validate matchers.request_kwargs_matcher
:return: None
"""
def run():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
"POST",
"http://example.com",
match=[matchers.urlencoded_params_matcher({"foo": "bar"})],
)
rsps.add(
"POST",
"http://example.com",
match=[matchers.json_params_matcher({"fail": "json"})],
)
with pytest.raises(ConnectionError) as excinfo:
requests.post("http://example.com", data={"id": "bad"})
msg = str(excinfo.value)
assert (
"request.body doesn't match: {id: bad} doesn't match {foo: bar}" in msg
)
assert (
"request.body doesn't match: JSONDecodeError: Cannot parse request.body"
in msg
)
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
"GET",
"http://111.com",
match=[matchers.query_param_matcher({"my": "params"})],
)
rsps.add(
method=responses.GET,
url="http://111.com/",
body="two",
match=[matchers.json_params_matcher({"page": "one"})],
)
with pytest.raises(ConnectionError) as excinfo:
requests.get(
"http://111.com", params={"id": "bad"}, json={"page": "two"}
)
msg = str(excinfo.value)
assert (
"Parameters do not match. {id: bad} doesn't match {my: params}" in msg
)
assert (
"request.body doesn't match: {page: two} doesn't match {page: one}"
in msg
)
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
req_kwargs = {
"stream": True,
"verify": False,
}
rsps.add(
"GET",
"http://111.com",
match=[matchers.request_kwargs_matcher(req_kwargs)],
)
with pytest.raises(ConnectionError) as excinfo:
requests.get("http://111.com", stream=True)
msg = str(excinfo.value)
assert (
"Arguments don't match: "
"{stream: True, verify: True} doesn't match {stream: True, verify: False}"
) in msg
run()
assert_reset()
@pytest.mark.parametrize(
"req_file,match_file",
[
(b"Old World!", "Old World!"),
("Old World!", b"Old World!"),
(b"Old World!", b"Old World!"),
("Old World!", "Old World!"),
(b"\xacHello World!", b"\xacHello World!"),
],
)
def test_multipart_matcher(req_file, match_file):
@responses.activate
def run():
req_data = {"some": "other", "data": "fields"}
responses.add(
responses.POST,
url="http://httpbin.org/post",
match=[
matchers.multipart_matcher(
files={"file_name": match_file}, data=req_data
)
],
)
resp = requests.post(
"http://httpbin.org/post", data=req_data, files={"file_name": req_file}
)
assert resp.status_code == 200
with pytest.raises(TypeError):
responses.add(
responses.POST,
url="http://httpbin.org/post",
match=[matchers.multipart_matcher(files={})],
)
run()
assert_reset()
def test_multipart_matcher_fail():
"""
Validate that Exception is raised if request does not match responses.matchers
validate matchers.multipart_matcher
:return: None
"""
def run():
# different file contents
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
req_data = {"some": "other", "data": "fields"}
req_files = {"file_name": b"Old World!"}
rsps.add(
responses.POST,
url="http://httpbin.org/post",
match=[matchers.multipart_matcher(req_files, data=req_data)],
)
with pytest.raises(ConnectionError) as excinfo:
requests.post(
"http://httpbin.org/post",
data=req_data,
files={"file_name": b"New World!"},
)
msg = str(excinfo.value)
assert "multipart/form-data doesn't match. Request body differs." in msg
if six.PY2:
assert (
'\r\nContent-Disposition: form-data; name="file_name"; '
'filename="file_name"\r\n\r\nOld World!\r\n'
) in msg
assert (
'\r\nContent-Disposition: form-data; name="file_name"; '
'filename="file_name"\r\n\r\nNew World!\r\n'
) in msg
else:
assert (
r'\r\nContent-Disposition: form-data; name="file_name"; '
r'filename="file_name"\r\n\r\nOld World!\r\n'
) in msg
assert (
r'\r\nContent-Disposition: form-data; name="file_name"; '
r'filename="file_name"\r\n\r\nNew World!\r\n'
) in msg
# x-www-form-urlencoded request
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
req_data = {"some": "other", "data": "fields"}
req_files = {"file_name": b"Old World!"}
rsps.add(
responses.POST,
url="http://httpbin.org/post",
match=[matchers.multipart_matcher(req_files, data=req_data)],
)
with pytest.raises(ConnectionError) as excinfo:
requests.post("http://httpbin.org/post", data=req_data)
msg = str(excinfo.value)
assert (
"multipart/form-data doesn't match. Request headers['Content-Type'] is different."
in msg
)
assert (
"application/x-www-form-urlencoded isn't equal to multipart/form-data; boundary="
in msg
)
# empty body request
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
req_files = {"file_name": b"Old World!"}
rsps.add(
responses.POST,
url="http://httpbin.org/post",
match=[matchers.multipart_matcher(req_files)],
)
with pytest.raises(ConnectionError) as excinfo:
requests.post("http://httpbin.org/post")
msg = str(excinfo.value)
assert "Request is missing the 'Content-Type' header" in msg
run()
assert_reset()
def test_query_string_matcher_raises():
"""
Validate that Exception is raised if request does not match responses.matchers
validate matchers.query_string_matcher
:return: None
"""
def run():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
"GET",
"http://111.com",
match=[matchers.query_string_matcher("didi=pro")],
)
with pytest.raises(ConnectionError) as excinfo:
requests.get("http://111.com", params={"test": "1", "didi": "pro"})
msg = str(excinfo.value)
assert (
"Query string doesn't match. {didi: pro, test: 1} doesn't match {didi: pro}"
in msg
)
run()
assert_reset()
def test_request_matches_headers():
@responses.activate
def run():
url = "http://example.com/"
responses.add(
method=responses.GET,
url=url,
json={"success": True},
match=[matchers.header_matcher({"Accept": "application/json"})],
)
responses.add(
method=responses.GET,
url=url,
body="success",
match=[matchers.header_matcher({"Accept": "text/plain"})],
)
# the actual request can contain extra headers (requests always adds some itself anyway)
resp = requests.get(
url, headers={"Accept": "application/json", "Accept-Charset": "utf-8"}
)
assert_response(resp, body='{"success": true}', content_type="application/json")
resp = requests.get(url, headers={"Accept": "text/plain"})
assert_response(resp, body="success", content_type="text/plain")
run()
assert_reset()
def test_request_matches_headers_no_match():
@responses.activate
def run():
url = "http://example.com/"
responses.add(
method=responses.GET,
url=url,
json={"success": True},
match=[matchers.header_matcher({"Accept": "application/json"})],
)
with pytest.raises(ConnectionError) as excinfo:
requests.get(url, headers={"Accept": "application/xml"})
msg = str(excinfo.value)
assert (
"Headers do not match: {Accept: application/xml} doesn't match "
"{Accept: application/json}"
) in msg
run()
assert_reset()
def test_request_matches_headers_strict_match():
@responses.activate
def run():
url = "http://example.com/"
responses.add(
method=responses.GET,
url=url,
body="success",
match=[
matchers.header_matcher({"Accept": "text/plain"}, strict_match=True)
],
)
# requests will add some extra headers of its own, so we have to use prepared requests
session = requests.Session()
# make sure we send *just* the header we're expectin
prepped = session.prepare_request(
requests.Request(
method="GET",
url=url,
)
)
prepped.headers.clear()
prepped.headers["Accept"] = "text/plain"
resp = session.send(prepped)
assert_response(resp, body="success", content_type="text/plain")
# include the "Accept-Charset" header, which will fail to match
prepped = session.prepare_request(
requests.Request(
method="GET",
url=url,
)
)
prepped.headers.clear()
prepped.headers["Accept"] = "text/plain"
prepped.headers["Accept-Charset"] = "utf-8"
with pytest.raises(ConnectionError) as excinfo:
session.send(prepped)
msg = str(excinfo.value)
assert (
"Headers do not match: {Accept: text/plain, Accept-Charset: utf-8} "
"doesn't match {Accept: text/plain}"
) in msg
run()
assert_reset()
def test_fragment_identifier_matcher():
@responses.activate
def run():
responses.add(
responses.GET,
"http://example.com",
match=[matchers.fragment_identifier_matcher("test=1&foo=bar")],
body=b"test",
)
resp = requests.get("http://example.com#test=1&foo=bar")
assert_response(resp, "test")
run()
assert_reset()
def test_fragment_identifier_matcher_error():
@responses.activate
def run():
responses.add(
responses.GET,
"http://example.com/",
match=[matchers.fragment_identifier_matcher("test=1")],
)
responses.add(
responses.GET,
"http://example.com/",
match=[matchers.fragment_identifier_matcher(None)],
)
with pytest.raises(ConnectionError) as excinfo:
requests.get("http://example.com/#test=2")
msg = str(excinfo.value)
assert (
"URL fragment identifier is different: test=1 doesn't match test=2"
) in msg
assert (
"URL fragment identifier is different: None doesn't match test=2"
) in msg
run()
assert_reset()
def test_fragment_identifier_matcher_and_match_querystring():
@responses.activate
def run():
url = "http://example.com?ab=xy&zed=qwe#test=1&foo=bar"
responses.add(
responses.GET,
url,
match_querystring=True,
match=[matchers.fragment_identifier_matcher("test=1&foo=bar")],
body=b"test",
)
# two requests to check reversed order of fragment identifier
resp = requests.get("http://example.com?ab=xy&zed=qwe#test=1&foo=bar")
assert_response(resp, "test")
resp = requests.get("http://example.com?zed=qwe&ab=xy#foo=bar&test=1")
assert_response(resp, "test")
run()
assert_reset()
def test_matchers_create_key_val_str():
"""
Test that matchers._create_key_val_str does recursive conversion
"""
data = {
"my_list": [
1,
2,
"a",
{"key1": "val1", "key2": 2, 3: "test"},
"!",
[["list", "nested"], {"nested": "dict"}],
],
1: 4,
"test": "val",
"high": {"nested": "nested_dict"},
}
conv_str = matchers._create_key_val_str(data)
reference = (
"{1: 4, high: {nested: nested_dict}, my_list: | |
<gh_stars>0
# -*- coding: utf-8 -*-
#!/usr/bin/python
import math
import numpy as np
import os
# Please cite https://tc.copernicus.org/articles/9/1797/2015/
# for original source --
#@Article{tc-9-1797-2015,
#AUTHOR = {<NAME>}<NAME>.},
#TITLE = {Inter-comparison and evaluation of sea ice algorithms: towards further identification of challenges and optimal approach using passive microwave observations},
#JOURNAL = {The Cryosphere},
#VOLUME = {9},
#YEAR = {2015},
#NUMBER = {5},
#PAGES = {1797--1817},
#URL = {https://tc.copernicus.org/articles/9/1797/2015/},
#DOI = {10.5194/tc-9-1797-2015}
#}
def asi(tb85v, tb85h):
"""The asi ice concentration algorithm
"""
P0 = 47.0
P1 = 7.5
P = tb85v - tb85h
"""method coefficients:"""
d3=1.64/100000.0
d2=-0.0016
d1=0.0192
d0=0.971
"""concentrations calculation:"""
ct = d3 * P**3.0 + d2 * P**2.0 + d1 * P + d0
return ct
def bootstrap_f(tb18v, tb37v, tiepts):
tw18v = tiepts[6]
tw37v = tiepts[0]
tfy18v = tiepts[8]
tfy37v = tiepts[2]
tmy18v = tiepts[7]
tmy37v = tiepts[1]
if (tb18v-tw18v)==0:
cf=np.nan
else:
af = (tfy37v - tmy37v)/(tfy18v - tmy18v)
bf = (tmy37v - af*tmy18v)
qf = (tb37v - tw37v)/(tb18v - tw18v)
wf = (tw37v - qf*tw18v)
ti18vf = (bf - wf)/(qf - af)
cf = (tb18v - tw18v)/(ti18vf - tw18v)
return cf
def bootstrap_p(tb37v, tb37h, tiepts):
tw37h = tiepts[3]
tw37v = tiepts[0]
tfy37h = tiepts[5]
tfy37v = tiepts[2]
tmy37h = tiepts[4]
tmy37v = tiepts[1]
if (tb37h-tw37h)==0:
cp=np.nan
else:
ap = (tfy37v - tmy37v) / (tfy37h - tmy37h)
bp = (tmy37v - ap * tmy37h)
qp = (tb37v - tw37v) / (tb37h - tw37h)
wp = (tw37v - qp * tw37h)
if (qp - ap)==0:
cp=np.nan
else:
ti37hp = (bp - wp) / (qp - ap)
ti37vp = ap * ti37hp + bp
if (ti37vp - tw37v)==0:
cp=np.nan
else:
cp = (tb37v - tw37v) / (ti37vp - tw37v)
return cp
def bristol(tb18v, tb37v, tb37h, tiepts):
"""Bristol ice concentration algorithm
"""
tw18v = tiepts[6]
tw37h = tiepts[3]
tw37v = tiepts[0]
tfy18v = tiepts[8]
tfy37h = tiepts[5]
tfy37v = tiepts[2]
tmy18v = tiepts[7]
tmy37h = tiepts[4]
tmy37v = tiepts[1]
xa = tmy37v + (1.045*tmy37h) + (0.525*tmy18v)
xd = tfy37v + (1.045*tfy37h) + (0.525*tfy18v)
xh = tw37v + (1.045*tw37h) + (0.525*tw18v)
xt = tb37v +(1.045*tb37h) + (0.525*tb18v)
ya = (0.9164*tmy18v) - tmy37v + (0.4965*tmy37h)
yd = (0.9164*tfy18v) - tfy37v + (0.4965*tfy37h)
yh = (0.9164*tw18v) - tw37v + (0.4965*tw37h)
yt = (0.9164*tb18v)- tb37v + (0.4965*tb37h)
a_ht = (yt - yh)/(xt - xh)
b_ht = yh - (a_ht*xh)
a_da = (ya - yd)/(xa - xd)
b_da = yd - (a_da*xd)
xi = (b_da - b_ht)/(a_ht - a_da)
cf = (xt - xh)/(xi - xh)
c = cf
return c
def calval(tb37v,tb18v,tiepts):
tw18v = tiepts[6]
tw37v = tiepts[0]
tfy18v = tiepts[8]
tfy37v = tiepts[2]
tmy18v = tiepts[7]
tmy37v = tiepts[1]
A=np.matrix([[tw37v, tw18v, 1.0],\
[tfy37v, tfy18v, 1.0],\
[tmy37v, tmy18v, 1.0]])
b=np.matrix([0.0, 1.0, 1.0])
d=A.I * b.T
C=d[0]*tb37v+d[1]*tb18v+d[2]
return C
def nasa(tb18v, tb18h, tb37v, tiepts):
"""NASA-Team ice concetration algorithm
"""
ow18v = tiepts[6]
ow18h = tiepts[9]
ow37v = tiepts[0]
fy18v = tiepts[8]
fy18h = tiepts[11]
fy37v = tiepts[2]
my18v = tiepts[7]
my18h = tiepts[10]
my37v = tiepts[1]
a0 = - ow18v + ow18h
a1 = ow18v + ow18h
a2 = my18v - my18h - ow18v + ow18h
a3 = - my18v - my18h + ow18v + ow18h
a4 = fy18v - fy18h - ow18v + ow18h
a5 = - fy18v - fy18h + ow18v + ow18h
b0 = - ow37v + ow18v
b1 = ow37v + ow18v
b2 = my37v - my18v - ow37v + ow18v
b3 = - my37v - my18v + ow37v + ow18v
b4 = fy37v - fy18v - ow37v + ow18v
b5 = - fy37v - fy18v + ow37v + ow18v
gr = (tb37v - tb18v)/(tb37v + tb18v)
pr = (tb18v - tb18h)/(tb18v + tb18h)
d0 = (-a2*b4) + (a4*b2)
d1 = (-a3*b4) + (a5*b2)
d2 = (-a2*b5) + (a4*b3)
d3 = (-a3*b5) + (a5*b3)
dd = d0 + d1*pr + d2*gr + d3*pr*gr
f0 = (a0*b2) - (a2*b0)
f1 = (a1*b2) - (a3*b0)
f2 = (a0*b3) - (a2*b1)
f3 = (a1*b3) - (a3*b1)
m0 = (-a0*b4) + (a4*b0)
m1 = (-a1*b4) + (a5*b0)
m2 = (-a0*b5) + (a4*b1)
m3 = (-a1*b5) + (a5*b1)
cf = (f0 + f1*pr + f2*gr + f3*pr*gr)/dd
cm = (m0 + m1*pr + m2*gr + m3*pr*gr)/dd
cf = cf
cm = cm
ct = cm + cf
return ct
def nasa2(tb18v, tb18h, tb37v, tb85v, tb85h):
"""The NASA Team 2 ice concentration algorithm
"""
"""NASA Team2 Model Data:"""
tbmow = readtxt2matrix('InputNT2/tbmow.txt')
tbmfy = readtxt2matrix('InputNT2/tbmfy.txt')
tbmcc = readtxt2matrix('InputNT2/tbmcc.txt')
tbmthin = readtxt2matrix('InputNT2/tbmthin.txt')
gr3719=(tb37v-tb18v)/(tb37v+tb18v)
"""number of atmospheres (models of atmosphere):"""
n_atm=12
"""Rotation:"""
"""angle in radians between GR-axis and A-B line (FY-MY line) for the PR(19)-GR(37V19V) damain. Arctic:"""
phi19=-0.18
"""angle in radians between GR-axis and A-B line (FY-MY line) for the PR(85)-GR(37V19V) damain. Arctic:"""
phi85=-0.06
"""Allocate memory:"""
LUT19=readtxt2matrix3D('InputNT2/LUT19_')
LUT85=readtxt2matrix3D('InputNT2/LUT85_')
LUT19thin=readtxt2matrix3D('InputNT2/LUT19thin_')
LUT85thin=readtxt2matrix3D('InputNT2/LUT85thin_')
LUTDGR=readtxt2matrix3D('InputNT2/LUTDGR_')
LUTGR37=readtxt2matrix3D('InputNT2/LUTGR37_')
camina=np.zeros((n_atm,1))
ccmina=np.zeros((n_atm,1))
dmina=np.zeros((n_atm,1))
"""calculate ice concentrations:"""
"""weights:"""
w19=1
w85=1
wgr=1
sinphi19=math.sin(phi19)
sinphi85=math.sin(phi85)
cosphi19=math.cos(phi19)
cosphi85=math.cos(phi85)
pr19=(tb18v-tb18h)/(tb18v+tb18h)
pr85=(tb85v-tb85h)/(tb85v+tb85h)
gr8519v=(tb85v-tb18v)/(tb85v+tb18v)
gr8519h=(tb85h-tb18h)/(tb85h+tb18h)
pr19r=-gr3719*sinphi19 + pr19*cosphi19
pr85r=-gr3719*sinphi85 + pr85*cosphi85
dgr=gr8519h-gr8519v
dmin=10000
for k in range(0,n_atm-1):
imin=5
jmin=5
ca=45
cc=45
while ((imin !=0) | (jmin != 0)):
dmin=10000
for i in range(-1,1):
for j in range(-1,1):
cai=ca+i
ccj=cc+j
if ((cai<121) & (ccj<121) & (cai>=1) & (ccj>=1) & ((cai+ccj)>=0) & ((cai+ccj)<121)):
if gr3719 > -0.01:
dpr19=pr19r-LUT19thin[k,cai,ccj]
dpr85=pr85r-LUT85thin[k,cai,ccj]
ddgr=gr3719-LUTGR37[k,cai,ccj]
else:
dpr19=pr19r-LUT19[k,cai,ccj]
dpr85=pr85r-LUT85[k,cai,ccj]
ddgr=dgr-LUTDGR[k,cai,ccj]
d=w19*dpr19*dpr19+w85*dpr85*dpr85+wgr*ddgr*ddgr
if d < dmin:
dmin=d
imin=i
jmin=j
ca=ca+imin
cc=cc+jmin
camina[k]=ca
ccmina[k]=cc
dmina[k]=dmin
bestk=20
dmin=1000
for k in range(0,n_atm-1):
if dmina[k] < dmin:
dmin=dmina[k]
bestk=k
CT=(camina[bestk]+ccmina[bestk])/100
return CT
def near90(tb85v, tb85h, tiepts):
tmy85v = tiepts[30]
tfy85v = tiepts[31]
tmy85h = tiepts[32]
tfy85h = tiepts[33]
tw85v = tiepts[34]
tw85h = tiepts[35]
P = tb85v - tb85h
P0 = tw85v - tw85h
P1 = tfy85v - tfy85h
A=np.matrix([[P1**3.0, P1**2.0, P1, 1.0],\
[P0**3.0, P0**2.0, P0, 1.0],\
[3.0*P1**3.0, 2.0*P1**2.0, P1, 0.0],\
[3.0*P0**3.0, 2.0*P0**2.0, P0, 0.0]])
b=np.matrix([1.0, 0.0, -0.14, -1.14])
d=A.I * b.T
#d=np.linalg.solve(A,b.T)
C = d[0] * P**3 + d[1] * P**2 + d[2] * P + d[3]
return np.float(C)
def near90_linear(tb85v, tb85h):
ct=1.22673-0.02652*(tb85v-tb85h)
return ct
def norsex(tb18v,tb37v,tiepts):
SAT = 260.0
T_sa = 270.0
T_a = 250.0
To = 272.0
tau_sa19v = 0.0610
tau_sa37v = 0.1000
tau_a19v = 0.0440
tau_a37v = 0.0700
TB_w_19v = tiepts[6]
TB_w_37v = tiepts[0]
TB_fy_19v = tiepts[8]
TB_fy_37v = tiepts[2]
TB_my_19v = tiepts[7]
TB_my_37v = tiepts[1]
#the sea ice temperature
T_ice = 0.4*SAT + 0.6*To
#Constants to be used in computing ice concentrations:
a11 = TB_fy_19v - TB_w_19v
a21 = TB_fy_37v - TB_w_37v
a12 = TB_my_19v - TB_w_19v
a22 = TB_my_37v - TB_w_37v
d_coef = a11 * a22 - a12 * a21
#Initialize atmospheric surface temperature:
t_atm_surf=SAT
#interpolate opacity between arctic and subarctic values:
tau19v = tau_a19v + (t_atm_surf - T_a) * (tau_sa19v - tau_a19v) / (T_sa - T_a)
tau37v = tau_a37v + (t_atm_surf - T_a) * (tau_sa37v - tau_a37v) / (T_sa - T_a)
#find emitted brightness temperature at the surface by correcting for
#atmospheric disturbances:
TB_surf_19v = (tb18v - t_atm_surf * (2.0 * tau19v - tau19v**2.0 + 0.01)) / (1.0 - 2.0 * tau19v + tau19v**2.0 - 0.01)
TB_surf_37v = (tb37v - t_atm_surf * (2.0 * tau37v - tau37v**2.0 + 0.01)) / (1.0 - 2.0 * tau37v + tau37v**2.0 - 0.01)
#Find new atmospheric surface brightness temperature and mean surface
#emissions by solving for first year and multi-year ice concentrations.
c1 = TB_surf_19v - TB_w_19v
c2 = TB_surf_37v - TB_w_37v
Cmy = (a11 * c2 - a21 * c1) / d_coef
Cfy = (a22 * c1 - a12 * c2) / d_coef
CT = Cfy + Cmy
t_atm_surf = To + (SAT - To) * CT
#interpolate opacity between arctic and subarctic values:
tau19v = tau_a19v + (t_atm_surf - T_a) * (tau_sa19v - tau_a19v) / (T_sa - T_a)
tau37v = tau_a37v + (t_atm_surf - T_a) * (tau_sa37v - tau_a37v) / (T_sa | |
numeric_fields is not None:
assert isinstance(numeric_fields, list)
for col in numeric_fields:
unlabeled_data[col] = unlabeled_data[col].apply(lambda x: x if x == "" else float(x))
if empty_str_to_none:
for col in unlabeled_data.columns.tolist():
empty_str_bool = (unlabeled_data[col] == "")
print("converting {} empty string values of column {} to None".format(empty_str_bool.sum(), col))
unlabeled_data.loc[empty_str_bool,col] = None
# converting NaNs of numeric columns (NaNs introduced because of the previous line) to None
if numeric_fields is not None:
for col in numeric_fields:
not_nan_bool = unlabeled_data[col].notnull()
print("converting {} NaN values of column {} to None".format((~not_nan_bool).sum(), col))
unlabeled_data[col] = unlabeled_data[col].where((not_nan_bool), None)
unlabeled_data = unlabeled_data.to_dict(orient = "index")
return unlabeled_data
def write_canonical_w_solo_unlabeled_data(canonicals_df, mapped_records_df, unlabeled_data,
canonical_w_solo_unlabeled_filepath):
# will be used for post cluster review, specifically on matching solos to clusters and merging clusters
# those two steps are based on the cluster canonicals
# remember to read in this written file using read_unlabeled_data_json later on
canonical_w_solo_data = canonicals_df.set_index("cluster id")\
.to_dict(orient = "index")
mapped_records_df = mapped_records_df.set_index("record id")
solo_records = mapped_records_df.loc[mapped_records_df["cluster type"] == "solo",:]\
.index.tolist()
for record_id in solo_records:
record = unlabeled_data[record_id]
cluster_id = mapped_records_df.loc[record_id,"cluster id"]
canonical_w_solo_data[cluster_id] = record
with open(canonical_w_solo_unlabeled_filepath, 'w') as outfile:
json.dump(canonical_w_solo_data, outfile)
def prepare_training_deduper(deduper, unlabeled_data, labeled_data_filepath, blocked_proportion = 0.5, sample_size = 15_000):
# If we have training data saved from a previous run of dedupe,
# look for it and load it in.
# __Note:__ if you want to train from scratch, delete the labeled_data_filepath
if os.path.exists(labeled_data_filepath):
print('reading labeled examples from ', labeled_data_filepath)
with open(labeled_data_filepath, 'rb') as labeled_data:
deduper.prepare_training(data = unlabeled_data, training_file = labeled_data,
blocked_proportion = blocked_proportion,
sample_size = sample_size)
else:
deduper.prepare_training(data = unlabeled_data, blocked_proportion = blocked_proportion,
sample_size = sample_size)
def save_trained_deduper(deduper, labeled_data_filepath, settings_filepath):
# When finished, save our training to disk
with open(labeled_data_filepath, 'w') as tf:
deduper.write_training(tf)
# Save our weights and predicates to disk. If the settings file
# exists, we will skip all the training and learning next time we run
# this file.
with open(settings_filepath, 'wb') as sf:
deduper.write_settings(sf)
def prepare_training_linker(linker, unlabeled_data_1, unlabeled_data_2, labeled_data_filepath, blocked_proportion = 0.5, sample_size = 15_000):
# If we have training data saved from a previous run of linker,
# look for it and load it in.
# __Note:__ if you want to train from scratch, delete the labeled_data_filepath
if os.path.exists(labeled_data_filepath):
print('reading labeled examples from ', labeled_data_filepath)
with open(labeled_data_filepath, 'rb') as labeled_data:
linker.prepare_training(data_1 = unlabeled_data_1, data_2 = unlabeled_data_2,
training_file = labeled_data,
blocked_proportion = blocked_proportion,
sample_size = sample_size)
else:
linker.prepare_training(data_1 = unlabeled_data_1, data_2 = unlabeled_data_2,
blocked_proportion = blocked_proportion,
sample_size = sample_size)
def save_trained_linker(linker, labeled_data_filepath, settings_filepath):
# When finished, save our training to disk
with open(labeled_data_filepath, 'w') as tf:
linker.write_training(tf)
# Save our weights and predicates to disk. If the settings file
# exists, we will skip all the training and learning next time we run
# this file.
with open(settings_filepath, 'wb') as sf:
linker.write_settings(sf)
def get_data_of_labeled_pairs(labeled_pairs_df, unlabeled_data):
df = pd.DataFrame.from_dict(unlabeled_data, orient = "index")
df_left = df.loc[labeled_pairs_df["record id 1"],:]
df_left.columns = ["{}_1".format(col) for col in df_left.columns]
df_left.index.name = "record id 1"
df_left = df_left.reset_index()
df_right = df.loc[labeled_pairs_df["record id 2"],:]
df_right.columns = ["{}_2".format(col) for col in df_right.columns]
df_right.index.name = "record id 2"
df_right = df_right.reset_index()
output = pd.concat([df_left, df_right], axis = 1, sort = False)
# sort columns
output = output.sort_index(axis = 1)
output = output.set_index(["record id 1", "record id 2"])
label_df = labeled_pairs_df.set_index(["record id 1", "record id 2"])
output = pd.merge(left = label_df, right = output, left_index = True, right_index = True, how = "inner")
return output
def get_deduped_data(mapped_records_df, canonicals_df, unlabeled_data, none_to_empty_str = True):
mapped_records_df = mapped_records_df.set_index("record id")
solo_record_ids = mapped_records_df.loc[mapped_records_df["cluster type"] == "solo","cluster id"].to_dict()
deduped_data = {cluster_id:unlabeled_data[record_id] for record_id,cluster_id in solo_record_ids.items()}
deduped_data = pd.DataFrame.from_dict(deduped_data, orient = "index")
deduped_data.index.name = "cluster id"
canonicals_df = canonicals_df.set_index("cluster id")
# appending the canonicalized cluster representations to the solo records
deduped_data = deduped_data.append(canonicals_df)
if none_to_empty_str:
deduped_data = deduped_data.where((deduped_data.notnull()), "")
return deduped_data
def write_deduper_blocks(deduper, unlabeled_data, blocks_filepath):
"""
simplify blocks by not writing the record entries, only the ids
"""
blocks = deduper.pairs(unlabeled_data)
with open(blocks_filepath, "w", newline = "") as csv_file:
writer = csv.writer(csv_file, quoting = csv.QUOTE_ALL)
header = ["block_id", "record_id"]
writer.writerow(header)
block_id = 1
for block in blocks:
"""
from dedupe source code:
Each item in a block must be a sequence of record_id, record and the
records also must be dictionaries
but we're only keeping the record_id, not the record here
"""
for record in block:
record_id, _, = record
block_entry = [block_id, record_id]
writer.writerow(block_entry)
block_id += 1
def read_deduper_blocks(unlabeled_data, blocks_filepath):
# assumes that the records are sorted by block number
current_block_id = None
block_records = []
"""
from dedupe source code:
Each item in a block must be a sequence of record_id, record, and the
records also must be dictionaries
"""
with open(blocks_filepath, "r") as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
block_id, record_id = row["block_id"], row["record_id"]
if current_block_id == block_id:
block_records.append((record_id, unlabeled_data[record_id]))
else:
if current_block_id is not None:
yield block_records
current_block_id = block_id
block_records = [(record_id, unlabeled_data[record_id])]
yield block_records
def write_linker_blocks(linker, unlabeled_data_1, unlabeled_data_2, blocks_filepath):
"""
simplify blocks by not writing the record entries, only the ids
"""
blocks = linker.pairs(unlabeled_data_1, unlabeled_data_2)
block_id = 1
with open(blocks_filepath, "w", newline = "") as csv_file:
writer = csv.writer(csv_file, quoting = csv.QUOTE_ALL)
header = ["record_set_num", "block_id", "record_id"]
writer.writerow(header)
for block in blocks:
rec_1, rec_2 = block
rec_1_id, _ = rec_1
block_entry = ["1", block_id, rec_1_id]
writer.writerow(block_entry)
rec_2_id, _ = rec_2
block_entry = ["2", block_id, rec_2_id]
writer.writerow(block_entry)
block_id += 1
def read_linker_blocks(unlabeled_data_1, unlabeled_data_2, blocks_filepath):
# assumes that the records sorted by block number
block_records = ()
block_set_1 = []
block_set_2 = []
current_block_id = None
"""
from dedupe source code:
Each block must be a made up of two sequences, (base_sequence, target_sequence)
"""
with open(blocks_filepath, "r") as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
record_set_num, block_id, record_id = row["record_set_num"], row["block_id"], row["record_id"]
if current_block_id == block_id:
if record_set_num == "1":
block_set_1.append((record_id, unlabeled_data_1[record_id]))
elif record_set_num == "2":
block_set_2.append((record_id, unlabeled_data_2[record_id]))
else:
raise ValueError("record_set_num should only be 1 or 2, but got {}".format(record_set_num))
else:
if current_block_id is not None:
block_records = (block_set_1, block_set_2)
yield block_records
current_block_id = block_id
if record_set_num == "1":
block_set_1 = [(record_id, unlabeled_data_1[record_id])]
block_set_2 = []
elif record_set_num == "2":
block_set_1 = []
block_set_2 = [(record_id, unlabeled_data_2[record_id])]
else:
raise ValueError("record_set_num should only be 1 or 2, but got {}".format(record_set_num))
block_records = (block_set_1, block_set_2)
yield block_records
def get_blocked_pairs(deduper_or_linker, blocked_data):
if isinstance(deduper_or_linker, dedupe.api.DedupeMatching):
pairs = (combinations(sorted(block), 2) for block in blocked_data)
elif isinstance(deduper_or_linker, dedupe.api.RecordLinkMatching):
pairs = (product(base, target) for base, target in blocked_data)
else:
raise ValueError("Passed not of class DedupeMatching or of RecordLinkMatching!")
return pairs
def count_blocked_pairs(deduper_or_linker, blocked_data):
candidate_records = itertools.chain.from_iterable(get_blocked_pairs(deduper_or_linker, blocked_data))
i = 0
for _ in candidate_records:
i += 1
return i
def write_training_set_from_pairs(labeled_pair_ids_df, labeled_data_filepath, unlabeled_data, unlabeled_data_2 = None):
# create a labeled training set directly for dedupe's consumption
labeled_data_train = {"distinct":[], "match":[]}
for _, row in labeled_pair_ids_df.iterrows():
rec_id_1 = row["record id 1"]
rec_id_2 = row["record id 2"]
rec_data_1 = unlabeled_data[rec_id_1]
if unlabeled_data_2 is None:
rec_data_2 = unlabeled_data[rec_id_2]
else:
rec_data_2 = unlabeled_data_2[rec_id_2]
label = row["label"]
data_entry = {
"__class__":"tuple",
"__value__":[rec_data_1, rec_data_2]
}
labeled_data_train[label].append(data_entry)
with open(labeled_data_filepath, "w") as json_file:
simplejson.dump(labeled_data_train,
json_file,
default=dedupe.serializer._to_json,
tuple_as_array=False,
ensure_ascii=True)
def get_deduped_data_for_rl(task_name, saved_files_path):
# gets deduped dataset from respective deduping for rl
dataset_name = task_name.split("-")[1]
dataset_1_name, dataset_2_name = dataset_name.split("_")
dedup_task_1 = "dedup-{}".format(dataset_1_name)
dedup_task_2 = "dedup-{}".format(dataset_2_name)
# get all filepaths
unlabeled_data_1_filepath, unlabeled_data_2_filepath = dm_file_checker.get_proper_unlabeled_data_filepath(task_name, saved_files_path)
numeric_fields_1, numeric_fields_2 = dm_file_checker.get_dataset_info(task_name, "numeric_fields", saved_files_path)
print("Numeric fields 1 are {}".format(numeric_fields_1))
print("Numeric fields 2 are {}".format(numeric_fields_2))
canonicals_1_filepath = dm_file_checker.get_filepath(dedup_task_1, "cluster_canonical", saved_files_path)
canonicals_2_filepath = dm_file_checker.get_filepath(dedup_task_2, "cluster_canonical", saved_files_path)
mapped_records_1_filepath = dm_file_checker.get_filepath(dedup_task_1, "mapped_records", saved_files_path)
mapped_records_2_filepath = dm_file_checker.get_filepath(dedup_task_2, "mapped_records", saved_files_path)
# read in data from filepaths
unlabeled_data_1 = read_unlabeled_data_json(unlabeled_data_1_filepath, empty_str_to_none = False,
numeric_fields = numeric_fields_1)
unlabeled_data_2 = read_unlabeled_data_json(unlabeled_data_2_filepath, empty_str_to_none = False,
numeric_fields = numeric_fields_2)
canonicals_1_df = pd.read_csv(canonicals_1_filepath, keep_default_na = False, low_memory = False)
canonicals_2_df = pd.read_csv(canonicals_2_filepath, keep_default_na = False, low_memory = False)
mapped_records_1_df = pd.read_csv(mapped_records_1_filepath, keep_default_na = False)
mapped_records_2_df = pd.read_csv(mapped_records_2_filepath, keep_default_na = False)
# get deduped data | |
= Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1237 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1238 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1239 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1240 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1241 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1242 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1243 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1244 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1245 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1246 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1247 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1248 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1249 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1250 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1251 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1252 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1253 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1254 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1255 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1256 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1257 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1258 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1259 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1260 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1261 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1262 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1263 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1264 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1265 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1266 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1267 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1268 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1269 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1270 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1271 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1272 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1273 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1274 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1275 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1276 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1277 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1278 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1279 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1280 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1281 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1282 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1283 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1284 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1285 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1286 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1287 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1288 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1289 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1290 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1291 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1292 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1293 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1294 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1295 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1296 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1297 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1298 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1299 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1300 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1301 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1302 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1303 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1304 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1305 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1306 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1307 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1308 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1309 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1310 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1311 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1312 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1313 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1314 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1315 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1316 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1317 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1318 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1319 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1320 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1321 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1322 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1323 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1324 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1325 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1326 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1327 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1328 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1329 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1330 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1331 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1332 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1333 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1334 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1335 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1336 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1337 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1338 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1339 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1340 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1341 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1342 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1343 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1344 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1345 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1346 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1347 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1348 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1349 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1350 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1351 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1352 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1353 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1354 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1355 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1356 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1357 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1358 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1359 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1360 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1361 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1362 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1363 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1364 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1365 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1366 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1367 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1368 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1369 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1370 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1371 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1372 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1373 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1374 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1375 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1376 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1377 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1378 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1379 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1380 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1381 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1382 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1383 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1384 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1385 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1386 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1387 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1388 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1389 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1390 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1391 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1392 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1393 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1394 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1395 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1396 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1397 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1398 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1399 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1400 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1401 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1402 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1403 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1404 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1405 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1406 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1407 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1408 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1409 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1410 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1411 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1412 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1413 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1414 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1415 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1416 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1417 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1418 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1419 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1420 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1421 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1422 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1423 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1424 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1425 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1426 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1427 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1428 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1429 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1430 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1431 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1432 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1433 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1434 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1435 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1436 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1437 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1438 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1439 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1440 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1441 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1442 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1443 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1444 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1445 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1446 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1447 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1448 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1449 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1450 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1451 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1452 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1453 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1454 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1455 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1456 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1457 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1458 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1459 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1460 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1461 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1462 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1463 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1464 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1465 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1466 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1467 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1468 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1469 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1470 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1471 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1472 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1473 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1474 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1475 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1476 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1477 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1478 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1479 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1480 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1481 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1482 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1483 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1484 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1485 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1486 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1487 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1488 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1489 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1490 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1491 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1492 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1493 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1494 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1495 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1496 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1497 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1498 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1499 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1500 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1501 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1502 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1503 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1504 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1505 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1506 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1507 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1508 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1509 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1510 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1511 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1512 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1513 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1514 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1515 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1516 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1517 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1518 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1519 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1520 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1521 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1522 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1523 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1524 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.x1525 = Var(within=Reals,bounds=(0,None),initialize=0.0016)
m.obj = Objective(expr= 35*m.b751 + 44*m.b752 + 91*m.b753 + 62*m.b754 + 55*m.b755 + 85*m.b756 + 67*m.b757 + 15*m.b758
+ 86*m.b759 + 84*m.b760 + 80*m.b761 + 31*m.b762 + 69*m.b763 + 2*m.b764 + 84*m.b765 + 31*m.b766
+ 49*m.b767 + 5*m.b768 + 86*m.b769 + 75*m.b770 + 69*m.b771 + 95*m.b772 + 90*m.b773 + 68*m.b774
+ 37*m.b775 + 18.317920140714*m.x776 + 50.5417406365265*m.x777 + 7.23887157420725*m.x778
+ 31.7161164224096*m.x779 + 26.5982806962124*m.x780 + 25.2003558029458*m.x781
+ 16.1299441008742*m.x782 + 22.7876212870155*m.x783 + 21.7074941364639*m.x784
+ 8.84495909871991*m.x785 + 33.3904033811499*m.x786 + 19.068365922671*m.x787
+ 23.4861371314648*m.x788 + 13.152021048086*m.x789 + 15.4995447875237*m.x790
+ 28.6882286544541*m.x791 + 46.4069438310726*m.x792 + 34.2842869537236*m.x793
+ 19.9377297916144*m.x794 + 23.189227663382*m.x795 + 52.881822931094*m.x796
+ 28.1176792940909*m.x797 + 28.1262486001112*m.x798 + 25.9733765203171*m.x799
+ 42.1823410885902*m.x800 + 43.5934045276037*m.x801 + 43.1951884028598*m.x802
+ 42.7561031337705*m.x803 + 44.8830560021809*m.x804 + 31.384368926487*m.x805
+ 26.0466833110394*m.x806 + 35.3519632097789*m.x807 + 27.3497467796216*m.x808
+ 19.1823245949226*m.x809 + 32.6848959154934*m.x810 + 26.719611630368*m.x811
+ 24.0750421497223*m.x812 + 37.4336455826642*m.x813 + 12.4870328861834*m.x814
+ 29.9646734719363*m.x815 + 11.7061835222621*m.x816 + 33.1056699953261*m.x817
+ 25.9535074865687*m.x818 + 35.5250910386477*m.x819 + 28.6790006328974*m.x820
+ 43.4113232048431*m.x821 + 36.0099115783421*m.x822 + 29.5805680481105*m.x823
+ 20.7315647903172*m.x824 + 6.99302006377018*m.x825 + 41.3707989442305*m.x826
+ 10.5363720682363*m.x827 + 47.032100334195*m.x828 + 6.86209789221352*m.x829
+ 33.0680131564835*m.x830 + 17.0130750735887*m.x831 + 31.1878929438216*m.x832
+ 34.8635359311466*m.x833 + 40.1851022591442*m.x834 + 26.3902986450093*m.x835
+ 13.8837995858511*m.x836 + 41.6939225602965*m.x837 + 17.4409085474614*m.x838
+ 29.0296771941515*m.x839 + 11.8752598820801*m.x840 + 16.5741615556562*m.x841
+ 15.8092041497997*m.x842 + 2.80664753095402*m.x843 + 27.4813510509779*m.x844
+ 14.7582416896057*m.x845 + 36.3895741537047*m.x846 + 6.74790963786835*m.x847
+ 16.0825941238826*m.x848 + 10.5347874027961*m.x849 + 11.4646478827216*m.x850
+ 5.4227391605132*m.x851 + 34.9367214149104*m.x852 + 23.4836655133002*m.x853
+ 19.4763652210318*m.x854 + 36.9309258006081*m.x855 + 40.6096260396591*m.x856
+ 32.1633476146608*m.x857 + 7.23744928353258*m.x858 + 33.453992326267*m.x859
+ 31.1386724856491*m.x860 + 46.8408059108518*m.x861 + 34.0499581478418*m.x862
+ 30.5488224425645*m.x863 + 29.5795535259439*m.x864 + 22.803338404088*m.x865
+ 22.8875142539559*m.x866 + 36.8206784185433*m.x867 + 23.1249554598248*m.x868
+ 19.0827867125553*m.x869 + 30.2622260942462*m.x870 + 24.5429695902386*m.x871
+ 20.6663863573018*m.x872 + 34.1782587461511*m.x873 + 9.87298237219923*m.x874
+ 25.8240404618963*m.x875 + 13.4588903804112*m.x876 + 29.7256542744278*m.x877
+ 23.5503024135801*m.x878 + 31.4958035760818*m.x879 + 25.1150231082704*m.x880
+ 40.3372190068453*m.x881 + 36.5419890131661*m.x882 + 28.7169164625805*m.x883
+ 17.9291685498324*m.x884 + 3.29974738568237*m.x885 + 42.2800435560718*m.x886
+ 10.4374663473534*m.x887 + 43.5749166341251*m.x888 + 5.89299720874657*m.x889
+ 33.2330261480484*m.x890 + 20.7305245448397*m.x891 + 31.8474409103857*m.x892
+ 34.8731848638771*m.x893 + 39.8199091961854*m.x894 + 25.3467692173983*m.x895
+ 17.6546249885179*m.x896 + 45.8634691771302*m.x897 + 19.2040532515657*m.x898
+ 33.252440687394*m.x899 + 16.1261274037575*m.x900 + 20.8273789839396*m.x901
+ 19.2728215031019*m.x902 + 7.07574699678281*m.x903 + 31.1124334317676*m.x904
+ 16.2769000323456*m.x905 + 40.4312242074416*m.x906 + 10.4130328148869*m.x907
+ 20.272267327817*m.x908 + 10.9489181155747*m.x909 + 14.6634100487518*m.x910
+ 6.86093554987709*m.x911 + 38.9959581192207*m.x912 + 27.7114737275747*m.x913
+ 23.3030465568468*m.x914 + 39.9827108936166*m.x915 + 44.5433042390447*m.x916
+ 36.068863793294*m.x917 + 4.11665036759906*m.x918 + 37.1040975947365*m.x919
+ 35.2679678998297*m.x920 + 50.9598284668476*m.x921 + 38.2539523316496*m.x922
+ 34.6012307339498*m.x923 + 33.3060212423024*m.x924 + 27.0862654773137*m.x925
+ 25.6052443166823*m.x926 + 47.0443448498989*m.x927 + 29.5918348175443*m.x928
+ 38.4911586436211*m.x929 + 20.3082495689446*m.x930 + 26.2828698610113*m.x931
+ 27.8579285191439*m.x932 + 14.3317490226775*m.x933 + 39.1373213233682*m.x934
+ 26.7596985635397*m.x935 + 46.8244810814358*m.x936 + 18.8973194470275*m.x937
+ 26.3918246309307*m.x938 + 21.6552560573349*m.x939 + 23.7537108329874*m.x940
+ 8.23262031055656*m.x941 + 39.4837149241124*m.x942 + 30.3662715039752*m.x943
+ 30.9209990751519*m.x944 + 49.1306132879028*m.x945 + 43.9933049626478*m.x946
+ 43.1496905105332*m.x947 + 6.8790902811152*m.x948 + 45.0094539541684*m.x949
+ 36.4756962216344*m.x950 + 56.7387445580221*m.x951 + 40.0652727267479*m.x952
+ 35.2489022960904*m.x953 + 32.1776621377557*m.x954 + 30.96678226207*m.x955
+ 19.870882380967*m.x956 + 52.5889674485449*m.x957 + 8.7434204425797*m.x958
+ 33.9325153654472*m.x959 + 27.7464102493544*m.x960 + 26.8309304269913*m.x961
+ 17.8907179731242*m.x962 + 23.1383351028176*m.x963 + 24.1560581141682*m.x964
+ 9.62505798440892*m.x965 + 35.8625129258679*m.x966 + 19.766043163461*m.x967
+ 25.1380056644321*m.x968 + 12.8836272863498*m.x969 + 16.6789220968229*m.x970
+ 28.748756298533*m.x971 + 48.2366137143732*m.x972 + 36.0055434136457*m.x973
+ 21.969810518488*m.x974 + 25.6765637031271*m.x975 + 54.6991940304609*m.x976
+ 30.5823053936182*m.x977 + 27.6125923053998*m.x978 + 28.5047023818799*m.x979
+ 44.0019065201746*m.x980 + 46.110154392053*m.x981 + 45.1627535811209*m.x982
+ 44.4906667246016*m.x983 + 46.3664627758094*m.x984 + 33.2140886176102*m.x985
+ 19.3645940233183*m.x986 + 42.9320869596726*m.x987 + 15.0766951711362*m.x988
+ 23.6654563729363*m.x989 + 28.2588156447016*m.x990 + 23.7753120786892*m.x991
+ 16.5709228659944*m.x992 + 29.3900310684354*m.x993 + 11.8564483451232*m.x994
+ 18.0579714876375*m.x995 + 21.5078042747312*m.x996 + 24.7842292860034*m.x997
+ 22.2806196631767*m.x998 + 23.9797192577055*m.x999 + 19.8792653889938*m.x1000
+ 35.849413125637*m.x1001 + 40.9463961132668*m.x1002 + 30.7204630102472*m.x1003
+ 16.4333834809736*m.x1004 + 8.13542761474758*m.x1005 + 47.1994833425915*m.x1006
+ 16.8225578271661*m.x1007 + 37.766322028356*m.x1008 + 13.1391814356668*m.x1009
+ 37.0796490134297*m.x1010 + 30.4135829605837*m.x1011 + 36.7145714238955*m.x1012
+ 38.3224608368608*m.x1013 + 42.2553742537591*m.x1014 + 27.2613350412179*m.x1015
+ 4.20325590793194*m.x1016 + 33.9400956302393*m.x1017 + 13.3761164516277*m.x1018
+ 19.0959037988233*m.x1019 + 6.01836291817402*m.x1020 + 7.10231989386958*m.x1021
+ 6.8761807377244*m.x1022 + 7.57054337966765*m.x1023 + 17.5944876872481*m.x1024
+ 12.1813190530298*m.x1025 + 26.1376142248563*m.x1026 + 4.33105563371409*m.x1027
+ 6.12779005580725*m.x1028 + 12.5065216975371*m.x1029 + 5.08481436235556*m.x1030
+ 13.3401079050352*m.x1031 + 28.1376812292325*m.x1032 + 15.7830557867359*m.x1033
+ 9.39580239114668*m.x1034 + 27.9516326242547*m.x1035 + 34.3780648407576*m.x1036
+ 21.937689771261*m.x1037 + 17.455944192281*m.x1038 + 23.4852292982593*m.x1039
+ 23.9858332454866*m.x1040 + 36.6413573127999*m.x1041 + 26.1656475252664*m.x1042
+ 23.9747105433326*m.x1043 + 24.9064324222923*m.x1044 + 14.0374476512452*m.x1045
+ 32.5307045343*m.x1046 + 8.81146853603199*m.x1047 + 43.5775086533129*m.x1048
+ 22.150770730328*m.x1049 + 26.638603236471*m.x1050 + 25.550674451719*m.x1051
+ 34.4447464461405*m.x1052 + 35.4498917358295*m.x1053 + 33.6935201909288*m.x1054
+ 43.3611773285297*m.x1055 + 28.9110396135262*m.x1056 + 35.4469710715193*m.x1057
+ 27.2094885127556*m.x1058 + 44.179811105689*m.x1059 + 36.2752777334068*m.x1060
+ 35.8586575696604*m.x1061 + 4.54840044576581*m.x1062 + 16.3199203989194*m.x1063
+ 30.9501009371959*m.x1064 + 44.0373106366546*m.x1065 + 2.90086496977747*m.x1066
+ 30.6232717728236*m.x1067 + 42.3161996777378*m.x1068 + 35.1757794618538*m.x1069
+ 8.49540953240994*m.x1070 + 31.5167441828445*m.x1071 + 9.25484597570439*m.x1072
+ 7.84098304655692*m.x1073 + 8.94759564781253*m.x1074 + 19.2103928685291*m.x1075
+ 13.25871089003*m.x1076 + 42.6898287611128*m.x1077 + 6.75836353868577*m.x1078
+ 23.4906068361686*m.x1079 + 22.3929855321258*m.x1080 + 19.2416530181295*m.x1081
+ 10.4685567913094*m.x1082 + 21.795462678466*m.x1083 + 12.9462175308779*m.x1084
+ 9.73387162804679*m.x1085 + 24.5975119316798*m.x1086 + 17.2742323975676*m.x1087
+ 17.5448157945333*m.x1088 + 15.6557519467861*m.x1089 + 12.4840418517587*m.x1090
+ 28.2457567274807*m.x1091 + 39.2500628661265*m.x1092 + 27.6699109852302*m.x1093
+ 12.6694629863682*m.x1094 + 15.7649075104085*m.x1095 + 45.7108329504802*m.x1096
+ 19.3313262114147*m.x1097 + 29.6568685811216*m.x1098 + 17.2525688342231*m.x1099
+ | |
<filename>MonkeyBusiness/elilik.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'm1.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5.QtGui import QImage, QPixmap, QPainter, QBrush, QColor
from PyQt5.QtGui import QPalette, QFont, QFontMetrics, QStandardItem, QStandardItemModel
from PyQt5.QtCore import Qt, QRect, QSize, QEvent, QCoreApplication, QMetaObject
from PyQt5.QtCore import QPointF, QRectF, pyqtSignal, pyqtSlot, QUrl
from PyQt5.QtWidgets import QWidget, QDialogButtonBox, QCheckBox, QDial
from PyQt5.QtWidgets import QSizePolicy, QGridLayout, QFormLayout,QHBoxLayout, QVBoxLayout
from PyQt5.QtWidgets import QLabel, QToolButton, QDoubleSpinBox, QLineEdit
from PyQt5.QtWidgets import QComboBox, QStyledItemDelegate, qApp, QListView
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QFileDialog, QMessageBox, QDialog
from PyQt5.QtWidgets import QGraphicsItem, QGraphicsPixmapItem, QPushButton, QAbstractScrollArea
from PyQt5.QtWidgets import QAction, QMenu, QMenuBar, QStatusBar
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication, QMainWindow, QGroupBox, QFrame, QSlider
from functools import partial
import numpy as np
import sys
import cv2
import os
from ElilikClasses import Ui_INI_Dialog, ColorMapsDialog, TransformScene, showText
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1871, 1200)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.transformsGroupBox = QGroupBox(self.centralwidget)
self.transformsGroupBox.setGeometry(QRect(1500, 170, 240, 500))
self.transformsGroupBox.setMaximumSize(QSize(240, 600))
font = QFont()
font.setFamily("MS Shell Dlg 2")
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.transformsGroupBox.setFont(font)
self.transformsGroupBox.setToolTip("")
self.transformsGroupBox.setWhatsThis("")
self.transformsGroupBox.setObjectName("transformsGroupBox")
self.edgesButton = QPushButton(self.transformsGroupBox)
self.edgesButton.setGeometry(QRect(110, 180, 120, 30))
self.edgesButton.setObjectName("edgesButton")
self.brightnessButton = QPushButton(self.transformsGroupBox)
self.brightnessButton.setGeometry(QRect(110, 20, 120, 30))
font = QFont()
font.setPointSize(8)
self.brightnessButton.setFont(font)
self.brightnessButton.setObjectName("brightnessButton")
self.getSizeButton = QPushButton(self.transformsGroupBox)
self.getSizeButton.setGeometry(QRect(0, 470, 75, 23))
self.getSizeButton.setObjectName("getSizeButton")
self.paramsGroupBox = QGroupBox(self.transformsGroupBox)
self.paramsGroupBox.setGeometry(QRect(10, 29, 91, 321))
font = QFont()
font.setPointSize(8)
self.paramsGroupBox.setFont(font)
self.paramsGroupBox.setObjectName("paramsGroupBox")
self.leftSlider = QSlider(self.paramsGroupBox)
self.leftSlider.setGeometry(QRect(10, 50, 20, 240))
sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.leftSlider.sizePolicy().hasHeightForWidth())
self.leftSlider.setSizePolicy(sizePolicy)
self.leftSlider.setOrientation(Qt.Vertical)
self.leftSlider.setTickPosition(QSlider.TicksAbove)
self.leftSlider.setObjectName("leftSlider")
self.rightSlider = QSlider(self.paramsGroupBox)
self.rightSlider.setGeometry(QRect(50, 50, 20, 240))
sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.rightSlider.sizePolicy().hasHeightForWidth())
self.rightSlider.setSizePolicy(sizePolicy)
self.rightSlider.setOrientation(Qt.Vertical)
self.rightSlider.setTickPosition(QSlider.TicksAbove)
self.rightSlider.setObjectName("rightSlider")
self.leftLabel = QLabel(self.paramsGroupBox)
self.leftLabel.setGeometry(QRect(10, 20, 20, 15))
self.leftLabel.setTextFormat(Qt.PlainText)
self.leftLabel.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
self.leftLabel.setObjectName("leftLabel")
self.rightLabel = QLabel(self.paramsGroupBox)
self.rightLabel.setGeometry(QRect(50, 20, 20, 15))
self.rightLabel.setTextFormat(Qt.PlainText)
self.rightLabel.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
self.rightLabel.setObjectName("rightLabel")
self.adaptiveThresholdButton = QPushButton(self.transformsGroupBox)
self.adaptiveThresholdButton.setGeometry(QRect(110, 140, 120, 30))
font = QFont()
font.setPointSize(8)
self.adaptiveThresholdButton.setFont(font)
self.adaptiveThresholdButton.setObjectName("adaptiveThresholdButton")
self.gray2colSelButton = QPushButton(self.transformsGroupBox)
self.gray2colSelButton.setGeometry(QRect(110, 100, 120, 30))
font = QFont()
font.setPointSize(8)
self.gray2colSelButton.setFont(font)
self.gray2colSelButton.setObjectName("gray2colSelButton")
self.gray2colAllButton = QPushButton(self.transformsGroupBox)
self.gray2colAllButton.setGeometry(QRect(110, 60, 120, 30))
font = QFont()
font.setPointSize(8)
self.gray2colAllButton.setFont(font)
self.gray2colAllButton.setObjectName("gray2colAllButton")
self.fftButton = QPushButton(self.transformsGroupBox)
self.fftButton.setGeometry(QRect(110, 220, 120, 30))
self.fftButton.setObjectName("fftButton")
self.dftButton = QPushButton(self.transformsGroupBox)
self.dftButton.setGeometry(QRect(110, 260, 120, 30))
self.dftButton.setObjectName("dftButton")
self.gaborButton = QPushButton(self.transformsGroupBox)
self.gaborButton.setGeometry(QRect(110, 300, 120, 30))
self.gaborButton.setObjectName("gaborButton")
self.differenceButton = QPushButton(self.transformsGroupBox)
self.differenceButton.setGeometry(QRect(110, 340, 120, 30))
self.differenceButton.setObjectName("differenceButton")
self.RGB2GrayButton = QPushButton(self.transformsGroupBox)
self.RGB2GrayButton.setGeometry(QRect(110, 380, 120, 30))
self.RGB2GrayButton.setObjectName("RGB2GrayButton")
self.invertedCheckBox = QCheckBox(self.transformsGroupBox)
self.invertedCheckBox.setGeometry(QRect(110, 430, 121, 17))
self.invertedCheckBox.setObjectName("invertedCheckBox")
self.angleDial = QDial(self.transformsGroupBox)
self.angleDial.setGeometry(QRect(20, 360, 81, 64))
self.angleDial.setMinimum(1)
self.angleDial.setMaximum(4)
self.angleDial.setPageStep(1)
self.angleDial.setSliderPosition(1)
self.angleDial.setWrapping(False)
self.angleDial.setNotchesVisible(True)
self.angleDial.setObjectName("angleDial")
self.groupButtonsBox = QGroupBox(self.centralwidget)
self.groupButtonsBox.setGeometry(QRect(1500, 730, 241, 141))
self.groupButtonsBox.setMaximumSize(QSize(250, 600))
font = QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.groupButtonsBox.setFont(font)
self.groupButtonsBox.setObjectName("groupButtonsBox")
self.addImgButton = QPushButton(self.groupButtonsBox)
self.addImgButton.setGeometry(QRect(50, 20, 150, 30))
palette = QPalette()
brush = QBrush(QColor(180, 146, 66))
brush.setStyle(Qt.SolidPattern)
palette.setBrush(QPalette.Active, QPalette.Button, brush)
brush = QBrush(QColor(180, 146, 66))
brush.setStyle(Qt.SolidPattern)
palette.setBrush(QPalette.Inactive, QPalette.Button, brush)
brush = QBrush(QColor(180, 146, 66))
brush.setStyle(Qt.SolidPattern)
palette.setBrush(QPalette.Disabled, QPalette.Button, brush)
self.addImgButton.setPalette(palette)
font = QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.addImgButton.setFont(font)
self.addImgButton.setObjectName("addImgButton")
self.saveSceneImgButton = QPushButton(self.groupButtonsBox)
self.saveSceneImgButton.setGeometry(QRect(50, 60, 150, 30))
font = QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.saveSceneImgButton.setFont(font)
self.saveSceneImgButton.setObjectName("saveSceneImgButton")
self.saveImgButton = QPushButton(self.groupButtonsBox)
self.saveImgButton.setGeometry(QRect(50, 100, 150, 30))
font = QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.saveImgButton.setFont(font)
self.saveImgButton.setObjectName("saveImgButton")
self.graphicsView = QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QRect(10, 15, 1471, 900))
self.graphicsView.setMaximumSize(QSize(4000, 3000))
self.graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.graphicsView.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
self.graphicsView.setObjectName("graphicsView")
self.scene = TransformScene()
self.graphicsView.setScene(self.scene)
self.scaleEditLabel = QLabel(self.centralwidget)
self.scaleEditLabel.setGeometry(QRect(1500, 100, 47, 13))
font = QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.scaleEditLabel.setFont(font)
self.scaleEditLabel.setObjectName("scaleEditLabel")
self.scaleBox = QDoubleSpinBox(self.centralwidget)
self.scaleBox.setGeometry(QRect(1550, 100, 62, 22))
font = QFont()
font.setBold(True)
font.setWeight(75)
self.scaleBox.setFont(font)
self.scaleBox.setMinimum(0.1)
self.scaleBox.setMaximum(10.0)
self.scaleBox.setSingleStep(0.1)
self.scaleBox.setProperty("value", 0.5)
self.scaleBox.setObjectName("scaleBox")
self.infoLabel = QLabel(self.centralwidget)
self.infoLabel.setGeometry(QRect(1499, 130, 230, 20))
self.infoLabel.setFrameShape(QFrame.WinPanel)
self.infoLabel.setText("")
self.infoLabel.setAlignment(Qt.AlignCenter)
self.infoLabel.setObjectName("infoLabel")
self.infoLabel_2 = QLabel(self.centralwidget)
self.infoLabel_2.setGeometry(QRect(1500, 20, 230, 20))
font = QFont()
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
self.infoLabel_2.setFont(font)
self.infoLabel_2.setFrameShape(QFrame.WinPanel)
self.infoLabel_2.setText("")
self.infoLabel_2.setAlignment(Qt.AlignCenter)
self.infoLabel_2.setObjectName("infoLabel_2")
self.infoLabel_3 = QLabel(self.centralwidget)
self.infoLabel_3.setGeometry(QRect(1500, 60, 230, 20))
font = QFont()
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
self.infoLabel_3.setFont(font)
self.infoLabel_3.setFrameShape(QFrame.Box)
self.infoLabel_3.setText("")
self.infoLabel_3.setAlignment(Qt.AlignCenter)
self.infoLabel_3.setObjectName("infoLabel_3")
self.clearImgButton = QPushButton(self.centralwidget)
self.clearImgButton.setGeometry(QRect(1550, 690, 150, 30))
font = QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.clearImgButton.setFont(font)
self.clearImgButton.setObjectName("clearImgButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QMenuBar(MainWindow)
self.menubar.setGeometry(QRect(0, 0, 1871, 21))
self.menubar.setObjectName("menubar")
self.menuHelp = QMenu(self.menubar)
self.menuHelp.setObjectName("menuHelp")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionExit = QAction(MainWindow)
self.actionExit.setObjectName("actionExit")
self.actionHelp = QAction(MainWindow)
self.actionHelp.setObjectName("actionHelp")
self.actionAbout = QAction(MainWindow)
self.actionAbout.setObjectName("actionAbout")
self.actionDefault_Values = QAction(MainWindow)
self.actionDefault_Values.setObjectName("actionDefault_Values")
self.menuHelp.addAction(self.actionHelp)
self.menuHelp.addAction(self.actionAbout)
self.menuHelp.addSeparator()
self.menuHelp.addAction(self.actionDefault_Values)
self.menubar.addAction(self.menuHelp.menuAction())
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
self.scene.file_signal.connect(on_file_signal)
self.scene.info_signal.connect(on_info_signal)
self.scene.sliders_reset_signal.connect(on_sliders_reset_signal)
def retranslateUi(self, MainWindow):
_translate = QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Green Monkey"))
self.transformsGroupBox.setTitle(_translate("MainWindow", "Transformations"))
self.edgesButton.setText(_translate("MainWindow", "Edges, Sobel"))
self.brightnessButton.setToolTip(_translate("MainWindow", "You can change brightness with left slider and blur with rigt one."))
self.brightnessButton.setWhatsThis(_translate("MainWindow", "You can change brightness with left slider and blur with rigt one."))
self.brightnessButton.setText(_translate("MainWindow", "Brightness and Blur"))
self.getSizeButton.setText(_translate("MainWindow", "get Size"))
self.paramsGroupBox.setTitle(_translate("MainWindow", "Parameters"))
self.leftSlider.setToolTip(_translate("MainWindow", "Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on."))
self.leftSlider.setWhatsThis(_translate("MainWindow", "Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on."))
self.rightSlider.setToolTip(_translate("MainWindow", "Adaptive Threshold\n"
"C – Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well."))
self.rightSlider.setWhatsThis(_translate("MainWindow", "Adaptive Threshold\n"
"C – Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well."))
self.leftLabel.setText(_translate("MainWindow", "0"))
self.rightLabel.setText(_translate("MainWindow", "0"))
self.adaptiveThresholdButton.setText(_translate("MainWindow", "Adaptive Threshold"))
self.gray2colSelButton.setToolTip(_translate("MainWindow", "Gray scale 0..255 to color with selected method only.\n"
"Image is converted to gray and finally to color."))
self.gray2colSelButton.setWhatsThis(_translate("MainWindow", "Gray scale 0..255 to color with selected method only.\n"
"Image is converted to gray and and finally to color."))
self.gray2colSelButton.setText(_translate("MainWindow", "Gray2Color Sel."))
self.gray2colAllButton.setToolTip(_translate("MainWindow", "Gray scale 0..255 to color for all available methods.\n"
"Image resized as per scale window and then is converted to gray and finally to color."))
self.gray2colAllButton.setWhatsThis(_translate("MainWindow", "Gray scale 0..255 to color for all available methods.\n"
"Image resized as per scale window and then is converted to gray and finally to color."))
self.gray2colAllButton.setText(_translate("MainWindow", "Gray2Color All"))
self.fftButton.setText(_translate("MainWindow", "FFT"))
self.dftButton.setText(_translate("MainWindow", "DFT"))
self.gaborButton.setToolTip(_translate("MainWindow", "Applies Gabor Filter"))
self.gaborButton.setWhatsThis(_translate("MainWindow", "Applies Gabor Filter"))
self.gaborButton.setText(_translate("MainWindow", "Gabor Filter"))
self.differenceButton.setText(_translate("MainWindow", "Difference"))
self.RGB2GrayButton.setText(_translate("MainWindow", "RGB to Gray"))
self.invertedCheckBox.setText(_translate("MainWindow", "Inverted Image"))
self.angleDial.setToolTip(_translate("MainWindow", "GABOR Filter - angle 1..4 ~ 1*np.pi/angle"))
self.angleDial.setWhatsThis(_translate("MainWindow", "GABOR Filter - angle 1..4 ~ 1*np.pi/angle"))
self.groupButtonsBox.setTitle(_translate("MainWindow", "Images"))
self.addImgButton.setText(_translate("MainWindow", "Add Image(s)"))
self.addImgButton.setShortcut(_translate("MainWindow", "Ctrl+A"))
self.saveSceneImgButton.setText(_translate("MainWindow", "Save Scene as Image"))
self.saveImgButton.setText(_translate("MainWindow", "Save Selected as Image"))
self.scaleEditLabel.setText(_translate("MainWindow", "Scale:"))
self.clearImgButton.setText(_translate("MainWindow", "Clear Image(s)"))
self.menuHelp.setTitle(_translate("MainWindow", "Help"))
self.actionExit.setText(_translate("MainWindow", "Exit"))
self.actionHelp.setText(_translate("MainWindow", "Help"))
self.actionAbout.setText(_translate("MainWindow", "About"))
self.actionDefault_Values.setText(_translate("MainWindow", "Default Values"))
self.actionHelp.setShortcut('F1')
self.actionHelp.setStatusTip('Help')
self.actionHelp.triggered.connect(self.showHelp)
self.actionAbout.setStatusTip('About')
self.actionAbout.triggered.connect(self.showAbout)
self.actionDefault_Values.setStatusTip('Default folders and other values')
self.actionDefault_Values.triggered.connect(self.updateINI)
self.addImgButton.clicked.connect(partial(self.scene.addImg))
self.clearImgButton.clicked.connect(self.scene.dialogClearScene)
self.saveSceneImgButton.clicked.connect(partial(self.scene.saveScene))
self.saveImgButton.clicked.connect(partial(self.scene.saveImg))
self.scaleBox.valueChanged.connect(self.onScaleBoxValueChanged)
self.getSizeButton.clicked.connect(self.showSceneSize)
self.brightnessButton.clicked.connect(self.startBrightnessAndBlur)
self.gray2colAllButton.clicked.connect(self.startGray2colAllButton)
self.gray2colSelButton.clicked.connect(self.startGray2colSelButton)
self.adaptiveThresholdButton.clicked.connect(self.startAdaptiveThreshold)
self.edgesButton.clicked.connect(self.startSobelXY)
self.fftButton.clicked.connect(self.startFFT)
self.dftButton.clicked.connect(self.startDFT)
self.gaborButton.clicked.connect(self.startGabor)
self.differenceButton.clicked.connect(self.startDifference)
self.RGB2GrayButton.clicked.connect(self.starRGB2Gray)
self.leftSlider.valueChanged['int'].connect(self. leftSliderChanged)
self.rightSlider.valueChanged['int'].connect(self.rightSliderChanged)
self.angleDial.valueChanged['int'].connect(self.angleDialChanged)
def setStart(self):
self.graphicsView.setAlignment(Qt.AlignLeft|Qt.AlignTop)
self.scene.setSceneRect(0, 0, 0, 0)
self.scene.imgScale = self.scaleBox.value()
self.clearSliders()
self.infoLabel.setText("")
self.scene.cv2Images = {}
self.transformsGroupBox.setEnabled(False)
self.transformsGroupBox.setEnabled(False)
self.invertedCheckBox.setChecked(False)
def clearSliders(self):
self.infoLabel_2.setText('')
self.infoLabel_3.setText('')
self.scene.currentTransform = 0
self.leftSlider.setEnabled(False)
self.leftSlider.setToolTip("")
self.leftSlider.setWhatsThis("")
self.leftSlider.setMaximum(99)
self.leftSlider.setMinimum(0)
self.leftSlider.setTickInterval(10)
self.leftSlider.setSingleStep(1)
self.leftSlider.setTickPosition(11)
self.rightSlider.setEnabled(False)
self.rightSlider.setToolTip("")
self.rightSlider.setWhatsThis("")
self.rightSlider.setMaximum(99)
self.rightSlider.setMinimum(0)
self.rightSlider.setTickInterval(10)
self.rightSlider.setSingleStep(1)
self.rightSlider.setTickPosition(0)
self.paramsGroupBox.setFlat(False)
self.paramsGroupBox.setStyleSheet('QGroupBox * {color: black; font-weight: normal;}')
self.angleDial.setEnabled(False)
self.angleDial.setToolTip(" ")
self.angleDial.setWhatsThis("")
def invertCheckBoxEvent(self, checked):
self.scene.inverted = checked
def showSceneSize(self):
x = self.scene.sceneRect().width()
y = self.scene.sceneRect().height()
self.infoLabel.setText(f'size: {x}x{y}, {self.scene.findSceneArea()}')
def onScaleBoxValueChanged(self, val):
self.scene.imgScale = val
def startBrightnessAndBlur(self):
self.scene.currentTransform = 1
self.infoLabel_2.setText('Adaptive Threshold')
self.scene.currentBrightnessValue = 0
self.scene.currentBlurValue = 0
self.scene.transform1()
self.infoLabel_2.setText('Brightness and Blur')
self.scene.currentTransform = 1
self.leftSlider.setEnabled(True)
self.rightSlider.setEnabled(True)
self.leftSlider.setToolTip("Change Brightness -> 0 .. 99")
self.leftSlider.setWhatsThis("Change Brightness -> 0 .. 99")
self.rightSlider.setToolTip("Change Blur -> 0 .. 99")
self.rightSlider.setWhatsThis("Change Blur -> 0 .. 99")
self.leftSlider.setMaximum(99)
self.leftSlider.setMinimum(0)
self.leftSlider.setTickInterval(10)
self.leftSlider.setSingleStep(1)
self.leftSlider.setTickPosition(11)
self.rightSlider.setMaximum(99)
self.rightSlider.setMinimum(0)
self.rightSlider.setTickInterval(10)
self.rightSlider.setSingleStep(1)
self.rightSlider.setTickPosition(0)
self.paramsGroupBox.setFlat(True)
self.paramsGroupBox.setStyleSheet('QGroupBox * {color: red; font-weight: bold;}')
def startGray2colAllButton(self):
self.infoLabel_2.setText('Gray to Color All Methods')
self.scene.currentTransform = 2
self.scene.transform2(1, 1)
def startGray2colSelButton(self):
self.scene.currentTransform = 3
self.infoLabel_2.setText(' Gray to Color')
self.scene.transform2(0, 1)
def startSobelXY(self):
self.scene.currentTransform = 4
self.infoLabel_2.setText('Edge Detection')
self.scene.transform4()
def startFFT(self):
self.scene.currentTransform = 7
self.infoLabel_2.setText('FFT')
self.scene.transform7()
def startDFT(self):
self.scene.currentTransform = 6
self.infoLabel_2.setText('DFT')
self.scene.transform6()
def startDenoising(self):
self.scene.currentTransform = 8
self.infoLabel_2.setText('Denoising')
self.scene.transform8()
def startDifference(self):
self.scene.currentTransform = 9
self.infoLabel_2.setText('Difference')
self.scene.transform9()
def starRGB2Gray(self):
self.scene.currentTransform = 10
#txt = self.infoLabel_2.text()
self.infoLabel_2.setText('RGB to Gray')
self.scene.transform10()
def startAdaptiveThreshold(self):
self.scene.currentTransform = 5
self.infoLabel_2.setText('Adaptive Threshold')
self.scene.currentBlockSizeValue = 11
self.scene.currentCValue = 5
self.scene.transform5()
self.leftSlider.setEnabled(True)
self.rightSlider.setEnabled(True)
self.leftSlider.setToolTip("Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.")
self.leftSlider.setWhatsThis("Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.")
self.rightSlider.setToolTip("Adaptive | |
, "year_filter":"and h.year <= %s" % (year)
, "gp_filter":150
, "grouping":"h.year, h.league, h.player_name"
, "ordering":"year, league, score"
, "ranking_bool":"@yr != year OR @lg != league"
}
, {"table_type": "historical_stats"
, "year_rename": ", h.year_span as year"
, "trophy_type_add":"_OverallLeader"
, "league_type": ", '' as league"
, "career_filter": "and h.group_type = 'full_season'"
, "year_filter":"and h.year_span <= %s" % (year)
, "gp_filter":150
, "grouping":"h.year_span, h.player_name"
, "ordering":"year, score"
, "ranking_bool":"@yr != year"
}
, {"table_type": "historical_stats"
, "year_rename": ", h.year_span as year"
, "trophy_type_add":"_AllTimeSingleSeason"
, "league_type": ", '' as league"
, "career_filter": "and h.group_type = 'full_season'"
, "year_filter":"and h.year_span <= %s" % (year)
, "gp_filter":150
, "grouping":"h.year_span, h.player_name"
, "ordering":"score"
, "ranking_bool":0
}
, {"table_type": "historical_stats"
, "year_rename": ", 0 as year"
, "trophy_type_add":"_AllTimeCareer"
, "league_type": ", '' as league"
, "career_filter": "and h.group_type = 'full_career'"
, "year_filter":""
, "gp_filter":1000
, "grouping":"h.player_name"
, "ordering":"score"
, "ranking_bool":0
}
]
for t in query_details:
for l in lg_details:
print '\t\t', t['trophy_name'], l['trophy_type_add']
query = base_query % (t['trophy_name']
, t['trophy_type']
, l['trophy_type_add']
, l['ranking_bool']
, l['ranking_bool']
, l['league_type']
, l['year_rename']
, t['score_formula']
, l['table_type']
, t['player_type']
, t['rate']
, t['per_g']
, l['gp_filter']
, l['career_filter']
, l['year_filter']
, l['grouping']
, t['score_filter']
, l['ordering']
, t['sort_type']
)
for q in query.split(";"):
if q.strip() != "":
# raw_input(q)
db.query(q)
db.conn.commit()
def outliers():
print '\tremoving old outliers'
q = "delete from trophies where update_type = 'outliers'"
# print q
db.query(q)
db.conn.commit()
q_dict = {"Triple Crowns":"""insert into trophies
select b.year
, b.rank_set as `rank_id`
, b.new_trophy_name as `trophy_name`
, b.league
, b.trophy_type
, b.position
, 1 as `rank`
, 0 as `ties`
, 0 as `score`
, 'outliers' AS `update_type`
, b.team_name
, b.player_name
from(
select a.*
, IF(@yr = a.year and @lg = a.league AND @tro = a.new_trophy_name, @row := @row+1, @row := 1) as rank_set
, @yr := a.year as yr_set
, @lg := a.league as lg_set
, @tro := a.new_trophy_name AS tro_set
from(
select t.*
, case
when trophy_name like "%%HITTERS_%%" then 'HITTERS_tripleCrown'
else 'PITCHERS_tripleCrown'
end as new_trophy_name
, group_concat(
concat(t.trophy_name
, ' ('
, t.rank
, if(t.ties > 0, CONCAT(' tied w/', t.ties, ' others'), '')
, ' - '
, case
when t.trophy_name = 'HITTERS_avg' then format(t.score, 3)
when t.trophy_name = 'PITCHERS_era' then format(t.score, 2)
else ROUND(t.score,0)
end
, ')'
)
order by t.rank asc, t.ties asc, t.trophy_name asc separator '\n') as details
, count(*) as dummy1
, count(IF(t.rank = 1, t.trophy_name, null)) as dummy2
, @row := 0 as row_init
, @yr := 0 as yr_init
, @lg := '' as lg_init
, @tro := '' AS tro_init
from trophies t
where 1
and t.update_type = 'leaders'
and t.trophy_type IN ('player_leagueLeader', 'player_overallLeader')
and t.trophy_name IN ('HITTERS_avg', 'HITTERS_hr', 'HITTERS_rbi', 'PITCHERS_w', 'PITCHERS_era', 'PITCHERS_k')
and t.rank <= 5
group by t.year, t.player_name, t.league, t.trophy_type
having 1
and dummy1 = 3
and dummy2 = 3
order by year, trophy_name, league
) a
) b
;"""
, "30-30 seasons": """insert into trophies
select b.year
, b.rank_set as `rank_id`
, 'HITTERS_30/30' as `trophy_name`
, '' AS `league`
, 'player' AS `trophy_type`
, '' AS `position`
, 1 as `rank`
, 0 as `ties`
, 0 as `score`
, 'outliers' AS `update_type`
, NULL AS `team_name`
, b.player_name
from(
select a.*
, IF(@yr = a.year and @lg = a.league, @row := @row+1, @row := 1) as rank_set
, @yr := a.year as yr_set
, @lg := a.league as lg_set
from(
select t.year
, t.player_name
, t.league
, GROUP_CONCAT(
CONCAT(t.trophy_name
, ' - '
, ROUND(t.score,0)
)
order by t.trophy_name asc separator '\n') as details
, count(*) as dummy1
, @row := 0 as row_init
, @yr := 0 as yr_init
, @lg := '' as lg_init
from trophies t
where 1
and t.update_type = 'leaders'
and t.trophy_type = 'player_OverallLeader'
and t.trophy_name IN ('HITTERS_sb', 'HITTERS_hr')
and t.score >= 30
group by t.year, t.player_name, t.league
having 1
and dummy1 = 2
ORDER BY year, SUM(t.score) DESC
) a
) b
;"""
}
print '\toutliers'
for desc, query in q_dict.items():
print '\t\tadding', desc
for q in query.split(";"):
if q.strip() != "":
# raw_input(q)
db.query(q)
db.conn.commit()
def format_ties(year):
print '\tformatting ties in trophies'
q = """UPDATE trophies t
JOIN(SELECT t1.*
, COUNT(*) AS ties_update
FROM trophies t1
JOIN trophies t2 ON (t1.trophy_name = t2.trophy_name
AND t1.league = t2.league
AND t1.trophy_type = t2.trophy_type
AND t1.rank = t2.rank
AND t1.score = t2.score
AND CASE
WHEN t1.trophy_type = 'player_LeagueLeader'
THEN t1.player_name != t2.player_name AND t1.year = t2.year AND t1.league = t2.league
WHEN t1.trophy_type = 'player_OverallLeader'
THEN t1.player_name != t2.player_name AND t1.year = t2.year
WHEN t1.trophy_type = 'player_AllTimeSingleSeason'
THEN t1.player_name != t2.player_name OR t1.year != t2.year
WHEN t1.trophy_type = 'player_AllTimeCareer'
THEN t1.player_name != t2.player_name
END
)
WHERE 1
AND t1.update_type = 'leaders'
AND t1.ties = 0
AND t1.year <= %s
GROUP BY t1.year, t1.rank_id, t1.trophy_name, t1.league, t1.trophy_type, t1.position
) b USING (year, rank_id, trophy_name, league, trophy_type, position)
SET t.ties = b.ties_update
;""" % (year)
# print q
db.query(q)
db.conn.commit()
def append_historical_stats():
print '\tadding trophies to historical_stats'
db.query("SET SESSION group_concat_max_len = 1000000;")
db.conn.commit()
for hp in ('hitters', 'pitchers'):
print '\t\t', hp
print '\t\t\tremoving trophy/ink'
q = "update historical_stats_%s set trophy_count = NULL, black_ink = NULL, gray_ink = NULL, trophy_details = NULL" % (hp)
# print q
db.query(q)
db.conn.commit()
print '\t\t\tadding seasonal trophies/ink'
season_q = """update historical_stats_%s h
join(
select a.year
, a.player_name
, a.h_team
, a.p_team
, count(distinct if(a.new_trophy_type = 'award'
and a.trophy_name != 'World Series'
and a.update_type != 'outliers'
and (a.rank = 1 or a.trophy_name = 'all star')
, a.trophy_name, null)) as trophy_count
, count(distinct if(a.trophy_type = 'player_leagueleader' and a.rank = 1, a.trophy_name, null)) as black_ink
, count(distinct if(a.trophy_type = 'player_leagueleader' and a.rank <= 10, a.trophy_name, null)) as gray_ink
, group_concat(concat('- '
, if(a.new_trophy_type != 'Award', concat(a.new_trophy_type, ' '), '')
, if(a.update_type = 'outliers' or a.trophy_name in ('World Series', 'All Star', 'Gold Glove', 'Silver Slugger') or (a.new_trophy_type = 'award' and a.rank = 1 and a.ties = 0)
, upper(a.new_trophy_name)
, concat(if(a.new_trophy_type = 'award' and a.rank = 1, upper(a.new_trophy_name), a.new_trophy_name)
, ' ('
, if(a.ties > 0, 'T-', '')
, a.rank
, if(a.ties > 0, concat(' w/', a.ties, ' others'), '')
, ')'
)
)
)
order by if(a.trophy_name = 'World Series', 1, 0) desc
, if(a.update_type = 'outliers', 1, 0) desc
, if(a.trophy_name in ('All Star', 'Gold Glove', 'Silver Slugger'), 1, 0) desc
, (case
when a.trophy_type = 'player' then 0
when a.trophy_type = 'player_alltimesingleseason' then 1
when a.trophy_type = 'player_overallleader' then 2
when a.trophy_type = 'player_leagueleader' then 3
end) asc, a.rank asc, a.rank_id asc, a.new_trophy_name asc
separator ' \n') as trophy_details
from(
select t.*
, case when t.trophy_type = 'player' then 'Award'
when t.trophy_type = 'player_alltimesingleseason' then 'All-Time Single Season'
when t.trophy_type = 'player_overallleader' then 'Overall'
when t.trophy_type = 'player_leagueleader' then t.league
end as new_trophy_type
, case
when t.trophy_type = 'player'
then (replace(replace(replace(replace(t.trophy_name, 'HITTERS_', ''), 'PITCHERS_', ''), '_plus', '+'), '_minus', '-'))
else upper(replace(replace(replace(replace(t.trophy_name, 'HITTERS_', ''), 'PITCHERS_', ''), '_plus', '+'), '_minus', '-'))
end as new_trophy_name
, group_concat(distinct h.team) AS h_team
, group_concat(distinct p.team) AS p_team
from trophies t
left join historical_stats_hitters h on (t.year = h.year_span
and t.player_name = h.player_name
and h.group_type = 'full_season'
and if(t.trophy_type != 'player', LEFT(t.trophy_name,1) = 'H', 1)
)
left join historical_stats_pitchers p on (t.year = p.year_span
and t.player_name = p.player_name
and p.group_type = 'full_season'
and if(t.trophy_type != 'player', LEFT(t.trophy_name,1) = 'P', 1)
)
where 1
and t.player_name is not null
and t.trophy_type in ('player', 'player_alltimesingleseason', 'player_overallleader', 'player_leagueleader')
and case
when t.trophy_type = 'player_alltimesingleseason' then t.rank <= 20
when t.trophy_type = 'player_overallleader' then t.rank <= 10
when t.trophy_type = 'player_leagueleader' then t.rank <= 10
else 1
end
group by t.year, t.trophy_name, t.league, t.trophy_type, t.rank, t.player_name
) a
group by year, player_name, h_team, p_team
order by trophy_count desc, black_ink desc, gray_ink desc, year desc
) t on (h.player_name = t.player_name and h.year_span = t.year and h.team = t.%s_team)
set h.trophy_count | |
= np.asarray(node_status).reshape(-1)
if np.prod(shape) != node_status.size:
raise ValueError(
"node status array does not match size of grid "
"(%d != %d)" % (np.prod(shape), len(node_status))
)
# status_at_link_start = node_status.flat[node_id_at_link_start(shape)]
# status_at_link_end = node_status.flat[node_id_at_link_end(shape)]
# status_at_link = node_status[StructuredQuadGraphTopology(shape).nodes_at_link]
return is_active_link(node_status[StructuredQuadGraphTopology(shape).nodes_at_link])
def vertical_active_link_ids(shape, active_ids, bad_index_value=-1):
"""ID of vertical active links.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
active_ids : array of int
Array of all active link ids
bad_index_value: int, optional
Value assigned to inactive indicies in the array.
Returns
-------
ndarray :
Link IDs at the VERTICAL active links. Length of
number_of_vertical_links.
Examples
--------
The following example uses this grid::
*---I-->*---I-->*---I-->*---I-->*
^ ^ ^ ^ ^
I I I I I
| | | | |
*---I-->o---H-->o---H-->o---I-->*
^ ^ ^ ^ ^
I 6 7 8 I
| | | | |
*---I-->o---H-->o---H-->o---I-->*
^ ^ ^ ^ ^
I I I I I
| | | | |
*---I-->*---I-->*---I-->*---I-->*
.. note::
``*`` indicates the nodes that are set to `NodeStatus.CLOSED`
``o`` indicates the nodes that are set to `NodeStatus.CORE`
``I`` indicates the links that are set to `LinkStatus.INACTIVE`
``H`` indicates horizontal active ids, which are ignored by this
function
Numeric values correspond to the vertical `LinkStatus.ACTIVE` IDs.
>>> from landlab import RasterModelGrid
>>> from landlab.components.overland_flow._links import (active_link_ids,
... vertical_active_link_ids)
>>> rmg = RasterModelGrid((4, 5))
>>> active_ids = active_link_ids((4, 5), rmg.status_at_node)
>>> active_ids # doctest: +NORMALIZE_WHITESPACE
array([ 5, 6, 7,
9, 10, 11, 12,
14, 15, 16,
18, 19, 20, 21,
23, 24, 25])
>>> vertical_active_link_ids((4, 5), active_ids)
... # doctest: +NORMALIZE_WHITESPACE
array([-1, 5, 6, 7, -1,
-1, 14, 15, 16, -1,
-1, 23, 24, 25, -1])
>>> rmg.set_closed_boundaries_at_grid_edges(True, True, True, True)
>>> status = rmg.status_at_node
>>> active_ids = active_link_ids((4, 5), status)
>>> vertical_active_link_ids((4, 5), active_ids)
... # doctest: +NORMALIZE_WHITESPACE
array([-1, -1, -1, -1, -1,
-1, 14, 15, 16, -1,
-1, -1, -1, -1, -1])
"""
number_of_vertical_links = (shape[0] - 1) * shape[1]
out = np.full(number_of_vertical_links, bad_index_value, dtype=int)
vertical_ids = active_ids[np.where(is_vertical_link(shape, active_ids))]
out[nth_vertical_link(shape, vertical_ids)] = vertical_ids
return out
def _number_of_links(shape):
"""Number of links in a structured quad grid.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
int :
Number of links in grid.
Examples
--------
>>> from landlab.components.overland_flow._links import _number_of_links
>>> _number_of_links((3, 4))
17
"""
return (shape[0] - 1) * shape[1] + shape[0] * (shape[1] - 1)
# return number_of_vertical_links(shape) + number_of_horizontal_links(shape)
def number_of_vertical_links(shape):
"""Number of vertical links in a structured quad grid.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
int :
Number of vertical links in grid.
Examples
--------
>>> from landlab.components.overland_flow._links import number_of_vertical_links
>>> number_of_vertical_links((3, 4))
8
"""
return (shape[0] - 1) * shape[1]
def number_of_horizontal_links(shape):
"""Number of horizontal links in a structured quad grid.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
int :
Number of horizontal links in grid.
Examples
--------
>>> from landlab.components.overland_flow._links import number_of_horizontal_links
>>> number_of_horizontal_links((3, 4))
9
"""
return shape[0] * (shape[1] - 1)
def is_vertical_link(shape, links):
"""Test if links are vertical.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
links : array of int
Array of link ids to test.
Returns
-------
ndarray of bool
`True` for links that are vertical.
Examples
--------
>>> from landlab.components.overland_flow._links import (is_vertical_link,
... _number_of_links)
>>> import numpy as np
>>> shape = (3, 4)
>>> links = np.arange(_number_of_links(shape))
>>> is_vertical_link(shape, links) # doctest: +NORMALIZE_WHITESPACE
array([False, False, False, True, True, True, True,
False, False, False, True, True, True, True,
False, False, False], dtype=bool)
"""
return ((links % (2 * shape[1] - 1)) >= shape[1] - 1) & (
links < _number_of_links(shape)
)
def nth_vertical_link(shape, links):
"""Convert link ID to vertical link ID.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
links : array of int
Array of link ids to test.
Returns
-------
ndarray of int
The link ID as the nth vertical links.
Examples
--------
>>> from landlab.components.overland_flow._links import nth_vertical_link
>>> shape = (3, 4)
>>> nth_vertical_link(shape, 4)
1
>>> nth_vertical_link(shape, (3, 4, 11))
array([0, 1, 5])
"""
links = np.asarray(links, dtype=int)
return as_id_array(
(links // (2 * shape[1] - 1)) * shape[1]
+ links % (2 * shape[1] - 1)
- (shape[1] - 1)
)
def horizontal_active_link_ids(shape, active_ids, bad_index_value=-1):
"""ID of horizontal active links.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
active_ids : array of int
Array of all active link ids
bad_index_value: int, optional
Value assigned to inactive indicies in the array.
Returns
-------
ndarray :
Link IDs at the HORIZONTAL active links. Length of
number_of_horizontal_links.
Examples
--------
The following example uses this grid::
*---I-->*---I-->*---I-->*---I-->*
^ ^ ^ ^ ^
I I I I I
| | | | |
*---I-->o--24-->o--25-->o---I-->*
^ ^ ^ ^ ^
I V V V I
| | | | |
*---I-->o--20-->o--21-->o---I-->*
^ ^ ^ ^ ^
I I I I I
| | | | |
*---I-->*---I-->*---I-->*---I-->*
.. note::
``*`` indicates the nodes that are set to `NodeStatus.CLOSED`
``o`` indicates the nodes that are set to `NodeStatus.CORE`
``I`` indicates the links that are set to `LinkStatus.INACTIVE`
``V`` indicates vertical active ids, which are ignored by this
function.
Numeric values correspond to the horizontal `LinkStatus.ACTIVE` ID.
>>> from landlab import RasterModelGrid
>>> from landlab.components.overland_flow._links import (active_link_ids,
... horizontal_active_link_ids)
>>> rmg = RasterModelGrid((4, 5))
>>> rmg.set_closed_boundaries_at_grid_edges(True, True, True, True)
>>> status = rmg.status_at_node
>>> status # doctest: +NORMALIZE_WHITESPACE
array([4, 4, 4, 4, 4,
4, 0, 0, 0, 4,
4, 0, 0, 0, 4,
4, 4, 4, 4, 4], dtype=uint8)
>>> active_ids = active_link_ids((4,5), status)
>>> horizontal_active_link_ids((4,5), active_ids)
... # doctest: +NORMALIZE_WHITESPACE
array([-1, -1, -1, -1,
-1, 10, 11, -1,
-1, 19, 20, -1,
-1, -1, -1, -1])
"""
number_of_horizontal_links = shape[0] * (shape[1] - 1)
out = np.full(number_of_horizontal_links, bad_index_value, dtype=int)
horizontal_ids = active_ids[np.where(~is_vertical_link(shape, active_ids))]
out[nth_horizontal_link(shape, horizontal_ids)] = horizontal_ids
return out
def nth_horizontal_link(shape, links):
"""Convert link ID to horizontal link ID.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
links : array of int
Array of link ids to test.
Returns
-------
ndarray of int
The link ID as the nth horizontal links.
Examples
--------
>>> from landlab.components.overland_flow._links import nth_horizontal_link
>>> shape = (3, 4)
>>> nth_horizontal_link(shape, 16)
8
>>> nth_horizontal_link(shape, (1, 7, 8))
array([1, 3, 4])
"""
links = np.asarray(links, dtype=int)
return as_id_array(
(links // (2 * shape[1] - 1)) * (shape[1] - 1) + links % (2 * shape[1] - 1)
)
def is_horizontal_link(shape, links):
"""Test if a link is horizontal.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
links : array of int
Array of link ids to test.
Returns
-------
ndarray of bool
`True` for links that are horizontal.
Examples
--------
>>> from landlab.components.overland_flow._links import (is_horizontal_link,
... _number_of_links)
>>> import numpy as np
>>> shape = (3, 4)
>>> links = np.arange(_number_of_links(shape))
>>> is_horizontal_link(shape, links) # doctest: +NORMALIZE_WHITESPACE
array([ True, True, True, False, False, False, False,
True, True, True, False, False, False, False,
True, True, True], dtype=bool)
"""
return (~is_vertical_link(shape, links)) & (links < _number_of_links(shape))
def horizontal_west_link_neighbor(shape, horizontal_ids, bad_index_value=-1):
"""ID of west, horizontal link neighbor.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
horizontal_ids : array of int
Array of all horizontal link ids - *must be of len(horizontal_links)*
bad_index_value: int, optional
Value assigned to inactive indicies in the array.
Returns
-------
ndarray :
Link IDs of west horizontal neighbor links. Length of
number_of_horizontal_links.
Examples
--------
The following example uses this grid::
*--27-->*--28-->*--29-->*--30-->*
*--18-->*--19-->*--20-->*--21-->*
*---9-->*--10-->*--11-->*--12-->*
*---0-->*---1-->*---2-->*---3-->*
.. note::
Only horizontal links are shown. When no neighbor is found,
bad_index_value is returned.
``*`` indicates nodes
Numeric values correspond to the horizontal IDs.
>>> from landlab import RasterModelGrid
>>> from landlab.components.overland_flow._links import (horizontal_link_ids,
... horizontal_west_link_neighbor)
>>> rmg = RasterModelGrid((4, 5))
>>> horizontal_links = horizontal_link_ids(rmg.shape).flatten()
>>> horizontal_west_link_neighbor(rmg.shape, horizontal_links)
array([-1, 0, 1, 2, -1, | |
"""This module contains the classes used for constructing and conducting an Experiment (most
notably, :class:`CVExperiment`). Any class contained herein whose name starts with "Base" should not
be used directly. :class:`CVExperiment` is the preferred means of conducting one-off experimentation
Related
-------
:mod:`hyperparameter_hunter.experiment_core`
Defines :class:`ExperimentMeta`, an understanding of which is critical to being able to
understand :mod:`experiments`
:mod:`hyperparameter_hunter.metrics`
Defines :class:`ScoringMixIn`, a parent of :class:`experiments.BaseExperiment` that enables
scoring and evaluating models
:mod:`hyperparameter_hunter.models`
Used to instantiate the actual learning models, which are a single part of the entire
experimentation workflow, albeit the most significant part
Notes
-----
As mentioned above, the inner workings of :mod:`experiments` will be very confusing without a grasp
on whats going on in :mod:`experiment_core`, and its related modules"""
##################################################
# Import Own Assets
##################################################
# noinspection PyProtectedMember
from hyperparameter_hunter import __version__
from hyperparameter_hunter.algorithm_handlers import (
identify_algorithm,
identify_algorithm_hyperparameters,
)
from hyperparameter_hunter.exceptions import (
EnvironmentInactiveError,
EnvironmentInvalidError,
RepeatedExperimentError,
)
from hyperparameter_hunter.experiment_core import ExperimentMeta
from hyperparameter_hunter.keys import HyperparameterKeyMaker
from hyperparameter_hunter.metrics import ScoringMixIn, get_formatted_target_metric
from hyperparameter_hunter.models import model_selector
from hyperparameter_hunter.recorders import RecorderList
from hyperparameter_hunter.settings import G
# from hyperparameter_hunter.tracers import TranslateTrace # TODO: Add when tested with `Mirror`
from hyperparameter_hunter.utils.file_utils import RetryMakeDirs
from hyperparameter_hunter.utils.general_utils import Deprecated
##################################################
# Import Miscellaneous Assets
##################################################
from abc import abstractmethod
from inspect import isclass
import numpy as np
import pandas as pd
import random
import shutil
from sys import exc_info
from uuid import uuid4 as uuid
import warnings
##################################################
# Import Learning Assets
##################################################
from sklearn.model_selection import KFold, StratifiedKFold, RepeatedKFold, RepeatedStratifiedKFold
import sklearn.utils as sklearn_utils
pd.set_option("display.expand_frame_repr", False)
warnings.simplefilter(action="ignore", category=FutureWarning)
warnings.simplefilter(action="ignore", category=DeprecationWarning)
warnings.simplefilter(action="ignore", category=sklearn_utils.DataConversionWarning)
np.random.seed(32)
class BaseExperiment(ScoringMixIn):
# @TranslateTrace("model", ("model_initializer", "model_init_params")) # TODO: Add when tested with `Mirror`
def __init__(
# TODO: Make `model_init_params` an optional kwarg - If not given, algorithm defaults used
self,
# model=None,
# model_initializer=None,
# model_init_params=None,
# TODO: Convert below 2 to above 3 lines for `TranslateTrace`
model_initializer,
model_init_params,
model_extra_params=None,
feature_engineer=None,
feature_selector=None,
notes=None,
do_raise_repeated=False,
auto_start=True,
target_metric=None,
):
# TODO: When `TranslateTrace` added document `model` below with expectation that if `model`
# TODO: ... given, (`model_initializer`, `model_init_params`) should not be, and vice versa
# TODO: `model` (Class instance, default=None);
# TODO: `model_initializer`/`model_init_params` docstring types += "default=None"
"""Base class for :class:`BaseCVExperiment`
Parameters
----------
model_initializer: Class, or functools.partial, or class instance
The algorithm class being used to initialize a model
model_init_params: Dict, or object
The dictionary of arguments given when creating a model instance with
`model_initializer` via the `__init__` method of :class:`models.Model`. Any kwargs that
are considered valid by the `__init__` method of `model_initializer` are valid in
`model_init_params`
model_extra_params: Dict, or None, default=None
A dictionary of extra parameters passed to :class:`models.Model`. This is used to
provide parameters to models' non-initialization methods (like `fit`, `predict`,
`predict_proba`, etc.), and for neural networks
feature_engineer: `FeatureEngineer`, or None, default=None
... # TODO: Add documentation
feature_selector: List of str, callable, list of booleans, default=None
The value provided when splitting apart the input data for all provided DataFrames.
`feature_selector` is provided as the second argument for calls to
`pandas.DataFrame.loc` in :meth:`BaseExperiment._initial_preprocessing`. If None,
`feature_selector` is set to all columns in :attr:`train_dataset`, less
:attr:`target_column`, and :attr:`id_column`
notes: String, or None, default=None
Additional information about the Experiment that will be saved with the Experiment's
description result file. This serves no purpose other than to facilitate saving
Experiment details in a more readable format
do_raise_repeated: Boolean, default=False
If True and this Experiment locates a previous Experiment's results with matching
Environment and Hyperparameter Keys, a RepeatedExperimentError will be raised. Else, a
warning will be logged
auto_start: Boolean, default=True
If True, after the Experiment is initialized, it will automatically call
:meth:`BaseExperiment.preparation_workflow`, followed by
:meth:`BaseExperiment.experiment_workflow`, effectively completing all essential tasks
without requiring additional method calls
target_metric: Tuple, str, default=('oof', <:attr:`environment.Environment.metrics`[0]>)
A path denoting the metric to be used to compare completed Experiments or to use for
certain early stopping procedures in some model classes. The first value should be one
of ['oof', 'holdout', 'in_fold']. The second value should be the name of a metric being
recorded according to the values supplied in
:attr:`environment.Environment.metrics_params`. See the documentation for
:func:`metrics.get_formatted_target_metric` for more info. Any values returned by, or
used as the `target_metric` input to this function are acceptable values for
:attr:`BaseExperiment.target_metric`"""
# self._model_original = model # TODO: Add for `TranslateTrace`
self.model_initializer = model_initializer
self.model_init_params = identify_algorithm_hyperparameters(self.model_initializer)
try:
self.model_init_params.update(model_init_params)
except TypeError:
self.model_init_params.update(dict(build_fn=model_init_params))
self.model_extra_params = model_extra_params if model_extra_params is not None else {}
self.feature_engineer = feature_engineer if feature_engineer is not None else {}
self.feature_selector = feature_selector if feature_selector is not None else []
self.notes = notes
self.do_raise_repeated = do_raise_repeated
self.auto_start = auto_start
self.target_metric = target_metric
#################### Attributes From Active Environment ####################
G.Env.initialize_reporting()
self._validate_environment()
self.train_dataset = G.Env.train_dataset.copy()
try:
self.holdout_dataset = G.Env.holdout_dataset.copy()
except AttributeError:
self.holdout_dataset = G.Env.holdout_dataset
try:
self.test_dataset = G.Env.test_dataset.copy()
except AttributeError:
self.test_dataset = G.Env.test_dataset
self.target_column = G.Env.target_column
self.id_column = G.Env.id_column
self.do_predict_proba = G.Env.do_predict_proba
self.prediction_formatter = G.Env.prediction_formatter
self.metrics_params = G.Env.metrics_params
self.experiment_params = G.Env.cross_experiment_params
self.cv_params = G.Env.cv_params
self.result_paths = G.Env.result_paths
self.cross_experiment_key = G.Env.cross_experiment_key
#################### Instantiate Other Attributes ####################
self.train_input_data = None
self.train_target_data = None
self.holdout_input_data = None
self.holdout_target_data = None
self.test_input_data = None
self.model = None
self.metrics = None # Set by :class:`metrics.ScoringMixIn`
self.stat_aggregates = dict()
self.result_description = None
#################### Experiment Identification Attributes ####################
self.experiment_id = None
self.hyperparameter_key = None
self.algorithm_name, self.module_name = identify_algorithm(self.model_initializer)
ScoringMixIn.__init__(self, **self.metrics_params if self.metrics_params else {})
if self.auto_start is True:
self.preparation_workflow()
self.experiment_workflow()
def __repr__(self):
return '{}("{}", cross_experiment_key="{}", hyperparameter_key="{}")'.format(
type(self).__name__,
self.experiment_id,
self.cross_experiment_key,
self.hyperparameter_key,
)
def __getattr__(self, attr):
"""If AttributeError thrown, check :attr:`settings.G.Env` for target attribute"""
try:
return getattr(G.Env, attr)
except AttributeError:
raise AttributeError(
"Could not find '{}' in 'G.Env', or any of the following locations: {}".format(
attr, [_.__name__ for _ in type(self).__mro__]
)
).with_traceback(exc_info()[2]) from None
def experiment_workflow(self):
"""Define the actual experiment process, including execution, result saving, and cleanup"""
if self.hyperparameter_key.exists is True:
_ex = f"{self!r} has already been run"
if self.do_raise_repeated is True:
self._clean_up()
raise RepeatedExperimentError(_ex)
G.debug(_ex)
G.warn("WARNING: Duplicate experiment!")
self._initialize_random_seeds()
self._initial_preprocessing()
self.execute()
#################### Save Experiment Results ####################
recorders = RecorderList(
file_blacklist=G.Env.file_blacklist, extra_recorders=G.Env.experiment_recorders
)
recorders.format_result()
G.log(f"Saving results for Experiment: '{self.experiment_id}'")
recorders.save_result()
self._clean_up()
def preparation_workflow(self):
"""Execute all tasks that must take place before the experiment is actually started. Such
tasks include (but are not limited to): Creating experiment IDs and hyperparameter keys,
creating script backups, and validating parameters"""
G.debug("Starting preparation_workflow...")
self._generate_experiment_id()
self._create_script_backup()
self._validate_parameters()
self._generate_hyperparameter_key()
self._additional_preparation_steps()
G.debug("Completed preparation_workflow")
@abstractmethod
def _additional_preparation_steps(self):
"""Perform extra preparation tasks prior to initializing random seeds and preprocessing"""
@abstractmethod
def execute(self):
"""Execute the fitting protocol for the Experiment, comprising the following: instantiation
of learners for each run, preprocessing of data as appropriate, training learners, making
predictions, and evaluating and aggregating those predictions and other stats/metrics for
later use"""
##################################################
# Data Preprocessing Methods:
##################################################
def _initial_preprocessing(self):
"""Perform preprocessing steps prior to executing fitting protocol (usually
cross-validation), consisting of: 1) Split train/holdout data into respective train/holdout
input and target data attributes, 2) Execute `feature_engineer` to perform "pre_cv"-stage
preprocessing, 3) Set datasets to their (modified) counterparts in `feature_engineer`"""
self.train_input_data = self.train_dataset.copy().loc[:, self.feature_selector]
self.train_target_data = self.train_dataset.copy().loc[:, self.target_column]
if isinstance(self.holdout_dataset, pd.DataFrame):
self.holdout_input_data = self.holdout_dataset.copy().loc[:, self.feature_selector]
self.holdout_target_data = self.holdout_dataset.copy().loc[:, self.target_column]
if isinstance(self.test_dataset, pd.DataFrame):
self.test_input_data = self.test_dataset.copy().loc[:, self.feature_selector]
if self.feature_engineer and callable(self.feature_engineer):
self.feature_engineer(
"pre_cv",
train_inputs=self.train_input_data,
train_targets=self.train_target_data,
holdout_inputs=self.holdout_input_data,
holdout_targets=self.holdout_target_data,
test_inputs=self.test_input_data,
)
self.train_input_data = self.feature_engineer.datasets["train_inputs"]
self.train_target_data = self.feature_engineer.datasets["train_targets"]
self.holdout_input_data = self.feature_engineer.datasets["holdout_inputs"]
self.holdout_target_data = self.feature_engineer.datasets["holdout_targets"]
self.test_input_data = self.feature_engineer.datasets["test_inputs"]
G.log("Initial preprocessing stage complete", 4)
##################################################
# Supporting Methods:
##################################################
def _validate_parameters(self):
"""Ensure provided input parameters are properly formatted"""
#################### target_metric ####################
self.target_metric = get_formatted_target_metric(self.target_metric, self.metrics)
#################### feature_selector ####################
self.feature_selector = self.feature_selector or self.train_dataset.columns.values
restricted_cols = [_ for _ in self.target_column + [self.id_column] if _ is not None]
self.feature_selector = [_ for _ in self.feature_selector if _ not in restricted_cols]
G.debug("Experiment parameters have been validated")
def _validate_environment(self):
"""Ensure there is a currently active Environment instance that is not already occupied"""
if G.Env is None:
raise EnvironmentInactiveError("")
if G.Env.current_task is None:
G.Env.current_task = self
G.log(f"Validated Environment: '{self.cross_experiment_key}'")
else:
raise EnvironmentInvalidError("Current experiment must finish before starting another")
@staticmethod
def _clean_up():
"""Clean up after experiment to prepare for next experiment"""
G.Env.current_task = None
##################################################
# Key/ID Methods:
##################################################
def _generate_experiment_id(self):
"""Set :attr:`experiment_id` to a UUID"""
self.experiment_id = str(uuid())
G.log("Initialized Experiment: '{}'".format(self.experiment_id))
def _generate_hyperparameter_key(self):
"""Set :attr:`hyperparameter_key` to a key to describe the experiment's hyperparameters"""
parameters = dict(
model_initializer=self.model_initializer,
model_init_params=self.model_init_params,
model_extra_params=self.model_extra_params,
feature_engineer=self.feature_engineer,
feature_selector=self.feature_selector,
# FLAG: Should probably add | |
# Copyright (c) 2016-present, <NAME>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
"""Python interface to the Zstandard (zstd) compression library."""
from __future__ import absolute_import, unicode_literals
# This should match what the C extension exports.
__all__ = [
#'BufferSegment',
#'BufferSegments',
#'BufferWithSegments',
#'BufferWithSegmentsCollection',
"CompressionParameters",
"ZstdCompressionDict",
"ZstdCompressionParameters",
"ZstdCompressor",
"ZstdError",
"ZstdDecompressor",
"FrameParameters",
"estimate_decompression_context_size",
"frame_content_size",
"frame_header_size",
"get_frame_parameters",
"train_dictionary",
# Constants.
"FLUSH_BLOCK",
"FLUSH_FRAME",
"COMPRESSOBJ_FLUSH_FINISH",
"COMPRESSOBJ_FLUSH_BLOCK",
"ZSTD_VERSION",
"FRAME_HEADER",
"CONTENTSIZE_UNKNOWN",
"CONTENTSIZE_ERROR",
"MAX_COMPRESSION_LEVEL",
"COMPRESSION_RECOMMENDED_INPUT_SIZE",
"COMPRESSION_RECOMMENDED_OUTPUT_SIZE",
"DECOMPRESSION_RECOMMENDED_INPUT_SIZE",
"DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE",
"MAGIC_NUMBER",
"BLOCKSIZELOG_MAX",
"BLOCKSIZE_MAX",
"WINDOWLOG_MIN",
"WINDOWLOG_MAX",
"CHAINLOG_MIN",
"CHAINLOG_MAX",
"HASHLOG_MIN",
"HASHLOG_MAX",
"HASHLOG3_MAX",
"MINMATCH_MIN",
"MINMATCH_MAX",
"SEARCHLOG_MIN",
"SEARCHLOG_MAX",
"SEARCHLENGTH_MIN",
"SEARCHLENGTH_MAX",
"TARGETLENGTH_MIN",
"TARGETLENGTH_MAX",
"LDM_MINMATCH_MIN",
"LDM_MINMATCH_MAX",
"LDM_BUCKETSIZELOG_MAX",
"STRATEGY_FAST",
"STRATEGY_DFAST",
"STRATEGY_GREEDY",
"STRATEGY_LAZY",
"STRATEGY_LAZY2",
"STRATEGY_BTLAZY2",
"STRATEGY_BTOPT",
"STRATEGY_BTULTRA",
"STRATEGY_BTULTRA2",
"DICT_TYPE_AUTO",
"DICT_TYPE_RAWCONTENT",
"DICT_TYPE_FULLDICT",
"FORMAT_ZSTD1",
"FORMAT_ZSTD1_MAGICLESS",
]
import io
import os
import sys
from _zstd_cffi import (
ffi,
lib,
)
if sys.version_info[0] == 2:
bytes_type = str
int_type = long
else:
bytes_type = bytes
int_type = int
COMPRESSION_RECOMMENDED_INPUT_SIZE = lib.ZSTD_CStreamInSize()
COMPRESSION_RECOMMENDED_OUTPUT_SIZE = lib.ZSTD_CStreamOutSize()
DECOMPRESSION_RECOMMENDED_INPUT_SIZE = lib.ZSTD_DStreamInSize()
DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE = lib.ZSTD_DStreamOutSize()
new_nonzero = ffi.new_allocator(should_clear_after_alloc=False)
MAX_COMPRESSION_LEVEL = lib.ZSTD_maxCLevel()
MAGIC_NUMBER = lib.ZSTD_MAGICNUMBER
FRAME_HEADER = b"\x28\xb5\x2f\xfd"
CONTENTSIZE_UNKNOWN = lib.ZSTD_CONTENTSIZE_UNKNOWN
CONTENTSIZE_ERROR = lib.ZSTD_CONTENTSIZE_ERROR
ZSTD_VERSION = (
lib.ZSTD_VERSION_MAJOR,
lib.ZSTD_VERSION_MINOR,
lib.ZSTD_VERSION_RELEASE,
)
BLOCKSIZELOG_MAX = lib.ZSTD_BLOCKSIZELOG_MAX
BLOCKSIZE_MAX = lib.ZSTD_BLOCKSIZE_MAX
WINDOWLOG_MIN = lib.ZSTD_WINDOWLOG_MIN
WINDOWLOG_MAX = lib.ZSTD_WINDOWLOG_MAX
CHAINLOG_MIN = lib.ZSTD_CHAINLOG_MIN
CHAINLOG_MAX = lib.ZSTD_CHAINLOG_MAX
HASHLOG_MIN = lib.ZSTD_HASHLOG_MIN
HASHLOG_MAX = lib.ZSTD_HASHLOG_MAX
HASHLOG3_MAX = lib.ZSTD_HASHLOG3_MAX
MINMATCH_MIN = lib.ZSTD_MINMATCH_MIN
MINMATCH_MAX = lib.ZSTD_MINMATCH_MAX
SEARCHLOG_MIN = lib.ZSTD_SEARCHLOG_MIN
SEARCHLOG_MAX = lib.ZSTD_SEARCHLOG_MAX
SEARCHLENGTH_MIN = lib.ZSTD_MINMATCH_MIN
SEARCHLENGTH_MAX = lib.ZSTD_MINMATCH_MAX
TARGETLENGTH_MIN = lib.ZSTD_TARGETLENGTH_MIN
TARGETLENGTH_MAX = lib.ZSTD_TARGETLENGTH_MAX
LDM_MINMATCH_MIN = lib.ZSTD_LDM_MINMATCH_MIN
LDM_MINMATCH_MAX = lib.ZSTD_LDM_MINMATCH_MAX
LDM_BUCKETSIZELOG_MAX = lib.ZSTD_LDM_BUCKETSIZELOG_MAX
STRATEGY_FAST = lib.ZSTD_fast
STRATEGY_DFAST = lib.ZSTD_dfast
STRATEGY_GREEDY = lib.ZSTD_greedy
STRATEGY_LAZY = lib.ZSTD_lazy
STRATEGY_LAZY2 = lib.ZSTD_lazy2
STRATEGY_BTLAZY2 = lib.ZSTD_btlazy2
STRATEGY_BTOPT = lib.ZSTD_btopt
STRATEGY_BTULTRA = lib.ZSTD_btultra
STRATEGY_BTULTRA2 = lib.ZSTD_btultra2
DICT_TYPE_AUTO = lib.ZSTD_dct_auto
DICT_TYPE_RAWCONTENT = lib.ZSTD_dct_rawContent
DICT_TYPE_FULLDICT = lib.ZSTD_dct_fullDict
FORMAT_ZSTD1 = lib.ZSTD_f_zstd1
FORMAT_ZSTD1_MAGICLESS = lib.ZSTD_f_zstd1_magicless
FLUSH_BLOCK = 0
FLUSH_FRAME = 1
COMPRESSOBJ_FLUSH_FINISH = 0
COMPRESSOBJ_FLUSH_BLOCK = 1
def _cpu_count():
# os.cpu_count() was introducd in Python 3.4.
try:
return os.cpu_count() or 0
except AttributeError:
pass
# Linux.
try:
if sys.version_info[0] == 2:
return os.sysconf(b"SC_NPROCESSORS_ONLN")
else:
return os.sysconf("SC_NPROCESSORS_ONLN")
except (AttributeError, ValueError):
pass
# TODO implement on other platforms.
return 0
class ZstdError(Exception):
pass
def _zstd_error(zresult):
# Resolves to bytes on Python 2 and 3. We use the string for formatting
# into error messages, which will be literal unicode. So convert it to
# unicode.
return ffi.string(lib.ZSTD_getErrorName(zresult)).decode("utf-8")
def _make_cctx_params(params):
res = lib.ZSTD_createCCtxParams()
if res == ffi.NULL:
raise MemoryError()
res = ffi.gc(res, lib.ZSTD_freeCCtxParams)
attrs = [
(lib.ZSTD_c_format, params.format),
(lib.ZSTD_c_compressionLevel, params.compression_level),
(lib.ZSTD_c_windowLog, params.window_log),
(lib.ZSTD_c_hashLog, params.hash_log),
(lib.ZSTD_c_chainLog, params.chain_log),
(lib.ZSTD_c_searchLog, params.search_log),
(lib.ZSTD_c_minMatch, params.min_match),
(lib.ZSTD_c_targetLength, params.target_length),
(lib.ZSTD_c_strategy, params.compression_strategy),
(lib.ZSTD_c_contentSizeFlag, params.write_content_size),
(lib.ZSTD_c_checksumFlag, params.write_checksum),
(lib.ZSTD_c_dictIDFlag, params.write_dict_id),
(lib.ZSTD_c_nbWorkers, params.threads),
(lib.ZSTD_c_jobSize, params.job_size),
(lib.ZSTD_c_overlapLog, params.overlap_log),
(lib.ZSTD_c_forceMaxWindow, params.force_max_window),
(lib.ZSTD_c_enableLongDistanceMatching, params.enable_ldm),
(lib.ZSTD_c_ldmHashLog, params.ldm_hash_log),
(lib.ZSTD_c_ldmMinMatch, params.ldm_min_match),
(lib.ZSTD_c_ldmBucketSizeLog, params.ldm_bucket_size_log),
(lib.ZSTD_c_ldmHashRateLog, params.ldm_hash_rate_log),
]
for param, value in attrs:
_set_compression_parameter(res, param, value)
return res
class ZstdCompressionParameters(object):
@staticmethod
def from_level(level, source_size=0, dict_size=0, **kwargs):
params = lib.ZSTD_getCParams(level, source_size, dict_size)
args = {
"window_log": "windowLog",
"chain_log": "chainLog",
"hash_log": "hashLog",
"search_log": "searchLog",
"min_match": "minMatch",
"target_length": "targetLength",
"compression_strategy": "strategy",
}
for arg, attr in args.items():
if arg not in kwargs:
kwargs[arg] = getattr(params, attr)
return ZstdCompressionParameters(**kwargs)
def __init__(
self,
format=0,
compression_level=0,
window_log=0,
hash_log=0,
chain_log=0,
search_log=0,
min_match=0,
target_length=0,
strategy=-1,
compression_strategy=-1,
write_content_size=1,
write_checksum=0,
write_dict_id=0,
job_size=0,
overlap_log=-1,
overlap_size_log=-1,
force_max_window=0,
enable_ldm=0,
ldm_hash_log=0,
ldm_min_match=0,
ldm_bucket_size_log=0,
ldm_hash_rate_log=-1,
ldm_hash_every_log=-1,
threads=0,
):
params = lib.ZSTD_createCCtxParams()
if params == ffi.NULL:
raise MemoryError()
params = ffi.gc(params, lib.ZSTD_freeCCtxParams)
self._params = params
if threads < 0:
threads = _cpu_count()
# We need to set ZSTD_c_nbWorkers before ZSTD_c_jobSize and ZSTD_c_overlapLog
# because setting ZSTD_c_nbWorkers resets the other parameters.
_set_compression_parameter(params, lib.ZSTD_c_nbWorkers, threads)
_set_compression_parameter(params, lib.ZSTD_c_format, format)
_set_compression_parameter(
params, lib.ZSTD_c_compressionLevel, compression_level
)
_set_compression_parameter(params, lib.ZSTD_c_windowLog, window_log)
_set_compression_parameter(params, lib.ZSTD_c_hashLog, hash_log)
_set_compression_parameter(params, lib.ZSTD_c_chainLog, chain_log)
_set_compression_parameter(params, lib.ZSTD_c_searchLog, search_log)
_set_compression_parameter(params, lib.ZSTD_c_minMatch, min_match)
_set_compression_parameter(
params, lib.ZSTD_c_targetLength, target_length
)
if strategy != -1 and compression_strategy != -1:
raise ValueError(
"cannot specify both compression_strategy and strategy"
)
if compression_strategy != -1:
strategy = compression_strategy
elif strategy == -1:
strategy = 0
_set_compression_parameter(params, lib.ZSTD_c_strategy, strategy)
_set_compression_parameter(
params, lib.ZSTD_c_contentSizeFlag, write_content_size
)
_set_compression_parameter(
params, lib.ZSTD_c_checksumFlag, write_checksum
)
_set_compression_parameter(params, lib.ZSTD_c_dictIDFlag, write_dict_id)
_set_compression_parameter(params, lib.ZSTD_c_jobSize, job_size)
if overlap_log != -1 and overlap_size_log != -1:
raise ValueError(
"cannot specify both overlap_log and overlap_size_log"
)
if overlap_size_log != -1:
overlap_log = overlap_size_log
elif overlap_log == -1:
overlap_log = 0
_set_compression_parameter(params, lib.ZSTD_c_overlapLog, overlap_log)
_set_compression_parameter(
params, lib.ZSTD_c_forceMaxWindow, force_max_window
)
_set_compression_parameter(
params, lib.ZSTD_c_enableLongDistanceMatching, enable_ldm
)
_set_compression_parameter(params, lib.ZSTD_c_ldmHashLog, ldm_hash_log)
_set_compression_parameter(
params, lib.ZSTD_c_ldmMinMatch, ldm_min_match
)
_set_compression_parameter(
params, lib.ZSTD_c_ldmBucketSizeLog, ldm_bucket_size_log
)
if ldm_hash_rate_log != -1 and ldm_hash_every_log != -1:
raise ValueError(
"cannot specify both ldm_hash_rate_log and ldm_hash_every_log"
)
if ldm_hash_every_log != -1:
ldm_hash_rate_log = ldm_hash_every_log
elif ldm_hash_rate_log == -1:
ldm_hash_rate_log = 0
_set_compression_parameter(
params, lib.ZSTD_c_ldmHashRateLog, ldm_hash_rate_log
)
@property
def format(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_format)
@property
def compression_level(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_compressionLevel
)
@property
def window_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_windowLog)
@property
def hash_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_hashLog)
@property
def chain_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_chainLog)
@property
def search_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_searchLog)
@property
def min_match(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_minMatch)
@property
def target_length(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_targetLength)
@property
def compression_strategy(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_strategy)
@property
def write_content_size(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_contentSizeFlag
)
@property
def write_checksum(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_checksumFlag)
@property
def write_dict_id(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_dictIDFlag)
@property
def job_size(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_jobSize)
@property
def overlap_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_overlapLog)
@property
def overlap_size_log(self):
return self.overlap_log
@property
def force_max_window(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_forceMaxWindow
)
@property
def enable_ldm(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_enableLongDistanceMatching
)
@property
def ldm_hash_log(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_ldmHashLog)
@property
def ldm_min_match(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_ldmMinMatch)
@property
def ldm_bucket_size_log(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_ldmBucketSizeLog
)
@property
def ldm_hash_rate_log(self):
return _get_compression_parameter(
self._params, lib.ZSTD_c_ldmHashRateLog
)
@property
def ldm_hash_every_log(self):
return self.ldm_hash_rate_log
@property
def threads(self):
return _get_compression_parameter(self._params, lib.ZSTD_c_nbWorkers)
def estimated_compression_context_size(self):
return lib.ZSTD_estimateCCtxSize_usingCCtxParams(self._params)
CompressionParameters = ZstdCompressionParameters
def estimate_decompression_context_size():
return lib.ZSTD_estimateDCtxSize()
def _set_compression_parameter(params, param, value):
zresult = lib.ZSTD_CCtxParams_setParameter(params, param, value)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"unable to set compression context parameter: %s"
% _zstd_error(zresult)
)
def _get_compression_parameter(params, param):
result = ffi.new("int *")
zresult = lib.ZSTD_CCtxParams_getParameter(params, param, result)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"unable to get compression context parameter: %s"
% _zstd_error(zresult)
)
return result[0]
class ZstdCompressionWriter(object):
def __init__(
self, compressor, writer, source_size, write_size, write_return_read
):
self._compressor = compressor
self._writer = writer
self._write_size = write_size
self._write_return_read = bool(write_return_read)
self._entered = False
self._closed = False
self._bytes_compressed = 0
self._dst_buffer = ffi.new("char[]", write_size)
self._out_buffer = ffi.new("ZSTD_outBuffer *")
self._out_buffer.dst = self._dst_buffer
self._out_buffer.size = len(self._dst_buffer)
self._out_buffer.pos = 0
zresult = lib.ZSTD_CCtx_setPledgedSrcSize(compressor._cctx, source_size)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"error setting source size: %s" % _zstd_error(zresult)
)
def __enter__(self):
if self._closed:
raise ValueError("stream is closed")
if self._entered:
raise ZstdError("cannot __enter__ multiple times")
self._entered = True
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self._entered = False
if not exc_type and not exc_value and not exc_tb:
self.close()
self._compressor = None
return False
def memory_size(self):
return lib.ZSTD_sizeof_CCtx(self._compressor._cctx)
def fileno(self):
f = getattr(self._writer, "fileno", None)
if f:
return f()
else:
raise OSError("fileno not available on underlying writer")
def close(self):
if self._closed:
return
try:
self.flush(FLUSH_FRAME)
finally:
self._closed = True
# Call close() on underlying stream as well.
f = getattr(self._writer, "close", None)
if f:
f()
@property
def closed(self):
return self._closed
def isatty(self):
return False
def readable(self):
return False
def readline(self, size=-1):
raise io.UnsupportedOperation()
def readlines(self, hint=-1):
raise io.UnsupportedOperation()
def seek(self, offset, whence=None):
raise io.UnsupportedOperation()
def seekable(self):
return False
def truncate(self, size=None):
raise io.UnsupportedOperation()
def writable(self):
return True
def writelines(self, lines):
raise NotImplementedError("writelines() is not yet implemented")
def read(self, size=-1):
raise io.UnsupportedOperation()
def readall(self):
raise io.UnsupportedOperation()
def readinto(self, b):
raise io.UnsupportedOperation()
def write(self, data):
if self._closed:
raise ValueError("stream is closed")
total_write = 0
data_buffer = ffi.from_buffer(data)
in_buffer = ffi.new("ZSTD_inBuffer *")
in_buffer.src = data_buffer
in_buffer.size = len(data_buffer)
in_buffer.pos = 0
out_buffer = self._out_buffer
out_buffer.pos = 0
while in_buffer.pos < in_buffer.size:
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx,
out_buffer,
in_buffer,
lib.ZSTD_e_continue,
)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"zstd compress error: %s" % _zstd_error(zresult)
)
if out_buffer.pos:
self._writer.write(
ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
)
total_write += out_buffer.pos
self._bytes_compressed += out_buffer.pos
out_buffer.pos = 0
if self._write_return_read:
return in_buffer.pos
else:
return total_write
def flush(self, flush_mode=FLUSH_BLOCK):
if flush_mode == FLUSH_BLOCK:
flush = lib.ZSTD_e_flush
elif flush_mode == FLUSH_FRAME:
flush = lib.ZSTD_e_end
else:
raise ValueError("unknown flush_mode: %r" % flush_mode)
if self._closed:
raise ValueError("stream is closed")
total_write = 0
out_buffer = self._out_buffer
out_buffer.pos = 0
in_buffer = ffi.new("ZSTD_inBuffer *")
in_buffer.src = ffi.NULL
in_buffer.size = 0
in_buffer.pos = 0
while True:
zresult = lib.ZSTD_compressStream2(
self._compressor._cctx, out_buffer, in_buffer, flush
)
if lib.ZSTD_isError(zresult):
raise ZstdError(
"zstd compress error: %s" % _zstd_error(zresult)
)
if out_buffer.pos:
self._writer.write(
ffi.buffer(out_buffer.dst, out_buffer.pos)[:]
)
total_write += out_buffer.pos
self._bytes_compressed += out_buffer.pos
out_buffer.pos = 0
if not zresult:
break
return total_write
def tell(self):
return self._bytes_compressed
class ZstdCompressionObj(object):
def | |
bbox_to_anchor=(0.5, 1.3), fontsize=12, frameon=False)
ax1.text(6, -15, 'Chemical Shift (ppm)', fontsize=16)
ax0.set_ylabel('Intensity', fontsize=16)
ax1.set_ylabel('Intensity', fontsize=16)
# add the relevant labels for species
# butenedial:
ax0.text(5.9, 60, r'\textbf{BD}', fontsize=10)
ax0.text(6.2, 90, r'\textbf{BD}', fontsize=10)
# pyrrolinone:
ax1.text(6.7, 7, r'\textbf{PR, h}', fontsize=10)
ax1.text(5.8, 20, 'PR, g', fontsize=10)
ax1.plot([5.9, 5.8], [8, 19], lw=1, color='0.25')
ax2.text(3.38, 25, 'PR,\nf', fontsize=10)
ax2.vlines(3.37, 16, 23, lw=1, color='0.25')
# butenedial-pyrrolinone dimer:
ax1.text(5.67, 14, r'\textbf{BD-PR,}', fontsize=10)
ax1.text(5.67, 11, r'\textbf{j}', fontsize=10)
ax1.text(5.45, 9, 'k', fontsize=10)
ax1.text(6.1, 18, 'BD-PR,', fontsize=10)
ax1.text(6., 15, 'n', fontsize=10)
ax1.text(6.08, 12, 'm', fontsize=10)
ax1.text(6.45, 15, 'BD-PR,\nl', fontsize=10)
ax1.vlines(6.3, 6, 16, lw=1, color='0.25')
ax1.vlines(6.05, 5, 11, lw=1, color='0.25')
ax1.vlines(5.97, 6, 14, lw=1, color='0.25')
ax2.text(3.49, 16, 'BD-PR,\ni', fontsize=10)
# add in the leftover molecules
ax0.text(5.15, 100, 'HDO', fontsize=10)
ax0.text(3.42, 100, 'DMS', fontsize=10)
ax0.text(2.1, 45, 'HAc', fontsize=10)
ax0.text(1.5, 15, 'MPA', fontsize=10)
ax2.text(3.38, 48, 'MeOH', fontsize=10)
fig_path = create_fig_path('bdnhx_nmr_spectrum')
plt.savefig(fig_path, bbox_inches='tight', dpi=300, transparent=True)
fns = ['20210126_bdohph11_5min.csv', '20210126_bdohph11_25min.csv',
'20210126_bdohph11_hr.csv']
path = os.path.join(d, 'data_raw', 'nmrs', fns[0])
df_0 = pd.read_csv(path, sep='\t', header=None, names=['PPM', 'SIG', 'x'])
df_0.drop(columns=['x'], inplace=True)
path = os.path.join(d, 'data_raw', 'nmrs', fns[1])
df_1 = pd.read_csv(path, sep='\t', header=None, names=['PPM', 'SIG', 'x'])
df_1.drop(columns=['x'], inplace=True)
path = os.path.join(d, 'data_raw', 'nmrs', fns[2])
df_2 = pd.read_csv(path, sep='\t', header=None, names=['PPM', 'SIG', 'x'])
df_2.drop(columns=['x'], inplace=True)
dmso_sig_0 = df_0.loc[(df_0.PPM > 3) & (df_0.PPM < 3.2)].SIG.max()
dmso_sig_1 = df_1.loc[(df_1.PPM > 3) & (df_1.PPM < 3.2)].SIG.max()
dmso_sig_2 = df_2.loc[(df_2.PPM > 3) & (df_2.PPM < 3.2)].SIG.max()
df_0 = scale_nmr(df_0, 'SIG', dmso_sig_0)
df_1 = scale_nmr(df_1, 'SIG', dmso_sig_1)
df_2 = scale_nmr(df_2, 'SIG', dmso_sig_2)
fig = plt.figure(figsize=(10, 5))
plt.tight_layout()
gs = GridSpec(2, 4)
gs.update(hspace=0.3)
gs.update(wspace=0.5)
ax0 = plt.subplot(gs[0:2, 0:2])
ax1 = plt.subplot(gs[0, 2:4])
ax2 = plt.subplot(gs[1, 2:4])
axes = [ax0, ax1, ax2]
xranges = [[8.1, 0.1], [4.6, 3.6], [6.3, 5.3]]
xlims_for_ymax = [[5, 6.5], [4.6, 3.6], [5.5, 5]]
for tick in range(3):
ax = axes[tick]
ax.plot(df_0.PPM, df_0.SIG, lw=2, color='blue', alpha=0.5, label='5 min reacted')
ax.plot(df_1.PPM, df_1.SIG, lw=2, color='red', alpha=0.5, label='25 min reacted')
ax.plot(df_2.PPM, df_2.SIG, lw=2, color='brown', alpha=0.5, label='2 hr reacted')
ymax = choose_ymax_nmr_subplot(df_0, 'PPM', xlims_for_ymax[tick])
ax.set_xlim(xranges[tick][0], xranges[tick][1])
ax.set_ylim(bottom=ymax * -0.02, top=ymax)
if tick > 0:
rect = patches.Rectangle((xranges[tick][0], -0.02),
xranges[tick][1] - xranges[tick][0], ymax*1.2,
linewidth=1, edgecolor='0.25', facecolor='0.8', alpha=0.2)
ax0.add_patch(rect)
ax0.legend(loc='upper center', ncol=3, bbox_to_anchor=(1.1, 1.1), fontsize=12, frameon=False)
ax0.set_ylabel('Intensity')
# add the relevant labels for species
# butenedial:
ax0.text(6.05, 10, r'\textbf{BD, a}', fontsize=10)
ax0.plot([6, 6], [6, 9], lw=1, color='0.25')
ax0.text(7.1, 30, r'\textbf{BD, b}', fontsize=10)
# products:
# ax0.text(5.75, 4, 'accretion\nproducts', fontsize=10)
# add in the leftover molecules
ax0.text(5.6, 40, 'HDO', fontsize=10)
ax0.text(3.05, 40, 'DMS', fontsize=10)
ax0.text(2.15, 15, 'HAc', fontsize=10)
ax0.text(4.2, 18, 'MeOH', fontsize=10)
ax2.text(6.7, -1.3, 'Chemical Shift (ppm)', fontsize=16)
ax0.set_ylabel('Intensity', fontsize=16)
fig_path = create_fig_path('bdoh_nmr_spectrum')
plt.savefig(fig_path, bbox_inches='tight', dpi=300, transparent=True)
# comparative plot of bd/nhx and bd/oh
fns = ['20200724_bd_as_nmr.csv', '20210126_bdohph11_5min.csv']
d = get_project_directory()
path = os.path.join(d, 'data_raw', 'nmrs', fns[0])
df_0 = pd.read_csv(path, sep='\t', header=None, names=['PPM', 'SIG', 'x'])
df_0.drop(columns=['x'], inplace=True)
path = os.path.join(d, 'data_raw', 'nmrs', fns[1])
df_1 = pd.read_csv(path, sep='\t', header=None, names=['PPM', 'SIG', 'x'])
df_1.drop(columns=['x'], inplace=True)
dmso_sig_0 = df_0.loc[(df_0.PPM > 3) & (df_0.PPM < 3.2)].SIG.max()
dmso_sig_1 = df_1.loc[(df_1.PPM > 3) & (df_1.PPM < 3.2)].SIG.max()
df_0 = scale_nmr(df_0, 'SIG', dmso_sig_0)
df_1 = scale_nmr(df_1, 'SIG', dmso_sig_1)
fig = plt.figure(figsize=(10, 5))
plt.tight_layout()
gs = GridSpec(2, 4)
gs.update(hspace=0.5)
gs.update(wspace=0.5)
ax0 = plt.subplot(gs[0, :], )
ax1 = plt.subplot(gs[1, 0:3])
ax2 = plt.subplot(gs[1, 3:4])
axes = [ax0, ax1, ax2]
xranges = [[8.1, 1.1], [7, 5], [3.5, 3.25]]
xlims_for_ymax = [[3, 3.2], [3.2, 4.2], [5.5, 6]]
for tick in range(3):
ax = axes[tick]
ax.plot(df_0.PPM, df_0.SIG, lw=2, color='blue', alpha=0.5, label='10 min reacted')
ax.plot(df_1.PPM, df_1.SIG, lw=2, color='red', alpha=0.5, label='120 min reacted')
ymax = choose_ymax_nmr_subplot(df_0, 'PPM', xlims_for_ymax[tick])
ax.set_xlim(xranges[tick][0], xranges[tick][1])
ax.set_ylim(bottom=ymax * -0.02, top=ymax)
if tick > 0:
rect = patches.Rectangle((min(xranges[tick]), ymax * -0.02),
max(xranges[tick]) - min(xranges[tick]), ymax,
linewidth=1, edgecolor='0.25', facecolor='0.8', alpha=0.2)
ax0.add_patch(rect)
ax0.legend(loc='upper center', ncol=2, bbox_to_anchor=(0.5, 1.3), fontsize=12, frameon=False)
ax1.text(6, -15, 'Chemical Shift (ppm)', fontsize=16)
ax0.set_ylabel('Intensity', fontsize=16)
ax1.set_ylabel('Intensity', fontsize=16)
# add the relevant labels for species
# butenedial:
ax0.text(5.9, 60, r'\textbf{BD}', fontsize=10)
ax0.text(6.2, 90, r'\textbf{BD}', fontsize=10)
# pyrrolinone:
ax1.text(6.7, 7, r'\textbf{PR, h}', fontsize=10)
ax1.text(5.8, 20, 'PR, g', fontsize=10)
ax1.plot([5.9, 5.8], [8, 19], lw=1, color='0.25')
ax2.text(3.38, 25, 'PR,\nf', fontsize=10)
ax2.vlines(3.37, 16, 23, lw=1, color='0.25')
# butenedial-pyrrolinone dimer:
ax1.text(5.67, 14, r'\textbf{BD-PR,}', fontsize=10)
ax1.text(5.67, 11, r'\textbf{j}', fontsize=10)
ax1.text(5.45, 9, 'k', fontsize=10)
ax1.text(6.1, 18, 'BD-PR,', fontsize=10)
ax1.text(6., 15, 'n', fontsize=10)
ax1.text(6.08, 12, 'm', fontsize=10)
ax1.text(6.45, 15, 'BD-PR,\nl', fontsize=10)
ax1.vlines(6.3, 6, 16, lw=1, color='0.25')
ax1.vlines(6.05, 5, 11, lw=1, color='0.25')
ax1.vlines(5.97, 6, 14, lw=1, color='0.25')
ax2.text(3.49, 16, 'BD-PR,\ni', fontsize=10)
# add in the leftover molecules
ax0.text(5.15, 100, 'HDO', fontsize=10)
ax0.text(3.42, 100, 'DMS', fontsize=10)
ax0.text(2.1, 45, 'HAc', fontsize=10)
ax0.text(1.5, 15, 'MPA', fontsize=10)
ax2.text(3.38, 48, 'MeOH', fontsize=10)
fig_path = create_fig_path('bdnhx_bdoh_nmr_spectrum')
plt.savefig(fig_path, bbox_inches='tight', dpi=300, transparent=True)
# 6: plots of the mass spec data
# load the data
project_dir = get_project_directory()
solution_file_name = '20210126_solution.txt'
background_file_name = '20210126_solution_background.txt'
data_path = os.path.join(project_dir, 'data_raw', 'ms_files', solution_file_name)
solution_df = pd.read_fwf(data_path, header=None)
data_path = os.path.join(project_dir, 'data_raw', 'ms_files', background_file_name)
background_df = pd.read_fwf(data_path, header=None)
# do some small data treatment
solution_df.columns = ['MZ', 'SIG']
background_df.columns = ['MZ', 'SIG']
solution_df.dropna(inplace=True)
background_df.dropna(inplace=True)
background_df.MZ = background_df.MZ.astype(float)
solution_df.MZ = solution_df.MZ.astype(float)
solution_df['BKGD_SUB_SIG'] = solution_df.SIG - background_df.SIG
solution_df = solution_df.round(0)
solution_df = solution_df.groupby(solution_df.MZ).sum().reset_index() # group by integer mz units
peg6_fragments = [45, 89, 133, 151, 177, 195, 221, 239, 283, 301]
# plot of total spectrum
fig = plt.figure(figsize=(10, 5))
plt.tight_layout()
gs = GridSpec(2, 6)
gs.update(hspace=0.3)
gs.update(wspace=1.2)
ax = plt.subplot(gs[0, :], )
ax1 = plt.subplot(gs[1, 0:2])
ax2 = plt.subplot(gs[1, 2:5])
ax3 = plt.subplot(gs[1, 5:6])
axes = [ax, ax1, ax2, ax3]
ax.stem(solution_df.MZ, solution_df.SIG, linefmt='0.8', markerfmt='None', use_line_collection=True,
basefmt='k')
ax.stem(solution_df.MZ, solution_df.BKGD_SUB_SIG, linefmt='0.3', markerfmt='None', use_line_collection=True,
basefmt='k')
ax.plot([-1, -1], [-5, -5], c='0.8', label='Raw signal')
ax.plot([-1, -1], [-5, -5], c='0.3', label='Background subtracted signal')
ax.set_xlim(20, 400)
ax.set_ylim(-5000, 100000)
ax.set_xticklabels(ax.get_xticks())
labels = [str(int(float(item.get_text()))) for item in ax.get_xticklabels()]
ax.set_xticklabels(labels)
ax.set_yticklabels(ax.get_yticks())
labels = [str(int(float(item.get_text()))) for item in ax.get_yticklabels()]
ax.set_yticklabels(labels)
ax.set_ylabel('Intensity')
for peg6_fragment in peg6_fragments:
if peg6_fragment is 283:
ax.text(peg6_fragment - 3, 5000 + solution_df.SIG[solution_df.MZ == peg6_fragment], '* PEG-6', fontsize=14)
else:
ax.text(peg6_fragment - 3, 5000 + solution_df.SIG[solution_df.MZ == peg6_fragment], '*', fontsize=14)
ax.text(78, 80000, '(a)', color='0.5', fontsize=16)
ax.text(143, 80000, '(b)', color='0.5', fontsize=16)
ax.text(163, 80000, '(c)', color='0.5', fontsize=16)
ax.legend(loc='upper center', ncol=2, bbox_to_anchor=(0.5, 1.3), fontsize=12, frameon=False)
ax1.stem(solution_df.MZ, solution_df.SIG, linefmt='0.8', markerfmt='None', use_line_collection=True, basefmt='k')
ax1.stem(solution_df.MZ, solution_df.BKGD_SUB_SIG, linefmt='0.4', markerfmt='None', use_line_collection=True,
basefmt='k')
ax1.set_xlim(83.5, 85.5)
ax1.set_ylim(-1000, 70000)
ax1.set_yticklabels(ax1.get_yticks())
labels = [str(int(float(item.get_text()))) for item in ax1.get_yticklabels()]
ax1.set_yticklabels(labels)
ax1.set_xticklabels(ax1.get_xticks())
labels = [str(int(float(item.get_text()))) for item in ax1.get_xticklabels()]
ax1.set_xticklabels(labels)
ax1.text(84.15, 55000, 'PR', fontsize=14)
ax1.text(84.9, 30000, 'BD', fontsize=14)
ax1.text(83.6, 60000, '(a)', color='0.5', fontsize=16)
ax1.set_ylabel('Intensity')
ax2.stem(solution_df.MZ, solution_df.SIG, linefmt='0.8', markerfmt='None', use_line_collection=True, basefmt='k')
ax2.stem(solution_df.MZ, solution_df.BKGD_SUB_SIG, linefmt='0.4', markerfmt='None', use_line_collection=True,
basefmt='k')
ax2.set_xlim(148.5, 151.5)
ax2.set_ylim(-500, 20000)
ax2.set_yticklabels(ax2.get_yticks())
labels = [str(int(float(item.get_text()))) for item in ax2.get_yticklabels()]
ax2.set_yticklabels(labels)
ax2.set_xticklabels(ax2.get_xticks())
labels = [str(int(float(item.get_text()))) for item in ax2.get_xticklabels()]
ax2.set_xticklabels(labels)
ax2.text(148.7, 5000, 'DZ', fontsize=14)
ax2.text(149.7, 13000, 'BD-PR', fontsize=14)
ax2.text(150.95, 10000, '*', fontsize=14)
ax2.text(148.6, 17000, '(b)', color='0.5', fontsize=16)
ax3.stem(solution_df.MZ, solution_df.SIG, linefmt='0.8', markerfmt='None', use_line_collection=True, basefmt='k')
ax3.stem(solution_df.MZ, solution_df.BKGD_SUB_SIG, linefmt='0.4', markerfmt='None', use_line_collection=True,
basefmt='k')
ax3.set_xlim(167.5, 168.5)
ax3.set_ylim(-500, 20000)
ax3.set_yticklabels(ax3.get_yticks())
labels = [str(int(float(item.get_text()))) for item in ax3.get_yticklabels()]
ax3.set_yticklabels(labels)
ax3.xaxis.set_major_locator(ticker.MultipleLocator(base=1))
ax3.set_xticklabels(ax3.get_xticks())
labels = [str(int(float(item.get_text()))) for item in ax3.get_xticklabels()]
ax3.set_xticklabels(labels)
ax3.text(167.55, 6000, 'BD-PR', fontsize=14)
ax3.text(167.6, 17000, '(c)', color='0.5', fontsize=16)
ax2.text(148.3, -8000, 'mass-to-charge ratio') # xlabel
fig_path = create_fig_path('solution_mass_spec')
plt.savefig(fig_path, bbox_inches='tight', dpi=300, transparent=False)
# 7: plots of the bd degradation data
expt_labels = ['bdph8_nmr', 'bdph9_nmr', 'bdph10_nmr', 'bdph11_nmr']
fig, (ax0, ax1, ax2, ax3) = plt.subplots(1, 4, figsize=(9, 2.5))
axes = [ax0, ax1, ax2, ax3]
plt.tight_layout()
for tick in range(4):
ax = axes[tick]
expt_label = expt_labels[tick]
fn = expts[expt_label]['paths']['processed_data']
df_processed = import_treated_csv_data(fn, expt_label)
fn = expts[expt_label]['paths']['modeled_data']
df_modeled = import_treated_csv_data(fn, expt_label)
df_model_params = import_treated_csv_data(expts[expt_label]['paths']['model_parameters_data'], expt_label)
title = round(np.mean(df_processed.pH), 1)
if title >= 10:
title = 'pH ' + str(title)[:4]
elif title < 10:
title = 'pH ' + str(title)[:3]
ax.plot(df_modeled['MINS_ELAPSED'], df_modeled['M_BUTENEDIAL'], color='0.25', lw=3, label='Model Fit')
ax.fill_between(df_modeled['MINS_ELAPSED'], df_modeled['M_BUTENEDIAL_MIN'], df_modeled['M_BUTENEDIAL_MAX'],
color='0.8', label='95\% Confidence Interval')
ax.scatter(df_processed['MINS_ELAPSED'], df_processed['M_BUTENEDIAL'], color='0.25', s=30, label='Observation')
k = 1000*df_model_params['k'][0]/60 # s
ax.text(2, 0.02, 'k = ' + str(k)[0:4] + r'$\times$10$^{-3}$ s$^{-1}$', fontsize=10)
ax.set_title(title)
# formatting
bottom, top = ax.get_ylim()
ax.set_ylim(ymin=0, ymax=0.25) # increase ymax of all other plots
ax.set_yticklabels(ax.get_yticks())
ylabels = [str(round(float(item.get_text()), 2)) for item in ax.get_yticklabels()]
ax.set_yticklabels(ylabels)
ax.set_xlabel('mins') # add xlabel only for the bottom plots
ax.set_xlim(0, 30)
ax.set_xticklabels(ax.get_xticks())
labels = [str(round(float(item.get_text()))) for item in ax.get_xticklabels()]
ax.set_xticklabels(labels)
ax0.set_ylabel('[BD] (M)')
ax1.legend(fancybox=False, loc='upper center', ncol=3, bbox_to_anchor=(1.25, 1.5), fontsize=12)
fig_path = create_fig_path('_'.join(expt_labels)) # save path
plt.savefig(fig_path, bbox_inches='tight', dpi=300, transparent=False)
ks_avg = []
phs_avg = []
for expt_label in expt_labels: # extract the fitted ks and phs from the experiments
df_model_params = import_treated_csv_data(expts[expt_label]['paths']['model_parameters_data'], expt_label)
df_processed = import_treated_csv_data(expts[expt_label]['paths']['processed_data'], expt_label)
ks_avg.append(df_model_params.k[0] / 60) # convert to seconds
phs_avg.append(df_processed['pH'].mean())
ohs_avg = [10 ** (-14 + x) for x in phs_avg] # convert from ph to [oh-]
# produce the disproportionation empirical fitting (k = f(ph) from the modeled datasets
def disproportionation(oh, ai, aii, aiii):
"""disproportionation rate law from Fratzke, 1986"""
return (ai * oh + aii * oh * oh) / (1 + aiii * oh)
a, acov = curve_fit(disproportionation, ohs_avg, ks_avg, p0=(1, 1, 1), bounds=([0, 0, 0], [10000, 1000, 100000000]))
# 8: summary figure plot of butenedial sinks
phs = np.linspace(3, 11.03, 300)
nhxs = np.logspace(-4, 2, 300)
x, y = np.meshgrid(nhxs, phs, sparse=True)
pr_rates = np.empty([len(nhxs), len(phs)])
hca_rates = np.empty([len(nhxs), len(phs)])
dep_rates = np.empty([len(nhxs), len(phs)])
expt_label = 'bdnhph5_nmr'
bdasnmr_params = import_treated_csv_data(expts[expt_label]['paths']['model_parameters_data'], expt_label)
expt_label = 'bdph9_nmr'
bdohnmr_params = import_treated_csv_data(expts[expt_label]['paths']['model_parameters_data'], expt_label)
# obtain estimates of first-order loss terms for comparison, plot with rgb
for tick in range(len(phs)):
ph = phs[tick]
hp = 10**-ph
oh = 1e-14 / hp
for tock in range(len(nhxs)):
nhx = nhxs[tock]
nh3 = nhx * (1 + hp / 10**(-9.25)) ** (-1)
nh4 = nhx * (1 + 10**(-9.25) / hp) ** (-1)
hca_rates[tick, tock] = disproportionation(oh, a[0], a[1], a[2]) * 60
pr_rates[tick, tock] = bdasnmr_params.k6[0] * nh3
dep_rates[tick, tock] = 1 / (7 * 24 * |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.